repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
angelejo/XLaboratorio | libraries/tess-two/jni/com_googlecode_leptonica_android/src/prog/otsutest1.c | 47 | 5509 | /*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- 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.
*====================================================================*/
/*
* otsutest1.c
*/
#include <math.h>
#include "allheaders.h"
static const l_int32 NTests = 5;
static const l_int32 gaussmean1[5] = {20, 40, 60, 80, 60};
static const l_int32 gaussstdev1[5] = {10, 20, 20, 20, 30};
static const l_int32 gaussmean2[5] = {220, 200, 140, 180, 150};
static const l_int32 gaussstdev2[5] = {15, 20, 40, 20, 30};
static const l_float32 gaussfract1[5] = {0.2, 0.3, 0.1, 0.5, 0.3};
static char buf[256];
static l_int32 GenerateSplitPlot(l_int32 i);
static NUMA *MakeGaussian(l_int32 mean, l_int32 stdev, l_float32 fract);
int main(int argc,
char **argv)
{
l_int32 i;
PIX *pix;
PIXA *pixa;
for (i = 0; i < NTests; i++)
GenerateSplitPlot(i);
/* Read the results back in ... */
pixa = pixaCreate(0);
for (i = 0; i < NTests; i++) {
sprintf(buf, "/tmp/junkplot.%d.png", i);
pix = pixRead(buf);
pixSaveTiled(pix, pixa, 1.0, 1, 25, 32);
pixDestroy(&pix);
sprintf(buf, "/tmp/junkplots.%d.png", i);
pix = pixRead(buf);
pixSaveTiled(pix, pixa, 1.0, 0, 25, 32);
pixDestroy(&pix);
}
/* ... and save into a tiled pix */
pix = pixaDisplay(pixa, 0, 0);
pixWrite("/tmp/junkotsuplot.png", pix, IFF_PNG);
pixDisplay(pix, 100, 100);
pixaDestroy(&pixa);
pixDestroy(&pix);
return 0;
}
static l_int32
GenerateSplitPlot(l_int32 i)
{
char title[256];
l_int32 split;
l_float32 ave1, ave2, num1, num2, maxnum, maxscore;
GPLOT *gplot;
NUMA *na1, *na2, *nascore, *nax, *nay;
/* Generate */
na1 = MakeGaussian(gaussmean1[i], gaussstdev1[i], gaussfract1[i]);
na2 = MakeGaussian(gaussmean2[i], gaussstdev1[i], 1.0 - gaussfract1[i]);
numaArithOp(na1, na1, na2, L_ARITH_ADD);
/* Otsu splitting */
numaSplitDistribution(na1, 0.08, &split, &ave1, &ave2, &num1, &num2,
&nascore);
fprintf(stderr, "split = %d, ave1 = %6.1f, ave2 = %6.1f\n",
split, ave1, ave2);
fprintf(stderr, "num1 = %8.0f, num2 = %8.0f\n", num1, num2);
/* Prepare for plotting a vertical line at the split point */
nax = numaMakeConstant(split, 2);
numaGetMax(na1, &maxnum, NULL);
nay = numaMakeConstant(0, 2);
numaReplaceNumber(nay, 1, (l_int32)(0.5 * maxnum));
/* Plot the input histogram with the split location */
sprintf(buf, "/tmp/junkplot.%d", i);
sprintf(title, "Plot %d", i);
gplot = gplotCreate(buf, GPLOT_PNG,
"Histogram: mixture of 2 gaussians",
"Grayscale value", "Number of pixels");
gplotAddPlot(gplot, NULL, na1, GPLOT_LINES, title);
gplotAddPlot(gplot, nax, nay, GPLOT_LINES, NULL);
gplotMakeOutput(gplot);
gplotDestroy(&gplot);
numaDestroy(&na1);
numaDestroy(&na2);
/* Plot the score function */
sprintf(buf, "/tmp/junkplots.%d", i);
sprintf(title, "Plot %d", i);
gplot = gplotCreate(buf, GPLOT_PNG,
"Otsu score function for splitting",
"Grayscale value", "Score");
gplotAddPlot(gplot, NULL, nascore, GPLOT_LINES, title);
numaGetMax(nascore, &maxscore, NULL);
numaReplaceNumber(nay, 1, maxscore);
gplotAddPlot(gplot, nax, nay, GPLOT_LINES, NULL);
gplotMakeOutput(gplot);
gplotDestroy(&gplot);
numaDestroy(&nax);
numaDestroy(&nay);
numaDestroy(&nascore);
return 0;
}
static NUMA *
MakeGaussian(l_int32 mean, l_int32 stdev, l_float32 fract)
{
l_int32 i, total;
l_float32 norm, val;
NUMA *na;
na = numaMakeConstant(0.0, 256);
norm = fract / ((l_float32)stdev * sqrt(2 * 3.14159));
total = 0;
for (i = 0; i < 256; i++) {
val = norm * 1000000. * exp(-(l_float32)((i - mean) * (i - mean)) /
(l_float32)(2 * stdev * stdev));
total += (l_int32)val;
numaSetValue(na, i, val);
}
fprintf(stderr, "Total = %d\n", total);
return na;
}
| unlicense |
u2yg/mongo-c-driver | src/mongoc/mongoc-cursor-array.c | 1 | 4862 | /*
* Copyright 2013 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc-cursor.h"
#include "mongoc-cursor-array-private.h"
#include "mongoc-cursor-private.h"
#include "mongoc-client-private.h"
#include "mongoc-counters-private.h"
#include "mongoc-error.h"
#include "mongoc-log.h"
#include "mongoc-opcode.h"
#include "mongoc-trace.h"
#undef MONGOC_LOG_DOMAIN
#define MONGOC_LOG_DOMAIN "cursor-array"
typedef struct
{
const bson_t *result;
bool has_array;
bool has_synthetic_bson;
bson_iter_t iter;
bson_t bson;
uint32_t document_len;
const uint8_t *document;
const char *field_name;
} mongoc_cursor_array_t;
static void *
_mongoc_cursor_array_new (const char *field_name)
{
mongoc_cursor_array_t *arr;
ENTRY;
arr = (mongoc_cursor_array_t *)bson_malloc0 (sizeof *arr);
arr->field_name = field_name;
RETURN (arr);
}
static void
_mongoc_cursor_array_destroy (mongoc_cursor_t *cursor)
{
mongoc_cursor_array_t *arr;
ENTRY;
arr = (mongoc_cursor_array_t *)cursor->iface_data;
if (arr->has_synthetic_bson) {
bson_destroy(&arr->bson);
}
bson_free (cursor->iface_data);
_mongoc_cursor_destroy (cursor);
EXIT;
}
bool
_mongoc_cursor_array_prime (mongoc_cursor_t *cursor)
{
bool ret = true;
mongoc_cursor_array_t *arr;
bson_iter_t iter;
ENTRY;
arr = (mongoc_cursor_array_t *)cursor->iface_data;
if (!arr->has_array) {
arr->has_array = true;
ret = _mongoc_cursor_next (cursor, &arr->result);
if (!(ret &&
bson_iter_init_find (&iter, arr->result, arr->field_name) &&
BSON_ITER_HOLDS_ARRAY (&iter) &&
bson_iter_recurse (&iter, &arr->iter))) {
ret = false;
}
}
return ret;
}
static bool
_mongoc_cursor_array_next (mongoc_cursor_t *cursor,
const bson_t **bson)
{
bool ret = true;
mongoc_cursor_array_t *arr;
ENTRY;
arr = (mongoc_cursor_array_t *)cursor->iface_data;
*bson = NULL;
if (!arr->has_array) {
ret = _mongoc_cursor_array_prime(cursor);
}
if (ret) {
ret = bson_iter_next (&arr->iter);
}
if (ret) {
bson_iter_document (&arr->iter, &arr->document_len, &arr->document);
bson_init_static (&arr->bson, arr->document, arr->document_len);
*bson = &arr->bson;
}
RETURN (ret);
}
static mongoc_cursor_t *
_mongoc_cursor_array_clone (const mongoc_cursor_t *cursor)
{
mongoc_cursor_array_t *arr;
mongoc_cursor_t *clone_;
ENTRY;
arr = (mongoc_cursor_array_t *)cursor->iface_data;
clone_ = _mongoc_cursor_clone (cursor);
_mongoc_cursor_array_init (clone_, arr->field_name);
RETURN (clone_);
}
static bool
_mongoc_cursor_array_more (mongoc_cursor_t *cursor)
{
bool ret;
mongoc_cursor_array_t *arr;
bson_iter_t iter;
ENTRY;
arr = (mongoc_cursor_array_t *)cursor->iface_data;
if (arr->has_array) {
memcpy (&iter, &arr->iter, sizeof iter);
ret = bson_iter_next (&iter);
} else {
ret = true;
}
RETURN (ret);
}
static bool
_mongoc_cursor_array_error (mongoc_cursor_t *cursor,
bson_error_t *error)
{
mongoc_cursor_array_t *arr;
ENTRY;
arr = (mongoc_cursor_array_t *)cursor->iface_data;
if (arr->has_synthetic_bson) {
return false;
} else {
return _mongoc_cursor_error(cursor, error);
}
}
static mongoc_cursor_interface_t gMongocCursorArray = {
_mongoc_cursor_array_clone,
_mongoc_cursor_array_destroy,
_mongoc_cursor_array_more,
_mongoc_cursor_array_next,
_mongoc_cursor_array_error,
};
void
_mongoc_cursor_array_init (mongoc_cursor_t *cursor,
const char *field_name)
{
ENTRY;
cursor->iface_data = _mongoc_cursor_array_new (field_name);
memcpy (&cursor->iface, &gMongocCursorArray,
sizeof (mongoc_cursor_interface_t));
EXIT;
}
void
_mongoc_cursor_array_set_bson (mongoc_cursor_t *cursor,
const bson_t *bson)
{
mongoc_cursor_array_t *arr;
ENTRY;
arr = (mongoc_cursor_array_t *)cursor->iface_data;
bson_copy_to(bson, &arr->bson);
arr->has_array = true;
arr->has_synthetic_bson = true;
bson_iter_init(&arr->iter, &arr->bson);
}
| apache-2.0 |
google-ar/WebARonARCore | third_party/WebKit/Source/core/animation/LegacyStyleInterpolation.cpp | 1 | 1730 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/animation/LegacyStyleInterpolation.h"
#include <memory>
namespace blink {
namespace {
bool typesMatch(const InterpolableValue* start, const InterpolableValue* end) {
if (start == end)
return true;
if (start->isNumber())
return end->isNumber();
if (start->isBool())
return end->isBool();
if (start->isAnimatableValue())
return end->isAnimatableValue();
if (!(start->isList() && end->isList()))
return false;
const InterpolableList* startList = toInterpolableList(start);
const InterpolableList* endList = toInterpolableList(end);
if (startList->length() != endList->length())
return false;
for (size_t i = 0; i < startList->length(); ++i) {
if (!typesMatch(startList->get(i), endList->get(i)))
return false;
}
return true;
}
} // namespace
LegacyStyleInterpolation::LegacyStyleInterpolation(
std::unique_ptr<InterpolableValue> start,
std::unique_ptr<InterpolableValue> end,
CSSPropertyID id)
: Interpolation(),
m_start(std::move(start)),
m_end(std::move(end)),
m_id(id),
m_cachedFraction(0),
m_cachedIteration(0),
m_cachedValue(m_start ? m_start->clone() : nullptr) {
RELEASE_ASSERT(typesMatch(m_start.get(), m_end.get()));
}
void LegacyStyleInterpolation::interpolate(int iteration, double fraction) {
if (m_cachedFraction != fraction || m_cachedIteration != iteration) {
m_start->interpolate(*m_end, fraction, *m_cachedValue);
m_cachedIteration = iteration;
m_cachedFraction = fraction;
}
}
} // namespace blink
| apache-2.0 |
bwp/SeleniumWebDriver | third_party/gecko-10/win32/include/AccessibleTable2_i.c | 1 | 1755 |
/* this ALWAYS GENERATED file contains the IIDs and CLSIDs */
/* link this file in with the server and any clients */
/* File created by MIDL compiler version 7.00.0555 */
/* at Sun Jan 29 02:48:49 2012
*/
/* Compiler settings for e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/other-licenses/ia2/AccessibleTable2.idl:
Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 7.00.0555
protocol : dce , ms_ext, app_config, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
/* @@MIDL_FILE_HEADING( ) */
#pragma warning( disable: 4049 ) /* more than 64k source lines */
#ifdef __cplusplus
extern "C"{
#endif
#include <rpc.h>
#include <rpcndr.h>
#ifdef _MIDL_USE_GUIDDEF_
#ifndef INITGUID
#define INITGUID
#include <guiddef.h>
#undef INITGUID
#else
#include <guiddef.h>
#endif
#define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \
DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8)
#else // !_MIDL_USE_GUIDDEF_
#ifndef __IID_DEFINED__
#define __IID_DEFINED__
typedef struct _IID
{
unsigned long x;
unsigned short s1;
unsigned short s2;
unsigned char c[8];
} IID;
#endif // __IID_DEFINED__
#ifndef CLSID_DEFINED
#define CLSID_DEFINED
typedef IID CLSID;
#endif // CLSID_DEFINED
#define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \
const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
#endif !_MIDL_USE_GUIDDEF_
MIDL_DEFINE_GUID(IID, IID_IAccessibleTable2,0x6167f295,0x06f0,0x4cdd,0xa1,0xfa,0x02,0xe2,0x51,0x53,0xd8,0x69);
#undef MIDL_DEFINE_GUID
#ifdef __cplusplus
}
#endif
| apache-2.0 |
RayRuizhiLiao/ITK_4D | Modules/ThirdParty/VNL/src/vxl/v3p/netlib/linpack/dsvdc.f | 1 | 15643 | subroutine dsvdc(x,ldx,n,p,s,e,u,ldu,v,ldv,work,job,info)
integer ldx,n,p,ldu,ldv,job,info
double precision x(ldx,1),s(1),e(1),u(ldu,1),v(ldv,1),work(1)
c
c
c dsvdc is a subroutine to reduce a double precision nxp matrix x
c by orthogonal transformations u and v to diagonal form. the
c diagonal elements s(i) are the singular values of x. the
c columns of u are the corresponding left singular vectors,
c and the columns of v the right singular vectors.
c
c on entry
c
c x double precision(ldx,p), where ldx.ge.n.
c x contains the matrix whose singular value
c decomposition is to be computed. x is
c destroyed by dsvdc.
c
c ldx integer.
c ldx is the leading dimension of the array x.
c
c n integer.
c n is the number of rows of the matrix x.
c
c p integer.
c p is the number of columns of the matrix x.
c
c ldu integer.
c ldu is the leading dimension of the array u.
c (see below).
c
c ldv integer.
c ldv is the leading dimension of the array v.
c (see below).
c
c work double precision(n).
c work is a scratch array.
c
c job integer.
c job controls the computation of the singular
c vectors. it has the decimal expansion ab
c with the following meaning
c
c a.eq.0 do not compute the left singular
c vectors.
c a.eq.1 return the n left singular vectors
c in u.
c a.ge.2 return the first min(n,p) singular
c vectors in u.
c b.eq.0 do not compute the right singular
c vectors.
c b.eq.1 return the right singular vectors
c in v.
c
c on return
c
c s double precision(mm), where mm=min(n+1,p).
c the first min(n,p) entries of s contain the
c singular values of x arranged in descending
c order of magnitude.
c
c e double precision(p),
c e ordinarily contains zeros. however see the
c discussion of info for exceptions.
c
c u double precision(ldu,k), where ldu.ge.n. if
c joba.eq.1 then k.eq.n, if joba.ge.2
c then k.eq.min(n,p).
c u contains the matrix of left singular vectors.
c u is not referenced if joba.eq.0. if n.le.p
c or if joba.eq.2, then u may be identified with x
c in the subroutine call.
c
c v double precision(ldv,p), where ldv.ge.p.
c v contains the matrix of right singular vectors.
c v is not referenced if job.eq.0. if p.le.n,
c then v may be identified with x in the
c subroutine call.
c
c info integer.
c the singular values (and their corresponding
c singular vectors) s(info+1),s(info+2),...,s(m)
c are correct (here m=min(n,p)). thus if
c info.eq.0, all the singular values and their
c vectors are correct. in any event, the matrix
c b = trans(u)*x*v is the bidiagonal matrix
c with the elements of s on its diagonal and the
c elements of e on its super-diagonal (trans(u)
c is the transpose of u). thus the singular
c values of x and b are the same.
c
c linpack. this version dated 08/14/78 .
c correction made to shift 2/84.
c g.w. stewart, university of maryland, argonne national lab.
c
c dsvdc uses the following functions and subprograms.
c
c external drot
c blas daxpy,ddot,dscal,dswap,dnrm2,drotg
c fortran dabs,dmax1,max0,min0,mod,dsqrt
c
c internal variables
c
integer i,iter,j,jobu,k,kase,kk,l,ll,lls,lm1,lp1,ls,lu,m,maxit,
* mm,mm1,mp1,nct,nctp1,ncu,nrt,nrtp1
double precision ddot,t,r
double precision b,c,cs,el,emm1,f,g,dnrm2,scale,shift,sl,sm,sn,
* smm1,t1,test,ztest
logical wantu,wantv
c
c
c set the maximum number of iterations.
c
maxit = 1000
c
c determine what is to be computed.
c
wantu = .false.
wantv = .false.
jobu = mod(job,100)/10
ncu = n
if (jobu .gt. 1) ncu = min0(n,p)
if (jobu .ne. 0) wantu = .true.
if (mod(job,10) .ne. 0) wantv = .true.
c
c reduce x to bidiagonal form, storing the diagonal elements
c in s and the super-diagonal elements in e.
c
info = 0
nct = min0(n-1,p)
nrt = max0(0,min0(p-2,n))
lu = max0(nct,nrt)
if (lu .lt. 1) go to 170
do 160 l = 1, lu
lp1 = l + 1
if (l .gt. nct) go to 20
c
c compute the transformation for the l-th column and
c place the l-th diagonal in s(l).
c
s(l) = dnrm2(n-l+1,x(l,l),1)
if (s(l) .eq. 0.0d0) go to 10
if (x(l,l) .ne. 0.0d0) s(l) = dsign(s(l),x(l,l))
call dscal(n-l+1,1.0d0/s(l),x(l,l),1)
x(l,l) = 1.0d0 + x(l,l)
10 continue
s(l) = -s(l)
20 continue
if (p .lt. lp1) go to 50
do 40 j = lp1, p
if (l .gt. nct) go to 30
if (s(l) .eq. 0.0d0) go to 30
c
c apply the transformation.
c
t = -ddot(n-l+1,x(l,l),1,x(l,j),1)/x(l,l)
call daxpy(n-l+1,t,x(l,l),1,x(l,j),1)
30 continue
c
c place the l-th row of x into e for the
c subsequent calculation of the row transformation.
c
e(j) = x(l,j)
40 continue
50 continue
if (.not.wantu .or. l .gt. nct) go to 70
c
c place the transformation in u for subsequent back
c multiplication.
c
do 60 i = l, n
u(i,l) = x(i,l)
60 continue
70 continue
if (l .gt. nrt) go to 150
c
c compute the l-th row transformation and place the
c l-th super-diagonal in e(l).
c
e(l) = dnrm2(p-l,e(lp1),1)
if (e(l) .eq. 0.0d0) go to 80
if (e(lp1) .ne. 0.0d0) e(l) = dsign(e(l),e(lp1))
call dscal(p-l,1.0d0/e(l),e(lp1),1)
e(lp1) = 1.0d0 + e(lp1)
80 continue
e(l) = -e(l)
if (lp1 .gt. n .or. e(l) .eq. 0.0d0) go to 120
c
c apply the transformation.
c
do 90 i = lp1, n
work(i) = 0.0d0
90 continue
do 100 j = lp1, p
call daxpy(n-l,e(j),x(lp1,j),1,work(lp1),1)
100 continue
do 110 j = lp1, p
call daxpy(n-l,-e(j)/e(lp1),work(lp1),1,x(lp1,j),1)
110 continue
120 continue
if (.not.wantv) go to 140
c
c place the transformation in v for subsequent
c back multiplication.
c
do 130 i = lp1, p
v(i,l) = e(i)
130 continue
140 continue
150 continue
160 continue
170 continue
c
c set up the final bidiagonal matrix or order m.
c
m = min0(p,n+1)
nctp1 = nct + 1
nrtp1 = nrt + 1
if (nct .lt. p) s(nctp1) = x(nctp1,nctp1)
if (n .lt. m) s(m) = 0.0d0
if (nrtp1 .lt. m) e(nrtp1) = x(nrtp1,m)
e(m) = 0.0d0
c
c if required, generate u.
c
if (.not.wantu) go to 300
if (ncu .lt. nctp1) go to 200
do 190 j = nctp1, ncu
do 180 i = 1, n
u(i,j) = 0.0d0
180 continue
u(j,j) = 1.0d0
190 continue
200 continue
if (nct .lt. 1) go to 290
do 280 ll = 1, nct
l = nct - ll + 1
if (s(l) .eq. 0.0d0) go to 250
lp1 = l + 1
if (ncu .lt. lp1) go to 220
do 210 j = lp1, ncu
t = -ddot(n-l+1,u(l,l),1,u(l,j),1)/u(l,l)
call daxpy(n-l+1,t,u(l,l),1,u(l,j),1)
210 continue
220 continue
call dscal(n-l+1,-1.0d0,u(l,l),1)
u(l,l) = 1.0d0 + u(l,l)
lm1 = l - 1
if (lm1 .lt. 1) go to 240
do 230 i = 1, lm1
u(i,l) = 0.0d0
230 continue
240 continue
go to 270
250 continue
do 260 i = 1, n
u(i,l) = 0.0d0
260 continue
u(l,l) = 1.0d0
270 continue
280 continue
290 continue
300 continue
c
c if it is required, generate v.
c
if (.not.wantv) go to 350
do 340 ll = 1, p
l = p - ll + 1
lp1 = l + 1
if (l .gt. nrt) go to 320
if (e(l) .eq. 0.0d0) go to 320
do 310 j = lp1, p
t = -ddot(p-l,v(lp1,l),1,v(lp1,j),1)/v(lp1,l)
call daxpy(p-l,t,v(lp1,l),1,v(lp1,j),1)
310 continue
320 continue
do 330 i = 1, p
v(i,l) = 0.0d0
330 continue
v(l,l) = 1.0d0
340 continue
350 continue
c
c main iteration loop for the singular values.
c
mm = m
iter = 0
360 continue
c
c quit if all the singular values have been found.
c
c ...exit
if (m .eq. 0) go to 620
c
c if too many iterations have been performed, set
c flag and return.
c
if (iter .lt. maxit) go to 370
info = m
c ......exit
go to 620
370 continue
c
c this section of the program inspects for
c negligible elements in the s and e arrays. on
c completion the variables kase and l are set as follows.
c
c kase = 1 if s(m) and e(l-1) are negligible and l.lt.m
c kase = 2 if s(l) is negligible and l.lt.m
c kase = 3 if e(l-1) is negligible, l.lt.m, and
c s(l), ..., s(m) are not negligible (qr step).
c kase = 4 if e(m-1) is negligible (convergence).
c
do 390 ll = 1, m
l = m - ll
c ...exit
if (l .eq. 0) go to 400
test = dabs(s(l)) + dabs(s(l+1))
ztest = test + dabs(e(l))
if (ztest .ne. test) go to 380
e(l) = 0.0d0
c ......exit
go to 400
380 continue
390 continue
400 continue
if (l .ne. m - 1) go to 410
kase = 4
go to 480
410 continue
lp1 = l + 1
mp1 = m + 1
do 430 lls = lp1, mp1
ls = m - lls + lp1
c ...exit
if (ls .eq. l) go to 440
test = 0.0d0
if (ls .ne. m) test = test + dabs(e(ls))
if (ls .ne. l + 1) test = test + dabs(e(ls-1))
ztest = test + dabs(s(ls))
if (ztest .ne. test) go to 420
s(ls) = 0.0d0
c ......exit
go to 440
420 continue
430 continue
440 continue
if (ls .ne. l) go to 450
kase = 3
go to 470
450 continue
if (ls .ne. m) go to 460
kase = 1
go to 470
460 continue
kase = 2
l = ls
470 continue
480 continue
l = l + 1
c
c perform the task indicated by kase.
c
go to (490,520,540,570), kase
c
c deflate negligible s(m).
c
490 continue
mm1 = m - 1
f = e(m-1)
e(m-1) = 0.0d0
do 510 kk = l, mm1
k = mm1 - kk + l
t1 = s(k)
call drotg(t1,f,cs,sn)
s(k) = t1
if (k .eq. l) go to 500
f = -sn*e(k-1)
e(k-1) = cs*e(k-1)
500 continue
if (wantv) call drot(p,v(1,k),1,v(1,m),1,cs,sn)
510 continue
go to 610
c
c split at negligible s(l).
c
520 continue
f = e(l-1)
e(l-1) = 0.0d0
do 530 k = l, m
t1 = s(k)
call drotg(t1,f,cs,sn)
s(k) = t1
f = -sn*e(k)
e(k) = cs*e(k)
if (wantu) call drot(n,u(1,k),1,u(1,l-1),1,cs,sn)
530 continue
go to 610
c
c perform one qr step.
c
540 continue
c
c calculate the shift.
c
scale = dmax1(dabs(s(m)),dabs(s(m-1)),dabs(e(m-1)),
* dabs(s(l)),dabs(e(l)))
sm = s(m)/scale
smm1 = s(m-1)/scale
emm1 = e(m-1)/scale
sl = s(l)/scale
el = e(l)/scale
b = ((smm1 + sm)*(smm1 - sm) + emm1**2)/2.0d0
c = (sm*emm1)**2
shift = 0.0d0
if (b .eq. 0.0d0 .and. c .eq. 0.0d0) go to 550
shift = dsqrt(b**2+c)
if (b .lt. 0.0d0) shift = -shift
shift = c/(b + shift)
550 continue
f = (sl + sm)*(sl - sm) + shift
g = sl*el
c
c chase zeros.
c
mm1 = m - 1
do 560 k = l, mm1
call drotg(f,g,cs,sn)
if (k .ne. l) e(k-1) = f
f = cs*s(k) + sn*e(k)
e(k) = cs*e(k) - sn*s(k)
g = sn*s(k+1)
s(k+1) = cs*s(k+1)
if (wantv) call drot(p,v(1,k),1,v(1,k+1),1,cs,sn)
call drotg(f,g,cs,sn)
s(k) = f
f = cs*e(k) + sn*s(k+1)
s(k+1) = -sn*e(k) + cs*s(k+1)
g = sn*e(k+1)
e(k+1) = cs*e(k+1)
if (wantu .and. k .lt. n)
* call drot(n,u(1,k),1,u(1,k+1),1,cs,sn)
560 continue
e(m-1) = f
iter = iter + 1
go to 610
c
c convergence.
c
570 continue
c
c make the singular value positive.
c
if (s(l) .ge. 0.0d0) go to 580
s(l) = -s(l)
if (wantv) call dscal(p,-1.0d0,v(1,l),1)
580 continue
c
c order the singular value.
c
590 if (l .eq. mm) go to 600
c ...exit
if (s(l) .ge. s(l+1)) go to 600
t = s(l)
s(l) = s(l+1)
s(l+1) = t
if (wantv .and. l .lt. p)
* call dswap(p,v(1,l),1,v(1,l+1),1)
if (wantu .and. l .lt. n)
* call dswap(n,u(1,l),1,u(1,l+1),1)
l = l + 1
go to 590
600 continue
iter = 0
m = m - 1
610 continue
go to 360
620 continue
return
end
| apache-2.0 |
kraj/zephyr | drivers/flash/soc_flash_mcux.c | 1 | 3619 | /*
* Copyright (c) 2016 Linaro Limited
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <logging/sys_log.h>
#include <kernel.h>
#include <device.h>
#include <string.h>
#include <flash.h>
#include <errno.h>
#include <init.h>
#include <soc.h>
#include "flash_priv.h"
#include "fsl_common.h"
#include "fsl_flash.h"
struct flash_priv {
flash_config_t config;
/*
* HACK: flash write protection is managed in software.
*/
struct k_sem write_lock;
};
/*
* Interrupt vectors could be executed from flash hence the need for locking.
* The underlying MCUX driver takes care of copying the functions to SRAM.
*
* For more information, see the application note below on Read-While-Write
* http://cache.freescale.com/files/32bit/doc/app_note/AN4695.pdf
*
*/
static int flash_mcux_erase(struct device *dev, off_t offset, size_t len)
{
struct flash_priv *priv = dev->driver_data;
u32_t addr;
status_t rc;
unsigned int key;
if (k_sem_take(&priv->write_lock, K_NO_WAIT)) {
return -EACCES;
}
addr = offset + priv->config.PFlashBlockBase;
key = irq_lock();
rc = FLASH_Erase(&priv->config, addr, len, kFLASH_ApiEraseKey);
irq_unlock(key);
k_sem_give(&priv->write_lock);
return (rc == kStatus_Success) ? 0 : -EINVAL;
}
static int flash_mcux_read(struct device *dev, off_t offset,
void *data, size_t len)
{
struct flash_priv *priv = dev->driver_data;
u32_t addr;
/*
* The MCUX supports different flash chips whose valid ranges are
* hidden below the API: until the API export these ranges, we can not
* do any generic validation
*/
addr = offset + priv->config.PFlashBlockBase;
memcpy(data, (void *) addr, len);
return 0;
}
static int flash_mcux_write(struct device *dev, off_t offset,
const void *data, size_t len)
{
struct flash_priv *priv = dev->driver_data;
u32_t addr;
status_t rc;
unsigned int key;
if (k_sem_take(&priv->write_lock, K_NO_WAIT)) {
return -EACCES;
}
addr = offset + priv->config.PFlashBlockBase;
key = irq_lock();
rc = FLASH_Program(&priv->config, addr, (uint32_t *) data, len);
irq_unlock(key);
k_sem_give(&priv->write_lock);
return (rc == kStatus_Success) ? 0 : -EINVAL;
}
static int flash_mcux_write_protection(struct device *dev, bool enable)
{
struct flash_priv *priv = dev->driver_data;
int rc = 0;
if (enable) {
rc = k_sem_take(&priv->write_lock, K_FOREVER);
} else {
k_sem_give(&priv->write_lock);
}
return rc;
}
#if defined(CONFIG_FLASH_PAGE_LAYOUT)
static const struct flash_pages_layout dev_layout = {
.pages_count = KB(CONFIG_FLASH_SIZE) / FLASH_ERASE_BLOCK_SIZE,
.pages_size = FLASH_ERASE_BLOCK_SIZE,
};
static void flash_mcux_pages_layout(struct device *dev,
const struct flash_pages_layout **layout,
size_t *layout_size)
{
*layout = &dev_layout;
*layout_size = 1;
}
#endif /* CONFIG_FLASH_PAGE_LAYOUT */
static struct flash_priv flash_data;
static const struct flash_driver_api flash_mcux_api = {
.write_protection = flash_mcux_write_protection,
.erase = flash_mcux_erase,
.write = flash_mcux_write,
.read = flash_mcux_read,
#if defined(CONFIG_FLASH_PAGE_LAYOUT)
.page_layout = flash_mcux_pages_layout,
#endif
.write_block_size = FSL_FEATURE_FLASH_PFLASH_BLOCK_WRITE_UNIT_SIZE,
};
static int flash_mcux_init(struct device *dev)
{
struct flash_priv *priv = dev->driver_data;
status_t rc;
k_sem_init(&priv->write_lock, 0, 1);
rc = FLASH_Init(&priv->config);
return (rc == kStatus_Success) ? 0 : -EIO;
}
DEVICE_AND_API_INIT(flash_mcux, FLASH_DEV_NAME,
flash_mcux_init, &flash_data, NULL, POST_KERNEL,
CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &flash_mcux_api);
| apache-2.0 |
execunix/vinos | external/bsd/openldap/dist/libraries/liblutil/tavl.c | 1 | 12242 | /* $NetBSD: tavl.c,v 1.1.1.4 2014/05/28 09:58:45 tron Exp $ */
/* avl.c - routines to implement an avl tree */
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
*
* Copyright 2005-2014 The OpenLDAP Foundation.
* Portions Copyright (c) 2005 by Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
/* ACKNOWLEDGEMENTS:
* This work was initially developed by Howard Chu for inclusion
* in OpenLDAP software.
*/
#include "portable.h"
#include <limits.h>
#include <stdio.h>
#include <ac/stdlib.h>
#ifdef CSRIMALLOC
#define ber_memalloc malloc
#define ber_memrealloc realloc
#define ber_memfree free
#else
#include "lber.h"
#endif
#define AVL_INTERNAL
#include "avl.h"
/* Maximum tree depth this host's address space could support */
#define MAX_TREE_DEPTH (sizeof(void *) * CHAR_BIT)
static const int avl_bfs[] = {LH, RH};
/*
* Threaded AVL trees - for fast in-order traversal of nodes.
*/
/*
* tavl_insert -- insert a node containing data data into the avl tree
* with root root. fcmp is a function to call to compare the data portion
* of two nodes. it should take two arguments and return <, >, or == 0,
* depending on whether its first argument is <, >, or == its second
* argument (like strcmp, e.g.). fdup is a function to call when a duplicate
* node is inserted. it should return 0, or -1 and its return value
* will be the return value from avl_insert in the case of a duplicate node.
* the function will be called with the original node's data as its first
* argument and with the incoming duplicate node's data as its second
* argument. this could be used, for example, to keep a count with each
* node.
*
* NOTE: this routine may malloc memory
*/
int
tavl_insert( Avlnode ** root, void *data, AVL_CMP fcmp, AVL_DUP fdup )
{
Avlnode *t, *p, *s, *q, *r;
int a, cmp, ncmp;
if ( *root == NULL ) {
if (( r = (Avlnode *) ber_memalloc( sizeof( Avlnode ))) == NULL ) {
return( -1 );
}
r->avl_link[0] = r->avl_link[1] = NULL;
r->avl_data = data;
r->avl_bf = EH;
r->avl_bits[0] = r->avl_bits[1] = AVL_THREAD;
*root = r;
return( 0 );
}
t = NULL;
s = p = *root;
/* find insertion point */
while (1) {
cmp = fcmp( data, p->avl_data );
if ( cmp == 0 )
return (*fdup)( p->avl_data, data );
cmp = (cmp > 0);
q = avl_child( p, cmp );
if (q == NULL) {
/* insert */
if (( q = (Avlnode *) ber_memalloc( sizeof( Avlnode ))) == NULL ) {
return( -1 );
}
q->avl_link[cmp] = p->avl_link[cmp];
q->avl_link[!cmp] = p;
q->avl_data = data;
q->avl_bf = EH;
q->avl_bits[0] = q->avl_bits[1] = AVL_THREAD;
p->avl_link[cmp] = q;
p->avl_bits[cmp] = AVL_CHILD;
break;
} else if ( q->avl_bf ) {
t = p;
s = q;
}
p = q;
}
/* adjust balance factors */
cmp = fcmp( data, s->avl_data ) > 0;
r = p = s->avl_link[cmp];
a = avl_bfs[cmp];
while ( p != q ) {
cmp = fcmp( data, p->avl_data ) > 0;
p->avl_bf = avl_bfs[cmp];
p = p->avl_link[cmp];
}
/* checks and balances */
if ( s->avl_bf == EH ) {
s->avl_bf = a;
return 0;
} else if ( s->avl_bf == -a ) {
s->avl_bf = EH;
return 0;
} else if ( s->avl_bf == a ) {
cmp = (a > 0);
ncmp = !cmp;
if ( r->avl_bf == a ) {
/* single rotation */
p = r;
if ( r->avl_bits[ncmp] == AVL_THREAD ) {
r->avl_bits[ncmp] = AVL_CHILD;
s->avl_bits[cmp] = AVL_THREAD;
} else {
s->avl_link[cmp] = r->avl_link[ncmp];
r->avl_link[ncmp] = s;
}
s->avl_bf = 0;
r->avl_bf = 0;
} else if ( r->avl_bf == -a ) {
/* double rotation */
p = r->avl_link[ncmp];
if ( p->avl_bits[cmp] == AVL_THREAD ) {
p->avl_bits[cmp] = AVL_CHILD;
r->avl_bits[ncmp] = AVL_THREAD;
} else {
r->avl_link[ncmp] = p->avl_link[cmp];
p->avl_link[cmp] = r;
}
if ( p->avl_bits[ncmp] == AVL_THREAD ) {
p->avl_bits[ncmp] = AVL_CHILD;
s->avl_link[cmp] = p;
s->avl_bits[cmp] = AVL_THREAD;
} else {
s->avl_link[cmp] = p->avl_link[ncmp];
p->avl_link[ncmp] = s;
}
if ( p->avl_bf == a ) {
s->avl_bf = -a;
r->avl_bf = 0;
} else if ( p->avl_bf == -a ) {
s->avl_bf = 0;
r->avl_bf = a;
} else {
s->avl_bf = 0;
r->avl_bf = 0;
}
p->avl_bf = 0;
}
/* Update parent */
if ( t == NULL )
*root = p;
else if ( s == t->avl_right )
t->avl_right = p;
else
t->avl_left = p;
}
return 0;
}
void*
tavl_delete( Avlnode **root, void* data, AVL_CMP fcmp )
{
Avlnode *p, *q, *r, *top;
int side, side_bf, shorter, nside = -1;
/* parent stack */
Avlnode *pptr[MAX_TREE_DEPTH];
unsigned char pdir[MAX_TREE_DEPTH];
int depth = 0;
if ( *root == NULL )
return NULL;
p = *root;
while (1) {
side = fcmp( data, p->avl_data );
if ( !side )
break;
side = ( side > 0 );
pdir[depth] = side;
pptr[depth++] = p;
if ( p->avl_bits[side] == AVL_THREAD )
return NULL;
p = p->avl_link[side];
}
data = p->avl_data;
/* If this node has two children, swap so we are deleting a node with
* at most one child.
*/
if ( p->avl_bits[0] == AVL_CHILD && p->avl_bits[1] == AVL_CHILD &&
p->avl_link[0] && p->avl_link[1] ) {
/* find the immediate predecessor <q> */
q = p->avl_link[0];
side = depth;
pdir[depth++] = 0;
while (q->avl_bits[1] == AVL_CHILD && q->avl_link[1]) {
pdir[depth] = 1;
pptr[depth++] = q;
q = q->avl_link[1];
}
/* swap links */
r = p->avl_link[0];
p->avl_link[0] = q->avl_link[0];
q->avl_link[0] = r;
q->avl_link[1] = p->avl_link[1];
p->avl_link[1] = q;
p->avl_bits[0] = q->avl_bits[0];
p->avl_bits[1] = q->avl_bits[1];
q->avl_bits[0] = q->avl_bits[1] = AVL_CHILD;
q->avl_bf = p->avl_bf;
/* fix stack positions: old parent of p points to q */
pptr[side] = q;
if ( side ) {
r = pptr[side-1];
r->avl_link[pdir[side-1]] = q;
} else {
*root = q;
}
/* new parent of p points to p */
if ( depth-side > 1 ) {
r = pptr[depth-1];
r->avl_link[1] = p;
} else {
q->avl_link[0] = p;
}
/* fix right subtree: successor of p points to q */
r = q->avl_link[1];
while ( r->avl_bits[0] == AVL_CHILD && r->avl_link[0] )
r = r->avl_link[0];
r->avl_link[0] = q;
}
/* now <p> has at most one child, get it */
if ( p->avl_link[0] && p->avl_bits[0] == AVL_CHILD ) {
q = p->avl_link[0];
/* Preserve thread continuity */
r = p->avl_link[1];
nside = 1;
} else if ( p->avl_link[1] && p->avl_bits[1] == AVL_CHILD ) {
q = p->avl_link[1];
r = p->avl_link[0];
nside = 0;
} else {
q = NULL;
if ( depth > 0 )
r = p->avl_link[pdir[depth-1]];
else
r = NULL;
}
ber_memfree( p );
/* Update child thread */
if ( q ) {
for ( ; q->avl_bits[nside] == AVL_CHILD && q->avl_link[nside];
q = q->avl_link[nside] ) ;
q->avl_link[nside] = r;
}
if ( !depth ) {
*root = q;
return data;
}
/* set the child into p's parent */
depth--;
p = pptr[depth];
side = pdir[depth];
p->avl_link[side] = q;
if ( !q ) {
p->avl_bits[side] = AVL_THREAD;
p->avl_link[side] = r;
}
top = NULL;
shorter = 1;
while ( shorter ) {
p = pptr[depth];
side = pdir[depth];
nside = !side;
side_bf = avl_bfs[side];
/* case 1: height unchanged */
if ( p->avl_bf == EH ) {
/* Tree is now heavier on opposite side */
p->avl_bf = avl_bfs[nside];
shorter = 0;
} else if ( p->avl_bf == side_bf ) {
/* case 2: taller subtree shortened, height reduced */
p->avl_bf = EH;
} else {
/* case 3: shorter subtree shortened */
if ( depth )
top = pptr[depth-1]; /* p->parent; */
else
top = NULL;
/* set <q> to the taller of the two subtrees of <p> */
q = p->avl_link[nside];
if ( q->avl_bf == EH ) {
/* case 3a: height unchanged, single rotate */
if ( q->avl_bits[side] == AVL_THREAD ) {
q->avl_bits[side] = AVL_CHILD;
p->avl_bits[nside] = AVL_THREAD;
} else {
p->avl_link[nside] = q->avl_link[side];
q->avl_link[side] = p;
}
shorter = 0;
q->avl_bf = side_bf;
p->avl_bf = (- side_bf);
} else if ( q->avl_bf == p->avl_bf ) {
/* case 3b: height reduced, single rotate */
if ( q->avl_bits[side] == AVL_THREAD ) {
q->avl_bits[side] = AVL_CHILD;
p->avl_bits[nside] = AVL_THREAD;
} else {
p->avl_link[nside] = q->avl_link[side];
q->avl_link[side] = p;
}
shorter = 1;
q->avl_bf = EH;
p->avl_bf = EH;
} else {
/* case 3c: height reduced, balance factors opposite */
r = q->avl_link[side];
if ( r->avl_bits[nside] == AVL_THREAD ) {
r->avl_bits[nside] = AVL_CHILD;
q->avl_bits[side] = AVL_THREAD;
} else {
q->avl_link[side] = r->avl_link[nside];
r->avl_link[nside] = q;
}
if ( r->avl_bits[side] == AVL_THREAD ) {
r->avl_bits[side] = AVL_CHILD;
p->avl_bits[nside] = AVL_THREAD;
p->avl_link[nside] = r;
} else {
p->avl_link[nside] = r->avl_link[side];
r->avl_link[side] = p;
}
if ( r->avl_bf == side_bf ) {
q->avl_bf = (- side_bf);
p->avl_bf = EH;
} else if ( r->avl_bf == (- side_bf)) {
q->avl_bf = EH;
p->avl_bf = side_bf;
} else {
q->avl_bf = EH;
p->avl_bf = EH;
}
r->avl_bf = EH;
q = r;
}
/* a rotation has caused <q> (or <r> in case 3c) to become
* the root. let <p>'s former parent know this.
*/
if ( top == NULL ) {
*root = q;
} else if (top->avl_link[0] == p) {
top->avl_link[0] = q;
} else {
top->avl_link[1] = q;
}
/* end case 3 */
p = q;
}
if ( !depth )
break;
depth--;
} /* end while(shorter) */
return data;
}
/*
* tavl_free -- traverse avltree root, freeing the memory it is using.
* the dfree() is called to free the data portion of each node. The
* number of items actually freed is returned.
*/
int
tavl_free( Avlnode *root, AVL_FREE dfree )
{
int nleft, nright;
if ( root == 0 )
return( 0 );
nleft = tavl_free( avl_lchild( root ), dfree );
nright = tavl_free( avl_rchild( root ), dfree );
if ( dfree )
(*dfree)( root->avl_data );
ber_memfree( root );
return( nleft + nright + 1 );
}
/*
* tavl_find -- search avltree root for a node with data data. the function
* cmp is used to compare things. it is called with data as its first arg
* and the current node data as its second. it should return 0 if they match,
* < 0 if arg1 is less than arg2 and > 0 if arg1 is greater than arg2.
*/
/*
* tavl_find2 - returns Avlnode instead of data pointer.
* tavl_find3 - as above, but returns Avlnode even if no match is found.
* also set *ret = last comparison result, or -1 if root == NULL.
*/
Avlnode *
tavl_find3( Avlnode *root, const void *data, AVL_CMP fcmp, int *ret )
{
int cmp = -1, dir;
Avlnode *prev = root;
while ( root != 0 && (cmp = (*fcmp)( data, root->avl_data )) != 0 ) {
prev = root;
dir = cmp > 0;
root = avl_child( root, dir );
}
*ret = cmp;
return root ? root : prev;
}
Avlnode *
tavl_find2( Avlnode *root, const void *data, AVL_CMP fcmp )
{
int cmp;
while ( root != 0 && (cmp = (*fcmp)( data, root->avl_data )) != 0 ) {
cmp = cmp > 0;
root = avl_child( root, cmp );
}
return root;
}
void*
tavl_find( Avlnode *root, const void* data, AVL_CMP fcmp )
{
int cmp;
while ( root != 0 && (cmp = (*fcmp)( data, root->avl_data )) != 0 ) {
cmp = cmp > 0;
root = avl_child( root, cmp );
}
return( root ? root->avl_data : 0 );
}
/* Return the leftmost or rightmost node in the tree */
Avlnode *
tavl_end( Avlnode *root, int dir )
{
if ( root ) {
while ( root->avl_bits[dir] == AVL_CHILD )
root = root->avl_link[dir];
}
return root;
}
/* Return the next node in the given direction */
Avlnode *
tavl_next( Avlnode *root, int dir )
{
if ( root ) {
int c = root->avl_bits[dir];
root = root->avl_link[dir];
if ( c == AVL_CHILD ) {
dir ^= 1;
while ( root->avl_bits[dir] == AVL_CHILD )
root = root->avl_link[dir];
}
}
return root;
}
| apache-2.0 |
andschwa/mesos | src/slave/containerizer/docker.cpp | 1 | 85218 | // 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 <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <mesos/slave/container_logger.hpp>
#include <mesos/slave/containerizer.hpp>
#include <process/check.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/io.hpp>
#include <process/network.hpp>
#include <process/owned.hpp>
#include <process/reap.hpp>
#include <process/subprocess.hpp>
#ifdef __WINDOWS__
#include <process/windows/jobobject.hpp>
#endif // __WINDOWS__
#include <stout/adaptor.hpp>
#include <stout/fs.hpp>
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/jsonify.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/protobuf.hpp>
#include <stout/uuid.hpp>
#include <stout/os/killtree.hpp>
#include <stout/os/which.hpp>
#ifdef __WINDOWS__
#include <stout/os/windows/jobobject.hpp>
#endif // __WINDOWS__
#include "common/status_utils.hpp"
#include "hook/manager.hpp"
#ifdef __linux__
#include "linux/cgroups.hpp"
#include "linux/fs.hpp"
#include "linux/systemd.hpp"
#endif // __linux__
#include "slave/paths.hpp"
#include "slave/slave.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/containerizer/docker.hpp"
#include "slave/containerizer/fetcher.hpp"
#include "slave/containerizer/mesos/isolators/cgroups/constants.hpp"
#include "usage/usage.hpp"
using namespace process;
using std::list;
using std::map;
using std::set;
using std::string;
using std::vector;
using mesos::slave::ContainerConfig;
using mesos::slave::ContainerIO;
using mesos::slave::ContainerLogger;
using mesos::slave::ContainerTermination;
using mesos::internal::slave::state::SlaveState;
using mesos::internal::slave::state::FrameworkState;
using mesos::internal::slave::state::ExecutorState;
using mesos::internal::slave::state::RunState;
namespace mesos {
namespace internal {
namespace slave {
// Declared in header, see explanation there.
const string DOCKER_NAME_PREFIX = "mesos-";
// Declared in header, see explanation there.
const string DOCKER_NAME_SEPERATOR = ".";
// Declared in header, see explanation there.
const string DOCKER_SYMLINK_DIRECTORY = path::join("docker", "links");
#ifdef __WINDOWS__
const string MESOS_DOCKER_EXECUTOR = "mesos-docker-executor.exe";
#else
const string MESOS_DOCKER_EXECUTOR = "mesos-docker-executor";
#endif // __WINDOWS__
// Parse the ContainerID from a Docker container and return None if
// the container was not launched from Mesos.
Option<ContainerID> parse(const Docker::Container& container)
{
Option<string> name = None();
Option<ContainerID> containerId = None();
if (strings::startsWith(container.name, DOCKER_NAME_PREFIX)) {
name = strings::remove(
container.name, DOCKER_NAME_PREFIX, strings::PREFIX);
} else if (strings::startsWith(container.name, "/" + DOCKER_NAME_PREFIX)) {
name = strings::remove(
container.name, "/" + DOCKER_NAME_PREFIX, strings::PREFIX);
}
if (name.isSome()) {
// For Mesos versions 0.23 to 1.3 (inclusive), the docker
// container name format was:
// DOCKER_NAME_PREFIX + SlaveID + DOCKER_NAME_SEPERATOR + ContainerID.
//
// In versions <= 0.22 or >= 1.4, the name format is:
// DOCKER_NAME_PREFIX + ContainerID.
//
// To be backward compatible during upgrade, we still have to
// support all formats.
if (!strings::contains(name.get(), DOCKER_NAME_SEPERATOR)) {
ContainerID id;
id.set_value(name.get());
containerId = id;
} else {
vector<string> parts = strings::split(name.get(), DOCKER_NAME_SEPERATOR);
if (parts.size() == 2 || parts.size() == 3) {
ContainerID id;
id.set_value(parts[1]);
containerId = id;
}
}
// Check if id is a valid UUID.
if (containerId.isSome()) {
Try<id::UUID> uuid = id::UUID::fromString(containerId->value());
if (uuid.isError()) {
return None();
}
}
}
return containerId;
}
Try<DockerContainerizer*> DockerContainerizer::create(
const Flags& flags,
Fetcher* fetcher,
const Option<NvidiaComponents>& nvidia)
{
// Create and initialize the container logger module.
Try<ContainerLogger*> logger =
ContainerLogger::create(flags.container_logger);
if (logger.isError()) {
return Error("Failed to create container logger: " + logger.error());
}
Try<Owned<Docker>> create = Docker::create(
flags.docker,
flags.docker_socket,
true,
flags.docker_config);
if (create.isError()) {
return Error("Failed to create docker: " + create.error());
}
Shared<Docker> docker = create->share();
if (flags.docker_mesos_image.isSome()) {
Try<Nothing> validateResult = docker->validateVersion(Version(1, 5, 0));
if (validateResult.isError()) {
string message = "Docker with mesos images requires docker 1.5+";
message += validateResult.error();
return Error(message);
}
}
// TODO(tnachen): We should also mark the work directory as shared
// mount here, more details please refer to MESOS-3483.
return new DockerContainerizer(
flags,
fetcher,
Owned<ContainerLogger>(logger.get()),
docker,
nvidia);
}
DockerContainerizer::DockerContainerizer(
const Owned<DockerContainerizerProcess>& _process)
: process(_process)
{
spawn(process.get());
}
DockerContainerizer::DockerContainerizer(
const Flags& flags,
Fetcher* fetcher,
const Owned<ContainerLogger>& logger,
Shared<Docker> docker,
const Option<NvidiaComponents>& nvidia)
: process(new DockerContainerizerProcess(
flags,
fetcher,
logger,
docker,
nvidia))
{
spawn(process.get());
}
DockerContainerizer::~DockerContainerizer()
{
terminate(process.get());
process::wait(process.get());
}
// Constructs the flags for the `mesos-docker-executor`.
// Custom docker executors will also be invoked with these flags.
//
// NOTE: `taskEnvironment` is currently used to propagate environment variables
// from a hook: `slavePreLaunchDockerEnvironmentDecorator`.
::mesos::internal::docker::Flags dockerFlags(
const Flags& flags,
const string& name,
const string& directory,
const Option<map<string, string>>& taskEnvironment)
{
::mesos::internal::docker::Flags dockerFlags;
dockerFlags.container = name;
dockerFlags.docker = flags.docker;
dockerFlags.sandbox_directory = directory;
dockerFlags.mapped_directory = flags.sandbox_directory;
dockerFlags.docker_socket = flags.docker_socket;
dockerFlags.launcher_dir = flags.launcher_dir;
if (taskEnvironment.isSome()) {
dockerFlags.task_environment = string(jsonify(taskEnvironment.get()));
}
if (flags.default_container_dns.isSome()) {
dockerFlags.default_container_dns =
string(jsonify(JSON::Protobuf(flags.default_container_dns.get())));
}
#ifdef __linux__
dockerFlags.cgroups_enable_cfs = flags.cgroups_enable_cfs,
#endif
// TODO(alexr): Remove this after the deprecation cycle (started in 1.0).
dockerFlags.stop_timeout = flags.docker_stop_timeout;
return dockerFlags;
}
Try<DockerContainerizerProcess::Container*>
DockerContainerizerProcess::Container::create(
const ContainerID& id,
const ContainerConfig& containerConfig,
const map<string, string>& environment,
const Option<string>& pidCheckpointPath,
const Flags& flags)
{
// We need to extract a SlaveID based on the sandbox directory,
// for the purpose of working around a limitation of the Docker CLI.
// If the sandbox directory contains a colon, the sandbox directory
// cannot be mounted directly into the container directory. Instead,
// we symlink the sandbox directory and mount the symlink.
// See MESOS-1833 for more details.
Try<paths::ExecutorRunPath> runPath =
paths::parseExecutorRunPath(flags.work_dir, containerConfig.directory());
CHECK_SOME(runPath) << "Unable to determine SlaveID from sandbox directory";
string dockerSymlinkPath = path::join(
paths::getSlavePath(flags.work_dir, runPath->slaveId),
DOCKER_SYMLINK_DIRECTORY);
Try<Nothing> mkdir = os::mkdir(dockerSymlinkPath);
if (mkdir.isError()) {
return Error("Unable to create symlink folder for docker " +
dockerSymlinkPath + ": " + mkdir.error());
}
bool symlinked = false;
string containerWorkdir = containerConfig.directory();
if (strings::contains(containerConfig.directory(), ":")) {
containerWorkdir = path::join(dockerSymlinkPath, id.value());
Try<Nothing> symlink =
::fs::symlink(containerConfig.directory(), containerWorkdir);
if (symlink.isError()) {
return Error(
"Failed to symlink directory '" + containerConfig.directory() +
"' to '" + containerWorkdir + "': " + symlink.error());
}
symlinked = true;
}
Option<ContainerInfo> containerInfo = None();
Option<CommandInfo> commandInfo = None();
bool launchesExecutorContainer = false;
if (containerConfig.has_task_info() && flags.docker_mesos_image.isSome()) {
// Override the container and command to launch an executor
// in a docker container.
ContainerInfo newContainerInfo;
// Mounting in the docker socket so the executor can communicate to
// the host docker daemon. We are assuming the current instance is
// launching docker containers to the host daemon as well.
Volume* dockerSockVolume = newContainerInfo.add_volumes();
dockerSockVolume->set_host_path(flags.docker_socket);
dockerSockVolume->set_container_path(flags.docker_socket);
dockerSockVolume->set_mode(Volume::RO);
// Mounting in sandbox so the logs from the executor can be
// persisted over container failures.
Volume* sandboxVolume = newContainerInfo.add_volumes();
sandboxVolume->set_host_path(containerWorkdir);
sandboxVolume->set_container_path(containerWorkdir);
sandboxVolume->set_mode(Volume::RW);
ContainerInfo::DockerInfo dockerInfo;
dockerInfo.set_image(flags.docker_mesos_image.get());
// `--pid=host` is required for `mesos-docker-executor` to find
// the pid of the task in `/proc` when running
// `mesos-docker-executor` in a separate docker container.
Parameter* pidParameter = dockerInfo.add_parameters();
pidParameter->set_key("pid");
pidParameter->set_value("host");
// `--cap-add=SYS_ADMIN` and `--cap-add=SYS_PTRACE` are required
// for `mesos-docker-executor` to enter the namespaces of the task
// during health checking when running `mesos-docker-executor` in a
// separate docker container.
Parameter* capAddParameter = dockerInfo.add_parameters();
capAddParameter->set_key("cap-add");
capAddParameter->set_value("SYS_ADMIN");
capAddParameter = dockerInfo.add_parameters();
capAddParameter->set_key("cap-add");
capAddParameter->set_value("SYS_PTRACE");
newContainerInfo.mutable_docker()->CopyFrom(dockerInfo);
// NOTE: We do not set the optional `taskEnvironment` here as
// this field is currently used to propagate environment variables
// from a hook. This hook is called after `Container::create`.
::mesos::internal::docker::Flags dockerExecutorFlags = dockerFlags(
flags,
Container::name(id),
containerWorkdir,
None());
// Override the command with the docker command executor.
CommandInfo newCommandInfo;
newCommandInfo.set_shell(false);
newCommandInfo.set_value(
path::join(flags.launcher_dir, MESOS_DOCKER_EXECUTOR));
// Stringify the flags as arguments.
// This minimizes the need for escaping flag values.
foreachvalue (const flags::Flag& flag, dockerExecutorFlags) {
Option<string> value = flag.stringify(dockerExecutorFlags);
if (value.isSome()) {
newCommandInfo.add_arguments(
"--" + flag.effective_name().value + "=" + value.get());
}
}
if (containerConfig.task_info().has_command()) {
newCommandInfo.mutable_uris()
->CopyFrom(containerConfig.task_info().command().uris());
}
containerInfo = newContainerInfo;
commandInfo = newCommandInfo;
launchesExecutorContainer = true;
}
return new Container(
id,
containerConfig,
environment,
pidCheckpointPath,
symlinked,
containerWorkdir,
commandInfo,
containerInfo,
launchesExecutorContainer);
}
Future<Nothing> DockerContainerizerProcess::fetch(
const ContainerID& containerId)
{
CHECK(containers_.contains(containerId));
Container* container = containers_.at(containerId);
return fetcher->fetch(
containerId,
container->command,
container->containerWorkDir,
container->containerConfig.has_user() ? container->containerConfig.user()
: Option<string>::none());
}
Future<Nothing> DockerContainerizerProcess::pull(
const ContainerID& containerId)
{
if (!containers_.contains(containerId)) {
return Failure("Container is already destroyed");
}
Container* container = containers_.at(containerId);
container->state = Container::PULLING;
string image = container->image();
Future<Docker::Image> future = metrics.image_pull.time(docker->pull(
container->containerWorkDir,
image,
container->forcePullImage()));
containers_.at(containerId)->pull = future;
return future.then(defer(self(), [=]() {
VLOG(1) << "Docker pull " << image << " completed";
return Nothing();
}));
}
Try<Nothing> DockerContainerizerProcess::updatePersistentVolumes(
const ContainerID& containerId,
const string& directory,
const Resources& current,
const Resources& updated)
{
// Docker Containerizer currently is only expected to run on Linux.
#ifdef __linux__
// Unmount all persistent volumes that are no longer present.
foreach (const Resource& resource, current.persistentVolumes()) {
// This is enforced by the master.
CHECK(resource.disk().has_volume());
// Ignore absolute and nested paths.
const string& containerPath = resource.disk().volume().container_path();
if (strings::contains(containerPath, "/")) {
LOG(WARNING) << "Skipping updating mount for persistent volume "
<< resource << " of container " << containerId
<< " because the container path '" << containerPath
<< "' contains slash";
continue;
}
if (updated.contains(resource)) {
continue;
}
const string target = path::join(
directory, resource.disk().volume().container_path());
Try<Nothing> unmount = fs::unmount(target);
if (unmount.isError()) {
return Error("Failed to unmount persistent volume at '" + target +
"': " + unmount.error());
}
// TODO(tnachen): Remove mount point after unmounting. This requires
// making sure the work directory is marked as a shared mount. For
// more details please refer to MESOS-3483.
}
// Get user and group info for this task based on the sandbox directory.
struct stat s;
if (::stat(directory.c_str(), &s) < 0) {
return Error("Failed to get ownership for '" + directory + "': " +
os::strerror(errno));
}
const uid_t uid = s.st_uid;
const gid_t gid = s.st_gid;
// Mount all new persistent volumes added.
foreach (const Resource& resource, updated.persistentVolumes()) {
// This is enforced by the master.
CHECK(resource.disk().has_volume());
if (current.contains(resource)) {
continue;
}
const string source =
paths::getPersistentVolumePath(flags.work_dir, resource);
// Ignore absolute and nested paths.
const string& containerPath = resource.disk().volume().container_path();
if (strings::contains(containerPath, "/")) {
LOG(WARNING) << "Skipping updating mount for persistent volume "
<< resource << " of container " << containerId
<< " because the container path '" << containerPath
<< "' contains slash";
continue;
}
bool isVolumeInUse = false;
foreachpair (const ContainerID& _containerId,
const Container* _container,
containers_) {
// Skip self.
if (_containerId == containerId) {
continue;
}
if (_container->resources.contains(resource)) {
isVolumeInUse = true;
break;
}
}
// Set the ownership of the persistent volume to match that of the sandbox
// directory if the volume is not already in use. If the volume is
// currently in use by other containers, tasks in this container may fail
// to read from or write to the persistent volume due to incompatible
// ownership and file system permissions.
if (!isVolumeInUse) {
LOG(INFO) << "Changing the ownership of the persistent volume at '"
<< source << "' with uid " << uid << " and gid " << gid;
Try<Nothing> chown = os::chown(uid, gid, source, false);
if (chown.isError()) {
return Error(
"Failed to change the ownership of the persistent volume at '" +
source + "' with uid " + stringify(uid) +
" and gid " + stringify(gid) + ": " + chown.error());
}
}
// TODO(tnachen): We should check if the target already exists
// when we support updating persistent mounts.
const string target = path::join(directory, containerPath);
Try<Nothing> mkdir = os::mkdir(target);
if (mkdir.isError()) {
return Error("Failed to create persistent mount point at '" + target
+ "': " + mkdir.error());
}
LOG(INFO) << "Mounting '" << source << "' to '" << target
<< "' for persistent volume " << resource
<< " of container " << containerId;
// Bind mount the persistent volume to the container.
Try<Nothing> mount = fs::mount(source, target, None(), MS_BIND, nullptr);
if (mount.isError()) {
return Error(
"Failed to mount persistent volume from '" +
source + "' to '" + target + "': " + mount.error());
}
// If the mount needs to be read-only, do a remount.
if (resource.disk().volume().mode() == Volume::RO) {
mount = fs::mount(
None(), target, None(), MS_BIND | MS_RDONLY | MS_REMOUNT, nullptr);
if (mount.isError()) {
return Error(
"Failed to remount persistent volume as read-only from '" +
source + "' to '" + target + "': " + mount.error());
}
}
}
#else
if (!current.persistentVolumes().empty() ||
!updated.persistentVolumes().empty()) {
return Error("Persistent volumes are only supported on linux");
}
#endif // __linux__
return Nothing();
}
Future<Nothing> DockerContainerizerProcess::mountPersistentVolumes(
const ContainerID& containerId)
{
if (!containers_.contains(containerId)) {
return Failure("Container is already destroyed");
}
Container* container = containers_.at(containerId);
container->state = Container::MOUNTING;
if (!container->containerConfig.has_task_info() &&
!container->resources.persistentVolumes().empty()) {
LOG(ERROR) << "Persistent volumes found with container '" << containerId
<< "' but are not supported with custom executors";
return Nothing();
}
Try<Nothing> updateVolumes = updatePersistentVolumes(
containerId,
container->containerWorkDir,
Resources(),
container->resources);
if (updateVolumes.isError()) {
return Failure(updateVolumes.error());
}
return Nothing();
}
/**
* Unmount persistent volumes that is mounted for a container.
*/
Try<Nothing> DockerContainerizerProcess::unmountPersistentVolumes(
const ContainerID& containerId)
{
// We assume volumes are only supported on Linux, and also
// the target path contains the containerId.
#ifdef __linux__
Try<fs::MountInfoTable> table = fs::MountInfoTable::read();
if (table.isError()) {
return Error("Failed to get mount table: " + table.error());
}
vector<string> unmountErrors;
foreach (const fs::MountInfoTable::Entry& entry,
adaptor::reverse(table->entries)) {
// TODO(tnachen): We assume there is only one docker container
// running per container Id and no other mounts will have the
// container Id name. We might need to revisit if this is no
// longer true.
//
// TODO(jieyu): Currently, we don't enforce that slave's work_dir
// is a slave+shared mount (similar to what we did in the Linux
// filesystem isolator). Therefore, it's likely that the
// persistent volume mounts are propagate to other mount points in
// the system (MESOS-4832). That's the reason we need the
// 'startsWith' check below. Consider making sure slave's work_dir
// is a slave_shared mount. In that way, we can lift that check.
//
// TODO(jieyu): Consider checking if 'entry.root' is under volume
// root directory or not as well.
if (strings::startsWith(entry.target, flags.work_dir) &&
strings::contains(entry.target, containerId.value())) {
LOG(INFO) << "Unmounting volume for container '" << containerId << "'";
// TODO(jieyu): Use MNT_DETACH here to workaround an issue of
// incorrect handling of container destroy failures. Currently,
// if unmount fails there, the containerizer will still treat
// the container as terminated, and the agent will schedule the
// cleanup of the container's sandbox. Since the mount hasn't
// been removed in the sandbox, that'll result in data in the
// persistent volume being incorrectly deleted. Use MNT_DETACH
// here so that the mount point in the sandbox will be removed
// immediately. See MESOS-7366 for more details.
Try<Nothing> unmount = fs::unmount(entry.target, MNT_DETACH);
if (unmount.isError()) {
// NOTE: Instead of short circuit, we try to perform as many
// unmount as possible. We'll accumulate the errors together
// in the end.
unmountErrors.push_back(
"Failed to unmount volume '" + entry.target +
"': " + unmount.error());
}
}
}
if (!unmountErrors.empty()) {
return Error(strings::join(", ", unmountErrors));
}
#endif // __linux__
return Nothing();
}
#ifdef __linux__
Future<Nothing> DockerContainerizerProcess::allocateNvidiaGpus(
const ContainerID& containerId,
const size_t count)
{
if (!nvidia.isSome()) {
return Failure("Attempted to allocate GPUs"
" without Nvidia libraries available");
}
if (!containers_.contains(containerId)) {
return Failure("Container is already destroyed");
}
return nvidia->allocator.allocate(count)
.then(defer(
self(),
&Self::_allocateNvidiaGpus,
containerId,
lambda::_1));
}
Future<Nothing> DockerContainerizerProcess::_allocateNvidiaGpus(
const ContainerID& containerId,
const set<Gpu>& allocated)
{
if (!containers_.contains(containerId)) {
return nvidia->allocator.deallocate(allocated);
}
foreach (const Gpu& gpu, allocated) {
containers_.at(containerId)->gpus.insert(gpu);
}
return Nothing();
}
Future<Nothing> DockerContainerizerProcess::deallocateNvidiaGpus(
const ContainerID& containerId)
{
if (!nvidia.isSome()) {
return Failure("Attempted to deallocate GPUs"
" without Nvidia libraries available");
}
return nvidia->allocator.deallocate(containers_.at(containerId)->gpus)
.then(defer(
self(),
&Self::_deallocateNvidiaGpus,
containerId,
containers_.at(containerId)->gpus));
}
Future<Nothing> DockerContainerizerProcess::_deallocateNvidiaGpus(
const ContainerID& containerId,
const set<Gpu>& deallocated)
{
if (containers_.contains(containerId)) {
foreach (const Gpu& gpu, deallocated) {
containers_.at(containerId)->gpus.erase(gpu);
}
}
return Nothing();
}
#endif // __linux__
Try<Nothing> DockerContainerizerProcess::checkpoint(
const ContainerID& containerId,
pid_t pid)
{
CHECK(containers_.contains(containerId));
Container* container = containers_.at(containerId);
container->executorPid = pid;
if (container->pidCheckpointPath.isSome()) {
LOG(INFO) << "Checkpointing pid " << pid
<< " to '" << container->pidCheckpointPath.get() << "'";
return slave::state::checkpoint(
container->pidCheckpointPath.get(), stringify(pid));
}
return Nothing();
}
Future<Nothing> DockerContainerizer::recover(
const Option<SlaveState>& state)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::recover,
state);
}
Future<Containerizer::LaunchResult> DockerContainerizer::launch(
const ContainerID& containerId,
const ContainerConfig& containerConfig,
const map<string, string>& environment,
const Option<string>& pidCheckpointPath)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::launch,
containerId,
containerConfig,
environment,
pidCheckpointPath);
}
Future<Nothing> DockerContainerizer::update(
const ContainerID& containerId,
const Resources& resources)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::update,
containerId,
resources,
false);
}
Future<ResourceStatistics> DockerContainerizer::usage(
const ContainerID& containerId)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::usage,
containerId);
}
Future<ContainerStatus> DockerContainerizer::status(
const ContainerID& containerId)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::status,
containerId);
}
Future<Option<ContainerTermination>> DockerContainerizer::wait(
const ContainerID& containerId)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::wait,
containerId);
}
Future<Option<ContainerTermination>> DockerContainerizer::destroy(
const ContainerID& containerId)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::destroy,
containerId, true);
}
Future<hashset<ContainerID>> DockerContainerizer::containers()
{
return dispatch(process.get(), &DockerContainerizerProcess::containers);
}
Future<Nothing> DockerContainerizer::pruneImages(
const vector<Image>& excludedImages)
{
VLOG(1) << "DockerContainerizer does not support pruneImages";
return Nothing();
}
Future<Nothing> DockerContainerizerProcess::recover(
const Option<SlaveState>& state)
{
LOG(INFO) << "Recovering Docker containers";
// Get the list of all Docker containers (running and exited) in
// order to remove any orphans and reconcile checkpointed executors.
return docker->ps(true, DOCKER_NAME_PREFIX)
.then(defer(self(), &Self::_recover, state, lambda::_1));
}
Future<Nothing> DockerContainerizerProcess::_recover(
const Option<SlaveState>& state,
const vector<Docker::Container>& _containers)
{
LOG(INFO) << "Got the list of Docker containers";
if (state.isSome()) {
// This mapping of ContainerIDs to running Docker container names
// is established for two reasons:
// * Docker containers launched by Mesos versions prior to 0.23
// did not checkpoint the container type, so the Docker
// Containerizer does not know if it should recover that
// container or not.
// * The naming scheme of Docker containers changed in Mesos
// versions 0.23 and 1.4. The Docker Containerizer code needs
// to use the name of the container when interacting with the
// Docker CLI, rather than generating the container name
// based on the current version's scheme.
hashmap<ContainerID, string> existingContainers;
// Tracks all the task containers that launched an executor in
// a docker container.
hashset<ContainerID> executorContainers;
foreach (const Docker::Container& container, _containers) {
Option<ContainerID> id = parse(container);
if (id.isSome()) {
// NOTE: The container name returned by `docker inspect` may
// sometimes be prefixed with a forward slash. While this is
// technically part of the container name, subsequent calls
// to the Docker CLI do not expect the prefix.
existingContainers[id.get()] = strings::remove(
container.name, "/", strings::PREFIX);
if (strings::contains(container.name, ".executor")) {
executorContainers.insert(id.get());
}
}
}
// Collection of pids that we've started reaping in order to
// detect very unlikely duplicate scenario (see below).
hashmap<ContainerID, pid_t> pids;
foreachvalue (const FrameworkState& framework, state->frameworks) {
foreachvalue (const ExecutorState& executor, framework.executors) {
if (executor.info.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its info could not be recovered";
continue;
}
if (executor.latest.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its latest run could not be recovered";
continue;
}
// We are only interested in the latest run of the executor!
const ContainerID& containerId = executor.latest.get();
Option<RunState> run = executor.runs.get(containerId);
CHECK_SOME(run);
CHECK_SOME(run->id);
CHECK_EQ(containerId, run->id.get());
// We need the pid so the reaper can monitor the executor so skip this
// executor if it's not present. We will also skip this executor if the
// libprocess pid is not present which means the slave exited before
// checkpointing it, in which case the executor will shutdown itself
// immediately. Both of these two cases are safe to skip because the
// slave will try to wait on the container which will return `None()`
// and everything will get cleaned up.
if (run->forkedPid.isNone() || run->libprocessPid.isNone()) {
continue;
}
if (run->completed) {
VLOG(1) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its latest run "
<< containerId << " is completed";
continue;
}
const ExecutorInfo executorInfo = executor.info.get();
if (executorInfo.has_container() &&
executorInfo.container().type() != ContainerInfo::DOCKER) {
LOG(INFO) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because it was not launched from docker "
<< "containerizer";
continue;
}
if (!executorInfo.has_container() &&
!existingContainers.contains(containerId)) {
LOG(INFO) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its executor is not marked as docker "
<< "and the docker container doesn't exist";
continue;
}
LOG(INFO) << "Recovering container '" << containerId
<< "' for executor '" << executor.id
<< "' of framework " << framework.id;
// Create and store a container.
Container* container = new Container(containerId);
containers_[containerId] = container;
container->state = Container::RUNNING;
container->launchesExecutorContainer =
executorContainers.contains(containerId);
if (existingContainers.contains(containerId)) {
container->containerName = existingContainers.at(containerId);
}
// Only reap the executor process if the executor can be connected
// otherwise just set `container->status` to `None()`. This is to
// avoid reaping an irrelevant process, e.g., after the agent host is
// rebooted, the executor pid happens to be reused by another process.
// See MESOS-8125 for details.
// Note that if both the pid and the port of the executor are reused
// by another process or two processes respectively after the agent
// host reboots we will still reap an irrelevant process, but that
// should be highly unlikely.
pid_t pid = run->forkedPid.get();
// Create a TCP socket.
Try<int_fd> socket = net::socket(AF_INET, SOCK_STREAM, 0);
if (socket.isError()) {
return Failure(
"Failed to create socket for connecting to executor '" +
stringify(executor.id) + "': " + socket.error());
}
Try<Nothing, SocketError> connect = process::network::connect(
socket.get(),
run->libprocessPid->address);
if (connect.isSome()) {
container->status.set(process::reap(pid));
} else {
LOG(WARNING) << "Failed to connect to executor '" << executor.id
<< "' of framework " << framework.id << ": "
<< connect.error().message;
container->status.set(Future<Option<int>>(None()));
}
// Shutdown and close the socket.
::shutdown(socket.get(), SHUT_RDWR);
os::close(socket.get());
container->status.future()
->onAny(defer(self(), &Self::reaped, containerId));
if (pids.containsValue(pid)) {
// This should (almost) never occur. There is the
// possibility that a new executor is launched with the same
// pid as one that just exited (highly unlikely) and the
// slave dies after the new executor is launched but before
// it hears about the termination of the earlier executor
// (also unlikely).
return Failure(
"Detected duplicate pid " + stringify(pid) +
" for container " + stringify(containerId));
}
pids.put(containerId, pid);
const string sandboxDirectory = paths::getExecutorRunPath(
flags.work_dir,
state->id,
framework.id,
executor.id,
containerId);
container->containerWorkDir = sandboxDirectory;
}
}
}
if (flags.docker_kill_orphans) {
return __recover(_containers);
}
return Nothing();
}
Future<Nothing> DockerContainerizerProcess::__recover(
const vector<Docker::Container>& _containers)
{
vector<ContainerID> containerIds;
vector<Future<Nothing>> futures;
foreach (const Docker::Container& container, _containers) {
VLOG(1) << "Checking if Docker container named '"
<< container.name << "' was started by Mesos";
Option<ContainerID> id = parse(container);
// Ignore containers that Mesos didn't start.
if (id.isNone()) {
continue;
}
VLOG(1) << "Checking if Mesos container with ID '"
<< stringify(id.get()) << "' has been orphaned";
// Check if we're watching an executor for this container ID and
// if not, rm -f the Docker container.
if (!containers_.contains(id.get())) {
// TODO(alexr): After the deprecation cycle (started in 1.0), update
// this to omit the timeout. Graceful shutdown of the container is not
// a containerizer responsibility; it is the responsibility of the agent
// in co-operation with the executor. Once `destroy()` is called, the
// container should be destroyed forcefully.
futures.push_back(
docker->stop(
container.id,
flags.docker_stop_timeout,
true));
containerIds.push_back(id.get());
}
}
return collect(futures)
.then(defer(self(), [=]() -> Future<Nothing> {
foreach (const ContainerID& containerId, containerIds) {
Try<Nothing> unmount = unmountPersistentVolumes(containerId);
if (unmount.isError()) {
return Failure("Unable to unmount volumes for Docker container '" +
containerId.value() + "': " + unmount.error());
}
}
LOG(INFO) << "Finished processing orphaned Docker containers";
return Nothing();
}));
}
Future<Containerizer::LaunchResult> DockerContainerizerProcess::launch(
const ContainerID& containerId,
const ContainerConfig& containerConfig,
const map<string, string>& environment,
const Option<string>& pidCheckpointPath)
{
if (containerId.has_parent()) {
return Failure("Nested containers are not supported");
}
if (containers_.contains(containerId)) {
return Failure("Container already started");
}
if (!containerConfig.has_container_info()) {
LOG(INFO) << "No container info found, skipping launch";
return Containerizer::LaunchResult::NOT_SUPPORTED;
}
if (containerConfig.container_info().type() != ContainerInfo::DOCKER) {
LOG(INFO) << "Skipping non-docker container";
return Containerizer::LaunchResult::NOT_SUPPORTED;
}
Try<Container*> container = Container::create(
containerId,
containerConfig,
environment,
pidCheckpointPath,
flags);
if (container.isError()) {
return Failure("Failed to create container: " + container.error());
}
containers_[containerId] = container.get();
LOG(INFO)
<< "Starting container '" << containerId
<< (containerConfig.has_task_info()
? "' for task '" + stringify(containerConfig.task_info().task_id())
: "")
<< "' (and executor '" << containerConfig.executor_info().executor_id()
<< "') of framework " << containerConfig.executor_info().framework_id();
Future<Nothing> f = Nothing();
if (HookManager::hooksAvailable()) {
f = HookManager::slavePreLaunchDockerTaskExecutorDecorator(
containerConfig.has_task_info()
? containerConfig.task_info()
: Option<TaskInfo>::none(),
containerConfig.executor_info(),
container.get()->containerName,
container.get()->containerWorkDir,
flags.sandbox_directory,
container.get()->environment)
.then(defer(self(), [this, containerId, containerConfig](
const DockerTaskExecutorPrepareInfo& decoratorInfo)
-> Future<Nothing> {
if (!containers_.contains(containerId)) {
return Failure("Container is already destroyed");
}
Container* container = containers_.at(containerId);
if (decoratorInfo.has_executorenvironment()) {
foreach (
const Environment::Variable& variable,
decoratorInfo.executorenvironment().variables()) {
// TODO(tillt): Tell the user about overrides possibly
// happening here while making sure we state the source
// hook causing this conflict.
container->environment[variable.name()] =
variable.value();
}
}
if (!decoratorInfo.has_taskenvironment()) {
return Nothing();
}
map<string, string> taskEnvironment;
foreach (
const Environment::Variable& variable,
decoratorInfo.taskenvironment().variables()) {
taskEnvironment[variable.name()] = variable.value();
}
if (containerConfig.has_task_info()) {
container->taskEnvironment = taskEnvironment;
// For dockerized command executors, the flags have already
// been serialized into the command, albeit without these
// environment variables. Append the last flag to the
// overridden command.
if (container->launchesExecutorContainer) {
container->command.add_arguments(
"--task_environment=" +
string(jsonify(taskEnvironment)));
}
} else {
// For custom executors, the environment variables from a
// hook are passed directly into the executor. It is up to
// the custom executor whether individual tasks should
// inherit these variables.
foreachpair (
const string& key,
const string& value,
taskEnvironment) {
container->environment[key] = value;
}
}
return Nothing();
}));
}
return f.then(defer(
self(),
&Self::_launch,
containerId,
containerConfig));
}
Future<Containerizer::LaunchResult> DockerContainerizerProcess::_launch(
const ContainerID& containerId,
const ContainerConfig& containerConfig)
{
if (!containers_.contains(containerId)) {
return Failure("Container is already destroyed");
}
Container* container = containers_.at(containerId);
if (containerConfig.has_task_info() && flags.docker_mesos_image.isNone()) {
// Launching task by forking a subprocess to run docker executor.
// TODO(steveniemitz): We should call 'update' to set CPU/CFS/mem
// quotas after 'launchExecutorProcess'. However, there is a race
// where 'update' can be called before mesos-docker-executor
// creates the Docker container for the task. See more details in
// the comments of r33174.
return container->launch = fetch(containerId)
.then(defer(self(), [=]() {
return pull(containerId);
}))
.then(defer(self(), [=]() {
if (HookManager::hooksAvailable()) {
HookManager::slavePostFetchHook(
containerId, containerConfig.directory());
}
return mountPersistentVolumes(containerId);
}))
.then(defer(self(), [=]() {
return launchExecutorProcess(containerId);
}))
.then(defer(self(), [=](pid_t pid) {
return reapExecutor(containerId, pid);
}))
.then([]() {
return Containerizer::LaunchResult::SUCCESS;
});
}
string containerName = container->containerName;
if (container->executorName().isSome()) {
// Launch the container with the executor name as we expect the
// executor will launch the docker container.
containerName = container->executorName().get();
}
// Launching task or executor by launching a separate docker
// container to run the executor.
// We need to do so for launching a task because as the slave is
// running in a container (via docker_mesos_image flag) we want the
// executor to keep running when the slave container dies.
return container->launch = fetch(containerId)
.then(defer(self(), [=]() {
return pull(containerId);
}))
.then(defer(self(), [=]() {
if (HookManager::hooksAvailable()) {
HookManager::slavePostFetchHook(
containerId, containerConfig.directory());
}
return mountPersistentVolumes(containerId);
}))
.then(defer(self(), [=]() {
return launchExecutorContainer(containerId, containerName);
}))
.then(defer(self(), [=](const Docker::Container& dockerContainer) {
// Call update to set CPU/CFS/mem quotas at launch.
// TODO(steveniemitz): Once the minimum docker version supported
// is >= 1.7 this can be changed to pass --cpu-period and
// --cpu-quota to the 'docker run' call in
// launchExecutorContainer.
return update(
containerId, containerConfig.executor_info().resources(), true)
.then([=]() {
return Future<Docker::Container>(dockerContainer);
});
}))
.then(defer(self(), [=](const Docker::Container& dockerContainer) {
return checkpointExecutor(containerId, dockerContainer);
}))
.then(defer(self(), [=](pid_t pid) {
return reapExecutor(containerId, pid);
}))
.then([]() {
return Containerizer::LaunchResult::SUCCESS;
});
}
Future<Docker::Container> DockerContainerizerProcess::launchExecutorContainer(
const ContainerID& containerId,
const string& containerName)
{
if (!containers_.contains(containerId)) {
return Failure("Container is already destroyed");
}
if (containers_[containerId]->state == Container::DESTROYING) {
return Failure(
"Container is being destroyed during launching excutor container");
}
Container* container = containers_.at(containerId);
container->state = Container::RUNNING;
return logger->prepare(container->id, container->containerConfig)
.then(defer(
self(),
[=](const ContainerIO& containerIO)
-> Future<Docker::Container> {
// We need to pass `flags.default_container_dns` only when the agent is not
// running in a Docker container. This is to handle the case of launching a
// custom executor in a Docker container. If the agent is running in a
// Docker container (i.e., flags.docker_mesos_image.isSome() == true), that
// is the case of launching `mesos-docker-executor` in a Docker container
// with the Docker image `flags.docker_mesos_image`. In that case we already
// set `flags.default_container_dns` in the method `dockerFlags()`.
Try<Docker::RunOptions> runOptions = Docker::RunOptions::create(
container->container,
container->command,
containerName,
container->containerWorkDir,
flags.sandbox_directory,
container->resources,
#ifdef __linux__
flags.cgroups_enable_cfs,
#else
false,
#endif
container->environment,
None(), // No extra devices.
flags.docker_mesos_image.isNone() ? flags.default_container_dns : None()
);
if (runOptions.isError()) {
return Failure(runOptions.error());
}
// Start the executor in a Docker container.
// This executor could either be a custom executor specified by an
// ExecutorInfo, or the docker executor.
Future<Option<int>> run = docker->run(
runOptions.get(),
containerIO.out,
containerIO.err);
// It's possible that 'run' terminates before we're able to
// obtain an 'inspect' result. It's also possible that 'run'
// fails in such a manner that we will never see the container
// via 'inspect'. In these cases we discard the 'inspect' and
// propagate a failure back.
auto promise = std::make_shared<Promise<Docker::Container>>();
Future<Docker::Container> inspect =
docker->inspect(containerName, slave::DOCKER_INSPECT_DELAY);
inspect
.onAny([=](Future<Docker::Container> container) {
promise->associate(container);
});
run.onAny([=]() mutable {
if (!run.isReady()) {
promise->fail(run.isFailed() ? run.failure() : "discarded");
inspect.discard();
} else if (run->isNone()) {
promise->fail("Failed to obtain exit status of container");
inspect.discard();
} else {
if (!WSUCCEEDED(run->get())) {
promise->fail("Container " + WSTRINGIFY(run->get()));
inspect.discard();
}
// TODO(bmahler): Handle the case where the 'run' exits
// cleanly but no 'inspect' result is available.
}
});
return promise->future();
}));
}
Future<pid_t> DockerContainerizerProcess::launchExecutorProcess(
const ContainerID& containerId)
{
if (!containers_.contains(containerId)) {
return Failure("Container is already destroyed");
}
if (containers_[containerId]->state == Container::DESTROYING) {
return Failure(
"Container is being destroyed during launching executor process");
}
Container* container = containers_.at(containerId);
container->state = Container::RUNNING;
// Prepare environment variables for the executor.
map<string, string> environment = container->environment;
// Include any environment variables from ExecutorInfo.
foreach (const Environment::Variable& variable,
container->containerConfig.executor_info()
.command().environment().variables()) {
const string& name = variable.name();
const string& value = variable.value();
if (environment.count(name)) {
VLOG(1) << "Overwriting environment variable '"
<< name << "', original: '"
<< environment[name] << "', new: '"
<< value << "', for container "
<< container->id;
}
environment[name] = value;
}
// Pass GLOG flag to the executor.
const Option<string> glog = os::getenv("GLOG_v");
if (glog.isSome()) {
environment["GLOG_v"] = glog.get();
}
if (environment.count("PATH") == 0) {
environment["PATH"] = os::host_default_path();
// TODO(andschwa): We will consider removing the `#ifdef` in future, as
// other platforms may benefit from being pointed to the same `docker` in
// both Agent and Executor (there is a chance that the cleaned path results
// in using a different docker, if multiple dockers are installed).
#ifdef __WINDOWS__
// Docker is generally not installed in `os::host_default_path()` on
// Windows, so the executor will not be able to find `docker`. We search for
// `docker` in `PATH` and prepend the parent directory to
// `environment["PATH"]`. We prepend instead of append so that in the off
// chance that `docker` is in `host_default_path`, the executor and agent
// will use the same `docker`.
Option<string> dockerPath = os::which("docker");
if (dockerPath.isSome()) {
environment["PATH"] =
Path(dockerPath.get()).dirname() + ";" + environment["PATH"];
}
#endif // __WINDOWS__
}
vector<string> argv;
argv.push_back(MESOS_DOCKER_EXECUTOR);
Future<Nothing> allocateGpus = Nothing();
#ifdef __linux__
Option<double> gpus = Resources(container->resources).gpus();
if (gpus.isSome() && gpus.get() > 0) {
// Make sure that the `gpus` resource is not fractional.
// We rely on scalar resources only have 3 digits of precision.
if (static_cast<long long>(gpus.get() * 1000.0) % 1000 != 0) {
return Failure("The 'gpus' resource must be an unsigned integer");
}
allocateGpus = allocateNvidiaGpus(containerId, gpus.get());
}
#endif // __linux__
return allocateGpus
.then(defer(self(), [=]() {
return logger->prepare(container->id, container->containerConfig);
}))
.then(defer(
self(),
[=](const ContainerIO& containerIO)
-> Future<pid_t> {
// NOTE: The child process will be blocked until all hooks have been
// executed.
vector<Subprocess::ParentHook> parentHooks;
// NOTE: Currently we don't care about the order of the hooks, as
// both hooks are independent.
// A hook that is executed in the parent process. It attempts to checkpoint
// the process pid.
//
// NOTE:
// - The child process is blocked by the hook infrastructure while
// these hooks are executed.
// - It is safe to bind `this`, as hooks are executed immediately
// in a `subprocess` call.
// - If `checkpoiont` returns an Error, the child process will be killed.
parentHooks.emplace_back(Subprocess::ParentHook(lambda::bind(
&DockerContainerizerProcess::checkpoint,
this,
containerId,
lambda::_1)));
#ifdef __linux__
// If we are on systemd, then extend the life of the executor. Any
// grandchildren's lives will also be extended.
if (systemd::enabled()) {
parentHooks.emplace_back(Subprocess::ParentHook(
&systemd::mesos::extendLifetime));
}
#elif __WINDOWS__
parentHooks.emplace_back(Subprocess::ParentHook::CREATE_JOB());
// Setting the "kill on close" job object limit ties the lifetime of the
// docker processes to that of the executor. This ensures that if the
// executor exits, the docker processes aren't leaked.
parentHooks.emplace_back(Subprocess::ParentHook(
[](pid_t pid) { return os::set_job_kill_on_close_limit(pid); }));
#endif // __linux__
// Prepare the flags to pass to the mesos docker executor process.
::mesos::internal::docker::Flags launchFlags = dockerFlags(
flags,
container->containerName,
container->containerWorkDir,
container->taskEnvironment);
VLOG(1) << "Launching 'mesos-docker-executor' with flags '"
<< launchFlags << "'";
// Construct the mesos-docker-executor using the "name" we gave the
// container (to distinguish it from Docker containers not created
// by Mesos).
Try<Subprocess> s = subprocess(
path::join(flags.launcher_dir, MESOS_DOCKER_EXECUTOR),
argv,
Subprocess::PIPE(),
containerIO.out,
containerIO.err,
&launchFlags,
environment,
None(),
parentHooks,
{Subprocess::ChildHook::SETSID(),
Subprocess::ChildHook::CHDIR(container->containerWorkDir)});
if (s.isError()) {
return Failure("Failed to fork executor: " + s.error());
}
return s->pid();
}));
}
Future<pid_t> DockerContainerizerProcess::checkpointExecutor(
const ContainerID& containerId,
const Docker::Container& dockerContainer)
{
// After we do Docker::run we shouldn't remove a container until
// after we set Container::status.
CHECK(containers_.contains(containerId));
Option<pid_t> pid = dockerContainer.pid;
if (!pid.isSome()) {
return Failure("Unable to get executor pid after launch");
}
Try<Nothing> checkpointed = checkpoint(containerId, pid.get());
if (checkpointed.isError()) {
return Failure(
"Failed to checkpoint executor's pid: " + checkpointed.error());
}
return pid.get();
}
Future<Nothing> DockerContainerizerProcess::reapExecutor(
const ContainerID& containerId,
pid_t pid)
{
// After we do Docker::run we shouldn't remove a container until
// after we set 'status', which we do in this function.
CHECK(containers_.contains(containerId));
Container* container = containers_.at(containerId);
// And finally watch for when the container gets reaped.
container->status.set(process::reap(pid));
container->status.future()
->onAny(defer(self(), &Self::reaped, containerId));
return Nothing();
}
Future<Nothing> DockerContainerizerProcess::update(
const ContainerID& containerId,
const Resources& _resources,
bool force)
{
CHECK(!containerId.has_parent());
if (!containers_.contains(containerId)) {
LOG(WARNING) << "Ignoring updating unknown container " << containerId;
return Nothing();
}
Container* container = containers_.at(containerId);
if (container->state == Container::DESTROYING) {
LOG(INFO) << "Ignoring updating container " << containerId
<< " that is being destroyed";
return Nothing();
}
if (container->resources == _resources && !force) {
LOG(INFO) << "Ignoring updating container " << containerId
<< " because resources passed to update are identical to"
<< " existing resources";
return Nothing();
}
// TODO(tnachen): Support updating persistent volumes, which requires
// Docker mount propagation support.
// TODO(gyliu): Support updating GPU resources.
// Store the resources for usage().
container->resources = _resources;
#ifdef __linux__
if (!_resources.cpus().isSome() && !_resources.mem().isSome()) {
LOG(WARNING) << "Ignoring update as no supported resources are present";
return Nothing();
}
// Skip inspecting the docker container if we already have the pid.
if (container->pid.isSome()) {
return __update(containerId, _resources, container->pid.get());
}
string containerName = containers_.at(containerId)->containerName;
// Since the Docker daemon might hang, we have to retry the inspect command.
//
// NOTE: This code is duplicated from the built-in docker executor, but
// the retry interval is not passed to `inspect`, because the container might
// be terminated.
// TODO(abudnik): Consider using a class helper for retrying docker commands.
auto inspectLoop = loop(
self(),
[=]() {
return await(
docker->inspect(containerName)
.after(
slave::DOCKER_INSPECT_TIMEOUT,
[=](Future<Docker::Container> future) {
LOG(WARNING) << "Docker inspect timed out after "
<< slave::DOCKER_INSPECT_TIMEOUT
<< " for container "
<< "'" << containerName << "'";
// We need to clean up the hanging Docker CLI process.
// Discarding the inspect future triggers a callback in
// the Docker library that kills the subprocess and
// transitions the future.
future.discard();
return future;
}));
},
[](const Future<Docker::Container>& future)
-> Future<ControlFlow<Docker::Container>> {
if (future.isReady()) {
return Break(future.get());
}
if (future.isFailed()) {
return Failure(future.failure());
}
return Continue();
});
return inspectLoop
.then(defer(self(), &Self::_update, containerId, _resources, lambda::_1));
#else
return Nothing();
#endif // __linux__
}
Future<Nothing> DockerContainerizerProcess::_update(
const ContainerID& containerId,
const Resources& _resources,
const Docker::Container& container)
{
if (container.pid.isNone()) {
return Nothing();
}
if (!containers_.contains(containerId)) {
LOG(INFO) << "Container has been removed after docker inspect, "
<< "skipping update";
return Nothing();
}
containers_.at(containerId)->pid = container.pid.get();
return __update(containerId, _resources, container.pid.get());
}
Future<Nothing> DockerContainerizerProcess::__update(
const ContainerID& containerId,
const Resources& _resources,
pid_t pid)
{
#ifdef __linux__
// Determine the cgroups hierarchies where the 'cpu' and
// 'memory' subsystems are mounted (they may be the same). Note that
// we make these static so we can reuse the result for subsequent
// calls.
static Result<string> cpuHierarchy = cgroups::hierarchy("cpu");
static Result<string> memoryHierarchy = cgroups::hierarchy("memory");
// NOTE: Normally, a Docker container should be in its own cgroup.
// However, a zombie process (exited but not reaped) will be
// temporarily moved into the system root cgroup. We add some
// defensive check here to make sure we are not changing the knobs
// in the root cgroup. See MESOS-8480 for details.
const string systemRootCgroup = stringify(os::PATH_SEPARATOR);
if (cpuHierarchy.isError()) {
return Failure("Failed to determine the cgroup hierarchy "
"where the 'cpu' subsystem is mounted: " +
cpuHierarchy.error());
}
if (memoryHierarchy.isError()) {
return Failure("Failed to determine the cgroup hierarchy "
"where the 'memory' subsystem is mounted: " +
memoryHierarchy.error());
}
// We need to find the cgroup(s) this container is currently running
// in for both the hierarchy with the 'cpu' subsystem attached and
// the hierarchy with the 'memory' subsystem attached so we can
// update the proper cgroup control files.
// Determine the cgroup for the 'cpu' subsystem (based on the
// container's pid).
Result<string> cpuCgroup = cgroups::cpu::cgroup(pid);
if (cpuCgroup.isError()) {
return Failure("Failed to determine cgroup for the 'cpu' subsystem: " +
cpuCgroup.error());
} else if (cpuCgroup.isNone()) {
LOG(WARNING) << "Container " << containerId
<< " does not appear to be a member of a cgroup"
<< " where the 'cpu' subsystem is mounted";
} else if (cpuCgroup.get() == systemRootCgroup) {
LOG(WARNING)
<< "Process '" << pid
<< "' should not be in the system root cgroup (being destroyed?)";
}
// And update the CPU shares (if applicable).
if (cpuHierarchy.isSome() &&
cpuCgroup.isSome() &&
cpuCgroup.get() != systemRootCgroup &&
_resources.cpus().isSome()) {
double cpuShares = _resources.cpus().get();
uint64_t shares =
std::max((uint64_t) (CPU_SHARES_PER_CPU * cpuShares), MIN_CPU_SHARES);
Try<Nothing> write =
cgroups::cpu::shares(cpuHierarchy.get(), cpuCgroup.get(), shares);
if (write.isError()) {
return Failure("Failed to update 'cpu.shares': " + write.error());
}
LOG(INFO) << "Updated 'cpu.shares' to " << shares
<< " at " << path::join(cpuHierarchy.get(), cpuCgroup.get())
<< " for container " << containerId;
// Set cfs quota if enabled.
if (flags.cgroups_enable_cfs) {
write = cgroups::cpu::cfs_period_us(
cpuHierarchy.get(),
cpuCgroup.get(),
CPU_CFS_PERIOD);
if (write.isError()) {
return Failure("Failed to update 'cpu.cfs_period_us': " +
write.error());
}
Duration quota = std::max(CPU_CFS_PERIOD * cpuShares, MIN_CPU_CFS_QUOTA);
write = cgroups::cpu::cfs_quota_us(
cpuHierarchy.get(),
cpuCgroup.get(),
quota);
if (write.isError()) {
return Failure("Failed to update 'cpu.cfs_quota_us': " + write.error());
}
LOG(INFO) << "Updated 'cpu.cfs_period_us' to " << CPU_CFS_PERIOD
<< " and 'cpu.cfs_quota_us' to " << quota
<< " (cpus " << cpuShares << ")"
<< " for container " << containerId;
}
}
// Now determine the cgroup for the 'memory' subsystem.
Result<string> memoryCgroup = cgroups::memory::cgroup(pid);
if (memoryCgroup.isError()) {
return Failure("Failed to determine cgroup for the 'memory' subsystem: " +
memoryCgroup.error());
} else if (memoryCgroup.isNone()) {
LOG(WARNING) << "Container " << containerId
<< " does not appear to be a member of a cgroup"
<< " where the 'memory' subsystem is mounted";
} else if (memoryCgroup.get() == systemRootCgroup) {
LOG(WARNING)
<< "Process '" << pid
<< "' should not be in the system root cgroup (being destroyed?)";
}
// And update the memory limits (if applicable).
if (memoryHierarchy.isSome() &&
memoryCgroup.isSome() &&
memoryCgroup.get() != systemRootCgroup &&
_resources.mem().isSome()) {
// TODO(tnachen): investigate and handle OOM with docker.
Bytes mem = _resources.mem().get();
Bytes limit = std::max(mem, MIN_MEMORY);
// Always set the soft limit.
Try<Nothing> write =
cgroups::memory::soft_limit_in_bytes(
memoryHierarchy.get(), memoryCgroup.get(), limit);
if (write.isError()) {
return Failure("Failed to set 'memory.soft_limit_in_bytes': " +
write.error());
}
LOG(INFO) << "Updated 'memory.soft_limit_in_bytes' to " << limit
<< " for container " << containerId;
// Read the existing limit.
Try<Bytes> currentLimit =
cgroups::memory::limit_in_bytes(
memoryHierarchy.get(), memoryCgroup.get());
if (currentLimit.isError()) {
return Failure("Failed to read 'memory.limit_in_bytes': " +
currentLimit.error());
}
// Only update if new limit is higher.
// TODO(benh): Introduce a MemoryWatcherProcess which monitors the
// discrepancy between usage and soft limit and introduces a
// "manual oom" if necessary.
if (limit > currentLimit.get()) {
write = cgroups::memory::limit_in_bytes(
memoryHierarchy.get(), memoryCgroup.get(), limit);
if (write.isError()) {
return Failure("Failed to set 'memory.limit_in_bytes': " +
write.error());
}
LOG(INFO) << "Updated 'memory.limit_in_bytes' to " << limit << " at "
<< path::join(memoryHierarchy.get(), memoryCgroup.get())
<< " for container " << containerId;
}
}
#endif // __linux__
return Nothing();
}
Future<ResourceStatistics> DockerContainerizerProcess::usage(
const ContainerID& containerId)
{
CHECK(!containerId.has_parent());
if (!containers_.contains(containerId)) {
return Failure("Unknown container: " + stringify(containerId));
}
Container* container = containers_.at(containerId);
if (container->state == Container::DESTROYING) {
return Failure("Container is being removed: " + stringify(containerId));
}
auto collectUsage = [this, containerId](
pid_t pid) -> Future<ResourceStatistics> {
// First make sure container is still there.
if (!containers_.contains(containerId)) {
return Failure("Container has been destroyed: " + stringify(containerId));
}
Container* container = containers_.at(containerId);
if (container->state == Container::DESTROYING) {
return Failure("Container is being removed: " + stringify(containerId));
}
ResourceStatistics result;
#ifdef __linux__
const Try<ResourceStatistics> cgroupStats = cgroupsStatistics(pid);
if (cgroupStats.isError()) {
return Failure("Failed to collect cgroup stats: " + cgroupStats.error());
}
result = cgroupStats.get();
#endif // __linux__
// Set the resource allocations.
const Resources& resource = container->resources;
const Option<Bytes> mem = resource.mem();
if (mem.isSome()) {
result.set_mem_limit_bytes(mem->bytes());
}
const Option<double> cpus = resource.cpus();
if (cpus.isSome()) {
result.set_cpus_limit(cpus.get());
}
return result;
};
// Skip inspecting the docker container if we already have the pid.
if (container->pid.isSome()) {
return collectUsage(container->pid.get());
}
return docker->inspect(container->containerName)
.then(defer(
self(),
[this, containerId, collectUsage]
(const Docker::Container& _container) -> Future<ResourceStatistics> {
const Option<pid_t> pid = _container.pid;
if (pid.isNone()) {
return Failure("Container is not running");
}
if (!containers_.contains(containerId)) {
return Failure(
"Container has been destroyed:" + stringify(containerId));
}
Container* container = containers_.at(containerId);
// Update the container's pid now. We ran inspect because we didn't have
// a pid for the container.
container->pid = pid;
return collectUsage(pid.get());
}));
}
Try<ResourceStatistics> DockerContainerizerProcess::cgroupsStatistics(
pid_t pid) const
{
#ifndef __linux__
return Error("Does not support cgroups on non-linux platform");
#else
const Result<string> cpuacctHierarchy = cgroups::hierarchy("cpuacct");
const Result<string> memHierarchy = cgroups::hierarchy("memory");
// NOTE: Normally, a Docker container should be in its own cgroup.
// However, a zombie process (exited but not reaped) will be
// temporarily moved into the system root cgroup. We add some
// defensive check here to make sure we are not reporting statistics
// for the root cgroup. See MESOS-8480 for details.
const string systemRootCgroup = stringify(os::PATH_SEPARATOR);
if (cpuacctHierarchy.isError()) {
return Error(
"Failed to determine the cgroup 'cpuacct' subsystem hierarchy: " +
cpuacctHierarchy.error());
}
if (memHierarchy.isError()) {
return Error(
"Failed to determine the cgroup 'memory' subsystem hierarchy: " +
memHierarchy.error());
}
const Result<string> cpuacctCgroup = cgroups::cpuacct::cgroup(pid);
if (cpuacctCgroup.isError()) {
return Error(
"Failed to determine cgroup for the 'cpuacct' subsystem: " +
cpuacctCgroup.error());
} else if (cpuacctCgroup.isNone()) {
return Error("Unable to find 'cpuacct' cgroup subsystem");
} else if (cpuacctCgroup.get() == systemRootCgroup) {
return Error(
"Process '" + stringify(pid) +
"' should not be in the system root cgroup (being destroyed?)");
}
const Result<string> memCgroup = cgroups::memory::cgroup(pid);
if (memCgroup.isError()) {
return Error(
"Failed to determine cgroup for the 'memory' subsystem: " +
memCgroup.error());
} else if (memCgroup.isNone()) {
return Error("Unable to find 'memory' cgroup subsystem");
} else if (memCgroup.get() == systemRootCgroup) {
return Error(
"Process '" + stringify(pid) +
"' should not be in the system root cgroup (being destroyed?)");
}
const Try<cgroups::cpuacct::Stats> cpuAcctStat =
cgroups::cpuacct::stat(cpuacctHierarchy.get(), cpuacctCgroup.get());
if (cpuAcctStat.isError()) {
return Error("Failed to get cpu.stat: " + cpuAcctStat.error());
}
const Try<hashmap<string, uint64_t>> memStats =
cgroups::stat(memHierarchy.get(), memCgroup.get(), "memory.stat");
if (memStats.isError()) {
return Error(
"Error getting memory statistics from cgroups memory subsystem: " +
memStats.error());
}
if (!memStats->contains("rss")) {
return Error("cgroups memory stats does not contain 'rss' data");
}
ResourceStatistics result;
result.set_timestamp(Clock::now().secs());
result.set_cpus_system_time_secs(cpuAcctStat->system.secs());
result.set_cpus_user_time_secs(cpuAcctStat->user.secs());
result.set_mem_rss_bytes(memStats->at("rss"));
// Add the cpu.stat information only if CFS is enabled.
if (flags.cgroups_enable_cfs) {
const Result<string> cpuHierarchy = cgroups::hierarchy("cpu");
if (cpuHierarchy.isError()) {
return Error(
"Failed to determine the cgroup 'cpu' subsystem hierarchy: " +
cpuHierarchy.error());
}
const Result<string> cpuCgroup = cgroups::cpu::cgroup(pid);
if (cpuCgroup.isError()) {
return Error(
"Failed to determine cgroup for the 'cpu' subsystem: " +
cpuCgroup.error());
} else if (cpuCgroup.isNone()) {
return Error("Unable to find 'cpu' cgroup subsystem");
} else if (cpuCgroup.get() == systemRootCgroup) {
return Error(
"Process '" + stringify(pid) +
"' should not be in the system root cgroup (being destroyed?)");
}
const Try<hashmap<string, uint64_t>> stat =
cgroups::stat(cpuHierarchy.get(), cpuCgroup.get(), "cpu.stat");
if (stat.isError()) {
return Error("Failed to read cpu.stat: " + stat.error());
}
Option<uint64_t> nr_periods = stat->get("nr_periods");
if (nr_periods.isSome()) {
result.set_cpus_nr_periods(nr_periods.get());
}
Option<uint64_t> nr_throttled = stat->get("nr_throttled");
if (nr_throttled.isSome()) {
result.set_cpus_nr_throttled(nr_throttled.get());
}
Option<uint64_t> throttled_time = stat->get("throttled_time");
if (throttled_time.isSome()) {
result.set_cpus_throttled_time_secs(
Nanoseconds(throttled_time.get()).secs());
}
}
return result;
#endif // __linux__
}
Future<ContainerStatus> DockerContainerizerProcess::status(
const ContainerID& containerId)
{
ContainerStatus result;
result.mutable_container_id()->CopyFrom(containerId);
return result;
}
Future<Option<ContainerTermination>> DockerContainerizerProcess::wait(
const ContainerID& containerId)
{
CHECK(!containerId.has_parent());
if (!containers_.contains(containerId)) {
return None();
}
return containers_.at(containerId)->termination.future()
.then(Option<ContainerTermination>::some);
}
Future<Option<ContainerTermination>> DockerContainerizerProcess::destroy(
const ContainerID& containerId,
bool killed)
{
if (!containers_.contains(containerId)) {
// TODO(bmahler): Currently the agent does not log destroy
// failures or unknown containers, so we log it here for now.
// Move this logging into the callers.
LOG(WARNING) << "Attempted to destroy unknown container " << containerId;
return None();
}
// TODO(klueska): Ideally, we would do this check as the first thing
// we do after entering this function. However, the containerizer
// API currently requires callers of `launch()` to also call
// `destroy()` if the launch fails (MESOS-6214). As such, putting
// the check at the top of this function would cause the
// containerizer to crash if the launch failure was due to the
// container having its `parent` field set. Once we remove the
// requirement for `destroy()` to be called explicitly after launch
// failures, we should move this check to the top of this function.
CHECK(!containerId.has_parent());
Container* container = containers_.at(containerId);
if (container->launch.isFailed()) {
VLOG(1) << "Container " << containerId << " launch failed";
// This means we failed to launch the container and we're trying to
// cleanup.
CHECK_PENDING(container->status.future());
ContainerTermination termination;
// NOTE: The launch error message will be retrieved by the slave
// and properly set in the corresponding status update.
container->termination.set(termination);
containers_.erase(containerId);
delete container;
return termination;
}
if (container->state == Container::DESTROYING) {
return container->termination.future()
.then(Option<ContainerTermination>::some);
}
// It's possible that destroy is getting called before
// DockerContainerizer::launch has completed (i.e., after we've
// returned a future but before we've completed the fetching of the
// URIs, or the Docker::run, or the wait, etc.).
//
// If we're FETCHING, we want to stop the fetching and then
// cleanup. Note, we need to make sure that we deal with the race
// with trying to terminate the fetcher so that even if the fetcher
// returns successfully we won't try to do a Docker::run.
//
// If we're PULLING, we want to terminate the 'docker pull' and then
// cleanup. Just as above, we'll need to deal with the race with
// 'docker pull' returning successfully.
//
// If we're MOUNTING, we want to unmount all the persistent volumes
// that has been mounted.
//
// If we're RUNNING, we want to wait for the status to get set, then
// do a Docker::kill, then wait for the status to complete, then
// cleanup.
if (container->state == Container::FETCHING) {
LOG(INFO) << "Destroying container " << containerId << " in FETCHING state";
fetcher->kill(containerId);
ContainerTermination termination;
termination.set_message("Container destroyed while fetching");
container->termination.set(termination);
// Even if the fetch succeeded just before we did the killtree,
// removing the container here means that we won't proceed with
// the Docker::run.
containers_.erase(containerId);
delete container;
return termination;
}
if (container->state == Container::PULLING) {
LOG(INFO) << "Destroying container " << containerId << " in PULLING state";
container->pull.discard();
ContainerTermination termination;
termination.set_message("Container destroyed while pulling image");
container->termination.set(termination);
containers_.erase(containerId);
delete container;
return termination;
}
if (container->state == Container::MOUNTING) {
LOG(INFO) << "Destroying container " << containerId << " in MOUNTING state";
// Persistent volumes might already been mounted, remove them
// if necessary.
Try<Nothing> unmount = unmountPersistentVolumes(containerId);
if (unmount.isError()) {
LOG(WARNING) << "Failed to remove persistent volumes on destroy for"
<< " container " << containerId << ": " << unmount.error();
}
ContainerTermination termination;
termination.set_message("Container destroyed while mounting volumes");
container->termination.set(termination);
containers_.erase(containerId);
delete container;
return termination;
}
CHECK(container->state == Container::RUNNING);
LOG(INFO) << "Destroying container " << containerId << " in RUNNING state";
container->state = Container::DESTROYING;
if (killed && container->executorPid.isSome()) {
LOG(INFO) << "Sending SIGTERM to executor with pid: "
<< container->executorPid.get();
// We need to clean up the executor as the executor might not have
// received run task due to a failed containerizer update.
// We also kill the executor first since container->status below
// is waiting for the executor to finish.
Try<list<os::ProcessTree>> kill =
os::killtree(container->executorPid.get(), SIGTERM);
if (kill.isError()) {
// Ignoring the error from killing executor as it can already
// have exited.
VLOG(1) << "Ignoring error when killing executor pid "
<< container->executorPid.get() << " in destroy, error: "
<< kill.error();
}
}
// Otherwise, wait for Docker::run to succeed, in which case we'll
// continue in _destroy (calling Docker::kill) or for Docker::run to
// fail, in which case we'll re-execute this function and cleanup
// above.
container->status.future()
.onAny(defer(self(), &Self::_destroy, containerId, killed));
return container->termination.future()
.then(Option<ContainerTermination>::some);
}
void DockerContainerizerProcess::_destroy(
const ContainerID& containerId,
bool killed)
{
CHECK(containers_.contains(containerId));
Container* container = containers_.at(containerId);
CHECK(container->state == Container::DESTROYING);
// Do a 'docker stop' which we'll then find out about in '_destroy'
// after we've reaped either the container's root process (in the
// event that we had just launched a container for an executor) or
// the mesos-docker-executor (in the case we launched a container
// for a task).
LOG(INFO) << "Running docker stop on container " << containerId;
if (killed) {
// TODO(alexr): After the deprecation cycle (started in 1.0), update
// this to omit the timeout. Graceful shutdown of the container is not
// a containerizer responsibility; it is the responsibility of the agent
// in co-operation with the executor. Once `destroy()` is called, the
// container should be destroyed forcefully.
// The `after` fallback should remain as a precaution against the docker
// stop command hanging.
docker->stop(container->containerName, flags.docker_stop_timeout)
.after(
flags.docker_stop_timeout + DOCKER_FORCE_KILL_TIMEOUT,
defer(self(), &Self::destroyTimeout, containerId, lambda::_1))
.onAny(defer(self(), &Self::__destroy, containerId, killed, lambda::_1));
} else {
__destroy(containerId, killed, Nothing());
}
}
void DockerContainerizerProcess::__destroy(
const ContainerID& containerId,
bool killed,
const Future<Nothing>& kill)
{
CHECK(containers_.contains(containerId));
Container* container = containers_.at(containerId);
if (!kill.isReady() && !container->status.future().isReady()) {
// TODO(benh): This means we've failed to do a Docker::kill, which
// means it's possible that the container is still going to be
// running after we return! We either need to have a periodic
// "garbage collector", or we need to retry the Docker::kill
// indefinitely until it has been successful.
string failure = "Failed to kill the Docker container: " +
(kill.isFailed() ? kill.failure() : "discarded future");
#ifdef __linux__
// TODO(gyliu): We will never de-allocate these GPUs,
// unless the agent is restarted!
if (!container->gpus.empty()) {
failure += ": " + stringify(container->gpus.size()) + " GPUs leaked";
}
#endif // __linux__
container->termination.fail(failure);
containers_.erase(containerId);
delay(
flags.docker_remove_delay,
self(),
&Self::remove,
container->containerName,
container->executorName());
delete container;
return;
}
// Status must be ready since we did a Docker::kill.
CHECK_READY(container->status.future());
container->status.future()
->onAny(defer(self(), &Self::___destroy, containerId, killed, lambda::_1));
}
void DockerContainerizerProcess::___destroy(
const ContainerID& containerId,
bool killed,
const Future<Option<int>>& status)
{
CHECK(containers_.contains(containerId));
Try<Nothing> unmount = unmountPersistentVolumes(containerId);
if (unmount.isError()) {
// TODO(tnachen): Failing to unmount a persistent volume now
// leads to leaving the volume on the host, and we won't retry
// again since the Docker container is removed. We should consider
// not removing the container so we can retry.
LOG(WARNING) << "Failed to remove persistent volumes on destroy for"
<< " container " << containerId << ": " << unmount.error();
}
Future<Nothing> deallocateGpus = Nothing();
#ifdef __linux__
// Deallocate GPU resources before we destroy container.
if (!containers_.at(containerId)->gpus.empty()) {
deallocateGpus = deallocateNvidiaGpus(containerId);
}
#endif // __linux__
deallocateGpus
.onAny(defer(self(), &Self::____destroy, containerId, killed, status));
}
void DockerContainerizerProcess::____destroy(
const ContainerID& containerId,
bool killed,
const Future<Option<int>>& status)
{
Container* container = containers_.at(containerId);
ContainerTermination termination;
if (status.isReady() && status->isSome()) {
termination.set_status(status->get());
}
termination.set_message(
killed ? "Container killed" : "Container terminated");
container->termination.set(termination);
containers_.erase(containerId);
delay(
flags.docker_remove_delay,
self(),
&Self::remove,
container->containerName,
container->executorName());
delete container;
}
Future<Nothing> DockerContainerizerProcess::destroyTimeout(
const ContainerID& containerId,
Future<Nothing> future)
{
CHECK(containers_.contains(containerId));
LOG(WARNING) << "Docker stop timed out for container " << containerId;
Container* container = containers_.at(containerId);
// A hanging `docker stop` could be a problem with docker or even a kernel
// bug. Assuming that this is a docker problem, circumventing docker and
// killing the process run by it ourselves might help here.
if (container->pid.isSome()) {
LOG(WARNING) << "Sending SIGKILL to process with pid "
<< container->pid.get();
Try<list<os::ProcessTree>> kill =
os::killtree(container->pid.get(), SIGKILL);
if (kill.isError()) {
// Ignoring the error from killing process as it can already
// have exited.
VLOG(1) << "Ignoring error when killing process pid "
<< container->pid.get() << " in destroy, error: "
<< kill.error();
}
}
return future;
}
Future<hashset<ContainerID>> DockerContainerizerProcess::containers()
{
return containers_.keys();
}
void DockerContainerizerProcess::reaped(const ContainerID& containerId)
{
if (!containers_.contains(containerId)) {
return;
}
LOG(INFO) << "Executor for container " << containerId << " has exited";
// The executor has exited so destroy the container.
destroy(containerId, false);
}
void DockerContainerizerProcess::remove(
const string& containerName,
const Option<string>& executor)
{
docker->rm(containerName, true);
if (executor.isSome()) {
docker->rm(executor.get(), true);
}
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
| apache-2.0 |
cmsi/smash | src/parallel.F90 | 1 | 15599 | ! Copyright 2014-2021 Kazuya Ishimura
!
! 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.
!
!----------------------------------
subroutine para_init(mpi_comm1)
!----------------------------------
!
! Start MPI and set mpi_comm1=MPI_COMM_WORLD
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: ierr
#else
implicit none
include "mpif.h"
integer(selected_int_kind(18)) :: ierr
#endif
integer,intent(out) :: mpi_comm1
!
call mpi_init(ierr)
mpi_comm1= MPI_COMM_WORLD
#endif
return
end
!----------------------------------------------
subroutine para_comm_size(nproc,mpi_commin)
!----------------------------------------------
!
! Return the number of processes in mpi_comm
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: mpi_comm4, nproc4, ierr
#else
implicit none
integer(selected_int_kind(18)) :: mpi_comm4, nproc4, ierr
#endif
integer,intent(in) :: mpi_commin
integer,intent(out) :: nproc
!
mpi_comm4= mpi_commin
call mpi_comm_size(mpi_comm4,nproc4,ierr)
nproc= nproc4
#else
integer,intent(in) :: mpi_commin
integer,intent(out) :: nproc
!
nproc= 1
#endif
return
end
!-----------------------------------------------
subroutine para_comm_rank(myrank,mpi_commin)
!-----------------------------------------------
!
! Return the MPI rank in mpi_comm
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: mpi_comm4, myrank4, ierr
#else
implicit none
integer(selected_int_kind(18)) :: mpi_comm4, myrank4, ierr
#endif
integer,intent(in) :: mpi_commin
integer,intent(out) :: myrank
!
mpi_comm4= mpi_commin
call mpi_comm_rank(mpi_comm4,myrank4,ierr)
myrank= myrank4
#else
integer,intent(in) :: mpi_commin
integer,intent(out) :: myrank
!
myrank= 0
#endif
return
end
!---------------------------
subroutine para_finalize
!---------------------------
!
! Finalize MPI
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: ierr
#else
implicit none
integer(selected_int_kind(18)) :: ierr
#endif
!
call mpi_finalize(ierr)
#endif
return
end
!------------------------
subroutine para_abort
!------------------------
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: icode, ierr
#else
implicit none
include "mpif.h"
integer(selected_int_kind(18)) :: icode, ierr
#endif
!
icode=9
call mpi_abort(MPI_COMM_WORLD,icode,ierr)
#endif
return
end
!----------------------------------
subroutine checkintsize4(isize)
!----------------------------------
implicit none
integer(selected_int_kind(9)),intent(out) :: isize
!
isize= 4
end
!----------------------------------
subroutine checkintsize8(isize)
!----------------------------------
implicit none
integer(selected_int_kind(18)),intent(out) :: isize
!
isize= 8
end
!----------------------------------------------------
subroutine para_bcastr(buff,num,irank,mpi_commin)
!----------------------------------------------------
!
! Broadcast real(8) data
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: num4, irank4, mpi_comm4, ierr
#else
implicit none
include "mpif.h"
integer(selected_int_kind(18)) :: num4, irank4, mpi_comm4, ierr
#endif
integer,intent(in) :: num, irank, mpi_commin
real(8),intent(inout) :: buff(*)
!
num4= num
irank4= irank
mpi_comm4= mpi_commin
!
call mpi_bcast(buff,num4,mpi_real8,irank4,mpi_comm4,ierr)
#endif
return
end
!-----------------------------------------------------
subroutine para_bcasti(ibuff,num,irank,mpi_commin)
!-----------------------------------------------------
!
! Broadcast integer data
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: num4, irank4, mpi_comm4, ierr
#else
implicit none
include "mpif.h"
integer(selected_int_kind(18)) :: num4, irank4, mpi_comm4, ierr
#endif
integer,intent(in) :: num, irank, mpi_commin
integer,intent(inout) :: ibuff(*)
integer :: isize
!
interface checkintsize
subroutine checkintsize4(isize)
integer(selected_int_kind(9)),intent(out) :: isize
end subroutine checkintsize4
subroutine checkintsize8(isize)
integer(selected_int_kind(18)),intent(out) :: isize
end subroutine checkintsize8
end interface checkintsize
!
num4= num
irank4= irank
mpi_comm4= mpi_commin
!
call checkintsize(isize)
if(isize == 4) then
call mpi_bcast(ibuff,num4,mpi_integer4,irank4,mpi_comm4,ierr)
elseif(isize == 8) then
call mpi_bcast(ibuff,num4,mpi_integer8,irank4,mpi_comm4,ierr)
endif
#endif
return
end
!----------------------------------------------------
subroutine para_bcastc(buff,num,irank,mpi_commin)
!----------------------------------------------------
!
! Broadcast character data
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: num4, irank4, mpi_comm4, ierr
#else
implicit none
include "mpif.h"
integer(selected_int_kind(18)) :: num4, irank4, mpi_comm4, ierr
#endif
integer,intent(in) :: num, irank, mpi_commin
character(*),intent(inout) :: buff(*)
!
num4= num
irank4= irank
mpi_comm4= mpi_commin
!
call mpi_bcast(buff,num4,mpi_character,irank4,mpi_comm4,ierr)
#endif
return
end
!----------------------------------------------------
subroutine para_bcastl(buff,num,irank,mpi_commin)
!----------------------------------------------------
!
! Broadcast logical data
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer,intent(in) :: num, irank, mpi_commin
integer(selected_int_kind(9)) :: num4, irank4, mpi_comm4, ierr, itmp(num)
#else
implicit none
include "mpif.h"
integer,intent(in) :: num, irank, mpi_commin
integer(selected_int_kind(18)) :: num4, irank4, mpi_comm4, ierr
integer(selected_int_kind(9)) :: itmp(num)
#endif
integer :: ii, myrank
logical,intent(inout) :: buff(*)
!
call para_comm_rank(myrank,mpi_commin)
!
if(irank == myrank) then
do ii= 1,num
if(buff(ii)) then
itmp(ii)= 1
else
itmp(ii)= 0
endif
enddo
endif
!
num4= num
irank4= irank
mpi_comm4= mpi_commin
!
call mpi_bcast(itmp,num4,mpi_integer4,irank4,mpi_comm4,ierr)
!
do ii= 1,num
if(itmp(ii) == 1) then
buff(ii)= .true.
else
buff(ii)= .false.
endif
enddo
#endif
return
end
!---------------------------------------------------------
subroutine para_allreducer(sbuff,rbuff,num,mpi_commin)
!---------------------------------------------------------
!
! Accumulate real(8) values from all processes and
! distributes the result back to all processes in mpi_comm
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: num4, mpi_comm4, ierr
#else
implicit none
include "mpif.h"
integer(selected_int_kind(18)) :: num4, mpi_comm4, ierr
#endif
integer,intent(in) :: num, mpi_commin
real(8),intent(in) :: sbuff(*)
real(8),intent(out) :: rbuff(*)
!
num4= num
mpi_comm4= mpi_commin
call mpi_allreduce(sbuff,rbuff,num4,mpi_real8,MPI_SUM,mpi_comm4,ierr)
#else
implicit none
integer,intent(in) :: num, mpi_commin
real(8),intent(in) :: sbuff(*)
real(8),intent(out) :: rbuff(*)
!
call dcopy(num,sbuff,1,rbuff,1)
#endif
return
end
!---------------------------------------------------------
subroutine para_allreducei(sbuff,rbuff,num,mpi_commin)
!---------------------------------------------------------
!
! Accumulate integer values from all processes and
! distributes the result back to all processes in mpi_comm
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer(selected_int_kind(9)) :: num4, mpi_comm4, ierr
#else
implicit none
include "mpif.h"
integer(selected_int_kind(18)) :: num4, mpi_comm4, ierr
#endif
integer,intent(in) :: num, mpi_commin
integer,intent(in) :: sbuff(*)
integer,intent(out) :: rbuff(*)
integer :: isize
!
interface checkintsize
subroutine checkintsize4(isize)
integer(selected_int_kind(9)),intent(out) :: isize
end subroutine checkintsize4
subroutine checkintsize8(isize)
integer(selected_int_kind(18)),intent(out) :: isize
end subroutine checkintsize8
end interface checkintsize
!
num4= num
mpi_comm4= mpi_commin
!
call checkintsize(isize)
if(isize == 4) then
call mpi_allreduce(sbuff,rbuff,num4,mpi_integer4,MPI_SUM,mpi_comm4,ierr)
elseif(isize == 8) then
call mpi_allreduce(sbuff,rbuff,num4,mpi_integer8,MPI_SUM,mpi_comm4,ierr)
endif
#else
implicit none
integer,intent(in) :: num, mpi_commin
integer,intent(in) :: sbuff(*)
integer,intent(out) :: rbuff(*)
integer ii
!
do ii= 1,num
rbuff(ii)= sbuff(ii)
enddo
#endif
return
end
!----------------------------------------------------------------------------
subroutine para_allgathervr(sbuff,num,rbuff,idisa,idisb,nproc,mpi_commin)
!----------------------------------------------------------------------------
!
! Gather data from all tasks and deliver the combined data to all tasks in mpi_comm
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer,intent(in) :: num, nproc, idisa(nproc), idisb(nproc), mpi_commin
integer(selected_int_kind(9)) :: num4, idisa4(nproc), idisb4(nproc), mpi_comm4, ierr
#else
implicit none
include "mpif.h"
integer,intent(in) :: num, nproc, idisa(nproc), idisb(nproc), mpi_commin
integer(selected_int_kind(18)) :: num4, idisa4(nproc), idisb4(nproc), mpi_comm4, ierr
#endif
real(8),intent(in) :: sbuff(*)
real(8),intent(out):: rbuff(*)
integer :: ii
!
num4= num
mpi_comm4= mpi_commin
do ii= 1,nproc
idisa4(ii)= idisa(ii)
idisb4(ii)= idisb(ii)
enddo
call mpi_allgatherv(sbuff,num4,mpi_real8,rbuff,idisa4,idisb4,mpi_real8,mpi_comm4,ierr)
#else
implicit none
integer,intent(in) :: num, nproc, idisa(nproc), idisb(nproc), mpi_commin
real(8),intent(in) :: sbuff(*)
real(8),intent(out):: rbuff(*)
!
call dcopy(num,sbuff,1,rbuff,1)
#endif
!
return
end
!----------------------------------------------------------------------------------------
subroutine para_sendrecvr(sbuff,nums,idest,ntags,rbuff,numr,isource,ntagr,mpi_commin)
!----------------------------------------------------------------------------------------
!
! Send and receive real(8) data
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer,intent(in) :: nums, idest, ntags, numr, isource, ntagr, mpi_commin
integer(selected_int_kind(9)) :: nums4, idest4, ntags4, numr4, isource4, ntagr4
integer(selected_int_kind(9)) :: mpi_comm4, ierr, STATUS(MPI_STATUS_SIZE)
#else
implicit none
include "mpif.h"
integer,intent(in) :: nums, idest, ntags, numr, isource, ntagr, mpi_commin
integer(selected_int_kind(18)) :: nums4, idest4, ntags4, numr4, isource4, ntagr4
integer(selected_int_kind(18)) :: mpi_comm4, ierr, STATUS(MPI_STATUS_SIZE)
#endif
real(8),intent(in) :: sbuff(*)
real(8),intent(out) :: rbuff(*)
!
nums4= nums
idest4= idest
ntags4= ntags
numr4= numr
isource4= isource
ntagr4 = ntagr
mpi_comm4= mpi_commin
call mpi_sendrecv(sbuff,nums4,MPI_DOUBLE_PRECISION,idest4,ntags4, &
& rbuff,numr4,MPI_DOUBLE_PRECISION,isource4,ntagr4,mpi_comm4,STATUS,ierr)
#else
implicit none
integer,intent(in) :: nums, idest, ntags, numr, isource, ntagr, mpi_commin
real(8),intent(in) :: sbuff(*)
real(8),intent(out) :: rbuff(*)
!
call dcopy(nums,sbuff,1,rbuff,1)
#endif
return
end
!--------------------------------------------------------------
subroutine para_isendr(buff,num,idest,ntag,mpi_commin,ireq)
!--------------------------------------------------------------
!
! Non-blocking MPI_Isend of real(8) data
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer,intent(in) :: num, idest, ntag, mpi_commin
integer,intent(out) :: ireq
integer(selected_int_kind(9)) :: num4, idest4, ntag4, ireq4, mpi_comm4, ierr
#else
implicit none
include "mpif.h"
integer,intent(in) :: num, idest, ntag, mpi_commin
integer,intent(out) :: ireq
integer(selected_int_kind(18)) :: num4, idest4, ntag4, ireq4, mpi_comm4, ierr
#endif
real(8),intent(in) :: buff(*)
!
num4= num
idest4= idest
ntag4= ntag
mpi_comm4= mpi_commin
!
call mpi_isend(buff,num4,MPI_DOUBLE_PRECISION,idest4,ntag4,mpi_comm4,ireq4,ierr)
!
ireq= ireq4
#endif
return
end
!----------------------------------------------------------------
subroutine para_irecvr(buff,num,isource,ntag,mpi_commin,ireq)
!----------------------------------------------------------------
!
! Non-blocking MPI_Irecv of real(8) data
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer,intent(in) :: num, isource, ntag, mpi_commin
integer,intent(out) :: ireq
integer(selected_int_kind(9)) :: num4, isource4, ntag4, ireq4, mpi_comm4, ierr
#else
implicit none
include "mpif.h"
integer,intent(in) :: num, isource, ntag, mpi_commin
integer,intent(out) :: ireq
integer(selected_int_kind(18)) :: num4, isource4, ntag4, ireq4, mpi_comm4, ierr
#endif
real(8),intent(out) :: buff(*)
!
num4= num
isource4= isource
ntag4= ntag
mpi_comm4= mpi_commin
!
call mpi_irecv(buff,num4,MPI_DOUBLE_PRECISION,isource4,ntag4,mpi_comm4,ireq4,ierr)
!
ireq= ireq4
#endif
return
end
!-------------------------------------
subroutine para_waitall(nump,ireq)
!-------------------------------------
!
! MPI_Waitall
!
#ifndef noMPI
#ifndef ILP64
use mpi
implicit none
integer,intent(in) :: nump, ireq(nump)
integer(selected_int_kind(9)) :: nump4, ireq4(nump), STATUS(MPI_STATUS_SIZE,nump), ierr
#else
implicit none
include "mpif.h"
integer,intent(in) :: nump, ireq(nump)
integer(selected_int_kind(18)) :: nump4, ireq4(nump), STATUS(MPI_STATUS_SIZE,nump), ierr
#endif
integer :: ii
!
nump4= nump
do ii= 1,nump
ireq4(ii)= ireq(ii)
enddo
!
call mpi_waitall(nump4,ireq4,STATUS,ierr)
#endif
return
end
| apache-2.0 |
NREL/HARP_Opt | Source/WT_Perf/v3.05.00a-adp/Source/setprog.f90 | 2 | 1084 | !=======================================================================
SUBROUTINE SetProg
! This routine sets the version number. By doing it this way instead
! of the old way of initializing it in a module, we will no longer
! have to recompile everything every time we change versions.
USE NWTC_Library
IMPLICIT NONE
! Local Variables:
CHARACTER(26) :: Version = 'v3.05.00a-adp, 09-Nov-2012' ! String containing the current version.
ProgName = 'WT_Perf'
IF ( ReKi == 4 ) THEN ! Single precision
ProgVer = ' ('//TRIM( Version )//')'
ELSEIF ( ReKi == 8 ) THEN ! Double precision
ProgVer = ' ('//TRIM( Version )//', compiled using double precision)'
ELSE ! Unknown precision - it should be impossible to compile using a KIND that is not 4 or 8, but I'll put this check here just in case.
ProgVer = ' ('//TRIM( Version )//', compiled using '//TRIM( Int2LStr( ReKi ) )//'-byte precision)'
ENDIF
RETURN
END SUBROUTINE SetProg
| apache-2.0 |
benlangmuir/swift | lib/Frontend/ModuleInterfaceBuilder.cpp | 2 | 16295 | //===----- ModuleInterfaceBuilder.cpp - Compiles .swiftinterface files ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "textual-module-interface"
#include "swift/Frontend/ModuleInterfaceLoader.h"
#include "ModuleInterfaceBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/Module.h"
#include "swift/Basic/Defer.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/ModuleInterfaceSupport.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Serialization/SerializationOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/xxhash.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/LockFileManager.h"
#include "llvm/ADT/STLExtras.h"
using namespace swift;
using FileDependency = SerializationOptions::FileDependency;
namespace path = llvm::sys::path;
/// If the file dependency in \p FullDepPath is inside the \p Base directory,
/// this returns its path relative to \p Base. Otherwise it returns None.
static Optional<StringRef> getRelativeDepPath(StringRef DepPath,
StringRef Base) {
// If Base is the root directory, or DepPath does not start with Base, bail.
if (Base.size() <= 1 || !DepPath.startswith(Base)) {
return None;
}
assert(DepPath.size() > Base.size() &&
"should never depend on a directory");
// Is the DepName something like ${Base}/foo.h"?
if (path::is_separator(DepPath[Base.size()]))
return DepPath.substr(Base.size() + 1);
// Is the DepName something like "${Base}foo.h", where Base
// itself contains a trailing slash?
if (path::is_separator(Base.back()))
return DepPath.substr(Base.size());
// We have something next to Base, like "Base.h", that's somehow
// become a dependency.
return None;
}
struct ErrorDowngradeConsumerRAII: DiagnosticConsumer {
DiagnosticEngine &Diag;
std::vector<DiagnosticConsumer *> allConsumers;
bool SeenError;
ErrorDowngradeConsumerRAII(DiagnosticEngine &Diag): Diag(Diag),
allConsumers(Diag.takeConsumers()), SeenError(false) {
Diag.addConsumer(*this);
}
~ErrorDowngradeConsumerRAII() {
for (auto *consumer: allConsumers) {
Diag.addConsumer(*consumer);
}
Diag.removeConsumer(*this);
}
void handleDiagnostic(SourceManager &SM, const DiagnosticInfo &Info) override {
DiagnosticInfo localInfo(Info);
if (localInfo.Kind == DiagnosticKind::Error) {
localInfo.Kind = DiagnosticKind::Warning;
SeenError = true;
for (auto *consumer: allConsumers) {
consumer->handleDiagnostic(SM, localInfo);
}
}
}
};
bool ExplicitModuleInterfaceBuilder::collectDepsForSerialization(
SmallVectorImpl<FileDependency> &Deps, StringRef interfacePath,
bool IsHashBased) {
llvm::vfs::FileSystem &fs = *Instance.getSourceMgr().getFileSystem();
auto &Opts = Instance.getASTContext().SearchPathOpts;
SmallString<128> SDKPath(Opts.getSDKPath());
path::native(SDKPath);
SmallString<128> ResourcePath(Opts.RuntimeResourcePath);
path::native(ResourcePath);
auto DTDeps = Instance.getDependencyTracker()->getDependencies();
SmallVector<std::string, 16> InitialDepNames(DTDeps.begin(), DTDeps.end());
auto IncDeps =
Instance.getDependencyTracker()->getIncrementalDependencyPaths();
InitialDepNames.append(IncDeps.begin(), IncDeps.end());
InitialDepNames.push_back(interfacePath.str());
for (const auto &extra : extraDependencies) {
InitialDepNames.push_back(extra.str());
}
SmallString<128> Scratch;
for (const auto &InitialDepName : InitialDepNames) {
path::native(InitialDepName, Scratch);
StringRef DepName = Scratch.str();
assert(moduleCachePath.empty() || !DepName.startswith(moduleCachePath));
// Serialize the paths of dependencies in the SDK relative to it.
Optional<StringRef> SDKRelativePath = getRelativeDepPath(DepName, SDKPath);
StringRef DepNameToStore = SDKRelativePath.getValueOr(DepName);
bool IsSDKRelative = SDKRelativePath.hasValue();
// Forwarding modules add the underlying prebuilt module to their
// dependency list -- don't serialize that.
if (!prebuiltCachePath.empty() && DepName.startswith(prebuiltCachePath))
continue;
// Don't serialize interface path if it's from the preferred interface dir.
// This ensures the prebuilt module caches generated from these interfaces
// are relocatable.
if (!backupInterfaceDir.empty() && DepName.startswith(backupInterfaceDir))
continue;
if (dependencyTracker) {
dependencyTracker->addDependency(DepName, /*isSystem*/ IsSDKRelative);
}
// Don't serialize compiler-relative deps so the cache is relocatable.
if (DepName.startswith(ResourcePath))
continue;
auto Status = fs.status(DepName);
if (!Status)
return true;
/// Lazily load the dependency buffer if we need it. If we're not
/// dealing with a hash-based dependencies, and if the dependency is
/// not a .swiftmodule, we can avoid opening the buffer.
std::unique_ptr<llvm::MemoryBuffer> DepBuf = nullptr;
auto getDepBuf = [&]() -> llvm::MemoryBuffer * {
if (DepBuf)
return DepBuf.get();
if (auto Buf = fs.getBufferForFile(DepName, /*FileSize=*/-1,
/*RequiresNullTerminator=*/false)) {
DepBuf = std::move(Buf.get());
return DepBuf.get();
}
return nullptr;
};
if (IsHashBased) {
auto buf = getDepBuf();
if (!buf)
return true;
uint64_t hash = xxHash64(buf->getBuffer());
Deps.push_back(FileDependency::hashBased(DepNameToStore, IsSDKRelative,
Status->getSize(), hash));
} else {
uint64_t mtime =
Status->getLastModificationTime().time_since_epoch().count();
Deps.push_back(FileDependency::modTimeBased(DepNameToStore, IsSDKRelative,
Status->getSize(), mtime));
}
}
return false;
}
std::error_code ExplicitModuleInterfaceBuilder::buildSwiftModuleFromInterface(
StringRef InterfacePath, StringRef OutputPath, bool ShouldSerializeDeps,
std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
ArrayRef<std::string> CompiledCandidates,
StringRef CompilerVersion) {
auto Invocation = Instance.getInvocation();
// Try building forwarding module first. If succeed, return.
if (Instance.getASTContext()
.getModuleInterfaceChecker()
->tryEmitForwardingModule(Invocation.getModuleName(), InterfacePath,
CompiledCandidates, OutputPath)) {
return std::error_code();
}
FrontendOptions &FEOpts = Invocation.getFrontendOptions();
bool isTypeChecking =
(FEOpts.RequestedAction == FrontendOptions::ActionType::Typecheck);
const auto &InputInfo = FEOpts.InputsAndOutputs.firstInput();
StringRef InPath = InputInfo.getFileName();
// Build the .swiftmodule; this is a _very_ abridged version of the logic
// in performCompile in libFrontendTool, specialized, to just the one
// module-serialization task we're trying to do here.
LLVM_DEBUG(llvm::dbgs() << "Setting up instance to compile " << InPath
<< " to " << OutputPath << "\n");
LLVM_DEBUG(llvm::dbgs() << "Performing sema\n");
if (isTypeChecking && FEOpts.DowngradeInterfaceVerificationError) {
ErrorDowngradeConsumerRAII R(Instance.getDiags());
Instance.performSema();
return std::error_code();
}
SWIFT_DEFER {
// Make sure to emit a generic top-level error if a module fails to
// load. This is not only good for users; it also makes sure that we've
// emitted an error in the parent diagnostic engine, which is what
// determines whether the process exits with a proper failure status.
if (Instance.getASTContext().hadError()) {
auto builtByCompiler = getSwiftInterfaceCompilerVersionForCurrentCompiler(
Instance.getASTContext());
if (!isTypeChecking && CompilerVersion.str() != builtByCompiler) {
diagnose(diag::module_interface_build_failed_mismatching_compiler,
InterfacePath,
Invocation.getModuleName(),
CompilerVersion,
builtByCompiler);
} else {
diagnose(diag::module_interface_build_failed,
InterfacePath,
isTypeChecking,
Invocation.getModuleName(),
CompilerVersion.str() == builtByCompiler,
CompilerVersion.str(),
builtByCompiler);
}
}
};
Instance.performSema();
if (Instance.getASTContext().hadError()) {
LLVM_DEBUG(llvm::dbgs() << "encountered errors\n");
return std::make_error_code(std::errc::not_supported);
}
// If we are just type-checking the interface, we are done.
if (isTypeChecking)
return std::error_code();
SILOptions &SILOpts = Invocation.getSILOptions();
auto Mod = Instance.getMainModule();
auto &TC = Instance.getSILTypes();
auto SILMod = performASTLowering(Mod, TC, SILOpts);
if (!SILMod) {
LLVM_DEBUG(llvm::dbgs() << "SILGen did not produce a module\n");
return std::make_error_code(std::errc::not_supported);
}
// Setup the callbacks for serialization, which can occur during the
// optimization pipeline.
SerializationOptions SerializationOpts;
std::string OutPathStr = OutputPath.str();
SerializationOpts.OutputPath = OutPathStr.c_str();
SerializationOpts.ModuleLinkName = FEOpts.ModuleLinkName;
SerializationOpts.AutolinkForceLoad =
!Invocation.getIRGenOptions().ForceLoadSymbolName.empty();
SerializationOpts.UserModuleVersion = FEOpts.UserModuleVersion;
// Record any non-SDK module interface files for the debug info.
StringRef SDKPath = Instance.getASTContext().SearchPathOpts.getSDKPath();
if (!getRelativeDepPath(InPath, SDKPath))
SerializationOpts.ModuleInterface = InPath;
SerializationOpts.SDKName = Instance.getASTContext().LangOpts.SDKName;
SerializationOpts.ABIDescriptorPath = ABIDescriptorPath.str();
SmallVector<FileDependency, 16> Deps;
bool SerializeHashes = FEOpts.SerializeModuleInterfaceDependencyHashes;
if (collectDepsForSerialization(Deps, InterfacePath, SerializeHashes)) {
return std::make_error_code(std::errc::not_supported);
}
if (ShouldSerializeDeps)
SerializationOpts.Dependencies = Deps;
SerializationOpts.IsOSSA = SILOpts.EnableOSSAModules;
SILMod->setSerializeSILAction([&]() {
// We don't want to serialize module docs in the cache -- they
// will be serialized beside the interface file.
serializeToBuffers(Mod, SerializationOpts, ModuleBuffer,
/*ModuleDocBuffer*/ nullptr,
/*SourceInfoBuffer*/ nullptr, SILMod.get());
});
LLVM_DEBUG(llvm::dbgs() << "Running SIL processing passes\n");
if (Instance.performSILProcessing(SILMod.get())) {
LLVM_DEBUG(llvm::dbgs() << "encountered errors\n");
return std::make_error_code(std::errc::not_supported);
}
if (Instance.getDiags().hadAnyError()) {
return std::make_error_code(std::errc::not_supported);
}
return std::error_code();
}
bool ImplicitModuleInterfaceBuilder::buildSwiftModuleInternal(
StringRef OutPath,
bool ShouldSerializeDeps,
std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
ArrayRef<std::string> CompiledCandidates) {
auto outerPrettyStackState = llvm::SavePrettyStackState();
bool SubError = false;
static const size_t ThreadStackSize = 8 << 20; // 8 MB.
bool RunSuccess = llvm::CrashRecoveryContext().RunSafelyOnThread([&] {
// Pretend we're on the original thread for pretty-stack-trace purposes.
auto savedInnerPrettyStackState = llvm::SavePrettyStackState();
llvm::RestorePrettyStackState(outerPrettyStackState);
SWIFT_DEFER {
llvm::RestorePrettyStackState(savedInnerPrettyStackState);
};
SubError = (bool)subASTDelegate.runInSubCompilerInstance(
moduleName, interfacePath, OutPath, diagnosticLoc,
[&](SubCompilerInstanceInfo &info) {
auto EBuilder = ExplicitModuleInterfaceBuilder(
*info.Instance, diags, sourceMgr, moduleCachePath, backupInterfaceDir,
prebuiltCachePath, ABIDescriptorPath, extraDependencies, diagnosticLoc,
dependencyTracker);
return EBuilder.buildSwiftModuleFromInterface(
interfacePath, OutPath, ShouldSerializeDeps, ModuleBuffer,
CompiledCandidates, info.CompilerVersion);
});
}, ThreadStackSize);
return !RunSuccess || SubError;
}
bool ImplicitModuleInterfaceBuilder::buildSwiftModule(StringRef OutPath,
bool ShouldSerializeDeps,
std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
llvm::function_ref<void()> RemarkRebuild,
ArrayRef<std::string> CompiledCandidates) {
auto build = [&]() {
if (RemarkRebuild) {
RemarkRebuild();
}
return buildSwiftModuleInternal(OutPath, ShouldSerializeDeps,
ModuleBuffer, CompiledCandidates);
};
if (disableInterfaceFileLock) {
return build();
}
while (1) {
// Attempt to lock the interface file. Only one process is allowed to build
// module from the interface so we don't consume too much memory when multiple
// processes are doing the same.
// FIXME: We should surface the module building step to the build system so
// we don't need to synchronize here.
llvm::LockFileManager Locked(OutPath);
switch (Locked) {
case llvm::LockFileManager::LFS_Error:{
// ModuleInterfaceBuilder takes care of correctness and locks are only
// necessary for performance. Fallback to building the module in case of any lock
// related errors.
if (RemarkRebuild) {
diagnose(diag::interface_file_lock_failure);
}
// Clear out any potential leftover.
Locked.unsafeRemoveLockFile();
LLVM_FALLTHROUGH;
}
case llvm::LockFileManager::LFS_Owned: {
return build();
}
case llvm::LockFileManager::LFS_Shared: {
// Someone else is responsible for building the module. Wait for them to
// finish.
switch (Locked.waitForUnlock(256)) {
case llvm::LockFileManager::Res_Success: {
// This process may have a different module output path. If the other
// process doesn't build the interface to this output path, we should try
// building ourselves.
auto bufferOrError = llvm::MemoryBuffer::getFile(OutPath);
if (!bufferOrError)
continue;
if (ModuleBuffer)
*ModuleBuffer = std::move(bufferOrError.get());
return false;
}
case llvm::LockFileManager::Res_OwnerDied: {
continue; // try again to get the lock.
}
case llvm::LockFileManager::Res_Timeout: {
// Since ModuleInterfaceBuilder takes care of correctness, we try waiting for
// another process to complete the build so swift does not do it done
// twice. If case of timeout, build it ourselves.
if (RemarkRebuild) {
diagnose(diag::interface_file_lock_timed_out, interfacePath);
}
// Clear the lock file so that future invocations can make progress.
Locked.unsafeRemoveLockFile();
continue;
}
}
break;
}
}
}
}
| apache-2.0 |
FlyLu/rt-thread | bsp/stm32/libraries/STM32H7xx_HAL/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_nand.c | 2 | 62600 | /**
******************************************************************************
* @file stm32h7xx_hal_nand.c
* @author MCD Application Team
* @brief NAND HAL module driver.
* This file provides a generic firmware to drive NAND memories mounted
* as external device.
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
This driver is a generic layered driver which contains a set of APIs used to
control NAND flash memories. It uses the FMC/FSMC layer functions to interface
with NAND devices. This driver is used as follows:
(+) NAND flash memory configuration sequence using the function HAL_NAND_Init()
with control and timing parameters for both common and attribute spaces.
(+) Read NAND flash memory maker and device IDs using the function
HAL_NAND_Read_ID(). The read information is stored in the NAND_ID_TypeDef
structure declared by the function caller.
(+) Access NAND flash memory by read/write operations using the functions
HAL_NAND_Read_Page_8b()/HAL_NAND_Read_SpareArea_8b(),
HAL_NAND_Write_Page_8b()/HAL_NAND_Write_SpareArea_8b(),
HAL_NAND_Read_Page_16b()/HAL_NAND_Read_SpareArea_16b(),
HAL_NAND_Write_Page_16b()/HAL_NAND_Write_SpareArea_16b()
to read/write page(s)/spare area(s). These functions use specific device
information (Block, page size..) predefined by the user in the NAND_DeviceConfigTypeDef
structure. The read/write address information is contained by the Nand_Address_Typedef
structure passed as parameter.
(+) Perform NAND flash Reset chip operation using the function HAL_NAND_Reset().
(+) Perform NAND flash erase block operation using the function HAL_NAND_Erase_Block().
The erase block address information is contained in the Nand_Address_Typedef
structure passed as parameter.
(+) Read the NAND flash status operation using the function HAL_NAND_Read_Status().
(+) You can also control the NAND device by calling the control APIs HAL_NAND_ECC_Enable()/
HAL_NAND_ECC_Disable() to respectively enable/disable the ECC code correction
feature or the function HAL_NAND_GetECC() to get the ECC correction code.
(+) You can monitor the NAND device HAL state by calling the function
HAL_NAND_GetState()
[..]
(@) This driver is a set of generic APIs which handle standard NAND flash operations.
If a NAND flash device contains different operations and/or implementations,
it should be implemented separately.
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* 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 STMicroelectronics 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx_hal.h"
/** @addtogroup STM32H7xx_HAL_Driver
* @{
*/
#ifdef HAL_NAND_MODULE_ENABLED
/** @defgroup NAND NAND
* @brief NAND HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private Constants ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup NAND_Exported_Functions NAND Exported Functions
* @{
*/
/** @defgroup NAND_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
==============================================================================
##### NAND Initialization and de-initialization functions #####
==============================================================================
[..]
This section provides functions allowing to initialize/de-initialize
the NAND memory
@endverbatim
* @{
*/
/**
* @brief Perform NAND memory Initialization sequence
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param ComSpace_Timing: pointer to Common space timing structure
* @param AttSpace_Timing: pointer to Attribute space timing structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FMC_NAND_PCC_TimingTypeDef *ComSpace_Timing, FMC_NAND_PCC_TimingTypeDef *AttSpace_Timing)
{
/* Check the NAND handle state */
if(hnand == NULL)
{
return HAL_ERROR;
}
if(hnand->State == HAL_NAND_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hnand->Lock = HAL_UNLOCKED;
/* Initialize the low level hardware (MSP) */
HAL_NAND_MspInit(hnand);
}
/* Initialize NAND control Interface */
FMC_NAND_Init(hnand->Instance, &(hnand->Init));
/* Initialize NAND common space timing Interface */
FMC_NAND_CommonSpace_Timing_Init(hnand->Instance, ComSpace_Timing, hnand->Init.NandBank);
/* Initialize NAND attribute space timing Interface */
FMC_NAND_AttributeSpace_Timing_Init(hnand->Instance, AttSpace_Timing, hnand->Init.NandBank);
/* Enable the NAND device */
__FMC_NAND_ENABLE(hnand->Instance);
/* Enable FMC IP */
__FMC_ENABLE();
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
return HAL_OK;
}
/**
* @brief Perform NAND memory De-Initialization sequence
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand)
{
/* Initialize the low level hardware (MSP) */
HAL_NAND_MspDeInit(hnand);
/* Configure the NAND registers with their reset values */
FMC_NAND_DeInit(hnand->Instance, hnand->Init.NandBank);
/* Reset the NAND controller state */
hnand->State = HAL_NAND_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief NAND MSP Init
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval None
*/
__weak void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnand);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NAND_MspInit could be implemented in the user file
*/
}
/**
* @brief NAND MSP DeInit
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval None
*/
__weak void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnand);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NAND_MspDeInit could be implemented in the user file
*/
}
/**
* @brief This function handles NAND device interrupt request.
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand)
{
/* Check NAND interrupt Rising edge flag */
if(__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_RISING_EDGE))
{
/* NAND interrupt callback*/
HAL_NAND_ITCallback(hnand);
/* Clear NAND interrupt Rising edge pending bit */
__FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_RISING_EDGE);
}
/* Check NAND interrupt Level flag */
if(__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_LEVEL))
{
/* NAND interrupt callback*/
HAL_NAND_ITCallback(hnand);
/* Clear NAND interrupt Level pending bit */
__FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_LEVEL);
}
/* Check NAND interrupt Falling edge flag */
if(__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FALLING_EDGE))
{
/* NAND interrupt callback*/
HAL_NAND_ITCallback(hnand);
/* Clear NAND interrupt Falling edge pending bit */
__FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_FALLING_EDGE);
}
/* Check NAND interrupt FIFO empty flag */
if(__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FEMPT))
{
/* NAND interrupt callback*/
HAL_NAND_ITCallback(hnand);
/* Clear NAND interrupt FIFO empty pending bit */
__FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_FEMPT);
}
}
/**
* @brief NAND interrupt feature callback
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval None
*/
__weak void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hnand);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_NAND_ITCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup NAND_Exported_Functions_Group2 Input and Output functions
* @brief Input Output and memory control functions
*
@verbatim
==============================================================================
##### NAND Input and Output functions #####
==============================================================================
[..]
This section provides functions allowing to use and control the NAND
memory
@endverbatim
* @{
*/
/**
* @brief Read the NAND memory electronic signature
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pNAND_ID: NAND ID structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID)
{
__IO uint32_t data = 0;
__IO uint32_t data1 = 0;
uint32_t deviceAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Send Read ID command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_READID;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
/* Read the electronic signature from NAND flash */
if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8)
{
data = *(__IO uint32_t *)deviceAddress;
/* Return the data read */
pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data);
pNAND_ID->Device_Id = ADDR_2ND_CYCLE(data);
pNAND_ID->Third_Id = ADDR_3RD_CYCLE(data);
pNAND_ID->Fourth_Id = ADDR_4TH_CYCLE(data);
}
else
{
data = *(__IO uint32_t *)deviceAddress;
data1 = *((__IO uint32_t *)deviceAddress + 4);
/* Return the data read */
pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data);
pNAND_ID->Device_Id = ADDR_3RD_CYCLE(data);
pNAND_ID->Third_Id = ADDR_1ST_CYCLE(data1);
pNAND_ID->Fourth_Id = ADDR_3RD_CYCLE(data1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief NAND memory reset
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand)
{
uint32_t deviceAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Send NAND reset command */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = 0xFF;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Configure the device: Enter the physical parameters of the device
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pDeviceConfig : pointer to NAND_DeviceConfigTypeDef structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig)
{
hnand->Config.PageSize = pDeviceConfig->PageSize;
hnand->Config.SpareAreaSize = pDeviceConfig->SpareAreaSize;
hnand->Config.BlockSize = pDeviceConfig->BlockSize;
hnand->Config.BlockNbr = pDeviceConfig->BlockNbr;
hnand->Config.PlaneSize = pDeviceConfig->PlaneSize;
hnand->Config.PlaneNbr = pDeviceConfig->PlaneNbr;
hnand->Config.ExtraCommandEnable = pDeviceConfig->ExtraCommandEnable;
return HAL_OK;
}
/**
* @brief Read Page(s) from NAND memory block (8-bits addressing)
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @param pBuffer : pointer to destination read buffer
* @param NumPageToRead : number of pages to read from block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead)
{
__IO uint32_t index = 0;
uint32_t tickstart = 0U;
uint32_t deviceAddress = 0, size = 0, numPagesRead = 0, nandAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* NAND raw address calculation */
nandAddress = ARRAY_ADDRESS(pAddress, hnand);
/* Page(s) read loop */
while((NumPageToRead != 0) && (nandAddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* update the buffer size */
size = (hnand->Config.PageSize) + ((hnand->Config.PageSize) * numPagesRead);
/* Send read page command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
/* Cards with page size <= 512 bytes */
if((hnand->Config.PageSize) <= 512)
{
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;
__DSB();
if(hnand->Config.ExtraCommandEnable == ENABLE)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while(HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Go back to read mode */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = ((uint8_t)0x00U);
__DSB();
}
/* Get Data into Buffer */
for(; index < size; index++)
{
*(uint8_t *)pBuffer++ = *(uint8_t *)deviceAddress;
}
/* Increment read pages number */
numPagesRead++;
/* Decrement pages to read */
NumPageToRead--;
/* Increment the NAND address */
nandAddress = (uint32_t)(nandAddress + 1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Read Page(s) from NAND memory block (16-bits addressing)
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @param pBuffer : pointer to destination read buffer. pBuffer should be 16bits aligned
* @param NumPageToRead : number of pages to read from block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumPageToRead)
{
__IO uint32_t index = 0;
uint32_t tickstart = 0;
uint32_t deviceAddress = 0, size = 0, numPagesRead = 0, nandAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* NAND raw address calculation */
nandAddress = ARRAY_ADDRESS(pAddress, hnand);
/* Page(s) read loop */
while((NumPageToRead != 0) && (nandAddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* update the buffer size */
size = (hnand->Config.PageSize) + ((hnand->Config.PageSize) * numPagesRead);
/* Send read page command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
/* Cards with page size <= 512 bytes */
if((hnand->Config.PageSize) <= 512)
{
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;
__DSB();
if(hnand->Config.ExtraCommandEnable == ENABLE)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while(HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Go back to read mode */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = ((uint8_t)0x00U);
__DSB();
}
/* Get Data into Buffer */
for(; index < size; index++)
{
*(uint16_t *)pBuffer++ = *(uint16_t *)deviceAddress;
}
/* Increment read pages number */
numPagesRead++;
/* Decrement pages to read */
NumPageToRead--;
/* Increment the NAND address */
nandAddress = (uint32_t)(nandAddress + 1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Write Page(s) to NAND memory block (8-bits addressing)
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @param pBuffer : pointer to source buffer to write
* @param NumPageToWrite : number of pages to write to block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Write_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite)
{
__IO uint32_t index = 0;
uint32_t tickstart = 0;
uint32_t deviceAddress = 0, size = 0, numPagesWritten = 0, nandAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* NAND raw address calculation */
nandAddress = ARRAY_ADDRESS(pAddress, hnand);
/* Page(s) write loop */
while((NumPageToWrite != 0) && (nandAddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* update the buffer size */
size = (hnand->Config.PageSize) + ((hnand->Config.PageSize) * numPagesWritten);
/* Send write page command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
/* Cards with page size <= 512 bytes */
if((hnand->Config.PageSize) <= 512)
{
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
/* Write data to memory */
for(; index < size; index++)
{
*(__IO uint8_t *)deviceAddress = *(uint8_t *)pBuffer++;
__DSB();
}
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;
__DSB();
/* Read status until NAND is ready */
while(HAL_NAND_Read_Status(hnand) != NAND_READY)
{
/* Get tick */
tickstart = HAL_GetTick();
if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Increment written pages number */
numPagesWritten++;
/* Decrement pages to write */
NumPageToWrite--;
/* Increment the NAND address */
nandAddress = (uint32_t)(nandAddress + 1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Write Page(s) to NAND memory block (16-bits addressing)
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @param pBuffer : pointer to source buffer to write. pBuffer should be 16bits aligned
* @param NumPageToWrite : number of pages to write to block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumPageToWrite)
{
__IO uint32_t index = 0;
uint32_t tickstart = 0;
uint32_t deviceAddress = 0, size = 0, numPagesWritten = 0, nandAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* NAND raw address calculation */
nandAddress = ARRAY_ADDRESS(pAddress, hnand);
/* Page(s) write loop */
while((NumPageToWrite != 0) && (nandAddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* update the buffer size */
size = (hnand->Config.PageSize) + ((hnand->Config.PageSize) * numPagesWritten);
/* Send write page command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
/* Cards with page size <= 512 bytes */
if((hnand->Config.PageSize) <= 512)
{
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
/* Write data to memory */
for(; index < size; index++)
{
*(__IO uint16_t *)deviceAddress = *(uint16_t *)pBuffer++;
__DSB();
}
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;
__DSB();
/* Read status until NAND is ready */
while(HAL_NAND_Read_Status(hnand) != NAND_READY)
{
/* Get tick */
tickstart = HAL_GetTick();
if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Increment written pages number */
numPagesWritten++;
/* Decrement pages to write */
NumPageToWrite--;
/* Increment the NAND address */
nandAddress = (uint32_t)(nandAddress + 1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Read Spare area(s) from NAND memory (8-bits addressing)
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @param pBuffer: pointer to source buffer to write
* @param NumSpareAreaToRead: Number of spare area to read
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead)
{
__IO uint32_t index = 0;
uint32_t tickstart = 0U;
uint32_t deviceAddress = 0, size = 0, numSpareAreaRead = 0, nandAddress = 0, columnAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* NAND raw address calculation */
nandAddress = ARRAY_ADDRESS(pAddress, hnand);
/* Column in page address */
columnAddress = COLUMN_ADDRESS(hnand);
/* Spare area(s) read loop */
while((NumSpareAreaToRead != 0) && (nandAddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* update the buffer size */
size = (hnand->Config.SpareAreaSize) + ((hnand->Config.SpareAreaSize) * numSpareAreaRead);
/* Cards with page size <= 512 bytes */
if((hnand->Config.PageSize) <= 512)
{
/* Send read spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_C;
__DSB();
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
/* Send read spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;
__DSB();
if(hnand->Config.ExtraCommandEnable == ENABLE)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while(HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Go back to read mode */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = ((uint8_t)0x00U);
__DSB();
}
/* Get Data into Buffer */
for(; index < size; index++)
{
*(uint8_t *)pBuffer++ = *(uint8_t *)deviceAddress;
}
/* Increment read spare areas number */
numSpareAreaRead++;
/* Decrement spare areas to read */
NumSpareAreaToRead--;
/* Increment the NAND address */
nandAddress = (uint32_t)(nandAddress + 1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Read Spare area(s) from NAND memory (16-bits addressing)
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @param pBuffer: pointer to source buffer to write. pBuffer should be 16bits aligned.
* @param NumSpareAreaToRead: Number of spare area to read
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumSpareAreaToRead)
{
__IO uint32_t index = 0;
uint32_t tickstart = 0U;
uint32_t deviceAddress = 0, size = 0, numSpareAreaRead = 0, nandAddress = 0, columnAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* NAND raw address calculation */
nandAddress = ARRAY_ADDRESS(pAddress, hnand);
/* Column in page address */
columnAddress = (uint32_t)(COLUMN_ADDRESS(hnand) * 2);
/* Spare area(s) read loop */
while((NumSpareAreaToRead != 0) && (nandAddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* update the buffer size */
size = (hnand->Config.SpareAreaSize) + ((hnand->Config.SpareAreaSize) * numSpareAreaRead);
/* Cards with page size <= 512 bytes */
if((hnand->Config.PageSize) <= 512)
{
/* Send read spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_C;
__DSB();
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
/* Send read spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;
__DSB();
if(hnand->Config.ExtraCommandEnable == ENABLE)
{
/* Get tick */
tickstart = HAL_GetTick();
/* Read status until NAND is ready */
while(HAL_NAND_Read_Status(hnand) != NAND_READY)
{
if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Go back to read mode */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = ((uint8_t)0x00U);
__DSB();
}
/* Get Data into Buffer */
for(; index < size; index++)
{
*(uint16_t *)pBuffer++ = *(uint16_t *)deviceAddress;
}
/* Increment read spare areas number */
numSpareAreaRead++;
/* Decrement spare areas to read */
NumSpareAreaToRead--;
/* Increment the NAND address */
nandAddress = (uint32_t)(nandAddress + 1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Write Spare area(s) to NAND memory (8-bits addressing)
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @param pBuffer : pointer to source buffer to write
* @param NumSpareAreaTowrite : number of spare areas to write to block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite)
{
__IO uint32_t index = 0;
uint32_t tickstart = 0;
uint32_t deviceAddress = 0, size = 0, numSpareAreaWritten = 0, nandAddress = 0, columnAddress =0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the FMC_NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Page address calculation */
nandAddress = ARRAY_ADDRESS(pAddress, hnand);
/* Column in page address */
columnAddress = COLUMN_ADDRESS(hnand);
/* Spare area(s) write loop */
while((NumSpareAreaTowrite != 0) && (nandAddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* update the buffer size */
size = (hnand->Config.SpareAreaSize) + ((hnand->Config.SpareAreaSize) * numSpareAreaWritten);
/* Cards with page size <= 512 bytes */
if((hnand->Config.PageSize) <= 512)
{
/* Send write Spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_C;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
/* Send write Spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
/* Write data to memory */
for(; index < size; index++)
{
*(__IO uint8_t *)deviceAddress = *(uint8_t *)pBuffer++;
__DSB();
}
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;
__DSB();
/* Read status until NAND is ready */
while(HAL_NAND_Read_Status(hnand) != NAND_READY)
{
/* Get tick */
tickstart = HAL_GetTick();
if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Increment written spare areas number */
numSpareAreaWritten++;
/* Decrement spare areas to write */
NumSpareAreaTowrite--;
/* Increment the NAND address */
nandAddress = (uint32_t)(nandAddress + 1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Write Spare area(s) to NAND memory (16-bits addressing)
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @param pBuffer : pointer to source buffer to write. pBuffer should be 16bits aligned.
* @param NumSpareAreaTowrite : number of spare areas to write to block
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumSpareAreaTowrite)
{
__IO uint32_t index = 0;
uint32_t tickstart = 0;
uint32_t deviceAddress = 0, size = 0, numSpareAreaWritten = 0, nandAddress = 0, columnAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
deviceAddress = NAND_DEVICE;
/* Update the FMC_NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* NAND raw address calculation */
nandAddress = ARRAY_ADDRESS(pAddress, hnand);
/* Column in page address */
columnAddress = (uint32_t)(COLUMN_ADDRESS(hnand) * 2);
/* Spare area(s) write loop */
while((NumSpareAreaTowrite != 0) && (nandAddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr))))
{
/* update the buffer size */
size = (hnand->Config.SpareAreaSize) + ((hnand->Config.SpareAreaSize) * numSpareAreaWritten);
/* Cards with page size <= 512 bytes */
if((hnand->Config.PageSize) <= 512)
{
/* Send write Spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_C;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = 0x00;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
else /* (hnand->Config.PageSize) > 512 */
{
/* Send write Spare area command sequence */
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_AREA_A;
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE0;
__DSB();
if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535)
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
}
else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */
{
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandAddress);
__DSB();
*(__IO uint8_t *)((uint32_t)(deviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandAddress);
__DSB();
}
}
/* Write data to memory */
for(; index < size; index++)
{
*(__IO uint16_t *)deviceAddress = *(uint16_t *)pBuffer++;
__DSB();
}
*(__IO uint8_t *)((uint32_t)(deviceAddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;
__DSB();
/* Read status until NAND is ready */
while(HAL_NAND_Read_Status(hnand) != NAND_READY)
{
/* Get tick */
tickstart = HAL_GetTick();
if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Increment written spare areas number */
numSpareAreaWritten++;
/* Decrement spare areas to write */
NumSpareAreaTowrite--;
/* Increment the NAND address */
nandAddress = (uint32_t)(nandAddress + 1);
}
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief NAND memory Block erase
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress : pointer to NAND address structure
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress)
{
uint32_t DeviceAddress = 0;
/* Process Locked */
__HAL_LOCK(hnand);
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Identify the device address */
DeviceAddress = NAND_DEVICE;
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Send Erase block command sequence */
*(__IO uint8_t *)((uint32_t)(DeviceAddress | CMD_AREA)) = NAND_CMD_ERASE0;
__DSB();
*(__IO uint8_t *)((uint32_t)(DeviceAddress | ADDR_AREA)) = ADDR_1ST_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
__DSB();
*(__IO uint8_t *)((uint32_t)(DeviceAddress | ADDR_AREA)) = ADDR_2ND_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
__DSB();
*(__IO uint8_t *)((uint32_t)(DeviceAddress | ADDR_AREA)) = ADDR_3RD_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
__DSB();
*(__IO uint8_t *)((uint32_t)(DeviceAddress | CMD_AREA)) = NAND_CMD_ERASE1;
__DSB();
/* Update the NAND controller state */
hnand->State = HAL_NAND_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(hnand);
return HAL_OK;
}
/**
* @brief Increment the NAND memory address
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param pAddress: pointer to NAND address structure
* @retval The new status of the increment address operation. It can be:
* - NAND_VALID_ADDRESS: When the new address is valid address
* - NAND_INVALID_ADDRESS: When the new address is invalid address
*/
uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress)
{
uint32_t status = NAND_VALID_ADDRESS;
/* Increment page address */
pAddress->Page++;
/* Check NAND address is valid */
if(pAddress->Page == hnand->Config.BlockSize)
{
pAddress->Page = 0;
pAddress->Block++;
if(pAddress->Block == hnand->Config.PlaneSize)
{
pAddress->Block = 0;
pAddress->Plane++;
if(pAddress->Plane == (hnand->Config.PlaneSize/ hnand->Config.BlockNbr))
{
status = NAND_INVALID_ADDRESS;
}
}
}
return (status);
}
/**
* @}
*/
/** @defgroup NAND_Exported_Functions_Group3 Peripheral Control functions
* @brief management functions
*
@verbatim
==============================================================================
##### NAND Control functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to control dynamically
the NAND interface.
@endverbatim
* @{
*/
/**
* @brief Enables dynamically NAND ECC feature.
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand)
{
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Enable ECC feature */
FMC_NAND_ECC_Enable(hnand->Instance, hnand->Init.NandBank);
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_READY;
return HAL_OK;
}
/**
* @brief Disables dynamically FMC_NAND ECC feature.
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand)
{
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Disable ECC feature */
FMC_NAND_ECC_Disable(hnand->Instance, hnand->Init.NandBank);
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_READY;
return HAL_OK;
}
/**
* @brief Disables dynamically NAND ECC feature.
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @param ECCval: pointer to ECC value
* @param Timeout: maximum timeout to wait
* @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the NAND controller state */
if(hnand->State == HAL_NAND_STATE_BUSY)
{
return HAL_BUSY;
}
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_BUSY;
/* Get NAND ECC value */
status = FMC_NAND_GetECC(hnand->Instance, ECCval, hnand->Init.NandBank, Timeout);
/* Update the NAND state */
hnand->State = HAL_NAND_STATE_READY;
return status;
}
/**
* @}
*/
/** @defgroup NAND_Exported_Functions_Group4 Peripheral State functions
* @brief Peripheral State functions
*
@verbatim
==============================================================================
##### NAND State functions #####
==============================================================================
[..]
This subsection permits to get in run-time the status of the NAND controller
and the data flow.
@endverbatim
* @{
*/
/**
* @brief return the NAND state
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval HAL state
*/
HAL_NAND_StateTypeDef HAL_NAND_GetState(NAND_HandleTypeDef *hnand)
{
return hnand->State;
}
/**
* @brief NAND memory read status
* @param hnand: pointer to a NAND_HandleTypeDef structure that contains
* the configuration information for NAND module.
* @retval NAND status
*/
uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand)
{
uint32_t data = 0;
uint32_t DeviceAddress = 0;
/* Identify the device address */
DeviceAddress = NAND_DEVICE;
/* Send Read status operation command */
*(__IO uint8_t *)((uint32_t)(DeviceAddress | CMD_AREA)) = NAND_CMD_STATUS;
/* Read status register data */
data = *(__IO uint8_t *)DeviceAddress;
/* Return the status */
if((data & NAND_ERROR) == NAND_ERROR)
{
return NAND_ERROR;
}
else if((data & NAND_READY) == NAND_READY)
{
return NAND_READY;
}
return NAND_BUSY;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_NAND_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
svagionitis/aws-sdk-cpp | aws-cpp-sdk-greengrass/source/model/DeleteFunctionDefinitionRequest.cpp | 2 | 1024 | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/greengrass/model/DeleteFunctionDefinitionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Greengrass::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteFunctionDefinitionRequest::DeleteFunctionDefinitionRequest() :
m_functionDefinitionIdHasBeenSet(false)
{
}
Aws::String DeleteFunctionDefinitionRequest::SerializePayload() const
{
return "";
}
| apache-2.0 |
hhool/ffplayer | jni/include/aosp-18/frameworks/base/native/android/input.cpp | 2 | 11406 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.
*/
#define LOG_TAG "input"
#include <utils/Log.h>
#include <android/input.h>
#include <androidfw/Input.h>
#include <androidfw/InputTransport.h>
#include <utils/Looper.h>
#include <utils/RefBase.h>
#include <utils/Vector.h>
#include <android_runtime/android_app_NativeActivity.h>
#include <android_runtime/android_view_InputQueue.h>
#include <poll.h>
#include <errno.h>
using android::InputEvent;
using android::InputQueue;
using android::KeyEvent;
using android::Looper;
using android::MotionEvent;
using android::sp;
using android::Vector;
int32_t AInputEvent_getType(const AInputEvent* event) {
return static_cast<const InputEvent*>(event)->getType();
}
int32_t AInputEvent_getDeviceId(const AInputEvent* event) {
return static_cast<const InputEvent*>(event)->getDeviceId();
}
int32_t AInputEvent_getSource(const AInputEvent* event) {
return static_cast<const InputEvent*>(event)->getSource();
}
int32_t AKeyEvent_getAction(const AInputEvent* key_event) {
return static_cast<const KeyEvent*>(key_event)->getAction();
}
int32_t AKeyEvent_getFlags(const AInputEvent* key_event) {
return static_cast<const KeyEvent*>(key_event)->getFlags();
}
int32_t AKeyEvent_getKeyCode(const AInputEvent* key_event) {
return static_cast<const KeyEvent*>(key_event)->getKeyCode();
}
int32_t AKeyEvent_getScanCode(const AInputEvent* key_event) {
return static_cast<const KeyEvent*>(key_event)->getScanCode();
}
int32_t AKeyEvent_getMetaState(const AInputEvent* key_event) {
return static_cast<const KeyEvent*>(key_event)->getMetaState();
}
int32_t AKeyEvent_getRepeatCount(const AInputEvent* key_event) {
return static_cast<const KeyEvent*>(key_event)->getRepeatCount();
}
int64_t AKeyEvent_getDownTime(const AInputEvent* key_event) {
return static_cast<const KeyEvent*>(key_event)->getDownTime();
}
int64_t AKeyEvent_getEventTime(const AInputEvent* key_event) {
return static_cast<const KeyEvent*>(key_event)->getEventTime();
}
int32_t AMotionEvent_getAction(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getAction();
}
int32_t AMotionEvent_getFlags(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getFlags();
}
int32_t AMotionEvent_getMetaState(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getMetaState();
}
int32_t AMotionEvent_getButtonState(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getButtonState();
}
int32_t AMotionEvent_getEdgeFlags(const AInputEvent* motion_event) {
return reinterpret_cast<const MotionEvent*>(motion_event)->getEdgeFlags();
}
int64_t AMotionEvent_getDownTime(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getDownTime();
}
int64_t AMotionEvent_getEventTime(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getEventTime();
}
float AMotionEvent_getXOffset(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getXOffset();
}
float AMotionEvent_getYOffset(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getYOffset();
}
float AMotionEvent_getXPrecision(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getXPrecision();
}
float AMotionEvent_getYPrecision(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getYPrecision();
}
size_t AMotionEvent_getPointerCount(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getPointerCount();
}
int32_t AMotionEvent_getPointerId(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getPointerId(pointer_index);
}
int32_t AMotionEvent_getToolType(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getToolType(pointer_index);
}
float AMotionEvent_getRawX(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getRawX(pointer_index);
}
float AMotionEvent_getRawY(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getRawY(pointer_index);
}
float AMotionEvent_getX(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getX(pointer_index);
}
float AMotionEvent_getY(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getY(pointer_index);
}
float AMotionEvent_getPressure(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getPressure(pointer_index);
}
float AMotionEvent_getSize(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getSize(pointer_index);
}
float AMotionEvent_getTouchMajor(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getTouchMajor(pointer_index);
}
float AMotionEvent_getTouchMinor(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getTouchMinor(pointer_index);
}
float AMotionEvent_getToolMajor(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getToolMajor(pointer_index);
}
float AMotionEvent_getToolMinor(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getToolMinor(pointer_index);
}
float AMotionEvent_getOrientation(const AInputEvent* motion_event, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getOrientation(pointer_index);
}
float AMotionEvent_getAxisValue(const AInputEvent* motion_event,
int32_t axis, size_t pointer_index) {
return static_cast<const MotionEvent*>(motion_event)->getAxisValue(axis, pointer_index);
}
size_t AMotionEvent_getHistorySize(const AInputEvent* motion_event) {
return static_cast<const MotionEvent*>(motion_event)->getHistorySize();
}
int64_t AMotionEvent_getHistoricalEventTime(AInputEvent* motion_event,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalEventTime(
history_index);
}
float AMotionEvent_getHistoricalRawX(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalRawX(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalRawY(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalRawY(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalX(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalX(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalY(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalY(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalPressure(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalPressure(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalSize(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalSize(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalTouchMajor(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalTouchMajor(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalTouchMinor(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalTouchMinor(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalToolMajor(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalToolMajor(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalToolMinor(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalToolMinor(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalOrientation(AInputEvent* motion_event, size_t pointer_index,
size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalOrientation(
pointer_index, history_index);
}
float AMotionEvent_getHistoricalAxisValue(const AInputEvent* motion_event,
int32_t axis, size_t pointer_index, size_t history_index) {
return static_cast<const MotionEvent*>(motion_event)->getHistoricalAxisValue(
axis, pointer_index, history_index);
}
void AInputQueue_attachLooper(AInputQueue* queue, ALooper* looper,
int ident, ALooper_callbackFunc callback, void* data) {
InputQueue* iq = static_cast<InputQueue*>(queue);
Looper* l = static_cast<Looper*>(looper);
iq->attachLooper(l, ident, callback, data);
}
void AInputQueue_detachLooper(AInputQueue* queue) {
InputQueue* iq = static_cast<InputQueue*>(queue);
iq->detachLooper();
}
int32_t AInputQueue_hasEvents(AInputQueue* queue) {
InputQueue* iq = static_cast<InputQueue*>(queue);
return iq->hasEvents();
}
int32_t AInputQueue_getEvent(AInputQueue* queue, AInputEvent** outEvent) {
InputQueue* iq = static_cast<InputQueue*>(queue);
InputEvent* event;
int32_t res = iq->getEvent(&event);
*outEvent = event;
return res;
}
int32_t AInputQueue_preDispatchEvent(AInputQueue* queue, AInputEvent* event) {
InputQueue* iq = static_cast<InputQueue*>(queue);
InputEvent* e = static_cast<InputEvent*>(event);
return iq->preDispatchEvent(e) ? 1 : 0;
}
void AInputQueue_finishEvent(AInputQueue* queue, AInputEvent* event, int handled) {
InputQueue* iq = static_cast<InputQueue*>(queue);
InputEvent* e = static_cast<InputEvent*>(event);
iq->finishEvent(e, handled != 0);
}
| apache-2.0 |
mosaic-cloud/mosaic-distribution-dependencies | dependencies/otp/r15b03-1/erts/emulator/beam/erl_arith.c | 3 | 53071 | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 1999-2010. All Rights Reserved.
*
* The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved online at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* %CopyrightEnd%
*/
/*
* Arithmetic functions formerly found in beam_emu.c
* now available as bifs as erl_db_util and db_match_compile needs
* them.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "sys.h"
#include "erl_vm.h"
#include "global.h"
#include "erl_process.h"
#include "error.h"
#include "bif.h"
#include "big.h"
#include "atom.h"
#ifndef MAX
# define MAX(x, y) (((x) > (y)) ? (x) : (y))
#endif
#if !HEAP_ON_C_STACK
# define DECLARE_TMP(VariableName,N,P) \
Eterm *VariableName = ((ERTS_PROC_GET_SCHDATA(P)->erl_arith_tmp_heap) + (2 * N))
#else
# define DECLARE_TMP(VariableName,N,P) \
Eterm VariableName[2]
#endif
# define ARG_IS_NOT_TMP(Arg,Tmp) ((Arg) != make_big((Tmp)))
static Eterm shift(Process* p, Eterm arg1, Eterm arg2, int right);
static ERTS_INLINE void maybe_shrink(Process* p, Eterm* hp, Eterm res, Uint alloc)
{
Uint actual;
if (is_immed(res)) {
if (p->heap <= hp && hp < p->htop) {
p->htop = hp;
}
else {
erts_heap_frag_shrink(p, hp);
}
} else if ((actual = bignum_header_arity(*hp)+1) < alloc) {
if (p->heap <= hp && hp < p->htop) {
p->htop = hp+actual;
}
else {
erts_heap_frag_shrink(p, hp+actual);
}
}
}
/*
* BIF interfaces. They will only be from match specs and
* when a BIF is applied.
*/
BIF_RETTYPE splus_1(BIF_ALIST_1)
{
if (is_number(BIF_ARG_1)) {
BIF_RET(BIF_ARG_1);
} else {
BIF_ERROR(BIF_P, BADARITH);
}
}
BIF_RETTYPE splus_2(BIF_ALIST_2)
{
BIF_RET(erts_mixed_plus(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE sminus_1(BIF_ALIST_1)
{
BIF_RET(erts_mixed_minus(BIF_P, make_small(0), BIF_ARG_1));
}
BIF_RETTYPE sminus_2(BIF_ALIST_2)
{
BIF_RET(erts_mixed_minus(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE stimes_2(BIF_ALIST_2)
{
BIF_RET(erts_mixed_times(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE div_2(BIF_ALIST_2)
{
BIF_RET(erts_mixed_div(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE intdiv_2(BIF_ALIST_2)
{
if (BIF_ARG_2 == SMALL_ZERO) {
BIF_ERROR(BIF_P, BADARITH);
}
if (is_both_small(BIF_ARG_1,BIF_ARG_2)){
Sint ires = signed_val(BIF_ARG_1) / signed_val(BIF_ARG_2);
if (MY_IS_SSMALL(ires))
BIF_RET(make_small(ires));
}
BIF_RET(erts_int_div(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE rem_2(BIF_ALIST_2)
{
if (BIF_ARG_2 == SMALL_ZERO) {
BIF_ERROR(BIF_P, BADARITH);
}
if (is_both_small(BIF_ARG_1,BIF_ARG_2)){
/* Is this really correct? Isn't there a difference between
remainder and modulo that is not defined in C? Well, I don't
remember, this is the way it's done in beam_emu anyway... */
BIF_RET(make_small(signed_val(BIF_ARG_1) % signed_val(BIF_ARG_2)));
}
BIF_RET(erts_int_rem(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE band_2(BIF_ALIST_2)
{
if (is_both_small(BIF_ARG_1,BIF_ARG_2)){
BIF_RET(BIF_ARG_1 & BIF_ARG_2);
}
BIF_RET(erts_band(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE bor_2(BIF_ALIST_2)
{
if (is_both_small(BIF_ARG_1,BIF_ARG_2)){
BIF_RET(BIF_ARG_1 | BIF_ARG_2);
}
BIF_RET(erts_bor(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE bxor_2(BIF_ALIST_2)
{
if (is_both_small(BIF_ARG_1,BIF_ARG_2)){
BIF_RET(make_small(signed_val(BIF_ARG_1) ^ signed_val(BIF_ARG_2)));
}
BIF_RET(erts_bxor(BIF_P, BIF_ARG_1, BIF_ARG_2));
}
BIF_RETTYPE bsl_2(BIF_ALIST_2)
{
BIF_RET(shift(BIF_P, BIF_ARG_1, BIF_ARG_2, 0));
}
BIF_RETTYPE bsr_2(BIF_ALIST_2)
{
BIF_RET(shift(BIF_P, BIF_ARG_1, BIF_ARG_2, 1));
}
static Eterm
shift(Process* p, Eterm arg1, Eterm arg2, int right)
{
Sint i;
Sint ires;
DECLARE_TMP(tmp_big1,0,p);
Eterm* bigp;
Uint need;
if (right) {
if (is_small(arg2)) {
i = -signed_val(arg2);
if (is_small(arg1)) {
goto small_shift;
} else if (is_big(arg1)) {
if (i == 0) {
BIF_RET(arg1);
}
goto big_shift;
}
} else if (is_big(arg2)) {
/*
* N bsr NegativeBigNum == N bsl MAX_SMALL
* N bsr PositiveBigNum == N bsl MIN_SMALL
*/
arg2 = make_small(bignum_header_is_neg(*big_val(arg2)) ?
MAX_SMALL : MIN_SMALL);
goto do_bsl;
}
} else {
do_bsl:
if (is_small(arg2)) {
i = signed_val(arg2);
if (is_small(arg1)) {
small_shift:
ires = signed_val(arg1);
if (i == 0 || ires == 0) {
BIF_RET(arg1);
} else if (i < 0) { /* Right shift */
i = -i;
if (i >= SMALL_BITS-1) {
arg1 = (ires < 0) ? SMALL_MINUS_ONE : SMALL_ZERO;
} else {
arg1 = make_small(ires >> i);
}
BIF_RET(arg1);
} else if (i < SMALL_BITS-1) { /* Left shift */
if ((ires > 0 && ((~(Uint)0 << ((SMALL_BITS-1)-i)) & ires) == 0) ||
((~(Uint)0 << ((SMALL_BITS-1)-i)) & ~ires) == 0) {
arg1 = make_small(ires << i);
BIF_RET(arg1);
}
}
arg1 = small_to_big(ires, tmp_big1);
big_shift:
if (i > 0) { /* Left shift. */
ires = big_size(arg1) + (i / D_EXP);
} else { /* Right shift. */
ires = big_size(arg1);
if (ires <= (-i / D_EXP))
ires = 3;
else
ires -= (-i / D_EXP);
}
/*
* Slightly conservative check the size to avoid
* allocating huge amounts of memory for bignums that
* clearly would overflow the arity in the header
* word.
*/
if (ires-8 > BIG_ARITY_MAX) {
BIF_ERROR(p, SYSTEM_LIMIT);
}
need = BIG_NEED_SIZE(ires+1);
bigp = HAlloc(p, need);
arg1 = big_lshift(arg1, i, bigp);
maybe_shrink(p, bigp, arg1, need);
if (is_nil(arg1)) {
/*
* This result must have been only slight larger
* than allowed since it wasn't caught by the
* previous test.
*/
BIF_ERROR(p, SYSTEM_LIMIT);
}
BIF_RET(arg1);
} else if (is_big(arg1)) {
if (i == 0) {
BIF_RET(arg1);
}
goto big_shift;
}
} else if (is_big(arg2)) {
if (bignum_header_is_neg(*big_val(arg2))) {
/*
* N bsl NegativeBigNum is either 0 or -1, depending on
* the sign of N. Since we don't believe this case
* is common, do the calculation with the minimum
* amount of code.
*/
arg2 = make_small(MIN_SMALL);
goto do_bsl;
} else if (is_small(arg1) || is_big(arg1)) {
/*
* N bsl PositiveBigNum is too large to represent.
*/
BIF_ERROR(p, SYSTEM_LIMIT);
}
/* Fall through if the left argument is not an integer. */
}
}
BIF_ERROR(p, BADARITH);
}
BIF_RETTYPE bnot_1(BIF_ALIST_1)
{
Eterm ret;
if (is_small(BIF_ARG_1)) {
ret = make_small(~signed_val(BIF_ARG_1));
} else if (is_big(BIF_ARG_1)) {
Uint need = BIG_NEED_SIZE(big_size(BIF_ARG_1)+1);
Eterm* bigp = HAlloc(BIF_P, need);
ret = big_bnot(BIF_ARG_1, bigp);
maybe_shrink(BIF_P, bigp, ret, need);
if (is_nil(ret)) {
BIF_ERROR(BIF_P, SYSTEM_LIMIT);
}
} else {
BIF_ERROR(BIF_P, BADARITH);
}
BIF_RET(ret);
}
/*
* Implementation and interfaces for the rest of the runtime system.
* The functions that follow are only used in match specs and when
* arithmetic functions are applied.
*/
Eterm
erts_mixed_plus(Process* p, Eterm arg1, Eterm arg2)
{
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm res;
Eterm hdr;
FloatDef f1, f2;
dsize_t sz1, sz2, sz;
int need_heap;
Eterm* hp;
Sint ires;
ERTS_FP_CHECK_INIT(p);
switch (arg1 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg1 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
ires = signed_val(arg1) + signed_val(arg2);
ASSERT(MY_IS_SSMALL(ires) == IS_SSMALL(ires));
if (MY_IS_SSMALL(ires)) {
return make_small(ires);
} else {
hp = HAlloc(p, 2);
res = small_to_big(ires, hp);
return res;
}
default:
badarith:
p->freason = BADARITH;
return THE_NON_VALUE;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
if (arg1 == SMALL_ZERO) {
return arg2;
}
arg1 = small_to_big(signed_val(arg1), tmp_big1);
goto do_big;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg1);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if (arg2 == SMALL_ZERO) {
return arg1;
}
arg2 = small_to_big(signed_val(arg2), tmp_big2);
goto do_big;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
do_big:
sz1 = big_size(arg1);
sz2 = big_size(arg2);
sz = MAX(sz1, sz2)+1;
need_heap = BIG_NEED_SIZE(sz);
hp = HAlloc(p, need_heap);
res = big_plus(arg1, arg2, hp);
maybe_shrink(p, hp, res, need_heap);
if (is_nil(res)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
return res;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
GET_DOUBLE(arg2, f2);
do_float:
f1.fd = f1.fd + f2.fd;
ERTS_FP_ERROR(p, f1.fd, goto badarith);
hp = HAlloc(p, FLOAT_SIZE_OBJECT);
res = make_float(hp);
PUT_DOUBLE(f1, hp);
return res;
default:
goto badarith;
}
default:
goto badarith;
}
}
default:
goto badarith;
}
}
Eterm
erts_mixed_minus(Process* p, Eterm arg1, Eterm arg2)
{
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm hdr;
Eterm res;
FloatDef f1, f2;
dsize_t sz1, sz2, sz;
int need_heap;
Eterm* hp;
Sint ires;
ERTS_FP_CHECK_INIT(p);
switch (arg1 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg1 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
ires = signed_val(arg1) - signed_val(arg2);
ASSERT(MY_IS_SSMALL(ires) == IS_SSMALL(ires));
if (MY_IS_SSMALL(ires)) {
return make_small(ires);
} else {
hp = HAlloc(p, 2);
res = small_to_big(ires, hp);
return res;
}
default:
badarith:
p->freason = BADARITH;
return THE_NON_VALUE;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
arg1 = small_to_big(signed_val(arg1), tmp_big1);
goto do_big;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg1);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if (arg2 == SMALL_ZERO) {
return arg1;
}
arg2 = small_to_big(signed_val(arg2), tmp_big2);
do_big:
sz1 = big_size(arg1);
sz2 = big_size(arg2);
sz = MAX(sz1, sz2)+1;
need_heap = BIG_NEED_SIZE(sz);
hp = HAlloc(p, need_heap);
res = big_minus(arg1, arg2, hp);
maybe_shrink(p, hp, res, need_heap);
if (is_nil(res)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
return res;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
goto do_big;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
GET_DOUBLE(arg2, f2);
do_float:
f1.fd = f1.fd - f2.fd;
ERTS_FP_ERROR(p, f1.fd, goto badarith);
hp = HAlloc(p, FLOAT_SIZE_OBJECT);
res = make_float(hp);
PUT_DOUBLE(f1, hp);
return res;
default:
goto badarith;
}
default:
goto badarith;
}
}
default:
goto badarith;
}
}
Eterm
erts_mixed_times(Process* p, Eterm arg1, Eterm arg2)
{
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm hdr;
Eterm res;
FloatDef f1, f2;
dsize_t sz1, sz2, sz;
int need_heap;
Eterm* hp;
ERTS_FP_CHECK_INIT(p);
switch (arg1 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg1 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if ((arg1 == SMALL_ZERO) || (arg2 == SMALL_ZERO)) {
return(SMALL_ZERO);
} else if (arg1 == SMALL_ONE) {
return(arg2);
} else if (arg2 == SMALL_ONE) {
return(arg1);
} else {
DeclareTmpHeap(big_res,3,p);
UseTmpHeap(3,p);
/*
* The following code is optimized for the case that
* result is small (which should be the most common case
* in practice).
*/
res = small_times(signed_val(arg1), signed_val(arg2), big_res);
if (is_small(res)) {
UnUseTmpHeap(3,p);
return res;
} else {
/*
* The result is a a big number.
* Allocate a heap fragment and copy the result.
* Be careful to allocate exactly what we need
* to not leave any holes.
*/
Uint arity;
ASSERT(is_big(res));
hdr = big_res[0];
arity = bignum_header_arity(hdr);
ASSERT(arity == 1 || arity == 2);
hp = HAlloc(p, arity+1);
res = make_big(hp);
*hp++ = hdr;
*hp++ = big_res[1];
if (arity > 1) {
*hp = big_res[2];
}
UnUseTmpHeap(3,p);
return res;
}
}
default:
badarith:
p->freason = BADARITH;
return THE_NON_VALUE;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
if (arg1 == SMALL_ZERO)
return(SMALL_ZERO);
if (arg1 == SMALL_ONE)
return(arg2);
arg1 = small_to_big(signed_val(arg1), tmp_big1);
sz = 2 + big_size(arg2);
goto do_big;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg1);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if (arg2 == SMALL_ZERO)
return(SMALL_ZERO);
if (arg2 == SMALL_ONE)
return(arg1);
arg2 = small_to_big(signed_val(arg2), tmp_big2);
sz = 2 + big_size(arg1);
goto do_big;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
sz1 = big_size(arg1);
sz2 = big_size(arg2);
sz = sz1 + sz2;
do_big:
need_heap = BIG_NEED_SIZE(sz);
hp = HAlloc(p, need_heap);
res = big_times(arg1, arg2, hp);
/*
* Note that the result must be big in this case, since
* at least one operand was big to begin with, and
* the absolute value of the other is > 1.
*/
maybe_shrink(p, hp, res, need_heap);
if (is_nil(res)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
return res;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
GET_DOUBLE(arg2, f2);
do_float:
f1.fd = f1.fd * f2.fd;
ERTS_FP_ERROR(p, f1.fd, goto badarith);
hp = HAlloc(p, FLOAT_SIZE_OBJECT);
res = make_float(hp);
PUT_DOUBLE(f1, hp);
return res;
default:
goto badarith;
}
default:
goto badarith;
}
}
default:
goto badarith;
}
}
Eterm
erts_mixed_div(Process* p, Eterm arg1, Eterm arg2)
{
FloatDef f1, f2;
Eterm* hp;
Eterm hdr;
ERTS_FP_CHECK_INIT(p);
switch (arg1 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg1 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
f2.fd = signed_val(arg2);
goto do_float;
default:
badarith:
p->freason = BADARITH;
return THE_NON_VALUE;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg1);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0 ||
big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
GET_DOUBLE(arg2, f2);
do_float:
f1.fd = f1.fd / f2.fd;
ERTS_FP_ERROR(p, f1.fd, goto badarith);
hp = HAlloc(p, FLOAT_SIZE_OBJECT);
PUT_DOUBLE(f1, hp);
return make_float(hp);
default:
goto badarith;
}
default:
goto badarith;
}
}
default:
goto badarith;
}
}
Eterm
erts_int_div(Process* p, Eterm arg1, Eterm arg2)
{
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
int ires;
switch (NUMBER_CODE(arg1, arg2)) {
case SMALL_SMALL:
/* This case occurs if the most negative fixnum is divided by -1. */
ASSERT(arg2 == make_small(-1));
arg1 = small_to_big(signed_val(arg1), tmp_big1);
/*FALLTHROUGH*/
case BIG_SMALL:
arg2 = small_to_big(signed_val(arg2), tmp_big2);
goto L_big_div;
case SMALL_BIG:
if (arg1 != make_small(MIN_SMALL)) {
return SMALL_ZERO;
}
arg1 = small_to_big(signed_val(arg1), tmp_big1);
/*FALLTHROUGH*/
case BIG_BIG:
L_big_div:
ires = big_ucomp(arg1, arg2);
if (ires < 0) {
arg1 = SMALL_ZERO;
} else if (ires == 0) {
arg1 = (big_sign(arg1) == big_sign(arg2)) ?
SMALL_ONE : SMALL_MINUS_ONE;
} else {
Eterm* hp;
int i = big_size(arg1);
Uint need;
ires = big_size(arg2);
need = BIG_NEED_SIZE(i-ires+1) + BIG_NEED_SIZE(i);
hp = HAlloc(p, need);
arg1 = big_div(arg1, arg2, hp);
maybe_shrink(p, hp, arg1, need);
if (is_nil(arg1)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
}
return arg1;
default:
p->freason = BADARITH;
return THE_NON_VALUE;
}
}
Eterm
erts_int_rem(Process* p, Eterm arg1, Eterm arg2)
{
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
int ires;
switch (NUMBER_CODE(arg1, arg2)) {
case BIG_SMALL:
arg2 = small_to_big(signed_val(arg2), tmp_big2);
goto L_big_rem;
case SMALL_BIG:
if (arg1 != make_small(MIN_SMALL)) {
return arg1;
} else {
Eterm tmp;
tmp = small_to_big(signed_val(arg1), tmp_big1);
if ((ires = big_ucomp(tmp, arg2)) == 0) {
return SMALL_ZERO;
} else {
ASSERT(ires < 0);
return arg1;
}
}
/* All paths returned */
case BIG_BIG:
L_big_rem:
ires = big_ucomp(arg1, arg2);
if (ires == 0) {
arg1 = SMALL_ZERO;
} else if (ires > 0) {
Uint need = BIG_NEED_SIZE(big_size(arg1));
Eterm* hp = HAlloc(p, need);
arg1 = big_rem(arg1, arg2, hp);
maybe_shrink(p, hp, arg1, need);
if (is_nil(arg1)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
}
return arg1;
default:
p->freason = BADARITH;
return THE_NON_VALUE;
}
}
Eterm erts_band(Process* p, Eterm arg1, Eterm arg2)
{
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm* hp;
int need;
switch (NUMBER_CODE(arg1, arg2)) {
case SMALL_BIG:
arg1 = small_to_big(signed_val(arg1), tmp_big1);
break;
case BIG_SMALL:
arg2 = small_to_big(signed_val(arg2), tmp_big2);
break;
case BIG_BIG:
break;
default:
p->freason = BADARITH;
return THE_NON_VALUE;
}
need = BIG_NEED_SIZE(MAX(big_size(arg1), big_size(arg2)) + 1);
hp = HAlloc(p, need);
arg1 = big_band(arg1, arg2, hp);
ASSERT(is_not_nil(arg1));
maybe_shrink(p, hp, arg1, need);
return arg1;
}
Eterm erts_bor(Process* p, Eterm arg1, Eterm arg2)
{
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm* hp;
int need;
switch (NUMBER_CODE(arg1, arg2)) {
case SMALL_BIG:
arg1 = small_to_big(signed_val(arg1), tmp_big1);
break;
case BIG_SMALL:
arg2 = small_to_big(signed_val(arg2), tmp_big2);
break;
case BIG_BIG:
break;
default:
p->freason = BADARITH;
return THE_NON_VALUE;
}
need = BIG_NEED_SIZE(MAX(big_size(arg1), big_size(arg2)) + 1);
hp = HAlloc(p, need);
arg1 = big_bor(arg1, arg2, hp);
ASSERT(is_not_nil(arg1));
maybe_shrink(p, hp, arg1, need);
return arg1;
}
Eterm erts_bxor(Process* p, Eterm arg1, Eterm arg2)
{
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm* hp;
int need;
switch (NUMBER_CODE(arg1, arg2)) {
case SMALL_BIG:
arg1 = small_to_big(signed_val(arg1), tmp_big1);
break;
case BIG_SMALL:
arg2 = small_to_big(signed_val(arg2), tmp_big2);
break;
case BIG_BIG:
break;
default:
p->freason = BADARITH;
return THE_NON_VALUE;
}
need = BIG_NEED_SIZE(MAX(big_size(arg1), big_size(arg2)) + 1);
hp = HAlloc(p, need);
arg1 = big_bxor(arg1, arg2, hp);
ASSERT(is_not_nil(arg1));
maybe_shrink(p, hp, arg1, need);
return arg1;
}
Eterm erts_bnot(Process* p, Eterm arg)
{
Eterm ret;
if (is_big(arg)) {
Uint need = BIG_NEED_SIZE(big_size(arg)+1);
Eterm* bigp = HAlloc(p, need);
ret = big_bnot(arg, bigp);
maybe_shrink(p, bigp, ret, need);
if (is_nil(ret)) {
p->freason = SYSTEM_LIMIT;
return NIL;
}
} else {
p->freason = BADARITH;
return NIL;
}
return ret;
}
#define ERTS_NEED_GC(p, need) ((HEAP_LIMIT((p)) - HEAP_TOP((p))) <= (need))
static ERTS_INLINE void
trim_heap(Process* p, Eterm* hp, Eterm res)
{
if (is_immed(res)) {
ASSERT(p->heap <= hp && hp <= p->htop);
p->htop = hp;
} else {
Eterm* new_htop;
ASSERT(is_big(res));
new_htop = hp + bignum_header_arity(*hp) + 1;
ASSERT(p->heap <= new_htop && new_htop <= p->htop);
p->htop = new_htop;
}
ASSERT(p->heap <= p->htop && p->htop <= p->stop);
}
/*
* The functions that follow are called from the emulator loop.
* They are not allowed to allocate heap fragments, but must do
* a garbage collection if there is insufficient heap space.
*/
#define erts_heap_frag_shrink horrible error
#define maybe_shrink horrible error
Eterm
erts_gc_mixed_plus(Process* p, Eterm* reg, Uint live)
{
Eterm arg1;
Eterm arg2;
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm res;
Eterm hdr;
FloatDef f1, f2;
dsize_t sz1, sz2, sz;
int need_heap;
Eterm* hp;
Sint ires;
arg1 = reg[live];
arg2 = reg[live+1];
ERTS_FP_CHECK_INIT(p);
switch (arg1 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg1 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
ires = signed_val(arg1) + signed_val(arg2);
ASSERT(MY_IS_SSMALL(ires) == IS_SSMALL(ires));
if (MY_IS_SSMALL(ires)) {
return make_small(ires);
} else {
if (ERTS_NEED_GC(p, 2)) {
erts_garbage_collect(p, 2, reg, live);
}
hp = p->htop;
p->htop += 2;
res = small_to_big(ires, hp);
return res;
}
default:
badarith:
p->freason = BADARITH;
return THE_NON_VALUE;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
if (arg1 == SMALL_ZERO) {
return arg2;
}
arg1 = small_to_big(signed_val(arg1), tmp_big1);
goto do_big;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg1);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if (arg2 == SMALL_ZERO) {
return arg1;
}
arg2 = small_to_big(signed_val(arg2), tmp_big2);
goto do_big;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
do_big:
sz1 = big_size(arg1);
sz2 = big_size(arg2);
sz = MAX(sz1, sz2)+1;
need_heap = BIG_NEED_SIZE(sz);
if (ERTS_NEED_GC(p, need_heap)) {
erts_garbage_collect(p, need_heap, reg, live+2);
if (ARG_IS_NOT_TMP(arg1,tmp_big1)) {
arg1 = reg[live];
}
if (ARG_IS_NOT_TMP(arg2,tmp_big2)) {
arg2 = reg[live+1];
}
}
hp = p->htop;
p->htop += need_heap;
res = big_plus(arg1, arg2, hp);
trim_heap(p, hp, res);
if (is_nil(res)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
return res;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
GET_DOUBLE(arg2, f2);
do_float:
f1.fd = f1.fd + f2.fd;
ERTS_FP_ERROR(p, f1.fd, goto badarith);
if (ERTS_NEED_GC(p, FLOAT_SIZE_OBJECT)) {
erts_garbage_collect(p, FLOAT_SIZE_OBJECT, reg, live);
}
hp = p->htop;
p->htop += FLOAT_SIZE_OBJECT;
res = make_float(hp);
PUT_DOUBLE(f1, hp);
return res;
default:
goto badarith;
}
default:
goto badarith;
}
}
default:
goto badarith;
}
}
Eterm
erts_gc_mixed_minus(Process* p, Eterm* reg, Uint live)
{
Eterm arg1;
Eterm arg2;
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm hdr;
Eterm res;
FloatDef f1, f2;
dsize_t sz1, sz2, sz;
int need_heap;
Eterm* hp;
Sint ires;
arg1 = reg[live];
arg2 = reg[live+1];
ERTS_FP_CHECK_INIT(p);
switch (arg1 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg1 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
ires = signed_val(arg1) - signed_val(arg2);
ASSERT(MY_IS_SSMALL(ires) == IS_SSMALL(ires));
if (MY_IS_SSMALL(ires)) {
return make_small(ires);
} else {
if (ERTS_NEED_GC(p, 2)) {
erts_garbage_collect(p, 2, reg, live);
}
hp = p->htop;
p->htop += 2;
res = small_to_big(ires, hp);
return res;
}
default:
badarith:
p->freason = BADARITH;
return THE_NON_VALUE;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
arg1 = small_to_big(signed_val(arg1), tmp_big1);
goto do_big;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg1);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if (arg2 == SMALL_ZERO) {
return arg1;
}
arg2 = small_to_big(signed_val(arg2), tmp_big2);
do_big:
sz1 = big_size(arg1);
sz2 = big_size(arg2);
sz = MAX(sz1, sz2)+1;
need_heap = BIG_NEED_SIZE(sz);
if (ERTS_NEED_GC(p, need_heap)) {
erts_garbage_collect(p, need_heap, reg, live+2);
if (ARG_IS_NOT_TMP(arg1,tmp_big1)) {
arg1 = reg[live];
}
if (ARG_IS_NOT_TMP(arg2,tmp_big2)) {
arg2 = reg[live+1];
}
}
hp = p->htop;
p->htop += need_heap;
res = big_minus(arg1, arg2, hp);
trim_heap(p, hp, res);
if (is_nil(res)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
return res;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
goto do_big;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
GET_DOUBLE(arg2, f2);
do_float:
f1.fd = f1.fd - f2.fd;
ERTS_FP_ERROR(p, f1.fd, goto badarith);
if (ERTS_NEED_GC(p, FLOAT_SIZE_OBJECT)) {
erts_garbage_collect(p, FLOAT_SIZE_OBJECT, reg, live);
}
hp = p->htop;
p->htop += FLOAT_SIZE_OBJECT;
res = make_float(hp);
PUT_DOUBLE(f1, hp);
return res;
default:
goto badarith;
}
default:
goto badarith;
}
}
default:
goto badarith;
}
}
Eterm
erts_gc_mixed_times(Process* p, Eterm* reg, Uint live)
{
Eterm arg1;
Eterm arg2;
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
Eterm hdr;
Eterm res;
FloatDef f1, f2;
dsize_t sz1, sz2, sz;
int need_heap;
Eterm* hp;
arg1 = reg[live];
arg2 = reg[live+1];
ERTS_FP_CHECK_INIT(p);
switch (arg1 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg1 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if ((arg1 == SMALL_ZERO) || (arg2 == SMALL_ZERO)) {
return(SMALL_ZERO);
} else if (arg1 == SMALL_ONE) {
return(arg2);
} else if (arg2 == SMALL_ONE) {
return(arg1);
} else {
DeclareTmpHeap(big_res,3,p);
UseTmpHeap(3,p);
/*
* The following code is optimized for the case that
* result is small (which should be the most common case
* in practice).
*/
res = small_times(signed_val(arg1), signed_val(arg2),
big_res);
if (is_small(res)) {
UnUseTmpHeap(3,p);
return res;
} else {
/*
* The result is a a big number.
* Allocate a heap fragment and copy the result.
* Be careful to allocate exactly what we need
* to not leave any holes.
*/
Uint arity;
Uint need;
ASSERT(is_big(res));
hdr = big_res[0];
arity = bignum_header_arity(hdr);
ASSERT(arity == 1 || arity == 2);
need = arity + 1;
if (ERTS_NEED_GC(p, need)) {
erts_garbage_collect(p, need, reg, live);
}
hp = p->htop;
p->htop += need;
res = make_big(hp);
*hp++ = hdr;
*hp++ = big_res[1];
if (arity > 1) {
*hp = big_res[2];
}
UnUseTmpHeap(3,p);
return res;
}
}
default:
badarith:
p->freason = BADARITH;
return THE_NON_VALUE;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
if (arg1 == SMALL_ZERO)
return(SMALL_ZERO);
if (arg1 == SMALL_ONE)
return(arg2);
arg1 = small_to_big(signed_val(arg1), tmp_big1);
sz = 2 + big_size(arg2);
goto do_big;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg1);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if (arg2 == SMALL_ZERO)
return(SMALL_ZERO);
if (arg2 == SMALL_ONE)
return(arg1);
arg2 = small_to_big(signed_val(arg2), tmp_big2);
sz = 2 + big_size(arg1);
goto do_big;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
sz1 = big_size(arg1);
sz2 = big_size(arg2);
sz = sz1 + sz2;
do_big:
need_heap = BIG_NEED_SIZE(sz);
if (ERTS_NEED_GC(p, need_heap)) {
erts_garbage_collect(p, need_heap, reg, live+2);
if (ARG_IS_NOT_TMP(arg1,tmp_big1)) {
arg1 = reg[live];
}
if (ARG_IS_NOT_TMP(arg2,tmp_big2)) {
arg2 = reg[live+1];
}
}
hp = p->htop;
p->htop += need_heap;
res = big_times(arg1, arg2, hp);
trim_heap(p, hp, res);
/*
* Note that the result must be big in this case, since
* at least one operand was big to begin with, and
* the absolute value of the other is > 1.
*/
if (is_nil(res)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
return res;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
GET_DOUBLE(arg2, f2);
do_float:
f1.fd = f1.fd * f2.fd;
ERTS_FP_ERROR(p, f1.fd, goto badarith);
if (ERTS_NEED_GC(p, FLOAT_SIZE_OBJECT)) {
erts_garbage_collect(p, FLOAT_SIZE_OBJECT, reg, live);
}
hp = p->htop;
p->htop += FLOAT_SIZE_OBJECT;
res = make_float(hp);
PUT_DOUBLE(f1, hp);
return res;
default:
goto badarith;
}
default:
goto badarith;
}
}
default:
goto badarith;
}
}
Eterm
erts_gc_mixed_div(Process* p, Eterm* reg, Uint live)
{
Eterm arg1;
Eterm arg2;
FloatDef f1, f2;
Eterm* hp;
Eterm hdr;
arg1 = reg[live];
arg2 = reg[live+1];
ERTS_FP_CHECK_INIT(p);
switch (arg1 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg1 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
f2.fd = signed_val(arg2);
goto do_float;
default:
badarith:
p->freason = BADARITH;
return THE_NON_VALUE;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
f1.fd = signed_val(arg1);
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg1);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0 ||
big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
if (big_to_double(arg1, &f1.fd) < 0) {
goto badarith;
}
GET_DOUBLE(arg2, f2);
goto do_float;
default:
goto badarith;
}
}
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
switch (arg2 & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_IMMED1:
switch ((arg2 & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
f2.fd = signed_val(arg2);
goto do_float;
default:
goto badarith;
}
case TAG_PRIMARY_BOXED:
hdr = *boxed_val(arg2);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE):
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
if (big_to_double(arg2, &f2.fd) < 0) {
goto badarith;
}
goto do_float;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE):
GET_DOUBLE(arg1, f1);
GET_DOUBLE(arg2, f2);
do_float:
f1.fd = f1.fd / f2.fd;
ERTS_FP_ERROR(p, f1.fd, goto badarith);
if (ERTS_NEED_GC(p, FLOAT_SIZE_OBJECT)) {
erts_garbage_collect(p, FLOAT_SIZE_OBJECT, reg, live);
}
hp = p->htop;
p->htop += FLOAT_SIZE_OBJECT;
PUT_DOUBLE(f1, hp);
return make_float(hp);
default:
goto badarith;
}
default:
goto badarith;
}
}
default:
goto badarith;
}
}
Eterm
erts_gc_int_div(Process* p, Eterm* reg, Uint live)
{
Eterm arg1;
Eterm arg2;
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
int ires;
arg1 = reg[live];
arg2 = reg[live+1];
switch (NUMBER_CODE(arg1, arg2)) {
case SMALL_SMALL:
/* This case occurs if the most negative fixnum is divided by -1. */
ASSERT(arg2 == make_small(-1));
arg1 = small_to_big(signed_val(arg1), tmp_big1);
/*FALLTHROUGH*/
case BIG_SMALL:
arg2 = small_to_big(signed_val(arg2), tmp_big2);
goto L_big_div;
case SMALL_BIG:
if (arg1 != make_small(MIN_SMALL)) {
return SMALL_ZERO;
}
arg1 = small_to_big(signed_val(arg1), tmp_big1);
/*FALLTHROUGH*/
case BIG_BIG:
L_big_div:
ires = big_ucomp(arg1, arg2);
if (ires < 0) {
arg1 = SMALL_ZERO;
} else if (ires == 0) {
arg1 = (big_sign(arg1) == big_sign(arg2)) ?
SMALL_ONE : SMALL_MINUS_ONE;
} else {
Eterm* hp;
int i = big_size(arg1);
Uint need;
ires = big_size(arg2);
need = BIG_NEED_SIZE(i-ires+1) + BIG_NEED_SIZE(i);
if (ERTS_NEED_GC(p, need)) {
erts_garbage_collect(p, need, reg, live+2);
if (ARG_IS_NOT_TMP(arg1,tmp_big1)) {
arg1 = reg[live];
}
if (ARG_IS_NOT_TMP(arg2,tmp_big2)) {
arg2 = reg[live+1];
}
}
hp = p->htop;
p->htop += need;
arg1 = big_div(arg1, arg2, hp);
trim_heap(p, hp, arg1);
if (is_nil(arg1)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
}
return arg1;
default:
p->freason = BADARITH;
return THE_NON_VALUE;
}
}
Eterm
erts_gc_int_rem(Process* p, Eterm* reg, Uint live)
{
Eterm arg1;
Eterm arg2;
DECLARE_TMP(tmp_big1,0,p);
DECLARE_TMP(tmp_big2,1,p);
int ires;
arg1 = reg[live];
arg2 = reg[live+1];
switch (NUMBER_CODE(arg1, arg2)) {
case BIG_SMALL:
arg2 = small_to_big(signed_val(arg2), tmp_big2);
goto L_big_rem;
case SMALL_BIG:
if (arg1 != make_small(MIN_SMALL)) {
return arg1;
} else {
Eterm tmp;
tmp = small_to_big(signed_val(arg1), tmp_big1);
if ((ires = big_ucomp(tmp, arg2)) == 0) {
return SMALL_ZERO;
} else {
ASSERT(ires < 0);
return arg1;
}
}
/* All paths returned */
case BIG_BIG:
L_big_rem:
ires = big_ucomp(arg1, arg2);
if (ires == 0) {
arg1 = SMALL_ZERO;
} else if (ires > 0) {
Eterm* hp;
Uint need = BIG_NEED_SIZE(big_size(arg1));
if (ERTS_NEED_GC(p, need)) {
erts_garbage_collect(p, need, reg, live+2);
if (ARG_IS_NOT_TMP(arg1,tmp_big1)) {
arg1 = reg[live];
}
if (ARG_IS_NOT_TMP(arg2,tmp_big2)) {
arg2 = reg[live+1];
}
}
hp = p->htop;
p->htop += need;
arg1 = big_rem(arg1, arg2, hp);
trim_heap(p, hp, arg1);
if (is_nil(arg1)) {
p->freason = SYSTEM_LIMIT;
return THE_NON_VALUE;
}
}
return arg1;
default:
p->freason = BADARITH;
return THE_NON_VALUE;
}
}
#define DEFINE_GC_LOGIC_FUNC(func) \
Eterm erts_gc_##func(Process* p, Eterm* reg, Uint live) \
{ \
Eterm arg1; \
Eterm arg2; \
DECLARE_TMP(tmp_big1,0,p); \
DECLARE_TMP(tmp_big2,1,p); \
Eterm* hp; \
int need; \
\
arg1 = reg[live]; \
arg2 = reg[live+1]; \
switch (NUMBER_CODE(arg1, arg2)) { \
case SMALL_BIG: \
arg1 = small_to_big(signed_val(arg1), tmp_big1); \
need = BIG_NEED_SIZE(big_size(arg2) + 1); \
if (ERTS_NEED_GC(p, need)) { \
erts_garbage_collect(p, need, reg, live+2); \
arg2 = reg[live+1]; \
} \
break; \
case BIG_SMALL: \
arg2 = small_to_big(signed_val(arg2), tmp_big2); \
need = BIG_NEED_SIZE(big_size(arg1) + 1); \
if (ERTS_NEED_GC(p, need)) { \
erts_garbage_collect(p, need, reg, live+2); \
arg1 = reg[live]; \
} \
break; \
case BIG_BIG: \
need = BIG_NEED_SIZE(MAX(big_size(arg1), big_size(arg2)) + 1); \
if (ERTS_NEED_GC(p, need)) { \
erts_garbage_collect(p, need, reg, live+2); \
arg1 = reg[live]; \
arg2 = reg[live+1]; \
} \
break; \
default: \
p->freason = BADARITH; \
return THE_NON_VALUE; \
} \
hp = p->htop; \
p->htop += need; \
arg1 = big_##func(arg1, arg2, hp); \
trim_heap(p, hp, arg1); \
return arg1; \
}
DEFINE_GC_LOGIC_FUNC(band)
DEFINE_GC_LOGIC_FUNC(bor)
DEFINE_GC_LOGIC_FUNC(bxor)
Eterm erts_gc_bnot(Process* p, Eterm* reg, Uint live)
{
Eterm result;
Eterm arg;
Uint need;
Eterm* bigp;
arg = reg[live];
if (is_not_big(arg)) {
p->freason = BADARITH;
return NIL;
} else {
need = BIG_NEED_SIZE(big_size(arg)+1);
if (ERTS_NEED_GC(p, need)) {
erts_garbage_collect(p, need, reg, live+1);
arg = reg[live];
}
bigp = p->htop;
p->htop += need;
result = big_bnot(arg, bigp);
trim_heap(p, bigp, result);
if (is_nil(result)) {
p->freason = SYSTEM_LIMIT;
return NIL;
}
}
return result;
}
| apache-2.0 |
parkera/swift | stdlib/public/Concurrency/GlobalExecutor.cpp | 3 | 15745 | ///===--- GlobalExecutor.cpp - Global concurrent executor ------------------===///
///
/// This source file is part of the Swift.org open source project
///
/// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
/// Licensed under Apache License v2.0 with Runtime Library Exception
///
/// See https:///swift.org/LICENSE.txt for license information
/// See https:///swift.org/CONTRIBUTORS.txt for the list of Swift project authors
///
///===----------------------------------------------------------------------===///
///
/// Routines related to the global concurrent execution service.
///
/// The execution side of Swift's concurrency model centers around
/// scheduling work onto various execution services ("executors").
/// Executors vary in several different dimensions:
///
/// First, executors may be exclusive or concurrent. An exclusive
/// executor can only execute one job at once; a concurrent executor
/// can execute many. Exclusive executors are usually used to achieve
/// some higher-level requirement, like exclusive access to some
/// resource or memory. Concurrent executors are usually used to
/// manage a pool of threads and prevent the number of allocated
/// threads from growing without limit.
///
/// Second, executors may own dedicated threads, or they may schedule
/// work onto some some underlying executor. Dedicated threads can
/// improve the responsiveness of a subsystem *locally*, but they impose
/// substantial costs which can drive down performance *globally*
/// if not used carefully. When an executor relies on running work
/// on its own dedicated threads, jobs that need to run briefly on
/// that executor may need to suspend and restart. Dedicating threads
/// to an executor is a decision that should be made carefully
/// and holistically.
///
/// If most executors should not have dedicated threads, they must
/// be backed by some underlying executor, typically a concurrent
/// executor. The purpose of most concurrent executors is to
/// manage threads and prevent excessive growth in the number
/// of threads. Having multiple independent concurrent executors
/// with their own dedicated threads would undermine that.
/// Therefore, it is sensible to have a single, global executor
/// that will ultimately schedule most of the work in the system.
/// With that as a baseline, special needs can be recognized and
/// carved out from the global executor with its cooperation.
///
/// This file defines Swift's interface to that global executor.
///
/// The default implementation is backed by libdispatch, but there
/// may be good reasons to provide alternatives (e.g. when building
/// a single-threaded runtime).
///
///===----------------------------------------------------------------------===///
#include "../CompatibilityOverride/CompatibilityOverride.h"
#include "swift/Runtime/Concurrency.h"
#include "swift/Runtime/EnvironmentVariables.h"
#include "TaskPrivate.h"
#include "Error.h"
#include <dispatch/dispatch.h>
#if !defined(_WIN32)
#include <dlfcn.h>
#endif
using namespace swift;
SWIFT_CC(swift)
void (*swift::swift_task_enqueueGlobal_hook)(
Job *job, swift_task_enqueueGlobal_original original) = nullptr;
SWIFT_CC(swift)
void (*swift::swift_task_enqueueGlobalWithDelay_hook)(
unsigned long long delay, Job *job,
swift_task_enqueueGlobalWithDelay_original original) = nullptr;
SWIFT_CC(swift)
void (*swift::swift_task_enqueueMainExecutor_hook)(
Job *job, swift_task_enqueueMainExecutor_original original) = nullptr;
#if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR
#include <chrono>
#include <thread>
static Job *JobQueue = nullptr;
class DelayedJob {
public:
Job *job;
unsigned long long when;
DelayedJob *next;
DelayedJob(Job *job, unsigned long long when) : job(job), when(when), next(nullptr) {}
};
static DelayedJob *DelayedJobQueue = nullptr;
/// Get the next-in-queue storage slot.
static Job *&nextInQueue(Job *cur) {
return reinterpret_cast<Job*&>(&cur->SchedulerPrivate[NextWaitingTaskIndex]);
}
/// Insert a job into the cooperative global queue.
static void insertIntoJobQueue(Job *newJob) {
Job **position = &JobQueue;
while (auto cur = *position) {
// If we find a job with lower priority, insert here.
if (cur->getPriority() < newJob->getPriority()) {
nextInQueue(newJob) = cur;
*position = newJob;
return;
}
// Otherwise, keep advancing through the queue.
position = &nextInQueue(cur);
}
nextInQueue(newJob) = nullptr;
*position = newJob;
}
static unsigned long long currentNanos() {
auto now = std::chrono::steady_clock::now();
auto nowNanos = std::chrono::time_point_cast<std::chrono::nanoseconds>(now);
auto value = std::chrono::duration_cast<std::chrono::nanoseconds>(nowNanos.time_since_epoch());
return value.count();
}
/// Insert a job into the cooperative global queue.
static void insertIntoDelayedJobQueue(unsigned long long delay, Job *job) {
DelayedJob **position = &DelayedJobQueue;
DelayedJob *newJob = new DelayedJob(job, currentNanos() + delay);
while (auto cur = *position) {
// If we find a job with lower priority, insert here.
if (cur->when > newJob->when) {
newJob->next = cur;
*position = newJob;
return;
}
// Otherwise, keep advancing through the queue.
position = &cur->next;
}
*position = newJob;
}
/// Claim the next job from the cooperative global queue.
static Job *claimNextFromJobQueue() {
// Check delayed jobs first
while (true) {
if (auto delayedJob = DelayedJobQueue) {
if (delayedJob->when < currentNanos()) {
DelayedJobQueue = delayedJob->next;
auto job = delayedJob->job;
delete delayedJob;
return job;
}
}
if (auto job = JobQueue) {
JobQueue = nextInQueue(job);
return job;
}
// there are only delayed jobs left, but they are not ready,
// so we sleep until the first one is
if (auto delayedJob = DelayedJobQueue) {
std::this_thread::sleep_for(std::chrono::nanoseconds(delayedJob->when - currentNanos()));
continue;
}
return nullptr;
}
}
void swift::donateThreadToGlobalExecutorUntil(bool (*condition)(void *),
void *conditionContext) {
while (!condition(conditionContext)) {
auto job = claimNextFromJobQueue();
if (!job) return;
job->run(ExecutorRef::generic());
}
}
#else
// Ensure that Job's layout is compatible with what Dispatch expects.
// Note: MinimalDispatchObjectHeader just has the fields we care about, it is
// not complete and should not be used for anything other than these asserts.
struct MinimalDispatchObjectHeader {
const void *VTable;
int Opaque0;
int Opaque1;
void *Linkage;
};
static_assert(
offsetof(Job, metadata) == offsetof(MinimalDispatchObjectHeader, VTable),
"Job Metadata field must match location of Dispatch VTable field.");
static_assert(offsetof(Job, SchedulerPrivate[Job::DispatchLinkageIndex]) ==
offsetof(MinimalDispatchObjectHeader, Linkage),
"Dispatch Linkage field must match Job "
"SchedulerPrivate[DispatchLinkageIndex].");
/// The function passed to dispatch_async_f to execute a job.
static void __swift_run_job(void *_job) {
Job *job = (Job*) _job;
auto metadata =
reinterpret_cast<const DispatchClassMetadata *>(job->metadata);
metadata->VTableInvoke(job, nullptr, 0);
}
/// The type of a function pointer for enqueueing a Job object onto a dispatch
/// queue.
typedef void (*dispatchEnqueueFuncType)(dispatch_queue_t queue, void *obj,
dispatch_qos_class_t qos);
/// Initialize dispatchEnqueueFunc and then call through to the proper
/// implementation.
static void initializeDispatchEnqueueFunc(dispatch_queue_t queue, void *obj,
dispatch_qos_class_t qos);
/// A function pointer to the function used to enqueue a Job onto a dispatch
/// queue. Initially set to initializeDispatchEnqueueFunc, so that the first
/// call will initialize it. initializeDispatchEnqueueFunc sets it to point
/// either to dispatch_async_swift_job when it's available, otherwise to
/// dispatchEnqueueDispatchAsync.
static std::atomic<dispatchEnqueueFuncType> dispatchEnqueueFunc{
initializeDispatchEnqueueFunc};
/// A small adapter that dispatches a Job onto a queue using dispatch_async_f.
static void dispatchEnqueueDispatchAsync(dispatch_queue_t queue, void *obj,
dispatch_qos_class_t qos) {
dispatch_async_f(queue, obj, __swift_run_job);
}
static void initializeDispatchEnqueueFunc(dispatch_queue_t queue, void *obj,
dispatch_qos_class_t qos) {
dispatchEnqueueFuncType func = nullptr;
// Always fall back to plain dispatch_async_f on Windows for now.
#if !defined(_WIN32)
if (runtime::environment::concurrencyEnableJobDispatchIntegration())
func = reinterpret_cast<dispatchEnqueueFuncType>(
dlsym(RTLD_NEXT, "dispatch_async_swift_job"));
#endif
if (!func)
func = dispatchEnqueueDispatchAsync;
dispatchEnqueueFunc.store(func, std::memory_order_relaxed);
func(queue, obj, qos);
}
/// Enqueue a Job onto a dispatch queue using dispatchEnqueueFunc.
static void dispatchEnqueue(dispatch_queue_t queue, Job *job,
dispatch_qos_class_t qos, void *executorQueue) {
job->SchedulerPrivate[Job::DispatchQueueIndex] = executorQueue;
dispatchEnqueueFunc.load(std::memory_order_relaxed)(queue, job, qos);
}
static constexpr size_t globalQueueCacheCount =
static_cast<size_t>(JobPriority::UserInteractive) + 1;
static std::atomic<dispatch_queue_t> globalQueueCache[globalQueueCacheCount];
static dispatch_queue_t getGlobalQueue(JobPriority priority) {
size_t numericPriority = static_cast<size_t>(priority);
if (numericPriority >= globalQueueCacheCount)
swift_Concurrency_fatalError(0, "invalid job priority %#zx");
auto *ptr = &globalQueueCache[numericPriority];
auto queue = ptr->load(std::memory_order_relaxed);
if (SWIFT_LIKELY(queue))
return queue;
// If we don't have a queue cached for this priority, cache it now. This may
// race with other threads doing this at the same time for this priority, but
// that's OK, they'll all end up writing the same value.
queue = dispatch_get_global_queue((dispatch_qos_class_t)priority,
/*flags*/ 0);
// Unconditionally store it back in the cache. If we raced with another
// thread, we'll just overwrite the entry with the same value.
ptr->store(queue, std::memory_order_relaxed);
return queue;
}
#endif
SWIFT_CC(swift)
static void swift_task_enqueueGlobalImpl(Job *job) {
assert(job && "no job provided");
#if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR
insertIntoJobQueue(job);
#else
// We really want four things from the global execution service:
// - Enqueuing work should have minimal runtime and memory overhead.
// - Adding work should never result in an "explosion" where many
// more threads are created than the available cores.
// - Jobs should run on threads with an appropriate priority.
// - Thread priorities should temporarily elevatable to avoid
// priority inversions.
//
// Of these, the first two are the most important. Many programs
// do not rely on high-usage priority scheduling, and many priority
// inversions can be avoided at a higher level (albeit with some
// performance cost, e.g. by creating higher-priority tasks to run
// critical sections that contend with high-priority work). In
// contrast, if the async feature adds too much overhead, or if
// heavy use of it leads to thread explosions and memory exhaustion,
// programmers will have no choice but to stop using it. So if
// goals are in conflict, it's best to focus on core properties over
// priority-inversion avoidance.
// We currently use Dispatch for our thread pool on all platforms.
// Dispatch currently backs its serial queues with a global
// concurrent queue that is prone to thread explosions when a flood
// of jobs are added to it. That problem does not apply equally
// to the global concurrent queues returned by dispatch_get_global_queue,
// which are not strictly CPU-limited but are at least much more
// cautious about adding new threads. We cannot safely elevate
// the priorities of work added to this queue using Dispatch's public
// API, but as discussed above, that is less important than avoiding
// performance problems.
JobPriority priority = job->getPriority();
auto queue = getGlobalQueue(priority);
dispatchEnqueue(queue, job, (dispatch_qos_class_t)priority,
DISPATCH_QUEUE_GLOBAL_EXECUTOR);
#endif
}
void swift::swift_task_enqueueGlobal(Job *job) {
_swift_tsan_release(job);
if (swift_task_enqueueGlobal_hook)
swift_task_enqueueGlobal_hook(job, swift_task_enqueueGlobalImpl);
else
swift_task_enqueueGlobalImpl(job);
}
SWIFT_CC(swift)
static void swift_task_enqueueGlobalWithDelayImpl(unsigned long long delay,
Job *job) {
assert(job && "no job provided");
#if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR
insertIntoDelayedJobQueue(delay, job);
#else
dispatch_function_t dispatchFunction = &__swift_run_job;
void *dispatchContext = job;
JobPriority priority = job->getPriority();
auto queue = getGlobalQueue(priority);
job->SchedulerPrivate[Job::DispatchQueueIndex] =
DISPATCH_QUEUE_GLOBAL_EXECUTOR;
dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, delay);
dispatch_after_f(when, queue, dispatchContext, dispatchFunction);
#endif
}
void swift::swift_task_enqueueGlobalWithDelay(unsigned long long delay,
Job *job) {
if (swift_task_enqueueGlobalWithDelay_hook)
swift_task_enqueueGlobalWithDelay_hook(
delay, job, swift_task_enqueueGlobalWithDelayImpl);
else
swift_task_enqueueGlobalWithDelayImpl(delay, job);
}
/// Enqueues a task on the main executor.
/// FIXME: only exists for the quick-and-dirty MainActor implementation.
SWIFT_CC(swift)
static void swift_task_enqueueMainExecutorImpl(Job *job) {
assert(job && "no job provided");
#if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR
insertIntoJobQueue(job);
#else
JobPriority priority = job->getPriority();
// This is an inline function that compiles down to a pointer to a global.
auto mainQueue = dispatch_get_main_queue();
dispatchEnqueue(mainQueue, job, (dispatch_qos_class_t)priority, mainQueue);
#endif
}
void swift::swift_task_enqueueMainExecutor(Job *job) {
if (swift_task_enqueueMainExecutor_hook)
swift_task_enqueueMainExecutor_hook(job,
swift_task_enqueueMainExecutorImpl);
else
swift_task_enqueueMainExecutorImpl(job);
}
void swift::swift_task_enqueueOnDispatchQueue(Job *job,
HeapObject *_queue) {
JobPriority priority = job->getPriority();
auto queue = reinterpret_cast<dispatch_queue_t>(_queue);
dispatchEnqueue(queue, job, (dispatch_qos_class_t)priority, queue);
}
ExecutorRef swift::swift_task_getMainExecutor() {
return ExecutorRef::forOrdinary(
reinterpret_cast<HeapObject*>(&_dispatch_main_q),
_swift_task_getDispatchQueueSerialExecutorWitnessTable());
}
bool ExecutorRef::isMainExecutor() const {
return Identity == reinterpret_cast<HeapObject*>(&_dispatch_main_q);
}
#define OVERRIDE_GLOBAL_EXECUTOR COMPATIBILITY_OVERRIDE
#include COMPATIBILITY_OVERRIDE_INCLUDE_PATH
| apache-2.0 |
jt70471/aws-sdk-cpp | aws-cpp-sdk-iam/source/model/GenerateOrganizationsAccessReportResult.cpp | 4 | 1791 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iam/model/GenerateOrganizationsAccessReportResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::IAM::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
GenerateOrganizationsAccessReportResult::GenerateOrganizationsAccessReportResult()
{
}
GenerateOrganizationsAccessReportResult::GenerateOrganizationsAccessReportResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
GenerateOrganizationsAccessReportResult& GenerateOrganizationsAccessReportResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "GenerateOrganizationsAccessReportResult"))
{
resultNode = rootNode.FirstChild("GenerateOrganizationsAccessReportResult");
}
if(!resultNode.IsNull())
{
XmlNode jobIdNode = resultNode.FirstChild("JobId");
if(!jobIdNode.IsNull())
{
m_jobId = Aws::Utils::Xml::DecodeEscapedXmlText(jobIdNode.GetText());
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::IAM::Model::GenerateOrganizationsAccessReportResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| apache-2.0 |
bboozzoo/zephyr | samples/testing/unit/main.c | 4 | 1160 | /*
* Copyright (c) 2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ztest.h>
unsigned int irq_lock(void)
{
return 0;
}
void irq_unlock(unsigned int key)
{
}
#include <net/buf.c>
void k_queue_init(struct k_queue *fifo) {}
void k_queue_append_list(struct k_queue *fifo, void *head, void *tail) {}
int k_is_in_isr(void)
{
return 0;
}
void *k_queue_get(struct k_queue *fifo, s32_t timeout)
{
return NULL;
}
void k_queue_append(struct k_queue *fifo, void *data)
{
}
void k_queue_prepend(struct k_queue *fifo, void *data)
{
}
#define TEST_BUF_COUNT 1
#define TEST_BUF_SIZE 74
NET_BUF_POOL_DEFINE(bufs_pool, TEST_BUF_COUNT, TEST_BUF_SIZE,
sizeof(int), NULL);
static void test_get_single_buffer(void)
{
struct net_buf *buf;
buf = net_buf_alloc(&bufs_pool, K_NO_WAIT);
zassert_equal(buf->ref, 1, "Invalid refcount");
zassert_equal(buf->len, 0, "Invalid length");
zassert_equal(buf->flags, 0, "Invalid flags");
zassert_equal_ptr(buf->frags, NULL, "Frags not NULL");
}
void test_main(void)
{
ztest_test_suite(net_buf_test,
ztest_unit_test(test_get_single_buffer)
);
ztest_run_test_suite(net_buf_test);
}
| apache-2.0 |
cedral/aws-sdk-cpp | aws-cpp-sdk-rds/source/model/ModifyCertificatesResult.cpp | 4 | 1622 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/rds/model/ModifyCertificatesResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::RDS::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
ModifyCertificatesResult::ModifyCertificatesResult()
{
}
ModifyCertificatesResult::ModifyCertificatesResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
ModifyCertificatesResult& ModifyCertificatesResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "ModifyCertificatesResult"))
{
resultNode = rootNode.FirstChild("ModifyCertificatesResult");
}
if(!resultNode.IsNull())
{
XmlNode certificateNode = resultNode.FirstChild("Certificate");
if(!certificateNode.IsNull())
{
m_certificate = certificateNode;
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::RDS::Model::ModifyCertificatesResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| apache-2.0 |
veritas-shine/minix3-rpi | lib/libc/arch/vax/gen/_lwp.c | 4 | 3091 | /* $NetBSD: _lwp.c,v 1.3 2012/03/22 17:32:22 christos Exp $ */
/*-
* Copyright (c) 2009 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christos Zoulas
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: _lwp.c,v 1.3 2012/03/22 17:32:22 christos Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <sys/types.h>
#include <inttypes.h>
#include <ucontext.h>
#include <lwp.h>
#include <stdlib.h>
void
_lwp_makecontext(ucontext_t *u, void (*start)(void *),
void *arg, void *private, caddr_t stack_base, size_t stack_size)
{
__greg_t *gr = u->uc_mcontext.__gregs;
int *sp;
getcontext(u);
u->uc_link = NULL;
u->uc_stack.ss_sp = stack_base;
u->uc_stack.ss_size = stack_size;
/* Align to a word */
/* LINTED uintptr_t is safe */
sp = (int *)((uintptr_t)(stack_base + stack_size) & ~0x3);
/*
* Allocate necessary stack space for arguments including arg count
* and call frame
*/
sp -= 1 + 1 + 5;
sp[0] = 0; /* condition handler is null */
sp[1] = 0x20000000; /* make this a CALLS frame */
sp[2] = 0; /* saved argument pointer */
sp[3] = 0; /* saved frame pointer */
sp[4] = (int)(uintptr_t)_lwp_exit + 2;/* return via _lwp_exit */
sp[5] = 1; /* argc */
sp[6] = (int)(uintptr_t)arg; /* argv */
gr[_REG_AP] = (__greg_t)(uintptr_t)(sp + 5);
gr[_REG_SP] = (__greg_t)(uintptr_t)sp;
gr[_REG_FP] = (__greg_t)(uintptr_t)sp;
gr[_REG_PC] = (__greg_t)(uintptr_t)start + 2;
/*
* Push the TLS pointer onto the new stack also.
* The _UC_TLSBASE flag tells the kernel to pop it and use it.
*/
*--sp = (int)(intptr_t)private;
gr[_REG_SP] = (__greg_t)(uintptr_t)sp;
u->uc_flags |= _UC_TLSBASE;
}
| apache-2.0 |
jsteemann/arangodb | arangod/RestServer/ConsoleThread.cpp | 4 | 8580 | ////////////////////////////////////////////////////////////////////////////////
/// @brief console thread
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "ConsoleThread.h"
#include <iostream>
#include "ApplicationServer/ApplicationServer.h"
#include "Basics/logging.h"
#include "Basics/tri-strings.h"
#include "Basics/MutexLocker.h"
#include "Rest/Version.h"
#include "VocBase/vocbase.h"
#include "V8/V8LineEditor.h"
#include "V8/v8-conv.h"
#include "V8/v8-utils.h"
#include <v8.h>
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace arangodb;
using namespace std;
// -----------------------------------------------------------------------------
// --SECTION-- class ConsoleThread
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- static public variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief the line editor object for use in debugging
////////////////////////////////////////////////////////////////////////////////
V8LineEditor* ConsoleThread::serverConsole = nullptr;
////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for console access
////////////////////////////////////////////////////////////////////////////////
Mutex ConsoleThread::serverConsoleMutex;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a console thread
////////////////////////////////////////////////////////////////////////////////
ConsoleThread::ConsoleThread (ApplicationServer* applicationServer,
ApplicationV8* applicationV8,
TRI_vocbase_t* vocbase)
: Thread("console"),
_applicationServer(applicationServer),
_applicationV8(applicationV8),
_context(nullptr),
_vocbase(vocbase),
_done(0),
_userAborted(false) {
allowAsynchronousCancelation();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroys a console thread
////////////////////////////////////////////////////////////////////////////////
ConsoleThread::~ConsoleThread () {
}
// -----------------------------------------------------------------------------
// --SECTION-- Thread methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief runs the thread
////////////////////////////////////////////////////////////////////////////////
void ConsoleThread::run () {
usleep(100 * 1000);
// enter V8 context
_context = _applicationV8->enterContext(_vocbase, true);
// work
try {
inner();
}
catch (const char*) {
}
catch (...) {
_applicationV8->exitContext(_context);
_done = true;
_applicationServer->beginShutdown();
throw;
}
// exit context
_applicationV8->exitContext(_context);
_done = true;
_applicationServer->beginShutdown();
}
// -----------------------------------------------------------------------------
// --SECTION-- private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief inner thread loop - this handles all the user inputs
////////////////////////////////////////////////////////////////////////////////
void ConsoleThread::inner () {
v8::Isolate* isolate = _context->isolate;
v8::HandleScope globalScope(isolate);
// run the shell
std::cout << "arangod console (" << rest::Version::getVerboseVersionString() << ")" << std::endl;
std::cout << "Copyright (c) ArangoDB GmbH" << std::endl;
v8::Local<v8::String> name(TRI_V8_ASCII_STRING(TRI_V8_SHELL_COMMAND_NAME));
auto localContext = v8::Local<v8::Context>::New(isolate, _context->_context);
localContext->Enter();
{
v8::Context::Scope contextScope(localContext);
// .............................................................................
// run console
// .............................................................................
const uint64_t gcInterval = 10;
uint64_t nrCommands = 0;
// read and eval .arangod.rc from home directory if it exists
char const* startupScript = R"SCRIPT(
start_pretty_print();
(function () {
var __fs__ = require("fs");
var __rcf__ = __fs__.join(__fs__.home(), ".arangod.rc");
if (__fs__.exists(__rcf__)) {
try {
var __content__ = __fs__.read(__rcf__);
eval(__content__);
}
catch (err) {
require("console").log("error in rc file '%s': %s", __rcf__, String(err.stack || err));
}
}
})();
)SCRIPT";
TRI_ExecuteJavaScriptString(isolate,
localContext,
TRI_V8_ASCII_STRING(startupScript),
TRI_V8_ASCII_STRING("(startup)"),
false);
#ifndef _WIN32
// allow SIGINT in this particular thread... otherwise we cannot CTRL-C the console
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
if (pthread_sigmask(SIG_UNBLOCK, &set, nullptr) < 0) {
LOG_ERROR("unable to install signal handler");
}
#endif
V8LineEditor console(isolate, localContext, ".arangod.history");
console.open(true);
{
MUTEX_LOCKER(serverConsoleMutex);
serverConsole = &console;
}
while (! _userAborted) {
if (nrCommands >= gcInterval) {
TRI_RunGarbageCollectionV8(isolate, 0.5);
nrCommands = 0;
}
string input;
bool eof;
{
MUTEX_LOCKER(serverConsoleMutex);
input = console.prompt("arangod> ", "arangod", eof);
}
if (eof) {
_userAborted = true;
}
if (_userAborted) {
break;
}
if (input.empty()) {
continue;
}
nrCommands++;
console.addHistory(input);
{
v8::TryCatch tryCatch;
v8::HandleScope scope(isolate);
console.isExecutingCommand(true);
TRI_ExecuteJavaScriptString(isolate, localContext, TRI_V8_STRING(input.c_str()), name, true);
console.isExecutingCommand(false);
if (_userAborted) {
std::cout << "command aborted" << std::endl;
}
else if (tryCatch.HasCaught()) {
if (! tryCatch.CanContinue() || tryCatch.HasTerminated()) {
std::cout << "command aborted" << std::endl;
}
else {
std::cout << TRI_StringifyV8Exception(isolate, &tryCatch);
}
}
}
}
{
MUTEX_LOCKER(serverConsoleMutex);
serverConsole = nullptr;
}
}
localContext->Exit();
throw "user aborted";
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
| apache-2.0 |
cloudbase/FreeRDP-dev | libfreerdp/cache/palette.c | 5 | 3415 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Palette (Color Table) Cache
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <winpr/crt.h>
#include <freerdp/log.h>
#include <freerdp/cache/palette.h>
#include "palette.h"
#define TAG FREERDP_TAG("cache.palette")
static void* palette_cache_get(rdpPaletteCache* palette, UINT32 index);
static void palette_cache_put(rdpPaletteCache* palette, UINT32 index, void* entry);
static BOOL update_gdi_cache_color_table(rdpContext* context,
const CACHE_COLOR_TABLE_ORDER* cacheColorTable)
{
UINT32* colorTable;
rdpCache* cache = context->cache;
colorTable = (UINT32*)malloc(sizeof(UINT32) * 256);
if (!colorTable)
return FALSE;
CopyMemory(colorTable, cacheColorTable->colorTable, sizeof(UINT32) * 256);
palette_cache_put(cache->palette, cacheColorTable->cacheIndex, (void*)colorTable);
return TRUE;
}
void* palette_cache_get(rdpPaletteCache* paletteCache, UINT32 index)
{
void* entry;
if (index >= paletteCache->maxEntries)
{
WLog_ERR(TAG, "invalid color table index: 0x%08" PRIX32 "", index);
return NULL;
}
entry = paletteCache->entries[index].entry;
if (!entry)
{
WLog_ERR(TAG, "invalid color table at index: 0x%08" PRIX32 "", index);
return NULL;
}
return entry;
}
void palette_cache_put(rdpPaletteCache* paletteCache, UINT32 index, void* entry)
{
if (index >= paletteCache->maxEntries)
{
WLog_ERR(TAG, "invalid color table index: 0x%08" PRIX32 "", index);
free(entry);
return;
}
free(paletteCache->entries[index].entry);
paletteCache->entries[index].entry = entry;
}
void palette_cache_register_callbacks(rdpUpdate* update)
{
update->secondary->CacheColorTable = update_gdi_cache_color_table;
}
rdpPaletteCache* palette_cache_new(rdpSettings* settings)
{
rdpPaletteCache* paletteCache;
paletteCache = (rdpPaletteCache*)calloc(1, sizeof(rdpPaletteCache));
if (paletteCache)
{
paletteCache->settings = settings;
paletteCache->maxEntries = 6;
paletteCache->entries =
(PALETTE_TABLE_ENTRY*)calloc(paletteCache->maxEntries, sizeof(PALETTE_TABLE_ENTRY));
}
return paletteCache;
}
void palette_cache_free(rdpPaletteCache* paletteCache)
{
if (paletteCache)
{
UINT32 i;
for (i = 0; i < paletteCache->maxEntries; i++)
free(paletteCache->entries[i].entry);
free(paletteCache->entries);
free(paletteCache);
}
}
void free_palette_update(rdpContext* context, PALETTE_UPDATE* pointer)
{
free(pointer);
}
PALETTE_UPDATE* copy_palette_update(rdpContext* context, const PALETTE_UPDATE* pointer)
{
PALETTE_UPDATE* dst = calloc(1, sizeof(PALETTE_UPDATE));
if (!dst || !pointer)
goto fail;
*dst = *pointer;
return dst;
fail:
free_palette_update(context, dst);
return NULL;
}
| apache-2.0 |
llvm-mirror/compiler-rt | lib/hwasan/hwasan_allocator.cpp | 5 | 14016 | //===-- hwasan_allocator.cpp ------------------------ ---------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is a part of HWAddressSanitizer.
//
// HWAddressSanitizer allocator.
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_atomic.h"
#include "sanitizer_common/sanitizer_errno.h"
#include "sanitizer_common/sanitizer_stackdepot.h"
#include "hwasan.h"
#include "hwasan_allocator.h"
#include "hwasan_checks.h"
#include "hwasan_mapping.h"
#include "hwasan_malloc_bisect.h"
#include "hwasan_thread.h"
#include "hwasan_report.h"
namespace __hwasan {
static Allocator allocator;
static AllocatorCache fallback_allocator_cache;
static SpinMutex fallback_mutex;
static atomic_uint8_t hwasan_allocator_tagging_enabled;
static const tag_t kFallbackAllocTag = 0xBB;
static const tag_t kFallbackFreeTag = 0xBC;
enum RightAlignMode {
kRightAlignNever,
kRightAlignSometimes,
kRightAlignAlways
};
// Initialized in HwasanAllocatorInit, an never changed.
static ALIGNED(16) u8 tail_magic[kShadowAlignment - 1];
bool HwasanChunkView::IsAllocated() const {
return metadata_ && metadata_->alloc_context_id && metadata_->requested_size;
}
// Aligns the 'addr' right to the granule boundary.
static uptr AlignRight(uptr addr, uptr requested_size) {
uptr tail_size = requested_size % kShadowAlignment;
if (!tail_size) return addr;
return addr + kShadowAlignment - tail_size;
}
uptr HwasanChunkView::Beg() const {
if (metadata_ && metadata_->right_aligned)
return AlignRight(block_, metadata_->requested_size);
return block_;
}
uptr HwasanChunkView::End() const {
return Beg() + UsedSize();
}
uptr HwasanChunkView::UsedSize() const {
return metadata_->requested_size;
}
u32 HwasanChunkView::GetAllocStackId() const {
return metadata_->alloc_context_id;
}
uptr HwasanChunkView::ActualSize() const {
return allocator.GetActuallyAllocatedSize(reinterpret_cast<void *>(block_));
}
bool HwasanChunkView::FromSmallHeap() const {
return allocator.FromPrimary(reinterpret_cast<void *>(block_));
}
void GetAllocatorStats(AllocatorStatCounters s) {
allocator.GetStats(s);
}
void HwasanAllocatorInit() {
atomic_store_relaxed(&hwasan_allocator_tagging_enabled,
!flags()->disable_allocator_tagging);
SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
allocator.Init(common_flags()->allocator_release_to_os_interval_ms);
for (uptr i = 0; i < sizeof(tail_magic); i++)
tail_magic[i] = GetCurrentThread()->GenerateRandomTag();
}
void AllocatorSwallowThreadLocalCache(AllocatorCache *cache) {
allocator.SwallowCache(cache);
}
static uptr TaggedSize(uptr size) {
if (!size) size = 1;
uptr new_size = RoundUpTo(size, kShadowAlignment);
CHECK_GE(new_size, size);
return new_size;
}
static void *HwasanAllocate(StackTrace *stack, uptr orig_size, uptr alignment,
bool zeroise) {
if (orig_size > kMaxAllowedMallocSize) {
if (AllocatorMayReturnNull()) {
Report("WARNING: HWAddressSanitizer failed to allocate 0x%zx bytes\n",
orig_size);
return nullptr;
}
ReportAllocationSizeTooBig(orig_size, kMaxAllowedMallocSize, stack);
}
alignment = Max(alignment, kShadowAlignment);
uptr size = TaggedSize(orig_size);
Thread *t = GetCurrentThread();
void *allocated;
if (t) {
allocated = allocator.Allocate(t->allocator_cache(), size, alignment);
} else {
SpinMutexLock l(&fallback_mutex);
AllocatorCache *cache = &fallback_allocator_cache;
allocated = allocator.Allocate(cache, size, alignment);
}
if (UNLIKELY(!allocated)) {
SetAllocatorOutOfMemory();
if (AllocatorMayReturnNull())
return nullptr;
ReportOutOfMemory(size, stack);
}
Metadata *meta =
reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
meta->requested_size = static_cast<u32>(orig_size);
meta->alloc_context_id = StackDepotPut(*stack);
meta->right_aligned = false;
if (zeroise) {
internal_memset(allocated, 0, size);
} else if (flags()->max_malloc_fill_size > 0) {
uptr fill_size = Min(size, (uptr)flags()->max_malloc_fill_size);
internal_memset(allocated, flags()->malloc_fill_byte, fill_size);
}
if (size != orig_size) {
internal_memcpy(reinterpret_cast<u8 *>(allocated) + orig_size, tail_magic,
size - orig_size - 1);
}
void *user_ptr = allocated;
// Tagging can only be skipped when both tag_in_malloc and tag_in_free are
// false. When tag_in_malloc = false and tag_in_free = true malloc needs to
// retag to 0.
if ((flags()->tag_in_malloc || flags()->tag_in_free) &&
atomic_load_relaxed(&hwasan_allocator_tagging_enabled)) {
if (flags()->tag_in_malloc && malloc_bisect(stack, orig_size)) {
tag_t tag = t ? t->GenerateRandomTag() : kFallbackAllocTag;
uptr tag_size = orig_size ? orig_size : 1;
uptr full_granule_size = RoundDownTo(tag_size, kShadowAlignment);
user_ptr =
(void *)TagMemoryAligned((uptr)user_ptr, full_granule_size, tag);
if (full_granule_size != tag_size) {
u8 *short_granule =
reinterpret_cast<u8 *>(allocated) + full_granule_size;
TagMemoryAligned((uptr)short_granule, kShadowAlignment,
tag_size % kShadowAlignment);
short_granule[kShadowAlignment - 1] = tag;
}
} else {
user_ptr = (void *)TagMemoryAligned((uptr)user_ptr, size, 0);
}
}
HWASAN_MALLOC_HOOK(user_ptr, size);
return user_ptr;
}
static bool PointerAndMemoryTagsMatch(void *tagged_ptr) {
CHECK(tagged_ptr);
uptr tagged_uptr = reinterpret_cast<uptr>(tagged_ptr);
tag_t mem_tag = *reinterpret_cast<tag_t *>(
MemToShadow(reinterpret_cast<uptr>(UntagPtr(tagged_ptr))));
return PossiblyShortTagMatches(mem_tag, tagged_uptr, 1);
}
static void HwasanDeallocate(StackTrace *stack, void *tagged_ptr) {
CHECK(tagged_ptr);
HWASAN_FREE_HOOK(tagged_ptr);
if (!PointerAndMemoryTagsMatch(tagged_ptr))
ReportInvalidFree(stack, reinterpret_cast<uptr>(tagged_ptr));
void *untagged_ptr = UntagPtr(tagged_ptr);
void *aligned_ptr = reinterpret_cast<void *>(
RoundDownTo(reinterpret_cast<uptr>(untagged_ptr), kShadowAlignment));
Metadata *meta =
reinterpret_cast<Metadata *>(allocator.GetMetaData(aligned_ptr));
uptr orig_size = meta->requested_size;
u32 free_context_id = StackDepotPut(*stack);
u32 alloc_context_id = meta->alloc_context_id;
// Check tail magic.
uptr tagged_size = TaggedSize(orig_size);
if (flags()->free_checks_tail_magic && orig_size &&
tagged_size != orig_size) {
uptr tail_size = tagged_size - orig_size - 1;
CHECK_LT(tail_size, kShadowAlignment);
void *tail_beg = reinterpret_cast<void *>(
reinterpret_cast<uptr>(aligned_ptr) + orig_size);
if (tail_size && internal_memcmp(tail_beg, tail_magic, tail_size))
ReportTailOverwritten(stack, reinterpret_cast<uptr>(tagged_ptr),
orig_size, tail_magic);
}
meta->requested_size = 0;
meta->alloc_context_id = 0;
// This memory will not be reused by anyone else, so we are free to keep it
// poisoned.
Thread *t = GetCurrentThread();
if (flags()->max_free_fill_size > 0) {
uptr fill_size =
Min(TaggedSize(orig_size), (uptr)flags()->max_free_fill_size);
internal_memset(aligned_ptr, flags()->free_fill_byte, fill_size);
}
if (flags()->tag_in_free && malloc_bisect(stack, 0) &&
atomic_load_relaxed(&hwasan_allocator_tagging_enabled))
TagMemoryAligned(reinterpret_cast<uptr>(aligned_ptr), TaggedSize(orig_size),
t ? t->GenerateRandomTag() : kFallbackFreeTag);
if (t) {
allocator.Deallocate(t->allocator_cache(), aligned_ptr);
if (auto *ha = t->heap_allocations())
ha->push({reinterpret_cast<uptr>(tagged_ptr), alloc_context_id,
free_context_id, static_cast<u32>(orig_size)});
} else {
SpinMutexLock l(&fallback_mutex);
AllocatorCache *cache = &fallback_allocator_cache;
allocator.Deallocate(cache, aligned_ptr);
}
}
static void *HwasanReallocate(StackTrace *stack, void *tagged_ptr_old,
uptr new_size, uptr alignment) {
if (!PointerAndMemoryTagsMatch(tagged_ptr_old))
ReportInvalidFree(stack, reinterpret_cast<uptr>(tagged_ptr_old));
void *tagged_ptr_new =
HwasanAllocate(stack, new_size, alignment, false /*zeroise*/);
if (tagged_ptr_old && tagged_ptr_new) {
void *untagged_ptr_old = UntagPtr(tagged_ptr_old);
Metadata *meta =
reinterpret_cast<Metadata *>(allocator.GetMetaData(untagged_ptr_old));
internal_memcpy(UntagPtr(tagged_ptr_new), untagged_ptr_old,
Min(new_size, static_cast<uptr>(meta->requested_size)));
HwasanDeallocate(stack, tagged_ptr_old);
}
return tagged_ptr_new;
}
static void *HwasanCalloc(StackTrace *stack, uptr nmemb, uptr size) {
if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
if (AllocatorMayReturnNull())
return nullptr;
ReportCallocOverflow(nmemb, size, stack);
}
return HwasanAllocate(stack, nmemb * size, sizeof(u64), true);
}
HwasanChunkView FindHeapChunkByAddress(uptr address) {
void *block = allocator.GetBlockBegin(reinterpret_cast<void*>(address));
if (!block)
return HwasanChunkView();
Metadata *metadata =
reinterpret_cast<Metadata*>(allocator.GetMetaData(block));
return HwasanChunkView(reinterpret_cast<uptr>(block), metadata);
}
static uptr AllocationSize(const void *tagged_ptr) {
const void *untagged_ptr = UntagPtr(tagged_ptr);
if (!untagged_ptr) return 0;
const void *beg = allocator.GetBlockBegin(untagged_ptr);
Metadata *b = (Metadata *)allocator.GetMetaData(untagged_ptr);
if (b->right_aligned) {
if (beg != reinterpret_cast<void *>(RoundDownTo(
reinterpret_cast<uptr>(untagged_ptr), kShadowAlignment)))
return 0;
} else {
if (beg != untagged_ptr) return 0;
}
return b->requested_size;
}
void *hwasan_malloc(uptr size, StackTrace *stack) {
return SetErrnoOnNull(HwasanAllocate(stack, size, sizeof(u64), false));
}
void *hwasan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
return SetErrnoOnNull(HwasanCalloc(stack, nmemb, size));
}
void *hwasan_realloc(void *ptr, uptr size, StackTrace *stack) {
if (!ptr)
return SetErrnoOnNull(HwasanAllocate(stack, size, sizeof(u64), false));
if (size == 0) {
HwasanDeallocate(stack, ptr);
return nullptr;
}
return SetErrnoOnNull(HwasanReallocate(stack, ptr, size, sizeof(u64)));
}
void *hwasan_reallocarray(void *ptr, uptr nmemb, uptr size, StackTrace *stack) {
if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
errno = errno_ENOMEM;
if (AllocatorMayReturnNull())
return nullptr;
ReportReallocArrayOverflow(nmemb, size, stack);
}
return hwasan_realloc(ptr, nmemb * size, stack);
}
void *hwasan_valloc(uptr size, StackTrace *stack) {
return SetErrnoOnNull(
HwasanAllocate(stack, size, GetPageSizeCached(), false));
}
void *hwasan_pvalloc(uptr size, StackTrace *stack) {
uptr PageSize = GetPageSizeCached();
if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
errno = errno_ENOMEM;
if (AllocatorMayReturnNull())
return nullptr;
ReportPvallocOverflow(size, stack);
}
// pvalloc(0) should allocate one page.
size = size ? RoundUpTo(size, PageSize) : PageSize;
return SetErrnoOnNull(HwasanAllocate(stack, size, PageSize, false));
}
void *hwasan_aligned_alloc(uptr alignment, uptr size, StackTrace *stack) {
if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
errno = errno_EINVAL;
if (AllocatorMayReturnNull())
return nullptr;
ReportInvalidAlignedAllocAlignment(size, alignment, stack);
}
return SetErrnoOnNull(HwasanAllocate(stack, size, alignment, false));
}
void *hwasan_memalign(uptr alignment, uptr size, StackTrace *stack) {
if (UNLIKELY(!IsPowerOfTwo(alignment))) {
errno = errno_EINVAL;
if (AllocatorMayReturnNull())
return nullptr;
ReportInvalidAllocationAlignment(alignment, stack);
}
return SetErrnoOnNull(HwasanAllocate(stack, size, alignment, false));
}
int hwasan_posix_memalign(void **memptr, uptr alignment, uptr size,
StackTrace *stack) {
if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
if (AllocatorMayReturnNull())
return errno_EINVAL;
ReportInvalidPosixMemalignAlignment(alignment, stack);
}
void *ptr = HwasanAllocate(stack, size, alignment, false);
if (UNLIKELY(!ptr))
// OOM error is already taken care of by HwasanAllocate.
return errno_ENOMEM;
CHECK(IsAligned((uptr)ptr, alignment));
*memptr = ptr;
return 0;
}
void hwasan_free(void *ptr, StackTrace *stack) {
return HwasanDeallocate(stack, ptr);
}
} // namespace __hwasan
using namespace __hwasan;
void __hwasan_enable_allocator_tagging() {
atomic_store_relaxed(&hwasan_allocator_tagging_enabled, 1);
}
void __hwasan_disable_allocator_tagging() {
atomic_store_relaxed(&hwasan_allocator_tagging_enabled, 0);
}
uptr __sanitizer_get_current_allocated_bytes() {
uptr stats[AllocatorStatCount];
allocator.GetStats(stats);
return stats[AllocatorStatAllocated];
}
uptr __sanitizer_get_heap_size() {
uptr stats[AllocatorStatCount];
allocator.GetStats(stats);
return stats[AllocatorStatMapped];
}
uptr __sanitizer_get_free_bytes() { return 1; }
uptr __sanitizer_get_unmapped_bytes() { return 1; }
uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }
| apache-2.0 |
janebeckman/gpdb | src/backend/nodes/tidbitmap.c | 5 | 40256 | /*-------------------------------------------------------------------------
*
* tidbitmap.c
* PostgreSQL tuple-id (TID) bitmap package
*
* This module provides bitmap data structures that are spiritually
* similar to Bitmapsets, but are specially adapted to store sets of
* tuple identifiers (TIDs), or ItemPointers. In particular, the division
* of an ItemPointer into BlockNumber and OffsetNumber is catered for.
* Also, since we wish to be able to store very large tuple sets in
* memory with this data structure, we support "lossy" storage, in which
* we no longer remember individual tuple offsets on a page but only the
* fact that a particular page needs to be visited.
*
* The "lossy" storage uses one bit per disk page, so at the standard 8K
* BLCKSZ, we can represent all pages in 64Gb of disk space in about 1Mb
* of memory. People pushing around tables of that size should have a
* couple of Mb to spare, so we don't worry about providing a second level
* of lossiness. In theory we could fall back to page ranges at some
* point, but for now that seems useless complexity.
*
*
* Copyright (c) 2003-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/nodes/tidbitmap.c,v 1.14 2008/01/01 19:45:50 momjian Exp $
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <limits.h>
#include "access/htup.h"
#include "access/bitmap.h" /* XXX: remove once pull_stream is generic */
#include "executor/instrument.h" /* Instrumentation */
#include "nodes/bitmapset.h"
#include "nodes/tidbitmap.h"
#include "storage/bufpage.h"
#include "utils/hsearch.h"
#define WORDNUM(x) ((x) / TBM_BITS_PER_BITMAPWORD)
#define BITNUM(x) ((x) % TBM_BITS_PER_BITMAPWORD)
static bool tbm_iterate_page(PagetableEntry *page, TBMIterateResult *output);
static bool tbm_iterate_hash(HashBitmap *tbm, TBMIterateResult *output);
static PagetableEntry *tbm_next_page(HashBitmap *tbm, bool *more);
/*
* dynahash.c is optimized for relatively large, long-lived hash tables.
* This is not ideal for TIDBitMap, particularly when we are using a bitmap
* scan on the inside of a nestloop join: a bitmap may well live only long
* enough to accumulate one entry in such cases. We therefore avoid creating
* an actual hashtable until we need two pagetable entries. When just one
* pagetable entry is needed, we store it in a fixed field of TIDBitMap.
* (NOTE: we don't get rid of the hashtable if the bitmap later shrinks down
* to zero or one page again. So, status can be TBM_HASH even when nentries
* is zero or one.)
*/
typedef enum
{
HASHBM_EMPTY, /* no hashtable, nentries == 0 */
HASHBM_ONE_PAGE, /* entry1 contains the single entry */
HASHBM_HASH /* pagetable is valid, entry1 is not */
} TBMStatus;
/*
* Here is the representation for a whole HashBitmap.
*/
struct HashBitmap
{
NodeTag type; /* to make it a valid Node */
MemoryContext mcxt; /* memory context containing me */
TBMStatus status; /* see codes above */
HTAB *pagetable; /* hash table of PagetableEntry's */
int nentries; /* number of entries in pagetable */
int nentries_hwm; /* high-water mark for number of entries */
int maxentries; /* limit on same to meet maxbytes */
int npages; /* number of exact entries in pagetable */
int nchunks; /* number of lossy entries in pagetable */
bool iterating; /* tbm_begin_iterate called? */
PagetableEntry entry1; /* used when status == HASHBM_ONE_PAGE */
/* the remaining fields are used while producing sorted output: */
PagetableEntry **spages; /* sorted exact-page list, or NULL */
PagetableEntry **schunks; /* sorted lossy-chunk list, or NULL */
int spageptr; /* next spages index */
int schunkptr; /* next schunks index */
int schunkbit; /* next bit to check in current schunk */
/* CDB: Statistics for EXPLAIN ANALYZE */
struct Instrumentation *instrument;
Size bytesperentry;
};
/* A struct to hide away HashBitmap state for a streaming bitmap */
typedef struct HashStreamOpaque
{
HashBitmap *tbm; /* HashStreamOpaque will not take the ownership of freeing HashBitmap */
PagetableEntry *entry;
} HashStreamOpaque;
/* Local function prototypes */
static void tbm_union_page(HashBitmap *a, const PagetableEntry *bpage);
static bool tbm_intersect_page(HashBitmap *a, PagetableEntry *apage,
const HashBitmap *b);
static const PagetableEntry *tbm_find_pageentry(const HashBitmap *tbm,
BlockNumber pageno);
static PagetableEntry *tbm_get_pageentry(HashBitmap *tbm, BlockNumber pageno);
static bool tbm_page_is_lossy(const HashBitmap *tbm, BlockNumber pageno);
static void tbm_mark_page_lossy(HashBitmap *tbm, BlockNumber pageno);
static void tbm_lossify(HashBitmap *tbm);
static int tbm_comparator(const void *left, const void *right);
static bool tbm_stream_block(StreamNode * self, PagetableEntry *e);
static void tbm_stream_free(StreamNode * self);
static void tbm_stream_set_instrument(StreamNode * self, struct Instrumentation *instr);
static void tbm_stream_upd_instrument(StreamNode * self);
/*
* tbm_create - create an initially-empty bitmap
*
* The bitmap will live in the memory context that is CurrentMemoryContext
* at the time of this call. It will be limited to (approximately) maxbytes
* total memory consumption.
*/
HashBitmap *
tbm_create(long maxbytes)
{
HashBitmap *tbm;
long nbuckets;
/*
* Ensure that we don't have heap tuple offsets going beyond (INT16_MAX +
* 1) or 32768. The executor iterates only over the first 32K tuples for
* lossy bitmap pages [MPP-24326].
*/
COMPILE_ASSERT(MaxHeapTuplesPerPage <= (INT16_MAX + 1));
/*
* Create the HashBitmap struct.
*/
tbm = (HashBitmap *) palloc0(sizeof(HashBitmap));
tbm->type = T_HashBitmap; /* Set NodeTag */
tbm->mcxt = CurrentMemoryContext;
tbm->status = HASHBM_EMPTY;
tbm->instrument = NULL;
/*
* Estimate number of hashtable entries we can have within maxbytes. This
* estimates the hash overhead at MAXALIGN(sizeof(HASHELEMENT)) plus a
* pointer per hash entry, which is crude but good enough for our purpose.
* Also count an extra Pointer per entry for the arrays created during
* iteration readout.
*/
tbm->bytesperentry =
(MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(sizeof(PagetableEntry))
+ sizeof(Pointer) + sizeof(Pointer));
nbuckets = maxbytes / tbm->bytesperentry;
nbuckets = Min(nbuckets, INT_MAX - 1); /* safety limit */
nbuckets = Max(nbuckets, 16); /* sanity limit */
tbm->maxentries = (int) nbuckets;
return tbm;
}
/*
* Actually create the hashtable. Since this is a moderately expensive
* proposition, we don't do it until we have to.
*/
static void
tbm_create_pagetable(HashBitmap *tbm)
{
HASHCTL hash_ctl;
Assert(tbm->status != HASHBM_HASH);
Assert(tbm->pagetable == NULL);
/* Create the hashtable proper */
MemSet(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = sizeof(BlockNumber);
hash_ctl.entrysize = sizeof(PagetableEntry);
hash_ctl.hash = tag_hash;
hash_ctl.hcxt = tbm->mcxt;
tbm->pagetable = hash_create("HashBitmap",
128, /* start small and extend */
&hash_ctl,
HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
/* If entry1 is valid, push it into the hashtable */
if (tbm->status == HASHBM_ONE_PAGE)
{
PagetableEntry *page;
bool found;
page = (PagetableEntry *) hash_search(tbm->pagetable,
(void *) &tbm->entry1.blockno,
HASH_ENTER, &found);
Assert(!found);
memcpy(page, &tbm->entry1, sizeof(PagetableEntry));
}
tbm->status = HASHBM_HASH;
}
/*
* tbm_free - free a HashBitmap
*/
void
tbm_free(HashBitmap *tbm)
{
if (tbm->instrument)
tbm_bitmap_upd_instrument((Node *) tbm);
if (tbm->pagetable)
hash_destroy(tbm->pagetable);
if (tbm->spages)
pfree(tbm->spages);
if (tbm->schunks)
pfree(tbm->schunks);
pfree(tbm);
}
/*
* tbm_upd_instrument - Update the Instrumentation attached to a HashBitmap.
*/
static void
tbm_upd_instrument(HashBitmap *tbm)
{
Instrumentation *instr = tbm->instrument;
Size workmemused;
if (!instr)
return;
/* Update page table high-water mark. */
tbm->nentries_hwm = Max(tbm->nentries_hwm, tbm->nentries);
/* How much of our work_mem quota was actually used? */
workmemused = tbm->nentries_hwm * tbm->bytesperentry;
instr->workmemused = Max(instr->workmemused, workmemused);
} /* tbm_upd_instrument */
/*
* tbm_set_instrument
* Attach caller's Instrumentation object to a HashBitmap, unless the
* HashBitmap already has one. We want the statistics to be associated
* with the plan node which originally created the bitmap, rather than a
* downstream consumer of the bitmap.
*/
static void
tbm_set_instrument(HashBitmap *tbm, struct Instrumentation *instr)
{
if (instr == NULL ||
tbm->instrument == NULL)
{
tbm->instrument = instr;
tbm_upd_instrument(tbm);
}
} /* tbm_set_instrument */
/*
* tbm_add_tuples - add some tuple IDs to a HashBitmap
*/
void
tbm_add_tuples(HashBitmap *tbm, const ItemPointer tids, int ntids)
{
int i;
Assert(!tbm->iterating);
for (i = 0; i < ntids; i++)
{
BlockNumber blk = ItemPointerGetBlockNumber(tids + i);
OffsetNumber off = ItemPointerGetOffsetNumber(tids + i);
PagetableEntry *page;
int wordnum,
bitnum;
/* safety check to ensure we don't overrun bit array bounds */
/* UNDONE: Turn this off until we convert this module to AO TIDs. */
#if 0
if (off < 1 || off > MAX_TUPLES_PER_PAGE)
elog(ERROR, "tuple offset out of range: %u", off);
#endif
if (tbm_page_is_lossy(tbm, blk))
continue; /* whole page is already marked */
page = tbm_get_pageentry(tbm, blk);
if (page->ischunk)
{
/* The page is a lossy chunk header, set bit for itself */
wordnum = bitnum = 0;
}
else
{
/* Page is exact, so set bit for individual tuple */
wordnum = WORDNUM(off - 1);
bitnum = BITNUM(off - 1);
}
page->words[wordnum] |= ((tbm_bitmapword) 1 << bitnum);
if (tbm->nentries > tbm->maxentries)
tbm_lossify(tbm);
}
}
/*
* tbm_union - set union
*
* a is modified in-place, b is not changed
*/
void
tbm_union(HashBitmap *a, const HashBitmap *b)
{
Assert(!a->iterating);
/* Nothing to do if b is empty */
if (b->nentries == 0)
return;
/* Scan through chunks and pages in b, merge into a */
if (b->status == HASHBM_ONE_PAGE)
tbm_union_page(a, &b->entry1);
else
{
HASH_SEQ_STATUS status;
PagetableEntry *bpage;
Assert(b->status == HASHBM_HASH);
hash_seq_init(&status, b->pagetable);
while ((bpage = (PagetableEntry *) hash_seq_search(&status)) != NULL)
tbm_union_page(a, bpage);
}
}
/* Process one page of b during a union op */
static void
tbm_union_page(HashBitmap *a, const PagetableEntry *bpage)
{
PagetableEntry *apage;
int wordnum;
if (bpage->ischunk)
{
/* Scan b's chunk, mark each indicated page lossy in a */
for (wordnum = 0; wordnum < WORDS_PER_PAGE; wordnum++)
{
tbm_bitmapword w = bpage->words[wordnum];
if (w != 0)
{
BlockNumber pg;
pg = bpage->blockno + (wordnum * TBM_BITS_PER_BITMAPWORD);
while (w != 0)
{
if (w & 1)
tbm_mark_page_lossy(a, pg);
pg++;
w >>= 1;
}
}
}
}
else if (tbm_page_is_lossy(a, bpage->blockno))
{
/* page is already lossy in a, nothing to do */
return;
}
else
{
apage = tbm_get_pageentry(a, bpage->blockno);
if (apage->ischunk)
{
/* The page is a lossy chunk header, set bit for itself */
apage->words[0] |= ((tbm_bitmapword) 1 << 0);
}
else
{
/* Both pages are exact, merge at the bit level */
for (wordnum = 0; wordnum < WORDS_PER_PAGE; wordnum++)
apage->words[wordnum] |= bpage->words[wordnum];
}
}
if (a->nentries > a->maxentries)
tbm_lossify(a);
}
/*
* tbm_intersect - set intersection
*
* a is modified in-place, b is not changed
*/
void
tbm_intersect(HashBitmap *a, const HashBitmap *b)
{
Assert(!a->iterating);
/* Nothing to do if a is empty */
if (a->nentries == 0)
return;
a->nentries_hwm = Max(a->nentries_hwm, a->nentries);
/* Scan through chunks and pages in a, try to match to b */
if (a->status == HASHBM_ONE_PAGE)
{
if (tbm_intersect_page(a, &a->entry1, b))
{
/* Page is now empty, remove it from a */
Assert(!a->entry1.ischunk);
a->npages--;
a->nentries--;
Assert(a->nentries == 0);
a->status = HASHBM_EMPTY;
}
}
else
{
HASH_SEQ_STATUS status;
PagetableEntry *apage;
Assert(a->status == HASHBM_HASH);
hash_seq_init(&status, a->pagetable);
while ((apage = (PagetableEntry *) hash_seq_search(&status)) != NULL)
{
if (tbm_intersect_page(a, apage, b))
{
/* Page or chunk is now empty, remove it from a */
if (apage->ischunk)
a->nchunks--;
else
a->npages--;
a->nentries--;
if (hash_search(a->pagetable,
(void *) &apage->blockno,
HASH_REMOVE, NULL) == NULL)
elog(ERROR, "hash table corrupted");
}
}
}
}
/*
* Process one page of a during an intersection op
*
* Returns TRUE if apage is now empty and should be deleted from a
*/
static bool
tbm_intersect_page(HashBitmap *a, PagetableEntry *apage, const HashBitmap *b)
{
const PagetableEntry *bpage;
int wordnum;
if (apage->ischunk)
{
/* Scan each bit in chunk, try to clear */
bool candelete = true;
for (wordnum = 0; wordnum < WORDS_PER_PAGE; wordnum++)
{
tbm_bitmapword w = apage->words[wordnum];
if (w != 0)
{
tbm_bitmapword neww = w;
BlockNumber pg;
int bitnum;
pg = apage->blockno + (wordnum * TBM_BITS_PER_BITMAPWORD);
bitnum = 0;
while (w != 0)
{
if (w & 1)
{
if (!tbm_page_is_lossy(b, pg) &&
tbm_find_pageentry(b, pg) == NULL)
{
/* Page is not in b at all, lose lossy bit */
neww &= ~((tbm_bitmapword) 1 << bitnum);
}
}
pg++;
bitnum++;
w >>= 1;
}
apage->words[wordnum] = neww;
if (neww != 0)
candelete = false;
}
}
return candelete;
}
else if (tbm_page_is_lossy(b, apage->blockno))
{
/*
* When the page is lossy in b, we have to mark it lossy in a too. We
* know that no bits need be set in bitmap a, but we do not know which
* ones should be cleared, and we have no API for "at most these
* tuples need be checked". (Perhaps it's worth adding that?)
*/
tbm_mark_page_lossy(a, apage->blockno);
/*
* Note: tbm_mark_page_lossy will have removed apage from a, and may
* have inserted a new lossy chunk instead. We can continue the same
* seq_search scan at the caller level, because it does not matter
* whether we visit such a new chunk or not: it will have only the bit
* for apage->blockno set, which is correct.
*
* We must return false here since apage was already deleted.
*/
return false;
}
else
{
bool candelete = true;
bpage = tbm_find_pageentry(b, apage->blockno);
if (bpage != NULL)
{
/* Both pages are exact, merge at the bit level */
Assert(!bpage->ischunk);
for (wordnum = 0; wordnum < WORDS_PER_PAGE; wordnum++)
{
apage->words[wordnum] &= bpage->words[wordnum];
if (apage->words[wordnum] != 0)
candelete = false;
}
}
return candelete;
}
}
/*
* tbm_is_empty - is a HashBitmap completely empty?
*/
bool
tbm_is_empty(const HashBitmap *tbm)
{
return (tbm->nentries == 0);
}
/*
* tbm_begin_iterate - prepare to iterate through a HashBitmap
*
* NB: after this is called, it is no longer allowed to modify the contents
* of the bitmap. However, you can call this multiple times to scan the
* contents repeatedly.
*/
void
tbm_begin_iterate(HashBitmap *tbm)
{
HASH_SEQ_STATUS status;
PagetableEntry *page;
int npages;
int nchunks;
tbm->iterating = true;
/*
* Reset iteration pointers.
*/
tbm->spageptr = 0;
tbm->schunkptr = 0;
tbm->schunkbit = 0;
/*
* Nothing else to do if no entries, nor if we don't have a hashtable.
*/
if (tbm->nentries == 0 || tbm->status != HASHBM_HASH)
return;
/*
* Create and fill the sorted page lists if we didn't already.
*/
if (!tbm->spages && tbm->npages > 0)
tbm->spages = (PagetableEntry **)
MemoryContextAlloc(tbm->mcxt,
tbm->npages * sizeof(PagetableEntry *));
if (!tbm->schunks && tbm->nchunks > 0)
tbm->schunks = (PagetableEntry **)
MemoryContextAlloc(tbm->mcxt,
tbm->nchunks * sizeof(PagetableEntry *));
hash_seq_init(&status, tbm->pagetable);
npages = nchunks = 0;
while ((page = (PagetableEntry *) hash_seq_search(&status)) != NULL)
{
if (page->ischunk)
tbm->schunks[nchunks++] = page;
else
tbm->spages[npages++] = page;
}
Assert(npages == tbm->npages);
Assert(nchunks == tbm->nchunks);
if (npages > 1)
qsort(tbm->spages, npages, sizeof(PagetableEntry *), tbm_comparator);
if (nchunks > 1)
qsort(tbm->schunks, nchunks, sizeof(PagetableEntry *), tbm_comparator);
}
/*
* tbm_iterate - scan through next page of a HashBitmap or a StreamBitmap.
*/
bool
tbm_iterate(Node *tbm, TBMIterateResult *output)
{
Assert(IsA(tbm, HashBitmap) || IsA(tbm, StreamBitmap));
switch (tbm->type)
{
case T_HashBitmap:
{
HashBitmap *hashBitmap = (HashBitmap *) tbm;
if (!hashBitmap->iterating)
tbm_begin_iterate(hashBitmap);
return tbm_iterate_hash(hashBitmap, output);
}
case T_StreamBitmap:
{
StreamBitmap *streamBitmap = (StreamBitmap *) tbm;
bool status;
StreamNode *s;
s = streamBitmap->streamNode;
status = bitmap_stream_iterate((void *) s, &(streamBitmap->entry));
/* XXX: perhaps we should only do this if status == true ? */
tbm_iterate_page(&(streamBitmap->entry), output);
return status;
}
default:
elog(ERROR, "unrecoganized node type");
}
return false;
}
/*
* tbm_iterate_page - get a TBMIterateResult from a given PagetableEntry.
*/
static bool
tbm_iterate_page(PagetableEntry *page, TBMIterateResult *output)
{
int ntuples;
int wordnum;
if (page->ischunk)
{
ntuples = -1;
}
else
{
/* scan bitmap to extract individual offset numbers */
ntuples = 0;
for (wordnum = 0; wordnum < WORDS_PER_PAGE; wordnum++)
{
tbm_bitmapword w = page->words[wordnum];
if (w != 0)
{
int off = wordnum * TBM_BITS_PER_BITMAPWORD + 1;
while (w != 0)
{
if (w & 1)
output->offsets[ntuples++] = (OffsetNumber) off;
off++;
w >>= 1;
}
}
}
}
output->blockno = page->blockno;
output->ntuples = ntuples;
return true;
}
/*
* tbm_iterate_hash - scan through next page of a HashBitmap
*
* Gets a TBMIterateResult representing one page, or NULL if there are
* no more pages to scan. Pages are guaranteed to be delivered in numerical
* order. If result->ntuples < 0, then the bitmap is "lossy" and failed to
* remember the exact tuples to look at on this page --- the caller must
* examine all tuples on the page and check if they meet the intended
* condition.
*
* If 'output' is NULL, simple advance the HashBitmap by one.
*/
static bool
tbm_iterate_hash(HashBitmap *tbm, TBMIterateResult *output)
{
PagetableEntry *e;
bool more;
e = tbm_next_page(tbm, &more);
if (more && e)
{
tbm_iterate_page(e, output);
return true;
}
return false;
}
/*
* tbm_next_page - actually traverse the HashBitmap
*
* Store the next block of matches in nextpage.
*/
static PagetableEntry *
tbm_next_page(HashBitmap *tbm, bool *more)
{
Assert(tbm->iterating);
*more = true;
/*
* If lossy chunk pages remain, make sure we've advanced schunkptr/
* schunkbit to the next set bit.
*/
while (tbm->schunkptr < tbm->nchunks)
{
PagetableEntry *chunk = tbm->schunks[tbm->schunkptr];
int schunkbit = tbm->schunkbit;
while (schunkbit < PAGES_PER_CHUNK)
{
int wordnum = WORDNUM(schunkbit);
int bitnum = BITNUM(schunkbit);
if ((chunk->words[wordnum] & ((tbm_bitmapword) 1 << bitnum)) != 0)
break;
schunkbit++;
}
if (schunkbit < PAGES_PER_CHUNK)
{
tbm->schunkbit = schunkbit;
break;
}
/* advance to next chunk */
tbm->schunkptr++;
tbm->schunkbit = 0;
}
/*
* If both chunk and per-page data remain, must output the numerically
* earlier page.
*/
if (tbm->schunkptr < tbm->nchunks)
{
PagetableEntry *chunk = tbm->schunks[tbm->schunkptr];
PagetableEntry *nextpage;
BlockNumber chunk_blockno;
chunk_blockno = chunk->blockno + tbm->schunkbit;
if (tbm->spageptr >= tbm->npages ||
chunk_blockno < tbm->spages[tbm->spageptr]->blockno)
{
/* Return a lossy page indicator from the chunk */
nextpage = (PagetableEntry *) palloc(sizeof(PagetableEntry));
nextpage->ischunk = true;
nextpage->blockno = chunk_blockno;
tbm->schunkbit++;
return nextpage;
}
}
if (tbm->spageptr < tbm->npages)
{
PagetableEntry *e;
/* In ONE_PAGE state, we don't allocate an spages[] array */
if (tbm->status == HASHBM_ONE_PAGE)
e = &tbm->entry1;
else
e = tbm->spages[tbm->spageptr];
tbm->spageptr++;
return e;
}
/* Nothing more in the bitmap */
*more = false;
return NULL;
}
/*
* tbm_find_pageentry - find a PagetableEntry for the pageno
*
* Returns NULL if there is no non-lossy entry for the pageno.
*/
static const PagetableEntry *
tbm_find_pageentry(const HashBitmap *tbm, BlockNumber pageno)
{
const PagetableEntry *page;
if (tbm->nentries == 0) /* in case pagetable doesn't exist */
return NULL;
if (tbm->status == HASHBM_ONE_PAGE)
{
page = &tbm->entry1;
if (page->blockno != pageno)
return NULL;
Assert(!page->ischunk);
return page;
}
page = (PagetableEntry *) hash_search(tbm->pagetable,
(void *) &pageno,
HASH_FIND, NULL);
if (page == NULL)
return NULL;
if (page->ischunk)
return NULL; /* don't want a lossy chunk header */
return page;
}
/*
* tbm_get_pageentry - find or create a PagetableEntry for the pageno
*
* If new, the entry is marked as an exact (non-chunk) entry.
*
* This may cause the table to exceed the desired memory size. It is
* up to the caller to call tbm_lossify() at the next safe point if so.
*/
static PagetableEntry *
tbm_get_pageentry(HashBitmap *tbm, BlockNumber pageno)
{
PagetableEntry *page;
bool found;
if (tbm->status == HASHBM_EMPTY)
{
/* Use the fixed slot */
page = &tbm->entry1;
found = false;
tbm->status = HASHBM_ONE_PAGE;
}
else
{
if (tbm->status == HASHBM_ONE_PAGE)
{
page = &tbm->entry1;
if (page->blockno == pageno)
return page;
/* Time to switch from one page to a hashtable */
tbm_create_pagetable(tbm);
}
/* Look up or create an entry */
page = (PagetableEntry *) hash_search(tbm->pagetable,
(void *) &pageno,
HASH_ENTER, &found);
}
/* Initialize it if not present before */
if (!found)
{
MemSet(page, 0, sizeof(PagetableEntry));
page->blockno = pageno;
/* must count it too */
tbm->nentries++;
tbm->npages++;
}
return page;
}
/*
* tbm_page_is_lossy - is the page marked as lossily stored?
*/
static bool
tbm_page_is_lossy(const HashBitmap *tbm, BlockNumber pageno)
{
PagetableEntry *page;
BlockNumber chunk_pageno;
int bitno;
/* we can skip the lookup if there are no lossy chunks */
if (tbm->nchunks == 0)
return false;
Assert(tbm->status == HASHBM_HASH);
bitno = pageno % PAGES_PER_CHUNK;
chunk_pageno = pageno - bitno;
page = (PagetableEntry *) hash_search(tbm->pagetable,
(void *) &chunk_pageno,
HASH_FIND, NULL);
if (page != NULL && page->ischunk)
{
int wordnum = WORDNUM(bitno);
int bitnum = BITNUM(bitno);
if ((page->words[wordnum] & ((tbm_bitmapword) 1 << bitnum)) != 0)
return true;
}
return false;
}
/*
* tbm_mark_page_lossy - mark the page number as lossily stored
*
* This may cause the table to exceed the desired memory size. It is
* up to the caller to call tbm_lossify() at the next safe point if so.
*/
static void
tbm_mark_page_lossy(HashBitmap *tbm, BlockNumber pageno)
{
PagetableEntry *page;
bool found;
BlockNumber chunk_pageno;
int bitno;
int wordnum;
int bitnum;
/* We force the bitmap into hashtable mode whenever it's lossy */
if (tbm->status != HASHBM_HASH)
tbm_create_pagetable(tbm);
bitno = pageno % PAGES_PER_CHUNK;
chunk_pageno = pageno - bitno;
/*
* Remove any extant non-lossy entry for the page. If the page is its own
* chunk header, however, we skip this and handle the case below.
*/
if (bitno != 0)
{
if (hash_search(tbm->pagetable,
(void *) &pageno,
HASH_REMOVE, NULL) != NULL)
{
/* It was present, so adjust counts */
tbm->nentries_hwm = Max(tbm->nentries_hwm, tbm->nentries);
tbm->nentries--;
tbm->npages--; /* assume it must have been non-lossy */
}
}
/* Look up or create entry for chunk-header page */
page = (PagetableEntry *) hash_search(tbm->pagetable,
(void *) &chunk_pageno,
HASH_ENTER, &found);
/* Initialize it if not present before */
if (!found)
{
MemSet(page, 0, sizeof(PagetableEntry));
page->blockno = chunk_pageno;
page->ischunk = true;
/* must count it too */
tbm->nentries++;
tbm->nchunks++;
}
else if (!page->ischunk)
{
/* chunk header page was formerly non-lossy, make it lossy */
MemSet(page, 0, sizeof(PagetableEntry));
page->blockno = chunk_pageno;
page->ischunk = true;
/* we assume it had some tuple bit(s) set, so mark it lossy */
page->words[0] = ((tbm_bitmapword) 1 << 0);
/* adjust counts */
tbm->nchunks++;
tbm->npages--;
}
/* Now set the original target page's bit */
wordnum = WORDNUM(bitno);
bitnum = BITNUM(bitno);
page->words[wordnum] |= ((tbm_bitmapword) 1 << bitnum);
}
/*
* tbm_lossify - lose some information to get back under the memory limit
*/
static void
tbm_lossify(HashBitmap *tbm)
{
HASH_SEQ_STATUS status;
PagetableEntry *page;
/*
* XXX Really stupid implementation: this just lossifies pages in
* essentially random order. We should be paying some attention to the
* number of bits set in each page, instead.
*
* Since we are called as soon as nentries exceeds maxentries, we should
* push nentries down to significantly less than maxentries, or else we'll
* just end up doing this again very soon. We shoot for maxentries/2.
*/
Assert(!tbm->iterating);
Assert(tbm->status == HASHBM_HASH);
hash_seq_init(&status, tbm->pagetable);
while ((page = (PagetableEntry *) hash_seq_search(&status)) != NULL)
{
if (page->ischunk)
continue; /* already a chunk header */
/*
* If the page would become a chunk header, we won't save anything by
* converting it to lossy, so skip it.
*/
if ((page->blockno % PAGES_PER_CHUNK) == 0)
continue;
/* This does the dirty work ... */
tbm_mark_page_lossy(tbm, page->blockno);
if (tbm->nentries <= tbm->maxentries)
{
/* we have done enough */
hash_seq_term(&status);
break;
}
/*
* Note: tbm_mark_page_lossy may have inserted a lossy chunk into the
* hashtable. We can continue the same seq_search scan since we do
* not care whether we visit lossy chunks or not.
*/
}
/*
* With a big bitmap and small work_mem, it's possible that we cannot
* get under maxentries. Again, if that happens, we'd end up uselessly
* calling tbm_lossify over and over. To prevent this from becoming a
* performance sink, force maxentries up to at least double the current
* number of entries. (In essence, we're admitting inability to fit
* within work_mem when we do this.) Note that this test will not fire
* if we broke out of the loop early; and if we didn't, the current
* number of entries is simply not reducible any further.
*/
if (tbm->nentries > tbm->maxentries / 2)
tbm->maxentries = Min(tbm->nentries, (INT_MAX - 1) / 2) * 2;
}
/*
* qsort comparator to handle PagetableEntry pointers.
*/
static int
tbm_comparator(const void *left, const void *right)
{
BlockNumber l = (*((const PagetableEntry **) left))->blockno;
BlockNumber r = (*((const PagetableEntry **) right))->blockno;
if (l < r)
return -1;
else if (l > r)
return 1;
return 0;
}
/*
* functions related to streaming
*/
static void
opstream_free(StreamNode *self)
{
ListCell *cell;
foreach(cell, self->input)
{
StreamNode *inp = (StreamNode *) lfirst(cell);
if (inp->free)
inp->free(inp);
}
list_free(self->input);
pfree(self);
}
static void
opstream_set_instrument(StreamNode *self, struct Instrumentation *instr)
{
ListCell *cell;
foreach(cell, self->input)
{
StreamNode *inp = (StreamNode *) lfirst(cell);
if (inp->set_instrument)
inp->set_instrument(inp, instr);
}
}
static void
opstream_upd_instrument(StreamNode *self)
{
ListCell *cell;
foreach(cell, self->input)
{
StreamNode *inp = (StreamNode *) lfirst(cell);
if (inp->upd_instrument)
inp->upd_instrument(inp);
}
}
static OpStream *
make_opstream(StreamType kind, StreamNode *n1, StreamNode *n2)
{
OpStream *op;
Assert(kind == BMS_OR || kind == BMS_AND);
Assert(PointerIsValid(n1));
op = (OpStream *) palloc0(sizeof(OpStream));
op->type = kind;
op->pull = bitmap_stream_iterate;
op->nextblock = 0;
op->input = list_make2(n1, n2);
op->free = opstream_free;
op->set_instrument = opstream_set_instrument;
op->upd_instrument = opstream_upd_instrument;
return (void *) op;
}
/*
* stream_move_node - move a streamnode from StreamBitMap (source)'s streamnode
* to given StreamBitMap(destination). Also transfer the ownership of source streamnode by
* resetting to NULL.
*/
void
stream_move_node(StreamBitmap *destination, StreamBitmap *source, StreamType kind)
{
Assert(NULL != destination);
Assert(NULL != source);
stream_add_node(destination,
source->streamNode, kind);
/* destination owns the streamNode and hence resetting it to NULL for source->streamNode. */
source->streamNode = NULL;
}
/*
* stream_add_node() - add a new node to a bitmap stream
* node is a base node -- i.e., an index/external
* kind is one of BMS_INDEX, BMS_OR or BMS_AND
*/
void
stream_add_node(StreamBitmap *sbm, StreamNode *node, StreamType kind)
{
/* CDB: Tell node where to put its statistics for EXPLAIN ANALYZE. */
if (node->set_instrument)
node->set_instrument(node, sbm->instrument);
/* initialised */
if (sbm->streamNode)
{
StreamNode *n = sbm->streamNode;
/* StreamNode is already an index, transform to OpStream */
if ((n->type == BMS_AND && kind == BMS_AND) ||
(n->type == BMS_OR && kind == BMS_OR))
{
OpStream *o = (OpStream *) n;
o->input = lappend(o->input, node);
}
else if ((n->type == BMS_AND && kind != BMS_AND) ||
(n->type == BMS_OR && kind != BMS_OR) ||
(n->type == BMS_INDEX))
{
sbm->streamNode = make_opstream(kind, sbm->streamNode, node);
}
else
elog(ERROR, "unknown stream type %i", (int) n->type);
}
else
{
if (kind == BMS_INDEX)
sbm->streamNode = node;
else
sbm->streamNode = make_opstream(kind, node, NULL);
}
}
/*
* tbm_create_stream_node() - turn a HashBitmap into a stream
*/
StreamNode *
tbm_create_stream_node(HashBitmap *tbm)
{
IndexStream *is;
HashStreamOpaque *op;
is = (IndexStream *) palloc0(sizeof(IndexStream));
op = (HashStreamOpaque *) palloc(sizeof(HashStreamOpaque));
is->type = BMS_INDEX;
is->nextblock = 0;
is->pull = tbm_stream_block;
is->free = tbm_stream_free;
is->set_instrument = tbm_stream_set_instrument;
is->upd_instrument = tbm_stream_upd_instrument;
op->tbm = tbm;
op->entry = NULL;
is->opaque = (void *) op;
return is;
}
/*
* tbm_stream_block() - Fetch the next block from HashBitmap stream
*
* Notice that the IndexStream passed in as opaque will tell us the
* desired block to stream. If the block requrested is greater than or equal
* to the block we've cached inside the HashStreamOpaque, return that.
*/
static bool
tbm_stream_block(StreamNode *self, PagetableEntry *e)
{
IndexStream *is = self;
HashStreamOpaque *op = (HashStreamOpaque *) is->opaque;
HashBitmap *tbm = op->tbm;
PagetableEntry *next = op->entry;
bool more;
/* have we already got an entry? */
if (next && is->nextblock <= next->blockno)
{
memcpy(e, next, sizeof(PagetableEntry));
return true;
}
if (!tbm->iterating)
tbm_begin_iterate(tbm);
/* we need a new entry */
op->entry = tbm_next_page(tbm, &more);
if (more)
{
Assert(op->entry);
memcpy(e, op->entry, sizeof(PagetableEntry));
}
is->nextblock++;
return more;
}
static void
tbm_stream_free(StreamNode *self)
{
HashStreamOpaque *op = (HashStreamOpaque *) self->opaque;
/*
* op->tbm is actually a reference to node->bitmap from BitmapIndexScanState
* BitmapIndexScanState would have freed the op->tbm already so we shouldn't
* access now.
*/
pfree(op);
pfree(self);
}
static void
tbm_stream_set_instrument(StreamNode *self, struct Instrumentation *instr)
{
tbm_set_instrument(((HashStreamOpaque *) self->opaque)->tbm, instr);
}
static void
tbm_stream_upd_instrument(StreamNode *self)
{
tbm_upd_instrument(((HashStreamOpaque *) self->opaque)->tbm);
}
/*
* bitmap_stream_iterate()
*
* This is a generic iterator for bitmap streams. The function doesn't
* know anything about the streams it is actually iterating.
*
* Returns false when no more results can be obtained, otherwise true.
*/
bool
bitmap_stream_iterate(StreamNode *n, PagetableEntry *e)
{
bool res = false;
MemSet(e, 0, sizeof(PagetableEntry));
if (n->type == BMS_INDEX)
{
IndexStream *is = (IndexStream *) n;
res = is->pull((void *) is, e);
}
else if (n->type == BMS_OR || n->type == BMS_AND)
{
/*
* There are two ways we can do this: either, we could maintain our
* own top level BatchWords structure and pull blocks out of that OR
* we could maintain batch words for each sub map and union/intersect
* those together to get the resulting page entries.
*
* Now, BatchWords are specific to bitmap indexes so we'd have to
* translate HashBitmaps. All the infrastructure is available to
* translate bitmap indexes into the HashBitmap mechanism so we'll do
* that for now.
*/
ListCell *map;
OpStream *op = (OpStream *) n;
BlockNumber minblockno;
ListCell *cell;
int wordnum;
List *matches;
bool empty;
/*
* First, iterate through each input bitmap stream and save the block
* which is returned. HashBitmaps are designed such that they do not
* return blocks with no matches -- that is, say a HashBitmap has
* matches for block 1, 4 and 5 it store matches only for those
* blocks. Therefore, we may have one stream return a match for block
* 10, another for block 15 and another yet for block 10 again. In
* this case, we cannot include block 15 in the union/intersection
* because it represents matches on some page later in the scan. We'll
* get around to it in good time.
*
* In this case, if we're doing a union, we perform the operation
* without reference to block 15. If we're performing an intersection
* we cannot perform it on block 10 because we didn't get any matches
* for block 10 for one of the streams: the intersection with fail.
* So, we set the desired block (op->nextblock) to block 15 and loop
* around to the `restart' label.
*/
restart:
e->blockno = InvalidBlockNumber;
empty = false;
matches = NIL;
minblockno = InvalidBlockNumber;
Assert(PointerIsValid(op->input));
foreach(map, op->input)
{
StreamNode *in = (StreamNode *) lfirst(map);
PagetableEntry *new;
bool r;
new = (PagetableEntry *) palloc(sizeof(PagetableEntry));
/* set the desired block */
in->nextblock = op->nextblock;
r = in->pull((void *) in, new);
/*
* Let to caller know we got a result from some input bitmap. This
* doesn't hold true if we're doing an intersection, and that is
* handled below
*/
res = res || r;
/* only include a match if the pull function tells us to */
if (r)
{
if (minblockno == InvalidBlockNumber)
minblockno = new->blockno;
else if (n->type == BMS_OR)
minblockno = Min(minblockno, new->blockno);
else
minblockno = Max(minblockno, new->blockno);
matches = lappend(matches, (void *) new);
}
else
{
pfree(new);
if (n->type == BMS_AND)
{
/*
* No more results for this stream and since we're doing
* an intersection we wont get any valid results from now
* on, so tell our caller that
*/
op->nextblock = minblockno + 1; /* seems safe */
return false;
}
else if (n->type == BMS_OR)
continue;
}
}
/*
* Now we iterate through the actual matches and perform the desired
* operation on those from the same minimum block
*/
foreach(cell, matches)
{
PagetableEntry *tmp = (PagetableEntry *) lfirst(cell);
if (tmp->blockno == minblockno)
{
if (e->blockno == InvalidBlockNumber)
{
memcpy(e, tmp, sizeof(PagetableEntry));
continue;
}
/* already initialised, so OR together */
if (tmp->ischunk == true)
{
/*
* Okay, new entry is lossy so match our output as lossy
*/
e->ischunk = true;
/* XXX: we can just return now... I think :) */
op->nextblock = minblockno + 1;
list_free_deep(matches);
return res;
}
/* union/intersect existing output and new matches */
for (wordnum = 0; wordnum < WORDS_PER_PAGE; wordnum++)
{
if (n->type == BMS_OR)
e->words[wordnum] |= tmp->words[wordnum];
else
e->words[wordnum] &= tmp->words[wordnum];
}
}
else if (n->type == BMS_AND)
{
/*
* One of our input maps didn't return a block for the desired
* block number so, we loop around again.
*
* Notice that we don't set the next block as minblockno + 1.
* We don't know if the other streams will find a match for
* minblockno, so we cannot skip past it yet.
*/
op->nextblock = minblockno;
empty = true;
break;
}
}
if (empty)
{
/* start again */
empty = false;
MemSet(e->words, 0, sizeof(tbm_bitmapword) * WORDS_PER_PAGE);
list_free_deep(matches);
goto restart;
}
else
list_free_deep(matches);
if (res)
op->nextblock = minblockno + 1;
}
return res;
}
/*
* --------- These functions accept either HashBitmap or StreamBitmap ---------
*/
/*
* tbm_bitmap_free - free a HashBitmap or StreamBitmap
*/
void
tbm_bitmap_free(Node *bm)
{
if (bm == NULL)
return;
switch (bm->type)
{
case T_HashBitmap:
tbm_free((HashBitmap *) bm);
break;
case T_StreamBitmap:
{
StreamBitmap *sbm = (StreamBitmap *) bm;
StreamNode *sn = sbm->streamNode;
sbm->streamNode = NULL;
if (sn &&
sn->free)
sn->free(sn);
pfree(sbm);
break;
}
default:
Assert(0);
}
} /* tbm_bitmap_free */
/*
* tbm_bitmap_set_instrument - attach caller's Instrumentation object to bitmap
*/
void
tbm_bitmap_set_instrument(Node *bm, struct Instrumentation *instr)
{
if (bm == NULL)
return;
switch (bm->type)
{
case T_HashBitmap:
tbm_set_instrument((HashBitmap *) bm, instr);
break;
case T_StreamBitmap:
{
StreamBitmap *sbm = (StreamBitmap *) bm;
if (sbm->streamNode &&
sbm->streamNode->set_instrument)
sbm->streamNode->set_instrument(sbm->streamNode, instr);
break;
}
default:
Assert(0);
}
} /* tbm_bitmap_set_instrument */
/*
* tbm_bitmap_upd_instrument - update stats in caller's Instrumentation object
*
* Some callers don't bother to tbm_free() their bitmaps, but let the storage
* be reclaimed when the MemoryContext is reset. Such callers should use this
* function to make sure the statistics are transferred to the Instrumentation
* object before the bitmap goes away.
*/
void
tbm_bitmap_upd_instrument(Node *bm)
{
if (bm == NULL)
return;
switch (bm->type)
{
case T_HashBitmap:
tbm_upd_instrument((HashBitmap *) bm);
break;
case T_StreamBitmap:
{
StreamBitmap *sbm = (StreamBitmap *) bm;
if (sbm->streamNode &&
sbm->streamNode->upd_instrument)
sbm->streamNode->upd_instrument(sbm->streamNode);
break;
}
default:
Assert(0);
}
} /* tbm_bitmap_upd_instrument */
void
tbm_convert_appendonly_tid_out(ItemPointer psudeoHeapTid, AOTupleId *aoTid)
{
/* UNDONE: For now, just copy. */
memcpy(aoTid, psudeoHeapTid, SizeOfIptrData);
}
| apache-2.0 |
bmanc2000/aws-sdk-cpp | aws-cpp-sdk-s3/source/model/VersioningConfiguration.cpp | 5 | 2501 | /*
* Copyright 2010-2015 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 <aws/s3/model/VersioningConfiguration.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::S3::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
VersioningConfiguration::VersioningConfiguration() :
m_mFADeleteHasBeenSet(false),
m_statusHasBeenSet(false)
{
}
VersioningConfiguration::VersioningConfiguration(const XmlNode& xmlNode) :
m_mFADeleteHasBeenSet(false),
m_statusHasBeenSet(false)
{
*this = xmlNode;
}
VersioningConfiguration& VersioningConfiguration::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode mFADeleteNode = resultNode.FirstChild("MFADelete");
if(mFADeleteNode.IsNull())
{
mFADeleteNode = resultNode;
}
if(!mFADeleteNode.IsNull())
{
m_mFADelete = MFADeleteMapper::GetMFADeleteForName(StringUtils::Trim(mFADeleteNode.GetText().c_str()).c_str());
m_mFADeleteHasBeenSet = true;
}
XmlNode statusNode = resultNode.FirstChild("Status");
if(statusNode.IsNull())
{
statusNode = resultNode;
}
if(!statusNode.IsNull())
{
m_status = BucketVersioningStatusMapper::GetBucketVersioningStatusForName(StringUtils::Trim(statusNode.GetText().c_str()).c_str());
m_statusHasBeenSet = true;
}
}
return *this;
}
void VersioningConfiguration::AddToNode(XmlNode& parentNode) const
{
Aws::StringStream ss;
if(m_mFADeleteHasBeenSet)
{
XmlNode mFADeleteNode = parentNode.CreateChildElement("MFADelete");
mFADeleteNode.SetText(MFADeleteMapper::GetNameForMFADelete(m_mFADelete));
}
if(m_statusHasBeenSet)
{
XmlNode statusNode = parentNode.CreateChildElement("MfaDelete");
statusNode.SetText(BucketVersioningStatusMapper::GetNameForBucketVersioningStatus(m_status));
}
}
| apache-2.0 |
tst-lsavoie/earthenterprise | earth_enterprise/src/common/proto_streaming_imagery.cpp | 5 | 2757 | // Copyright 2017 Google Inc.
// Copyright 2020 The Open GEE Contributors
//
// 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 "common/proto_streaming_imagery.h"
#include <third_party/rsa_md5/crc32.h>
#include "google/protobuf/descriptor.h"
#include "common/khTileAddr.h"
// geEarthImageryPacket
geEarthImageryPacket::geEarthImageryPacket(void) {
}
geEarthImageryPacket::~geEarthImageryPacket(void) {
}
size_t geEarthImageryPacket::GetMetadataSize() const {
// message_metadata_size = (field_count * field_metadata_size);
// field_metadata_size = varint_key_field(1 byte) +
// length_field (3 bytes for tile size 255*255*3) + reserved(1 byte);
const size_t kFieldMetadataSize = 5;
size_t metadata_size = packet_.GetDescriptor()->field_count() *
kFieldMetadataSize;
return metadata_size;
}
// geProtobufPacketBuilder
geProtobufPacketBuilder::geProtobufPacketBuilder(size_t _data_size)
: packet_buf_(),
packet_() {
// Allocate memory for packet_buf:
// packet_size = metadata_size + data_size.
size_t packet_buf_size = packet_.GetMetadataSize() + _data_size;
packet_buf_.reserve(packet_buf_size);
}
geProtobufPacketBuilder::~geProtobufPacketBuilder() {
}
void geProtobufPacketBuilder::Build(char **packet_data, unsigned int *packet_size) {
// Serialize EarthImagery packet.
bool serialized = packet_.SerializeToArray(
&packet_buf_[0], packet_buf_.capacity());
// Note: GetCachedSize() is faster then ByteSize(). We use it here because
// ByteSize() was called in SerializeToArray().
size_t serialized_size = packet_.GetCachedSize();
// packet_buf should have at least kCRC32Size bytes available on the end.
std::uint32_t pack_size = serialized_size + kCRC32Size;
if ((!serialized) || (pack_size > packet_buf_.capacity())) {
// Note: can't be reached but just to be sure.
// Reallocate larger buffer and serialize.
// new_buffer_size = pack_size + reserve(1/4 pack_size);
packet_buf_.reserve(pack_size + (pack_size >> 2));
packet_.SerializeToArray(&packet_buf_[0], packet_buf_.capacity());
}
// Clear EarthImagery packet fields.
packet_.Clear();
// Fill in returned values.
*packet_size = pack_size;
*packet_data = &(packet_buf_[0]);
}
| apache-2.0 |
llvm-mirror/clang | test/OpenMP/target_parallel_firstprivate_messages.cpp | 7 | 4888 | // RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd -ferror-limit 100 %s -Wuninitialized
typedef void **omp_allocator_handle_t;
extern const omp_allocator_handle_t omp_default_mem_alloc;
extern const omp_allocator_handle_t omp_large_cap_mem_alloc;
extern const omp_allocator_handle_t omp_const_mem_alloc;
extern const omp_allocator_handle_t omp_high_bw_mem_alloc;
extern const omp_allocator_handle_t omp_low_lat_mem_alloc;
extern const omp_allocator_handle_t omp_cgroup_mem_alloc;
extern const omp_allocator_handle_t omp_pteam_mem_alloc;
extern const omp_allocator_handle_t omp_thread_mem_alloc;
void foo() {
}
bool foobool(int argc) {
return argc;
}
void xxx(int argc) {
int fp; // expected-note {{initialize the variable 'fp' to silence this warning}}
#pragma omp target parallel firstprivate(fp) // expected-warning {{variable 'fp' is uninitialized when used here}}
for (int i = 0; i < 10; ++i)
;
}
struct S1; // expected-note {{declared here}} expected-note{{forward declaration of 'S1'}}
extern S1 a;
class S2 {
mutable int a;
public:
S2():a(0) { }
S2(const S2 &s2):a(s2.a) { }
static float S2s;
static const float S2sc;
};
const float S2::S2sc = 0;
const S2 b;
const S2 ba[5];
class S3 {
int a;
public:
S3():a(0) { }
S3(const S3 &s3):a(s3.a) { }
};
const S3 c;
const S3 ca[5];
extern const int f;
class S4 {
int a;
S4();
S4(const S4 &s4); // expected-note {{implicitly declared private here}}
public:
S4(int v):a(v) { }
};
class S5 {
int a;
S5():a(0) {}
S5(const S5 &s5):a(s5.a) { } // expected-note {{implicitly declared private here}}
public:
S5(int v):a(v) { }
};
S3 h;
#pragma omp threadprivate(h) // expected-note {{defined as threadprivate or thread local}}
namespace A {
double x;
#pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}}
}
namespace B {
using A::x;
}
int main(int argc, char **argv) {
const int d = 5;
const int da[5] = { 0 };
S4 e(4);
S5 g(5);
int i, z;
int &j = i;
static int m;
#pragma omp target parallel firstprivate // expected-error {{expected '(' after 'firstprivate'}}
foo();
#pragma omp target parallel firstprivate ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
foo();
#pragma omp target parallel firstprivate () // expected-error {{expected expression}}
foo();
#pragma omp target parallel firstprivate (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
foo();
#pragma omp target parallel firstprivate (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
foo();
#pragma omp target parallel firstprivate (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
foo();
#pragma omp target parallel firstprivate (argc) allocate , allocate(, allocate(omp_default , allocate(omp_default_mem_alloc, allocate(omp_default_mem_alloc:, allocate(omp_default_mem_alloc: argc, allocate(omp_default_mem_alloc: argv), allocate(argv) // expected-error {{expected '(' after 'allocate'}} expected-error 2 {{expected expression}} expected-error 2 {{expected ')'}} expected-error {{use of undeclared identifier 'omp_default'}} expected-note 2 {{to match this '('}}
foo();
#pragma omp target parallel firstprivate (S1) // expected-error {{'S1' does not refer to a value}}
foo();
#pragma omp target parallel firstprivate (a, b, c, d, f) // expected-error {{firstprivate variable with incomplete type 'S1'}}
foo();
#pragma omp target parallel firstprivate (argv[1]) // expected-error {{expected variable name}}
foo();
#pragma omp target parallel firstprivate(ba) allocate(omp_thread_mem_alloc: ba) // expected-warning {{allocator with the 'thread' trait access has unspecified behavior on 'target parallel' directive}}
foo();
#pragma omp target parallel firstprivate(ca, z)
foo();
#pragma omp target parallel firstprivate(da)
foo();
#pragma omp target parallel firstprivate(S2::S2s)
foo();
#pragma omp target parallel firstprivate(S2::S2sc)
foo();
#pragma omp target parallel firstprivate(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}}
foo();
#pragma omp target parallel firstprivate(h, B::x) // expected-error 2 {{threadprivate or thread local variable cannot be firstprivate}}
foo();
#pragma omp target parallel private(i), firstprivate(i) // expected-error {{private variable cannot be firstprivate}} expected-note{{defined as private}}
foo();
#pragma omp target parallel shared(i)
foo();
#pragma omp target parallel firstprivate(i)
foo();
#pragma omp target parallel firstprivate(j)
foo();
#pragma omp target parallel firstprivate(m)
foo();
return 0;
}
| apache-2.0 |
minhlongdo/bde | groups/bal/balm/balm_defaultmetricsmanager.t.cpp | 7 | 25969 | // balm_defaultmetricsmanager.t.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <balm_defaultmetricsmanager.h>
#include <balm_metricsmanager.h>
#include <balm_metricsample.h>
#include <balm_publisher.h>
#include <balm_streampublisher.h>
#include <bslma_defaultallocatorguard.h>
#include <bslma_managedptr.h>
#include <bslma_testallocator.h>
#include <bsl_cstdlib.h>
#include <bsl_cstring.h>
#include <bsl_iostream.h>
#include <bsl_ostream.h>
#include <bsl_sstream.h>
#include <bslim_testutil.h>
using namespace BloombergLP;
using bsl::cout;
using bsl::endl;
using bsl::flush;
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// The 'balm::DefaultMetricsManager' is a namespace for a related set of
// functions of managing an instance of the 'balm::MetricsManager' they are
// interrelated and must be tested together.
//
// The 'balm::DefaultMetricsManagerScopedGuard' is a simple scoped guard with
// only a single constructor and destructor and can be test with a single
// case.
// ----------------------------------------------------------------------------
// balm::DefaultMetricsManager
// CLASS METHODS
// [ 3] static balm::MetricsManager *manager(balm::MetricsManager *manager);
// [ 1] static balm::MetricsManager *create(bslma::Allocator *);
// [ 2] static balm::MetricsManager *create(ostream& , Allocator *);
// [ 1] static balm::MetricsManager *instance();
// [ 1] static void destroy();
// ----------------------------------------------------------------------------
// balm::DefaultMetricsManagerScopedGuard
// CREATORS
// [ 4] balm::DefaultMetricsManagerScopedGuard(bslma::Allocator *);
// [ 5] balm::DefaultMetricsManagerScopedGuard(bsl::cout, Allocator)
// [ 3] ~balm::DefaultMetricsManagerScopedGuard();
// ----------------------------------------------------------------------------
// [ 6] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST MACRO
// ----------------------------------------------------------------------------
static int testStatus = 0;
static void aSsErT(int c, const char *s, int i)
{
if (c) {
bsl::cout << "Error " << __FILE__ << "(" << i << "): " << s
<< " (failed)" << bsl::endl;
if (0 <= testStatus && testStatus <= 100) ++testStatus;
}
}
// ============================================================================
// STANDARD BDE TEST DRIVER MACROS
// ----------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
// ============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
// ----------------------------------------------------------------------------
typedef balm::DefaultMetricsManagerScopedGuard ObjGuard;
typedef balm::DefaultMetricsManager Obj;
typedef balm::MetricsManager Mgr;
// ============================================================================
// USAGE EXAMPLE
// ----------------------------------------------------------------------------
// ============================================================================
// MAIN PROGRAM
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? bsl::atoi(argv[1]) : 0;
int verbose = argc > 2;
int veryVerbose = argc > 3;
int veryVeryVerbose = argc > 4;
bsl::cout << "TEST " << __FILE__ << " CASE " << test << bsl::endl;;
bslma::TestAllocator testAllocator;
bslma::TestAllocator *Z = &testAllocator;
bslma::TestAllocator defaultAllocator, globalAllocator;
bslma::DefaultAllocatorGuard guard(&defaultAllocator);
switch (test) { case 0: // Zero is always the leading case.
case 6: {
// --------------------------------------------------------------------
// TESTING USAGE EXAMPLE
//
// Concerns:
// The usage example provided in the component header file must
// compile, link, and run on all platforms as shown.
//
// Plan:
// Incorporate usage example from header into driver, remove leading
// comment characters, and replace 'assert' with 'ASSERT'.
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Usage Example"
<< "\n=====================" << endl;
///Usage
///-----
// The following examples demonstrate how to create, configure, and destroy
// the default 'balm::MetricsManager' instance.
//
///Example 1 - Create and Access the Default 'balm::MetricsManager' Instance
///- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// This example demonstrates how to create the default 'balm::MetricManager'
// instance and publish a single metric to the console. See the documentation
// of 'balm_metric' and 'balm_metricsmanager' for information on how to record
// metrics.
//
// First we create a 'balm::DefaultMetricsManagerScopedGuard', which manages
// the lifetime of the default metrics manager instance. At construction, we
// provide the 'balm::DefaultMetricsManagerScopedGuard' an output stream
// ('stdout') to which it will publish metrics. Note that the default metrics
// manager is intended to be created and destroyed by the *owner* of 'main'.
// The instance should be created during the initialization of an application
// (while the task has a single thread) and destroyed just prior to termination
// (when there is similarly a single thread).
//..
// int main(int argc, char *argv[])
{
// ...
balm::DefaultMetricsManagerScopedGuard managerGuard(bsl::cout);
//..
// Once the default instance has been created, it can be accessed using the
// static 'instance' method.
//..
balm::MetricsManager *manager = balm::DefaultMetricsManager::instance();
ASSERT(0 != manager);
//..
// The default metrics manager, by default, is configured with a
// 'balm::StreamPublisher' object that will publish all recorded metrics to the
// consoled. We use the default 'manager' instance to update the collector
// for a single metric, and then publish all metrics.
//..
balm::Collector *myMetric =
manager->collectorRepository().getDefaultCollector(
"MyCategory", "MyMetric");
myMetric->update(10);
manager->publishAll();
// ... rest of program elided ...
}
//..
// The output of this example would look similar to:
//..
// 05FEB2009_19:20:12.697+0000 1 Records
// Elapsed Time: 0.009311s
// MyCategory.MyMetric [ count = 1, total = 10, min = 10, max = 10 ]
//..
// Note that the default metrics manager will be destroyed when 'managerGuard'
// exits this scope and is destroyed. Clients that choose to explicitly call
// 'balm::DefaultMetricsManager::create()' must also explicitly call
// 'balm::DefaultMetricsManager::destroy()'.
ASSERT(0 == balm::DefaultMetricsManager::instance());
} break;
case 5: {
// --------------------------------------------------------------------
// CLASS: balm::DefaultMetricsManagerScopedGuard
//
// Concerns:
// That the scoped guard behaves as described
//
// Plan:
// Create a scoped guard with an allocator, verify memory was
// allocated from that allocator and that the default instance has
// been created, the destroy the guard and verify memory was
// reclaimed and the default instance is 0. Repeat the test
// without passing the optional allocator, verify memory was
// allocated from the global allocator.
//
//
// Testing:
// balm::DefaultMetricsManagerScopedGuard(bsl::cout, Allocator)
//
// --------------------------------------------------------------------
if (verbose) cout
<< endl
<< "balm::DefaultMetricsManagerScopedGuard(cout, ...)" << endl
<< "=================================================" << endl;
bslma::Default::setGlobalAllocator(&globalAllocator);
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 == Obj::instance());
{
// Test with passed allocator.
ObjGuard guard(bsl::cout, Z);
ASSERT(0 < testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 != Obj::instance());
bsl::vector<balm::Publisher *> publishers;
ASSERT(1 == Obj::instance()->findGeneralPublishers(&publishers));
ASSERT(
0 != dynamic_cast<balm::StreamPublisher *>(publishers[0]));
}
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 == Obj::instance());
{
// Test with global allocator.
ObjGuard guard(bsl::cout);
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 < globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 != Obj::instance());
bsl::vector<balm::Publisher *> publishers;
ASSERT(1 == Obj::instance()->findGeneralPublishers(&publishers));
ASSERT(
0 != dynamic_cast<balm::StreamPublisher *>(publishers[0]));
}
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 == Obj::instance());
} break;
case 4: {
// --------------------------------------------------------------------
// CLASS: balm::DefaultMetricsManagerScopedGuard
//
// Concerns:
// That the scoped guard behaves as described
//
// Plan:
// Create a scoped guard with an allocator, verify memory was
// allocated from that allocator and that the default instance has
// been created, the destroy the guard and verify memory was
// reclaimed and the default instance is 0. Repeat the test
// without passing the optional allocator, verify memory was
// allocated from the global allocator.
//
//
// Testing:
// balm::DefaultMetricsManagerScopedGuard(bslma::Allocator *)
// ~balm::DefaultMetricsManagerScopedGuard();
//
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "balm::DefaultMetricsManagerScopedGuard" << endl
<< "======================================" << endl;
bslma::Default::setGlobalAllocator(&globalAllocator);
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 == Obj::instance());
{
// Test with passed allocator.
ObjGuard guard(Z);
ASSERT(0 < testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 != Obj::instance());
ASSERT(Obj::instance() == guard.instance());
bsl::vector<balm::Publisher *> publishers;
ASSERT(0 == Obj::instance()->findGeneralPublishers(&publishers));
}
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 == Obj::instance());
{
// Test with global allocator.
ObjGuard guard;
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 < globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 != Obj::instance());
ASSERT(Obj::instance() == guard.instance());
bsl::vector<balm::Publisher *> publishers;
ASSERT(0 == Obj::instance()->findGeneralPublishers(&publishers));
}
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 == Obj::instance());
} break;
case 3: {
// --------------------------------------------------------------------
// CLASS METHOD TEST: manager
//
// Concerns:
// That the manager function behaves as described.
//
// Plan:
// Invoke 'manager' with both a valid pointer and 0, ensure the
// values returned is correct. Perform that test both with and
// without a default instance of the metrics manager created.
//
// Testing:
// static balm::MetricsManager *manager(balm::MetricsManager *);
//
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "METHOD: manager" << endl
<< "===============" << endl;
bslma::Default::setGlobalAllocator(&globalAllocator);
Mgr x(Z); const Mgr& X = x;
ASSERT(0 == Obj::instance());
ASSERT(0 == Obj::manager(0));
ASSERT(&X == Obj::manager(&x));
ASSERT(0 < testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
Mgr *y = Obj::create();
ASSERT(0 < testAllocator.numBytesInUse());
ASSERT(0 < globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(y == Obj::instance());
ASSERT(y == Obj::manager(0));
ASSERT(&X == Obj::manager(&x));
Obj::destroy();
ASSERT(0 < testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
} break;
case 2: {
// --------------------------------------------------------------------
// CLASS METHOD TEST: create(bool, bslma::Allocator *);
//
// Concerns:
// That the 'create' method behaves as documented
//
// Plan:
//
//
// Testing:
// static balm::MetricsManager *create(ostream& , Allocator *);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "METHOD: create(bsl::ostream& , ...)" << endl
<< "===================================" << endl;
bslma::Default::setGlobalAllocator(&globalAllocator);
ASSERT(0 == Obj::instance());
{
if (verbose) {
bsl::cout
<< "\tTest with an explicit allocator."
<< endl;
}
bslma::TestAllocator streamAllocator;
bslma::ManagedPtr<bsl::ostringstream> ostream(
new (streamAllocator) bsl::ostringstream(),
&streamAllocator);
// Create an instance and verify it is initialized.
Mgr *x = Obj::create(*ostream, Z);
ASSERT(0 != x);
ASSERT(x == Obj::instance());
// Verify memory usage is from the correct allocator.
ASSERT(0 < testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
// Sanity check that the object returned is a valid metrics
// manager.
ASSERT(0 == x->metricRegistry().numMetrics());
ASSERT(&x->metricRegistry() ==
&x->collectorRepository().registry());
// Verify that the metrics manager is initialized with a stream
// publisher.
{
bsl::vector<balm::Publisher *> publishers;
ASSERT(1 == x->findGeneralPublishers(&publishers));
balm::StreamPublisher *streamPublisher =
dynamic_cast<balm::StreamPublisher *>(publishers[0]);
ASSERT(0 != streamPublisher);
balm::Category CA("A");
balm::MetricDescription MA(&CA, "A");
balm::MetricId id(&MA);
balm::MetricRecord record(id);
balm::MetricSample sample;
sample.appendGroup(&record, 1, bsls::TimeInterval(1, 0));
ASSERT("" == ostream->str());
streamPublisher->publish(sample);
ASSERT("" != ostream->str());
}
// Verify release releases the instance
Obj::destroy();
ASSERT(0 == Obj::instance());
ostream.clear();
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
}
ASSERT(0 == Obj::instance());
{
if (verbose) {
bsl::cout << "\tTest with the default allocator"
<< endl;
}
// Create an instance and verify it is initialized.
Mgr *x = Obj::create(bsl::cout);
ASSERT(0 != x);
ASSERT(x == Obj::instance());
// Verify memory usage is from the correct allocator.
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 < globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
// Sanity check that the object returned is a valid metrics
// manager.
ASSERT(0 == x->metricRegistry().numMetrics());
ASSERT(&x->metricRegistry() ==
&x->collectorRepository().registry());
// Verify that the metrics manager is initialized with a stream
// publisher.
{
bsl::vector<balm::Publisher *> publishers;
ASSERT(1 == x->findGeneralPublishers(&publishers));
balm::StreamPublisher *streamPublisher =
dynamic_cast<balm::StreamPublisher *>(publishers[0]);
ASSERT(0 != streamPublisher);
}
// Verify release releases the instance
Obj::destroy();
ASSERT(0 == Obj::instance());
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
}
} break;
case 1: {
// --------------------------------------------------------------------
// PRIMARY CLASS METHOD TEST:
//
// Concerns:
// That the primary functions, 'create', 'instance', and 'release'
// all behave as documented.
//
// Plan:
// Using a supplied allocator, create a default instance for the
// metrics manager, validate the memory is allocated from the
// correct allocator, and that the default instance is valid,
// release the default instance and verify the memory is
// reclaimed. Perform the same test without supplying an allocator
// (using the global allocator).
//
// Testing:
// static balm::MetricsManager *create(bslma::Allocator *);
// static balm::MetricsManager *instance();
// static void destroy();
//
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "PRIMARY CLASS METHOD TEST" << endl
<< "=========================" << endl;
bslma::Default::setGlobalAllocator(&globalAllocator);
ASSERT(0 == Obj::instance());
{
if (verbose) {
bsl::cout
<< "\tCreate a default instance from supplied allocator."
<< endl;
}
// Create an instance and verify it is initialized.
Mgr *x = Obj::create(Z);
ASSERT(0 != x);
ASSERT(x == Obj::instance());
// Verify memory usage is from the correct allocator.
ASSERT(0 < testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
// Verify that the metrics manager is initialized with a stream
// publisher.
{
bsl::vector<balm::Publisher *> publishers;
ASSERT(0 == x->findGeneralPublishers(&publishers));
ASSERT(0 == publishers.size());
}
// Sanity check that the object returned is a valid metrics
// manager.
ASSERT(0 == x->metricRegistry().numMetrics());
ASSERT(&x->metricRegistry() ==
&x->collectorRepository().registry());
// Verify release releases the instance
Obj::destroy();
ASSERT(0 == Obj::instance());
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
}
{
if (verbose) {
bsl::cout
<< "\tCreate a default instance from global allocator."
<< endl;
}
// Create an instance and verify it is initialized.
Mgr *x = Obj::create();
ASSERT(0 != x);
ASSERT(x == Obj::instance());
// Verify memory usage is from the correct allocator.
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 < globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
// Sanity check that the object returned is a valid metrics
// manager.
ASSERT(0 == x->metricRegistry().numMetrics());
ASSERT(&x->metricRegistry() ==
&x->collectorRepository().registry());
// Verify release releases the instance
Obj::destroy();
ASSERT(0 == Obj::instance());
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == globalAllocator.numBytesInUse());
ASSERT(0 == defaultAllocator.numBytesInUse());
}
bslma::Default::setGlobalAllocator(0);
} break;
default: {
bsl::cerr << "WARNING: CASE `" << test << "' NOT FOUND." << bsl::endl;
testStatus = -1;
}
}
if (testStatus > 0) {
bsl::cerr << "Error, non-zero test status = " << testStatus << "."
<< bsl::endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| apache-2.0 |
yurashek/FreeRDP | winpr/libwinpr/synch/test/TestSynchCritical.c | 8 | 8992 |
#include <stdio.h>
#include <winpr/crt.h>
#include <winpr/windows.h>
#include <winpr/synch.h>
#include <winpr/sysinfo.h>
#include <winpr/thread.h>
#include <winpr/interlocked.h>
#define TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS 500
#define TEST_SYNC_CRITICAL_TEST1_RUNS 4
static CRITICAL_SECTION critical;
static LONG gTestValueVulnerable = 0;
static LONG gTestValueSerialized = 0;
static BOOL TestSynchCritical_TriggerAndCheckRaceCondition(HANDLE OwningThread, LONG RecursionCount)
{
/* if called unprotected this will hopefully trigger a race condition ... */
gTestValueVulnerable++;
if (critical.OwningThread != OwningThread)
{
printf("CriticalSection failure: OwningThread is invalid\n");
return FALSE;
}
if (critical.RecursionCount != RecursionCount)
{
printf("CriticalSection failure: RecursionCount is invalid\n");
return FALSE;
}
/* ... which we try to detect using the serialized counter */
if (gTestValueVulnerable != InterlockedIncrement(&gTestValueSerialized))
{
printf("CriticalSection failure: Data corruption detected\n");
return FALSE;
}
return TRUE;
}
/* this thread function shall increment the global dwTestValue until the PBOOL passsed in arg is FALSE */
static DWORD WINAPI TestSynchCritical_Test1(LPVOID arg)
{
int i, j, rc;
HANDLE hThread = (HANDLE) (ULONG_PTR) GetCurrentThreadId();
PBOOL pbContinueRunning = (PBOOL)arg;
while(*pbContinueRunning)
{
EnterCriticalSection(&critical);
rc = 1;
if (!TestSynchCritical_TriggerAndCheckRaceCondition(hThread, rc))
return 1;
/* add some random recursion level */
j = rand()%5;
for (i=0; i<j; i++)
{
if (!TestSynchCritical_TriggerAndCheckRaceCondition(hThread, rc++))
return 2;
EnterCriticalSection(&critical);
}
for (i=0; i<j; i++)
{
if (!TestSynchCritical_TriggerAndCheckRaceCondition(hThread, rc--))
return 2;
LeaveCriticalSection(&critical);
}
if (!TestSynchCritical_TriggerAndCheckRaceCondition(hThread, rc))
return 3;
LeaveCriticalSection(&critical);
}
return 0;
}
/* this thread function tries to call TryEnterCriticalSection while the main thread holds the lock */
static DWORD WINAPI TestSynchCritical_Test2(LPVOID arg)
{
if (TryEnterCriticalSection(&critical)==TRUE)
{
LeaveCriticalSection(&critical);
return 1;
}
return 0;
}
static DWORD WINAPI TestSynchCritical_Main(LPVOID arg)
{
int i, j;
SYSTEM_INFO sysinfo;
DWORD dwPreviousSpinCount;
DWORD dwSpinCount;
DWORD dwSpinCountExpected;
HANDLE hMainThread;
HANDLE* hThreads;
HANDLE hThread;
DWORD dwThreadCount;
DWORD dwThreadExitCode;
BOOL bTest1Running;
PBOOL pbThreadTerminated = (PBOOL)arg;
GetNativeSystemInfo(&sysinfo);
hMainThread = (HANDLE) (ULONG_PTR) GetCurrentThreadId();
/**
* Test SpinCount in SetCriticalSectionSpinCount, InitializeCriticalSectionEx and InitializeCriticalSectionAndSpinCount
* SpinCount must be forced to be zero on on uniprocessor systems and on systems
* where WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT is defined
*/
dwSpinCount = 100;
InitializeCriticalSectionEx(&critical, dwSpinCount, 0);
while(--dwSpinCount)
{
dwPreviousSpinCount = SetCriticalSectionSpinCount(&critical, dwSpinCount);
dwSpinCountExpected = 0;
#if !defined(WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT)
if (sysinfo.dwNumberOfProcessors > 1)
dwSpinCountExpected = dwSpinCount+1;
#endif
if (dwPreviousSpinCount != dwSpinCountExpected)
{
printf("CriticalSection failure: SetCriticalSectionSpinCount returned %"PRIu32" (expected: %"PRIu32")\n", dwPreviousSpinCount, dwSpinCountExpected);
goto fail;
}
DeleteCriticalSection(&critical);
if (dwSpinCount%2==0)
InitializeCriticalSectionAndSpinCount(&critical, dwSpinCount);
else
InitializeCriticalSectionEx(&critical, dwSpinCount, 0);
}
DeleteCriticalSection(&critical);
/**
* Test single-threaded recursive TryEnterCriticalSection/EnterCriticalSection/LeaveCriticalSection
*
*/
InitializeCriticalSection(&critical);
for (i = 0; i < 1000; i++)
{
if (critical.RecursionCount != i)
{
printf("CriticalSection failure: RecursionCount field is %"PRId32" instead of %d.\n", critical.RecursionCount, i);
goto fail;
}
if (i%2==0)
{
EnterCriticalSection(&critical);
}
else
{
if (TryEnterCriticalSection(&critical) == FALSE)
{
printf("CriticalSection failure: TryEnterCriticalSection failed where it should not.\n");
goto fail;
}
}
if (critical.OwningThread != hMainThread)
{
printf("CriticalSection failure: Could not verify section ownership (loop index=%d).\n", i);
goto fail;
}
}
while (--i >= 0)
{
LeaveCriticalSection(&critical);
if (critical.RecursionCount != i)
{
printf("CriticalSection failure: RecursionCount field is %"PRId32" instead of %d.\n", critical.RecursionCount, i);
goto fail;
}
if (critical.OwningThread != (HANDLE)(i ? hMainThread : NULL))
{
printf("CriticalSection failure: Could not verify section ownership (loop index=%d).\n", i);
goto fail;
}
}
DeleteCriticalSection(&critical);
/**
* Test using multiple threads modifying the same value
*/
dwThreadCount = sysinfo.dwNumberOfProcessors > 1 ? sysinfo.dwNumberOfProcessors : 2;
hThreads = (HANDLE*) calloc(dwThreadCount, sizeof(HANDLE));
if (!hThreads)
{
printf("Problem allocating memory\n");
goto fail;
}
for (j = 0; j < TEST_SYNC_CRITICAL_TEST1_RUNS; j++)
{
dwSpinCount = j * 1000;
InitializeCriticalSectionAndSpinCount(&critical, dwSpinCount);
gTestValueVulnerable = 0;
gTestValueSerialized = 0;
/* the TestSynchCritical_Test1 threads shall run until bTest1Running is FALSE */
bTest1Running = TRUE;
for (i = 0; i < (int) dwThreadCount; i++)
{
if (!(hThreads[i] = CreateThread(NULL, 0, TestSynchCritical_Test1, &bTest1Running, 0, NULL)))
{
printf("CriticalSection failure: Failed to create test_1 thread #%d\n", i);
goto fail;
}
}
/* let it run for TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS ... */
Sleep(TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS);
bTest1Running = FALSE;
for (i = 0; i < (int) dwThreadCount; i++)
{
if (WaitForSingleObject(hThreads[i], INFINITE) != WAIT_OBJECT_0)
{
printf("CriticalSection failure: Failed to wait for thread #%d\n", i);
goto fail;
}
GetExitCodeThread(hThreads[i], &dwThreadExitCode);
if(dwThreadExitCode != 0)
{
printf("CriticalSection failure: Thread #%d returned error code %"PRIu32"\n", i, dwThreadExitCode);
goto fail;
}
CloseHandle(hThreads[i]);
}
if (gTestValueVulnerable != gTestValueSerialized)
{
printf("CriticalSection failure: unexpected test value %"PRId32" (expected %"PRId32")\n", gTestValueVulnerable, gTestValueSerialized);
goto fail;
}
DeleteCriticalSection(&critical);
}
free(hThreads);
/**
* TryEnterCriticalSection in thread must fail if we hold the lock in the main thread
*/
InitializeCriticalSection(&critical);
if (TryEnterCriticalSection(&critical) == FALSE)
{
printf("CriticalSection failure: TryEnterCriticalSection unexpectedly failed.\n");
goto fail;
}
/* This thread tries to call TryEnterCriticalSection which must fail */
if (!(hThread = CreateThread(NULL, 0, TestSynchCritical_Test2, NULL, 0, NULL)))
{
printf("CriticalSection failure: Failed to create test_2 thread\n");
goto fail;
}
if (WaitForSingleObject(hThread, INFINITE) != WAIT_OBJECT_0)
{
printf("CriticalSection failure: Failed to wait for thread\n");
goto fail;
}
GetExitCodeThread(hThread, &dwThreadExitCode);
if(dwThreadExitCode != 0)
{
printf("CriticalSection failure: Thread returned error code %"PRIu32"\n", dwThreadExitCode);
goto fail;
}
CloseHandle(hThread);
*pbThreadTerminated = TRUE; /* requ. for winpr issue, see below */
return 0;
fail:
*pbThreadTerminated = TRUE; /* requ. for winpr issue, see below */
return 1;
}
int TestSynchCritical(int argc, char* argv[])
{
BOOL bThreadTerminated = FALSE;
HANDLE hThread;
DWORD dwThreadExitCode;
DWORD dwDeadLockDetectionTimeMs;
DWORD i;
dwDeadLockDetectionTimeMs = 2 * TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS * TEST_SYNC_CRITICAL_TEST1_RUNS;
printf("Deadlock will be assumed after %"PRIu32" ms.\n", dwDeadLockDetectionTimeMs);
if (!(hThread = CreateThread(NULL, 0, TestSynchCritical_Main, &bThreadTerminated, 0, NULL)))
{
printf("CriticalSection failure: Failed to create main thread\n");
return -1;
}
/**
* We have to be able to detect dead locks in this test.
* At the time of writing winpr's WaitForSingleObject has not implemented timeout for thread wait
*
* Workaround checking the value of bThreadTerminated which is passed in the thread arg
*/
for (i = 0; i < dwDeadLockDetectionTimeMs; i += 100)
{
if (bThreadTerminated)
break;
Sleep(100);
}
if (!bThreadTerminated)
{
printf("CriticalSection failure: Possible dead lock detected\n");
return -1;
}
GetExitCodeThread(hThread, &dwThreadExitCode);
CloseHandle(hThread);
if (dwThreadExitCode != 0)
{
return -1;
}
return 0;
}
| apache-2.0 |
llvm-mirror/libcxx | test/std/diagnostics/syserr/syserr.hash/error_code.pass.cpp | 10 | 1133 | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <functional>
// template <class T>
// struct hash
// : public unary_function<T, size_t>
// {
// size_t operator()(T val) const;
// };
#include <system_error>
#include <cassert>
#include <type_traits>
#include "test_macros.h"
void
test(int i)
{
typedef std::error_code T;
typedef std::hash<T> H;
static_assert((std::is_same<H::argument_type, T>::value), "" );
static_assert((std::is_same<H::result_type, std::size_t>::value), "" );
ASSERT_NOEXCEPT(H()(T()));
H h;
T ec(i, std::system_category());
const std::size_t result = h(ec);
LIBCPP_ASSERT(result == static_cast<std::size_t>(i));
((void)result); // Prevent unused warning
}
int main(int, char**)
{
test(0);
test(2);
test(10);
return 0;
}
| apache-2.0 |
qbit/es-operating-system | libraries/webkit/es/WebCore/platform/es/PasteboardES.cpp | 12 | 2739 | /*
* Copyright (c) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 "config.h"
#include "Pasteboard.h"
#include "DocumentFragment.h"
#include "Frame.h"
#include "NotImplemented.h"
#include "Range.h"
namespace WebCore {
Pasteboard::Pasteboard()
{
notImplemented();
}
Pasteboard* Pasteboard::generalPasteboard()
{
notImplemented();
static Pasteboard* pasteboard = new Pasteboard();
return pasteboard;
}
void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, Frame* frame)
{
notImplemented();
}
void Pasteboard::writeURL(const KURL& url, const String&, Frame* frame)
{
notImplemented();
}
void Pasteboard::writeImage(Node* node, const KURL&, const String&)
{
notImplemented();
}
void Pasteboard::clear()
{
notImplemented();
}
bool Pasteboard::canSmartReplace()
{
notImplemented();
return false;
}
PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame* frame, PassRefPtr<Range> context,
bool allowPlainText, bool& chosePlainText)
{
notImplemented();
return 0;
}
String Pasteboard::plainText(Frame* frame)
{
notImplemented();
}
} // namespace WebCore
| apache-2.0 |
xinzweb/gpdb | src/backend/access/appendonly/test/aomd_test.c | 12 | 7484 | #include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include "cmockery.h"
#include "postgres.h"
#include "access/htup_details.h"
#include "utils/memutils.h"
#include "access/appendonlywriter.h"
#include "catalog/pg_tablespace.h"
#define PATH_TO_DATA_FILE "/tmp/md_test/1234"
#define MAX_SEGNO_FILES (MAX_AOREL_CONCURRENCY * MaxHeapAttributeNumber)
static bool file_present[MAX_SEGNO_FILES];
static int num_unlink_called = 0;
static bool unlink_passing = true;
static void
setup_test_structures()
{
num_unlink_called = 0;
memset(file_present, false, sizeof(file_present));
unlink_passing = true;
}
/*
*******************************************************************************
* Mocking access and unlink for unittesting
*******************************************************************************
*/
#undef unlink
#define unlink mock_unlink
static int
mock_unlink(const char *path)
{
int ec = 0;
u_int segfile = 0; /* parse the path */
const char *tmp_path = path + strlen(PATH_TO_DATA_FILE) + 1;
if (strcmp(tmp_path, "") != 0)
{
segfile = atoi(tmp_path);
}
if (!file_present[segfile])
{
ec = -1;
errno = ENOENT;
}
else
{
num_unlink_called++;
}
#if 0
elog(WARNING, "UNLINK %s %d num_times_called=%d unlink_passing %d\n",
path, segfile, num_unlink_called, unlink_passing);
#endif
return ec;
}
/*
*******************************************************************************
*/
#include "../aomd.c"
static void
test__AOSegmentFilePathNameLen(void **state)
{
RelationData reldata;
char *basepath = "base/21381/123";
reldata.rd_node.relNode = 123;
reldata.rd_node.spcNode = DEFAULTTABLESPACE_OID;
reldata.rd_node.dbNode = 21381;
reldata.rd_backend = -1;
int r = AOSegmentFilePathNameLen(&reldata);
assert_in_range(r, strlen(basepath) + 3, strlen(basepath) + 10);
}
static void
test__FormatAOSegmentFileName(void **state)
{
char *basepath = "base/21381/123";
int32 fileSegNo;
char filepathname[256];
/* seg 0, no columns */
FormatAOSegmentFileName(basepath, 0, -1, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123");
assert_int_equal(fileSegNo, 0);
/* seg 1, no columns */
FormatAOSegmentFileName(basepath, 1, -1, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123.1");
assert_int_equal(fileSegNo, 1);
/* seg 0, column 1 */
FormatAOSegmentFileName(basepath, 0, 1, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123.128");
assert_int_equal(fileSegNo, 128);
/* seg 1, column 1 */
FormatAOSegmentFileName(basepath, 1, 1, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123.129");
assert_int_equal(fileSegNo, 129);
/* seg 0, column 2 */
FormatAOSegmentFileName(basepath, 0, 2, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123.256");
assert_int_equal(fileSegNo, 256);
}
static void
test__MakeAOSegmentFileName(void **state)
{
int32 fileSegNo;
char filepathname[256];
RelationData reldata;
reldata.rd_node.relNode = 123;
reldata.rd_node.spcNode = DEFAULTTABLESPACE_OID;
reldata.rd_node.dbNode = 21381;
reldata.rd_backend = -1;
/* seg 0, no columns */
MakeAOSegmentFileName(&reldata, 0, -1, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123");
assert_int_equal(fileSegNo, 0);
/* seg 1, no columns */
MakeAOSegmentFileName(&reldata, 1, -1, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123.1");
assert_int_equal(fileSegNo, 1);
/* seg 0, column 1 */
MakeAOSegmentFileName(&reldata, 0, 1, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123.128");
assert_int_equal(fileSegNo, 128);
/* seg 1, column 1 */
MakeAOSegmentFileName(&reldata, 1, 1, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123.129");
assert_int_equal(fileSegNo, 129);
/* seg 0, column 2 */
MakeAOSegmentFileName(&reldata, 0, 2, &fileSegNo, filepathname);
assert_string_equal(filepathname, "base/21381/123.256");
assert_int_equal(fileSegNo, 256);
}
static void
test_mdunlink_co_no_file_exists(void **state)
{
setup_test_structures();
mdunlink_ao(PATH_TO_DATA_FILE, MAIN_FORKNUM);
// called 1 time checking column
assert_true(num_unlink_called == 0);
return;
}
/* concurrency = 1 max_column = 4 */
static void
test_mdunlink_co_4_columns_1_concurrency(void **state)
{
setup_test_structures();
/* concurrency 1 exists */
file_present[1] = true;
/* max column exists */
file_present[(1*AOTupleId_MultiplierSegmentFileNum) + 1] = true;
file_present[(2*AOTupleId_MultiplierSegmentFileNum) + 1] = true;
file_present[(3*AOTupleId_MultiplierSegmentFileNum) + 1] = true;
mdunlink_ao(PATH_TO_DATA_FILE, MAIN_FORKNUM);
assert_true(num_unlink_called == 4);
assert_true(unlink_passing);
return;
}
/* concurrency = 1,5 max_column = 3 */
static void
test_mdunlink_co_3_columns_2_concurrency(void **state)
{
setup_test_structures();
/* concurrency 1,5 exists */
file_present[1] = true;
file_present[5] = true;
/* Concurrency 1 files */
file_present[(1*AOTupleId_MultiplierSegmentFileNum) + 1] = true;
file_present[(2*AOTupleId_MultiplierSegmentFileNum) + 1] = true;
/* Concurrency 5 files */
file_present[(1*AOTupleId_MultiplierSegmentFileNum) + 5] = true;
file_present[(2*AOTupleId_MultiplierSegmentFileNum) + 5] = true;
mdunlink_ao(PATH_TO_DATA_FILE, MAIN_FORKNUM);
assert_true(num_unlink_called == 6);
assert_true(unlink_passing);
return;
}
static void
test_mdunlink_co_all_columns_full_concurrency(void **state)
{
setup_test_structures();
memset(file_present, true, sizeof(file_present));
mdunlink_ao(PATH_TO_DATA_FILE, MAIN_FORKNUM);
/*
* Note num_unlink_called is one less than total files because .0 is NOT unlinked
* by mdunlink_ao()
*/
assert_true(num_unlink_called == (MAX_SEGNO_FILES - 1));
assert_true(unlink_passing);
return;
}
static void
test_mdunlink_co_one_columns_one_concurrency(void **state)
{
setup_test_structures();
file_present[1] = true;
mdunlink_ao(PATH_TO_DATA_FILE, MAIN_FORKNUM);
assert_true(num_unlink_called == 1);
assert_true(unlink_passing);
return;
}
static void
test_mdunlink_does_not_unlink_for_init_fork(void **state)
{
setup_test_structures();
file_present[1] = true;
mdunlink_ao(PATH_TO_DATA_FILE, INIT_FORKNUM);
assert_true(num_unlink_called == 0);
assert_true(unlink_passing);
return;
}
static void
test_mdunlink_co_one_columns_full_concurrency(void **state)
{
setup_test_structures();
file_present[0] = true;
for (int filenum=1; filenum < MAX_AOREL_CONCURRENCY; filenum++)
file_present[filenum] = true;
mdunlink_ao(PATH_TO_DATA_FILE, MAIN_FORKNUM);
assert_true(num_unlink_called == (MAX_AOREL_CONCURRENCY - 1));
assert_true(unlink_passing);
return;
}
int
main(int argc, char *argv[])
{
cmockery_parse_arguments(argc, argv);
const UnitTest tests[] = {
unit_test(test__AOSegmentFilePathNameLen),
unit_test(test__FormatAOSegmentFileName),
unit_test(test__MakeAOSegmentFileName),
unit_test(test_mdunlink_co_one_columns_full_concurrency),
unit_test(test_mdunlink_co_one_columns_one_concurrency),
unit_test(test_mdunlink_co_all_columns_full_concurrency),
unit_test(test_mdunlink_co_3_columns_2_concurrency),
unit_test(test_mdunlink_co_4_columns_1_concurrency),
unit_test(test_mdunlink_does_not_unlink_for_init_fork),
unit_test(test_mdunlink_co_no_file_exists)
};
MemoryContextInit();
return run_tests(tests);
}
| apache-2.0 |
nvlsianpu/mbed | targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.c | 13 | 63352 | /**
******************************************************************************
* @file stm32f1xx_ll_usb.c
* @author MCD Application Team
* @version V1.0.5
* @date 06-December-2016
* @brief USB Low Layer HAL module driver.
*
* This file provides firmware functions to manage the following
* functionalities of the USB Peripheral Controller:
* + Initialization/de-initialization functions
* + I/O operation functions
* + Peripheral Control functions
* + Peripheral State functions
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
(#) Fill parameters of Init structure in USB_OTG_CfgTypeDef structure.
(#) Call USB_CoreInit() API to initialize the USB Core peripheral.
(#) The upper HAL HCD/PCD driver will call the right routines for its internal processes.
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* 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 STMicroelectronics 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
* @{
*/
/** @defgroup USB_LL USB Low Layer
* @brief Low layer module for USB_FS and USB_OTG_FS drivers
* @{
*/
#if defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED)
#if defined(STM32F102x6) || defined(STM32F102xB) || \
defined(STM32F103x6) || defined(STM32F103xB) || \
defined(STM32F103xE) || defined(STM32F103xG) || \
defined(STM32F105xC) || defined(STM32F107xC)
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
#if defined (USB_OTG_FS)
/** @defgroup USB_LL_Private_Functions USB Low Layer Private Functions
* @{
*/
static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx);
/**
* @}
*/
#endif /* USB_OTG_FS */
/* Exported functions --------------------------------------------------------*/
/** @defgroup USB_LL_Exported_Functions USB Low Layer Exported Functions
* @{
*/
/** @defgroup USB_LL_Exported_Functions_Group1 Peripheral Control functions
* @brief management functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to control the PCD data
transfers.
@endverbatim
* @{
*/
/*==============================================================================
USB OTG FS peripheral available on STM32F105xx and STM32F107xx devices
==============================================================================*/
#if defined (USB_OTG_FS)
/**
* @brief Initializes the USB Core
* @param USBx: USB Instance
* @param cfg : pointer to a USB_OTG_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_CoreInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg)
{
/* Select FS Embedded PHY */
USBx->GUSBCFG |= USB_OTG_GUSBCFG_PHYSEL;
/* Reset after a PHY select and set Host mode */
USB_CoreReset(USBx);
/* Deactivate the power down*/
USBx->GCCFG = USB_OTG_GCCFG_PWRDWN;
return HAL_OK;
}
/**
* @brief USB_EnableGlobalInt
* Enables the controller's Global Int in the AHB Config reg
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx)
{
USBx->GAHBCFG |= USB_OTG_GAHBCFG_GINT;
return HAL_OK;
}
/**
* @brief USB_DisableGlobalInt
* Disable the controller's Global Int in the AHB Config reg
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx)
{
USBx->GAHBCFG &= ~USB_OTG_GAHBCFG_GINT;
return HAL_OK;
}
/**
* @brief USB_SetCurrentMode : Set functional mode
* @param USBx : Selected device
* @param mode : current core mode
* This parameter can be one of the these values:
* @arg USB_DEVICE_MODE: Peripheral mode mode
* @arg USB_HOST_MODE: Host mode
* @arg USB_DRD_MODE: Dual Role Device mode
* @retval HAL status
*/
HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx , USB_ModeTypeDef mode)
{
USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_FHMOD | USB_OTG_GUSBCFG_FDMOD);
if ( mode == USB_HOST_MODE)
{
USBx->GUSBCFG |= USB_OTG_GUSBCFG_FHMOD;
}
else if ( mode == USB_DEVICE_MODE)
{
USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD;
}
HAL_Delay(50);
return HAL_OK;
}
/**
* @brief USB_DevInit : Initializes the USB_OTG controller registers
* for device mode
* @param USBx : Selected device
* @param cfg : pointer to a USB_OTG_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg)
{
uint32_t index = 0;
for (index = 0; index < 15 ; index++)
{
USBx->DIEPTXF[index] = 0;
}
/*Activate VBUS Sensing B */
USBx->GCCFG |= USB_OTG_GCCFG_VBUSBSEN;
/* Restart the Phy Clock */
USBx_PCGCCTL = 0;
/* Device mode configuration */
USBx_DEVICE->DCFG |= DCFG_FRAME_INTERVAL_80;
/* Set Full speed phy */
USB_SetDevSpeed (USBx , USB_OTG_SPEED_FULL);
/* Flush the FIFOs */
USB_FlushTxFifo(USBx , 0x10); /* all Tx FIFOs */
USB_FlushRxFifo(USBx);
/* Clear all pending Device Interrupts */
USBx_DEVICE->DIEPMSK = 0;
USBx_DEVICE->DOEPMSK = 0;
USBx_DEVICE->DAINT = 0xFFFFFFFF;
USBx_DEVICE->DAINTMSK = 0;
for (index = 0; index < cfg.dev_endpoints; index++)
{
if ((USBx_INEP(index)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA)
{
USBx_INEP(index)->DIEPCTL = (USB_OTG_DIEPCTL_EPDIS | USB_OTG_DIEPCTL_SNAK);
}
else
{
USBx_INEP(index)->DIEPCTL = 0;
}
USBx_INEP(index)->DIEPTSIZ = 0;
USBx_INEP(index)->DIEPINT = 0xFF;
}
for (index = 0; index < cfg.dev_endpoints; index++)
{
if ((USBx_OUTEP(index)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA)
{
USBx_OUTEP(index)->DOEPCTL = (USB_OTG_DOEPCTL_EPDIS | USB_OTG_DOEPCTL_SNAK);
}
else
{
USBx_OUTEP(index)->DOEPCTL = 0;
}
USBx_OUTEP(index)->DOEPTSIZ = 0;
USBx_OUTEP(index)->DOEPINT = 0xFF;
}
USBx_DEVICE->DIEPMSK &= ~(USB_OTG_DIEPMSK_TXFURM);
/* Disable all interrupts. */
USBx->GINTMSK = 0;
/* Clear any pending interrupts */
USBx->GINTSTS = 0xBFFFFFFF;
/* Enable the common interrupts */
USBx->GINTMSK |= USB_OTG_GINTMSK_RXFLVLM;
/* Enable interrupts matching to the Device mode ONLY */
USBx->GINTMSK |= (USB_OTG_GINTMSK_USBSUSPM | USB_OTG_GINTMSK_USBRST |\
USB_OTG_GINTMSK_ENUMDNEM | USB_OTG_GINTMSK_IEPINT |\
USB_OTG_GINTMSK_OEPINT | USB_OTG_GINTMSK_IISOIXFRM|\
USB_OTG_GINTMSK_PXFRM_IISOOXFRM | USB_OTG_GINTMSK_WUIM);
if(cfg.Sof_enable)
{
USBx->GINTMSK |= USB_OTG_GINTMSK_SOFM;
}
if (cfg.vbus_sensing_enable == ENABLE)
{
USBx->GINTMSK |= (USB_OTG_GINTMSK_SRQIM | USB_OTG_GINTMSK_OTGINT);
}
return HAL_OK;
}
/**
* @brief USB_OTG_FlushTxFifo : Flush a Tx FIFO
* @param USBx : Selected device
* @param num : FIFO number
* This parameter can be a value from 1 to 15
15 means Flush all Tx FIFOs
* @retval HAL status
*/
HAL_StatusTypeDef USB_FlushTxFifo (USB_OTG_GlobalTypeDef *USBx, uint32_t num )
{
uint32_t count = 0;
USBx->GRSTCTL = ( USB_OTG_GRSTCTL_TXFFLSH |(uint32_t)( num << 6));
do
{
if (++count > 200000)
{
return HAL_TIMEOUT;
}
}
while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_TXFFLSH) == USB_OTG_GRSTCTL_TXFFLSH);
return HAL_OK;
}
/**
* @brief USB_FlushRxFifo : Flush Rx FIFO
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx)
{
uint32_t count = 0;
USBx->GRSTCTL = USB_OTG_GRSTCTL_RXFFLSH;
do
{
if (++count > 200000)
{
return HAL_TIMEOUT;
}
}
while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_RXFFLSH) == USB_OTG_GRSTCTL_RXFFLSH);
return HAL_OK;
}
/**
* @brief USB_SetDevSpeed :Initializes the DevSpd field of DCFG register
* depending the PHY type and the enumeration speed of the device.
* @param USBx : Selected device
* @param speed : device speed
* This parameter can be one of the these values:
* @arg USB_OTG_SPEED_FULL: Full speed mode
* @arg USB_OTG_SPEED_LOW: Low speed mode
* @retval Hal status
*/
HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx , uint8_t speed)
{
USBx_DEVICE->DCFG |= speed;
return HAL_OK;
}
/**
* @brief USB_GetDevSpeed :Return the Dev Speed
* @param USBx : Selected device
* @retval speed : device speed
* This parameter can be one of the these values:
* @arg USB_OTG_SPEED_FULL: Full speed mode
* @arg USB_OTG_SPEED_LOW: Low speed mode
*/
uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx)
{
uint8_t speed = 0;
if (((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ)||
((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_FS_PHY_48MHZ))
{
speed = USB_OTG_SPEED_FULL;
}
else if((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_LS_PHY_6MHZ)
{
speed = USB_OTG_SPEED_LOW;
}
return speed;
}
/**
* @brief Activate and configure an endpoint
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep)
{
if (ep->is_in)
{
/* Assign a Tx FIFO */
ep->tx_fifo_num = ep->num;
}
/* Set initial data PID. */
if (ep->type == EP_TYPE_BULK )
{
ep->data_pid_start = 0;
}
if (ep->is_in == 1)
{
USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num)));
if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_USBAEP) == 0)
{
USBx_INEP(ep->num)->DIEPCTL |= ((ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ ) | (ep->type << 18 ) |\
((ep->num) << 22 ) | (USB_OTG_DIEPCTL_SD0PID_SEVNFRM) | (USB_OTG_DIEPCTL_USBAEP));
}
}
else
{
USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_OEPM & ((1 << (ep->num)) << 16);
if (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_USBAEP) == 0)
{
USBx_OUTEP(ep->num)->DOEPCTL |= ((ep->maxpacket & USB_OTG_DOEPCTL_MPSIZ ) | (ep->type << 18 ) |\
(USB_OTG_DIEPCTL_SD0PID_SEVNFRM)| (USB_OTG_DOEPCTL_USBAEP));
}
}
return HAL_OK;
}
/**
* @brief De-activate and de-initialize an endpoint
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep)
{
/* Read DEPCTLn register */
if (ep->is_in == 1)
{
USBx_DEVICE->DEACHMSK &= ~(USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num))));
USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num))));
USBx_INEP(ep->num)->DIEPCTL &= ~ USB_OTG_DIEPCTL_USBAEP;
}
else
{
USBx_DEVICE->DEACHMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((1 << (ep->num)) << 16));
USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((1 << (ep->num)) << 16));
USBx_OUTEP(ep->num)->DOEPCTL &= ~USB_OTG_DOEPCTL_USBAEP;
}
return HAL_OK;
}
/**
* @brief USB_EPStartXfer : setup and starts a transfer over an EP
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep)
{
uint16_t pktcnt = 0;
/* IN endpoint */
if (ep->is_in == 1)
{
/* Zero Length Packet? */
if (ep->xfer_len == 0)
{
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT);
USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1 << 19)) ;
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ);
}
else
{
/* Program the transfer size and packet count
* as follows: xfersize = N * maxpacket +
* short_packet pktcnt = N + (short_packet
* exist ? 1 : 0)
*/
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ);
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT);
USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (((ep->xfer_len + ep->maxpacket -1)/ ep->maxpacket) << 19)) ;
USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_XFRSIZ & ep->xfer_len);
if (ep->type == EP_TYPE_ISOC)
{
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_MULCNT);
USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_MULCNT & (1 << 29));
}
}
if (ep->type != EP_TYPE_ISOC)
{
/* Enable the Tx FIFO Empty Interrupt for this EP */
if (ep->xfer_len > 0)
{
USBx_DEVICE->DIEPEMPMSK |= 1 << ep->num;
}
}
if (ep->type == EP_TYPE_ISOC)
{
if ((USBx_DEVICE->DSTS & ( 1 << 8 )) == 0)
{
USBx_INEP(ep->num)->DIEPCTL |= USB_OTG_DIEPCTL_SODDFRM;
}
else
{
USBx_INEP(ep->num)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM;
}
}
/* EP enable, IN data in FIFO */
USBx_INEP(ep->num)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA);
if (ep->type == EP_TYPE_ISOC)
{
USB_WritePacket(USBx, ep->xfer_buff, ep->num, ep->xfer_len);
}
}
else /* OUT endpoint */
{
/* Program the transfer size and packet count as follows:
* pktcnt = N
* xfersize = N * maxpacket
*/
USBx_OUTEP(ep->num)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_XFRSIZ);
USBx_OUTEP(ep->num)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_PKTCNT);
if (ep->xfer_len == 0)
{
USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & ep->maxpacket);
USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19));
}
else
{
pktcnt = (ep->xfer_len + ep->maxpacket -1)/ ep->maxpacket;
USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (pktcnt << 19));
USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & (ep->maxpacket * pktcnt));
}
if (ep->type == EP_TYPE_ISOC)
{
if ((USBx_DEVICE->DSTS & ( 1 << 8 )) == 0)
{
USBx_OUTEP(ep->num)->DOEPCTL |= USB_OTG_DOEPCTL_SODDFRM;
}
else
{
USBx_OUTEP(ep->num)->DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM;
}
}
/* EP enable */
USBx_OUTEP(ep->num)->DOEPCTL |= (USB_OTG_DOEPCTL_CNAK | USB_OTG_DOEPCTL_EPENA);
}
return HAL_OK;
}
/**
* @brief USB_EP0StartXfer : setup and starts a transfer over the EP 0
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep)
{
/* IN endpoint */
if (ep->is_in == 1)
{
/* Zero Length Packet? */
if (ep->xfer_len == 0)
{
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT);
USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1 << 19));
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ);
}
else
{
/* Program the transfer size and packet count
* as follows: xfersize = N * maxpacket +
* short_packet pktcnt = N + (short_packet
* exist ? 1 : 0)
*/
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ);
USBx_INEP(ep->num)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT);
if(ep->xfer_len > ep->maxpacket)
{
ep->xfer_len = ep->maxpacket;
}
USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1 << 19));
USBx_INEP(ep->num)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_XFRSIZ & ep->xfer_len);
}
/* Enable the Tx FIFO Empty Interrupt for this EP */
if (ep->xfer_len > 0)
{
USBx_DEVICE->DIEPEMPMSK |= 1 << (ep->num);
}
/* EP enable, IN data in FIFO */
USBx_INEP(ep->num)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA);
}
else /* OUT endpoint */
{
/* Program the transfer size and packet count as follows:
* pktcnt = N
* xfersize = N * maxpacket
*/
USBx_OUTEP(ep->num)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_XFRSIZ);
USBx_OUTEP(ep->num)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_PKTCNT);
if (ep->xfer_len > 0)
{
ep->xfer_len = ep->maxpacket;
}
USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19));
USBx_OUTEP(ep->num)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & (ep->maxpacket));
/* EP enable */
USBx_OUTEP(ep->num)->DOEPCTL |= (USB_OTG_DOEPCTL_CNAK | USB_OTG_DOEPCTL_EPENA);
}
return HAL_OK;
}
/**
* @brief USB_WritePacket : Writes a packet into the Tx FIFO associated
* with the EP/channel
* @param USBx : Selected device
* @param src : pointer to source buffer
* @param ch_ep_num : endpoint or host channel number
* @param len : Number of bytes to write
* @retval HAL status
*/
HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len)
{
uint32_t count32b = 0 , index = 0;
count32b = (len + 3) / 4;
for (index = 0; index < count32b; index++, src += 4)
{
USBx_DFIFO(ch_ep_num) = *((__packed uint32_t *)src);
}
return HAL_OK;
}
/**
* @brief USB_ReadPacket : read a packet from the Tx FIFO associated
* with the EP/channel
* @param USBx : Selected device
* @param dest : destination pointer
* @param len : Number of bytes to read
* @retval pointer to destination buffer
*/
void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len)
{
uint32_t index = 0;
uint32_t count32b = (len + 3) / 4;
for ( index = 0; index < count32b; index++, dest += 4 )
{
*(__packed uint32_t *)dest = USBx_DFIFO(0);
}
return ((void *)dest);
}
/**
* @brief USB_EPSetStall : set a stall condition over an EP
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep)
{
if (ep->is_in == 1)
{
if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_EPENA) == 0)
{
USBx_INEP(ep->num)->DIEPCTL &= ~(USB_OTG_DIEPCTL_EPDIS);
}
USBx_INEP(ep->num)->DIEPCTL |= USB_OTG_DIEPCTL_STALL;
}
else
{
if (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_EPENA) == 0)
{
USBx_OUTEP(ep->num)->DOEPCTL &= ~(USB_OTG_DOEPCTL_EPDIS);
}
USBx_OUTEP(ep->num)->DOEPCTL |= USB_OTG_DOEPCTL_STALL;
}
return HAL_OK;
}
/**
* @brief USB_EPClearStall : Clear a stall condition over an EP
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep)
{
if (ep->is_in == 1)
{
USBx_INEP(ep->num)->DIEPCTL &= ~USB_OTG_DIEPCTL_STALL;
if (ep->type == EP_TYPE_INTR || ep->type == EP_TYPE_BULK)
{
USBx_INEP(ep->num)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; /* DATA0 */
}
}
else
{
USBx_OUTEP(ep->num)->DOEPCTL &= ~USB_OTG_DOEPCTL_STALL;
if (ep->type == EP_TYPE_INTR || ep->type == EP_TYPE_BULK)
{
USBx_OUTEP(ep->num)->DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM; /* DATA0 */
}
}
return HAL_OK;
}
/**
* @brief USB_StopDevice : Stop the usb device mode
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx)
{
uint32_t index = 0;
/* Clear Pending interrupt */
for (index = 0; index < 15 ; index++)
{
USBx_INEP(index)->DIEPINT = 0xFF;
USBx_OUTEP(index)->DOEPINT = 0xFF;
}
USBx_DEVICE->DAINT = 0xFFFFFFFF;
/* Clear interrupt masks */
USBx_DEVICE->DIEPMSK = 0;
USBx_DEVICE->DOEPMSK = 0;
USBx_DEVICE->DAINTMSK = 0;
/* Flush the FIFO */
USB_FlushRxFifo(USBx);
USB_FlushTxFifo(USBx , 0x10 );
return HAL_OK;
}
/**
* @brief USB_SetDevAddress : Stop the usb device mode
* @param USBx : Selected device
* @param address : new device address to be assigned
* This parameter can be a value from 0 to 255
* @retval HAL status
*/
HAL_StatusTypeDef USB_SetDevAddress (USB_OTG_GlobalTypeDef *USBx, uint8_t address)
{
USBx_DEVICE->DCFG &= ~ (USB_OTG_DCFG_DAD);
USBx_DEVICE->DCFG |= (address << 4) & USB_OTG_DCFG_DAD;
return HAL_OK;
}
/**
* @brief USB_DevConnect : Connect the USB device by enabling the pull-up/pull-down
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevConnect (USB_OTG_GlobalTypeDef *USBx)
{
USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_SDIS ;
HAL_Delay(3);
return HAL_OK;
}
/**
* @brief USB_DevDisconnect : Disconnect the USB device by disabling the pull-up/pull-down
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevDisconnect (USB_OTG_GlobalTypeDef *USBx)
{
USBx_DEVICE->DCTL |= USB_OTG_DCTL_SDIS;
HAL_Delay(3);
return HAL_OK;
}
/**
* @brief USB_ReadInterrupts: return the global USB interrupt status
* @param USBx : Selected device
* @retval HAL status
*/
uint32_t USB_ReadInterrupts (USB_OTG_GlobalTypeDef *USBx)
{
uint32_t tmpreg = 0;
tmpreg = USBx->GINTSTS;
tmpreg &= USBx->GINTMSK;
return tmpreg;
}
/**
* @brief USB_ReadDevAllOutEpInterrupt: return the USB device OUT endpoints interrupt status
* @param USBx : Selected device
* @retval HAL status
*/
uint32_t USB_ReadDevAllOutEpInterrupt (USB_OTG_GlobalTypeDef *USBx)
{
uint32_t tmpreg = 0;
tmpreg = USBx_DEVICE->DAINT;
tmpreg &= USBx_DEVICE->DAINTMSK;
return ((tmpreg & 0xffff0000) >> 16);
}
/**
* @brief USB_ReadDevAllInEpInterrupt: return the USB device IN endpoints interrupt status
* @param USBx : Selected device
* @retval HAL status
*/
uint32_t USB_ReadDevAllInEpInterrupt (USB_OTG_GlobalTypeDef *USBx)
{
uint32_t tmpreg = 0;
tmpreg = USBx_DEVICE->DAINT;
tmpreg &= USBx_DEVICE->DAINTMSK;
return ((tmpreg & 0xFFFF));
}
/**
* @brief Returns Device OUT EP Interrupt register
* @param USBx : Selected device
* @param epnum : endpoint number
* This parameter can be a value from 0 to 15
* @retval Device OUT EP Interrupt register
*/
uint32_t USB_ReadDevOutEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum)
{
uint32_t tmpreg = 0;
tmpreg = USBx_OUTEP(epnum)->DOEPINT;
tmpreg &= USBx_DEVICE->DOEPMSK;
return tmpreg;
}
/**
* @brief Returns Device IN EP Interrupt register
* @param USBx : Selected device
* @param epnum : endpoint number
* This parameter can be a value from 0 to 15
* @retval Device IN EP Interrupt register
*/
uint32_t USB_ReadDevInEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum)
{
uint32_t tmpreg = 0, msk = 0, emp = 0;
msk = USBx_DEVICE->DIEPMSK;
emp = USBx_DEVICE->DIEPEMPMSK;
msk |= ((emp >> epnum) & 0x1) << 7;
tmpreg = USBx_INEP(epnum)->DIEPINT & msk;
return tmpreg;
}
/**
* @brief USB_ClearInterrupts: clear a USB interrupt
* @param USBx : Selected device
* @param interrupt : interrupt flag
* @retval None
*/
void USB_ClearInterrupts (USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt)
{
USBx->GINTSTS |= interrupt;
}
/**
* @brief Returns USB core mode
* @param USBx : Selected device
* @retval return core mode : Host or Device
* This parameter can be one of the these values:
* 0 : Host
* 1 : Device
*/
uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx)
{
return ((USBx->GINTSTS ) & 0x1);
}
/**
* @brief Activate EP0 for Setup transactions
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateSetup (USB_OTG_GlobalTypeDef *USBx)
{
/* Set the MPS of the IN EP based on the enumeration speed */
USBx_INEP(0)->DIEPCTL &= ~USB_OTG_DIEPCTL_MPSIZ;
if((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_LS_PHY_6MHZ)
{
USBx_INEP(0)->DIEPCTL |= 3;
}
USBx_DEVICE->DCTL |= USB_OTG_DCTL_CGINAK;
return HAL_OK;
}
/**
* @brief Prepare the EP0 to start the first control setup
* @param USBx : Selected device
* @param psetup : pointer to setup packet
* @retval HAL status
*/
HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t *psetup)
{
USBx_OUTEP(0)->DOEPTSIZ = 0;
USBx_OUTEP(0)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19));
USBx_OUTEP(0)->DOEPTSIZ |= (3 * 8);
USBx_OUTEP(0)->DOEPTSIZ |= USB_OTG_DOEPTSIZ_STUPCNT;
return HAL_OK;
}
/**
* @brief USB_HostInit : Initializes the USB OTG controller registers
* for Host mode
* @param USBx : Selected device
* @param cfg : pointer to a USB_OTG_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_HostInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg)
{
uint32_t index = 0;
/* Restart the Phy Clock */
USBx_PCGCCTL = 0;
/* no VBUS sensing*/
USBx->GCCFG &=~ (USB_OTG_GCCFG_VBUSASEN);
USBx->GCCFG &=~ (USB_OTG_GCCFG_VBUSBSEN);
/* Disable the FS/LS support mode only */
if((cfg.speed == USB_OTG_SPEED_FULL)&&
(USBx != USB_OTG_FS))
{
USBx_HOST->HCFG |= USB_OTG_HCFG_FSLSS;
}
else
{
USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSS);
}
/* Make sure the FIFOs are flushed. */
USB_FlushTxFifo(USBx, 0x10 ); /* all Tx FIFOs */
USB_FlushRxFifo(USBx);
/* Clear all pending HC Interrupts */
for (index = 0; index < cfg.Host_channels; index++)
{
USBx_HC(index)->HCINT = 0xFFFFFFFF;
USBx_HC(index)->HCINTMSK = 0;
}
/* Enable VBUS driving */
USB_DriveVbus(USBx, 1);
HAL_Delay(200);
/* Disable all interrupts. */
USBx->GINTMSK = 0;
/* Clear any pending interrupts */
USBx->GINTSTS = 0xFFFFFFFF;
if(USBx == USB_OTG_FS)
{
/* set Rx FIFO size */
USBx->GRXFSIZ = (uint32_t )0x80;
USBx->DIEPTXF0_HNPTXFSIZ = (uint32_t )(((0x60 << 16)& USB_OTG_NPTXFD) | 0x80);
USBx->HPTXFSIZ = (uint32_t )(((0x40 << 16)& USB_OTG_HPTXFSIZ_PTXFD) | 0xE0);
}
/* Enable the common interrupts */
USBx->GINTMSK |= USB_OTG_GINTMSK_RXFLVLM;
/* Enable interrupts matching to the Host mode ONLY */
USBx->GINTMSK |= (USB_OTG_GINTMSK_PRTIM | USB_OTG_GINTMSK_HCIM |\
USB_OTG_GINTMSK_SOFM |USB_OTG_GINTSTS_DISCINT|\
USB_OTG_GINTMSK_PXFRM_IISOOXFRM | USB_OTG_GINTMSK_WUIM);
return HAL_OK;
}
/**
* @brief USB_InitFSLSPClkSel : Initializes the FSLSPClkSel field of the
* HCFG register on the PHY type and set the right frame interval
* @param USBx : Selected device
* @param freq : clock frequency
* This parameter can be one of the these values:
* HCFG_48_MHZ : Full Speed 48 MHz Clock
* HCFG_6_MHZ : Low Speed 6 MHz Clock
* @retval HAL status
*/
HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx , uint8_t freq)
{
USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSPCS);
USBx_HOST->HCFG |= (freq & USB_OTG_HCFG_FSLSPCS);
if (freq == HCFG_48_MHZ)
{
USBx_HOST->HFIR = (uint32_t)48000;
}
else if (freq == HCFG_6_MHZ)
{
USBx_HOST->HFIR = (uint32_t)6000;
}
return HAL_OK;
}
/**
* @brief USB_OTG_ResetPort : Reset Host Port
* @param USBx : Selected device
* @retval HAL status
* @note : (1)The application must wait at least 10 ms
* before clearing the reset bit.
*/
HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx)
{
__IO uint32_t hprt0 = 0;
hprt0 = USBx_HPRT0;
hprt0 &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\
USB_OTG_HPRT_PENCHNG | USB_OTG_HPRT_POCCHNG );
USBx_HPRT0 = (USB_OTG_HPRT_PRST | hprt0);
HAL_Delay (10); /* See Note #1 */
USBx_HPRT0 = ((~USB_OTG_HPRT_PRST) & hprt0);
return HAL_OK;
}
/**
* @brief USB_DriveVbus : activate or de-activate vbus
* @param state : VBUS state
* This parameter can be one of the these values:
* 0 : VBUS Active
* 1 : VBUS Inactive
* @retval HAL status
*/
HAL_StatusTypeDef USB_DriveVbus (USB_OTG_GlobalTypeDef *USBx, uint8_t state)
{
__IO uint32_t hprt0 = 0;
hprt0 = USBx_HPRT0;
hprt0 &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\
USB_OTG_HPRT_PENCHNG | USB_OTG_HPRT_POCCHNG );
if (((hprt0 & USB_OTG_HPRT_PPWR) == 0 ) && (state == 1 ))
{
USBx_HPRT0 = (USB_OTG_HPRT_PPWR | hprt0);
}
if (((hprt0 & USB_OTG_HPRT_PPWR) == USB_OTG_HPRT_PPWR) && (state == 0 ))
{
USBx_HPRT0 = ((~USB_OTG_HPRT_PPWR) & hprt0);
}
return HAL_OK;
}
/**
* @brief Return Host Core speed
* @param USBx : Selected device
* @retval speed : Host speed
* This parameter can be one of the these values:
* @arg USB_OTG_SPEED_FULL: Full speed mode
* @arg USB_OTG_SPEED_LOW: Low speed mode
*/
uint32_t USB_GetHostSpeed (USB_OTG_GlobalTypeDef *USBx)
{
__IO uint32_t hprt0 = 0;
hprt0 = USBx_HPRT0;
return ((hprt0 & USB_OTG_HPRT_PSPD) >> 17);
}
/**
* @brief Return Host Current Frame number
* @param USBx : Selected device
* @retval current frame number
*/
uint32_t USB_GetCurrentFrame (USB_OTG_GlobalTypeDef *USBx)
{
return (USBx_HOST->HFNUM & USB_OTG_HFNUM_FRNUM);
}
/**
* @brief Initialize a host channel
* @param USBx : Selected device
* @param ch_num : Channel number
* This parameter can be a value from 1 to 15
* @param epnum : Endpoint number
* This parameter can be a value from 1 to 15
* @param dev_address : Current device address
* This parameter can be a value from 0 to 255
* @param speed : Current device speed
* This parameter can be one of the these values:
* @arg USB_OTG_SPEED_FULL: Full speed mode
* @arg USB_OTG_SPEED_LOW: Low speed mode
* @param ep_type : Endpoint Type
* This parameter can be one of the these values:
* @arg EP_TYPE_CTRL: Control type
* @arg EP_TYPE_ISOC: Isochronous type
* @arg EP_TYPE_BULK: Bulk type
* @arg EP_TYPE_INTR: Interrupt type
* @param mps : Max Packet Size
* This parameter can be a value from 0 to32K
* @retval HAL state
*/
HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx,
uint8_t ch_num,
uint8_t epnum,
uint8_t dev_address,
uint8_t speed,
uint8_t ep_type,
uint16_t mps)
{
/* Clear old interrupt conditions for this host channel. */
USBx_HC(ch_num)->HCINT = 0xFFFFFFFF;
/* Enable channel interrupts required for this transfer. */
switch (ep_type)
{
case EP_TYPE_CTRL:
case EP_TYPE_BULK:
USBx_HC(ch_num)->HCINTMSK = USB_OTG_HCINTMSK_XFRCM |\
USB_OTG_HCINTMSK_STALLM |\
USB_OTG_HCINTMSK_TXERRM |\
USB_OTG_HCINTMSK_DTERRM |\
USB_OTG_HCINTMSK_AHBERR |\
USB_OTG_HCINTMSK_NAKM ;
if (epnum & 0x80)
{
USBx_HC(ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_BBERRM;
}
break;
case EP_TYPE_INTR:
USBx_HC(ch_num)->HCINTMSK = USB_OTG_HCINTMSK_XFRCM |\
USB_OTG_HCINTMSK_STALLM |\
USB_OTG_HCINTMSK_TXERRM |\
USB_OTG_HCINTMSK_DTERRM |\
USB_OTG_HCINTMSK_NAKM |\
USB_OTG_HCINTMSK_AHBERR |\
USB_OTG_HCINTMSK_FRMORM ;
if (epnum & 0x80)
{
USBx_HC(ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_BBERRM;
}
break;
case EP_TYPE_ISOC:
USBx_HC(ch_num)->HCINTMSK = USB_OTG_HCINTMSK_XFRCM |\
USB_OTG_HCINTMSK_ACKM |\
USB_OTG_HCINTMSK_AHBERR |\
USB_OTG_HCINTMSK_FRMORM ;
if (epnum & 0x80)
{
USBx_HC(ch_num)->HCINTMSK |= (USB_OTG_HCINTMSK_TXERRM | USB_OTG_HCINTMSK_BBERRM);
}
break;
}
/* Enable the top level host channel interrupt. */
USBx_HOST->HAINTMSK |= (1 << ch_num);
/* Make sure host channel interrupts are enabled. */
USBx->GINTMSK |= USB_OTG_GINTMSK_HCIM;
/* Program the HCCHAR register */
USBx_HC(ch_num)->HCCHAR = (((dev_address << 22) & USB_OTG_HCCHAR_DAD) |\
(((epnum & 0x7F)<< 11) & USB_OTG_HCCHAR_EPNUM)|\
((((epnum & 0x80) == 0x80)<< 15) & USB_OTG_HCCHAR_EPDIR)|\
(((speed == HPRT0_PRTSPD_LOW_SPEED)<< 17) & USB_OTG_HCCHAR_LSDEV)|\
((ep_type << 18) & USB_OTG_HCCHAR_EPTYP)|\
(mps & USB_OTG_HCCHAR_MPSIZ));
if (ep_type == EP_TYPE_INTR)
{
USBx_HC(ch_num)->HCCHAR |= USB_OTG_HCCHAR_ODDFRM ;
}
return HAL_OK;
}
/**
* @brief Start a transfer over a host channel
* @param USBx : Selected device
* @param hc : pointer to host channel structure
* @retval HAL state
*/
#if defined (__CC_ARM) /*!< ARM Compiler */
#pragma O0
#elif defined (__GNUC__) /*!< GNU Compiler */
#pragma GCC optimize ("O0")
#endif /* __CC_ARM */
HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc)
{
uint8_t is_oddframe = 0;
uint16_t len_words = 0;
uint16_t num_packets = 0;
uint16_t max_hc_pkt_count = 256;
uint32_t tmpreg = 0;
/* Compute the expected number of packets associated to the transfer */
if (hc->xfer_len > 0)
{
num_packets = (hc->xfer_len + hc->max_packet - 1) / hc->max_packet;
if (num_packets > max_hc_pkt_count)
{
num_packets = max_hc_pkt_count;
hc->xfer_len = num_packets * hc->max_packet;
}
}
else
{
num_packets = 1;
}
if (hc->ep_is_in)
{
hc->xfer_len = num_packets * hc->max_packet;
}
/* Initialize the HCTSIZn register */
USBx_HC(hc->ch_num)->HCTSIZ = (((hc->xfer_len) & USB_OTG_HCTSIZ_XFRSIZ)) |\
((num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) |\
(((hc->data_pid) << 29) & USB_OTG_HCTSIZ_DPID);
is_oddframe = (USBx_HOST->HFNUM & 0x01) ? 0 : 1;
USBx_HC(hc->ch_num)->HCCHAR &= ~USB_OTG_HCCHAR_ODDFRM;
USBx_HC(hc->ch_num)->HCCHAR |= (is_oddframe << 29);
/* Set host channel enable */
tmpreg = USBx_HC(hc->ch_num)->HCCHAR;
tmpreg &= ~USB_OTG_HCCHAR_CHDIS;
tmpreg |= USB_OTG_HCCHAR_CHENA;
USBx_HC(hc->ch_num)->HCCHAR = tmpreg;
if((hc->ep_is_in == 0) && (hc->xfer_len > 0))
{
switch(hc->ep_type)
{
/* Non periodic transfer */
case EP_TYPE_CTRL:
case EP_TYPE_BULK:
len_words = (hc->xfer_len + 3) / 4;
/* check if there is enough space in FIFO space */
if(len_words > (USBx->HNPTXSTS & 0xFFFF))
{
/* need to process data in nptxfempty interrupt */
USBx->GINTMSK |= USB_OTG_GINTMSK_NPTXFEM;
}
break;
/* Periodic transfer */
case EP_TYPE_INTR:
case EP_TYPE_ISOC:
len_words = (hc->xfer_len + 3) / 4;
/* check if there is enough space in FIFO space */
if(len_words > (USBx_HOST->HPTXSTS & 0xFFFF)) /* split the transfer */
{
/* need to process data in ptxfempty interrupt */
USBx->GINTMSK |= USB_OTG_GINTMSK_PTXFEM;
}
break;
default:
break;
}
/* Write packet into the Tx FIFO. */
USB_WritePacket(USBx, hc->xfer_buff, hc->ch_num, hc->xfer_len);
}
return HAL_OK;
}
/**
* @brief Read all host channel interrupts status
* @param USBx : Selected device
* @retval HAL state
*/
uint32_t USB_HC_ReadInterrupt (USB_OTG_GlobalTypeDef *USBx)
{
return ((USBx_HOST->HAINT) & 0xFFFF);
}
/**
* @brief Halt a host channel
* @param USBx : Selected device
* @param hc_num : Host Channel number
* This parameter can be a value from 1 to 15
* @retval HAL state
*/
HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx , uint8_t hc_num)
{
uint32_t count = 0;
/* Check for space in the request queue to issue the halt. */
if (((USBx_HC(hc_num)->HCCHAR) & (HCCHAR_CTRL << 18)) || ((USBx_HC(hc_num)->HCCHAR) & (HCCHAR_BULK << 18)))
{
USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHDIS;
if ((USBx->HNPTXSTS & 0xFFFF) == 0)
{
USBx_HC(hc_num)->HCCHAR &= ~USB_OTG_HCCHAR_CHENA;
USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
USBx_HC(hc_num)->HCCHAR &= ~USB_OTG_HCCHAR_EPDIR;
do
{
if (++count > 1000)
{
break;
}
}
while ((USBx_HC(hc_num)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA);
}
else
{
USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
}
}
else
{
USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHDIS;
if ((USBx_HOST->HPTXSTS & 0xFFFF) == 0)
{
USBx_HC(hc_num)->HCCHAR &= ~USB_OTG_HCCHAR_CHENA;
USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
USBx_HC(hc_num)->HCCHAR &= ~USB_OTG_HCCHAR_EPDIR;
do
{
if (++count > 1000)
{
break;
}
}
while ((USBx_HC(hc_num)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA);
}
else
{
USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHENA;
}
}
return HAL_OK;
}
/**
* @brief Initiate Do Ping protocol
* @param USBx : Selected device
* @param hc_num : Host Channel number
* This parameter can be a value from 1 to 15
* @retval HAL state
*/
HAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx , uint8_t ch_num)
{
uint8_t num_packets = 1;
uint32_t tmpreg = 0;
USBx_HC(ch_num)->HCTSIZ = ((num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) |\
USB_OTG_HCTSIZ_DOPING;
/* Set host channel enable */
tmpreg = USBx_HC(ch_num)->HCCHAR;
tmpreg &= ~USB_OTG_HCCHAR_CHDIS;
tmpreg |= USB_OTG_HCCHAR_CHENA;
USBx_HC(ch_num)->HCCHAR = tmpreg;
return HAL_OK;
}
/**
* @brief Stop Host Core
* @param USBx : Selected device
* @retval HAL state
*/
HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx)
{
uint8_t index;
uint32_t count = 0;
uint32_t value = 0;
USB_DisableGlobalInt(USBx);
/* Flush FIFO */
USB_FlushTxFifo(USBx, 0x10);
USB_FlushRxFifo(USBx);
/* Flush out any leftover queued requests. */
for (index = 0; index <= 15; index++)
{
value = USBx_HC(index)->HCCHAR;
value |= USB_OTG_HCCHAR_CHDIS;
value &= ~USB_OTG_HCCHAR_CHENA;
value &= ~USB_OTG_HCCHAR_EPDIR;
USBx_HC(index)->HCCHAR = value;
}
/* Halt all channels to put them into a known state. */
for (index = 0; index <= 15; index++)
{
value = USBx_HC(index)->HCCHAR ;
value |= USB_OTG_HCCHAR_CHDIS;
value |= USB_OTG_HCCHAR_CHENA;
value &= ~USB_OTG_HCCHAR_EPDIR;
USBx_HC(index)->HCCHAR = value;
do
{
if (++count > 1000)
{
break;
}
}
while ((USBx_HC(index)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA);
}
/* Clear any pending Host interrupts */
USBx_HOST->HAINT = 0xFFFFFFFF;
USBx->GINTSTS = 0xFFFFFFFF;
USB_EnableGlobalInt(USBx);
return HAL_OK;
}
/**
* @brief USB_ActivateRemoteWakeup : active remote wakeup signalling
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx)
{
if((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS)
{
/* active Remote wakeup signalling */
USBx_DEVICE->DCTL |= USB_OTG_DCTL_RWUSIG;
}
return HAL_OK;
}
/**
* @brief USB_DeActivateRemoteWakeup : de-active remote wakeup signalling
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx)
{
/* active Remote wakeup signalling */
USBx_DEVICE->DCTL &= ~(USB_OTG_DCTL_RWUSIG);
return HAL_OK;
}
#endif /* USB_OTG_FS */
/*==============================================================================
USB Device FS peripheral available on STM32F102xx and STM32F103xx devices
==============================================================================*/
#if defined (USB)
/**
* @brief Initializes the USB Core
* @param USBx: USB Instance
* @param cfg : pointer to a USB_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_CoreInit(USB_TypeDef *USBx, USB_CfgTypeDef cfg)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_EnableGlobalInt
* Enables the controller's Global Int in the AHB Config reg
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_EnableGlobalInt(USB_TypeDef *USBx)
{
uint32_t winterruptmask = 0;
/* Set winterruptmask variable */
winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \
| USB_CNTR_ESOFM | USB_CNTR_RESETM;
/* Set interrupt mask */
USBx->CNTR |= winterruptmask;
return HAL_OK;
}
/**
* @brief USB_DisableGlobalInt
* Disable the controller's Global Int in the AHB Config reg
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DisableGlobalInt(USB_TypeDef *USBx)
{
uint32_t winterruptmask = 0;
/* Set winterruptmask variable */
winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \
| USB_CNTR_ESOFM | USB_CNTR_RESETM;
/* Clear interrupt mask */
USBx->CNTR &= ~winterruptmask;
return HAL_OK;
}
/**
* @brief USB_SetCurrentMode : Set functional mode
* @param USBx : Selected device
* @param mode : current core mode
* This parameter can be one of the these values:
* @arg USB_DEVICE_MODE: Peripheral mode mode
* @retval HAL status
*/
HAL_StatusTypeDef USB_SetCurrentMode(USB_TypeDef *USBx , USB_ModeTypeDef mode)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_DevInit : Initializes the USB controller registers
* for device mode
* @param USBx : Selected device
* @param cfg : pointer to a USB_CfgTypeDef structure that contains
* the configuration information for the specified USBx peripheral.
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevInit (USB_TypeDef *USBx, USB_CfgTypeDef cfg)
{
/* Init Device */
/*CNTR_FRES = 1*/
USBx->CNTR = USB_CNTR_FRES;
/*CNTR_FRES = 0*/
USBx->CNTR = 0;
/*Clear pending interrupts*/
USBx->ISTR = 0;
/*Set Btable Address*/
USBx->BTABLE = BTABLE_ADDRESS;
return HAL_OK;
}
/**
* @brief USB_FlushTxFifo : Flush a Tx FIFO
* @param USBx : Selected device
* @param num : FIFO number
* This parameter can be a value from 1 to 15
15 means Flush all Tx FIFOs
* @retval HAL status
*/
HAL_StatusTypeDef USB_FlushTxFifo (USB_TypeDef *USBx, uint32_t num )
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_FlushRxFifo : Flush Rx FIFO
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_FlushRxFifo(USB_TypeDef *USBx)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief Activate and configure an endpoint
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateEndpoint(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
/* initialize Endpoint */
switch (ep->type)
{
case EP_TYPE_CTRL:
PCD_SET_EPTYPE(USBx, ep->num, USB_EP_CONTROL);
break;
case EP_TYPE_BULK:
PCD_SET_EPTYPE(USBx, ep->num, USB_EP_BULK);
break;
case EP_TYPE_INTR:
PCD_SET_EPTYPE(USBx, ep->num, USB_EP_INTERRUPT);
break;
case EP_TYPE_ISOC:
PCD_SET_EPTYPE(USBx, ep->num, USB_EP_ISOCHRONOUS);
break;
default:
break;
}
PCD_SET_EP_ADDRESS(USBx, ep->num, ep->num);
if (ep->doublebuffer == 0)
{
if (ep->is_in)
{
/*Set the endpoint Transmit buffer address */
PCD_SET_EP_TX_ADDRESS(USBx, ep->num, ep->pmaadress);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
/* Configure NAK status for the Endpoint*/
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK);
}
else
{
/*Set the endpoint Receive buffer address */
PCD_SET_EP_RX_ADDRESS(USBx, ep->num, ep->pmaadress);
/*Set the endpoint Receive buffer counter*/
PCD_SET_EP_RX_CNT(USBx, ep->num, ep->maxpacket);
PCD_CLEAR_RX_DTOG(USBx, ep->num);
/* Configure VALID status for the Endpoint*/
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
}
/*Double Buffer*/
else
{
/*Set the endpoint as double buffered*/
PCD_SET_EP_DBUF(USBx, ep->num);
/*Set buffer address for double buffered mode*/
PCD_SET_EP_DBUF_ADDR(USBx, ep->num,ep->pmaaddr0, ep->pmaaddr1);
if (ep->is_in==0)
{
/* Clear the data toggle bits for the endpoint IN/OUT*/
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
/* Reset value of the data toggle bits for the endpoint out*/
PCD_TX_DTOG(USBx, ep->num);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
/* Clear the data toggle bits for the endpoint IN/OUT*/
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
PCD_RX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint*/
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
return HAL_OK;
}
/**
* @brief De-activate and de-initialize an endpoint
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_DeactivateEndpoint(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
if (ep->doublebuffer == 0)
{
if (ep->is_in)
{
PCD_CLEAR_TX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint*/
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
PCD_CLEAR_RX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint*/
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
/*Double Buffer*/
else
{
if (ep->is_in==0)
{
/* Clear the data toggle bits for the endpoint IN/OUT*/
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
/* Reset value of the data toggle bits for the endpoint out*/
PCD_TX_DTOG(USBx, ep->num);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
}
else
{
/* Clear the data toggle bits for the endpoint IN/OUT*/
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_CLEAR_TX_DTOG(USBx, ep->num);
PCD_RX_DTOG(USBx, ep->num);
/* Configure DISABLE status for the Endpoint*/
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS);
}
}
return HAL_OK;
}
/**
* @brief USB_EPStartXfer : setup and starts a transfer over an EP
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPStartXfer(USB_TypeDef *USBx , USB_EPTypeDef *ep)
{
uint16_t pmabuffer = 0;
uint32_t len = ep->xfer_len;
/* IN endpoint */
if (ep->is_in == 1)
{
/*Multi packet transfer*/
if (ep->xfer_len > ep->maxpacket)
{
len=ep->maxpacket;
ep->xfer_len-=len;
}
else
{
len=ep->xfer_len;
ep->xfer_len =0;
}
/* configure and validate Tx endpoint */
if (ep->doublebuffer == 0)
{
USB_WritePMA(USBx, ep->xfer_buff, ep->pmaadress, len);
PCD_SET_EP_TX_CNT(USBx, ep->num, len);
}
else
{
/* Write the data to the USB endpoint */
if (PCD_GET_ENDPOINT(USBx, ep->num)& USB_EP_DTOG_TX)
{
/* Set the Double buffer counter for pmabuffer1 */
PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr1;
}
else
{
/* Set the Double buffer counter for pmabuffer0 */
PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len);
pmabuffer = ep->pmaaddr0;
}
USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, len);
PCD_FreeUserBuffer(USBx, ep->num, ep->is_in);
}
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_VALID);
}
else /* OUT endpoint */
{
/* Multi packet transfer*/
if (ep->xfer_len > ep->maxpacket)
{
len=ep->maxpacket;
ep->xfer_len-=len;
}
else
{
len=ep->xfer_len;
ep->xfer_len =0;
}
/* configure and validate Rx endpoint */
if (ep->doublebuffer == 0)
{
/*Set RX buffer count*/
PCD_SET_EP_RX_CNT(USBx, ep->num, len);
}
else
{
/*Set the Double buffer counter*/
PCD_SET_EP_DBUF_CNT(USBx, ep->num, ep->is_in, len);
}
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
return HAL_OK;
}
/**
* @brief USB_WritePacket : Writes a packet into the Tx FIFO associated
* with the EP/channel
* @param USBx : Selected device
* @param src : pointer to source buffer
* @param ch_ep_num : endpoint or host channel number
* @param len : Number of bytes to write
* @retval HAL status
*/
HAL_StatusTypeDef USB_WritePacket(USB_TypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_ReadPacket : read a packet from the Tx FIFO associated
* with the EP/channel
* @param USBx : Selected device
* @param dest : destination pointer
* @param len : Number of bytes to read
* @retval pointer to destination buffer
*/
void *USB_ReadPacket(USB_TypeDef *USBx, uint8_t *dest, uint16_t len)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return ((void *)NULL);
}
/**
* @brief USB_EPSetStall : set a stall condition over an EP
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPSetStall(USB_TypeDef *USBx , USB_EPTypeDef *ep)
{
if (ep->num == 0)
{
/* This macro sets STALL status for RX & TX*/
PCD_SET_EP_TXRX_STATUS(USBx, ep->num, USB_EP_RX_STALL, USB_EP_TX_STALL);
}
else
{
if (ep->is_in)
{
PCD_SET_EP_TX_STATUS(USBx, ep->num , USB_EP_TX_STALL);
}
else
{
PCD_SET_EP_RX_STATUS(USBx, ep->num , USB_EP_RX_STALL);
}
}
return HAL_OK;
}
/**
* @brief USB_EPClearStall : Clear a stall condition over an EP
* @param USBx : Selected device
* @param ep: pointer to endpoint structure
* @retval HAL status
*/
HAL_StatusTypeDef USB_EPClearStall(USB_TypeDef *USBx, USB_EPTypeDef *ep)
{
if (ep->is_in)
{
PCD_CLEAR_TX_DTOG(USBx, ep->num);
PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_VALID);
}
else
{
PCD_CLEAR_RX_DTOG(USBx, ep->num);
PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID);
}
return HAL_OK;
}
/**
* @brief USB_StopDevice : Stop the usb device mode
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_StopDevice(USB_TypeDef *USBx)
{
/* disable all interrupts and force USB reset */
USBx->CNTR = USB_CNTR_FRES;
/* clear interrupt status register */
USBx->ISTR = 0;
/* switch-off device */
USBx->CNTR = (USB_CNTR_FRES | USB_CNTR_PDWN);
return HAL_OK;
}
/**
* @brief USB_SetDevAddress : Stop the usb device mode
* @param USBx : Selected device
* @param address : new device address to be assigned
* This parameter can be a value from 0 to 255
* @retval HAL status
*/
HAL_StatusTypeDef USB_SetDevAddress (USB_TypeDef *USBx, uint8_t address)
{
if(address == 0)
{
/* set device address and enable function */
USBx->DADDR = USB_DADDR_EF;
}
return HAL_OK;
}
/**
* @brief USB_DevConnect : Connect the USB device by enabling the pull-up/pull-down
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevConnect (USB_TypeDef *USBx)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_DevDisconnect : Disconnect the USB device by disabling the pull-up/pull-down
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DevDisconnect (USB_TypeDef *USBx)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_ReadInterrupts: return the global USB interrupt status
* @param USBx : Selected device
* @retval HAL status
*/
uint32_t USB_ReadInterrupts (USB_TypeDef *USBx)
{
uint32_t tmpreg = 0;
tmpreg = USBx->ISTR;
return tmpreg;
}
/**
* @brief USB_ReadDevAllOutEpInterrupt: return the USB device OUT endpoints interrupt status
* @param USBx : Selected device
* @retval HAL status
*/
uint32_t USB_ReadDevAllOutEpInterrupt (USB_TypeDef *USBx)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return (0);
}
/**
* @brief USB_ReadDevAllInEpInterrupt: return the USB device IN endpoints interrupt status
* @param USBx : Selected device
* @retval HAL status
*/
uint32_t USB_ReadDevAllInEpInterrupt (USB_TypeDef *USBx)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return (0);
}
/**
* @brief Returns Device OUT EP Interrupt register
* @param USBx : Selected device
* @param epnum : endpoint number
* This parameter can be a value from 0 to 15
* @retval Device OUT EP Interrupt register
*/
uint32_t USB_ReadDevOutEPInterrupt (USB_TypeDef *USBx , uint8_t epnum)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return (0);
}
/**
* @brief Returns Device IN EP Interrupt register
* @param USBx : Selected device
* @param epnum : endpoint number
* This parameter can be a value from 0 to 15
* @retval Device IN EP Interrupt register
*/
uint32_t USB_ReadDevInEPInterrupt (USB_TypeDef *USBx , uint8_t epnum)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return (0);
}
/**
* @brief USB_ClearInterrupts: clear a USB interrupt
* @param USBx : Selected device
* @param interrupt : interrupt flag
* @retval None
*/
void USB_ClearInterrupts (USB_TypeDef *USBx, uint32_t interrupt)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
}
/**
* @brief Prepare the EP0 to start the first control setup
* @param USBx : Selected device
* @param psetup : pointer to setup packet
* @retval HAL status
*/
HAL_StatusTypeDef USB_EP0_OutStart(USB_TypeDef *USBx, uint8_t *psetup)
{
/* NOTE : - This function is not required by USB Device FS peripheral, it is used
only by USB OTG FS peripheral.
- This function is added to ensure compatibility across platforms.
*/
return HAL_OK;
}
/**
* @brief USB_ActivateRemoteWakeup : active remote wakeup signalling
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_TypeDef *USBx)
{
USBx->CNTR |= USB_CNTR_RESUME;
return HAL_OK;
}
/**
* @brief USB_DeActivateRemoteWakeup : de-active remote wakeup signalling
* @param USBx : Selected device
* @retval HAL status
*/
HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_TypeDef *USBx)
{
USBx->CNTR &= ~(USB_CNTR_RESUME);
return HAL_OK;
}
/**
* @brief Copy a buffer from user memory area to packet memory area (PMA)
* @param USBx : pointer to USB register.
* @param pbUsrBuf : pointer to user memory area.
* @param wPMABufAddr : address into PMA.
* @param wNBytes : number of bytes to be copied.
* @retval None
*/
void USB_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes)
{
uint32_t nbytes = (wNBytes + 1) >> 1; /* nbytes = (wNBytes + 1) / 2 */
uint32_t index = 0, temp1 = 0, temp2 = 0;
uint16_t *pdwVal = NULL;
pdwVal = (uint16_t *)(wPMABufAddr * 2 + (uint32_t)USBx + 0x400);
for (index = nbytes; index != 0; index--)
{
temp1 = (uint16_t) * pbUsrBuf;
pbUsrBuf++;
temp2 = temp1 | (uint16_t) * pbUsrBuf << 8;
*pdwVal++ = temp2;
pdwVal++;
pbUsrBuf++;
}
}
/**
* @brief Copy a buffer from user memory area to packet memory area (PMA)
* @param USBx : pointer to USB register.
* @param pbUsrBuf : pointer to user memory area.
* @param wPMABufAddr : address into PMA.
* @param wNBytes : number of bytes to be copied.
* @retval None
*/
void USB_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes)
{
uint32_t nbytes = (wNBytes + 1) >> 1;/* /2*/
uint32_t index = 0;
uint32_t *pdwVal = NULL;
pdwVal = (uint32_t *)(wPMABufAddr * 2 + (uint32_t)USBx + 0x400);
for (index = nbytes; index != 0; index--)
{
*(uint16_t*)pbUsrBuf++ = *pdwVal++;
pbUsrBuf++;
}
}
#endif /* USB */
/**
* @}
*/
/**
* @}
*/
#if defined (USB_OTG_FS)
/** @addtogroup USB_LL_Private_Functions
* @{
*/
/**
* @brief Reset the USB Core (needed after USB clock settings change)
* @param USBx : Selected device
* @retval HAL status
*/
static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx)
{
uint32_t count = 0;
/* Wait for AHB master IDLE state. */
do
{
if (++count > 200000)
{
return HAL_TIMEOUT;
}
}
while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0);
/* Core Soft Reset */
count = 0;
USBx->GRSTCTL |= USB_OTG_GRSTCTL_CSRST;
do
{
if (++count > 200000)
{
return HAL_TIMEOUT;
}
}
while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_CSRST) == USB_OTG_GRSTCTL_CSRST);
return HAL_OK;
}
/**
* @}
*/
#endif /* USB_OTG_FS */
#endif /* STM32F102x6 || STM32F102xB || */
/* STM32F103x6 || STM32F103xB || */
/* STM32F103xE || STM32F103xG || */
/* STM32F105xC || STM32F107xC */
#endif /* defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
infitude/node-gdal | deps/libgdal/gdal/frmts/zlib/uncompr.c | 14 | 2134 | /* uncompr.c -- decompress a memory buffer
* Copyright (C) 1995-2003 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id: uncompr.c 10656 2007-01-19 01:31:01Z mloskot $ */
#define ZLIB_INTERNAL
#include "zlib.h"
/* ===========================================================================
Decompresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total
size of the destination buffer, which must be large enough to hold the
entire uncompressed data. (The size of the uncompressed data must have
been saved previously by the compressor and transmitted to the decompressor
by some mechanism outside the scope of this compression library.)
Upon exit, destLen is the actual size of the compressed buffer.
This function can be used to decompress a whole file at once if the
input file is mmap'ed.
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer, or Z_DATA_ERROR if the input data was corrupted.
*/
int ZEXPORT uncompress (dest, destLen, source, sourceLen)
Bytef *dest;
uLongf *destLen;
const Bytef *source;
uLong sourceLen;
{
z_stream stream;
int err;
stream.next_in = (Bytef*)source;
stream.avail_in = (uInt)sourceLen;
/* Check for source > 64K on 16-bit machine: */
if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
stream.next_out = dest;
stream.avail_out = (uInt)*destLen;
if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
err = inflateInit(&stream);
if (err != Z_OK) return err;
err = inflate(&stream, Z_FINISH);
if (err != Z_STREAM_END) {
inflateEnd(&stream);
if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
return Z_DATA_ERROR;
return err;
}
*destLen = stream.total_out;
err = inflateEnd(&stream);
return err;
}
| apache-2.0 |
hezlog/rt-thread | bsp/stm32/stm32mp157a-st-discovery/board/ports/timer_sample.c | 16 | 3909 | /*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-07-27 thread-liu first version
*/
#include <board.h>
#if defined(BSP_USING_TIM14) && defined(BSP_USING_ADC2)
#include <rtthread.h>
#include <rtdevice.h>
#define HWTIMER_DEV_NAME "timer14"
#define HWADC_DEV_NAME "adc2"
#define REFER_VOLTAGE 330 /* voltage reference */
#define CONVERT_BITS (1 << 12) /* Conversion digit */
#define ADC_DEV_CHANNEL 6
static rt_adc_device_t adc_dev = RT_NULL;
static rt_err_t timeout_cb(rt_device_t dev, rt_size_t size)
{
rt_uint32_t value = 0 , vol = 0;
/* read adc value */
value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);
rt_kprintf("the value is :%d \n", value);
vol = value * REFER_VOLTAGE / CONVERT_BITS;
rt_kprintf("the voltage is :%d.%02d \n", vol / 100, vol % 100);
return 0;
}
static int hwtimer_stop(void)
{
rt_err_t ret = RT_EOK;
rt_device_t hw_dev = RT_NULL;
hw_dev = rt_device_find(HWTIMER_DEV_NAME);
if (hw_dev == RT_NULL)
{
rt_kprintf("hwtimer sample run failed! can't find %s device!\n", HWTIMER_DEV_NAME);
return RT_ERROR;
}
ret = rt_device_close(hw_dev);
if (ret != RT_EOK)
{
rt_kprintf("close %s device failed!\n", HWTIMER_DEV_NAME);
return ret;
}
/* close adc channel */
ret = rt_adc_disable(adc_dev, ADC_DEV_CHANNEL);
return ret;
}
static int hwtimer_start(void)
{
rt_err_t ret = RT_EOK;
rt_hwtimerval_t timeout_s;
rt_device_t hw_dev = RT_NULL;
rt_hwtimer_mode_t mode;
hw_dev = rt_device_find(HWTIMER_DEV_NAME);
if (hw_dev == RT_NULL)
{
rt_kprintf("hwtimer sample run failed! can't find %s device!\n", HWTIMER_DEV_NAME);
return RT_ERROR;
}
/* find adc dev */
adc_dev = (rt_adc_device_t)rt_device_find(HWADC_DEV_NAME);
if (adc_dev == RT_NULL)
{
rt_kprintf("hwtimer sample run failed! can't find %s device!\n", HWADC_DEV_NAME);
return RT_ERROR;
}
/* Open the device in read/write mode */
ret = rt_device_open(hw_dev, RT_DEVICE_OFLAG_RDWR);
if (ret != RT_EOK)
{
rt_kprintf("open %s device failed!\n", HWTIMER_DEV_NAME);
return ret;
}
/* Set the timeout callback function */
rt_device_set_rx_indicate(hw_dev, timeout_cb);
/* Set the mode to periodic timer */
mode = HWTIMER_MODE_PERIOD;
ret = rt_device_control(hw_dev, HWTIMER_CTRL_MODE_SET, &mode);
if (ret != RT_EOK)
{
rt_kprintf("set mode failed! ret is :%d\n", ret);
return ret;
}
timeout_s.sec = 5;
timeout_s.usec = 0;
if (rt_device_write(hw_dev, 0, &timeout_s, sizeof(timeout_s)) != sizeof(timeout_s))
{
rt_kprintf("set timeout value failed\n");
return RT_ERROR;
}
rt_thread_mdelay(3500);
rt_device_read(hw_dev, 0, &timeout_s, sizeof(timeout_s));
rt_kprintf("Read: Sec = %d, Usec = %d\n", timeout_s.sec, timeout_s.usec);
/* enable adc channel */
ret = rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);
return ret;
}
static int tim_sample(int argc, char *argv[])
{
if (argc > 1)
{
if (!rt_strcmp(argv[1], "start"))
{
rt_kprintf("tim14 will start\n");
hwtimer_start();
return RT_EOK;
}
else if (!rt_strcmp(argv[1], "stop"))
{
hwtimer_stop();
rt_kprintf("stop tim14 success!\n");
return RT_EOK;
}
else
{
goto _exit;
}
}
_exit:
{
rt_kprintf("Usage:\n");
rt_kprintf("tim_sample start - start TIM14 \n");
rt_kprintf("tim_sample stop - stop TIM14 \n");
}
return RT_ERROR;
}
MSH_CMD_EXPORT(tim_sample, tim sample);
#endif
| apache-2.0 |
osrf/opensplice | examples/dcps/Listener/c/src/CheckStatus.c | 18 | 2443 | /*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. 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.
*
*/
/************************************************************************
* LOGICAL_NAME: CheckStatus.c
* FUNCTION: Implementation of Basic error handling functions for OpenSplice API.
* MODULE: Examples for the C programming language.
* DATE September 2010.
***********************************************************************/
#include "CheckStatus.h"
/* Array to hold the names for all ReturnCodes. */
char *RetCodeName[13] = {
"DDS_RETCODE_OK",
"DDS_RETCODE_ERROR",
"DDS_RETCODE_UNSUPPORTED",
"DDS_RETCODE_BAD_PARAMETER",
"DDS_RETCODE_PRECONDITION_NOT_MET",
"DDS_RETCODE_OUT_OF_RESOURCES",
"DDS_RETCODE_NOT_ENABLED",
"DDS_RETCODE_IMMUTABLE_POLICY",
"DDS_RETCODE_INCONSISTENT_POLICY",
"DDS_RETCODE_ALREADY_DELETED",
"DDS_RETCODE_TIMEOUT",
"DDS_RETCODE_NO_DATA",
"DDS_RETCODE_ILLEGAL_OPERATION" };
/**
* Returns the name of an error code.
**/
char *getErrorName(DDS_ReturnCode_t status)
{
return RetCodeName[status];
}
/**
* Check the return status for errors. If there is an error, then terminate.
**/
void checkStatus(
DDS_ReturnCode_t status,
const char *info ) {
if (status != DDS_RETCODE_OK && status != DDS_RETCODE_NO_DATA) {
fprintf(stderr, "\n Error in %s: %s\n", info, getErrorName(status));
exit (1);
}
}
/**
* Check whether a valid handle has been returned. If not, then terminate.
**/
void checkHandle(
void *handle,
const char *info ) {
if (!handle) {
fprintf(stderr, "\n Error in %s: Creation failed: invalid handle\n", info);
exit (1);
}
}
| apache-2.0 |
NixaSoftware/CVis | venv/bin/libs/multi_index/test/test_special_set_ops.cpp | 18 | 2253 | /* Boost.MultiIndex test for special set operations.
*
* Copyright 2003-2013 Joaquin M Lopez Munoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/multi_index for library home page.
*/
#include "test_special_set_ops.hpp"
#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <algorithm>
#include <sstream>
#include "pre_multi_index.hpp"
#include "employee.hpp"
#include <boost/detail/lightweight_test.hpp>
using namespace boost::multi_index;
static int string_to_int(const std::string& str)
{
std::istringstream iss(str);
int res;
iss>>res;
return res;
}
struct comp_int_string
{
bool operator()(int x,const std::string& y)const
{
return x<string_to_int(y);
}
bool operator()(const std::string& x,int y)const
{
return string_to_int(x)<y;
}
};
struct hash_string_as_int
{
int operator()(const std::string& x)const
{
return boost::hash<int>()(string_to_int(x));
}
};
struct eq_string_int
{
bool operator()(int x,const std::string& y)const
{
return x==string_to_int(y);
}
bool operator()(const std::string& x,int y)const
{
return operator()(y,x);
}
};
void test_special_set_ops()
{
employee_set es;
es.insert(employee(0,"Joe",31,1123));
es.insert(employee(1,"Robert",27,5601));
es.insert(employee(2,"John",40,7889));
es.insert(employee(3,"Albert",20,9012));
es.insert(employee(4,"John",57,1002));
std::pair<employee_set_by_ssn::iterator,employee_set_by_ssn::iterator> p=
get<ssn>(es).equal_range(
"7889",hash_string_as_int(),eq_string_int());
BOOST_TEST(std::distance(p.first,p.second)==1&&(p.first)->id==2);
BOOST_TEST(
get<ssn>(es).count(
"5601",hash_string_as_int(),eq_string_int())==1);
BOOST_TEST(
get<ssn>(es).find(
"1123",hash_string_as_int(),eq_string_int())->name=="Joe");
BOOST_TEST(
std::distance(
get<age>(es).lower_bound("27",comp_int_string()),
get<age>(es).upper_bound("40",comp_int_string()))==3);
BOOST_TEST(es.count(2,employee::comp_id())==1);
BOOST_TEST(es.count(5,employee::comp_id())==0);
}
| apache-2.0 |
vworkspace/FreeRDP | winpr/libwinpr/interlocked/test/TestInterlockedAccess.c | 18 | 4000 |
#include <stdio.h>
#include <winpr/crt.h>
#include <winpr/windows.h>
#include <winpr/interlocked.h>
int TestInterlockedAccess(int argc, char* argv[])
{
int index;
LONG* Addend;
LONG* Target;
LONG oldValue;
LONG* Destination;
LONGLONG oldValue64;
LONGLONG* Destination64;
/* InterlockedIncrement */
Addend = _aligned_malloc(sizeof(LONG), sizeof(LONG));
*Addend = 0;
for (index = 0; index < 10; index ++)
InterlockedIncrement(Addend);
if (*Addend != 10)
{
printf("InterlockedIncrement failure: Actual: %d, Expected: %d\n", (int) *Addend, 10);
return -1;
}
/* InterlockedDecrement */
for (index = 0; index < 10; index ++)
InterlockedDecrement(Addend);
if (*Addend != 0)
{
printf("InterlockedDecrement failure: Actual: %d, Expected: %d\n", (int) *Addend, 0);
return -1;
}
/* InterlockedExchange */
Target = _aligned_malloc(sizeof(LONG), sizeof(LONG));
*Target = 0xAA;
oldValue = InterlockedExchange(Target, 0xFF);
if (oldValue != 0xAA)
{
printf("InterlockedExchange failure: Actual: 0x%08X, Expected: 0x%08X\n", (int) oldValue, 0xAA);
return -1;
}
if (*Target != 0xFF)
{
printf("InterlockedExchange failure: Actual: 0x%08X, Expected: 0x%08X\n", (int) *Target, 0xFF);
return -1;
}
/* InterlockedExchangeAdd */
*Addend = 25;
oldValue = InterlockedExchangeAdd(Addend, 100);
if (oldValue != 25)
{
printf("InterlockedExchangeAdd failure: Actual: %d, Expected: %d\n", (int) oldValue, 25);
return -1;
}
if (*Addend != 125)
{
printf("InterlockedExchangeAdd failure: Actual: %d, Expected: %d\n", (int) *Addend, 125);
return -1;
}
/* InterlockedCompareExchange (*Destination == Comparand) */
Destination = _aligned_malloc(sizeof(LONG), sizeof(LONG));
*Destination = 0xAABBCCDD;
oldValue = InterlockedCompareExchange(Destination, 0xCCDDEEFF, 0xAABBCCDD);
if (oldValue != 0xAABBCCDD)
{
printf("InterlockedCompareExchange failure: Actual: 0x%08X, Expected: 0x%08X\n", (int) oldValue, 0xAABBCCDD);
return -1;
}
if (*Destination != 0xCCDDEEFF)
{
printf("InterlockedCompareExchange failure: Actual: 0x%08X, Expected: 0x%08X\n", (int) *Destination, 0xCCDDEEFF);
return -1;
}
/* InterlockedCompareExchange (*Destination != Comparand) */
*Destination = 0xAABBCCDD;
oldValue = InterlockedCompareExchange(Destination, 0xCCDDEEFF, 0x66778899);
if (oldValue != 0xAABBCCDD)
{
printf("InterlockedCompareExchange failure: Actual: 0x%08X, Expected: 0x%08X\n", (int) oldValue, 0xAABBCCDD);
return -1;
}
if (*Destination != 0xAABBCCDD)
{
printf("InterlockedCompareExchange failure: Actual: 0x%08X, Expected: 0x%08X\n", (int) *Destination, 0xAABBCCDD);
return -1;
}
/* InterlockedCompareExchange64 (*Destination == Comparand) */
Destination64 = _aligned_malloc(sizeof(LONGLONG), sizeof(LONGLONG));
*Destination64 = 0x66778899AABBCCDD;
oldValue64 = InterlockedCompareExchange64(Destination64, 0x8899AABBCCDDEEFF, 0x66778899AABBCCDD);
if (oldValue64 != 0x66778899AABBCCDD)
{
printf("InterlockedCompareExchange failure: Actual: %lld, Expected: %lld\n", oldValue64, (LONGLONG) 0x66778899AABBCCDD);
return -1;
}
if (*Destination64 != 0x8899AABBCCDDEEFF)
{
printf("InterlockedCompareExchange failure: Actual: %lld, Expected: %lld\n", *Destination64, (LONGLONG) 0x8899AABBCCDDEEFF);
return -1;
}
/* InterlockedCompareExchange64 (*Destination != Comparand) */
*Destination64 = 0x66778899AABBCCDD;
oldValue64 = InterlockedCompareExchange64(Destination64, 0x8899AABBCCDDEEFF, 12345);
if (oldValue64 != 0x66778899AABBCCDD)
{
printf("InterlockedCompareExchange failure: Actual: %lld, Expected: %lld\n", oldValue64, (LONGLONG) 0x66778899AABBCCDD);
return -1;
}
if (*Destination64 != 0x66778899AABBCCDD)
{
printf("InterlockedCompareExchange failure: Actual: %lld, Expected: %lld\n", *Destination64, (LONGLONG) 0x66778899AABBCCDD);
return -1;
}
_aligned_free(Addend);
_aligned_free(Target);
_aligned_free(Destination);
_aligned_free(Destination64);
return 0;
}
| apache-2.0 |
supriyantomaftuh/watchman | query/base.c | 19 | 3531 | /* Copyright 2013-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include "watchman.h"
/* Basic boolean and compound expressions */
struct w_expr_list {
bool allof;
size_t num;
w_query_expr **exprs;
};
static void dispose_expr(void *data)
{
w_query_expr *expr = data;
w_query_expr_delref(expr);
}
static bool eval_not(struct w_query_ctx *ctx,
struct watchman_file *file,
void *data)
{
w_query_expr *expr = data;
return !w_query_expr_evaluate(expr, ctx, file);
}
static w_query_expr *not_parser(w_query *query, json_t *term)
{
json_t *other;
w_query_expr *other_expr;
/* rigidly require ["not", expr] */
if (!json_is_array(term) || json_array_size(term) != 2) {
query->errmsg = strdup("must use [\"not\", expr]");
return NULL;
}
other = json_array_get(term, 1);
other_expr = w_query_expr_parse(query, other);
if (!other_expr) {
// other expr sets errmsg
return NULL;
}
return w_query_expr_new(eval_not, dispose_expr, other_expr);
}
W_TERM_PARSER("not", not_parser)
static bool eval_bool(struct w_query_ctx *ctx,
struct watchman_file *file,
void *data)
{
unused_parameter(ctx);
unused_parameter(file);
return data ? true : false;
}
static w_query_expr *true_parser(w_query *query, json_t *term)
{
unused_parameter(term);
unused_parameter(query);
return w_query_expr_new(eval_bool, NULL, (void*)1);
}
W_TERM_PARSER("true", true_parser)
static w_query_expr *false_parser(w_query *query, json_t *term)
{
unused_parameter(term);
unused_parameter(query);
return w_query_expr_new(eval_bool, NULL, 0);
}
W_TERM_PARSER("false", false_parser)
static bool eval_list(struct w_query_ctx *ctx,
struct watchman_file *file,
void *data)
{
struct w_expr_list *list = data;
size_t i;
for (i = 0; i < list->num; i++) {
bool res = w_query_expr_evaluate(
list->exprs[i],
ctx, file);
if (!res && list->allof) {
return false;
}
if (res && !list->allof) {
return true;
}
}
return list->allof;
}
static void dispose_list(void *data)
{
struct w_expr_list *list = data;
size_t i;
for (i = 0; i < list->num; i++) {
if (list->exprs[i]) {
w_query_expr_delref(list->exprs[i]);
}
}
free(list->exprs);
free(list);
}
static w_query_expr *parse_list(w_query *query, json_t *term, bool allof)
{
struct w_expr_list *list;
size_t i;
/* don't allow "allof" on its own */
if (!json_is_array(term) || json_array_size(term) < 2) {
query->errmsg = strdup("must use [\"allof\", expr...]");
return NULL;
}
list = calloc(1, sizeof(*list));
if (!list) {
query->errmsg = strdup("out of memory");
return NULL;
}
list->allof = allof;
list->num = json_array_size(term) - 1;
list->exprs = calloc(list->num, sizeof(list->exprs[0]));
for (i = 0; i < list->num; i++) {
w_query_expr *parsed;
json_t *exp = json_array_get(term, i + 1);
parsed = w_query_expr_parse(query, exp);
if (!parsed) {
// other expression parser sets errmsg
dispose_list(list);
return NULL;
}
list->exprs[i] = parsed;
}
return w_query_expr_new(eval_list, dispose_list, list);
}
static w_query_expr *anyof_parser(w_query *query, json_t *term)
{
return parse_list(query, term, false);
}
W_TERM_PARSER("anyof", anyof_parser)
static w_query_expr *allof_parser(w_query *query, json_t *term)
{
return parse_list(query, term, true);
}
W_TERM_PARSER("allof", allof_parser)
/* vim:ts=2:sw=2:et:
*/
| apache-2.0 |
sergecodd/FireFox-OS | B2G/build/libs/host/pseudolocalize.cpp | 23 | 3661 | #include <host/pseudolocalize.h>
using namespace std;
static const char*
pseudolocalize_char(char c)
{
switch (c) {
case 'a': return "\xc4\x83";
case 'b': return "\xcf\x84";
case 'c': return "\xc4\x8b";
case 'd': return "\xc4\x8f";
case 'e': return "\xc4\x99";
case 'f': return "\xc6\x92";
case 'g': return "\xc4\x9d";
case 'h': return "\xd1\x9b";
case 'i': return "\xcf\x8a";
case 'j': return "\xc4\xb5";
case 'k': return "\xc4\xb8";
case 'l': return "\xc4\xba";
case 'm': return "\xe1\xb8\xbf";
case 'n': return "\xd0\xb8";
case 'o': return "\xcf\x8c";
case 'p': return "\xcf\x81";
case 'q': return "\x51";
case 'r': return "\xd2\x91";
case 's': return "\xc5\xa1";
case 't': return "\xd1\x82";
case 'u': return "\xce\xb0";
case 'v': return "\x56";
case 'w': return "\xe1\xba\x85";
case 'x': return "\xd1\x85";
case 'y': return "\xe1\xbb\xb3";
case 'z': return "\xc5\xba";
case 'A': return "\xc3\x85";
case 'B': return "\xce\xb2";
case 'C': return "\xc4\x88";
case 'D': return "\xc4\x90";
case 'E': return "\xd0\x84";
case 'F': return "\xce\x93";
case 'G': return "\xc4\x9e";
case 'H': return "\xc4\xa6";
case 'I': return "\xd0\x87";
case 'J': return "\xc4\xb5";
case 'K': return "\xc4\xb6";
case 'L': return "\xc5\x81";
case 'M': return "\xe1\xb8\xbe";
case 'N': return "\xc5\x83";
case 'O': return "\xce\x98";
case 'P': return "\xcf\x81";
case 'Q': return "\x71";
case 'R': return "\xd0\xaf";
case 'S': return "\xc8\x98";
case 'T': return "\xc5\xa6";
case 'U': return "\xc5\xa8";
case 'V': return "\xce\xbd";
case 'W': return "\xe1\xba\x84";
case 'X': return "\xc3\x97";
case 'Y': return "\xc2\xa5";
case 'Z': return "\xc5\xbd";
default: return NULL;
}
}
/**
* Converts characters so they look like they've been localized.
*
* Note: This leaves escape sequences untouched so they can later be
* processed by ResTable::collectString in the normal way.
*/
string
pseudolocalize_string(const string& source)
{
const char* s = source.c_str();
string result;
const size_t I = source.length();
for (size_t i=0; i<I; i++) {
char c = s[i];
if (c == '\\') {
if (i<I-1) {
result += '\\';
i++;
c = s[i];
switch (c) {
case 'u':
// this one takes up 5 chars
result += string(s+i, 5);
i += 4;
break;
case 't':
case 'n':
case '#':
case '@':
case '?':
case '"':
case '\'':
case '\\':
default:
result += c;
break;
}
} else {
result += c;
}
} else {
const char* p = pseudolocalize_char(c);
if (p != NULL) {
result += p;
} else {
result += c;
}
}
}
//printf("result=\'%s\'\n", result.c_str());
return result;
}
| apache-2.0 |
CapeDrew/DCMTK-ITK | Modules/ThirdParty/VNL/src/vxl/v3p/netlib/lapack/double/dlascl.c | 24 | 14073 | /* lapack/double/dlascl.f -- translated by f2c (version 20050501).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "v3p_netlib.h"
/*< SUBROUTINE DLASCL( TYPE, KL, KU, CFROM, CTO, M, N, A, LDA, INFO ) >*/
/* Subroutine */ int dlascl_(char *type__, integer *kl, integer *ku,
doublereal *cfrom, doublereal *cto, integer *m, integer *n,
doublereal *a, integer *lda, integer *info, ftnlen type_len)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5;
/* Local variables */
integer i__, j, k1, k2, k3, k4;
doublereal mul, cto1;
logical done;
doublereal ctoc;
extern logical lsame_(const char *, const char *, ftnlen, ftnlen);
integer itype;
doublereal cfrom1;
extern doublereal dlamch_(char *, ftnlen);
doublereal cfromc;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen);
doublereal bignum, smlnum;
(void)type_len;
/* -- LAPACK auxiliary routine (version 3.0) -- */
/* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */
/* Courant Institute, Argonne National Lab, and Rice University */
/* February 29, 1992 */
/* .. Scalar Arguments .. */
/*< CHARACTER TYPE >*/
/*< INTEGER INFO, KL, KU, LDA, M, N >*/
/*< DOUBLE PRECISION CFROM, CTO >*/
/* .. */
/* .. Array Arguments .. */
/*< DOUBLE PRECISION A( LDA, * ) >*/
/* .. */
/* Purpose */
/* ======= */
/* DLASCL multiplies the M by N real matrix A by the real scalar */
/* CTO/CFROM. This is done without over/underflow as long as the final */
/* result CTO*A(I,J)/CFROM does not over/underflow. TYPE specifies that */
/* A may be full, upper triangular, lower triangular, upper Hessenberg, */
/* or banded. */
/* Arguments */
/* ========= */
/* TYPE (input) CHARACTER*1 */
/* TYPE indices the storage type of the input matrix. */
/* = 'G': A is a full matrix. */
/* = 'L': A is a lower triangular matrix. */
/* = 'U': A is an upper triangular matrix. */
/* = 'H': A is an upper Hessenberg matrix. */
/* = 'B': A is a symmetric band matrix with lower bandwidth KL */
/* and upper bandwidth KU and with the only the lower */
/* half stored. */
/* = 'Q': A is a symmetric band matrix with lower bandwidth KL */
/* and upper bandwidth KU and with the only the upper */
/* half stored. */
/* = 'Z': A is a band matrix with lower bandwidth KL and upper */
/* bandwidth KU. */
/* KL (input) INTEGER */
/* The lower bandwidth of A. Referenced only if TYPE = 'B', */
/* 'Q' or 'Z'. */
/* KU (input) INTEGER */
/* The upper bandwidth of A. Referenced only if TYPE = 'B', */
/* 'Q' or 'Z'. */
/* CFROM (input) DOUBLE PRECISION */
/* CTO (input) DOUBLE PRECISION */
/* The matrix A is multiplied by CTO/CFROM. A(I,J) is computed */
/* without over/underflow if the final result CTO*A(I,J)/CFROM */
/* can be represented without over/underflow. CFROM must be */
/* nonzero. */
/* M (input) INTEGER */
/* The number of rows of the matrix A. M >= 0. */
/* N (input) INTEGER */
/* The number of columns of the matrix A. N >= 0. */
/* A (input/output) DOUBLE PRECISION array, dimension (LDA,M) */
/* The matrix to be multiplied by CTO/CFROM. See TYPE for the */
/* storage type. */
/* LDA (input) INTEGER */
/* The leading dimension of the array A. LDA >= max(1,M). */
/* INFO (output) INTEGER */
/* 0 - successful exit */
/* <0 - if INFO = -i, the i-th argument had an illegal value. */
/* ===================================================================== */
/* .. Parameters .. */
/*< DOUBLE PRECISION ZERO, ONE >*/
/*< PARAMETER ( ZERO = 0.0D0, ONE = 1.0D0 ) >*/
/* .. */
/* .. Local Scalars .. */
/*< LOGICAL DONE >*/
/*< INTEGER I, ITYPE, J, K1, K2, K3, K4 >*/
/*< DOUBLE PRECISION BIGNUM, CFROM1, CFROMC, CTO1, CTOC, MUL, SMLNUM >*/
/* .. */
/* .. External Functions .. */
/*< LOGICAL LSAME >*/
/*< DOUBLE PRECISION DLAMCH >*/
/*< EXTERNAL LSAME, DLAMCH >*/
/* .. */
/* .. Intrinsic Functions .. */
/*< INTRINSIC ABS, MAX, MIN >*/
/* .. */
/* .. External Subroutines .. */
/*< EXTERNAL XERBLA >*/
/* .. */
/* .. Executable Statements .. */
/* Test the input arguments */
/*< INFO = 0 >*/
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
/* Function Body */
*info = 0;
/*< IF( LSAME( TYPE, 'G' ) ) THEN >*/
if (lsame_(type__, "G", (ftnlen)1, (ftnlen)1)) {
/*< ITYPE = 0 >*/
itype = 0;
/*< ELSE IF( LSAME( TYPE, 'L' ) ) THEN >*/
} else if (lsame_(type__, "L", (ftnlen)1, (ftnlen)1)) {
/*< ITYPE = 1 >*/
itype = 1;
/*< ELSE IF( LSAME( TYPE, 'U' ) ) THEN >*/
} else if (lsame_(type__, "U", (ftnlen)1, (ftnlen)1)) {
/*< ITYPE = 2 >*/
itype = 2;
/*< ELSE IF( LSAME( TYPE, 'H' ) ) THEN >*/
} else if (lsame_(type__, "H", (ftnlen)1, (ftnlen)1)) {
/*< ITYPE = 3 >*/
itype = 3;
/*< ELSE IF( LSAME( TYPE, 'B' ) ) THEN >*/
} else if (lsame_(type__, "B", (ftnlen)1, (ftnlen)1)) {
/*< ITYPE = 4 >*/
itype = 4;
/*< ELSE IF( LSAME( TYPE, 'Q' ) ) THEN >*/
} else if (lsame_(type__, "Q", (ftnlen)1, (ftnlen)1)) {
/*< ITYPE = 5 >*/
itype = 5;
/*< ELSE IF( LSAME( TYPE, 'Z' ) ) THEN >*/
} else if (lsame_(type__, "Z", (ftnlen)1, (ftnlen)1)) {
/*< ITYPE = 6 >*/
itype = 6;
/*< ELSE >*/
} else {
/*< ITYPE = -1 >*/
itype = -1;
/*< END IF >*/
}
/*< IF( ITYPE.EQ.-1 ) THEN >*/
if (itype == -1) {
/*< INFO = -1 >*/
*info = -1;
/*< ELSE IF( CFROM.EQ.ZERO ) THEN >*/
} else if (*cfrom == 0.) {
/*< INFO = -4 >*/
*info = -4;
/*< ELSE IF( M.LT.0 ) THEN >*/
} else if (*m < 0) {
/*< INFO = -6 >*/
*info = -6;
/*< >*/
} else if (*n < 0 || (itype == 4 && *n != *m) || (itype == 5 && *n != *m)) {
/*< INFO = -7 >*/
*info = -7;
/*< ELSE IF( ITYPE.LE.3 .AND. LDA.LT.MAX( 1, M ) ) THEN >*/
} else if (itype <= 3 && *lda < max(1,*m)) {
/*< INFO = -9 >*/
*info = -9;
/*< ELSE IF( ITYPE.GE.4 ) THEN >*/
} else if (itype >= 4) {
/*< IF( KL.LT.0 .OR. KL.GT.MAX( M-1, 0 ) ) THEN >*/
/* Computing MAX */
i__1 = *m - 1;
if (*kl < 0 || *kl > max(i__1,0)) {
/*< INFO = -2 >*/
*info = -2;
/*< >*/
} else /* if(complicated condition) */ {
/* Computing MAX */
i__1 = *n - 1;
if (*ku < 0 || *ku > max(i__1,0) || ((itype == 4 || itype == 5) &&
*kl != *ku)) {
/*< INFO = -3 >*/
*info = -3;
/*< >*/
} else if ((itype == 4 && *lda < *kl + 1) || (itype == 5 && *lda < *
ku + 1) || (itype == 6 && *lda < (*kl << 1) + *ku + 1)) {
/*< INFO = -9 >*/
*info = -9;
/*< END IF >*/
}
}
/*< END IF >*/
}
/*< IF( INFO.NE.0 ) THEN >*/
if (*info != 0) {
/*< CALL XERBLA( 'DLASCL', -INFO ) >*/
i__1 = -(*info);
xerbla_("DLASCL", &i__1, (ftnlen)6);
/*< RETURN >*/
return 0;
/*< END IF >*/
}
/* Quick return if possible */
/*< >*/
if (*n == 0 || *m == 0) {
return 0;
}
/* Get machine parameters */
/*< SMLNUM = DLAMCH( 'S' ) >*/
smlnum = dlamch_("S", (ftnlen)1);
/*< BIGNUM = ONE / SMLNUM >*/
bignum = 1. / smlnum;
/*< CFROMC = CFROM >*/
cfromc = *cfrom;
/*< CTOC = CTO >*/
ctoc = *cto;
/*< 10 CONTINUE >*/
L10:
/*< CFROM1 = CFROMC*SMLNUM >*/
cfrom1 = cfromc * smlnum;
/*< CTO1 = CTOC / BIGNUM >*/
cto1 = ctoc / bignum;
/*< IF( ABS( CFROM1 ).GT.ABS( CTOC ) .AND. CTOC.NE.ZERO ) THEN >*/
if (abs(cfrom1) > abs(ctoc) && ctoc != 0.) {
/*< MUL = SMLNUM >*/
mul = smlnum;
/*< DONE = .FALSE. >*/
done = FALSE_;
/*< CFROMC = CFROM1 >*/
cfromc = cfrom1;
/*< ELSE IF( ABS( CTO1 ).GT.ABS( CFROMC ) ) THEN >*/
} else if (abs(cto1) > abs(cfromc)) {
/*< MUL = BIGNUM >*/
mul = bignum;
/*< DONE = .FALSE. >*/
done = FALSE_;
/*< CTOC = CTO1 >*/
ctoc = cto1;
/*< ELSE >*/
} else {
/*< MUL = CTOC / CFROMC >*/
mul = ctoc / cfromc;
/*< DONE = .TRUE. >*/
done = TRUE_;
/*< END IF >*/
}
/*< IF( ITYPE.EQ.0 ) THEN >*/
if (itype == 0) {
/* Full matrix */
/*< DO 30 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DO 20 I = 1, M >*/
i__2 = *m;
for (i__ = 1; i__ <= i__2; ++i__) {
/*< A( I, J ) = A( I, J )*MUL >*/
a[i__ + j * a_dim1] *= mul;
/*< 20 CONTINUE >*/
/* L20: */
}
/*< 30 CONTINUE >*/
/* L30: */
}
/*< ELSE IF( ITYPE.EQ.1 ) THEN >*/
} else if (itype == 1) {
/* Lower triangular matrix */
/*< DO 50 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DO 40 I = J, M >*/
i__2 = *m;
for (i__ = j; i__ <= i__2; ++i__) {
/*< A( I, J ) = A( I, J )*MUL >*/
a[i__ + j * a_dim1] *= mul;
/*< 40 CONTINUE >*/
/* L40: */
}
/*< 50 CONTINUE >*/
/* L50: */
}
/*< ELSE IF( ITYPE.EQ.2 ) THEN >*/
} else if (itype == 2) {
/* Upper triangular matrix */
/*< DO 70 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DO 60 I = 1, MIN( J, M ) >*/
i__2 = min(j,*m);
for (i__ = 1; i__ <= i__2; ++i__) {
/*< A( I, J ) = A( I, J )*MUL >*/
a[i__ + j * a_dim1] *= mul;
/*< 60 CONTINUE >*/
/* L60: */
}
/*< 70 CONTINUE >*/
/* L70: */
}
/*< ELSE IF( ITYPE.EQ.3 ) THEN >*/
} else if (itype == 3) {
/* Upper Hessenberg matrix */
/*< DO 90 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DO 80 I = 1, MIN( J+1, M ) >*/
/* Computing MIN */
i__3 = j + 1;
i__2 = min(i__3,*m);
for (i__ = 1; i__ <= i__2; ++i__) {
/*< A( I, J ) = A( I, J )*MUL >*/
a[i__ + j * a_dim1] *= mul;
/*< 80 CONTINUE >*/
/* L80: */
}
/*< 90 CONTINUE >*/
/* L90: */
}
/*< ELSE IF( ITYPE.EQ.4 ) THEN >*/
} else if (itype == 4) {
/* Lower half of a symmetric band matrix */
/*< K3 = KL + 1 >*/
k3 = *kl + 1;
/*< K4 = N + 1 >*/
k4 = *n + 1;
/*< DO 110 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DO 100 I = 1, MIN( K3, K4-J ) >*/
/* Computing MIN */
i__3 = k3, i__4 = k4 - j;
i__2 = min(i__3,i__4);
for (i__ = 1; i__ <= i__2; ++i__) {
/*< A( I, J ) = A( I, J )*MUL >*/
a[i__ + j * a_dim1] *= mul;
/*< 100 CONTINUE >*/
/* L100: */
}
/*< 110 CONTINUE >*/
/* L110: */
}
/*< ELSE IF( ITYPE.EQ.5 ) THEN >*/
} else if (itype == 5) {
/* Upper half of a symmetric band matrix */
/*< K1 = KU + 2 >*/
k1 = *ku + 2;
/*< K3 = KU + 1 >*/
k3 = *ku + 1;
/*< DO 130 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DO 120 I = MAX( K1-J, 1 ), K3 >*/
/* Computing MAX */
i__2 = k1 - j;
i__3 = k3;
for (i__ = max(i__2,1); i__ <= i__3; ++i__) {
/*< A( I, J ) = A( I, J )*MUL >*/
a[i__ + j * a_dim1] *= mul;
/*< 120 CONTINUE >*/
/* L120: */
}
/*< 130 CONTINUE >*/
/* L130: */
}
/*< ELSE IF( ITYPE.EQ.6 ) THEN >*/
} else if (itype == 6) {
/* Band matrix */
/*< K1 = KL + KU + 2 >*/
k1 = *kl + *ku + 2;
/*< K2 = KL + 1 >*/
k2 = *kl + 1;
/*< K3 = 2*KL + KU + 1 >*/
k3 = (*kl << 1) + *ku + 1;
/*< K4 = KL + KU + 1 + M >*/
k4 = *kl + *ku + 1 + *m;
/*< DO 150 J = 1, N >*/
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/*< DO 140 I = MAX( K1-J, K2 ), MIN( K3, K4-J ) >*/
/* Computing MAX */
i__3 = k1 - j;
/* Computing MIN */
i__4 = k3, i__5 = k4 - j;
i__2 = min(i__4,i__5);
for (i__ = max(i__3,k2); i__ <= i__2; ++i__) {
/*< A( I, J ) = A( I, J )*MUL >*/
a[i__ + j * a_dim1] *= mul;
/*< 140 CONTINUE >*/
/* L140: */
}
/*< 150 CONTINUE >*/
/* L150: */
}
/*< END IF >*/
}
/*< >*/
if (! done) {
goto L10;
}
/*< RETURN >*/
return 0;
/* End of DLASCL */
/*< END >*/
} /* dlascl_ */
#ifdef __cplusplus
}
#endif
| apache-2.0 |
eile/ITK | Modules/ThirdParty/VNL/src/vxl/v3p/netlib/lapack/single/sgeqr2.c | 24 | 5977 | /* lapack/single/sgeqr2.f -- translated by f2c (version 20050501).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "v3p_netlib.h"
/* Table of constant values */
static integer c__1 = 1;
/*< SUBROUTINE SGEQR2( M, N, A, LDA, TAU, WORK, INFO ) >*/
/* Subroutine */ int sgeqr2_(integer *m, integer *n, real *a, integer *lda,
real *tau, real *work, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3;
/* Local variables */
integer i__, k;
real aii;
extern /* Subroutine */ int slarf_(char *, integer *, integer *, real *,
integer *, real *, real *, integer *, real *, ftnlen), xerbla_(
char *, integer *, ftnlen), slarfg_(integer *, real *, real *,
integer *, real *);
/* -- LAPACK routine (version 3.0) -- */
/* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */
/* Courant Institute, Argonne National Lab, and Rice University */
/* February 29, 1992 */
/* .. Scalar Arguments .. */
/*< INTEGER INFO, LDA, M, N >*/
/* .. */
/* .. Array Arguments .. */
/*< REAL A( LDA, * ), TAU( * ), WORK( * ) >*/
/* .. */
/* Purpose */
/* ======= */
/* SGEQR2 computes a QR factorization of a real m by n matrix A: */
/* A = Q * R. */
/* Arguments */
/* ========= */
/* M (input) INTEGER */
/* The number of rows of the matrix A. M >= 0. */
/* N (input) INTEGER */
/* The number of columns of the matrix A. N >= 0. */
/* A (input/output) REAL array, dimension (LDA,N) */
/* On entry, the m by n matrix A. */
/* On exit, the elements on and above the diagonal of the array */
/* contain the min(m,n) by n upper trapezoidal matrix R (R is */
/* upper triangular if m >= n); the elements below the diagonal, */
/* with the array TAU, represent the orthogonal matrix Q as a */
/* product of elementary reflectors (see Further Details). */
/* LDA (input) INTEGER */
/* The leading dimension of the array A. LDA >= max(1,M). */
/* TAU (output) REAL array, dimension (min(M,N)) */
/* The scalar factors of the elementary reflectors (see Further */
/* Details). */
/* WORK (workspace) REAL array, dimension (N) */
/* INFO (output) INTEGER */
/* = 0: successful exit */
/* < 0: if INFO = -i, the i-th argument had an illegal value */
/* Further Details */
/* =============== */
/* The matrix Q is represented as a product of elementary reflectors */
/* Q = H(1) H(2) . . . H(k), where k = min(m,n). */
/* Each H(i) has the form */
/* H(i) = I - tau * v * v' */
/* where tau is a real scalar, and v is a real vector with */
/* v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), */
/* and tau in TAU(i). */
/* ===================================================================== */
/* .. Parameters .. */
/*< REAL ONE >*/
/*< PARAMETER ( ONE = 1.0E+0 ) >*/
/* .. */
/* .. Local Scalars .. */
/*< INTEGER I, K >*/
/*< REAL AII >*/
/* .. */
/* .. External Subroutines .. */
/*< EXTERNAL SLARF, SLARFG, XERBLA >*/
/* .. */
/* .. Intrinsic Functions .. */
/*< INTRINSIC MAX, MIN >*/
/* .. */
/* .. Executable Statements .. */
/* Test the input arguments */
/*< INFO = 0 >*/
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--tau;
--work;
/* Function Body */
*info = 0;
/*< IF( M.LT.0 ) THEN >*/
if (*m < 0) {
/*< INFO = -1 >*/
*info = -1;
/*< ELSE IF( N.LT.0 ) THEN >*/
} else if (*n < 0) {
/*< INFO = -2 >*/
*info = -2;
/*< ELSE IF( LDA.LT.MAX( 1, M ) ) THEN >*/
} else if (*lda < max(1,*m)) {
/*< INFO = -4 >*/
*info = -4;
/*< END IF >*/
}
/*< IF( INFO.NE.0 ) THEN >*/
if (*info != 0) {
/*< CALL XERBLA( 'SGEQR2', -INFO ) >*/
i__1 = -(*info);
xerbla_("SGEQR2", &i__1, (ftnlen)6);
/*< RETURN >*/
return 0;
/*< END IF >*/
}
/*< K = MIN( M, N ) >*/
k = min(*m,*n);
/*< DO 10 I = 1, K >*/
i__1 = k;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */
/*< >*/
i__2 = *m - i__ + 1;
/* Computing MIN */
i__3 = i__ + 1;
slarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1]
, &c__1, &tau[i__]);
/*< IF( I.LT.N ) THEN >*/
if (i__ < *n) {
/* Apply H(i) to A(i:m,i+1:n) from the left */
/*< AII = A( I, I ) >*/
aii = a[i__ + i__ * a_dim1];
/*< A( I, I ) = ONE >*/
a[i__ + i__ * a_dim1] = (float)1.;
/*< >*/
i__2 = *m - i__ + 1;
i__3 = *n - i__;
slarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &tau[
i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1], (
ftnlen)4);
/*< A( I, I ) = AII >*/
a[i__ + i__ * a_dim1] = aii;
/*< END IF >*/
}
/*< 10 CONTINUE >*/
/* L10: */
}
/*< RETURN >*/
return 0;
/* End of SGEQR2 */
/*< END >*/
} /* sgeqr2_ */
#ifdef __cplusplus
}
#endif
| apache-2.0 |
plxaye/chromium | src/third_party/mesa/MesaLib/src/mesa/tnl/t_vb_cull.c | 32 | 2883 | /*
* Mesa 3-D graphics library
* Version: 6.5
*
* Copyright (C) 1999-2006 Brian Paul All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Authors:
* Keith Whitwell <keith@tungstengraphics.com>
*/
#include "main/glheader.h"
#include "main/colormac.h"
#include "main/macros.h"
#include "main/imports.h"
#include "main/mtypes.h"
#include "math/m_xform.h"
#include "t_context.h"
#include "t_pipeline.h"
/* EXT_vertex_cull. Not really a big win, but probably depends on
* your application. This stage not included in the default pipeline.
*/
static GLboolean run_cull_stage( GLcontext *ctx,
struct tnl_pipeline_stage *stage )
{
TNLcontext *tnl = TNL_CONTEXT(ctx);
struct vertex_buffer *VB = &tnl->vb;
const GLfloat a = ctx->Transform.CullObjPos[0];
const GLfloat b = ctx->Transform.CullObjPos[1];
const GLfloat c = ctx->Transform.CullObjPos[2];
GLfloat *norm = (GLfloat *)VB->AttribPtr[_TNL_ATTRIB_NORMAL]->data;
GLuint stride = VB->AttribPtr[_TNL_ATTRIB_NORMAL]->stride;
GLuint count = VB->Count;
GLuint i;
if (ctx->VertexProgram._Current ||
!ctx->Transform.CullVertexFlag)
return GL_TRUE;
VB->ClipOrMask &= ~CLIP_CULL_BIT;
VB->ClipAndMask |= CLIP_CULL_BIT;
for (i = 0 ; i < count ; i++) {
GLfloat dp = (norm[0] * a +
norm[1] * b +
norm[2] * c);
if (dp < 0) {
VB->ClipMask[i] |= CLIP_CULL_BIT;
VB->ClipOrMask |= CLIP_CULL_BIT;
}
else {
VB->ClipMask[i] &= ~CLIP_CULL_BIT;
VB->ClipAndMask &= ~CLIP_CULL_BIT;
}
STRIDE_F(norm, stride);
}
return !(VB->ClipAndMask & CLIP_CULL_BIT);
}
const struct tnl_pipeline_stage _tnl_vertex_cull_stage =
{
"EXT_cull_vertex",
NULL, /* private data */
NULL, /* ctr */
NULL, /* destructor */
NULL,
run_cull_stage /* run -- initially set to init */
};
| apache-2.0 |
jason-bean/sagetv | third_party/mplayer/TOOLS/realcodecs/rv30.c | 33 | 15222 | /*
GPL v2 blah blah
This is a small dll that works as a wrapper for the actual cook.so.6.0
dll from real player 8.0.
*/
/*
Assuming that RACloseCodec is the last call.
*/
#include <stddef.h>
#include <stdio.h>
#include <dlfcn.h>
#include <sys/time.h>
typedef unsigned long ulong;
ulong (*pncOpen)(ulong,ulong);
ulong (*pncClose)(ulong);
ulong (*pncGetUIName)(ulong,ulong);
ulong (*pncGetVersion)(ulong,ulong);
ulong (*pncQueryMediaFormat)(ulong,ulong,ulong,ulong);
ulong (*pncPreferredMediaFormat)(ulong,ulong,ulong,ulong);
ulong (*pncGetMediaFormats)(ulong,ulong,ulong,ulong);
ulong (*pncStreamOpen)(ulong,ulong,ulong);
ulong (*pnsOpenSettingsBox)(ulong,ulong);
ulong (*pnsGetIPNUnknown)(ulong);
ulong (*pnsSetDataCallback)(ulong,ulong,ulong,ulong);
ulong (*pnsSetProperty)(ulong,ulong,ulong);
ulong (*pnsGetProperty)(ulong,ulong,ulong);
ulong (*pnsClose)(ulong);
ulong (*pnsGetStreamHeaderSize)(ulong,ulong);
ulong (*pnsGetStreamHeader)(ulong,ulong);
ulong (*pnsInput)(ulong,ulong,ulong);
ulong (*pnsSetOutputPacketSize)(ulong,ulong,ulong,ulong);
ulong (*pnsGetInputBufferSize)(ulong,ulong);
void (*setDLLAccessPath)(ulong);
int b_dlOpened=0;
void *handle=NULL;
/* exits program when failure */
void loadSyms() {
fputs("loadSyms()\n", stderr);
if (!b_dlOpened) {
char *error;
fputs("opening dll...\n", stderr);
handle = dlopen ("/usr/local/RealPlayer8/Codecs/realrv30.so.6.0", RTLD_LAZY);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
pncOpen = dlsym(handle, "PNCodec_Open");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pncOpen): %s\n", error);
exit(1);
}
pncClose = dlsym(handle, "PNCodec_Close");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pncClose): %s\n", error);
exit(1);
}
pncGetUIName = dlsym(handle, "PNCodec_GetUIName");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pncGetUIName): %s\n", error);
exit(1);
}
pncGetVersion = dlsym(handle, "PNCodec_GetVersion");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pncGetVersion): %s\n", error);
exit(1);
}
pncQueryMediaFormat = dlsym(handle, "PNCodec_QueryMediaFormat");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pncQueryMediaFormat): %s\n", error);
exit(1);
}
pncPreferredMediaFormat = dlsym(handle, "PNCodec_PreferredMediaFormat");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pncPreferredMediaFormat): %s\n", error);
exit(1);
}
pncGetMediaFormats = dlsym(handle, "PNCodec_GetMediaFormats");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pncGetMediaFormats): %s\n", error);
exit(1);
}
pncStreamOpen = dlsym(handle, "PNCodec_StreamOpen");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pncStreamOpen): %s\n", error);
exit(1);
}
pnsOpenSettingsBox = dlsym(handle, "PNStream_OpenSettingsBox");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsOpenSettingsBox): %s\n", error);
exit(1);
}
pnsGetIPNUnknown = dlsym(handle, "PNStream_GetIPNUnknown");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsGetIPNUnknown): %s\n", error);
exit(1);
}
pnsSetDataCallback = dlsym(handle, "PNStream_SetDataCallback");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsSetDataCallback): %s\n", error);
exit(1);
}
pnsSetProperty = dlsym(handle, "PNStream_SetProperty");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsSetProperty): %s\n", error);
exit(1);
}
pnsGetProperty = dlsym(handle, "PNStream_GetProperty");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsGetProperty): %s\n", error);
exit(1);
}
pnsClose = dlsym(handle, "PNStream_Close");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsClose): %s\n", error);
exit(1);
}
pnsGetStreamHeaderSize = dlsym(handle, "PNStream_GetStreamHeaderSize");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsGetStreamHeaderSize): %s\n", error);
exit(1);
}
pnsGetStreamHeader = dlsym(handle, "PNStream_GetStreamHeader");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsGetStreamHeader): %s\n", error);
exit(1);
}
pnsInput = dlsym(handle, "PNStream_Input");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsInput): %s\n", error);
exit(1);
}
pnsSetOutputPacketSize = dlsym(handle, "PNStream_SetOutputPacketSize");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsSetOutputPacketSize): %s\n", error);
exit(1);
}
pnsGetInputBufferSize = dlsym(handle, "PNStream_GetInputBufferSize");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(pnsGetInputBufferSize): %s\n", error);
exit(1);
}
setDLLAccessPath = dlsym(handle, "SetDLLAccessPath");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "dlsym(SetDLLAccessPath): %s\n", error);
exit(1);
}
b_dlOpened=1;
}
}
void closeDll() {
if (handle) {
b_dlOpened=0;
dlclose(handle);
handle=NULL;
}
}
void _init(void) {
loadSyms();
}
struct timezone tz;
struct timeval tv1, tv2;
void tic() {
gettimeofday(&tv1, &tz);
}
void toc() {
long secs, usecs;
gettimeofday(&tv2, &tz);
secs=tv2.tv_sec-tv1.tv_sec;
usecs=tv2.tv_usec-tv1.tv_usec;
if (usecs<0) {
usecs+=1000000;
--secs;
}
fprintf(stderr, "Duration: %d.%0.6ds\n", secs, usecs);
}
void hexdump(void *pos, int len) {
unsigned char *cpos=pos, *cpos1;
int lines=(len+15)>>4;
while(lines--) {
int len1=len, i;
fprintf(stderr, "%0x ", cpos);
cpos1=cpos;
for (i=0;i<16;i++) {
if (len1>0) {
fprintf(stderr, "%02x ", *(cpos++));
} else {
fprintf(stderr, " ");
}
len1--;
}
fputs(" ", stderr);
cpos=cpos1;
for (i=0;i<16;i++) {
if (len>0) {
unsigned char ch=(*(cpos++));
if ((ch<32)||(ch>127)) ch='.';
fputc(ch, stderr);
}
len--;
}
fputs("\n", stderr);
}
fputc('\n', stderr);
}
ulong PNCodec_Open(ulong p1,ulong p2) {
ulong result;
fprintf(stderr, "PNCodec_Open(ulong fourcc=0x%0x(%d), ", p1, p1);
fprintf(stderr, "PNCMain **pncMain=0x%0x(%d))\n", p2, p2);
// hexdump((void*)p1, 44);
tic();
result=(*pncOpen)(p1,p2);
toc();
hexdump((void*)p2, 4);
// hexdump(*((void**)p2), 0x1278);
fprintf(stderr, "PNCodec_Open --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNCodec_Close(ulong p1) {
ulong result;
fprintf(stderr, "PNCodec_Close(PNCMain *pncMain=0x%0x(%d))\n", p1, p1);
// hexdump((void*)p1, 44);
tic();
result=(*pncClose)(p1);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNCodec_Close --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNCodec_GetUIName(ulong p1,ulong p2) {
ulong result;
fprintf(stderr, "PNCodec_GetUIName(PNCMain *pncMain=0x%0x(%d), ", p1, p1);
fprintf(stderr, "char **appname=0x%0x(%d))\n", p2, p2);
// hexdump((void*)p1, 0x1278);
// hexdump((void*)p2, 128);
tic();
result=(*pncGetUIName)(p1,p2);
toc();
// hexdump((void*)p1, 0x1278);
// hexdump((void*)p2, 128);
fprintf(stderr, "PNCodec_GetUIName --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNCodec_GetVersion(ulong p1,ulong p2) {
ulong result;
fprintf(stderr, "PNCodec_GetVersion(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d))\n", p2, p2);
// hexdump((void*)p1, 44);
tic();
result=(*pncGetVersion)(p1,p2);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNCodec_GetVersion --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNCodec_QueryMediaFormat(ulong p1,ulong p2,ulong p3,ulong p4) {
ulong result;
fprintf(stderr, "PNCodec_QueryMediaFormat(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong p3=0x%0x(%d),", p3, p3);
fprintf(stderr, "ulong p4=0x%0x(%d),\n", p4, p4);
// hexdump((void*)p1, 44);
tic();
result=(*pncQueryMediaFormat)(p1,p2,p3,p4);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNCodec_QueryMediaFormat --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNCodec_PreferredMediaFormat(ulong p1,ulong p2,ulong p3,ulong p4) {
ulong result;
fprintf(stderr, "PNCodec_PreferredMediaFormat(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong p3=0x%0x(%d),", p3, p3);
fprintf(stderr, "ulong p4=0x%0x(%d),\n", p4, p4);
// hexdump((void*)p1, 44);
tic();
result=(*pncPreferredMediaFormat)(p1,p2,p3,p4);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNCodec_PreferredMediaFormat --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNCodec_GetMediaFormats(ulong p1,ulong p2,ulong p3,ulong p4) {
ulong result;
fprintf(stderr, "PNCodec_GetMediaFormats(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong p3=0x%0x(%d),", p3, p3);
fprintf(stderr, "ulong p4=0x%0x(%d),\n", p4, p4);
// hexdump((void*)p1, 44);
tic();
result=(*pncGetMediaFormats)(p1,p2,p3,p4);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNCodec_GetMediaFormats --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNCodec_StreamOpen(ulong p1,ulong p2,ulong p3) {
ulong result;
fprintf(stderr, "PNCodec_StreamOpen(PNCMain *pncMain=0x%0x(%d), ", p1, p1);
fprintf(stderr, "PNSMain **pnsMain=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong **p3=0x%0x(%d),\n", p3, p3);
// hexdump((void*)p1, 0x1278);
// hexdump((void*)p2, 128);
// hexdump((void*)p3, 4);
hexdump(*((void**)p3), 4);
tic();
result=(*pncStreamOpen)(p1,p2,p3);
toc();
// hexdump((void*)p1, 0x1278);
hexdump((void*)p2, 4);
// hexdump((void*)p3, 128);
hexdump(*((void**)p2), 128);
hexdump(**((void***)p2), 128);
fprintf(stderr, "PNCodec_StreamOpen --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_OpenSettingsBox(ulong p1,ulong p2) {
ulong result;
fprintf(stderr, "PNStream_OpenSettingsBox(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n", p2, p2);
// hexdump((void*)p1, 44);
tic();
result=(*pnsOpenSettingsBox)(p1,p2);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNStream_OpenSettingsBox --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_GetIPNUnknown(ulong p1) {
ulong result;
fprintf(stderr, "PNStream_GetIPNUnknown(ulong p1=0x%0x(%d))\n", p1, p1);
// hexdump((void*)p1, 44);
tic();
result=(*pnsGetIPNUnknown)(p1);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNStream_GetIPNUnknown --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_SetDataCallback(ulong p1,ulong p2,ulong p3,ulong p4) {
ulong result;
int i=0;
void **pp;
fprintf(stderr, "PNStream_SetDataCallback(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong p3=0x%0x(%d),", p3, p3);
fprintf(stderr, "ulong p4=0x%0x(%d))\n", p4, p4);
hexdump((void*)p1, 0x24);
hexdump((void*)p2, 32);
hexdump((void*)p3, 4);
hexdump((void*)p4, 32);
fprintf(stderr, "content of the callback functions:\n\n");
while(i<8) {
hexdump(*((void**)p2+i), (i==0)?32*4:16);
i++;
}
i=0;
pp=(*(void***)p2);
fprintf(stderr, "content of the callback functions (first entry):\n\n");
while(i<15) {
hexdump(*((void**)pp+i), 32);
i++;
}
tic();
result=(*pnsSetDataCallback)(p1,p2,p3,p4);
toc();
hexdump((void*)p1, 0x24);
// hexdump((void*)p2, 256);
// hexdump((void*)p3, 4);
hexdump(*((void**)p3), 256);
fprintf(stderr, "PNStream_SetDataCallback --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_SetProperty(ulong p1,ulong p2,ulong p3) {
ulong result;
fprintf(stderr, "PNStream_SetProperty(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong p3=0x%0x(%d))\n", p3, p3);
hexdump((void*)p3, 4);
tic();
result=(*pnsSetProperty)(p1,p2,p3);
toc();
// hexdump((void*)p3, 44);
fprintf(stderr, "PNStream_SetProperty --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_GetProperty(ulong p1,ulong p2,ulong p3) {
ulong result;
fprintf(stderr, "PNStream_GetProperty(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong p3=0x%0x(%d))\n", p3, p3);
// hexdump((void*)p3, 44);
tic();
result=(*pnsGetProperty)(p1,p2,p3);
toc();
hexdump((void*)p3, 4);
fprintf(stderr, "PNStream_GetProperty --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_Close(ulong p1) {
ulong result;
fprintf(stderr, "PNStream_Close(ulong p1=0x%0x(%d))\n", p1, p1);
// hexdump((void*)p1, 44);
tic();
result=(*pnsClose)(p1);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNStream_Close --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong streamHeaderSize=0;
ulong PNStream_GetStreamHeaderSize(ulong p1,ulong p2) {
ulong result;
fprintf(stderr, "PNStream_GetStreamHeaderSize(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n", p2, p2);
// hexdump((void*)p2, 44);
tic();
result=(*pnsGetStreamHeaderSize)(p1,p2);
toc();
hexdump((void*)p2, 4);
streamHeaderSize=*((ulong *)p2);
fprintf(stderr, "PNStream_GetStreamHeaderSize --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_GetStreamHeader(ulong p1,ulong p2) {
ulong result;
fprintf(stderr, "PNStream_GetStreamHeader(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n", p2, p2);
// hexdump((void*)p2, 44);
tic();
result=(*pnsGetStreamHeader)(p1,p2);
toc();
hexdump((void*)p2, streamHeaderSize);
fprintf(stderr, "PNStream_GetStreamHeader --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_Input(ulong p1,ulong p2,ulong p3) {
ulong result;
fprintf(stderr, "PNStream_Input(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong p3=0x%0x(%d))\n", p3, p3);
hexdump((void*)p3, 4);
tic();
result=(*pnsInput)(p1,p2,p3);
toc();
// hexdump((void*)p3, 44);
fprintf(stderr, "PNStream_Input --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_SetOutputPacketSize(ulong p1,ulong p2,ulong p3,ulong p4) {
ulong result;
fprintf(stderr, "PNStream_SetOutputPacketSize(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d),\n\t", p2, p2);
fprintf(stderr, "ulong p3=0x%0x(%d),", p3, p3);
fprintf(stderr, "ulong p4=0x%0x(%d))\n", p4, p4);
// hexdump((void*)p1, 44);
tic();
result=(*pnsSetOutputPacketSize)(p1,p2,p3,p4);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNStream_SetOutputPacketSize --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
ulong PNStream_GetInputBufferSize(ulong p1,ulong p2) {
ulong result;
fprintf(stderr, "PNStream_GetInputBufferSize(ulong p1=0x%0x(%d), ", p1, p1);
fprintf(stderr, "ulong p2=0x%0x(%d))\n", p2, p2);
// hexdump((void*)p1, 44);
tic();
result=(*pnsGetInputBufferSize)(p1,p2);
toc();
// hexdump((void*)p1, 44);
fprintf(stderr, "PNStream_GetInputBufferSize --> 0x%0x(%d)\n\n\n", result, result);
return result;
}
void SetDLLAccessPath(ulong p1) {
fprintf(stderr, "SetDLLAccessPath(ulong p1=0x%0x(%d))\n", p1, p1);
// hexdump((void*)p1, 44);
(*setDLLAccessPath)(p1);
// hexdump((void*)p1, 44);
fprintf(stderr, "--> void\n\n\n");
}
| apache-2.0 |
dtn-kaist/cedos | dprox-nginx/src/os/unix/ngx_readv_chain.c | 38 | 6147 |
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
#define NGX_IOVS 16
#if (NGX_HAVE_KQUEUE)
ssize_t
ngx_readv_chain(ngx_connection_t *c, ngx_chain_t *chain)
{
u_char *prev;
ssize_t n, size;
ngx_err_t err;
ngx_array_t vec;
ngx_event_t *rev;
struct iovec *iov, iovs[NGX_IOVS];
rev = c->read;
if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) {
ngx_log_debug3(NGX_LOG_DEBUG_EVENT, c->log, 0,
"readv: eof:%d, avail:%d, err:%d",
rev->pending_eof, rev->available, rev->kq_errno);
if (rev->available == 0) {
if (rev->pending_eof) {
rev->ready = 0;
rev->eof = 1;
ngx_log_error(NGX_LOG_INFO, c->log, rev->kq_errno,
"kevent() reported about an closed connection");
if (rev->kq_errno) {
rev->error = 1;
ngx_set_socket_errno(rev->kq_errno);
return NGX_ERROR;
}
return 0;
} else {
return NGX_AGAIN;
}
}
}
prev = NULL;
iov = NULL;
size = 0;
vec.elts = iovs;
vec.nelts = 0;
vec.size = sizeof(struct iovec);
vec.nalloc = NGX_IOVS;
vec.pool = c->pool;
/* coalesce the neighbouring bufs */
while (chain) {
if (prev == chain->buf->last) {
iov->iov_len += chain->buf->end - chain->buf->last;
} else {
if (vec.nelts >= IOV_MAX) {
break;
}
iov = ngx_array_push(&vec);
if (iov == NULL) {
return NGX_ERROR;
}
iov->iov_base = (void *) chain->buf->last;
iov->iov_len = chain->buf->end - chain->buf->last;
}
size += chain->buf->end - chain->buf->last;
prev = chain->buf->end;
chain = chain->next;
}
ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,
"readv: %d, last:%d", vec.nelts, iov->iov_len);
rev = c->read;
do {
n = readv(c->fd, (struct iovec *) vec.elts, vec.nelts);
if (n >= 0) {
if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) {
rev->available -= n;
/*
* rev->available may be negative here because some additional
* bytes may be received between kevent() and recv()
*/
if (rev->available <= 0) {
if (!rev->pending_eof) {
rev->ready = 0;
}
if (rev->available < 0) {
rev->available = 0;
}
}
if (n == 0) {
/*
* on FreeBSD recv() may return 0 on closed socket
* even if kqueue reported about available data
*/
#if 0
ngx_log_error(NGX_LOG_ALERT, c->log, 0,
"readv() returned 0 while kevent() reported "
"%d available bytes", rev->available);
#endif
rev->eof = 1;
rev->available = 0;
}
return n;
}
if (n < size) {
rev->ready = 0;
}
if (n == 0) {
rev->eof = 1;
}
return n;
}
err = ngx_socket_errno;
if (err == NGX_EAGAIN || err == NGX_EINTR) {
ngx_log_debug0(NGX_LOG_DEBUG_EVENT, c->log, err,
"readv() not ready");
n = NGX_AGAIN;
} else {
n = ngx_connection_error(c, err, "readv() failed");
break;
}
} while (err == NGX_EINTR);
rev->ready = 0;
if (n == NGX_ERROR) {
c->read->error = 1;
}
return n;
}
#else /* ! NGX_HAVE_KQUEUE */
ssize_t
ngx_readv_chain(ngx_connection_t *c, ngx_chain_t *chain)
{
u_char *prev;
ssize_t n, size;
ngx_err_t err;
ngx_array_t vec;
ngx_event_t *rev;
struct iovec *iov, iovs[NGX_IOVS];
prev = NULL;
iov = NULL;
size = 0;
vec.elts = iovs;
vec.nelts = 0;
vec.size = sizeof(struct iovec);
vec.nalloc = NGX_IOVS;
vec.pool = c->pool;
/* coalesce the neighbouring bufs */
while (chain) {
if (prev == chain->buf->last) {
iov->iov_len += chain->buf->end - chain->buf->last;
} else {
if (vec.nelts >= IOV_MAX) {
break;
}
iov = ngx_array_push(&vec);
if (iov == NULL) {
return NGX_ERROR;
}
iov->iov_base = (void *) chain->buf->last;
iov->iov_len = chain->buf->end - chain->buf->last;
}
size += chain->buf->end - chain->buf->last;
prev = chain->buf->end;
chain = chain->next;
}
ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,
"readv: %d:%d", vec.nelts, iov->iov_len);
rev = c->read;
do {
n = readv(c->fd, (struct iovec *) vec.elts, vec.nelts);
if (n == 0) {
rev->ready = 0;
rev->eof = 1;
return n;
} else if (n > 0) {
if (n < size && !(ngx_event_flags & NGX_USE_GREEDY_EVENT)) {
rev->ready = 0;
}
return n;
}
err = ngx_socket_errno;
if (err == NGX_EAGAIN || err == NGX_EINTR) {
ngx_log_debug0(NGX_LOG_DEBUG_EVENT, c->log, err,
"readv() not ready");
n = NGX_AGAIN;
} else {
n = ngx_connection_error(c, err, "readv() failed");
break;
}
} while (err == NGX_EINTR);
rev->ready = 0;
if (n == NGX_ERROR) {
c->read->error = 1;
}
return n;
}
#endif /* NGX_HAVE_KQUEUE */
| apache-2.0 |
LucasGandel/ITK | Modules/ThirdParty/VNL/src/vxl/v3p/netlib/blas/ccopy.c | 41 | 2555 | /* blas/ccopy.f -- translated by f2c (version 20050501).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "v3p_netlib.h"
/*< subroutine ccopy(n,cx,incx,cy,incy) >*/
/* Subroutine */ int ccopy_(integer *n, complex *cx, integer *incx, complex *
cy, integer *incy)
{
/* System generated locals */
integer i__1, i__2, i__3;
/* Local variables */
integer i__, ix, iy;
/* copies a vector, x, to a vector, y. */
/* jack dongarra, linpack, 3/11/78. */
/* modified 12/3/93, array(1) declarations changed to array(*) */
/*< complex cx(*),cy(*) >*/
/*< integer i,incx,incy,ix,iy,n >*/
/*< if(n.le.0)return >*/
/* Parameter adjustments */
--cy;
--cx;
/* Function Body */
if (*n <= 0) {
return 0;
}
/*< if(incx.eq.1.and.incy.eq.1)go to 20 >*/
if (*incx == 1 && *incy == 1) {
goto L20;
}
/* code for unequal increments or equal increments */
/* not equal to 1 */
/*< ix = 1 >*/
ix = 1;
/*< iy = 1 >*/
iy = 1;
/*< if(incx.lt.0)ix = (-n+1)*incx + 1 >*/
if (*incx < 0) {
ix = (-(*n) + 1) * *incx + 1;
}
/*< if(incy.lt.0)iy = (-n+1)*incy + 1 >*/
if (*incy < 0) {
iy = (-(*n) + 1) * *incy + 1;
}
/*< do 10 i = 1,n >*/
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< cy(iy) = cx(ix) >*/
i__2 = iy;
i__3 = ix;
cy[i__2].r = cx[i__3].r, cy[i__2].i = cx[i__3].i;
/*< ix = ix + incx >*/
ix += *incx;
/*< iy = iy + incy >*/
iy += *incy;
/*< 10 continue >*/
/* L10: */
}
/*< return >*/
return 0;
/* code for both increments equal to 1 */
/*< 20 do 30 i = 1,n >*/
L20:
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/*< cy(i) = cx(i) >*/
i__2 = i__;
i__3 = i__;
cy[i__2].r = cx[i__3].r, cy[i__2].i = cx[i__3].i;
/*< 30 continue >*/
/* L30: */
}
/*< return >*/
return 0;
/*< end >*/
} /* ccopy_ */
#ifdef __cplusplus
}
#endif
| apache-2.0 |
NixaSoftware/CVis | venv/bin/libs/graph/example/kruskal-example.cpp | 45 | 2702 | //=======================================================================
// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/kruskal_min_spanning_tree.hpp>
#include <iostream>
#include <fstream>
int
main()
{
using namespace boost;
typedef adjacency_list < vecS, vecS, undirectedS,
no_property, property < edge_weight_t, int > > Graph;
typedef graph_traits < Graph >::edge_descriptor Edge;
typedef graph_traits < Graph >::vertex_descriptor Vertex;
typedef std::pair<int, int> E;
const int num_nodes = 5;
E edge_array[] = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3),
E(3, 4), E(4, 0), E(4, 1)
};
int weights[] = { 1, 1, 2, 7, 3, 1, 1, 1 };
std::size_t num_edges = sizeof(edge_array) / sizeof(E);
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
Graph g(num_nodes);
property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);
for (std::size_t j = 0; j < num_edges; ++j) {
Edge e; bool inserted;
boost::tie(e, inserted) = add_edge(edge_array[j].first, edge_array[j].second, g);
weightmap[e] = weights[j];
}
#else
Graph g(edge_array, edge_array + num_edges, weights, num_nodes);
#endif
property_map < Graph, edge_weight_t >::type weight = get(edge_weight, g);
std::vector < Edge > spanning_tree;
kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));
std::cout << "Print the edges in the MST:" << std::endl;
for (std::vector < Edge >::iterator ei = spanning_tree.begin();
ei != spanning_tree.end(); ++ei) {
std::cout << source(*ei, g) << " <--> " << target(*ei, g)
<< " with weight of " << weight[*ei]
<< std::endl;
}
std::ofstream fout("figs/kruskal-eg.dot");
fout << "graph A {\n"
<< " rankdir=LR\n"
<< " size=\"3,3\"\n"
<< " ratio=\"filled\"\n"
<< " edge[style=\"bold\"]\n" << " node[shape=\"circle\"]\n";
graph_traits<Graph>::edge_iterator eiter, eiter_end;
for (boost::tie(eiter, eiter_end) = edges(g); eiter != eiter_end; ++eiter) {
fout << source(*eiter, g) << " -- " << target(*eiter, g);
if (std::find(spanning_tree.begin(), spanning_tree.end(), *eiter)
!= spanning_tree.end())
fout << "[color=\"black\", label=\"" << get(edge_weight, g, *eiter)
<< "\"];\n";
else
fout << "[color=\"gray\", label=\"" << get(edge_weight, g, *eiter)
<< "\"];\n";
}
fout << "}\n";
return EXIT_SUCCESS;
}
| apache-2.0 |
Sweet-Peas/mbed | libraries/mbed/targets/cmsis/TARGET_STM/TARGET_STM32F1/stm32f1xx_hal_irda.c | 50 | 50975 | /**
******************************************************************************
* @file stm32f1xx_hal_irda.c
* @author MCD Application Team
* @version V1.0.0
* @date 15-December-2014
* @brief IRDA HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the IrDA SIR ENDEC block (IrDA):
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral State and Errors functions
* + Peripheral Control functions
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The IRDA HAL driver can be used as follows:
(#) Declare a IRDA_HandleTypeDef handle structure.
(#) Initialize the IRDA low level resources by implementing the HAL_IRDA_MspInit() API:
(##) Enable the USARTx interface clock.
(##) IRDA pins configuration:
(+++) Enable the clock for the IRDA GPIOs.
(+++) Configure the USART pins (TX as alternate function pull-up, RX as alternate function Input).
(##) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT()
and HAL_IRDA_Receive_IT() APIs):
(+++) Configure the USARTx interrupt priority.
(+++) Enable the NVIC USART IRQ handle.
(##) DMA Configuration if you need to use DMA process (HAL_IRDA_Transmit_DMA()
and HAL_IRDA_Receive_DMA() APIs):
(+++) Declare a DMA handle structure for the Tx/Rx channel.
(+++) Enable the DMAx interface clock.
(+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
(+++) Configure the DMA Tx/Rx channel.
(+++) Associate the initilalized DMA handle to the IRDA DMA Tx/Rx handle.
(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx channel.
(+++) Configure the USARTx interrupt priority and enable the NVIC USART IRQ handle
(used for last byte sending completion detection in DMA non circular mode)
(#) Program the Baud Rate, Word Length, Parity, IrDA Mode, Prescaler
and Mode(Receiver/Transmitter) in the hirda Init structure.
(#) Initialize the IRDA registers by calling the HAL_IRDA_Init() API:
(++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
by calling the customed HAL_IRDA_MspInit() API.
-@@- The specific IRDA interrupts (Transmission complete interrupt,
RXNE interrupt and Error Interrupts) will be managed using the macros
__HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process.
(#) Three operation modes are available within this driver :
*** Polling mode IO operation ***
=================================
[..]
(+) Send an amount of data in blocking mode using HAL_IRDA_Transmit()
(+) Receive an amount of data in blocking mode using HAL_IRDA_Receive()
*** Interrupt mode IO operation ***
===================================
[..]
(+) Send an amount of data in non blocking mode using HAL_IRDA_Transmit_IT()
(+) At transmission end of transfer HAL_IRDA_TxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_IRDA_TxCpltCallback
(+) Receive an amount of data in non blocking mode using HAL_IRDA_Receive_IT()
(+) At reception end of transfer HAL_IRDA_RxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_IRDA_RxCpltCallback
(+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_IRDA_ErrorCallback
*** DMA mode IO operation ***
==============================
[..]
(+) Send an amount of data in non blocking mode (DMA) using HAL_IRDA_Transmit_DMA()
(+) At transmission end of transfer HAL_IRDA_TxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_IRDA_TxCpltCallback
(+) Receive an amount of data in non blocking mode (DMA) using HAL_IRDA_Receive_DMA()
(+) At reception end of transfer HAL_IRDA_RxCpltCallback is executed and user can
add his own code by customization of function pointer HAL_IRDA_RxCpltCallback
(+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_IRDA_ErrorCallback
*** IRDA HAL driver macros list ***
====================================
[..]
Below the list of most used macros in IRDA HAL driver.
(+) __HAL_IRDA_ENABLE: Enable the IRDA peripheral
(+) __HAL_IRDA_DISABLE: Disable the IRDA peripheral
(+) __HAL_IRDA_GET_FLAG : Check whether the specified IRDA flag is set or not
(+) __HAL_IRDA_CLEAR_FLAG : Clear the specified IRDA pending flag
(+) __HAL_IRDA_ENABLE_IT: Enable the specified IRDA interrupt
(+) __HAL_IRDA_DISABLE_IT: Disable the specified IRDA interrupt
(+) __HAL_IRDA_GET_IT_SOURCE: Check whether the specified IRDA interrupt has occurred or not
[..]
(@) You can refer to the IRDA HAL driver header file for more useful macros
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
*
* 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 STMicroelectronics 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
* @{
*/
/** @defgroup IRDA IRDA
* @brief HAL IRDA module driver
* @{
*/
#ifdef HAL_IRDA_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup IRDA_Private_Constants IRDA Private Constants
* @{
*/
#define IRDA_DR_MASK_U16_8DATABITS (uint16_t)0x00FF
#define IRDA_DR_MASK_U16_9DATABITS (uint16_t)0x01FF
#define IRDA_DR_MASK_U8_7DATABITS (uint8_t)0x7F
#define IRDA_DR_MASK_U8_8DATABITS (uint8_t)0xFF
/**
* @}
*/
/* Private macros --------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup IRDA_Private_Functions IRDA Private Functions
* @{
*/
static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda);
static HAL_StatusTypeDef IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda);
static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda);
static void IRDA_SetConfig (IRDA_HandleTypeDef *hirda);
static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAError(DMA_HandleTypeDef *hdma);
static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
/**
* @}
*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup IRDA_Exported_Functions IRDA Exported Functions
* @{
*/
/** @defgroup IRDA_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
==============================================================================
##### Initialization and Configuration functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to initialize the USARTx or the UARTy
in IrDA mode.
(+) For the asynchronous mode only these parameters can be configured:
(++) Baud Rate
(++) Word Length
(++) Parity: If the parity is enabled, then the MSB bit of the data written
in the data register is transmitted but is changed by the parity bit.
Depending on the frame length defined by the M bit (8-bits or 9-bits),
the possible IRDA frame formats are as listed in the following table:
(+++) +-------------------------------------------------------------+
(+++) | M bit | PCE bit | IRDA frame |
(+++) |---------------------|---------------------------------------|
(+++) | 0 | 0 | | SB | 8 bit data | STB | |
(+++) |---------|-----------|---------------------------------------|
(+++) | 0 | 1 | | SB | 7 bit data | PB | STB | |
(+++) |---------|-----------|---------------------------------------|
(+++) | 1 | 0 | | SB | 9 bit data | STB | |
(+++) |---------|-----------|---------------------------------------|
(+++) | 1 | 1 | | SB | 8 bit data | PB | STB | |
(+++) +-------------------------------------------------------------+
(++) Prescaler: A pulse of width less than two and greater than one PSC period(s) may or may
not be rejected. The receiver set up time should be managed by software. The IrDA physical layer
specification specifies a minimum of 10 ms delay between transmission and
reception (IrDA is a half duplex protocol).
(++) Mode: Receiver/transmitter modes
(++) IrDAMode: the IrDA can operate in the Normal mode or in the Low power mode.
[..]
The HAL_IRDA_Init() function follows IRDA configuration procedures (details for the procedures
are available in reference manuals (RM0008 for STM32F10Xxx MCUs and RM0041 for STM32F100xx MCUs)).
@endverbatim
* @{
*/
/**
* @brief Initializes the IRDA mode according to the specified
* parameters in the IRDA_InitTypeDef and create the associated handle.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda)
{
/* Check the IRDA handle allocation */
if(hirda == NULL)
{
return HAL_ERROR;
}
/* Check the IRDA instance parameters */
assert_param(IS_IRDA_INSTANCE(hirda->Instance));
/* Check the IRDA mode parameter in the IRDA handle */
assert_param(IS_IRDA_POWERMODE(hirda->Init.IrDAMode));
if(hirda->State == HAL_IRDA_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hirda-> Lock = HAL_UNLOCKED;
/* Init the low level hardware */
HAL_IRDA_MspInit(hirda);
}
hirda->State = HAL_IRDA_STATE_BUSY;
/* Disable the IRDA peripheral */
__HAL_IRDA_DISABLE(hirda);
/* Set the IRDA communication parameters */
IRDA_SetConfig(hirda);
/* In IrDA mode, the following bits must be kept cleared:
- LINEN, STOP and CLKEN bits in the USART_CR2 register,
- SCEN and HDSEL bits in the USART_CR3 register.*/
CLEAR_BIT(hirda->Instance->CR2, (USART_CR2_LINEN | USART_CR2_STOP | USART_CR2_CLKEN));
CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL));
/* Enable the IRDA peripheral */
__HAL_IRDA_ENABLE(hirda);
/* Set the prescaler */
MODIFY_REG(hirda->Instance->GTPR, USART_GTPR_PSC, hirda->Init.Prescaler);
/* Configure the IrDA mode */
MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.IrDAMode);
/* Enable the IrDA mode by setting the IREN bit in the CR3 register */
SET_BIT(hirda->Instance->CR3, USART_CR3_IREN);
/* Initialize the IRDA state*/
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->State= HAL_IRDA_STATE_READY;
return HAL_OK;
}
/**
* @brief DeInitializes the IRDA peripheral
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda)
{
/* Check the IRDA handle allocation */
if(hirda == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_IRDA_INSTANCE(hirda->Instance));
hirda->State = HAL_IRDA_STATE_BUSY;
/* Disable the Peripheral */
__HAL_IRDA_DISABLE(hirda);
/* DeInit the low level hardware */
HAL_IRDA_MspDeInit(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->State = HAL_IRDA_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief IRDA MSP Init.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda)
{
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_MspInit can be implemented in the user file
*/
}
/**
* @brief IRDA MSP DeInit.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda)
{
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_MspDeInit can be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup IRDA_Exported_Functions_Group2 IO operation functions
* @brief IRDA Transmit and Receive functions
*
@verbatim
==============================================================================
##### IO operation functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to manage the IRDA data transfers.
[..]
IrDA is a half duplex communication protocol. If the Transmitter is busy, any data
on the IrDA receive line will be ignored by the IrDA decoder and if the Receiver
is busy, data on the TX from the USART to IrDA will not be encoded by IrDA.
While receiving data, transmission should be avoided as the data to be transmitted
could be corrupted.
(#) There are two modes of transfer:
(++) Blocking mode: The communication is performed in polling mode.
The HAL status of all data processing is returned by the same function
after finishing transfer.
(++) No-Blocking mode: The communication is performed using Interrupts
or DMA, These API's return the HAL status.
The end of the data processing will be indicated through the
dedicated IRDA IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
The HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxCpltCallback() user callbacks
will be executed respectively at the end of the transmit or Receive process
The HAL_IRDA_ErrorCallback() user callback will be executed when a communication
error is detected
(#) Blocking mode APIs are :
(++) HAL_IRDA_Transmit()
(++) HAL_IRDA_Receive()
(#) Non Blocking mode APIs with Interrupt are :
(++) HAL_IRDA_Transmit_IT()
(++) HAL_IRDA_Receive_IT()
(++) HAL_IRDA_IRQHandler()
(#) Non Blocking mode functions with DMA are :
(++) HAL_IRDA_Transmit_DMA()
(++) HAL_IRDA_Receive_DMA()
(++) HAL_IRDA_DMAPause()
(++) HAL_IRDA_DMAResume()
(++) HAL_IRDA_DMAStop()
(#) A set of Transfer Complete Callbacks are provided in non Blocking mode:
(++) HAL_IRDA_TxHalfCpltCallback()
(++) HAL_IRDA_TxCpltCallback()
(++) HAL_IRDA_RxHalfCpltCallback()
(++) HAL_IRDA_RxCpltCallback()
(++) HAL_IRDA_ErrorCallback()
@endverbatim
* @{
*/
/**
* @brief Sends an amount of data in blocking mode.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be sent
* @param Timeout: Specify timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t* tmp = 0;
uint32_t tmp_state = 0;
tmp_state = hirda->State;
if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_RX))
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
if(hirda->State == HAL_IRDA_STATE_BUSY_RX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
}
else
{
hirda->State = HAL_IRDA_STATE_BUSY_TX;
}
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
while(hirda->TxXferCount > 0)
{
if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B)
{
if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
tmp = (uint16_t*) pData;
WRITE_REG(hirda->Instance->DR,(*tmp & IRDA_DR_MASK_U16_9DATABITS));
if(hirda->Init.Parity == IRDA_PARITY_NONE)
{
pData +=2;
}
else
{
pData +=1;
}
}
else
{
if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
WRITE_REG(hirda->Instance->DR, (*pData++ & IRDA_DR_MASK_U8_8DATABITS));
}
hirda->TxXferCount--;
}
if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
{
hirda->State = HAL_IRDA_STATE_BUSY_RX;
}
else
{
hirda->State = HAL_IRDA_STATE_READY;
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in blocking mode.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be received
* @param Timeout: Specify timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t* tmp = 0;
uint32_t tmp_state = 0;
tmp_state = hirda->State;
if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_TX))
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
if(hirda->State == HAL_IRDA_STATE_BUSY_TX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
}
else
{
hirda->State = HAL_IRDA_STATE_BUSY_RX;
}
hirda->RxXferSize = Size;
hirda->RxXferCount = Size;
/* Check the remain data to be received */
while(hirda->RxXferCount > 0)
{
if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B)
{
if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
tmp = (uint16_t*) pData ;
if(hirda->Init.Parity == IRDA_PARITY_NONE)
{
*tmp = (uint16_t)(hirda->Instance->DR & IRDA_DR_MASK_U16_9DATABITS);
pData +=2;
}
else
{
*tmp = (uint16_t)(hirda->Instance->DR & IRDA_DR_MASK_U16_8DATABITS);
pData +=1;
}
}
else
{
if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if(hirda->Init.Parity == IRDA_PARITY_NONE)
{
*pData++ = (uint8_t)(hirda->Instance->DR & IRDA_DR_MASK_U8_8DATABITS);
}
else
{
*pData++ = (uint8_t)(hirda->Instance->DR & IRDA_DR_MASK_U8_7DATABITS);
}
}
hirda->RxXferCount--;
}
if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX;
}
else
{
hirda->State = HAL_IRDA_STATE_READY;
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sends an amount of data in non-blocking mode.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
uint32_t tmp_state = 0;
tmp_state = hirda->State;
if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_RX))
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pTxBuffPtr = pData;
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
if(hirda->State == HAL_IRDA_STATE_BUSY_RX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
}
else
{
hirda->State = HAL_IRDA_STATE_BUSY_TX;
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR);
/* Enable the IRDA Transmit Data Register Empty Interrupt */
__HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TXE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives an amount of data in non-blocking mode.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be received
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
uint32_t tmp_state = 0;
tmp_state = hirda->State;
if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_TX))
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pRxBuffPtr = pData;
hirda->RxXferSize = Size;
hirda->RxXferCount = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
if(hirda->State == HAL_IRDA_STATE_BUSY_TX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
}
else
{
hirda->State = HAL_IRDA_STATE_BUSY_RX;
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Enable the IRDA Data Register not empty Interrupt */
__HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_RXNE);
/* Enable the IRDA Parity Error Interrupt */
__HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_PE);
/* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sends an amount of data in non-blocking mode.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
uint32_t *tmp = 0;
uint32_t tmp_state = 0;
tmp_state = hirda->State;
if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_RX))
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pTxBuffPtr = pData;
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
if(hirda->State == HAL_IRDA_STATE_BUSY_RX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
}
else
{
hirda->State = HAL_IRDA_STATE_BUSY_TX;
}
/* Set the IRDA DMA transfer complete callback */
hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt;
/* Set the IRDA DMA half transfert complete callback */
hirda->hdmatx->XferHalfCpltCallback = IRDA_DMATransmitHalfCplt;
/* Set the DMA error callback */
hirda->hdmatx->XferErrorCallback = IRDA_DMAError;
/* Enable the IRDA transmit DMA channel */
tmp = (uint32_t*)&pData;
HAL_DMA_Start_IT(hirda->hdmatx, *(uint32_t*)tmp, (uint32_t)&hirda->Instance->DR, Size);
/* Clear the TC flag in the SR register by writing 0 to it */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_FLAG_TC);
/* Enable the DMA transfer for transmit request by setting the DMAT bit
in the USART CR3 register */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in non-blocking mode.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be received
* @note When the IRDA parity is enabled (PCE = 1) the data received contain the parity bit.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
uint32_t *tmp = 0;
uint32_t tmp_state = 0;
tmp_state = hirda->State;
if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_TX))
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pRxBuffPtr = pData;
hirda->RxXferSize = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
if(hirda->State == HAL_IRDA_STATE_BUSY_TX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX_RX;
}
else
{
hirda->State = HAL_IRDA_STATE_BUSY_RX;
}
/* Set the IRDA DMA transfer complete callback */
hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt;
/* Set the IRDA DMA half transfert complete callback */
hirda->hdmarx->XferHalfCpltCallback = IRDA_DMAReceiveHalfCplt;
/* Set the DMA error callback */
hirda->hdmarx->XferErrorCallback = IRDA_DMAError;
/* Enable the DMA channel */
tmp = (uint32_t*)&pData;
HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->DR, *(uint32_t*)tmp, Size);
/* Enable the DMA transfer for the receiver request by setting the DMAR bit
in the USART CR3 register */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Pauses the DMA Transfer.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda)
{
/* Process Locked */
__HAL_LOCK(hirda);
if(hirda->State == HAL_IRDA_STATE_BUSY_TX)
{
/* Disable the IRDA DMA Tx request */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
}
else if(hirda->State == HAL_IRDA_STATE_BUSY_RX)
{
/* Disable the IRDA DMA Rx request */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
}
else if (hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
{
/* Disable the IRDA DMA Tx & Rx requests */
CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR));
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_ERROR;
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Resumes the DMA Transfer.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda)
{
/* Process Locked */
__HAL_LOCK(hirda);
if(hirda->State == HAL_IRDA_STATE_BUSY_TX)
{
/* Enable the IRDA DMA Tx request */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
}
else if(hirda->State == HAL_IRDA_STATE_BUSY_RX)
{
/* Clear the Overrun flag before resumming the Rx transfer*/
__HAL_IRDA_CLEAR_OREFLAG(hirda);
/* Enable the IRDA DMA Rx request */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
}
else if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
{
/* Clear the Overrun flag before resumming the Rx transfer*/
__HAL_IRDA_CLEAR_OREFLAG(hirda);
/* Enable the IRDA DMA Tx & Rx request */
SET_BIT(hirda->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR));
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_ERROR;
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Stops the DMA Transfer.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda)
{
/* The Lock is not implemented on this API to allow the user application
to call the HAL IRDA API under callbacks HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback():
when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated
and the correspond call back is executed HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback()
*/
/* Disable the IRDA Tx/Rx DMA requests */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA tx channel */
if(hirda->hdmatx != NULL)
{
HAL_DMA_Abort(hirda->hdmatx);
}
/* Abort the IRDA DMA rx channel */
if(hirda->hdmarx != NULL)
{
HAL_DMA_Abort(hirda->hdmarx);
}
hirda->State = HAL_IRDA_STATE_READY;
return HAL_OK;
}
/**
* @brief This function handles IRDA interrupt request.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda)
{
uint32_t tmp_flag = 0, tmp_it_source = 0;
tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_PE);
tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_PE);
/* IRDA parity error interrupt occurred -----------------------------------*/
if((tmp_flag != RESET) && (tmp_it_source != RESET))
{
__HAL_IRDA_CLEAR_PEFLAG(hirda);
hirda->ErrorCode |= HAL_IRDA_ERROR_PE;
}
tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_FE);
tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR);
/* IRDA frame error interrupt occurred ------------------------------------*/
if((tmp_flag != RESET) && (tmp_it_source != RESET))
{
__HAL_IRDA_CLEAR_FEFLAG(hirda);
hirda->ErrorCode |= HAL_IRDA_ERROR_FE;
}
tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_NE);
/* IRDA noise error interrupt occurred ------------------------------------*/
if((tmp_flag != RESET) && (tmp_it_source != RESET))
{
__HAL_IRDA_CLEAR_NEFLAG(hirda);
hirda->ErrorCode |= HAL_IRDA_ERROR_NE;
}
tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_ORE);
/* IRDA Over-Run interrupt occurred ---------------------------------------*/
if((tmp_flag != RESET) && (tmp_it_source != RESET))
{
__HAL_IRDA_CLEAR_OREFLAG(hirda);
hirda->ErrorCode |= HAL_IRDA_ERROR_ORE;
}
/* Call the Error call Back in case of Errors */
if(hirda->ErrorCode != HAL_IRDA_ERROR_NONE)
{
/* Disable PE and ERR interrupt */
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE);
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE);
/* Set the IRDA state ready to be able to start again the process */
hirda->State = HAL_IRDA_STATE_READY;
HAL_IRDA_ErrorCallback(hirda);
}
tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_RXNE);
tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_RXNE);
/* IRDA in mode Receiver --------------------------------------------------*/
if((tmp_flag != RESET) && (tmp_it_source != RESET))
{
IRDA_Receive_IT(hirda);
}
tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_TXE);
tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_TXE);
/* IRDA in mode Transmitter -----------------------------------------------*/
if((tmp_flag != RESET) && (tmp_it_source != RESET))
{
IRDA_Transmit_IT(hirda);
}
tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_TC);
tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_TC);
/* IRDA in mode Transmitter (transmission end) -----------------------------*/
if((tmp_flag != RESET) && (tmp_it_source != RESET))
{
IRDA_EndTransmit_IT(hirda);
}
}
/**
* @brief Tx Transfer completed callbacks.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_TxCpltCallback can be implemented in the user file
*/
}
/**
* @brief Tx Half Transfer completed callbacks.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified USART module.
* @retval None
*/
__weak void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_TxHalfCpltCallback can be implemented in the user file
*/
}
/**
* @brief Rx Transfer completed callbacks.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_RxCpltCallback can be implemented in the user file
*/
}
/**
* @brief Rx Half Transfer complete callbacks.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_RxHalfCpltCallback can be implemented in the user file
*/
}
/**
* @brief IRDA error callbacks.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda)
{
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_ErrorCallback can be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup IRDA_Exported_Functions_Group3 Peripheral State and Errors functions
* @brief IRDA State and Errors functions
*
@verbatim
==============================================================================
##### Peripheral State and Errors functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to return the State of IrDA
communication process and also return Peripheral Errors occurred during communication process
(+) HAL_IRDA_GetState() API can be helpful to check in run-time the state
of the IRDA peripheral.
(+) HAL_IRDA_GetError() check in run-time errors that could be occurred during
communication.
@endverbatim
* @{
*/
/**
* @brief Returns the IRDA state.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL state
*/
HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda)
{
return hirda->State;
}
/**
* @brief Return the IRDA error code
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval IRDA Error Code
*/
uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda)
{
return hirda->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup IRDA_Private_Functions IRDA Private Functions
* @brief IRDA Private functions
* @{
*/
/**
* @brief DMA IRDA transmit process complete callback.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* DMA Normal mode */
if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) )
{
hirda->TxXferCount = 0;
/* Disable the DMA transfer for transmit request by setting the DMAT bit
in the IRDA CR3 register */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Enable the IRDA Transmit Complete Interrupt */
__HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TC);
}
/* DMA Circular mode */
else
{
HAL_IRDA_TxCpltCallback(hirda);
}
}
/**
* @brief DMA IRDA receive process half complete callback
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
HAL_IRDA_TxHalfCpltCallback(hirda);
}
/**
* @brief DMA IRDA receive process complete callback.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* DMA Normal mode */
if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) )
{
hirda->RxXferCount = 0;
/* Disable the DMA transfer for the receiver request by setting the DMAR bit
in the IRDA CR3 register */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX;
}
else
{
hirda->State = HAL_IRDA_STATE_READY;
}
}
HAL_IRDA_RxCpltCallback(hirda);
}
/**
* @brief DMA IRDA receive process half complete callback
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
HAL_IRDA_RxHalfCpltCallback(hirda);
}
/**
* @brief DMA IRDA communication error callback.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAError(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
hirda->RxXferCount = 0;
hirda->TxXferCount = 0;
hirda->ErrorCode |= HAL_IRDA_ERROR_DMA;
hirda->State= HAL_IRDA_STATE_READY;
HAL_IRDA_ErrorCallback(hirda);
}
/**
* @brief This function handles IRDA Communication Timeout.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param Flag: specifies the IRDA flag to check.
* @param Status: The new Flag status (SET or RESET).
* @param Timeout: Timeout duration
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
{
uint32_t tickstart = 0;
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until flag is set */
if(Status == RESET)
{
while(__HAL_IRDA_GET_FLAG(hirda, Flag) == RESET)
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE);
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE);
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE);
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
hirda->State= HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_TIMEOUT;
}
}
}
}
else
{
while(__HAL_IRDA_GET_FLAG(hirda, Flag) != RESET)
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE);
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE);
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE);
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
hirda->State= HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_TIMEOUT;
}
}
}
}
return HAL_OK;
}
/**
* @brief Send an amount of data in non-blocking mode.
* Function called under interruption only, once
* interruptions have been enabled by HAL_IRDA_Transmit_IT()
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda)
{
uint16_t* tmp = 0;
uint32_t tmp_state = 0;
tmp_state = hirda->State;
if((tmp_state == HAL_IRDA_STATE_BUSY_TX) || (tmp_state == HAL_IRDA_STATE_BUSY_TX_RX))
{
if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B)
{
tmp = (uint16_t*) hirda->pTxBuffPtr;
WRITE_REG(hirda->Instance->DR, (uint16_t)(*tmp & IRDA_DR_MASK_U16_9DATABITS));
if(hirda->Init.Parity == IRDA_PARITY_NONE)
{
hirda->pTxBuffPtr += 2;
}
else
{
hirda->pTxBuffPtr += 1;
}
}
else
{
WRITE_REG(hirda->Instance->DR, (uint8_t)(*hirda->pTxBuffPtr++ & IRDA_DR_MASK_U8_8DATABITS));
}
if(--hirda->TxXferCount == 0)
{
/* Disable the IRDA Transmit Data Register Empty Interrupt */
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE);
/* Enable the IRDA Transmit Complete Interrupt */
__HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TC);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Wraps up transmission in non blocking mode.
* @param hirda: pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda)
{
/* Disable the IRDA Transmit Complete Interrupt */
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TC);
/* Check if a receive process is ongoing or not */
if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
{
hirda->State = HAL_IRDA_STATE_BUSY_RX;
}
else
{
/* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
hirda->State = HAL_IRDA_STATE_READY;
}
HAL_IRDA_TxCpltCallback(hirda);
return HAL_OK;
}
/**
* @brief Receive an amount of data in non-blocking mode.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda)
{
uint16_t* tmp = 0;
uint32_t tmp_state = 0;
tmp_state = hirda->State;
if((tmp_state == HAL_IRDA_STATE_BUSY_RX) || (tmp_state == HAL_IRDA_STATE_BUSY_TX_RX))
{
if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B)
{
tmp = (uint16_t*) hirda->pRxBuffPtr;
if(hirda->Init.Parity == IRDA_PARITY_NONE)
{
*tmp = (uint16_t)(hirda->Instance->DR & IRDA_DR_MASK_U16_9DATABITS);
hirda->pRxBuffPtr += 2;
}
else
{
*tmp = (uint16_t)(hirda->Instance->DR & IRDA_DR_MASK_U16_8DATABITS);
hirda->pRxBuffPtr += 1;
}
}
else
{
if(hirda->Init.Parity == IRDA_PARITY_NONE)
{
*hirda->pRxBuffPtr++ = (uint8_t)(hirda->Instance->DR & IRDA_DR_MASK_U8_8DATABITS);
}
else
{
*hirda->pRxBuffPtr++ = (uint8_t)(hirda->Instance->DR & IRDA_DR_MASK_U8_7DATABITS);
}
}
if(--hirda->RxXferCount == 0)
{
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE);
if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)
{
hirda->State = HAL_IRDA_STATE_BUSY_TX;
}
else
{
/* Disable the IRDA Parity Error Interrupt */
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE);
/* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR);
hirda->State = HAL_IRDA_STATE_READY;
}
HAL_IRDA_RxCpltCallback(hirda);
return HAL_OK;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Configures the IRDA peripheral.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
static void IRDA_SetConfig(IRDA_HandleTypeDef *hirda)
{
/* Check the parameters */
assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate));
assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength));
assert_param(IS_IRDA_PARITY(hirda->Init.Parity));
assert_param(IS_IRDA_MODE(hirda->Init.Mode));
/*------- IRDA-associated USART registers setting : CR2 Configuration ------*/
/* Clear STOP[13:12] bits */
CLEAR_BIT(hirda->Instance->CR2, USART_CR2_STOP);
/*------- IRDA-associated USART registers setting : CR1 Configuration ------*/
/* Configure the USART Word Length, Parity and mode:
Set the M bits according to hirda->Init.WordLength value
Set PCE and PS bits according to hirda->Init.Parity value
Set TE and RE bits according to hirda->Init.Mode value */
MODIFY_REG(hirda->Instance->CR1,
((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)),
(uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode);
/*------- IRDA-associated USART registers setting : CR3 Configuration ------*/
/* Clear CTSE and RTSE bits */
CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE));
/*------- IRDA-associated USART registers setting : BRR Configuration ------*/
if(hirda->Instance == USART1)
{
hirda->Instance->BRR = IRDA_BRR(HAL_RCC_GetPCLK2Freq(), hirda->Init.BaudRate);
}
else
{
hirda->Instance->BRR = IRDA_BRR(HAL_RCC_GetPCLK1Freq(), hirda->Init.BaudRate);
}
}
/**
* @}
*/
#endif /* HAL_IRDA_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
b1v1r/ironbee | libs/luajit-2.0-ironbee/src/lj_asm.c | 56 | 57315 | /*
** IR assembler (SSA IR -> machine code).
** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_asm_c
#define LUA_CORE
#include "lj_obj.h"
#if LJ_HASJIT
#include "lj_gc.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_frame.h"
#if LJ_HASFFI
#include "lj_ctype.h"
#endif
#include "lj_ir.h"
#include "lj_jit.h"
#include "lj_ircall.h"
#include "lj_iropt.h"
#include "lj_mcode.h"
#include "lj_iropt.h"
#include "lj_trace.h"
#include "lj_snap.h"
#include "lj_asm.h"
#include "lj_dispatch.h"
#include "lj_vm.h"
#include "lj_target.h"
#ifdef LUA_USE_ASSERT
#include <stdio.h>
#endif
/* -- Assembler state and common macros ----------------------------------- */
/* Assembler state. */
typedef struct ASMState {
RegCost cost[RID_MAX]; /* Reference and blended allocation cost for regs. */
MCode *mcp; /* Current MCode pointer (grows down). */
MCode *mclim; /* Lower limit for MCode memory + red zone. */
#ifdef LUA_USE_ASSERT
MCode *mcp_prev; /* Red zone overflow check. */
#endif
IRIns *ir; /* Copy of pointer to IR instructions/constants. */
jit_State *J; /* JIT compiler state. */
#if LJ_TARGET_X86ORX64
x86ModRM mrm; /* Fused x86 address operand. */
#endif
RegSet freeset; /* Set of free registers. */
RegSet modset; /* Set of registers modified inside the loop. */
RegSet weakset; /* Set of weakly referenced registers. */
RegSet phiset; /* Set of PHI registers. */
uint32_t flags; /* Copy of JIT compiler flags. */
int loopinv; /* Loop branch inversion (0:no, 1:yes, 2:yes+CC_P). */
int32_t evenspill; /* Next even spill slot. */
int32_t oddspill; /* Next odd spill slot (or 0). */
IRRef curins; /* Reference of current instruction. */
IRRef stopins; /* Stop assembly before hitting this instruction. */
IRRef orignins; /* Original T->nins. */
IRRef snapref; /* Current snapshot is active after this reference. */
IRRef snaprename; /* Rename highwater mark for snapshot check. */
SnapNo snapno; /* Current snapshot number. */
SnapNo loopsnapno; /* Loop snapshot number. */
IRRef fuseref; /* Fusion limit (loopref, 0 or FUSE_DISABLED). */
IRRef sectref; /* Section base reference (loopref or 0). */
IRRef loopref; /* Reference of LOOP instruction (or 0). */
BCReg topslot; /* Number of slots for stack check (unless 0). */
int32_t gcsteps; /* Accumulated number of GC steps (per section). */
GCtrace *T; /* Trace to assemble. */
GCtrace *parent; /* Parent trace (or NULL). */
MCode *mcbot; /* Bottom of reserved MCode. */
MCode *mctop; /* Top of generated MCode. */
MCode *mcloop; /* Pointer to loop MCode (or NULL). */
MCode *invmcp; /* Points to invertible loop branch (or NULL). */
MCode *flagmcp; /* Pending opportunity to merge flag setting ins. */
MCode *realign; /* Realign loop if not NULL. */
#ifdef RID_NUM_KREF
int32_t krefk[RID_NUM_KREF];
#endif
IRRef1 phireg[RID_MAX]; /* PHI register references. */
uint16_t parentmap[LJ_MAX_JSLOTS]; /* Parent instruction to RegSP map. */
} ASMState;
#define IR(ref) (&as->ir[(ref)])
#define ASMREF_TMP1 REF_TRUE /* Temp. register. */
#define ASMREF_TMP2 REF_FALSE /* Temp. register. */
#define ASMREF_L REF_NIL /* Stores register for L. */
/* Check for variant to invariant references. */
#define iscrossref(as, ref) ((ref) < as->sectref)
/* Inhibit memory op fusion from variant to invariant references. */
#define FUSE_DISABLED (~(IRRef)0)
#define mayfuse(as, ref) ((ref) > as->fuseref)
#define neverfuse(as) (as->fuseref == FUSE_DISABLED)
#define canfuse(as, ir) (!neverfuse(as) && !irt_isphi((ir)->t))
#define opisfusableload(o) \
((o) == IR_ALOAD || (o) == IR_HLOAD || (o) == IR_ULOAD || \
(o) == IR_FLOAD || (o) == IR_XLOAD || (o) == IR_SLOAD || (o) == IR_VLOAD)
/* Sparse limit checks using a red zone before the actual limit. */
#define MCLIM_REDZONE 64
static LJ_NORET LJ_NOINLINE void asm_mclimit(ASMState *as)
{
lj_mcode_limiterr(as->J, (size_t)(as->mctop - as->mcp + 4*MCLIM_REDZONE));
}
static LJ_AINLINE void checkmclim(ASMState *as)
{
#ifdef LUA_USE_ASSERT
if (as->mcp + MCLIM_REDZONE < as->mcp_prev) {
IRIns *ir = IR(as->curins+1);
fprintf(stderr, "RED ZONE OVERFLOW: %p IR %04d %02d %04d %04d\n", as->mcp,
as->curins+1-REF_BIAS, ir->o, ir->op1-REF_BIAS, ir->op2-REF_BIAS);
lua_assert(0);
}
#endif
if (LJ_UNLIKELY(as->mcp < as->mclim)) asm_mclimit(as);
#ifdef LUA_USE_ASSERT
as->mcp_prev = as->mcp;
#endif
}
#ifdef RID_NUM_KREF
#define ra_iskref(ref) ((ref) < RID_NUM_KREF)
#define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref)))
#define ra_krefk(as, ref) (as->krefk[(ref)])
static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, int32_t k)
{
IRRef ref = (IRRef)(r - RID_MIN_KREF);
as->krefk[ref] = k;
as->cost[r] = REGCOST(ref, ref);
}
#else
#define ra_iskref(ref) 0
#define ra_krefreg(ref) RID_MIN_GPR
#define ra_krefk(as, ref) 0
#endif
/* Arch-specific field offsets. */
static const uint8_t field_ofs[IRFL__MAX+1] = {
#define FLOFS(name, ofs) (uint8_t)(ofs),
IRFLDEF(FLOFS)
#undef FLOFS
0
};
/* -- Target-specific instruction emitter --------------------------------- */
#if LJ_TARGET_X86ORX64
#include "lj_emit_x86.h"
#elif LJ_TARGET_ARM
#include "lj_emit_arm.h"
#elif LJ_TARGET_PPC
#include "lj_emit_ppc.h"
#elif LJ_TARGET_MIPS
#include "lj_emit_mips.h"
#else
#error "Missing instruction emitter for target CPU"
#endif
/* -- Register allocator debugging ---------------------------------------- */
/* #define LUAJIT_DEBUG_RA */
#ifdef LUAJIT_DEBUG_RA
#include <stdio.h>
#include <stdarg.h>
#define RIDNAME(name) #name,
static const char *const ra_regname[] = {
GPRDEF(RIDNAME)
FPRDEF(RIDNAME)
VRIDDEF(RIDNAME)
NULL
};
#undef RIDNAME
static char ra_dbg_buf[65536];
static char *ra_dbg_p;
static char *ra_dbg_merge;
static MCode *ra_dbg_mcp;
static void ra_dstart(void)
{
ra_dbg_p = ra_dbg_buf;
ra_dbg_merge = NULL;
ra_dbg_mcp = NULL;
}
static void ra_dflush(void)
{
fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
ra_dstart();
}
static void ra_dprintf(ASMState *as, const char *fmt, ...)
{
char *p;
va_list argp;
va_start(argp, fmt);
p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
ra_dbg_mcp = NULL;
p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
for (;;) {
const char *e = strchr(fmt, '$');
if (e == NULL) break;
memcpy(p, fmt, (size_t)(e-fmt));
p += e-fmt;
if (e[1] == 'r') {
Reg r = va_arg(argp, Reg) & RID_MASK;
if (r <= RID_MAX) {
const char *q;
for (q = ra_regname[r]; *q; q++)
*p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
} else {
*p++ = '?';
lua_assert(0);
}
} else if (e[1] == 'f' || e[1] == 'i') {
IRRef ref;
if (e[1] == 'f')
ref = va_arg(argp, IRRef);
else
ref = va_arg(argp, IRIns *) - as->ir;
if (ref >= REF_BIAS)
p += sprintf(p, "%04d", ref - REF_BIAS);
else
p += sprintf(p, "K%03d", REF_BIAS - ref);
} else if (e[1] == 's') {
uint32_t slot = va_arg(argp, uint32_t);
p += sprintf(p, "[sp+0x%x]", sps_scale(slot));
} else if (e[1] == 'x') {
p += sprintf(p, "%08x", va_arg(argp, int32_t));
} else {
lua_assert(0);
}
fmt = e+2;
}
va_end(argp);
while (*fmt)
*p++ = *fmt++;
*p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n';
if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) {
fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout);
p = ra_dbg_buf;
}
ra_dbg_p = p;
}
#define RA_DBG_START() ra_dstart()
#define RA_DBG_FLUSH() ra_dflush()
#define RA_DBG_REF() \
do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
#define RA_DBGX(x) ra_dprintf x
#else
#define RA_DBG_START() ((void)0)
#define RA_DBG_FLUSH() ((void)0)
#define RA_DBG_REF() ((void)0)
#define RA_DBGX(x) ((void)0)
#endif
/* -- Register allocator -------------------------------------------------- */
#define ra_free(as, r) rset_set(as->freeset, (r))
#define ra_modified(as, r) rset_set(as->modset, (r))
#define ra_weak(as, r) rset_set(as->weakset, (r))
#define ra_noweak(as, r) rset_clear(as->weakset, (r))
#define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
/* Setup register allocator. */
static void ra_setup(ASMState *as)
{
Reg r;
/* Initially all regs (except the stack pointer) are free for use. */
as->freeset = RSET_INIT;
as->modset = RSET_EMPTY;
as->weakset = RSET_EMPTY;
as->phiset = RSET_EMPTY;
memset(as->phireg, 0, sizeof(as->phireg));
for (r = RID_MIN_GPR; r < RID_MAX; r++)
as->cost[r] = REGCOST(~0u, 0u);
}
/* Rematerialize constants. */
static Reg ra_rematk(ASMState *as, IRRef ref)
{
IRIns *ir;
Reg r;
if (ra_iskref(ref)) {
r = ra_krefreg(ref);
lua_assert(!rset_test(as->freeset, r));
ra_free(as, r);
ra_modified(as, r);
emit_loadi(as, r, ra_krefk(as, ref));
return r;
}
ir = IR(ref);
r = ir->r;
lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
ra_free(as, r);
ra_modified(as, r);
ir->r = RID_INIT; /* Do not keep any hint. */
RA_DBGX((as, "remat $i $r", ir, r));
#if !LJ_SOFTFP
if (ir->o == IR_KNUM) {
emit_loadn(as, r, ir_knum(ir));
} else
#endif
if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
ra_sethint(ir->r, RID_BASE); /* Restore BASE register hint. */
emit_getgl(as, r, jit_base);
} else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */
emit_getgl(as, r, jit_L);
#if LJ_64
} else if (ir->o == IR_KINT64) {
emit_loadu64(as, r, ir_kint64(ir)->u64);
#endif
} else {
lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
emit_loadi(as, r, ir->i);
}
return r;
}
/* Force a spill. Allocate a new spill slot if needed. */
static int32_t ra_spill(ASMState *as, IRIns *ir)
{
int32_t slot = ir->s;
if (!ra_hasspill(slot)) {
if (irt_is64(ir->t)) {
slot = as->evenspill;
as->evenspill += 2;
} else if (as->oddspill) {
slot = as->oddspill;
as->oddspill = 0;
} else {
slot = as->evenspill;
as->oddspill = slot+1;
as->evenspill += 2;
}
if (as->evenspill > 256)
lj_trace_err(as->J, LJ_TRERR_SPILLOV);
ir->s = (uint8_t)slot;
}
return sps_scale(slot);
}
/* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
static Reg ra_releasetmp(ASMState *as, IRRef ref)
{
IRIns *ir = IR(ref);
Reg r = ir->r;
lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
ra_free(as, r);
ra_modified(as, r);
ir->r = RID_INIT;
return r;
}
/* Restore a register (marked as free). Rematerialize or force a spill. */
static Reg ra_restore(ASMState *as, IRRef ref)
{
if (emit_canremat(ref)) {
return ra_rematk(as, ref);
} else {
IRIns *ir = IR(ref);
int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */
Reg r = ir->r;
lua_assert(ra_hasreg(r));
ra_sethint(ir->r, r); /* Keep hint. */
ra_free(as, r);
if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */
ra_modified(as, r);
RA_DBGX((as, "restore $i $r", ir, r));
emit_spload(as, ir, r, ofs);
}
return r;
}
}
/* Save a register to a spill slot. */
static void ra_save(ASMState *as, IRIns *ir, Reg r)
{
RA_DBGX((as, "save $i $r", ir, r));
emit_spstore(as, ir, r, sps_scale(ir->s));
}
#define MINCOST(name) \
if (rset_test(RSET_ALL, RID_##name) && \
LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
cost = as->cost[RID_##name];
/* Evict the register with the lowest cost, forcing a restore. */
static Reg ra_evict(ASMState *as, RegSet allow)
{
IRRef ref;
RegCost cost = ~(RegCost)0;
lua_assert(allow != RSET_EMPTY);
if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
GPRDEF(MINCOST)
} else {
FPRDEF(MINCOST)
}
ref = regcost_ref(cost);
lua_assert(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins));
/* Preferably pick any weak ref instead of a non-weak, non-const ref. */
if (!irref_isk(ref) && (as->weakset & allow)) {
IRIns *ir = IR(ref);
if (!rset_test(as->weakset, ir->r))
ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
}
return ra_restore(as, ref);
}
/* Pick any register (marked as free). Evict on-demand. */
static Reg ra_pick(ASMState *as, RegSet allow)
{
RegSet pick = as->freeset & allow;
if (!pick)
return ra_evict(as, allow);
else
return rset_picktop(pick);
}
/* Get a scratch register (marked as free). */
static Reg ra_scratch(ASMState *as, RegSet allow)
{
Reg r = ra_pick(as, allow);
ra_modified(as, r);
RA_DBGX((as, "scratch $r", r));
return r;
}
/* Evict all registers from a set (if not free). */
static void ra_evictset(ASMState *as, RegSet drop)
{
RegSet work;
as->modset |= drop;
#if !LJ_SOFTFP
work = (drop & ~as->freeset) & RSET_FPR;
while (work) {
Reg r = rset_pickbot(work);
ra_restore(as, regcost_ref(as->cost[r]));
rset_clear(work, r);
checkmclim(as);
}
#endif
work = (drop & ~as->freeset);
while (work) {
Reg r = rset_pickbot(work);
ra_restore(as, regcost_ref(as->cost[r]));
rset_clear(work, r);
checkmclim(as);
}
}
/* Evict (rematerialize) all registers allocated to constants. */
static void ra_evictk(ASMState *as)
{
RegSet work;
#if !LJ_SOFTFP
work = ~as->freeset & RSET_FPR;
while (work) {
Reg r = rset_pickbot(work);
IRRef ref = regcost_ref(as->cost[r]);
if (emit_canremat(ref) && irref_isk(ref)) {
ra_rematk(as, ref);
checkmclim(as);
}
rset_clear(work, r);
}
#endif
work = ~as->freeset & RSET_GPR;
while (work) {
Reg r = rset_pickbot(work);
IRRef ref = regcost_ref(as->cost[r]);
if (emit_canremat(ref) && irref_isk(ref)) {
ra_rematk(as, ref);
checkmclim(as);
}
rset_clear(work, r);
}
}
#ifdef RID_NUM_KREF
/* Allocate a register for a constant. */
static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
{
/* First try to find a register which already holds the same constant. */
RegSet pick, work = ~as->freeset & RSET_GPR;
Reg r;
while (work) {
IRRef ref;
r = rset_pickbot(work);
ref = regcost_ref(as->cost[r]);
if (ref < ASMREF_L &&
k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
return r;
rset_clear(work, r);
}
pick = as->freeset & allow;
if (pick) {
/* Constants should preferably get unmodified registers. */
if ((pick & ~as->modset))
pick &= ~as->modset;
r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
} else {
r = ra_evict(as, allow);
}
RA_DBGX((as, "allock $x $r", k, r));
ra_setkref(as, r, k);
rset_clear(as->freeset, r);
ra_noweak(as, r);
return r;
}
/* Allocate a specific register for a constant. */
static void ra_allockreg(ASMState *as, int32_t k, Reg r)
{
Reg kr = ra_allock(as, k, RID2RSET(r));
if (kr != r) {
IRIns irdummy;
irdummy.t.irt = IRT_INT;
ra_scratch(as, RID2RSET(r));
emit_movrr(as, &irdummy, r, kr);
}
}
#else
#define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
#endif
/* Allocate a register for ref from the allowed set of registers.
** Note: this function assumes the ref does NOT have a register yet!
** Picks an optimal register, sets the cost and marks the register as non-free.
*/
static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
{
IRIns *ir = IR(ref);
RegSet pick = as->freeset & allow;
Reg r;
lua_assert(ra_noreg(ir->r));
if (pick) {
/* First check register hint from propagation or PHI. */
if (ra_hashint(ir->r)) {
r = ra_gethint(ir->r);
if (rset_test(pick, r)) /* Use hint register if possible. */
goto found;
/* Rematerialization is cheaper than missing a hint. */
if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) {
ra_rematk(as, regcost_ref(as->cost[r]));
goto found;
}
RA_DBGX((as, "hintmiss $f $r", ref, r));
}
/* Invariants should preferably get unmodified registers. */
if (ref < as->loopref && !irt_isphi(ir->t)) {
if ((pick & ~as->modset))
pick &= ~as->modset;
r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
} else {
/* We've got plenty of regs, so get callee-save regs if possible. */
if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH))
pick &= ~RSET_SCRATCH;
r = rset_picktop(pick);
}
} else {
r = ra_evict(as, allow);
}
found:
RA_DBGX((as, "alloc $f $r", ref, r));
ir->r = (uint8_t)r;
rset_clear(as->freeset, r);
ra_noweak(as, r);
as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
return r;
}
/* Allocate a register on-demand. */
static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
{
Reg r = IR(ref)->r;
/* Note: allow is ignored if the register is already allocated. */
if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
ra_noweak(as, r);
return r;
}
/* Rename register allocation and emit move. */
static void ra_rename(ASMState *as, Reg down, Reg up)
{
IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]);
IRIns *ir = IR(ref);
ir->r = (uint8_t)up;
as->cost[down] = 0;
lua_assert((down < RID_MAX_GPR) == (up < RID_MAX_GPR));
lua_assert(!rset_test(as->freeset, down) && rset_test(as->freeset, up));
ra_free(as, down); /* 'down' is free ... */
ra_modified(as, down);
rset_clear(as->freeset, up); /* ... and 'up' is now allocated. */
ra_noweak(as, up);
RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up));
emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */
if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */
lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, as->snapno);
ren = tref_ref(lj_ir_emit(as->J));
as->ir = as->T->ir; /* The IR may have been reallocated. */
IR(ren)->r = (uint8_t)down;
IR(ren)->s = SPS_NONE;
}
}
/* Pick a destination register (marked as free).
** Caveat: allow is ignored if there's already a destination register.
** Use ra_destreg() to get a specific register.
*/
static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
{
Reg dest = ir->r;
if (ra_hasreg(dest)) {
ra_free(as, dest);
ra_modified(as, dest);
} else {
if (ra_hashint(dest) && rset_test((as->freeset&allow), ra_gethint(dest))) {
dest = ra_gethint(dest);
ra_modified(as, dest);
RA_DBGX((as, "dest $r", dest));
} else {
dest = ra_scratch(as, allow);
}
ir->r = dest;
}
if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
return dest;
}
/* Force a specific destination register (marked as free). */
static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
{
Reg dest = ra_dest(as, ir, RID2RSET(r));
if (dest != r) {
lua_assert(rset_test(as->freeset, r));
ra_modified(as, r);
emit_movrr(as, ir, dest, r);
}
}
#if LJ_TARGET_X86ORX64
/* Propagate dest register to left reference. Emit moves as needed.
** This is a required fixup step for all 2-operand machine instructions.
*/
static void ra_left(ASMState *as, Reg dest, IRRef lref)
{
IRIns *ir = IR(lref);
Reg left = ir->r;
if (ra_noreg(left)) {
if (irref_isk(lref)) {
if (ir->o == IR_KNUM) {
cTValue *tv = ir_knum(ir);
/* FP remat needs a load except for +0. Still better than eviction. */
if (tvispzero(tv) || !(as->freeset & RSET_FPR)) {
emit_loadn(as, dest, tv);
return;
}
#if LJ_64
} else if (ir->o == IR_KINT64) {
emit_loadu64(as, dest, ir_kint64(ir)->u64);
return;
#endif
} else {
lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
emit_loadi(as, dest, ir->i);
return;
}
}
if (!ra_hashint(left) && !iscrossref(as, lref))
ra_sethint(ir->r, dest); /* Propagate register hint. */
left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR);
}
ra_noweak(as, left);
/* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
if (dest != left) {
/* Use register renaming if dest is the PHI reg. */
if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
ra_modified(as, left);
ra_rename(as, left, dest);
} else {
emit_movrr(as, ir, dest, left);
}
}
}
#else
/* Similar to ra_left, except we override any hints. */
static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
{
IRIns *ir = IR(lref);
Reg left = ir->r;
if (ra_noreg(left)) {
ra_sethint(ir->r, dest); /* Propagate register hint. */
left = ra_allocref(as, lref,
(LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR);
}
ra_noweak(as, left);
if (dest != left) {
/* Use register renaming if dest is the PHI reg. */
if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
ra_modified(as, left);
ra_rename(as, left, dest);
} else {
emit_movrr(as, ir, dest, left);
}
}
}
#endif
#if !LJ_64
/* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
static void ra_destpair(ASMState *as, IRIns *ir)
{
Reg destlo = ir->r, desthi = (ir+1)->r;
/* First spill unrelated refs blocking the destination registers. */
if (!rset_test(as->freeset, RID_RETLO) &&
destlo != RID_RETLO && desthi != RID_RETLO)
ra_restore(as, regcost_ref(as->cost[RID_RETLO]));
if (!rset_test(as->freeset, RID_RETHI) &&
destlo != RID_RETHI && desthi != RID_RETHI)
ra_restore(as, regcost_ref(as->cost[RID_RETHI]));
/* Next free the destination registers (if any). */
if (ra_hasreg(destlo)) {
ra_free(as, destlo);
ra_modified(as, destlo);
} else {
destlo = RID_RETLO;
}
if (ra_hasreg(desthi)) {
ra_free(as, desthi);
ra_modified(as, desthi);
} else {
desthi = RID_RETHI;
}
/* Check for conflicts and shuffle the registers as needed. */
if (destlo == RID_RETHI) {
if (desthi == RID_RETLO) {
#if LJ_TARGET_X86
*--as->mcp = XI_XCHGa + RID_RETHI;
#else
emit_movrr(as, ir, RID_RETHI, RID_TMP);
emit_movrr(as, ir, RID_RETLO, RID_RETHI);
emit_movrr(as, ir, RID_TMP, RID_RETLO);
#endif
} else {
emit_movrr(as, ir, RID_RETHI, RID_RETLO);
if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
}
} else if (desthi == RID_RETLO) {
emit_movrr(as, ir, RID_RETLO, RID_RETHI);
if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
} else {
if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
}
/* Restore spill slots (if any). */
if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI);
if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO);
}
#endif
/* -- Snapshot handling --------- ----------------------------------------- */
/* Can we rematerialize a KNUM instead of forcing a spill? */
static int asm_snap_canremat(ASMState *as)
{
Reg r;
for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
if (irref_isk(regcost_ref(as->cost[r])))
return 1;
return 0;
}
/* Check whether a sunk store corresponds to an allocation. */
static int asm_sunk_store(ASMState *as, IRIns *ira, IRIns *irs)
{
if (irs->s == 255) {
if (irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
irs->o == IR_FSTORE || irs->o == IR_XSTORE) {
IRIns *irk = IR(irs->op1);
if (irk->o == IR_AREF || irk->o == IR_HREFK)
irk = IR(irk->op1);
return (IR(irk->op1) == ira);
}
return 0;
} else {
return (ira + irs->s == irs); /* Quick check. */
}
}
/* Allocate register or spill slot for a ref that escapes to a snapshot. */
static void asm_snap_alloc1(ASMState *as, IRRef ref)
{
IRIns *ir = IR(ref);
if (!irref_isk(ref) && (!(ra_used(ir) || ir->r == RID_SUNK))) {
if (ir->r == RID_SINK) {
ir->r = RID_SUNK;
#if LJ_HASFFI
if (ir->o == IR_CNEWI) { /* Allocate CNEWI value. */
asm_snap_alloc1(as, ir->op2);
if (LJ_32 && (ir+1)->o == IR_HIOP)
asm_snap_alloc1(as, (ir+1)->op2);
} else
#endif
{ /* Allocate stored values for TNEW, TDUP and CNEW. */
IRIns *irs;
lua_assert(ir->o == IR_TNEW || ir->o == IR_TDUP || ir->o == IR_CNEW);
for (irs = IR(as->snapref-1); irs > ir; irs--)
if (irs->r == RID_SINK && asm_sunk_store(as, ir, irs)) {
lua_assert(irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
irs->o == IR_FSTORE || irs->o == IR_XSTORE);
asm_snap_alloc1(as, irs->op2);
if (LJ_32 && (irs+1)->o == IR_HIOP)
asm_snap_alloc1(as, (irs+1)->op2);
}
}
} else {
RegSet allow;
if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT) {
IRIns *irc;
for (irc = IR(as->curins); irc > ir; irc--)
if ((irc->op1 == ref || irc->op2 == ref) &&
!(irc->r == RID_SINK || irc->r == RID_SUNK))
goto nosink; /* Don't sink conversion if result is used. */
asm_snap_alloc1(as, ir->op1);
return;
}
nosink:
allow = (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR;
if ((as->freeset & allow) ||
(allow == RSET_FPR && asm_snap_canremat(as))) {
/* Get a weak register if we have a free one or can rematerialize. */
Reg r = ra_allocref(as, ref, allow); /* Allocate a register. */
if (!irt_isphi(ir->t))
ra_weak(as, r); /* But mark it as weakly referenced. */
checkmclim(as);
RA_DBGX((as, "snapreg $f $r", ref, ir->r));
} else {
ra_spill(as, ir); /* Otherwise force a spill slot. */
RA_DBGX((as, "snapspill $f $s", ref, ir->s));
}
}
}
}
/* Allocate refs escaping to a snapshot. */
static void asm_snap_alloc(ASMState *as)
{
SnapShot *snap = &as->T->snap[as->snapno];
SnapEntry *map = &as->T->snapmap[snap->mapofs];
MSize n, nent = snap->nent;
for (n = 0; n < nent; n++) {
SnapEntry sn = map[n];
IRRef ref = snap_ref(sn);
if (!irref_isk(ref)) {
asm_snap_alloc1(as, ref);
if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM)) {
lua_assert(irt_type(IR(ref+1)->t) == IRT_SOFTFP);
asm_snap_alloc1(as, ref+1);
}
}
}
}
/* All guards for a snapshot use the same exitno. This is currently the
** same as the snapshot number. Since the exact origin of the exit cannot
** be determined, all guards for the same snapshot must exit with the same
** RegSP mapping.
** A renamed ref which has been used in a prior guard for the same snapshot
** would cause an inconsistency. The easy way out is to force a spill slot.
*/
static int asm_snap_checkrename(ASMState *as, IRRef ren)
{
SnapShot *snap = &as->T->snap[as->snapno];
SnapEntry *map = &as->T->snapmap[snap->mapofs];
MSize n, nent = snap->nent;
for (n = 0; n < nent; n++) {
SnapEntry sn = map[n];
IRRef ref = snap_ref(sn);
if (ref == ren || (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM) && ++ref == ren)) {
IRIns *ir = IR(ref);
ra_spill(as, ir); /* Register renamed, so force a spill slot. */
RA_DBGX((as, "snaprensp $f $s", ref, ir->s));
return 1; /* Found. */
}
}
return 0; /* Not found. */
}
/* Prepare snapshot for next guard instruction. */
static void asm_snap_prep(ASMState *as)
{
if (as->curins < as->snapref) {
do {
if (as->snapno == 0) return; /* Called by sunk stores before snap #0. */
as->snapno--;
as->snapref = as->T->snap[as->snapno].ref;
} while (as->curins < as->snapref);
asm_snap_alloc(as);
as->snaprename = as->T->nins;
} else {
/* Process any renames above the highwater mark. */
for (; as->snaprename < as->T->nins; as->snaprename++) {
IRIns *ir = IR(as->snaprename);
if (asm_snap_checkrename(as, ir->op1))
ir->op2 = REF_BIAS-1; /* Kill rename. */
}
}
}
/* -- Miscellaneous helpers ----------------------------------------------- */
/* Collect arguments from CALL* and CARG instructions. */
static void asm_collectargs(ASMState *as, IRIns *ir,
const CCallInfo *ci, IRRef *args)
{
uint32_t n = CCI_NARGS(ci);
lua_assert(n <= CCI_NARGS_MAX*2); /* Account for split args. */
if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
while (n-- > 1) {
ir = IR(ir->op1);
lua_assert(ir->o == IR_CARG);
args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
}
args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
lua_assert(IR(ir->op1)->o != IR_CARG);
}
/* Reconstruct CCallInfo flags for CALLX*. */
static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
{
uint32_t nargs = 0;
if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
IRIns *ira = IR(ir->op1);
nargs++;
while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
}
#if LJ_HASFFI
if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */
CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
#if LJ_TARGET_X86
nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
#endif
}
#endif
return (nargs | (ir->t.irt << CCI_OTSHIFT));
}
/* Calculate stack adjustment. */
static int32_t asm_stack_adjust(ASMState *as)
{
if (as->evenspill <= SPS_FIXED)
return 0;
return sps_scale(sps_align(as->evenspill));
}
/* Must match with hash*() in lj_tab.c. */
static uint32_t ir_khash(IRIns *ir)
{
uint32_t lo, hi;
if (irt_isstr(ir->t)) {
return ir_kstr(ir)->hash;
} else if (irt_isnum(ir->t)) {
lo = ir_knum(ir)->u32.lo;
hi = ir_knum(ir)->u32.hi << 1;
} else if (irt_ispri(ir->t)) {
lua_assert(!irt_isnil(ir->t));
return irt_type(ir->t)-IRT_FALSE;
} else {
lua_assert(irt_isgcv(ir->t));
lo = u32ptr(ir_kgc(ir));
hi = lo + HASH_BIAS;
}
return hashrot(lo, hi);
}
/* -- Allocations --------------------------------------------------------- */
static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
static void asm_snew(ASMState *as, IRIns *ir)
{
const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
IRRef args[3];
args[0] = ASMREF_L; /* lua_State *L */
args[1] = ir->op1; /* const char *str */
args[2] = ir->op2; /* size_t len */
as->gcsteps++;
asm_setupresult(as, ir, ci); /* GCstr * */
asm_gencall(as, ci, args);
}
static void asm_tnew(ASMState *as, IRIns *ir)
{
const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
IRRef args[2];
args[0] = ASMREF_L; /* lua_State *L */
args[1] = ASMREF_TMP1; /* uint32_t ahsize */
as->gcsteps++;
asm_setupresult(as, ir, ci); /* GCtab * */
asm_gencall(as, ci, args);
ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1));
}
static void asm_tdup(ASMState *as, IRIns *ir)
{
const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
IRRef args[2];
args[0] = ASMREF_L; /* lua_State *L */
args[1] = ir->op1; /* const GCtab *kt */
as->gcsteps++;
asm_setupresult(as, ir, ci); /* GCtab * */
asm_gencall(as, ci, args);
}
static void asm_gc_check(ASMState *as);
/* Explicit GC step. */
static void asm_gcstep(ASMState *as, IRIns *ir)
{
IRIns *ira;
for (ira = IR(as->stopins+1); ira < ir; ira++)
if ((ira->o == IR_TNEW || ira->o == IR_TDUP ||
(LJ_HASFFI && (ira->o == IR_CNEW || ira->o == IR_CNEWI))) &&
ra_used(ira))
as->gcsteps++;
if (as->gcsteps)
asm_gc_check(as);
as->gcsteps = 0x80000000; /* Prevent implicit GC check further up. */
}
/* -- PHI and loop handling ----------------------------------------------- */
/* Break a PHI cycle by renaming to a free register (evict if needed). */
static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
RegSet allow)
{
RegSet candidates = blocked & allow;
if (candidates) { /* If this register file has candidates. */
/* Note: the set for ra_pick cannot be empty, since each register file
** has some registers never allocated to PHIs.
*/
Reg down, up = ra_pick(as, ~blocked & allow); /* Get a free register. */
if (candidates & ~blockedby) /* Optimize shifts, else it's a cycle. */
candidates = candidates & ~blockedby;
down = rset_picktop(candidates); /* Pick candidate PHI register. */
ra_rename(as, down, up); /* And rename it to the free register. */
}
}
/* PHI register shuffling.
**
** The allocator tries hard to preserve PHI register assignments across
** the loop body. Most of the time this loop does nothing, since there
** are no register mismatches.
**
** If a register mismatch is detected and ...
** - the register is currently free: rename it.
** - the register is blocked by an invariant: restore/remat and rename it.
** - Otherwise the register is used by another PHI, so mark it as blocked.
**
** The renames are order-sensitive, so just retry the loop if a register
** is marked as blocked, but has been freed in the meantime. A cycle is
** detected if all of the blocked registers are allocated. To break the
** cycle rename one of them to a free register and retry.
**
** Note that PHI spill slots are kept in sync and don't need to be shuffled.
*/
static void asm_phi_shuffle(ASMState *as)
{
RegSet work;
/* Find and resolve PHI register mismatches. */
for (;;) {
RegSet blocked = RSET_EMPTY;
RegSet blockedby = RSET_EMPTY;
RegSet phiset = as->phiset;
while (phiset) { /* Check all left PHI operand registers. */
Reg r = rset_pickbot(phiset);
IRIns *irl = IR(as->phireg[r]);
Reg left = irl->r;
if (r != left) { /* Mismatch? */
if (!rset_test(as->freeset, r)) { /* PHI register blocked? */
IRRef ref = regcost_ref(as->cost[r]);
/* Blocked by other PHI (w/reg)? */
if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) {
rset_set(blocked, r);
if (ra_hasreg(left))
rset_set(blockedby, left);
left = RID_NONE;
} else { /* Otherwise grab register from invariant. */
ra_restore(as, ref);
checkmclim(as);
}
}
if (ra_hasreg(left)) {
ra_rename(as, left, r);
checkmclim(as);
}
}
rset_clear(phiset, r);
}
if (!blocked) break; /* Finished. */
if (!(as->freeset & blocked)) { /* Break cycles if none are free. */
asm_phi_break(as, blocked, blockedby, RSET_GPR);
if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR);
checkmclim(as);
} /* Else retry some more renames. */
}
/* Restore/remat invariants whose registers are modified inside the loop. */
#if !LJ_SOFTFP
work = as->modset & ~(as->freeset | as->phiset) & RSET_FPR;
while (work) {
Reg r = rset_pickbot(work);
ra_restore(as, regcost_ref(as->cost[r]));
rset_clear(work, r);
checkmclim(as);
}
#endif
work = as->modset & ~(as->freeset | as->phiset);
while (work) {
Reg r = rset_pickbot(work);
ra_restore(as, regcost_ref(as->cost[r]));
rset_clear(work, r);
checkmclim(as);
}
/* Allocate and save all unsaved PHI regs and clear marks. */
work = as->phiset;
while (work) {
Reg r = rset_picktop(work);
IRRef lref = as->phireg[r];
IRIns *ir = IR(lref);
if (ra_hasspill(ir->s)) { /* Left PHI gained a spill slot? */
irt_clearmark(ir->t); /* Handled here, so clear marker now. */
ra_alloc1(as, lref, RID2RSET(r));
ra_save(as, ir, r); /* Save to spill slot inside the loop. */
checkmclim(as);
}
rset_clear(work, r);
}
}
/* Copy unsynced left/right PHI spill slots. Rarely needed. */
static void asm_phi_copyspill(ASMState *as)
{
int need = 0;
IRIns *ir;
for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--)
if (ra_hasspill(ir->s) && ra_hasspill(IR(ir->op1)->s))
need |= irt_isfp(ir->t) ? 2 : 1; /* Unsynced spill slot? */
if ((need & 1)) { /* Copy integer spill slots. */
#if !LJ_TARGET_X86ORX64
Reg r = RID_TMP;
#else
Reg r = RID_RET;
if ((as->freeset & RSET_GPR))
r = rset_pickbot((as->freeset & RSET_GPR));
else
emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
#endif
for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
if (ra_hasspill(ir->s)) {
IRIns *irl = IR(ir->op1);
if (ra_hasspill(irl->s) && !irt_isfp(ir->t)) {
emit_spstore(as, irl, r, sps_scale(irl->s));
emit_spload(as, ir, r, sps_scale(ir->s));
checkmclim(as);
}
}
}
#if LJ_TARGET_X86ORX64
if (!rset_test(as->freeset, r))
emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
#endif
}
#if !LJ_SOFTFP
if ((need & 2)) { /* Copy FP spill slots. */
#if LJ_TARGET_X86
Reg r = RID_XMM0;
#else
Reg r = RID_FPRET;
#endif
if ((as->freeset & RSET_FPR))
r = rset_pickbot((as->freeset & RSET_FPR));
if (!rset_test(as->freeset, r))
emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
if (ra_hasspill(ir->s)) {
IRIns *irl = IR(ir->op1);
if (ra_hasspill(irl->s) && irt_isfp(ir->t)) {
emit_spstore(as, irl, r, sps_scale(irl->s));
emit_spload(as, ir, r, sps_scale(ir->s));
checkmclim(as);
}
}
}
if (!rset_test(as->freeset, r))
emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
}
#endif
}
/* Emit renames for left PHIs which are only spilled outside the loop. */
static void asm_phi_fixup(ASMState *as)
{
RegSet work = as->phiset;
while (work) {
Reg r = rset_picktop(work);
IRRef lref = as->phireg[r];
IRIns *ir = IR(lref);
if (irt_ismarked(ir->t)) {
irt_clearmark(ir->t);
/* Left PHI gained a spill slot before the loop? */
if (ra_hasspill(ir->s)) {
IRRef ren;
lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), lref, as->loopsnapno);
ren = tref_ref(lj_ir_emit(as->J));
as->ir = as->T->ir; /* The IR may have been reallocated. */
IR(ren)->r = (uint8_t)r;
IR(ren)->s = SPS_NONE;
}
}
rset_clear(work, r);
}
}
/* Setup right PHI reference. */
static void asm_phi(ASMState *as, IRIns *ir)
{
RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
~as->phiset;
RegSet afree = (as->freeset & allow);
IRIns *irl = IR(ir->op1);
IRIns *irr = IR(ir->op2);
if (ir->r == RID_SINK) /* Sink PHI. */
return;
/* Spill slot shuffling is not implemented yet (but rarely needed). */
if (ra_hasspill(irl->s) || ra_hasspill(irr->s))
lj_trace_err(as->J, LJ_TRERR_NYIPHI);
/* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
if ((afree & (afree-1))) { /* Two or more free registers? */
Reg r;
if (ra_noreg(irr->r)) { /* Get a register for the right PHI. */
r = ra_allocref(as, ir->op2, allow);
} else { /* Duplicate right PHI, need a copy (rare). */
r = ra_scratch(as, allow);
emit_movrr(as, irr, r, irr->r);
}
ir->r = (uint8_t)r;
rset_set(as->phiset, r);
as->phireg[r] = (IRRef1)ir->op1;
irt_setmark(irl->t); /* Marks left PHIs _with_ register. */
if (ra_noreg(irl->r))
ra_sethint(irl->r, r); /* Set register hint for left PHI. */
} else { /* Otherwise allocate a spill slot. */
/* This is overly restrictive, but it triggers only on synthetic code. */
if (ra_hasreg(irl->r) || ra_hasreg(irr->r))
lj_trace_err(as->J, LJ_TRERR_NYIPHI);
ra_spill(as, ir);
irr->s = ir->s; /* Set right PHI spill slot. Sync left slot later. */
}
}
static void asm_loop_fixup(ASMState *as);
/* Middle part of a loop. */
static void asm_loop(ASMState *as)
{
MCode *mcspill;
/* LOOP is a guard, so the snapno is up to date. */
as->loopsnapno = as->snapno;
if (as->gcsteps)
asm_gc_check(as);
/* LOOP marks the transition from the variant to the invariant part. */
as->flagmcp = as->invmcp = NULL;
as->sectref = 0;
if (!neverfuse(as)) as->fuseref = 0;
asm_phi_shuffle(as);
mcspill = as->mcp;
asm_phi_copyspill(as);
asm_loop_fixup(as);
as->mcloop = as->mcp;
RA_DBGX((as, "===== LOOP ====="));
if (!as->realign) RA_DBG_FLUSH();
if (as->mcp != mcspill)
emit_jmp(as, mcspill);
}
/* -- Target-specific assembler ------------------------------------------- */
#if LJ_TARGET_X86ORX64
#include "lj_asm_x86.h"
#elif LJ_TARGET_ARM
#include "lj_asm_arm.h"
#elif LJ_TARGET_PPC
#include "lj_asm_ppc.h"
#elif LJ_TARGET_MIPS
#include "lj_asm_mips.h"
#else
#error "Missing assembler for target CPU"
#endif
/* -- Head of trace ------------------------------------------------------- */
/* Head of a root trace. */
static void asm_head_root(ASMState *as)
{
int32_t spadj;
asm_head_root_base(as);
emit_setvmstate(as, (int32_t)as->T->traceno);
spadj = asm_stack_adjust(as);
as->T->spadjust = (uint16_t)spadj;
emit_spsub(as, spadj);
/* Root traces assume a checked stack for the starting proto. */
as->T->topslot = gcref(as->T->startpt)->pt.framesize;
}
/* Head of a side trace.
**
** The current simplistic algorithm requires that all slots inherited
** from the parent are live in a register between pass 2 and pass 3. This
** avoids the complexity of stack slot shuffling. But of course this may
** overflow the register set in some cases and cause the dreaded error:
** "NYI: register coalescing too complex". A refined algorithm is needed.
*/
static void asm_head_side(ASMState *as)
{
IRRef1 sloadins[RID_MAX];
RegSet allow = RSET_ALL; /* Inverse of all coalesced registers. */
RegSet live = RSET_EMPTY; /* Live parent registers. */
IRIns *irp = &as->parent->ir[REF_BASE]; /* Parent base. */
int32_t spadj, spdelta;
int pass2 = 0;
int pass3 = 0;
IRRef i;
allow = asm_head_side_base(as, irp, allow);
/* Scan all parent SLOADs and collect register dependencies. */
for (i = as->stopins; i > REF_BASE; i--) {
IRIns *ir = IR(i);
RegSP rs;
lua_assert((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) ||
(LJ_SOFTFP && ir->o == IR_HIOP) || ir->o == IR_PVAL);
rs = as->parentmap[i - REF_FIRST];
if (ra_hasreg(ir->r)) {
rset_clear(allow, ir->r);
if (ra_hasspill(ir->s)) {
ra_save(as, ir, ir->r);
checkmclim(as);
}
} else if (ra_hasspill(ir->s)) {
irt_setmark(ir->t);
pass2 = 1;
}
if (ir->r == rs) { /* Coalesce matching registers right now. */
ra_free(as, ir->r);
} else if (ra_hasspill(regsp_spill(rs))) {
if (ra_hasreg(ir->r))
pass3 = 1;
} else if (ra_used(ir)) {
sloadins[rs] = (IRRef1)i;
rset_set(live, rs); /* Block live parent register. */
}
}
/* Calculate stack frame adjustment. */
spadj = asm_stack_adjust(as);
spdelta = spadj - (int32_t)as->parent->spadjust;
if (spdelta < 0) { /* Don't shrink the stack frame. */
spadj = (int32_t)as->parent->spadjust;
spdelta = 0;
}
as->T->spadjust = (uint16_t)spadj;
/* Reload spilled target registers. */
if (pass2) {
for (i = as->stopins; i > REF_BASE; i--) {
IRIns *ir = IR(i);
if (irt_ismarked(ir->t)) {
RegSet mask;
Reg r;
RegSP rs;
irt_clearmark(ir->t);
rs = as->parentmap[i - REF_FIRST];
if (!ra_hasspill(regsp_spill(rs)))
ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */
else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
continue; /* Same spill slot, do nothing. */
mask = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
if (mask == RSET_EMPTY)
lj_trace_err(as->J, LJ_TRERR_NYICOAL);
r = ra_allocref(as, i, mask);
ra_save(as, ir, r);
rset_clear(allow, r);
if (r == rs) { /* Coalesce matching registers right now. */
ra_free(as, r);
rset_clear(live, r);
} else if (ra_hasspill(regsp_spill(rs))) {
pass3 = 1;
}
checkmclim(as);
}
}
}
/* Store trace number and adjust stack frame relative to the parent. */
emit_setvmstate(as, (int32_t)as->T->traceno);
emit_spsub(as, spdelta);
#if !LJ_TARGET_X86ORX64
/* Restore BASE register from parent spill slot. */
if (ra_hasspill(irp->s))
emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
#endif
/* Restore target registers from parent spill slots. */
if (pass3) {
RegSet work = ~as->freeset & RSET_ALL;
while (work) {
Reg r = rset_pickbot(work);
IRRef ref = regcost_ref(as->cost[r]);
RegSP rs = as->parentmap[ref - REF_FIRST];
rset_clear(work, r);
if (ra_hasspill(regsp_spill(rs))) {
int32_t ofs = sps_scale(regsp_spill(rs));
ra_free(as, r);
emit_spload(as, IR(ref), r, ofs);
checkmclim(as);
}
}
}
/* Shuffle registers to match up target regs with parent regs. */
for (;;) {
RegSet work;
/* Repeatedly coalesce free live registers by moving to their target. */
while ((work = as->freeset & live) != RSET_EMPTY) {
Reg rp = rset_pickbot(work);
IRIns *ir = IR(sloadins[rp]);
rset_clear(live, rp);
rset_clear(allow, rp);
ra_free(as, ir->r);
emit_movrr(as, ir, ir->r, rp);
checkmclim(as);
}
/* We're done if no live registers remain. */
if (live == RSET_EMPTY)
break;
/* Break cycles by renaming one target to a temp. register. */
if (live & RSET_GPR) {
RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
if (tmpset == RSET_EMPTY)
lj_trace_err(as->J, LJ_TRERR_NYICOAL);
ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
}
if (!LJ_SOFTFP && (live & RSET_FPR)) {
RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
if (tmpset == RSET_EMPTY)
lj_trace_err(as->J, LJ_TRERR_NYICOAL);
ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
}
checkmclim(as);
/* Continue with coalescing to fix up the broken cycle(s). */
}
/* Inherit top stack slot already checked by parent trace. */
as->T->topslot = as->parent->topslot;
if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */
#ifdef EXITSTATE_CHECKEXIT
/* Highest exit + 1 indicates stack check. */
ExitNo exitno = as->T->nsnap;
#else
/* Reuse the parent exit in the context of the parent trace. */
ExitNo exitno = as->J->exitno;
#endif
as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */
asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno);
}
}
/* -- Tail of trace ------------------------------------------------------- */
/* Get base slot for a snapshot. */
static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
{
SnapEntry *map = &as->T->snapmap[snap->mapofs];
MSize n;
for (n = snap->nent; n > 0; n--) {
SnapEntry sn = map[n-1];
if ((sn & SNAP_FRAME)) {
*gotframe = 1;
return snap_slot(sn);
}
}
return 0;
}
/* Link to another trace. */
static void asm_tail_link(ASMState *as)
{
SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */
SnapShot *snap = &as->T->snap[snapno];
int gotframe = 0;
BCReg baseslot = asm_baseslot(as, snap, &gotframe);
as->topslot = snap->topslot;
checkmclim(as);
ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
if (as->T->link == 0) {
/* Setup fixed registers for exit to interpreter. */
const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]);
int32_t mres;
if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
if (bc_isret(bc_op(*retpc)))
pc = retpc;
}
ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
ra_allockreg(as, i32ptr(pc), RID_LPC);
mres = (int32_t)(snap->nslots - baseslot);
switch (bc_op(*pc)) {
case BC_CALLM: case BC_CALLMT:
mres -= (int32_t)(1 + bc_a(*pc) + bc_c(*pc)); break;
case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
}
ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */
} else if (baseslot) {
/* Save modified BASE for linking to trace with higher start frame. */
emit_setgl(as, RID_BASE, jit_base);
}
emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
/* Sync the interpreter state with the on-trace state. */
asm_stack_restore(as, snap);
/* Root traces that add frames need to check the stack at the end. */
if (!as->parent && gotframe)
asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
}
/* -- Trace setup --------------------------------------------------------- */
/* Clear reg/sp for all instructions and add register hints. */
static void asm_setup_regsp(ASMState *as)
{
GCtrace *T = as->T;
int sink = T->sinktags;
IRRef nins = T->nins;
IRIns *ir, *lastir;
int inloop;
#if LJ_TARGET_ARM
uint32_t rload = 0xa6402a64;
#endif
ra_setup(as);
/* Clear reg/sp for constants. */
for (ir = IR(T->nk), lastir = IR(REF_BASE); ir < lastir; ir++)
ir->prev = REGSP_INIT;
/* REF_BASE is used for implicit references to the BASE register. */
lastir->prev = REGSP_HINT(RID_BASE);
ir = IR(nins-1);
if (ir->o == IR_RENAME) {
do { ir--; nins--; } while (ir->o == IR_RENAME);
T->nins = nins; /* Remove any renames left over from ASM restart. */
}
as->snaprename = nins;
as->snapref = nins;
as->snapno = T->nsnap;
as->stopins = REF_BASE;
as->orignins = nins;
as->curins = nins;
/* Setup register hints for parent link instructions. */
ir = IR(REF_FIRST);
if (as->parent) {
uint16_t *p;
lastir = lj_snap_regspmap(as->parent, as->J->exitno, ir);
if (lastir - ir > LJ_MAX_JSLOTS)
lj_trace_err(as->J, LJ_TRERR_NYICOAL);
as->stopins = (IRRef)((lastir-1) - as->ir);
for (p = as->parentmap; ir < lastir; ir++) {
RegSP rs = ir->prev;
*p++ = (uint16_t)rs; /* Copy original parent RegSP to parentmap. */
if (!ra_hasspill(regsp_spill(rs)))
ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
else
ir->prev = REGSP_INIT;
}
}
inloop = 0;
as->evenspill = SPS_FIRST;
for (lastir = IR(nins); ir < lastir; ir++) {
if (sink) {
if (ir->r == RID_SINK)
continue;
if (ir->r == RID_SUNK) { /* Revert after ASM restart. */
ir->r = RID_SINK;
continue;
}
}
switch (ir->o) {
case IR_LOOP:
inloop = 1;
break;
#if LJ_TARGET_ARM
case IR_SLOAD:
if (!((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP))
break;
/* fallthrough */
case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
if (!LJ_SOFTFP && irt_isnum(ir->t)) break;
ir->prev = (uint16_t)REGSP_HINT((rload & 15));
rload = lj_ror(rload, 4);
continue;
#endif
case IR_CALLXS: {
CCallInfo ci;
ci.flags = asm_callx_flags(as, ir);
ir->prev = asm_setup_call_slots(as, ir, &ci);
if (inloop)
as->modset |= RSET_SCRATCH;
continue;
}
case IR_CALLN: case IR_CALLL: case IR_CALLS: {
const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
ir->prev = asm_setup_call_slots(as, ir, ci);
if (inloop)
as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
(RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
continue;
}
#if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
case IR_HIOP:
switch ((ir-1)->o) {
#if LJ_SOFTFP && LJ_TARGET_ARM
case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
if (ra_hashint((ir-1)->r)) {
ir->prev = (ir-1)->prev + 1;
continue;
}
break;
#endif
#if !LJ_SOFTFP && LJ_NEED_FP64
case IR_CONV:
if (irt_isfp((ir-1)->t)) {
ir->prev = REGSP_HINT(RID_FPRET);
continue;
}
/* fallthrough */
#endif
case IR_CALLN: case IR_CALLXS:
#if LJ_SOFTFP
case IR_MIN: case IR_MAX:
#endif
(ir-1)->prev = REGSP_HINT(RID_RETLO);
ir->prev = REGSP_HINT(RID_RETHI);
continue;
default:
break;
}
break;
#endif
#if LJ_SOFTFP
case IR_MIN: case IR_MAX:
if ((ir+1)->o != IR_HIOP) break;
/* fallthrough */
#endif
/* C calls evict all scratch regs and return results in RID_RET. */
case IR_SNEW: case IR_XSNEW: case IR_NEWREF:
if (REGARG_NUMGPR < 3 && as->evenspill < 3)
as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
case IR_TNEW: case IR_TDUP: case IR_CNEW: case IR_CNEWI: case IR_TOSTR:
ir->prev = REGSP_HINT(RID_RET);
if (inloop)
as->modset = RSET_SCRATCH;
continue;
case IR_STRTO: case IR_OBAR:
if (inloop)
as->modset = RSET_SCRATCH;
break;
#if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
case IR_ATAN2: case IR_LDEXP:
#endif
case IR_POW:
if (!LJ_SOFTFP && irt_isnum(ir->t)) {
#if LJ_TARGET_X86ORX64
ir->prev = REGSP_HINT(RID_XMM0);
if (inloop)
as->modset |= RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
#else
ir->prev = REGSP_HINT(RID_FPRET);
if (inloop)
as->modset |= RSET_SCRATCH;
#endif
continue;
}
/* fallthrough for integer POW */
case IR_DIV: case IR_MOD:
if (!irt_isnum(ir->t)) {
ir->prev = REGSP_HINT(RID_RET);
if (inloop)
as->modset |= (RSET_SCRATCH & RSET_GPR);
continue;
}
break;
case IR_FPMATH:
#if LJ_TARGET_X86ORX64
if (ir->op2 == IRFPM_EXP2) { /* May be joined to lj_vm_pow_sse. */
ir->prev = REGSP_HINT(RID_XMM0);
#if !LJ_64
if (as->evenspill < 4) /* Leave room for 16 byte scratch area. */
as->evenspill = 4;
#endif
if (inloop)
as->modset |= RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
continue;
} else if (ir->op2 <= IRFPM_TRUNC && !(as->flags & JIT_F_SSE4_1)) {
ir->prev = REGSP_HINT(RID_XMM0);
if (inloop)
as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
continue;
}
break;
#else
ir->prev = REGSP_HINT(RID_FPRET);
if (inloop)
as->modset |= RSET_SCRATCH;
continue;
#endif
#if LJ_TARGET_X86ORX64
/* Non-constant shift counts need to be in RID_ECX on x86/x64. */
case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR:
if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
IR(ir->op2)->r = REGSP_HINT(RID_ECX);
if (inloop)
rset_set(as->modset, RID_ECX);
}
break;
#endif
/* Do not propagate hints across type conversions or loads. */
case IR_TOBIT:
case IR_XLOAD:
#if !LJ_TARGET_ARM
case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
#endif
break;
case IR_CONV:
if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
(ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
break;
/* fallthrough */
default:
/* Propagate hints across likely 'op reg, imm' or 'op reg'. */
if (irref_isk(ir->op2) && !irref_isk(ir->op1) &&
ra_hashint(regsp_reg(IR(ir->op1)->prev))) {
ir->prev = IR(ir->op1)->prev;
continue;
}
break;
}
ir->prev = REGSP_INIT;
}
if ((as->evenspill & 1))
as->oddspill = as->evenspill++;
else
as->oddspill = 0;
}
/* -- Assembler core ------------------------------------------------------ */
/* Assemble a trace. */
void lj_asm_trace(jit_State *J, GCtrace *T)
{
ASMState as_;
ASMState *as = &as_;
MCode *origtop;
/* Ensure an initialized instruction beyond the last one for HIOP checks. */
J->cur.nins = lj_ir_nextins(J);
J->cur.ir[J->cur.nins].o = IR_NOP;
/* Setup initial state. Copy some fields to reduce indirections. */
as->J = J;
as->T = T;
as->ir = T->ir;
as->flags = J->flags;
as->loopref = J->loopref;
as->realign = NULL;
as->loopinv = 0;
as->parent = J->parent ? traceref(J, J->parent) : NULL;
/* Reserve MCode memory. */
as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot);
as->mcp = as->mctop;
as->mclim = as->mcbot + MCLIM_REDZONE;
asm_setup_target(as);
do {
as->mcp = as->mctop;
#ifdef LUA_USE_ASSERT
as->mcp_prev = as->mcp;
#endif
as->curins = T->nins;
RA_DBG_START();
RA_DBGX((as, "===== STOP ====="));
/* General trace setup. Emit tail of trace. */
asm_tail_prep(as);
as->mcloop = NULL;
as->flagmcp = NULL;
as->topslot = 0;
as->gcsteps = 0;
as->sectref = as->loopref;
as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
asm_setup_regsp(as);
if (!as->loopref)
asm_tail_link(as);
/* Assemble a trace in linear backwards order. */
for (as->curins--; as->curins > as->stopins; as->curins--) {
IRIns *ir = IR(as->curins);
lua_assert(!(LJ_32 && irt_isint64(ir->t))); /* Handled by SPLIT. */
if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
continue; /* Dead-code elimination can be soooo easy. */
if (irt_isguard(ir->t))
asm_snap_prep(as);
RA_DBG_REF();
checkmclim(as);
asm_ir(as, ir);
}
} while (as->realign); /* Retry in case the MCode needs to be realigned. */
/* Emit head of trace. */
RA_DBG_REF();
checkmclim(as);
if (as->gcsteps > 0) {
as->curins = as->T->snap[0].ref;
asm_snap_prep(as); /* The GC check is a guard. */
asm_gc_check(as);
}
ra_evictk(as);
if (as->parent)
asm_head_side(as);
else
asm_head_root(as);
asm_phi_fixup(as);
RA_DBGX((as, "===== START ===="));
RA_DBG_FLUSH();
if (as->freeset != RSET_ALL)
lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */
/* Set trace entry point before fixing up tail to allow link to self. */
T->mcode = as->mcp;
T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
if (!as->loopref)
asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */
T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
lj_mcode_sync(T->mcode, origtop);
}
#undef IR
#endif
| apache-2.0 |
jmanday/Master | TFM/library/boost_1_63_0/libs/units/example/conversion.cpp | 62 | 3255 | // Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
\file
\brief conversion.cpp
\details
Test explicit and implicit unit conversion.
Output:
@verbatim
//[conversion_output_1
L1 = 2 m
L2 = 2 m
L3 = 2 m
L4 = 200 cm
L5 = 5 m
L6 = 4 m
L7 = 200 cm
//]
//[conversion_output_2
volume (m^3) = 1 m^3
volume (cm^3) = 1e+06 cm^3
volume (m^3) = 1 m^3
energy (joules) = 1 J
energy (ergs) = 1e+07 erg
energy (joules) = 1 J
velocity (2 m/s) = 2 m s^-1
velocity (2 cm/s) = 0.02 m s^-1
//]
@endverbatim
**/
#include <iostream>
#include <boost/units/io.hpp>
#include <boost/units/pow.hpp>
#include <boost/units/systems/cgs.hpp>
#include <boost/units/systems/cgs/io.hpp>
#include <boost/units/systems/si.hpp>
#include <boost/units/systems/si/io.hpp>
using namespace boost::units;
int main()
{
// test quantity_cast
{
// implicit value_type conversions
//[conversion_snippet_1
quantity<si::length> L1 = quantity<si::length,int>(int(2.5)*si::meters);
quantity<si::length,int> L2(quantity<si::length,double>(2.5*si::meters));
//]
//[conversion_snippet_3
quantity<si::length,int> L3 = static_cast<quantity<si::length,int> >(L1);
//]
//[conversion_snippet_4
quantity<cgs::length> L4 = static_cast<quantity<cgs::length> >(L1);
//]
quantity<si::length,int> L5(4*si::meters),
L6(5*si::meters);
quantity<cgs::length> L7(L1);
swap(L5,L6);
std::cout << "L1 = " << L1 << std::endl
<< "L2 = " << L2 << std::endl
<< "L3 = " << L3 << std::endl
<< "L4 = " << L4 << std::endl
<< "L5 = " << L5 << std::endl
<< "L6 = " << L6 << std::endl
<< "L7 = " << L7 << std::endl
<< std::endl;
}
// test explicit unit system conversion
{
//[conversion_snippet_5
quantity<si::volume> vs(1.0*pow<3>(si::meter));
quantity<cgs::volume> vc(vs);
quantity<si::volume> vs2(vc);
quantity<si::energy> es(1.0*si::joule);
quantity<cgs::energy> ec(es);
quantity<si::energy> es2(ec);
quantity<si::velocity> v1 = 2.0*si::meters/si::second,
v2(2.0*cgs::centimeters/cgs::second);
//]
std::cout << "volume (m^3) = " << vs << std::endl
<< "volume (cm^3) = " << vc << std::endl
<< "volume (m^3) = " << vs2 << std::endl
<< std::endl;
std::cout << "energy (joules) = " << es << std::endl
<< "energy (ergs) = " << ec << std::endl
<< "energy (joules) = " << es2 << std::endl
<< std::endl;
std::cout << "velocity (2 m/s) = " << v1 << std::endl
<< "velocity (2 cm/s) = " << v2 << std::endl
<< std::endl;
}
return 0;
}
| apache-2.0 |
screamerbg/mbed | targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_mmc.c | 65 | 79422 | /**
******************************************************************************
* @file stm32f7xx_hal_mmc.c
* @author MCD Application Team
* @version V1.2.0
* @date 30-December-2016
* @brief MMC card HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Secure Digital (MMC) peripheral:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral Control functions
* + MMC card Control functions
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
This driver implements a high level communication layer for read and write from/to
this memory. The needed STM32 hardware resources (SDMMC and GPIO) are performed by
the user in HAL_MMC_MspInit() function (MSP layer).
Basically, the MSP layer configuration should be the same as we provide in the
examples.
You can easily tailor this configuration according to hardware resources.
[..]
This driver is a generic layered driver for SDMMC memories which uses the HAL
SDMMC driver functions to interface with MMC and eMMC cards devices.
It is used as follows:
(#)Initialize the SDMMC low level resources by implement the HAL_MMC_MspInit() API:
(##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE();
(##) SDMMC pins configuration for MMC card
(+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE();
(+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init()
and according to your pin assignment;
(##) DMA Configuration if you need to use DMA process (HAL_MMC_ReadBlocks_DMA()
and HAL_MMC_WriteBlocks_DMA() APIs).
(+++) Enable the DMAx interface clock using __HAL_RCC_DMAx_CLK_ENABLE();
(+++) Configure the DMA using the function HAL_DMA_Init() with predeclared and filled.
(##) NVIC configuration if you need to use interrupt process when using DMA transfer.
(+++) Configure the SDMMC and DMA interrupt priorities using functions
HAL_NVIC_SetPriority(); DMA priority is superior to SDMMC's priority
(+++) Enable the NVIC DMA and SDMMC IRQs using function HAL_NVIC_EnableIRQ()
(+++) SDMMC interrupts are managed using the macros __HAL_MMC_ENABLE_IT()
and __HAL_MMC_DISABLE_IT() inside the communication process.
(+++) SDMMC interrupts pending bits are managed using the macros __HAL_MMC_GET_IT()
and __HAL_MMC_CLEAR_IT()
(##) NVIC configuration if you need to use interrupt process (HAL_MMC_ReadBlocks_IT()
and HAL_MMC_WriteBlocks_IT() APIs).
(+++) Configure the SDMMC interrupt priorities using function
HAL_NVIC_SetPriority();
(+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ()
(+++) SDMMC interrupts are managed using the macros __HAL_MMC_ENABLE_IT()
and __HAL_MMC_DISABLE_IT() inside the communication process.
(+++) SDMMC interrupts pending bits are managed using the macros __HAL_MMC_GET_IT()
and __HAL_MMC_CLEAR_IT()
(#) At this stage, you can perform MMC read/write/erase operations after MMC card initialization
*** MMC Card Initialization and configuration ***
================================================
[..]
To initialize the MMC Card, use the HAL_MMC_Init() function. It Initializes
SDMMC IP (STM32 side) and the MMC Card, and put it into StandBy State (Ready for data transfer).
This function provide the following operations:
(#) Initialize the SDMMC peripheral interface with defaullt configuration.
The initialization process is done at 400KHz. You can change or adapt
this frequency by adjusting the "ClockDiv" field.
The MMC Card frequency (SDMMC_CK) is computed as follows:
SDMMC_CK = SDMMCCLK / (ClockDiv + 2)
In initialization mode and according to the MMC Card standard,
make sure that the SDMMC_CK frequency doesn't exceed 400KHz.
This phase of initialization is done through SDMMC_Init() and
SDMMC_PowerState_ON() SDMMC low level APIs.
(#) Initialize the MMC card. The API used is HAL_MMC_InitCard().
This phase allows the card initialization and identification
and check the MMC Card type (Standard Capacity or High Capacity)
The initialization flow is compatible with MMC standard.
This API (HAL_MMC_InitCard()) could be used also to reinitialize the card in case
of plug-off plug-in.
(#) Configure the MMC Card Data transfer frequency. By Default, the card transfer
frequency is set to 24MHz. You can change or adapt this frequency by adjusting
the "ClockDiv" field.
In transfer mode and according to the MMC Card standard, make sure that the
SDMMC_CK frequency doesn't exceed 25MHz and 50MHz in High-speed mode switch.
To be able to use a frequency higher than 24MHz, you should use the SDMMC
peripheral in bypass mode. Refer to the corresponding reference manual
for more details.
(#) Select the corresponding MMC Card according to the address read with the step 2.
(#) Configure the MMC Card in wide bus mode: 4-bits data.
*** MMC Card Read operation ***
==============================
[..]
(+) You can read from MMC card in polling mode by using function HAL_MMC_ReadBlocks().
This function allows the read of 512 bytes blocks.
You can choose either one block read operation or multiple block read operation
by adjusting the "NumberOfBlocks" parameter.
After this, you have to ensure that the transfer is done correctly. The check is done
through HAL_MMC_GetCardState() function for MMC card state.
(+) You can read from MMC card in DMA mode by using function HAL_MMC_ReadBlocks_DMA().
This function allows the read of 512 bytes blocks.
You can choose either one block read operation or multiple block read operation
by adjusting the "NumberOfBlocks" parameter.
After this, you have to ensure that the transfer is done correctly. The check is done
through HAL_MMC_GetCardState() function for MMC card state.
You could also check the DMA transfer process through the MMC Rx interrupt event.
(+) You can read from MMC card in Interrupt mode by using function HAL_MMC_ReadBlocks_IT().
This function allows the read of 512 bytes blocks.
You can choose either one block read operation or multiple block read operation
by adjusting the "NumberOfBlocks" parameter.
After this, you have to ensure that the transfer is done correctly. The check is done
through HAL_MMC_GetCardState() function for MMC card state.
You could also check the IT transfer process through the MMC Rx interrupt event.
*** MMC Card Write operation ***
===============================
[..]
(+) You can write to MMC card in polling mode by using function HAL_MMC_WriteBlocks().
This function allows the read of 512 bytes blocks.
You can choose either one block read operation or multiple block read operation
by adjusting the "NumberOfBlocks" parameter.
After this, you have to ensure that the transfer is done correctly. The check is done
through HAL_MMC_GetCardState() function for MMC card state.
(+) You can write to MMC card in DMA mode by using function HAL_MMC_WriteBlocks_DMA().
This function allows the read of 512 bytes blocks.
You can choose either one block read operation or multiple block read operation
by adjusting the "NumberOfBlocks" parameter.
After this, you have to ensure that the transfer is done correctly. The check is done
through HAL_MMC_GetCardState() function for MMC card state.
You could also check the DMA transfer process through the MMC Tx interrupt event.
(+) You can write to MMC card in Interrupt mode by using function HAL_MMC_WriteBlocks_IT().
This function allows the read of 512 bytes blocks.
You can choose either one block read operation or multiple block read operation
by adjusting the "NumberOfBlocks" parameter.
After this, you have to ensure that the transfer is done correctly. The check is done
through HAL_MMC_GetCardState() function for MMC card state.
You could also check the IT transfer process through the MMC Tx interrupt event.
*** MMC card information ***
===========================
[..]
(+) To get MMC card information, you can use the function HAL_MMC_GetCardInfo().
It returns useful information about the MMC card such as block size, card type,
block number ...
*** MMC card CSD register ***
============================
[..]
(+) The HAL_MMC_GetCardCSD() API allows to get the parameters of the CSD register.
Some of the CSD parameters are useful for card initialization and identification.
*** MMC card CID register ***
============================
[..]
(+) The HAL_MMC_GetCardCID() API allows to get the parameters of the CID register.
Some of the CID parameters are useful for card initialization and identification.
*** MMC HAL driver macros list ***
==================================
[..]
Below the list of most used macros in MMC HAL driver.
(+) __HAL_MMC_ENABLE : Enable the MMC device
(+) __HAL_MMC_DISABLE : Disable the MMC device
(+) __HAL_MMC_DMA_ENABLE: Enable the SDMMC DMA transfer
(+) __HAL_MMC_DMA_DISABLE: Disable the SDMMC DMA transfer
(+) __HAL_MMC_ENABLE_IT: Enable the MMC device interrupt
(+) __HAL_MMC_DISABLE_IT: Disable the MMC device interrupt
(+) __HAL_MMC_GET_FLAG:Check whether the specified MMC flag is set or not
(+) __HAL_MMC_CLEAR_FLAG: Clear the MMC's pending flags
[..]
(@) You can refer to the MMC HAL driver header file for more useful macros
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* 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 STMicroelectronics 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx_hal.h"
/** @addtogroup STM32F7xx_HAL_Driver
* @{
*/
/** @defgroup MMC MMC
* @brief MMC HAL module driver
* @{
*/
#ifdef HAL_MMC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup MMC_Private_Defines
* @{
*/
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup MMC_Private_Functions MMC Private Functions
* @{
*/
static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc);
static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc);
static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus);
static HAL_StatusTypeDef MMC_PowerOFF(MMC_HandleTypeDef *hmmc);
static HAL_StatusTypeDef MMC_Write_IT(MMC_HandleTypeDef *hmmc);
static HAL_StatusTypeDef MMC_Read_IT(MMC_HandleTypeDef *hmmc);
static void MMC_DMATransmitCplt(DMA_HandleTypeDef *hdma);
static void MMC_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
static void MMC_DMAError(DMA_HandleTypeDef *hdma);
static void MMC_DMATxAbort(DMA_HandleTypeDef *hdma);
static void MMC_DMARxAbort(DMA_HandleTypeDef *hdma);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup MMC_Exported_Functions
* @{
*/
/** @addtogroup MMC_Exported_Functions_Group1
* @brief Initialization and de-initialization functions
*
@verbatim
==============================================================================
##### Initialization and de-initialization functions #####
==============================================================================
[..]
This section provides functions allowing to initialize/de-initialize the MMC
card device to be ready for use.
@endverbatim
* @{
*/
/**
* @brief Initializes the MMC according to the specified parameters in the
MMC_HandleTypeDef and create the associated handle.
* @param hmmc: Pointer to the MMC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_Init(MMC_HandleTypeDef *hmmc)
{
/* Check the MMC handle allocation */
if(hmmc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SDMMC_ALL_INSTANCE(hmmc->Instance));
assert_param(IS_SDMMC_CLOCK_EDGE(hmmc->Init.ClockEdge));
assert_param(IS_SDMMC_CLOCK_BYPASS(hmmc->Init.ClockBypass));
assert_param(IS_SDMMC_CLOCK_POWER_SAVE(hmmc->Init.ClockPowerSave));
assert_param(IS_SDMMC_BUS_WIDE(hmmc->Init.BusWide));
assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(hmmc->Init.HardwareFlowControl));
assert_param(IS_SDMMC_CLKDIV(hmmc->Init.ClockDiv));
if(hmmc->State == HAL_MMC_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hmmc->Lock = HAL_UNLOCKED;
/* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
HAL_MMC_MspInit(hmmc);
}
hmmc->State = HAL_MMC_STATE_BUSY;
/* Initialize the Card parameters */
HAL_MMC_InitCard(hmmc);
/* Initialize the error code */
hmmc->ErrorCode = HAL_DMA_ERROR_NONE;
/* Initialize the MMC operation */
hmmc->Context = MMC_CONTEXT_NONE;
/* Initialize the MMC state */
hmmc->State = HAL_MMC_STATE_READY;
return HAL_OK;
}
/**
* @brief Initializes the MMC Card.
* @param hmmc: Pointer to MMC handle
* @note This function initializes the MMC card. It could be used when a card
re-initialization is needed.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_InitCard(MMC_HandleTypeDef *hmmc)
{
uint32_t errorstate = HAL_MMC_ERROR_NONE;
MMC_InitTypeDef Init;
/* Default SDMMC peripheral configuration for MMC card initialization */
Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING;
Init.ClockBypass = SDMMC_CLOCK_BYPASS_DISABLE;
Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE;
Init.BusWide = SDMMC_BUS_WIDE_1B;
Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE;
Init.ClockDiv = SDMMC_INIT_CLK_DIV;
/* Initialize SDMMC peripheral interface with default configuration */
SDMMC_Init(hmmc->Instance, Init);
/* Disable SDMMC Clock */
__HAL_MMC_DISABLE(hmmc);
/* Set Power State to ON */
SDMMC_PowerState_ON(hmmc->Instance);
/* Enable MMC Clock */
__HAL_MMC_ENABLE(hmmc);
/* Identify card operating voltage */
errorstate = MMC_PowerON(hmmc);
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->State = HAL_MMC_STATE_READY;
hmmc->ErrorCode |= errorstate;
return HAL_ERROR;
}
/* Card initialization */
errorstate = MMC_InitCard(hmmc);
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->State = HAL_MMC_STATE_READY;
hmmc->ErrorCode |= errorstate;
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief De-Initializes the MMC card.
* @param hmmc: Pointer to MMC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_DeInit(MMC_HandleTypeDef *hmmc)
{
/* Check the MMC handle allocation */
if(hmmc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SDMMC_ALL_INSTANCE(hmmc->Instance));
hmmc->State = HAL_MMC_STATE_BUSY;
/* Set MMC power state to off */
MMC_PowerOFF(hmmc);
/* De-Initialize the MSP layer */
HAL_MMC_MspDeInit(hmmc);
hmmc->ErrorCode = HAL_MMC_ERROR_NONE;
hmmc->State = HAL_MMC_STATE_RESET;
return HAL_OK;
}
/**
* @brief Initializes the MMC MSP.
* @param hmmc: Pointer to MMC handle
* @retval None
*/
__weak void HAL_MMC_MspInit(MMC_HandleTypeDef *hmmc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hmmc);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_MMC_MspInit could be implemented in the user file
*/
}
/**
* @brief De-Initialize MMC MSP.
* @param hmmc: Pointer to MMC handle
* @retval None
*/
__weak void HAL_MMC_MspDeInit(MMC_HandleTypeDef *hmmc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hmmc);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_MMC_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @addtogroup MMC_Exported_Functions_Group2
* @brief Data transfer functions
*
@verbatim
==============================================================================
##### IO operation functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to manage the data
transfer from/to MMC card.
@endverbatim
* @{
*/
/**
* @brief Reads block(s) from a specified address in a card. The Data transfer
* is managed by polling mode.
* @note This API should be followed by a check on the card state through
* HAL_MMC_GetCardState().
* @param hmmc: Pointer to MMC handle
* @param pData: pointer to the buffer that will contain the received data
* @param BlockAdd: Block Address from where data is to be read
* @param NumberOfBlocks: Number of MMC blocks to read
* @param Timeout: Specify timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout)
{
SDMMC_DataInitTypeDef config;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
uint32_t tickstart = HAL_GetTick();
uint32_t count = 0, *tempbuff = (uint32_t *)pData;
if(NULL == pData)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM;
return HAL_ERROR;
}
if(hmmc->State == HAL_MMC_STATE_READY)
{
hmmc->ErrorCode = HAL_DMA_ERROR_NONE;
if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr))
{
hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE;
return HAL_ERROR;
}
hmmc->State = HAL_MMC_STATE_BUSY;
/* Initialize data control register */
hmmc->Instance->DCTRL = 0;
/* Check the Card capacity in term of Logical number of blocks */
if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY)
{
BlockAdd *= 512;
}
/* Set Block Size for Card */
errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Configure the MMC DPSM (Data Path State Machine) */
config.DataTimeOut = SDMMC_DATATIMEOUT;
config.DataLength = NumberOfBlocks * BLOCKSIZE;
config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC;
config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK;
config.DPSM = SDMMC_DPSM_ENABLE;
SDMMC_ConfigData(hmmc->Instance, &config);
/* Read block(s) in polling mode */
if(NumberOfBlocks > 1)
{
hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK;
/* Read Multi Block command */
errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, BlockAdd);
}
else
{
hmmc->Context = MMC_CONTEXT_READ_SINGLE_BLOCK;
/* Read Single Block command */
errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, BlockAdd);
}
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Poll on SDMMC flags */
while(!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND))
{
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF))
{
/* Read data from SDMMC Rx FIFO */
for(count = 0U; count < 8U; count++)
{
*(tempbuff + count) = SDMMC_ReadFIFO(hmmc->Instance);
}
tempbuff += 8U;
}
if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT;
hmmc->State= HAL_MMC_STATE_READY;
return HAL_TIMEOUT;
}
}
/* Send stop transmission command in case of multiblock read */
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U))
{
/* Send stop transmission command */
errorstate = SDMMC_CmdStopTransfer(hmmc->Instance);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
}
/* Get error state */
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
else if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
else if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Empty FIFO if there is still any data */
while ((__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXDAVL)))
{
*tempbuff = SDMMC_ReadFIFO(hmmc->Instance);
tempbuff++;
if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT;
hmmc->State= HAL_MMC_STATE_READY;
return HAL_ERROR;
}
}
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->State = HAL_MMC_STATE_READY;
return HAL_OK;
}
else
{
hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY;
return HAL_ERROR;
}
}
/**
* @brief Allows to write block(s) to a specified address in a card. The Data
* transfer is managed by polling mode.
* @note This API should be followed by a check on the card state through
* HAL_MMC_GetCardState().
* @param hmmc: Pointer to MMC handle
* @param pData: pointer to the buffer that will contain the data to transmit
* @param BlockAdd: Block Address where data will be written
* @param NumberOfBlocks: Number of MMC blocks to write
* @param Timeout: Specify timeout value
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_WriteBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout)
{
SDMMC_DataInitTypeDef config;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
uint32_t tickstart = HAL_GetTick();
uint32_t count = 0;
uint32_t *tempbuff = (uint32_t *)pData;
if(NULL == pData)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM;
return HAL_ERROR;
}
if(hmmc->State == HAL_MMC_STATE_READY)
{
hmmc->ErrorCode = HAL_DMA_ERROR_NONE;
if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr))
{
hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE;
return HAL_ERROR;
}
hmmc->State = HAL_MMC_STATE_BUSY;
/* Initialize data control register */
hmmc->Instance->DCTRL = 0;
/* Check the Card capacity in term of Logical number of blocks */
if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY)
{
BlockAdd *= 512;
}
/* Set Block Size for Card */
errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Write Blocks in Polling mode */
if(NumberOfBlocks > 1U)
{
hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK;
/* Write Multi Block command */
errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, BlockAdd);
}
else
{
hmmc->Context = MMC_CONTEXT_WRITE_SINGLE_BLOCK;
/* Write Single Block command */
errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, BlockAdd);
}
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Configure the MMC DPSM (Data Path State Machine) */
config.DataTimeOut = SDMMC_DATATIMEOUT;
config.DataLength = NumberOfBlocks * BLOCKSIZE;
config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD;
config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK;
config.DPSM = SDMMC_DPSM_ENABLE;
SDMMC_ConfigData(hmmc->Instance, &config);
/* Write block(s) in polling mode */
while(!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND))
{
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE))
{
/* Write data to SDMMC Tx FIFO */
for(count = 0U; count < 8U; count++)
{
SDMMC_WriteFIFO(hmmc->Instance, (tempbuff + count));
}
tempbuff += 8U;
}
if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_TIMEOUT;
}
}
/* Send stop transmission command in case of multiblock write */
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U))
{
/* Send stop transmission command */
errorstate = SDMMC_CmdStopTransfer(hmmc->Instance);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
}
/* Get error state */
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
else if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
else if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR))
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->State = HAL_MMC_STATE_READY;
return HAL_OK;
}
else
{
hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY;
return HAL_ERROR;
}
}
/**
* @brief Reads block(s) from a specified address in a card. The Data transfer
* is managed in interrupt mode.
* @note This API should be followed by a check on the card state through
* HAL_MMC_GetCardState().
* @note You could also check the IT transfer process through the MMC Rx
* interrupt event.
* @param hmmc: Pointer to MMC handle
* @param pData: Pointer to the buffer that will contain the received data
* @param BlockAdd: Block Address from where data is to be read
* @param NumberOfBlocks: Number of blocks to read.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_ReadBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks)
{
SDMMC_DataInitTypeDef config;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
if(NULL == pData)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM;
return HAL_ERROR;
}
if(hmmc->State == HAL_MMC_STATE_READY)
{
hmmc->ErrorCode = HAL_DMA_ERROR_NONE;
if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr))
{
hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE;
return HAL_ERROR;
}
hmmc->State = HAL_MMC_STATE_BUSY;
/* Initialize data control register */
hmmc->Instance->DCTRL = 0U;
hmmc->pRxBuffPtr = (uint32_t *)pData;
hmmc->RxXferSize = BLOCKSIZE * NumberOfBlocks;
__HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | SDMMC_FLAG_RXFIFOHF));
/* Check the Card capacity in term of Logical number of blocks */
if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY)
{
BlockAdd *= 512;
}
/* Configure the MMC DPSM (Data Path State Machine) */
config.DataTimeOut = SDMMC_DATATIMEOUT;
config.DataLength = BLOCKSIZE * NumberOfBlocks;
config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC;
config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK;
config.DPSM = SDMMC_DPSM_ENABLE;
SDMMC_ConfigData(hmmc->Instance, &config);
/* Set Block Size for Card */
errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Read Blocks in IT mode */
if(NumberOfBlocks > 1U)
{
hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_IT);
/* Read Multi Block command */
errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, BlockAdd);
}
else
{
hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_IT);
/* Read Single Block command */
errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, BlockAdd);
}
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Writes block(s) to a specified address in a card. The Data transfer
* is managed in interrupt mode.
* @note This API should be followed by a check on the card state through
* HAL_MMC_GetCardState().
* @note You could also check the IT transfer process through the MMC Tx
* interrupt event.
* @param hmmc: Pointer to MMC handle
* @param pData: Pointer to the buffer that will contain the data to transmit
* @param BlockAdd: Block Address where data will be written
* @param NumberOfBlocks: Number of blocks to write
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_WriteBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks)
{
SDMMC_DataInitTypeDef config;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
if(NULL == pData)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM;
return HAL_ERROR;
}
if(hmmc->State == HAL_MMC_STATE_READY)
{
hmmc->ErrorCode = HAL_DMA_ERROR_NONE;
if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr))
{
hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE;
return HAL_ERROR;
}
hmmc->State = HAL_MMC_STATE_BUSY;
/* Initialize data control register */
hmmc->Instance->DCTRL = 0U;
hmmc->pTxBuffPtr = (uint32_t *)pData;
hmmc->TxXferSize = BLOCKSIZE * NumberOfBlocks;
/* Enable transfer interrupts */
__HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | SDMMC_FLAG_TXFIFOHE));
/* Check the Card capacity in term of Logical number of blocks */
if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY)
{
BlockAdd *= 512;
}
/* Set Block Size for Card */
errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Write Blocks in Polling mode */
if(NumberOfBlocks > 1U)
{
hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK| MMC_CONTEXT_IT);
/* Write Multi Block command */
errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, BlockAdd);
}
else
{
hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_IT);
/* Write Single Block command */
errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, BlockAdd);
}
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Configure the MMC DPSM (Data Path State Machine) */
config.DataTimeOut = SDMMC_DATATIMEOUT;
config.DataLength = BLOCKSIZE * NumberOfBlocks;
config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD;
config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK;
config.DPSM = SDMMC_DPSM_ENABLE;
SDMMC_ConfigData(hmmc->Instance, &config);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Reads block(s) from a specified address in a card. The Data transfer
* is managed by DMA mode.
* @note This API should be followed by a check on the card state through
* HAL_MMC_GetCardState().
* @note You could also check the DMA transfer process through the MMC Rx
* interrupt event.
* @param hmmc: Pointer MMC handle
* @param pData: Pointer to the buffer that will contain the received data
* @param BlockAdd: Block Address from where data is to be read
* @param NumberOfBlocks: Number of blocks to read.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_ReadBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks)
{
SDMMC_DataInitTypeDef config;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
if(NULL == pData)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM;
return HAL_ERROR;
}
if(hmmc->State == HAL_MMC_STATE_READY)
{
hmmc->ErrorCode = HAL_DMA_ERROR_NONE;
if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr))
{
hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE;
return HAL_ERROR;
}
hmmc->State = HAL_MMC_STATE_BUSY;
/* Initialize data control register */
hmmc->Instance->DCTRL = 0U;
__HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND));
/* Set the DMA transfer complete callback */
hmmc->hdmarx->XferCpltCallback = MMC_DMAReceiveCplt;
/* Set the DMA error callback */
hmmc->hdmarx->XferErrorCallback = MMC_DMAError;
/* Set the DMA Abort callback */
hmmc->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA Channel */
HAL_DMA_Start_IT(hmmc->hdmarx, (uint32_t)&hmmc->Instance->FIFO, (uint32_t)pData, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4);
/* Enable MMC DMA transfer */
__HAL_MMC_DMA_ENABLE(hmmc);
/* Check the Card capacity in term of Logical number of blocks */
if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY)
{
BlockAdd *= 512;
}
/* Configure the MMC DPSM (Data Path State Machine) */
config.DataTimeOut = SDMMC_DATATIMEOUT;
config.DataLength = BLOCKSIZE * NumberOfBlocks;
config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC;
config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK;
config.DPSM = SDMMC_DPSM_ENABLE;
SDMMC_ConfigData(hmmc->Instance, &config);
/* Set Block Size for Card */
errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Read Blocks in DMA mode */
if(NumberOfBlocks > 1U)
{
hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA);
/* Read Multi Block command */
errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, BlockAdd);
}
else
{
hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_DMA);
/* Read Single Block command */
errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, BlockAdd);
}
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Writes block(s) to a specified address in a card. The Data transfer
* is managed by DMA mode.
* @note This API should be followed by a check on the card state through
* HAL_MMC_GetCardState().
* @note You could also check the DMA transfer process through the MMC Tx
* interrupt event.
* @param hmmc: Pointer to MMC handle
* @param pData: Pointer to the buffer that will contain the data to transmit
* @param BlockAdd: Block Address where data will be written
* @param NumberOfBlocks: Number of blocks to write
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_WriteBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks)
{
SDMMC_DataInitTypeDef config;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
if(NULL == pData)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM;
return HAL_ERROR;
}
if(hmmc->State == HAL_MMC_STATE_READY)
{
hmmc->ErrorCode = HAL_DMA_ERROR_NONE;
if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr))
{
hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE;
return HAL_ERROR;
}
hmmc->State = HAL_MMC_STATE_BUSY;
/* Initialize data control register */
hmmc->Instance->DCTRL = 0U;
/* Enable MMC Error interrupts */
__HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR));
/* Set the DMA transfer complete callback */
hmmc->hdmatx->XferCpltCallback = MMC_DMATransmitCplt;
/* Set the DMA error callback */
hmmc->hdmatx->XferErrorCallback = MMC_DMAError;
/* Set the DMA Abort callback */
hmmc->hdmatx->XferAbortCallback = NULL;
/* Check the Card capacity in term of Logical number of blocks */
if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY)
{
BlockAdd *= 512;
}
/* Set Block Size for Card */
errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Write Blocks in Polling mode */
if(NumberOfBlocks > 1U)
{
hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_DMA);
/* Write Multi Block command */
errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, BlockAdd);
}
else
{
hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_DMA);
/* Write Single Block command */
errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, BlockAdd);
}
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Enable SDMMC DMA transfer */
__HAL_MMC_DMA_ENABLE(hmmc);
/* Enable the DMA Channel */
HAL_DMA_Start_IT(hmmc->hdmatx, (uint32_t)pData, (uint32_t)&hmmc->Instance->FIFO, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4);
/* Configure the MMC DPSM (Data Path State Machine) */
config.DataTimeOut = SDMMC_DATATIMEOUT;
config.DataLength = BLOCKSIZE * NumberOfBlocks;
config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD;
config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK;
config.DPSM = SDMMC_DPSM_ENABLE;
SDMMC_ConfigData(hmmc->Instance, &config);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Erases the specified memory area of the given MMC card.
* @note This API should be followed by a check on the card state through
* HAL_MMC_GetCardState().
* @param hmmc: Pointer to MMC handle
* @param BlockStartAdd: Start Block address
* @param BlockEndAdd: End Block address
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_Erase(MMC_HandleTypeDef *hmmc, uint32_t BlockStartAdd, uint32_t BlockEndAdd)
{
uint32_t errorstate = HAL_MMC_ERROR_NONE;
if(hmmc->State == HAL_MMC_STATE_READY)
{
hmmc->ErrorCode = HAL_DMA_ERROR_NONE;
if(BlockEndAdd < BlockStartAdd)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM;
return HAL_ERROR;
}
if(BlockEndAdd > (hmmc->MmcCard.LogBlockNbr))
{
hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE;
return HAL_ERROR;
}
hmmc->State = HAL_MMC_STATE_BUSY;
/* Check if the card command class supports erase command */
if(((hmmc->MmcCard.Class) & SDMMC_CCCC_ERASE) == 0U)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
if((SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= HAL_MMC_ERROR_LOCK_UNLOCK_FAILED;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Check the Card capacity in term of Logical number of blocks */
if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY)
{
BlockStartAdd *= 512U;
BlockEndAdd *= 512U;
}
/* Send CMD35 MMC_ERASE_GRP_START with argument as addr */
errorstate = SDMMC_CmdEraseStartAdd(hmmc->Instance, BlockStartAdd);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Send CMD36 MMC_ERASE_GRP_END with argument as addr */
errorstate = SDMMC_CmdEraseEndAdd(hmmc->Instance, BlockEndAdd);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
/* Send CMD38 ERASE */
errorstate = SDMMC_CmdErase(hmmc->Instance);
if(errorstate != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->ErrorCode |= errorstate;
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
hmmc->State = HAL_MMC_STATE_READY;
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief This function handles MMC card interrupt request.
* @param hmmc: Pointer to MMC handle
* @retval None
*/
void HAL_MMC_IRQHandler(MMC_HandleTypeDef *hmmc)
{
uint32_t errorstate = HAL_MMC_ERROR_NONE;
/* Check for SDMMC interrupt flags */
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_DATAEND) != RESET)
{
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_DATAEND);
__HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT|\
SDMMC_IT_TXUNDERR| SDMMC_IT_RXOVERR);
if((hmmc->Context & MMC_CONTEXT_IT) != RESET)
{
if(((hmmc->Context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != RESET) || ((hmmc->Context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != RESET))
{
errorstate = SDMMC_CmdStopTransfer(hmmc->Instance);
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->ErrorCode |= errorstate;
HAL_MMC_ErrorCallback(hmmc);
}
}
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->State = HAL_MMC_STATE_READY;
if(((hmmc->Context & MMC_CONTEXT_READ_SINGLE_BLOCK) != RESET) || ((hmmc->Context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != RESET))
{
HAL_MMC_RxCpltCallback(hmmc);
}
else
{
HAL_MMC_TxCpltCallback(hmmc);
}
}
else if((hmmc->Context & MMC_CONTEXT_DMA) != RESET)
{
if((hmmc->Context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != RESET)
{
errorstate = SDMMC_CmdStopTransfer(hmmc->Instance);
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->ErrorCode |= errorstate;
HAL_MMC_ErrorCallback(hmmc);
}
}
if(((hmmc->Context & MMC_CONTEXT_READ_SINGLE_BLOCK) == RESET) && ((hmmc->Context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) == RESET))
{
/* Disable the DMA transfer for transmit request by setting the DMAEN bit
in the MMC DCTRL register */
hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDMMC_DCTRL_DMAEN);
hmmc->State = HAL_MMC_STATE_READY;
HAL_MMC_TxCpltCallback(hmmc);
}
}
}
else if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_TXFIFOHE) != RESET)
{
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE);
MMC_Write_IT(hmmc);
}
else if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_RXFIFOHF) != RESET)
{
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF);
MMC_Read_IT(hmmc);
}
else if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_TXUNDERR) != RESET)
{
/* Set Error code */
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_DCRCFAIL) != RESET)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL;
}
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_DTIMEOUT) != RESET)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT;
}
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_RXOVERR) != RESET)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN;
}
if(__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_TXUNDERR) != RESET)
{
hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN;
}
/* Clear All flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
/* Disable all interrupts */
__HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT|\
SDMMC_IT_TXUNDERR| SDMMC_IT_RXOVERR);
if((hmmc->Context & MMC_CONTEXT_DMA) != RESET)
{
/* Abort the MMC DMA Streams */
if(hmmc->hdmatx != NULL)
{
/* Set the DMA Tx abort callback */
hmmc->hdmatx->XferAbortCallback = MMC_DMATxAbort;
/* Abort DMA in IT mode */
if(HAL_DMA_Abort_IT(hmmc->hdmatx) != HAL_OK)
{
MMC_DMATxAbort(hmmc->hdmatx);
}
}
else if(hmmc->hdmarx != NULL)
{
/* Set the DMA Rx abort callback */
hmmc->hdmarx->XferAbortCallback = MMC_DMARxAbort;
/* Abort DMA in IT mode */
if(HAL_DMA_Abort_IT(hmmc->hdmarx) != HAL_OK)
{
MMC_DMARxAbort(hmmc->hdmarx);
}
}
else
{
hmmc->ErrorCode = HAL_MMC_ERROR_NONE;
hmmc->State = HAL_MMC_STATE_READY;
HAL_MMC_AbortCallback(hmmc);
}
}
else if((hmmc->Context & MMC_CONTEXT_IT) != RESET)
{
/* Set the MMC state to ready to be able to start again the process */
hmmc->State = HAL_MMC_STATE_READY;
HAL_MMC_ErrorCallback(hmmc);
}
}
}
/**
* @brief return the MMC state
* @param hmmc: Pointer to mmc handle
* @retval HAL state
*/
HAL_MMC_StateTypeDef HAL_MMC_GetState(MMC_HandleTypeDef *hmmc)
{
return hmmc->State;
}
/**
* @brief Return the MMC error code
* @param hmmc : Pointer to a MMC_HandleTypeDef structure that contains
* the configuration information.
* @retval MMC Error Code
*/
uint32_t HAL_MMC_GetError(MMC_HandleTypeDef *hmmc)
{
return hmmc->ErrorCode;
}
/**
* @brief Tx Transfer completed callbacks
* @param hmmc: Pointer to MMC handle
* @retval None
*/
__weak void HAL_MMC_TxCpltCallback(MMC_HandleTypeDef *hmmc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hmmc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_MMC_TxCpltCallback can be implemented in the user file
*/
}
/**
* @brief Rx Transfer completed callbacks
* @param hmmc: Pointer MMC handle
* @retval None
*/
__weak void HAL_MMC_RxCpltCallback(MMC_HandleTypeDef *hmmc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hmmc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_MMC_ErrorCallback can be implemented in the user file
*/
}
/**
* @brief MMC error callbacks
* @param hmmc: Pointer MMC handle
* @retval None
*/
__weak void HAL_MMC_ErrorCallback(MMC_HandleTypeDef *hmmc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hmmc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_MMC_ErrorCallback can be implemented in the user file
*/
}
/**
* @brief MMC Abort callbacks
* @param hmmc: Pointer MMC handle
* @retval None
*/
__weak void HAL_MMC_AbortCallback(MMC_HandleTypeDef *hmmc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hmmc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_MMC_ErrorCallback can be implemented in the user file
*/
}
/**
* @}
*/
/** @addtogroup MMC_Exported_Functions_Group3
* @brief management functions
*
@verbatim
==============================================================================
##### Peripheral Control functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to control the MMC card
operations and get the related information
@endverbatim
* @{
*/
/**
* @brief Returns information the information of the card which are stored on
* the CID register.
* @param hmmc: Pointer to MMC handle
* @param pCID: Pointer to a HAL_MMC_CIDTypedef structure that
* contains all CID register parameters
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_GetCardCID(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCIDTypeDef *pCID)
{
uint32_t tmp = 0;
/* Byte 0 */
tmp = (uint8_t)((hmmc->CID[0] & 0xFF000000U) >> 24);
pCID->ManufacturerID = tmp;
/* Byte 1 */
tmp = (uint8_t)((hmmc->CID[0] & 0x00FF0000) >> 16);
pCID->OEM_AppliID = tmp << 8;
/* Byte 2 */
tmp = (uint8_t)((hmmc->CID[0] & 0x000000FF00) >> 8);
pCID->OEM_AppliID |= tmp;
/* Byte 3 */
tmp = (uint8_t)(hmmc->CID[0] & 0x000000FF);
pCID->ProdName1 = tmp << 24;
/* Byte 4 */
tmp = (uint8_t)((hmmc->CID[1] & 0xFF000000U) >> 24);
pCID->ProdName1 |= tmp << 16;
/* Byte 5 */
tmp = (uint8_t)((hmmc->CID[1] & 0x00FF0000) >> 16);
pCID->ProdName1 |= tmp << 8;
/* Byte 6 */
tmp = (uint8_t)((hmmc->CID[1] & 0x0000FF00) >> 8);
pCID->ProdName1 |= tmp;
/* Byte 7 */
tmp = (uint8_t)(hmmc->CID[1] & 0x000000FF);
pCID->ProdName2 = tmp;
/* Byte 8 */
tmp = (uint8_t)((hmmc->CID[2] & 0xFF000000U) >> 24);
pCID->ProdRev = tmp;
/* Byte 9 */
tmp = (uint8_t)((hmmc->CID[2] & 0x00FF0000) >> 16);
pCID->ProdSN = tmp << 24;
/* Byte 10 */
tmp = (uint8_t)((hmmc->CID[2] & 0x0000FF00) >> 8);
pCID->ProdSN |= tmp << 16;
/* Byte 11 */
tmp = (uint8_t)(hmmc->CID[2] & 0x000000FF);
pCID->ProdSN |= tmp << 8;
/* Byte 12 */
tmp = (uint8_t)((hmmc->CID[3] & 0xFF000000U) >> 24);
pCID->ProdSN |= tmp;
/* Byte 13 */
tmp = (uint8_t)((hmmc->CID[3] & 0x00FF0000) >> 16);
pCID->Reserved1 |= (tmp & 0xF0) >> 4;
pCID->ManufactDate = (tmp & 0x0F) << 8;
/* Byte 14 */
tmp = (uint8_t)((hmmc->CID[3] & 0x0000FF00) >> 8);
pCID->ManufactDate |= tmp;
/* Byte 15 */
tmp = (uint8_t)(hmmc->CID[3] & 0x000000FF);
pCID->CID_CRC = (tmp & 0xFE) >> 1;
pCID->Reserved2 = 1;
return HAL_OK;
}
/**
* @brief Returns information the information of the card which are stored on
* the CSD register.
* @param hmmc: Pointer to MMC handle
* @param pCSD: Pointer to a HAL_MMC_CardInfoTypeDef structure that
* contains all CSD register parameters
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_GetCardCSD(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCSDTypeDef *pCSD)
{
uint32_t tmp = 0;
/* Byte 0 */
tmp = (hmmc->CSD[0] & 0xFF000000U) >> 24;
pCSD->CSDStruct = (uint8_t)((tmp & 0xC0) >> 6);
pCSD->SysSpecVersion = (uint8_t)((tmp & 0x3C) >> 2);
pCSD->Reserved1 = tmp & 0x03;
/* Byte 1 */
tmp = (hmmc->CSD[0] & 0x00FF0000) >> 16;
pCSD->TAAC = (uint8_t)tmp;
/* Byte 2 */
tmp = (hmmc->CSD[0] & 0x0000FF00) >> 8;
pCSD->NSAC = (uint8_t)tmp;
/* Byte 3 */
tmp = hmmc->CSD[0] & 0x000000FF;
pCSD->MaxBusClkFrec = (uint8_t)tmp;
/* Byte 4 */
tmp = (hmmc->CSD[1] & 0xFF000000U) >> 24;
pCSD->CardComdClasses = (uint16_t)(tmp << 4);
/* Byte 5 */
tmp = (hmmc->CSD[1] & 0x00FF0000U) >> 16;
pCSD->CardComdClasses |= (uint16_t)((tmp & 0xF0) >> 4);
pCSD->RdBlockLen = (uint8_t)(tmp & 0x0F);
/* Byte 6 */
tmp = (hmmc->CSD[1] & 0x0000FF00U) >> 8;
pCSD->PartBlockRead = (uint8_t)((tmp & 0x80) >> 7);
pCSD->WrBlockMisalign = (uint8_t)((tmp & 0x40) >> 6);
pCSD->RdBlockMisalign = (uint8_t)((tmp & 0x20) >> 5);
pCSD->DSRImpl = (uint8_t)((tmp & 0x10) >> 4);
pCSD->Reserved2 = 0; /*!< Reserved */
pCSD->DeviceSize = (tmp & 0x03) << 10;
/* Byte 7 */
tmp = (uint8_t)(hmmc->CSD[1] & 0x000000FFU);
pCSD->DeviceSize |= (tmp) << 2;
/* Byte 8 */
tmp = (uint8_t)((hmmc->CSD[2] & 0xFF000000U) >> 24);
pCSD->DeviceSize |= (tmp & 0xC0) >> 6;
pCSD->MaxRdCurrentVDDMin = (tmp & 0x38) >> 3;
pCSD->MaxRdCurrentVDDMax = (tmp & 0x07);
/* Byte 9 */
tmp = (uint8_t)((hmmc->CSD[2] & 0x00FF0000U) >> 16);
pCSD->MaxWrCurrentVDDMin = (tmp & 0xE0) >> 5;
pCSD->MaxWrCurrentVDDMax = (tmp & 0x1C) >> 2;
pCSD->DeviceSizeMul = (tmp & 0x03) << 1;
/* Byte 10 */
tmp = (uint8_t)((hmmc->CSD[2] & 0x0000FF00U) >> 8);
pCSD->DeviceSizeMul |= (tmp & 0x80) >> 7;
hmmc->MmcCard.BlockNbr = (pCSD->DeviceSize + 1) ;
hmmc->MmcCard.BlockNbr *= (1 << (pCSD->DeviceSizeMul + 2));
hmmc->MmcCard.BlockSize = 1 << (pCSD->RdBlockLen);
hmmc->MmcCard.LogBlockNbr = (hmmc->MmcCard.BlockNbr) * ((hmmc->MmcCard.BlockSize) / 512);
hmmc->MmcCard.LogBlockSize = 512;
pCSD->EraseGrSize = (tmp & 0x40) >> 6;
pCSD->EraseGrMul = (tmp & 0x3F) << 1;
/* Byte 11 */
tmp = (uint8_t)(hmmc->CSD[2] & 0x000000FF);
pCSD->EraseGrMul |= (tmp & 0x80) >> 7;
pCSD->WrProtectGrSize = (tmp & 0x7F);
/* Byte 12 */
tmp = (uint8_t)((hmmc->CSD[3] & 0xFF000000U) >> 24);
pCSD->WrProtectGrEnable = (tmp & 0x80) >> 7;
pCSD->ManDeflECC = (tmp & 0x60) >> 5;
pCSD->WrSpeedFact = (tmp & 0x1C) >> 2;
pCSD->MaxWrBlockLen = (tmp & 0x03) << 2;
/* Byte 13 */
tmp = (uint8_t)((hmmc->CSD[3] & 0x00FF0000) >> 16);
pCSD->MaxWrBlockLen |= (tmp & 0xC0) >> 6;
pCSD->WriteBlockPaPartial = (tmp & 0x20) >> 5;
pCSD->Reserved3 = 0;
pCSD->ContentProtectAppli = (tmp & 0x01);
/* Byte 14 */
tmp = (uint8_t)((hmmc->CSD[3] & 0x0000FF00) >> 8);
pCSD->FileFormatGrouop = (tmp & 0x80) >> 7;
pCSD->CopyFlag = (tmp & 0x40) >> 6;
pCSD->PermWrProtect = (tmp & 0x20) >> 5;
pCSD->TempWrProtect = (tmp & 0x10) >> 4;
pCSD->FileFormat = (tmp & 0x0C) >> 2;
pCSD->ECC = (tmp & 0x03);
/* Byte 15 */
tmp = (uint8_t)(hmmc->CSD[3] & 0x000000FF);
pCSD->CSD_CRC = (tmp & 0xFE) >> 1;
pCSD->Reserved4 = 1;
return HAL_OK;
}
/**
* @brief Gets the MMC card info.
* @param hmmc: Pointer to MMC handle
* @param pCardInfo: Pointer to the HAL_MMC_CardInfoTypeDef structure that
* will contain the MMC card status information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_GetCardInfo(MMC_HandleTypeDef *hmmc, HAL_MMC_CardInfoTypeDef *pCardInfo)
{
pCardInfo->CardType = (uint32_t)(hmmc->MmcCard.CardType);
pCardInfo->Class = (uint32_t)(hmmc->MmcCard.Class);
pCardInfo->RelCardAdd = (uint32_t)(hmmc->MmcCard.RelCardAdd);
pCardInfo->BlockNbr = (uint32_t)(hmmc->MmcCard.BlockNbr);
pCardInfo->BlockSize = (uint32_t)(hmmc->MmcCard.BlockSize);
pCardInfo->LogBlockNbr = (uint32_t)(hmmc->MmcCard.LogBlockNbr);
pCardInfo->LogBlockSize = (uint32_t)(hmmc->MmcCard.LogBlockSize);
return HAL_OK;
}
/**
* @brief Enables wide bus operation for the requested card if supported by
* card.
* @param hmmc: Pointer to MMC handle
* @param WideMode: Specifies the MMC card wide bus mode
* This parameter can be one of the following values:
* @arg SDMMC_BUS_WIDE_8B: 8-bit data transfer
* @arg SDMMC_BUS_WIDE_4B: 4-bit data transfer
* @arg SDMMC_BUS_WIDE_1B: 1-bit data transfer
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32_t WideMode)
{
__IO uint32_t count = 0;
SDMMC_InitTypeDef Init;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
uint32_t response = 0, busy = 0;
/* Check the parameters */
assert_param(IS_SDMMC_BUS_WIDE(WideMode));
/* Chnage Satte */
hmmc->State = HAL_MMC_STATE_BUSY;
/* Update Clock for Bus mode update */
Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING;
Init.ClockBypass = SDMMC_CLOCK_BYPASS_DISABLE;
Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE;
Init.BusWide = WideMode;
Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE;
Init.ClockDiv = SDMMC_INIT_CLK_DIV;
/* Initialize SDMMC*/
SDMMC_Init(hmmc->Instance, Init);
if(WideMode == SDMMC_BUS_WIDE_8B)
{
errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70200);
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->ErrorCode |= errorstate;
}
}
else if(WideMode == SDMMC_BUS_WIDE_4B)
{
errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70100);
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->ErrorCode |= errorstate;
}
}
else if(WideMode == SDMMC_BUS_WIDE_1B)
{
errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70000);
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->ErrorCode |= errorstate;
}
}
else
{
/* WideMode is not a valid argument*/
hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM;
}
/* Check for switch error and violation of the trial number of sending CMD 13 */
while(busy == 0)
{
if(count++ == SDMMC_MAX_TRIAL)
{
hmmc->State = HAL_MMC_STATE_READY;
hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE;
return HAL_ERROR;
}
/* While card is not ready for data and trial number for sending CMD13 is not exceeded */
errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16));
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->ErrorCode |= errorstate;
}
/* Get command response */
response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1);
/* Get operating voltage*/
busy = (((response >> 7) == 1) ? 0 : 1);
}
/* While card is not ready for data and trial number for sending CMD13 is not exceeded */
count = SDMMC_DATATIMEOUT;
while((response & 0x00000100) == 0)
{
if(count-- == 0)
{
hmmc->State = HAL_MMC_STATE_READY;
hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE;
return HAL_ERROR;
}
/* While card is not ready for data and trial number for sending CMD13 is not exceeded */
errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16));
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->ErrorCode |= errorstate;
}
/* Get command response */
response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1);
}
if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE)
{
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->State = HAL_MMC_STATE_READY;
return HAL_ERROR;
}
else
{
/* Configure the SDMMC peripheral */
Init.ClockEdge = hmmc->Init.ClockEdge;
Init.ClockBypass = hmmc->Init.ClockBypass;
Init.ClockPowerSave = hmmc->Init.ClockPowerSave;
Init.BusWide = WideMode;
Init.HardwareFlowControl = hmmc->Init.HardwareFlowControl;
Init.ClockDiv = hmmc->Init.ClockDiv;
SDMMC_Init(hmmc->Instance, Init);
}
/* Change State */
hmmc->State = HAL_MMC_STATE_READY;
return HAL_OK;
}
/**
* @brief Gets the current mmc card data state.
* @param hmmc: pointer to MMC handle
* @retval Card state
*/
HAL_MMC_CardStateTypeDef HAL_MMC_GetCardState(MMC_HandleTypeDef *hmmc)
{
HAL_MMC_CardStateTypeDef cardstate = HAL_MMC_CARD_TRANSFER;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
uint32_t resp1 = 0;
errorstate = MMC_SendStatus(hmmc, &resp1);
if(errorstate != HAL_OK)
{
hmmc->ErrorCode |= errorstate;
}
cardstate = (HAL_MMC_CardStateTypeDef)((resp1 >> 9) & 0x0F);
return cardstate;
}
/**
* @brief Abort the current transfer and disable the MMC.
* @param hmmc: pointer to a MMC_HandleTypeDef structure that contains
* the configuration information for MMC module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_Abort(MMC_HandleTypeDef *hmmc)
{
HAL_MMC_CardStateTypeDef CardState;
/* DIsable All interrupts */
__HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT|\
SDMMC_IT_TXUNDERR| SDMMC_IT_RXOVERR);
/* Clear All flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
if((hmmc->hdmatx != NULL) || (hmmc->hdmarx != NULL))
{
/* Disable the MMC DMA request */
hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDMMC_DCTRL_DMAEN);
/* Abort the MMC DMA Tx Stream */
if(hmmc->hdmatx != NULL)
{
HAL_DMA_Abort(hmmc->hdmatx);
}
/* Abort the MMC DMA Rx Stream */
if(hmmc->hdmarx != NULL)
{
HAL_DMA_Abort(hmmc->hdmarx);
}
}
hmmc->State = HAL_MMC_STATE_READY;
CardState = HAL_MMC_GetCardState(hmmc);
if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING))
{
hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance);
}
if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE)
{
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Abort the current transfer and disable the MMC (IT mode).
* @param hmmc: pointer to a MMC_HandleTypeDef structure that contains
* the configuration information for MMC module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MMC_Abort_IT(MMC_HandleTypeDef *hmmc)
{
HAL_MMC_CardStateTypeDef CardState;
/* DIsable All interrupts */
__HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT|\
SDMMC_IT_TXUNDERR| SDMMC_IT_RXOVERR);
/* Clear All flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
if((hmmc->hdmatx != NULL) || (hmmc->hdmarx != NULL))
{
/* Disable the MMC DMA request */
hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDMMC_DCTRL_DMAEN);
/* Abort the MMC DMA Tx Stream */
if(hmmc->hdmatx != NULL)
{
hmmc->hdmatx->XferAbortCallback = MMC_DMATxAbort;
if(HAL_DMA_Abort_IT(hmmc->hdmatx) != HAL_OK)
{
hmmc->hdmatx = NULL;
}
}
/* Abort the MMC DMA Rx Stream */
if(hmmc->hdmarx != NULL)
{
hmmc->hdmarx->XferAbortCallback = MMC_DMARxAbort;
if(HAL_DMA_Abort_IT(hmmc->hdmarx) != HAL_OK)
{
hmmc->hdmarx = NULL;
}
}
}
/* No transfer ongoing on both DMA channels*/
if((hmmc->hdmatx == NULL) && (hmmc->hdmarx == NULL))
{
CardState = HAL_MMC_GetCardState(hmmc);
hmmc->State = HAL_MMC_STATE_READY;
if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING))
{
hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance);
}
if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE)
{
return HAL_ERROR;
}
else
{
HAL_MMC_AbortCallback(hmmc);
}
}
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
/* Private function ----------------------------------------------------------*/
/** @addtogroup MMC_Private_Functions
* @{
*/
/**
* @brief DMA MMC transmit process complete callback
* @param hdma: DMA handle
* @retval None
*/
static void MMC_DMATransmitCplt(DMA_HandleTypeDef *hdma)
{
MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent);
/* Enable DATAEND Interrupt */
__HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DATAEND));
}
/**
* @brief DMA MMC receive process complete callback
* @param hdma: DMA handle
* @retval None
*/
static void MMC_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
{
MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent);
uint32_t errorstate = HAL_MMC_ERROR_NONE;
/* Send stop command in multiblock write */
if(hmmc->Context == (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA))
{
errorstate = SDMMC_CmdStopTransfer(hmmc->Instance);
if(errorstate != HAL_MMC_ERROR_NONE)
{
hmmc->ErrorCode |= errorstate;
HAL_MMC_ErrorCallback(hmmc);
}
}
/* Disable the DMA transfer for transmit request by setting the DMAEN bit
in the MMC DCTRL register */
hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDMMC_DCTRL_DMAEN);
/* Clear all the static flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
hmmc->State = HAL_MMC_STATE_READY;
HAL_MMC_RxCpltCallback(hmmc);
}
/**
* @brief DMA MMC communication error callback
* @param hdma: DMA handle
* @retval None
*/
static void MMC_DMAError(DMA_HandleTypeDef *hdma)
{
MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent);
HAL_MMC_CardStateTypeDef CardState;
if((hmmc->hdmarx->ErrorCode == HAL_DMA_ERROR_TE) || (hmmc->hdmatx->ErrorCode == HAL_DMA_ERROR_TE))
{
/* Clear All flags */
__HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS);
/* Disable All interrupts */
__HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT|\
SDMMC_IT_TXUNDERR| SDMMC_IT_RXOVERR);
hmmc->ErrorCode |= HAL_MMC_ERROR_DMA;
CardState = HAL_MMC_GetCardState(hmmc);
if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING))
{
hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance);
}
hmmc->State= HAL_MMC_STATE_READY;
}
HAL_MMC_ErrorCallback(hmmc);
}
/**
* @brief DMA MMC Tx Abort callback
* @param hdma: DMA handle
* @retval None
*/
static void MMC_DMATxAbort(DMA_HandleTypeDef *hdma)
{
MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent);
HAL_MMC_CardStateTypeDef CardState;
if(hmmc->hdmatx != NULL)
{
hmmc->hdmatx = NULL;
}
/* All DMA channels are aborted */
if(hmmc->hdmarx == NULL)
{
CardState = HAL_MMC_GetCardState(hmmc);
hmmc->ErrorCode = HAL_MMC_ERROR_NONE;
hmmc->State = HAL_MMC_STATE_READY;
if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING))
{
hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance);
if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE)
{
HAL_MMC_AbortCallback(hmmc);
}
else
{
HAL_MMC_ErrorCallback(hmmc);
}
}
}
}
/**
* @brief DMA MMC Rx Abort callback
* @param hdma: DMA handle
* @retval None
*/
static void MMC_DMARxAbort(DMA_HandleTypeDef *hdma)
{
MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent);
HAL_MMC_CardStateTypeDef CardState;
if(hmmc->hdmarx != NULL)
{
hmmc->hdmarx = NULL;
}
/* All DMA channels are aborted */
if(hmmc->hdmatx == NULL)
{
CardState = HAL_MMC_GetCardState(hmmc);
hmmc->ErrorCode = HAL_MMC_ERROR_NONE;
hmmc->State = HAL_MMC_STATE_READY;
if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING))
{
hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance);
if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE)
{
HAL_MMC_AbortCallback(hmmc);
}
else
{
HAL_MMC_ErrorCallback(hmmc);
}
}
}
}
/**
* @brief Initializes the mmc card.
* @param hmmc: Pointer to MMC handle
* @retval MMC Card error state
*/
static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc)
{
HAL_MMC_CardCSDTypeDef CSD;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
uint16_t mmc_rca = 1;
/* Check the power State */
if(SDMMC_GetPowerState(hmmc->Instance) == 0)
{
/* Power off */
return HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE;
}
/* Send CMD2 ALL_SEND_CID */
errorstate = SDMMC_CmdSendCID(hmmc->Instance);
if(errorstate != HAL_MMC_ERROR_NONE)
{
return errorstate;
}
else
{
/* Get Card identification number data */
hmmc->CID[0] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1);
hmmc->CID[1] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2);
hmmc->CID[2] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP3);
hmmc->CID[3] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP4);
}
/* Send CMD3 SET_REL_ADDR with argument 0 */
/* MMC Card publishes its RCA. */
errorstate = SDMMC_CmdSetRelAdd(hmmc->Instance, &mmc_rca);
if(errorstate != HAL_MMC_ERROR_NONE)
{
return errorstate;
}
/* Get the MMC card RCA */
hmmc->MmcCard.RelCardAdd = mmc_rca;
/* Send CMD9 SEND_CSD with argument as card's RCA */
errorstate = SDMMC_CmdSendCSD(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U));
if(errorstate != HAL_MMC_ERROR_NONE)
{
return errorstate;
}
else
{
/* Get Card Specific Data */
hmmc->CSD[0U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1);
hmmc->CSD[1U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2);
hmmc->CSD[2U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP3);
hmmc->CSD[3U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP4);
}
/* Get the Card Class */
hmmc->MmcCard.Class = (SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2) >> 20);
/* Get CSD parameters */
HAL_MMC_GetCardCSD(hmmc, &CSD);
/* Select the Card */
errorstate = SDMMC_CmdSelDesel(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16));
if(errorstate != HAL_MMC_ERROR_NONE)
{
return errorstate;
}
/* Configure SDMMC peripheral interface */
SDMMC_Init(hmmc->Instance, hmmc->Init);
/* All cards are initialized */
return HAL_MMC_ERROR_NONE;
}
/**
* @brief Enquires cards about their operating voltage and configures clock
* controls and stores MMC information that will be needed in future
* in the MMC handle.
* @param hmmc: Pointer to MMC handle
* @retval error state
*/
static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc)
{
__IO uint32_t count = 0;
uint32_t response = 0, validvoltage = 0;
uint32_t errorstate = HAL_MMC_ERROR_NONE;
/* CMD0: GO_IDLE_STATE */
errorstate = SDMMC_CmdGoIdleState(hmmc->Instance);
if(errorstate != HAL_MMC_ERROR_NONE)
{
return errorstate;
}
while(validvoltage == 0)
{
if(count++ == SDMMC_MAX_VOLT_TRIAL)
{
return HAL_MMC_ERROR_INVALID_VOLTRANGE;
}
/* SEND CMD1 APP_CMD with MMC_HIGH_VOLTAGE_RANGE(0xC0FF8000) as argument */
errorstate = SDMMC_CmdOpCondition(hmmc->Instance, eMMC_HIGH_VOLTAGE_RANGE);
if(errorstate != HAL_MMC_ERROR_NONE)
{
return HAL_MMC_ERROR_UNSUPPORTED_FEATURE;
}
/* Get command response */
response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1);
/* Get operating voltage*/
validvoltage = (((response >> 31) == 1) ? 1 : 0);
}
/* When power routine is finished and command returns valid voltage */
if ((response & MMC_HIGH_VOLTAGE_RANGE) == MMC_HIGH_VOLTAGE_RANGE)
{
/* When voltage range of the card is within 2.7V and 3.6V */
hmmc->MmcCard.CardType = MMC_HIGH_VOLTAGE_CARD;
}
else
{
/* When voltage range of the card is within 1.65V and 1.95V or 2.7V and 3.6V */
hmmc->MmcCard.CardType = MMC_DUAL_VOLTAGE_CARD;
}
return HAL_MMC_ERROR_NONE;
}
/**
* @brief Turns the SDMMC output signals off.
* @param hmmc: Pointer to MMC handle
* @retval HAL status
*/
static HAL_StatusTypeDef MMC_PowerOFF(MMC_HandleTypeDef *hmmc)
{
/* Set Power State to OFF */
SDMMC_PowerState_OFF(hmmc->Instance);
return HAL_OK;
}
/**
* @brief Returns the current card's status.
* @param hmmc: Pointer to MMC handle
* @param pCardStatus: pointer to the buffer that will contain the MMC card
* status (Card Status register)
* @retval error state
*/
static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus)
{
uint32_t errorstate = HAL_MMC_ERROR_NONE;
if(pCardStatus == NULL)
{
return HAL_MMC_ERROR_PARAM;
}
/* Send Status command */
errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16));
if(errorstate != HAL_OK)
{
return errorstate;
}
/* Get MMC card status */
*pCardStatus = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1);
return HAL_MMC_ERROR_NONE;
}
/**
* @brief Wrap up reading in non-blocking mode.
* @param hmmc: pointer to a MMC_HandleTypeDef structure that contains
* the configuration information.
* @retval HAL status
*/
static HAL_StatusTypeDef MMC_Read_IT(MMC_HandleTypeDef *hmmc)
{
uint32_t count = 0;
uint32_t* tmp;
tmp = (uint32_t*)hmmc->pRxBuffPtr;
/* Read data from SDMMC Rx FIFO */
for(count = 0; count < 8; count++)
{
*(tmp + count) = SDMMC_ReadFIFO(hmmc->Instance);
}
hmmc->pRxBuffPtr += 8;
return HAL_OK;
}
/**
* @brief Wrap up writing in non-blocking mode.
* @param hmmc: pointer to a MMC_HandleTypeDef structure that contains
* the configuration information.
* @retval HAL status
*/
static HAL_StatusTypeDef MMC_Write_IT(MMC_HandleTypeDef *hmmc)
{
uint32_t count = 0;
uint32_t* tmp;
tmp = (uint32_t*)hmmc->pTxBuffPtr;
/* Write data to SDMMC Tx FIFO */
for(count = 0; count < 8; count++)
{
SDMMC_WriteFIFO(hmmc->Instance, (tmp + count));
}
hmmc->pTxBuffPtr += 8;
return HAL_OK;
}
/**
* @}
*/
#endif /* HAL_SD_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
GustavWi/mbed | libraries/rtos/rtos/Semaphore.cpp | 77 | 1710 | /* mbed Microcontroller Library
* Copyright (c) 2006-2012 ARM Limited
*
* 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 "Semaphore.h"
#include <string.h>
namespace rtos {
Semaphore::Semaphore(int32_t count) {
#ifdef CMSIS_OS_RTX
memset(_semaphore_data, 0, sizeof(_semaphore_data));
_osSemaphoreDef.semaphore = _semaphore_data;
#endif
_osSemaphoreId = osSemaphoreCreate(&_osSemaphoreDef, count);
}
int32_t Semaphore::wait(uint32_t millisec) {
return osSemaphoreWait(_osSemaphoreId, millisec);
}
osStatus Semaphore::release(void) {
return osSemaphoreRelease(_osSemaphoreId);
}
Semaphore::~Semaphore() {
osSemaphoreDelete(_osSemaphoreId);
}
}
| apache-2.0 |
andcor02/mbed-os | targets/TARGET_Atmel/TARGET_SAM_CortexM4/drivers/usart/usart.c | 79 | 54962 | /**
* \file
*
* \brief Universal Synchronous Asynchronous Receiver Transmitter (USART) driver
* for SAM.
*
* Copyright (c) 2011-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 "usart.h"
/// @cond 0
/**INDENT-OFF**/
#ifdef __cplusplus
extern "C" {
#endif
/**INDENT-ON**/
/// @endcond
/**
* \defgroup sam_drivers_usart_group Universal Synchronous Asynchronous
* Receiver Transmitter (USART)
*
* The Universal Synchronous Asynchronous Receiver Transceiver (USART)
* provides one full duplex universal synchronous asynchronous serial link.
* Data frame format is widely programmable (data length, parity, number of
* stop bits) to support a maximum of standards. The receiver implements
* parity error, framing error and overrun error detection. The receiver
* time-out enables handling variable-length frames and the transmitter
* timeguard facilitates communications with slow remote devices. Multidrop
* communications are also supported through address bit handling in reception
* and transmission. The driver supports the following modes:
* RS232, RS485, SPI, IrDA, ISO7816, MODEM, Hardware handshaking and LIN.
*
* @{
*/
/* The write protect key value. */
#ifndef US_WPMR_WPKEY_PASSWD
#define US_WPMR_WPKEY_PASSWD US_WPMR_WPKEY(0x555341U)
#endif
#ifndef US_WPMR_WPKEY_PASSWD
# define US_WPMR_WPKEY_PASSWD US_WPMR_WPKEY(US_WPKEY_VALUE)
#endif
/* The CD value scope programmed in MR register. */
#define MIN_CD_VALUE 0x01
#define MIN_CD_VALUE_SPI 0x04
#define MAX_CD_VALUE US_BRGR_CD_Msk
/* The receiver sampling divide of baudrate clock. */
#define HIGH_FRQ_SAMPLE_DIV 16
#define LOW_FRQ_SAMPLE_DIV 8
/* Max transmitter timeguard. */
#define MAX_TRAN_GUARD_TIME US_TTGR_TG_Msk
/* The non-existent parity error number. */
#define USART_PARITY_ERROR 5
/* ISO7816 protocol type. */
#define ISO7816_T_0 0
#define ISO7816_T_1 1
/**
* \brief Calculate a clock divider(CD) and a fractional part (FP) for the
* USART asynchronous modes to generate a baudrate as close as possible to
* the baudrate set point.
*
* \note Baud rate calculation: Baudrate = ul_mck/(Over * (CD + FP/8))
* (Over being 16 or 8). The maximal oversampling is selected if it allows to
* generate a baudrate close to the set point.
*
* \param p_usart Pointer to a USART instance.
* \param baudrate Baud rate set point.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 Baud rate is successfully initialized.
* \retval 1 Baud rate set point is out of range for the given input clock
* frequency.
*/
uint32_t usart_set_async_baudrate(Usart *p_usart,
uint32_t baudrate, uint32_t ul_mck)
{
uint32_t over;
uint32_t cd_fp;
uint32_t cd;
uint32_t fp;
/* Calculate the receiver sampling divide of baudrate clock. */
if (ul_mck >= HIGH_FRQ_SAMPLE_DIV * baudrate) {
over = HIGH_FRQ_SAMPLE_DIV;
} else {
over = LOW_FRQ_SAMPLE_DIV;
}
/* Calculate clock divider according to the fraction calculated formula. */
cd_fp = (8 * ul_mck + (over * baudrate) / 2) / (over * baudrate);
cd = cd_fp >> 3;
fp = cd_fp & 0x07;
if (cd < MIN_CD_VALUE || cd > MAX_CD_VALUE) {
return 1;
}
/* Configure the OVER bit in MR register. */
if (over == 8) {
p_usart->US_MR |= US_MR_OVER;
}
/* Configure the baudrate generate register. */
p_usart->US_BRGR = (cd << US_BRGR_CD_Pos) | (fp << US_BRGR_FP_Pos);
return 0;
}
/**
* \brief Calculate a clock divider for the USART synchronous master modes
* to generate a baudrate as close as possible to the baudrate set point.
*
* \note Synchronous baudrate calculation: baudrate = ul_mck / cd
*
* \param p_usart Pointer to a USART instance.
* \param baudrate Baud rate set point.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 Baud rate is successfully initialized.
* \retval 1 Baud rate set point is out of range for the given input clock
* frequency.
*/
static uint32_t usart_set_sync_master_baudrate(Usart *p_usart,
uint32_t baudrate, uint32_t ul_mck)
{
uint32_t cd;
/* Calculate clock divider according to the formula in synchronous mode. */
cd = (ul_mck + baudrate / 2) / baudrate;
if (cd < MIN_CD_VALUE || cd > MAX_CD_VALUE) {
return 1;
}
/* Configure the baudrate generate register. */
p_usart->US_BRGR = cd << US_BRGR_CD_Pos;
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USCLKS_Msk) |
US_MR_USCLKS_MCK | US_MR_SYNC;
return 0;
}
/**
* \brief Select the SCK pin as the source of baud rate for the USART
* synchronous slave modes.
*
* \param p_usart Pointer to a USART instance.
*/
static void usart_set_sync_slave_baudrate(Usart *p_usart)
{
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USCLKS_Msk) |
US_MR_USCLKS_SCK | US_MR_SYNC;
}
/**
* \brief Calculate a clock divider (\e CD) for the USART SPI master mode to
* generate a baud rate as close as possible to the baud rate set point.
*
* \note Baud rate calculation:
* \f$ Baudrate = \frac{SelectedClock}{CD} \f$.
*
* \param p_usart Pointer to a USART instance.
* \param baudrate Baud rate set point.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 Baud rate is successfully initialized.
* \retval 1 Baud rate set point is out of range for the given input clock
* frequency.
*/
static uint32_t usart_set_spi_master_baudrate(Usart *p_usart,
uint32_t baudrate, uint32_t ul_mck)
{
uint32_t cd;
/* Calculate the clock divider according to the formula in SPI mode. */
cd = (ul_mck + baudrate / 2) / baudrate;
if (cd < MIN_CD_VALUE_SPI || cd > MAX_CD_VALUE) {
return 1;
}
p_usart->US_BRGR = cd << US_BRGR_CD_Pos;
return 0;
}
/**
* \brief Select the SCK pin as the source of baudrate for the USART SPI slave
* mode.
*
* \param p_usart Pointer to a USART instance.
*/
static void usart_set_spi_slave_baudrate(Usart *p_usart)
{
p_usart->US_MR &= ~US_MR_USCLKS_Msk;
p_usart->US_MR |= US_MR_USCLKS_SCK;
}
/**
* \brief Reset the USART and disable TX and RX.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_reset(Usart *p_usart)
{
/* Disable the Write Protect. */
usart_disable_writeprotect(p_usart);
/* Reset registers that could cause unpredictable behavior after reset. */
p_usart->US_MR = 0;
p_usart->US_RTOR = 0;
p_usart->US_TTGR = 0;
/* Disable TX and RX. */
usart_reset_tx(p_usart);
usart_reset_rx(p_usart);
/* Reset status bits. */
usart_reset_status(p_usart);
/* Turn off RTS and DTR if exist. */
usart_drive_RTS_pin_high(p_usart);
#if (SAM3S || SAM4S || SAM3U || SAM4L || SAM4E)
usart_drive_DTR_pin_high(p_usart);
#endif
}
/**
* \brief Configure USART to work in RS232 mode.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_rs232(Usart *p_usart,
const sam_usart_opt_t *p_usart_opt, uint32_t ul_mck)
{
static uint32_t ul_reg_val;
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
ul_reg_val = 0;
/* Check whether the input values are legal. */
if (!p_usart_opt || usart_set_async_baudrate(p_usart,
p_usart_opt->baudrate, ul_mck)) {
return 1;
}
/* Configure the USART option. */
ul_reg_val |= p_usart_opt->char_length | p_usart_opt->parity_type |
p_usart_opt->channel_mode | p_usart_opt->stop_bits;
/* Configure the USART mode as normal mode. */
ul_reg_val |= US_MR_USART_MODE_NORMAL;
p_usart->US_MR |= ul_reg_val;
return 0;
}
/**
* \brief Configure USART to work in hardware handshaking mode.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_hw_handshaking(Usart *p_usart,
const sam_usart_opt_t *p_usart_opt, uint32_t ul_mck)
{
/* Initialize the USART as standard RS232. */
if (usart_init_rs232(p_usart, p_usart_opt, ul_mck)) {
return 1;
}
/* Set hardware handshaking mode. */
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USART_MODE_Msk) |
US_MR_USART_MODE_HW_HANDSHAKING;
return 0;
}
#if (SAM3S || SAM4S || SAM3U || SAM4L || SAM4E)
/**
* \brief Configure USART to work in modem mode.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_modem(Usart *p_usart,
const sam_usart_opt_t *p_usart_opt, uint32_t ul_mck)
{
/*
* SAM3S, SAM4S and SAM4E series support MODEM mode only on USART1,
* SAM3U and SAM4L series support MODEM mode only on USART0.
*/
#if (SAM3S || SAM4S || SAM4E)
#ifdef USART1
if (p_usart != USART1) {
return 1;
}
#endif
#elif (SAM3U || SAM4L)
if (p_usart != USART0) {
return 1;
}
#endif
/* Initialize the USART as standard RS232. */
if (usart_init_rs232(p_usart, p_usart_opt, ul_mck)) {
return 1;
}
/* Set MODEM mode. */
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USART_MODE_Msk) |
US_MR_USART_MODE_MODEM;
return 0;
}
#endif
/**
* \brief Configure USART to work in SYNC mode and act as a master.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_sync_master(Usart *p_usart,
const sam_usart_opt_t *p_usart_opt, uint32_t ul_mck)
{
static uint32_t ul_reg_val;
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
ul_reg_val = 0;
/* Check whether the input values are legal. */
if (!p_usart_opt || usart_set_sync_master_baudrate(p_usart,
p_usart_opt->baudrate, ul_mck)) {
return 1;
}
/* Configure the USART option. */
ul_reg_val |= p_usart_opt->char_length | p_usart_opt->parity_type |
p_usart_opt->channel_mode | p_usart_opt->stop_bits;
/* Set normal mode and output clock as synchronous master. */
ul_reg_val |= US_MR_USART_MODE_NORMAL | US_MR_CLKO;
p_usart->US_MR |= ul_reg_val;
return 0;
}
/**
* \brief Configure USART to work in SYNC mode and act as a slave.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_sync_slave(Usart *p_usart,
const sam_usart_opt_t *p_usart_opt)
{
static uint32_t ul_reg_val;
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
ul_reg_val = 0;
usart_set_sync_slave_baudrate(p_usart);
/* Check whether the input values are legal. */
if (!p_usart_opt) {
return 1;
}
/* Configure the USART option. */
ul_reg_val |= p_usart_opt->char_length | p_usart_opt->parity_type |
p_usart_opt->channel_mode | p_usart_opt->stop_bits;
/* Set normal mode. */
ul_reg_val |= US_MR_USART_MODE_NORMAL;
p_usart->US_MR |= ul_reg_val;
return 0;
}
/**
* \brief Configure USART to work in RS485 mode.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_rs485(Usart *p_usart,
const sam_usart_opt_t *p_usart_opt, uint32_t ul_mck)
{
/* Initialize the USART as standard RS232. */
if (usart_init_rs232(p_usart, p_usart_opt, ul_mck)) {
return 1;
}
/* Set RS485 mode. */
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USART_MODE_Msk) |
US_MR_USART_MODE_RS485;
return 0;
}
#if (!SAMG55 && !SAMV71 && !SAMV70 && !SAME70 && !SAMS70)
/**
* \brief Configure USART to work in IrDA mode.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_irda(Usart *p_usart,
const sam_usart_opt_t *p_usart_opt, uint32_t ul_mck)
{
/* Initialize the USART as standard RS232. */
if (usart_init_rs232(p_usart, p_usart_opt, ul_mck)) {
return 1;
}
/* Set IrDA filter. */
p_usart->US_IF = p_usart_opt->irda_filter;
/* Set IrDA mode. */
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USART_MODE_Msk) |
US_MR_USART_MODE_IRDA;
return 0;
}
#endif
#if (!SAMV71 && !SAMV70 && !SAME70 && !SAMS70)
/**
* \brief Calculate a clock divider (\e CD) for the USART ISO7816 mode to
* generate an ISO7816 clock as close as possible to the clock set point.
*
* \note ISO7816 clock calculation: Clock = ul_mck / cd
*
* \param p_usart Pointer to a USART instance.
* \param clock ISO7816 clock set point.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 ISO7816 clock is successfully initialized.
* \retval 1 ISO7816 clock set point is out of range for the given input clock
* frequency.
*/
static uint32_t usart_set_iso7816_clock(Usart *p_usart,
uint32_t clock, uint32_t ul_mck)
{
uint32_t cd;
/* Calculate clock divider according to the formula in ISO7816 mode. */
cd = (ul_mck + clock / 2) / clock;
if (cd < MIN_CD_VALUE || cd > MAX_CD_VALUE) {
return 1;
}
p_usart->US_MR = (p_usart->US_MR & ~(US_MR_USCLKS_Msk | US_MR_SYNC |
US_MR_OVER)) | US_MR_USCLKS_MCK | US_MR_CLKO;
/* Configure the baudrate generate register. */
p_usart->US_BRGR = cd << US_BRGR_CD_Pos;
return 0;
}
/**
* \brief Configure USART to work in ISO7816 mode.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_iso7816(Usart *p_usart,
const usart_iso7816_opt_t *p_usart_opt, uint32_t ul_mck)
{
static uint32_t ul_reg_val;
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
ul_reg_val = 0;
/* Check whether the input values are legal. */
if (!p_usart_opt || ((p_usart_opt->parity_type != US_MR_PAR_EVEN) &&
(p_usart_opt->parity_type != US_MR_PAR_ODD))) {
return 1;
}
if (p_usart_opt->protocol_type == ISO7816_T_0) {
ul_reg_val |= US_MR_USART_MODE_IS07816_T_0 | US_MR_NBSTOP_2_BIT |
(p_usart_opt->max_iterations << US_MR_MAX_ITERATION_Pos);
if (p_usart_opt->bit_order) {
ul_reg_val |= US_MR_MSBF;
}
} else if (p_usart_opt->protocol_type == ISO7816_T_1) {
/*
* Only LSBF is used in the T=1 protocol, and max_iterations field
* is only used in T=0 mode.
*/
if (p_usart_opt->bit_order || p_usart_opt->max_iterations) {
return 1;
}
/* Set USART mode to ISO7816, T=1, and always uses 1 stop bit. */
ul_reg_val |= US_MR_USART_MODE_IS07816_T_1 | US_MR_NBSTOP_1_BIT;
} else {
return 1;
}
/* Set up the baudrate. */
if (usart_set_iso7816_clock(p_usart, p_usart_opt->iso7816_hz, ul_mck)) {
return 1;
}
/* Set FIDI register: bit rate = iso7816_hz / fidi_ratio. */
p_usart->US_FIDI = p_usart_opt->fidi_ratio;
/* Set ISO7816 parity type in the MODE register. */
ul_reg_val |= p_usart_opt->parity_type;
if (p_usart_opt->inhibit_nack) {
ul_reg_val |= US_MR_INACK;
}
if (p_usart_opt->dis_suc_nack) {
ul_reg_val |= US_MR_DSNACK;
}
p_usart->US_MR |= ul_reg_val;
return 0;
}
/**
* \brief Reset the ITERATION in US_CSR when the ISO7816 mode is enabled.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_reset_iterations(Usart *p_usart)
{
p_usart->US_CR = US_CR_RSTIT;
}
/**
* \brief Reset NACK in US_CSR.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_reset_nack(Usart *p_usart)
{
p_usart->US_CR = US_CR_RSTNACK;
}
/**
* \brief Check if one receive buffer is filled.
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 Receive is complete.
* \retval 0 Receive is still pending.
*/
uint32_t usart_is_rx_buf_end(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_ENDRX) > 0;
}
/**
* \brief Check if one transmit buffer is empty.
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 Transmit is complete.
* \retval 0 Transmit is still pending.
*/
uint32_t usart_is_tx_buf_end(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_ENDTX) > 0;
}
/**
* \brief Check if both receive buffers are full.
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 Receive buffers are full.
* \retval 0 Receive buffers are not full.
*/
uint32_t usart_is_rx_buf_full(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_RXBUFF) > 0;
}
/**
* \brief Check if both transmit buffers are empty.
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 Transmit buffers are empty.
* \retval 0 Transmit buffers are not empty.
*/
uint32_t usart_is_tx_buf_empty(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_TXBUFE) > 0;
}
/**
* \brief Get the total number of errors that occur during an ISO7816 transfer.
*
* \param p_usart Pointer to a USART instance.
*
* \return The number of errors that occurred.
*/
uint8_t usart_get_error_number(Usart *p_usart)
{
return (p_usart->US_NER & US_NER_NB_ERRORS_Msk);
}
#endif
/**
* \brief Configure USART to work in SPI mode and act as a master.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_spi_master(Usart *p_usart,
const usart_spi_opt_t *p_usart_opt, uint32_t ul_mck)
{
static uint32_t ul_reg_val;
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
ul_reg_val = 0;
/* Check whether the input values are legal. */
if (!p_usart_opt || (p_usart_opt->spi_mode > SPI_MODE_3) ||
usart_set_spi_master_baudrate(p_usart, p_usart_opt->baudrate,
ul_mck)) {
return 1;
}
/* Configure the character length bit in MR register. */
ul_reg_val |= p_usart_opt->char_length;
/* Set SPI master mode and channel mode. */
ul_reg_val |= US_MR_USART_MODE_SPI_MASTER | US_MR_CLKO |
p_usart_opt->channel_mode;
switch (p_usart_opt->spi_mode) {
case SPI_MODE_0:
ul_reg_val |= US_MR_CPHA;
ul_reg_val &= ~US_MR_CPOL;
break;
case SPI_MODE_1:
ul_reg_val &= ~US_MR_CPHA;
ul_reg_val &= ~US_MR_CPOL;
break;
case SPI_MODE_2:
ul_reg_val |= US_MR_CPHA;
ul_reg_val |= US_MR_CPOL;
break;
case SPI_MODE_3:
ul_reg_val &= ~US_MR_CPHA;
ul_reg_val |= US_MR_CPOL;
break;
default:
break;
}
p_usart->US_MR |= ul_reg_val;
return 0;
}
/**
* \brief Configure USART to work in SPI mode and act as a slave.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param p_usart_opt Pointer to sam_usart_opt_t instance.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_spi_slave(Usart *p_usart,
const usart_spi_opt_t *p_usart_opt)
{
static uint32_t ul_reg_val;
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
ul_reg_val = 0;
usart_set_spi_slave_baudrate(p_usart);
/* Check whether the input values are legal. */
if (!p_usart_opt || p_usart_opt->spi_mode > SPI_MODE_3) {
return 1;
}
/* Configure the character length bit in MR register. */
ul_reg_val |= p_usart_opt->char_length;
/* Set SPI slave mode and channel mode. */
ul_reg_val |= US_MR_USART_MODE_SPI_SLAVE | p_usart_opt->channel_mode;
switch (p_usart_opt->spi_mode) {
case SPI_MODE_0:
ul_reg_val |= US_MR_CPHA;
ul_reg_val &= ~US_MR_CPOL;
break;
case SPI_MODE_1:
ul_reg_val &= ~US_MR_CPHA;
ul_reg_val &= ~US_MR_CPOL;
break;
case SPI_MODE_2:
ul_reg_val |= US_MR_CPHA;
ul_reg_val |= US_MR_CPOL;
break;
case SPI_MODE_3:
ul_reg_val |= US_MR_CPOL;
ul_reg_val &= ~US_MR_CPHA;
break;
default:
break;
}
p_usart->US_MR |= ul_reg_val;
return 0;
}
#if (SAM3XA || SAM4L || SAMG55 || SAMV71 || SAMV70 || SAME70 || SAMS70)
/**
* \brief Configure USART to work in LIN mode and act as a LIN master.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param ul_baudrate Baudrate to be used.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_lin_master(Usart *p_usart,uint32_t ul_baudrate,
uint32_t ul_mck)
{
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
/* Set up the baudrate. */
if (usart_set_async_baudrate(p_usart, ul_baudrate, ul_mck)) {
return 1;
}
/* Set LIN master mode. */
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USART_MODE_Msk) |
US_MR_USART_MODE_LIN_MASTER;
usart_enable_rx(p_usart);
usart_enable_tx(p_usart);
return 0;
}
/**
* \brief Configure USART to work in LIN mode and act as a LIN slave.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param ul_baudrate Baudrate to be used.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_lin_slave(Usart *p_usart, uint32_t ul_baudrate,
uint32_t ul_mck)
{
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
usart_enable_rx(p_usart);
usart_enable_tx(p_usart);
/* Set LIN slave mode. */
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USART_MODE_Msk) |
US_MR_USART_MODE_LIN_SLAVE;
/* Set up the baudrate. */
if (usart_set_async_baudrate(p_usart, ul_baudrate, ul_mck)) {
return 1;
}
return 0;
}
/**
* \brief Abort the current LIN transmission.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_abort_tx(Usart *p_usart)
{
p_usart->US_CR = US_CR_LINABT;
}
/**
* \brief Send a wakeup signal on the LIN bus.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_send_wakeup_signal(Usart *p_usart)
{
p_usart->US_CR = US_CR_LINWKUP;
}
/**
* \brief Configure the LIN node action, which should be one of PUBLISH,
* SUBSCRIBE or IGNORE.
*
* \param p_usart Pointer to a USART instance.
* \param uc_action 0 for PUBLISH, 1 for SUBSCRIBE, 2 for IGNORE.
*/
void usart_lin_set_node_action(Usart *p_usart, uint8_t uc_action)
{
p_usart->US_LINMR = (p_usart->US_LINMR & ~US_LINMR_NACT_Msk) |
(uc_action << US_LINMR_NACT_Pos);
}
/**
* \brief Disable the parity check during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_disable_parity(Usart *p_usart)
{
p_usart->US_LINMR |= US_LINMR_PARDIS;
}
/**
* \brief Enable the parity check during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_enable_parity(Usart *p_usart)
{
p_usart->US_LINMR &= ~US_LINMR_PARDIS;
}
/**
* \brief Disable the checksum during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_disable_checksum(Usart *p_usart)
{
p_usart->US_LINMR |= US_LINMR_CHKDIS;
}
/**
* \brief Enable the checksum during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_enable_checksum(Usart *p_usart)
{
p_usart->US_LINMR &= ~US_LINMR_CHKDIS;
}
/**
* \brief Configure the checksum type during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
* \param uc_type 0 for LIN 2.0 Enhanced checksum or 1 for LIN 1.3 Classic
* checksum.
*/
void usart_lin_set_checksum_type(Usart *p_usart, uint8_t uc_type)
{
p_usart->US_LINMR = (p_usart->US_LINMR & ~US_LINMR_CHKTYP) |
(uc_type << 4);
}
/**
* \brief Configure the data length mode during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
* \param uc_mode Indicate the data length type: 0 if the data length is
* defined by the DLC of LIN mode register or 1 if the data length is defined
* by the bit 5 and 6 of the identifier.
*/
void usart_lin_set_data_len_mode(Usart *p_usart, uint8_t uc_mode)
{
p_usart->US_LINMR = (p_usart->US_LINMR & ~US_LINMR_DLM) |
(uc_mode << 5);
}
/**
* \brief Disable the frame slot mode during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_disable_frame_slot(Usart *p_usart)
{
p_usart->US_LINMR |= US_LINMR_FSDIS;
}
/**
* \brief Enable the frame slot mode during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_enable_frame_slot(Usart *p_usart)
{
p_usart->US_LINMR &= ~US_LINMR_FSDIS;
}
/**
* \brief Configure the wakeup signal type during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
* \param uc_type Indicate the checksum type: 0 if the wakeup signal is a
* LIN 2.0 wakeup signal; 1 if the wakeup signal is a LIN 1.3 wakeup signal.
*/
void usart_lin_set_wakeup_signal_type(Usart *p_usart, uint8_t uc_type)
{
p_usart->US_LINMR = (p_usart->US_LINMR & ~US_LINMR_WKUPTYP) |
(uc_type << 7);
}
/**
* \brief Configure the response data length if the data length is defined by
* the DLC field during the LIN communication.
*
* \param p_usart Pointer to a USART instance.
* \param uc_len Indicate the response data length.
*/
void usart_lin_set_response_data_len(Usart *p_usart, uint8_t uc_len)
{
p_usart->US_LINMR = (p_usart->US_LINMR & ~US_LINMR_DLC_Msk) |
((uc_len - 1) << US_LINMR_DLC_Pos);
}
/**
* \brief The LIN mode register is not written by the PDC.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_disable_pdc_mode(Usart *p_usart)
{
p_usart->US_LINMR &= ~US_LINMR_PDCM;
}
/**
* \brief The LIN mode register (except this flag) is written by the PDC.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lin_enable_pdc_mode(Usart *p_usart)
{
p_usart->US_LINMR |= US_LINMR_PDCM;
}
/**
* \brief Configure the LIN identifier when USART works in LIN master mode.
*
* \param p_usart Pointer to a USART instance.
* \param uc_id The identifier to be transmitted.
*/
void usart_lin_set_tx_identifier(Usart *p_usart, uint8_t uc_id)
{
p_usart->US_LINIR = (p_usart->US_LINIR & ~US_LINIR_IDCHR_Msk) |
US_LINIR_IDCHR(uc_id);
}
/**
* \brief Read the identifier when USART works in LIN mode.
*
* \param p_usart Pointer to a USART instance.
*
* \return The last identifier received in LIN slave mode or the last
* identifier transmitted in LIN master mode.
*/
uint8_t usart_lin_read_identifier(Usart *p_usart)
{
return (p_usart->US_LINIR & US_LINIR_IDCHR_Msk);
}
/**
* \brief Get data length.
*
* \param p_usart Pointer to a USART instance.
*
* \return Data length.
*/
uint8_t usart_lin_get_data_length(Usart *usart)
{
if (usart->US_LINMR & US_LINMR_DLM) {
uint8_t data_length = 1 << ((usart->US_LINIR >>
(US_LINIR_IDCHR_Pos + 4)) & 0x03);
return data_length;
} else {
return ((usart->US_LINMR & US_LINMR_DLC_Msk) >> US_LINMR_DLC_Pos) + 1;
}
}
#endif
#if (SAMV71 || SAMV70 || SAME70 || SAMS70)
/**
* \brief Get identifier send status.
*
* \param p_usart Pointer to a USART instance.
*
* \return
* 0: No LIN identifier has been sent since the last RSTSTA.
* 1: :At least one LIN identifier has been sent since the last RSTSTA.
*/
uint8_t usart_lin_identifier_send_complete(Usart *usart)
{
return (usart->US_CSR & US_CSR_LINID) > 0;
}
/**
* \brief Get identifier received status.
*
* \param p_usart Pointer to a USART instance.
*
* \return
* 0: No LIN identifier has been reveived since the last RSTSTA.
* 1: At least one LIN identifier has been received since the last RSTSTA.
*/
uint8_t usart_lin_identifier_reception_complete(Usart *usart)
{
return (usart->US_CSR & US_CSR_LINID) > 0;
}
/**
* \brief Get transmission status.
*
* \param p_usart Pointer to a USART instance.
*
* \return
* 0: The USART is idle or a LIN transfer is ongoing.
* 1: A LIN transfer has been completed since the last RSTSTA.
*/
uint8_t usart_lin_tx_complete(Usart *usart)
{
return (usart->US_CSR & US_CSR_LINTC) > 0;
}
/**
* \brief Configure USART to work in LON mode.
*
* \note By default, the transmitter and receiver aren't enabled.
*
* \param p_usart Pointer to a USART instance.
* \param ul_baudrate Baudrate to be used.
* \param ul_mck USART module input clock frequency.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_init_lon(Usart *p_usart,uint32_t ul_baudrate,
uint32_t ul_mck)
{
/* Reset the USART and shut down TX and RX. */
usart_reset(p_usart);
/* Set up the baudrate. */
if (usart_set_async_baudrate(p_usart, ul_baudrate, ul_mck)) {
return 1;
}
/* Set LIN master mode. */
p_usart->US_MR = (p_usart->US_MR & ~US_MR_USART_MODE_Msk) |
US_MR_USART_MODE_LON;
usart_enable_rx(p_usart);
usart_enable_tx(p_usart);
return 0;
}
/**
* \brief set LON parameter value.
*
* \param p_usart Pointer to a USART instance.
* \param uc_type 0: LON comm_type = 1 mode,
* 1: LON comm_type = 2 mode
*/
void usart_lon_set_comm_type(Usart *p_usart, uint8_t uc_type)
{
p_usart->US_LONMR = (p_usart->US_LONMR & ~US_LONMR_COMMT) |
(uc_type << 0);
}
/**
* \brief Disable LON Collision Detection Feature.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lon_disable_coll_detection(Usart *p_usart)
{
p_usart->US_LONMR |= US_LONMR_COLDET;
}
/**
* \brief Enable LON Collision Detection Feature.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_lon_enable_coll_detection(Usart *p_usart)
{
p_usart->US_LONMR &= ~US_LONMR_COLDET;
}
/**
* \brief set Terminate Frame upon Collision Notification.
*
* \param p_usart Pointer to a USART instance.
* \param uc_type 0: Do not terminate the frame in LON comm_type = 1 mode upon collision detection.
* 1:Terminate the frame in LON comm_type = 1 mode upon collision detection if possible.
*/
void usart_lon_set_tcol(Usart *p_usart, uint8_t uc_type)
{
p_usart->US_LONMR = (p_usart->US_LONMR & ~US_LONMR_TCOL) |
(uc_type << 2);
}
/**
* \brief set LON Collision Detection on Frame Tail.
*
* \param p_usart Pointer to a USART instance.
* \param uc_type 0: Detect collisions after CRC has been sent but prior end of transmission in LON comm_type = 1 mode.
* 1: Ignore collisions after CRC has been sent but prior end of transmission in LON comm_type = 1 mode.
*/
void usart_lon_set_cdtail(Usart *p_usart, uint8_t uc_type)
{
p_usart->US_LONMR = (p_usart->US_LONMR & ~US_LONMR_CDTAIL) |
(uc_type << 3);
}
/**
* \brief set LON DMA Mode.
*
* \param p_usart Pointer to a USART instance.
* \param uc_type 0: The LON data length register US_LONDL is not written by the DMA.
* 1: The LON data length register US_LONDL is written by the DMA.
*/
void usart_lon_set_dmam(Usart *p_usart, uint8_t uc_type)
{
p_usart->US_LONMR = (p_usart->US_LONMR & ~US_LONMR_DMAM) |
(uc_type << 4);
}
/**
* \brief set LON Beta1 Length after Transmission.
*
* \param p_usart Pointer to a USART instance.
* \param ul_len 1-16777215: LON beta1 length after transmission in tbit
*/
void usart_lon_set_beta1_tx_len(Usart *p_usart, uint32_t ul_len)
{
p_usart->US_LONB1TX = US_LONB1TX_BETA1TX(ul_len);
}
/**
* \brief set LON Beta1 Length after Reception.
*
* \param p_usart Pointer to a USART instance.
* \param ul_len 1-16777215: LON beta1 length after reception in tbit.
*/
void usart_lon_set_beta1_rx_len(Usart *p_usart, uint32_t ul_len)
{
p_usart->US_LONB1RX = US_LONB1RX_BETA1RX(ul_len);
}
/**
* \brief set LON Priority.
*
* \param p_usart Pointer to a USART instance.
* \param uc_psnb 0 -127: LON Priority Slot Number.
* \param uc_nps 0 -127: LON Node Priority Slot.
*/
void usart_lon_set_priority(Usart *p_usart, uint8_t uc_psnb, uint8_t uc_nps)
{
p_usart->US_LONPRIO = US_LONPRIO_PSNB(uc_psnb) | US_LONPRIO_NPS(uc_nps);
}
/**
* \brief set LON Indeterminate Time after Transmission.
*
* \param p_usart Pointer to a USART instance.
* \param ul_time 1-16777215: LON Indeterminate Time after Transmission (comm_type = 1 mode only).
*/
void usart_lon_set_tx_idt(Usart *p_usart, uint32_t ul_time)
{
p_usart->US_IDTTX = US_IDTTX_IDTTX(ul_time);
}
/**
* \brief set LON Indeterminate Time after Reception.
*
* \param p_usart Pointer to a USART instance.
* \param ul_time 1-16777215: LON Indeterminate Time after Reception (comm_type = 1 mode only).
*/
void usart_lon_set_rx_idt(Usart *p_usart, uint32_t ul_time)
{
p_usart->US_IDTRX = US_IDTRX_IDTRX(ul_time);
}
/**
* \brief set LON Preamble Length.
*
* \param p_usart Pointer to a USART instance.
* \param ul_len 1-16383: LON preamble length in tbit(without byte-sync).
*/
void usart_lon_set_pre_len(Usart *p_usart, uint32_t ul_len)
{
p_usart->US_LONPR = US_LONPR_LONPL(ul_len);
}
/**
* \brief set LON Data Length.
*
* \param p_usart Pointer to a USART instance.
* \param uc_len 0-255: LON data length is LONDL+1 bytes.
*/
void usart_lon_set_data_len(Usart *p_usart, uint8_t uc_len)
{
p_usart->US_LONDL = US_LONDL_LONDL(uc_len);
}
/**
* \brief set LON Priority.
*
* \param p_usart Pointer to a USART instance.
* \param uc_bli LON Backlog Increment.
* \param uc_altp LON Alternate Path Bit.
* \param uc_pb LON Priority Bit.
*/
void usart_lon_set_l2hdr(Usart *p_usart, uint8_t uc_bli, uint8_t uc_altp, uint8_t uc_pb)
{
p_usart->US_LONL2HDR = US_LONL2HDR_BLI(uc_bli) | (uc_altp << 6) | (uc_pb << 7);
}
/**
* \brief Check if LON Transmission End.
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 At least one transmission has been performed since the last RSTSTA.
* \retval 0 Transmission on going or no transmission occurred since the last RSTSTA.
*/
uint32_t usart_lon_is_tx_end(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_LTXD) > 0;
}
/**
* \brief Check if LON Reception End.
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 At least one Reception has been performed since the last RSTSTA.
* \retval 0 Reception on going or no Reception occurred since the last RSTSTA.
*/
uint32_t usart_lon_is_rx_end(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_LRXD) > 0;
}
#endif
/**
* \brief Enable USART transmitter.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_enable_tx(Usart *p_usart)
{
p_usart->US_CR = US_CR_TXEN;
}
/**
* \brief Disable USART transmitter.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_disable_tx(Usart *p_usart)
{
p_usart->US_CR = US_CR_TXDIS;
}
/**
* \brief Immediately stop and disable USART transmitter.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_reset_tx(Usart *p_usart)
{
/* Reset transmitter */
p_usart->US_CR = US_CR_RSTTX | US_CR_TXDIS;
}
/**
* \brief Configure the transmit timeguard register.
*
* \param p_usart Pointer to a USART instance.
* \param timeguard The value of transmit timeguard.
*/
void usart_set_tx_timeguard(Usart *p_usart, uint32_t timeguard)
{
p_usart->US_TTGR = timeguard;
}
/**
* \brief Enable USART receiver.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_enable_rx(Usart *p_usart)
{
p_usart->US_CR = US_CR_RXEN;
}
/**
* \brief Disable USART receiver.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_disable_rx(Usart *p_usart)
{
p_usart->US_CR = US_CR_RXDIS;
}
/**
* \brief Immediately stop and disable USART receiver.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_reset_rx(Usart *p_usart)
{
/* Reset Receiver */
p_usart->US_CR = US_CR_RSTRX | US_CR_RXDIS;
}
/**
* \brief Configure the receive timeout register.
*
* \param p_usart Pointer to a USART instance.
* \param timeout The value of receive timeout.
*/
void usart_set_rx_timeout(Usart *p_usart, uint32_t timeout)
{
p_usart->US_RTOR = timeout;
}
/**
* \brief Enable USART interrupts.
*
* \param p_usart Pointer to a USART peripheral.
* \param ul_sources Interrupt sources bit map.
*/
void usart_enable_interrupt(Usart *p_usart, uint32_t ul_sources)
{
p_usart->US_IER = ul_sources;
}
/**
* \brief Disable USART interrupts.
*
* \param p_usart Pointer to a USART peripheral.
* \param ul_sources Interrupt sources bit map.
*/
void usart_disable_interrupt(Usart *p_usart, uint32_t ul_sources)
{
p_usart->US_IDR = ul_sources;
}
/**
* \brief Read USART interrupt mask.
*
* \param p_usart Pointer to a USART peripheral.
*
* \return The interrupt mask value.
*/
uint32_t usart_get_interrupt_mask(Usart *p_usart)
{
return p_usart->US_IMR;
}
/**
* \brief Get current status.
*
* \param p_usart Pointer to a USART instance.
*
* \return The current USART status.
*/
uint32_t usart_get_status(Usart *p_usart)
{
return p_usart->US_CSR;
}
/**
* \brief Reset status bits (PARE, OVER, MANERR, UNRE and PXBRK in US_CSR).
*
* \param p_usart Pointer to a USART instance.
*/
void usart_reset_status(Usart *p_usart)
{
p_usart->US_CR = US_CR_RSTSTA;
}
/**
* \brief Start transmission of a break.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_start_tx_break(Usart *p_usart)
{
p_usart->US_CR = US_CR_STTBRK;
}
/**
* \brief Stop transmission of a break.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_stop_tx_break(Usart *p_usart)
{
p_usart->US_CR = US_CR_STPBRK;
}
/**
* \brief Start waiting for a character before clocking the timeout count.
* Reset the status bit TIMEOUT in US_CSR.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_start_rx_timeout(Usart *p_usart)
{
p_usart->US_CR = US_CR_STTTO;
}
/**
* \brief In Multidrop mode only, the next character written to the US_THR
* is sent with the address bit set.
*
* \param p_usart Pointer to a USART instance.
* \param ul_addr The address to be sent out.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_send_address(Usart *p_usart, uint32_t ul_addr)
{
if ((p_usart->US_MR & US_MR_PAR_MULTIDROP) != US_MR_PAR_MULTIDROP) {
return 1;
}
p_usart->US_CR = US_CR_SENDA;
if (usart_write(p_usart, ul_addr)) {
return 1;
} else {
return 0;
}
}
/**
* \brief Restart the receive timeout.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_restart_rx_timeout(Usart *p_usart)
{
p_usart->US_CR = US_CR_RETTO;
}
#if (SAM3S || SAM4S || SAM3U || SAM4L || SAM4E)
/**
* \brief Drive the pin DTR to 0.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_drive_DTR_pin_low(Usart *p_usart)
{
p_usart->US_CR = US_CR_DTREN;
}
/**
* \brief Drive the pin DTR to 1.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_drive_DTR_pin_high(Usart *p_usart)
{
p_usart->US_CR = US_CR_DTRDIS;
}
#endif
/**
* \brief Drive the pin RTS to 0.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_drive_RTS_pin_low(Usart *p_usart)
{
p_usart->US_CR = US_CR_RTSEN;
}
/**
* \brief Drive the pin RTS to 1.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_drive_RTS_pin_high(Usart *p_usart)
{
p_usart->US_CR = US_CR_RTSDIS;
}
/**
* \brief Drive the slave select line NSS (RTS pin) to 0 in SPI master mode.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_spi_force_chip_select(Usart *p_usart)
{
p_usart->US_CR = US_CR_FCS;
}
/**
* \brief Drive the slave select line NSS (RTS pin) to 1 in SPI master mode.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_spi_release_chip_select(Usart *p_usart)
{
p_usart->US_CR = US_CR_RCS;
}
/**
* \brief Check if Transmit is Ready.
* Check if data have been loaded in USART_THR and are waiting to be loaded
* into the Transmit Shift Register (TSR).
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 No data is in the Transmit Holding Register.
* \retval 0 There is data in the Transmit Holding Register.
*/
uint32_t usart_is_tx_ready(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_TXRDY) > 0;
}
/**
* \brief Check if Transmit Holding Register is empty.
* Check if the last data written in USART_THR have been loaded in TSR and the
* last data loaded in TSR have been transmitted.
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 Transmitter is empty.
* \retval 0 Transmitter is not empty.
*/
uint32_t usart_is_tx_empty(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_TXEMPTY) > 0;
}
/**
* \brief Check if the received data are ready.
* Check if Data have been received and loaded into USART_RHR.
*
* \param p_usart Pointer to a USART instance.
*
* \retval 1 Some data has been received.
* \retval 0 No data has been received.
*/
uint32_t usart_is_rx_ready(Usart *p_usart)
{
return (p_usart->US_CSR & US_CSR_RXRDY) > 0;
}
/**
* \brief Write to USART Transmit Holding Register.
*
* \note Before writing user should check if tx is ready (or empty).
*
* \param p_usart Pointer to a USART instance.
* \param c Data to be sent.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_write(Usart *p_usart, uint32_t c)
{
if (!(p_usart->US_CSR & US_CSR_TXRDY)) {
return 1;
}
p_usart->US_THR = US_THR_TXCHR(c);
return 0;
}
/**
* \brief Write to USART Transmit Holding Register.
*
* \note Before writing user should check if tx is ready (or empty).
*
* \param p_usart Pointer to a USART instance.
* \param c Data to be sent.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
uint32_t usart_putchar(Usart *p_usart, uint32_t c)
{
while (!(p_usart->US_CSR & US_CSR_TXRDY)) {
}
p_usart->US_THR = US_THR_TXCHR(c);
return 0;
}
/**
* \brief Write one-line string through USART.
*
* \param p_usart Pointer to a USART instance.
* \param string Pointer to one-line string to be sent.
*/
void usart_write_line(Usart *p_usart, const char *string)
{
while (*string != '\0') {
usart_putchar(p_usart, *string++);
}
}
/**
* \brief Read from USART Receive Holding Register.
*
* \note Before reading user should check if rx is ready.
*
* \param p_usart Pointer to a USART instance.
* \param c Pointer where the one-byte received data will be stored.
*
* \retval 0 on success.
* \retval 1 if no data is available or errors.
*/
uint32_t usart_read(Usart *p_usart, uint32_t *c)
{
if (!(p_usart->US_CSR & US_CSR_RXRDY)) {
return 1;
}
/* Read character */
*c = p_usart->US_RHR & US_RHR_RXCHR_Msk;
return 0;
}
/**
* \brief Read from USART Receive Holding Register.
* Before reading user should check if rx is ready.
*
* \param p_usart Pointer to a USART instance.
* \param c Pointer where the one-byte received data will be stored.
*
* \retval 0 Data has been received.
* \retval 1 on failure.
*/
uint32_t usart_getchar(Usart *p_usart, uint32_t *c)
{
/* Wait until it's not empty or timeout has reached. */
while (!(p_usart->US_CSR & US_CSR_RXRDY)) {
}
/* Read character */
*c = p_usart->US_RHR & US_RHR_RXCHR_Msk;
return 0;
}
#if (SAM3XA || SAM3U)
/**
* \brief Get Transmit address for DMA operation.
*
* \param p_usart Pointer to a USART instance.
*
* \return Transmit address for DMA access.
*/
uint32_t *usart_get_tx_access(Usart *p_usart)
{
return (uint32_t *)&(p_usart->US_THR);
}
/**
* \brief Get Receive address for DMA operation.
*
* \param p_usart Pointer to a USART instance.
*
* \return Receive address for DMA access.
*/
uint32_t *usart_get_rx_access(Usart *p_usart)
{
return (uint32_t *)&(p_usart->US_RHR);
}
#endif
#if (!SAM4L && !SAMV71 && !SAMV70 && !SAME70 && !SAMS70)
/**
* \brief Get USART PDC base address.
*
* \param p_usart Pointer to a UART instance.
*
* \return USART PDC registers base for PDC driver to access.
*/
Pdc *usart_get_pdc_base(Usart *p_usart)
{
Pdc *p_pdc_base;
p_pdc_base = (Pdc *)NULL;
#ifdef PDC_USART
if (p_usart == USART) {
p_pdc_base = PDC_USART;
return p_pdc_base;
}
#endif
#ifdef PDC_USART0
if (p_usart == USART0) {
p_pdc_base = PDC_USART0;
return p_pdc_base;
}
#endif
#ifdef PDC_USART1
else if (p_usart == USART1) {
p_pdc_base = PDC_USART1;
return p_pdc_base;
}
#endif
#ifdef PDC_USART2
else if (p_usart == USART2) {
p_pdc_base = PDC_USART2;
return p_pdc_base;
}
#endif
#ifdef PDC_USART3
else if (p_usart == USART3) {
p_pdc_base = PDC_USART3;
return p_pdc_base;
}
#endif
#ifdef PDC_USART4
else if (p_usart == USART4) {
p_pdc_base = PDC_USART4;
return p_pdc_base;
}
#endif
#ifdef PDC_USART5
else if (p_usart == USART5) {
p_pdc_base = PDC_USART5;
return p_pdc_base;
}
#endif
#ifdef PDC_USART6
else if (p_usart == USART6) {
p_pdc_base = PDC_USART6;
return p_pdc_base;
}
#endif
#ifdef PDC_USART7
else if (p_usart == USART7) {
p_pdc_base = PDC_USART7;
return p_pdc_base;
}
#endif
return p_pdc_base;
}
#endif
/**
* \brief Enable write protect of USART registers.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_enable_writeprotect(Usart *p_usart)
{
p_usart->US_WPMR = US_WPMR_WPEN | US_WPMR_WPKEY_PASSWD;
}
/**
* \brief Disable write protect of USART registers.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_disable_writeprotect(Usart *p_usart)
{
p_usart->US_WPMR = US_WPMR_WPKEY_PASSWD;
}
/**
* \brief Get write protect status.
*
* \param p_usart Pointer to a USART instance.
*
* \return 0 if no write protect violation occurred, or 16-bit write protect
* violation source.
*/
uint32_t usart_get_writeprotect_status(Usart *p_usart)
{
uint32_t reg_value;
reg_value = p_usart->US_WPSR;
if (reg_value & US_WPSR_WPVS) {
return (reg_value & US_WPSR_WPVSRC_Msk) >> US_WPSR_WPVSRC_Pos;
} else {
return 0;
}
}
#if (SAM3S || SAM4S || SAM3U || SAM3XA || SAM4L || SAM4E || SAM4C || SAM4CP || SAM4CM)
/**
* \brief Configure the transmitter preamble length when the Manchester
* encode/decode is enabled.
*
* \param p_usart Pointer to a USART instance.
* \param uc_len The transmitter preamble length, which should be 0 ~ 15.
*/
void usart_man_set_tx_pre_len(Usart *p_usart, uint8_t uc_len)
{
p_usart->US_MAN = (p_usart->US_MAN & ~US_MAN_TX_PL_Msk) |
US_MAN_TX_PL(uc_len);
}
/**
* \brief Configure the transmitter preamble pattern when the Manchester
* encode/decode is enabled, which should be 0 ~ 3.
*
* \param p_usart Pointer to a USART instance.
* \param uc_pattern 0 if the preamble is composed of '1's;
* 1 if the preamble is composed of '0's;
* 2 if the preamble is composed of '01's;
* 3 if the preamble is composed of '10's.
*/
void usart_man_set_tx_pre_pattern(Usart *p_usart, uint8_t uc_pattern)
{
p_usart->US_MAN = (p_usart->US_MAN & ~US_MAN_TX_PP_Msk) |
(uc_pattern << US_MAN_TX_PP_Pos);
}
/**
* \brief Configure the transmitter Manchester polarity when the Manchester
* encode/decode is enabled.
*
* \param p_usart Pointer to a USART instance.
* \param uc_polarity Indicate the transmitter Manchester polarity, which
* should be 0 or 1.
*/
void usart_man_set_tx_polarity(Usart *p_usart, uint8_t uc_polarity)
{
p_usart->US_MAN = (p_usart->US_MAN & ~US_MAN_TX_MPOL) |
(uc_polarity << 12);
}
/**
* \brief Configure the detected receiver preamble length when the Manchester
* encode/decode is enabled.
*
* \param p_usart Pointer to a USART instance.
* \param uc_len The detected receiver preamble length, which should be 0 ~ 15.
*/
void usart_man_set_rx_pre_len(Usart *p_usart, uint8_t uc_len)
{
p_usart->US_MAN = (p_usart->US_MAN & ~US_MAN_RX_PL_Msk) |
US_MAN_RX_PL(uc_len);
}
/**
* \brief Configure the detected receiver preamble pattern when the Manchester
* encode/decode is enabled, which should be 0 ~ 3.
*
* \param p_usart Pointer to a USART instance.
* \param uc_pattern 0 if the preamble is composed of '1's;
* 1 if the preamble is composed of '0's;
* 2 if the preamble is composed of '01's;
* 3 if the preamble is composed of '10's.
*/
void usart_man_set_rx_pre_pattern(Usart *p_usart, uint8_t uc_pattern)
{
p_usart->US_MAN = (p_usart->US_MAN & ~US_MAN_RX_PP_Msk) |
(uc_pattern << US_MAN_RX_PP_Pos);
}
/**
* \brief Configure the receiver Manchester polarity when the Manchester
* encode/decode is enabled.
*
* \param p_usart Pointer to a USART instance.
* \param uc_polarity Indicate the receiver Manchester polarity, which should
* be 0 or 1.
*/
void usart_man_set_rx_polarity(Usart *p_usart, uint8_t uc_polarity)
{
p_usart->US_MAN = (p_usart->US_MAN & ~US_MAN_RX_MPOL) |
(uc_polarity << 28);
}
/**
* \brief Enable drift compensation.
*
* \note The 16X clock mode must be enabled.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_man_enable_drift_compensation(Usart *p_usart)
{
p_usart->US_MAN |= US_MAN_DRIFT;
}
/**
* \brief Disable drift compensation.
*
* \param p_usart Pointer to a USART instance.
*/
void usart_man_disable_drift_compensation(Usart *p_usart)
{
p_usart->US_MAN &= ~US_MAN_DRIFT;
}
#endif
#if SAM4L
uint32_t usart_get_version(Usart *p_usart)
{
return p_usart->US_VERSION;
}
#endif
#if SAMG55
/**
* \brief Set sleepwalking match mode.
*
* \param p_uart Pointer to a USART instance.
* \param ul_low_value First comparison value for received character.
* \param ul_high_value Second comparison value for received character.
* \param cmpmode ture for start condition, false for flag only.
* \param cmppar ture for parity check, false for no.
*/
void usart_set_sleepwalking(Usart *p_uart, uint8_t ul_low_value,
bool cmpmode, bool cmppar, uint8_t ul_high_value)
{
Assert(ul_low_value <= ul_high_value);
uint32_t temp = 0;
if (cmpmode) {
temp |= US_CMPR_CMPMODE_START_CONDITION;
}
if (cmppar) {
temp |= US_CMPR_CMPPAR;
}
temp |= US_CMPR_VAL1(ul_low_value);
temp |= US_CMPR_VAL2(ul_high_value);
p_uart->US_CMPR= temp;
}
#endif
//@}
/// @cond 0
/**INDENT-OFF**/
#ifdef __cplusplus
}
#endif
/**INDENT-ON**/
/// @endcond
| apache-2.0 |
apache/thrift | lib/cpp/src/thrift/server/TServer.cpp | 103 | 1458 | /*
* 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 <thrift/thrift-config.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
namespace apache {
namespace thrift {
namespace server {
#ifdef HAVE_SYS_RESOURCE_H
int increase_max_fds(int max_fds = (1 << 24)) {
struct rlimit fdmaxrl;
for (fdmaxrl.rlim_cur = max_fds, fdmaxrl.rlim_max = max_fds;
max_fds && (setrlimit(RLIMIT_NOFILE, &fdmaxrl) < 0);
fdmaxrl.rlim_cur = max_fds, fdmaxrl.rlim_max = max_fds) {
max_fds /= 2;
}
return static_cast<int>(fdmaxrl.rlim_cur);
}
#endif
}
}
} // apache::thrift::server
| apache-2.0 |
MCGallaspy/selenium | cpp/iedriverserver/stdafx.cpp | 108 | 1100 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// stdafx.cpp : source file that includes just the standard includes
// InternetExplorerDriver.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| apache-2.0 |
Natoto/TeamTalk | win-client/src/Modules/Session/Operation/DownloadAvatarHttpOperation.cpp | 126 | 3170 | /*******************************************************************************
* @file DownloadImgHttpOperation.cpp 2014\8\14 10:19:07 $
* @author ¿ìµ¶<kuaidao@mogujie.com>
* @brief
******************************************************************************/
#include "stdafx.h"
#include "DownloadAvatarHttpOperation.h"
#include "http/httpclient/http.h"
#include "Modules/IMiscModule.h"
#include "Modules/IDatabaseModule.h"
#include "Modules/ISysConfigModule.h"
#include "Modules/IUserListModule.h"
#include "utility/utilStrCodingAPI.h"
#include "cxImage/cxImage/ximage.h"
/******************************************************************************/
// -----------------------------------------------------------------------------
// DownloadImgHttpOperation: Public, Constructor
DownloadAvatarHttpOperation::DownloadAvatarHttpOperation(std::string sId, std::string& downUrl, BOOL bGrayScale
,const std::string format, module::IOperationDelegate callback)
:IHttpOperation(callback)
,m_downUrl(downUrl)
,m_sId(sId)
,m_bGrayScale(bGrayScale)
,m_format(format)
{
}
// -----------------------------------------------------------------------------
// DownloadImgHttpOperation: Public, Destructor
DownloadAvatarHttpOperation::~DownloadAvatarHttpOperation()
{
}
void DownloadAvatarHttpOperation::processOpertion()
{
CString extName = ::PathFindExtension(util::stringToCString(m_downUrl));
UInt32 hashcode = util::hash_BKDR((m_downUrl + m_format).c_str());
std::string downFormat = util::cStringToString(extName);
Http::HttpResponse response;
Http::HttpClient client;
Http::HttpRequest request("GET", m_downUrl);
if (isCanceled())
return;
//ÏÂÔØ×ÊÔ´
CString csFileName = util::int32ToCString(hashcode) + extName;
CString csLocalPath = module::getMiscModule()->getDownloadDir() + csFileName;
std::wstring cs = csLocalPath;
request.saveToFile(cs);
if (!client.execute(&request, &response))
{
CString csTemp = util::stringToCString(m_downUrl, CP_UTF8);
LOG__(ERR, _T("DownloadImgHttpOperation failed %s"), csTemp);
client.killSelf();
return;
}
client.killSelf();
if (PathFileExists(csLocalPath))
{
DownloadImgParam* pParam = new DownloadImgParam;
pParam->m_sId = m_sId;
pParam->m_result = DownloadImgParam::DOWNLOADIMG_OK;
//´æÈëImImage±í
std::string localPath = util::cStringToString(csFileName);
module::ImImageEntity imgTemp;
module::ImImageEntity imgEntity = { hashcode, localPath, m_downUrl };
module::getDatabaseModule()->sqlInsertImImageEntity(imgEntity);
//»áÍ·Ïñ×ö»Ò¶È´¦Àí£¬²¢ÇÒ±£´æµ½±¾µØ
if (m_bGrayScale)
{
CxImage cximage;
bool bSucc = cximage.Load(csLocalPath);
if (bSucc)
{
if (cximage.GrayScale())
{
CString csGrayPath = module::getMiscModule()->getDownloadDir()
+ PREFIX_GRAY_AVATAR + csFileName;
cximage.Save(csGrayPath, CXIMAGE_SUPPORT_JPG);
}
}
}
if (!isCanceled())
{
//»Øµ÷
pParam->m_imgEntity = imgEntity;
asyncCallback(std::shared_ptr<void>(pParam));
}
}
}
void DownloadAvatarHttpOperation::release()
{
delete this;
}
/******************************************************************************/ | apache-2.0 |
christisall/TeamTalk | server/src/http_msg_server/RouteServConn.cpp | 128 | 4386 | /*
* RouteServConn.cpp
*
* Created on: 2013-7-8
* Author: ziteng@mogujie.com
*/
#include "RouteServConn.h"
#include "DBServConn.h"
#include "HttpConn.h"
#include "HttpPdu.h"
#include "IM.Server.pb.h"
#include "IM.Other.pb.h"
#include "ImPduBase.h"
namespace HTTP {
static ConnMap_t g_route_server_conn_map;
static serv_info_t* g_route_server_list;
static uint32_t g_route_server_count;
static CRouteServConn* g_master_rs_conn = NULL;
void route_server_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam)
{
ConnMap_t::iterator it_old;
CRouteServConn* pConn = NULL;
uint64_t cur_time = get_tick_count();
for (ConnMap_t::iterator it = g_route_server_conn_map.begin(); it != g_route_server_conn_map.end(); ) {
it_old = it;
it++;
pConn = (CRouteServConn*)it_old->second;
pConn->OnTimer(cur_time);
}
// reconnect RouteServer
serv_check_reconnect<CRouteServConn>(g_route_server_list, g_route_server_count);
}
void init_route_serv_conn(serv_info_t* server_list, uint32_t server_count)
{
g_route_server_list = server_list;
g_route_server_count = server_count;
serv_init<CRouteServConn>(g_route_server_list, g_route_server_count);
netlib_register_timer(route_server_conn_timer_callback, NULL, 1000);
}
bool is_route_server_available()
{
CRouteServConn* pConn = NULL;
for (uint32_t i = 0; i < g_route_server_count; i++) {
pConn = (CRouteServConn*)g_route_server_list[i].serv_conn;
if (pConn && pConn->IsOpen()) {
return true;
}
}
return false;
}
void send_to_all_route_server(CImPdu* pPdu)
{
CRouteServConn* pConn = NULL;
for (uint32_t i = 0; i < g_route_server_count; i++) {
pConn = (CRouteServConn*)g_route_server_list[i].serv_conn;
if (pConn && pConn->IsOpen()) {
pConn->SendPdu(pPdu);
}
}
}
// get the oldest route server connection
CRouteServConn* get_route_serv_conn()
{
return g_master_rs_conn;
}
void update_master_route_serv_conn()
{
uint64_t oldest_connect_time = (uint64_t)-1;
CRouteServConn* pOldestConn = NULL;
CRouteServConn* pConn = NULL;
for (uint32_t i = 0; i < g_route_server_count; i++) {
pConn = (CRouteServConn*)g_route_server_list[i].serv_conn;
if (pConn && pConn->IsOpen() && (pConn->GetConnectTime() < oldest_connect_time) ){
pOldestConn = pConn;
oldest_connect_time = pConn->GetConnectTime();
}
}
g_master_rs_conn = pOldestConn;
if (g_master_rs_conn) {
IM::Server::IMRoleSet msg;
msg.set_master(1);
CImPdu pdu;
pdu.SetPBMsg(&msg);
pdu.SetServiceId(IM::BaseDefine::SID_OTHER);
pdu.SetCommandId(IM::BaseDefine::CID_OTHER_ROLE_SET);
g_master_rs_conn->SendPdu(&pdu);
}
}
CRouteServConn::CRouteServConn()
{
m_bOpen = false;
m_serv_idx = 0;
}
CRouteServConn::~CRouteServConn()
{
}
void CRouteServConn::Connect(const char* server_ip, uint16_t server_port, uint32_t idx)
{
log("Connecting to RouteServer %s:%d ", server_ip, server_port);
m_serv_idx = idx;
m_handle = netlib_connect(server_ip, server_port, imconn_callback, (void*)&g_route_server_conn_map);
if (m_handle != NETLIB_INVALID_HANDLE) {
g_route_server_conn_map.insert(make_pair(m_handle, this));
}
}
void CRouteServConn::Close()
{
serv_reset<CRouteServConn>(g_route_server_list, g_route_server_count, m_serv_idx);
m_bOpen = false;
if (m_handle != NETLIB_INVALID_HANDLE) {
netlib_close(m_handle);
g_route_server_conn_map.erase(m_handle);
}
ReleaseRef();
if (g_master_rs_conn == this) {
update_master_route_serv_conn();
}
}
void CRouteServConn::OnConfirm()
{
log("connect to route server success ");
m_bOpen = true;
m_connect_time = get_tick_count();
g_route_server_list[m_serv_idx].reconnect_cnt = MIN_RECONNECT_CNT / 2;
if (g_master_rs_conn == NULL) {
update_master_route_serv_conn();
}
}
void CRouteServConn::OnClose()
{
log("onclose from route server handle=%d ", m_handle);
Close();
}
void CRouteServConn::OnTimer(uint64_t curr_tick)
{
if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) {
IM::Other::IMHeartBeat msg;
CImPdu pdu;
pdu.SetPBMsg(&msg);
pdu.SetServiceId(IM::BaseDefine::SID_OTHER);
pdu.SetCommandId(IM::BaseDefine::CID_OTHER_HEARTBEAT);
SendPdu(&pdu);
}
if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) {
log("conn to route server timeout ");
Close();
}
}
void CRouteServConn::HandlePdu(CImPdu* pPdu)
{
}
};
| apache-2.0 |
ColinHebert/docker | vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.c | 179 | 6198 | /* Obtained from: https://github.com/iSECPartners/ssl-conservatory */
/*
Copyright (C) 2012, iSEC Partners.
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.
*/
/*
* Helper functions to perform basic hostname validation using OpenSSL.
*
* Please read "everything-you-wanted-to-know-about-openssl.pdf" before
* attempting to use this code. This whitepaper describes how the code works,
* how it should be used, and what its limitations are.
*
* Author: Alban Diquet
* License: See LICENSE
*
*/
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#include "third_party/curl/hostcheck.h"
#include "third_party/isec_partners/openssl_hostname_validation.h"
#define HOSTNAME_MAX_SIZE 255
/**
* Tries to find a match for hostname in the certificate's Common Name field.
*
* Returns MatchFound if a match was found.
* Returns MatchNotFound if no matches were found.
* Returns MalformedCertificate if the Common Name had a NUL character embedded
* in it.
* Returns Error if the Common Name could not be extracted.
*/
static HostnameValidationResult matches_common_name(const char *hostname,
const X509 *server_cert) {
int common_name_loc = -1;
X509_NAME_ENTRY *common_name_entry = NULL;
ASN1_STRING *common_name_asn1 = NULL;
char *common_name_str = NULL;
// Find the position of the CN field in the Subject field of the certificate
common_name_loc =
X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *)server_cert),
NID_commonName, -1);
if (common_name_loc < 0) {
return Error;
}
// Extract the CN field
common_name_entry =
X509_NAME_get_entry(X509_get_subject_name((X509 *)server_cert),
common_name_loc);
if (common_name_entry == NULL) {
return Error;
}
// Convert the CN field to a C string
common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
if (common_name_asn1 == NULL) {
return Error;
}
common_name_str = (char *)ASN1_STRING_data(common_name_asn1);
// Make sure there isn't an embedded NUL character in the CN
if ((size_t)ASN1_STRING_length(common_name_asn1) !=
strlen(common_name_str)) {
return MalformedCertificate;
}
// Compare expected hostname with the CN
if (Curl_cert_hostcheck(common_name_str, hostname) == CURL_HOST_MATCH) {
return MatchFound;
} else {
return MatchNotFound;
}
}
/**
* Tries to find a match for hostname in the certificate's Subject Alternative
* Name extension.
*
* Returns MatchFound if a match was found.
* Returns MatchNotFound if no matches were found.
* Returns MalformedCertificate if any of the hostnames had a NUL character
* embedded in it.
* Returns NoSANPresent if the SAN extension was not present in the certificate.
*/
static HostnameValidationResult matches_subject_alternative_name(
const char *hostname, const X509 *server_cert) {
HostnameValidationResult result = MatchNotFound;
int i;
int san_names_nb = -1;
STACK_OF(GENERAL_NAME) *san_names = NULL;
// Try to extract the names within the SAN extension from the certificate
san_names =
X509_get_ext_d2i((X509 *)server_cert, NID_subject_alt_name, NULL, NULL);
if (san_names == NULL) {
return NoSANPresent;
}
san_names_nb = sk_GENERAL_NAME_num(san_names);
// Check each name within the extension
for (i = 0; i < san_names_nb; i++) {
const GENERAL_NAME *current_name = sk_GENERAL_NAME_value(san_names, i);
if (current_name->type == GEN_DNS) {
// Current name is a DNS name, let's check it
char *dns_name = (char *)ASN1_STRING_data(current_name->d.dNSName);
// Make sure there isn't an embedded NUL character in the DNS name
if ((size_t)ASN1_STRING_length(current_name->d.dNSName) !=
strlen(dns_name)) {
result = MalformedCertificate;
break;
} else { // Compare expected hostname with the DNS name
if (Curl_cert_hostcheck(dns_name, hostname) == CURL_HOST_MATCH) {
result = MatchFound;
break;
}
}
}
}
sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
return result;
}
/**
* Validates the server's identity by looking for the expected hostname in the
* server's certificate. As described in RFC 6125, it first tries to find a
* match
* in the Subject Alternative Name extension. If the extension is not present in
* the certificate, it checks the Common Name instead.
*
* Returns MatchFound if a match was found.
* Returns MatchNotFound if no matches were found.
* Returns MalformedCertificate if any of the hostnames had a NUL character
* embedded in it.
* Returns Error if there was an error.
*/
HostnameValidationResult validate_hostname(const char *hostname,
const X509 *server_cert) {
HostnameValidationResult result;
if ((hostname == NULL) || (server_cert == NULL))
return Error;
// First try the Subject Alternative Names extension
result = matches_subject_alternative_name(hostname, server_cert);
if (result == NoSANPresent) {
// Extension was not found: try the Common Name
result = matches_common_name(hostname, server_cert);
}
return result;
}
| apache-2.0 |
shwetasshinde24/Panoply | case-studies/h2o/topenssl/crypto/o_fips.c | 187 | 3484 | /*
* Written by Stephen henson (steve@openssl.org) for the OpenSSL project
* 2011.
*/
/* ====================================================================
* Copyright (c) 2011 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``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 THE OpenSSL PROJECT 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "cryptlib.h"
#ifdef OPENSSL_FIPS
# include <openssl/fips.h>
# include <openssl/fips_rand.h>
# include <openssl/rand.h>
#endif
int FIPS_mode(void)
{
OPENSSL_init();
#ifdef OPENSSL_FIPS
return FIPS_module_mode();
#else
return 0;
#endif
}
int FIPS_mode_set(int r)
{
OPENSSL_init();
#ifdef OPENSSL_FIPS
# ifndef FIPS_AUTH_USER_PASS
# define FIPS_AUTH_USER_PASS "Default FIPS Crypto User Password"
# endif
if (!FIPS_module_mode_set(r, FIPS_AUTH_USER_PASS))
return 0;
if (r)
RAND_set_rand_method(FIPS_rand_get_method());
else
RAND_set_rand_method(NULL);
return 1;
#else
if (r == 0)
return 1;
CRYPTOerr(CRYPTO_F_FIPS_MODE_SET, CRYPTO_R_FIPS_MODE_NOT_SUPPORTED);
return 0;
#endif
}
| apache-2.0 |
LTommy/tommyslab | core/misc/heartbleed/openssl-1.0.1f/crypto/asn1/a_verify.c | 205 | 6935 | /* crypto/asn1/a_verify.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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 cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <time.h>
#include "cryptlib.h"
#include "asn1_locl.h"
#ifndef NO_SYS_TYPES_H
# include <sys/types.h>
#endif
#include <openssl/bn.h>
#include <openssl/x509.h>
#include <openssl/objects.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#ifndef NO_ASN1_OLD
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,
char *data, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *p,*buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
inl=i2d(data,NULL);
buf_in=OPENSSL_malloc((unsigned int)inl);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
p=buf_in;
i2d(data,&p);
if (!EVP_VerifyInit_ex(&ctx,type, NULL)
|| !EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl))
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
#endif
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
if (mdnid == NID_undef)
{
if (!pkey->ameth || !pkey->ameth->item_verify)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(&ctx, it, asn, a,
signature, pkey);
/* Return value of 2 means carry on, anything else means we
* exit straight away: either a fatal error of the underlying
* verification routine handles all verification.
*/
if (ret != 2)
goto err;
ret = -1;
}
else
{
const EVP_MD *type;
type=EVP_get_digestbynid(mdnid);
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_DigestVerifyFinal(&ctx,signature->data,
(size_t)signature->length) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
| apache-2.0 |
letitvi/VideoGridPlayer | thirdparty/source/SDL2-2.0.4/src/libm/e_pow.c | 233 | 13440 | /* @(#)e_pow.c 5.1 93/09/24 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#if defined(LIBM_SCCS) && !defined(lint)
static char rcsid[] = "$NetBSD: e_pow.c,v 1.9 1995/05/12 04:57:32 jtc Exp $";
#endif
/* __ieee754_pow(x,y) return x**y
*
* n
* Method: Let x = 2 * (1+f)
* 1. Compute and return log2(x) in two pieces:
* log2(x) = w1 + w2,
* where w1 has 53-24 = 29 bit trailing zeros.
* 2. Perform y*log2(x) = n+y' by simulating muti-precision
* arithmetic, where |y'|<=0.5.
* 3. Return x**y = 2**n*exp(y'*log2)
*
* Special cases:
* 1. (anything) ** 0 is 1
* 2. (anything) ** 1 is itself
* 3. (anything) ** NAN is NAN
* 4. NAN ** (anything except 0) is NAN
* 5. +-(|x| > 1) ** +INF is +INF
* 6. +-(|x| > 1) ** -INF is +0
* 7. +-(|x| < 1) ** +INF is +0
* 8. +-(|x| < 1) ** -INF is +INF
* 9. +-1 ** +-INF is NAN
* 10. +0 ** (+anything except 0, NAN) is +0
* 11. -0 ** (+anything except 0, NAN, odd integer) is +0
* 12. +0 ** (-anything except 0, NAN) is +INF
* 13. -0 ** (-anything except 0, NAN, odd integer) is +INF
* 14. -0 ** (odd integer) = -( +0 ** (odd integer) )
* 15. +INF ** (+anything except 0,NAN) is +INF
* 16. +INF ** (-anything except 0,NAN) is +0
* 17. -INF ** (anything) = -0 ** (-anything)
* 18. (-anything) ** (integer) is (-1)**(integer)*(+anything**integer)
* 19. (-anything except 0 and inf) ** (non-integer) is NAN
*
* Accuracy:
* pow(x,y) returns x**y nearly rounded. In particular
* pow(integer,integer)
* always returns the correct integer provided it is
* representable.
*
* Constants :
* The hexadecimal values are the intended ones for the following
* constants. The decimal values may be used, provided that the
* compiler will convert from decimal to binary accurately enough
* to produce the hexadecimal values shown.
*/
#include "math_libm.h"
#include "math_private.h"
libm_hidden_proto(scalbn)
libm_hidden_proto(fabs)
#ifdef __STDC__
static const double
#else
static double
#endif
bp[] = { 1.0, 1.5, }, dp_h[] = {
0.0, 5.84962487220764160156e-01,}, /* 0x3FE2B803, 0x40000000 */
dp_l[] = {
0.0, 1.35003920212974897128e-08,}, /* 0x3E4CFDEB, 0x43CFD006 */
zero = 0.0, one = 1.0, two = 2.0, two53 = 9007199254740992.0, /* 0x43400000, 0x00000000 */
huge_val = 1.0e300, tiny = 1.0e-300,
/* poly coefs for (3/2)*(log(x)-2s-2/3*s**3 */
L1 = 5.99999999999994648725e-01, /* 0x3FE33333, 0x33333303 */
L2 = 4.28571428578550184252e-01, /* 0x3FDB6DB6, 0xDB6FABFF */
L3 = 3.33333329818377432918e-01, /* 0x3FD55555, 0x518F264D */
L4 = 2.72728123808534006489e-01, /* 0x3FD17460, 0xA91D4101 */
L5 = 2.30660745775561754067e-01, /* 0x3FCD864A, 0x93C9DB65 */
L6 = 2.06975017800338417784e-01, /* 0x3FCA7E28, 0x4A454EEF */
P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */
P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */
P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */
P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */
P5 = 4.13813679705723846039e-08, /* 0x3E663769, 0x72BEA4D0 */
lg2 = 6.93147180559945286227e-01, /* 0x3FE62E42, 0xFEFA39EF */
lg2_h = 6.93147182464599609375e-01, /* 0x3FE62E43, 0x00000000 */
lg2_l = -1.90465429995776804525e-09, /* 0xBE205C61, 0x0CA86C39 */
ovt = 8.0085662595372944372e-0017, /* -(1024-log2(ovfl+.5ulp)) */
cp = 9.61796693925975554329e-01, /* 0x3FEEC709, 0xDC3A03FD =2/(3ln2) */
cp_h = 9.61796700954437255859e-01, /* 0x3FEEC709, 0xE0000000 =(float)cp */
cp_l = -7.02846165095275826516e-09, /* 0xBE3E2FE0, 0x145B01F5 =tail of cp_h */
ivln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE =1/ln2 */
ivln2_h = 1.44269502162933349609e+00, /* 0x3FF71547, 0x60000000 =24b 1/ln2 */
ivln2_l = 1.92596299112661746887e-08; /* 0x3E54AE0B, 0xF85DDF44 =1/ln2 tail */
#ifdef __STDC__
double attribute_hidden __ieee754_pow(double x, double y)
#else
double attribute_hidden __ieee754_pow(x, y)
double x, y;
#endif
{
double z, ax, z_h, z_l, p_h, p_l;
double y1, t1, t2, r, s, t, u, v, w;
int32_t i, j, k, yisint, n;
int32_t hx, hy, ix, iy;
u_int32_t lx, ly;
EXTRACT_WORDS(hx, lx, x);
EXTRACT_WORDS(hy, ly, y);
ix = hx & 0x7fffffff;
iy = hy & 0x7fffffff;
/* y==zero: x**0 = 1 */
if ((iy | ly) == 0)
return one;
/* +-NaN return x+y */
if (ix > 0x7ff00000 || ((ix == 0x7ff00000) && (lx != 0)) ||
iy > 0x7ff00000 || ((iy == 0x7ff00000) && (ly != 0)))
return x + y;
/* determine if y is an odd int when x < 0
* yisint = 0 ... y is not an integer
* yisint = 1 ... y is an odd int
* yisint = 2 ... y is an even int
*/
yisint = 0;
if (hx < 0) {
if (iy >= 0x43400000)
yisint = 2; /* even integer y */
else if (iy >= 0x3ff00000) {
k = (iy >> 20) - 0x3ff; /* exponent */
if (k > 20) {
j = ly >> (52 - k);
if ((j << (52 - k)) == ly)
yisint = 2 - (j & 1);
} else if (ly == 0) {
j = iy >> (20 - k);
if ((j << (20 - k)) == iy)
yisint = 2 - (j & 1);
}
}
}
/* special value of y */
if (ly == 0) {
if (iy == 0x7ff00000) { /* y is +-inf */
if (((ix - 0x3ff00000) | lx) == 0)
return y - y; /* inf**+-1 is NaN */
else if (ix >= 0x3ff00000) /* (|x|>1)**+-inf = inf,0 */
return (hy >= 0) ? y : zero;
else /* (|x|<1)**-,+inf = inf,0 */
return (hy < 0) ? -y : zero;
}
if (iy == 0x3ff00000) { /* y is +-1 */
if (hy < 0)
return one / x;
else
return x;
}
if (hy == 0x40000000)
return x * x; /* y is 2 */
if (hy == 0x3fe00000) { /* y is 0.5 */
if (hx >= 0) /* x >= +0 */
return __ieee754_sqrt(x);
}
}
ax = fabs(x);
/* special value of x */
if (lx == 0) {
if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) {
z = ax; /* x is +-0,+-inf,+-1 */
if (hy < 0)
z = one / z; /* z = (1/|x|) */
if (hx < 0) {
if (((ix - 0x3ff00000) | yisint) == 0) {
z = (z - z) / (z - z); /* (-1)**non-int is NaN */
} else if (yisint == 1)
z = -z; /* (x<0)**odd = -(|x|**odd) */
}
return z;
}
}
/* (x<0)**(non-int) is NaN */
if (((((u_int32_t) hx >> 31) - 1) | yisint) == 0)
return (x - x) / (x - x);
/* |y| is huge */
if (iy > 0x41e00000) { /* if |y| > 2**31 */
if (iy > 0x43f00000) { /* if |y| > 2**64, must o/uflow */
if (ix <= 0x3fefffff)
return (hy < 0) ? huge_val * huge_val : tiny * tiny;
if (ix >= 0x3ff00000)
return (hy > 0) ? huge_val * huge_val : tiny * tiny;
}
/* over/underflow if x is not close to one */
if (ix < 0x3fefffff)
return (hy < 0) ? huge_val * huge_val : tiny * tiny;
if (ix > 0x3ff00000)
return (hy > 0) ? huge_val * huge_val : tiny * tiny;
/* now |1-x| is tiny <= 2**-20, suffice to compute
log(x) by x-x^2/2+x^3/3-x^4/4 */
t = x - 1; /* t has 20 trailing zeros */
w = (t * t) * (0.5 - t * (0.3333333333333333333333 - t * 0.25));
u = ivln2_h * t; /* ivln2_h has 21 sig. bits */
v = t * ivln2_l - w * ivln2;
t1 = u + v;
SET_LOW_WORD(t1, 0);
t2 = v - (t1 - u);
} else {
double s2, s_h, s_l, t_h, t_l;
n = 0;
/* take care subnormal number */
if (ix < 0x00100000) {
ax *= two53;
n -= 53;
GET_HIGH_WORD(ix, ax);
}
n += ((ix) >> 20) - 0x3ff;
j = ix & 0x000fffff;
/* determine interval */
ix = j | 0x3ff00000; /* normalize ix */
if (j <= 0x3988E)
k = 0; /* |x|<sqrt(3/2) */
else if (j < 0xBB67A)
k = 1; /* |x|<sqrt(3) */
else {
k = 0;
n += 1;
ix -= 0x00100000;
}
SET_HIGH_WORD(ax, ix);
/* compute s = s_h+s_l = (x-1)/(x+1) or (x-1.5)/(x+1.5) */
u = ax - bp[k]; /* bp[0]=1.0, bp[1]=1.5 */
v = one / (ax + bp[k]);
s = u * v;
s_h = s;
SET_LOW_WORD(s_h, 0);
/* t_h=ax+bp[k] High */
t_h = zero;
SET_HIGH_WORD(t_h,
((ix >> 1) | 0x20000000) + 0x00080000 + (k << 18));
t_l = ax - (t_h - bp[k]);
s_l = v * ((u - s_h * t_h) - s_h * t_l);
/* compute log(ax) */
s2 = s * s;
r = s2 * s2 * (L1 +
s2 * (L2 +
s2 * (L3 +
s2 * (L4 + s2 * (L5 + s2 * L6)))));
r += s_l * (s_h + s);
s2 = s_h * s_h;
t_h = 3.0 + s2 + r;
SET_LOW_WORD(t_h, 0);
t_l = r - ((t_h - 3.0) - s2);
/* u+v = s*(1+...) */
u = s_h * t_h;
v = s_l * t_h + t_l * s;
/* 2/(3log2)*(s+...) */
p_h = u + v;
SET_LOW_WORD(p_h, 0);
p_l = v - (p_h - u);
z_h = cp_h * p_h; /* cp_h+cp_l = 2/(3*log2) */
z_l = cp_l * p_h + p_l * cp + dp_l[k];
/* log2(ax) = (s+..)*2/(3*log2) = n + dp_h + z_h + z_l */
t = (double) n;
t1 = (((z_h + z_l) + dp_h[k]) + t);
SET_LOW_WORD(t1, 0);
t2 = z_l - (((t1 - t) - dp_h[k]) - z_h);
}
s = one; /* s (sign of result -ve**odd) = -1 else = 1 */
if (((((u_int32_t) hx >> 31) - 1) | (yisint - 1)) == 0)
s = -one; /* (-ve)**(odd int) */
/* split up y into y1+y2 and compute (y1+y2)*(t1+t2) */
y1 = y;
SET_LOW_WORD(y1, 0);
p_l = (y - y1) * t1 + y * t2;
p_h = y1 * t1;
z = p_l + p_h;
EXTRACT_WORDS(j, i, z);
if (j >= 0x40900000) { /* z >= 1024 */
if (((j - 0x40900000) | i) != 0) /* if z > 1024 */
return s * huge_val * huge_val; /* overflow */
else {
if (p_l + ovt > z - p_h)
return s * huge_val * huge_val; /* overflow */
}
} else if ((j & 0x7fffffff) >= 0x4090cc00) { /* z <= -1075 */
if (((j - 0xc090cc00) | i) != 0) /* z < -1075 */
return s * tiny * tiny; /* underflow */
else {
if (p_l <= z - p_h)
return s * tiny * tiny; /* underflow */
}
}
/*
* compute 2**(p_h+p_l)
*/
i = j & 0x7fffffff;
k = (i >> 20) - 0x3ff;
n = 0;
if (i > 0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */
n = j + (0x00100000 >> (k + 1));
k = ((n & 0x7fffffff) >> 20) - 0x3ff; /* new k for n */
t = zero;
SET_HIGH_WORD(t, n & ~(0x000fffff >> k));
n = ((n & 0x000fffff) | 0x00100000) >> (20 - k);
if (j < 0)
n = -n;
p_h -= t;
}
t = p_l + p_h;
SET_LOW_WORD(t, 0);
u = t * lg2_h;
v = (p_l - (t - p_h)) * lg2 + t * lg2_l;
z = u + v;
w = v - (z - u);
t = z * z;
t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5))));
r = (z * t1) / (t1 - two) - (w + z * w);
z = one - (r - z);
GET_HIGH_WORD(j, z);
j += (n << 20);
if ((j >> 20) <= 0)
z = scalbn(z, n); /* subnormal output */
else
SET_HIGH_WORD(z, j);
return s * z;
}
| apache-2.0 |
buribu/sources | sqlite3src/util.c | 17 | 36229 | /*
** 2001 September 15
**
** 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.
**
*************************************************************************
** Utility functions used throughout sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
*/
#include "sqliteInt.h"
#include <stdarg.h>
#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
# include <math.h>
#endif
/*
** Routine needed to support the testcase() macro.
*/
#ifdef SQLITE_COVERAGE_TEST
void sqlite3Coverage(int x){
static unsigned dummy = 0;
dummy += (unsigned)x;
}
#endif
/*
** Give a callback to the test harness that can be used to simulate faults
** in places where it is difficult or expensive to do so purely by means
** of inputs.
**
** The intent of the integer argument is to let the fault simulator know
** which of multiple sqlite3FaultSim() calls has been hit.
**
** Return whatever integer value the test callback returns, or return
** SQLITE_OK if no test callback is installed.
*/
#ifndef SQLITE_OMIT_BUILTIN_TEST
int sqlite3FaultSim(int iTest){
int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
return xCallback ? xCallback(iTest) : SQLITE_OK;
}
#endif
#ifndef SQLITE_OMIT_FLOATING_POINT
/*
** Return true if the floating point value is Not a Number (NaN).
**
** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
** Otherwise, we have our own implementation that works on most systems.
*/
int sqlite3IsNaN(double x){
int rc; /* The value return */
#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
/*
** Systems that support the isnan() library function should probably
** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
** found that many systems do not have a working isnan() function so
** this implementation is provided as an alternative.
**
** This NaN test sometimes fails if compiled on GCC with -ffast-math.
** On the other hand, the use of -ffast-math comes with the following
** warning:
**
** This option [-ffast-math] should never be turned on by any
** -O option since it can result in incorrect output for programs
** which depend on an exact implementation of IEEE or ISO
** rules/specifications for math functions.
**
** Under MSVC, this NaN test may fail if compiled with a floating-
** point precision mode other than /fp:precise. From the MSDN
** documentation:
**
** The compiler [with /fp:precise] will properly handle comparisons
** involving NaN. For example, x != x evaluates to true if x is NaN
** ...
*/
#ifdef __FAST_MATH__
# error SQLite will not work correctly with the -ffast-math option of GCC.
#endif
volatile double y = x;
volatile double z = y;
rc = (y!=z);
#else /* if HAVE_ISNAN */
rc = isnan(x);
#endif /* HAVE_ISNAN */
testcase( rc );
return rc;
}
#endif /* SQLITE_OMIT_FLOATING_POINT */
/*
** Compute a string length that is limited to what can be stored in
** lower 30 bits of a 32-bit signed integer.
**
** The value returned will never be negative. Nor will it ever be greater
** than the actual length of the string. For very long strings (greater
** than 1GiB) the value returned might be less than the true string length.
*/
int sqlite3Strlen30(const char *z){
const char *z2 = z;
if( z==0 ) return 0;
while( *z2 ){ z2++; }
return 0x3fffffff & (int)(z2 - z);
}
/*
** Set the current error code to err_code and clear any prior error message.
*/
void sqlite3Error(sqlite3 *db, int err_code){
assert( db!=0 );
db->errCode = err_code;
if( db->pErr ) sqlite3ValueSetNull(db->pErr);
}
/*
** Set the most recent error code and error string for the sqlite
** handle "db". The error code is set to "err_code".
**
** If it is not NULL, string zFormat specifies the format of the
** error string in the style of the printf functions: The following
** format characters are allowed:
**
** %s Insert a string
** %z A string that should be freed after use
** %d Insert an integer
** %T Insert a token
** %S Insert the first element of a SrcList
**
** zFormat and any string tokens that follow it are assumed to be
** encoded in UTF-8.
**
** To clear the most recent error for sqlite handle "db", sqlite3Error
** should be called with err_code set to SQLITE_OK and zFormat set
** to NULL.
*/
void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
assert( db!=0 );
db->errCode = err_code;
if( zFormat==0 ){
sqlite3Error(db, err_code);
}else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
char *z;
va_list ap;
va_start(ap, zFormat);
z = sqlite3VMPrintf(db, zFormat, ap);
va_end(ap);
sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
}
}
/*
** Add an error message to pParse->zErrMsg and increment pParse->nErr.
** The following formatting characters are allowed:
**
** %s Insert a string
** %z A string that should be freed after use
** %d Insert an integer
** %T Insert a token
** %S Insert the first element of a SrcList
**
** This function should be used to report any error that occurs while
** compiling an SQL statement (i.e. within sqlite3_prepare()). The
** last thing the sqlite3_prepare() function does is copy the error
** stored by this function into the database handle using sqlite3Error().
** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
** during statement execution (sqlite3_step() etc.).
*/
void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
char *zMsg;
va_list ap;
sqlite3 *db = pParse->db;
va_start(ap, zFormat);
zMsg = sqlite3VMPrintf(db, zFormat, ap);
va_end(ap);
if( db->suppressErr ){
sqlite3DbFree(db, zMsg);
}else{
pParse->nErr++;
sqlite3DbFree(db, pParse->zErrMsg);
pParse->zErrMsg = zMsg;
pParse->rc = SQLITE_ERROR;
}
}
/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters. The conversion is done in-place. If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** The input string must be zero-terminated. A new zero-terminator
** is added to the dequoted string.
**
** The return value is -1 if no dequoting occurs or the length of the
** dequoted string, exclusive of the zero terminator, if dequoting does
** occur.
**
** 2002-Feb-14: This routine is extended to remove MS-Access style
** brackets from around identifiers. For example: "[a-b-c]" becomes
** "a-b-c".
*/
int sqlite3Dequote(char *z){
char quote;
int i, j;
if( z==0 ) return -1;
quote = z[0];
switch( quote ){
case '\'': break;
case '"': break;
case '`': break; /* For MySQL compatibility */
case '[': quote = ']'; break; /* For MS SqlServer compatibility */
default: return -1;
}
for(i=1, j=0;; i++){
assert( z[i] );
if( z[i]==quote ){
if( z[i+1]==quote ){
z[j++] = quote;
i++;
}else{
break;
}
}else{
z[j++] = z[i];
}
}
z[j] = 0;
return j;
}
/* Convenient short-hand */
#define UpperToLower sqlite3UpperToLower
/*
** Some systems have stricmp(). Others have strcasecmp(). Because
** there is no consistency, we will define our own.
**
** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
** sqlite3_strnicmp() APIs allow applications and extensions to compare
** the contents of two buffers containing UTF-8 strings in a
** case-independent fashion, using the same definition of "case
** independence" that SQLite uses internally when comparing identifiers.
*/
int sqlite3_stricmp(const char *zLeft, const char *zRight){
register unsigned char *a, *b;
if( zLeft==0 ){
return zRight ? -1 : 0;
}else if( zRight==0 ){
return 1;
}
a = (unsigned char *)zLeft;
b = (unsigned char *)zRight;
while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
return UpperToLower[*a] - UpperToLower[*b];
}
int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
register unsigned char *a, *b;
if( zLeft==0 ){
return zRight ? -1 : 0;
}else if( zRight==0 ){
return 1;
}
a = (unsigned char *)zLeft;
b = (unsigned char *)zRight;
while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
}
/*
** The string z[] is an text representation of a real number.
** Convert this string to a double and write it into *pResult.
**
** The string z[] is length bytes in length (bytes, not characters) and
** uses the encoding enc. The string is not necessarily zero-terminated.
**
** Return TRUE if the result is a valid real number (or integer) and FALSE
** if the string is empty or contains extraneous text. Valid numbers
** are in one of these formats:
**
** [+-]digits[E[+-]digits]
** [+-]digits.[digits][E[+-]digits]
** [+-].digits[E[+-]digits]
**
** Leading and trailing whitespace is ignored for the purpose of determining
** validity.
**
** If some prefix of the input string is a valid number, this routine
** returns FALSE but it still converts the prefix and writes the result
** into *pResult.
*/
int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
#ifndef SQLITE_OMIT_FLOATING_POINT
int incr;
const char *zEnd = z + length;
/* sign * significand * (10 ^ (esign * exponent)) */
int sign = 1; /* sign of significand */
i64 s = 0; /* significand */
int d = 0; /* adjust exponent for shifting decimal point */
int esign = 1; /* sign of exponent */
int e = 0; /* exponent */
int eValid = 1; /* True exponent is either not used or is well-formed */
double result;
int nDigits = 0;
int nonNum = 0;
assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
*pResult = 0.0; /* Default return value, in case of an error */
if( enc==SQLITE_UTF8 ){
incr = 1;
}else{
int i;
incr = 2;
assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
for(i=3-enc; i<length && z[i]==0; i+=2){}
nonNum = i<length;
zEnd = z+i+enc-3;
z += (enc&1);
}
/* skip leading spaces */
while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
if( z>=zEnd ) return 0;
/* get sign of significand */
if( *z=='-' ){
sign = -1;
z+=incr;
}else if( *z=='+' ){
z+=incr;
}
/* skip leading zeroes */
while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
/* copy max significant digits to significand */
while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
s = s*10 + (*z - '0');
z+=incr, nDigits++;
}
/* skip non-significant significand digits
** (increase exponent by d to shift decimal left) */
while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
if( z>=zEnd ) goto do_atof_calc;
/* if decimal point is present */
if( *z=='.' ){
z+=incr;
/* copy digits from after decimal to significand
** (decrease exponent by d to shift decimal right) */
while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
s = s*10 + (*z - '0');
z+=incr, nDigits++, d--;
}
/* skip non-significant digits */
while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
}
if( z>=zEnd ) goto do_atof_calc;
/* if exponent is present */
if( *z=='e' || *z=='E' ){
z+=incr;
eValid = 0;
if( z>=zEnd ) goto do_atof_calc;
/* get sign of exponent */
if( *z=='-' ){
esign = -1;
z+=incr;
}else if( *z=='+' ){
z+=incr;
}
/* copy digits to exponent */
while( z<zEnd && sqlite3Isdigit(*z) ){
e = e<10000 ? (e*10 + (*z - '0')) : 10000;
z+=incr;
eValid = 1;
}
}
/* skip trailing spaces */
if( nDigits && eValid ){
while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
}
do_atof_calc:
/* adjust exponent by d, and update sign */
e = (e*esign) + d;
if( e<0 ) {
esign = -1;
e *= -1;
} else {
esign = 1;
}
/* if 0 significand */
if( !s ) {
/* In the IEEE 754 standard, zero is signed.
** Add the sign if we've seen at least one digit */
result = (sign<0 && nDigits) ? -(double)0 : (double)0;
} else {
/* attempt to reduce exponent */
if( esign>0 ){
while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
}else{
while( !(s%10) && e>0 ) e--,s/=10;
}
/* adjust the sign of significand */
s = sign<0 ? -s : s;
/* if exponent, scale significand as appropriate
** and store in result. */
if( e ){
LONGDOUBLE_TYPE scale = 1.0;
/* attempt to handle extremely small/large numbers better */
if( e>307 && e<342 ){
while( e%308 ) { scale *= 1.0e+1; e -= 1; }
if( esign<0 ){
result = s / scale;
result /= 1.0e+308;
}else{
result = s * scale;
result *= 1.0e+308;
}
}else if( e>=342 ){
if( esign<0 ){
result = 0.0*s;
}else{
result = 1e308*1e308*s; /* Infinity */
}
}else{
/* 1.0e+22 is the largest power of 10 than can be
** represented exactly. */
while( e%22 ) { scale *= 1.0e+1; e -= 1; }
while( e>0 ) { scale *= 1.0e+22; e -= 22; }
if( esign<0 ){
result = s / scale;
}else{
result = s * scale;
}
}
} else {
result = (double)s;
}
}
/* store the result */
*pResult = result;
/* return true if number and no extra non-whitespace chracters after */
return z>=zEnd && nDigits>0 && eValid && nonNum==0;
#else
return !sqlite3Atoi64(z, pResult, length, enc);
#endif /* SQLITE_OMIT_FLOATING_POINT */
}
/*
** Compare the 19-character string zNum against the text representation
** value 2^63: 9223372036854775808. Return negative, zero, or positive
** if zNum is less than, equal to, or greater than the string.
** Note that zNum must contain exactly 19 characters.
**
** Unlike memcmp() this routine is guaranteed to return the difference
** in the values of the last digit if the only difference is in the
** last digit. So, for example,
**
** compare2pow63("9223372036854775800", 1)
**
** will return -8.
*/
static int compare2pow63(const char *zNum, int incr){
int c = 0;
int i;
/* 012345678901234567 */
const char *pow63 = "922337203685477580";
for(i=0; c==0 && i<18; i++){
c = (zNum[i*incr]-pow63[i])*10;
}
if( c==0 ){
c = zNum[18*incr] - '8';
testcase( c==(-1) );
testcase( c==0 );
testcase( c==(+1) );
}
return c;
}
/*
** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
** routine does *not* accept hexadecimal notation.
**
** If the zNum value is representable as a 64-bit twos-complement
** integer, then write that value into *pNum and return 0.
**
** If zNum is exactly 9223372036854775808, return 2. This special
** case is broken out because while 9223372036854775808 cannot be a
** signed 64-bit integer, its negative -9223372036854775808 can be.
**
** If zNum is too big for a 64-bit integer and is not
** 9223372036854775808 or if zNum contains any non-numeric text,
** then return 1.
**
** length is the number of bytes in the string (bytes, not characters).
** The string is not necessarily zero-terminated. The encoding is
** given by enc.
*/
int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
int incr;
u64 u = 0;
int neg = 0; /* assume positive */
int i;
int c = 0;
int nonNum = 0;
const char *zStart;
const char *zEnd = zNum + length;
assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
if( enc==SQLITE_UTF8 ){
incr = 1;
}else{
incr = 2;
assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
for(i=3-enc; i<length && zNum[i]==0; i+=2){}
nonNum = i<length;
zEnd = zNum+i+enc-3;
zNum += (enc&1);
}
while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
if( zNum<zEnd ){
if( *zNum=='-' ){
neg = 1;
zNum+=incr;
}else if( *zNum=='+' ){
zNum+=incr;
}
}
zStart = zNum;
while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
u = u*10 + c - '0';
}
if( u>LARGEST_INT64 ){
*pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
}else if( neg ){
*pNum = -(i64)u;
}else{
*pNum = (i64)u;
}
testcase( i==18 );
testcase( i==19 );
testcase( i==20 );
if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
/* zNum is empty or contains non-numeric text or is longer
** than 19 digits (thus guaranteeing that it is too large) */
return 1;
}else if( i<19*incr ){
/* Less than 19 digits, so we know that it fits in 64 bits */
assert( u<=LARGEST_INT64 );
return 0;
}else{
/* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
c = compare2pow63(zNum, incr);
if( c<0 ){
/* zNum is less than 9223372036854775808 so it fits */
assert( u<=LARGEST_INT64 );
return 0;
}else if( c>0 ){
/* zNum is greater than 9223372036854775808 so it overflows */
return 1;
}else{
/* zNum is exactly 9223372036854775808. Fits if negative. The
** special case 2 overflow if positive */
assert( u-1==LARGEST_INT64 );
return neg ? 0 : 2;
}
}
}
/*
** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
** into a 64-bit signed integer. This routine accepts hexadecimal literals,
** whereas sqlite3Atoi64() does not.
**
** Returns:
**
** 0 Successful transformation. Fits in a 64-bit signed integer.
** 1 Integer too large for a 64-bit signed integer or is malformed
** 2 Special case of 9223372036854775808
*/
int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
#ifndef SQLITE_OMIT_HEX_INTEGER
if( z[0]=='0'
&& (z[1]=='x' || z[1]=='X')
&& sqlite3Isxdigit(z[2])
){
u64 u = 0;
int i, k;
for(i=2; z[i]=='0'; i++){}
for(k=i; sqlite3Isxdigit(z[k]); k++){
u = u*16 + sqlite3HexToInt(z[k]);
}
memcpy(pOut, &u, 8);
return (z[k]==0 && k-i<=16) ? 0 : 1;
}else
#endif /* SQLITE_OMIT_HEX_INTEGER */
{
return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
}
}
/*
** If zNum represents an integer that will fit in 32-bits, then set
** *pValue to that integer and return true. Otherwise return false.
**
** This routine accepts both decimal and hexadecimal notation for integers.
**
** Any non-numeric characters that following zNum are ignored.
** This is different from sqlite3Atoi64() which requires the
** input number to be zero-terminated.
*/
int sqlite3GetInt32(const char *zNum, int *pValue){
sqlite_int64 v = 0;
int i, c;
int neg = 0;
if( zNum[0]=='-' ){
neg = 1;
zNum++;
}else if( zNum[0]=='+' ){
zNum++;
}
#ifndef SQLITE_OMIT_HEX_INTEGER
else if( zNum[0]=='0'
&& (zNum[1]=='x' || zNum[1]=='X')
&& sqlite3Isxdigit(zNum[2])
){
u32 u = 0;
zNum += 2;
while( zNum[0]=='0' ) zNum++;
for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
u = u*16 + sqlite3HexToInt(zNum[i]);
}
if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
memcpy(pValue, &u, 4);
return 1;
}else{
return 0;
}
}
#endif
while( zNum[0]=='0' ) zNum++;
for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
v = v*10 + c;
}
/* The longest decimal representation of a 32 bit integer is 10 digits:
**
** 1234567890
** 2^31 -> 2147483648
*/
testcase( i==10 );
if( i>10 ){
return 0;
}
testcase( v-neg==2147483647 );
if( v-neg>2147483647 ){
return 0;
}
if( neg ){
v = -v;
}
*pValue = (int)v;
return 1;
}
/*
** Return a 32-bit integer value extracted from a string. If the
** string is not an integer, just return 0.
*/
int sqlite3Atoi(const char *z){
int x = 0;
if( z ) sqlite3GetInt32(z, &x);
return x;
}
/*
** The variable-length integer encoding is as follows:
**
** KEY:
** A = 0xxxxxxx 7 bits of data and one flag bit
** B = 1xxxxxxx 7 bits of data and one flag bit
** C = xxxxxxxx 8 bits of data
**
** 7 bits - A
** 14 bits - BA
** 21 bits - BBA
** 28 bits - BBBA
** 35 bits - BBBBA
** 42 bits - BBBBBA
** 49 bits - BBBBBBA
** 56 bits - BBBBBBBA
** 64 bits - BBBBBBBBC
*/
/*
** Write a 64-bit variable-length integer to memory starting at p[0].
** The length of data write will be between 1 and 9 bytes. The number
** of bytes written is returned.
**
** A variable-length integer consists of the lower 7 bits of each byte
** for all bytes that have the 8th bit set and one byte with the 8th
** bit clear. Except, if we get to the 9th byte, it stores the full
** 8 bits and is the last byte.
*/
static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
int i, j, n;
u8 buf[10];
if( v & (((u64)0xff000000)<<32) ){
p[8] = (u8)v;
v >>= 8;
for(i=7; i>=0; i--){
p[i] = (u8)((v & 0x7f) | 0x80);
v >>= 7;
}
return 9;
}
n = 0;
do{
buf[n++] = (u8)((v & 0x7f) | 0x80);
v >>= 7;
}while( v!=0 );
buf[0] &= 0x7f;
assert( n<=9 );
for(i=0, j=n-1; j>=0; j--, i++){
p[i] = buf[j];
}
return n;
}
int sqlite3PutVarint(unsigned char *p, u64 v){
if( v<=0x7f ){
p[0] = v&0x7f;
return 1;
}
if( v<=0x3fff ){
p[0] = ((v>>7)&0x7f)|0x80;
p[1] = v&0x7f;
return 2;
}
return putVarint64(p,v);
}
/*
** Bitmasks used by sqlite3GetVarint(). These precomputed constants
** are defined here rather than simply putting the constant expressions
** inline in order to work around bugs in the RVT compiler.
**
** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
**
** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
*/
#define SLOT_2_0 0x001fc07f
#define SLOT_4_2_0 0xf01fc07f
/*
** Read a 64-bit variable-length integer from memory starting at p[0].
** Return the number of bytes read. The value is stored in *v.
*/
u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
u32 a,b,s;
a = *p;
/* a: p0 (unmasked) */
if (!(a&0x80))
{
*v = a;
return 1;
}
p++;
b = *p;
/* b: p1 (unmasked) */
if (!(b&0x80))
{
a &= 0x7f;
a = a<<7;
a |= b;
*v = a;
return 2;
}
/* Verify that constants are precomputed correctly */
assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
p++;
a = a<<14;
a |= *p;
/* a: p0<<14 | p2 (unmasked) */
if (!(a&0x80))
{
a &= SLOT_2_0;
b &= 0x7f;
b = b<<7;
a |= b;
*v = a;
return 3;
}
/* CSE1 from below */
a &= SLOT_2_0;
p++;
b = b<<14;
b |= *p;
/* b: p1<<14 | p3 (unmasked) */
if (!(b&0x80))
{
b &= SLOT_2_0;
/* moved CSE1 up */
/* a &= (0x7f<<14)|(0x7f); */
a = a<<7;
a |= b;
*v = a;
return 4;
}
/* a: p0<<14 | p2 (masked) */
/* b: p1<<14 | p3 (unmasked) */
/* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
/* moved CSE1 up */
/* a &= (0x7f<<14)|(0x7f); */
b &= SLOT_2_0;
s = a;
/* s: p0<<14 | p2 (masked) */
p++;
a = a<<14;
a |= *p;
/* a: p0<<28 | p2<<14 | p4 (unmasked) */
if (!(a&0x80))
{
/* we can skip these cause they were (effectively) done above in calc'ing s */
/* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
/* b &= (0x7f<<14)|(0x7f); */
b = b<<7;
a |= b;
s = s>>18;
*v = ((u64)s)<<32 | a;
return 5;
}
/* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
s = s<<7;
s |= b;
/* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
p++;
b = b<<14;
b |= *p;
/* b: p1<<28 | p3<<14 | p5 (unmasked) */
if (!(b&0x80))
{
/* we can skip this cause it was (effectively) done above in calc'ing s */
/* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
a &= SLOT_2_0;
a = a<<7;
a |= b;
s = s>>18;
*v = ((u64)s)<<32 | a;
return 6;
}
p++;
a = a<<14;
a |= *p;
/* a: p2<<28 | p4<<14 | p6 (unmasked) */
if (!(a&0x80))
{
a &= SLOT_4_2_0;
b &= SLOT_2_0;
b = b<<7;
a |= b;
s = s>>11;
*v = ((u64)s)<<32 | a;
return 7;
}
/* CSE2 from below */
a &= SLOT_2_0;
p++;
b = b<<14;
b |= *p;
/* b: p3<<28 | p5<<14 | p7 (unmasked) */
if (!(b&0x80))
{
b &= SLOT_4_2_0;
/* moved CSE2 up */
/* a &= (0x7f<<14)|(0x7f); */
a = a<<7;
a |= b;
s = s>>4;
*v = ((u64)s)<<32 | a;
return 8;
}
p++;
a = a<<15;
a |= *p;
/* a: p4<<29 | p6<<15 | p8 (unmasked) */
/* moved CSE2 up */
/* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
b &= SLOT_2_0;
b = b<<8;
a |= b;
s = s<<4;
b = p[-4];
b &= 0x7f;
b = b>>3;
s |= b;
*v = ((u64)s)<<32 | a;
return 9;
}
/*
** Read a 32-bit variable-length integer from memory starting at p[0].
** Return the number of bytes read. The value is stored in *v.
**
** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
** integer, then set *v to 0xffffffff.
**
** A MACRO version, getVarint32, is provided which inlines the
** single-byte case. All code should use the MACRO version as
** this function assumes the single-byte case has already been handled.
*/
u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
u32 a,b;
/* The 1-byte case. Overwhelmingly the most common. Handled inline
** by the getVarin32() macro */
a = *p;
/* a: p0 (unmasked) */
#ifndef getVarint32
if (!(a&0x80))
{
/* Values between 0 and 127 */
*v = a;
return 1;
}
#endif
/* The 2-byte case */
p++;
b = *p;
/* b: p1 (unmasked) */
if (!(b&0x80))
{
/* Values between 128 and 16383 */
a &= 0x7f;
a = a<<7;
*v = a | b;
return 2;
}
/* The 3-byte case */
p++;
a = a<<14;
a |= *p;
/* a: p0<<14 | p2 (unmasked) */
if (!(a&0x80))
{
/* Values between 16384 and 2097151 */
a &= (0x7f<<14)|(0x7f);
b &= 0x7f;
b = b<<7;
*v = a | b;
return 3;
}
/* A 32-bit varint is used to store size information in btrees.
** Objects are rarely larger than 2MiB limit of a 3-byte varint.
** A 3-byte varint is sufficient, for example, to record the size
** of a 1048569-byte BLOB or string.
**
** We only unroll the first 1-, 2-, and 3- byte cases. The very
** rare larger cases can be handled by the slower 64-bit varint
** routine.
*/
#if 1
{
u64 v64;
u8 n;
p -= 2;
n = sqlite3GetVarint(p, &v64);
assert( n>3 && n<=9 );
if( (v64 & SQLITE_MAX_U32)!=v64 ){
*v = 0xffffffff;
}else{
*v = (u32)v64;
}
return n;
}
#else
/* For following code (kept for historical record only) shows an
** unrolling for the 3- and 4-byte varint cases. This code is
** slightly faster, but it is also larger and much harder to test.
*/
p++;
b = b<<14;
b |= *p;
/* b: p1<<14 | p3 (unmasked) */
if (!(b&0x80))
{
/* Values between 2097152 and 268435455 */
b &= (0x7f<<14)|(0x7f);
a &= (0x7f<<14)|(0x7f);
a = a<<7;
*v = a | b;
return 4;
}
p++;
a = a<<14;
a |= *p;
/* a: p0<<28 | p2<<14 | p4 (unmasked) */
if (!(a&0x80))
{
/* Values between 268435456 and 34359738367 */
a &= SLOT_4_2_0;
b &= SLOT_4_2_0;
b = b<<7;
*v = a | b;
return 5;
}
/* We can only reach this point when reading a corrupt database
** file. In that case we are not in any hurry. Use the (relatively
** slow) general-purpose sqlite3GetVarint() routine to extract the
** value. */
{
u64 v64;
u8 n;
p -= 4;
n = sqlite3GetVarint(p, &v64);
assert( n>5 && n<=9 );
*v = (u32)v64;
return n;
}
#endif
}
/*
** Return the number of bytes that will be needed to store the given
** 64-bit integer.
*/
int sqlite3VarintLen(u64 v){
int i = 0;
do{
i++;
v >>= 7;
}while( v!=0 && ALWAYS(i<9) );
return i;
}
/*
** Read or write a four-byte big-endian integer value.
*/
u32 sqlite3Get4byte(const u8 *p){
testcase( p[0]&0x80 );
return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
}
void sqlite3Put4byte(unsigned char *p, u32 v){
p[0] = (u8)(v>>24);
p[1] = (u8)(v>>16);
p[2] = (u8)(v>>8);
p[3] = (u8)v;
}
/*
** Translate a single byte of Hex into an integer.
** This routine only works if h really is a valid hexadecimal
** character: 0..9a..fA..F
*/
u8 sqlite3HexToInt(int h){
assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
#ifdef SQLITE_ASCII
h += 9*(1&(h>>6));
#endif
#ifdef SQLITE_EBCDIC
h += 9*(1&~(h>>4));
#endif
return (u8)(h & 0xf);
}
#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
/*
** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
** value. Return a pointer to its binary value. Space to hold the
** binary value has been obtained from malloc and must be freed by
** the calling routine.
*/
void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
char *zBlob;
int i;
zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
n--;
if( zBlob ){
for(i=0; i<n; i+=2){
zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
}
zBlob[i/2] = 0;
}
return zBlob;
}
#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
/*
** Log an error that is an API call on a connection pointer that should
** not have been used. The "type" of connection pointer is given as the
** argument. The zType is a word like "NULL" or "closed" or "invalid".
*/
static void logBadConnection(const char *zType){
sqlite3_log(SQLITE_MISUSE,
"API call with %s database connection pointer",
zType
);
}
/*
** Check to make sure we have a valid db pointer. This test is not
** foolproof but it does provide some measure of protection against
** misuse of the interface such as passing in db pointers that are
** NULL or which have been previously closed. If this routine returns
** 1 it means that the db pointer is valid and 0 if it should not be
** dereferenced for any reason. The calling function should invoke
** SQLITE_MISUSE immediately.
**
** sqlite3SafetyCheckOk() requires that the db pointer be valid for
** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
** open properly and is not fit for general use but which can be
** used as an argument to sqlite3_errmsg() or sqlite3_close().
*/
int sqlite3SafetyCheckOk(sqlite3 *db){
u32 magic;
if( db==0 ){
logBadConnection("NULL");
return 0;
}
magic = db->magic;
if( magic!=SQLITE_MAGIC_OPEN ){
if( sqlite3SafetyCheckSickOrOk(db) ){
testcase( sqlite3GlobalConfig.xLog!=0 );
logBadConnection("unopened");
}
return 0;
}else{
return 1;
}
}
int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
u32 magic;
magic = db->magic;
if( magic!=SQLITE_MAGIC_SICK &&
magic!=SQLITE_MAGIC_OPEN &&
magic!=SQLITE_MAGIC_BUSY ){
testcase( sqlite3GlobalConfig.xLog!=0 );
logBadConnection("invalid");
return 0;
}else{
return 1;
}
}
/*
** Attempt to add, substract, or multiply the 64-bit signed value iB against
** the other 64-bit signed integer at *pA and store the result in *pA.
** Return 0 on success. Or if the operation would have resulted in an
** overflow, leave *pA unchanged and return 1.
*/
int sqlite3AddInt64(i64 *pA, i64 iB){
i64 iA = *pA;
testcase( iA==0 ); testcase( iA==1 );
testcase( iB==-1 ); testcase( iB==0 );
if( iB>=0 ){
testcase( iA>0 && LARGEST_INT64 - iA == iB );
testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
}else{
testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
}
*pA += iB;
return 0;
}
int sqlite3SubInt64(i64 *pA, i64 iB){
testcase( iB==SMALLEST_INT64+1 );
if( iB==SMALLEST_INT64 ){
testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
if( (*pA)>=0 ) return 1;
*pA -= iB;
return 0;
}else{
return sqlite3AddInt64(pA, -iB);
}
}
#define TWOPOWER32 (((i64)1)<<32)
#define TWOPOWER31 (((i64)1)<<31)
int sqlite3MulInt64(i64 *pA, i64 iB){
i64 iA = *pA;
i64 iA1, iA0, iB1, iB0, r;
iA1 = iA/TWOPOWER32;
iA0 = iA % TWOPOWER32;
iB1 = iB/TWOPOWER32;
iB0 = iB % TWOPOWER32;
if( iA1==0 ){
if( iB1==0 ){
*pA *= iB;
return 0;
}
r = iA0*iB1;
}else if( iB1==0 ){
r = iA1*iB0;
}else{
/* If both iA1 and iB1 are non-zero, overflow will result */
return 1;
}
testcase( r==(-TWOPOWER31)-1 );
testcase( r==(-TWOPOWER31) );
testcase( r==TWOPOWER31 );
testcase( r==TWOPOWER31-1 );
if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
r *= TWOPOWER32;
if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
*pA = r;
return 0;
}
/*
** Compute the absolute value of a 32-bit signed integer, of possible. Or
** if the integer has a value of -2147483648, return +2147483647
*/
int sqlite3AbsInt32(int x){
if( x>=0 ) return x;
if( x==(int)0x80000000 ) return 0x7fffffff;
return -x;
}
#ifdef SQLITE_ENABLE_8_3_NAMES
/*
** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
** three characters, then shorten the suffix on z[] to be the last three
** characters of the original suffix.
**
** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
** do the suffix shortening regardless of URI parameter.
**
** Examples:
**
** test.db-journal => test.nal
** test.db-wal => test.wal
** test.db-shm => test.shm
** test.db-mj7f3319fa => test.9fa
*/
void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
#if SQLITE_ENABLE_8_3_NAMES<2
if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
#endif
{
int i, sz;
sz = sqlite3Strlen30(z);
for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
}
}
#endif
/*
** Find (an approximate) sum of two LogEst values. This computation is
** not a simple "+" operator because LogEst is stored as a logarithmic
** value.
**
*/
LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
static const unsigned char x[] = {
10, 10, /* 0,1 */
9, 9, /* 2,3 */
8, 8, /* 4,5 */
7, 7, 7, /* 6,7,8 */
6, 6, 6, /* 9,10,11 */
5, 5, 5, /* 12-14 */
4, 4, 4, 4, /* 15-18 */
3, 3, 3, 3, 3, 3, /* 19-24 */
2, 2, 2, 2, 2, 2, 2, /* 25-31 */
};
if( a>=b ){
if( a>b+49 ) return a;
if( a>b+31 ) return a+1;
return a+x[a-b];
}else{
if( b>a+49 ) return b;
if( b>a+31 ) return b+1;
return b+x[b-a];
}
}
/*
** Convert an integer into a LogEst. In other words, compute an
** approximation for 10*log2(x).
*/
LogEst sqlite3LogEst(u64 x){
static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
LogEst y = 40;
if( x<8 ){
if( x<2 ) return 0;
while( x<8 ){ y -= 10; x <<= 1; }
}else{
while( x>255 ){ y += 40; x >>= 4; }
while( x>15 ){ y += 10; x >>= 1; }
}
return a[x&7] + y - 10;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Convert a double into a LogEst
** In other words, compute an approximation for 10*log2(x).
*/
LogEst sqlite3LogEstFromDouble(double x){
u64 a;
LogEst e;
assert( sizeof(x)==8 && sizeof(a)==8 );
if( x<=1 ) return 0;
if( x<=2000000000 ) return sqlite3LogEst((u64)x);
memcpy(&a, &x, 8);
e = (a>>52) - 1022;
return e*10;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */
/*
** Convert a LogEst into an integer.
*/
u64 sqlite3LogEstToInt(LogEst x){
u64 n;
if( x<10 ) return 1;
n = x%10;
x /= 10;
if( n>=5 ) n -= 2;
else if( n>=1 ) n -= 1;
if( x>=3 ){
return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
}
return (n+8)>>(3-x);
}
| artistic-2.0 |
blakemcbride/Dynace | WinExam/exam24/main.c | 1 | 1875 |
#include "generics.h"
#include "resource.h"
static long file_dialog(object wind, unsigned id);
static long file_exit(object wind, unsigned id);
static int recalc(object actl, object dlg);
int start()
{
object win;
char title[80];
sprintf(title, "My Test Application - %d", 8*(int)sizeof(char *));
win = vNew(MainWindow, title);
mLoadIcon(win, ALGOCORP_ICON);
mLoadMenu(win, IDR_MENU1);
mAssociate(win, ID_FILE_DIALOG, file_dialog);
mAssociate(win, ID_FILE_EXIT, file_exit);
return gProcessMessages(win);
}
static void init_controls(object dlg)
{
object ctl;
ctl = mAddControl(dlg, NumericControl, IDC_VALUE1);
gNumericRange(ctl, 0.0, 1000000.0, 2);
gSetFunction(ctl, recalc);
ctl = mAddControl(dlg, NumericControl, IDC_VALUE2);
gNumericRange(ctl, 0.0, 1000000.0, 2);
gSetFunction(ctl, recalc);
ctl = mAddControl(dlg, NumericControl, IDC_TOTAL);
gNumericRange(ctl, 0.0, 1000000.0, 2);
gDisable(ctl);
}
static void displayValues(object wind, object dlg)
{
double dval;
dval = mCtlDoubleValue(dlg, IDC_VALUE1);
vPrintf(wind, "Value 1 = %.2f\n", dval);
dval = mCtlDoubleValue(dlg, IDC_VALUE2);
vPrintf(wind, "Value 2 = %.2f\n", dval);
dval = mCtlDoubleValue(dlg, IDC_TOTAL);
vPrintf(wind, "Total = %.2f\n\n", dval);
}
static long file_dialog(object wind, unsigned id)
{
object dlg;
int r;
dlg = mNewDialog(ModalDialog, DL1, wind);
init_controls(dlg);
r = gPerform(dlg);
if (r == TRUE)
displayValues(wind, dlg);
gDispose(dlg);
return 0L;
}
static long file_exit(object wind, unsigned id)
{
gQuitApplication(Application, 0);
return 0L;
}
static int recalc(object actl, object dlg)
{
object ctl;
double tot;
ctl = mGetControl(dlg, IDC_VALUE1);
tot = gDoubleValue(ctl);
ctl = mGetControl(dlg, IDC_VALUE2);
tot += gDoubleValue(ctl);
ctl = mGetControl(dlg, IDC_TOTAL);
gSetDoubleValue(ctl, tot);
return 0;
}
| bsd-2-clause |
katef/libfsm | src/libfsm/closure.c | 1 | 6320 | /*
* Copyright 2019 Katherine Flavel
*
* See LICENCE for the full copyright terms.
*/
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fsm/fsm.h>
#include <fsm/pred.h>
#include <fsm/walk.h>
#include <fsm/options.h>
#include <adt/queue.h>
#include <adt/set.h>
#include <adt/stateset.h>
#include <adt/edgeset.h>
#include "internal.h"
static int
epsilon_closure_single(const struct fsm *fsm, struct state_set **closures, fsm_state_t s)
{
struct state_iter it;
struct queue *q;
fsm_state_t p;
assert(fsm != NULL);
assert(closures != NULL);
assert(s < fsm->statecount);
q = queue_new(fsm->opt->alloc, fsm->statecount);
if (q == NULL) {
return 1;
}
fsm->states[s].visited = 1;
p = s;
goto start;
for (;;) {
struct state_iter state_iter;
fsm_state_t es;
/* XXX: don't need a queue, a set would suffice */
if (!queue_pop(q, &p)) {
break;
}
start:
assert(p < fsm->statecount);
/*
* If the closure for this state is already done (i.e. non-NULL),
* we can use it as part of the closure we're computing.
* For single-threaded traversal, this situation only happens on edges
* to lower-numbered states.
*
* Because an epsilon closure always includes its own state, we know
* done sets will never be NULL.
*
* Note we will never populate (or create the set for) any state other
* than closures[s] here; we only ever read from closures[p], not write.
*
* TODO: for a multithreaded implementation, this needs to be atomic.
* TODO: use partially-constructed (i.e. not readable) sets, and finalize later
*/
if (p != s && closures[p] != NULL) {
if (!state_set_copy(&closures[s], fsm->opt->alloc, closures[p])) {
goto error;
}
}
/*
* ... otherwise we have to traverse s ourselves, but we can't store the
* result of that in closures[s], because of cycles in the graph which
* include both states (that is, s and the origional state for which we
* are computing a closure).
*
* The exception to this would be when s does not reach the origional
* state, but this is expensive to compute without undertaking the same
* traversal we're doing in the first place. So we live with potentially
* multiple threads repeating some of the same work here.
*/
if (!state_set_add(&closures[s], fsm->opt->alloc, p)) {
goto error;
}
for (state_set_reset(fsm->states[p].epsilons, &state_iter); state_set_next(&state_iter, &es); ) {
if (fsm->states[es].visited) {
continue;
}
if (!queue_push(q, es)) {
goto error;
}
fsm->states[es].visited = 1;
}
}
/* TODO: when we allow partially-constructed sets, then sort closures[s] here and finalize the set */
/*
* Clear .visited because any particular state may belong to multiple closures,
* and so we may need to visit this state again.
*/
for (state_set_reset(closures[s], &it); state_set_next(&it, &p); ) {
fsm->states[p].visited = 0;
}
queue_free(q);
return 1;
error:
queue_free(q);
return 0;
}
struct state_set **
epsilon_closure(struct fsm *fsm)
{
struct state_set **closures;
fsm_state_t s;
assert(fsm != NULL);
assert(fsm->statecount > 0);
closures = f_malloc(fsm->opt->alloc, fsm->statecount * sizeof *closures);
if (closures == NULL) {
return NULL;
}
for (s = 0; s < fsm->statecount; s++) {
fsm->states[s].visited = 0;
closures[s] = NULL;
/*
* In the simplest case of having no epsilon transitions, the
* epsilon closure contains only itself. We populate that case
* here because it doesn't need any traversal and so we can
* avoid the bookkeeping overhead needed for general case.
*/
if (fsm->states[s].epsilons == NULL) {
if (!state_set_add(&closures[s], fsm->opt->alloc, s)) {
goto error;
}
}
}
/*
* TODO: Here we would arbitrarily partition the state array and iterate
* over states in parallel. Because of the contention on "done" states,
* it might be better to visit states randomly rather than iterating
* in order, because nearby states tend to share overlap in their closures.
*
* We might prefer to have threads re-do the same work rather than blocking
* on a mutex, and use an atomic read for reading .visited and similar.
*/
for (s = 0; s < fsm->statecount; s++) {
if (closures[s] != NULL) {
continue;
}
epsilon_closure_single(fsm, closures, s);
}
return closures;
error:
for (s = 0; s < fsm->statecount; s++) {
state_set_free(closures[s]);
}
f_free(fsm->opt->alloc, closures);
return NULL;
}
int
symbol_closure_without_epsilons(const struct fsm *fsm, fsm_state_t s,
struct state_set *sclosures[static FSM_SIGMA_COUNT])
{
struct edge_iter jt;
struct fsm_edge e;
assert(fsm != NULL);
assert(sclosures != NULL);
if (fsm->states[s].edges == NULL) {
return 1;
}
/*
* TODO: it's common for many symbols to have transitions to the same state
* (the worst case being an "any" transition). It'd be nice to find a way
* to avoid repeating that work by de-duplicating on the destination.
*/
for (edge_set_reset(fsm->states[s].edges, &jt); edge_set_next(&jt, &e); ) {
if (!state_set_add(&sclosures[e.symbol], fsm->opt->alloc, e.state)) {
return 0;
}
}
return 1;
}
int
symbol_closure(const struct fsm *fsm, fsm_state_t s,
struct state_set * const eclosures[static FSM_SIGMA_COUNT],
struct state_set *sclosures[static FSM_SIGMA_COUNT])
{
struct edge_iter jt;
struct fsm_edge e;
assert(fsm != NULL);
assert(eclosures != NULL);
assert(sclosures != NULL);
if (fsm->states[s].edges == NULL) {
return 1;
}
/*
* TODO: it's common for many symbols to have transitions to the same state
* (the worst case being an "any" transition). It'd be nice to find a way
* to avoid repeating that work by de-duplicating on the destination.
*
* The epsilon closure of a state will always include itself,
* so there's no need to explicitly copy the state itself here.
*/
for (edge_set_reset(fsm->states[s].edges, &jt); edge_set_next(&jt, &e); ) {
if (!state_set_copy(&sclosures[e.symbol], fsm->opt->alloc, eclosures[e.state])) {
return 0;
}
}
return 1;
}
void
closure_free(struct state_set **closures, size_t n)
{
fsm_state_t s;
for (s = 0; s < n; s++) {
state_set_free(closures[s]);
}
free(closures);
}
| bsd-2-clause |
cvpoienaru/CDevPack | src/list/array_list.c | 1 | 1530 | /**
* Copyright (c) 2016, Codrin-Victor Poienaru <cvpoienaru@gmail.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided by the 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 <list/array_list.h>
#include <defs.h>
#include <logger/logger.h>
#include <list/list_metadata.h>
#include <stdlib.h>
| bsd-2-clause |
hendersa/sel4px4 | apps/px4/src/lib/geo/geo.c | 3 | 19082 | /****************************************************************************
*
* Copyright (c) 2012-2014 PX4 Development Team. 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 PX4 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.
*
****************************************************************************/
/**
* @file geo.c
*
* Geo / math functions to perform geodesic calculations
*
* @author Thomas Gubler <thomasgubler@student.ethz.ch>
* @author Julian Oes <joes@student.ethz.ch>
* @author Lorenz Meier <lm@inf.ethz.ch>
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <geo/geo.h>
#include <px4_config.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
#include <float.h>
#include <systemlib/err.h>
#include <drivers/drv_hrt.h>
/*
* Azimuthal Equidistant Projection
* formulas according to: http://mathworld.wolfram.com/AzimuthalEquidistantProjection.html
*/
static struct map_projection_reference_s mp_ref = {0.0, 0.0, 0.0, 0.0, false, 0};
static struct globallocal_converter_reference_s gl_ref = {0.0f, false};
__EXPORT bool map_projection_global_initialized()
{
return map_projection_initialized(&mp_ref);
}
__EXPORT bool map_projection_initialized(const struct map_projection_reference_s *ref)
{
return ref->init_done;
}
__EXPORT uint64_t map_projection_global_timestamp()
{
return map_projection_timestamp(&mp_ref);
}
__EXPORT uint64_t map_projection_timestamp(const struct map_projection_reference_s *ref)
{
return ref->timestamp;
}
__EXPORT int map_projection_global_init(double lat_0, double lon_0, uint64_t timestamp) //lat_0, lon_0 are expected to be in correct format: -> 47.1234567 and not 471234567
{
if (strcmp("commander", getprogname()) == 0) {
return map_projection_init_timestamped(&mp_ref, lat_0, lon_0, timestamp);
} else {
return -1;
}
}
__EXPORT int map_projection_init_timestamped(struct map_projection_reference_s *ref, double lat_0, double lon_0, uint64_t timestamp) //lat_0, lon_0 are expected to be in correct format: -> 47.1234567 and not 471234567
{
ref->lat_rad = lat_0 * M_DEG_TO_RAD;
ref->lon_rad = lon_0 * M_DEG_TO_RAD;
ref->sin_lat = sin(ref->lat_rad);
ref->cos_lat = cos(ref->lat_rad);
ref->timestamp = timestamp;
ref->init_done = true;
return 0;
}
__EXPORT int map_projection_init(struct map_projection_reference_s *ref, double lat_0, double lon_0) //lat_0, lon_0 are expected to be in correct format: -> 47.1234567 and not 471234567
{
return map_projection_init_timestamped(ref, lat_0, lon_0, hrt_absolute_time());
}
__EXPORT int map_projection_global_reference(double *ref_lat_rad, double *ref_lon_rad)
{
return map_projection_reference(&mp_ref, ref_lat_rad, ref_lon_rad);
}
__EXPORT int map_projection_reference(const struct map_projection_reference_s *ref, double *ref_lat_rad, double *ref_lon_rad)
{
if (!map_projection_initialized(ref)) {
return -1;
}
*ref_lat_rad = ref->lat_rad;
*ref_lon_rad = ref->lon_rad;
return 0;
}
__EXPORT int map_projection_global_project(double lat, double lon, float *x, float *y)
{
return map_projection_project(&mp_ref, lat, lon, x, y);
}
__EXPORT int map_projection_project(const struct map_projection_reference_s *ref, double lat, double lon, float *x, float *y)
{
if (!map_projection_initialized(ref)) {
return -1;
}
double lat_rad = lat * M_DEG_TO_RAD;
double lon_rad = lon * M_DEG_TO_RAD;
double sin_lat = sin(lat_rad);
double cos_lat = cos(lat_rad);
double cos_d_lon = cos(lon_rad - ref->lon_rad);
double c = acos(ref->sin_lat * sin_lat + ref->cos_lat * cos_lat * cos_d_lon);
double k = (fabs(c) < DBL_EPSILON) ? 1.0 : (c / sin(c));
*x = k * (ref->cos_lat * sin_lat - ref->sin_lat * cos_lat * cos_d_lon) * CONSTANTS_RADIUS_OF_EARTH;
*y = k * cos_lat * sin(lon_rad - ref->lon_rad) * CONSTANTS_RADIUS_OF_EARTH;
return 0;
}
__EXPORT int map_projection_global_reproject(float x, float y, double *lat, double *lon)
{
return map_projection_reproject(&mp_ref, x, y, lat, lon);
}
__EXPORT int map_projection_reproject(const struct map_projection_reference_s *ref, float x, float y, double *lat, double *lon)
{
if (!map_projection_initialized(ref)) {
return -1;
}
double x_rad = x / CONSTANTS_RADIUS_OF_EARTH;
double y_rad = y / CONSTANTS_RADIUS_OF_EARTH;
double c = sqrtf(x_rad * x_rad + y_rad * y_rad);
double sin_c = sin(c);
double cos_c = cos(c);
double lat_rad;
double lon_rad;
if (fabs(c) > DBL_EPSILON) {
lat_rad = asin(cos_c * ref->sin_lat + (x_rad * sin_c * ref->cos_lat) / c);
lon_rad = (ref->lon_rad + atan2(y_rad * sin_c, c * ref->cos_lat * cos_c - x_rad * ref->sin_lat * sin_c));
} else {
lat_rad = ref->lat_rad;
lon_rad = ref->lon_rad;
}
*lat = lat_rad * 180.0 / M_PI;
*lon = lon_rad * 180.0 / M_PI;
return 0;
}
__EXPORT int map_projection_global_getref(double *lat_0, double *lon_0)
{
if (!map_projection_global_initialized()) {
return -1;
}
if (lat_0 != NULL) {
*lat_0 = M_RAD_TO_DEG * mp_ref.lat_rad;
}
if (lon_0 != NULL) {
*lon_0 = M_RAD_TO_DEG * mp_ref.lon_rad;
}
return 0;
}
__EXPORT int globallocalconverter_init(double lat_0, double lon_0, float alt_0, uint64_t timestamp)
{
if (strcmp("commander", getprogname()) == 0) {
gl_ref.alt = alt_0;
if (!map_projection_global_init(lat_0, lon_0, timestamp))
{
gl_ref.init_done = true;
return 0;
} else {
gl_ref.init_done = false;
return -1;
}
} else {
return -1;
}
}
__EXPORT bool globallocalconverter_initialized()
{
return gl_ref.init_done && map_projection_global_initialized();
}
__EXPORT int globallocalconverter_tolocal(double lat, double lon, float alt, float *x, float *y, float *z)
{
if (!map_projection_global_initialized()) {
return -1;
}
map_projection_global_project(lat, lon, x, y);
*z = gl_ref.alt - alt;
return 0;
}
__EXPORT int globallocalconverter_toglobal(float x, float y, float z, double *lat, double *lon, float *alt)
{
if (!map_projection_global_initialized()) {
return -1;
}
map_projection_global_reproject(x, y, lat, lon);
*alt = gl_ref.alt - z;
return 0;
}
__EXPORT int globallocalconverter_getref(double *lat_0, double *lon_0, float *alt_0)
{
if (!map_projection_global_initialized()) {
return -1;
}
if (map_projection_global_getref(lat_0, lon_0))
{
return -1;
}
if (alt_0 != NULL) {
*alt_0 = gl_ref.alt;
}
return 0;
}
__EXPORT float get_distance_to_next_waypoint(double lat_now, double lon_now, double lat_next, double lon_next)
{
double lat_now_rad = lat_now / (double)180.0 * M_PI;
double lon_now_rad = lon_now / (double)180.0 * M_PI;
double lat_next_rad = lat_next / (double)180.0 * M_PI;
double lon_next_rad = lon_next / (double)180.0 * M_PI;
double d_lat = lat_next_rad - lat_now_rad;
double d_lon = lon_next_rad - lon_now_rad;
double a = sin(d_lat / (double)2.0) * sin(d_lat / (double)2.0) + sin(d_lon / (double)2.0) * sin(d_lon / (double)2.0) * cos(lat_now_rad) * cos(lat_next_rad);
double c = (double)2.0 * atan2(sqrt(a), sqrt((double)1.0 - a));
return CONSTANTS_RADIUS_OF_EARTH * c;
}
__EXPORT float get_bearing_to_next_waypoint(double lat_now, double lon_now, double lat_next, double lon_next)
{
double lat_now_rad = lat_now * M_DEG_TO_RAD;
double lon_now_rad = lon_now * M_DEG_TO_RAD;
double lat_next_rad = lat_next * M_DEG_TO_RAD;
double lon_next_rad = lon_next * M_DEG_TO_RAD;
double d_lon = lon_next_rad - lon_now_rad;
/* conscious mix of double and float trig function to maximize speed and efficiency */
float theta = atan2f(sin(d_lon) * cos(lat_next_rad) , cos(lat_now_rad) * sin(lat_next_rad) - sin(lat_now_rad) * cos(lat_next_rad) * cos(d_lon));
theta = _wrap_pi(theta);
return theta;
}
__EXPORT void get_vector_to_next_waypoint(double lat_now, double lon_now, double lat_next, double lon_next, float *v_n, float *v_e)
{
double lat_now_rad = lat_now * M_DEG_TO_RAD;
double lon_now_rad = lon_now * M_DEG_TO_RAD;
double lat_next_rad = lat_next * M_DEG_TO_RAD;
double lon_next_rad = lon_next * M_DEG_TO_RAD;
double d_lon = lon_next_rad - lon_now_rad;
/* conscious mix of double and float trig function to maximize speed and efficiency */
*v_n = CONSTANTS_RADIUS_OF_EARTH * (cos(lat_now_rad) * sin(lat_next_rad) - sin(lat_now_rad) * cos(lat_next_rad) * cos(d_lon));
*v_e = CONSTANTS_RADIUS_OF_EARTH * sin(d_lon) * cos(lat_next_rad);
}
__EXPORT void get_vector_to_next_waypoint_fast(double lat_now, double lon_now, double lat_next, double lon_next, float *v_n, float *v_e)
{
double lat_now_rad = lat_now * M_DEG_TO_RAD;
double lon_now_rad = lon_now * M_DEG_TO_RAD;
double lat_next_rad = lat_next * M_DEG_TO_RAD;
double lon_next_rad = lon_next * M_DEG_TO_RAD;
double d_lat = lat_next_rad - lat_now_rad;
double d_lon = lon_next_rad - lon_now_rad;
/* conscious mix of double and float trig function to maximize speed and efficiency */
*v_n = CONSTANTS_RADIUS_OF_EARTH * d_lat;
*v_e = CONSTANTS_RADIUS_OF_EARTH * d_lon * cos(lat_now_rad);
}
__EXPORT void add_vector_to_global_position(double lat_now, double lon_now, float v_n, float v_e, double *lat_res, double *lon_res)
{
double lat_now_rad = lat_now * M_DEG_TO_RAD;
double lon_now_rad = lon_now * M_DEG_TO_RAD;
*lat_res = (lat_now_rad + (double)v_n / CONSTANTS_RADIUS_OF_EARTH) * M_RAD_TO_DEG;
*lon_res = (lon_now_rad + (double)v_e / (CONSTANTS_RADIUS_OF_EARTH * cos(lat_now_rad))) * M_RAD_TO_DEG;
}
// Additional functions - @author Doug Weibel <douglas.weibel@colorado.edu>
__EXPORT int get_distance_to_line(struct crosstrack_error_s *crosstrack_error, double lat_now, double lon_now, double lat_start, double lon_start, double lat_end, double lon_end)
{
// This function returns the distance to the nearest point on the track line. Distance is positive if current
// position is right of the track and negative if left of the track as seen from a point on the track line
// headed towards the end point.
float dist_to_end;
float bearing_end;
float bearing_track;
float bearing_diff;
int return_value = ERROR; // Set error flag, cleared when valid result calculated.
crosstrack_error->past_end = false;
crosstrack_error->distance = 0.0f;
crosstrack_error->bearing = 0.0f;
dist_to_end = get_distance_to_next_waypoint(lat_now, lon_now, lat_end, lon_end);
// Return error if arguments are bad
if (dist_to_end < 0.1f) {
return ERROR;
}
bearing_end = get_bearing_to_next_waypoint(lat_now, lon_now, lat_end, lon_end);
bearing_track = get_bearing_to_next_waypoint(lat_start, lon_start, lat_end, lon_end);
bearing_diff = bearing_track - bearing_end;
bearing_diff = _wrap_pi(bearing_diff);
// Return past_end = true if past end point of line
if (bearing_diff > M_PI_2_F || bearing_diff < -M_PI_2_F) {
crosstrack_error->past_end = true;
return_value = OK;
return return_value;
}
crosstrack_error->distance = (dist_to_end) * sinf(bearing_diff);
if (sin(bearing_diff) >= 0) {
crosstrack_error->bearing = _wrap_pi(bearing_track - M_PI_2_F);
} else {
crosstrack_error->bearing = _wrap_pi(bearing_track + M_PI_2_F);
}
return_value = OK;
return return_value;
}
__EXPORT int get_distance_to_arc(struct crosstrack_error_s *crosstrack_error, double lat_now, double lon_now, double lat_center, double lon_center,
float radius, float arc_start_bearing, float arc_sweep)
{
// This function returns the distance to the nearest point on the track arc. Distance is positive if current
// position is right of the arc and negative if left of the arc as seen from the closest point on the arc and
// headed towards the end point.
// Determine if the current position is inside or outside the sector between the line from the center
// to the arc start and the line from the center to the arc end
float bearing_sector_start;
float bearing_sector_end;
float bearing_now = get_bearing_to_next_waypoint(lat_now, lon_now, lat_center, lon_center);
bool in_sector;
int return_value = ERROR; // Set error flag, cleared when valid result calculated.
crosstrack_error->past_end = false;
crosstrack_error->distance = 0.0f;
crosstrack_error->bearing = 0.0f;
// Return error if arguments are bad
if (radius < 0.1f) { return return_value; }
if (arc_sweep >= 0.0f) {
bearing_sector_start = arc_start_bearing;
bearing_sector_end = arc_start_bearing + arc_sweep;
if (bearing_sector_end > 2.0f * M_PI_F) { bearing_sector_end -= M_TWOPI_F; }
} else {
bearing_sector_end = arc_start_bearing;
bearing_sector_start = arc_start_bearing - arc_sweep;
if (bearing_sector_start < 0.0f) { bearing_sector_start += M_TWOPI_F; }
}
in_sector = false;
// Case where sector does not span zero
if (bearing_sector_end >= bearing_sector_start && bearing_now >= bearing_sector_start && bearing_now <= bearing_sector_end) { in_sector = true; }
// Case where sector does span zero
if (bearing_sector_end < bearing_sector_start && (bearing_now > bearing_sector_start || bearing_now < bearing_sector_end)) { in_sector = true; }
// If in the sector then calculate distance and bearing to closest point
if (in_sector) {
crosstrack_error->past_end = false;
float dist_to_center = get_distance_to_next_waypoint(lat_now, lon_now, lat_center, lon_center);
if (dist_to_center <= radius) {
crosstrack_error->distance = radius - dist_to_center;
crosstrack_error->bearing = bearing_now + M_PI_F;
} else {
crosstrack_error->distance = dist_to_center - radius;
crosstrack_error->bearing = bearing_now;
}
// If out of the sector then calculate dist and bearing to start or end point
} else {
// Use the approximation that 111,111 meters in the y direction is 1 degree (of latitude)
// and 111,111 * cos(latitude) meters in the x direction is 1 degree (of longitude) to
// calculate the position of the start and end points. We should not be doing this often
// as this function generally will not be called repeatedly when we are out of the sector.
double start_disp_x = (double)radius * sin(arc_start_bearing);
double start_disp_y = (double)radius * cos(arc_start_bearing);
double end_disp_x = (double)radius * sin(_wrap_pi((double)(arc_start_bearing + arc_sweep)));
double end_disp_y = (double)radius * cos(_wrap_pi((double)(arc_start_bearing + arc_sweep)));
double lon_start = lon_now + start_disp_x / 111111.0;
double lat_start = lat_now + start_disp_y * cos(lat_now) / 111111.0;
double lon_end = lon_now + end_disp_x / 111111.0;
double lat_end = lat_now + end_disp_y * cos(lat_now) / 111111.0;
double dist_to_start = get_distance_to_next_waypoint(lat_now, lon_now, lat_start, lon_start);
double dist_to_end = get_distance_to_next_waypoint(lat_now, lon_now, lat_end, lon_end);
if (dist_to_start < dist_to_end) {
crosstrack_error->distance = dist_to_start;
crosstrack_error->bearing = get_bearing_to_next_waypoint(lat_now, lon_now, lat_start, lon_start);
} else {
crosstrack_error->past_end = true;
crosstrack_error->distance = dist_to_end;
crosstrack_error->bearing = get_bearing_to_next_waypoint(lat_now, lon_now, lat_end, lon_end);
}
}
crosstrack_error->bearing = _wrap_pi((double)crosstrack_error->bearing);
return_value = OK;
return return_value;
}
__EXPORT float get_distance_to_point_global_wgs84(double lat_now, double lon_now, float alt_now,
double lat_next, double lon_next, float alt_next,
float *dist_xy, float *dist_z)
{
double current_x_rad = lat_next / 180.0 * M_PI;
double current_y_rad = lon_next / 180.0 * M_PI;
double x_rad = lat_now / 180.0 * M_PI;
double y_rad = lon_now / 180.0 * M_PI;
double d_lat = x_rad - current_x_rad;
double d_lon = y_rad - current_y_rad;
double a = sin(d_lat / 2.0) * sin(d_lat / 2.0) + sin(d_lon / 2.0) * sin(d_lon / 2.0) * cos(current_x_rad) * cos(x_rad);
double c = 2 * atan2(sqrt(a), sqrt(1 - a));
float dxy = CONSTANTS_RADIUS_OF_EARTH * c;
float dz = alt_now - alt_next;
*dist_xy = fabsf(dxy);
*dist_z = fabsf(dz);
return sqrtf(dxy * dxy + dz * dz);
}
__EXPORT float mavlink_wpm_distance_to_point_local(float x_now, float y_now, float z_now,
float x_next, float y_next, float z_next,
float *dist_xy, float *dist_z)
{
float dx = x_now - x_next;
float dy = y_now - y_next;
float dz = z_now - z_next;
*dist_xy = sqrtf(dx * dx + dy * dy);
*dist_z = fabsf(dz);
return sqrtf(dx * dx + dy * dy + dz * dz);
}
__EXPORT float _wrap_pi(float bearing)
{
/* value is inf or NaN */
if (!isfinite(bearing)) {
return bearing;
}
int c = 0;
while (bearing >= M_PI_F) {
bearing -= M_TWOPI_F;
if (c++ > 3) {
return NAN;
}
}
c = 0;
while (bearing < -M_PI_F) {
bearing += M_TWOPI_F;
if (c++ > 3) {
return NAN;
}
}
return bearing;
}
__EXPORT float _wrap_2pi(float bearing)
{
/* value is inf or NaN */
if (!isfinite(bearing)) {
return bearing;
}
int c = 0;
while (bearing >= M_TWOPI_F) {
bearing -= M_TWOPI_F;
if (c++ > 3) {
return NAN;
}
}
c = 0;
while (bearing < 0.0f) {
bearing += M_TWOPI_F;
if (c++ > 3) {
return NAN;
}
}
return bearing;
}
__EXPORT float _wrap_180(float bearing)
{
/* value is inf or NaN */
if (!isfinite(bearing)) {
return bearing;
}
int c = 0;
while (bearing >= 180.0f) {
bearing -= 360.0f;
if (c++ > 3) {
return NAN;
}
}
c = 0;
while (bearing < -180.0f) {
bearing += 360.0f;
if (c++ > 3) {
return NAN;
}
}
return bearing;
}
__EXPORT float _wrap_360(float bearing)
{
/* value is inf or NaN */
if (!isfinite(bearing)) {
return bearing;
}
int c = 0;
while (bearing >= 360.0f) {
bearing -= 360.0f;
if (c++ > 3) {
return NAN;
}
}
c = 0;
while (bearing < 0.0f) {
bearing += 360.0f;
if (c++ > 3) {
return NAN;
}
}
return bearing;
}
| bsd-2-clause |
ah744/ScaffCC_RKQC | clang/lib/Rewrite/RewriteMacros.cpp | 6 | 8105 | //===--- RewriteMacros.cpp - Rewrite macros into their expansions ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This code rewrites macro invocations into their expansions. This gives you
// a macro expanded file that retains comments and #includes.
//
//===----------------------------------------------------------------------===//
#include "clang/Rewrite/Rewriters.h"
#include "clang/Rewrite/Rewriter.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Path.h"
#include "llvm/ADT/OwningPtr.h"
#include <cstdio>
using namespace clang;
/// isSameToken - Return true if the two specified tokens start have the same
/// content.
static bool isSameToken(Token &RawTok, Token &PPTok) {
// If two tokens have the same kind and the same identifier info, they are
// obviously the same.
if (PPTok.getKind() == RawTok.getKind() &&
PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
return true;
// Otherwise, if they are different but have the same identifier info, they
// are also considered to be the same. This allows keywords and raw lexed
// identifiers with the same name to be treated the same.
if (PPTok.getIdentifierInfo() &&
PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
return true;
return false;
}
/// GetNextRawTok - Return the next raw token in the stream, skipping over
/// comments if ReturnComment is false.
static const Token &GetNextRawTok(const std::vector<Token> &RawTokens,
unsigned &CurTok, bool ReturnComment) {
assert(CurTok < RawTokens.size() && "Overran eof!");
// If the client doesn't want comments and we have one, skip it.
if (!ReturnComment && RawTokens[CurTok].is(tok::comment))
++CurTok;
return RawTokens[CurTok++];
}
/// LexRawTokensFromMainFile - Lets all the raw tokens from the main file into
/// the specified vector.
static void LexRawTokensFromMainFile(Preprocessor &PP,
std::vector<Token> &RawTokens) {
SourceManager &SM = PP.getSourceManager();
// Create a lexer to lex all the tokens of the main file in raw mode. Even
// though it is in raw mode, it will not return comments.
const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
// Switch on comment lexing because we really do want them.
RawLex.SetCommentRetentionState(true);
Token RawTok;
do {
RawLex.LexFromRawLexer(RawTok);
// If we have an identifier with no identifier info for our raw token, look
// up the indentifier info. This is important for equality comparison of
// identifier tokens.
if (RawTok.is(tok::raw_identifier))
PP.LookUpIdentifierInfo(RawTok);
RawTokens.push_back(RawTok);
} while (RawTok.isNot(tok::eof));
}
/// RewriteMacrosInInput - Implement -rewrite-macros mode.
void clang::RewriteMacrosInInput(Preprocessor &PP, raw_ostream *OS) {
SourceManager &SM = PP.getSourceManager();
Rewriter Rewrite;
Rewrite.setSourceMgr(SM, PP.getLangOpts());
RewriteBuffer &RB = Rewrite.getEditBuffer(SM.getMainFileID());
std::vector<Token> RawTokens;
LexRawTokensFromMainFile(PP, RawTokens);
unsigned CurRawTok = 0;
Token RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
// Get the first preprocessing token.
PP.EnterMainSourceFile();
Token PPTok;
PP.Lex(PPTok);
// Preprocess the input file in parallel with raw lexing the main file. Ignore
// all tokens that are preprocessed from a file other than the main file (e.g.
// a header). If we see tokens that are in the preprocessed file but not the
// lexed file, we have a macro expansion. If we see tokens in the lexed file
// that aren't in the preprocessed view, we have macros that expand to no
// tokens, or macro arguments etc.
while (RawTok.isNot(tok::eof) || PPTok.isNot(tok::eof)) {
SourceLocation PPLoc = SM.getExpansionLoc(PPTok.getLocation());
// If PPTok is from a different source file, ignore it.
if (!SM.isFromMainFile(PPLoc)) {
PP.Lex(PPTok);
continue;
}
// If the raw file hits a preprocessor directive, they will be extra tokens
// in the raw file that don't exist in the preprocsesed file. However, we
// choose to preserve them in the output file and otherwise handle them
// specially.
if (RawTok.is(tok::hash) && RawTok.isAtStartOfLine()) {
// If this is a #warning directive or #pragma mark (GNU extensions),
// comment the line out.
if (RawTokens[CurRawTok].is(tok::identifier)) {
const IdentifierInfo *II = RawTokens[CurRawTok].getIdentifierInfo();
if (II->getName() == "warning") {
// Comment out #warning.
RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//");
} else if (II->getName() == "pragma" &&
RawTokens[CurRawTok+1].is(tok::identifier) &&
(RawTokens[CurRawTok+1].getIdentifierInfo()->getName() ==
"mark")) {
// Comment out #pragma mark.
RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//");
}
}
// Otherwise, if this is a #include or some other directive, just leave it
// in the file by skipping over the line.
RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
while (!RawTok.isAtStartOfLine() && RawTok.isNot(tok::eof))
RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
continue;
}
// Okay, both tokens are from the same file. Get their offsets from the
// start of the file.
unsigned PPOffs = SM.getFileOffset(PPLoc);
unsigned RawOffs = SM.getFileOffset(RawTok.getLocation());
// If the offsets are the same and the token kind is the same, ignore them.
if (PPOffs == RawOffs && isSameToken(RawTok, PPTok)) {
RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
PP.Lex(PPTok);
continue;
}
// If the PP token is farther along than the raw token, something was
// deleted. Comment out the raw token.
if (RawOffs <= PPOffs) {
// Comment out a whole run of tokens instead of bracketing each one with
// comments. Add a leading space if RawTok didn't have one.
bool HasSpace = RawTok.hasLeadingSpace();
RB.InsertTextAfter(RawOffs, &" /*"[HasSpace]);
unsigned EndPos;
do {
EndPos = RawOffs+RawTok.getLength();
RawTok = GetNextRawTok(RawTokens, CurRawTok, true);
RawOffs = SM.getFileOffset(RawTok.getLocation());
if (RawTok.is(tok::comment)) {
// Skip past the comment.
RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
break;
}
} while (RawOffs <= PPOffs && !RawTok.isAtStartOfLine() &&
(PPOffs != RawOffs || !isSameToken(RawTok, PPTok)));
RB.InsertTextBefore(EndPos, "*/");
continue;
}
// Otherwise, there was a replacement an expansion. Insert the new token
// in the output buffer. Insert the whole run of new tokens at once to get
// them in the right order.
unsigned InsertPos = PPOffs;
std::string Expansion;
while (PPOffs < RawOffs) {
Expansion += ' ' + PP.getSpelling(PPTok);
PP.Lex(PPTok);
PPLoc = SM.getExpansionLoc(PPTok.getLocation());
PPOffs = SM.getFileOffset(PPLoc);
}
Expansion += ' ';
RB.InsertTextBefore(InsertPos, Expansion);
}
// Get the buffer corresponding to MainFileID. If we haven't changed it, then
// we are done.
if (const RewriteBuffer *RewriteBuf =
Rewrite.getRewriteBufferFor(SM.getMainFileID())) {
//printf("Changed:\n");
*OS << std::string(RewriteBuf->begin(), RewriteBuf->end());
} else {
fprintf(stderr, "No changes\n");
}
OS->flush();
}
| bsd-2-clause |
ironpinguin/php_rsync | librsync/isprefix.c | 6 | 1189 | /*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
* librsync -- dynamic caching and delta update in HTTP
* $Id: isprefix.c,v 1.5 2001/03/05 07:09:37 mbp Exp $
*
* Copyright (C) 2000, 2001 by Martin Pool <mbp@samba.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "isprefix.h"
/**
* Return true if TIP is a prefix of ICEBERG.
*/
int
isprefix(char const *tip, char const *iceberg)
{
while (*tip) {
if (*tip != *iceberg)
return 0;
tip++; iceberg++;
}
return 1;
}
| bsd-2-clause |
endplay/omniplay | linux-lts-quantal-3.5.0/drivers/staging/comedi/drivers/cb_pcidda.c | 50 | 23985 | /*
comedi/drivers/cb_pcidda.c
This intends to be a driver for the ComputerBoards / MeasurementComputing
PCI-DDA series.
Copyright (C) 2001 Ivan Martinez <ivanmr@altavista.com>
Copyright (C) 2001 Frank Mori Hess <fmhess@users.sourceforge.net>
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-8 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: cb_pcidda
Description: MeasurementComputing PCI-DDA series
Author: Ivan Martinez <ivanmr@altavista.com>, Frank Mori Hess <fmhess@users.sourceforge.net>
Status: Supports 08/16, 04/16, 02/16, 08/12, 04/12, and 02/12
Devices: [Measurement Computing] PCI-DDA08/12 (cb_pcidda), PCI-DDA04/12,
PCI-DDA02/12, PCI-DDA08/16, PCI-DDA04/16, PCI-DDA02/16
Configuration options:
[0] - PCI bus of device (optional)
[1] - PCI slot of device (optional)
If bus/slot is not specified, the first available PCI
device will be used.
Only simple analog output writing is supported.
So far it has only been tested with:
- PCI-DDA08/12
Please report success/failure with other different cards to
<comedi@comedi.org>.
*/
#include "../comedidev.h"
#include "comedi_pci.h"
#include "8255.h"
/* PCI vendor number of ComputerBoards */
#define PCI_VENDOR_ID_CB 0x1307
#define EEPROM_SIZE 128 /* number of entries in eeprom */
/* maximum number of ao channels for supported boards */
#define MAX_AO_CHANNELS 8
/* PCI-DDA base addresses */
#define DIGITALIO_BADRINDEX 2
/* DIGITAL I/O is pci_dev->resource[2] */
#define DIGITALIO_SIZE 8
/* DIGITAL I/O uses 8 I/O port addresses */
#define DAC_BADRINDEX 3
/* DAC is pci_dev->resource[3] */
/* Digital I/O registers */
#define PORT1A 0 /* PORT 1A DATA */
#define PORT1B 1 /* PORT 1B DATA */
#define PORT1C 2 /* PORT 1C DATA */
#define CONTROL1 3 /* CONTROL REGISTER 1 */
#define PORT2A 4 /* PORT 2A DATA */
#define PORT2B 5 /* PORT 2B DATA */
#define PORT2C 6 /* PORT 2C DATA */
#define CONTROL2 7 /* CONTROL REGISTER 2 */
/* DAC registers */
#define DACONTROL 0 /* D/A CONTROL REGISTER */
#define SU 0000001 /* Simultaneous update enabled */
#define NOSU 0000000 /* Simultaneous update disabled */
#define ENABLEDAC 0000002 /* Enable specified DAC */
#define DISABLEDAC 0000000 /* Disable specified DAC */
#define RANGE2V5 0000000 /* 2.5V */
#define RANGE5V 0000200 /* 5V */
#define RANGE10V 0000300 /* 10V */
#define UNIP 0000400 /* Unipolar outputs */
#define BIP 0000000 /* Bipolar outputs */
#define DACALIBRATION1 4 /* D/A CALIBRATION REGISTER 1 */
/* write bits */
/* serial data input for eeprom, caldacs, reference dac */
#define SERIAL_IN_BIT 0x1
#define CAL_CHANNEL_MASK (0x7 << 1)
#define CAL_CHANNEL_BITS(channel) (((channel) << 1) & CAL_CHANNEL_MASK)
/* read bits */
#define CAL_COUNTER_MASK 0x1f
/* calibration counter overflow status bit */
#define CAL_COUNTER_OVERFLOW_BIT 0x20
/* analog output is less than reference dac voltage */
#define AO_BELOW_REF_BIT 0x40
#define SERIAL_OUT_BIT 0x80 /* serial data out, for reading from eeprom */
#define DACALIBRATION2 6 /* D/A CALIBRATION REGISTER 2 */
#define SELECT_EEPROM_BIT 0x1 /* send serial data in to eeprom */
/* don't send serial data to MAX542 reference dac */
#define DESELECT_REF_DAC_BIT 0x2
/* don't send serial data to caldac n */
#define DESELECT_CALDAC_BIT(n) (0x4 << (n))
/* manual says to set this bit with no explanation */
#define DUMMY_BIT 0x40
#define DADATA 8 /* FIRST D/A DATA REGISTER (0) */
static const struct comedi_lrange cb_pcidda_ranges = {
6,
{
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2.5),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2.5),
}
};
/*
* Board descriptions for two imaginary boards. Describing the
* boards in this way is optional, and completely driver-dependent.
* Some drivers use arrays such as this, other do not.
*/
struct cb_pcidda_board {
const char *name;
char status; /* Driver status: */
/*
* 0 - tested
* 1 - manual read, not tested
* 2 - manual not read
*/
unsigned short device_id;
int ao_chans;
int ao_bits;
const struct comedi_lrange *ranges;
};
static const struct cb_pcidda_board cb_pcidda_boards[] = {
{
.name = "pci-dda02/12",
.status = 1,
.device_id = 0x20,
.ao_chans = 2,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda04/12",
.status = 1,
.device_id = 0x21,
.ao_chans = 4,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda08/12",
.status = 0,
.device_id = 0x22,
.ao_chans = 8,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda02/16",
.status = 2,
.device_id = 0x23,
.ao_chans = 2,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda04/16",
.status = 2,
.device_id = 0x24,
.ao_chans = 4,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda08/16",
.status = 0,
.device_id = 0x25,
.ao_chans = 8,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
};
/*
* Useful for shorthand access to the particular board structure
*/
#define thisboard ((const struct cb_pcidda_board *)dev->board_ptr)
/*
* this structure is for data unique to this hardware driver. If
* several hardware drivers keep similar information in this structure,
* feel free to suggest moving the variable to the struct comedi_device
* struct.
*/
struct cb_pcidda_private {
int data;
/* would be useful for a PCI device */
struct pci_dev *pci_dev;
unsigned long digitalio;
unsigned long dac;
/* unsigned long control_status; */
/* unsigned long adc_fifo; */
/* bits last written to da calibration register 1 */
unsigned int dac_cal1_bits;
/* current range settings for output channels */
unsigned int ao_range[MAX_AO_CHANNELS];
u16 eeprom_data[EEPROM_SIZE]; /* software copy of board's eeprom */
};
/*
* most drivers define the following macro to make it easy to
* access the private structure.
*/
#define devpriv ((struct cb_pcidda_private *)dev->private)
/* static int cb_pcidda_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data); */
static int cb_pcidda_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
/* static int cb_pcidda_ai_cmd(struct comedi_device *dev, struct *comedi_subdevice *s);*/
/* static int cb_pcidda_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd); */
/* static int cb_pcidda_ns_to_timer(unsigned int *ns,int *round); */
static unsigned int cb_pcidda_serial_in(struct comedi_device *dev);
static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits);
static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
unsigned int address);
static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
unsigned int range);
/*
* Attach is called by the Comedi core to configure the driver
* for a particular board.
*/
static int cb_pcidda_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
struct pci_dev *pcidev = NULL;
int index;
/*
* Allocate the private structure area.
*/
if (alloc_private(dev, sizeof(struct cb_pcidda_private)) < 0)
return -ENOMEM;
/*
* Probe the device to determine what device in the series it is.
*/
for_each_pci_dev(pcidev) {
if (pcidev->vendor == PCI_VENDOR_ID_CB) {
if (it->options[0] || it->options[1]) {
if (pcidev->bus->number != it->options[0] ||
PCI_SLOT(pcidev->devfn) != it->options[1]) {
continue;
}
}
for (index = 0; index < ARRAY_SIZE(cb_pcidda_boards); index++) {
if (cb_pcidda_boards[index].device_id ==
pcidev->device) {
goto found;
}
}
}
}
if (!pcidev) {
dev_err(dev->hw_dev, "Not a ComputerBoards/MeasurementComputing card on requested position\n");
return -EIO;
}
found:
devpriv->pci_dev = pcidev;
dev->board_ptr = cb_pcidda_boards + index;
/* "thisboard" macro can be used from here. */
dev_dbg(dev->hw_dev, "Found %s at requested position\n",
thisboard->name);
/*
* Enable PCI device and request regions.
*/
if (comedi_pci_enable(pcidev, thisboard->name)) {
dev_err(dev->hw_dev, "cb_pcidda: failed to enable PCI device and request regions\n");
return -EIO;
}
/*
* Allocate the I/O ports.
*/
devpriv->digitalio =
pci_resource_start(devpriv->pci_dev, DIGITALIO_BADRINDEX);
devpriv->dac = pci_resource_start(devpriv->pci_dev, DAC_BADRINDEX);
/*
* Warn about the status of the driver.
*/
if (thisboard->status == 2)
printk
("WARNING: DRIVER FOR THIS BOARD NOT CHECKED WITH MANUAL. "
"WORKS ASSUMING FULL COMPATIBILITY WITH PCI-DDA08/12. "
"PLEASE REPORT USAGE TO <ivanmr@altavista.com>.\n");
/*
* Initialize dev->board_name.
*/
dev->board_name = thisboard->name;
/*
* Allocate the subdevice structures.
*/
if (alloc_subdevices(dev, 3) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
/* analog output subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE;
s->n_chan = thisboard->ao_chans;
s->maxdata = (1 << thisboard->ao_bits) - 1;
s->range_table = thisboard->ranges;
s->insn_write = cb_pcidda_ao_winsn;
/* s->subdev_flags |= SDF_CMD_READ; */
/* s->do_cmd = cb_pcidda_ai_cmd; */
/* s->do_cmdtest = cb_pcidda_ai_cmdtest; */
/* two 8255 digital io subdevices */
s = dev->subdevices + 1;
subdev_8255_init(dev, s, NULL, devpriv->digitalio);
s = dev->subdevices + 2;
subdev_8255_init(dev, s, NULL, devpriv->digitalio + PORT2A);
dev_dbg(dev->hw_dev, "eeprom:\n");
for (index = 0; index < EEPROM_SIZE; index++) {
devpriv->eeprom_data[index] = cb_pcidda_read_eeprom(dev, index);
dev_dbg(dev->hw_dev, "%i:0x%x\n", index,
devpriv->eeprom_data[index]);
}
/* set calibrations dacs */
for (index = 0; index < thisboard->ao_chans; index++)
cb_pcidda_calibrate(dev, index, devpriv->ao_range[index]);
return 1;
}
static void cb_pcidda_detach(struct comedi_device *dev)
{
if (devpriv) {
if (devpriv->pci_dev) {
if (devpriv->dac)
comedi_pci_disable(devpriv->pci_dev);
pci_dev_put(devpriv->pci_dev);
}
}
if (dev->subdevices) {
subdev_8255_cleanup(dev, dev->subdevices + 1);
subdev_8255_cleanup(dev, dev->subdevices + 2);
}
}
/*
* I will program this later... ;-)
*/
#if 0
static int cb_pcidda_ai_cmd(struct comedi_device *dev,
struct comedi_subdevice *s)
{
printk("cb_pcidda_ai_cmd\n");
printk("subdev: %d\n", cmd->subdev);
printk("flags: %d\n", cmd->flags);
printk("start_src: %d\n", cmd->start_src);
printk("start_arg: %d\n", cmd->start_arg);
printk("scan_begin_src: %d\n", cmd->scan_begin_src);
printk("convert_src: %d\n", cmd->convert_src);
printk("convert_arg: %d\n", cmd->convert_arg);
printk("scan_end_src: %d\n", cmd->scan_end_src);
printk("scan_end_arg: %d\n", cmd->scan_end_arg);
printk("stop_src: %d\n", cmd->stop_src);
printk("stop_arg: %d\n", cmd->stop_arg);
printk("chanlist_len: %d\n", cmd->chanlist_len);
}
#endif
#if 0
static int cb_pcidda_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
/* cmdtest tests a particular command to see if it is valid.
* Using the cmdtest ioctl, a user can create a valid cmd
* and then have it executes by the cmd ioctl.
*
* cmdtest returns 1,2,3,4 or 0, depending on which tests
* the command passes. */
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/*
* step 2: make sure trigger sources are unique and mutually
* compatible
*/
/* note that mutual compatibility is not an issue here */
if (cmd->scan_begin_src != TRIG_TIMER
&& cmd->scan_begin_src != TRIG_EXT)
err++;
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->stop_src != TRIG_TIMER && cmd->stop_src != TRIG_EXT)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
#define MAX_SPEED 10000 /* in nanoseconds */
#define MIN_SPEED 1000000000 /* in nanoseconds */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->scan_begin_arg < MAX_SPEED) {
cmd->scan_begin_arg = MAX_SPEED;
err++;
}
if (cmd->scan_begin_arg > MIN_SPEED) {
cmd->scan_begin_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* should be level/edge, hi/lo specification here */
/* should specify multiple external triggers */
if (cmd->scan_begin_arg > 9) {
cmd->scan_begin_arg = 9;
err++;
}
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < MAX_SPEED) {
cmd->convert_arg = MAX_SPEED;
err++;
}
if (cmd->convert_arg > MIN_SPEED) {
cmd->convert_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* see above */
if (cmd->convert_arg > 9) {
cmd->convert_arg = 9;
err++;
}
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
if (cmd->stop_arg > 0x00ffffff) {
cmd->stop_arg = 0x00ffffff;
err++;
}
} else {
/* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
tmp = cmd->scan_begin_arg;
cb_pcidda_ns_to_timer(&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->scan_begin_arg)
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
cb_pcidda_ns_to_timer(&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
err++;
if (cmd->scan_begin_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->scan_end_arg) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->scan_end_arg;
err++;
}
}
if (err)
return 4;
return 0;
}
#endif
/* This function doesn't require a particular form, this is just
* what happens to be used in some of the drivers. It should
* convert ns nanoseconds to a counter value suitable for programming
* the device. Also, it should adjust ns so that it cooresponds to
* the actual time that the device will use. */
#if 0
static int cb_pcidda_ns_to_timer(unsigned int *ns, int round)
{
/* trivial timer */
return *ns;
}
#endif
static int cb_pcidda_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int command;
unsigned int channel, range;
channel = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
/* adjust calibration dacs if range has changed */
if (range != devpriv->ao_range[channel])
cb_pcidda_calibrate(dev, channel, range);
/* output channel configuration */
command = NOSU | ENABLEDAC;
/* output channel range */
switch (range) {
case 0:
command |= BIP | RANGE10V;
break;
case 1:
command |= BIP | RANGE5V;
break;
case 2:
command |= BIP | RANGE2V5;
break;
case 3:
command |= UNIP | RANGE10V;
break;
case 4:
command |= UNIP | RANGE5V;
break;
case 5:
command |= UNIP | RANGE2V5;
break;
}
/* output channel specification */
command |= channel << 2;
outw(command, devpriv->dac + DACONTROL);
/* write data */
outw(data[0], devpriv->dac + DADATA + channel * 2);
/* return the number of samples read/written */
return 1;
}
/* lowlevel read from eeprom */
static unsigned int cb_pcidda_serial_in(struct comedi_device *dev)
{
unsigned int value = 0;
int i;
const int value_width = 16; /* number of bits wide values are */
for (i = 1; i <= value_width; i++) {
/* read bits most significant bit first */
if (inw_p(devpriv->dac + DACALIBRATION1) & SERIAL_OUT_BIT)
value |= 1 << (value_width - i);
}
return value;
}
/* lowlevel write to eeprom/dac */
static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits)
{
int i;
for (i = 1; i <= num_bits; i++) {
/* send bits most significant bit first */
if (value & (1 << (num_bits - i)))
devpriv->dac_cal1_bits |= SERIAL_IN_BIT;
else
devpriv->dac_cal1_bits &= ~SERIAL_IN_BIT;
outw_p(devpriv->dac_cal1_bits, devpriv->dac + DACALIBRATION1);
}
}
/* reads a 16 bit value from board's eeprom */
static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
unsigned int address)
{
unsigned int i;
unsigned int cal2_bits;
unsigned int value;
/* one caldac for every two dac channels */
const int max_num_caldacs = 4;
/* bits to send to tell eeprom we want to read */
const int read_instruction = 0x6;
const int instruction_length = 3;
const int address_length = 8;
/* send serial output stream to eeprom */
cal2_bits = SELECT_EEPROM_BIT | DESELECT_REF_DAC_BIT | DUMMY_BIT;
/* deactivate caldacs (one caldac for every two channels) */
for (i = 0; i < max_num_caldacs; i++)
cal2_bits |= DESELECT_CALDAC_BIT(i);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
/* tell eeprom we want to read */
cb_pcidda_serial_out(dev, read_instruction, instruction_length);
/* send address we want to read from */
cb_pcidda_serial_out(dev, address, address_length);
value = cb_pcidda_serial_in(dev);
/* deactivate eeprom */
cal2_bits &= ~SELECT_EEPROM_BIT;
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
return value;
}
/* writes to 8 bit calibration dacs */
static void cb_pcidda_write_caldac(struct comedi_device *dev,
unsigned int caldac, unsigned int channel,
unsigned int value)
{
unsigned int cal2_bits;
unsigned int i;
/* caldacs use 3 bit channel specification */
const int num_channel_bits = 3;
const int num_caldac_bits = 8; /* 8 bit calibration dacs */
/* one caldac for every two dac channels */
const int max_num_caldacs = 4;
/* write 3 bit channel */
cb_pcidda_serial_out(dev, channel, num_channel_bits);
/* write 8 bit caldac value */
cb_pcidda_serial_out(dev, value, num_caldac_bits);
/*
* latch stream into appropriate caldac deselect reference dac
*/
cal2_bits = DESELECT_REF_DAC_BIT | DUMMY_BIT;
/* deactivate caldacs (one caldac for every two channels) */
for (i = 0; i < max_num_caldacs; i++)
cal2_bits |= DESELECT_CALDAC_BIT(i);
/* activate the caldac we want */
cal2_bits &= ~DESELECT_CALDAC_BIT(caldac);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
/* deactivate caldac */
cal2_bits |= DESELECT_CALDAC_BIT(caldac);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
}
/* returns caldac that calibrates given analog out channel */
static unsigned int caldac_number(unsigned int channel)
{
return channel / 2;
}
/* returns caldac channel that provides fine gain for given ao channel */
static unsigned int fine_gain_channel(unsigned int ao_channel)
{
return 4 * (ao_channel % 2);
}
/* returns caldac channel that provides coarse gain for given ao channel */
static unsigned int coarse_gain_channel(unsigned int ao_channel)
{
return 1 + 4 * (ao_channel % 2);
}
/* returns caldac channel that provides coarse offset for given ao channel */
static unsigned int coarse_offset_channel(unsigned int ao_channel)
{
return 2 + 4 * (ao_channel % 2);
}
/* returns caldac channel that provides fine offset for given ao channel */
static unsigned int fine_offset_channel(unsigned int ao_channel)
{
return 3 + 4 * (ao_channel % 2);
}
/* returns eeprom address that provides offset for given ao channel and range */
static unsigned int offset_eeprom_address(unsigned int ao_channel,
unsigned int range)
{
return 0x7 + 2 * range + 12 * ao_channel;
}
/*
* returns eeprom address that provides gain calibration for given ao
* channel and range
*/
static unsigned int gain_eeprom_address(unsigned int ao_channel,
unsigned int range)
{
return 0x8 + 2 * range + 12 * ao_channel;
}
/*
* returns upper byte of eeprom entry, which gives the coarse adjustment
* values
*/
static unsigned int eeprom_coarse_byte(unsigned int word)
{
return (word >> 8) & 0xff;
}
/* returns lower byte of eeprom entry, which gives the fine adjustment values */
static unsigned int eeprom_fine_byte(unsigned int word)
{
return word & 0xff;
}
/* set caldacs to eeprom values for given channel and range */
static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
unsigned int range)
{
unsigned int coarse_offset, fine_offset, coarse_gain, fine_gain;
/* remember range so we can tell when we need to readjust calibration */
devpriv->ao_range[channel] = range;
/* get values from eeprom data */
coarse_offset =
eeprom_coarse_byte(devpriv->eeprom_data
[offset_eeprom_address(channel, range)]);
fine_offset =
eeprom_fine_byte(devpriv->eeprom_data
[offset_eeprom_address(channel, range)]);
coarse_gain =
eeprom_coarse_byte(devpriv->eeprom_data
[gain_eeprom_address(channel, range)]);
fine_gain =
eeprom_fine_byte(devpriv->eeprom_data
[gain_eeprom_address(channel, range)]);
/* set caldacs */
cb_pcidda_write_caldac(dev, caldac_number(channel),
coarse_offset_channel(channel), coarse_offset);
cb_pcidda_write_caldac(dev, caldac_number(channel),
fine_offset_channel(channel), fine_offset);
cb_pcidda_write_caldac(dev, caldac_number(channel),
coarse_gain_channel(channel), coarse_gain);
cb_pcidda_write_caldac(dev, caldac_number(channel),
fine_gain_channel(channel), fine_gain);
}
static struct comedi_driver cb_pcidda_driver = {
.driver_name = "cb_pcidda",
.module = THIS_MODULE,
.attach = cb_pcidda_attach,
.detach = cb_pcidda_detach,
};
static int __devinit cb_pcidda_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, &cb_pcidda_driver);
}
static void __devexit cb_pcidda_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static DEFINE_PCI_DEVICE_TABLE(cb_pcidda_pci_table) = {
{ PCI_DEVICE(PCI_VENDOR_ID_CB, 0x0020) },
{ PCI_DEVICE(PCI_VENDOR_ID_CB, 0x0021) },
{ PCI_DEVICE(PCI_VENDOR_ID_CB, 0x0022) },
{ PCI_DEVICE(PCI_VENDOR_ID_CB, 0x0023) },
{ PCI_DEVICE(PCI_VENDOR_ID_CB, 0x0024) },
{ PCI_DEVICE(PCI_VENDOR_ID_CB, 0x0025) },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, cb_pcidda_pci_table);
static struct pci_driver cb_pcidda_pci_driver = {
.name = "cb_pcidda",
.id_table = cb_pcidda_pci_table,
.probe = cb_pcidda_pci_probe,
.remove = __devexit_p(cb_pcidda_pci_remove),
};
module_comedi_pci_driver(cb_pcidda_driver, cb_pcidda_pci_driver);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| bsd-2-clause |
LomoX-Offical/nginx-openresty-windows | src/nginx/objs/lib/openssl/crypto/md2/md2_dgst.c | 58 | 8009 | /* crypto/md2/md2_dgst.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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 cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md2.h>
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
const char MD2_version[] = "MD2" OPENSSL_VERSION_PTEXT;
/*
* Implemented from RFC1319 The MD2 Message-Digest Algorithm
*/
#define UCHAR unsigned char
static void md2_block(MD2_CTX *c, const unsigned char *d);
/*
* The magic S table - I have converted it to hex since it is basically just
* a random byte string.
*/
static const MD2_INT S[256] = {
0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01,
0x3D, 0x36, 0x54, 0xA1, 0xEC, 0xF0, 0x06, 0x13,
0x62, 0xA7, 0x05, 0xF3, 0xC0, 0xC7, 0x73, 0x8C,
0x98, 0x93, 0x2B, 0xD9, 0xBC, 0x4C, 0x82, 0xCA,
0x1E, 0x9B, 0x57, 0x3C, 0xFD, 0xD4, 0xE0, 0x16,
0x67, 0x42, 0x6F, 0x18, 0x8A, 0x17, 0xE5, 0x12,
0xBE, 0x4E, 0xC4, 0xD6, 0xDA, 0x9E, 0xDE, 0x49,
0xA0, 0xFB, 0xF5, 0x8E, 0xBB, 0x2F, 0xEE, 0x7A,
0xA9, 0x68, 0x79, 0x91, 0x15, 0xB2, 0x07, 0x3F,
0x94, 0xC2, 0x10, 0x89, 0x0B, 0x22, 0x5F, 0x21,
0x80, 0x7F, 0x5D, 0x9A, 0x5A, 0x90, 0x32, 0x27,
0x35, 0x3E, 0xCC, 0xE7, 0xBF, 0xF7, 0x97, 0x03,
0xFF, 0x19, 0x30, 0xB3, 0x48, 0xA5, 0xB5, 0xD1,
0xD7, 0x5E, 0x92, 0x2A, 0xAC, 0x56, 0xAA, 0xC6,
0x4F, 0xB8, 0x38, 0xD2, 0x96, 0xA4, 0x7D, 0xB6,
0x76, 0xFC, 0x6B, 0xE2, 0x9C, 0x74, 0x04, 0xF1,
0x45, 0x9D, 0x70, 0x59, 0x64, 0x71, 0x87, 0x20,
0x86, 0x5B, 0xCF, 0x65, 0xE6, 0x2D, 0xA8, 0x02,
0x1B, 0x60, 0x25, 0xAD, 0xAE, 0xB0, 0xB9, 0xF6,
0x1C, 0x46, 0x61, 0x69, 0x34, 0x40, 0x7E, 0x0F,
0x55, 0x47, 0xA3, 0x23, 0xDD, 0x51, 0xAF, 0x3A,
0xC3, 0x5C, 0xF9, 0xCE, 0xBA, 0xC5, 0xEA, 0x26,
0x2C, 0x53, 0x0D, 0x6E, 0x85, 0x28, 0x84, 0x09,
0xD3, 0xDF, 0xCD, 0xF4, 0x41, 0x81, 0x4D, 0x52,
0x6A, 0xDC, 0x37, 0xC8, 0x6C, 0xC1, 0xAB, 0xFA,
0x24, 0xE1, 0x7B, 0x08, 0x0C, 0xBD, 0xB1, 0x4A,
0x78, 0x88, 0x95, 0x8B, 0xE3, 0x63, 0xE8, 0x6D,
0xE9, 0xCB, 0xD5, 0xFE, 0x3B, 0x00, 0x1D, 0x39,
0xF2, 0xEF, 0xB7, 0x0E, 0x66, 0x58, 0xD0, 0xE4,
0xA6, 0x77, 0x72, 0xF8, 0xEB, 0x75, 0x4B, 0x0A,
0x31, 0x44, 0x50, 0xB4, 0x8F, 0xED, 0x1F, 0x1A,
0xDB, 0x99, 0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14,
};
const char *MD2_options(void)
{
if (sizeof(MD2_INT) == 1)
return ("md2(char)");
else
return ("md2(int)");
}
fips_md_init(MD2)
{
c->num = 0;
memset(c->state, 0, sizeof c->state);
memset(c->cksm, 0, sizeof c->cksm);
memset(c->data, 0, sizeof c->data);
return 1;
}
int MD2_Update(MD2_CTX *c, const unsigned char *data, size_t len)
{
register UCHAR *p;
if (len == 0)
return 1;
p = c->data;
if (c->num != 0) {
if ((c->num + len) >= MD2_BLOCK) {
memcpy(&(p[c->num]), data, MD2_BLOCK - c->num);
md2_block(c, c->data);
data += (MD2_BLOCK - c->num);
len -= (MD2_BLOCK - c->num);
c->num = 0;
/* drop through and do the rest */
} else {
memcpy(&(p[c->num]), data, len);
/* data+=len; */
c->num += (int)len;
return 1;
}
}
/*
* we now can process the input data in blocks of MD2_BLOCK chars and
* save the leftovers to c->data.
*/
while (len >= MD2_BLOCK) {
md2_block(c, data);
data += MD2_BLOCK;
len -= MD2_BLOCK;
}
memcpy(p, data, len);
c->num = (int)len;
return 1;
}
static void md2_block(MD2_CTX *c, const unsigned char *d)
{
register MD2_INT t, *sp1, *sp2;
register int i, j;
MD2_INT state[48];
sp1 = c->state;
sp2 = c->cksm;
j = sp2[MD2_BLOCK - 1];
for (i = 0; i < 16; i++) {
state[i] = sp1[i];
state[i + 16] = t = d[i];
state[i + 32] = (t ^ sp1[i]);
j = sp2[i] ^= S[t ^ j];
}
t = 0;
for (i = 0; i < 18; i++) {
for (j = 0; j < 48; j += 8) {
t = state[j + 0] ^= S[t];
t = state[j + 1] ^= S[t];
t = state[j + 2] ^= S[t];
t = state[j + 3] ^= S[t];
t = state[j + 4] ^= S[t];
t = state[j + 5] ^= S[t];
t = state[j + 6] ^= S[t];
t = state[j + 7] ^= S[t];
}
t = (t + i) & 0xff;
}
memcpy(sp1, state, 16 * sizeof(MD2_INT));
OPENSSL_cleanse(state, 48 * sizeof(MD2_INT));
}
int MD2_Final(unsigned char *md, MD2_CTX *c)
{
int i, v;
register UCHAR *cp;
register MD2_INT *p1, *p2;
cp = c->data;
p1 = c->state;
p2 = c->cksm;
v = MD2_BLOCK - c->num;
for (i = c->num; i < MD2_BLOCK; i++)
cp[i] = (UCHAR) v;
md2_block(c, cp);
for (i = 0; i < MD2_BLOCK; i++)
cp[i] = (UCHAR) p2[i];
md2_block(c, cp);
for (i = 0; i < 16; i++)
md[i] = (UCHAR) (p1[i] & 0xff);
OPENSSL_cleanse(c, sizeof(*c));
return 1;
}
| bsd-2-clause |
ganyangbbl/openh264 | test/encoder/EncUT_EncoderMb.cpp | 73 | 10344 | #include <gtest/gtest.h>
#include "memory_align.h"
#include "utils/DataGenerator.h"
#include "encode_mb_aux.h"
using namespace WelsEnc;
ALIGNED_DECLARE (const int16_t, g_kiQuantInterFFCompare[104][8], 16) = {
/* 0*/ { 0, 1, 0, 1, 1, 1, 1, 1 },
/* 1*/ { 0, 1, 0, 1, 1, 1, 1, 1 },
/* 2*/ { 1, 1, 1, 1, 1, 1, 1, 1 },
/* 3*/ { 1, 1, 1, 1, 1, 2, 1, 2 },
/* 4*/ { 1, 1, 1, 1, 1, 2, 1, 2 },
/* 5*/ { 1, 1, 1, 1, 1, 2, 1, 2 },
/* 6*/ { 1, 1, 1, 1, 1, 2, 1, 2 },
/* 7*/ { 1, 2, 1, 2, 2, 2, 2, 2 },
/* 8*/ { 1, 2, 1, 2, 2, 3, 2, 3 },
/* 9*/ { 1, 2, 1, 2, 2, 3, 2, 3 },
/*10*/ { 1, 2, 1, 2, 2, 3, 2, 3 },
/*11*/ { 2, 2, 2, 2, 2, 4, 2, 4 },
/*12*/ { 2, 3, 2, 3, 3, 4, 3, 4 },
/*13*/ { 2, 3, 2, 3, 3, 5, 3, 5 },
/*14*/ { 2, 3, 2, 3, 3, 5, 3, 5 },
/*15*/ { 2, 4, 2, 4, 4, 6, 4, 6 },
/*16*/ { 3, 4, 3, 4, 4, 7, 4, 7 },
/*17*/ { 3, 5, 3, 5, 5, 8, 5, 8 },
/*18*/ { 3, 6, 3, 6, 6, 9, 6, 9 },
/*19*/ { 4, 6, 4, 6, 6, 10, 6, 10 },
/*20*/ { 4, 7, 4, 7, 7, 11, 7, 11 },
/*21*/ { 5, 8, 5, 8, 8, 12, 8, 12 },
/*22*/ { 6, 9, 6, 9, 9, 13, 9, 13 },
/*23*/ { 6, 10, 6, 10, 10, 16, 10, 16 },
/*24*/ { 7, 11, 7, 11, 11, 17, 11, 17 },
/*25*/ { 8, 12, 8, 12, 12, 19, 12, 19 },
/*26*/ { 9, 14, 9, 14, 14, 21, 14, 21 },
/*27*/ { 10, 15, 10, 15, 15, 25, 15, 25 },
/*28*/ { 11, 17, 11, 17, 17, 27, 17, 27 },
/*29*/ { 12, 20, 12, 20, 20, 31, 20, 31 },
/*30*/ { 14, 22, 14, 22, 22, 34, 22, 34 },
/*31*/ { 15, 24, 15, 24, 24, 39, 24, 39 },
/*32*/ { 18, 27, 18, 27, 27, 43, 27, 43 },
/*33*/ { 19, 31, 19, 31, 31, 49, 31, 49 },
/*34*/ { 22, 34, 22, 34, 34, 54, 34, 54 },
/*35*/ { 25, 40, 25, 40, 40, 62, 40, 62 },
/*36*/ { 27, 45, 27, 45, 45, 69, 45, 69 },
/*37*/ { 30, 48, 30, 48, 48, 77, 48, 77 },
/*38*/ { 36, 55, 36, 55, 55, 86, 55, 86 },
/*39*/ { 38, 62, 38, 62, 62, 99, 62, 99 },
/*40*/ { 44, 69, 44, 69, 69, 107, 69, 107 },
/*41*/ { 49, 79, 49, 79, 79, 125, 79, 125 },
/*42*/ { 55, 89, 55, 89, 89, 137, 89, 137 },
/*43*/ { 61, 96, 61, 96, 96, 154, 96, 154 },
/*44*/ { 71, 110, 71, 110, 110, 171, 110, 171 },
/*45*/ { 77, 124, 77, 124, 124, 198, 124, 198 },
/*46*/ { 88, 137, 88, 137, 137, 217, 137, 217 },
/*47*/ { 99, 159, 99, 159, 159, 250, 159, 250 },
/*48*/ { 110, 179, 110, 179, 179, 275, 179, 275 },
/*49*/ { 121, 191, 121, 191, 191, 313, 191, 313 },
/*50*/ { 143, 221, 143, 221, 221, 341, 221, 341 },
/*51*/ { 154, 245, 154, 245, 245, 402, 245, 402 },
//from here below is intra
/* 0*/ { 1, 1, 1, 1, 1, 2, 1, 2 },
/* 1*/ { 1, 1, 1, 1, 1, 2, 1, 2 },
/* 2*/ { 1, 2, 1, 2, 2, 3, 2, 3 },
/* 3*/ { 1, 2, 1, 2, 2, 3, 2, 3 },
/* 4*/ { 1, 2, 1, 2, 2, 3, 2, 3 },
/* 5*/ { 1, 2, 1, 2, 2, 4, 2, 4 },
/* 6*/ { 2, 3, 2, 3, 3, 4, 3, 4 },
/* 7*/ { 2, 3, 2, 3, 3, 5, 3, 5 },
/* 8*/ { 2, 3, 2, 3, 3, 5, 3, 5 },
/* 9*/ { 2, 4, 2, 4, 4, 6, 4, 6 },
/*10*/ { 3, 4, 3, 4, 4, 6, 4, 6 },
/*11*/ { 3, 5, 3, 5, 5, 7, 5, 7 },
/*12*/ { 3, 5, 3, 5, 5, 8, 5, 8 },
/*13*/ { 4, 6, 4, 6, 6, 9, 6, 9 },
/*14*/ { 4, 7, 4, 7, 7, 10, 7, 10 },
/*15*/ { 5, 7, 5, 7, 7, 12, 7, 12 },
/*16*/ { 5, 8, 5, 8, 8, 13, 8, 13 },
/*17*/ { 6, 9, 6, 9, 9, 15, 9, 15 },
/*18*/ { 7, 11, 7, 11, 11, 16, 11, 16 },
/*19*/ { 7, 11, 7, 11, 11, 18, 11, 18 },
/*20*/ { 9, 13, 9, 13, 13, 20, 13, 20 },
/*21*/ { 9, 15, 9, 15, 15, 24, 15, 24 },
/*22*/ { 11, 16, 11, 16, 16, 26, 16, 26 },
/*23*/ { 12, 19, 12, 19, 19, 30, 19, 30 },
/*24*/ { 13, 21, 13, 21, 21, 33, 21, 33 },
/*25*/ { 14, 23, 14, 23, 23, 37, 23, 37 },
/*26*/ { 17, 26, 17, 26, 26, 41, 26, 41 },
/*27*/ { 18, 30, 18, 30, 30, 47, 30, 47 },
/*28*/ { 21, 33, 21, 33, 33, 51, 33, 51 },
/*29*/ { 24, 38, 24, 38, 38, 59, 38, 59 },
/*30*/ { 26, 43, 26, 43, 43, 66, 43, 66 },
/*31*/ { 29, 46, 29, 46, 46, 74, 46, 74 },
/*32*/ { 34, 52, 34, 52, 52, 82, 52, 82 },
/*33*/ { 37, 59, 37, 59, 59, 94, 59, 94 },
/*34*/ { 42, 66, 42, 66, 66, 102, 66, 102 },
/*35*/ { 47, 75, 47, 75, 75, 119, 75, 119 },
/*36*/ { 52, 85, 52, 85, 85, 131, 85, 131 },
/*37*/ { 58, 92, 58, 92, 92, 147, 92, 147 },
/*38*/ { 68, 105, 68, 105, 105, 164, 105, 164 },
/*39*/ { 73, 118, 73, 118, 118, 189, 118, 189 },
/*40*/ { 84, 131, 84, 131, 131, 205, 131, 205 },
/*41*/ { 94, 151, 94, 151, 151, 239, 151, 239 },
/*42*/ { 105, 171, 105, 171, 171, 262, 171, 262 },
/*43*/ { 116, 184, 116, 184, 184, 295, 184, 295 },
/*44*/ { 136, 211, 136, 211, 211, 326, 211, 326 },
/*45*/ { 147, 236, 147, 236, 236, 377, 236, 377 },
/*46*/ { 168, 262, 168, 262, 262, 414, 262, 414 },
/*47*/ { 189, 303, 189, 303, 303, 478, 303, 478 },
/*48*/ { 211, 341, 211, 341, 341, 524, 341, 524 },
/*49*/ { 231, 364, 231, 364, 364, 597, 364, 597 },
/*50*/ { 272, 422, 272, 422, 422, 652, 422, 652 },
/*51*/ { 295, 467, 295, 467, 467, 768, 467, 768 }
};
#define ThValue 2
void TestQuant (uint32_t qp, uint8_t* pSrc, uint8_t* pPred, int16_t* pDct,
int16_t* pDctCompare, int16_t iWidth, int16_t iHeight) {
const int16_t* pMf = g_kiQuantMF[qp];
const int16_t* pFfCompareI = g_kiQuantInterFFCompare[52 + qp];
const int16_t* pFfCompareP = g_kiQuantInterFFCompare[qp];
const int16_t* pFfI = g_kiQuantInterFF[6 + qp];
const int16_t* pFfP = g_kiQuantInterFF[qp];
//quant4x4 Intra MB
RandomPixelDataGenerator (pSrc, iWidth, iHeight, iWidth);
RandomPixelDataGenerator (pPred, iWidth, iHeight, iWidth);
for (int16_t i = 0; i < 16; i++) {
pDct[i] = pSrc[i] - pPred[i];
pDctCompare[i] = pSrc[i] - pPred[i];
}
WelsQuant4x4_c (pDct, pFfI, pMf);
WelsQuant4x4_c (pDctCompare, pFfCompareI, pMf);
for (int16_t i = 0; i < 16; i++) {
int16_t iDeta = WELS_ABS (pDct[i] - pDctCompare[i]);
iDeta = (iDeta < ThValue) ? 0 : iDeta;
EXPECT_EQ (iDeta, 0);
}
//quant4x4 DC
RandomPixelDataGenerator (pSrc, iWidth, iHeight, iWidth);
RandomPixelDataGenerator (pPred, iWidth, iHeight, iWidth);
for (int16_t i = 0; i < 16; i++) {
pDct[i] = pSrc[i] - pPred[i];
pDctCompare[i] = pSrc[i] - pPred[i];
}
WelsQuant4x4Dc_c (pDct, pFfI[0] << 1, pMf[0]>>1);
WelsQuant4x4Dc_c (pDctCompare, pFfCompareI[0] << 1, pMf[0]>>1);
for (int16_t i = 0; i < 16; i++) {
int16_t iDeta = WELS_ABS (pDct[i] - pDctCompare[i]);
iDeta = (iDeta < ThValue) ? 0 : iDeta;
EXPECT_EQ (iDeta, 0);
}
//quant4x4 Inter MB
RandomPixelDataGenerator (pSrc, iWidth, iHeight, iWidth);
RandomPixelDataGenerator (pPred, iWidth, iHeight, iWidth);
for (int16_t i = 0; i < 64; i++) {
pDct[i] = pSrc[i] - pPred[i];
pDctCompare[i] = pSrc[i] - pPred[i];
}
WelsQuantFour4x4_c (pDct, pFfP, pMf);
WelsQuantFour4x4_c (pDctCompare, pFfCompareP, pMf);
for (int16_t i = 0; i < 64; i++) {
int16_t iDeta = WELS_ABS (pDct[i] - pDctCompare[i]);
iDeta = (iDeta < ThValue) ? 0 : iDeta;
EXPECT_EQ (iDeta, 0);
}
}
TEST (EncoderMbTest, TestQuantTable) {
CMemoryAlign cMemoryAlign (0);
int16_t iWidth = 16;
int16_t iHeight = 16;
uint8_t* pSrc = (uint8_t*)cMemoryAlign.WelsMalloc (iWidth * iHeight, "quant_src");
uint8_t* pPred = (uint8_t*)cMemoryAlign.WelsMalloc (iWidth * iHeight, "quant_pred");
int16_t* pDct = (int16_t*)cMemoryAlign.WelsMalloc (64 * sizeof (int16_t), "Dct Buffer");
int16_t* pDctCompare = (int16_t*)cMemoryAlign.WelsMalloc (64 * sizeof (int16_t), "DctCompare Buffer");
for (int32_t iQP = 0; iQP < 51; iQP++) {
TestQuant (iQP, pSrc, pPred, pDct, pDctCompare, iWidth, iHeight);
}
cMemoryAlign.WelsFree (pSrc, "quant_src");
cMemoryAlign.WelsFree (pPred, "quant_pred");
cMemoryAlign.WelsFree (pDct, "Dct Buffer");
cMemoryAlign.WelsFree (pDctCompare, "DctCompare Buffer");
}
| bsd-2-clause |
andrewjylee/omniplay | eglibc-2.15/libio/bug-ungetc.c | 94 | 1255 | /* Test program for ungetc/ftell interaction bug. */
#include <stdio.h>
static void do_prepare (void);
#define PREPARE(argc, argv) do_prepare ()
static int do_test (void);
#define TEST_FUNCTION do_test ()
#include <test-skeleton.c>
static const char pattern[] = "12345";
static char *temp_file;
static void
do_prepare (void)
{
int fd = create_temp_file ("bug-ungetc.", &temp_file);
if (fd == -1)
{
printf ("cannot create temporary file: %m\n");
exit (1);
}
write (fd, pattern, sizeof (pattern));
close (fd);
}
static int
do_test (void)
{
int i;
FILE *f;
char buf[10];
long offset, diff;
int result = 0;
f = fopen (temp_file, "rw");
rewind (f);
for (i = 0; i < 3; i++)
printf ("%c\n", getc (f));
offset = ftell (f);
printf ("offset = %ld\n", offset);
if (ungetc ('4', f) != '4')
{
printf ("ungetc failed\n");
abort ();
}
printf ("offset after ungetc = %ld\n", ftell (f));
i = fread ((void *) buf, 4, (size_t) 1, f);
printf ("read %d (%c), offset = %ld\n", i, buf[0], ftell (f));
diff = ftell (f) - offset;
if (diff != 3)
{
printf ("ftell did not update properly. got %ld, expected 3\n", diff);
result = 1;
}
fclose (f);
return result;
}
| bsd-2-clause |
pinghe/nginx-openresty-windows | nginx/objs/lib_x64/openssl-1.0.1p/apps/errstr.c | 125 | 4835 | /* apps/errstr.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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 cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apps.h"
#include <openssl/bio.h>
#include <openssl/lhash.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#undef PROG
#define PROG errstr_main
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
int i, ret = 0;
char buf[256];
unsigned long l;
apps_startup();
if (bio_err == NULL)
if ((bio_err = BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
SSL_load_error_strings();
if ((argc > 1) && (strcmp(argv[1], "-stats") == 0)) {
BIO *out = NULL;
out = BIO_new(BIO_s_file());
if ((out != NULL) && BIO_set_fp(out, stdout, BIO_NOCLOSE)) {
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
lh_ERR_STRING_DATA_node_stats_bio(ERR_get_string_table(), out);
lh_ERR_STRING_DATA_stats_bio(ERR_get_string_table(), out);
lh_ERR_STRING_DATA_node_usage_stats_bio(ERR_get_string_table(),
out);
}
if (out != NULL)
BIO_free_all(out);
argc--;
argv++;
}
for (i = 1; i < argc; i++) {
if (sscanf(argv[i], "%lx", &l)) {
ERR_error_string_n(l, buf, sizeof buf);
printf("%s\n", buf);
} else {
printf("%s: bad error code\n", argv[i]);
printf("usage: errstr [-stats] <errno> ...\n");
ret++;
}
}
apps_shutdown();
OPENSSL_EXIT(ret);
}
| bsd-2-clause |
avaitla/Haskell-to-C---Bridge | gccxml/GCC/libiberty/pex-unix.c | 1 | 13625 | /* Utilities to execute a program in a subprocess (possibly linked by pipes
with other subprocesses), and wait for it. Generic Unix version
(also used for UWIN and VMS).
Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
Free Software Foundation, Inc.
This file is part of the libiberty library.
Libiberty is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
Libiberty is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with libiberty; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
Boston, MA 02110-1301, USA. */
#include "config.h"
#include "libiberty.h"
#include "pex-common.h"
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#ifdef NEED_DECLARATION_ERRNO
extern int errno;
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/types.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_GETRUSAGE
#include <sys/time.h>
#include <sys/resource.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef vfork /* Autoconf may define this to fork for us. */
# define VFORK_STRING "fork"
#else
# define VFORK_STRING "vfork"
#endif
#ifdef HAVE_VFORK_H
#include <vfork.h>
#endif
#ifdef VMS
#define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
#endif /* VMS */
/* File mode to use for private and world-readable files. */
#if defined (S_IRUSR) && defined (S_IWUSR) && defined (S_IRGRP) && defined (S_IWGRP) && defined (S_IROTH) && defined (S_IWOTH)
#define PUBLIC_MODE \
(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
#else
#define PUBLIC_MODE 0666
#endif
/* Get the exit status of a particular process, and optionally get the
time that it took. This is simple if we have wait4, slightly
harder if we have waitpid, and is a pain if we only have wait. */
static pid_t pex_wait (struct pex_obj *, pid_t, int *, struct pex_time *);
#ifdef HAVE_WAIT4
static pid_t
pex_wait (struct pex_obj *obj ATTRIBUTE_UNUSED, pid_t pid, int *status,
struct pex_time *time)
{
pid_t ret;
struct rusage r;
#ifdef HAVE_WAITPID
if (time == NULL)
return waitpid (pid, status, 0);
#endif
ret = wait4 (pid, status, 0, &r);
if (time != NULL)
{
time->user_seconds = r.ru_utime.tv_sec;
time->user_microseconds= r.ru_utime.tv_usec;
time->system_seconds = r.ru_stime.tv_sec;
time->system_microseconds= r.ru_stime.tv_usec;
}
return ret;
}
#else /* ! defined (HAVE_WAIT4) */
#ifdef HAVE_WAITPID
#ifndef HAVE_GETRUSAGE
static pid_t
pex_wait (struct pex_obj *obj ATTRIBUTE_UNUSED, pid_t pid, int *status,
struct pex_time *time)
{
if (time != NULL)
memset (time, 0, sizeof (struct pex_time));
return waitpid (pid, status, 0);
}
#else /* defined (HAVE_GETRUSAGE) */
static pid_t
pex_wait (struct pex_obj *obj ATTRIBUTE_UNUSED, pid_t pid, int *status,
struct pex_time *time)
{
struct rusage r1, r2;
pid_t ret;
if (time == NULL)
return waitpid (pid, status, 0);
getrusage (RUSAGE_CHILDREN, &r1);
ret = waitpid (pid, status, 0);
if (ret < 0)
return ret;
getrusage (RUSAGE_CHILDREN, &r2);
time->user_seconds = r2.ru_utime.tv_sec - r1.ru_utime.tv_sec;
time->user_microseconds = r2.ru_utime.tv_usec - r1.ru_utime.tv_usec;
if (r2.ru_utime.tv_usec < r1.ru_utime.tv_usec)
{
--time->user_seconds;
time->user_microseconds += 1000000;
}
time->system_seconds = r2.ru_stime.tv_sec - r1.ru_stime.tv_sec;
time->system_microseconds = r2.ru_stime.tv_usec - r1.ru_stime.tv_usec;
if (r2.ru_stime.tv_usec < r1.ru_stime.tv_usec)
{
--time->system_seconds;
time->system_microseconds += 1000000;
}
return ret;
}
#endif /* defined (HAVE_GETRUSAGE) */
#else /* ! defined (HAVE_WAITPID) */
struct status_list
{
struct status_list *next;
pid_t pid;
int status;
struct pex_time time;
};
static pid_t
pex_wait (struct pex_obj *obj, pid_t pid, int *status, struct pex_time *time)
{
struct status_list **pp;
for (pp = (struct status_list **) &obj->sysdep;
*pp != NULL;
pp = &(*pp)->next)
{
if ((*pp)->pid == pid)
{
struct status_list *p;
p = *pp;
*status = p->status;
if (time != NULL)
*time = p->time;
*pp = p->next;
free (p);
return pid;
}
}
while (1)
{
pid_t cpid;
struct status_list *psl;
struct pex_time pt;
#ifdef HAVE_GETRUSAGE
struct rusage r1, r2;
#endif
if (time != NULL)
{
#ifdef HAVE_GETRUSAGE
getrusage (RUSAGE_CHILDREN, &r1);
#else
memset (&pt, 0, sizeof (struct pex_time));
#endif
}
cpid = wait (status);
#ifdef HAVE_GETRUSAGE
if (time != NULL && cpid >= 0)
{
getrusage (RUSAGE_CHILDREN, &r2);
pt.user_seconds = r2.ru_utime.tv_sec - r1.ru_utime.tv_sec;
pt.user_microseconds = r2.ru_utime.tv_usec - r1.ru_utime.tv_usec;
if (pt.user_microseconds < 0)
{
--pt.user_seconds;
pt.user_microseconds += 1000000;
}
pt.system_seconds = r2.ru_stime.tv_sec - r1.ru_stime.tv_sec;
pt.system_microseconds = r2.ru_stime.tv_usec - r1.ru_stime.tv_usec;
if (pt.system_microseconds < 0)
{
--pt.system_seconds;
pt.system_microseconds += 1000000;
}
}
#endif
if (cpid < 0 || cpid == pid)
{
if (time != NULL)
*time = pt;
return cpid;
}
psl = XNEW (struct status_list);
psl->pid = cpid;
psl->status = *status;
if (time != NULL)
psl->time = pt;
psl->next = (struct status_list *) obj->sysdep;
obj->sysdep = (void *) psl;
}
}
#endif /* ! defined (HAVE_WAITPID) */
#endif /* ! defined (HAVE_WAIT4) */
static void pex_child_error (struct pex_obj *, const char *, const char *, int)
ATTRIBUTE_NORETURN;
static int pex_unix_open_read (struct pex_obj *, const char *, int);
static int pex_unix_open_write (struct pex_obj *, const char *, int);
static long pex_unix_exec_child (struct pex_obj *, int, const char *,
char * const *, char * const *,
int, int, int, int,
const char **, int *);
static int pex_unix_close (struct pex_obj *, int);
static int pex_unix_wait (struct pex_obj *, long, int *, struct pex_time *,
int, const char **, int *);
static int pex_unix_pipe (struct pex_obj *, int *, int);
static FILE *pex_unix_fdopenr (struct pex_obj *, int, int);
static FILE *pex_unix_fdopenw (struct pex_obj *, int, int);
static void pex_unix_cleanup (struct pex_obj *);
/* The list of functions we pass to the common routines. */
const struct pex_funcs funcs =
{
pex_unix_open_read,
pex_unix_open_write,
pex_unix_exec_child,
pex_unix_close,
pex_unix_wait,
pex_unix_pipe,
pex_unix_fdopenr,
pex_unix_fdopenw,
pex_unix_cleanup
};
/* Return a newly initialized pex_obj structure. */
struct pex_obj *
pex_init (int flags, const char *pname, const char *tempbase)
{
return pex_init_common (flags, pname, tempbase, &funcs);
}
/* Open a file for reading. */
static int
pex_unix_open_read (struct pex_obj *obj ATTRIBUTE_UNUSED, const char *name,
int binary ATTRIBUTE_UNUSED)
{
return open (name, O_RDONLY);
}
/* Open a file for writing. */
static int
pex_unix_open_write (struct pex_obj *obj ATTRIBUTE_UNUSED, const char *name,
int binary ATTRIBUTE_UNUSED)
{
/* Note that we can't use O_EXCL here because gcc may have already
created the temporary file via make_temp_file. */
return open (name, O_WRONLY | O_CREAT | O_TRUNC, PUBLIC_MODE);
}
/* Close a file. */
static int
pex_unix_close (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd)
{
return close (fd);
}
/* Report an error from a child process. We don't use stdio routines,
because we might be here due to a vfork call. */
static void
pex_child_error (struct pex_obj *obj, const char *executable,
const char *errmsg, int err)
{
#define writeerr(s) write (STDERR_FILE_NO, s, strlen (s))
writeerr (obj->pname);
writeerr (": error trying to exec '");
writeerr (executable);
writeerr ("': ");
writeerr (errmsg);
writeerr (": ");
writeerr (xstrerror (err));
writeerr ("\n");
_exit (-1);
}
/* Execute a child. */
extern char **environ;
static long
pex_unix_exec_child (struct pex_obj *obj, int flags, const char *executable,
char * const * argv, char * const * env,
int in, int out, int errdes,
int toclose, const char **errmsg, int *err)
{
pid_t pid;
/* We declare these to be volatile to avoid warnings from gcc about
them being clobbered by vfork. */
volatile int sleep_interval;
volatile int retries;
sleep_interval = 1;
pid = -1;
for (retries = 0; retries < 4; ++retries)
{
pid = vfork ();
if (pid >= 0)
break;
sleep (sleep_interval);
sleep_interval *= 2;
}
switch (pid)
{
case -1:
*err = errno;
*errmsg = VFORK_STRING;
return -1;
case 0:
/* Child process. */
if (in != STDIN_FILE_NO)
{
if (dup2 (in, STDIN_FILE_NO) < 0)
pex_child_error (obj, executable, "dup2", errno);
if (close (in) < 0)
pex_child_error (obj, executable, "close", errno);
}
if (out != STDOUT_FILE_NO)
{
if (dup2 (out, STDOUT_FILE_NO) < 0)
pex_child_error (obj, executable, "dup2", errno);
if (close (out) < 0)
pex_child_error (obj, executable, "close", errno);
}
if (errdes != STDERR_FILE_NO)
{
if (dup2 (errdes, STDERR_FILE_NO) < 0)
pex_child_error (obj, executable, "dup2", errno);
if (close (errdes) < 0)
pex_child_error (obj, executable, "close", errno);
}
if (toclose >= 0)
{
if (close (toclose) < 0)
pex_child_error (obj, executable, "close", errno);
}
if ((flags & PEX_STDERR_TO_STDOUT) != 0)
{
if (dup2 (STDOUT_FILE_NO, STDERR_FILE_NO) < 0)
pex_child_error (obj, executable, "dup2", errno);
}
if (env)
environ = (char**) env;
if ((flags & PEX_SEARCH) != 0)
{
execvp (executable, argv);
pex_child_error (obj, executable, "execvp", errno);
}
else
{
execv (executable, argv);
pex_child_error (obj, executable, "execv", errno);
}
/* NOTREACHED */
return -1;
default:
/* Parent process. */
if (in != STDIN_FILE_NO)
{
if (close (in) < 0)
{
*err = errno;
*errmsg = "close";
return -1;
}
}
if (out != STDOUT_FILE_NO)
{
if (close (out) < 0)
{
*err = errno;
*errmsg = "close";
return -1;
}
}
if (errdes != STDERR_FILE_NO)
{
if (close (errdes) < 0)
{
*err = errno;
*errmsg = "close";
return -1;
}
}
return (long) pid;
}
}
/* Wait for a child process to complete. */
static int
pex_unix_wait (struct pex_obj *obj, long pid, int *status,
struct pex_time *time, int done, const char **errmsg,
int *err)
{
/* If we are cleaning up when the caller didn't retrieve process
status for some reason, encourage the process to go away. */
if (done)
kill (pid, SIGTERM);
if (pex_wait (obj, pid, status, time) < 0)
{
*err = errno;
*errmsg = "wait";
return -1;
}
return 0;
}
/* Create a pipe. */
static int
pex_unix_pipe (struct pex_obj *obj ATTRIBUTE_UNUSED, int *p,
int binary ATTRIBUTE_UNUSED)
{
return pipe (p);
}
/* Get a FILE pointer to read from a file descriptor. */
static FILE *
pex_unix_fdopenr (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd,
int binary ATTRIBUTE_UNUSED)
{
return fdopen (fd, "r");
}
static FILE *
pex_unix_fdopenw (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd,
int binary ATTRIBUTE_UNUSED)
{
if (fcntl (fd, F_SETFD, FD_CLOEXEC) < 0)
return NULL;
return fdopen (fd, "w");
}
static void
pex_unix_cleanup (struct pex_obj *obj ATTRIBUTE_UNUSED)
{
#if !defined (HAVE_WAIT4) && !defined (HAVE_WAITPID)
while (obj->sysdep != NULL)
{
struct status_list *this;
struct status_list *next;
this = (struct status_list *) obj->sysdep;
next = this->next;
free (this);
obj->sysdep = (void *) next;
}
#endif
}
| bsd-3-clause |
aam/skiaex | app/main.cpp | 1 | 9747 | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This sample progam demonstrates how to use Skia and HarfBuzz to
// produce a PDF file from UTF-8 text in stdin.
#include <cassert>
#include <iostream>
#include <map>
#include <string>
#include <hb-ot.h>
#include "SkCanvas.h"
#include "SkDocument.h"
#include "SkStream.h"
#include "SkTextBlob.h"
#include "SkTypeface.h"
struct BaseOption {
std::string selector;
std::string description;
virtual void set(std::string _value) = 0;
virtual std::string valueToString() = 0;
BaseOption(std::string _selector, std::string _description) :
selector(_selector),
description(_description) {}
virtual ~BaseOption() {}
};
template <class T> struct Option : BaseOption {
T value;
Option(std::string selector, std::string description, T defaultValue) :
BaseOption(selector, description),
value(defaultValue) {}
};
struct DoubleOption : Option<double> {
virtual void set(std::string _value) {
value = atof(_value.c_str());
}
virtual std::string valueToString() {
return std::to_string(value);
}
DoubleOption(std::string selector, std::string description, double defaultValue) :
Option<double>(selector, description, defaultValue) {}
};
struct SkStringOption : Option<SkString> {
virtual void set(std::string _value) {
value = _value.c_str();
}
virtual std::string valueToString() {
return value.c_str();
}
SkStringOption(std::string selector, std::string description, SkString defaultValue) :
Option<SkString>(selector, description, defaultValue) {}
};
struct StdStringOption : Option<std::string> {
virtual void set(std::string _value) {
value = _value;
}
virtual std::string valueToString() {
return value;
}
StdStringOption(std::string selector, std::string description, std::string defaultValue) :
Option<std::string>(selector, description, defaultValue) {}
};
struct Config {
DoubleOption *page_width = new DoubleOption("-w", "Page width", 600.0f);
DoubleOption *page_height = new DoubleOption("-h", "Page height", 800.0f);
SkStringOption *title = new SkStringOption("-t", "PDF title", SkString("---"));
SkStringOption *author = new SkStringOption("-a", "PDF author", SkString("---"));
SkStringOption *subject = new SkStringOption("-k", "PDF subject", SkString("---"));
SkStringOption *keywords = new SkStringOption("-c", "PDF keywords", SkString("---"));
SkStringOption *creator = new SkStringOption("-t", "PDF creator", SkString("---"));
StdStringOption *font_file = new StdStringOption("-f", ".ttf font file", "fonts/DejaVuSans.ttf");
DoubleOption *font_size = new DoubleOption("-z", "Font size", 8.0f);
DoubleOption *left_margin = new DoubleOption("-m", "Left margin", 20.0f);
DoubleOption *line_spacing_ratio = new DoubleOption("-h", "Line spacing ratio", 1.5f);
StdStringOption *output_file_name = new StdStringOption("-o", ".pdf output file name", "out-skiahf.pdf");
std::map<std::string, BaseOption*> options = {
{ page_width->selector, page_width },
{ page_height->selector, page_height },
{ title->selector, title },
{ author->selector, author },
{ subject->selector, subject },
{ keywords->selector, keywords },
{ creator->selector, creator },
{ font_file->selector, font_file },
{ font_size->selector, font_size },
{ left_margin->selector, left_margin },
{ line_spacing_ratio->selector, line_spacing_ratio },
{ output_file_name->selector, output_file_name },
};
Config(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::string option_selector(argv[i]);
auto it = options.find(option_selector);
if (it != options.end()) {
if (i >= argc) {
break;
}
const char *option_value = argv[i + 1];
it->second->set(option_value);
i++;
} else {
printf("Ignoring unrecognized option: %s.\n", argv[i]);
printf("Usage: %s {option value}\n", argv[0]);
printf("\tTakes text from stdin and produces pdf file.\n");
printf("Supported options:\n");
for (auto it = options.begin(); it != options.end(); ++it) {
printf("\t%s\t%s (%s)\n", it->first.c_str(),
it->second->description.c_str(),
it->second->valueToString().c_str());
}
exit(-1);
}
}
} // end of Config::Config
};
const double FONT_SIZE_SCALE = 64.0f;
struct Face {
struct HBFDel { void operator()(hb_face_t* f) { hb_face_destroy(f); } };
std::unique_ptr<hb_face_t, HBFDel> fHarfBuzzFace;
sk_sp<SkTypeface> fSkiaTypeface;
Face(const char* path, int index) {
// fairly portable mmap impl
auto data = SkData::MakeFromFileName(path);
assert(data);
if (!data) { return; }
fSkiaTypeface = SkTypeface::MakeFromStream(
new SkMemoryStream(data), index);
assert(fSkiaTypeface);
if (!fSkiaTypeface) { return; }
auto destroy = [](void *d) { static_cast<SkData*>(d)->unref(); };
const char* bytes = (const char*)data->data();
unsigned int size = (unsigned int)data->size();
hb_blob_t* blob = hb_blob_create(bytes,
size,
HB_MEMORY_MODE_READONLY,
data.release(),
destroy);
assert(blob);
hb_blob_make_immutable(blob);
hb_face_t* face = hb_face_create(blob, (unsigned)index);
hb_blob_destroy(blob);
assert(face);
if (!face) {
fSkiaTypeface.reset();
return;
}
hb_face_set_index(face, (unsigned)index);
hb_face_set_upem(face, fSkiaTypeface->getUnitsPerEm());
fHarfBuzzFace.reset(face);
}
};
class Placement {
public:
Placement(Config &_config, SkWStream* outputStream) : config(_config) {
face = new Face(config.font_file->value.c_str(), 0 /* index */);
hb_font = hb_font_create(face->fHarfBuzzFace.get());
hb_font_set_scale(hb_font,
FONT_SIZE_SCALE * config.font_size->value,
FONT_SIZE_SCALE * config.font_size->value);
hb_ot_font_set_funcs(hb_font);
SkDocument::PDFMetadata pdf_info;
pdf_info.fTitle = config.title->value;
pdf_info.fAuthor = config.author->value;
pdf_info.fSubject = config.subject->value;
pdf_info.fKeywords = config.keywords->value;
pdf_info.fCreator = config.creator->value;
SkTime::DateTime now;
SkTime::GetDateTime(&now);
pdf_info.fCreation.fEnabled = true;
pdf_info.fCreation.fDateTime = now;
pdf_info.fModified.fEnabled = true;
pdf_info.fModified.fDateTime = now;
pdfDocument = SkDocument::MakePDF(outputStream, SK_ScalarDefaultRasterDPI,
pdf_info, nullptr, true);
assert(pdfDocument);
white_paint.setColor(SK_ColorWHITE);
glyph_paint.setFlags(
SkPaint::kAntiAlias_Flag |
SkPaint::kSubpixelText_Flag); // ... avoid waggly text when rotating.
glyph_paint.setColor(SK_ColorBLACK);
glyph_paint.setTextSize(config.font_size->value);
glyph_paint.setTypeface(face->fSkiaTypeface);
glyph_paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
NewPage();
} // end of Placement
~Placement() {
delete face;
hb_font_destroy (hb_font);
}
void WriteLine(const char *text) {
/* Create hb-buffer and populate. */
hb_buffer_t *hb_buffer = hb_buffer_create ();
hb_buffer_add_utf8 (hb_buffer, text, -1, 0, -1);
hb_buffer_guess_segment_properties (hb_buffer);
/* Shape it! */
hb_shape (hb_font, hb_buffer, NULL, 0);
DrawGlyphs(hb_buffer);
hb_buffer_destroy (hb_buffer);
// Advance to the next line.
current_y += config.line_spacing_ratio->value * config.font_size->value;
if (current_y > config.page_height->value) {
pdfDocument->endPage();
NewPage();
}
}
void Close() {
pdfDocument->close();
}
private:
Config config;
Face *face;
hb_font_t *hb_font;
sk_sp<SkDocument> pdfDocument;
SkCanvas* pageCanvas;
SkPaint white_paint;
SkPaint glyph_paint;
double current_x;
double current_y;
void NewPage() {
pageCanvas = pdfDocument->beginPage(config.page_width->value, config.page_height->value);
pageCanvas->drawPaint(white_paint);
current_x = config.left_margin->value;
current_y = config.line_spacing_ratio->value * config.font_size->value;
}
bool DrawGlyphs(hb_buffer_t *hb_buffer) {
SkTextBlobBuilder textBlobBuilder;
unsigned len = hb_buffer_get_length (hb_buffer);
if (len == 0) {
return true;
}
hb_glyph_info_t *info = hb_buffer_get_glyph_infos (hb_buffer, NULL);
hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (hb_buffer, NULL);
auto runBuffer = textBlobBuilder.allocRunPos(glyph_paint, len);
double x = 0;
double y = 0;
for (unsigned int i = 0; i < len; i++)
{
runBuffer.glyphs[i] = info[i].codepoint;
reinterpret_cast<SkPoint*>(runBuffer.pos)[i] = SkPoint::Make(
x + pos[i].x_offset / FONT_SIZE_SCALE,
y - pos[i].y_offset / FONT_SIZE_SCALE);
x += pos[i].x_advance / FONT_SIZE_SCALE;
y += pos[i].y_advance / FONT_SIZE_SCALE;
}
pageCanvas->drawTextBlob(textBlobBuilder.make(), current_x, current_y, glyph_paint);
return true;
} // end of DrawGlyphs
}; // end of Placement class
int main(int argc, char** argv) {
Config config(argc, argv);
Placement placement(config, new SkFILEWStream(config.output_file_name->value.c_str()));
for (std::string line; std::getline(std::cin, line);) {
placement.WriteLine(line.c_str());
}
placement.Close();
return 0;
}
| bsd-3-clause |
ekawahyu/MSP430Ware | examples/MSP430FR5xx_6xx/eusci_a_uart/eusci_a_uart_ex1_loopbackAdvanced.c | 1 | 7164 | /* --COPYRIGHT--,BSD
* Copyright (c) 2014, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* --/COPYRIGHT--*/
//******************************************************************************
//! EUSCI_A0 External Loopback test using EUSCI_A_UART_initAdvanced API
//!
//! Description: This demo connects TX to RX of the MSP430 UART
//! The example code shows proper initialization of registers
//! and interrupts to receive and transmit data.
//!
//! ACLK = BRCLK = 32.768kHz, MCLK = SMCLK = DCO = ~1MHz
//!
//!
//! Tested on MSP430FR5969
//! -----------------
//! RST -| P2.0/UCA0TXD|----|
//! | | |
//! | | |
//! | P2.1/UCA0RXD|----|
//! | |
//!
//! This example uses the following peripherals and I/O signals. You must
//! review these and change as needed for your own board:
//! - UART peripheral
//! - GPIO Port peripheral (for UART pins)
//! - UCA0TXD
//! - UCA0RXD
//!
//! This example uses the following interrupt handlers. To use this example
//! in your own application you must add these interrupt handlers to your
//! vector table.
//! - USCI_A0_VECTOR.
//******************************************************************************
#include "driverlib.h"
uint16_t i;
uint8_t RXData = 0, TXData = 0;
uint8_t check = 0;
void main(void)
{
// stop watchdog
WDT_A_hold(WDT_A_BASE);
// LFXT Setup
//Set PJ.4 and PJ.5 as Primary Module Function Input.
/*
* Select Port J
* Set Pin 4, 5 to input Primary Module Function, LFXT.
*/
GPIO_setAsPeripheralModuleFunctionInputPin(
GPIO_PORT_PJ,
GPIO_PIN4 + GPIO_PIN5,
GPIO_PRIMARY_MODULE_FUNCTION
);
//Set DCO frequency to 1 MHz
CS_setDCOFreq(CS_DCORSEL_0, CS_DCOFSEL_0);
//Set external clock frequency to 32.768 KHz
CS_setExternalClockSource(32768, 0);
//Set ACLK=LFXT
CS_clockSignalInit(CS_ACLK, CS_LFXTCLK_SELECT, CS_CLOCK_DIVIDER_1);
//Set SMCLK = DCO with frequency divider of 1
CS_clockSignalInit(CS_SMCLK, CS_DCOCLK_SELECT, CS_CLOCK_DIVIDER_1);
//Set MCLK = DCO with frequency divider of 1
CS_clockSignalInit(CS_MCLK, CS_DCOCLK_SELECT, CS_CLOCK_DIVIDER_1);
//Start XT1 with no time out
CS_LFXTStart(CS_LFXTDRIVE_0);
// Configure UART pins
//Set P2.0 and P2.1 as Secondary Module Function Input.
/*
* Select Port 2d
* Set Pin 0, 1 to input Secondary Module Function, (UCA0TXD/UCA0SIMO, UCA0RXD/UCA0SOMI).
*/
GPIO_setAsPeripheralModuleFunctionInputPin(
GPIO_PORT_P2,
GPIO_PIN0 + GPIO_PIN1,
GPIO_SECONDARY_MODULE_FUNCTION
);
/*
* Disable the GPIO power-on default high-impedance mode to activate
* previously configured port settings
*/
PMM_unlockLPM5();
// Configure UART
if ( STATUS_FAIL == EUSCI_A_UART_initAdvance(EUSCI_A0_BASE,
EUSCI_A_UART_CLOCKSOURCE_ACLK,
15,
0,
68,
EUSCI_A_UART_NO_PARITY,
EUSCI_A_UART_LSB_FIRST,
EUSCI_A_UART_ONE_STOP_BIT,
EUSCI_A_UART_MODE,
EUSCI_A_UART_LOW_FREQUENCY_BAUDRATE_GENERATION ))
return;
EUSCI_A_UART_enable(EUSCI_A0_BASE);
EUSCI_A_UART_clearInterruptFlag(EUSCI_A0_BASE,
EUSCI_A_UART_RECEIVE_INTERRUPT);
// Enable USCI_A0 RX interrupt
EUSCI_A_UART_enableInterrupt(EUSCI_A0_BASE,
EUSCI_A_UART_RECEIVE_INTERRUPT); // Enable interrupt
__enable_interrupt();
while (1) {
TXData = TXData + 1; // Increment TX data
// Load data onto buffer
EUSCI_A_UART_transmitData(EUSCI_A0_BASE,
TXData);
while (check != 1) ;
check = 0;
}
}
//******************************************************************************
//
//This is the USCI_A0 interrupt vector service routine.
//
//******************************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=USCI_A0_VECTOR
__interrupt
#elif defined(__GNUC__)
__attribute__((interrupt(USCI_A0_VECTOR)))
#endif
void USCI_A0_ISR(void)
{
switch (__even_in_range(UCA0IV, USCI_UART_UCTXCPTIFG)) {
case USCI_NONE: break;
case USCI_UART_UCRXIFG:
RXData = EUSCI_A_UART_receiveData(EUSCI_A0_BASE);
if (!(RXData == TXData)) // Check value
while (1) ;
check = 1;
break;
case USCI_UART_UCTXIFG: break;
case USCI_UART_UCSTTIFG: break;
case USCI_UART_UCTXCPTIFG: break;
}
}
| bsd-3-clause |
DominicDirkx/tudat | Tudat/Astrodynamics/Ephemerides/rotationalEphemeris.cpp | 1 | 5250 | /* Copyright (c) 2010-2018, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#include "Tudat/Astrodynamics/Ephemerides/rotationalEphemeris.h"
#include "Tudat/Mathematics/BasicMathematics/linearAlgebra.h"
namespace tudat
{
namespace ephemerides
{
//! Function to calculate the rotational velocity vector of frame B w.r.t frame A.
Eigen::Vector3d getRotationalVelocityVectorInBaseFrameFromMatrices(
const Eigen::Matrix3d& rotationToTargetFrame,
const Eigen::Matrix3d& rotationMatrixToGlobalFrameDerivative )
{
Eigen::Matrix3d crossProductMatrix =
rotationMatrixToGlobalFrameDerivative * rotationToTargetFrame;
return ( Eigen::Vector3d( ) << crossProductMatrix( 2, 1 ),
crossProductMatrix( 0, 2 ), crossProductMatrix( 1, 0 ) ).finished( );
}
//! Function to calculate the time derivative of rotation matrix from frame A to frame B.
Eigen::Matrix3d getDerivativeOfRotationMatrixToFrame(
const Eigen::Matrix3d& rotationToTargetFrame,
const Eigen::Vector3d& rotationalVelocityVectorOfTargetFrameInBaseFrame )
{
return linear_algebra::getCrossProductMatrix(
-rotationToTargetFrame * rotationalVelocityVectorOfTargetFrameInBaseFrame ) *
rotationToTargetFrame;
}
//! Get rotation quaternion from target frame to base frame.
template< >
Eigen::Quaterniond RotationalEphemeris::getRotationToBaseFrameTemplated< double >(
const double timeSinceEpoch )
{
return getRotationToBaseFrame( timeSinceEpoch );
}
//! Get rotation quaternion from target frame to base frame.
template< >
Eigen::Quaterniond RotationalEphemeris::getRotationToBaseFrameTemplated< Time >(
const Time timeSinceEpoch )
{
return getRotationToBaseFrameFromExtendedTime( timeSinceEpoch );
}
//! Get rotation quaternion to target frame from base frame.
template< >
Eigen::Quaterniond RotationalEphemeris::getRotationToTargetFrameTemplated< double >(
const double secondsSinceEpoch )
{
return getRotationToTargetFrame( secondsSinceEpoch );
}
//! Get rotation quaternion to target frame from base frame.
template< >
Eigen::Quaterniond RotationalEphemeris::getRotationToTargetFrameTemplated< Time >(
const Time secondsSinceEpoch )
{
return getRotationToTargetFrameFromExtendedTime( secondsSinceEpoch );
}
//! Function to calculate the derivative of the rotation matrix from target frame to original frame.
template< >
Eigen::Matrix3d RotationalEphemeris::getDerivativeOfRotationToBaseFrameTemplated< double >(
const double timeSinceEpoch )
{
return getDerivativeOfRotationToBaseFrame( timeSinceEpoch );
}
//! Function to calculate the derivative of the rotation matrix from target frame to original frame.
template< >
Eigen::Matrix3d RotationalEphemeris::getDerivativeOfRotationToBaseFrameTemplated< Time >(
const Time timeSinceEpoch )
{
return getDerivativeOfRotationToBaseFrameFromExtendedTime( timeSinceEpoch );
}
//! Function to calculate the derivative of the rotation matrix to target frame from original frame.
template< >
Eigen::Matrix3d RotationalEphemeris::getDerivativeOfRotationToTargetFrameTemplated< double >(
const double secondsSinceEpoch )
{
return getDerivativeOfRotationToTargetFrame( secondsSinceEpoch );
}
//! Function to calculate the derivative of the rotation matrix to target frame from original frame.
template< >
Eigen::Matrix3d RotationalEphemeris::getDerivativeOfRotationToTargetFrameTemplated< Time >(
const Time secondsSinceEpoch )
{
return getDerivativeOfRotationToTargetFrameFromExtendedTime( secondsSinceEpoch );
}
//! Function to calculate the full rotational state at given time
template< >
void RotationalEphemeris::getFullRotationalQuantitiesToTargetFrameTemplated< double >(
Eigen::Quaterniond& currentRotationToLocalFrame,
Eigen::Matrix3d& currentRotationToLocalFrameDerivative,
Eigen::Vector3d& currentAngularVelocityVectorInGlobalFrame,
const double timeSinceEpoch )
{
getFullRotationalQuantitiesToTargetFrame(
currentRotationToLocalFrame, currentRotationToLocalFrameDerivative, currentAngularVelocityVectorInGlobalFrame,
timeSinceEpoch );
}
//! Function to calculate the full rotational state at given time
template< >
void RotationalEphemeris::getFullRotationalQuantitiesToTargetFrameTemplated< Time >(
Eigen::Quaterniond& currentRotationToLocalFrame,
Eigen::Matrix3d& currentRotationToLocalFrameDerivative,
Eigen::Vector3d& currentAngularVelocityVectorInGlobalFrame,
const Time timeSinceEpoch )
{
getFullRotationalQuantitiesToTargetFrameFromExtendedTime(
currentRotationToLocalFrame, currentRotationToLocalFrameDerivative, currentAngularVelocityVectorInGlobalFrame,
timeSinceEpoch );
}
} // namespace tudat
} // namespace ephemerides
| bsd-3-clause |
hlzz/dotfiles | graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Parameterization_plugin.cpp | 1 | 5885 | #include <QApplication>
#include <QAction>
#include <QMainWindow>
#include <QStringList>
#include "Scene_polyhedron_item.h"
#include "Scene_textured_polyhedron_item.h"
#include "Textured_polyhedron_type.h"
#include "Polyhedron_type.h"
#include <QTime>
#include <CGAL/Parameterization_polyhedron_adaptor_3.h>
#include <CGAL/parameterize.h>
#include <CGAL/Discrete_conformal_map_parameterizer_3.h>
#include <CGAL/LSCM_parameterizer_3.h>
#include <CGAL/Two_vertices_parameterizer_3.h>
#include <CGAL/Textured_polyhedron_builder.h>
#include <iostream>
#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>
#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>
typedef Kernel::FT FT;
using namespace CGAL::Three;
class Polyhedron_demo_parameterization_plugin :
public QObject,
public Polyhedron_demo_plugin_helper
{
Q_OBJECT
Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)
Q_PLUGIN_METADATA(IID "com.geometryfactory.PolyhedronDemo.PluginInterface/1.0")
public:
// used by Polyhedron_demo_plugin_helper
QStringList actionsNames() const {
return QStringList() << "actionMVC"
<< "actionDCP"
<< "actionLSC";
}
void init(QMainWindow* mainWindow,
Scene_interface* scene_interface)
{
mw = mainWindow;
scene = scene_interface;
actions_map["actionMVC"] = new QAction("Mean Value Coordinates", mw);
actions_map["actionMVC"]->setProperty("subMenuName",
"Triangulated Surface Mesh Parameterization");
actions_map["actionDCP"] = new QAction ("Discrete Conformal Map", mw);
actions_map["actionDCP"]->setProperty("subMenuName",
"Triangulated Surface Mesh Parameterization");
actions_map["actionLSC"] = new QAction("Least Square Conformal Map", mw);
actions_map["actionLSC"]->setProperty("subMenuName",
"Triangulated Surface Mesh Parameterization");
connect(actions_map["actionMVC"], SIGNAL(triggered()),
this, SLOT(on_actionMVC_triggered()));
connect(actions_map["actionDCP"], SIGNAL(triggered()),
this, SLOT(on_actionDCP_triggered()));
connect(actions_map["actionLSC"], SIGNAL(triggered()),
this, SLOT(on_actionLSC_triggered()));
}
bool applicable(QAction*) const {
return qobject_cast<Scene_polyhedron_item*>(scene->item(scene->mainSelectionIndex()));
}
public Q_SLOTS:
void on_actionMVC_triggered();
void on_actionDCP_triggered();
void on_actionLSC_triggered();
protected:
enum Parameterization_method { PARAM_MVC, PARAM_DCP, PARAM_LSC };
void parameterize(Parameterization_method method);
}; // end Polyhedron_demo_parameterization_plugin
void Polyhedron_demo_parameterization_plugin::parameterize(const Parameterization_method method)
{
// get active polyhedron
const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();
Scene_polyhedron_item* poly_item =
qobject_cast<Scene_polyhedron_item*>(scene->item(index));
if(!poly_item)
return;
Polyhedron* pMesh = poly_item->polyhedron();
if(!pMesh)
return;
QApplication::setOverrideCursor(Qt::WaitCursor);
// parameterize
QTime time;
time.start();
typedef CGAL::Parameterization_polyhedron_adaptor_3<Polyhedron> Adaptor;
Adaptor adaptor(*pMesh);
bool success = false;
switch(method)
{
case PARAM_MVC:
{
std::cout << "Parameterize (MVC)...";
typedef CGAL::Mean_value_coordinates_parameterizer_3<Adaptor> Parameterizer;
Parameterizer::Error_code err = CGAL::parameterize(adaptor,Parameterizer());
success = err == Parameterizer::OK;
break;
}
case PARAM_DCP:
{
std::cout << "Parameterize (DCP)...";
typedef CGAL::Discrete_conformal_map_parameterizer_3<Adaptor> Parameterizer;
Parameterizer::Error_code err = CGAL::parameterize(adaptor,Parameterizer());
success = err == Parameterizer::OK;
}
case PARAM_LSC:
{
std::cout << "Parameterize (LSC)...";
typedef CGAL::LSCM_parameterizer_3<Adaptor> Parameterizer;
Parameterizer::Error_code err = CGAL::parameterize(adaptor,Parameterizer());
success = err == Parameterizer::OK;
}
}
if(success)
std::cout << "ok (" << time.elapsed() << " ms)" << std::endl;
else
{
std::cout << "failure" << std::endl;
QApplication::restoreOverrideCursor();
return;
}
// add textured polyhedon to the scene
Textured_polyhedron *pTex_polyhedron = new Textured_polyhedron();
Textured_polyhedron_builder<Polyhedron,Textured_polyhedron,Kernel> builder;
builder.run(*pMesh,*pTex_polyhedron);
pTex_polyhedron->compute_normals();
Polyhedron::Vertex_iterator it1;
Textured_polyhedron::Vertex_iterator it2;
for(it1 = pMesh->vertices_begin(),
it2 = pTex_polyhedron->vertices_begin();
it1 != pMesh->vertices_end() &&
it2 != pTex_polyhedron->vertices_end();
it1++, it2++)
{
// (u,v) pair is stored per halfedge
FT u = adaptor.info(it1->halfedge())->uv().x();
FT v = adaptor.info(it1->halfedge())->uv().y();
it2->u() = u;
it2->v() = v;
}
Scene_item* new_item = new Scene_textured_polyhedron_item(pTex_polyhedron);
new_item->setName(tr("%1 (parameterized)").arg(poly_item->name()));
new_item->setColor(Qt::white);
new_item->setRenderingMode(poly_item->renderingMode());
poly_item->setVisible(false);
scene->itemChanged(index);
scene->addItem(new_item);
QApplication::restoreOverrideCursor();
}
void Polyhedron_demo_parameterization_plugin::on_actionMVC_triggered()
{
parameterize(PARAM_MVC);
}
void Polyhedron_demo_parameterization_plugin::on_actionDCP_triggered()
{
std::cerr << "DCP...";
parameterize(PARAM_DCP);
}
void Polyhedron_demo_parameterization_plugin::on_actionLSC_triggered()
{
std::cerr << "LSC...";
parameterize(PARAM_LSC);
}
#include "Parameterization_plugin.moc"
| bsd-3-clause |
anselmolsm/soletta | src/samples/coap/simple-client.c | 1 | 5163 | /*
* This file is part of the Soletta Project
*
* Copyright (C) 2015 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:
*
* * 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 <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include "sol-log.h"
#include "sol-mainloop.h"
#include "sol-network.h"
#include "sol-str-slice.h"
#include "sol-util.h"
#include "sol-vector.h"
#include "sol-coap.h"
#define DEFAULT_UDP_PORT 5683
struct context {
struct sol_coap_server *server;
struct sol_str_slice *path;
};
static void
disable_observing(struct sol_coap_packet *req, struct sol_coap_server *server,
struct sol_str_slice path[], const struct sol_network_link_addr *cliaddr)
{
struct sol_coap_packet *pkt = sol_coap_packet_new(req);
uint8_t observe = 1;
int i;
if (!pkt)
return;
sol_coap_header_set_code(pkt, SOL_COAP_METHOD_GET);
sol_coap_header_set_type(pkt, SOL_COAP_TYPE_CON);
sol_coap_add_option(pkt, SOL_COAP_OPTION_OBSERVE, &observe, sizeof(observe));
for (i = 0; path[i].data; i++)
sol_coap_add_option(pkt, SOL_COAP_OPTION_URI_PATH, path[i].data, path[i].len);
sol_coap_send_packet(server, pkt, cliaddr);
SOL_INF("Disabled observing");
}
static int
reply_cb(struct sol_coap_packet *req, const struct sol_network_link_addr *cliaddr,
void *data)
{
struct context *context = data;
static int count;
char addr[SOL_INET_ADDR_STRLEN];
uint8_t *payload;
uint16_t len;
sol_network_addr_to_str(cliaddr, addr, sizeof(addr));
SOL_INF("Got response from %s", addr);
sol_coap_packet_get_payload(req, &payload, &len);
SOL_INF("Payload: %.*s", len, payload);
if (++count == 10)
disable_observing(req, context->server, context->path, cliaddr);
return 0;
}
int
main(int argc, char *argv[])
{
struct context context = { };
struct sol_network_link_addr cliaddr = { };
struct sol_coap_packet *req;
uint8_t observe = 0;
int i;
uint8_t token[4] = { 0x41, 0x42, 0x43, 0x44 };
sol_init();
if (argc < 3) {
SOL_INF("Usage: %s <address> <path> [path]\n", argv[0]);
return 0;
}
context.server = sol_coap_server_new(0);
if (!context.server) {
SOL_WRN("Could not create a coap server.");
return -1;
}
req = sol_coap_packet_request_new(SOL_COAP_METHOD_GET, SOL_COAP_TYPE_CON);
if (!req) {
SOL_WRN("Could not make a GET request to resource %s", argv[2]);
return -1;
}
sol_coap_header_set_token(req, token, sizeof(token));
context.path = calloc(argc - 1, sizeof(*context.path));
if (!context.path) {
sol_coap_packet_unref(req);
return -1;
}
for (i = 2; i < argc; i++) {
context.path[i - 2] = sol_str_slice_from_str(argv[i]);
}
sol_coap_add_option(req, SOL_COAP_OPTION_OBSERVE, &observe, sizeof(observe));
for (i = 0; context.path[i].data; i++)
sol_coap_add_option(req, SOL_COAP_OPTION_URI_PATH, context.path[i].data, context.path[i].len);
cliaddr.family = AF_INET;
if (!sol_network_addr_from_str(&cliaddr, argv[1])) {
SOL_WRN("%s is an invalid IPv4 address", argv[1]);
free(context.path);
sol_coap_packet_unref(req);
return -1;
}
cliaddr.port = DEFAULT_UDP_PORT;
/* Takes the ownership of 'req'. */
sol_coap_send_packet_with_reply(context.server, req, &cliaddr, reply_cb, &context);
sol_run();
sol_coap_server_unref(context.server);
free(context.path);
return 0;
}
| bsd-3-clause |
xianyi/OpenBLAS | lapack-netlib/SRC/sorgr2.c | 1 | 19884 | #include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#endif
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimagf(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* > \brief \b SORGR2 generates all or part of the orthogonal matrix Q from an RQ factorization determined by
sgerqf (unblocked algorithm). */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download SORGR2 + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/sorgr2.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/sorgr2.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/sorgr2.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE SORGR2( M, N, K, A, LDA, TAU, WORK, INFO ) */
/* INTEGER INFO, K, LDA, M, N */
/* REAL A( LDA, * ), TAU( * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > SORGR2 generates an m by n real matrix Q with orthonormal rows, */
/* > which is defined as the last m rows of a product of k elementary */
/* > reflectors of order n */
/* > */
/* > Q = H(1) H(2) . . . H(k) */
/* > */
/* > as returned by SGERQF. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of rows of the matrix Q. M >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrix Q. N >= M. */
/* > \endverbatim */
/* > */
/* > \param[in] K */
/* > \verbatim */
/* > K is INTEGER */
/* > The number of elementary reflectors whose product defines the */
/* > matrix Q. M >= K >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is REAL array, dimension (LDA,N) */
/* > On entry, the (m-k+i)-th row must contain the vector which */
/* > defines the elementary reflector H(i), for i = 1,2,...,k, as */
/* > returned by SGERQF in the last k rows of its array argument */
/* > A. */
/* > On exit, the m by n matrix Q. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The first dimension of the array A. LDA >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[in] TAU */
/* > \verbatim */
/* > TAU is REAL array, dimension (K) */
/* > TAU(i) must contain the scalar factor of the elementary */
/* > reflector H(i), as returned by SGERQF. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is REAL array, dimension (M) */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument has an illegal value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup realOTHERcomputational */
/* ===================================================================== */
/* Subroutine */ int sorgr2_(integer *m, integer *n, integer *k, real *a,
integer *lda, real *tau, real *work, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3;
real r__1;
/* Local variables */
integer i__, j, l;
extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *),
slarf_(char *, integer *, integer *, real *, integer *, real *,
real *, integer *, real *);
integer ii;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen);
/* -- LAPACK computational routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* ===================================================================== */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--tau;
--work;
/* Function Body */
*info = 0;
if (*m < 0) {
*info = -1;
} else if (*n < *m) {
*info = -2;
} else if (*k < 0 || *k > *m) {
*info = -3;
} else if (*lda < f2cmax(1,*m)) {
*info = -5;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SORGR2", &i__1, (ftnlen)6);
return 0;
}
/* Quick return if possible */
if (*m <= 0) {
return 0;
}
if (*k < *m) {
/* Initialise rows 1:m-k to rows of the unit matrix */
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
i__2 = *m - *k;
for (l = 1; l <= i__2; ++l) {
a[l + j * a_dim1] = 0.f;
/* L10: */
}
if (j > *n - *m && j <= *n - *k) {
a[*m - *n + j + j * a_dim1] = 1.f;
}
/* L20: */
}
}
i__1 = *k;
for (i__ = 1; i__ <= i__1; ++i__) {
ii = *m - *k + i__;
/* Apply H(i) to A(1:m-k+i,1:n-k+i) from the right */
a[ii + (*n - *m + ii) * a_dim1] = 1.f;
i__2 = ii - 1;
i__3 = *n - *m + ii;
slarf_("Right", &i__2, &i__3, &a[ii + a_dim1], lda, &tau[i__], &a[
a_offset], lda, &work[1]);
i__2 = *n - *m + ii - 1;
r__1 = -tau[i__];
sscal_(&i__2, &r__1, &a[ii + a_dim1], lda);
a[ii + (*n - *m + ii) * a_dim1] = 1.f - tau[i__];
/* Set A(m-k+i,n-k+i+1:n) to zero */
i__2 = *n;
for (l = *n - *m + ii + 1; l <= i__2; ++l) {
a[ii + l * a_dim1] = 0.f;
/* L30: */
}
/* L40: */
}
return 0;
/* End of SORGR2 */
} /* sorgr2_ */
| bsd-3-clause |
raspberrypi/userland | interface/mmal/test/examples/example_basic_2.c | 1 | 15866 | /*
Copyright (c) 2012, Broadcom Europe Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the 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.
*/
#include "bcm_host.h"
#include "mmal.h"
#include "util/mmal_default_components.h"
#include "util/mmal_util_params.h"
#include "util/mmal_util.h"
#include "interface/vcos/vcos.h"
#include <stdio.h>
#define CHECK_STATUS(status, msg) if (status != MMAL_SUCCESS) { fprintf(stderr, msg"\n"); goto error; }
static uint8_t codec_header_bytes[128];
static unsigned int codec_header_bytes_size = sizeof(codec_header_bytes);
static FILE *source_file;
/* Macros abstracting the I/O, just to make the example code clearer */
#define SOURCE_OPEN(uri) \
source_file = fopen(uri, "rb"); if (!source_file) goto error;
#define SOURCE_READ_CODEC_CONFIG_DATA(bytes, size) \
size = fread(bytes, 1, size, source_file); rewind(source_file)
#define SOURCE_READ_DATA_INTO_BUFFER(a) \
a->length = fread(a->data, 1, a->alloc_size - 128, source_file); \
a->offset = 0
#define SOURCE_CLOSE() \
if (source_file) fclose(source_file)
/** Context for our application */
static struct CONTEXT_T {
VCOS_SEMAPHORE_T semaphore;
MMAL_QUEUE_T *queue;
MMAL_STATUS_T status;
} context;
static void log_video_format(MMAL_ES_FORMAT_T *format)
{
if (format->type != MMAL_ES_TYPE_VIDEO)
return;
fprintf(stderr, "fourcc: %4.4s, width: %i, height: %i, (%i,%i,%i,%i)\n",
(char *)&format->encoding,
format->es->video.width, format->es->video.height,
format->es->video.crop.x, format->es->video.crop.y,
format->es->video.crop.width, format->es->video.crop.height);
}
/** Callback from the control port.
* Component is sending us an event. */
static void control_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
{
struct CONTEXT_T *ctx = (struct CONTEXT_T *)port->userdata;
switch (buffer->cmd)
{
case MMAL_EVENT_EOS:
/* Only sink component generate EOS events */
break;
case MMAL_EVENT_ERROR:
/* Something went wrong. Signal this to the application */
ctx->status = *(MMAL_STATUS_T *)buffer->data;
break;
default:
break;
}
/* Done with the event, recycle it */
mmal_buffer_header_release(buffer);
/* Kick the processing thread */
vcos_semaphore_post(&ctx->semaphore);
}
/** Callback from the input port.
* Buffer has been consumed and is available to be used again. */
static void input_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
{
struct CONTEXT_T *ctx = (struct CONTEXT_T *)port->userdata;
/* The decoder is done with the data, just recycle the buffer header into its pool */
mmal_buffer_header_release(buffer);
/* Kick the processing thread */
vcos_semaphore_post(&ctx->semaphore);
}
/** Callback from the output port.
* Buffer has been produced by the port and is available for processing. */
static void output_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
{
struct CONTEXT_T *ctx = (struct CONTEXT_T *)port->userdata;
/* Queue the decoded video frame */
mmal_queue_put(ctx->queue, buffer);
/* Kick the processing thread */
vcos_semaphore_post(&ctx->semaphore);
}
int main(int argc, char **argv)
{
MMAL_STATUS_T status = MMAL_EINVAL;
MMAL_COMPONENT_T *decoder = 0;
MMAL_POOL_T *pool_in = 0, *pool_out = 0;
MMAL_BOOL_T eos_sent = MMAL_FALSE, eos_received = MMAL_FALSE;
unsigned int count;
if (argc < 2)
{
fprintf(stderr, "invalid arguments\n");
return -1;
}
bcm_host_init();
vcos_semaphore_create(&context.semaphore, "example", 1);
SOURCE_OPEN(argv[1]);
/* Create the decoder component.
* This specific component exposes 2 ports (1 input and 1 output). Like most components
* its expects the format of its input port to be set by the client in order for it to
* know what kind of data it will be fed. */
status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_DECODER, &decoder);
CHECK_STATUS(status, "failed to create decoder");
/* Enable control port so we can receive events from the component */
decoder->control->userdata = (void *)&context;
status = mmal_port_enable(decoder->control, control_callback);
CHECK_STATUS(status, "failed to enable control port");
/* Get statistics on the input port */
MMAL_PARAMETER_CORE_STATISTICS_T stats = {{0}};
stats.hdr.id = MMAL_PARAMETER_CORE_STATISTICS;
stats.hdr.size = sizeof(MMAL_PARAMETER_CORE_STATISTICS_T);
status = mmal_port_parameter_get(decoder->input[0], &stats.hdr);
CHECK_STATUS(status, "failed to get stats");
fprintf(stderr, "stats: %i, %i", stats.stats.buffer_count, stats.stats.max_delay);
/* Set the zero-copy parameter on the input port */
MMAL_PARAMETER_BOOLEAN_T zc = {{MMAL_PARAMETER_ZERO_COPY, sizeof(zc)}, MMAL_TRUE};
status = mmal_port_parameter_set(decoder->input[0], &zc.hdr);
fprintf(stderr, "status: %i\n", status);
/* Set the zero-copy parameter on the output port */
status = mmal_port_parameter_set_boolean(decoder->output[0], MMAL_PARAMETER_ZERO_COPY, MMAL_TRUE);
fprintf(stderr, "status: %i\n", status);
/* Set format of video decoder input port */
MMAL_ES_FORMAT_T *format_in = decoder->input[0]->format;
format_in->type = MMAL_ES_TYPE_VIDEO;
format_in->encoding = MMAL_ENCODING_H264;
format_in->es->video.width = 1280;
format_in->es->video.height = 720;
format_in->es->video.frame_rate.num = 30;
format_in->es->video.frame_rate.den = 1;
format_in->es->video.par.num = 1;
format_in->es->video.par.den = 1;
/* If the data is known to be framed then the following flag should be set:
* format_in->flags |= MMAL_ES_FORMAT_FLAG_FRAMED; */
SOURCE_READ_CODEC_CONFIG_DATA(codec_header_bytes, codec_header_bytes_size);
status = mmal_format_extradata_alloc(format_in, codec_header_bytes_size);
CHECK_STATUS(status, "failed to allocate extradata");
format_in->extradata_size = codec_header_bytes_size;
if (format_in->extradata_size)
memcpy(format_in->extradata, codec_header_bytes, format_in->extradata_size);
status = mmal_port_format_commit(decoder->input[0]);
CHECK_STATUS(status, "failed to commit format");
/* Our decoder can do internal colour conversion, ask for a conversion to RGB565 */
MMAL_ES_FORMAT_T *format_out = decoder->output[0]->format;
format_out->encoding = MMAL_ENCODING_RGB16;
status = mmal_port_format_commit(decoder->output[0]);
CHECK_STATUS(status, "failed to commit format");
/* Display the output port format */
fprintf(stderr, "%s\n", decoder->output[0]->name);
fprintf(stderr, " type: %i, fourcc: %4.4s\n", format_out->type, (char *)&format_out->encoding);
fprintf(stderr, " bitrate: %i, framed: %i\n", format_out->bitrate,
!!(format_out->flags & MMAL_ES_FORMAT_FLAG_FRAMED));
fprintf(stderr, " extra data: %i, %p\n", format_out->extradata_size, format_out->extradata);
fprintf(stderr, " width: %i, height: %i, (%i,%i,%i,%i)\n",
format_out->es->video.width, format_out->es->video.height,
format_out->es->video.crop.x, format_out->es->video.crop.y,
format_out->es->video.crop.width, format_out->es->video.crop.height);
/* The format of both ports is now set so we can get their buffer requirements and create
* our buffer headers. We use the buffer pool API to create these. */
decoder->input[0]->buffer_num = decoder->input[0]->buffer_num_min;
decoder->input[0]->buffer_size = decoder->input[0]->buffer_size_min;
decoder->output[0]->buffer_num = decoder->output[0]->buffer_num_min;
decoder->output[0]->buffer_size = decoder->output[0]->buffer_size_min;
pool_in = mmal_port_pool_create(decoder->output[0],
decoder->input[0]->buffer_num,
decoder->input[0]->buffer_size);
pool_out = mmal_port_pool_create(decoder->output[0],
decoder->output[0]->buffer_num,
decoder->output[0]->buffer_size);
/* Create a queue to store our decoded video frames. The callback we will get when
* a frame has been decoded will put the frame into this queue. */
context.queue = mmal_queue_create();
/* Store a reference to our context in each port (will be used during callbacks) */
decoder->input[0]->userdata = (void *)&context;
decoder->output[0]->userdata = (void *)&context;
/* Enable all the input port and the output port.
* The callback specified here is the function which will be called when the buffer header
* we sent to the component has been processed. */
status = mmal_port_enable(decoder->input[0], input_callback);
CHECK_STATUS(status, "failed to enable input port");
status = mmal_port_enable(decoder->output[0], output_callback);
CHECK_STATUS(status, "failed to enable output port");
/* Component won't start processing data until it is enabled. */
status = mmal_component_enable(decoder);
CHECK_STATUS(status, "failed to enable component");
/* Start decoding */
fprintf(stderr, "start decoding\n");
/* This is the main processing loop */
for (count = 0; !eos_received && count < 500; count++)
{
MMAL_BUFFER_HEADER_T *buffer;
/* Wait for buffer headers to be available on either of the decoder ports */
vcos_semaphore_wait(&context.semaphore);
/* Check for errors */
if (context.status != MMAL_SUCCESS)
{
fprintf(stderr, "Aborting due to error\n");
break;
}
/* Send data to decode to the input port of the video decoder */
if (!eos_sent && (buffer = mmal_queue_get(pool_in->queue)) != NULL)
{
SOURCE_READ_DATA_INTO_BUFFER(buffer);
if(!buffer->length) eos_sent = MMAL_TRUE;
buffer->flags = buffer->length ? 0 : MMAL_BUFFER_HEADER_FLAG_EOS;
buffer->pts = buffer->dts = MMAL_TIME_UNKNOWN;
fprintf(stderr, "sending %i bytes\n", (int)buffer->length);
status = mmal_port_send_buffer(decoder->input[0], buffer);
CHECK_STATUS(status, "failed to send buffer");
}
/* Get our decoded frames */
while ((buffer = mmal_queue_get(context.queue)) != NULL)
{
/* We have a frame, do something with it (why not display it for instance?).
* Once we're done with it, we release it. It will automatically go back
* to its original pool so it can be reused for a new video frame.
*/
eos_received = buffer->flags & MMAL_BUFFER_HEADER_FLAG_EOS;
if (buffer->cmd)
{
fprintf(stderr, "received event %4.4s\n", (char *)&buffer->cmd);
if (buffer->cmd == MMAL_EVENT_FORMAT_CHANGED)
{
MMAL_EVENT_FORMAT_CHANGED_T *event = mmal_event_format_changed_get(buffer);
if (event)
{
fprintf(stderr, "----------Port format changed----------\n");
log_video_format(decoder->output[0]->format);
fprintf(stderr, "-----------------to---------------------\n");
log_video_format(event->format);
fprintf(stderr, " buffers num (opt %i, min %i), size (opt %i, min: %i)\n",
event->buffer_num_recommended, event->buffer_num_min,
event->buffer_size_recommended, event->buffer_size_min);
fprintf(stderr, "----------------------------------------\n");
}
//Assume we can't reuse the buffers, so have to disable, destroy
//pool, create new pool, enable port, feed in buffers.
status = mmal_port_disable(decoder->output[0]);
CHECK_STATUS(status, "failed to disable port");
//Clear the queue of all buffers
while(mmal_queue_length(pool_out->queue) != pool_out->headers_num)
{
MMAL_BUFFER_HEADER_T *buf;
fprintf(stderr, "Wait for buffers to be returned. Have %d of %d buffers\n",
mmal_queue_length(pool_out->queue), pool_out->headers_num);
vcos_semaphore_wait(&context.semaphore);
fprintf(stderr, "Got semaphore\n");
buf = mmal_queue_get(context.queue);
mmal_buffer_header_release(buf);
}
fprintf(stderr, "Got all buffers\n");
mmal_port_pool_destroy(decoder->output[0], pool_out);
status = mmal_format_full_copy(decoder->output[0]->format, event->format);
CHECK_STATUS(status, "failed to copy port format");
status = mmal_port_format_commit(decoder->output[0]);
CHECK_STATUS(status, "failed to commit port format");
pool_out = mmal_port_pool_create(decoder->output[0],
decoder->output[0]->buffer_num,
decoder->output[0]->buffer_size);
status = mmal_port_enable(decoder->output[0], output_callback);
CHECK_STATUS(status, "failed to enable port");
//Allow the following loop to send all the buffers back to the decoder
}
}
else
fprintf(stderr, "decoded frame (flags %x)\n", buffer->flags);
mmal_buffer_header_release(buffer);
}
/* Send empty buffers to the output port of the decoder */
while ((buffer = mmal_queue_get(pool_out->queue)) != NULL)
{
status = mmal_port_send_buffer(decoder->output[0], buffer);
CHECK_STATUS(status, "failed to send buffer");
}
}
/* Stop decoding */
fprintf(stderr, "stop decoding - count %d, eos_received %d\n", count, eos_received);
/* Stop everything. Not strictly necessary since mmal_component_destroy()
* will do that anyway */
mmal_port_disable(decoder->input[0]);
mmal_port_disable(decoder->output[0]);
mmal_component_disable(decoder);
error:
/* Cleanup everything */
if (pool_in)
mmal_port_pool_destroy(decoder->input[0], pool_in);
if (pool_out)
mmal_port_pool_destroy(decoder->output[0], pool_out);
if (decoder)
mmal_component_destroy(decoder);
if (context.queue)
mmal_queue_destroy(context.queue);
SOURCE_CLOSE();
vcos_semaphore_delete(&context.semaphore);
return status == MMAL_SUCCESS ? 0 : -1;
}
| bsd-3-clause |
jmesmon/jaus-- | src/jaus/mobility/sensors/setgeomagneticproperty.cpp | 1 | 7586 | ////////////////////////////////////////////////////////////////////////////////////
///
/// \file setgeomagneticproperty.cpp
/// \brief This file contains the implementation of a JAUS message.
///
/// <br>Author(s): Bo Sun
/// <br>Created: 3 December 2009
/// <br>Copyright (c) 2009
/// <br>Applied Cognition and Training in Immersive Virtual Environments
/// <br>(ACTIVE) Laboratory
/// <br>Institute for Simulation and Training (IST)
/// <br>University of Central Florida (UCF)
/// <br>All rights reserved.
/// <br>Email: bsun@ist.ucf.edu
/// <br>Web: http://active.ist.ucf.edu
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright
/// notice, this list of conditions and the following disclaimer in the
/// documentation and/or other materials provided with the distribution.
/// * Neither the name of the ACTIVE LAB, IST, UCF, 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 ACTIVE LAB''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 UCF 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 "jaus/mobility/sensors/setgeomagneticproperty.h"
#include "jaus/core/scaledinteger.h"
#include <cxutils/math/cxmath.h>
const double JAUS::SetGeomagneticProperty::Limits::MinMagneticVariation = -CxUtils::CX_PI;
const double JAUS::SetGeomagneticProperty::Limits::MaxMagneticVariation = CxUtils::CX_PI;
using namespace JAUS;
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Constructor, initializes default values.
///
/// \param[in] src Source ID of message sender.
/// \param[in] dest Destination ID of message.
///
////////////////////////////////////////////////////////////////////////////////////
SetGeomagneticProperty::SetGeomagneticProperty(const Address& dest, const Address& src) : Message(SET_GEOMAGNETIC_PROPERTY, dest, src)
{
mMagneticVariation = 0;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Copy constructor.
///
////////////////////////////////////////////////////////////////////////////////////
SetGeomagneticProperty::SetGeomagneticProperty(const SetGeomagneticProperty& message) : Message(SET_GEOMAGNETIC_PROPERTY)
{
*this = message;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Destructor.
///
////////////////////////////////////////////////////////////////////////////////////
SetGeomagneticProperty::~SetGeomagneticProperty()
{
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Sets the magnetic variation and updates the presence vector for the
/// message.
///
/// \param[in] radians Desired magnetic variation in meters per second [-PI, PI].
///
/// \return JAUS_OK on success, otherwise false.
///
////////////////////////////////////////////////////////////////////////////////////
bool SetGeomagneticProperty::SetMagneticVariation(const double radians)
{
if(radians >= Limits::MinMagneticVariation && radians <= Limits::MaxMagneticVariation)
{
mMagneticVariation = radians;
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Writes message payload to the packet.
///
/// Message contents are written to the packet following the JAUS standard.
///
/// \param[out] packet Packet to write payload to.
///
/// \return -1 on error, otherwise number of bytes written.
///
////////////////////////////////////////////////////////////////////////////////////
int SetGeomagneticProperty::WriteMessageBody(Packet& packet) const
{
int expected = USHORT_SIZE;
int written = 0;
written += ScaledInteger::Write(packet, mMagneticVariation, Limits::MaxMagneticVariation, Limits::MinMagneticVariation, ScaledInteger::UShort);
return expected == written ? written : -1;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Reads message payload from the packet.
///
/// Message contents are read from the packet following the JAUS standard.
///
/// \param[in] packet Packet containing message payload data to read.
///
/// \return -1 on error, otherwise number of bytes written.
///
////////////////////////////////////////////////////////////////////////////////////
int SetGeomagneticProperty::ReadMessageBody(const Packet& packet)
{
int expected = USHORT_SIZE;
int read = 0;
read += ScaledInteger::Read(packet, mMagneticVariation, Limits::MaxMagneticVariation, Limits::MinMagneticVariation, ScaledInteger::UShort);
return expected == read ? read : -1;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Clears message payload data.
///
////////////////////////////////////////////////////////////////////////////////////
void SetGeomagneticProperty::ClearMessageBody()
{
mMagneticVariation = 0;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Runs a test case to validate the message class.
///
/// \return 1 on success, otherwise 0.
///
////////////////////////////////////////////////////////////////////////////////////
int SetGeomagneticProperty::RunTestCase() const
{
int result = 0;
Packet packet;
SetGeomagneticProperty msg1, msg2;
msg1.SetMagneticVariation(1.2333);
if(msg1.WriteMessageBody(packet))
{
msg2.ClearMessage();
if(msg2.ReadMessageBody(packet))
{
if(msg1.GetMagneticVariation() - msg2.GetMagneticVariation() <= 0.001)
{
result = 1;
}
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Sets equal to.
///
////////////////////////////////////////////////////////////////////////////////////
SetGeomagneticProperty& SetGeomagneticProperty::operator=(const SetGeomagneticProperty& message)
{
if(this != &message)
{
CopyHeaderData(&message);
mMagneticVariation = message.mMagneticVariation;
}
return *this;
}
/* End of File */
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s02/CWE78_OS_Command_Injection__char_console_w32_spawnv_61a.c | 1 | 3340 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_console_w32_spawnv_61a.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-61a.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: console Read input from the console
* GoodSource: Fixed string
* Sinks: w32_spawnv
* BadSink : execute command with spawnv
* Flow Variant: 61 Data flow: data returned from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#include <process.h>
#ifndef OMITBAD
/* bad function declaration */
char * CWE78_OS_Command_Injection__char_console_w32_spawnv_61b_badSource(char * data);
void CWE78_OS_Command_Injection__char_console_w32_spawnv_61_bad()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
data = CWE78_OS_Command_Injection__char_console_w32_spawnv_61b_badSource(data);
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* spawnv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
_spawnv(_P_WAIT, COMMAND_INT_PATH, args);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
char * CWE78_OS_Command_Injection__char_console_w32_spawnv_61b_goodG2BSource(char * data);
static void goodG2B()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
data = CWE78_OS_Command_Injection__char_console_w32_spawnv_61b_goodG2BSource(data);
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* spawnv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
_spawnv(_P_WAIT, COMMAND_INT_PATH, args);
}
}
void CWE78_OS_Command_Injection__char_console_w32_spawnv_61_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE78_OS_Command_Injection__char_console_w32_spawnv_61_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__char_console_w32_spawnv_61_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
MarginC/kame | freebsd2/sys/netinet/tcp_debug.c | 1 | 4725 | /*
* Copyright (c) 1982, 1986, 1993
* 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 the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)tcp_debug.c 8.1 (Berkeley) 6/10/93
* $Id: tcp_debug.c,v 1.7.2.1 1997/09/16 18:37:00 joerg Exp $
*/
#include "opt_tcpdebug.h"
#ifdef TCPDEBUG
/* load symbolic names */
#define PRUREQUESTS
#define TCPSTATES
#define TCPTIMERS
#define TANAMES
#endif
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/protosw.h>
#include <sys/errno.h>
#include <net/route.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/ip_var.h>
#include <netinet/tcp.h>
#include <netinet/tcp_fsm.h>
#include <netinet/tcp_seq.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#include <netinet/tcpip.h>
#include <netinet/tcp_debug.h>
#ifdef TCPDEBUG
static int tcpconsdebug = 0;
#endif
static struct tcp_debug tcp_debug[TCP_NDEBUG];
static int tcp_debx;
/*
* Tcp debug routines
*/
void
tcp_trace(act, ostate, tp, ti, req)
short act, ostate;
struct tcpcb *tp;
struct tcpiphdr *ti;
int req;
{
tcp_seq seq, ack;
int len, flags;
struct tcp_debug *td = &tcp_debug[tcp_debx++];
if (tcp_debx == TCP_NDEBUG)
tcp_debx = 0;
td->td_time = iptime();
td->td_act = act;
td->td_ostate = ostate;
td->td_tcb = (caddr_t)tp;
if (tp)
td->td_cb = *tp;
else
bzero((caddr_t)&td->td_cb, sizeof (*tp));
if (ti)
td->td_ti = *ti;
else
bzero((caddr_t)&td->td_ti, sizeof (*ti));
td->td_req = req;
#ifdef TCPDEBUG
if (tcpconsdebug == 0)
return;
if (tp)
printf("%p %s:", tp, tcpstates[ostate]);
else
printf("???????? ");
printf("%s ", tanames[act]);
switch (act) {
case TA_INPUT:
case TA_OUTPUT:
case TA_DROP:
if (ti == 0)
break;
seq = ti->ti_seq;
ack = ti->ti_ack;
len = ti->ti_len;
if (act == TA_OUTPUT) {
seq = ntohl(seq);
ack = ntohl(ack);
len = ntohs((u_short)len);
}
if (act == TA_OUTPUT)
len -= sizeof (struct tcphdr);
if (len)
printf("[%x..%x)", seq, seq+len);
else
printf("%x", seq);
printf("@%x, urp=%x", ack, ti->ti_urp);
flags = ti->ti_flags;
if (flags) {
char *cp = "<";
#define pf(f) { \
if (ti->ti_flags & TH_##f) { \
printf("%s%s", cp, #f); \
cp = ","; \
} \
}
pf(SYN); pf(ACK); pf(FIN); pf(RST); pf(PUSH); pf(URG);
printf(">");
}
break;
case TA_USER:
printf("%s", prurequests[req&0xff]);
if ((req & 0xff) == PRU_SLOWTIMO)
printf("<%s>", tcptimers[req>>8]);
break;
}
if (tp)
printf(" -> %s", tcpstates[tp->t_state]);
/* print out internal state of tp !?! */
printf("\n");
if (tp == 0)
return;
printf("\trcv_(nxt,wnd,up) (%x,%x,%x) snd_(una,nxt,max) (%x,%x,%x)\n",
tp->rcv_nxt, tp->rcv_wnd, tp->rcv_up, tp->snd_una, tp->snd_nxt,
tp->snd_max);
printf("\tsnd_(wl1,wl2,wnd) (%x,%x,%x)\n",
tp->snd_wl1, tp->snd_wl2, tp->snd_wnd);
#endif /* TCPDEBUG */
}
| bsd-3-clause |
Sevalecan/paintown | src/util/input/input-source.cpp | 2 | 1366 | #include "input-source.h"
using std::vector;
InputSource::InputSource(bool default_){
if (default_){
keyboard.push_back(0);
keyboard.push_back(1);
joystick.push_back(0);
joystick.push_back(1);
}
}
InputSource::InputSource(const InputSource & copy):
keyboard(copy.keyboard),
joystick(copy.joystick){
}
InputSource::InputSource(const vector<int> & keyboard, const vector<int> & joystick):
keyboard(keyboard),
joystick(joystick){
}
InputSource & InputSource::operator=(const InputSource & copy){
this->keyboard = copy.keyboard;
this->joystick = copy.joystick;
return *this;
}
InputSource InputSource::addKeyboard(int keyboard){
vector<int> keyboardCopy(this->keyboard);
keyboardCopy.push_back(keyboard);
return InputSource(keyboardCopy, joystick);
}
InputSource InputSource::addJoystick(int joystick){
vector<int> joystickCopy(this->joystick);
joystickCopy.push_back(joystick);
return InputSource(keyboard, joystickCopy);
}
InputSource::~InputSource(){
}
bool InputSource::useKeyboard() const {
return keyboard.size() > 0;
}
bool InputSource::useJoystick() const {
return joystick.size() > 0;
}
const vector<int> & InputSource::getKeyboard() const {
return keyboard;
}
const vector<int> & InputSource::getJoystick() const {
return joystick;
}
| bsd-3-clause |
youtube/cobalt_sandbox | third_party/skia/tools/ProcStats.cpp | 2 | 2633 | /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkTypes.h"
#include "tools/ProcStats.h"
#if defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS) || defined(SK_BUILD_FOR_ANDROID)
#include <sys/resource.h>
int sk_tools::getMaxResidentSetSizeMB() {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
return static_cast<int>(ru.ru_maxrss / 1024 / 1024); // Darwin reports bytes.
#else
return static_cast<int>(ru.ru_maxrss / 1024); // Linux reports kilobytes.
#endif
}
#elif defined(SK_BUILD_FOR_WIN)
#include <windows.h>
#include <psapi.h>
int sk_tools::getMaxResidentSetSizeMB() {
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
return static_cast<int>(info.PeakWorkingSetSize / 1024 / 1024); // Windows reports bytes.
}
#else
int sk_tools::getMaxResidentSetSizeMB() { return -1; }
#endif
#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
#include <mach/mach.h>
int sk_tools::getCurrResidentSetSizeMB() {
mach_task_basic_info info;
mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS !=
task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &count)) {
return -1;
}
return info.resident_size / 1024 / 1024; // Darwin reports bytes.
}
#elif defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_ANDROID) // N.B. /proc is Linux-only.
#include <unistd.h>
#include <stdio.h>
int sk_tools::getCurrResidentSetSizeMB() {
const long pageSize = sysconf(_SC_PAGESIZE);
long long rssPages = 0;
if (FILE* statm = fopen("/proc/self/statm", "r")) {
// statm contains: program-size rss shared text lib data dirty, all in page counts.
int rc = fscanf(statm, "%*d %lld", &rssPages);
fclose(statm);
if (rc != 1) {
return -1;
}
}
return rssPages * pageSize / 1024 / 1024;
}
#elif defined(SK_BUILD_FOR_WIN)
int sk_tools::getCurrResidentSetSizeMB() {
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
return static_cast<int>(info.WorkingSetSize / 1024 / 1024); // Windows reports bytes.
}
#else
int sk_tools::getCurrResidentSetSizeMB() { return -1; }
#endif
| bsd-3-clause |
The-OpenROAD-Project/OpenROAD | src/odb/src/lef/clef/xlefiPropType.cpp | 2 | 1733 | // *****************************************************************************
// *****************************************************************************
// ATTENTION: THIS IS AN AUTO-GENERATED FILE. DO NOT CHANGE IT!
// *****************************************************************************
// *****************************************************************************
// Copyright 2012, Cadence Design Systems
//
// This file is part of the Cadence LEF/DEF Open Source
// Distribution, Product Version 5.8.
//
// 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.
//
//
// For updates, support, or to become part of the LEF/DEF Community,
// check www.openeda.org for details.
//
// $Author: dell $
// $Revision: #1 $
// $Date: 2017/06/06 $
// $State: $
// *****************************************************************************
// *****************************************************************************
#define EXTERN extern "C"
#include "lefiPropType.h"
#include "lefiPropType.hpp"
// Wrappers definitions.
const char lefiPropType_propType(const ::lefiPropType* obj, char* name)
{
return ((const LefDefParser::lefiPropType*) obj)->propType(name);
}
| bsd-3-clause |
PedroTrujilloV/chrono | src/unit_PARALLEL/chrono_opengl/shapes/obj/ChOpenGLOBJLoader.cpp | 2 | 3186 | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Hammad Mazhar
// =============================================================================
// Uses the tiny_obj_loader library to load an OBJ file in the proper format
// =============================================================================
#include <iostream>
#include "ChOpenGLOBJLoader.h"
#include <sstream>
#include <string>
using namespace glm;
namespace chrono {
namespace opengl {
ChOpenGLOBJLoader::ChOpenGLOBJLoader() {
}
// load an obj mesh. Each mesh can have multiple sub meshes
void ChOpenGLOBJLoader::LoadObject(const char* mesh_file,
std::vector<std::vector<glm::vec3> >& vertices,
std::vector<std::vector<glm::vec3> >& normals,
std::vector<std::vector<glm::vec2> >& texcoords,
std::vector<std::vector<GLuint> >& indices,
std::vector<std::string>& names) {
std::vector<tinyobj::shape_t> shapes;
std::string err = tinyobj::LoadObj(shapes, mesh_file);
std::cout << " # of shapes : " << shapes.size() << std::endl;
vertices.resize(shapes.size());
normals.resize(shapes.size());
texcoords.resize(shapes.size());
indices.resize(shapes.size());
names.resize(shapes.size());
// convert between mesh loader data structure and vector data structure
for (size_t i = 0; i < shapes.size(); i++) {
vertices[i].resize(shapes[i].mesh.positions.size() / 3);
normals[i].resize(shapes[i].mesh.normals.size() / 3);
texcoords[i].resize(shapes[i].mesh.texcoords.size() / 2);
indices[i].resize(shapes[i].mesh.indices.size());
names[i] = shapes[i].name;
std::cout << shapes[i].mesh.positions.size() / 3 << " " << shapes[i].mesh.normals.size() / 3 << " "
<< shapes[i].mesh.texcoords.size() / 2 << " " << shapes[i].mesh.indices.size() << std::endl;
for (size_t v = 0; v < shapes[i].mesh.positions.size() / 3; v++) {
vertices[i][v] = vec3(shapes[i].mesh.positions[3 * v + 0],
shapes[i].mesh.positions[3 * v + 1],
shapes[i].mesh.positions[3 * v + 2]);
}
for (size_t n = 0; n < shapes[i].mesh.normals.size() / 3; n++) {
normals[i][n] =
vec3(shapes[i].mesh.normals[3 * n + 0], shapes[i].mesh.normals[3 * n + 1], shapes[i].mesh.normals[3 * n + 2]);
}
for (size_t t = 0; t < shapes[i].mesh.texcoords.size() / 2; t++) {
texcoords[i][t] = vec2(shapes[i].mesh.texcoords[2 * t + 0], shapes[i].mesh.texcoords[2 * t + 1] * -1);
}
for (size_t f = 0; f < shapes[i].mesh.indices.size(); f++) {
indices[i][f] = shapes[i].mesh.indices[f];
}
}
}
}
}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE195_Signed_to_Unsigned_Conversion_Error/s02/CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_54e.c | 2 | 2085 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_54e.c
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-54e.tmpl.c
*/
/*
* @description
* CWE: 195 Signed to Unsigned Conversion Error
* BadSource: rand Set data to result of rand(), which may be zero
* GoodSource: Positive integer
* Sink: memmove
* BadSink : Copy strings using memmove() with the length of data
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
void CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_54e_badSink(int data)
{
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign conversion could result in a very large number */
memmove(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_54e_goodG2BSink(int data)
{
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign conversion could result in a very large number */
memmove(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITGOOD */
| bsd-3-clause |
MITK/MITK | Modules/LegacyIO/mitkSTLFileIOFactory.cpp | 2 | 1108 | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkSTLFileIOFactory.h"
#include "mitkIOAdapter.h"
#include "mitkSTLFileReader.h"
#include "itkVersion.h"
namespace mitk
{
STLFileIOFactory::STLFileIOFactory()
{
this->RegisterOverride("mitkIOAdapter",
"mitkSTLFileReader",
"mitk STL Surface IO",
true,
itk::CreateObjectFunction<IOAdapter<STLFileReader>>::New());
}
STLFileIOFactory::~STLFileIOFactory() {}
const char *STLFileIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; }
const char *STLFileIOFactory::GetDescription() const { return "STLFile IO Factory, allows the loading of STL files"; }
} // end namespace mitk
| bsd-3-clause |
coreboot/chrome-ec | driver/als_isl29035.c | 2 | 2130 | /* Copyright 2013 The ChromiumOS Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Intersil ILS29035 light sensor driver
*/
#include "driver/als_isl29035.h"
#include "i2c.h"
/* I2C interface */
#define ILS29035_I2C_ADDR_FLAGS 0x44
#define ILS29035_REG_COMMAND_I 0
#define ILS29035_REG_COMMAND_II 1
#define ILS29035_REG_DATA_LSB 2
#define ILS29035_REG_DATA_MSB 3
#define ILS29035_REG_INT_LT_LSB 4
#define ILS29035_REG_INT_LT_MSB 5
#define ILS29035_REG_INT_HT_LSB 6
#define ILS29035_REG_INT_HT_MSB 7
#define ILS29035_REG_ID 15
int isl29035_init(void)
{
/*
* Tell it to read continually. This uses 70uA, as opposed to nearly
* zero, but it makes the hook/update code cleaner (we don't want to
* wait 90ms to read on demand while processing hook callbacks).
*/
return i2c_write8(I2C_PORT_ALS, ILS29035_I2C_ADDR_FLAGS,
ILS29035_REG_COMMAND_I, 0xa0);
}
int isl29035_read_lux(int *lux, int af)
{
int rv, lsb, msb, data;
/*
* NOTE: It is necessary to read the LSB first, then the MSB. If you do
* it in the opposite order, the results are not correct. This is
* apparently an undocumented "feature". It's especially noticeable in
* one-shot mode.
*/
/* Read lsb */
rv = i2c_read8(I2C_PORT_ALS, ILS29035_I2C_ADDR_FLAGS,
ILS29035_REG_DATA_LSB, &lsb);
if (rv)
return rv;
/* Read msb */
rv = i2c_read8(I2C_PORT_ALS, ILS29035_I2C_ADDR_FLAGS,
ILS29035_REG_DATA_MSB, &msb);
if (rv)
return rv;
data = (msb << 8) | lsb;
/*
* The default power-on values will give 16 bits of precision:
* 0x0000-0xffff indicates 0-1000 lux. We multiply the sensor value by
* a scaling factor to account for attentuation by glass, tinting, etc.
*
* Caution: Don't go nuts with the attentuation factor. If it's
* greater than 32, the signed int math will roll over and you'll get
* very wrong results. Of course, if you have that much attenuation and
* are still getting useful readings, you probably have your sensor
* pointed directly into the sun.
*/
*lux = data * af * 1000 / 0xffff;
return EC_SUCCESS;
}
| bsd-3-clause |
igor-m/retrobsd-with-double-precison | sys/kernel/sys_inode.c | 2 | 17236 | /*
* Copyright (c) 1986 Regents of the University of California.
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*/
#include "param.h"
#include "user.h"
#include "proc.h"
#include "signalvar.h"
#include "inode.h"
#include "buf.h"
#include "fs.h"
#include "file.h"
#include "stat.h"
#include "mount.h"
#include "conf.h"
#include "uio.h"
#include "ioctl.h"
#include "tty.h"
#include "kernel.h"
#include "systm.h"
#include "syslog.h"
daddr_t rablock; /* block to be read ahead */
int
ino_rw(fp, uio)
struct file *fp;
register struct uio *uio;
{
register struct inode *ip = (struct inode *)fp->f_data;
u_int count, error;
int ioflag;
if ((ip->i_mode&IFMT) != IFCHR)
ILOCK(ip);
uio->uio_offset = fp->f_offset;
count = uio->uio_resid;
if (uio->uio_rw == UIO_READ) {
error = rwip(ip, uio, fp->f_flag & FNONBLOCK ? IO_NDELAY : 0);
fp->f_offset += (count - uio->uio_resid);
} else {
ioflag = 0;
if ((ip->i_mode&IFMT) == IFREG && (fp->f_flag & FAPPEND))
ioflag |= IO_APPEND;
if (fp->f_flag & FNONBLOCK)
ioflag |= IO_NDELAY;
if (fp->f_flag & FFSYNC ||
(ip->i_fs->fs_flags & MNT_SYNCHRONOUS))
ioflag |= IO_SYNC;
error = rwip(ip, uio, ioflag);
if (ioflag & IO_APPEND)
fp->f_offset = uio->uio_offset;
else
fp->f_offset += (count - uio->uio_resid);
}
if ((ip->i_mode&IFMT) != IFCHR)
IUNLOCK(ip);
return (error);
}
int
ino_ioctl(fp, com, data)
register struct file *fp;
register u_int com;
caddr_t data;
{
register struct inode *ip = ((struct inode *)fp->f_data);
dev_t dev;
switch (ip->i_mode & IFMT) {
case IFREG:
case IFDIR:
if (com == FIONREAD) {
if (fp->f_type==DTYPE_PIPE && !(fp->f_flag&FREAD))
*(off_t *)data = 0;
else
*(off_t *)data = ip->i_size - fp->f_offset;
return (0);
}
if (com == FIONBIO || com == FIOASYNC) /* XXX */
return (0); /* XXX */
/* fall into ... */
default:
return (ENOTTY);
case IFCHR:
dev = ip->i_rdev;
u.u_rval = 0;
if (setjmp(&u.u_qsave)) {
/*
* The ONLY way we can get here is via the longjump in sleep. Signals have
* been checked for and u_error set accordingly. All that remains to do
* is 'return'.
*/
return(u.u_error);
}
return((*cdevsw[major(dev)].d_ioctl)(dev,com,data,fp->f_flag));
case IFBLK:
dev = ip->i_rdev;
u.u_rval = 0;
if (setjmp(&u.u_qsave)) {
/*
* The ONLY way we can get here is via the longjump in sleep. Signals have
* been checked for and u_error set accordingly. All that remains to do
* is 'return'.
*/
return(u.u_error);
}
return((*bdevsw[major(dev)].d_ioctl)(dev,com,data,fp->f_flag));
}
}
int
ino_select(fp, which)
struct file *fp;
int which;
{
register struct inode *ip = (struct inode *)fp->f_data;
register dev_t dev;
switch (ip->i_mode & IFMT) {
default:
return (1); /* XXX */
case IFCHR:
dev = ip->i_rdev;
return (*cdevsw[major(dev)].d_select)(dev, which);
}
}
const struct fileops inodeops = {
ino_rw, ino_ioctl, ino_select, vn_closefile
};
int
rdwri (rw, ip, base, len, offset, ioflg, aresid)
enum uio_rw rw;
struct inode *ip;
caddr_t base;
int len;
off_t offset;
int ioflg;
register int *aresid;
{
struct uio auio;
struct iovec aiov;
register int error;
auio.uio_iov = &aiov;
auio.uio_iovcnt = 1;
aiov.iov_base = base;
aiov.iov_len = len;
auio.uio_rw = rw;
auio.uio_resid = len;
auio.uio_offset = offset;
error = rwip(ip, &auio, ioflg);
if (aresid)
*aresid = auio.uio_resid;
else
if (auio.uio_resid)
error = EIO;
return (error);
}
int
rwip (ip, uio, ioflag)
register struct inode *ip;
register struct uio *uio;
int ioflag;
{
dev_t dev = (dev_t)ip->i_rdev;
register struct buf *bp;
off_t osize;
daddr_t lbn, bn;
int n, on, type, resid;
int error = 0;
int flags;
//if (uio->uio_offset < 0)
//return (EINVAL);
type = ip->i_mode & IFMT;
/*
* The write case below checks that i/o is done synchronously to directories
* and that i/o to append only files takes place at the end of file.
* We do not panic on non-sync directory i/o - the sync bit is forced on.
*/
if (uio->uio_rw == UIO_READ) {
if (! (ip->i_fs->fs_flags & MNT_NOATIME))
ip->i_flag |= IACC;
} else {
switch (type) {
case IFREG:
if (ioflag & IO_APPEND)
uio->uio_offset = ip->i_size;
if (ip->i_flags & APPEND && uio->uio_offset != ip->i_size)
return(EPERM);
break;
case IFDIR:
if ((ioflag & IO_SYNC) == 0)
ioflag |= IO_SYNC;
break;
case IFLNK:
case IFBLK:
case IFCHR:
break;
default:
return (EFTYPE);
}
}
/*
* The IO_SYNC flag is turned off here if the 'async' mount flag is on.
* Otherwise directory I/O (which is done by the kernel) would still
* synchronous (because the kernel carefully passes IO_SYNC for all directory
* I/O) even if the fs was mounted with "-o async".
*
* A side effect of this is that if the system administrator mounts a filesystem
* 'async' then the O_FSYNC flag to open() is ignored.
*
* This behaviour should probably be selectable via "sysctl fs.async.dirs" and
* "fs.async.ofsync". A project for a rainy day.
*/
if (type == IFREG || (type == IFDIR && (ip->i_fs->fs_flags & MNT_ASYNC)))
ioflag &= ~IO_SYNC;
if (type == IFCHR) {
if (uio->uio_rw == UIO_READ) {
if (! (ip->i_fs->fs_flags & MNT_NOATIME))
ip->i_flag |= IACC;
error = (*cdevsw[major(dev)].d_read)(dev, uio, ioflag);
} else {
ip->i_flag |= IUPD|ICHG;
error = (*cdevsw[major(dev)].d_write)(dev, uio, ioflag);
}
return (error);
}
if (uio->uio_resid == 0)
return (0);
if (uio->uio_rw == UIO_WRITE && type == IFREG &&
uio->uio_offset + uio->uio_resid >
u.u_rlimit[RLIMIT_FSIZE].rlim_cur) {
psignal(u.u_procp, SIGXFSZ);
return (EFBIG);
}
if (type != IFBLK)
dev = ip->i_dev;
resid = uio->uio_resid;
osize = ip->i_size;
flags = ioflag & IO_SYNC ? B_SYNC : 0;
do {
lbn = lblkno(uio->uio_offset);
on = blkoff(uio->uio_offset);
n = MIN((u_int)(DEV_BSIZE - on), uio->uio_resid);
if (type != IFBLK) {
if (uio->uio_rw == UIO_READ) {
off_t diff = ip->i_size - uio->uio_offset;
if (diff <= 0)
return (0);
if (diff < n)
n = diff;
bn = bmap(ip, lbn, B_READ, flags);
} else
bn = bmap(ip,lbn,B_WRITE,
n == DEV_BSIZE ? flags : flags|B_CLRBUF);
if (u.u_error || (uio->uio_rw == UIO_WRITE && (long)bn < 0))
return (u.u_error);
if (uio->uio_rw == UIO_WRITE && uio->uio_offset + n > ip->i_size &&
(type == IFDIR || type == IFREG || type == IFLNK))
ip->i_size = uio->uio_offset + n;
} else {
bn = lbn;
rablock = bn + 1;
}
if (uio->uio_rw == UIO_READ) {
if ((long)bn < 0) {
bp = geteblk();
bzero (bp->b_addr, MAXBSIZE);
} else if (ip->i_lastr + 1 == lbn)
bp = breada (dev, bn, rablock);
else
bp = bread (dev, bn);
ip->i_lastr = lbn;
} else {
if (n == DEV_BSIZE)
bp = getblk (dev, bn);
else
bp = bread (dev, bn);
/*
* 4.3 didn't do this, but 2.10 did. not sure why.
* something about tape drivers don't clear buffers on end-of-tape
* any longer (clrbuf can't be called from interrupt).
*/
if (bp->b_resid == DEV_BSIZE) {
bp->b_resid = 0;
bzero (bp->b_addr, MAXBSIZE);
}
}
n = MIN(n, DEV_BSIZE - bp->b_resid);
if (bp->b_flags & B_ERROR) {
error = EIO;
brelse(bp);
break;
}
u.u_error = uiomove (bp->b_addr + on, n, uio);
if (uio->uio_rw == UIO_READ) {
if (n + on == DEV_BSIZE || uio->uio_offset == ip->i_size) {
bp->b_flags |= B_AGE;
if (ip->i_flag & IPIPE)
bp->b_flags &= ~B_DELWRI;
}
brelse(bp);
} else {
if (ioflag & IO_SYNC)
bwrite(bp);
/*
* The check below interacts _very_ badly with virtual memory tmp files
* such as those used by 'ld'. These files tend to be small and repeatedly
* rewritten in 1kb chunks. The check below causes the device driver to be
* called (and I/O initiated) constantly. Not sure what to do about this yet
* but this comment is being placed here as a reminder.
*/
else if (n + on == DEV_BSIZE && !(ip->i_flag & IPIPE)) {
bp->b_flags |= B_AGE;
bawrite(bp);
} else
bdwrite(bp);
ip->i_flag |= IUPD|ICHG;
if (u.u_ruid != 0)
ip->i_mode &= ~(ISUID|ISGID);
}
} while (u.u_error == 0 && uio->uio_resid && n != 0);
if (error == 0) /* XXX */
error = u.u_error; /* XXX */
if (error && (uio->uio_rw == UIO_WRITE) && (ioflag & IO_UNIT) &&
(type != IFBLK)) {
itrunc(ip, osize, ioflag & IO_SYNC);
uio->uio_offset -= (resid - uio->uio_resid);
uio->uio_resid = resid;
/*
* Should back out the change to the quota here but that would be a lot
* of work for little benefit. Besides we've already made the assumption
* that the entire write would succeed and users can't turn on the IO_UNIT
* bit for their writes anyways.
*/
}
#ifdef whybother
if (! error && (ioflag & IO_SYNC))
IUPDAT(ip, &time, &time, 1);
#endif
return (error);
}
int
ino_stat(ip, sb)
register struct inode *ip;
register struct stat *sb;
{
register struct icommon2 *ic2;
ic2 = &ip->i_ic2;
/*
* inlined ITIMES which takes advantage of the common times pointer.
*/
if (ip->i_flag & (IUPD|IACC|ICHG)) {
ip->i_flag |= IMOD;
if (ip->i_flag & IACC)
ic2->ic_atime = time.tv_sec;
if (ip->i_flag & IUPD)
ic2->ic_mtime = time.tv_sec;
if (ip->i_flag & ICHG)
ic2->ic_ctime = time.tv_sec;
ip->i_flag &= ~(IUPD|IACC|ICHG);
}
sb->st_dev = ip->i_dev;
sb->st_ino = ip->i_number;
sb->st_mode = ip->i_mode;
sb->st_nlink = ip->i_nlink;
sb->st_uid = ip->i_uid;
sb->st_gid = ip->i_gid;
sb->st_rdev = (dev_t)ip->i_rdev;
sb->st_size = ip->i_size;
sb->st_atime = ic2->ic_atime;
sb->st_mtime = ic2->ic_mtime;
sb->st_ctime = ic2->ic_ctime;
sb->st_blksize = MAXBSIZE;
/*
* blocks are too tough to do; it's not worth the effort.
*/
sb->st_blocks = btod (ip->i_size);
sb->st_flags = ip->i_flags;
return (0);
}
/*
* This routine, like its counterpart openi(), calls the device driver for
* special (IBLK, ICHR) files. Normal files simply return early (the default
* case in the switch statement). Pipes and sockets do NOT come here because
* they have their own close routines.
*/
int
closei (ip, flag)
register struct inode *ip;
int flag;
{
register struct mount *mp;
register struct file *fp;
int mode, error;
dev_t dev;
int (*cfunc)();
mode = ip->i_mode & IFMT;
dev = ip->i_rdev;
switch (mode) {
case IFCHR:
cfunc = cdevsw[major(dev)].d_close;
break;
case IFBLK:
/*
* We don't want to really close the device if it is mounted
*/
/* MOUNT TABLE SHOULD HOLD INODE */
for (mp = mount; mp < &mount[NMOUNT]; mp++)
if (mp->m_inodp != NULL && mp->m_dev == dev)
return(0);
cfunc = bdevsw[major(dev)].d_close;
break;
default:
return(0);
}
/*
* Check that another inode for the same device isn't active.
* This is because the same device can be referenced by two
* different inodes.
*/
for (fp = file; fp < file+NFILE; fp++) {
if (fp->f_type != DTYPE_INODE)
continue;
if (fp->f_count && (ip = (struct inode *)fp->f_data) &&
ip->i_rdev == dev && (ip->i_mode&IFMT) == mode)
return(0);
}
if (mode == IFBLK) {
/*
* On last close of a block device (that isn't mounted)
* we must invalidate any in core blocks, so that
* we can, for instance, change floppy disks.
*/
bflush(dev);
binval(dev);
}
/*
* NOTE: none of the device drivers appear to either set u_error OR return
* anything meaningful from their close routines. It's a good thing
* programs don't bother checking the error status on close() calls.
* Apparently the only time "errno" is meaningful after a "close" is
* when the process is interrupted.
*/
if (setjmp (&u.u_qsave)) {
/*
* If device close routine is interrupted,
* must return so closef can clean up.
*/
if ((error = u.u_error) == 0)
error = EINTR;
} else
error = (*cfunc)(dev, flag, mode);
return (error);
}
/*
* Place an advisory lock on an inode.
* NOTE: callers of this routine must be prepared to deal with the pseudo
* error return ERESTART.
*/
int
ino_lock(fp, cmd)
register struct file *fp;
int cmd;
{
register int priority = PLOCK;
register struct inode *ip = (struct inode *)fp->f_data;
int error;
if ((cmd & LOCK_EX) == 0)
priority += 4;
/*
* If there's a exclusive lock currently applied to the file then we've
* gotta wait for the lock with everyone else.
*
* NOTE: We can NOT sleep on i_exlockc because it is on an odd byte boundary
* and the low (oddness) bit is reserved for networking/supervisor mode
* sleep channels. Thus we always sleep on i_shlockc and simply check
* the proper bits to see if the lock we want is granted. This may
* mean an extra wakeup/sleep event is done once in a while but
* everything will work correctly.
*/
again:
while (ip->i_flag & IEXLOCK) {
/*
* If we're holding an exclusive
* lock, then release it.
*/
if (fp->f_flag & FEXLOCK) {
ino_unlock(fp, FEXLOCK);
continue;
}
if (cmd & LOCK_NB)
return (EWOULDBLOCK);
ip->i_flag |= ILWAIT;
error = tsleep((caddr_t)&ip->i_shlockc, priority | PCATCH, 0);
if (error)
return(error);
}
if ((cmd & LOCK_EX) && (ip->i_flag & ISHLOCK)) {
/*
* Must wait for any shared locks to finish
* before we try to apply a exclusive lock.
*
* If we're holding a shared
* lock, then release it.
*/
if (fp->f_flag & FSHLOCK) {
ino_unlock(fp, FSHLOCK);
goto again;
}
if (cmd & LOCK_NB)
return (EWOULDBLOCK);
ip->i_flag |= ILWAIT;
error = tsleep((caddr_t)&ip->i_shlockc, PLOCK | PCATCH, 0);
if (error)
return(error);
goto again;
}
if (cmd & LOCK_EX) {
cmd &= ~LOCK_SH;
ip->i_exlockc++;
ip->i_flag |= IEXLOCK;
fp->f_flag |= FEXLOCK;
}
if ((cmd & LOCK_SH) && (fp->f_flag & FSHLOCK) == 0) {
ip->i_shlockc++;
ip->i_flag |= ISHLOCK;
fp->f_flag |= FSHLOCK;
}
return (0);
}
/*
* Unlock a file.
*/
void
ino_unlock(fp, kind)
register struct file *fp;
int kind;
{
register struct inode *ip = (struct inode *)fp->f_data;
register int flags;
kind &= fp->f_flag;
if (ip == NULL || kind == 0)
return;
flags = ip->i_flag;
if (kind & FSHLOCK) {
if (--ip->i_shlockc == 0) {
ip->i_flag &= ~ISHLOCK;
if (flags & ILWAIT)
wakeup((caddr_t)&ip->i_shlockc);
}
fp->f_flag &= ~FSHLOCK;
}
if (kind & FEXLOCK) {
if (--ip->i_exlockc == 0) {
ip->i_flag &= ~(IEXLOCK|ILWAIT);
if (flags & ILWAIT)
wakeup((caddr_t)&ip->i_shlockc);
}
fp->f_flag &= ~FEXLOCK;
}
}
/*
* Openi called to allow handler of special files to initialize and
* validate before actual IO.
*/
int
openi (ip, mode)
register struct inode *ip;
{
register dev_t dev = ip->i_rdev;
register int maj = major(dev);
dev_t bdev;
int error;
switch (ip->i_mode&IFMT) {
case IFCHR:
if (ip->i_fs->fs_flags & MNT_NODEV)
return(ENXIO);
if ((u_int)maj >= nchrdev)
return (ENXIO);
if (mode & FWRITE) {
/*
* When running in very secure mode, do not allow
* opens for writing of any disk character devices.
*/
if (securelevel >= 2 && isdisk(dev, IFCHR))
return(EPERM);
/*
* When running in secure mode, do not allow opens
* for writing of /dev/mem, /dev/kmem, or character
* devices whose corresponding block devices are
* currently mounted.
*/
if (securelevel >= 1) {
if ((bdev = chrtoblk(dev)) != NODEV &&
(error = ufs_mountedon(bdev)))
return(error);
if (iskmemdev(dev))
return(EPERM);
}
}
return ((*cdevsw[maj].d_open)(dev, mode, S_IFCHR));
case IFBLK:
if (ip->i_fs->fs_flags & MNT_NODEV)
return(ENXIO);
if ((u_int)maj >= nblkdev)
return (ENXIO);
/*
* When running in very secure mode, do not allow
* opens for writing of any disk block devices.
*/
if (securelevel >= 2 && (mode & FWRITE) && isdisk(dev, IFBLK))
return(EPERM);
/*
* Do not allow opens of block devices that are
* currently mounted.
*
* 2.11BSD must relax this restriction to allow 'fsck' to
* open the root filesystem (which is always mounted) during
* a reboot. Once in secure or very secure mode the
* above restriction is fully effective. On the otherhand
* fsck should 1) use the raw device, 2) not do sync calls...
*/
if (securelevel > 0 && (error = ufs_mountedon(dev)))
return(error);
return ((*bdevsw[maj].d_open)(dev, mode, S_IFBLK));
}
return (0);
}
static void
forceclose(dev)
register dev_t dev;
{
register struct file *fp;
register struct inode *ip;
for (fp = file; fp < file+NFILE; fp++) {
if (fp->f_count == 0)
continue;
if (fp->f_type != DTYPE_INODE)
continue;
ip = (struct inode *)fp->f_data;
if (ip == 0)
continue;
if ((ip->i_mode & IFMT) != IFCHR)
continue;
if (ip->i_rdev != dev)
continue;
fp->f_flag &= ~(FREAD | FWRITE);
}
}
/*
* Revoke access the current tty by all processes.
* Used only by the super-user in init
* to give ``clean'' terminals at login.
*/
void
vhangup()
{
if (! suser())
return;
if (u.u_ttyp == NULL)
return;
forceclose(u.u_ttyd);
if ((u.u_ttyp->t_state) & TS_ISOPEN)
gsignal(u.u_ttyp->t_pgrp, SIGHUP);
}
| bsd-3-clause |
youtube/cobalt_sandbox | third_party/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFDebugLoc.cpp | 3 | 7834 | //===- DWARFDebugLoc.cpp --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
#include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/WithColor.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cinttypes>
#include <cstdint>
using namespace llvm;
// When directly dumping the .debug_loc without a compile unit, we have to guess
// at the DWARF version. This only affects DW_OP_call_ref, which is a rare
// expression that LLVM doesn't produce. Guessing the wrong version means we
// won't be able to pretty print expressions in DWARF2 binaries produced by
// non-LLVM tools.
static void dumpExpression(raw_ostream &OS, ArrayRef<char> Data,
bool IsLittleEndian, unsigned AddressSize,
const MCRegisterInfo *MRI) {
DWARFDataExtractor Extractor(StringRef(Data.data(), Data.size()),
IsLittleEndian, AddressSize);
DWARFExpression(Extractor, dwarf::DWARF_VERSION, AddressSize).print(OS, MRI);
}
void DWARFDebugLoc::LocationList::dump(raw_ostream &OS, bool IsLittleEndian,
unsigned AddressSize,
const MCRegisterInfo *MRI,
uint64_t BaseAddress,
unsigned Indent) const {
for (const Entry &E : Entries) {
OS << '\n';
OS.indent(Indent);
OS << format("[0x%*.*" PRIx64 ", ", AddressSize * 2, AddressSize * 2,
BaseAddress + E.Begin);
OS << format(" 0x%*.*" PRIx64 ")", AddressSize * 2, AddressSize * 2,
BaseAddress + E.End);
OS << ": ";
dumpExpression(OS, E.Loc, IsLittleEndian, AddressSize, MRI);
}
}
DWARFDebugLoc::LocationList const *
DWARFDebugLoc::getLocationListAtOffset(uint64_t Offset) const {
auto It = std::lower_bound(
Locations.begin(), Locations.end(), Offset,
[](const LocationList &L, uint64_t Offset) { return L.Offset < Offset; });
if (It != Locations.end() && It->Offset == Offset)
return &(*It);
return nullptr;
}
void DWARFDebugLoc::dump(raw_ostream &OS, const MCRegisterInfo *MRI,
Optional<uint64_t> Offset) const {
auto DumpLocationList = [&](const LocationList &L) {
OS << format("0x%8.8x: ", L.Offset);
L.dump(OS, IsLittleEndian, AddressSize, MRI, 0, 12);
OS << "\n\n";
};
if (Offset) {
if (auto *L = getLocationListAtOffset(*Offset))
DumpLocationList(*L);
return;
}
for (const LocationList &L : Locations) {
DumpLocationList(L);
}
}
Optional<DWARFDebugLoc::LocationList>
DWARFDebugLoc::parseOneLocationList(DWARFDataExtractor Data, unsigned *Offset) {
LocationList LL;
LL.Offset = *Offset;
// 2.6.2 Location Lists
// A location list entry consists of:
while (true) {
Entry E;
if (!Data.isValidOffsetForDataOfSize(*Offset, 2 * Data.getAddressSize())) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
// 1. A beginning address offset. ...
E.Begin = Data.getRelocatedAddress(Offset);
// 2. An ending address offset. ...
E.End = Data.getRelocatedAddress(Offset);
// The end of any given location list is marked by an end of list entry,
// which consists of a 0 for the beginning address offset and a 0 for the
// ending address offset.
if (E.Begin == 0 && E.End == 0)
return LL;
if (!Data.isValidOffsetForDataOfSize(*Offset, 2)) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
unsigned Bytes = Data.getU16(Offset);
if (!Data.isValidOffsetForDataOfSize(*Offset, Bytes)) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
// A single location description describing the location of the object...
StringRef str = Data.getData().substr(*Offset, Bytes);
*Offset += Bytes;
E.Loc.reserve(str.size());
std::copy(str.begin(), str.end(), std::back_inserter(E.Loc));
LL.Entries.push_back(std::move(E));
}
}
void DWARFDebugLoc::parse(const DWARFDataExtractor &data) {
IsLittleEndian = data.isLittleEndian();
AddressSize = data.getAddressSize();
uint32_t Offset = 0;
while (data.isValidOffset(Offset + data.getAddressSize() - 1)) {
if (auto LL = parseOneLocationList(data, &Offset))
Locations.push_back(std::move(*LL));
else
break;
}
if (data.isValidOffset(Offset))
WithColor::error() << "failed to consume entire .debug_loc section\n";
}
Optional<DWARFDebugLocDWO::LocationList>
DWARFDebugLocDWO::parseOneLocationList(DataExtractor Data, unsigned *Offset) {
LocationList LL;
LL.Offset = *Offset;
// dwarf::DW_LLE_end_of_list_entry is 0 and indicates the end of the list.
while (auto Kind =
static_cast<dwarf::LocationListEntry>(Data.getU8(Offset))) {
if (Kind != dwarf::DW_LLE_startx_length) {
WithColor::error() << "dumping support for LLE of kind " << (int)Kind
<< " not implemented\n";
return None;
}
Entry E;
E.Start = Data.getULEB128(Offset);
E.Length = Data.getU32(Offset);
unsigned Bytes = Data.getU16(Offset);
// A single location description describing the location of the object...
StringRef str = Data.getData().substr(*Offset, Bytes);
*Offset += Bytes;
E.Loc.resize(str.size());
std::copy(str.begin(), str.end(), E.Loc.begin());
LL.Entries.push_back(std::move(E));
}
return LL;
}
void DWARFDebugLocDWO::parse(DataExtractor data) {
IsLittleEndian = data.isLittleEndian();
AddressSize = data.getAddressSize();
uint32_t Offset = 0;
while (data.isValidOffset(Offset)) {
if (auto LL = parseOneLocationList(data, &Offset))
Locations.push_back(std::move(*LL));
else
return;
}
}
DWARFDebugLocDWO::LocationList const *
DWARFDebugLocDWO::getLocationListAtOffset(uint64_t Offset) const {
auto It = std::lower_bound(
Locations.begin(), Locations.end(), Offset,
[](const LocationList &L, uint64_t Offset) { return L.Offset < Offset; });
if (It != Locations.end() && It->Offset == Offset)
return &(*It);
return nullptr;
}
void DWARFDebugLocDWO::LocationList::dump(raw_ostream &OS, bool IsLittleEndian,
unsigned AddressSize,
const MCRegisterInfo *MRI,
unsigned Indent) const {
for (const Entry &E : Entries) {
OS << '\n';
OS.indent(Indent);
OS << "Addr idx " << E.Start << " (w/ length " << E.Length << "): ";
dumpExpression(OS, E.Loc, IsLittleEndian, AddressSize, MRI);
}
}
void DWARFDebugLocDWO::dump(raw_ostream &OS, const MCRegisterInfo *MRI,
Optional<uint64_t> Offset) const {
auto DumpLocationList = [&](const LocationList &L) {
OS << format("0x%8.8x: ", L.Offset);
L.dump(OS, IsLittleEndian, AddressSize, MRI, /*Indent=*/12);
OS << "\n\n";
};
if (Offset) {
if (auto *L = getLocationListAtOffset(*Offset))
DumpLocationList(*L);
return;
}
for (const LocationList &L : Locations) {
DumpLocationList(L);
}
}
| bsd-3-clause |
daviddoria/PCLMirror | doc/tutorials/content/sources/pcl_visualizer/pcl_visualizer_demo.cpp | 3 | 14389 | /* \author Geoffrey Biggs */
#include <iostream>
#include <boost/thread/thread.hpp>
#include <pcl/common/common_headers.h>
#include <pcl/common/common_headers.h>
#include <pcl/features/normal_3d.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/console/parse.h>
// --------------
// -----Help-----
// --------------
void
printUsage (const char* progName)
{
std::cout << "\n\nUsage: "<<progName<<" [options]\n\n"
<< "Options:\n"
<< "-------------------------------------------\n"
<< "-h this help\n"
<< "-s Simple visualisation example\n"
<< "-r RGB colour visualisation example\n"
<< "-c Custom colour visualisation example\n"
<< "-n Normals visualisation example\n"
<< "-a Shapes visualisation example\n"
<< "-v Viewports example\n"
<< "-i Interaction Customization example\n"
<< "\n\n";
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
viewer->addPointCloud<pcl::PointXYZ> (cloud, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> rgbVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> customColourVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(cloud, 0, 255, 0);
viewer->addPointCloud<pcl::PointXYZ> (cloud, single_color, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> normalsVis (
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals)
{
// --------------------------------------------------------
// -----Open 3D viewer and add point cloud and normals-----
// --------------------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals, 10, 0.05, "normals");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> shapesVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
//------------------------------------
//-----Add shapes at cloud points-----
//------------------------------------
viewer->addLine<pcl::PointXYZRGB> (cloud->points[0],
cloud->points[cloud->size() - 1], "line");
viewer->addSphere (cloud->points[0], 0.2, 0.5, 0.5, 0.0, "sphere");
//---------------------------------------
//-----Add shapes at other locations-----
//---------------------------------------
pcl::ModelCoefficients coeffs;
coeffs.values.push_back (0.0);
coeffs.values.push_back (0.0);
coeffs.values.push_back (1.0);
coeffs.values.push_back (0.0);
viewer->addPlane (coeffs, "plane");
coeffs.values.clear ();
coeffs.values.push_back (0.3);
coeffs.values.push_back (0.3);
coeffs.values.push_back (0.0);
coeffs.values.push_back (0.0);
coeffs.values.push_back (1.0);
coeffs.values.push_back (0.0);
coeffs.values.push_back (5.0);
viewer->addCone (coeffs, "cone");
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewportsVis (
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals1, pcl::PointCloud<pcl::Normal>::ConstPtr normals2)
{
// --------------------------------------------------------
// -----Open 3D viewer and add point cloud and normals-----
// --------------------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->initCameraParameters ();
int v1(0);
viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1);
viewer->setBackgroundColor (0, 0, 0, v1);
viewer->addText("Radius: 0.01", 10, 10, "v1 text", v1);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud1", v1);
int v2(0);
viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2);
viewer->setBackgroundColor (0.3, 0.3, 0.3, v2);
viewer->addText("Radius: 0.1", 10, 10, "v2 text", v2);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> single_color(cloud, 0, 255, 0);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, single_color, "sample cloud2", v2);
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud1");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud2");
viewer->addCoordinateSystem (1.0);
viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals1, 10, 0.05, "normals1", v1);
viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals2, 10, 0.05, "normals2", v2);
return (viewer);
}
unsigned int text_id = 0;
void keyboardEventOccurred (const pcl::visualization::KeyboardEvent &event,
void* viewer_void)
{
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = *static_cast<boost::shared_ptr<pcl::visualization::PCLVisualizer> *> (viewer_void);
if (event.getKeySym () == "r" && event.keyDown ())
{
std::cout << "r was pressed => removing all text" << std::endl;
char str[512];
for (unsigned int i = 0; i < text_id; ++i)
{
sprintf (str, "text#%03d", i);
viewer->removeShape (str);
}
text_id = 0;
}
}
void mouseEventOccurred (const pcl::visualization::MouseEvent &event,
void* viewer_void)
{
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = *static_cast<boost::shared_ptr<pcl::visualization::PCLVisualizer> *> (viewer_void);
if (event.getButton () == pcl::visualization::MouseEvent::LeftButton &&
event.getType () == pcl::visualization::MouseEvent::MouseButtonRelease)
{
std::cout << "Left mouse button released at position (" << event.getX () << ", " << event.getY () << ")" << std::endl;
char str[512];
sprintf (str, "text#%03d", text_id ++);
viewer->addText ("clicked here", event.getX (), event.getY (), str);
}
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> interactionCustomizationVis ()
{
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
viewer->addCoordinateSystem (1.0);
viewer->registerKeyboardCallback (keyboardEventOccurred, (void*)&viewer);
viewer->registerMouseCallback (mouseEventOccurred, (void*)&viewer);
return (viewer);
}
// --------------
// -----Main-----
// --------------
int
main (int argc, char** argv)
{
// --------------------------------------
// -----Parse Command Line Arguments-----
// --------------------------------------
if (pcl::console::find_argument (argc, argv, "-h") >= 0)
{
printUsage (argv[0]);
return 0;
}
bool simple(false), rgb(false), custom_c(false), normals(false),
shapes(false), viewports(false), interaction_customization(false);
if (pcl::console::find_argument (argc, argv, "-s") >= 0)
{
simple = true;
std::cout << "Simple visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-c") >= 0)
{
custom_c = true;
std::cout << "Custom colour visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-r") >= 0)
{
rgb = true;
std::cout << "RGB colour visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-n") >= 0)
{
normals = true;
std::cout << "Normals visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-a") >= 0)
{
shapes = true;
std::cout << "Shapes visualisation example\n";
}
else if (pcl::console::find_argument (argc, argv, "-v") >= 0)
{
viewports = true;
std::cout << "Viewports example\n";
}
else if (pcl::console::find_argument (argc, argv, "-i") >= 0)
{
interaction_customization = true;
std::cout << "Interaction Customization example\n";
}
else
{
printUsage (argv[0]);
return 0;
}
// ------------------------------------
// -----Create example point cloud-----
// ------------------------------------
pcl::PointCloud<pcl::PointXYZ>::Ptr basic_cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr point_cloud_ptr (new pcl::PointCloud<pcl::PointXYZRGB>);
std::cout << "Genarating example point clouds.\n\n";
// We're going to make an ellipse extruded along the z-axis. The colour for
// the XYZRGB cloud will gradually go from red to green to blue.
uint8_t r(255), g(15), b(15);
for (float z(-1.0); z <= 1.0; z += 0.05)
{
for (float angle(0.0); angle <= 360.0; angle += 5.0)
{
pcl::PointXYZ basic_point;
basic_point.x = 0.5 * cosf (pcl::deg2rad(angle));
basic_point.y = sinf (pcl::deg2rad(angle));
basic_point.z = z;
basic_cloud_ptr->points.push_back(basic_point);
pcl::PointXYZRGB point;
point.x = basic_point.x;
point.y = basic_point.y;
point.z = basic_point.z;
uint32_t rgb = (static_cast<uint32_t>(r) << 16 |
static_cast<uint32_t>(g) << 8 | static_cast<uint32_t>(b));
point.rgb = *reinterpret_cast<float*>(&rgb);
point_cloud_ptr->points.push_back (point);
}
if (z < 0.0)
{
r -= 12;
g += 12;
}
else
{
g -= 12;
b += 12;
}
}
basic_cloud_ptr->width = (int) basic_cloud_ptr->points.size ();
basic_cloud_ptr->height = 1;
point_cloud_ptr->width = (int) point_cloud_ptr->points.size ();
point_cloud_ptr->height = 1;
// ----------------------------------------------------------------
// -----Calculate surface normals with a search radius of 0.05-----
// ----------------------------------------------------------------
pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne;
ne.setInputCloud (point_cloud_ptr);
pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB> ());
ne.setSearchMethod (tree);
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals1 (new pcl::PointCloud<pcl::Normal>);
ne.setRadiusSearch (0.05);
ne.compute (*cloud_normals1);
// ---------------------------------------------------------------
// -----Calculate surface normals with a search radius of 0.1-----
// ---------------------------------------------------------------
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2 (new pcl::PointCloud<pcl::Normal>);
ne.setRadiusSearch (0.1);
ne.compute (*cloud_normals2);
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
if (simple)
{
viewer = simpleVis(basic_cloud_ptr);
}
else if (rgb)
{
viewer = rgbVis(point_cloud_ptr);
}
else if (custom_c)
{
viewer = customColourVis(basic_cloud_ptr);
}
else if (normals)
{
viewer = normalsVis(point_cloud_ptr, cloud_normals2);
}
else if (shapes)
{
viewer = shapesVis(point_cloud_ptr);
}
else if (viewports)
{
viewer = viewportsVis(point_cloud_ptr, cloud_normals1, cloud_normals2);
}
else if (interaction_customization)
{
viewer = interactionCustomizationVis();
}
//--------------------
// -----Main loop-----
//--------------------
while (!viewer->wasStopped ())
{
viewer->spinOnce (100);
boost::this_thread::sleep (boost::posix_time::microseconds (100000));
}
}
| bsd-3-clause |
stephenplaza/NeuTu | neurolabi/c/testscalarfield.c | 3 | 4922 | /* testscalarfield.c
*
* 27-Apr-2008 Initial write: Ting Zhao
*/
#include <stdio.h>
#include <image_lib.h>
#include "tz_constant.h"
#include "tz_stack_draw.h"
#include "tz_local_neuroseg.h"
#include "tz_bifold_neuroseg.h"
#include "tz_stack_stat.h"
#include "tz_farray.h"
#include "tz_geo3d_point_array.h"
#include "tz_geo3d_scalar_field.h"
#include "tz_stack_bwmorph.h"
#include "tz_darray.h"
int main()
{
#if 0
/* Make a label stack */
Stack *stack = Make_Stack(FLOAT32, 100, 100, 50);
Zero_Stack(stack);
#endif
#if 0
/* Make test neuron segment */
Local_Neuroseg *locseg = New_Local_Neuroseg();
Set_Local_Neuroseg(locseg, 1, 2, 24, 0, 0,
NEUROSEG_MAX_CURVATURE, 50, 50, 25);
Print_Local_Neuroseg(locseg);
/* Generate field */
Geo3d_Scalar_Field *field = Local_Neuroseg_Field_S(locseg, 1.0, NULL);
//Print_Geo3d_Scalar_Field(field);
Delete_Local_Neuroseg(locseg);
#endif
#if 0
/* Make bifold neuron segment */
Bifold_Neuroseg *bn = New_Bifold_Neuroseg();
Set_Bifold_Neuroseg(bn, 2, 2, 2, 2, 24, 0.5, 1, 1, 1, 0);
/* Generate field */
Geo3d_Scalar_Field *field = Bifold_Neuroseg_Field(bn, 1.0, NULL);
Geo3d_Scalar_Field_Translate(field, 50, 50, 25);
Delete_Bifold_Neuroseg(bn);
#endif
#if 0
//Print_Geo3d_Scalar_Field(field);
/* Draw it in a stack */
double coef[] = {0.1, 1000.0};
double range[] = {0.0, 10000.0};
Geo3d_Scalar_Field_Draw_Stack(field, stack, coef, range);
int idx;
printf("%g\n", Stack_Max(stack, &idx, NULL));
/* Turn the stack to GREY type */
Translate_Stack(stack, GREY, 1);
printf("%g\n", Stack_Max(stack, &idx, NULL));
/* Make canvas */
Stack *canvas = Make_Stack(COLOR, stack->width, stack->height, stack->depth);
Zero_Stack(canvas);
/* Label the canvas */
Stack_Label_Color(canvas, stack, 5.0, 1.0, stack);
/* Save the stack */
Write_Stack("../data/test.tif", canvas);
/* clean up */
Kill_Geo3d_Scalar_Field(field);
Kill_Stack(stack);
Kill_Stack(canvas);
#endif
#if 0
Geo3d_Scalar_Field *field = Read_Geo3d_Scalar_Field("../data/diadem_e3/seeds");
Print_Geo3d_Scalar_Field(field);
Geo3d_Scalar_Field_Export_V3d_Marker(field, "../data/test.marker");
#endif
#if 0
Stack_Fit_Score fs;
fs.n = 2;
fs.scores[0] = 0.5;
fs.options[0] = 1;
fs.scores[1] = 110.5;
fs.options[1] = 0;
Print_Stack_Fit_Score(&fs);
/*
FILE *fp = fopen("../data/test.bn", "w");
Stack_Fit_Score_Fwrite(&fs, fp);
fclose(fp);
*/
Stack_Fit_Score fs2;
FILE *fp2 = fopen("../data/test.bn", "r");
Stack_Fit_Score_Fread(&fs2, fp2);
fclose(fp2);
Print_Stack_Fit_Score(&fs2);
#endif
#if 0
Geo3d_Scalar_Field *field = Geo3d_Scalar_Field_Import_Apo("/Users/zhaot/Data/jinny/edswc_A copy/edswc_A0002.swc.apo");
Print_Geo3d_Scalar_Field(field);
#endif
#if 0
Geo3d_Ball *ball = New_Geo3d_Ball();
ball->r = 3.0;
Stack *stack = Make_Stack(GREY, 100, 100, 100);
One_Stack(stack);
int i, j, k;
int offset = 0;
for (k = 0; k < stack->depth; k++) {
for (j = 0; j < stack->height; j++) {
for (i = 0; i < stack->width; i++) {
if ((i == 0) || (j == 0) || (k == 0) ||
(i == stack->width-1) || (j == stack->height-1) ||
(k == stack->depth - 1)) {
stack->array[offset] = 0;
}
offset++;
}
}
}
Stack *distmap = Stack_Bwdist_L_U16(stack, NULL, 0);
tic();
Geo3d_Ball_Mean_Shift(ball, distmap, 1.0, 0.5);
printf("%llu\n", toc());
Print_Geo3d_Ball(ball);
#endif
#if 0
Geo3d_Scalar_Field *field1 = Make_Geo3d_Scalar_Field(3);
Set_Coordinate_3d(field1->points[0], 1, 1, 1);
Set_Coordinate_3d(field1->points[1], 2, 2, 2);
Set_Coordinate_3d(field1->points[2], 3, 3, 3);
field1->values[0] = 1;
field1->values[1] = 2;
field1->values[2] = 3;
Geo3d_Scalar_Field *field2 = Make_Geo3d_Scalar_Field(3);
Set_Coordinate_3d(field2->points[0], 4, 4, 4);
Set_Coordinate_3d(field2->points[1], 5, 5, 5);
Set_Coordinate_3d(field2->points[2], 6, 6, 6);
field2->values[0] = 4;
field2->values[1] = 5;
field2->values[2] = 6;
Print_Geo3d_Scalar_Field(field1);
Print_Geo3d_Scalar_Field(field2);
Geo3d_Scalar_Field *field = Make_Geo3d_Scalar_Field(2);
Geo3d_Scalar_Field_Merge(field1, field2, field);
Print_Geo3d_Scalar_Field(field);
#endif
#if 1
Geo3d_Scalar_Field *field1 = Make_Geo3d_Scalar_Field(6);
Set_Coordinate_3d(field1->points[0], 1, 1, 1);
Set_Coordinate_3d(field1->points[1], 2, 4, 2);
Set_Coordinate_3d(field1->points[2], 3, 3, 8);
Set_Coordinate_3d(field1->points[3], 8, 4, 4);
Set_Coordinate_3d(field1->points[4], 3, 5, 5);
Set_Coordinate_3d(field1->points[5], 6, 7, 9);
field1->values[0] = 1;
field1->values[1] = 1;
field1->values[2] = 1;
field1->values[3] = 1;
field1->values[4] = 1;
field1->values[5] = 1;
double vec[9];
double value[3];
Geo3d_Scalar_Field_Pca(field1, value, vec);
darray_print2(vec, 3, 3);
darray_print2(value, 3, 1);
#endif
return 0;
}
| bsd-3-clause |
axinging/chromium-crosswalk | third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp | 3 | 15702 | /*
* Copyright (c) 2011, Google 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:
*
* * 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 Google 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
* 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 "platform/scroll/ScrollAnimator.h"
#include "cc/animation/scroll_offset_animation_curve.h"
#include "platform/TraceEvent.h"
#include "platform/animation/CompositorAnimation.h"
#include "platform/graphics/CompositorFactory.h"
#include "platform/graphics/GraphicsLayer.h"
#include "platform/scroll/MainThreadScrollingReason.h"
#include "platform/scroll/ScrollableArea.h"
#include "public/platform/Platform.h"
#include "public/platform/WebCompositorSupport.h"
#include "wtf/CurrentTime.h"
#include "wtf/PassRefPtr.h"
namespace blink {
namespace {
WebLayer* toWebLayer(GraphicsLayer* layer)
{
return layer ? layer->platformLayer() : nullptr;
}
} // namespace
ScrollAnimatorBase* ScrollAnimatorBase::create(ScrollableArea* scrollableArea)
{
if (scrollableArea && scrollableArea->scrollAnimatorEnabled())
return new ScrollAnimator(scrollableArea);
return new ScrollAnimatorBase(scrollableArea);
}
ScrollAnimator::ScrollAnimator(ScrollableArea* scrollableArea, WTF::TimeFunction timeFunction)
: ScrollAnimatorBase(scrollableArea)
, m_timeFunction(timeFunction)
, m_lastGranularity(ScrollByPixel)
{
}
ScrollAnimator::~ScrollAnimator()
{
}
FloatPoint ScrollAnimator::desiredTargetPosition() const
{
if (m_runState == RunState::WaitingToCancelOnCompositor)
return currentPosition();
return (m_animationCurve || m_runState == RunState::WaitingToSendToCompositor)
? m_targetOffset : currentPosition();
}
bool ScrollAnimator::hasRunningAnimation() const
{
return (m_animationCurve || m_runState == RunState::WaitingToSendToCompositor);
}
FloatSize ScrollAnimator::computeDeltaToConsume(const FloatSize& delta) const
{
FloatPoint pos = desiredTargetPosition();
FloatPoint newPos = toFloatPoint(m_scrollableArea->clampScrollPosition(pos + delta));
return newPos - pos;
}
void ScrollAnimator::resetAnimationState()
{
ScrollAnimatorCompositorCoordinator::resetAnimationState();
if (m_animationCurve)
m_animationCurve.clear();
m_startTime = 0.0;
}
ScrollResult ScrollAnimator::userScroll(
ScrollGranularity granularity, const FloatSize& delta)
{
if (!m_scrollableArea->scrollAnimatorEnabled())
return ScrollAnimatorBase::userScroll(granularity, delta);
TRACE_EVENT0("blink", "ScrollAnimator::scroll");
if (granularity == ScrollByPrecisePixel) {
// Cancel scroll animation because asked to instant scroll.
if (hasRunningAnimation())
cancelAnimation();
return ScrollAnimatorBase::userScroll(granularity, delta);
}
bool needsPostAnimationCleanup = m_runState == RunState::PostAnimationCleanup;
if (m_runState == RunState::PostAnimationCleanup)
resetAnimationState();
FloatSize consumedDelta = computeDeltaToConsume(delta);
FloatPoint targetPos = desiredTargetPosition();
targetPos.move(consumedDelta);
if (willAnimateToOffset(targetPos)) {
m_lastGranularity = granularity;
// Report unused delta only if there is no animation running. See
// comment below regarding scroll latching.
// TODO(bokan): Need to standardize how ScrollAnimators report
// unusedDelta. This differs from ScrollAnimatorMac currently.
return ScrollResult(true, true, 0, 0);
}
// If the run state when this method was called was PostAnimationCleanup and
// we're not starting an animation, stay in PostAnimationCleanup state so
// that the main thread scrolling reason can be removed.
if (needsPostAnimationCleanup)
m_runState = RunState::PostAnimationCleanup;
// Report unused delta only if there is no animation and we are not
// starting one. This ensures we latch for the duration of the
// animation rather than animating multiple scrollers at the same time.
return ScrollResult(false, false, delta.width(), delta.height());
}
bool ScrollAnimator::willAnimateToOffset(const FloatPoint& targetPos)
{
if (m_runState == RunState::PostAnimationCleanup)
resetAnimationState();
if (m_runState == RunState::WaitingToCancelOnCompositor) {
ASSERT(m_animationCurve);
m_targetOffset = targetPos;
if (registerAndScheduleAnimation())
m_runState = RunState::WaitingToCancelOnCompositorButNewScroll;
return true;
}
if (m_animationCurve) {
if ((targetPos - m_targetOffset).isZero())
return true;
m_targetOffset = targetPos;
ASSERT(m_runState == RunState::RunningOnMainThread
|| m_runState == RunState::RunningOnCompositor
|| m_runState == RunState::RunningOnCompositorButNeedsUpdate
|| m_runState == RunState::RunningOnCompositorButNeedsTakeover);
// Running on the main thread, simply update the target offset instead
// of sending to the compositor.
if (m_runState == RunState::RunningOnMainThread) {
m_animationCurve->updateTarget(m_timeFunction() - m_startTime,
compositorOffsetFromBlinkOffset(targetPos));
return true;
}
if (registerAndScheduleAnimation())
m_runState = RunState::RunningOnCompositorButNeedsUpdate;
return true;
}
if ((targetPos - currentPosition()).isZero())
return false;
m_targetOffset = targetPos;
m_startTime = m_timeFunction();
if (registerAndScheduleAnimation())
m_runState = RunState::WaitingToSendToCompositor;
return true;
}
void ScrollAnimator::scrollToOffsetWithoutAnimation(const FloatPoint& offset)
{
m_currentPos = offset;
resetAnimationState();
notifyPositionChanged();
}
void ScrollAnimator::tickAnimation(double monotonicTime)
{
if (m_runState != RunState::RunningOnMainThread)
return;
TRACE_EVENT0("blink", "ScrollAnimator::tickAnimation");
double elapsedTime = monotonicTime - m_startTime;
bool isFinished = (elapsedTime > m_animationCurve->duration());
FloatPoint offset = blinkOffsetFromCompositorOffset(isFinished
? m_animationCurve->targetValue()
: m_animationCurve->getValue(elapsedTime));
offset = FloatPoint(m_scrollableArea->clampScrollPosition(offset));
m_currentPos = offset;
if (isFinished)
m_runState = RunState::PostAnimationCleanup;
else
getScrollableArea()->scheduleAnimation();
TRACE_EVENT0("blink", "ScrollAnimator::notifyPositionChanged");
notifyPositionChanged();
}
void ScrollAnimator::postAnimationCleanupAndReset()
{
// Remove the temporary main thread scrolling reason that was added while
// main thread had scheduled an animation.
removeMainThreadScrollingReason();
resetAnimationState();
}
bool ScrollAnimator::sendAnimationToCompositor()
{
if (m_scrollableArea->shouldScrollOnMainThread())
return false;
OwnPtr<CompositorAnimation> animation = adoptPtr(
CompositorFactory::current().createAnimation(
*m_animationCurve,
CompositorTargetProperty::SCROLL_OFFSET));
// Being here means that either there is an animation that needs
// to be sent to the compositor, or an animation that needs to
// be updated (a new scroll event before the previous animation
// is finished). In either case, the start time is when the
// first animation was initiated. This re-targets the animation
// using the current time on main thread.
animation->setStartTime(m_startTime);
int animationId = animation->id();
int animationGroupId = animation->group();
bool sentToCompositor = addAnimation(std::move(animation));
if (sentToCompositor) {
m_runState = RunState::RunningOnCompositor;
m_compositorAnimationId = animationId;
m_compositorAnimationGroupId = animationGroupId;
}
return sentToCompositor;
}
void ScrollAnimator::updateCompositorAnimations()
{
if (m_runState == RunState::PostAnimationCleanup) {
postAnimationCleanupAndReset();
return;
}
if (m_compositorAnimationId && m_runState != RunState::RunningOnCompositor
&& m_runState != RunState::RunningOnCompositorButNeedsUpdate
&& m_runState != RunState::WaitingToCancelOnCompositorButNewScroll) {
// If the current run state is WaitingToSendToCompositor but we have a
// non-zero compositor animation id, there's a currently running
// compositor animation that needs to be removed here before the new
// animation is added below.
ASSERT(m_runState == RunState::WaitingToCancelOnCompositor
|| m_runState == RunState::WaitingToSendToCompositor
|| m_runState == RunState::RunningOnCompositorButNeedsTakeover);
if (m_runState == RunState::RunningOnCompositorButNeedsTakeover) {
// The animation is already aborted when the call to
// ::takeoverCompositorAnimation is made.
m_runState = RunState::WaitingToSendToCompositor;
} else {
abortAnimation();
}
m_compositorAnimationId = 0;
m_compositorAnimationGroupId = 0;
if (m_runState == RunState::WaitingToCancelOnCompositor) {
postAnimationCleanupAndReset();
return;
}
}
if (m_runState == RunState::RunningOnCompositorButNeedsUpdate
|| m_runState == RunState::WaitingToCancelOnCompositorButNewScroll) {
// Abort the running animation before a new one with an updated
// target is added.
abortAnimation();
m_compositorAnimationId = 0;
m_compositorAnimationGroupId = 0;
m_animationCurve->updateTarget(m_timeFunction() - m_startTime,
compositorOffsetFromBlinkOffset(m_targetOffset));
if (m_runState == RunState::WaitingToCancelOnCompositorButNewScroll)
m_animationCurve->setInitialValue(compositorOffsetFromBlinkOffset(currentPosition()));
m_runState = RunState::WaitingToSendToCompositor;
}
if (m_runState == RunState::WaitingToSendToCompositor) {
if (!m_compositorAnimationAttachedToLayerId)
reattachCompositorPlayerIfNeeded(getScrollableArea()->compositorAnimationTimeline());
if (!m_animationCurve) {
m_animationCurve = adoptPtr(CompositorFactory::current().createScrollOffsetAnimationCurve(
compositorOffsetFromBlinkOffset(m_targetOffset),
CompositorAnimationCurve::TimingFunctionTypeEaseInOut,
m_lastGranularity == ScrollByPixel ?
CompositorScrollOffsetAnimationCurve::ScrollDurationInverseDelta :
CompositorScrollOffsetAnimationCurve::ScrollDurationConstant));
m_animationCurve->setInitialValue(compositorOffsetFromBlinkOffset(currentPosition()));
}
bool runningOnMainThread = false;
bool sentToCompositor = sendAnimationToCompositor();
if (!sentToCompositor) {
runningOnMainThread = registerAndScheduleAnimation();
if (runningOnMainThread)
m_runState = RunState::RunningOnMainThread;
}
// Main thread should deal with the scroll animations it started.
if (sentToCompositor || runningOnMainThread)
addMainThreadScrollingReason();
else
removeMainThreadScrollingReason();
}
}
void ScrollAnimator::addMainThreadScrollingReason()
{
if (WebLayer* scrollLayer = toWebLayer(getScrollableArea()->layerForScrolling())) {
scrollLayer->addMainThreadScrollingReasons(
MainThreadScrollingReason::kAnimatingScrollOnMainThread);
}
}
void ScrollAnimator::removeMainThreadScrollingReason()
{
if (WebLayer* scrollLayer = toWebLayer(getScrollableArea()->layerForScrolling())) {
scrollLayer->clearMainThreadScrollingReasons(
MainThreadScrollingReason::kAnimatingScrollOnMainThread);
}
}
void ScrollAnimator::notifyCompositorAnimationAborted(int groupId)
{
// An animation aborted by the compositor is treated as a finished
// animation.
ScrollAnimatorCompositorCoordinator::compositorAnimationFinished(groupId);
}
void ScrollAnimator::notifyCompositorAnimationFinished(int groupId)
{
ScrollAnimatorCompositorCoordinator::compositorAnimationFinished(groupId);
}
void ScrollAnimator::notifyAnimationTakeover(
double monotonicTime,
double animationStartTime,
std::unique_ptr<cc::AnimationCurve> curve)
{
// If there is already an animation running and the compositor asks to take
// over an animation, do nothing to avoid judder.
if (hasRunningAnimation())
return;
cc::ScrollOffsetAnimationCurve* scrollOffsetAnimationCurve =
curve->ToScrollOffsetAnimationCurve();
FloatPoint targetValue(scrollOffsetAnimationCurve->target_value().x(),
scrollOffsetAnimationCurve->target_value().y());
if (willAnimateToOffset(targetValue)) {
m_animationCurve = adoptPtr(
CompositorFactory::current().createScrollOffsetAnimationCurve(
std::move(scrollOffsetAnimationCurve)));
m_startTime = animationStartTime;
}
}
void ScrollAnimator::cancelAnimation()
{
ScrollAnimatorCompositorCoordinator::cancelAnimation();
}
void ScrollAnimator::takeoverCompositorAnimation()
{
if (m_runState == RunState::RunningOnCompositor
|| m_runState == RunState::RunningOnCompositorButNeedsUpdate)
removeMainThreadScrollingReason();
ScrollAnimatorCompositorCoordinator::takeoverCompositorAnimation();
}
void ScrollAnimator::layerForCompositedScrollingDidChange(
CompositorAnimationTimeline* timeline)
{
if (reattachCompositorPlayerIfNeeded(timeline) && m_animationCurve)
addMainThreadScrollingReason();
}
bool ScrollAnimator::registerAndScheduleAnimation()
{
getScrollableArea()->registerForAnimation();
if (!m_scrollableArea->scheduleAnimation()) {
scrollToOffsetWithoutAnimation(m_targetOffset);
resetAnimationState();
return false;
}
return true;
}
DEFINE_TRACE(ScrollAnimator)
{
ScrollAnimatorBase::trace(visitor);
}
} // namespace blink
| bsd-3-clause |
wuhengzhi/chromium-crosswalk | third_party/WebKit/Source/core/animation/AnimationTimeline.cpp | 4 | 11174 | /*
* Copyright (C) 2013 Google 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:
*
* * 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 Google 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
* 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 "core/animation/AnimationTimeline.h"
#include "core/animation/AnimationClock.h"
#include "core/animation/ElementAnimations.h"
#include "core/dom/Document.h"
#include "core/frame/FrameView.h"
#include "core/loader/DocumentLoader.h"
#include "core/page/Page.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "platform/animation/CompositorAnimationTimeline.h"
#include "platform/graphics/CompositorFactory.h"
#include "public/platform/Platform.h"
#include "public/platform/WebCompositorSupport.h"
#include <algorithm>
namespace blink {
namespace {
bool compareAnimations(const Member<Animation>& left, const Member<Animation>& right)
{
return Animation::hasLowerPriority(left.get(), right.get());
}
}
// This value represents 1 frame at 30Hz plus a little bit of wiggle room.
// TODO: Plumb a nominal framerate through and derive this value from that.
const double AnimationTimeline::s_minimumDelay = 0.04;
AnimationTimeline* AnimationTimeline::create(Document* document, PlatformTiming* timing)
{
return new AnimationTimeline(document, timing);
}
AnimationTimeline::AnimationTimeline(Document* document, PlatformTiming* timing)
: m_document(document)
, m_zeroTime(0) // 0 is used by unit tests which cannot initialize from the loader
, m_zeroTimeInitialized(false)
, m_outdatedAnimationCount(0)
, m_playbackRate(1)
, m_lastCurrentTimeInternal(0)
{
ThreadState::current()->registerPreFinalizer(this);
if (!timing)
m_timing = new AnimationTimelineTiming(this);
else
m_timing = timing;
if (Platform::current()->isThreadedAnimationEnabled())
m_compositorTimeline = adoptPtr(CompositorFactory::current().createAnimationTimeline());
ASSERT(document);
}
AnimationTimeline::~AnimationTimeline()
{
}
void AnimationTimeline::dispose()
{
// The Animation objects depend on using this AnimationTimeline to
// unregister from its underlying compositor timeline. To arrange
// for that safely, this dispose() method will return first
// during prefinalization, notifying each Animation object of
// impending destruction.
for (const auto& animation : m_animations)
animation->dispose();
}
bool AnimationTimeline::isActive()
{
return m_document && m_document->page();
}
void AnimationTimeline::animationAttached(Animation& animation)
{
ASSERT(animation.timeline() == this);
ASSERT(!m_animations.contains(&animation));
m_animations.add(&animation);
}
Animation* AnimationTimeline::play(AnimationEffect* child)
{
if (!m_document)
return nullptr;
Animation* animation = Animation::create(child, this);
ASSERT(m_animations.contains(animation));
animation->play();
ASSERT(m_animationsNeedingUpdate.contains(animation));
return animation;
}
HeapVector<Member<Animation>> AnimationTimeline::getAnimations()
{
HeapVector<Member<Animation>> animations;
for (const auto& animation : m_animations) {
if (animation->effect() && (animation->effect()->isCurrent() || animation->effect()->isInEffect()))
animations.append(animation);
}
std::sort(animations.begin(), animations.end(), compareAnimations);
return animations;
}
void AnimationTimeline::wake()
{
m_timing->serviceOnNextFrame();
}
void AnimationTimeline::serviceAnimations(TimingUpdateReason reason)
{
TRACE_EVENT0("blink", "AnimationTimeline::serviceAnimations");
m_lastCurrentTimeInternal = currentTimeInternal();
HeapVector<Member<Animation>> animations;
animations.reserveInitialCapacity(m_animationsNeedingUpdate.size());
for (Animation* animation : m_animationsNeedingUpdate)
animations.append(animation);
std::sort(animations.begin(), animations.end(), Animation::hasLowerPriority);
for (Animation* animation : animations) {
if (!animation->update(reason))
m_animationsNeedingUpdate.remove(animation);
}
ASSERT(m_outdatedAnimationCount == 0);
ASSERT(m_lastCurrentTimeInternal == currentTimeInternal() || (std::isnan(currentTimeInternal()) && std::isnan(m_lastCurrentTimeInternal)));
#if ENABLE(ASSERT)
for (const auto& animation : m_animationsNeedingUpdate)
ASSERT(!animation->outdated());
#endif
}
void AnimationTimeline::scheduleNextService()
{
ASSERT(m_outdatedAnimationCount == 0);
double timeToNextEffect = std::numeric_limits<double>::infinity();
for (const auto& animation : m_animationsNeedingUpdate) {
timeToNextEffect = std::min(timeToNextEffect, animation->timeToEffectChange());
}
if (timeToNextEffect < s_minimumDelay) {
m_timing->serviceOnNextFrame();
} else if (timeToNextEffect != std::numeric_limits<double>::infinity()) {
m_timing->wakeAfter(timeToNextEffect - s_minimumDelay);
}
}
void AnimationTimeline::AnimationTimelineTiming::wakeAfter(double duration)
{
if (m_timer.isActive() && m_timer.nextFireInterval() < duration)
return;
m_timer.startOneShot(duration, BLINK_FROM_HERE);
}
void AnimationTimeline::AnimationTimelineTiming::serviceOnNextFrame()
{
if (m_timeline->m_document && m_timeline->m_document->view())
m_timeline->m_document->view()->scheduleAnimation();
}
DEFINE_TRACE(AnimationTimeline::AnimationTimelineTiming)
{
visitor->trace(m_timeline);
AnimationTimeline::PlatformTiming::trace(visitor);
}
double AnimationTimeline::zeroTime()
{
if (!m_zeroTimeInitialized && m_document && m_document->loader()) {
m_zeroTime = m_document->loader()->timing().referenceMonotonicTime();
m_zeroTimeInitialized = true;
}
return m_zeroTime;
}
void AnimationTimeline::resetForTesting()
{
m_zeroTime = 0;
m_zeroTimeInitialized = true;
m_playbackRate = 1;
m_lastCurrentTimeInternal = 0;
}
double AnimationTimeline::currentTime(bool& isNull)
{
return currentTimeInternal(isNull) * 1000;
}
double AnimationTimeline::currentTimeInternal(bool& isNull)
{
if (!isActive()) {
isNull = true;
return std::numeric_limits<double>::quiet_NaN();
}
double result = m_playbackRate == 0
? zeroTime()
: (document()->animationClock().currentTime() - zeroTime()) * m_playbackRate;
isNull = std::isnan(result);
return result;
}
double AnimationTimeline::currentTime()
{
return currentTimeInternal() * 1000;
}
double AnimationTimeline::currentTimeInternal()
{
bool isNull;
return currentTimeInternal(isNull);
}
void AnimationTimeline::setCurrentTime(double currentTime)
{
setCurrentTimeInternal(currentTime / 1000);
}
void AnimationTimeline::setCurrentTimeInternal(double currentTime)
{
if (!isActive())
return;
m_zeroTime = m_playbackRate == 0
? currentTime
: document()->animationClock().currentTime() - currentTime / m_playbackRate;
m_zeroTimeInitialized = true;
for (const auto& animation : m_animations) {
// The Player needs a timing update to pick up a new time.
animation->setOutdated();
}
// Any corresponding compositor animation will need to be restarted. Marking the
// effect changed forces this.
setAllCompositorPending(true);
}
double AnimationTimeline::effectiveTime()
{
double time = currentTimeInternal();
return std::isnan(time) ? 0 : time;
}
void AnimationTimeline::pauseAnimationsForTesting(double pauseTime)
{
for (const auto& animation : m_animationsNeedingUpdate)
animation->pauseForTesting(pauseTime);
serviceAnimations(TimingUpdateOnDemand);
}
bool AnimationTimeline::needsAnimationTimingUpdate()
{
if (currentTimeInternal() == m_lastCurrentTimeInternal)
return false;
if (std::isnan(currentTimeInternal()) && std::isnan(m_lastCurrentTimeInternal))
return false;
// We allow m_lastCurrentTimeInternal to advance here when there
// are no animations to allow animations spawned during style
// recalc to not invalidate this flag.
if (m_animationsNeedingUpdate.isEmpty())
m_lastCurrentTimeInternal = currentTimeInternal();
return !m_animationsNeedingUpdate.isEmpty();
}
void AnimationTimeline::clearOutdatedAnimation(Animation* animation)
{
ASSERT(!animation->outdated());
m_outdatedAnimationCount--;
}
void AnimationTimeline::setOutdatedAnimation(Animation* animation)
{
ASSERT(animation->outdated());
m_outdatedAnimationCount++;
m_animationsNeedingUpdate.add(animation);
if (isActive() && !m_document->page()->animator().isServicingAnimations())
m_timing->serviceOnNextFrame();
}
void AnimationTimeline::setPlaybackRate(double playbackRate)
{
if (!isActive())
return;
double currentTime = currentTimeInternal();
m_playbackRate = playbackRate;
m_zeroTime = playbackRate == 0
? currentTime
: document()->animationClock().currentTime() - currentTime / playbackRate;
m_zeroTimeInitialized = true;
// Corresponding compositor animation may need to be restarted to pick up
// the new playback rate. Marking the effect changed forces this.
setAllCompositorPending(true);
}
void AnimationTimeline::setAllCompositorPending(bool sourceChanged)
{
for (const auto& animation : m_animations) {
animation->setCompositorPending(sourceChanged);
}
}
double AnimationTimeline::playbackRate() const
{
return m_playbackRate;
}
DEFINE_TRACE(AnimationTimeline)
{
visitor->trace(m_document);
visitor->trace(m_timing);
visitor->trace(m_animationsNeedingUpdate);
visitor->trace(m_animations);
}
} // namespace blink
| bsd-3-clause |
Milad-Rakhsha/chrono | src/chrono_models/vehicle/man/MAN_5t_Wheel.cpp | 4 | 1672 | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Rainer Gericke
// =============================================================================
//
// MAN Kat 1 wheel subsystem
//
// =============================================================================
#include <algorithm>
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_models/vehicle/man/MAN_5t_Wheel.h"
#include "chrono_thirdparty/filesystem/path.h"
namespace chrono {
namespace vehicle {
namespace man {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const double MAN_5t_Wheel::m_mass = 30.0;
const ChVector<> MAN_5t_Wheel::m_inertia(.6, .63, .6);
const double MAN_5t_Wheel::m_radius = 0.254;
const double MAN_5t_Wheel::m_width = 0.254;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
MAN_5t_Wheel::MAN_5t_Wheel(const std::string& name) : ChWheel(name) {
m_vis_mesh_file = "MAN_Kat1/meshes/MAN_rim.obj";
}
} // namespace man
} // end namespace vehicle
} // end namespace chrono
| bsd-3-clause |
yuyichao/OpenBLAS | lapack-netlib/LAPACKE/src/lapacke_zunmbr.c | 5 | 3959 | /*****************************************************************************
Copyright (c) 2014, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of 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.
*****************************************************************************
* Contents: Native high-level C interface to LAPACK function zunmbr
* Author: Intel Corporation
* Generated November 2015
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_zunmbr( int matrix_layout, char vect, char side, char trans,
lapack_int m, lapack_int n, lapack_int k,
const lapack_complex_double* a, lapack_int lda,
const lapack_complex_double* tau,
lapack_complex_double* c, lapack_int ldc )
{
lapack_int info = 0;
lapack_int lwork = -1;
lapack_complex_double* work = NULL;
lapack_complex_double work_query;
lapack_int nq, r;
if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_zunmbr", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
/* Optionally check input matrices for NaNs */
nq = LAPACKE_lsame( side, 'l' ) ? m : n;
r = LAPACKE_lsame( vect, 'q' ) ? nq : MIN(nq,k);
if( LAPACKE_zge_nancheck( matrix_layout, r, MIN(nq,k), a, lda ) ) {
return -8;
}
if( LAPACKE_zge_nancheck( matrix_layout, m, n, c, ldc ) ) {
return -11;
}
if( LAPACKE_z_nancheck( MIN(nq,k), tau, 1 ) ) {
return -10;
}
#endif
/* Query optimal working array(s) size */
info = LAPACKE_zunmbr_work( matrix_layout, vect, side, trans, m, n, k, a,
lda, tau, c, ldc, &work_query, lwork );
if( info != 0 ) {
goto exit_level_0;
}
lwork = LAPACK_Z2INT( work_query );
/* Allocate memory for work arrays */
work = (lapack_complex_double*)
LAPACKE_malloc( sizeof(lapack_complex_double) * lwork );
if( work == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
/* Call middle-level interface */
info = LAPACKE_zunmbr_work( matrix_layout, vect, side, trans, m, n, k, a,
lda, tau, c, ldc, work, lwork );
/* Release memory and exit */
LAPACKE_free( work );
exit_level_0:
if( info == LAPACK_WORK_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_zunmbr", info );
}
return info;
}
| bsd-3-clause |
uwsampa/grappa | applications/NPB/SERIAL/UA/transfer.f | 5 | 30019 | c------------------------------------------------------------------
subroutine transf(tmor,tx)
c------------------------------------------------------------------
c Map values from mortar(tmor) to element(tx)
c------------------------------------------------------------------
include 'header.h'
double precision tmor(*),tx(*), tmp(lx1,lx1,2)
integer ig1,ig2,ig3,ig4,ie,iface,il1,il2,il3,il4,
& nnje,ije1,ije2,col,i,j,ig,il
c.....zero out tx on element boundaries
call col2(tx,tmult,ntot)
do ie=1,nelt
do iface=1,nsides
c.........get the collocation point index of the four local corners on the
c face iface of element ie
il1=idel(1,1,iface,ie)
il2=idel(lx1,1,iface,ie)
il3=idel(1,lx1,iface,ie)
il4=idel(lx1,lx1,iface,ie)
c.........get the mortar indices of the four local corners
ig1= idmo(1, 1 ,1,1,iface,ie)
ig2= idmo(lx1,1 ,1,2,iface,ie)
ig3= idmo(1, lx1,2,1,iface,ie)
ig4= idmo(lx1,lx1,2,2,iface,ie)
c.........copy the value from tmor to tx for these four local corners
tx(il1) = tmor(ig1)
tx(il2) = tmor(ig2)
tx(il3) = tmor(ig3)
tx(il4) = tmor(ig4)
c.........nnje=1 for conforming faces, nnje=2 for nonconforming faces
if(cbc(iface,ie).eq.3) then
nnje=2
else
nnje=1
end if
c.........for nonconforming faces
if(nnje.eq.2) then
c...........nonconforming faces have four pieces of mortar, first map them to
c two intermediate mortars, stored in tmp
call r_init(tmp,lx1*lx1*2,0.d0)
do ije1=1,nnje
do ije2=1,nnje
do col=1,lx1
c.................in each row col, when coloumn i=1 or lx1, the value
c in tmor is copied to tmp
i = v_end(ije2)
ig=idmo(i,col,ije1,ije2,iface,ie)
tmp(i,col,ije1)=tmor(ig)
c.................in each row col, value in the interior three collocation
c points is computed by apply mapping matrix qbnew to tmor
do i=2,lx1-1
il= idel(i,col,iface,ie)
do j=1,lx1
ig=idmo(j,col,ije1,ije2,iface,ie)
tmp(i,col,ije1) = tmp(i,col,ije1) +
& qbnew(i-1,j,ije2)*tmor(ig)
end do
end do
end do
end do
end do
c...........mapping from two pieces of intermediate mortar tmp to element
c face tx
do ije1=1, nnje
c.............the first column, col=1, is an edge of face iface.
c the value on the three interior collocation points, tx, is
c computed by applying mapping matrices qbnew to tmp.
c the mapping result is divided by 2, because there will be
c duplicated contribution from another face sharing this edge.
col=1
do i=2,lx1-1
il= idel(col,i,iface,ie)
do j=1,lx1
tx(il) = tx(il) + qbnew(i-1,j,ije1)*
& tmp(col,j,ije1)*0.5d0
end do
end do
c.............for column 2 ~ lx-1
do col=2,lx1-1
c...............when i=1 or lx1, the collocation points are also on an edge of
c the face, so the mapping result also needs to be divided by 2
i = v_end(ije1)
il= idel(col,i,iface,ie)
tx(il)=tx(il)+tmp(col,i,ije1)*0.5d0
c...............compute the value at interior collocation points in
c columns 2 ~ lx1
do i=2,lx1-1
il= idel(col,i,iface,ie)
do j=1,lx1
tx(il) = tx(il) + qbnew(i-1,j,ije1)* tmp(col,j,ije1)
end do
end do
end do
c.............same as col=1
col=lx1
do i=2,lx1-1
il= idel(col,i,iface,ie)
do j=1,lx1
tx(il) = tx(il) + qbnew(i-1,j,ije1)*
& tmp(col,j,ije1)*0.5d0
end do
end do
end do
c.........for conforming faces
else
c.........face interior
do col=2,lx1-1
do i=2,lx1-1
il= idel(i,col,iface,ie)
ig= idmo(i,col,1,1,iface,ie)
tx(il)=tmor(ig)
end do
end do
c...........edges of conforming faces
c...........if local edge 1 is a nonconforming edge
if(idmo(lx1,1,1,1,iface,ie).ne.0)then
do i=2,lx1-1
il= idel(i,1,iface,ie)
do ije1=1,2
do j=1,lx1
ig=idmo(j,1,1,ije1,iface,ie)
tx(il) = tx(il) + qbnew(i-1,j,ije1)*tmor(ig)*0.5d0
end do
end do
end do
c...........if local edge 1 is a conforming edge
else
do i=2,lx1-1
il= idel(i,1,iface,ie)
ig= idmo(i,1,1,1,iface,ie)
tx(il)=tmor(ig)
end do
end if
c...........if local edge 2 is a nonconforming edge
if(idmo(lx1,2,1,2,iface,ie).ne.0)then
do i=2,lx1-1
il= idel(lx1,i,iface,ie)
do ije1=1,2
do j=1,lx1
ig=idmo(lx1,j,ije1,2,iface,ie)
tx(il) = tx(il) + qbnew(i-1,j,ije1)*tmor(ig)*0.5d0
end do
end do
end do
c...........if local edge 2 is a conforming edge
else
do i=2,lx1-1
il= idel(lx1,i,iface,ie)
ig= idmo(lx1,i,1,1,iface,ie)
tx(il)=tmor(ig)
end do
end if
c...........if local edge 3 is a nonconforming edge
if(idmo(2,lx1,2,1,iface,ie).ne.0)then
do i=2,lx1-1
il= idel(i,lx1,iface,ie)
do ije1=1,2
do j=1,lx1
ig=idmo(j,lx1,2,ije1,iface,ie)
tx(il) = tx(il) + qbnew(i-1,j,ije1)*tmor(ig)*0.5d0
end do
end do
end do
c...........if local edge 3 is a conforming edge
else
do i=2,lx1-1
il= idel(i,lx1,iface,ie)
ig= idmo(i,lx1,1,1,iface,ie)
tx(il)=tmor(ig)
end do
end if
c...........if local edge 4 is a nonconforming edge
if(idmo(1,lx1,1,1,iface,ie).ne.0)then
do i=2,lx1-1
il= idel(1,i,iface,ie)
do ije1=1,2
do j=1,lx1
ig=idmo(1,j,ije1,1,iface,ie)
tx(il) = tx(il) + qbnew(i-1,j,ije1)*tmor(ig)*0.5d0
end do
end do
end do
c...........if local edge 4 is a conforming edge
else
do i=2,lx1-1
il= idel(1,i,iface,ie)
ig= idmo(1,i,1,1,iface,ie)
tx(il)=tmor(ig)
end do
end if
end if
end do
end do
return
end
c------------------------------------------------------------------
subroutine transfb(tmor,tx)
c------------------------------------------------------------------
c Map from element(tx) to mortar(tmor).
c tmor sums contributions from all elements.
c------------------------------------------------------------------
include 'header.h'
double precision third
parameter (third=1.d0/3.d0)
integer shift
double precision tmp,tmp1,tx(*),tmor(*),temp(lx1,lx1,2),
& top(lx1,2)
integer il1,il2,il3,il4,ig1,ig2,ig3,ig4,ie,iface,nnje,
& ije1,ije2,col,i,j,ije,ig,il
call r_init(tmor,nmor,0.d0)
do ie=1,nelt
do iface=1,nsides
c.........nnje=1 for conforming faces, nnje=2 for nonconforming faces
if(cbc(iface,ie).eq.3) then
nnje=2
else
nnje=1
end if
c.........get collocation point index of four local corners on the face
il1 = idel(1, 1, iface,ie)
il2 = idel(lx1,1, iface,ie)
il3 = idel(1, lx1,iface,ie)
il4 = idel(lx1,lx1,iface,ie)
c.........get the mortar indices of the four local corners
ig1 = idmo(1, 1, 1,1,iface,ie)
ig2 = idmo(lx1,1, 1,2,iface,ie)
ig3 = idmo(1, lx1,2,1,iface,ie )
ig4 = idmo(lx1,lx1,2,2,iface,ie)
c.........sum the values from tx to tmor for these four local corners
c only 1/3 of the value is summed, since there will be two duplicated
c contributions from the other two faces sharing this vertex
tmor(ig1) = tmor(ig1)+tx(il1)*third
tmor(ig2) = tmor(ig2)+tx(il2)*third
tmor(ig3) = tmor(ig3)+tx(il3)*third
tmor(ig4) = tmor(ig4)+tx(il4)*third
c.........for nonconforming faces
if(nnje.eq.2) then
call r_init(temp,lx1*lx1*2,0.d0)
c...........nonconforming faces have four pieces of mortar, first map tx to
c two intermediate mortars stored in temp
do ije2 = 1, nnje
shift = ije2-1
do col=1,lx1
c...............For mortar points on face edge (top and bottom), copy the
c value from tx to temp
il=idel(col,v_end(ije2),iface,ie)
temp(col,v_end(ije2),ije2)=tx(il)
c...............For mortar points on face edge (top and bottom), calculate
c the interior points' contribution to them, i.e. top()
j = v_end(ije2)
tmp=0.d0
do i=2,lx1-1
il=idel(col,i,iface,ie)
tmp = tmp + qbnew(i-1,j,ije2)*tx(il)
end do
top(col,ije2)=tmp
c...............Use mapping matrices qbnew to map the value from tx to temp
c for mortar points not on the top bottom face edge.
do j=2-shift,lx1-shift
tmp=0.d0
do i=2,lx1-1
il=idel(col,i,iface,ie)
tmp = tmp + qbnew(i-1,j,ije2)*tx(il)
end do
temp(col,j,ije2) = tmp + temp(col,j,ije2)
end do
end do
end do
c...........mapping from temp to tmor
do ije1=1, nnje
shift = ije1-1
do ije2=1,nnje
c...............for each column of collocation points on a piece of mortar
do col=2-shift,lx1-shift
c.................For the end point, which is on an edge (local edge 2,4),
c the contribution is halved since there will be duplicated
c contribution from another face sharing this edge.
ig=idmo(v_end(ije2),col,ije1,ije2,iface,ie)
tmor(ig)=tmor(ig)+temp(v_end(ije2),col,ije1)*0.5d0
c.................In each row of collocation points on a piece of mortar,
c sum the contributions from interior collocation points
c (i=2,lx1-1)
do j=1,lx1
tmp=0.d0
do i=2,lx1-1
tmp = tmp + qbnew(i-1,j,ije2) * temp(i,col,ije1)
end do
ig=idmo(j,col,ije1,ije2,iface,ie)
tmor(ig)=tmor(ig)+tmp
end do
end do
c...............For tmor on local edge 1 and 3, tmp is the contribution from
c an edge, so it is halved because of duplicated contribution
c from another face sharing this edge. tmp1 is contribution
c from face interior.
col = v_end(ije1)
ig=idmo(v_end(ije2),col,ije1,ije2,iface,ie)
tmor(ig)=tmor(ig)+top(v_end(ije2),ije1)*0.5d0
do j=1,lx1
tmp=0.d0
tmp1=0.d0
do i=2,lx1-1
tmp = tmp + qbnew(i-1,j,ije2) * temp(i,col,ije1)
tmp1 = tmp1 + qbnew(i-1,j,ije2) * top(i,ije1)
end do
ig=idmo(j,col,ije1,ije2,iface,ie)
tmor(ig)=tmor(ig)+tmp*0.5d0+tmp1
end do
end do
end do
c.........for conforming faces
else
c.........face interior
do col=2,lx1-1
do j=2,lx1-1
il=idel(j,col,iface,ie)
ig=idmo(j,col,1,1,iface,ie)
tmor(ig)=tmor(ig)+tx(il)
end do
end do
c...........edges of conforming faces
c...........if local edge 1 is a nonconforming edge
if(idmo(lx1,1,1,1,iface,ie).ne.0)then
do ije=1,2
do j=1,lx1
tmp=0.d0
do i=2,lx1-1
il=idel(i,1,iface,ie)
tmp= tmp + qbnew(i-1,j,ije)*tx(il)
end do
ig=idmo(j,1,1,ije,iface,ie)
tmor(ig)=tmor(ig)+tmp*0.5d0
end do
end do
c...........if local edge 1 is a conforming edge
else
do j=2,lx1-1
il=idel(j,1,iface,ie)
ig=idmo(j,1,1,1,iface,ie)
tmor(ig)=tmor(ig)+tx(il)*0.5d0
end do
end if
c...........if local edge 2 is a nonconforming edge
if(idmo(lx1,2,1,2,iface,ie).ne.0)then
do ije=1,2
do j=1,lx1
tmp=0.d0
do i=2,lx1-1
il=idel(lx1,i,iface,ie)
tmp = tmp + qbnew(i-1,j,ije)*tx(il)
end do
ig=idmo(lx1,j,ije,2,iface,ie)
tmor(ig)=tmor(ig)+tmp*0.5d0
end do
end do
c...........if local edge 2 is a conforming edge
else
do j=2,lx1-1
il=idel(lx1,j,iface,ie)
ig=idmo(lx1,j,1,1,iface,ie)
tmor(ig)=tmor(ig)+tx(il)*0.5d0
end do
end if
c...........if local edge 3 is a nonconforming edge
if(idmo(2,lx1,2,1,iface,ie).ne.0)then
do ije=1,2
do j=1,lx1
tmp=0.d0
do i=2,lx1-1
il=idel(i,lx1,iface,ie)
tmp = tmp + qbnew(i-1,j,ije)*tx(il)
end do
ig=idmo(j,lx1,2,ije,iface,ie)
tmor(ig)=tmor(ig)+tmp*0.5d0
end do
end do
c...........if local edge 3 is a conforming edge
else
do j=2,lx1-1
il=idel(j,lx1,iface,ie)
ig=idmo(j,lx1,1,1,iface,ie)
tmor(ig)=tmor(ig)+tx(il)*0.5d0
end do
end if
c...........if local edge 4 is a nonconforming edge
if(idmo(1,lx1,1,1,iface,ie).ne.0)then
do ije=1,2
do j=1,lx1
tmp=0.d0
do i=2,lx1-1
il=idel(1,i,iface,ie)
tmp = tmp + qbnew(i-1,j,ije)*tx(il)
end do
ig=idmo(1,j,ije,1,iface,ie)
tmor(ig)=tmor(ig)+tmp*0.5d0
end do
end do
c...........if local edge 4 is a conforming edge
else
do j=2,lx1-1
il=idel(1,j,iface,ie)
ig=idmo(1,j,1,1,iface,ie)
tmor(ig)=tmor(ig)+tx(il)*0.5d0
end do
end if
end if!nnje=1
end do
end do
return
end
c--------------------------------------------------------------
subroutine transfb_cor_e(n,tmor,tx)
c--------------------------------------------------------------
c This subroutine performs the edge to mortar mapping and
c calculates the mapping result on the mortar point at a vertex
c under situation 1,2, or 3.
c n refers to the configuration of three edges sharing a vertex,
c n = 1: only one edge is nonconforming
c n = 2: two edges are nonconforming
c n = 3: three edges are nonconforming
c-------------------------------------------------------------------
include 'header.h'
double precision tmor,tx(lx1,lx1,lx1),tmp
integer i,n
tmor=tx(1,1,1)
do i=2,lx1-1
tmor= tmor + qbnew(i-1,1,1)*tx(i,1,1)
end do
if(n.gt.1)then
do i=2,lx1-1
tmor= tmor + qbnew(i-1,1,1)*tx(1,i,1)
end do
end if
if(n.eq.3)then
do i=2,lx1-1
tmor= tmor + qbnew(i-1,1,1)*tx(1,1,i)
end do
end if
return
end
c--------------------------------------------------------------
subroutine transfb_cor_f(n,tmor,tx)
c--------------------------------------------------------------
c This subroutine performs the mapping from face to mortar.
c Output tmor is the mapping result on a mortar vertex
c of situations of three edges and three faces sharing a vertex:
c n=4: only one face is nonconforming
c n=5: one face and one edge are nonconforming
c n=6: two faces are nonconforming
c n=7: three faces are nonconforming
c--------------------------------------------------------------
include 'header.h'
double precision tx(lx1,lx1,lx1),tmor,temp(lx1)
integer col,i,n
call r_init(temp,lx1,0.d0)
do col=1,lx1
temp(col)=tx(col,1,1)
do i=2,lx1-1
temp(col) = temp(col) + qbnew(i-1,1,1)*tx(col,i,1)
end do
end do
tmor=temp(1)
do i=2,lx1-1
tmor = tmor + qbnew(i-1,1,1) *temp(i)
end do
if(n.eq.5)then
do i=2,lx1-1
tmor = tmor + qbnew(i-1,1,1) *tx(1,1,i)
end do
end if
if(n.ge.6)then
call r_init(temp,lx1,0.d0)
do col=1,lx1
do i=2,lx1-1
temp(col) = temp(col) + qbnew(i-1,1,1)*tx(col,1,i)
end do
end do
tmor=tmor+temp(1)
do i=2,lx1-1
tmor = tmor +qbnew(i-1,1,1) *temp(i)
end do
end if
if(n.eq.7)then
call r_init(temp,lx1,0.d0)
do col=2,lx1-1
do i=2,lx1-1
temp(col) = temp(col) + qbnew(i-1,1,1)*tx(1,col,i)
end do
end do
do i=2,lx1-1
tmor = tmor + qbnew(i-1,1,1) *temp(i)
end do
end if
return
end
c-------------------------------------------------------------------------
subroutine transf_nc(tmor,tx)
c------------------------------------------------------------------------
c Perform mortar to element mapping on a nonconforming face.
c This subroutin is used when all entries in tmor are zero except
c one tmor(i,j)=1. So this routine is simplified. Only one piece of
c mortar (tmor only has two indices) and one piece of intermediate
c mortar (tmp) are involved.
c------------------------------------------------------------------------
include 'header.h'
double precision tmor(lx1,lx1), tx(lx1,lx1), tmp(lx1,lx1)
integer col,i,j
call r_init(tmp,lx1*lx1,0.d0)
do col=1,lx1
i = 1
tmp(i,col)=tmor(i,col)
do i=2,lx1-1
do j=1,lx1
tmp(i,col) = tmp(i,col) + qbnew(i-1,j,1)*tmor(j,col)
end do
end do
end do
do col=1,lx1
i = 1
tx(col,i) = tx(col,i) + tmp(col,i)
do i=2,lx1-1
do j=1,lx1
tx(col,i) = tx(col,i) + qbnew(i-1,j,1)*tmp(col,j)
end do
end do
end do
return
end
c------------------------------------------------------------------------
subroutine transfb_nc0(tmor,tx)
c------------------------------------------------------------------------
c Performs mapping from element to mortar when the nonconforming
c edges are shared by two conforming faces of an element.
c------------------------------------------------------------------------
include 'header.h'
double precision tmor(lx1,lx1),tx(lx1,lx1,lx1)
integer i,j
call r_init(tmor,lx1*lx1,0.d0)
do j=1,lx1
do i=2,lx1-1
tmor(j,1)= tmor(j,1) + qbnew(i-1,j ,1)*tx(i,1,1)
end do
end do
return
end
c------------------------------------------------------------------------
subroutine transfb_nc2(tmor,tx)
c------------------------------------------------------------------------
c Maps values from element to mortar when the nonconforming edges are
c shared by two nonconforming faces of an element.
c Although each face shall have four pieces of mortar, only value in
c one piece (location (1,1)) is used in the calling routine so only
c the value in the first mortar is calculated in this subroutine.
c------------------------------------------------------------------------
include 'header.h'
double precision tx(lx1,lx1),tmor(lx1,lx1),bottom(lx1),
& temp(lx1,lx1)
integer col,j,i
call r_init(tmor,lx1*lx1,0.d0)
call r_init(temp,lx1*lx1,0.d0)
tmor(1,1)=tx(1,1)
c.....mapping from tx to intermediate mortar temp + bottom
do col=1,lx1
temp(col,1)=tx(col,1)
j=1
bottom(col)= 0.d0
do i=2,lx1-1
bottom(col) = bottom(col) + qbnew(i-1,j,1)*tx(col,i)
end do
do j=2,lx1
do i=2,lx1-1
temp(col,j) = temp(col,j) + qbnew(i-1,j,1)*tx(col,i)
end do
end do
end do
c.....from intermediate mortar to mortar
c.....On the nonconforming edge, temp is divided by 2 as there will be
c a duplicate contribution from another face sharing this edge
col=1
do j=1,lx1
do i=2,lx1-1
tmor(j,col)=tmor(j,col)+ qbnew(i-1,j,1) * bottom(i) +
& qbnew(i-1,j,1) * temp(i,col) * 0.5d0
end do
end do
do col=2,lx1
tmor(1,col)=tmor(1,col)+temp(1,col)
do j=1,lx1
do i=2,lx1-1
tmor(j,col) = tmor(j,col) + qbnew(i-1,j,1) *temp(i,col)
end do
end do
end do
return
end
c------------------------------------------------------------------------
subroutine transfb_nc1(tmor,tx)
c------------------------------------------------------------------------
c Maps values from element to mortar when the nonconforming edges are
c shared by a nonconforming face and a conforming face of an element
c------------------------------------------------------------------------
include 'header.h'
double precision tx(lx1,lx1),tmor(lx1,lx1),bottom(lx1),
& temp(lx1,lx1)
integer col,j,i
call r_init(tmor,lx1*lx1,0.d0)
call r_init(temp,lx1*lx1,0.d0)
tmor(1,1)=tx(1,1)
c.....Contribution from the nonconforming faces
c Since the calling subroutine is only interested in the value on the
c mortar (location (1,1)), only this piece of mortar is calculated.
do col=1,lx1
temp(col,1)=tx(col,1)
j = 1
bottom(col)= 0.d0
do i=2,lx1-1
bottom(col)=bottom(col) + qbnew(i-1,j,1)*tx(col,i)
end do
do j=2,lx1
do i=2,lx1-1
temp(col,j) = temp(col,j) + qbnew(i-1,j,1)*tx(col,i)
end do
end do
end do
col=1
tmor(1,col)=tmor(1,col)+bottom(1)
do j=1,lx1
do i=2,lx1-1
c.........temp is not divided by 2 here. It includes the contribution
c from the other conforming face.
tmor(j,col)=tmor(j,col) + qbnew(i-1,j,1) *bottom(i) +
& qbnew(i-1,j,1) *temp(i,col)
end do
end do
do col=2,lx1
tmor(1,col)=tmor(1,col)+temp(1,col)
do j=1,lx1
do i=2,lx1-1
tmor(j,col) = tmor(j,col) + qbnew(i-1,j,1) *temp(i,col)
end do
end do
end do
return
end
c-------------------------------------------------------------------
subroutine transfb_c(tx)
c-------------------------------------------------------------------
c Prepare initial guess for cg. All values from conforming
c boundary are copied and summed on tmor.
c-------------------------------------------------------------------
include 'header.h'
double precision third
parameter (third = 1.d0/3.d0)
double precision tx(*)
integer il1,il2,il3,il4,ig1,ig2,ig3,ig4,ie,iface,col,j,ig,il
call r_init(tmort,nmor,0.d0)
do ie=1,nelt
do iface=1,nsides
if(cbc(iface,ie).ne.3)then
il1 = idel(1,1,iface,ie)
il2 = idel(lx1,1,iface,ie)
il3 = idel(1,lx1,iface,ie)
il4 = idel(lx1,lx1,iface,ie)
ig1 = idmo(1, 1, 1,1,iface,ie)
ig2 = idmo(lx1,1, 1,2,iface,ie)
ig3 = idmo(1, lx1,2,1,iface,ie)
ig4 = idmo(lx1,lx1,2,2,iface,ie)
tmort(ig1) = tmort(ig1)+tx(il1)*third
tmort(ig2) = tmort(ig2)+tx(il2)*third
tmort(ig3) = tmort(ig3)+tx(il3)*third
tmort(ig4) = tmort(ig4)+tx(il4)*third
do col=2,lx1-1
do j=2,lx1-1
il=idel(j,col,iface,ie)
ig=idmo(j,col,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)
end do
end do
if(idmo(lx1,1,1,1,iface,ie).eq.0)then
do j=2,lx1-1
il=idel(j,1,iface,ie)
ig=idmo(j,1,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)*0.5d0
end do
end if
if(idmo(lx1,2,1,2,iface,ie).eq.0)then
do j=2,lx1-1
il=idel(lx1,j,iface,ie)
ig=idmo(lx1,j,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)*0.5d0
end do
end if
if(idmo(2,lx1,2,1,iface,ie).eq.0)then
do j=2,lx1-1
il=idel(j,lx1,iface,ie)
ig=idmo(j,lx1,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)*0.5d0
end do
end if
if(idmo(1,lx1,1,1,iface,ie).eq.0)then
do j=2,lx1-1
il=idel(1,j,iface,ie)
ig=idmo(1,j,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)*0.5d0
end do
end if
end if!
end do
end do
return
end
c-------------------------------------------------------------------
subroutine transfb_c_2(tx)
c-------------------------------------------------------------------
c Prepare initial guess for CG. All values from conforming
c boundary are copied and summed in tmort.
c mormult is multiplicity, which is used to average tmort.
c-------------------------------------------------------------------
include 'header.h'
double precision third
parameter (third = 1.d0/3.d0)
double precision tx(*)
integer il1,il2,il3,il4,ig1,ig2,ig3,ig4,ie,iface,col,j,ig,il
call r_init(tmort,nmor,0.d0)
call r_init(mormult,nmor,0.d0)
do ie=1,nelt
do iface=1,nsides
if(cbc(iface,ie).ne.3)then
il1 = idel(1, 1, iface,ie)
il2 = idel(lx1,1, iface,ie)
il3 = idel(1, lx1,iface,ie)
il4 = idel(lx1,lx1,iface,ie)
ig1 = idmo(1, 1, 1,1,iface,ie)
ig2 = idmo(lx1,1, 1,2,iface,ie)
ig3 = idmo(1, lx1,2,1,iface,ie)
ig4 = idmo(lx1,lx1,2,2,iface,ie)
tmort(ig1) = tmort(ig1)+tx(il1)*third
tmort(ig2) = tmort(ig2)+tx(il2)*third
tmort(ig3) = tmort(ig3)+tx(il3)*third
tmort(ig4) = tmort(ig4)+tx(il4)*third
mormult(ig1) = mormult(ig1)+third
mormult(ig2) = mormult(ig2)+third
mormult(ig3) = mormult(ig3)+third
mormult(ig4) = mormult(ig4)+third
do col=2,lx1-1
do j=2,lx1-1
il=idel(j,col,iface,ie)
ig=idmo(j,col,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)
mormult(ig)=mormult(ig)+1.d0
end do
end do
if(idmo(lx1,1,1,1,iface,ie).eq.0)then
do j=2,lx1-1
il=idel(j,1,iface,ie)
ig=idmo(j,1,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)*0.5d0
mormult(ig)=mormult(ig)+0.5d0
end do
end if
if(idmo(lx1,2,1,2,iface,ie).eq.0)then
do j=2,lx1-1
il=idel(lx1,j,iface,ie)
ig=idmo(lx1,j,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)*0.5d0
mormult(ig)=mormult(ig)+0.5d0
end do
end if
if(idmo(2,lx1,2,1,iface,ie).eq.0)then
do j=2,lx1-1
il=idel(j,lx1,iface,ie)
ig=idmo(j,lx1,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)*0.5d0
mormult(ig)=mormult(ig)+0.5d0
end do
end if
if(idmo(1,lx1,1,1,iface,ie).eq.0)then
do j=2,lx1-1
il=idel(1,j,iface,ie)
ig=idmo(1,j,1,1,iface,ie)
tmort(ig)=tmort(ig)+tx(il)*0.5d0
mormult(ig)=mormult(ig)+0.5d0
end do
end if
end if
end do
end do
return
end
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.