code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* 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 "libm.h"
typedef float float_t;
typedef union {
float f;
struct {
uint32_t m : 23;
uint32_t e : 8;
uint32_t s : 1;
};
} float_s_t;
int __signbitf(float f) {
float_s_t u = {.f = f};
return u.s;
}
#ifndef NDEBUG
float copysignf(float x, float y) {
float_s_t fx={.f = x};
float_s_t fy={.f = y};
// copy sign bit;
fx.s = fy.s;
return fx.f;
}
#endif
static const float _M_LN10 = 2.30258509299404f; // 0x40135d8e
float log10f(float x) { return logf(x) / (float)_M_LN10; }
float tanhf(float x) {
int sign = 0;
if (x < 0) {
sign = 1;
x = -x;
}
x = expm1f(-2 * x);
x = x / (x + 2);
return sign ? x : -x;
}
/*****************************************************************************/
/*****************************************************************************/
// __fpclassifyf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
int __fpclassifyf(float x)
{
union {float f; uint32_t i;} u = {x};
int e = u.i>>23 & 0xff;
if (!e) return u.i<<1 ? FP_SUBNORMAL : FP_ZERO;
if (e==0xff) return u.i<<9 ? FP_NAN : FP_INFINITE;
return FP_NORMAL;
}
/*****************************************************************************/
/*****************************************************************************/
// scalbnf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
float scalbnf(float x, int n)
{
union {float f; uint32_t i;} u;
float_t y = x;
if (n > 127) {
y *= 0x1p127f;
n -= 127;
if (n > 127) {
y *= 0x1p127f;
n -= 127;
if (n > 127)
n = 127;
}
} else if (n < -126) {
y *= 0x1p-126f;
n += 126;
if (n < -126) {
y *= 0x1p-126f;
n += 126;
if (n < -126)
n = -126;
}
}
u.i = (uint32_t)(0x7f+n)<<23;
x = y * u.f;
return x;
}
/*****************************************************************************/
/*****************************************************************************/
// powf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
/* origin: FreeBSD /usr/src/lib/msun/src/e_powf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
static const float
bp[] = {1.0f, 1.5f,},
dp_h[] = { 0.0f, 5.84960938e-01f,}, /* 0x3f15c000 */
dp_l[] = { 0.0f, 1.56322085e-06f,}, /* 0x35d1cfdc */
two24 = 16777216.0f, /* 0x4b800000 */
huge = 1.0e30f,
tiny = 1.0e-30f,
/* poly coefs for (3/2)*(log(x)-2s-2/3*s**3 */
L1 = 6.0000002384e-01f, /* 0x3f19999a */
L2 = 4.2857143283e-01f, /* 0x3edb6db7 */
L3 = 3.3333334327e-01f, /* 0x3eaaaaab */
L4 = 2.7272811532e-01f, /* 0x3e8ba305 */
L5 = 2.3066075146e-01f, /* 0x3e6c3255 */
L6 = 2.0697501302e-01f, /* 0x3e53f142 */
P1 = 1.6666667163e-01f, /* 0x3e2aaaab */
P2 = -2.7777778450e-03f, /* 0xbb360b61 */
P3 = 6.6137559770e-05f, /* 0x388ab355 */
P4 = -1.6533901999e-06f, /* 0xb5ddea0e */
P5 = 4.1381369442e-08f, /* 0x3331bb4c */
lg2 = 6.9314718246e-01f, /* 0x3f317218 */
lg2_h = 6.93145752e-01f, /* 0x3f317200 */
lg2_l = 1.42860654e-06f, /* 0x35bfbe8c */
ovt = 4.2995665694e-08f, /* -(128-log2(ovfl+.5ulp)) */
cp = 9.6179670095e-01f, /* 0x3f76384f =2/(3ln2) */
cp_h = 9.6191406250e-01f, /* 0x3f764000 =12b cp */
cp_l = -1.1736857402e-04f, /* 0xb8f623c6 =tail of cp_h */
ivln2 = 1.4426950216e+00f, /* 0x3fb8aa3b =1/ln2 */
ivln2_h = 1.4426879883e+00f, /* 0x3fb8aa00 =16b 1/ln2*/
ivln2_l = 7.0526075433e-06f; /* 0x36eca570 =1/ln2 tail*/
float powf(float x, float y)
{
float z,ax,z_h,z_l,p_h,p_l;
float y1,t1,t2,r,s,sn,t,u,v,w;
int32_t i,j,k,yisint,n;
int32_t hx,hy,ix,iy,is;
GET_FLOAT_WORD(hx, x);
GET_FLOAT_WORD(hy, y);
ix = hx & 0x7fffffff;
iy = hy & 0x7fffffff;
/* x**0 = 1, even if x is NaN */
if (iy == 0)
return 1.0f;
/* 1**y = 1, even if y is NaN */
if (hx == 0x3f800000)
return 1.0f;
/* NaN if either arg is NaN */
if (ix > 0x7f800000 || iy > 0x7f800000)
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 >= 0x4b800000)
yisint = 2; /* even integer y */
else if (iy >= 0x3f800000) {
k = (iy>>23) - 0x7f; /* exponent */
j = iy>>(23-k);
if ((j<<(23-k)) == iy)
yisint = 2 - (j & 1);
}
}
/* special value of y */
if (iy == 0x7f800000) { /* y is +-inf */
if (ix == 0x3f800000) /* (-1)**+-inf is 1 */
return 1.0f;
else if (ix > 0x3f800000) /* (|x|>1)**+-inf = inf,0 */
return hy >= 0 ? y : 0.0f;
else if (ix != 0) /* (|x|<1)**+-inf = 0,inf if x!=0 */
return hy >= 0 ? 0.0f: -y;
}
if (iy == 0x3f800000) /* y is +-1 */
return hy >= 0 ? x : 1.0f/x;
if (hy == 0x40000000) /* y is 2 */
return x*x;
if (hy == 0x3f000000) { /* y is 0.5 */
if (hx >= 0) /* x >= +0 */
return sqrtf(x);
}
ax = fabsf(x);
/* special value of x */
if (ix == 0x7f800000 || ix == 0 || ix == 0x3f800000) { /* x is +-0,+-inf,+-1 */
z = ax;
if (hy < 0) /* z = (1/|x|) */
z = 1.0f/z;
if (hx < 0) {
if (((ix-0x3f800000)|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;
}
sn = 1.0f; /* sign of result */
if (hx < 0) {
if (yisint == 0) /* (x<0)**(non-int) is NaN */
return (x-x)/(x-x);
if (yisint == 1) /* (x<0)**(odd int) */
sn = -1.0f;
}
/* |y| is huge */
if (iy > 0x4d000000) { /* if |y| > 2**27 */
/* over/underflow if x is not close to one */
if (ix < 0x3f7ffff8)
return hy < 0 ? sn*huge*huge : sn*tiny*tiny;
if (ix > 0x3f800007)
return hy > 0 ? sn*huge*huge : sn*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 = ax - 1; /* t has 20 trailing zeros */
w = (t*t)*(0.5f - t*(0.333333333333f - t*0.25f));
u = ivln2_h*t; /* ivln2_h has 16 sig. bits */
v = t*ivln2_l - w*ivln2;
t1 = u + v;
GET_FLOAT_WORD(is, t1);
SET_FLOAT_WORD(t1, is & 0xfffff000);
t2 = v - (t1-u);
} else {
float s2,s_h,s_l,t_h,t_l;
n = 0;
/* take care subnormal number */
if (ix < 0x00800000) {
ax *= two24;
n -= 24;
GET_FLOAT_WORD(ix, ax);
}
n += ((ix)>>23) - 0x7f;
j = ix & 0x007fffff;
/* determine interval */
ix = j | 0x3f800000; /* normalize ix */
if (j <= 0x1cc471) /* |x|<sqrt(3/2) */
k = 0;
else if (j < 0x5db3d7) /* |x|<sqrt(3) */
k = 1;
else {
k = 0;
n += 1;
ix -= 0x00800000;
}
SET_FLOAT_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 = 1.0f/(ax+bp[k]);
s = u*v;
s_h = s;
GET_FLOAT_WORD(is, s_h);
SET_FLOAT_WORD(s_h, is & 0xfffff000);
/* t_h=ax+bp[k] High */
is = ((ix>>1) & 0xfffff000) | 0x20000000;
SET_FLOAT_WORD(t_h, is + 0x00400000 + (k<<21));
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.0f + s2 + r;
GET_FLOAT_WORD(is, t_h);
SET_FLOAT_WORD(t_h, is & 0xfffff000);
t_l = r - ((t_h - 3.0f) - 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;
GET_FLOAT_WORD(is, p_h);
SET_FLOAT_WORD(p_h, is & 0xfffff000);
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 = (float)n;
t1 = (((z_h + z_l) + dp_h[k]) + t);
GET_FLOAT_WORD(is, t1);
SET_FLOAT_WORD(t1, is & 0xfffff000);
t2 = z_l - (((t1 - t) - dp_h[k]) - z_h);
}
/* split up y into y1+y2 and compute (y1+y2)*(t1+t2) */
GET_FLOAT_WORD(is, y);
SET_FLOAT_WORD(y1, is & 0xfffff000);
p_l = (y-y1)*t1 + y*t2;
p_h = y1*t1;
z = p_l + p_h;
GET_FLOAT_WORD(j, z);
if (j > 0x43000000) /* if z > 128 */
return sn*huge*huge; /* overflow */
else if (j == 0x43000000) { /* if z == 128 */
if (p_l + ovt > z - p_h)
return sn*huge*huge; /* overflow */
} else if ((j&0x7fffffff) > 0x43160000) /* z < -150 */ // FIXME: check should be (uint32_t)j > 0xc3160000
return sn*tiny*tiny; /* underflow */
else if (j == 0xc3160000) { /* z == -150 */
if (p_l <= z-p_h)
return sn*tiny*tiny; /* underflow */
}
/*
* compute 2**(p_h+p_l)
*/
i = j & 0x7fffffff;
k = (i>>23) - 0x7f;
n = 0;
if (i > 0x3f000000) { /* if |z| > 0.5, set n = [z+0.5] */
n = j + (0x00800000>>(k+1));
k = ((n&0x7fffffff)>>23) - 0x7f; /* new k for n */
SET_FLOAT_WORD(t, n & ~(0x007fffff>>k));
n = ((n&0x007fffff)|0x00800000)>>(23-k);
if (j < 0)
n = -n;
p_h -= t;
}
t = p_l + p_h;
GET_FLOAT_WORD(is, t);
SET_FLOAT_WORD(t, is & 0xffff8000);
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-2.0f) - (w+z*w);
z = 1.0f - (r - z);
GET_FLOAT_WORD(j, z);
j += n<<23;
if ((j>>23) <= 0) /* subnormal output */
z = scalbnf(z, n);
else
SET_FLOAT_WORD(z, j);
return sn*z;
}
/*****************************************************************************/
/*****************************************************************************/
// expf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
/* origin: FreeBSD /usr/src/lib/msun/src/e_expf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
static const float
half[2] = {0.5f,-0.5f},
ln2hi = 6.9314575195e-1f, /* 0x3f317200 */
ln2lo = 1.4286067653e-6f, /* 0x35bfbe8e */
invln2 = 1.4426950216e+0f, /* 0x3fb8aa3b */
/*
* Domain [-0.34568, 0.34568], range ~[-4.278e-9, 4.447e-9]:
* |x*(exp(x)+1)/(exp(x)-1) - p(x)| < 2**-27.74
*/
expf_P1 = 1.6666625440e-1f, /* 0xaaaa8f.0p-26 */
expf_P2 = -2.7667332906e-3f; /* -0xb55215.0p-32 */
float expf(float x)
{
float_t hi, lo, c, xx, y;
int k, sign;
uint32_t hx;
GET_FLOAT_WORD(hx, x);
sign = hx >> 31; /* sign bit of x */
hx &= 0x7fffffff; /* high word of |x| */
/* special cases */
if (hx >= 0x42aeac50) { /* if |x| >= -87.33655f or NaN */
if (hx >= 0x42b17218 && !sign) { /* x >= 88.722839f */
/* overflow */
x *= 0x1p127f;
return x;
}
if (sign) {
/* underflow */
FORCE_EVAL(-0x1p-149f/x);
if (hx >= 0x42cff1b5) /* x <= -103.972084f */
return 0;
}
}
/* argument reduction */
if (hx > 0x3eb17218) { /* if |x| > 0.5 ln2 */
if (hx > 0x3f851592) /* if |x| > 1.5 ln2 */
k = (int)(invln2*x + half[sign]);
else
k = 1 - sign - sign;
hi = x - k*ln2hi; /* k*ln2hi is exact here */
lo = k*ln2lo;
x = hi - lo;
} else if (hx > 0x39000000) { /* |x| > 2**-14 */
k = 0;
hi = x;
lo = 0;
} else {
/* raise inexact */
FORCE_EVAL(0x1p127f + x);
return 1 + x;
}
/* x is now in primary range */
xx = x*x;
c = x - xx*(expf_P1+xx*expf_P2);
y = 1 + (x*c/(2-c) - lo + hi);
if (k == 0)
return y;
return scalbnf(y, k);
}
/*****************************************************************************/
/*****************************************************************************/
// expm1f from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
/* origin: FreeBSD /usr/src/lib/msun/src/s_expm1f.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
static const float
o_threshold = 8.8721679688e+01f, /* 0x42b17180 */
ln2_hi = 6.9313812256e-01f, /* 0x3f317180 */
ln2_lo = 9.0580006145e-06f, /* 0x3717f7d1 */
//invln2 = 1.4426950216e+00, /* 0x3fb8aa3b */
/*
* Domain [-0.34568, 0.34568], range ~[-6.694e-10, 6.696e-10]:
* |6 / x * (1 + 2 * (1 / (exp(x) - 1) - 1 / x)) - q(x)| < 2**-30.04
* Scaled coefficients: Qn_here = 2**n * Qn_for_q (see s_expm1.c):
*/
Q1 = -3.3333212137e-2f, /* -0x888868.0p-28 */
Q2 = 1.5807170421e-3f; /* 0xcf3010.0p-33 */
float expm1f(float x)
{
float_t y,hi,lo,c,t,e,hxs,hfx,r1,twopk;
union {float f; uint32_t i;} u = {x};
uint32_t hx = u.i & 0x7fffffff;
int k, sign = u.i >> 31;
/* filter out huge and non-finite argument */
if (hx >= 0x4195b844) { /* if |x|>=27*ln2 */
if (hx > 0x7f800000) /* NaN */
return x;
if (sign)
return -1;
if (x > o_threshold) {
x *= 0x1p127f;
return x;
}
}
/* argument reduction */
if (hx > 0x3eb17218) { /* if |x| > 0.5 ln2 */
if (hx < 0x3F851592) { /* and |x| < 1.5 ln2 */
if (!sign) {
hi = x - ln2_hi;
lo = ln2_lo;
k = 1;
} else {
hi = x + ln2_hi;
lo = -ln2_lo;
k = -1;
}
} else {
k = (int)(invln2*x + (sign ? -0.5f : 0.5f));
t = k;
hi = x - t*ln2_hi; /* t*ln2_hi is exact here */
lo = t*ln2_lo;
}
x = hi-lo;
c = (hi-x)-lo;
} else if (hx < 0x33000000) { /* when |x|<2**-25, return x */
if (hx < 0x00800000)
FORCE_EVAL(x*x);
return x;
} else
k = 0;
/* x is now in primary range */
hfx = 0.5f*x;
hxs = x*hfx;
r1 = 1.0f+hxs*(Q1+hxs*Q2);
t = 3.0f - r1*hfx;
e = hxs*((r1-t)/(6.0f - x*t));
if (k == 0) /* c is 0 */
return x - (x*e-hxs);
e = x*(e-c) - c;
e -= hxs;
/* exp(x) ~ 2^k (x_reduced - e + 1) */
if (k == -1)
return 0.5f*(x-e) - 0.5f;
if (k == 1) {
if (x < -0.25f)
return -2.0f*(e-(x+0.5f));
return 1.0f + 2.0f*(x-e);
}
u.i = (0x7f+k)<<23; /* 2^k */
twopk = u.f;
if (k < 0 || k > 56) { /* suffice to return exp(x)-1 */
y = x - e + 1.0f;
if (k == 128)
y = y*2.0f*0x1p127f;
else
y = y*twopk;
return y - 1.0f;
}
u.i = (0x7f-k)<<23; /* 2^-k */
if (k < 23)
y = (x-e+(1-u.f))*twopk;
else
y = (x-(e+u.f)+1)*twopk;
return y;
}
/*****************************************************************************/
/*****************************************************************************/
// __expo2f from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
/* k is such that k*ln2 has minimal relative error and x - kln2 > log(FLT_MIN) */
static const int k = 235;
static const float kln2 = 0x1.45c778p+7f;
/* expf(x)/2 for x >= log(FLT_MAX), slightly better than 0.5f*expf(x/2)*expf(x/2) */
float __expo2f(float x)
{
float scale;
/* note that k is odd and scale*scale overflows */
SET_FLOAT_WORD(scale, (uint32_t)(0x7f + k/2) << 23);
/* exp(x - k ln2) * 2**(k-1) */
return expf(x - kln2) * scale * scale;
}
/*****************************************************************************/
/*****************************************************************************/
// logf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
/* origin: FreeBSD /usr/src/lib/msun/src/e_logf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
static const float
/* |(log(1+s)-log(1-s))/s - Lg(s)| < 2**-34.24 (~[-4.95e-11, 4.97e-11]). */
Lg1 = 0xaaaaaa.0p-24, /* 0.66666662693 */
Lg2 = 0xccce13.0p-25, /* 0.40000972152 */
Lg3 = 0x91e9ee.0p-25, /* 0.28498786688 */
Lg4 = 0xf89e26.0p-26; /* 0.24279078841 */
float logf(float x)
{
union {float f; uint32_t i;} u = {x};
float_t hfsq,f,s,z,R,w,t1,t2,dk;
uint32_t ix;
int k;
ix = u.i;
k = 0;
if (ix < 0x00800000 || ix>>31) { /* x < 2**-126 */
if (ix<<1 == 0)
return -1/(x*x); /* log(+-0)=-inf */
if (ix>>31)
return (x-x)/0.0f; /* log(-#) = NaN */
/* subnormal number, scale up x */
k -= 25;
x *= 0x1p25f;
u.f = x;
ix = u.i;
} else if (ix >= 0x7f800000) {
return x;
} else if (ix == 0x3f800000)
return 0;
/* reduce x into [sqrt(2)/2, sqrt(2)] */
ix += 0x3f800000 - 0x3f3504f3;
k += (int)(ix>>23) - 0x7f;
ix = (ix&0x007fffff) + 0x3f3504f3;
u.i = ix;
x = u.f;
f = x - 1.0f;
s = f/(2.0f + f);
z = s*s;
w = z*z;
t1= w*(Lg2+w*Lg4);
t2= z*(Lg1+w*Lg3);
R = t2 + t1;
hfsq = 0.5f*f*f;
dk = k;
return s*(hfsq+R) + dk*ln2_lo - hfsq + f + dk*ln2_hi;
}
/*****************************************************************************/
/*****************************************************************************/
// coshf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
float coshf(float x)
{
union {float f; uint32_t i;} u = {.f = x};
uint32_t w;
float t;
/* |x| */
u.i &= 0x7fffffff;
x = u.f;
w = u.i;
/* |x| < log(2) */
if (w < 0x3f317217) {
if (w < 0x3f800000 - (12<<23)) {
FORCE_EVAL(x + 0x1p120f);
return 1;
}
t = expm1f(x);
return 1 + t*t/(2*(1+t));
}
/* |x| < log(FLT_MAX) */
if (w < 0x42b17217) {
t = expf(x);
return 0.5f*(t + 1/t);
}
/* |x| > log(FLT_MAX) or nan */
t = __expo2f(x);
return t;
}
/*****************************************************************************/
/*****************************************************************************/
// sinhf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
float sinhf(float x)
{
union {float f; uint32_t i;} u = {.f = x};
uint32_t w;
float t, h, absx;
h = 0.5;
if (u.i >> 31)
h = -h;
/* |x| */
u.i &= 0x7fffffff;
absx = u.f;
w = u.i;
/* |x| < log(FLT_MAX) */
if (w < 0x42b17217) {
t = expm1f(absx);
if (w < 0x3f800000) {
if (w < 0x3f800000 - (12<<23))
return x;
return h*(2*t - t*t/(t+1));
}
return h*(t + t/(t+1));
}
/* |x| > logf(FLT_MAX) or nan */
t = 2*h*__expo2f(absx);
return t;
}
/*****************************************************************************/
/*****************************************************************************/
// ceilf, floorf and truncf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
float ceilf(float x)
{
union {float f; uint32_t i;} u = {x};
int e = (int)(u.i >> 23 & 0xff) - 0x7f;
uint32_t m;
if (e >= 23)
return x;
if (e >= 0) {
m = 0x007fffff >> e;
if ((u.i & m) == 0)
return x;
FORCE_EVAL(x + 0x1p120f);
if (u.i >> 31 == 0)
u.i += m;
u.i &= ~m;
} else {
FORCE_EVAL(x + 0x1p120f);
if (u.i >> 31)
u.f = -0.0;
else if (u.i << 1)
u.f = 1.0;
}
return u.f;
}
float floorf(float x)
{
union {float f; uint32_t i;} u = {x};
int e = (int)(u.i >> 23 & 0xff) - 0x7f;
uint32_t m;
if (e >= 23)
return x;
if (e >= 0) {
m = 0x007fffff >> e;
if ((u.i & m) == 0)
return x;
FORCE_EVAL(x + 0x1p120f);
if (u.i >> 31)
u.i += m;
u.i &= ~m;
} else {
FORCE_EVAL(x + 0x1p120f);
if (u.i >> 31 == 0)
u.i = 0;
else if (u.i << 1)
u.f = -1.0;
}
return u.f;
}
float truncf(float x)
{
union {float f; uint32_t i;} u = {x};
int e = (int)(u.i >> 23 & 0xff) - 0x7f + 9;
uint32_t m;
if (e >= 23 + 9)
return x;
if (e < 9)
e = 1;
m = -1U >> e;
if ((u.i & m) == 0)
return x;
FORCE_EVAL(x + 0x1p120f);
u.i &= ~m;
return u.f;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/math.c | C | apache-2.0 | 22,451 |
// adapted from the rintf() function from musl-1.1.16
#include "libm.h"
float nearbyintf(float x)
{
union {float f; uint32_t i;} u = {x};
int e = u.i>>23 & 0xff;
int s = u.i>>31;
float_t y;
if (e >= 0x7f+23)
return x;
if (s)
y = x - 0x1p23f + 0x1p23f;
else
y = x + 0x1p23f - 0x1p23f;
if (y == 0)
return s ? -0.0f : 0.0f;
return y;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/nearbyintf.c | C | apache-2.0 | 353 |
/*****************************************************************************/
/*****************************************************************************/
// roundf from musl-0.9.15
/*****************************************************************************/
/*****************************************************************************/
#include "libm.h"
float roundf(float x)
{
union {float f; uint32_t i;} u = {x};
int e = u.i >> 23 & 0xff;
float_t y;
if (e >= 0x7f+23)
return x;
if (u.i >> 31)
x = -x;
if (e < 0x7f-1) {
FORCE_EVAL(x + 0x1p23f);
return 0*u.f;
}
y = (float)(x + 0x1p23f) - 0x1p23f - x;
if (y > 0.5f)
y = y + x - 1;
else if (y <= -0.5f)
y = y + x + 1;
else
y = y + x;
if (u.i >> 31)
y = -y;
return y;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/roundf.c | C | apache-2.0 | 762 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* sf_cos.c -- float version of s_cos.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
#include "fdlibm.h"
#ifdef __STDC__
float cosf(float x)
#else
float cosf(x)
float x;
#endif
{
float y[2],z=0.0;
__int32_t n,ix;
GET_FLOAT_WORD(ix,x);
/* |x| ~< pi/4 */
ix &= 0x7fffffff;
if(ix <= 0x3f490fd8) return __kernel_cosf(x,z);
/* cos(Inf or NaN) is NaN */
else if (!FLT_UWORD_IS_FINITE(ix)) return x-x;
/* argument reduction needed */
else {
n = __ieee754_rem_pio2f(x,y);
switch(n&3) {
case 0: return __kernel_cosf(y[0],y[1]);
case 1: return -__kernel_sinf(y[0],y[1],1);
case 2: return -__kernel_cosf(y[0],y[1]);
default:
return __kernel_sinf(y[0],y[1],1);
}
}
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double cos(double x)
#else
double cos(x)
double x;
#endif
{
return (double) cosf((float) x);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/sf_cos.c | C | apache-2.0 | 1,611 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* sf_erf.c -- float version of s_erf.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
#include "fdlibm.h"
#define __ieee754_expf expf
#ifdef __v810__
#define const
#endif
#ifdef __STDC__
static const float
#else
static float
#endif
tiny = 1e-30f,
half= 5.0000000000e-01f, /* 0x3F000000 */
one = 1.0000000000e+00f, /* 0x3F800000 */
two = 2.0000000000e+00f, /* 0x40000000 */
/* c = (subfloat)0.84506291151 */
erx = 8.4506291151e-01f, /* 0x3f58560b */
/*
* Coefficients for approximation to erf on [0,0.84375]
*/
efx = 1.2837916613e-01f, /* 0x3e0375d4 */
efx8= 1.0270333290e+00f, /* 0x3f8375d4 */
pp0 = 1.2837916613e-01f, /* 0x3e0375d4 */
pp1 = -3.2504209876e-01f, /* 0xbea66beb */
pp2 = -2.8481749818e-02f, /* 0xbce9528f */
pp3 = -5.7702702470e-03f, /* 0xbbbd1489 */
pp4 = -2.3763017452e-05f, /* 0xb7c756b1 */
qq1 = 3.9791721106e-01f, /* 0x3ecbbbce */
qq2 = 6.5022252500e-02f, /* 0x3d852a63 */
qq3 = 5.0813062117e-03f, /* 0x3ba68116 */
qq4 = 1.3249473704e-04f, /* 0x390aee49 */
qq5 = -3.9602282413e-06f, /* 0xb684e21a */
/*
* Coefficients for approximation to erf in [0.84375,1.25]
*/
pa0 = -2.3621185683e-03f, /* 0xbb1acdc6 */
pa1 = 4.1485610604e-01f, /* 0x3ed46805 */
pa2 = -3.7220788002e-01f, /* 0xbebe9208 */
pa3 = 3.1834661961e-01f, /* 0x3ea2fe54 */
pa4 = -1.1089469492e-01f, /* 0xbde31cc2 */
pa5 = 3.5478305072e-02f, /* 0x3d1151b3 */
pa6 = -2.1663755178e-03f, /* 0xbb0df9c0 */
qa1 = 1.0642088205e-01f, /* 0x3dd9f331 */
qa2 = 5.4039794207e-01f, /* 0x3f0a5785 */
qa3 = 7.1828655899e-02f, /* 0x3d931ae7 */
qa4 = 1.2617121637e-01f, /* 0x3e013307 */
qa5 = 1.3637083583e-02f, /* 0x3c5f6e13 */
qa6 = 1.1984500103e-02f, /* 0x3c445aa3 */
/*
* Coefficients for approximation to erfc in [1.25,1/0.35]
*/
ra0 = -9.8649440333e-03f, /* 0xbc21a093 */
ra1 = -6.9385856390e-01f, /* 0xbf31a0b7 */
ra2 = -1.0558626175e+01f, /* 0xc128f022 */
ra3 = -6.2375331879e+01f, /* 0xc2798057 */
ra4 = -1.6239666748e+02f, /* 0xc322658c */
ra5 = -1.8460508728e+02f, /* 0xc3389ae7 */
ra6 = -8.1287437439e+01f, /* 0xc2a2932b */
ra7 = -9.8143291473e+00f, /* 0xc11d077e */
sa1 = 1.9651271820e+01f, /* 0x419d35ce */
sa2 = 1.3765776062e+02f, /* 0x4309a863 */
sa3 = 4.3456588745e+02f, /* 0x43d9486f */
sa4 = 6.4538726807e+02f, /* 0x442158c9 */
sa5 = 4.2900814819e+02f, /* 0x43d6810b */
sa6 = 1.0863500214e+02f, /* 0x42d9451f */
sa7 = 6.5702495575e+00f, /* 0x40d23f7c */
sa8 = -6.0424413532e-02f, /* 0xbd777f97 */
/*
* Coefficients for approximation to erfc in [1/.35,28]
*/
rb0 = -9.8649431020e-03f, /* 0xbc21a092 */
rb1 = -7.9928326607e-01f, /* 0xbf4c9dd4 */
rb2 = -1.7757955551e+01f, /* 0xc18e104b */
rb3 = -1.6063638306e+02f, /* 0xc320a2ea */
rb4 = -6.3756646729e+02f, /* 0xc41f6441 */
rb5 = -1.0250950928e+03f, /* 0xc480230b */
rb6 = -4.8351919556e+02f, /* 0xc3f1c275 */
sb1 = 3.0338060379e+01f, /* 0x41f2b459 */
sb2 = 3.2579251099e+02f, /* 0x43a2e571 */
sb3 = 1.5367296143e+03f, /* 0x44c01759 */
sb4 = 3.1998581543e+03f, /* 0x4547fdbb */
sb5 = 2.5530502930e+03f, /* 0x451f90ce */
sb6 = 4.7452853394e+02f, /* 0x43ed43a7 */
sb7 = -2.2440952301e+01f; /* 0xc1b38712 */
#ifdef __STDC__
float erff(float x)
#else
float erff(x)
float x;
#endif
{
__int32_t hx,ix,i;
float R,S,P,Q,s,y,z,r;
GET_FLOAT_WORD(hx,x);
ix = hx&0x7fffffff;
if(!FLT_UWORD_IS_FINITE(ix)) { /* erf(nan)=nan */
i = ((__uint32_t)hx>>31)<<1;
return (float)(1-i)+one/x; /* erf(+-inf)=+-1 */
}
if(ix < 0x3f580000) { /* |x|<0.84375 */
if(ix < 0x31800000) { /* |x|<2**-28 */
if (ix < 0x04000000)
/*avoid underflow */
return (float)0.125*((float)8.0*x+efx8*x);
return x + efx*x;
}
z = x*x;
r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
y = r/s;
return x + x*y;
}
if(ix < 0x3fa00000) { /* 0.84375 <= |x| < 1.25 */
s = fabsf(x)-one;
P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
if(hx>=0) return erx + P/Q; else return -erx - P/Q;
}
if (ix >= 0x40c00000) { /* inf>|x|>=6 */
if(hx>=0) return one-tiny; else return tiny-one;
}
x = fabsf(x);
s = one/(x*x);
if(ix< 0x4036DB6E) { /* |x| < 1/0.35 */
R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(
ra5+s*(ra6+s*ra7))))));
S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(
sa5+s*(sa6+s*(sa7+s*sa8)))))));
} else { /* |x| >= 1/0.35 */
R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(
rb5+s*rb6)))));
S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(
sb5+s*(sb6+s*sb7))))));
}
GET_FLOAT_WORD(ix,x);
SET_FLOAT_WORD(z,ix&0xfffff000);
r = __ieee754_expf(-z*z-(float)0.5625)*__ieee754_expf((z-x)*(z+x)+R/S);
if(hx>=0) return one-r/x; else return r/x-one;
}
#ifdef __STDC__
float erfcf(float x)
#else
float erfcf(x)
float x;
#endif
{
__int32_t hx,ix;
float R,S,P,Q,s,y,z,r;
GET_FLOAT_WORD(hx,x);
ix = hx&0x7fffffff;
if(!FLT_UWORD_IS_FINITE(ix)) { /* erfc(nan)=nan */
/* erfc(+-inf)=0,2 */
return (float)(((__uint32_t)hx>>31)<<1)+one/x;
}
if(ix < 0x3f580000) { /* |x|<0.84375 */
if(ix < 0x23800000) /* |x|<2**-56 */
return one-x;
z = x*x;
r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
y = r/s;
if(hx < 0x3e800000) { /* x<1/4 */
return one-(x+x*y);
} else {
r = x*y;
r += (x-half);
return half - r ;
}
}
if(ix < 0x3fa00000) { /* 0.84375 <= |x| < 1.25 */
s = fabsf(x)-one;
P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
if(hx>=0) {
z = one-erx; return z - P/Q;
} else {
z = erx+P/Q; return one+z;
}
}
if (ix < 0x41e00000) { /* |x|<28 */
x = fabsf(x);
s = one/(x*x);
if(ix< 0x4036DB6D) { /* |x| < 1/.35 ~ 2.857143*/
R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(
ra5+s*(ra6+s*ra7))))));
S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(
sa5+s*(sa6+s*(sa7+s*sa8)))))));
} else { /* |x| >= 1/.35 ~ 2.857143 */
if(hx<0&&ix>=0x40c00000) return two-tiny;/* x < -6 */
R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(
rb5+s*rb6)))));
S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(
sb5+s*(sb6+s*sb7))))));
}
GET_FLOAT_WORD(ix,x);
SET_FLOAT_WORD(z,ix&0xfffff000);
r = __ieee754_expf(-z*z-(float)0.5625)*
__ieee754_expf((z-x)*(z+x)+R/S);
if(hx>0) return r/x; else return two-r/x;
} else {
if(hx>0) return tiny*tiny; else return two-tiny;
}
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double erf(double x)
#else
double erf(x)
double x;
#endif
{
return (double) erff((float) x);
}
#ifdef __STDC__
double erfc(double x)
#else
double erfc(x)
double x;
#endif
{
return (double) erfcf((float) x);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/sf_erf.c | C | apache-2.0 | 7,546 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* sf_frexp.c -- float version of s_frexp.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
#include "fdlibm.h"
#ifdef __STDC__
static const float
#else
static float
#endif
two25 = 3.3554432000e+07f; /* 0x4c000000 */
#ifdef __STDC__
float frexpf(float x, int *eptr)
#else
float frexpf(x, eptr)
float x; int *eptr;
#endif
{
__int32_t hx, ix;
GET_FLOAT_WORD(hx,x);
ix = 0x7fffffff&hx;
*eptr = 0;
if(!FLT_UWORD_IS_FINITE(ix)||FLT_UWORD_IS_ZERO(ix)) return x; /* 0,inf,nan */
if (FLT_UWORD_IS_SUBNORMAL(ix)) { /* subnormal */
x *= two25;
GET_FLOAT_WORD(hx,x);
ix = hx&0x7fffffff;
*eptr = -25;
}
*eptr += (ix>>23)-126;
hx = (hx&0x807fffff)|0x3f000000;
SET_FLOAT_WORD(x,hx);
return x;
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double frexp(double x, int *eptr)
#else
double frexp(x, eptr)
double x; int *eptr;
#endif
{
return (double) frexpf((float) x, eptr);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/sf_frexp.c | C | apache-2.0 | 1,649 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* sf_ldexp.c -- float version of s_ldexp.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
#include "fdlibm.h"
#ifdef __STDC__
float ldexpf(float value, int exp)
#else
float ldexpf(value, exp)
float value; int exp;
#endif
{
if(!isfinite(value)||value==(float)0.0) return value;
value = scalbnf(value,exp);
//if(!finitef(value)||value==(float)0.0) errno = ERANGE;
return value;
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double ldexp(double value, int exp)
#else
double ldexp(value, exp)
double value; int exp;
#endif
{
return (double) ldexpf((float) value, exp);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/sf_ldexp.c | C | apache-2.0 | 1,328 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/common
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* sf_modf.c -- float version of s_modf.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
#include "fdlibm.h"
#ifdef __STDC__
static const float one = 1.0f;
#else
static float one = 1.0f;
#endif
#ifdef __STDC__
float modff(float x, float *iptr)
#else
float modff(x, iptr)
float x,*iptr;
#endif
{
__int32_t i0,j0;
__uint32_t i;
GET_FLOAT_WORD(i0,x);
j0 = ((i0>>23)&0xff)-0x7f; /* exponent of x */
if(j0<23) { /* integer part in x */
if(j0<0) { /* |x|<1 */
SET_FLOAT_WORD(*iptr,i0&0x80000000); /* *iptr = +-0 */
return x;
} else {
i = (0x007fffff)>>j0;
if((i0&i)==0) { /* x is integral */
__uint32_t ix;
*iptr = x;
GET_FLOAT_WORD(ix,x);
SET_FLOAT_WORD(x,ix&0x80000000); /* return +-0 */
return x;
} else {
SET_FLOAT_WORD(*iptr,i0&(~i));
return x - *iptr;
}
}
} else { /* no fraction part */
__uint32_t ix;
*iptr = x*one;
GET_FLOAT_WORD(ix,x);
SET_FLOAT_WORD(x,ix&0x80000000); /* return +-0 */
return x;
}
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double modf(double x, double *iptr)
#else
double modf(x, iptr)
double x,*iptr;
#endif
{
return (double) modff((float) x, (float *) iptr);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/sf_modf.c | C | apache-2.0 | 1,963 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* sf_sin.c -- float version of s_sin.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
#include "fdlibm.h"
#ifdef __STDC__
float sinf(float x)
#else
float sinf(x)
float x;
#endif
{
float y[2],z=0.0;
__int32_t n,ix;
GET_FLOAT_WORD(ix,x);
/* |x| ~< pi/4 */
ix &= 0x7fffffff;
if(ix <= 0x3f490fd8) return __kernel_sinf(x,z,0);
/* sin(Inf or NaN) is NaN */
else if (!FLT_UWORD_IS_FINITE(ix)) return x-x;
/* argument reduction needed */
else {
n = __ieee754_rem_pio2f(x,y);
switch(n&3) {
case 0: return __kernel_sinf(y[0],y[1],1);
case 1: return __kernel_cosf(y[0],y[1]);
case 2: return -__kernel_sinf(y[0],y[1],1);
default:
return -__kernel_cosf(y[0],y[1]);
}
}
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double sin(double x)
#else
double sin(x)
double x;
#endif
{
return (double) sinf((float) x);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/sf_sin.c | C | apache-2.0 | 1,606 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* sf_tan.c -- float version of s_tan.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
#include "fdlibm.h"
#ifdef __STDC__
float tanf(float x)
#else
float tanf(x)
float x;
#endif
{
float y[2],z=0.0;
__int32_t n,ix;
GET_FLOAT_WORD(ix,x);
/* |x| ~< pi/4 */
ix &= 0x7fffffff;
if(ix <= 0x3f490fda) return __kernel_tanf(x,z,1);
/* tan(Inf or NaN) is NaN */
else if (!FLT_UWORD_IS_FINITE(ix)) return x-x; /* NaN */
/* argument reduction needed */
else {
n = __ieee754_rem_pio2f(x,y);
return __kernel_tanf(y[0],y[1],1-((n&1)<<1)); /* 1 -- n even
-1 -- n odd */
}
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double tan(double x)
#else
double tan(x)
double x;
#endif
{
return (double) tanf((float) x);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/sf_tan.c | C | apache-2.0 | 1,503 |
// an implementation of sqrtf for Thumb using hardware VFP instructions
#include <math.h>
float sqrtf(float x) {
asm volatile (
"vsqrt.f32 %[r], %[x]\n"
: [r] "=t" (x)
: [x] "t" (x));
return x;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/thumb_vfp_sqrtf.c | C | apache-2.0 | 244 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* wf_lgamma.c -- float version of w_lgamma.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*
*/
#include "fdlibm.h"
#define _IEEE_LIBM 1
#ifdef __STDC__
float lgammaf(float x)
#else
float lgammaf(x)
float x;
#endif
{
#ifdef _IEEE_LIBM
int sign;
return __ieee754_lgammaf_r(x,&sign);
#else
float y;
struct exception exc;
y = __ieee754_lgammaf_r(x,&(_REENT_SIGNGAM(_REENT)));
if(_LIB_VERSION == _IEEE_) return y;
if(!finitef(y)&&finitef(x)) {
#ifndef HUGE_VAL
#define HUGE_VAL inf
double inf = 0.0;
SET_HIGH_WORD(inf,0x7ff00000); /* set inf to infinite */
#endif
exc.name = "lgammaf";
exc.err = 0;
exc.arg1 = exc.arg2 = (double)x;
if (_LIB_VERSION == _SVID_)
exc.retval = HUGE;
else
exc.retval = HUGE_VAL;
if(floorf(x)==x&&x<=(float)0.0) {
/* lgammaf(-integer) */
exc.type = SING;
if (_LIB_VERSION == _POSIX_)
errno = EDOM;
else if (!matherr(&exc)) {
errno = EDOM;
}
} else {
/* lgammaf(finite) overflow */
exc.type = OVERFLOW;
if (_LIB_VERSION == _POSIX_)
errno = ERANGE;
else if (!matherr(&exc)) {
errno = ERANGE;
}
}
if (exc.err != 0)
errno = exc.err;
return (float)exc.retval;
} else
return y;
#endif
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double lgamma(double x)
#else
double lgamma(x)
double x;
#endif
{
return (double) lgammaf((float) x);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/wf_lgamma.c | C | apache-2.0 | 2,302 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* w_gammaf.c -- float version of w_gamma.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* 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.
* ====================================================
*/
#include "math.h"
#include "fdlibm.h"
#define _IEEE_LIBM 1
#ifdef __STDC__
float tgammaf(float x)
#else
float tgammaf(x)
float x;
#endif
{
float y;
int local_signgam;
if (!isfinite(x)) {
/* special cases: tgammaf(nan)=nan, tgammaf(inf)=inf, tgammaf(-inf)=nan */
return x + INFINITY;
}
y = expf(__ieee754_lgammaf_r(x,&local_signgam));
if (local_signgam < 0) y = -y;
#ifdef _IEEE_LIBM
return y;
#else
if(_LIB_VERSION == _IEEE_) return y;
if(!finitef(y)&&finitef(x)) {
if(floorf(x)==x&&x<=(float)0.0)
/* tgammaf pole */
return (float)__kernel_standard((double)x,(double)x,141);
else
/* tgammaf overflow */
return (float)__kernel_standard((double)x,(double)x,140);
}
return y;
#endif
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double tgamma(double x)
#else
double tgamma(x)
double x;
#endif
{
return (double) tgammaf((float) x);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm/wf_tgamma.c | C | apache-2.0 | 1,727 |
/* origin: FreeBSD /usr/src/lib/msun/src/k_cos.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/*
* __cos( x, y )
* kernel cos function on [-pi/4, pi/4], pi/4 ~ 0.785398164
* Input x is assumed to be bounded by ~pi/4 in magnitude.
* Input y is the tail of x.
*
* Algorithm
* 1. Since cos(-x) = cos(x), we need only to consider positive x.
* 2. if x < 2^-27 (hx<0x3e400000 0), return 1 with inexact if x!=0.
* 3. cos(x) is approximated by a polynomial of degree 14 on
* [0,pi/4]
* 4 14
* cos(x) ~ 1 - x*x/2 + C1*x + ... + C6*x
* where the remez error is
*
* | 2 4 6 8 10 12 14 | -58
* |cos(x)-(1-.5*x +C1*x +C2*x +C3*x +C4*x +C5*x +C6*x )| <= 2
* | |
*
* 4 6 8 10 12 14
* 4. let r = C1*x +C2*x +C3*x +C4*x +C5*x +C6*x , then
* cos(x) ~ 1 - x*x/2 + r
* since cos(x+y) ~ cos(x) - sin(x)*y
* ~ cos(x) - x*y,
* a correction term is necessary in cos(x) and hence
* cos(x+y) = 1 - (x*x/2 - (r - x*y))
* For better accuracy, rearrange to
* cos(x+y) ~ w + (tmp + (r-x*y))
* where w = 1 - x*x/2 and tmp is a tiny correction term
* (1 - x*x/2 == w + tmp exactly in infinite precision).
* The exactness of w + tmp in infinite precision depends on w
* and tmp having the same precision as x. If they have extra
* precision due to compiler bugs, then the extra precision is
* only good provided it is retained in all terms of the final
* expression for cos(). Retention happens in all cases tested
* under FreeBSD, so don't pessimize things by forcibly clipping
* any extra precision in w.
*/
#include "libm.h"
static const double
C1 = 4.16666666666666019037e-02, /* 0x3FA55555, 0x5555554C */
C2 = -1.38888888888741095749e-03, /* 0xBF56C16C, 0x16C15177 */
C3 = 2.48015872894767294178e-05, /* 0x3EFA01A0, 0x19CB1590 */
C4 = -2.75573143513906633035e-07, /* 0xBE927E4F, 0x809C52AD */
C5 = 2.08757232129817482790e-09, /* 0x3E21EE9E, 0xBDB4B1C4 */
C6 = -1.13596475577881948265e-11; /* 0xBDA8FAE9, 0xBE8838D4 */
double __cos(double x, double y)
{
double_t hz,z,r,w;
z = x*x;
w = z*z;
r = z*(C1+z*(C2+z*C3)) + w*w*(C4+z*(C5+z*C6));
hz = 0.5*z;
w = 1.0-hz;
return w + (((1.0-w)-hz) + (z*r-x*y));
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/__cos.c | C | apache-2.0 | 2,884 |
#include "libm.h"
/* k is such that k*ln2 has minimal relative error and x - kln2 > log(DBL_MIN) */
static const int k = 2043;
static const double kln2 = 0x1.62066151add8bp+10;
/* exp(x)/2 for x >= log(DBL_MAX), slightly better than 0.5*exp(x/2)*exp(x/2) */
double __expo2(double x)
{
double scale;
/* note that k is odd and scale*scale overflows */
INSERT_WORDS(scale, (uint32_t)(0x3ff + k/2) << 20, 0);
/* exp(x - k ln2) * 2**(k-1) */
return exp(x - kln2) * scale * scale;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/__expo2.c | C | apache-2.0 | 485 |
#include <math.h>
#include <stdint.h>
int __fpclassifyd(double x)
{
union {double f; uint64_t i;} u = {x};
int e = u.i>>52 & 0x7ff;
if (!e) return u.i<<1 ? FP_SUBNORMAL : FP_ZERO;
if (e==0x7ff) return u.i<<12 ? FP_NAN : FP_INFINITE;
return FP_NORMAL;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/__fpclassify.c | C | apache-2.0 | 259 |
/* origin: FreeBSD /usr/src/lib/msun/src/e_rem_pio2.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*
* Optimized by Bruce D. Evans.
*/
/* __rem_pio2(x,y)
*
* return the remainder of x rem pi/2 in y[0]+y[1]
* use __rem_pio2_large() for large x
*/
#include "libm.h"
#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1
#define EPS DBL_EPSILON
#elif FLT_EVAL_METHOD==2
#define EPS LDBL_EPSILON
#endif
/*
* invpio2: 53 bits of 2/pi
* pio2_1: first 33 bit of pi/2
* pio2_1t: pi/2 - pio2_1
* pio2_2: second 33 bit of pi/2
* pio2_2t: pi/2 - (pio2_1+pio2_2)
* pio2_3: third 33 bit of pi/2
* pio2_3t: pi/2 - (pio2_1+pio2_2+pio2_3)
*/
static const double
toint = 1.5/EPS,
invpio2 = 6.36619772367581382433e-01, /* 0x3FE45F30, 0x6DC9C883 */
pio2_1 = 1.57079632673412561417e+00, /* 0x3FF921FB, 0x54400000 */
pio2_1t = 6.07710050650619224932e-11, /* 0x3DD0B461, 0x1A626331 */
pio2_2 = 6.07710050630396597660e-11, /* 0x3DD0B461, 0x1A600000 */
pio2_2t = 2.02226624879595063154e-21, /* 0x3BA3198A, 0x2E037073 */
pio2_3 = 2.02226624871116645580e-21, /* 0x3BA3198A, 0x2E000000 */
pio2_3t = 8.47842766036889956997e-32; /* 0x397B839A, 0x252049C1 */
/* caller must handle the case when reduction is not needed: |x| ~<= pi/4 */
int __rem_pio2(double x, double *y)
{
union {double f; uint64_t i;} u = {x};
double_t z,w,t,r,fn;
double tx[3],ty[2];
uint32_t ix;
int sign, n, ex, ey, i;
sign = u.i>>63;
ix = u.i>>32 & 0x7fffffff;
if (ix <= 0x400f6a7a) { /* |x| ~<= 5pi/4 */
if ((ix & 0xfffff) == 0x921fb) /* |x| ~= pi/2 or 2pi/2 */
goto medium; /* cancellation -- use medium case */
if (ix <= 0x4002d97c) { /* |x| ~<= 3pi/4 */
if (!sign) {
z = x - pio2_1; /* one round good to 85 bits */
y[0] = z - pio2_1t;
y[1] = (z-y[0]) - pio2_1t;
return 1;
} else {
z = x + pio2_1;
y[0] = z + pio2_1t;
y[1] = (z-y[0]) + pio2_1t;
return -1;
}
} else {
if (!sign) {
z = x - 2*pio2_1;
y[0] = z - 2*pio2_1t;
y[1] = (z-y[0]) - 2*pio2_1t;
return 2;
} else {
z = x + 2*pio2_1;
y[0] = z + 2*pio2_1t;
y[1] = (z-y[0]) + 2*pio2_1t;
return -2;
}
}
}
if (ix <= 0x401c463b) { /* |x| ~<= 9pi/4 */
if (ix <= 0x4015fdbc) { /* |x| ~<= 7pi/4 */
if (ix == 0x4012d97c) /* |x| ~= 3pi/2 */
goto medium;
if (!sign) {
z = x - 3*pio2_1;
y[0] = z - 3*pio2_1t;
y[1] = (z-y[0]) - 3*pio2_1t;
return 3;
} else {
z = x + 3*pio2_1;
y[0] = z + 3*pio2_1t;
y[1] = (z-y[0]) + 3*pio2_1t;
return -3;
}
} else {
if (ix == 0x401921fb) /* |x| ~= 4pi/2 */
goto medium;
if (!sign) {
z = x - 4*pio2_1;
y[0] = z - 4*pio2_1t;
y[1] = (z-y[0]) - 4*pio2_1t;
return 4;
} else {
z = x + 4*pio2_1;
y[0] = z + 4*pio2_1t;
y[1] = (z-y[0]) + 4*pio2_1t;
return -4;
}
}
}
if (ix < 0x413921fb) { /* |x| ~< 2^20*(pi/2), medium size */
medium:
/* rint(x/(pi/2)), Assume round-to-nearest. */
fn = (double_t)x*invpio2 + toint - toint;
n = (int32_t)fn;
r = x - fn*pio2_1;
w = fn*pio2_1t; /* 1st round, good to 85 bits */
y[0] = r - w;
u.f = y[0];
ey = u.i>>52 & 0x7ff;
ex = ix>>20;
if (ex - ey > 16) { /* 2nd round, good to 118 bits */
t = r;
w = fn*pio2_2;
r = t - w;
w = fn*pio2_2t - ((t-r)-w);
y[0] = r - w;
u.f = y[0];
ey = u.i>>52 & 0x7ff;
if (ex - ey > 49) { /* 3rd round, good to 151 bits, covers all cases */
t = r;
w = fn*pio2_3;
r = t - w;
w = fn*pio2_3t - ((t-r)-w);
y[0] = r - w;
}
}
y[1] = (r - y[0]) - w;
return n;
}
/*
* all other (large) arguments
*/
if (ix >= 0x7ff00000) { /* x is inf or NaN */
y[0] = y[1] = x - x;
return 0;
}
/* set z = scalbn(|x|,-ilogb(x)+23) */
u.f = x;
u.i &= (uint64_t)-1>>12;
u.i |= (uint64_t)(0x3ff + 23)<<52;
z = u.f;
for (i=0; i < 2; i++) {
tx[i] = (double)(int32_t)z;
z = (z-tx[i])*0x1p24;
}
tx[i] = z;
/* skip zero terms, first term is non-zero */
while (tx[i] == 0.0)
i--;
n = __rem_pio2_large(tx,ty,(int)(ix>>20)-(0x3ff+23),i+1,1);
if (sign) {
y[0] = -ty[0];
y[1] = -ty[1];
return -n;
}
y[0] = ty[0];
y[1] = ty[1];
return n;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/__rem_pio2.c | C | apache-2.0 | 4,474 |
/* origin: FreeBSD /usr/src/lib/msun/src/k_rem_pio2.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/*
* __rem_pio2_large(x,y,e0,nx,prec)
* double x[],y[]; int e0,nx,prec;
*
* __rem_pio2_large return the last three digits of N with
* y = x - N*pi/2
* so that |y| < pi/2.
*
* The method is to compute the integer (mod 8) and fraction parts of
* (2/pi)*x without doing the full multiplication. In general we
* skip the part of the product that are known to be a huge integer (
* more accurately, = 0 mod 8 ). Thus the number of operations are
* independent of the exponent of the input.
*
* (2/pi) is represented by an array of 24-bit integers in ipio2[].
*
* Input parameters:
* x[] The input value (must be positive) is broken into nx
* pieces of 24-bit integers in double precision format.
* x[i] will be the i-th 24 bit of x. The scaled exponent
* of x[0] is given in input parameter e0 (i.e., x[0]*2^e0
* match x's up to 24 bits.
*
* Example of breaking a double positive z into x[0]+x[1]+x[2]:
* e0 = ilogb(z)-23
* z = scalbn(z,-e0)
* for i = 0,1,2
* x[i] = floor(z)
* z = (z-x[i])*2**24
*
*
* y[] ouput result in an array of double precision numbers.
* The dimension of y[] is:
* 24-bit precision 1
* 53-bit precision 2
* 64-bit precision 2
* 113-bit precision 3
* The actual value is the sum of them. Thus for 113-bit
* precison, one may have to do something like:
*
* long double t,w,r_head, r_tail;
* t = (long double)y[2] + (long double)y[1];
* w = (long double)y[0];
* r_head = t+w;
* r_tail = w - (r_head - t);
*
* e0 The exponent of x[0]. Must be <= 16360 or you need to
* expand the ipio2 table.
*
* nx dimension of x[]
*
* prec an integer indicating the precision:
* 0 24 bits (single)
* 1 53 bits (double)
* 2 64 bits (extended)
* 3 113 bits (quad)
*
* External function:
* double scalbn(), floor();
*
*
* Here is the description of some local variables:
*
* jk jk+1 is the initial number of terms of ipio2[] needed
* in the computation. The minimum and recommended value
* for jk is 3,4,4,6 for single, double, extended, and quad.
* jk+1 must be 2 larger than you might expect so that our
* recomputation test works. (Up to 24 bits in the integer
* part (the 24 bits of it that we compute) and 23 bits in
* the fraction part may be lost to cancelation before we
* recompute.)
*
* jz local integer variable indicating the number of
* terms of ipio2[] used.
*
* jx nx - 1
*
* jv index for pointing to the suitable ipio2[] for the
* computation. In general, we want
* ( 2^e0*x[0] * ipio2[jv-1]*2^(-24jv) )/8
* is an integer. Thus
* e0-3-24*jv >= 0 or (e0-3)/24 >= jv
* Hence jv = max(0,(e0-3)/24).
*
* jp jp+1 is the number of terms in PIo2[] needed, jp = jk.
*
* q[] double array with integral value, representing the
* 24-bits chunk of the product of x and 2/pi.
*
* q0 the corresponding exponent of q[0]. Note that the
* exponent for q[i] would be q0-24*i.
*
* PIo2[] double precision array, obtained by cutting pi/2
* into 24 bits chunks.
*
* f[] ipio2[] in floating point
*
* iq[] integer array by breaking up q[] in 24-bits chunk.
*
* fq[] final product of x*(2/pi) in fq[0],..,fq[jk]
*
* ih integer. If >0 it indicates q[] is >= 0.5, hence
* it also indicates the *sign* of the result.
*
*/
/*
* 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 "libm.h"
static const int init_jk[] = {3,4,4,6}; /* initial value for jk */
/*
* Table of constants for 2/pi, 396 Hex digits (476 decimal) of 2/pi
*
* integer array, contains the (24*i)-th to (24*i+23)-th
* bit of 2/pi after binary point. The corresponding
* floating value is
*
* ipio2[i] * 2^(-24(i+1)).
*
* NB: This table must have at least (e0-3)/24 + jk terms.
* For quad precision (e0 <= 16360, jk = 6), this is 686.
*/
static const int32_t ipio2[] = {
0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62,
0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A,
0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129,
0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41,
0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8,
0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF,
0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5,
0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08,
0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3,
0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880,
0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B,
#if LDBL_MAX_EXP > 1024
0x47C419, 0xC367CD, 0xDCE809, 0x2A8359, 0xC4768B, 0x961CA6,
0xDDAF44, 0xD15719, 0x053EA5, 0xFF0705, 0x3F7E33, 0xE832C2,
0xDE4F98, 0x327DBB, 0xC33D26, 0xEF6B1E, 0x5EF89F, 0x3A1F35,
0xCAF27F, 0x1D87F1, 0x21907C, 0x7C246A, 0xFA6ED5, 0x772D30,
0x433B15, 0xC614B5, 0x9D19C3, 0xC2C4AD, 0x414D2C, 0x5D000C,
0x467D86, 0x2D71E3, 0x9AC69B, 0x006233, 0x7CD2B4, 0x97A7B4,
0xD55537, 0xF63ED7, 0x1810A3, 0xFC764D, 0x2A9D64, 0xABD770,
0xF87C63, 0x57B07A, 0xE71517, 0x5649C0, 0xD9D63B, 0x3884A7,
0xCB2324, 0x778AD6, 0x23545A, 0xB91F00, 0x1B0AF1, 0xDFCE19,
0xFF319F, 0x6A1E66, 0x615799, 0x47FBAC, 0xD87F7E, 0xB76522,
0x89E832, 0x60BFE6, 0xCDC4EF, 0x09366C, 0xD43F5D, 0xD7DE16,
0xDE3B58, 0x929BDE, 0x2822D2, 0xE88628, 0x4D58E2, 0x32CAC6,
0x16E308, 0xCB7DE0, 0x50C017, 0xA71DF3, 0x5BE018, 0x34132E,
0x621283, 0x014883, 0x5B8EF5, 0x7FB0AD, 0xF2E91E, 0x434A48,
0xD36710, 0xD8DDAA, 0x425FAE, 0xCE616A, 0xA4280A, 0xB499D3,
0xF2A606, 0x7F775C, 0x83C2A3, 0x883C61, 0x78738A, 0x5A8CAF,
0xBDD76F, 0x63A62D, 0xCBBFF4, 0xEF818D, 0x67C126, 0x45CA55,
0x36D9CA, 0xD2A828, 0x8D61C2, 0x77C912, 0x142604, 0x9B4612,
0xC459C4, 0x44C5C8, 0x91B24D, 0xF31700, 0xAD43D4, 0xE54929,
0x10D5FD, 0xFCBE00, 0xCC941E, 0xEECE70, 0xF53E13, 0x80F1EC,
0xC3E7B3, 0x28F8C7, 0x940593, 0x3E71C1, 0xB3092E, 0xF3450B,
0x9C1288, 0x7B20AB, 0x9FB52E, 0xC29247, 0x2F327B, 0x6D550C,
0x90A772, 0x1FE76B, 0x96CB31, 0x4A1679, 0xE27941, 0x89DFF4,
0x9794E8, 0x84E6E2, 0x973199, 0x6BED88, 0x365F5F, 0x0EFDBB,
0xB49A48, 0x6CA467, 0x427271, 0x325D8D, 0xB8159F, 0x09E5BC,
0x25318D, 0x3974F7, 0x1C0530, 0x010C0D, 0x68084B, 0x58EE2C,
0x90AA47, 0x02E774, 0x24D6BD, 0xA67DF7, 0x72486E, 0xEF169F,
0xA6948E, 0xF691B4, 0x5153D1, 0xF20ACF, 0x339820, 0x7E4BF5,
0x6863B2, 0x5F3EDD, 0x035D40, 0x7F8985, 0x295255, 0xC06437,
0x10D86D, 0x324832, 0x754C5B, 0xD4714E, 0x6E5445, 0xC1090B,
0x69F52A, 0xD56614, 0x9D0727, 0x50045D, 0xDB3BB4, 0xC576EA,
0x17F987, 0x7D6B49, 0xBA271D, 0x296996, 0xACCCC6, 0x5414AD,
0x6AE290, 0x89D988, 0x50722C, 0xBEA404, 0x940777, 0x7030F3,
0x27FC00, 0xA871EA, 0x49C266, 0x3DE064, 0x83DD97, 0x973FA3,
0xFD9443, 0x8C860D, 0xDE4131, 0x9D3992, 0x8C70DD, 0xE7B717,
0x3BDF08, 0x2B3715, 0xA0805C, 0x93805A, 0x921110, 0xD8E80F,
0xAF806C, 0x4BFFDB, 0x0F9038, 0x761859, 0x15A562, 0xBBCB61,
0xB989C7, 0xBD4010, 0x04F2D2, 0x277549, 0xF6B6EB, 0xBB22DB,
0xAA140A, 0x2F2689, 0x768364, 0x333B09, 0x1A940E, 0xAA3A51,
0xC2A31D, 0xAEEDAF, 0x12265C, 0x4DC26D, 0x9C7A2D, 0x9756C0,
0x833F03, 0xF6F009, 0x8C402B, 0x99316D, 0x07B439, 0x15200C,
0x5BC3D8, 0xC492F5, 0x4BADC6, 0xA5CA4E, 0xCD37A7, 0x36A9E6,
0x9492AB, 0x6842DD, 0xDE6319, 0xEF8C76, 0x528B68, 0x37DBFC,
0xABA1AE, 0x3115DF, 0xA1AE00, 0xDAFB0C, 0x664D64, 0xB705ED,
0x306529, 0xBF5657, 0x3AFF47, 0xB9F96A, 0xF3BE75, 0xDF9328,
0x3080AB, 0xF68C66, 0x15CB04, 0x0622FA, 0x1DE4D9, 0xA4B33D,
0x8F1B57, 0x09CD36, 0xE9424E, 0xA4BE13, 0xB52333, 0x1AAAF0,
0xA8654F, 0xA5C1D2, 0x0F3F0B, 0xCD785B, 0x76F923, 0x048B7B,
0x721789, 0x53A6C6, 0xE26E6F, 0x00EBEF, 0x584A9B, 0xB7DAC4,
0xBA66AA, 0xCFCF76, 0x1D02D1, 0x2DF1B1, 0xC1998C, 0x77ADC3,
0xDA4886, 0xA05DF7, 0xF480C6, 0x2FF0AC, 0x9AECDD, 0xBC5C3F,
0x6DDED0, 0x1FC790, 0xB6DB2A, 0x3A25A3, 0x9AAF00, 0x9353AD,
0x0457B6, 0xB42D29, 0x7E804B, 0xA707DA, 0x0EAA76, 0xA1597B,
0x2A1216, 0x2DB7DC, 0xFDE5FA, 0xFEDB89, 0xFDBE89, 0x6C76E4,
0xFCA906, 0x70803E, 0x156E85, 0xFF87FD, 0x073E28, 0x336761,
0x86182A, 0xEABD4D, 0xAFE7B3, 0x6E6D8F, 0x396795, 0x5BBF31,
0x48D784, 0x16DF30, 0x432DC7, 0x356125, 0xCE70C9, 0xB8CB30,
0xFD6CBF, 0xA200A4, 0xE46C05, 0xA0DD5A, 0x476F21, 0xD21262,
0x845CB9, 0x496170, 0xE0566B, 0x015299, 0x375550, 0xB7D51E,
0xC4F133, 0x5F6E13, 0xE4305D, 0xA92E85, 0xC3B21D, 0x3632A1,
0xA4B708, 0xD4B1EA, 0x21F716, 0xE4698F, 0x77FF27, 0x80030C,
0x2D408D, 0xA0CD4F, 0x99A520, 0xD3A2B3, 0x0A5D2F, 0x42F9B4,
0xCBDA11, 0xD0BE7D, 0xC1DB9B, 0xBD17AB, 0x81A2CA, 0x5C6A08,
0x17552E, 0x550027, 0xF0147F, 0x8607E1, 0x640B14, 0x8D4196,
0xDEBE87, 0x2AFDDA, 0xB6256B, 0x34897B, 0xFEF305, 0x9EBFB9,
0x4F6A68, 0xA82A4A, 0x5AC44F, 0xBCF82D, 0x985AD7, 0x95C7F4,
0x8D4D0D, 0xA63A20, 0x5F57A4, 0xB13F14, 0x953880, 0x0120CC,
0x86DD71, 0xB6DEC9, 0xF560BF, 0x11654D, 0x6B0701, 0xACB08C,
0xD0C0B2, 0x485551, 0x0EFB1E, 0xC37295, 0x3B06A3, 0x3540C0,
0x7BDC06, 0xCC45E0, 0xFA294E, 0xC8CAD6, 0x41F3E8, 0xDE647C,
0xD8649B, 0x31BED9, 0xC397A4, 0xD45877, 0xC5E369, 0x13DAF0,
0x3C3ABA, 0x461846, 0x5F7555, 0xF5BDD2, 0xC6926E, 0x5D2EAC,
0xED440E, 0x423E1C, 0x87C461, 0xE9FD29, 0xF3D6E7, 0xCA7C22,
0x35916F, 0xC5E008, 0x8DD7FF, 0xE26A6E, 0xC6FDB0, 0xC10893,
0x745D7C, 0xB2AD6B, 0x9D6ECD, 0x7B723E, 0x6A11C6, 0xA9CFF7,
0xDF7329, 0xBAC9B5, 0x5100B7, 0x0DB2E2, 0x24BA74, 0x607DE5,
0x8AD874, 0x2C150D, 0x0C1881, 0x94667E, 0x162901, 0x767A9F,
0xBEFDFD, 0xEF4556, 0x367ED9, 0x13D9EC, 0xB9BA8B, 0xFC97C4,
0x27A831, 0xC36EF1, 0x36C594, 0x56A8D8, 0xB5A8B4, 0x0ECCCF,
0x2D8912, 0x34576F, 0x89562C, 0xE3CE99, 0xB920D6, 0xAA5E6B,
0x9C2A3E, 0xCC5F11, 0x4A0BFD, 0xFBF4E1, 0x6D3B8E, 0x2C86E2,
0x84D4E9, 0xA9B4FC, 0xD1EEEF, 0xC9352E, 0x61392F, 0x442138,
0xC8D91B, 0x0AFC81, 0x6A4AFB, 0xD81C2F, 0x84B453, 0x8C994E,
0xCC2254, 0xDC552A, 0xD6C6C0, 0x96190B, 0xB8701A, 0x649569,
0x605A26, 0xEE523F, 0x0F117F, 0x11B5F4, 0xF5CBFC, 0x2DBC34,
0xEEBC34, 0xCC5DE8, 0x605EDD, 0x9B8E67, 0xEF3392, 0xB817C9,
0x9B5861, 0xBC57E1, 0xC68351, 0x103ED8, 0x4871DD, 0xDD1C2D,
0xA118AF, 0x462C21, 0xD7F359, 0x987AD9, 0xC0549E, 0xFA864F,
0xFC0656, 0xAE79E5, 0x362289, 0x22AD38, 0xDC9367, 0xAAE855,
0x382682, 0x9BE7CA, 0xA40D51, 0xB13399, 0x0ED7A9, 0x480569,
0xF0B265, 0xA7887F, 0x974C88, 0x36D1F9, 0xB39221, 0x4A827B,
0x21CF98, 0xDC9F40, 0x5547DC, 0x3A74E1, 0x42EB67, 0xDF9DFE,
0x5FD45E, 0xA4677B, 0x7AACBA, 0xA2F655, 0x23882B, 0x55BA41,
0x086E59, 0x862A21, 0x834739, 0xE6E389, 0xD49EE5, 0x40FB49,
0xE956FF, 0xCA0F1C, 0x8A59C5, 0x2BFA94, 0xC5C1D3, 0xCFC50F,
0xAE5ADB, 0x86C547, 0x624385, 0x3B8621, 0x94792C, 0x876110,
0x7B4C2A, 0x1A2C80, 0x12BF43, 0x902688, 0x893C78, 0xE4C4A8,
0x7BDBE5, 0xC23AC4, 0xEAF426, 0x8A67F7, 0xBF920D, 0x2BA365,
0xB1933D, 0x0B7CBD, 0xDC51A4, 0x63DD27, 0xDDE169, 0x19949A,
0x9529A8, 0x28CE68, 0xB4ED09, 0x209F44, 0xCA984E, 0x638270,
0x237C7E, 0x32B90F, 0x8EF5A7, 0xE75614, 0x08F121, 0x2A9DB5,
0x4D7E6F, 0x5119A5, 0xABF9B5, 0xD6DF82, 0x61DD96, 0x023616,
0x9F3AC4, 0xA1A283, 0x6DED72, 0x7A8D39, 0xA9B882, 0x5C326B,
0x5B2746, 0xED3400, 0x7700D2, 0x55F4FC, 0x4D5901, 0x8071E0,
#endif
};
static const double PIo2[] = {
1.57079625129699707031e+00, /* 0x3FF921FB, 0x40000000 */
7.54978941586159635335e-08, /* 0x3E74442D, 0x00000000 */
5.39030252995776476554e-15, /* 0x3CF84698, 0x80000000 */
3.28200341580791294123e-22, /* 0x3B78CC51, 0x60000000 */
1.27065575308067607349e-29, /* 0x39F01B83, 0x80000000 */
1.22933308981111328932e-36, /* 0x387A2520, 0x40000000 */
2.73370053816464559624e-44, /* 0x36E38222, 0x80000000 */
2.16741683877804819444e-51, /* 0x3569F31D, 0x00000000 */
};
int __rem_pio2_large(double *x, double *y, int e0, int nx, int prec)
{
int32_t jz,jx,jv,jp,jk,carry,n,iq[20],i,j,k,m,q0,ih;
double z,fw,f[20],fq[20],q[20];
/* initialize jk*/
jk = init_jk[prec];
jp = jk;
/* determine jx,jv,q0, note that 3>q0 */
jx = nx-1;
jv = (e0-3)/24; if(jv<0) jv=0;
q0 = e0-24*(jv+1);
/* set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk] */
j = jv-jx; m = jx+jk;
for (i=0; i<=m; i++,j++)
f[i] = j<0 ? 0.0 : (double)ipio2[j];
/* compute q[0],q[1],...q[jk] */
for (i=0; i<=jk; i++) {
for (j=0,fw=0.0; j<=jx; j++)
fw += x[j]*f[jx+i-j];
q[i] = fw;
}
jz = jk;
recompute:
/* distill q[] into iq[] reversingly */
for (i=0,j=jz,z=q[jz]; j>0; i++,j--) {
fw = (double)(int32_t)(0x1p-24*z);
iq[i] = (int32_t)(z - 0x1p24*fw);
z = q[j-1]+fw;
}
/* compute n */
z = scalbn(z,q0); /* actual value of z */
z -= 8.0*floor(z*0.125); /* trim off integer >= 8 */
n = (int32_t)z;
z -= (double)n;
ih = 0;
if (q0 > 0) { /* need iq[jz-1] to determine n */
i = iq[jz-1]>>(24-q0); n += i;
iq[jz-1] -= i<<(24-q0);
ih = iq[jz-1]>>(23-q0);
}
else if (q0 == 0) ih = iq[jz-1]>>23;
else if (z >= 0.5) ih = 2;
if (ih > 0) { /* q > 0.5 */
n += 1; carry = 0;
for (i=0; i<jz; i++) { /* compute 1-q */
j = iq[i];
if (carry == 0) {
if (j != 0) {
carry = 1;
iq[i] = 0x1000000 - j;
}
} else
iq[i] = 0xffffff - j;
}
if (q0 > 0) { /* rare case: chance is 1 in 12 */
switch(q0) {
case 1:
iq[jz-1] &= 0x7fffff; break;
case 2:
iq[jz-1] &= 0x3fffff; break;
}
}
if (ih == 2) {
z = 1.0 - z;
if (carry != 0)
z -= scalbn(1.0,q0);
}
}
/* check if recomputation is needed */
if (z == 0.0) {
j = 0;
for (i=jz-1; i>=jk; i--) j |= iq[i];
if (j == 0) { /* need recomputation */
for (k=1; iq[jk-k]==0; k++); /* k = no. of terms needed */
for (i=jz+1; i<=jz+k; i++) { /* add q[jz+1] to q[jz+k] */
f[jx+i] = (double)ipio2[jv+i];
for (j=0,fw=0.0; j<=jx; j++)
fw += x[j]*f[jx+i-j];
q[i] = fw;
}
jz += k;
goto recompute;
}
}
/* chop off zero terms */
if (z == 0.0) {
jz -= 1;
q0 -= 24;
while (iq[jz] == 0) {
jz--;
q0 -= 24;
}
} else { /* break z into 24-bit if necessary */
z = scalbn(z,-q0);
if (z >= 0x1p24) {
fw = (double)(int32_t)(0x1p-24*z);
iq[jz] = (int32_t)(z - 0x1p24*fw);
jz += 1;
q0 += 24;
iq[jz] = (int32_t)fw;
} else
iq[jz] = (int32_t)z;
}
/* convert integer "bit" chunk to floating-point value */
fw = scalbn(1.0,q0);
for (i=jz; i>=0; i--) {
q[i] = fw*(double)iq[i];
fw *= 0x1p-24;
}
/* compute PIo2[0,...,jp]*q[jz,...,0] */
for(i=jz; i>=0; i--) {
for (fw=0.0,k=0; k<=jp && k<=jz-i; k++)
fw += PIo2[k]*q[i+k];
fq[jz-i] = fw;
}
/* compress fq[] into y[] */
switch(prec) {
case 0:
fw = 0.0;
for (i=jz; i>=0; i--)
fw += fq[i];
y[0] = ih==0 ? fw : -fw;
break;
case 1:
case 2:
fw = 0.0;
for (i=jz; i>=0; i--)
fw += fq[i];
// TODO: drop excess precision here once double_t is used
fw = (double)fw;
y[0] = ih==0 ? fw : -fw;
fw = fq[0]-fw;
for (i=1; i<=jz; i++)
fw += fq[i];
y[1] = ih==0 ? fw : -fw;
break;
case 3: /* painful */
for (i=jz; i>0; i--) {
fw = fq[i-1]+fq[i];
fq[i] += fq[i-1]-fw;
fq[i-1] = fw;
}
for (i=jz; i>1; i--) {
fw = fq[i-1]+fq[i];
fq[i] += fq[i-1]-fw;
fq[i-1] = fw;
}
for (fw=0.0,i=jz; i>=2; i--)
fw += fq[i];
if (ih==0) {
y[0] = fq[0]; y[1] = fq[1]; y[2] = fw;
} else {
y[0] = -fq[0]; y[1] = -fq[1]; y[2] = -fw;
}
}
return n&7;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/__rem_pio2_large.c | C | apache-2.0 | 16,408 |
#include "libm.h"
int __signbitd(double x)
{
union {
double d;
uint64_t i;
} y = { x };
return y.i>>63;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/__signbit.c | C | apache-2.0 | 116 |
/* origin: FreeBSD /usr/src/lib/msun/src/k_sin.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* __sin( x, y, iy)
* kernel sin function on ~[-pi/4, pi/4] (except on -0), pi/4 ~ 0.7854
* Input x is assumed to be bounded by ~pi/4 in magnitude.
* Input y is the tail of x.
* Input iy indicates whether y is 0. (if iy=0, y assume to be 0).
*
* Algorithm
* 1. Since sin(-x) = -sin(x), we need only to consider positive x.
* 2. Callers must return sin(-0) = -0 without calling here since our
* odd polynomial is not evaluated in a way that preserves -0.
* Callers may do the optimization sin(x) ~ x for tiny x.
* 3. sin(x) is approximated by a polynomial of degree 13 on
* [0,pi/4]
* 3 13
* sin(x) ~ x + S1*x + ... + S6*x
* where
*
* |sin(x) 2 4 6 8 10 12 | -58
* |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x +S6*x )| <= 2
* | x |
*
* 4. sin(x+y) = sin(x) + sin'(x')*y
* ~ sin(x) + (1-x*x/2)*y
* For better accuracy, let
* 3 2 2 2 2
* r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6))))
* then 3 2
* sin(x) = x + (S1*x + (x *(r-y/2)+y))
*/
#include "libm.h"
static const double
S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */
S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */
S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */
S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */
S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */
S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */
double __sin(double x, double y, int iy)
{
double_t z,r,v,w;
z = x*x;
w = z*z;
r = S2 + z*(S3 + z*S4) + z*w*(S5 + z*S6);
v = z*x;
if (iy == 0)
return x + v*(S1 + z*r);
else
return x - ((z*(0.5*y - v*r) - y) - v*S1);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/__sin.c | C | apache-2.0 | 2,364 |
/* origin: FreeBSD /usr/src/lib/msun/src/k_tan.c */
/*
* ====================================================
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* __tan( x, y, k )
* kernel tan function on ~[-pi/4, pi/4] (except on -0), pi/4 ~ 0.7854
* Input x is assumed to be bounded by ~pi/4 in magnitude.
* Input y is the tail of x.
* Input odd indicates whether tan (if odd = 0) or -1/tan (if odd = 1) is returned.
*
* Algorithm
* 1. Since tan(-x) = -tan(x), we need only to consider positive x.
* 2. Callers must return tan(-0) = -0 without calling here since our
* odd polynomial is not evaluated in a way that preserves -0.
* Callers may do the optimization tan(x) ~ x for tiny x.
* 3. tan(x) is approximated by a odd polynomial of degree 27 on
* [0,0.67434]
* 3 27
* tan(x) ~ x + T1*x + ... + T13*x
* where
*
* |tan(x) 2 4 26 | -59.2
* |----- - (1+T1*x +T2*x +.... +T13*x )| <= 2
* | x |
*
* Note: tan(x+y) = tan(x) + tan'(x)*y
* ~ tan(x) + (1+x*x)*y
* Therefore, for better accuracy in computing tan(x+y), let
* 3 2 2 2 2
* r = x *(T2+x *(T3+x *(...+x *(T12+x *T13))))
* then
* 3 2
* tan(x+y) = x + (T1*x + (x *(r+y)+y))
*
* 4. For x in [0.67434,pi/4], let y = pi/4 - x, then
* tan(x) = tan(pi/4-y) = (1-tan(y))/(1+tan(y))
* = 1 - 2*(tan(y) - (tan(y)^2)/(1+tan(y)))
*/
#include "libm.h"
static const double T[] = {
3.33333333333334091986e-01, /* 3FD55555, 55555563 */
1.33333333333201242699e-01, /* 3FC11111, 1110FE7A */
5.39682539762260521377e-02, /* 3FABA1BA, 1BB341FE */
2.18694882948595424599e-02, /* 3F9664F4, 8406D637 */
8.86323982359930005737e-03, /* 3F8226E3, E96E8493 */
3.59207910759131235356e-03, /* 3F6D6D22, C9560328 */
1.45620945432529025516e-03, /* 3F57DBC8, FEE08315 */
5.88041240820264096874e-04, /* 3F4344D8, F2F26501 */
2.46463134818469906812e-04, /* 3F3026F7, 1A8D1068 */
7.81794442939557092300e-05, /* 3F147E88, A03792A6 */
7.14072491382608190305e-05, /* 3F12B80F, 32F0A7E9 */
-1.85586374855275456654e-05, /* BEF375CB, DB605373 */
2.59073051863633712884e-05, /* 3EFB2A70, 74BF7AD4 */
},
pio4 = 7.85398163397448278999e-01, /* 3FE921FB, 54442D18 */
pio4lo = 3.06161699786838301793e-17; /* 3C81A626, 33145C07 */
double __tan(double x, double y, int odd)
{
double_t z, r, v, w, s, a;
double w0, a0;
uint32_t hx;
int big, sign;
GET_HIGH_WORD(hx,x);
big = (hx&0x7fffffff) >= 0x3FE59428; /* |x| >= 0.6744 */
if (big) {
sign = hx>>31;
if (sign) {
x = -x;
y = -y;
}
x = (pio4 - x) + (pio4lo - y);
y = 0.0;
}
z = x * x;
w = z * z;
/*
* Break x^5*(T[1]+x^2*T[2]+...) into
* x^5(T[1]+x^4*T[3]+...+x^20*T[11]) +
* x^5(x^2*(T[2]+x^4*T[4]+...+x^22*[T12]))
*/
r = T[1] + w*(T[3] + w*(T[5] + w*(T[7] + w*(T[9] + w*T[11]))));
v = z*(T[2] + w*(T[4] + w*(T[6] + w*(T[8] + w*(T[10] + w*T[12])))));
s = z * x;
r = y + z*(s*(r + v) + y) + s*T[0];
w = x + r;
if (big) {
s = 1 - 2*odd;
v = s - 2.0 * (x + (r - w*w/(w + s)));
return sign ? -v : v;
}
if (!odd)
return w;
/* -1.0/(x+r) has up to 2ulp error, so compute it accurately */
w0 = w;
SET_LOW_WORD(w0, 0);
v = r - (w0 - x); /* w0+v = r+x */
a0 = a = -1.0 / w;
SET_LOW_WORD(a0, 0);
return a0 + a*(1.0 + a0*w0 + a0*v);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/__tan.c | C | apache-2.0 | 3,963 |
/* origin: FreeBSD /usr/src/lib/msun/src/e_acos.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* acos(x)
* Method :
* acos(x) = pi/2 - asin(x)
* acos(-x) = pi/2 + asin(x)
* For |x|<=0.5
* acos(x) = pi/2 - (x + x*x^2*R(x^2)) (see asin.c)
* For x>0.5
* acos(x) = pi/2 - (pi/2 - 2asin(sqrt((1-x)/2)))
* = 2asin(sqrt((1-x)/2))
* = 2s + 2s*z*R(z) ...z=(1-x)/2, s=sqrt(z)
* = 2f + (2c + 2s*z*R(z))
* where f=hi part of s, and c = (z-f*f)/(s+f) is the correction term
* for f so that f+c ~ sqrt(z).
* For x<-0.5
* acos(x) = pi - 2asin(sqrt((1-|x|)/2))
* = pi - 0.5*(s+s*z*R(z)), where z=(1-|x|)/2,s=sqrt(z)
*
* Special cases:
* if x is NaN, return x itself;
* if |x|>1, return NaN with invalid signal.
*
* Function needed: sqrt
*/
#include "libm.h"
static const double
pio2_hi = 1.57079632679489655800e+00, /* 0x3FF921FB, 0x54442D18 */
pio2_lo = 6.12323399573676603587e-17, /* 0x3C91A626, 0x33145C07 */
pS0 = 1.66666666666666657415e-01, /* 0x3FC55555, 0x55555555 */
pS1 = -3.25565818622400915405e-01, /* 0xBFD4D612, 0x03EB6F7D */
pS2 = 2.01212532134862925881e-01, /* 0x3FC9C155, 0x0E884455 */
pS3 = -4.00555345006794114027e-02, /* 0xBFA48228, 0xB5688F3B */
pS4 = 7.91534994289814532176e-04, /* 0x3F49EFE0, 0x7501B288 */
pS5 = 3.47933107596021167570e-05, /* 0x3F023DE1, 0x0DFDF709 */
qS1 = -2.40339491173441421878e+00, /* 0xC0033A27, 0x1C8A2D4B */
qS2 = 2.02094576023350569471e+00, /* 0x40002AE5, 0x9C598AC8 */
qS3 = -6.88283971605453293030e-01, /* 0xBFE6066C, 0x1B8D0159 */
qS4 = 7.70381505559019352791e-02; /* 0x3FB3B8C5, 0xB12E9282 */
static double R(double z)
{
double_t p, q;
p = z*(pS0+z*(pS1+z*(pS2+z*(pS3+z*(pS4+z*pS5)))));
q = 1.0+z*(qS1+z*(qS2+z*(qS3+z*qS4)));
return p/q;
}
double acos(double x)
{
double z,w,s,c,df;
uint32_t hx,ix;
GET_HIGH_WORD(hx, x);
ix = hx & 0x7fffffff;
/* |x| >= 1 or nan */
if (ix >= 0x3ff00000) {
uint32_t lx;
GET_LOW_WORD(lx,x);
if (((ix-0x3ff00000) | lx) == 0) {
/* acos(1)=0, acos(-1)=pi */
if (hx >> 31)
return 2*pio2_hi + 0x1p-120f;
return 0;
}
return 0/(x-x);
}
/* |x| < 0.5 */
if (ix < 0x3fe00000) {
if (ix <= 0x3c600000) /* |x| < 2**-57 */
return pio2_hi + 0x1p-120f;
return pio2_hi - (x - (pio2_lo-x*R(x*x)));
}
/* x < -0.5 */
if (hx >> 31) {
z = (1.0+x)*0.5;
s = sqrt(z);
w = R(z)*s-pio2_lo;
return 2*(pio2_hi - (s+w));
}
/* x > 0.5 */
z = (1.0-x)*0.5;
s = sqrt(z);
df = s;
SET_LOW_WORD(df,0);
c = (z-df*df)/(s+df);
w = R(z)*s+c;
return 2*(df+w);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/acos.c | C | apache-2.0 | 2,933 |
#include "libm.h"
#if FLT_EVAL_METHOD==2
#undef sqrt
#define sqrt sqrtl
#endif
/* acosh(x) = log(x + sqrt(x*x-1)) */
double acosh(double x)
{
union {double f; uint64_t i;} u = {.f = x};
unsigned e = u.i >> 52 & 0x7ff;
/* x < 1 domain error is handled in the called functions */
if (e < 0x3ff + 1)
/* |x| < 2, up to 2ulp error in [1,1.125] */
return log1p(x-1 + sqrt((x-1)*(x-1)+2*(x-1)));
if (e < 0x3ff + 26)
/* |x| < 0x1p26 */
return log(2*x - 1/(x+sqrt(x*x-1)));
/* |x| >= 0x1p26 or nan */
return log(x) + 0.693147180559945309417232121458176568;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/acosh.c | C | apache-2.0 | 569 |
/* origin: FreeBSD /usr/src/lib/msun/src/e_asin.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* asin(x)
* Method :
* Since asin(x) = x + x^3/6 + x^5*3/40 + x^7*15/336 + ...
* we approximate asin(x) on [0,0.5] by
* asin(x) = x + x*x^2*R(x^2)
* where
* R(x^2) is a rational approximation of (asin(x)-x)/x^3
* and its remez error is bounded by
* |(asin(x)-x)/x^3 - R(x^2)| < 2^(-58.75)
*
* For x in [0.5,1]
* asin(x) = pi/2-2*asin(sqrt((1-x)/2))
* Let y = (1-x), z = y/2, s := sqrt(z), and pio2_hi+pio2_lo=pi/2;
* then for x>0.98
* asin(x) = pi/2 - 2*(s+s*z*R(z))
* = pio2_hi - (2*(s+s*z*R(z)) - pio2_lo)
* For x<=0.98, let pio4_hi = pio2_hi/2, then
* f = hi part of s;
* c = sqrt(z) - f = (z-f*f)/(s+f) ...f+c=sqrt(z)
* and
* asin(x) = pi/2 - 2*(s+s*z*R(z))
* = pio4_hi+(pio4-2s)-(2s*z*R(z)-pio2_lo)
* = pio4_hi+(pio4-2f)-(2s*z*R(z)-(pio2_lo+2c))
*
* Special cases:
* if x is NaN, return x itself;
* if |x|>1, return NaN with invalid signal.
*
*/
#include "libm.h"
static const double
pio2_hi = 1.57079632679489655800e+00, /* 0x3FF921FB, 0x54442D18 */
pio2_lo = 6.12323399573676603587e-17, /* 0x3C91A626, 0x33145C07 */
/* coefficients for R(x^2) */
pS0 = 1.66666666666666657415e-01, /* 0x3FC55555, 0x55555555 */
pS1 = -3.25565818622400915405e-01, /* 0xBFD4D612, 0x03EB6F7D */
pS2 = 2.01212532134862925881e-01, /* 0x3FC9C155, 0x0E884455 */
pS3 = -4.00555345006794114027e-02, /* 0xBFA48228, 0xB5688F3B */
pS4 = 7.91534994289814532176e-04, /* 0x3F49EFE0, 0x7501B288 */
pS5 = 3.47933107596021167570e-05, /* 0x3F023DE1, 0x0DFDF709 */
qS1 = -2.40339491173441421878e+00, /* 0xC0033A27, 0x1C8A2D4B */
qS2 = 2.02094576023350569471e+00, /* 0x40002AE5, 0x9C598AC8 */
qS3 = -6.88283971605453293030e-01, /* 0xBFE6066C, 0x1B8D0159 */
qS4 = 7.70381505559019352791e-02; /* 0x3FB3B8C5, 0xB12E9282 */
static double R(double z)
{
double_t p, q;
p = z*(pS0+z*(pS1+z*(pS2+z*(pS3+z*(pS4+z*pS5)))));
q = 1.0+z*(qS1+z*(qS2+z*(qS3+z*qS4)));
return p/q;
}
double asin(double x)
{
double z,r,s;
uint32_t hx,ix;
GET_HIGH_WORD(hx, x);
ix = hx & 0x7fffffff;
/* |x| >= 1 or nan */
if (ix >= 0x3ff00000) {
uint32_t lx;
GET_LOW_WORD(lx, x);
if (((ix-0x3ff00000) | lx) == 0)
/* asin(1) = +-pi/2 with inexact */
return x*pio2_hi + 0x1p-120f;
return 0/(x-x);
}
/* |x| < 0.5 */
if (ix < 0x3fe00000) {
/* if 0x1p-1022 <= |x| < 0x1p-26, avoid raising underflow */
if (ix < 0x3e500000 && ix >= 0x00100000)
return x;
return x + x*R(x*x);
}
/* 1 > |x| >= 0.5 */
z = (1 - fabs(x))*0.5;
s = sqrt(z);
r = R(z);
if (ix >= 0x3fef3333) { /* if |x| > 0.975 */
x = pio2_hi-(2*(s+s*r)-pio2_lo);
} else {
double f,c;
/* f+c = sqrt(z) */
f = s;
SET_LOW_WORD(f,0);
c = (z-f*f)/(s+f);
x = 0.5*pio2_hi - (2*s*r - (pio2_lo-2*c) - (0.5*pio2_hi-2*f));
}
if (hx >> 31)
return -x;
return x;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/asin.c | C | apache-2.0 | 3,404 |
#include "libm.h"
/* asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5) */
double asinh(double x)
{
union {double f; uint64_t i;} u = {.f = x};
unsigned e = u.i >> 52 & 0x7ff;
unsigned s = u.i >> 63;
/* |x| */
u.i &= (uint64_t)-1/2;
x = u.f;
if (e >= 0x3ff + 26) {
/* |x| >= 0x1p26 or inf or nan */
x = log(x) + 0.693147180559945309417232121458176568;
} else if (e >= 0x3ff + 1) {
/* |x| >= 2 */
x = log(2*x + 1/(sqrt(x*x+1)+x));
} else if (e >= 0x3ff - 26) {
/* |x| >= 0x1p-26, up to 1.6ulp error in [0.125,0.5] */
x = log1p(x + x*x/(sqrt(x*x+1)+1));
} else {
/* |x| < 0x1p-26, raise inexact if x != 0 */
FORCE_EVAL(x + 0x1p120f);
}
return s ? -x : x;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/asinh.c | C | apache-2.0 | 697 |
/* origin: FreeBSD /usr/src/lib/msun/src/s_atan.c */
/*
* ====================================================
* 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.
* ====================================================
*/
/* atan(x)
* Method
* 1. Reduce x to positive by atan(x) = -atan(-x).
* 2. According to the integer k=4t+0.25 chopped, t=x, the argument
* is further reduced to one of the following intervals and the
* arctangent of t is evaluated by the corresponding formula:
*
* [0,7/16] atan(x) = t-t^3*(a1+t^2*(a2+...(a10+t^2*a11)...)
* [7/16,11/16] atan(x) = atan(1/2) + atan( (t-0.5)/(1+t/2) )
* [11/16.19/16] atan(x) = atan( 1 ) + atan( (t-1)/(1+t) )
* [19/16,39/16] atan(x) = atan(3/2) + atan( (t-1.5)/(1+1.5t) )
* [39/16,INF] atan(x) = atan(INF) + atan( -1/t )
*
* 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 "libm.h"
static const double atanhi[] = {
4.63647609000806093515e-01, /* atan(0.5)hi 0x3FDDAC67, 0x0561BB4F */
7.85398163397448278999e-01, /* atan(1.0)hi 0x3FE921FB, 0x54442D18 */
9.82793723247329054082e-01, /* atan(1.5)hi 0x3FEF730B, 0xD281F69B */
1.57079632679489655800e+00, /* atan(inf)hi 0x3FF921FB, 0x54442D18 */
};
static const double atanlo[] = {
2.26987774529616870924e-17, /* atan(0.5)lo 0x3C7A2B7F, 0x222F65E2 */
3.06161699786838301793e-17, /* atan(1.0)lo 0x3C81A626, 0x33145C07 */
1.39033110312309984516e-17, /* atan(1.5)lo 0x3C700788, 0x7AF0CBBD */
6.12323399573676603587e-17, /* atan(inf)lo 0x3C91A626, 0x33145C07 */
};
static const double aT[] = {
3.33333333333329318027e-01, /* 0x3FD55555, 0x5555550D */
-1.99999999998764832476e-01, /* 0xBFC99999, 0x9998EBC4 */
1.42857142725034663711e-01, /* 0x3FC24924, 0x920083FF */
-1.11111104054623557880e-01, /* 0xBFBC71C6, 0xFE231671 */
9.09088713343650656196e-02, /* 0x3FB745CD, 0xC54C206E */
-7.69187620504482999495e-02, /* 0xBFB3B0F2, 0xAF749A6D */
6.66107313738753120669e-02, /* 0x3FB10D66, 0xA0D03D51 */
-5.83357013379057348645e-02, /* 0xBFADDE2D, 0x52DEFD9A */
4.97687799461593236017e-02, /* 0x3FA97B4B, 0x24760DEB */
-3.65315727442169155270e-02, /* 0xBFA2B444, 0x2C6A6C2F */
1.62858201153657823623e-02, /* 0x3F90AD3A, 0xE322DA11 */
};
double atan(double x)
{
double_t w,s1,s2,z;
uint32_t ix,sign;
int id;
GET_HIGH_WORD(ix, x);
sign = ix >> 31;
ix &= 0x7fffffff;
if (ix >= 0x44100000) { /* if |x| >= 2^66 */
if (isnan(x))
return x;
z = atanhi[3] + 0x1p-120f;
return sign ? -z : z;
}
if (ix < 0x3fdc0000) { /* |x| < 0.4375 */
if (ix < 0x3e400000) { /* |x| < 2^-27 */
if (ix < 0x00100000)
/* raise underflow for subnormal x */
FORCE_EVAL((float)x);
return x;
}
id = -1;
} else {
x = fabs(x);
if (ix < 0x3ff30000) { /* |x| < 1.1875 */
if (ix < 0x3fe60000) { /* 7/16 <= |x| < 11/16 */
id = 0;
x = (2.0*x-1.0)/(2.0+x);
} else { /* 11/16 <= |x| < 19/16 */
id = 1;
x = (x-1.0)/(x+1.0);
}
} else {
if (ix < 0x40038000) { /* |x| < 2.4375 */
id = 2;
x = (x-1.5)/(1.0+1.5*x);
} else { /* 2.4375 <= |x| < 2^66 */
id = 3;
x = -1.0/x;
}
}
}
/* end of argument reduction */
z = x*x;
w = z*z;
/* break sum from i=0 to 10 aT[i]z**(i+1) into odd and even poly */
s1 = z*(aT[0]+w*(aT[2]+w*(aT[4]+w*(aT[6]+w*(aT[8]+w*aT[10])))));
s2 = w*(aT[1]+w*(aT[3]+w*(aT[5]+w*(aT[7]+w*aT[9]))));
if (id < 0)
return x - x*(s1+s2);
z = atanhi[id] - (x*(s1+s2) - atanlo[id] - x);
return sign ? -z : z;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/atan.c | C | apache-2.0 | 3,934 |
/* origin: FreeBSD /usr/src/lib/msun/src/e_atan2.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*
*/
/* atan2(y,x)
* Method :
* 1. Reduce y to positive by atan2(y,x)=-atan2(-y,x).
* 2. Reduce x to positive by (if x and y are unexceptional):
* ARG (x+iy) = arctan(y/x) ... if x > 0,
* ARG (x+iy) = pi - arctan[y/(-x)] ... if x < 0,
*
* Special cases:
*
* ATAN2((anything), NaN ) is NaN;
* ATAN2(NAN , (anything) ) is NaN;
* ATAN2(+-0, +(anything but NaN)) is +-0 ;
* ATAN2(+-0, -(anything but NaN)) is +-pi ;
* ATAN2(+-(anything but 0 and NaN), 0) is +-pi/2;
* ATAN2(+-(anything but INF and NaN), +INF) is +-0 ;
* ATAN2(+-(anything but INF and NaN), -INF) is +-pi;
* ATAN2(+-INF,+INF ) is +-pi/4 ;
* ATAN2(+-INF,-INF ) is +-3pi/4;
* ATAN2(+-INF, (anything but,0,NaN, and INF)) is +-pi/2;
*
* 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 "libm.h"
static const double
pi = 3.1415926535897931160E+00, /* 0x400921FB, 0x54442D18 */
pi_lo = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */
double atan2(double y, double x)
{
double z;
uint32_t m,lx,ly,ix,iy;
if (isnan(x) || isnan(y))
return x+y;
EXTRACT_WORDS(ix, lx, x);
EXTRACT_WORDS(iy, ly, y);
if (((ix-0x3ff00000) | lx) == 0) /* x = 1.0 */
return atan(y);
m = ((iy>>31)&1) | ((ix>>30)&2); /* 2*sign(x)+sign(y) */
ix = ix & 0x7fffffff;
iy = iy & 0x7fffffff;
/* when y = 0 */
if ((iy|ly) == 0) {
switch(m) {
case 0:
case 1: return y; /* atan(+-0,+anything)=+-0 */
case 2: return pi; /* atan(+0,-anything) = pi */
case 3: return -pi; /* atan(-0,-anything) =-pi */
}
}
/* when x = 0 */
if ((ix|lx) == 0)
return m&1 ? -pi/2 : pi/2;
/* when x is INF */
if (ix == 0x7ff00000) {
if (iy == 0x7ff00000) {
switch(m) {
case 0: return pi/4; /* atan(+INF,+INF) */
case 1: return -pi/4; /* atan(-INF,+INF) */
case 2: return 3*pi/4; /* atan(+INF,-INF) */
case 3: return -3*pi/4; /* atan(-INF,-INF) */
}
} else {
switch(m) {
case 0: return 0.0; /* atan(+...,+INF) */
case 1: return -0.0; /* atan(-...,+INF) */
case 2: return pi; /* atan(+...,-INF) */
case 3: return -pi; /* atan(-...,-INF) */
}
}
}
/* |y/x| > 0x1p64 */
if (ix+(64<<20) < iy || iy == 0x7ff00000)
return m&1 ? -pi/2 : pi/2;
/* z = atan(|y/x|) without spurious underflow */
if ((m&2) && iy+(64<<20) < ix) /* |y/x| < 0x1p-64, x<0 */
z = 0;
else
z = atan(fabs(y/x));
switch (m) {
case 0: return z; /* atan(+,+) */
case 1: return -z; /* atan(-,+) */
case 2: return pi - (z-pi_lo); /* atan(+,-) */
default: /* case 3 */
return (z-pi_lo) - pi; /* atan(-,-) */
}
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/atan2.c | C | apache-2.0 | 3,285 |
#include "libm.h"
/* atanh(x) = log((1+x)/(1-x))/2 = log1p(2x/(1-x))/2 ~= x + x^3/3 + o(x^5) */
double atanh(double x)
{
union {double f; uint64_t i;} u = {.f = x};
unsigned e = u.i >> 52 & 0x7ff;
unsigned s = u.i >> 63;
double_t y;
/* |x| */
u.i &= (uint64_t)-1/2;
y = u.f;
if (e < 0x3ff - 1) {
if (e < 0x3ff - 32) {
/* handle underflow */
if (e == 0)
FORCE_EVAL((float)y);
} else {
/* |x| < 0.5, up to 1.7ulp error */
y = 0.5*log1p(2*y + 2*y*y/(1-y));
}
} else {
/* avoid overflow */
y = 0.5*log1p(2*(y/(1-y)));
}
return s ? -y : y;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/atanh.c | C | apache-2.0 | 577 |
#include "libm.h"
#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1
#define EPS DBL_EPSILON
#elif FLT_EVAL_METHOD==2
#define EPS LDBL_EPSILON
#endif
static const double_t toint = 1/EPS;
double ceil(double x)
{
union {double f; uint64_t i;} u = {x};
int e = u.i >> 52 & 0x7ff;
double_t y;
if (e >= 0x3ff+52 || x == 0)
return x;
/* y = int(x) - x, where int(x) is an integer neighbor of x */
if (u.i >> 63)
y = x - toint + toint - x;
else
y = x + toint - toint - x;
/* special case because of non-nearest rounding modes */
if (e <= 0x3ff-1) {
FORCE_EVAL(y);
return u.i >> 63 ? -0.0 : 1;
}
if (y < 0)
return x + y + 1;
return x + y;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/ceil.c | C | apache-2.0 | 654 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* 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 "libm.h"
#ifndef NDEBUG
typedef union {
double d;
struct {
uint64_t m : 52;
uint64_t e : 11;
uint64_t s : 1;
};
} double_s_t;
double copysign(double x, double y) {
double_s_t dx={.d = x};
double_s_t dy={.d = y};
// copy sign bit;
dx.s = dy.s;
return dx.d;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/copysign.c | C | apache-2.0 | 1,566 |
/* origin: FreeBSD /usr/src/lib/msun/src/s_cos.c */
/*
* ====================================================
* 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.
* ====================================================
*/
/* cos(x)
* Return cosine function of x.
*
* kernel function:
* __sin ... sine function on [-pi/4,pi/4]
* __cos ... cosine function on [-pi/4,pi/4]
* __rem_pio2 ... argument reduction routine
*
* Method.
* Let S,C and T denote the sin, cos and tan respectively on
* [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2
* in [-pi/4 , +pi/4], and let n = k mod 4.
* We have
*
* n sin(x) cos(x) tan(x)
* ----------------------------------------------------------
* 0 S C T
* 1 C -S -1/T
* 2 -S -C T
* 3 -C S -1/T
* ----------------------------------------------------------
*
* Special cases:
* Let trig be any of sin, cos, or tan.
* trig(+-INF) is NaN, with signals;
* trig(NaN) is that NaN;
*
* Accuracy:
* TRIG(x) returns trig(x) nearly rounded
*/
#include "libm.h"
double cos(double x)
{
double y[2];
uint32_t ix;
unsigned n;
GET_HIGH_WORD(ix, x);
ix &= 0x7fffffff;
/* |x| ~< pi/4 */
if (ix <= 0x3fe921fb) {
if (ix < 0x3e46a09e) { /* |x| < 2**-27 * sqrt(2) */
/* raise inexact if x!=0 */
FORCE_EVAL(x + 0x1p120f);
return 1.0;
}
return __cos(x, 0);
}
/* cos(Inf or NaN) is NaN */
if (ix >= 0x7ff00000)
return x-x;
/* argument reduction */
n = __rem_pio2(x, y);
switch (n&3) {
case 0: return __cos(y[0], y[1]);
case 1: return -__sin(y[0], y[1], 1);
case 2: return -__cos(y[0], y[1]);
default:
return __sin(y[0], y[1], 1);
}
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/cos.c | C | apache-2.0 | 2,111 |
#include "libm.h"
/* cosh(x) = (exp(x) + 1/exp(x))/2
* = 1 + 0.5*(exp(x)-1)*(exp(x)-1)/exp(x)
* = 1 + x*x/2 + o(x^4)
*/
double cosh(double x)
{
union {double f; uint64_t i;} u = {.f = x};
uint32_t w;
double t;
/* |x| */
u.i &= (uint64_t)-1/2;
x = u.f;
w = u.i >> 32;
/* |x| < log(2) */
if (w < 0x3fe62e42) {
if (w < 0x3ff00000 - (26<<20)) {
/* raise inexact if x!=0 */
FORCE_EVAL(x + 0x1p120f);
return 1;
}
t = expm1(x);
return 1 + t*t/(2*(1+t));
}
/* |x| < log(DBL_MAX) */
if (w < 0x40862e42) {
t = exp(x);
/* note: if x>log(0x1p26) then the 1/t is not needed */
return 0.5*(t + 1/t);
}
/* |x| > log(DBL_MAX) or nan */
/* note: the result is stored to handle overflow */
t = __expo2(x);
return t;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/cosh.c | C | apache-2.0 | 764 |
/* origin: FreeBSD /usr/src/lib/msun/src/s_erf.c */
/*
* ====================================================
* 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.
* ====================================================
*/
/* double erf(double x)
* double erfc(double x)
* x
* 2 |\
* erf(x) = --------- | exp(-t*t)dt
* sqrt(pi) \|
* 0
*
* erfc(x) = 1-erf(x)
* Note that
* erf(-x) = -erf(x)
* erfc(-x) = 2 - erfc(x)
*
* Method:
* 1. For |x| in [0, 0.84375]
* erf(x) = x + x*R(x^2)
* erfc(x) = 1 - erf(x) if x in [-.84375,0.25]
* = 0.5 + ((0.5-x)-x*R) if x in [0.25,0.84375]
* where R = P/Q where P is an odd poly of degree 8 and
* Q is an odd poly of degree 10.
* -57.90
* | R - (erf(x)-x)/x | <= 2
*
*
* Remark. The formula is derived by noting
* erf(x) = (2/sqrt(pi))*(x - x^3/3 + x^5/10 - x^7/42 + ....)
* and that
* 2/sqrt(pi) = 1.128379167095512573896158903121545171688
* is close to one. The interval is chosen because the fix
* point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is
* near 0.6174), and by some experiment, 0.84375 is chosen to
* guarantee the error is less than one ulp for erf.
*
* 2. For |x| in [0.84375,1.25], let s = |x| - 1, and
* c = 0.84506291151 rounded to single (24 bits)
* erf(x) = sign(x) * (c + P1(s)/Q1(s))
* erfc(x) = (1-c) - P1(s)/Q1(s) if x > 0
* 1+(c+P1(s)/Q1(s)) if x < 0
* |P1/Q1 - (erf(|x|)-c)| <= 2**-59.06
* Remark: here we use the taylor series expansion at x=1.
* erf(1+s) = erf(1) + s*Poly(s)
* = 0.845.. + P1(s)/Q1(s)
* That is, we use rational approximation to approximate
* erf(1+s) - (c = (single)0.84506291151)
* Note that |P1/Q1|< 0.078 for x in [0.84375,1.25]
* where
* P1(s) = degree 6 poly in s
* Q1(s) = degree 6 poly in s
*
* 3. For x in [1.25,1/0.35(~2.857143)],
* erfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1)
* erf(x) = 1 - erfc(x)
* where
* R1(z) = degree 7 poly in z, (z=1/x^2)
* S1(z) = degree 8 poly in z
*
* 4. For x in [1/0.35,28]
* erfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0
* = 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6<x<0
* = 2.0 - tiny (if x <= -6)
* erf(x) = sign(x)*(1.0 - erfc(x)) if x < 6, else
* erf(x) = sign(x)*(1.0 - tiny)
* where
* R2(z) = degree 6 poly in z, (z=1/x^2)
* S2(z) = degree 7 poly in z
*
* Note1:
* To compute exp(-x*x-0.5625+R/S), let s be a single
* precision number and s := x; then
* -x*x = -s*s + (s-x)*(s+x)
* exp(-x*x-0.5626+R/S) =
* exp(-s*s-0.5625)*exp((s-x)*(s+x)+R/S);
* Note2:
* Here 4 and 5 make use of the asymptotic series
* exp(-x*x)
* erfc(x) ~ ---------- * ( 1 + Poly(1/x^2) )
* x*sqrt(pi)
* We use rational approximation to approximate
* g(s)=f(1/x^2) = log(erfc(x)*x) - x*x + 0.5625
* Here is the error bound for R1/S1 and R2/S2
* |R1/S1 - f(x)| < 2**(-62.57)
* |R2/S2 - f(x)| < 2**(-61.52)
*
* 5. For inf > x >= 28
* erf(x) = sign(x) *(1 - tiny) (raise inexact)
* erfc(x) = tiny*tiny (raise underflow) if x > 0
* = 2 - tiny if x<0
*
* 7. Special case:
* erf(0) = 0, erf(inf) = 1, erf(-inf) = -1,
* erfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2,
* erfc/erf(NaN) is NaN
*/
#include "libm.h"
static const double
erx = 8.45062911510467529297e-01, /* 0x3FEB0AC1, 0x60000000 */
/*
* Coefficients for approximation to erf on [0,0.84375]
*/
efx8 = 1.02703333676410069053e+00, /* 0x3FF06EBA, 0x8214DB69 */
pp0 = 1.28379167095512558561e-01, /* 0x3FC06EBA, 0x8214DB68 */
pp1 = -3.25042107247001499370e-01, /* 0xBFD4CD7D, 0x691CB913 */
pp2 = -2.84817495755985104766e-02, /* 0xBF9D2A51, 0xDBD7194F */
pp3 = -5.77027029648944159157e-03, /* 0xBF77A291, 0x236668E4 */
pp4 = -2.37630166566501626084e-05, /* 0xBEF8EAD6, 0x120016AC */
qq1 = 3.97917223959155352819e-01, /* 0x3FD97779, 0xCDDADC09 */
qq2 = 6.50222499887672944485e-02, /* 0x3FB0A54C, 0x5536CEBA */
qq3 = 5.08130628187576562776e-03, /* 0x3F74D022, 0xC4D36B0F */
qq4 = 1.32494738004321644526e-04, /* 0x3F215DC9, 0x221C1A10 */
qq5 = -3.96022827877536812320e-06, /* 0xBED09C43, 0x42A26120 */
/*
* Coefficients for approximation to erf in [0.84375,1.25]
*/
pa0 = -2.36211856075265944077e-03, /* 0xBF6359B8, 0xBEF77538 */
pa1 = 4.14856118683748331666e-01, /* 0x3FDA8D00, 0xAD92B34D */
pa2 = -3.72207876035701323847e-01, /* 0xBFD7D240, 0xFBB8C3F1 */
pa3 = 3.18346619901161753674e-01, /* 0x3FD45FCA, 0x805120E4 */
pa4 = -1.10894694282396677476e-01, /* 0xBFBC6398, 0x3D3E28EC */
pa5 = 3.54783043256182359371e-02, /* 0x3FA22A36, 0x599795EB */
pa6 = -2.16637559486879084300e-03, /* 0xBF61BF38, 0x0A96073F */
qa1 = 1.06420880400844228286e-01, /* 0x3FBB3E66, 0x18EEE323 */
qa2 = 5.40397917702171048937e-01, /* 0x3FE14AF0, 0x92EB6F33 */
qa3 = 7.18286544141962662868e-02, /* 0x3FB2635C, 0xD99FE9A7 */
qa4 = 1.26171219808761642112e-01, /* 0x3FC02660, 0xE763351F */
qa5 = 1.36370839120290507362e-02, /* 0x3F8BEDC2, 0x6B51DD1C */
qa6 = 1.19844998467991074170e-02, /* 0x3F888B54, 0x5735151D */
/*
* Coefficients for approximation to erfc in [1.25,1/0.35]
*/
ra0 = -9.86494403484714822705e-03, /* 0xBF843412, 0x600D6435 */
ra1 = -6.93858572707181764372e-01, /* 0xBFE63416, 0xE4BA7360 */
ra2 = -1.05586262253232909814e+01, /* 0xC0251E04, 0x41B0E726 */
ra3 = -6.23753324503260060396e+01, /* 0xC04F300A, 0xE4CBA38D */
ra4 = -1.62396669462573470355e+02, /* 0xC0644CB1, 0x84282266 */
ra5 = -1.84605092906711035994e+02, /* 0xC067135C, 0xEBCCABB2 */
ra6 = -8.12874355063065934246e+01, /* 0xC0545265, 0x57E4D2F2 */
ra7 = -9.81432934416914548592e+00, /* 0xC023A0EF, 0xC69AC25C */
sa1 = 1.96512716674392571292e+01, /* 0x4033A6B9, 0xBD707687 */
sa2 = 1.37657754143519042600e+02, /* 0x4061350C, 0x526AE721 */
sa3 = 4.34565877475229228821e+02, /* 0x407B290D, 0xD58A1A71 */
sa4 = 6.45387271733267880336e+02, /* 0x40842B19, 0x21EC2868 */
sa5 = 4.29008140027567833386e+02, /* 0x407AD021, 0x57700314 */
sa6 = 1.08635005541779435134e+02, /* 0x405B28A3, 0xEE48AE2C */
sa7 = 6.57024977031928170135e+00, /* 0x401A47EF, 0x8E484A93 */
sa8 = -6.04244152148580987438e-02, /* 0xBFAEEFF2, 0xEE749A62 */
/*
* Coefficients for approximation to erfc in [1/.35,28]
*/
rb0 = -9.86494292470009928597e-03, /* 0xBF843412, 0x39E86F4A */
rb1 = -7.99283237680523006574e-01, /* 0xBFE993BA, 0x70C285DE */
rb2 = -1.77579549177547519889e+01, /* 0xC031C209, 0x555F995A */
rb3 = -1.60636384855821916062e+02, /* 0xC064145D, 0x43C5ED98 */
rb4 = -6.37566443368389627722e+02, /* 0xC083EC88, 0x1375F228 */
rb5 = -1.02509513161107724954e+03, /* 0xC0900461, 0x6A2E5992 */
rb6 = -4.83519191608651397019e+02, /* 0xC07E384E, 0x9BDC383F */
sb1 = 3.03380607434824582924e+01, /* 0x403E568B, 0x261D5190 */
sb2 = 3.25792512996573918826e+02, /* 0x40745CAE, 0x221B9F0A */
sb3 = 1.53672958608443695994e+03, /* 0x409802EB, 0x189D5118 */
sb4 = 3.19985821950859553908e+03, /* 0x40A8FFB7, 0x688C246A */
sb5 = 2.55305040643316442583e+03, /* 0x40A3F219, 0xCEDF3BE6 */
sb6 = 4.74528541206955367215e+02, /* 0x407DA874, 0xE79FE763 */
sb7 = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */
static double erfc1(double x)
{
double_t s,P,Q;
s = fabs(x) - 1;
P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
Q = 1+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
return 1 - erx - P/Q;
}
static double erfc2(uint32_t ix, double x)
{
double_t s,R,S;
double z;
if (ix < 0x3ff40000) /* |x| < 1.25 */
return erfc1(x);
x = fabs(x);
s = 1/(x*x);
if (ix < 0x4006db6d) { /* |x| < 1/.35 ~ 2.85714 */
R = ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(
ra5+s*(ra6+s*ra7))))));
S = 1.0+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(
sa5+s*(sa6+s*(sa7+s*sa8)))))));
} else { /* |x| > 1/.35 */
R = rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(
rb5+s*rb6)))));
S = 1.0+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(
sb5+s*(sb6+s*sb7))))));
}
z = x;
SET_LOW_WORD(z,0);
return exp(-z*z-0.5625)*exp((z-x)*(z+x)+R/S)/x;
}
double erf(double x)
{
double r,s,z,y;
uint32_t ix;
int sign;
GET_HIGH_WORD(ix, x);
sign = ix>>31;
ix &= 0x7fffffff;
if (ix >= 0x7ff00000) {
/* erf(nan)=nan, erf(+-inf)=+-1 */
return 1-2*sign + 1/x;
}
if (ix < 0x3feb0000) { /* |x| < 0.84375 */
if (ix < 0x3e300000) { /* |x| < 2**-28 */
/* avoid underflow */
return 0.125*(8*x + efx8*x);
}
z = x*x;
r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
s = 1.0+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
y = r/s;
return x + x*y;
}
if (ix < 0x40180000) /* 0.84375 <= |x| < 6 */
y = 1 - erfc2(ix,x);
else
y = 1 - 0x1p-1022;
return sign ? -y : y;
}
double erfc(double x)
{
double r,s,z,y;
uint32_t ix;
int sign;
GET_HIGH_WORD(ix, x);
sign = ix>>31;
ix &= 0x7fffffff;
if (ix >= 0x7ff00000) {
/* erfc(nan)=nan, erfc(+-inf)=0,2 */
return 2*sign + 1/x;
}
if (ix < 0x3feb0000) { /* |x| < 0.84375 */
if (ix < 0x3c700000) /* |x| < 2**-56 */
return 1.0 - x;
z = x*x;
r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
s = 1.0+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
y = r/s;
if (sign || ix < 0x3fd00000) { /* x < 1/4 */
return 1.0 - (x+x*y);
}
return 0.5 - (x - 0.5 + x*y);
}
if (ix < 0x403c0000) { /* 0.84375 <= |x| < 28 */
return sign ? 2 - erfc2(ix,x) : erfc2(ix,x);
}
return sign ? 2 - 0x1p-1022 : 0x1p-1022*0x1p-1022;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/erf.c | C | apache-2.0 | 10,346 |
/* origin: FreeBSD /usr/src/lib/msun/src/e_exp.c */
/*
* ====================================================
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* exp(x)
* Returns the exponential of x.
*
* Method
* 1. Argument reduction:
* Reduce x to an r so that |r| <= 0.5*ln2 ~ 0.34658.
* Given x, find r and integer k such that
*
* x = k*ln2 + r, |r| <= 0.5*ln2.
*
* Here r will be represented as r = hi-lo for better
* accuracy.
*
* 2. Approximation of exp(r) by a special rational function on
* the interval [0,0.34658]:
* Write
* R(r**2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r**4/360 + ...
* We use a special Remez algorithm on [0,0.34658] to generate
* a polynomial of degree 5 to approximate R. The maximum error
* of this polynomial approximation is bounded by 2**-59. In
* other words,
* R(z) ~ 2.0 + P1*z + P2*z**2 + P3*z**3 + P4*z**4 + P5*z**5
* (where z=r*r, and the values of P1 to P5 are listed below)
* and
* | 5 | -59
* | 2.0+P1*z+...+P5*z - R(z) | <= 2
* | |
* The computation of exp(r) thus becomes
* 2*r
* exp(r) = 1 + ----------
* R(r) - r
* r*c(r)
* = 1 + r + ----------- (for better accuracy)
* 2 - c(r)
* where
* 2 4 10
* c(r) = r - (P1*r + P2*r + ... + P5*r ).
*
* 3. Scale back to obtain exp(x):
* From step 1, we have
* exp(x) = 2^k * exp(r)
*
* Special cases:
* exp(INF) is INF, exp(NaN) is NaN;
* exp(-INF) is 0, and
* for finite argument, only exp(0)=1 is exact.
*
* Accuracy:
* according to an error analysis, the error is always less than
* 1 ulp (unit in the last place).
*
* Misc. info.
* For IEEE double
* if x > 709.782712893383973096 then exp(x) overflows
* if x < -745.133219101941108420 then exp(x) underflows
*/
#include "libm.h"
static const double
half[2] = {0.5,-0.5},
ln2hi = 6.93147180369123816490e-01, /* 0x3fe62e42, 0xfee00000 */
ln2lo = 1.90821492927058770002e-10, /* 0x3dea39ef, 0x35793c76 */
invln2 = 1.44269504088896338700e+00, /* 0x3ff71547, 0x652b82fe */
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 */
double exp(double x)
{
double_t hi, lo, c, xx, y;
int k, sign;
uint32_t hx;
GET_HIGH_WORD(hx, x);
sign = hx>>31;
hx &= 0x7fffffff; /* high word of |x| */
/* special cases */
if (hx >= 0x4086232b) { /* if |x| >= 708.39... */
if (isnan(x))
return x;
if (x > 709.782712893383973096) {
/* overflow if x!=inf */
x *= 0x1p1023;
return x;
}
if (x < -708.39641853226410622) {
/* underflow if x!=-inf */
FORCE_EVAL((float)(-0x1p-149/x));
if (x < -745.13321910194110842)
return 0;
}
}
/* argument reduction */
if (hx > 0x3fd62e42) { /* if |x| > 0.5 ln2 */
if (hx >= 0x3ff0a2b2) /* if |x| >= 1.5 ln2 */
k = (int)(invln2*x + half[sign]);
else
k = 1 - sign - sign;
hi = x - k*ln2hi; /* k*ln2hi is exact here */
lo = k*ln2lo;
x = hi - lo;
} else if (hx > 0x3e300000) { /* if |x| > 2**-28 */
k = 0;
hi = x;
lo = 0;
} else {
/* inexact if x!=0 */
FORCE_EVAL(0x1p1023 + x);
return 1 + x;
}
/* x is now in primary range */
xx = x*x;
c = x - xx*(P1+xx*(P2+xx*(P3+xx*(P4+xx*P5))));
y = 1 + (x*c/(2-c) - lo + hi);
if (k == 0)
return y;
return scalbn(y, k);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/exp.c | C | apache-2.0 | 4,118 |
/* origin: FreeBSD /usr/src/lib/msun/src/s_expm1.c */
/*
* ====================================================
* 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.
* ====================================================
*/
/* expm1(x)
* Returns exp(x)-1, the exponential of x minus 1.
*
* Method
* 1. Argument reduction:
* Given x, find r and integer k such that
*
* x = k*ln2 + r, |r| <= 0.5*ln2 ~ 0.34658
*
* Here a correction term c will be computed to compensate
* the error in r when rounded to a floating-point number.
*
* 2. Approximating expm1(r) by a special rational function on
* the interval [0,0.34658]:
* Since
* r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 - r^4/360 + ...
* we define R1(r*r) by
* r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 * R1(r*r)
* That is,
* R1(r**2) = 6/r *((exp(r)+1)/(exp(r)-1) - 2/r)
* = 6/r * ( 1 + 2.0*(1/(exp(r)-1) - 1/r))
* = 1 - r^2/60 + r^4/2520 - r^6/100800 + ...
* We use a special Remez algorithm on [0,0.347] to generate
* a polynomial of degree 5 in r*r to approximate R1. The
* maximum error of this polynomial approximation is bounded
* by 2**-61. In other words,
* R1(z) ~ 1.0 + Q1*z + Q2*z**2 + Q3*z**3 + Q4*z**4 + Q5*z**5
* where Q1 = -1.6666666666666567384E-2,
* Q2 = 3.9682539681370365873E-4,
* Q3 = -9.9206344733435987357E-6,
* Q4 = 2.5051361420808517002E-7,
* Q5 = -6.2843505682382617102E-9;
* z = r*r,
* with error bounded by
* | 5 | -61
* | 1.0+Q1*z+...+Q5*z - R1(z) | <= 2
* | |
*
* expm1(r) = exp(r)-1 is then computed by the following
* specific way which minimize the accumulation rounding error:
* 2 3
* r r [ 3 - (R1 + R1*r/2) ]
* expm1(r) = r + --- + --- * [--------------------]
* 2 2 [ 6 - r*(3 - R1*r/2) ]
*
* To compensate the error in the argument reduction, we use
* expm1(r+c) = expm1(r) + c + expm1(r)*c
* ~ expm1(r) + c + r*c
* Thus c+r*c will be added in as the correction terms for
* expm1(r+c). Now rearrange the term to avoid optimization
* screw up:
* ( 2 2 )
* ({ ( r [ R1 - (3 - R1*r/2) ] ) } r )
* expm1(r+c)~r - ({r*(--- * [--------------------]-c)-c} - --- )
* ({ ( 2 [ 6 - r*(3 - R1*r/2) ] ) } 2 )
* ( )
*
* = r - E
* 3. Scale back to obtain expm1(x):
* From step 1, we have
* expm1(x) = either 2^k*[expm1(r)+1] - 1
* = or 2^k*[expm1(r) + (1-2^-k)]
* 4. Implementation notes:
* (A). To save one multiplication, we scale the coefficient Qi
* to Qi*2^i, and replace z by (x^2)/2.
* (B). To achieve maximum accuracy, we compute expm1(x) by
* (i) if x < -56*ln2, return -1.0, (raise inexact if x!=inf)
* (ii) if k=0, return r-E
* (iii) if k=-1, return 0.5*(r-E)-0.5
* (iv) if k=1 if r < -0.25, return 2*((r+0.5)- E)
* else return 1.0+2.0*(r-E);
* (v) if (k<-2||k>56) return 2^k(1-(E-r)) - 1 (or exp(x)-1)
* (vi) if k <= 20, return 2^k((1-2^-k)-(E-r)), else
* (vii) return 2^k(1-((E+2^-k)-r))
*
* Special cases:
* expm1(INF) is INF, expm1(NaN) is NaN;
* expm1(-INF) is -1, and
* for finite argument, only expm1(0)=0 is exact.
*
* Accuracy:
* according to an error analysis, the error is always less than
* 1 ulp (unit in the last place).
*
* Misc. info.
* For IEEE double
* if x > 7.09782712893383973096e+02 then expm1(x) overflow
*
* 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 "libm.h"
static const double
o_threshold = 7.09782712893383973096e+02, /* 0x40862E42, 0xFEFA39EF */
ln2_hi = 6.93147180369123816490e-01, /* 0x3fe62e42, 0xfee00000 */
ln2_lo = 1.90821492927058770002e-10, /* 0x3dea39ef, 0x35793c76 */
invln2 = 1.44269504088896338700e+00, /* 0x3ff71547, 0x652b82fe */
/* Scaled Q's: Qn_here = 2**n * Qn_above, for R(2*z) where z = hxs = x*x/2: */
Q1 = -3.33333333333331316428e-02, /* BFA11111 111110F4 */
Q2 = 1.58730158725481460165e-03, /* 3F5A01A0 19FE5585 */
Q3 = -7.93650757867487942473e-05, /* BF14CE19 9EAADBB7 */
Q4 = 4.00821782732936239552e-06, /* 3ED0CFCA 86E65239 */
Q5 = -2.01099218183624371326e-07; /* BE8AFDB7 6E09C32D */
double expm1(double x)
{
double_t y,hi,lo,c,t,e,hxs,hfx,r1,twopk;
union {double f; uint64_t i;} u = {x};
uint32_t hx = u.i>>32 & 0x7fffffff;
int k, sign = u.i>>63;
/* filter out huge and non-finite argument */
if (hx >= 0x4043687A) { /* if |x|>=56*ln2 */
if (isnan(x))
return x;
if (sign)
return -1;
if (x > o_threshold) {
x *= 0x1p1023;
return x;
}
}
/* argument reduction */
if (hx > 0x3fd62e42) { /* if |x| > 0.5 ln2 */
if (hx < 0x3FF0A2B2) { /* and |x| < 1.5 ln2 */
if (!sign) {
hi = x - ln2_hi;
lo = ln2_lo;
k = 1;
} else {
hi = x + ln2_hi;
lo = -ln2_lo;
k = -1;
}
} else {
k = invln2*x + (sign ? -0.5 : 0.5);
t = k;
hi = x - t*ln2_hi; /* t*ln2_hi is exact here */
lo = t*ln2_lo;
}
x = hi-lo;
c = (hi-x)-lo;
} else if (hx < 0x3c900000) { /* |x| < 2**-54, return x */
if (hx < 0x00100000)
FORCE_EVAL((float)x);
return x;
} else
k = 0;
/* x is now in primary range */
hfx = 0.5*x;
hxs = x*hfx;
r1 = 1.0+hxs*(Q1+hxs*(Q2+hxs*(Q3+hxs*(Q4+hxs*Q5))));
t = 3.0-r1*hfx;
e = hxs*((r1-t)/(6.0 - x*t));
if (k == 0) /* c is 0 */
return x - (x*e-hxs);
e = x*(e-c) - c;
e -= hxs;
/* exp(x) ~ 2^k (x_reduced - e + 1) */
if (k == -1)
return 0.5*(x-e) - 0.5;
if (k == 1) {
if (x < -0.25)
return -2.0*(e-(x+0.5));
return 1.0+2.0*(x-e);
}
u.i = (uint64_t)(0x3ff + k)<<52; /* 2^k */
twopk = u.f;
if (k < 0 || k > 56) { /* suffice to return exp(x)-1 */
y = x - e + 1.0;
if (k == 1024)
y = y*2.0*0x1p1023;
else
y = y*twopk;
return y - 1.0;
}
u.i = (uint64_t)(0x3ff - k)<<52; /* 2^-k */
if (k < 20)
y = (x-e+(1-u.f))*twopk;
else
y = (x-(e+u.f)+1)*twopk;
return y;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/expm1.c | C | apache-2.0 | 6,964 |
#include "libm.h"
#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1
#define EPS DBL_EPSILON
#elif FLT_EVAL_METHOD==2
#define EPS LDBL_EPSILON
#endif
static const double_t toint = 1/EPS;
double floor(double x)
{
union {double f; uint64_t i;} u = {x};
int e = u.i >> 52 & 0x7ff;
double_t y;
if (e >= 0x3ff+52 || x == 0)
return x;
/* y = int(x) - x, where int(x) is an integer neighbor of x */
if (u.i >> 63)
y = x - toint + toint - x;
else
y = x + toint - toint - x;
/* special case because of non-nearest rounding modes */
if (e <= 0x3ff-1) {
FORCE_EVAL(y);
return u.i >> 63 ? -1 : 0;
}
if (y > 0)
return x + y - 1;
return x + y;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/floor.c | C | apache-2.0 | 653 |
#include <math.h>
#include <stdint.h>
double fmod(double x, double y)
{
union {double f; uint64_t i;} ux = {x}, uy = {y};
int ex = ux.i>>52 & 0x7ff;
int ey = uy.i>>52 & 0x7ff;
int sx = ux.i>>63;
uint64_t i;
/* in the followings uxi should be ux.i, but then gcc wrongly adds */
/* float load/store to inner loops ruining performance and code size */
uint64_t uxi = ux.i;
if (uy.i<<1 == 0 || isnan(y) || ex == 0x7ff)
return (x*y)/(x*y);
if (uxi<<1 <= uy.i<<1) {
if (uxi<<1 == uy.i<<1)
return 0*x;
return x;
}
/* normalize x and y */
if (!ex) {
for (i = uxi<<12; i>>63 == 0; ex--, i <<= 1);
uxi <<= -ex + 1;
} else {
uxi &= -1ULL >> 12;
uxi |= 1ULL << 52;
}
if (!ey) {
for (i = uy.i<<12; i>>63 == 0; ey--, i <<= 1);
uy.i <<= -ey + 1;
} else {
uy.i &= -1ULL >> 12;
uy.i |= 1ULL << 52;
}
/* x mod y */
for (; ex > ey; ex--) {
i = uxi - uy.i;
if (i >> 63 == 0) {
if (i == 0)
return 0*x;
uxi = i;
}
uxi <<= 1;
}
i = uxi - uy.i;
if (i >> 63 == 0) {
if (i == 0)
return 0*x;
uxi = i;
}
for (; uxi>>52 == 0; uxi <<= 1, ex--);
/* scale result */
if (ex > 0) {
uxi -= 1ULL << 52;
uxi |= (uint64_t)ex << 52;
} else {
uxi >>= -ex + 1;
}
uxi |= (uint64_t)sx << 63;
ux.i = uxi;
return ux.f;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/fmod.c | C | apache-2.0 | 1,270 |
#include <math.h>
#include <stdint.h>
double frexp(double x, int *e)
{
union { double d; uint64_t i; } y = { x };
int ee = y.i>>52 & 0x7ff;
if (!ee) {
if (x) {
x = frexp(x*0x1p64, e);
*e -= 64;
} else *e = 0;
return x;
} else if (ee == 0x7ff) {
return x;
}
*e = ee - 0x3fe;
y.i &= 0x800fffffffffffffull;
y.i |= 0x3fe0000000000000ull;
return y.d;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/frexp.c | C | apache-2.0 | 374 |
#include <math.h>
double ldexp(double x, int n)
{
return scalbn(x, n);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/ldexp.c | C | apache-2.0 | 75 |
#include <math.h>
double __lgamma_r(double, int*);
double lgamma(double x) {
int sign;
return __lgamma_r(x, &sign);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/lgamma.c | C | apache-2.0 | 128 |
// Portions of this file are extracted from musl-1.1.16 src/internal/libm.h
/* origin: FreeBSD /usr/src/lib/msun/src/math_private.h */
/*
* ====================================================
* 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.
* ====================================================
*/
#include <stdint.h>
#include <math.h>
#define FLT_EVAL_METHOD 0
#define FORCE_EVAL(x) do { \
if (sizeof(x) == sizeof(float)) { \
volatile float __x; \
__x = (x); \
(void)__x; \
} else if (sizeof(x) == sizeof(double)) { \
volatile double __x; \
__x = (x); \
(void)__x; \
} else { \
volatile long double __x; \
__x = (x); \
(void)__x; \
} \
} while(0)
/* Get two 32 bit ints from a double. */
#define EXTRACT_WORDS(hi,lo,d) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
(hi) = __u.i >> 32; \
(lo) = (uint32_t)__u.i; \
} while (0)
/* Get the more significant 32 bit int from a double. */
#define GET_HIGH_WORD(hi,d) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
(hi) = __u.i >> 32; \
} while (0)
/* Get the less significant 32 bit int from a double. */
#define GET_LOW_WORD(lo,d) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
(lo) = (uint32_t)__u.i; \
} while (0)
/* Set a double from two 32 bit ints. */
#define INSERT_WORDS(d,hi,lo) \
do { \
union {double f; uint64_t i;} __u; \
__u.i = ((uint64_t)(hi)<<32) | (uint32_t)(lo); \
(d) = __u.f; \
} while (0)
/* Set the more significant 32 bits of a double from an int. */
#define SET_HIGH_WORD(d,hi) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
__u.i &= 0xffffffff; \
__u.i |= (uint64_t)(hi) << 32; \
(d) = __u.f; \
} while (0)
/* Set the less significant 32 bits of a double from an int. */
#define SET_LOW_WORD(d,lo) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
__u.i &= 0xffffffff00000000ull; \
__u.i |= (uint32_t)(lo); \
(d) = __u.f; \
} while (0)
#define DBL_EPSILON 2.22044604925031308085e-16
int __rem_pio2(double, double*);
int __rem_pio2_large(double*, double*, int, int, int);
double __sin(double, double, int);
double __cos(double, double);
double __tan(double, double, int);
double __expo2(double);
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/libm.h | C | apache-2.0 | 3,699 |
/* origin: FreeBSD /usr/src/lib/msun/src/e_log.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* log(x)
* Return the logarithm of x
*
* Method :
* 1. Argument Reduction: find k and f such that
* x = 2^k * (1+f),
* where sqrt(2)/2 < 1+f < sqrt(2) .
*
* 2. Approximation of log(1+f).
* Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s)
* = 2s + 2/3 s**3 + 2/5 s**5 + .....,
* = 2s + s*R
* We use a special Remez algorithm on [0,0.1716] to generate
* a polynomial of degree 14 to approximate R The maximum error
* of this polynomial approximation is bounded by 2**-58.45. In
* other words,
* 2 4 6 8 10 12 14
* R(z) ~ Lg1*s +Lg2*s +Lg3*s +Lg4*s +Lg5*s +Lg6*s +Lg7*s
* (the values of Lg1 to Lg7 are listed in the program)
* and
* | 2 14 | -58.45
* | Lg1*s +...+Lg7*s - R(z) | <= 2
* | |
* Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2.
* In order to guarantee error in log below 1ulp, we compute log
* by
* log(1+f) = f - s*(f - R) (if f is not too large)
* log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy)
*
* 3. Finally, log(x) = k*ln2 + log(1+f).
* = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo)))
* Here ln2 is split into two floating point number:
* ln2_hi + ln2_lo,
* where n*ln2_hi is always exact for |n| < 2000.
*
* Special cases:
* log(x) is NaN with signal if x < 0 (including -INF) ;
* log(+INF) is +INF; log(0) is -INF with signal;
* log(NaN) is that NaN with no signal.
*
* Accuracy:
* according to an error analysis, the error is always less than
* 1 ulp (unit in the last place).
*
* 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.h>
#include <stdint.h>
static const double
ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */
ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */
Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */
Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */
Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */
Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */
Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */
Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */
Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */
double log(double x)
{
union {double f; uint64_t i;} u = {x};
double_t hfsq,f,s,z,R,w,t1,t2,dk;
uint32_t hx;
int k;
hx = u.i>>32;
k = 0;
if (hx < 0x00100000 || hx>>31) {
if (u.i<<1 == 0)
return -1/(x*x); /* log(+-0)=-inf */
if (hx>>31)
return (x-x)/0.0; /* log(-#) = NaN */
/* subnormal number, scale x up */
k -= 54;
x *= 0x1p54;
u.f = x;
hx = u.i>>32;
} else if (hx >= 0x7ff00000) {
return x;
} else if (hx == 0x3ff00000 && u.i<<32 == 0)
return 0;
/* reduce x into [sqrt(2)/2, sqrt(2)] */
hx += 0x3ff00000 - 0x3fe6a09e;
k += (int)(hx>>20) - 0x3ff;
hx = (hx&0x000fffff) + 0x3fe6a09e;
u.i = (uint64_t)hx<<32 | (u.i&0xffffffff);
x = u.f;
f = x - 1.0;
hfsq = 0.5*f*f;
s = f/(2.0+f);
z = s*s;
w = z*z;
t1 = w*(Lg2+w*(Lg4+w*Lg6));
t2 = z*(Lg1+w*(Lg3+w*(Lg5+w*Lg7)));
R = t2 + t1;
dk = k;
return s*(hfsq+R) + dk*ln2_lo - hfsq + f + dk*ln2_hi;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/log.c | C | apache-2.0 | 4,026 |
#include <math.h>
static const double _M_LN10 = 2.302585092994046;
double log10(double x) {
return log(x) / (double)_M_LN10;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/log10.c | C | apache-2.0 | 133 |
/* origin: FreeBSD /usr/src/lib/msun/src/s_log1p.c */
/*
* ====================================================
* 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.
* ====================================================
*/
/* double log1p(double x)
* Return the natural logarithm of 1+x.
*
* Method :
* 1. Argument Reduction: find k and f such that
* 1+x = 2^k * (1+f),
* where sqrt(2)/2 < 1+f < sqrt(2) .
*
* Note. If k=0, then f=x is exact. However, if k!=0, then f
* may not be representable exactly. In that case, a correction
* term is need. Let u=1+x rounded. Let c = (1+x)-u, then
* log(1+x) - log(u) ~ c/u. Thus, we proceed to compute log(u),
* and add back the correction term c/u.
* (Note: when x > 2**53, one can simply return log(x))
*
* 2. Approximation of log(1+f): See log.c
*
* 3. Finally, log1p(x) = k*ln2 + log(1+f) + c/u. See log.c
*
* Special cases:
* log1p(x) is NaN with signal if x < -1 (including -INF) ;
* log1p(+INF) is +INF; log1p(-1) is -INF with signal;
* log1p(NaN) is that NaN with no signal.
*
* Accuracy:
* according to an error analysis, the error is always less than
* 1 ulp (unit in the last place).
*
* 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.
*
* Note: Assuming log() return accurate answer, the following
* algorithm can be used to compute log1p(x) to within a few ULP:
*
* u = 1+x;
* if(u==1.0) return x ; else
* return log(u)*(x/(u-1.0));
*
* See HP-15C Advanced Functions Handbook, p.193.
*/
#include "libm.h"
static const double
ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */
ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */
Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */
Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */
Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */
Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */
Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */
Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */
Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */
double log1p(double x)
{
union {double f; uint64_t i;} u = {x};
double_t hfsq,f,c,s,z,R,w,t1,t2,dk;
uint32_t hx,hu;
int k;
hx = u.i>>32;
k = 1;
if (hx < 0x3fda827a || hx>>31) { /* 1+x < sqrt(2)+ */
if (hx >= 0xbff00000) { /* x <= -1.0 */
if (x == -1)
return x/0.0; /* log1p(-1) = -inf */
return (x-x)/0.0; /* log1p(x<-1) = NaN */
}
if (hx<<1 < 0x3ca00000<<1) { /* |x| < 2**-53 */
/* underflow if subnormal */
if ((hx&0x7ff00000) == 0)
FORCE_EVAL((float)x);
return x;
}
if (hx <= 0xbfd2bec4) { /* sqrt(2)/2- <= 1+x < sqrt(2)+ */
k = 0;
c = 0;
f = x;
}
} else if (hx >= 0x7ff00000)
return x;
if (k) {
u.f = 1 + x;
hu = u.i>>32;
hu += 0x3ff00000 - 0x3fe6a09e;
k = (int)(hu>>20) - 0x3ff;
/* correction term ~ log(1+x)-log(u), avoid underflow in c/u */
if (k < 54) {
c = k >= 2 ? 1-(u.f-x) : x-(u.f-1);
c /= u.f;
} else
c = 0;
/* reduce u into [sqrt(2)/2, sqrt(2)] */
hu = (hu&0x000fffff) + 0x3fe6a09e;
u.i = (uint64_t)hu<<32 | (u.i&0xffffffff);
f = u.f - 1;
}
hfsq = 0.5*f*f;
s = f/(2.0+f);
z = s*s;
w = z*z;
t1 = w*(Lg2+w*(Lg4+w*Lg6));
t2 = z*(Lg1+w*(Lg3+w*(Lg5+w*Lg7)));
R = t2 + t1;
dk = k;
return s*(hfsq+R) + (dk*ln2_lo+c) - hfsq + f + dk*ln2_hi;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/log1p.c | C | apache-2.0 | 3,865 |
#include "libm.h"
double modf(double x, double *iptr)
{
union {double f; uint64_t i;} u = {x};
uint64_t mask;
int e = (int)(u.i>>52 & 0x7ff) - 0x3ff;
/* no fractional part */
if (e >= 52) {
*iptr = x;
if (e == 0x400 && u.i<<12 != 0) /* nan */
return x;
u.i &= 1ULL<<63;
return u.f;
}
/* no integral part*/
if (e < 0) {
u.i &= 1ULL<<63;
*iptr = u.f;
return x;
}
mask = -1ULL>>12>>e;
if ((u.i & mask) == 0) {
*iptr = x;
u.i &= 1ULL<<63;
return u.f;
}
u.i &= ~mask;
*iptr = u.f;
return x - u.f;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/modf.c | C | apache-2.0 | 536 |
#include <math.h>
/* nearbyint is the same as rint, but it must not raise the inexact exception */
double nearbyint(double x)
{
#ifdef FE_INEXACT
#pragma STDC FENV_ACCESS ON
int e;
e = fetestexcept(FE_INEXACT);
#endif
x = rint(x);
#ifdef FE_INEXACT
if (!e)
feclearexcept(FE_INEXACT);
#endif
return x;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/nearbyint.c | C | apache-2.0 | 314 |
/* origin: FreeBSD /usr/src/lib/msun/src/e_pow.c */
/*
* ====================================================
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* 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. 1 ** (anything) is 1
* 3. (anything except 1) ** 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 1
* 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, raise divbyzero
* 13. -0 ** (-anything except 0, NAN, odd integer) is +INF, raise divbyzero
* 14. -0 ** (+odd integer) is -0
* 15. -0 ** (-odd integer) is -INF, raise divbyzero
* 16. +INF ** (+anything except 0,NAN) is +INF
* 17. +INF ** (-anything except 0,NAN) is +0
* 18. -INF ** (+odd integer) is -INF
* 19. -INF ** (anything) = -0 ** (-anything), (anything except odd integer)
* 20. (anything) ** 1 is (anything)
* 21. (anything) ** -1 is 1/(anything)
* 22. (-anything) ** (integer) is (-1)**(integer)*(+anything**integer)
* 23. (-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 "libm.h"
static const double
bp[] = {1.0, 1.5,},
dp_h[] = { 0.0, 5.84962487220764160156e-01,}, /* 0x3FE2B803, 0x40000000 */
dp_l[] = { 0.0, 1.35003920212974897128e-08,}, /* 0x3E4CFDEB, 0x43CFD006 */
two53 = 9007199254740992.0, /* 0x43400000, 0x00000000 */
huge = 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-017, /* -(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*/
double pow(double x, double y)
{
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;
uint32_t lx,ly;
EXTRACT_WORDS(hx, lx, x);
EXTRACT_WORDS(hy, ly, y);
ix = hx & 0x7fffffff;
iy = hy & 0x7fffffff;
/* x**0 = 1, even if x is NaN */
if ((iy|ly) == 0)
return 1.0;
/* 1**y = 1, even if y is NaN */
if (hx == 0x3ff00000 && lx == 0)
return 1.0;
/* NaN if either arg is NaN */
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) {
uint32_t j = ly>>(52-k);
if ((j<<(52-k)) == ly)
yisint = 2 - (j&1);
} else if (ly == 0) {
uint32_t 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) /* (-1)**+-inf is 1 */
return 1.0;
else if (ix >= 0x3ff00000) /* (|x|>1)**+-inf = inf,0 */
return hy >= 0 ? y : 0.0;
else /* (|x|<1)**+-inf = 0,inf */
return hy >= 0 ? 0.0 : -y;
}
if (iy == 0x3ff00000) { /* y is +-1 */
if (hy >= 0)
return x;
y = 1/x;
#if FLT_EVAL_METHOD!=0
{
union {double f; uint64_t i;} u = {y};
uint64_t i = u.i & -1ULL/2;
if (i>>52 == 0 && (i&(i-1)))
FORCE_EVAL((float)y);
}
#endif
return y;
}
if (hy == 0x40000000) /* y is 2 */
return x*x;
if (hy == 0x3fe00000) { /* y is 0.5 */
if (hx >= 0) /* x >= +0 */
return sqrt(x);
}
}
ax = fabs(x);
/* special value of x */
if (lx == 0) {
if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) { /* x is +-0,+-inf,+-1 */
z = ax;
if (hy < 0) /* z = (1/|x|) */
z = 1.0/z;
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;
}
}
s = 1.0; /* sign of result */
if (hx < 0) {
if (yisint == 0) /* (x<0)**(non-int) is NaN */
return (x-x)/(x-x);
if (yisint == 1) /* (x<0)**(odd int) */
s = -1.0;
}
/* |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*huge : tiny*tiny;
if (ix >= 0x3ff00000)
return hy > 0 ? huge*huge : tiny*tiny;
}
/* over/underflow if x is not close to one */
if (ix < 0x3fefffff)
return hy < 0 ? s*huge*huge : s*tiny*tiny;
if (ix > 0x3ff00000)
return hy > 0 ? s*huge*huge : s*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 = ax - 1.0; /* 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 ss,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) /* |x|<sqrt(3/2) */
k = 0;
else if (j < 0xBB67A) /* |x|<sqrt(3) */
k = 1;
else {
k = 0;
n += 1;
ix -= 0x00100000;
}
SET_HIGH_WORD(ax, ix);
/* compute ss = 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 = 1.0/(ax+bp[k]);
ss = u*v;
s_h = ss;
SET_LOW_WORD(s_h, 0);
/* t_h=ax+bp[k] High */
t_h = 0.0;
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 = ss*ss;
r = s2*s2*(L1+s2*(L2+s2*(L3+s2*(L4+s2*(L5+s2*L6)))));
r += s_l*(s_h+ss);
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 = ss*(1+...) */
u = s_h*t_h;
v = s_l*t_h + t_l*ss;
/* 2/(3log2)*(ss+...) */
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) = (ss+..)*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);
}
/* 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*huge; /* overflow */
if (p_l + ovt > z - p_h)
return s*huge*huge; /* overflow */
} else if ((j&0x7fffffff) >= 0x4090cc00) { /* z <= -1075 */ // FIXME: instead of abs(j) use unsigned j
if (((j-0xc090cc00)|i) != 0) /* z < -1075 */
return s*tiny*tiny; /* underflow */
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 = 0.0;
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-2.0) - (w + z*w);
z = 1.0 - (r-z);
GET_HIGH_WORD(j, z);
j += n<<20;
if ((j>>20) <= 0) /* subnormal output */
z = scalbn(z,n);
else
SET_HIGH_WORD(z, j);
return s*z;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/pow.c | C | apache-2.0 | 10,383 |
#include <float.h>
#include <math.h>
#include <stdint.h>
#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1
#define EPS DBL_EPSILON
#elif FLT_EVAL_METHOD==2
#define EPS LDBL_EPSILON
#endif
static const double_t toint = 1/EPS;
double rint(double x)
{
union {double f; uint64_t i;} u = {x};
int e = u.i>>52 & 0x7ff;
int s = u.i>>63;
double_t y;
if (e >= 0x3ff+52)
return x;
if (s)
y = x - toint + toint;
else
y = x + toint - toint;
if (y == 0)
return s ? -0.0 : 0;
return y;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/rint.c | C | apache-2.0 | 489 |
#include "libm.h"
#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1
#define EPS DBL_EPSILON
#elif FLT_EVAL_METHOD==2
#define EPS LDBL_EPSILON
#endif
static const double_t toint = 1/EPS;
double round(double x)
{
union {double f; uint64_t i;} u = {x};
int e = u.i >> 52 & 0x7ff;
double_t y;
if (e >= 0x3ff+52)
return x;
if (u.i >> 63)
x = -x;
if (e < 0x3ff-1) {
/* raise inexact if x!=0 */
FORCE_EVAL(x + toint);
return 0*u.f;
}
y = x + toint - toint - x;
if (y > 0.5)
y = y + x - 1;
else if (y <= -0.5)
y = y + x + 1;
else
y = y + x;
if (u.i >> 63)
y = -y;
return y;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/round.c | C | apache-2.0 | 597 |
#include <math.h>
#include <stdint.h>
double scalbn(double x, int n)
{
union {double f; uint64_t i;} u;
double_t y = x;
if (n > 1023) {
y *= 0x1p1023;
n -= 1023;
if (n > 1023) {
y *= 0x1p1023;
n -= 1023;
if (n > 1023)
n = 1023;
}
} else if (n < -1022) {
/* make sure final n < -53 to avoid double
rounding in the subnormal range */
y *= 0x1p-1022 * 0x1p53;
n += 1022 - 53;
if (n < -1022) {
y *= 0x1p-1022 * 0x1p53;
n += 1022 - 53;
if (n < -1022)
n = -1022;
}
}
u.i = (uint64_t)(0x3ff+n)<<52;
x = y * u.f;
return x;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/scalbn.c | C | apache-2.0 | 576 |
/* origin: FreeBSD /usr/src/lib/msun/src/s_sin.c */
/*
* ====================================================
* 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.
* ====================================================
*/
/* sin(x)
* Return sine function of x.
*
* kernel function:
* __sin ... sine function on [-pi/4,pi/4]
* __cos ... cose function on [-pi/4,pi/4]
* __rem_pio2 ... argument reduction routine
*
* Method.
* Let S,C and T denote the sin, cos and tan respectively on
* [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2
* in [-pi/4 , +pi/4], and let n = k mod 4.
* We have
*
* n sin(x) cos(x) tan(x)
* ----------------------------------------------------------
* 0 S C T
* 1 C -S -1/T
* 2 -S -C T
* 3 -C S -1/T
* ----------------------------------------------------------
*
* Special cases:
* Let trig be any of sin, cos, or tan.
* trig(+-INF) is NaN, with signals;
* trig(NaN) is that NaN;
*
* Accuracy:
* TRIG(x) returns trig(x) nearly rounded
*/
#include "libm.h"
double sin(double x)
{
double y[2];
uint32_t ix;
unsigned n;
/* High word of x. */
GET_HIGH_WORD(ix, x);
ix &= 0x7fffffff;
/* |x| ~< pi/4 */
if (ix <= 0x3fe921fb) {
if (ix < 0x3e500000) { /* |x| < 2**-26 */
/* raise inexact if x != 0 and underflow if subnormal*/
FORCE_EVAL(ix < 0x00100000 ? x/0x1p120f : x+0x1p120f);
return x;
}
return __sin(x, 0.0, 0);
}
/* sin(Inf or NaN) is NaN */
if (ix >= 0x7ff00000)
return x - x;
/* argument reduction needed */
n = __rem_pio2(x, y);
switch (n&3) {
case 0: return __sin(y[0], y[1], 1);
case 1: return __cos(y[0], y[1]);
case 2: return -__sin(y[0], y[1], 1);
default:
return -__cos(y[0], y[1]);
}
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/sin.c | C | apache-2.0 | 2,192 |
#include "libm.h"
/* sinh(x) = (exp(x) - 1/exp(x))/2
* = (exp(x)-1 + (exp(x)-1)/exp(x))/2
* = x + x^3/6 + o(x^5)
*/
double sinh(double x)
{
union {double f; uint64_t i;} u = {.f = x};
uint32_t w;
double t, h, absx;
h = 0.5;
if (u.i >> 63)
h = -h;
/* |x| */
u.i &= (uint64_t)-1/2;
absx = u.f;
w = u.i >> 32;
/* |x| < log(DBL_MAX) */
if (w < 0x40862e42) {
t = expm1(absx);
if (w < 0x3ff00000) {
if (w < 0x3ff00000 - (26<<20))
/* note: inexact and underflow are raised by expm1 */
/* note: this branch avoids spurious underflow */
return x;
return h*(2*t - t*t/(t+1));
}
/* note: |x|>log(0x1p26)+eps could be just h*exp(x) */
return h*(t + t/(t+1));
}
/* |x| > log(DBL_MAX) or nan */
/* note: the result is stored to handle overflow */
t = 2*h*__expo2(absx);
return t;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/sinh.c | C | apache-2.0 | 837 |
/* origin: FreeBSD /usr/src/lib/msun/src/e_sqrt.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* sqrt(x)
* Return correctly rounded sqrt.
* ------------------------------------------
* | Use the hardware sqrt if you have one |
* ------------------------------------------
* Method:
* Bit by bit method using integer arithmetic. (Slow, but portable)
* 1. Normalization
* Scale x to y in [1,4) with even powers of 2:
* find an integer k such that 1 <= (y=x*2^(2k)) < 4, then
* sqrt(x) = 2^k * sqrt(y)
* 2. Bit by bit computation
* Let q = sqrt(y) truncated to i bit after binary point (q = 1),
* i 0
* i+1 2
* s = 2*q , and y = 2 * ( y - q ). (1)
* i i i i
*
* To compute q from q , one checks whether
* i+1 i
*
* -(i+1) 2
* (q + 2 ) <= y. (2)
* i
* -(i+1)
* If (2) is false, then q = q ; otherwise q = q + 2 .
* i+1 i i+1 i
*
* With some algebric manipulation, it is not difficult to see
* that (2) is equivalent to
* -(i+1)
* s + 2 <= y (3)
* i i
*
* The advantage of (3) is that s and y can be computed by
* i i
* the following recurrence formula:
* if (3) is false
*
* s = s , y = y ; (4)
* i+1 i i+1 i
*
* otherwise,
* -i -(i+1)
* s = s + 2 , y = y - s - 2 (5)
* i+1 i i+1 i i
*
* One may easily use induction to prove (4) and (5).
* Note. Since the left hand side of (3) contain only i+2 bits,
* it does not necessary to do a full (53-bit) comparison
* in (3).
* 3. Final rounding
* After generating the 53 bits result, we compute one more bit.
* Together with the remainder, we can decide whether the
* result is exact, bigger than 1/2ulp, or less than 1/2ulp
* (it will never equal to 1/2ulp).
* The rounding mode can be detected by checking whether
* huge + tiny is equal to huge, and whether huge - tiny is
* equal to huge for some floating point number "huge" and "tiny".
*
* Special cases:
* sqrt(+-0) = +-0 ... exact
* sqrt(inf) = inf
* sqrt(-ve) = NaN ... with invalid signal
* sqrt(NaN) = NaN ... with invalid signal for signaling NaN
*/
#include "libm.h"
static const double tiny = 1.0e-300;
double sqrt(double x)
{
double z;
int32_t sign = (int)0x80000000;
int32_t ix0,s0,q,m,t,i;
uint32_t r,t1,s1,ix1,q1;
EXTRACT_WORDS(ix0, ix1, x);
/* take care of Inf and NaN */
if ((ix0&0x7ff00000) == 0x7ff00000) {
return x*x + x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf, sqrt(-inf)=sNaN */
}
/* take care of zero */
if (ix0 <= 0) {
if (((ix0&~sign)|ix1) == 0)
return x; /* sqrt(+-0) = +-0 */
if (ix0 < 0)
return (x-x)/(x-x); /* sqrt(-ve) = sNaN */
}
/* normalize x */
m = ix0>>20;
if (m == 0) { /* subnormal x */
while (ix0 == 0) {
m -= 21;
ix0 |= (ix1>>11);
ix1 <<= 21;
}
for (i=0; (ix0&0x00100000) == 0; i++)
ix0<<=1;
m -= i - 1;
ix0 |= ix1>>(32-i);
ix1 <<= i;
}
m -= 1023; /* unbias exponent */
ix0 = (ix0&0x000fffff)|0x00100000;
if (m & 1) { /* odd m, double x to make it even */
ix0 += ix0 + ((ix1&sign)>>31);
ix1 += ix1;
}
m >>= 1; /* m = [m/2] */
/* generate sqrt(x) bit by bit */
ix0 += ix0 + ((ix1&sign)>>31);
ix1 += ix1;
q = q1 = s0 = s1 = 0; /* [q,q1] = sqrt(x) */
r = 0x00200000; /* r = moving bit from right to left */
while (r != 0) {
t = s0 + r;
if (t <= ix0) {
s0 = t + r;
ix0 -= t;
q += r;
}
ix0 += ix0 + ((ix1&sign)>>31);
ix1 += ix1;
r >>= 1;
}
r = sign;
while (r != 0) {
t1 = s1 + r;
t = s0;
if (t < ix0 || (t == ix0 && t1 <= ix1)) {
s1 = t1 + r;
if ((t1&sign) == sign && (s1&sign) == 0)
s0++;
ix0 -= t;
if (ix1 < t1)
ix0--;
ix1 -= t1;
q1 += r;
}
ix0 += ix0 + ((ix1&sign)>>31);
ix1 += ix1;
r >>= 1;
}
/* use floating add to find out rounding direction */
if ((ix0|ix1) != 0) {
z = 1.0 - tiny; /* raise inexact flag */
if (z >= 1.0) {
z = 1.0 + tiny;
if (q1 == (uint32_t)0xffffffff) {
q1 = 0;
q++;
} else if (z > 1.0) {
if (q1 == (uint32_t)0xfffffffe)
q++;
q1 += 2;
} else
q1 += q1 & 1;
}
}
ix0 = (q>>1) + 0x3fe00000;
ix1 = q1>>1;
if (q&1)
ix1 |= sign;
ix0 += m << 20;
INSERT_WORDS(z, ix0, ix1);
return z;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/sqrt.c | C | apache-2.0 | 5,425 |
/* origin: FreeBSD /usr/src/lib/msun/src/s_tan.c */
/*
* ====================================================
* 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.
* ====================================================
*/
/* tan(x)
* Return tangent function of x.
*
* kernel function:
* __tan ... tangent function on [-pi/4,pi/4]
* __rem_pio2 ... argument reduction routine
*
* Method.
* Let S,C and T denote the sin, cos and tan respectively on
* [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2
* in [-pi/4 , +pi/4], and let n = k mod 4.
* We have
*
* n sin(x) cos(x) tan(x)
* ----------------------------------------------------------
* 0 S C T
* 1 C -S -1/T
* 2 -S -C T
* 3 -C S -1/T
* ----------------------------------------------------------
*
* Special cases:
* Let trig be any of sin, cos, or tan.
* trig(+-INF) is NaN, with signals;
* trig(NaN) is that NaN;
*
* Accuracy:
* TRIG(x) returns trig(x) nearly rounded
*/
#include "libm.h"
double tan(double x)
{
double y[2];
uint32_t ix;
unsigned n;
GET_HIGH_WORD(ix, x);
ix &= 0x7fffffff;
/* |x| ~< pi/4 */
if (ix <= 0x3fe921fb) {
if (ix < 0x3e400000) { /* |x| < 2**-27 */
/* raise inexact if x!=0 and underflow if subnormal */
FORCE_EVAL(ix < 0x00100000 ? x/0x1p120f : x+0x1p120f);
return x;
}
return __tan(x, 0.0, 0);
}
/* tan(Inf or NaN) is NaN */
if (ix >= 0x7ff00000)
return x - x;
/* argument reduction */
n = __rem_pio2(x, y);
return __tan(y[0], y[1], n&1);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/tan.c | C | apache-2.0 | 1,965 |
#include <math.h>
double tanh(double x) {
int sign = 0;
if (x < 0) {
sign = 1;
x = -x;
}
x = expm1(-2 * x);
x = x / (x + 2);
return sign ? x : -x;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/tanh.c | C | apache-2.0 | 190 |
/*
"A Precision Approximation of the Gamma Function" - Cornelius Lanczos (1964)
"Lanczos Implementation of the Gamma Function" - Paul Godfrey (2001)
"An Analysis of the Lanczos Gamma Approximation" - Glendon Ralph Pugh (2004)
approximation method:
(x - 0.5) S(x)
Gamma(x) = (x + g - 0.5) * ----------------
exp(x + g - 0.5)
with
a1 a2 a3 aN
S(x) ~= [ a0 + ----- + ----- + ----- + ... + ----- ]
x + 1 x + 2 x + 3 x + N
with a0, a1, a2, a3,.. aN constants which depend on g.
for x < 0 the following reflection formula is used:
Gamma(x)*Gamma(-x) = -pi/(x sin(pi x))
most ideas and constants are from boost and python
*/
#include "libm.h"
static const double pi = 3.141592653589793238462643383279502884;
/* sin(pi x) with x > 0x1p-100, if sin(pi*x)==0 the sign is arbitrary */
static double sinpi(double x)
{
int n;
/* argument reduction: x = |x| mod 2 */
/* spurious inexact when x is odd int */
x = x * 0.5;
x = 2 * (x - floor(x));
/* reduce x into [-.25,.25] */
n = 4 * x;
n = (n+1)/2;
x -= n * 0.5;
x *= pi;
switch (n) {
default: /* case 4 */
case 0:
return __sin(x, 0, 0);
case 1:
return __cos(x, 0);
case 2:
return __sin(-x, 0, 0);
case 3:
return -__cos(x, 0);
}
}
#define N 12
//static const double g = 6.024680040776729583740234375;
static const double gmhalf = 5.524680040776729583740234375;
static const double Snum[N+1] = {
23531376880.410759688572007674451636754734846804940,
42919803642.649098768957899047001988850926355848959,
35711959237.355668049440185451547166705960488635843,
17921034426.037209699919755754458931112671403265390,
6039542586.3520280050642916443072979210699388420708,
1439720407.3117216736632230727949123939715485786772,
248874557.86205415651146038641322942321632125127801,
31426415.585400194380614231628318205362874684987640,
2876370.6289353724412254090516208496135991145378768,
186056.26539522349504029498971604569928220784236328,
8071.6720023658162106380029022722506138218516325024,
210.82427775157934587250973392071336271166969580291,
2.5066282746310002701649081771338373386264310793408,
};
static const double Sden[N+1] = {
0, 39916800, 120543840, 150917976, 105258076, 45995730, 13339535,
2637558, 357423, 32670, 1925, 66, 1,
};
/* n! for small integer n */
static const double fact[] = {
1, 1, 2, 6, 24, 120, 720, 5040.0, 40320.0, 362880.0, 3628800.0, 39916800.0,
479001600.0, 6227020800.0, 87178291200.0, 1307674368000.0, 20922789888000.0,
355687428096000.0, 6402373705728000.0, 121645100408832000.0,
2432902008176640000.0, 51090942171709440000.0, 1124000727777607680000.0,
};
/* S(x) rational function for positive x */
static double S(double x)
{
double_t num = 0, den = 0;
int i;
/* to avoid overflow handle large x differently */
if (x < 8)
for (i = N; i >= 0; i--) {
num = num * x + Snum[i];
den = den * x + Sden[i];
}
else
for (i = 0; i <= N; i++) {
num = num / x + Snum[i];
den = den / x + Sden[i];
}
return num/den;
}
double tgamma(double x)
{
union {double f; uint64_t i;} u = {x};
double absx, y;
double_t dy, z, r;
uint32_t ix = u.i>>32 & 0x7fffffff;
int sign = u.i>>63;
/* special cases */
if (ix >= 0x7ff00000)
/* tgamma(nan)=nan, tgamma(inf)=inf, tgamma(-inf)=nan with invalid */
return x + INFINITY;
if (ix < (0x3ff-54)<<20)
/* |x| < 2^-54: tgamma(x) ~ 1/x, +-0 raises div-by-zero */
return 1/x;
/* integer arguments */
/* raise inexact when non-integer */
if (x == floor(x)) {
if (sign)
return 0/0.0;
if (x <= sizeof fact/sizeof *fact)
return fact[(int)x - 1];
}
/* x >= 172: tgamma(x)=inf with overflow */
/* x =< -184: tgamma(x)=+-0 with underflow */
if (ix >= 0x40670000) { /* |x| >= 184 */
if (sign) {
FORCE_EVAL((float)(0x1p-126/x));
if (floor(x) * 0.5 == floor(x * 0.5))
return 0;
return -0.0;
}
x *= 0x1p1023;
return x;
}
absx = sign ? -x : x;
/* handle the error of x + g - 0.5 */
y = absx + gmhalf;
if (absx > gmhalf) {
dy = y - absx;
dy -= gmhalf;
} else {
dy = y - gmhalf;
dy -= absx;
}
z = absx - 0.5;
r = S(absx) * exp(-y);
if (x < 0) {
/* reflection formula for negative x */
/* sinpi(absx) is not 0, integers are already handled */
r = -pi / (sinpi(absx) * absx * r);
dy = -dy;
z = -z;
}
r += dy * (gmhalf+0.5) * r / y;
z = pow(y, 0.5*z);
y = r * z * z;
return y;
}
#if 1
double __lgamma_r(double x, int *sign)
{
double r, absx;
*sign = 1;
/* special cases */
if (!isfinite(x))
/* lgamma(nan)=nan, lgamma(+-inf)=inf */
return x*x;
/* integer arguments */
if (x == floor(x) && x <= 2) {
/* n <= 0: lgamma(n)=inf with divbyzero */
/* n == 1,2: lgamma(n)=0 */
if (x <= 0)
return 1/0.0;
return 0;
}
absx = fabs(x);
/* lgamma(x) ~ -log(|x|) for tiny |x| */
if (absx < 0x1p-54) {
*sign = 1 - 2*!!signbit(x);
return -log(absx);
}
/* use tgamma for smaller |x| */
if (absx < 128) {
x = tgamma(x);
*sign = 1 - 2*!!signbit(x);
return log(fabs(x));
}
/* second term (log(S)-g) could be more precise here.. */
/* or with stirling: (|x|-0.5)*(log(|x|)-1) + poly(1/|x|) */
r = (absx-0.5)*(log(absx+gmhalf)-1) + (log(S(absx)) - (gmhalf+0.5));
if (x < 0) {
/* reflection formula for negative x */
x = sinpi(absx);
*sign = 2*!!signbit(x) - 1;
r = log(pi/(fabs(x)*absx)) - r;
}
return r;
}
//weak_alias(__lgamma_r, lgamma_r);
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/tgamma.c | C | apache-2.0 | 5,466 |
// an implementation of sqrt for Thumb using hardware double-precision VFP instructions
double sqrt(double x) {
double ret;
asm volatile (
"vsqrt.f64 %P0, %P1\n"
: "=w" (ret)
: "w" (x));
return ret;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/thumb_vfp_sqrt.c | C | apache-2.0 | 252 |
#include "libm.h"
double trunc(double x)
{
union {double f; uint64_t i;} u = {x};
int e = (int)(u.i >> 52 & 0x7ff) - 0x3ff + 12;
uint64_t m;
if (e >= 52 + 12)
return x;
if (e < 12)
e = 1;
m = -1ULL >> e;
if ((u.i & m) == 0)
return x;
FORCE_EVAL(x + 0x1p120f);
u.i &= ~m;
return u.f;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/libm_dbl/trunc.c | C | apache-2.0 | 303 |
/*
* The little filesystem
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "lfs1.h"
#include "lfs1_util.h"
#include <inttypes.h>
/// Caching block device operations ///
static int lfs1_cache_read(lfs1_t *lfs1, lfs1_cache_t *rcache,
const lfs1_cache_t *pcache, lfs1_block_t block,
lfs1_off_t off, void *buffer, lfs1_size_t size) {
uint8_t *data = buffer;
LFS1_ASSERT(block < lfs1->cfg->block_count);
while (size > 0) {
if (pcache && block == pcache->block && off >= pcache->off &&
off < pcache->off + lfs1->cfg->prog_size) {
// is already in pcache?
lfs1_size_t diff = lfs1_min(size,
lfs1->cfg->prog_size - (off-pcache->off));
memcpy(data, &pcache->buffer[off-pcache->off], diff);
data += diff;
off += diff;
size -= diff;
continue;
}
if (block == rcache->block && off >= rcache->off &&
off < rcache->off + lfs1->cfg->read_size) {
// is already in rcache?
lfs1_size_t diff = lfs1_min(size,
lfs1->cfg->read_size - (off-rcache->off));
memcpy(data, &rcache->buffer[off-rcache->off], diff);
data += diff;
off += diff;
size -= diff;
continue;
}
if (off % lfs1->cfg->read_size == 0 && size >= lfs1->cfg->read_size) {
// bypass cache?
lfs1_size_t diff = size - (size % lfs1->cfg->read_size);
int err = lfs1->cfg->read(lfs1->cfg, block, off, data, diff);
if (err) {
return err;
}
data += diff;
off += diff;
size -= diff;
continue;
}
// load to cache, first condition can no longer fail
rcache->block = block;
rcache->off = off - (off % lfs1->cfg->read_size);
int err = lfs1->cfg->read(lfs1->cfg, rcache->block,
rcache->off, rcache->buffer, lfs1->cfg->read_size);
if (err) {
return err;
}
}
return 0;
}
static int lfs1_cache_cmp(lfs1_t *lfs1, lfs1_cache_t *rcache,
const lfs1_cache_t *pcache, lfs1_block_t block,
lfs1_off_t off, const void *buffer, lfs1_size_t size) {
const uint8_t *data = buffer;
for (lfs1_off_t i = 0; i < size; i++) {
uint8_t c;
int err = lfs1_cache_read(lfs1, rcache, pcache,
block, off+i, &c, 1);
if (err) {
return err;
}
if (c != data[i]) {
return false;
}
}
return true;
}
static int lfs1_cache_crc(lfs1_t *lfs1, lfs1_cache_t *rcache,
const lfs1_cache_t *pcache, lfs1_block_t block,
lfs1_off_t off, lfs1_size_t size, uint32_t *crc) {
for (lfs1_off_t i = 0; i < size; i++) {
uint8_t c;
int err = lfs1_cache_read(lfs1, rcache, pcache,
block, off+i, &c, 1);
if (err) {
return err;
}
lfs1_crc(crc, &c, 1);
}
return 0;
}
static inline void lfs1_cache_drop(lfs1_t *lfs1, lfs1_cache_t *rcache) {
// do not zero, cheaper if cache is readonly or only going to be
// written with identical data (during relocates)
(void)lfs1;
rcache->block = 0xffffffff;
}
static inline void lfs1_cache_zero(lfs1_t *lfs1, lfs1_cache_t *pcache) {
// zero to avoid information leak
memset(pcache->buffer, 0xff, lfs1->cfg->prog_size);
pcache->block = 0xffffffff;
}
static int lfs1_cache_flush(lfs1_t *lfs1,
lfs1_cache_t *pcache, lfs1_cache_t *rcache) {
if (pcache->block != 0xffffffff) {
int err = lfs1->cfg->prog(lfs1->cfg, pcache->block,
pcache->off, pcache->buffer, lfs1->cfg->prog_size);
if (err) {
return err;
}
if (rcache) {
int res = lfs1_cache_cmp(lfs1, rcache, NULL, pcache->block,
pcache->off, pcache->buffer, lfs1->cfg->prog_size);
if (res < 0) {
return res;
}
if (!res) {
return LFS1_ERR_CORRUPT;
}
}
lfs1_cache_zero(lfs1, pcache);
}
return 0;
}
static int lfs1_cache_prog(lfs1_t *lfs1, lfs1_cache_t *pcache,
lfs1_cache_t *rcache, lfs1_block_t block,
lfs1_off_t off, const void *buffer, lfs1_size_t size) {
const uint8_t *data = buffer;
LFS1_ASSERT(block < lfs1->cfg->block_count);
while (size > 0) {
if (block == pcache->block && off >= pcache->off &&
off < pcache->off + lfs1->cfg->prog_size) {
// is already in pcache?
lfs1_size_t diff = lfs1_min(size,
lfs1->cfg->prog_size - (off-pcache->off));
memcpy(&pcache->buffer[off-pcache->off], data, diff);
data += diff;
off += diff;
size -= diff;
if (off % lfs1->cfg->prog_size == 0) {
// eagerly flush out pcache if we fill up
int err = lfs1_cache_flush(lfs1, pcache, rcache);
if (err) {
return err;
}
}
continue;
}
// pcache must have been flushed, either by programming and
// entire block or manually flushing the pcache
LFS1_ASSERT(pcache->block == 0xffffffff);
if (off % lfs1->cfg->prog_size == 0 &&
size >= lfs1->cfg->prog_size) {
// bypass pcache?
lfs1_size_t diff = size - (size % lfs1->cfg->prog_size);
int err = lfs1->cfg->prog(lfs1->cfg, block, off, data, diff);
if (err) {
return err;
}
if (rcache) {
int res = lfs1_cache_cmp(lfs1, rcache, NULL,
block, off, data, diff);
if (res < 0) {
return res;
}
if (!res) {
return LFS1_ERR_CORRUPT;
}
}
data += diff;
off += diff;
size -= diff;
continue;
}
// prepare pcache, first condition can no longer fail
pcache->block = block;
pcache->off = off - (off % lfs1->cfg->prog_size);
}
return 0;
}
/// General lfs1 block device operations ///
static int lfs1_bd_read(lfs1_t *lfs1, lfs1_block_t block,
lfs1_off_t off, void *buffer, lfs1_size_t size) {
// if we ever do more than writes to alternating pairs,
// this may need to consider pcache
return lfs1_cache_read(lfs1, &lfs1->rcache, NULL,
block, off, buffer, size);
}
static int lfs1_bd_prog(lfs1_t *lfs1, lfs1_block_t block,
lfs1_off_t off, const void *buffer, lfs1_size_t size) {
return lfs1_cache_prog(lfs1, &lfs1->pcache, NULL,
block, off, buffer, size);
}
static int lfs1_bd_cmp(lfs1_t *lfs1, lfs1_block_t block,
lfs1_off_t off, const void *buffer, lfs1_size_t size) {
return lfs1_cache_cmp(lfs1, &lfs1->rcache, NULL, block, off, buffer, size);
}
static int lfs1_bd_crc(lfs1_t *lfs1, lfs1_block_t block,
lfs1_off_t off, lfs1_size_t size, uint32_t *crc) {
return lfs1_cache_crc(lfs1, &lfs1->rcache, NULL, block, off, size, crc);
}
static int lfs1_bd_erase(lfs1_t *lfs1, lfs1_block_t block) {
return lfs1->cfg->erase(lfs1->cfg, block);
}
static int lfs1_bd_sync(lfs1_t *lfs1) {
lfs1_cache_drop(lfs1, &lfs1->rcache);
int err = lfs1_cache_flush(lfs1, &lfs1->pcache, NULL);
if (err) {
return err;
}
return lfs1->cfg->sync(lfs1->cfg);
}
/// Internal operations predeclared here ///
int lfs1_traverse(lfs1_t *lfs1, int (*cb)(void*, lfs1_block_t), void *data);
static int lfs1_pred(lfs1_t *lfs1, const lfs1_block_t dir[2], lfs1_dir_t *pdir);
static int lfs1_parent(lfs1_t *lfs1, const lfs1_block_t dir[2],
lfs1_dir_t *parent, lfs1_entry_t *entry);
static int lfs1_moved(lfs1_t *lfs1, const void *e);
static int lfs1_relocate(lfs1_t *lfs1,
const lfs1_block_t oldpair[2], const lfs1_block_t newpair[2]);
int lfs1_deorphan(lfs1_t *lfs1);
/// Block allocator ///
static int lfs1_alloc_lookahead(void *p, lfs1_block_t block) {
lfs1_t *lfs1 = p;
lfs1_block_t off = ((block - lfs1->free.off)
+ lfs1->cfg->block_count) % lfs1->cfg->block_count;
if (off < lfs1->free.size) {
lfs1->free.buffer[off / 32] |= 1U << (off % 32);
}
return 0;
}
static int lfs1_alloc(lfs1_t *lfs1, lfs1_block_t *block) {
while (true) {
while (lfs1->free.i != lfs1->free.size) {
lfs1_block_t off = lfs1->free.i;
lfs1->free.i += 1;
lfs1->free.ack -= 1;
if (!(lfs1->free.buffer[off / 32] & (1U << (off % 32)))) {
// found a free block
*block = (lfs1->free.off + off) % lfs1->cfg->block_count;
// eagerly find next off so an alloc ack can
// discredit old lookahead blocks
while (lfs1->free.i != lfs1->free.size &&
(lfs1->free.buffer[lfs1->free.i / 32]
& (1U << (lfs1->free.i % 32)))) {
lfs1->free.i += 1;
lfs1->free.ack -= 1;
}
return 0;
}
}
// check if we have looked at all blocks since last ack
if (lfs1->free.ack == 0) {
LFS1_WARN("No more free space %" PRIu32,
lfs1->free.i + lfs1->free.off);
return LFS1_ERR_NOSPC;
}
lfs1->free.off = (lfs1->free.off + lfs1->free.size)
% lfs1->cfg->block_count;
lfs1->free.size = lfs1_min(lfs1->cfg->lookahead, lfs1->free.ack);
lfs1->free.i = 0;
// find mask of free blocks from tree
memset(lfs1->free.buffer, 0, lfs1->cfg->lookahead/8);
int err = lfs1_traverse(lfs1, lfs1_alloc_lookahead, lfs1);
if (err) {
return err;
}
}
}
static void lfs1_alloc_ack(lfs1_t *lfs1) {
lfs1->free.ack = lfs1->cfg->block_count;
}
/// Endian swapping functions ///
static void lfs1_dir_fromle32(struct lfs1_disk_dir *d) {
d->rev = lfs1_fromle32(d->rev);
d->size = lfs1_fromle32(d->size);
d->tail[0] = lfs1_fromle32(d->tail[0]);
d->tail[1] = lfs1_fromle32(d->tail[1]);
}
static void lfs1_dir_tole32(struct lfs1_disk_dir *d) {
d->rev = lfs1_tole32(d->rev);
d->size = lfs1_tole32(d->size);
d->tail[0] = lfs1_tole32(d->tail[0]);
d->tail[1] = lfs1_tole32(d->tail[1]);
}
static void lfs1_entry_fromle32(struct lfs1_disk_entry *d) {
d->u.dir[0] = lfs1_fromle32(d->u.dir[0]);
d->u.dir[1] = lfs1_fromle32(d->u.dir[1]);
}
static void lfs1_entry_tole32(struct lfs1_disk_entry *d) {
d->u.dir[0] = lfs1_tole32(d->u.dir[0]);
d->u.dir[1] = lfs1_tole32(d->u.dir[1]);
}
static void lfs1_superblock_fromle32(struct lfs1_disk_superblock *d) {
d->root[0] = lfs1_fromle32(d->root[0]);
d->root[1] = lfs1_fromle32(d->root[1]);
d->block_size = lfs1_fromle32(d->block_size);
d->block_count = lfs1_fromle32(d->block_count);
d->version = lfs1_fromle32(d->version);
}
static void lfs1_superblock_tole32(struct lfs1_disk_superblock *d) {
d->root[0] = lfs1_tole32(d->root[0]);
d->root[1] = lfs1_tole32(d->root[1]);
d->block_size = lfs1_tole32(d->block_size);
d->block_count = lfs1_tole32(d->block_count);
d->version = lfs1_tole32(d->version);
}
/// Metadata pair and directory operations ///
static inline void lfs1_pairswap(lfs1_block_t pair[2]) {
lfs1_block_t t = pair[0];
pair[0] = pair[1];
pair[1] = t;
}
static inline bool lfs1_pairisnull(const lfs1_block_t pair[2]) {
return pair[0] == 0xffffffff || pair[1] == 0xffffffff;
}
static inline int lfs1_paircmp(
const lfs1_block_t paira[2],
const lfs1_block_t pairb[2]) {
return !(paira[0] == pairb[0] || paira[1] == pairb[1] ||
paira[0] == pairb[1] || paira[1] == pairb[0]);
}
static inline bool lfs1_pairsync(
const lfs1_block_t paira[2],
const lfs1_block_t pairb[2]) {
return (paira[0] == pairb[0] && paira[1] == pairb[1]) ||
(paira[0] == pairb[1] && paira[1] == pairb[0]);
}
static inline lfs1_size_t lfs1_entry_size(const lfs1_entry_t *entry) {
return 4 + entry->d.elen + entry->d.alen + entry->d.nlen;
}
static int lfs1_dir_alloc(lfs1_t *lfs1, lfs1_dir_t *dir) {
// allocate pair of dir blocks
for (int i = 0; i < 2; i++) {
int err = lfs1_alloc(lfs1, &dir->pair[i]);
if (err) {
return err;
}
}
// rather than clobbering one of the blocks we just pretend
// the revision may be valid
int err = lfs1_bd_read(lfs1, dir->pair[0], 0, &dir->d.rev, 4);
if (err && err != LFS1_ERR_CORRUPT) {
return err;
}
if (err != LFS1_ERR_CORRUPT) {
dir->d.rev = lfs1_fromle32(dir->d.rev);
}
// set defaults
dir->d.rev += 1;
dir->d.size = sizeof(dir->d)+4;
dir->d.tail[0] = 0xffffffff;
dir->d.tail[1] = 0xffffffff;
dir->off = sizeof(dir->d);
// don't write out yet, let caller take care of that
return 0;
}
static int lfs1_dir_fetch(lfs1_t *lfs1,
lfs1_dir_t *dir, const lfs1_block_t pair[2]) {
// copy out pair, otherwise may be aliasing dir
const lfs1_block_t tpair[2] = {pair[0], pair[1]};
bool valid = false;
// check both blocks for the most recent revision
for (int i = 0; i < 2; i++) {
struct lfs1_disk_dir test;
int err = lfs1_bd_read(lfs1, tpair[i], 0, &test, sizeof(test));
lfs1_dir_fromle32(&test);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
continue;
}
return err;
}
if (valid && lfs1_scmp(test.rev, dir->d.rev) < 0) {
continue;
}
if ((0x7fffffff & test.size) < sizeof(test)+4 ||
(0x7fffffff & test.size) > lfs1->cfg->block_size) {
continue;
}
uint32_t crc = 0xffffffff;
lfs1_dir_tole32(&test);
lfs1_crc(&crc, &test, sizeof(test));
lfs1_dir_fromle32(&test);
err = lfs1_bd_crc(lfs1, tpair[i], sizeof(test),
(0x7fffffff & test.size) - sizeof(test), &crc);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
continue;
}
return err;
}
if (crc != 0) {
continue;
}
valid = true;
// setup dir in case it's valid
dir->pair[0] = tpair[(i+0) % 2];
dir->pair[1] = tpair[(i+1) % 2];
dir->off = sizeof(dir->d);
dir->d = test;
}
if (!valid) {
LFS1_ERROR("Corrupted dir pair at %" PRIu32 " %" PRIu32 ,
tpair[0], tpair[1]);
return LFS1_ERR_CORRUPT;
}
return 0;
}
struct lfs1_region {
lfs1_off_t oldoff;
lfs1_size_t oldlen;
const void *newdata;
lfs1_size_t newlen;
};
static int lfs1_dir_commit(lfs1_t *lfs1, lfs1_dir_t *dir,
const struct lfs1_region *regions, int count) {
// increment revision count
dir->d.rev += 1;
// keep pairs in order such that pair[0] is most recent
lfs1_pairswap(dir->pair);
for (int i = 0; i < count; i++) {
dir->d.size += regions[i].newlen - regions[i].oldlen;
}
const lfs1_block_t oldpair[2] = {dir->pair[0], dir->pair[1]};
bool relocated = false;
while (true) {
if (true) {
int err = lfs1_bd_erase(lfs1, dir->pair[0]);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
uint32_t crc = 0xffffffff;
lfs1_dir_tole32(&dir->d);
lfs1_crc(&crc, &dir->d, sizeof(dir->d));
err = lfs1_bd_prog(lfs1, dir->pair[0], 0, &dir->d, sizeof(dir->d));
lfs1_dir_fromle32(&dir->d);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
int i = 0;
lfs1_off_t oldoff = sizeof(dir->d);
lfs1_off_t newoff = sizeof(dir->d);
while (newoff < (0x7fffffff & dir->d.size)-4) {
if (i < count && regions[i].oldoff == oldoff) {
lfs1_crc(&crc, regions[i].newdata, regions[i].newlen);
err = lfs1_bd_prog(lfs1, dir->pair[0],
newoff, regions[i].newdata, regions[i].newlen);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
oldoff += regions[i].oldlen;
newoff += regions[i].newlen;
i += 1;
} else {
uint8_t data;
err = lfs1_bd_read(lfs1, oldpair[1], oldoff, &data, 1);
if (err) {
return err;
}
lfs1_crc(&crc, &data, 1);
err = lfs1_bd_prog(lfs1, dir->pair[0], newoff, &data, 1);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
oldoff += 1;
newoff += 1;
}
}
crc = lfs1_tole32(crc);
err = lfs1_bd_prog(lfs1, dir->pair[0], newoff, &crc, 4);
crc = lfs1_fromle32(crc);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
err = lfs1_bd_sync(lfs1);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
// successful commit, check checksum to make sure
uint32_t ncrc = 0xffffffff;
err = lfs1_bd_crc(lfs1, dir->pair[0], 0,
(0x7fffffff & dir->d.size)-4, &ncrc);
if (err) {
return err;
}
if (ncrc != crc) {
goto relocate;
}
}
break;
relocate:
//commit was corrupted
LFS1_DEBUG("Bad block at %" PRIu32, dir->pair[0]);
// drop caches and prepare to relocate block
relocated = true;
lfs1_cache_drop(lfs1, &lfs1->pcache);
// can't relocate superblock, filesystem is now frozen
if (lfs1_paircmp(oldpair, (const lfs1_block_t[2]){0, 1}) == 0) {
LFS1_WARN("Superblock %" PRIu32 " has become unwritable",
oldpair[0]);
return LFS1_ERR_CORRUPT;
}
// relocate half of pair
int err = lfs1_alloc(lfs1, &dir->pair[0]);
if (err) {
return err;
}
}
if (relocated) {
// update references if we relocated
LFS1_DEBUG("Relocating %" PRIu32 " %" PRIu32 " to %" PRIu32 " %" PRIu32,
oldpair[0], oldpair[1], dir->pair[0], dir->pair[1]);
int err = lfs1_relocate(lfs1, oldpair, dir->pair);
if (err) {
return err;
}
}
// shift over any directories that are affected
for (lfs1_dir_t *d = lfs1->dirs; d; d = d->next) {
if (lfs1_paircmp(d->pair, dir->pair) == 0) {
d->pair[0] = dir->pair[0];
d->pair[1] = dir->pair[1];
}
}
return 0;
}
static int lfs1_dir_update(lfs1_t *lfs1, lfs1_dir_t *dir,
lfs1_entry_t *entry, const void *data) {
lfs1_entry_tole32(&entry->d);
int err = lfs1_dir_commit(lfs1, dir, (struct lfs1_region[]){
{entry->off, sizeof(entry->d), &entry->d, sizeof(entry->d)},
{entry->off+sizeof(entry->d), entry->d.nlen, data, entry->d.nlen}
}, data ? 2 : 1);
lfs1_entry_fromle32(&entry->d);
return err;
}
static int lfs1_dir_append(lfs1_t *lfs1, lfs1_dir_t *dir,
lfs1_entry_t *entry, const void *data) {
// check if we fit, if top bit is set we do not and move on
while (true) {
if (dir->d.size + lfs1_entry_size(entry) <= lfs1->cfg->block_size) {
entry->off = dir->d.size - 4;
lfs1_entry_tole32(&entry->d);
int err = lfs1_dir_commit(lfs1, dir, (struct lfs1_region[]){
{entry->off, 0, &entry->d, sizeof(entry->d)},
{entry->off, 0, data, entry->d.nlen}
}, 2);
lfs1_entry_fromle32(&entry->d);
return err;
}
// we need to allocate a new dir block
if (!(0x80000000 & dir->d.size)) {
lfs1_dir_t olddir = *dir;
int err = lfs1_dir_alloc(lfs1, dir);
if (err) {
return err;
}
dir->d.tail[0] = olddir.d.tail[0];
dir->d.tail[1] = olddir.d.tail[1];
entry->off = dir->d.size - 4;
lfs1_entry_tole32(&entry->d);
err = lfs1_dir_commit(lfs1, dir, (struct lfs1_region[]){
{entry->off, 0, &entry->d, sizeof(entry->d)},
{entry->off, 0, data, entry->d.nlen}
}, 2);
lfs1_entry_fromle32(&entry->d);
if (err) {
return err;
}
olddir.d.size |= 0x80000000;
olddir.d.tail[0] = dir->pair[0];
olddir.d.tail[1] = dir->pair[1];
return lfs1_dir_commit(lfs1, &olddir, NULL, 0);
}
int err = lfs1_dir_fetch(lfs1, dir, dir->d.tail);
if (err) {
return err;
}
}
}
static int lfs1_dir_remove(lfs1_t *lfs1, lfs1_dir_t *dir, lfs1_entry_t *entry) {
// check if we should just drop the directory block
if ((dir->d.size & 0x7fffffff) == sizeof(dir->d)+4
+ lfs1_entry_size(entry)) {
lfs1_dir_t pdir;
int res = lfs1_pred(lfs1, dir->pair, &pdir);
if (res < 0) {
return res;
}
if (pdir.d.size & 0x80000000) {
pdir.d.size &= dir->d.size | 0x7fffffff;
pdir.d.tail[0] = dir->d.tail[0];
pdir.d.tail[1] = dir->d.tail[1];
return lfs1_dir_commit(lfs1, &pdir, NULL, 0);
}
}
// shift out the entry
int err = lfs1_dir_commit(lfs1, dir, (struct lfs1_region[]){
{entry->off, lfs1_entry_size(entry), NULL, 0},
}, 1);
if (err) {
return err;
}
// shift over any files/directories that are affected
for (lfs1_file_t *f = lfs1->files; f; f = f->next) {
if (lfs1_paircmp(f->pair, dir->pair) == 0) {
if (f->poff == entry->off) {
f->pair[0] = 0xffffffff;
f->pair[1] = 0xffffffff;
} else if (f->poff > entry->off) {
f->poff -= lfs1_entry_size(entry);
}
}
}
for (lfs1_dir_t *d = lfs1->dirs; d; d = d->next) {
if (lfs1_paircmp(d->pair, dir->pair) == 0) {
if (d->off > entry->off) {
d->off -= lfs1_entry_size(entry);
d->pos -= lfs1_entry_size(entry);
}
}
}
return 0;
}
static int lfs1_dir_next(lfs1_t *lfs1, lfs1_dir_t *dir, lfs1_entry_t *entry) {
while (dir->off + sizeof(entry->d) > (0x7fffffff & dir->d.size)-4) {
if (!(0x80000000 & dir->d.size)) {
entry->off = dir->off;
return LFS1_ERR_NOENT;
}
int err = lfs1_dir_fetch(lfs1, dir, dir->d.tail);
if (err) {
return err;
}
dir->off = sizeof(dir->d);
dir->pos += sizeof(dir->d) + 4;
}
int err = lfs1_bd_read(lfs1, dir->pair[0], dir->off,
&entry->d, sizeof(entry->d));
lfs1_entry_fromle32(&entry->d);
if (err) {
return err;
}
entry->off = dir->off;
dir->off += lfs1_entry_size(entry);
dir->pos += lfs1_entry_size(entry);
return 0;
}
static int lfs1_dir_find(lfs1_t *lfs1, lfs1_dir_t *dir,
lfs1_entry_t *entry, const char **path) {
const char *pathname = *path;
size_t pathlen;
entry->d.type = LFS1_TYPE_DIR;
entry->d.elen = sizeof(entry->d) - 4;
entry->d.alen = 0;
entry->d.nlen = 0;
entry->d.u.dir[0] = lfs1->root[0];
entry->d.u.dir[1] = lfs1->root[1];
while (true) {
nextname:
// skip slashes
pathname += strspn(pathname, "/");
pathlen = strcspn(pathname, "/");
// skip '.' and root '..'
if ((pathlen == 1 && memcmp(pathname, ".", 1) == 0) ||
(pathlen == 2 && memcmp(pathname, "..", 2) == 0)) {
pathname += pathlen;
goto nextname;
}
// skip if matched by '..' in name
const char *suffix = pathname + pathlen;
size_t sufflen;
int depth = 1;
while (true) {
suffix += strspn(suffix, "/");
sufflen = strcspn(suffix, "/");
if (sufflen == 0) {
break;
}
if (sufflen == 2 && memcmp(suffix, "..", 2) == 0) {
depth -= 1;
if (depth == 0) {
pathname = suffix + sufflen;
goto nextname;
}
} else {
depth += 1;
}
suffix += sufflen;
}
// found path
if (pathname[0] == '\0') {
return 0;
}
// update what we've found
*path = pathname;
// continue on if we hit a directory
if (entry->d.type != LFS1_TYPE_DIR) {
return LFS1_ERR_NOTDIR;
}
int err = lfs1_dir_fetch(lfs1, dir, entry->d.u.dir);
if (err) {
return err;
}
// find entry matching name
while (true) {
err = lfs1_dir_next(lfs1, dir, entry);
if (err) {
return err;
}
if (((0x7f & entry->d.type) != LFS1_TYPE_REG &&
(0x7f & entry->d.type) != LFS1_TYPE_DIR) ||
entry->d.nlen != pathlen) {
continue;
}
int res = lfs1_bd_cmp(lfs1, dir->pair[0],
entry->off + 4+entry->d.elen+entry->d.alen,
pathname, pathlen);
if (res < 0) {
return res;
}
// found match
if (res) {
break;
}
}
// check that entry has not been moved
if (!lfs1->moving && entry->d.type & 0x80) {
int moved = lfs1_moved(lfs1, &entry->d.u);
if (moved < 0 || moved) {
return (moved < 0) ? moved : LFS1_ERR_NOENT;
}
entry->d.type &= ~0x80;
}
// to next name
pathname += pathlen;
}
}
/// Top level directory operations ///
int lfs1_mkdir(lfs1_t *lfs1, const char *path) {
// deorphan if we haven't yet, needed at most once after poweron
if (!lfs1->deorphaned) {
int err = lfs1_deorphan(lfs1);
if (err) {
return err;
}
}
// fetch parent directory
lfs1_dir_t cwd;
lfs1_entry_t entry;
int err = lfs1_dir_find(lfs1, &cwd, &entry, &path);
if (err != LFS1_ERR_NOENT || strchr(path, '/') != NULL) {
return err ? err : LFS1_ERR_EXIST;
}
// build up new directory
lfs1_alloc_ack(lfs1);
lfs1_dir_t dir;
err = lfs1_dir_alloc(lfs1, &dir);
if (err) {
return err;
}
dir.d.tail[0] = cwd.d.tail[0];
dir.d.tail[1] = cwd.d.tail[1];
err = lfs1_dir_commit(lfs1, &dir, NULL, 0);
if (err) {
return err;
}
entry.d.type = LFS1_TYPE_DIR;
entry.d.elen = sizeof(entry.d) - 4;
entry.d.alen = 0;
entry.d.nlen = strlen(path);
entry.d.u.dir[0] = dir.pair[0];
entry.d.u.dir[1] = dir.pair[1];
cwd.d.tail[0] = dir.pair[0];
cwd.d.tail[1] = dir.pair[1];
err = lfs1_dir_append(lfs1, &cwd, &entry, path);
if (err) {
return err;
}
lfs1_alloc_ack(lfs1);
return 0;
}
int lfs1_dir_open(lfs1_t *lfs1, lfs1_dir_t *dir, const char *path) {
dir->pair[0] = lfs1->root[0];
dir->pair[1] = lfs1->root[1];
lfs1_entry_t entry;
int err = lfs1_dir_find(lfs1, dir, &entry, &path);
if (err) {
return err;
} else if (entry.d.type != LFS1_TYPE_DIR) {
return LFS1_ERR_NOTDIR;
}
err = lfs1_dir_fetch(lfs1, dir, entry.d.u.dir);
if (err) {
return err;
}
// setup head dir
// special offset for '.' and '..'
dir->head[0] = dir->pair[0];
dir->head[1] = dir->pair[1];
dir->pos = sizeof(dir->d) - 2;
dir->off = sizeof(dir->d);
// add to list of directories
dir->next = lfs1->dirs;
lfs1->dirs = dir;
return 0;
}
int lfs1_dir_close(lfs1_t *lfs1, lfs1_dir_t *dir) {
// remove from list of directories
for (lfs1_dir_t **p = &lfs1->dirs; *p; p = &(*p)->next) {
if (*p == dir) {
*p = dir->next;
break;
}
}
return 0;
}
int lfs1_dir_read(lfs1_t *lfs1, lfs1_dir_t *dir, struct lfs1_info *info) {
memset(info, 0, sizeof(*info));
// special offset for '.' and '..'
if (dir->pos == sizeof(dir->d) - 2) {
info->type = LFS1_TYPE_DIR;
strcpy(info->name, ".");
dir->pos += 1;
return 1;
} else if (dir->pos == sizeof(dir->d) - 1) {
info->type = LFS1_TYPE_DIR;
strcpy(info->name, "..");
dir->pos += 1;
return 1;
}
lfs1_entry_t entry;
while (true) {
int err = lfs1_dir_next(lfs1, dir, &entry);
if (err) {
return (err == LFS1_ERR_NOENT) ? 0 : err;
}
if ((0x7f & entry.d.type) != LFS1_TYPE_REG &&
(0x7f & entry.d.type) != LFS1_TYPE_DIR) {
continue;
}
// check that entry has not been moved
if (entry.d.type & 0x80) {
int moved = lfs1_moved(lfs1, &entry.d.u);
if (moved < 0) {
return moved;
}
if (moved) {
continue;
}
entry.d.type &= ~0x80;
}
break;
}
info->type = entry.d.type;
if (info->type == LFS1_TYPE_REG) {
info->size = entry.d.u.file.size;
}
int err = lfs1_bd_read(lfs1, dir->pair[0],
entry.off + 4+entry.d.elen+entry.d.alen,
info->name, entry.d.nlen);
if (err) {
return err;
}
return 1;
}
int lfs1_dir_seek(lfs1_t *lfs1, lfs1_dir_t *dir, lfs1_off_t off) {
// simply walk from head dir
int err = lfs1_dir_rewind(lfs1, dir);
if (err) {
return err;
}
dir->pos = off;
while (off > (0x7fffffff & dir->d.size)) {
off -= 0x7fffffff & dir->d.size;
if (!(0x80000000 & dir->d.size)) {
return LFS1_ERR_INVAL;
}
err = lfs1_dir_fetch(lfs1, dir, dir->d.tail);
if (err) {
return err;
}
}
dir->off = off;
return 0;
}
lfs1_soff_t lfs1_dir_tell(lfs1_t *lfs1, lfs1_dir_t *dir) {
(void)lfs1;
return dir->pos;
}
int lfs1_dir_rewind(lfs1_t *lfs1, lfs1_dir_t *dir) {
// reload the head dir
int err = lfs1_dir_fetch(lfs1, dir, dir->head);
if (err) {
return err;
}
dir->pair[0] = dir->head[0];
dir->pair[1] = dir->head[1];
dir->pos = sizeof(dir->d) - 2;
dir->off = sizeof(dir->d);
return 0;
}
/// File index list operations ///
static int lfs1_ctz_index(lfs1_t *lfs1, lfs1_off_t *off) {
lfs1_off_t size = *off;
lfs1_off_t b = lfs1->cfg->block_size - 2*4;
lfs1_off_t i = size / b;
if (i == 0) {
return 0;
}
i = (size - 4*(lfs1_popc(i-1)+2)) / b;
*off = size - b*i - 4*lfs1_popc(i);
return i;
}
static int lfs1_ctz_find(lfs1_t *lfs1,
lfs1_cache_t *rcache, const lfs1_cache_t *pcache,
lfs1_block_t head, lfs1_size_t size,
lfs1_size_t pos, lfs1_block_t *block, lfs1_off_t *off) {
if (size == 0) {
*block = 0xffffffff;
*off = 0;
return 0;
}
lfs1_off_t current = lfs1_ctz_index(lfs1, &(lfs1_off_t){size-1});
lfs1_off_t target = lfs1_ctz_index(lfs1, &pos);
while (current > target) {
lfs1_size_t skip = lfs1_min(
lfs1_npw2(current-target+1) - 1,
lfs1_ctz(current));
int err = lfs1_cache_read(lfs1, rcache, pcache, head, 4*skip, &head, 4);
head = lfs1_fromle32(head);
if (err) {
return err;
}
LFS1_ASSERT(head >= 2 && head <= lfs1->cfg->block_count);
current -= 1 << skip;
}
*block = head;
*off = pos;
return 0;
}
static int lfs1_ctz_extend(lfs1_t *lfs1,
lfs1_cache_t *rcache, lfs1_cache_t *pcache,
lfs1_block_t head, lfs1_size_t size,
lfs1_block_t *block, lfs1_off_t *off) {
while (true) {
// go ahead and grab a block
lfs1_block_t nblock;
int err = lfs1_alloc(lfs1, &nblock);
if (err) {
return err;
}
LFS1_ASSERT(nblock >= 2 && nblock <= lfs1->cfg->block_count);
if (true) {
err = lfs1_bd_erase(lfs1, nblock);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
if (size == 0) {
*block = nblock;
*off = 0;
return 0;
}
size -= 1;
lfs1_off_t index = lfs1_ctz_index(lfs1, &size);
size += 1;
// just copy out the last block if it is incomplete
if (size != lfs1->cfg->block_size) {
for (lfs1_off_t i = 0; i < size; i++) {
uint8_t data;
err = lfs1_cache_read(lfs1, rcache, NULL,
head, i, &data, 1);
if (err) {
return err;
}
err = lfs1_cache_prog(lfs1, pcache, rcache,
nblock, i, &data, 1);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
}
*block = nblock;
*off = size;
return 0;
}
// append block
index += 1;
lfs1_size_t skips = lfs1_ctz(index) + 1;
for (lfs1_off_t i = 0; i < skips; i++) {
head = lfs1_tole32(head);
err = lfs1_cache_prog(lfs1, pcache, rcache,
nblock, 4*i, &head, 4);
head = lfs1_fromle32(head);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
if (i != skips-1) {
err = lfs1_cache_read(lfs1, rcache, NULL,
head, 4*i, &head, 4);
head = lfs1_fromle32(head);
if (err) {
return err;
}
}
LFS1_ASSERT(head >= 2 && head <= lfs1->cfg->block_count);
}
*block = nblock;
*off = 4*skips;
return 0;
}
relocate:
LFS1_DEBUG("Bad block at %" PRIu32, nblock);
// just clear cache and try a new block
lfs1_cache_drop(lfs1, &lfs1->pcache);
}
}
static int lfs1_ctz_traverse(lfs1_t *lfs1,
lfs1_cache_t *rcache, const lfs1_cache_t *pcache,
lfs1_block_t head, lfs1_size_t size,
int (*cb)(void*, lfs1_block_t), void *data) {
if (size == 0) {
return 0;
}
lfs1_off_t index = lfs1_ctz_index(lfs1, &(lfs1_off_t){size-1});
while (true) {
int err = cb(data, head);
if (err) {
return err;
}
if (index == 0) {
return 0;
}
lfs1_block_t heads[2];
int count = 2 - (index & 1);
err = lfs1_cache_read(lfs1, rcache, pcache, head, 0, &heads, count*4);
heads[0] = lfs1_fromle32(heads[0]);
heads[1] = lfs1_fromle32(heads[1]);
if (err) {
return err;
}
for (int i = 0; i < count-1; i++) {
err = cb(data, heads[i]);
if (err) {
return err;
}
}
head = heads[count-1];
index -= count;
}
}
/// Top level file operations ///
int lfs1_file_opencfg(lfs1_t *lfs1, lfs1_file_t *file,
const char *path, int flags,
const struct lfs1_file_config *cfg) {
// deorphan if we haven't yet, needed at most once after poweron
if ((flags & 3) != LFS1_O_RDONLY && !lfs1->deorphaned) {
int err = lfs1_deorphan(lfs1);
if (err) {
return err;
}
}
// allocate entry for file if it doesn't exist
lfs1_dir_t cwd;
lfs1_entry_t entry;
int err = lfs1_dir_find(lfs1, &cwd, &entry, &path);
if (err && (err != LFS1_ERR_NOENT || strchr(path, '/') != NULL)) {
return err;
}
if (err == LFS1_ERR_NOENT) {
if (!(flags & LFS1_O_CREAT)) {
return LFS1_ERR_NOENT;
}
// create entry to remember name
entry.d.type = LFS1_TYPE_REG;
entry.d.elen = sizeof(entry.d) - 4;
entry.d.alen = 0;
entry.d.nlen = strlen(path);
entry.d.u.file.head = 0xffffffff;
entry.d.u.file.size = 0;
err = lfs1_dir_append(lfs1, &cwd, &entry, path);
if (err) {
return err;
}
} else if (entry.d.type == LFS1_TYPE_DIR) {
return LFS1_ERR_ISDIR;
} else if (flags & LFS1_O_EXCL) {
return LFS1_ERR_EXIST;
}
// setup file struct
file->cfg = cfg;
file->pair[0] = cwd.pair[0];
file->pair[1] = cwd.pair[1];
file->poff = entry.off;
file->head = entry.d.u.file.head;
file->size = entry.d.u.file.size;
file->flags = flags;
file->pos = 0;
if (flags & LFS1_O_TRUNC) {
if (file->size != 0) {
file->flags |= LFS1_F_DIRTY;
}
file->head = 0xffffffff;
file->size = 0;
}
// allocate buffer if needed
file->cache.block = 0xffffffff;
if (file->cfg && file->cfg->buffer) {
file->cache.buffer = file->cfg->buffer;
} else if (lfs1->cfg->file_buffer) {
if (lfs1->files) {
// already in use
return LFS1_ERR_NOMEM;
}
file->cache.buffer = lfs1->cfg->file_buffer;
} else if ((file->flags & 3) == LFS1_O_RDONLY) {
file->cache.buffer = lfs1_malloc(lfs1->cfg->read_size);
if (!file->cache.buffer) {
return LFS1_ERR_NOMEM;
}
} else {
file->cache.buffer = lfs1_malloc(lfs1->cfg->prog_size);
if (!file->cache.buffer) {
return LFS1_ERR_NOMEM;
}
}
// zero to avoid information leak
lfs1_cache_drop(lfs1, &file->cache);
if ((file->flags & 3) != LFS1_O_RDONLY) {
lfs1_cache_zero(lfs1, &file->cache);
}
// add to list of files
file->next = lfs1->files;
lfs1->files = file;
return 0;
}
int lfs1_file_open(lfs1_t *lfs1, lfs1_file_t *file,
const char *path, int flags) {
return lfs1_file_opencfg(lfs1, file, path, flags, NULL);
}
int lfs1_file_close(lfs1_t *lfs1, lfs1_file_t *file) {
int err = lfs1_file_sync(lfs1, file);
// remove from list of files
for (lfs1_file_t **p = &lfs1->files; *p; p = &(*p)->next) {
if (*p == file) {
*p = file->next;
break;
}
}
// clean up memory
if (!(file->cfg && file->cfg->buffer) && !lfs1->cfg->file_buffer) {
lfs1_free(file->cache.buffer);
}
return err;
}
static int lfs1_file_relocate(lfs1_t *lfs1, lfs1_file_t *file) {
relocate:
LFS1_DEBUG("Bad block at %" PRIu32, file->block);
// just relocate what exists into new block
lfs1_block_t nblock;
int err = lfs1_alloc(lfs1, &nblock);
if (err) {
return err;
}
err = lfs1_bd_erase(lfs1, nblock);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
// either read from dirty cache or disk
for (lfs1_off_t i = 0; i < file->off; i++) {
uint8_t data;
err = lfs1_cache_read(lfs1, &lfs1->rcache, &file->cache,
file->block, i, &data, 1);
if (err) {
return err;
}
err = lfs1_cache_prog(lfs1, &lfs1->pcache, &lfs1->rcache,
nblock, i, &data, 1);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
}
// copy over new state of file
memcpy(file->cache.buffer, lfs1->pcache.buffer, lfs1->cfg->prog_size);
file->cache.block = lfs1->pcache.block;
file->cache.off = lfs1->pcache.off;
lfs1_cache_zero(lfs1, &lfs1->pcache);
file->block = nblock;
return 0;
}
static int lfs1_file_flush(lfs1_t *lfs1, lfs1_file_t *file) {
if (file->flags & LFS1_F_READING) {
// just drop read cache
lfs1_cache_drop(lfs1, &file->cache);
file->flags &= ~LFS1_F_READING;
}
if (file->flags & LFS1_F_WRITING) {
lfs1_off_t pos = file->pos;
// copy over anything after current branch
lfs1_file_t orig = {
.head = file->head,
.size = file->size,
.flags = LFS1_O_RDONLY,
.pos = file->pos,
.cache = lfs1->rcache,
};
lfs1_cache_drop(lfs1, &lfs1->rcache);
while (file->pos < file->size) {
// copy over a byte at a time, leave it up to caching
// to make this efficient
uint8_t data;
lfs1_ssize_t res = lfs1_file_read(lfs1, &orig, &data, 1);
if (res < 0) {
return res;
}
res = lfs1_file_write(lfs1, file, &data, 1);
if (res < 0) {
return res;
}
// keep our reference to the rcache in sync
if (lfs1->rcache.block != 0xffffffff) {
lfs1_cache_drop(lfs1, &orig.cache);
lfs1_cache_drop(lfs1, &lfs1->rcache);
}
}
// write out what we have
while (true) {
int err = lfs1_cache_flush(lfs1, &file->cache, &lfs1->rcache);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
return err;
}
break;
relocate:
err = lfs1_file_relocate(lfs1, file);
if (err) {
return err;
}
}
// actual file updates
file->head = file->block;
file->size = file->pos;
file->flags &= ~LFS1_F_WRITING;
file->flags |= LFS1_F_DIRTY;
file->pos = pos;
}
return 0;
}
int lfs1_file_sync(lfs1_t *lfs1, lfs1_file_t *file) {
int err = lfs1_file_flush(lfs1, file);
if (err) {
return err;
}
if ((file->flags & LFS1_F_DIRTY) &&
!(file->flags & LFS1_F_ERRED) &&
!lfs1_pairisnull(file->pair)) {
// update dir entry
lfs1_dir_t cwd;
err = lfs1_dir_fetch(lfs1, &cwd, file->pair);
if (err) {
return err;
}
lfs1_entry_t entry = {.off = file->poff};
err = lfs1_bd_read(lfs1, cwd.pair[0], entry.off,
&entry.d, sizeof(entry.d));
lfs1_entry_fromle32(&entry.d);
if (err) {
return err;
}
LFS1_ASSERT(entry.d.type == LFS1_TYPE_REG);
entry.d.u.file.head = file->head;
entry.d.u.file.size = file->size;
err = lfs1_dir_update(lfs1, &cwd, &entry, NULL);
if (err) {
return err;
}
file->flags &= ~LFS1_F_DIRTY;
}
return 0;
}
lfs1_ssize_t lfs1_file_read(lfs1_t *lfs1, lfs1_file_t *file,
void *buffer, lfs1_size_t size) {
uint8_t *data = buffer;
lfs1_size_t nsize = size;
if ((file->flags & 3) == LFS1_O_WRONLY) {
return LFS1_ERR_BADF;
}
if (file->flags & LFS1_F_WRITING) {
// flush out any writes
int err = lfs1_file_flush(lfs1, file);
if (err) {
return err;
}
}
if (file->pos >= file->size) {
// eof if past end
return 0;
}
size = lfs1_min(size, file->size - file->pos);
nsize = size;
while (nsize > 0) {
// check if we need a new block
if (!(file->flags & LFS1_F_READING) ||
file->off == lfs1->cfg->block_size) {
int err = lfs1_ctz_find(lfs1, &file->cache, NULL,
file->head, file->size,
file->pos, &file->block, &file->off);
if (err) {
return err;
}
file->flags |= LFS1_F_READING;
}
// read as much as we can in current block
lfs1_size_t diff = lfs1_min(nsize, lfs1->cfg->block_size - file->off);
int err = lfs1_cache_read(lfs1, &file->cache, NULL,
file->block, file->off, data, diff);
if (err) {
return err;
}
file->pos += diff;
file->off += diff;
data += diff;
nsize -= diff;
}
return size;
}
lfs1_ssize_t lfs1_file_write(lfs1_t *lfs1, lfs1_file_t *file,
const void *buffer, lfs1_size_t size) {
const uint8_t *data = buffer;
lfs1_size_t nsize = size;
if ((file->flags & 3) == LFS1_O_RDONLY) {
return LFS1_ERR_BADF;
}
if (file->flags & LFS1_F_READING) {
// drop any reads
int err = lfs1_file_flush(lfs1, file);
if (err) {
return err;
}
}
if ((file->flags & LFS1_O_APPEND) && file->pos < file->size) {
file->pos = file->size;
}
if (file->pos + size > LFS1_FILE_MAX) {
// larger than file limit?
return LFS1_ERR_FBIG;
}
if (!(file->flags & LFS1_F_WRITING) && file->pos > file->size) {
// fill with zeros
lfs1_off_t pos = file->pos;
file->pos = file->size;
while (file->pos < pos) {
lfs1_ssize_t res = lfs1_file_write(lfs1, file, &(uint8_t){0}, 1);
if (res < 0) {
return res;
}
}
}
while (nsize > 0) {
// check if we need a new block
if (!(file->flags & LFS1_F_WRITING) ||
file->off == lfs1->cfg->block_size) {
if (!(file->flags & LFS1_F_WRITING) && file->pos > 0) {
// find out which block we're extending from
int err = lfs1_ctz_find(lfs1, &file->cache, NULL,
file->head, file->size,
file->pos-1, &file->block, &file->off);
if (err) {
file->flags |= LFS1_F_ERRED;
return err;
}
// mark cache as dirty since we may have read data into it
lfs1_cache_zero(lfs1, &file->cache);
}
// extend file with new blocks
lfs1_alloc_ack(lfs1);
int err = lfs1_ctz_extend(lfs1, &lfs1->rcache, &file->cache,
file->block, file->pos,
&file->block, &file->off);
if (err) {
file->flags |= LFS1_F_ERRED;
return err;
}
file->flags |= LFS1_F_WRITING;
}
// program as much as we can in current block
lfs1_size_t diff = lfs1_min(nsize, lfs1->cfg->block_size - file->off);
while (true) {
int err = lfs1_cache_prog(lfs1, &file->cache, &lfs1->rcache,
file->block, file->off, data, diff);
if (err) {
if (err == LFS1_ERR_CORRUPT) {
goto relocate;
}
file->flags |= LFS1_F_ERRED;
return err;
}
break;
relocate:
err = lfs1_file_relocate(lfs1, file);
if (err) {
file->flags |= LFS1_F_ERRED;
return err;
}
}
file->pos += diff;
file->off += diff;
data += diff;
nsize -= diff;
lfs1_alloc_ack(lfs1);
}
file->flags &= ~LFS1_F_ERRED;
return size;
}
lfs1_soff_t lfs1_file_seek(lfs1_t *lfs1, lfs1_file_t *file,
lfs1_soff_t off, int whence) {
// write out everything beforehand, may be noop if rdonly
int err = lfs1_file_flush(lfs1, file);
if (err) {
return err;
}
// find new pos
lfs1_soff_t npos = file->pos;
if (whence == LFS1_SEEK_SET) {
npos = off;
} else if (whence == LFS1_SEEK_CUR) {
npos = file->pos + off;
} else if (whence == LFS1_SEEK_END) {
npos = file->size + off;
}
if (npos < 0 || npos > LFS1_FILE_MAX) {
// file position out of range
return LFS1_ERR_INVAL;
}
// update pos
file->pos = npos;
return npos;
}
int lfs1_file_truncate(lfs1_t *lfs1, lfs1_file_t *file, lfs1_off_t size) {
if ((file->flags & 3) == LFS1_O_RDONLY) {
return LFS1_ERR_BADF;
}
lfs1_off_t oldsize = lfs1_file_size(lfs1, file);
if (size < oldsize) {
// need to flush since directly changing metadata
int err = lfs1_file_flush(lfs1, file);
if (err) {
return err;
}
// lookup new head in ctz skip list
err = lfs1_ctz_find(lfs1, &file->cache, NULL,
file->head, file->size,
size, &file->head, &(lfs1_off_t){0});
if (err) {
return err;
}
file->size = size;
file->flags |= LFS1_F_DIRTY;
} else if (size > oldsize) {
lfs1_off_t pos = file->pos;
// flush+seek if not already at end
if (file->pos != oldsize) {
int err = lfs1_file_seek(lfs1, file, 0, LFS1_SEEK_END);
if (err < 0) {
return err;
}
}
// fill with zeros
while (file->pos < size) {
lfs1_ssize_t res = lfs1_file_write(lfs1, file, &(uint8_t){0}, 1);
if (res < 0) {
return res;
}
}
// restore pos
int err = lfs1_file_seek(lfs1, file, pos, LFS1_SEEK_SET);
if (err < 0) {
return err;
}
}
return 0;
}
lfs1_soff_t lfs1_file_tell(lfs1_t *lfs1, lfs1_file_t *file) {
(void)lfs1;
return file->pos;
}
int lfs1_file_rewind(lfs1_t *lfs1, lfs1_file_t *file) {
lfs1_soff_t res = lfs1_file_seek(lfs1, file, 0, LFS1_SEEK_SET);
if (res < 0) {
return res;
}
return 0;
}
lfs1_soff_t lfs1_file_size(lfs1_t *lfs1, lfs1_file_t *file) {
(void)lfs1;
if (file->flags & LFS1_F_WRITING) {
return lfs1_max(file->pos, file->size);
} else {
return file->size;
}
}
/// General fs operations ///
int lfs1_stat(lfs1_t *lfs1, const char *path, struct lfs1_info *info) {
lfs1_dir_t cwd;
lfs1_entry_t entry;
int err = lfs1_dir_find(lfs1, &cwd, &entry, &path);
if (err) {
return err;
}
memset(info, 0, sizeof(*info));
info->type = entry.d.type;
if (info->type == LFS1_TYPE_REG) {
info->size = entry.d.u.file.size;
}
if (lfs1_paircmp(entry.d.u.dir, lfs1->root) == 0) {
strcpy(info->name, "/");
} else {
err = lfs1_bd_read(lfs1, cwd.pair[0],
entry.off + 4+entry.d.elen+entry.d.alen,
info->name, entry.d.nlen);
if (err) {
return err;
}
}
return 0;
}
int lfs1_remove(lfs1_t *lfs1, const char *path) {
// deorphan if we haven't yet, needed at most once after poweron
if (!lfs1->deorphaned) {
int err = lfs1_deorphan(lfs1);
if (err) {
return err;
}
}
lfs1_dir_t cwd;
lfs1_entry_t entry;
int err = lfs1_dir_find(lfs1, &cwd, &entry, &path);
if (err) {
return err;
}
lfs1_dir_t dir;
if (entry.d.type == LFS1_TYPE_DIR) {
// must be empty before removal, checking size
// without masking top bit checks for any case where
// dir is not empty
err = lfs1_dir_fetch(lfs1, &dir, entry.d.u.dir);
if (err) {
return err;
} else if (dir.d.size != sizeof(dir.d)+4) {
return LFS1_ERR_NOTEMPTY;
}
}
// remove the entry
err = lfs1_dir_remove(lfs1, &cwd, &entry);
if (err) {
return err;
}
// if we were a directory, find pred, replace tail
if (entry.d.type == LFS1_TYPE_DIR) {
int res = lfs1_pred(lfs1, dir.pair, &cwd);
if (res < 0) {
return res;
}
LFS1_ASSERT(res); // must have pred
cwd.d.tail[0] = dir.d.tail[0];
cwd.d.tail[1] = dir.d.tail[1];
err = lfs1_dir_commit(lfs1, &cwd, NULL, 0);
if (err) {
return err;
}
}
return 0;
}
int lfs1_rename(lfs1_t *lfs1, const char *oldpath, const char *newpath) {
// deorphan if we haven't yet, needed at most once after poweron
if (!lfs1->deorphaned) {
int err = lfs1_deorphan(lfs1);
if (err) {
return err;
}
}
// find old entry
lfs1_dir_t oldcwd;
lfs1_entry_t oldentry;
int err = lfs1_dir_find(lfs1, &oldcwd, &oldentry, &(const char *){oldpath});
if (err) {
return err;
}
// mark as moving
oldentry.d.type |= 0x80;
err = lfs1_dir_update(lfs1, &oldcwd, &oldentry, NULL);
if (err) {
return err;
}
// allocate new entry
lfs1_dir_t newcwd;
lfs1_entry_t preventry;
err = lfs1_dir_find(lfs1, &newcwd, &preventry, &newpath);
if (err && (err != LFS1_ERR_NOENT || strchr(newpath, '/') != NULL)) {
return err;
}
// must have same type
bool prevexists = (err != LFS1_ERR_NOENT);
if (prevexists && preventry.d.type != (0x7f & oldentry.d.type)) {
return LFS1_ERR_ISDIR;
}
lfs1_dir_t dir;
if (prevexists && preventry.d.type == LFS1_TYPE_DIR) {
// must be empty before removal, checking size
// without masking top bit checks for any case where
// dir is not empty
err = lfs1_dir_fetch(lfs1, &dir, preventry.d.u.dir);
if (err) {
return err;
} else if (dir.d.size != sizeof(dir.d)+4) {
return LFS1_ERR_NOTEMPTY;
}
}
// move to new location
lfs1_entry_t newentry = preventry;
newentry.d = oldentry.d;
newentry.d.type &= ~0x80;
newentry.d.nlen = strlen(newpath);
if (prevexists) {
err = lfs1_dir_update(lfs1, &newcwd, &newentry, newpath);
if (err) {
return err;
}
} else {
err = lfs1_dir_append(lfs1, &newcwd, &newentry, newpath);
if (err) {
return err;
}
}
// fetch old pair again in case dir block changed
lfs1->moving = true;
err = lfs1_dir_find(lfs1, &oldcwd, &oldentry, &oldpath);
if (err) {
return err;
}
lfs1->moving = false;
// remove old entry
err = lfs1_dir_remove(lfs1, &oldcwd, &oldentry);
if (err) {
return err;
}
// if we were a directory, find pred, replace tail
if (prevexists && preventry.d.type == LFS1_TYPE_DIR) {
int res = lfs1_pred(lfs1, dir.pair, &newcwd);
if (res < 0) {
return res;
}
LFS1_ASSERT(res); // must have pred
newcwd.d.tail[0] = dir.d.tail[0];
newcwd.d.tail[1] = dir.d.tail[1];
err = lfs1_dir_commit(lfs1, &newcwd, NULL, 0);
if (err) {
return err;
}
}
return 0;
}
/// Filesystem operations ///
static void lfs1_deinit(lfs1_t *lfs1) {
// free allocated memory
if (!lfs1->cfg->read_buffer) {
lfs1_free(lfs1->rcache.buffer);
}
if (!lfs1->cfg->prog_buffer) {
lfs1_free(lfs1->pcache.buffer);
}
if (!lfs1->cfg->lookahead_buffer) {
lfs1_free(lfs1->free.buffer);
}
}
static int lfs1_init(lfs1_t *lfs1, const struct lfs1_config *cfg) {
lfs1->cfg = cfg;
// setup read cache
if (lfs1->cfg->read_buffer) {
lfs1->rcache.buffer = lfs1->cfg->read_buffer;
} else {
lfs1->rcache.buffer = lfs1_malloc(lfs1->cfg->read_size);
if (!lfs1->rcache.buffer) {
goto cleanup;
}
}
// setup program cache
if (lfs1->cfg->prog_buffer) {
lfs1->pcache.buffer = lfs1->cfg->prog_buffer;
} else {
lfs1->pcache.buffer = lfs1_malloc(lfs1->cfg->prog_size);
if (!lfs1->pcache.buffer) {
goto cleanup;
}
}
// zero to avoid information leaks
lfs1_cache_zero(lfs1, &lfs1->pcache);
lfs1_cache_drop(lfs1, &lfs1->rcache);
// setup lookahead, round down to nearest 32-bits
LFS1_ASSERT(lfs1->cfg->lookahead % 32 == 0);
LFS1_ASSERT(lfs1->cfg->lookahead > 0);
if (lfs1->cfg->lookahead_buffer) {
lfs1->free.buffer = lfs1->cfg->lookahead_buffer;
} else {
lfs1->free.buffer = lfs1_malloc(lfs1->cfg->lookahead/8);
if (!lfs1->free.buffer) {
goto cleanup;
}
}
// check that program and read sizes are multiples of the block size
LFS1_ASSERT(lfs1->cfg->prog_size % lfs1->cfg->read_size == 0);
LFS1_ASSERT(lfs1->cfg->block_size % lfs1->cfg->prog_size == 0);
// check that the block size is large enough to fit ctz pointers
LFS1_ASSERT(4*lfs1_npw2(0xffffffff / (lfs1->cfg->block_size-2*4))
<= lfs1->cfg->block_size);
// setup default state
lfs1->root[0] = 0xffffffff;
lfs1->root[1] = 0xffffffff;
lfs1->files = NULL;
lfs1->dirs = NULL;
lfs1->deorphaned = false;
lfs1->moving = false;
return 0;
cleanup:
lfs1_deinit(lfs1);
return LFS1_ERR_NOMEM;
}
int lfs1_format(lfs1_t *lfs1, const struct lfs1_config *cfg) {
int err = 0;
if (true) {
err = lfs1_init(lfs1, cfg);
if (err) {
return err;
}
// create free lookahead
memset(lfs1->free.buffer, 0, lfs1->cfg->lookahead/8);
lfs1->free.off = 0;
lfs1->free.size = lfs1_min(lfs1->cfg->lookahead, lfs1->cfg->block_count);
lfs1->free.i = 0;
lfs1_alloc_ack(lfs1);
// create superblock dir
lfs1_dir_t superdir;
err = lfs1_dir_alloc(lfs1, &superdir);
if (err) {
goto cleanup;
}
// write root directory
lfs1_dir_t root;
err = lfs1_dir_alloc(lfs1, &root);
if (err) {
goto cleanup;
}
err = lfs1_dir_commit(lfs1, &root, NULL, 0);
if (err) {
goto cleanup;
}
lfs1->root[0] = root.pair[0];
lfs1->root[1] = root.pair[1];
// write superblocks
lfs1_superblock_t superblock = {
.off = sizeof(superdir.d),
.d.type = LFS1_TYPE_SUPERBLOCK,
.d.elen = sizeof(superblock.d) - sizeof(superblock.d.magic) - 4,
.d.nlen = sizeof(superblock.d.magic),
.d.version = LFS1_DISK_VERSION,
.d.magic = {"littlefs"},
.d.block_size = lfs1->cfg->block_size,
.d.block_count = lfs1->cfg->block_count,
.d.root = {lfs1->root[0], lfs1->root[1]},
};
superdir.d.tail[0] = root.pair[0];
superdir.d.tail[1] = root.pair[1];
superdir.d.size = sizeof(superdir.d) + sizeof(superblock.d) + 4;
// write both pairs to be safe
lfs1_superblock_tole32(&superblock.d);
bool valid = false;
for (int i = 0; i < 2; i++) {
err = lfs1_dir_commit(lfs1, &superdir, (struct lfs1_region[]){
{sizeof(superdir.d), sizeof(superblock.d),
&superblock.d, sizeof(superblock.d)}
}, 1);
if (err && err != LFS1_ERR_CORRUPT) {
goto cleanup;
}
valid = valid || !err;
}
if (!valid) {
err = LFS1_ERR_CORRUPT;
goto cleanup;
}
// sanity check that fetch works
err = lfs1_dir_fetch(lfs1, &superdir, (const lfs1_block_t[2]){0, 1});
if (err) {
goto cleanup;
}
lfs1_alloc_ack(lfs1);
}
cleanup:
lfs1_deinit(lfs1);
return err;
}
int lfs1_mount(lfs1_t *lfs1, const struct lfs1_config *cfg) {
int err = 0;
if (true) {
err = lfs1_init(lfs1, cfg);
if (err) {
return err;
}
// setup free lookahead
lfs1->free.off = 0;
lfs1->free.size = 0;
lfs1->free.i = 0;
lfs1_alloc_ack(lfs1);
// load superblock
lfs1_dir_t dir;
lfs1_superblock_t superblock;
err = lfs1_dir_fetch(lfs1, &dir, (const lfs1_block_t[2]){0, 1});
if (err && err != LFS1_ERR_CORRUPT) {
goto cleanup;
}
if (!err) {
err = lfs1_bd_read(lfs1, dir.pair[0], sizeof(dir.d),
&superblock.d, sizeof(superblock.d));
lfs1_superblock_fromle32(&superblock.d);
if (err) {
goto cleanup;
}
lfs1->root[0] = superblock.d.root[0];
lfs1->root[1] = superblock.d.root[1];
}
if (err || memcmp(superblock.d.magic, "littlefs", 8) != 0) {
LFS1_ERROR("Invalid superblock at %d %d", 0, 1);
err = LFS1_ERR_CORRUPT;
goto cleanup;
}
uint16_t major_version = (0xffff & (superblock.d.version >> 16));
uint16_t minor_version = (0xffff & (superblock.d.version >> 0));
if ((major_version != LFS1_DISK_VERSION_MAJOR ||
minor_version > LFS1_DISK_VERSION_MINOR)) {
LFS1_ERROR("Invalid version %d.%d", major_version, minor_version);
err = LFS1_ERR_INVAL;
goto cleanup;
}
return 0;
}
cleanup:
lfs1_deinit(lfs1);
return err;
}
int lfs1_unmount(lfs1_t *lfs1) {
lfs1_deinit(lfs1);
return 0;
}
/// Littlefs specific operations ///
int lfs1_traverse(lfs1_t *lfs1, int (*cb)(void*, lfs1_block_t), void *data) {
if (lfs1_pairisnull(lfs1->root)) {
return 0;
}
// iterate over metadata pairs
lfs1_dir_t dir;
lfs1_entry_t entry;
lfs1_block_t cwd[2] = {0, 1};
while (true) {
for (int i = 0; i < 2; i++) {
int err = cb(data, cwd[i]);
if (err) {
return err;
}
}
int err = lfs1_dir_fetch(lfs1, &dir, cwd);
if (err) {
return err;
}
// iterate over contents
while (dir.off + sizeof(entry.d) <= (0x7fffffff & dir.d.size)-4) {
err = lfs1_bd_read(lfs1, dir.pair[0], dir.off,
&entry.d, sizeof(entry.d));
lfs1_entry_fromle32(&entry.d);
if (err) {
return err;
}
dir.off += lfs1_entry_size(&entry);
if ((0x70 & entry.d.type) == (0x70 & LFS1_TYPE_REG)) {
err = lfs1_ctz_traverse(lfs1, &lfs1->rcache, NULL,
entry.d.u.file.head, entry.d.u.file.size, cb, data);
if (err) {
return err;
}
}
}
cwd[0] = dir.d.tail[0];
cwd[1] = dir.d.tail[1];
if (lfs1_pairisnull(cwd)) {
break;
}
}
// iterate over any open files
for (lfs1_file_t *f = lfs1->files; f; f = f->next) {
if (f->flags & LFS1_F_DIRTY) {
int err = lfs1_ctz_traverse(lfs1, &lfs1->rcache, &f->cache,
f->head, f->size, cb, data);
if (err) {
return err;
}
}
if (f->flags & LFS1_F_WRITING) {
int err = lfs1_ctz_traverse(lfs1, &lfs1->rcache, &f->cache,
f->block, f->pos, cb, data);
if (err) {
return err;
}
}
}
return 0;
}
static int lfs1_pred(lfs1_t *lfs1, const lfs1_block_t dir[2], lfs1_dir_t *pdir) {
if (lfs1_pairisnull(lfs1->root)) {
return 0;
}
// iterate over all directory directory entries
int err = lfs1_dir_fetch(lfs1, pdir, (const lfs1_block_t[2]){0, 1});
if (err) {
return err;
}
while (!lfs1_pairisnull(pdir->d.tail)) {
if (lfs1_paircmp(pdir->d.tail, dir) == 0) {
return true;
}
err = lfs1_dir_fetch(lfs1, pdir, pdir->d.tail);
if (err) {
return err;
}
}
return false;
}
static int lfs1_parent(lfs1_t *lfs1, const lfs1_block_t dir[2],
lfs1_dir_t *parent, lfs1_entry_t *entry) {
if (lfs1_pairisnull(lfs1->root)) {
return 0;
}
parent->d.tail[0] = 0;
parent->d.tail[1] = 1;
// iterate over all directory directory entries
while (!lfs1_pairisnull(parent->d.tail)) {
int err = lfs1_dir_fetch(lfs1, parent, parent->d.tail);
if (err) {
return err;
}
while (true) {
err = lfs1_dir_next(lfs1, parent, entry);
if (err && err != LFS1_ERR_NOENT) {
return err;
}
if (err == LFS1_ERR_NOENT) {
break;
}
if (((0x70 & entry->d.type) == (0x70 & LFS1_TYPE_DIR)) &&
lfs1_paircmp(entry->d.u.dir, dir) == 0) {
return true;
}
}
}
return false;
}
static int lfs1_moved(lfs1_t *lfs1, const void *e) {
if (lfs1_pairisnull(lfs1->root)) {
return 0;
}
// skip superblock
lfs1_dir_t cwd;
int err = lfs1_dir_fetch(lfs1, &cwd, (const lfs1_block_t[2]){0, 1});
if (err) {
return err;
}
// iterate over all directory directory entries
lfs1_entry_t entry;
while (!lfs1_pairisnull(cwd.d.tail)) {
err = lfs1_dir_fetch(lfs1, &cwd, cwd.d.tail);
if (err) {
return err;
}
while (true) {
err = lfs1_dir_next(lfs1, &cwd, &entry);
if (err && err != LFS1_ERR_NOENT) {
return err;
}
if (err == LFS1_ERR_NOENT) {
break;
}
if (!(0x80 & entry.d.type) &&
memcmp(&entry.d.u, e, sizeof(entry.d.u)) == 0) {
return true;
}
}
}
return false;
}
static int lfs1_relocate(lfs1_t *lfs1,
const lfs1_block_t oldpair[2], const lfs1_block_t newpair[2]) {
// find parent
lfs1_dir_t parent;
lfs1_entry_t entry;
int res = lfs1_parent(lfs1, oldpair, &parent, &entry);
if (res < 0) {
return res;
}
if (res) {
// update disk, this creates a desync
entry.d.u.dir[0] = newpair[0];
entry.d.u.dir[1] = newpair[1];
int err = lfs1_dir_update(lfs1, &parent, &entry, NULL);
if (err) {
return err;
}
// update internal root
if (lfs1_paircmp(oldpair, lfs1->root) == 0) {
LFS1_DEBUG("Relocating root %" PRIu32 " %" PRIu32,
newpair[0], newpair[1]);
lfs1->root[0] = newpair[0];
lfs1->root[1] = newpair[1];
}
// clean up bad block, which should now be a desync
return lfs1_deorphan(lfs1);
}
// find pred
res = lfs1_pred(lfs1, oldpair, &parent);
if (res < 0) {
return res;
}
if (res) {
// just replace bad pair, no desync can occur
parent.d.tail[0] = newpair[0];
parent.d.tail[1] = newpair[1];
return lfs1_dir_commit(lfs1, &parent, NULL, 0);
}
// couldn't find dir, must be new
return 0;
}
int lfs1_deorphan(lfs1_t *lfs1) {
lfs1->deorphaned = true;
if (lfs1_pairisnull(lfs1->root)) {
return 0;
}
lfs1_dir_t pdir = {.d.size = 0x80000000};
lfs1_dir_t cwd = {.d.tail[0] = 0, .d.tail[1] = 1};
// iterate over all directory directory entries
for (lfs1_size_t i = 0; i < lfs1->cfg->block_count; i++) {
if (lfs1_pairisnull(cwd.d.tail)) {
return 0;
}
int err = lfs1_dir_fetch(lfs1, &cwd, cwd.d.tail);
if (err) {
return err;
}
// check head blocks for orphans
if (!(0x80000000 & pdir.d.size)) {
// check if we have a parent
lfs1_dir_t parent;
lfs1_entry_t entry;
int res = lfs1_parent(lfs1, pdir.d.tail, &parent, &entry);
if (res < 0) {
return res;
}
if (!res) {
// we are an orphan
LFS1_DEBUG("Found orphan %" PRIu32 " %" PRIu32,
pdir.d.tail[0], pdir.d.tail[1]);
pdir.d.tail[0] = cwd.d.tail[0];
pdir.d.tail[1] = cwd.d.tail[1];
err = lfs1_dir_commit(lfs1, &pdir, NULL, 0);
if (err) {
return err;
}
return 0;
}
if (!lfs1_pairsync(entry.d.u.dir, pdir.d.tail)) {
// we have desynced
LFS1_DEBUG("Found desync %" PRIu32 " %" PRIu32,
entry.d.u.dir[0], entry.d.u.dir[1]);
pdir.d.tail[0] = entry.d.u.dir[0];
pdir.d.tail[1] = entry.d.u.dir[1];
err = lfs1_dir_commit(lfs1, &pdir, NULL, 0);
if (err) {
return err;
}
return 0;
}
}
// check entries for moves
lfs1_entry_t entry;
while (true) {
err = lfs1_dir_next(lfs1, &cwd, &entry);
if (err && err != LFS1_ERR_NOENT) {
return err;
}
if (err == LFS1_ERR_NOENT) {
break;
}
// found moved entry
if (entry.d.type & 0x80) {
int moved = lfs1_moved(lfs1, &entry.d.u);
if (moved < 0) {
return moved;
}
if (moved) {
LFS1_DEBUG("Found move %" PRIu32 " %" PRIu32,
entry.d.u.dir[0], entry.d.u.dir[1]);
err = lfs1_dir_remove(lfs1, &cwd, &entry);
if (err) {
return err;
}
} else {
LFS1_DEBUG("Found partial move %" PRIu32 " %" PRIu32,
entry.d.u.dir[0], entry.d.u.dir[1]);
entry.d.type &= ~0x80;
err = lfs1_dir_update(lfs1, &cwd, &entry, NULL);
if (err) {
return err;
}
}
}
}
memcpy(&pdir, &cwd, sizeof(pdir));
}
// If we reached here, we have more directory pairs than blocks in the
// filesystem... So something must be horribly wrong
return LFS1_ERR_CORRUPT;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/littlefs/lfs1.c | C | apache-2.0 | 71,973 |
/*
* The little filesystem
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef LFS1_H
#define LFS1_H
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C"
{
#endif
/// Version info ///
// Software library version
// Major (top-nibble), incremented on backwards incompatible changes
// Minor (bottom-nibble), incremented on feature additions
#define LFS1_VERSION 0x00010007
#define LFS1_VERSION_MAJOR (0xffff & (LFS1_VERSION >> 16))
#define LFS1_VERSION_MINOR (0xffff & (LFS1_VERSION >> 0))
// Version of On-disk data structures
// Major (top-nibble), incremented on backwards incompatible changes
// Minor (bottom-nibble), incremented on feature additions
#define LFS1_DISK_VERSION 0x00010001
#define LFS1_DISK_VERSION_MAJOR (0xffff & (LFS1_DISK_VERSION >> 16))
#define LFS1_DISK_VERSION_MINOR (0xffff & (LFS1_DISK_VERSION >> 0))
/// Definitions ///
// Type definitions
typedef uint32_t lfs1_size_t;
typedef uint32_t lfs1_off_t;
typedef int32_t lfs1_ssize_t;
typedef int32_t lfs1_soff_t;
typedef uint32_t lfs1_block_t;
// Max name size in bytes
#ifndef LFS1_NAME_MAX
#define LFS1_NAME_MAX 255
#endif
// Max file size in bytes
#ifndef LFS1_FILE_MAX
#define LFS1_FILE_MAX 2147483647
#endif
// Possible error codes, these are negative to allow
// valid positive return values
enum lfs1_error {
LFS1_ERR_OK = 0, // No error
LFS1_ERR_IO = -5, // Error during device operation
LFS1_ERR_CORRUPT = -52, // Corrupted
LFS1_ERR_NOENT = -2, // No directory entry
LFS1_ERR_EXIST = -17, // Entry already exists
LFS1_ERR_NOTDIR = -20, // Entry is not a dir
LFS1_ERR_ISDIR = -21, // Entry is a dir
LFS1_ERR_NOTEMPTY = -39, // Dir is not empty
LFS1_ERR_BADF = -9, // Bad file number
LFS1_ERR_FBIG = -27, // File too large
LFS1_ERR_INVAL = -22, // Invalid parameter
LFS1_ERR_NOSPC = -28, // No space left on device
LFS1_ERR_NOMEM = -12, // No more memory available
};
// File types
enum lfs1_type {
LFS1_TYPE_REG = 0x11,
LFS1_TYPE_DIR = 0x22,
LFS1_TYPE_SUPERBLOCK = 0x2e,
};
// File open flags
enum lfs1_open_flags {
// open flags
LFS1_O_RDONLY = 1, // Open a file as read only
LFS1_O_WRONLY = 2, // Open a file as write only
LFS1_O_RDWR = 3, // Open a file as read and write
LFS1_O_CREAT = 0x0100, // Create a file if it does not exist
LFS1_O_EXCL = 0x0200, // Fail if a file already exists
LFS1_O_TRUNC = 0x0400, // Truncate the existing file to zero size
LFS1_O_APPEND = 0x0800, // Move to end of file on every write
// internally used flags
LFS1_F_DIRTY = 0x10000, // File does not match storage
LFS1_F_WRITING = 0x20000, // File has been written since last flush
LFS1_F_READING = 0x40000, // File has been read since last flush
LFS1_F_ERRED = 0x80000, // An error occured during write
};
// File seek flags
enum lfs1_whence_flags {
LFS1_SEEK_SET = 0, // Seek relative to an absolute position
LFS1_SEEK_CUR = 1, // Seek relative to the current file position
LFS1_SEEK_END = 2, // Seek relative to the end of the file
};
// Configuration provided during initialization of the littlefs
struct lfs1_config {
// Opaque user provided context that can be used to pass
// information to the block device operations
void *context;
// Read a region in a block. Negative error codes are propogated
// to the user.
int (*read)(const struct lfs1_config *c, lfs1_block_t block,
lfs1_off_t off, void *buffer, lfs1_size_t size);
// Program a region in a block. The block must have previously
// been erased. Negative error codes are propogated to the user.
// May return LFS1_ERR_CORRUPT if the block should be considered bad.
int (*prog)(const struct lfs1_config *c, lfs1_block_t block,
lfs1_off_t off, const void *buffer, lfs1_size_t size);
// Erase a block. A block must be erased before being programmed.
// The state of an erased block is undefined. Negative error codes
// are propogated to the user.
// May return LFS1_ERR_CORRUPT if the block should be considered bad.
int (*erase)(const struct lfs1_config *c, lfs1_block_t block);
// Sync the state of the underlying block device. Negative error codes
// are propogated to the user.
int (*sync)(const struct lfs1_config *c);
// Minimum size of a block read. This determines the size of read buffers.
// This may be larger than the physical read size to improve performance
// by caching more of the block device.
lfs1_size_t read_size;
// Minimum size of a block program. This determines the size of program
// buffers. This may be larger than the physical program size to improve
// performance by caching more of the block device.
// Must be a multiple of the read size.
lfs1_size_t prog_size;
// Size of an erasable block. This does not impact ram consumption and
// may be larger than the physical erase size. However, this should be
// kept small as each file currently takes up an entire block.
// Must be a multiple of the program size.
lfs1_size_t block_size;
// Number of erasable blocks on the device.
lfs1_size_t block_count;
// Number of blocks to lookahead during block allocation. A larger
// lookahead reduces the number of passes required to allocate a block.
// The lookahead buffer requires only 1 bit per block so it can be quite
// large with little ram impact. Should be a multiple of 32.
lfs1_size_t lookahead;
// Optional, statically allocated read buffer. Must be read sized.
void *read_buffer;
// Optional, statically allocated program buffer. Must be program sized.
void *prog_buffer;
// Optional, statically allocated lookahead buffer. Must be 1 bit per
// lookahead block.
void *lookahead_buffer;
// Optional, statically allocated buffer for files. Must be program sized.
// If enabled, only one file may be opened at a time.
void *file_buffer;
};
// Optional configuration provided during lfs1_file_opencfg
struct lfs1_file_config {
// Optional, statically allocated buffer for files. Must be program sized.
// If NULL, malloc will be used by default.
void *buffer;
};
// File info structure
struct lfs1_info {
// Type of the file, either LFS1_TYPE_REG or LFS1_TYPE_DIR
uint8_t type;
// Size of the file, only valid for REG files
lfs1_size_t size;
// Name of the file stored as a null-terminated string
char name[LFS1_NAME_MAX+1];
};
/// littlefs data structures ///
typedef struct lfs1_entry {
lfs1_off_t off;
struct lfs1_disk_entry {
uint8_t type;
uint8_t elen;
uint8_t alen;
uint8_t nlen;
union {
struct {
lfs1_block_t head;
lfs1_size_t size;
} file;
lfs1_block_t dir[2];
} u;
} d;
} lfs1_entry_t;
typedef struct lfs1_cache {
lfs1_block_t block;
lfs1_off_t off;
uint8_t *buffer;
} lfs1_cache_t;
typedef struct lfs1_file {
struct lfs1_file *next;
lfs1_block_t pair[2];
lfs1_off_t poff;
lfs1_block_t head;
lfs1_size_t size;
const struct lfs1_file_config *cfg;
uint32_t flags;
lfs1_off_t pos;
lfs1_block_t block;
lfs1_off_t off;
lfs1_cache_t cache;
} lfs1_file_t;
typedef struct lfs1_dir {
struct lfs1_dir *next;
lfs1_block_t pair[2];
lfs1_off_t off;
lfs1_block_t head[2];
lfs1_off_t pos;
struct lfs1_disk_dir {
uint32_t rev;
lfs1_size_t size;
lfs1_block_t tail[2];
} d;
} lfs1_dir_t;
typedef struct lfs1_superblock {
lfs1_off_t off;
struct lfs1_disk_superblock {
uint8_t type;
uint8_t elen;
uint8_t alen;
uint8_t nlen;
lfs1_block_t root[2];
uint32_t block_size;
uint32_t block_count;
uint32_t version;
char magic[8];
} d;
} lfs1_superblock_t;
typedef struct lfs1_free {
lfs1_block_t off;
lfs1_block_t size;
lfs1_block_t i;
lfs1_block_t ack;
uint32_t *buffer;
} lfs1_free_t;
// The littlefs type
typedef struct lfs1 {
const struct lfs1_config *cfg;
lfs1_block_t root[2];
lfs1_file_t *files;
lfs1_dir_t *dirs;
lfs1_cache_t rcache;
lfs1_cache_t pcache;
lfs1_free_t free;
bool deorphaned;
bool moving;
} lfs1_t;
/// Filesystem functions ///
// Format a block device with the littlefs
//
// Requires a littlefs object and config struct. This clobbers the littlefs
// object, and does not leave the filesystem mounted. The config struct must
// be zeroed for defaults and backwards compatibility.
//
// Returns a negative error code on failure.
int lfs1_format(lfs1_t *lfs1, const struct lfs1_config *config);
// Mounts a littlefs
//
// Requires a littlefs object and config struct. Multiple filesystems
// may be mounted simultaneously with multiple littlefs objects. Both
// lfs1 and config must be allocated while mounted. The config struct must
// be zeroed for defaults and backwards compatibility.
//
// Returns a negative error code on failure.
int lfs1_mount(lfs1_t *lfs1, const struct lfs1_config *config);
// Unmounts a littlefs
//
// Does nothing besides releasing any allocated resources.
// Returns a negative error code on failure.
int lfs1_unmount(lfs1_t *lfs1);
/// General operations ///
// Removes a file or directory
//
// If removing a directory, the directory must be empty.
// Returns a negative error code on failure.
int lfs1_remove(lfs1_t *lfs1, const char *path);
// Rename or move a file or directory
//
// If the destination exists, it must match the source in type.
// If the destination is a directory, the directory must be empty.
//
// Returns a negative error code on failure.
int lfs1_rename(lfs1_t *lfs1, const char *oldpath, const char *newpath);
// Find info about a file or directory
//
// Fills out the info structure, based on the specified file or directory.
// Returns a negative error code on failure.
int lfs1_stat(lfs1_t *lfs1, const char *path, struct lfs1_info *info);
/// File operations ///
// Open a file
//
// The mode that the file is opened in is determined by the flags, which
// are values from the enum lfs1_open_flags that are bitwise-ored together.
//
// Returns a negative error code on failure.
int lfs1_file_open(lfs1_t *lfs1, lfs1_file_t *file,
const char *path, int flags);
// Open a file with extra configuration
//
// The mode that the file is opened in is determined by the flags, which
// are values from the enum lfs1_open_flags that are bitwise-ored together.
//
// The config struct provides additional config options per file as described
// above. The config struct must be allocated while the file is open, and the
// config struct must be zeroed for defaults and backwards compatibility.
//
// Returns a negative error code on failure.
int lfs1_file_opencfg(lfs1_t *lfs1, lfs1_file_t *file,
const char *path, int flags,
const struct lfs1_file_config *config);
// Close a file
//
// Any pending writes are written out to storage as though
// sync had been called and releases any allocated resources.
//
// Returns a negative error code on failure.
int lfs1_file_close(lfs1_t *lfs1, lfs1_file_t *file);
// Synchronize a file on storage
//
// Any pending writes are written out to storage.
// Returns a negative error code on failure.
int lfs1_file_sync(lfs1_t *lfs1, lfs1_file_t *file);
// Read data from file
//
// Takes a buffer and size indicating where to store the read data.
// Returns the number of bytes read, or a negative error code on failure.
lfs1_ssize_t lfs1_file_read(lfs1_t *lfs1, lfs1_file_t *file,
void *buffer, lfs1_size_t size);
// Write data to file
//
// Takes a buffer and size indicating the data to write. The file will not
// actually be updated on the storage until either sync or close is called.
//
// Returns the number of bytes written, or a negative error code on failure.
lfs1_ssize_t lfs1_file_write(lfs1_t *lfs1, lfs1_file_t *file,
const void *buffer, lfs1_size_t size);
// Change the position of the file
//
// The change in position is determined by the offset and whence flag.
// Returns the old position of the file, or a negative error code on failure.
lfs1_soff_t lfs1_file_seek(lfs1_t *lfs1, lfs1_file_t *file,
lfs1_soff_t off, int whence);
// Truncates the size of the file to the specified size
//
// Returns a negative error code on failure.
int lfs1_file_truncate(lfs1_t *lfs1, lfs1_file_t *file, lfs1_off_t size);
// Return the position of the file
//
// Equivalent to lfs1_file_seek(lfs1, file, 0, LFS1_SEEK_CUR)
// Returns the position of the file, or a negative error code on failure.
lfs1_soff_t lfs1_file_tell(lfs1_t *lfs1, lfs1_file_t *file);
// Change the position of the file to the beginning of the file
//
// Equivalent to lfs1_file_seek(lfs1, file, 0, LFS1_SEEK_CUR)
// Returns a negative error code on failure.
int lfs1_file_rewind(lfs1_t *lfs1, lfs1_file_t *file);
// Return the size of the file
//
// Similar to lfs1_file_seek(lfs1, file, 0, LFS1_SEEK_END)
// Returns the size of the file, or a negative error code on failure.
lfs1_soff_t lfs1_file_size(lfs1_t *lfs1, lfs1_file_t *file);
/// Directory operations ///
// Create a directory
//
// Returns a negative error code on failure.
int lfs1_mkdir(lfs1_t *lfs1, const char *path);
// Open a directory
//
// Once open a directory can be used with read to iterate over files.
// Returns a negative error code on failure.
int lfs1_dir_open(lfs1_t *lfs1, lfs1_dir_t *dir, const char *path);
// Close a directory
//
// Releases any allocated resources.
// Returns a negative error code on failure.
int lfs1_dir_close(lfs1_t *lfs1, lfs1_dir_t *dir);
// Read an entry in the directory
//
// Fills out the info structure, based on the specified file or directory.
// Returns a negative error code on failure.
int lfs1_dir_read(lfs1_t *lfs1, lfs1_dir_t *dir, struct lfs1_info *info);
// Change the position of the directory
//
// The new off must be a value previous returned from tell and specifies
// an absolute offset in the directory seek.
//
// Returns a negative error code on failure.
int lfs1_dir_seek(lfs1_t *lfs1, lfs1_dir_t *dir, lfs1_off_t off);
// Return the position of the directory
//
// The returned offset is only meant to be consumed by seek and may not make
// sense, but does indicate the current position in the directory iteration.
//
// Returns the position of the directory, or a negative error code on failure.
lfs1_soff_t lfs1_dir_tell(lfs1_t *lfs1, lfs1_dir_t *dir);
// Change the position of the directory to the beginning of the directory
//
// Returns a negative error code on failure.
int lfs1_dir_rewind(lfs1_t *lfs1, lfs1_dir_t *dir);
/// Miscellaneous littlefs specific operations ///
// Traverse through all blocks in use by the filesystem
//
// The provided callback will be called with each block address that is
// currently in use by the filesystem. This can be used to determine which
// blocks are in use or how much of the storage is available.
//
// Returns a negative error code on failure.
int lfs1_traverse(lfs1_t *lfs1, int (*cb)(void*, lfs1_block_t), void *data);
// Prunes any recoverable errors that may have occured in the filesystem
//
// Not needed to be called by user unless an operation is interrupted
// but the filesystem is still mounted. This is already called on first
// allocation.
//
// Returns a negative error code on failure.
int lfs1_deorphan(lfs1_t *lfs1);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/littlefs/lfs1.h | C | apache-2.0 | 15,814 |
/*
* lfs1 util functions
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "lfs1_util.h"
// Only compile if user does not provide custom config
#ifndef LFS1_CONFIG
// Software CRC implementation with small lookup table
void lfs1_crc(uint32_t *restrict crc, const void *buffer, size_t size) {
static const uint32_t rtable[16] = {
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c,
};
const uint8_t *data = buffer;
for (size_t i = 0; i < size; i++) {
*crc = (*crc >> 4) ^ rtable[(*crc ^ (data[i] >> 0)) & 0xf];
*crc = (*crc >> 4) ^ rtable[(*crc ^ (data[i] >> 4)) & 0xf];
}
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/littlefs/lfs1_util.c | C | apache-2.0 | 861 |
/*
* lfs1 utility functions
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef LFS1_UTIL_H
#define LFS1_UTIL_H
// Users can override lfs1_util.h with their own configuration by defining
// LFS1_CONFIG as a header file to include (-DLFS1_CONFIG=lfs1_config.h).
//
// If LFS1_CONFIG is used, none of the default utils will be emitted and must be
// provided by the config file. To start I would suggest copying lfs1_util.h and
// modifying as needed.
#ifdef LFS1_CONFIG
#define LFS1_STRINGIZE(x) LFS1_STRINGIZE2(x)
#define LFS1_STRINGIZE2(x) #x
#include LFS1_STRINGIZE(LFS1_CONFIG)
#else
// System includes
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#ifndef LFS1_NO_MALLOC
#include <stdlib.h>
#endif
#ifndef LFS1_NO_ASSERT
#include <assert.h>
#endif
#if !defined(LFS1_NO_DEBUG) || !defined(LFS1_NO_WARN) || !defined(LFS1_NO_ERROR)
#include <stdio.h>
#endif
#ifdef __cplusplus
extern "C"
{
#endif
// Macros, may be replaced by system specific wrappers. Arguments to these
// macros must not have side-effects as the macros can be removed for a smaller
// code footprint
// Logging functions
#ifndef LFS1_NO_DEBUG
#define LFS1_DEBUG(fmt, ...) \
printf("lfs1 debug:%d: " fmt "\n", __LINE__, __VA_ARGS__)
#else
#define LFS1_DEBUG(fmt, ...)
#endif
#ifndef LFS1_NO_WARN
#define LFS1_WARN(fmt, ...) \
printf("lfs1 warn:%d: " fmt "\n", __LINE__, __VA_ARGS__)
#else
#define LFS1_WARN(fmt, ...)
#endif
#ifndef LFS1_NO_ERROR
#define LFS1_ERROR(fmt, ...) \
printf("lfs1 error:%d: " fmt "\n", __LINE__, __VA_ARGS__)
#else
#define LFS1_ERROR(fmt, ...)
#endif
// Runtime assertions
#ifndef LFS1_NO_ASSERT
#define LFS1_ASSERT(test) assert(test)
#else
#define LFS1_ASSERT(test)
#endif
// Builtin functions, these may be replaced by more efficient
// toolchain-specific implementations. LFS1_NO_INTRINSICS falls back to a more
// expensive basic C implementation for debugging purposes
// Min/max functions for unsigned 32-bit numbers
static inline uint32_t lfs1_max(uint32_t a, uint32_t b) {
return (a > b) ? a : b;
}
static inline uint32_t lfs1_min(uint32_t a, uint32_t b) {
return (a < b) ? a : b;
}
// Find the next smallest power of 2 less than or equal to a
static inline uint32_t lfs1_npw2(uint32_t a) {
#if !defined(LFS1_NO_INTRINSICS) && (defined(__GNUC__) || defined(__CC_ARM))
return 32 - __builtin_clz(a-1);
#else
uint32_t r = 0;
uint32_t s;
a -= 1;
s = (a > 0xffff) << 4; a >>= s; r |= s;
s = (a > 0xff ) << 3; a >>= s; r |= s;
s = (a > 0xf ) << 2; a >>= s; r |= s;
s = (a > 0x3 ) << 1; a >>= s; r |= s;
return (r | (a >> 1)) + 1;
#endif
}
// Count the number of trailing binary zeros in a
// lfs1_ctz(0) may be undefined
static inline uint32_t lfs1_ctz(uint32_t a) {
#if !defined(LFS1_NO_INTRINSICS) && defined(__GNUC__)
return __builtin_ctz(a);
#else
return lfs1_npw2((a & -a) + 1) - 1;
#endif
}
// Count the number of binary ones in a
static inline uint32_t lfs1_popc(uint32_t a) {
#if !defined(LFS1_NO_INTRINSICS) && (defined(__GNUC__) || defined(__CC_ARM))
return __builtin_popcount(a);
#else
a = a - ((a >> 1) & 0x55555555);
a = (a & 0x33333333) + ((a >> 2) & 0x33333333);
return (((a + (a >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24;
#endif
}
// Find the sequence comparison of a and b, this is the distance
// between a and b ignoring overflow
static inline int lfs1_scmp(uint32_t a, uint32_t b) {
return (int)(unsigned)(a - b);
}
// Convert from 32-bit little-endian to native order
static inline uint32_t lfs1_fromle32(uint32_t a) {
#if !defined(LFS1_NO_INTRINSICS) && ( \
(defined( BYTE_ORDER ) && BYTE_ORDER == ORDER_LITTLE_ENDIAN ) || \
(defined(__BYTE_ORDER ) && __BYTE_ORDER == __ORDER_LITTLE_ENDIAN ) || \
(defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
return a;
#elif !defined(LFS1_NO_INTRINSICS) && ( \
(defined( BYTE_ORDER ) && BYTE_ORDER == ORDER_BIG_ENDIAN ) || \
(defined(__BYTE_ORDER ) && __BYTE_ORDER == __ORDER_BIG_ENDIAN ) || \
(defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
return __builtin_bswap32(a);
#else
return (((uint8_t*)&a)[0] << 0) |
(((uint8_t*)&a)[1] << 8) |
(((uint8_t*)&a)[2] << 16) |
(((uint8_t*)&a)[3] << 24);
#endif
}
// Convert to 32-bit little-endian from native order
static inline uint32_t lfs1_tole32(uint32_t a) {
return lfs1_fromle32(a);
}
// Calculate CRC-32 with polynomial = 0x04c11db7
void lfs1_crc(uint32_t *crc, const void *buffer, size_t size);
// Allocate memory, only used if buffers are not provided to littlefs
static inline void *lfs1_malloc(size_t size) {
#ifndef LFS1_NO_MALLOC
return malloc(size);
#else
(void)size;
return NULL;
#endif
}
// Deallocate memory, only used if buffers are not provided to littlefs
static inline void lfs1_free(void *p) {
#ifndef LFS1_NO_MALLOC
free(p);
#else
(void)p;
#endif
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/littlefs/lfs1_util.h | C | apache-2.0 | 5,082 |
/*
* The little filesystem
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "lfs2.h"
#include "lfs2_util.h"
#define LFS2_BLOCK_NULL ((lfs2_block_t)-1)
#define LFS2_BLOCK_INLINE ((lfs2_block_t)-2)
/// Caching block device operations ///
static inline void lfs2_cache_drop(lfs2_t *lfs2, lfs2_cache_t *rcache) {
// do not zero, cheaper if cache is readonly or only going to be
// written with identical data (during relocates)
(void)lfs2;
rcache->block = LFS2_BLOCK_NULL;
}
static inline void lfs2_cache_zero(lfs2_t *lfs2, lfs2_cache_t *pcache) {
// zero to avoid information leak
memset(pcache->buffer, 0xff, lfs2->cfg->cache_size);
pcache->block = LFS2_BLOCK_NULL;
}
static int lfs2_bd_read(lfs2_t *lfs2,
const lfs2_cache_t *pcache, lfs2_cache_t *rcache, lfs2_size_t hint,
lfs2_block_t block, lfs2_off_t off,
void *buffer, lfs2_size_t size) {
uint8_t *data = buffer;
if (block >= lfs2->cfg->block_count ||
off+size > lfs2->cfg->block_size) {
return LFS2_ERR_CORRUPT;
}
while (size > 0) {
lfs2_size_t diff = size;
if (pcache && block == pcache->block &&
off < pcache->off + pcache->size) {
if (off >= pcache->off) {
// is already in pcache?
diff = lfs2_min(diff, pcache->size - (off-pcache->off));
memcpy(data, &pcache->buffer[off-pcache->off], diff);
data += diff;
off += diff;
size -= diff;
continue;
}
// pcache takes priority
diff = lfs2_min(diff, pcache->off-off);
}
if (block == rcache->block &&
off < rcache->off + rcache->size) {
if (off >= rcache->off) {
// is already in rcache?
diff = lfs2_min(diff, rcache->size - (off-rcache->off));
memcpy(data, &rcache->buffer[off-rcache->off], diff);
data += diff;
off += diff;
size -= diff;
continue;
}
// rcache takes priority
diff = lfs2_min(diff, rcache->off-off);
}
if (size >= hint && off % lfs2->cfg->read_size == 0 &&
size >= lfs2->cfg->read_size) {
// bypass cache?
diff = lfs2_aligndown(diff, lfs2->cfg->read_size);
int err = lfs2->cfg->read(lfs2->cfg, block, off, data, diff);
if (err) {
return err;
}
data += diff;
off += diff;
size -= diff;
continue;
}
// load to cache, first condition can no longer fail
LFS2_ASSERT(block < lfs2->cfg->block_count);
rcache->block = block;
rcache->off = lfs2_aligndown(off, lfs2->cfg->read_size);
rcache->size = lfs2_min(
lfs2_min(
lfs2_alignup(off+hint, lfs2->cfg->read_size),
lfs2->cfg->block_size)
- rcache->off,
lfs2->cfg->cache_size);
int err = lfs2->cfg->read(lfs2->cfg, rcache->block,
rcache->off, rcache->buffer, rcache->size);
LFS2_ASSERT(err <= 0);
if (err) {
return err;
}
}
return 0;
}
enum {
LFS2_CMP_EQ = 0,
LFS2_CMP_LT = 1,
LFS2_CMP_GT = 2,
};
static int lfs2_bd_cmp(lfs2_t *lfs2,
const lfs2_cache_t *pcache, lfs2_cache_t *rcache, lfs2_size_t hint,
lfs2_block_t block, lfs2_off_t off,
const void *buffer, lfs2_size_t size) {
const uint8_t *data = buffer;
lfs2_size_t diff = 0;
for (lfs2_off_t i = 0; i < size; i += diff) {
uint8_t dat[8];
diff = lfs2_min(size-i, sizeof(dat));
int res = lfs2_bd_read(lfs2,
pcache, rcache, hint-i,
block, off+i, &dat, diff);
if (res) {
return res;
}
res = memcmp(dat, data + i, diff);
if (res) {
return res < 0 ? LFS2_CMP_LT : LFS2_CMP_GT;
}
}
return LFS2_CMP_EQ;
}
#ifndef LFS2_READONLY
static int lfs2_bd_flush(lfs2_t *lfs2,
lfs2_cache_t *pcache, lfs2_cache_t *rcache, bool validate) {
if (pcache->block != LFS2_BLOCK_NULL && pcache->block != LFS2_BLOCK_INLINE) {
LFS2_ASSERT(pcache->block < lfs2->cfg->block_count);
lfs2_size_t diff = lfs2_alignup(pcache->size, lfs2->cfg->prog_size);
int err = lfs2->cfg->prog(lfs2->cfg, pcache->block,
pcache->off, pcache->buffer, diff);
LFS2_ASSERT(err <= 0);
if (err) {
return err;
}
if (validate) {
// check data on disk
lfs2_cache_drop(lfs2, rcache);
int res = lfs2_bd_cmp(lfs2,
NULL, rcache, diff,
pcache->block, pcache->off, pcache->buffer, diff);
if (res < 0) {
return res;
}
if (res != LFS2_CMP_EQ) {
return LFS2_ERR_CORRUPT;
}
}
lfs2_cache_zero(lfs2, pcache);
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_bd_sync(lfs2_t *lfs2,
lfs2_cache_t *pcache, lfs2_cache_t *rcache, bool validate) {
lfs2_cache_drop(lfs2, rcache);
int err = lfs2_bd_flush(lfs2, pcache, rcache, validate);
if (err) {
return err;
}
err = lfs2->cfg->sync(lfs2->cfg);
LFS2_ASSERT(err <= 0);
return err;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_bd_prog(lfs2_t *lfs2,
lfs2_cache_t *pcache, lfs2_cache_t *rcache, bool validate,
lfs2_block_t block, lfs2_off_t off,
const void *buffer, lfs2_size_t size) {
const uint8_t *data = buffer;
LFS2_ASSERT(block == LFS2_BLOCK_INLINE || block < lfs2->cfg->block_count);
LFS2_ASSERT(off + size <= lfs2->cfg->block_size);
while (size > 0) {
if (block == pcache->block &&
off >= pcache->off &&
off < pcache->off + lfs2->cfg->cache_size) {
// already fits in pcache?
lfs2_size_t diff = lfs2_min(size,
lfs2->cfg->cache_size - (off-pcache->off));
memcpy(&pcache->buffer[off-pcache->off], data, diff);
data += diff;
off += diff;
size -= diff;
pcache->size = lfs2_max(pcache->size, off - pcache->off);
if (pcache->size == lfs2->cfg->cache_size) {
// eagerly flush out pcache if we fill up
int err = lfs2_bd_flush(lfs2, pcache, rcache, validate);
if (err) {
return err;
}
}
continue;
}
// pcache must have been flushed, either by programming and
// entire block or manually flushing the pcache
LFS2_ASSERT(pcache->block == LFS2_BLOCK_NULL);
// prepare pcache, first condition can no longer fail
pcache->block = block;
pcache->off = lfs2_aligndown(off, lfs2->cfg->prog_size);
pcache->size = 0;
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_bd_erase(lfs2_t *lfs2, lfs2_block_t block) {
LFS2_ASSERT(block < lfs2->cfg->block_count);
int err = lfs2->cfg->erase(lfs2->cfg, block);
LFS2_ASSERT(err <= 0);
return err;
}
#endif
/// Small type-level utilities ///
// operations on block pairs
static inline void lfs2_pair_swap(lfs2_block_t pair[2]) {
lfs2_block_t t = pair[0];
pair[0] = pair[1];
pair[1] = t;
}
static inline bool lfs2_pair_isnull(const lfs2_block_t pair[2]) {
return pair[0] == LFS2_BLOCK_NULL || pair[1] == LFS2_BLOCK_NULL;
}
static inline int lfs2_pair_cmp(
const lfs2_block_t paira[2],
const lfs2_block_t pairb[2]) {
return !(paira[0] == pairb[0] || paira[1] == pairb[1] ||
paira[0] == pairb[1] || paira[1] == pairb[0]);
}
static inline bool lfs2_pair_sync(
const lfs2_block_t paira[2],
const lfs2_block_t pairb[2]) {
return (paira[0] == pairb[0] && paira[1] == pairb[1]) ||
(paira[0] == pairb[1] && paira[1] == pairb[0]);
}
static inline void lfs2_pair_fromle32(lfs2_block_t pair[2]) {
pair[0] = lfs2_fromle32(pair[0]);
pair[1] = lfs2_fromle32(pair[1]);
}
static inline void lfs2_pair_tole32(lfs2_block_t pair[2]) {
pair[0] = lfs2_tole32(pair[0]);
pair[1] = lfs2_tole32(pair[1]);
}
// operations on 32-bit entry tags
typedef uint32_t lfs2_tag_t;
typedef int32_t lfs2_stag_t;
#define LFS2_MKTAG(type, id, size) \
(((lfs2_tag_t)(type) << 20) | ((lfs2_tag_t)(id) << 10) | (lfs2_tag_t)(size))
#define LFS2_MKTAG_IF(cond, type, id, size) \
((cond) ? LFS2_MKTAG(type, id, size) : LFS2_MKTAG(LFS2_FROM_NOOP, 0, 0))
#define LFS2_MKTAG_IF_ELSE(cond, type1, id1, size1, type2, id2, size2) \
((cond) ? LFS2_MKTAG(type1, id1, size1) : LFS2_MKTAG(type2, id2, size2))
static inline bool lfs2_tag_isvalid(lfs2_tag_t tag) {
return !(tag & 0x80000000);
}
static inline bool lfs2_tag_isdelete(lfs2_tag_t tag) {
return ((int32_t)(tag << 22) >> 22) == -1;
}
static inline uint16_t lfs2_tag_type1(lfs2_tag_t tag) {
return (tag & 0x70000000) >> 20;
}
static inline uint16_t lfs2_tag_type3(lfs2_tag_t tag) {
return (tag & 0x7ff00000) >> 20;
}
static inline uint8_t lfs2_tag_chunk(lfs2_tag_t tag) {
return (tag & 0x0ff00000) >> 20;
}
static inline int8_t lfs2_tag_splice(lfs2_tag_t tag) {
return (int8_t)lfs2_tag_chunk(tag);
}
static inline uint16_t lfs2_tag_id(lfs2_tag_t tag) {
return (tag & 0x000ffc00) >> 10;
}
static inline lfs2_size_t lfs2_tag_size(lfs2_tag_t tag) {
return tag & 0x000003ff;
}
static inline lfs2_size_t lfs2_tag_dsize(lfs2_tag_t tag) {
return sizeof(tag) + lfs2_tag_size(tag + lfs2_tag_isdelete(tag));
}
// operations on attributes in attribute lists
struct lfs2_mattr {
lfs2_tag_t tag;
const void *buffer;
};
struct lfs2_diskoff {
lfs2_block_t block;
lfs2_off_t off;
};
#define LFS2_MKATTRS(...) \
(struct lfs2_mattr[]){__VA_ARGS__}, \
sizeof((struct lfs2_mattr[]){__VA_ARGS__}) / sizeof(struct lfs2_mattr)
// operations on global state
static inline void lfs2_gstate_xor(lfs2_gstate_t *a, const lfs2_gstate_t *b) {
for (int i = 0; i < 3; i++) {
((uint32_t*)a)[i] ^= ((const uint32_t*)b)[i];
}
}
static inline bool lfs2_gstate_iszero(const lfs2_gstate_t *a) {
for (int i = 0; i < 3; i++) {
if (((uint32_t*)a)[i] != 0) {
return false;
}
}
return true;
}
static inline bool lfs2_gstate_hasorphans(const lfs2_gstate_t *a) {
return lfs2_tag_size(a->tag);
}
static inline uint8_t lfs2_gstate_getorphans(const lfs2_gstate_t *a) {
return lfs2_tag_size(a->tag);
}
static inline bool lfs2_gstate_hasmove(const lfs2_gstate_t *a) {
return lfs2_tag_type1(a->tag);
}
static inline bool lfs2_gstate_hasmovehere(const lfs2_gstate_t *a,
const lfs2_block_t *pair) {
return lfs2_tag_type1(a->tag) && lfs2_pair_cmp(a->pair, pair) == 0;
}
static inline void lfs2_gstate_fromle32(lfs2_gstate_t *a) {
a->tag = lfs2_fromle32(a->tag);
a->pair[0] = lfs2_fromle32(a->pair[0]);
a->pair[1] = lfs2_fromle32(a->pair[1]);
}
static inline void lfs2_gstate_tole32(lfs2_gstate_t *a) {
a->tag = lfs2_tole32(a->tag);
a->pair[0] = lfs2_tole32(a->pair[0]);
a->pair[1] = lfs2_tole32(a->pair[1]);
}
// other endianness operations
static void lfs2_ctz_fromle32(struct lfs2_ctz *ctz) {
ctz->head = lfs2_fromle32(ctz->head);
ctz->size = lfs2_fromle32(ctz->size);
}
#ifndef LFS2_READONLY
static void lfs2_ctz_tole32(struct lfs2_ctz *ctz) {
ctz->head = lfs2_tole32(ctz->head);
ctz->size = lfs2_tole32(ctz->size);
}
#endif
static inline void lfs2_superblock_fromle32(lfs2_superblock_t *superblock) {
superblock->version = lfs2_fromle32(superblock->version);
superblock->block_size = lfs2_fromle32(superblock->block_size);
superblock->block_count = lfs2_fromle32(superblock->block_count);
superblock->name_max = lfs2_fromle32(superblock->name_max);
superblock->file_max = lfs2_fromle32(superblock->file_max);
superblock->attr_max = lfs2_fromle32(superblock->attr_max);
}
static inline void lfs2_superblock_tole32(lfs2_superblock_t *superblock) {
superblock->version = lfs2_tole32(superblock->version);
superblock->block_size = lfs2_tole32(superblock->block_size);
superblock->block_count = lfs2_tole32(superblock->block_count);
superblock->name_max = lfs2_tole32(superblock->name_max);
superblock->file_max = lfs2_tole32(superblock->file_max);
superblock->attr_max = lfs2_tole32(superblock->attr_max);
}
#ifndef LFS2_NO_ASSERT
static inline bool lfs2_mlist_isopen(struct lfs2_mlist *head,
struct lfs2_mlist *node) {
for (struct lfs2_mlist **p = &head; *p; p = &(*p)->next) {
if (*p == (struct lfs2_mlist*)node) {
return true;
}
}
return false;
}
#endif
static inline void lfs2_mlist_remove(lfs2_t *lfs2, struct lfs2_mlist *mlist) {
for (struct lfs2_mlist **p = &lfs2->mlist; *p; p = &(*p)->next) {
if (*p == mlist) {
*p = (*p)->next;
break;
}
}
}
static inline void lfs2_mlist_append(lfs2_t *lfs2, struct lfs2_mlist *mlist) {
mlist->next = lfs2->mlist;
lfs2->mlist = mlist;
}
/// Internal operations predeclared here ///
#ifndef LFS2_READONLY
static int lfs2_dir_commit(lfs2_t *lfs2, lfs2_mdir_t *dir,
const struct lfs2_mattr *attrs, int attrcount);
static int lfs2_dir_compact(lfs2_t *lfs2,
lfs2_mdir_t *dir, const struct lfs2_mattr *attrs, int attrcount,
lfs2_mdir_t *source, uint16_t begin, uint16_t end);
static lfs2_ssize_t lfs2_file_rawwrite(lfs2_t *lfs2, lfs2_file_t *file,
const void *buffer, lfs2_size_t size);
static int lfs2_file_rawsync(lfs2_t *lfs2, lfs2_file_t *file);
static int lfs2_file_outline(lfs2_t *lfs2, lfs2_file_t *file);
static int lfs2_file_flush(lfs2_t *lfs2, lfs2_file_t *file);
static void lfs2_fs_preporphans(lfs2_t *lfs2, int8_t orphans);
static void lfs2_fs_prepmove(lfs2_t *lfs2,
uint16_t id, const lfs2_block_t pair[2]);
static int lfs2_fs_pred(lfs2_t *lfs2, const lfs2_block_t dir[2],
lfs2_mdir_t *pdir);
static lfs2_stag_t lfs2_fs_parent(lfs2_t *lfs2, const lfs2_block_t dir[2],
lfs2_mdir_t *parent);
static int lfs2_fs_relocate(lfs2_t *lfs2,
const lfs2_block_t oldpair[2], lfs2_block_t newpair[2]);
static int lfs2_fs_forceconsistency(lfs2_t *lfs2);
#endif
#ifdef LFS2_MIGRATE
static int lfs21_traverse(lfs2_t *lfs2,
int (*cb)(void*, lfs2_block_t), void *data);
#endif
static int lfs2_dir_rawrewind(lfs2_t *lfs2, lfs2_dir_t *dir);
static lfs2_ssize_t lfs2_file_rawread(lfs2_t *lfs2, lfs2_file_t *file,
void *buffer, lfs2_size_t size);
static int lfs2_file_rawclose(lfs2_t *lfs2, lfs2_file_t *file);
static lfs2_soff_t lfs2_file_rawsize(lfs2_t *lfs2, lfs2_file_t *file);
static lfs2_ssize_t lfs2_fs_rawsize(lfs2_t *lfs2);
static int lfs2_fs_rawtraverse(lfs2_t *lfs2,
int (*cb)(void *data, lfs2_block_t block), void *data,
bool includeorphans);
static int lfs2_deinit(lfs2_t *lfs2);
static int lfs2_rawunmount(lfs2_t *lfs2);
/// Block allocator ///
#ifndef LFS2_READONLY
static int lfs2_alloc_lookahead(void *p, lfs2_block_t block) {
lfs2_t *lfs2 = (lfs2_t*)p;
lfs2_block_t off = ((block - lfs2->free.off)
+ lfs2->cfg->block_count) % lfs2->cfg->block_count;
if (off < lfs2->free.size) {
lfs2->free.buffer[off / 32] |= 1U << (off % 32);
}
return 0;
}
#endif
// indicate allocated blocks have been committed into the filesystem, this
// is to prevent blocks from being garbage collected in the middle of a
// commit operation
static void lfs2_alloc_ack(lfs2_t *lfs2) {
lfs2->free.ack = lfs2->cfg->block_count;
}
// drop the lookahead buffer, this is done during mounting and failed
// traversals in order to avoid invalid lookahead state
static void lfs2_alloc_drop(lfs2_t *lfs2) {
lfs2->free.size = 0;
lfs2->free.i = 0;
lfs2_alloc_ack(lfs2);
}
#ifndef LFS2_READONLY
static int lfs2_alloc(lfs2_t *lfs2, lfs2_block_t *block) {
while (true) {
while (lfs2->free.i != lfs2->free.size) {
lfs2_block_t off = lfs2->free.i;
lfs2->free.i += 1;
lfs2->free.ack -= 1;
if (!(lfs2->free.buffer[off / 32] & (1U << (off % 32)))) {
// found a free block
*block = (lfs2->free.off + off) % lfs2->cfg->block_count;
// eagerly find next off so an alloc ack can
// discredit old lookahead blocks
while (lfs2->free.i != lfs2->free.size &&
(lfs2->free.buffer[lfs2->free.i / 32]
& (1U << (lfs2->free.i % 32)))) {
lfs2->free.i += 1;
lfs2->free.ack -= 1;
}
return 0;
}
}
// check if we have looked at all blocks since last ack
if (lfs2->free.ack == 0) {
LFS2_ERROR("No more free space %"PRIu32,
lfs2->free.i + lfs2->free.off);
return LFS2_ERR_NOSPC;
}
lfs2->free.off = (lfs2->free.off + lfs2->free.size)
% lfs2->cfg->block_count;
lfs2->free.size = lfs2_min(8*lfs2->cfg->lookahead_size, lfs2->free.ack);
lfs2->free.i = 0;
// find mask of free blocks from tree
memset(lfs2->free.buffer, 0, lfs2->cfg->lookahead_size);
int err = lfs2_fs_rawtraverse(lfs2, lfs2_alloc_lookahead, lfs2, true);
if (err) {
lfs2_alloc_drop(lfs2);
return err;
}
}
}
#endif
/// Metadata pair and directory operations ///
static lfs2_stag_t lfs2_dir_getslice(lfs2_t *lfs2, const lfs2_mdir_t *dir,
lfs2_tag_t gmask, lfs2_tag_t gtag,
lfs2_off_t goff, void *gbuffer, lfs2_size_t gsize) {
lfs2_off_t off = dir->off;
lfs2_tag_t ntag = dir->etag;
lfs2_stag_t gdiff = 0;
if (lfs2_gstate_hasmovehere(&lfs2->gdisk, dir->pair) &&
lfs2_tag_id(gmask) != 0 &&
lfs2_tag_id(lfs2->gdisk.tag) <= lfs2_tag_id(gtag)) {
// synthetic moves
gdiff -= LFS2_MKTAG(0, 1, 0);
}
// iterate over dir block backwards (for faster lookups)
while (off >= sizeof(lfs2_tag_t) + lfs2_tag_dsize(ntag)) {
off -= lfs2_tag_dsize(ntag);
lfs2_tag_t tag = ntag;
int err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, sizeof(ntag),
dir->pair[0], off, &ntag, sizeof(ntag));
if (err) {
return err;
}
ntag = (lfs2_frombe32(ntag) ^ tag) & 0x7fffffff;
if (lfs2_tag_id(gmask) != 0 &&
lfs2_tag_type1(tag) == LFS2_TYPE_SPLICE &&
lfs2_tag_id(tag) <= lfs2_tag_id(gtag - gdiff)) {
if (tag == (LFS2_MKTAG(LFS2_TYPE_CREATE, 0, 0) |
(LFS2_MKTAG(0, 0x3ff, 0) & (gtag - gdiff)))) {
// found where we were created
return LFS2_ERR_NOENT;
}
// move around splices
gdiff += LFS2_MKTAG(0, lfs2_tag_splice(tag), 0);
}
if ((gmask & tag) == (gmask & (gtag - gdiff))) {
if (lfs2_tag_isdelete(tag)) {
return LFS2_ERR_NOENT;
}
lfs2_size_t diff = lfs2_min(lfs2_tag_size(tag), gsize);
err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, diff,
dir->pair[0], off+sizeof(tag)+goff, gbuffer, diff);
if (err) {
return err;
}
memset((uint8_t*)gbuffer + diff, 0, gsize - diff);
return tag + gdiff;
}
}
return LFS2_ERR_NOENT;
}
static lfs2_stag_t lfs2_dir_get(lfs2_t *lfs2, const lfs2_mdir_t *dir,
lfs2_tag_t gmask, lfs2_tag_t gtag, void *buffer) {
return lfs2_dir_getslice(lfs2, dir,
gmask, gtag,
0, buffer, lfs2_tag_size(gtag));
}
static int lfs2_dir_getread(lfs2_t *lfs2, const lfs2_mdir_t *dir,
const lfs2_cache_t *pcache, lfs2_cache_t *rcache, lfs2_size_t hint,
lfs2_tag_t gmask, lfs2_tag_t gtag,
lfs2_off_t off, void *buffer, lfs2_size_t size) {
uint8_t *data = buffer;
if (off+size > lfs2->cfg->block_size) {
return LFS2_ERR_CORRUPT;
}
while (size > 0) {
lfs2_size_t diff = size;
if (pcache && pcache->block == LFS2_BLOCK_INLINE &&
off < pcache->off + pcache->size) {
if (off >= pcache->off) {
// is already in pcache?
diff = lfs2_min(diff, pcache->size - (off-pcache->off));
memcpy(data, &pcache->buffer[off-pcache->off], diff);
data += diff;
off += diff;
size -= diff;
continue;
}
// pcache takes priority
diff = lfs2_min(diff, pcache->off-off);
}
if (rcache->block == LFS2_BLOCK_INLINE &&
off < rcache->off + rcache->size) {
if (off >= rcache->off) {
// is already in rcache?
diff = lfs2_min(diff, rcache->size - (off-rcache->off));
memcpy(data, &rcache->buffer[off-rcache->off], diff);
data += diff;
off += diff;
size -= diff;
continue;
}
// rcache takes priority
diff = lfs2_min(diff, rcache->off-off);
}
// load to cache, first condition can no longer fail
rcache->block = LFS2_BLOCK_INLINE;
rcache->off = lfs2_aligndown(off, lfs2->cfg->read_size);
rcache->size = lfs2_min(lfs2_alignup(off+hint, lfs2->cfg->read_size),
lfs2->cfg->cache_size);
int err = lfs2_dir_getslice(lfs2, dir, gmask, gtag,
rcache->off, rcache->buffer, rcache->size);
if (err < 0) {
return err;
}
}
return 0;
}
#ifndef LFS2_READONLY
static int lfs2_dir_traverse_filter(void *p,
lfs2_tag_t tag, const void *buffer) {
lfs2_tag_t *filtertag = p;
(void)buffer;
// which mask depends on unique bit in tag structure
uint32_t mask = (tag & LFS2_MKTAG(0x100, 0, 0))
? LFS2_MKTAG(0x7ff, 0x3ff, 0)
: LFS2_MKTAG(0x700, 0x3ff, 0);
// check for redundancy
if ((mask & tag) == (mask & *filtertag) ||
lfs2_tag_isdelete(*filtertag) ||
(LFS2_MKTAG(0x7ff, 0x3ff, 0) & tag) == (
LFS2_MKTAG(LFS2_TYPE_DELETE, 0, 0) |
(LFS2_MKTAG(0, 0x3ff, 0) & *filtertag))) {
return true;
}
// check if we need to adjust for created/deleted tags
if (lfs2_tag_type1(tag) == LFS2_TYPE_SPLICE &&
lfs2_tag_id(tag) <= lfs2_tag_id(*filtertag)) {
*filtertag += LFS2_MKTAG(0, lfs2_tag_splice(tag), 0);
}
return false;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_traverse(lfs2_t *lfs2,
const lfs2_mdir_t *dir, lfs2_off_t off, lfs2_tag_t ptag,
const struct lfs2_mattr *attrs, int attrcount,
lfs2_tag_t tmask, lfs2_tag_t ttag,
uint16_t begin, uint16_t end, int16_t diff,
int (*cb)(void *data, lfs2_tag_t tag, const void *buffer), void *data) {
// iterate over directory and attrs
while (true) {
lfs2_tag_t tag;
const void *buffer;
struct lfs2_diskoff disk;
if (off+lfs2_tag_dsize(ptag) < dir->off) {
off += lfs2_tag_dsize(ptag);
int err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, sizeof(tag),
dir->pair[0], off, &tag, sizeof(tag));
if (err) {
return err;
}
tag = (lfs2_frombe32(tag) ^ ptag) | 0x80000000;
disk.block = dir->pair[0];
disk.off = off+sizeof(lfs2_tag_t);
buffer = &disk;
ptag = tag;
} else if (attrcount > 0) {
tag = attrs[0].tag;
buffer = attrs[0].buffer;
attrs += 1;
attrcount -= 1;
} else {
return 0;
}
lfs2_tag_t mask = LFS2_MKTAG(0x7ff, 0, 0);
if ((mask & tmask & tag) != (mask & tmask & ttag)) {
continue;
}
// do we need to filter? inlining the filtering logic here allows
// for some minor optimizations
if (lfs2_tag_id(tmask) != 0) {
// scan for duplicates and update tag based on creates/deletes
int filter = lfs2_dir_traverse(lfs2,
dir, off, ptag, attrs, attrcount,
0, 0, 0, 0, 0,
lfs2_dir_traverse_filter, &tag);
if (filter < 0) {
return filter;
}
if (filter) {
continue;
}
// in filter range?
if (!(lfs2_tag_id(tag) >= begin && lfs2_tag_id(tag) < end)) {
continue;
}
}
// handle special cases for mcu-side operations
if (lfs2_tag_type3(tag) == LFS2_FROM_NOOP) {
// do nothing
} else if (lfs2_tag_type3(tag) == LFS2_FROM_MOVE) {
uint16_t fromid = lfs2_tag_size(tag);
uint16_t toid = lfs2_tag_id(tag);
int err = lfs2_dir_traverse(lfs2,
buffer, 0, 0xffffffff, NULL, 0,
LFS2_MKTAG(0x600, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, 0, 0),
fromid, fromid+1, toid-fromid+diff,
cb, data);
if (err) {
return err;
}
} else if (lfs2_tag_type3(tag) == LFS2_FROM_USERATTRS) {
for (unsigned i = 0; i < lfs2_tag_size(tag); i++) {
const struct lfs2_attr *a = buffer;
int err = cb(data, LFS2_MKTAG(LFS2_TYPE_USERATTR + a[i].type,
lfs2_tag_id(tag) + diff, a[i].size), a[i].buffer);
if (err) {
return err;
}
}
} else {
int err = cb(data, tag + LFS2_MKTAG(0, diff, 0), buffer);
if (err) {
return err;
}
}
}
}
#endif
static lfs2_stag_t lfs2_dir_fetchmatch(lfs2_t *lfs2,
lfs2_mdir_t *dir, const lfs2_block_t pair[2],
lfs2_tag_t fmask, lfs2_tag_t ftag, uint16_t *id,
int (*cb)(void *data, lfs2_tag_t tag, const void *buffer), void *data) {
// we can find tag very efficiently during a fetch, since we're already
// scanning the entire directory
lfs2_stag_t besttag = -1;
// if either block address is invalid we return LFS2_ERR_CORRUPT here,
// otherwise later writes to the pair could fail
if (pair[0] >= lfs2->cfg->block_count || pair[1] >= lfs2->cfg->block_count) {
return LFS2_ERR_CORRUPT;
}
// find the block with the most recent revision
uint32_t revs[2] = {0, 0};
int r = 0;
for (int i = 0; i < 2; i++) {
int err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, sizeof(revs[i]),
pair[i], 0, &revs[i], sizeof(revs[i]));
revs[i] = lfs2_fromle32(revs[i]);
if (err && err != LFS2_ERR_CORRUPT) {
return err;
}
if (err != LFS2_ERR_CORRUPT &&
lfs2_scmp(revs[i], revs[(i+1)%2]) > 0) {
r = i;
}
}
dir->pair[0] = pair[(r+0)%2];
dir->pair[1] = pair[(r+1)%2];
dir->rev = revs[(r+0)%2];
dir->off = 0; // nonzero = found some commits
// now scan tags to fetch the actual dir and find possible match
for (int i = 0; i < 2; i++) {
lfs2_off_t off = 0;
lfs2_tag_t ptag = 0xffffffff;
uint16_t tempcount = 0;
lfs2_block_t temptail[2] = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL};
bool tempsplit = false;
lfs2_stag_t tempbesttag = besttag;
dir->rev = lfs2_tole32(dir->rev);
uint32_t crc = lfs2_crc(0xffffffff, &dir->rev, sizeof(dir->rev));
dir->rev = lfs2_fromle32(dir->rev);
while (true) {
// extract next tag
lfs2_tag_t tag;
off += lfs2_tag_dsize(ptag);
int err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, lfs2->cfg->block_size,
dir->pair[0], off, &tag, sizeof(tag));
if (err) {
if (err == LFS2_ERR_CORRUPT) {
// can't continue?
dir->erased = false;
break;
}
return err;
}
crc = lfs2_crc(crc, &tag, sizeof(tag));
tag = lfs2_frombe32(tag) ^ ptag;
// next commit not yet programmed or we're not in valid range
if (!lfs2_tag_isvalid(tag)) {
dir->erased = (lfs2_tag_type1(ptag) == LFS2_TYPE_CRC &&
dir->off % lfs2->cfg->prog_size == 0);
break;
} else if (off + lfs2_tag_dsize(tag) > lfs2->cfg->block_size) {
dir->erased = false;
break;
}
ptag = tag;
if (lfs2_tag_type1(tag) == LFS2_TYPE_CRC) {
// check the crc attr
uint32_t dcrc;
err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, lfs2->cfg->block_size,
dir->pair[0], off+sizeof(tag), &dcrc, sizeof(dcrc));
if (err) {
if (err == LFS2_ERR_CORRUPT) {
dir->erased = false;
break;
}
return err;
}
dcrc = lfs2_fromle32(dcrc);
if (crc != dcrc) {
dir->erased = false;
break;
}
// reset the next bit if we need to
ptag ^= (lfs2_tag_t)(lfs2_tag_chunk(tag) & 1U) << 31;
// toss our crc into the filesystem seed for
// pseudorandom numbers, note we use another crc here
// as a collection function because it is sufficiently
// random and convenient
lfs2->seed = lfs2_crc(lfs2->seed, &crc, sizeof(crc));
// update with what's found so far
besttag = tempbesttag;
dir->off = off + lfs2_tag_dsize(tag);
dir->etag = ptag;
dir->count = tempcount;
dir->tail[0] = temptail[0];
dir->tail[1] = temptail[1];
dir->split = tempsplit;
// reset crc
crc = 0xffffffff;
continue;
}
// crc the entry first, hopefully leaving it in the cache
for (lfs2_off_t j = sizeof(tag); j < lfs2_tag_dsize(tag); j++) {
uint8_t dat;
err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, lfs2->cfg->block_size,
dir->pair[0], off+j, &dat, 1);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
dir->erased = false;
break;
}
return err;
}
crc = lfs2_crc(crc, &dat, 1);
}
// directory modification tags?
if (lfs2_tag_type1(tag) == LFS2_TYPE_NAME) {
// increase count of files if necessary
if (lfs2_tag_id(tag) >= tempcount) {
tempcount = lfs2_tag_id(tag) + 1;
}
} else if (lfs2_tag_type1(tag) == LFS2_TYPE_SPLICE) {
tempcount += lfs2_tag_splice(tag);
if (tag == (LFS2_MKTAG(LFS2_TYPE_DELETE, 0, 0) |
(LFS2_MKTAG(0, 0x3ff, 0) & tempbesttag))) {
tempbesttag |= 0x80000000;
} else if (tempbesttag != -1 &&
lfs2_tag_id(tag) <= lfs2_tag_id(tempbesttag)) {
tempbesttag += LFS2_MKTAG(0, lfs2_tag_splice(tag), 0);
}
} else if (lfs2_tag_type1(tag) == LFS2_TYPE_TAIL) {
tempsplit = (lfs2_tag_chunk(tag) & 1);
err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, lfs2->cfg->block_size,
dir->pair[0], off+sizeof(tag), &temptail, 8);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
dir->erased = false;
break;
}
}
lfs2_pair_fromle32(temptail);
}
// found a match for our fetcher?
if ((fmask & tag) == (fmask & ftag)) {
int res = cb(data, tag, &(struct lfs2_diskoff){
dir->pair[0], off+sizeof(tag)});
if (res < 0) {
if (res == LFS2_ERR_CORRUPT) {
dir->erased = false;
break;
}
return res;
}
if (res == LFS2_CMP_EQ) {
// found a match
tempbesttag = tag;
} else if ((LFS2_MKTAG(0x7ff, 0x3ff, 0) & tag) ==
(LFS2_MKTAG(0x7ff, 0x3ff, 0) & tempbesttag)) {
// found an identical tag, but contents didn't match
// this must mean that our besttag has been overwritten
tempbesttag = -1;
} else if (res == LFS2_CMP_GT &&
lfs2_tag_id(tag) <= lfs2_tag_id(tempbesttag)) {
// found a greater match, keep track to keep things sorted
tempbesttag = tag | 0x80000000;
}
}
}
// consider what we have good enough
if (dir->off > 0) {
// synthetic move
if (lfs2_gstate_hasmovehere(&lfs2->gdisk, dir->pair)) {
if (lfs2_tag_id(lfs2->gdisk.tag) == lfs2_tag_id(besttag)) {
besttag |= 0x80000000;
} else if (besttag != -1 &&
lfs2_tag_id(lfs2->gdisk.tag) < lfs2_tag_id(besttag)) {
besttag -= LFS2_MKTAG(0, 1, 0);
}
}
// found tag? or found best id?
if (id) {
*id = lfs2_min(lfs2_tag_id(besttag), dir->count);
}
if (lfs2_tag_isvalid(besttag)) {
return besttag;
} else if (lfs2_tag_id(besttag) < dir->count) {
return LFS2_ERR_NOENT;
} else {
return 0;
}
}
// failed, try the other block?
lfs2_pair_swap(dir->pair);
dir->rev = revs[(r+1)%2];
}
LFS2_ERROR("Corrupted dir pair at {0x%"PRIx32", 0x%"PRIx32"}",
dir->pair[0], dir->pair[1]);
return LFS2_ERR_CORRUPT;
}
static int lfs2_dir_fetch(lfs2_t *lfs2,
lfs2_mdir_t *dir, const lfs2_block_t pair[2]) {
// note, mask=-1, tag=-1 can never match a tag since this
// pattern has the invalid bit set
return (int)lfs2_dir_fetchmatch(lfs2, dir, pair,
(lfs2_tag_t)-1, (lfs2_tag_t)-1, NULL, NULL, NULL);
}
static int lfs2_dir_getgstate(lfs2_t *lfs2, const lfs2_mdir_t *dir,
lfs2_gstate_t *gstate) {
lfs2_gstate_t temp;
lfs2_stag_t res = lfs2_dir_get(lfs2, dir, LFS2_MKTAG(0x7ff, 0, 0),
LFS2_MKTAG(LFS2_TYPE_MOVESTATE, 0, sizeof(temp)), &temp);
if (res < 0 && res != LFS2_ERR_NOENT) {
return res;
}
if (res != LFS2_ERR_NOENT) {
// xor together to find resulting gstate
lfs2_gstate_fromle32(&temp);
lfs2_gstate_xor(gstate, &temp);
}
return 0;
}
static int lfs2_dir_getinfo(lfs2_t *lfs2, lfs2_mdir_t *dir,
uint16_t id, struct lfs2_info *info) {
if (id == 0x3ff) {
// special case for root
strcpy(info->name, "/");
info->type = LFS2_TYPE_DIR;
return 0;
}
lfs2_stag_t tag = lfs2_dir_get(lfs2, dir, LFS2_MKTAG(0x780, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_NAME, id, lfs2->name_max+1), info->name);
if (tag < 0) {
return (int)tag;
}
info->type = lfs2_tag_type3(tag);
struct lfs2_ctz ctz;
tag = lfs2_dir_get(lfs2, dir, LFS2_MKTAG(0x700, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, id, sizeof(ctz)), &ctz);
if (tag < 0) {
return (int)tag;
}
lfs2_ctz_fromle32(&ctz);
if (lfs2_tag_type3(tag) == LFS2_TYPE_CTZSTRUCT) {
info->size = ctz.size;
} else if (lfs2_tag_type3(tag) == LFS2_TYPE_INLINESTRUCT) {
info->size = lfs2_tag_size(tag);
}
return 0;
}
struct lfs2_dir_find_match {
lfs2_t *lfs2;
const void *name;
lfs2_size_t size;
};
static int lfs2_dir_find_match(void *data,
lfs2_tag_t tag, const void *buffer) {
struct lfs2_dir_find_match *name = data;
lfs2_t *lfs2 = name->lfs2;
const struct lfs2_diskoff *disk = buffer;
// compare with disk
lfs2_size_t diff = lfs2_min(name->size, lfs2_tag_size(tag));
int res = lfs2_bd_cmp(lfs2,
NULL, &lfs2->rcache, diff,
disk->block, disk->off, name->name, diff);
if (res != LFS2_CMP_EQ) {
return res;
}
// only equal if our size is still the same
if (name->size != lfs2_tag_size(tag)) {
return (name->size < lfs2_tag_size(tag)) ? LFS2_CMP_LT : LFS2_CMP_GT;
}
// found a match!
return LFS2_CMP_EQ;
}
static lfs2_stag_t lfs2_dir_find(lfs2_t *lfs2, lfs2_mdir_t *dir,
const char **path, uint16_t *id) {
// we reduce path to a single name if we can find it
const char *name = *path;
if (id) {
*id = 0x3ff;
}
// default to root dir
lfs2_stag_t tag = LFS2_MKTAG(LFS2_TYPE_DIR, 0x3ff, 0);
dir->tail[0] = lfs2->root[0];
dir->tail[1] = lfs2->root[1];
while (true) {
nextname:
// skip slashes
name += strspn(name, "/");
lfs2_size_t namelen = strcspn(name, "/");
// skip '.' and root '..'
if ((namelen == 1 && memcmp(name, ".", 1) == 0) ||
(namelen == 2 && memcmp(name, "..", 2) == 0)) {
name += namelen;
goto nextname;
}
// skip if matched by '..' in name
const char *suffix = name + namelen;
lfs2_size_t sufflen;
int depth = 1;
while (true) {
suffix += strspn(suffix, "/");
sufflen = strcspn(suffix, "/");
if (sufflen == 0) {
break;
}
if (sufflen == 2 && memcmp(suffix, "..", 2) == 0) {
depth -= 1;
if (depth == 0) {
name = suffix + sufflen;
goto nextname;
}
} else {
depth += 1;
}
suffix += sufflen;
}
// found path
if (name[0] == '\0') {
return tag;
}
// update what we've found so far
*path = name;
// only continue if we hit a directory
if (lfs2_tag_type3(tag) != LFS2_TYPE_DIR) {
return LFS2_ERR_NOTDIR;
}
// grab the entry data
if (lfs2_tag_id(tag) != 0x3ff) {
lfs2_stag_t res = lfs2_dir_get(lfs2, dir, LFS2_MKTAG(0x700, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, lfs2_tag_id(tag), 8), dir->tail);
if (res < 0) {
return res;
}
lfs2_pair_fromle32(dir->tail);
}
// find entry matching name
while (true) {
tag = lfs2_dir_fetchmatch(lfs2, dir, dir->tail,
LFS2_MKTAG(0x780, 0, 0),
LFS2_MKTAG(LFS2_TYPE_NAME, 0, namelen),
// are we last name?
(strchr(name, '/') == NULL) ? id : NULL,
lfs2_dir_find_match, &(struct lfs2_dir_find_match){
lfs2, name, namelen});
if (tag < 0) {
return tag;
}
if (tag) {
break;
}
if (!dir->split) {
return LFS2_ERR_NOENT;
}
}
// to next name
name += namelen;
}
}
// commit logic
struct lfs2_commit {
lfs2_block_t block;
lfs2_off_t off;
lfs2_tag_t ptag;
uint32_t crc;
lfs2_off_t begin;
lfs2_off_t end;
};
#ifndef LFS2_READONLY
static int lfs2_dir_commitprog(lfs2_t *lfs2, struct lfs2_commit *commit,
const void *buffer, lfs2_size_t size) {
int err = lfs2_bd_prog(lfs2,
&lfs2->pcache, &lfs2->rcache, false,
commit->block, commit->off ,
(const uint8_t*)buffer, size);
if (err) {
return err;
}
commit->crc = lfs2_crc(commit->crc, buffer, size);
commit->off += size;
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_commitattr(lfs2_t *lfs2, struct lfs2_commit *commit,
lfs2_tag_t tag, const void *buffer) {
// check if we fit
lfs2_size_t dsize = lfs2_tag_dsize(tag);
if (commit->off + dsize > commit->end) {
return LFS2_ERR_NOSPC;
}
// write out tag
lfs2_tag_t ntag = lfs2_tobe32((tag & 0x7fffffff) ^ commit->ptag);
int err = lfs2_dir_commitprog(lfs2, commit, &ntag, sizeof(ntag));
if (err) {
return err;
}
if (!(tag & 0x80000000)) {
// from memory
err = lfs2_dir_commitprog(lfs2, commit, buffer, dsize-sizeof(tag));
if (err) {
return err;
}
} else {
// from disk
const struct lfs2_diskoff *disk = buffer;
for (lfs2_off_t i = 0; i < dsize-sizeof(tag); i++) {
// rely on caching to make this efficient
uint8_t dat;
err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, dsize-sizeof(tag)-i,
disk->block, disk->off+i, &dat, 1);
if (err) {
return err;
}
err = lfs2_dir_commitprog(lfs2, commit, &dat, 1);
if (err) {
return err;
}
}
}
commit->ptag = tag & 0x7fffffff;
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_commitcrc(lfs2_t *lfs2, struct lfs2_commit *commit) {
// align to program units
const lfs2_off_t end = lfs2_alignup(commit->off + 2*sizeof(uint32_t),
lfs2->cfg->prog_size);
lfs2_off_t off1 = 0;
uint32_t crc1 = 0;
// create crc tags to fill up remainder of commit, note that
// padding is not crced, which lets fetches skip padding but
// makes committing a bit more complicated
while (commit->off < end) {
lfs2_off_t off = commit->off + sizeof(lfs2_tag_t);
lfs2_off_t noff = lfs2_min(end - off, 0x3fe) + off;
if (noff < end) {
noff = lfs2_min(noff, end - 2*sizeof(uint32_t));
}
// read erased state from next program unit
lfs2_tag_t tag = 0xffffffff;
int err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, sizeof(tag),
commit->block, noff, &tag, sizeof(tag));
if (err && err != LFS2_ERR_CORRUPT) {
return err;
}
// build crc tag
bool reset = ~lfs2_frombe32(tag) >> 31;
tag = LFS2_MKTAG(LFS2_TYPE_CRC + reset, 0x3ff, noff - off);
// write out crc
uint32_t footer[2];
footer[0] = lfs2_tobe32(tag ^ commit->ptag);
commit->crc = lfs2_crc(commit->crc, &footer[0], sizeof(footer[0]));
footer[1] = lfs2_tole32(commit->crc);
err = lfs2_bd_prog(lfs2,
&lfs2->pcache, &lfs2->rcache, false,
commit->block, commit->off, &footer, sizeof(footer));
if (err) {
return err;
}
// keep track of non-padding checksum to verify
if (off1 == 0) {
off1 = commit->off + sizeof(uint32_t);
crc1 = commit->crc;
}
commit->off += sizeof(tag)+lfs2_tag_size(tag);
commit->ptag = tag ^ ((lfs2_tag_t)reset << 31);
commit->crc = 0xffffffff; // reset crc for next "commit"
}
// flush buffers
int err = lfs2_bd_sync(lfs2, &lfs2->pcache, &lfs2->rcache, false);
if (err) {
return err;
}
// successful commit, check checksums to make sure
lfs2_off_t off = commit->begin;
lfs2_off_t noff = off1;
while (off < end) {
uint32_t crc = 0xffffffff;
for (lfs2_off_t i = off; i < noff+sizeof(uint32_t); i++) {
// check against written crc, may catch blocks that
// become readonly and match our commit size exactly
if (i == off1 && crc != crc1) {
return LFS2_ERR_CORRUPT;
}
// leave it up to caching to make this efficient
uint8_t dat;
err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, noff+sizeof(uint32_t)-i,
commit->block, i, &dat, 1);
if (err) {
return err;
}
crc = lfs2_crc(crc, &dat, 1);
}
// detected write error?
if (crc != 0) {
return LFS2_ERR_CORRUPT;
}
// skip padding
off = lfs2_min(end - noff, 0x3fe) + noff;
if (off < end) {
off = lfs2_min(off, end - 2*sizeof(uint32_t));
}
noff = off + sizeof(uint32_t);
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_alloc(lfs2_t *lfs2, lfs2_mdir_t *dir) {
// allocate pair of dir blocks (backwards, so we write block 1 first)
for (int i = 0; i < 2; i++) {
int err = lfs2_alloc(lfs2, &dir->pair[(i+1)%2]);
if (err) {
return err;
}
}
// zero for reproducability in case initial block is unreadable
dir->rev = 0;
// rather than clobbering one of the blocks we just pretend
// the revision may be valid
int err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, sizeof(dir->rev),
dir->pair[0], 0, &dir->rev, sizeof(dir->rev));
dir->rev = lfs2_fromle32(dir->rev);
if (err && err != LFS2_ERR_CORRUPT) {
return err;
}
// to make sure we don't immediately evict, align the new revision count
// to our block_cycles modulus, see lfs2_dir_compact for why our modulus
// is tweaked this way
if (lfs2->cfg->block_cycles > 0) {
dir->rev = lfs2_alignup(dir->rev, ((lfs2->cfg->block_cycles+1)|1));
}
// set defaults
dir->off = sizeof(dir->rev);
dir->etag = 0xffffffff;
dir->count = 0;
dir->tail[0] = LFS2_BLOCK_NULL;
dir->tail[1] = LFS2_BLOCK_NULL;
dir->erased = false;
dir->split = false;
// don't write out yet, let caller take care of that
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_drop(lfs2_t *lfs2, lfs2_mdir_t *dir, lfs2_mdir_t *tail) {
// steal state
int err = lfs2_dir_getgstate(lfs2, tail, &lfs2->gdelta);
if (err) {
return err;
}
// steal tail
lfs2_pair_tole32(tail->tail);
err = lfs2_dir_commit(lfs2, dir, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_TAIL + tail->split, 0x3ff, 8), tail->tail}));
lfs2_pair_fromle32(tail->tail);
if (err) {
return err;
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_split(lfs2_t *lfs2,
lfs2_mdir_t *dir, const struct lfs2_mattr *attrs, int attrcount,
lfs2_mdir_t *source, uint16_t split, uint16_t end) {
// create tail directory
lfs2_alloc_ack(lfs2);
lfs2_mdir_t tail;
int err = lfs2_dir_alloc(lfs2, &tail);
if (err) {
return err;
}
tail.split = dir->split;
tail.tail[0] = dir->tail[0];
tail.tail[1] = dir->tail[1];
err = lfs2_dir_compact(lfs2, &tail, attrs, attrcount, source, split, end);
if (err) {
return err;
}
dir->tail[0] = tail.pair[0];
dir->tail[1] = tail.pair[1];
dir->split = true;
// update root if needed
if (lfs2_pair_cmp(dir->pair, lfs2->root) == 0 && split == 0) {
lfs2->root[0] = tail.pair[0];
lfs2->root[1] = tail.pair[1];
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_commit_size(void *p, lfs2_tag_t tag, const void *buffer) {
lfs2_size_t *size = p;
(void)buffer;
*size += lfs2_tag_dsize(tag);
return 0;
}
#endif
#ifndef LFS2_READONLY
struct lfs2_dir_commit_commit {
lfs2_t *lfs2;
struct lfs2_commit *commit;
};
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_commit_commit(void *p, lfs2_tag_t tag, const void *buffer) {
struct lfs2_dir_commit_commit *commit = p;
return lfs2_dir_commitattr(commit->lfs2, commit->commit, tag, buffer);
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_compact(lfs2_t *lfs2,
lfs2_mdir_t *dir, const struct lfs2_mattr *attrs, int attrcount,
lfs2_mdir_t *source, uint16_t begin, uint16_t end) {
// save some state in case block is bad
const lfs2_block_t oldpair[2] = {dir->pair[0], dir->pair[1]};
bool relocated = false;
bool tired = false;
// should we split?
while (end - begin > 1) {
// find size
lfs2_size_t size = 0;
int err = lfs2_dir_traverse(lfs2,
source, 0, 0xffffffff, attrs, attrcount,
LFS2_MKTAG(0x400, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_NAME, 0, 0),
begin, end, -begin,
lfs2_dir_commit_size, &size);
if (err) {
return err;
}
// space is complicated, we need room for tail, crc, gstate,
// cleanup delete, and we cap at half a block to give room
// for metadata updates.
if (end - begin < 0xff &&
size <= lfs2_min(lfs2->cfg->block_size - 36,
lfs2_alignup(lfs2->cfg->block_size/2,
lfs2->cfg->prog_size))) {
break;
}
// can't fit, need to split, we should really be finding the
// largest size that fits with a small binary search, but right now
// it's not worth the code size
uint16_t split = (end - begin) / 2;
err = lfs2_dir_split(lfs2, dir, attrs, attrcount,
source, begin+split, end);
if (err) {
// if we fail to split, we may be able to overcompact, unless
// we're too big for even the full block, in which case our
// only option is to error
if (err == LFS2_ERR_NOSPC && size <= lfs2->cfg->block_size - 36) {
break;
}
return err;
}
end = begin + split;
}
// increment revision count
dir->rev += 1;
// If our revision count == n * block_cycles, we should force a relocation,
// this is how littlefs wear-levels at the metadata-pair level. Note that we
// actually use (block_cycles+1)|1, this is to avoid two corner cases:
// 1. block_cycles = 1, which would prevent relocations from terminating
// 2. block_cycles = 2n, which, due to aliasing, would only ever relocate
// one metadata block in the pair, effectively making this useless
if (lfs2->cfg->block_cycles > 0 &&
(dir->rev % ((lfs2->cfg->block_cycles+1)|1) == 0)) {
if (lfs2_pair_cmp(dir->pair, (const lfs2_block_t[2]){0, 1}) == 0) {
// oh no! we're writing too much to the superblock,
// should we expand?
lfs2_ssize_t res = lfs2_fs_rawsize(lfs2);
if (res < 0) {
return res;
}
// do we have extra space? littlefs can't reclaim this space
// by itself, so expand cautiously
if ((lfs2_size_t)res < lfs2->cfg->block_count/2) {
LFS2_DEBUG("Expanding superblock at rev %"PRIu32, dir->rev);
int err = lfs2_dir_split(lfs2, dir, attrs, attrcount,
source, begin, end);
if (err && err != LFS2_ERR_NOSPC) {
return err;
}
// welp, we tried, if we ran out of space there's not much
// we can do, we'll error later if we've become frozen
if (!err) {
end = begin;
}
}
#ifdef LFS2_MIGRATE
} else if (lfs2->lfs21) {
// do not proactively relocate blocks during migrations, this
// can cause a number of failure states such: clobbering the
// v1 superblock if we relocate root, and invalidating directory
// pointers if we relocate the head of a directory. On top of
// this, relocations increase the overall complexity of
// lfs2_migration, which is already a delicate operation.
#endif
} else {
// we're writing too much, time to relocate
tired = true;
goto relocate;
}
}
// begin loop to commit compaction to blocks until a compact sticks
while (true) {
{
// setup commit state
struct lfs2_commit commit = {
.block = dir->pair[1],
.off = 0,
.ptag = 0xffffffff,
.crc = 0xffffffff,
.begin = 0,
.end = lfs2->cfg->block_size - 8,
};
// erase block to write to
int err = lfs2_bd_erase(lfs2, dir->pair[1]);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
// write out header
dir->rev = lfs2_tole32(dir->rev);
err = lfs2_dir_commitprog(lfs2, &commit,
&dir->rev, sizeof(dir->rev));
dir->rev = lfs2_fromle32(dir->rev);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
// traverse the directory, this time writing out all unique tags
err = lfs2_dir_traverse(lfs2,
source, 0, 0xffffffff, attrs, attrcount,
LFS2_MKTAG(0x400, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_NAME, 0, 0),
begin, end, -begin,
lfs2_dir_commit_commit, &(struct lfs2_dir_commit_commit){
lfs2, &commit});
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
// commit tail, which may be new after last size check
if (!lfs2_pair_isnull(dir->tail)) {
lfs2_pair_tole32(dir->tail);
err = lfs2_dir_commitattr(lfs2, &commit,
LFS2_MKTAG(LFS2_TYPE_TAIL + dir->split, 0x3ff, 8),
dir->tail);
lfs2_pair_fromle32(dir->tail);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
}
// bring over gstate?
lfs2_gstate_t delta = {0};
if (!relocated) {
lfs2_gstate_xor(&delta, &lfs2->gdisk);
lfs2_gstate_xor(&delta, &lfs2->gstate);
}
lfs2_gstate_xor(&delta, &lfs2->gdelta);
delta.tag &= ~LFS2_MKTAG(0, 0, 0x3ff);
err = lfs2_dir_getgstate(lfs2, dir, &delta);
if (err) {
return err;
}
if (!lfs2_gstate_iszero(&delta)) {
lfs2_gstate_tole32(&delta);
err = lfs2_dir_commitattr(lfs2, &commit,
LFS2_MKTAG(LFS2_TYPE_MOVESTATE, 0x3ff,
sizeof(delta)), &delta);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
}
// complete commit with crc
err = lfs2_dir_commitcrc(lfs2, &commit);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
// successful compaction, swap dir pair to indicate most recent
LFS2_ASSERT(commit.off % lfs2->cfg->prog_size == 0);
lfs2_pair_swap(dir->pair);
dir->count = end - begin;
dir->off = commit.off;
dir->etag = commit.ptag;
// update gstate
lfs2->gdelta = (lfs2_gstate_t){0};
if (!relocated) {
lfs2->gdisk = lfs2->gstate;
}
}
break;
relocate:
// commit was corrupted, drop caches and prepare to relocate block
relocated = true;
lfs2_cache_drop(lfs2, &lfs2->pcache);
if (!tired) {
LFS2_DEBUG("Bad block at 0x%"PRIx32, dir->pair[1]);
}
// can't relocate superblock, filesystem is now frozen
if (lfs2_pair_cmp(dir->pair, (const lfs2_block_t[2]){0, 1}) == 0) {
LFS2_WARN("Superblock 0x%"PRIx32" has become unwritable",
dir->pair[1]);
return LFS2_ERR_NOSPC;
}
// relocate half of pair
int err = lfs2_alloc(lfs2, &dir->pair[1]);
if (err && (err != LFS2_ERR_NOSPC || !tired)) {
return err;
}
tired = false;
continue;
}
if (relocated) {
// update references if we relocated
LFS2_DEBUG("Relocating {0x%"PRIx32", 0x%"PRIx32"} "
"-> {0x%"PRIx32", 0x%"PRIx32"}",
oldpair[0], oldpair[1], dir->pair[0], dir->pair[1]);
int err = lfs2_fs_relocate(lfs2, oldpair, dir->pair);
if (err) {
return err;
}
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_dir_commit(lfs2_t *lfs2, lfs2_mdir_t *dir,
const struct lfs2_mattr *attrs, int attrcount) {
// check for any inline files that aren't RAM backed and
// forcefully evict them, needed for filesystem consistency
for (lfs2_file_t *f = (lfs2_file_t*)lfs2->mlist; f; f = f->next) {
if (dir != &f->m && lfs2_pair_cmp(f->m.pair, dir->pair) == 0 &&
f->type == LFS2_TYPE_REG && (f->flags & LFS2_F_INLINE) &&
f->ctz.size > lfs2->cfg->cache_size) {
int err = lfs2_file_outline(lfs2, f);
if (err) {
return err;
}
err = lfs2_file_flush(lfs2, f);
if (err) {
return err;
}
}
}
// calculate changes to the directory
lfs2_mdir_t olddir = *dir;
bool hasdelete = false;
for (int i = 0; i < attrcount; i++) {
if (lfs2_tag_type3(attrs[i].tag) == LFS2_TYPE_CREATE) {
dir->count += 1;
} else if (lfs2_tag_type3(attrs[i].tag) == LFS2_TYPE_DELETE) {
LFS2_ASSERT(dir->count > 0);
dir->count -= 1;
hasdelete = true;
} else if (lfs2_tag_type1(attrs[i].tag) == LFS2_TYPE_TAIL) {
dir->tail[0] = ((lfs2_block_t*)attrs[i].buffer)[0];
dir->tail[1] = ((lfs2_block_t*)attrs[i].buffer)[1];
dir->split = (lfs2_tag_chunk(attrs[i].tag) & 1);
lfs2_pair_fromle32(dir->tail);
}
}
// should we actually drop the directory block?
if (hasdelete && dir->count == 0) {
lfs2_mdir_t pdir;
int err = lfs2_fs_pred(lfs2, dir->pair, &pdir);
if (err && err != LFS2_ERR_NOENT) {
*dir = olddir;
return err;
}
if (err != LFS2_ERR_NOENT && pdir.split) {
err = lfs2_dir_drop(lfs2, &pdir, dir);
if (err) {
*dir = olddir;
return err;
}
}
}
if (dir->erased || dir->count >= 0xff) {
// try to commit
struct lfs2_commit commit = {
.block = dir->pair[0],
.off = dir->off,
.ptag = dir->etag,
.crc = 0xffffffff,
.begin = dir->off,
.end = lfs2->cfg->block_size - 8,
};
// traverse attrs that need to be written out
lfs2_pair_tole32(dir->tail);
int err = lfs2_dir_traverse(lfs2,
dir, dir->off, dir->etag, attrs, attrcount,
0, 0, 0, 0, 0,
lfs2_dir_commit_commit, &(struct lfs2_dir_commit_commit){
lfs2, &commit});
lfs2_pair_fromle32(dir->tail);
if (err) {
if (err == LFS2_ERR_NOSPC || err == LFS2_ERR_CORRUPT) {
goto compact;
}
*dir = olddir;
return err;
}
// commit any global diffs if we have any
lfs2_gstate_t delta = {0};
lfs2_gstate_xor(&delta, &lfs2->gstate);
lfs2_gstate_xor(&delta, &lfs2->gdisk);
lfs2_gstate_xor(&delta, &lfs2->gdelta);
delta.tag &= ~LFS2_MKTAG(0, 0, 0x3ff);
if (!lfs2_gstate_iszero(&delta)) {
err = lfs2_dir_getgstate(lfs2, dir, &delta);
if (err) {
*dir = olddir;
return err;
}
lfs2_gstate_tole32(&delta);
err = lfs2_dir_commitattr(lfs2, &commit,
LFS2_MKTAG(LFS2_TYPE_MOVESTATE, 0x3ff,
sizeof(delta)), &delta);
if (err) {
if (err == LFS2_ERR_NOSPC || err == LFS2_ERR_CORRUPT) {
goto compact;
}
*dir = olddir;
return err;
}
}
// finalize commit with the crc
err = lfs2_dir_commitcrc(lfs2, &commit);
if (err) {
if (err == LFS2_ERR_NOSPC || err == LFS2_ERR_CORRUPT) {
goto compact;
}
*dir = olddir;
return err;
}
// successful commit, update dir
LFS2_ASSERT(commit.off % lfs2->cfg->prog_size == 0);
dir->off = commit.off;
dir->etag = commit.ptag;
// and update gstate
lfs2->gdisk = lfs2->gstate;
lfs2->gdelta = (lfs2_gstate_t){0};
} else {
compact:
// fall back to compaction
lfs2_cache_drop(lfs2, &lfs2->pcache);
int err = lfs2_dir_compact(lfs2, dir, attrs, attrcount,
dir, 0, dir->count);
if (err) {
*dir = olddir;
return err;
}
}
// this complicated bit of logic is for fixing up any active
// metadata-pairs that we may have affected
//
// note we have to make two passes since the mdir passed to
// lfs2_dir_commit could also be in this list, and even then
// we need to copy the pair so they don't get clobbered if we refetch
// our mdir.
for (struct lfs2_mlist *d = lfs2->mlist; d; d = d->next) {
if (&d->m != dir && lfs2_pair_cmp(d->m.pair, olddir.pair) == 0) {
d->m = *dir;
for (int i = 0; i < attrcount; i++) {
if (lfs2_tag_type3(attrs[i].tag) == LFS2_TYPE_DELETE &&
d->id == lfs2_tag_id(attrs[i].tag)) {
d->m.pair[0] = LFS2_BLOCK_NULL;
d->m.pair[1] = LFS2_BLOCK_NULL;
} else if (lfs2_tag_type3(attrs[i].tag) == LFS2_TYPE_DELETE &&
d->id > lfs2_tag_id(attrs[i].tag)) {
d->id -= 1;
if (d->type == LFS2_TYPE_DIR) {
((lfs2_dir_t*)d)->pos -= 1;
}
} else if (lfs2_tag_type3(attrs[i].tag) == LFS2_TYPE_CREATE &&
d->id >= lfs2_tag_id(attrs[i].tag)) {
d->id += 1;
if (d->type == LFS2_TYPE_DIR) {
((lfs2_dir_t*)d)->pos += 1;
}
}
}
}
}
for (struct lfs2_mlist *d = lfs2->mlist; d; d = d->next) {
if (lfs2_pair_cmp(d->m.pair, olddir.pair) == 0) {
while (d->id >= d->m.count && d->m.split) {
// we split and id is on tail now
d->id -= d->m.count;
int err = lfs2_dir_fetch(lfs2, &d->m, d->m.tail);
if (err) {
return err;
}
}
}
}
return 0;
}
#endif
/// Top level directory operations ///
#ifndef LFS2_READONLY
static int lfs2_rawmkdir(lfs2_t *lfs2, const char *path) {
// deorphan if we haven't yet, needed at most once after poweron
int err = lfs2_fs_forceconsistency(lfs2);
if (err) {
return err;
}
struct lfs2_mlist cwd;
cwd.next = lfs2->mlist;
uint16_t id;
err = lfs2_dir_find(lfs2, &cwd.m, &path, &id);
if (!(err == LFS2_ERR_NOENT && id != 0x3ff)) {
return (err < 0) ? err : LFS2_ERR_EXIST;
}
// check that name fits
lfs2_size_t nlen = strlen(path);
if (nlen > lfs2->name_max) {
return LFS2_ERR_NAMETOOLONG;
}
// build up new directory
lfs2_alloc_ack(lfs2);
lfs2_mdir_t dir;
err = lfs2_dir_alloc(lfs2, &dir);
if (err) {
return err;
}
// find end of list
lfs2_mdir_t pred = cwd.m;
while (pred.split) {
err = lfs2_dir_fetch(lfs2, &pred, pred.tail);
if (err) {
return err;
}
}
// setup dir
lfs2_pair_tole32(pred.tail);
err = lfs2_dir_commit(lfs2, &dir, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_SOFTTAIL, 0x3ff, 8), pred.tail}));
lfs2_pair_fromle32(pred.tail);
if (err) {
return err;
}
// current block end of list?
if (cwd.m.split) {
// update tails, this creates a desync
lfs2_fs_preporphans(lfs2, +1);
// it's possible our predecessor has to be relocated, and if
// our parent is our predecessor's predecessor, this could have
// caused our parent to go out of date, fortunately we can hook
// ourselves into littlefs to catch this
cwd.type = 0;
cwd.id = 0;
lfs2->mlist = &cwd;
lfs2_pair_tole32(dir.pair);
err = lfs2_dir_commit(lfs2, &pred, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_SOFTTAIL, 0x3ff, 8), dir.pair}));
lfs2_pair_fromle32(dir.pair);
if (err) {
lfs2->mlist = cwd.next;
return err;
}
lfs2->mlist = cwd.next;
lfs2_fs_preporphans(lfs2, -1);
}
// now insert into our parent block
lfs2_pair_tole32(dir.pair);
err = lfs2_dir_commit(lfs2, &cwd.m, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_CREATE, id, 0), NULL},
{LFS2_MKTAG(LFS2_TYPE_DIR, id, nlen), path},
{LFS2_MKTAG(LFS2_TYPE_DIRSTRUCT, id, 8), dir.pair},
{LFS2_MKTAG_IF(!cwd.m.split,
LFS2_TYPE_SOFTTAIL, 0x3ff, 8), dir.pair}));
lfs2_pair_fromle32(dir.pair);
if (err) {
return err;
}
return 0;
}
#endif
static int lfs2_dir_rawopen(lfs2_t *lfs2, lfs2_dir_t *dir, const char *path) {
lfs2_stag_t tag = lfs2_dir_find(lfs2, &dir->m, &path, NULL);
if (tag < 0) {
return tag;
}
if (lfs2_tag_type3(tag) != LFS2_TYPE_DIR) {
return LFS2_ERR_NOTDIR;
}
lfs2_block_t pair[2];
if (lfs2_tag_id(tag) == 0x3ff) {
// handle root dir separately
pair[0] = lfs2->root[0];
pair[1] = lfs2->root[1];
} else {
// get dir pair from parent
lfs2_stag_t res = lfs2_dir_get(lfs2, &dir->m, LFS2_MKTAG(0x700, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, lfs2_tag_id(tag), 8), pair);
if (res < 0) {
return res;
}
lfs2_pair_fromle32(pair);
}
// fetch first pair
int err = lfs2_dir_fetch(lfs2, &dir->m, pair);
if (err) {
return err;
}
// setup entry
dir->head[0] = dir->m.pair[0];
dir->head[1] = dir->m.pair[1];
dir->id = 0;
dir->pos = 0;
// add to list of mdirs
dir->type = LFS2_TYPE_DIR;
lfs2_mlist_append(lfs2, (struct lfs2_mlist *)dir);
return 0;
}
static int lfs2_dir_rawclose(lfs2_t *lfs2, lfs2_dir_t *dir) {
// remove from list of mdirs
lfs2_mlist_remove(lfs2, (struct lfs2_mlist *)dir);
return 0;
}
static int lfs2_dir_rawread(lfs2_t *lfs2, lfs2_dir_t *dir, struct lfs2_info *info) {
memset(info, 0, sizeof(*info));
// special offset for '.' and '..'
if (dir->pos == 0) {
info->type = LFS2_TYPE_DIR;
strcpy(info->name, ".");
dir->pos += 1;
return true;
} else if (dir->pos == 1) {
info->type = LFS2_TYPE_DIR;
strcpy(info->name, "..");
dir->pos += 1;
return true;
}
while (true) {
if (dir->id == dir->m.count) {
if (!dir->m.split) {
return false;
}
int err = lfs2_dir_fetch(lfs2, &dir->m, dir->m.tail);
if (err) {
return err;
}
dir->id = 0;
}
int err = lfs2_dir_getinfo(lfs2, &dir->m, dir->id, info);
if (err && err != LFS2_ERR_NOENT) {
return err;
}
dir->id += 1;
if (err != LFS2_ERR_NOENT) {
break;
}
}
dir->pos += 1;
return true;
}
static int lfs2_dir_rawseek(lfs2_t *lfs2, lfs2_dir_t *dir, lfs2_off_t off) {
// simply walk from head dir
int err = lfs2_dir_rawrewind(lfs2, dir);
if (err) {
return err;
}
// first two for ./..
dir->pos = lfs2_min(2, off);
off -= dir->pos;
// skip superblock entry
dir->id = (off > 0 && lfs2_pair_cmp(dir->head, lfs2->root) == 0);
while (off > 0) {
int diff = lfs2_min(dir->m.count - dir->id, off);
dir->id += diff;
dir->pos += diff;
off -= diff;
if (dir->id == dir->m.count) {
if (!dir->m.split) {
return LFS2_ERR_INVAL;
}
err = lfs2_dir_fetch(lfs2, &dir->m, dir->m.tail);
if (err) {
return err;
}
dir->id = 0;
}
}
return 0;
}
static lfs2_soff_t lfs2_dir_rawtell(lfs2_t *lfs2, lfs2_dir_t *dir) {
(void)lfs2;
return dir->pos;
}
static int lfs2_dir_rawrewind(lfs2_t *lfs2, lfs2_dir_t *dir) {
// reload the head dir
int err = lfs2_dir_fetch(lfs2, &dir->m, dir->head);
if (err) {
return err;
}
dir->id = 0;
dir->pos = 0;
return 0;
}
/// File index list operations ///
static int lfs2_ctz_index(lfs2_t *lfs2, lfs2_off_t *off) {
lfs2_off_t size = *off;
lfs2_off_t b = lfs2->cfg->block_size - 2*4;
lfs2_off_t i = size / b;
if (i == 0) {
return 0;
}
i = (size - 4*(lfs2_popc(i-1)+2)) / b;
*off = size - b*i - 4*lfs2_popc(i);
return i;
}
static int lfs2_ctz_find(lfs2_t *lfs2,
const lfs2_cache_t *pcache, lfs2_cache_t *rcache,
lfs2_block_t head, lfs2_size_t size,
lfs2_size_t pos, lfs2_block_t *block, lfs2_off_t *off) {
if (size == 0) {
*block = LFS2_BLOCK_NULL;
*off = 0;
return 0;
}
lfs2_off_t current = lfs2_ctz_index(lfs2, &(lfs2_off_t){size-1});
lfs2_off_t target = lfs2_ctz_index(lfs2, &pos);
while (current > target) {
lfs2_size_t skip = lfs2_min(
lfs2_npw2(current-target+1) - 1,
lfs2_ctz(current));
int err = lfs2_bd_read(lfs2,
pcache, rcache, sizeof(head),
head, 4*skip, &head, sizeof(head));
head = lfs2_fromle32(head);
if (err) {
return err;
}
current -= 1 << skip;
}
*block = head;
*off = pos;
return 0;
}
#ifndef LFS2_READONLY
static int lfs2_ctz_extend(lfs2_t *lfs2,
lfs2_cache_t *pcache, lfs2_cache_t *rcache,
lfs2_block_t head, lfs2_size_t size,
lfs2_block_t *block, lfs2_off_t *off) {
while (true) {
// go ahead and grab a block
lfs2_block_t nblock;
int err = lfs2_alloc(lfs2, &nblock);
if (err) {
return err;
}
{
err = lfs2_bd_erase(lfs2, nblock);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
if (size == 0) {
*block = nblock;
*off = 0;
return 0;
}
lfs2_size_t noff = size - 1;
lfs2_off_t index = lfs2_ctz_index(lfs2, &noff);
noff = noff + 1;
// just copy out the last block if it is incomplete
if (noff != lfs2->cfg->block_size) {
for (lfs2_off_t i = 0; i < noff; i++) {
uint8_t data;
err = lfs2_bd_read(lfs2,
NULL, rcache, noff-i,
head, i, &data, 1);
if (err) {
return err;
}
err = lfs2_bd_prog(lfs2,
pcache, rcache, true,
nblock, i, &data, 1);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
}
*block = nblock;
*off = noff;
return 0;
}
// append block
index += 1;
lfs2_size_t skips = lfs2_ctz(index) + 1;
lfs2_block_t nhead = head;
for (lfs2_off_t i = 0; i < skips; i++) {
nhead = lfs2_tole32(nhead);
err = lfs2_bd_prog(lfs2, pcache, rcache, true,
nblock, 4*i, &nhead, 4);
nhead = lfs2_fromle32(nhead);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
if (i != skips-1) {
err = lfs2_bd_read(lfs2,
NULL, rcache, sizeof(nhead),
nhead, 4*i, &nhead, sizeof(nhead));
nhead = lfs2_fromle32(nhead);
if (err) {
return err;
}
}
}
*block = nblock;
*off = 4*skips;
return 0;
}
relocate:
LFS2_DEBUG("Bad block at 0x%"PRIx32, nblock);
// just clear cache and try a new block
lfs2_cache_drop(lfs2, pcache);
}
}
#endif
static int lfs2_ctz_traverse(lfs2_t *lfs2,
const lfs2_cache_t *pcache, lfs2_cache_t *rcache,
lfs2_block_t head, lfs2_size_t size,
int (*cb)(void*, lfs2_block_t), void *data) {
if (size == 0) {
return 0;
}
lfs2_off_t index = lfs2_ctz_index(lfs2, &(lfs2_off_t){size-1});
while (true) {
int err = cb(data, head);
if (err) {
return err;
}
if (index == 0) {
return 0;
}
lfs2_block_t heads[2];
int count = 2 - (index & 1);
err = lfs2_bd_read(lfs2,
pcache, rcache, count*sizeof(head),
head, 0, &heads, count*sizeof(head));
heads[0] = lfs2_fromle32(heads[0]);
heads[1] = lfs2_fromle32(heads[1]);
if (err) {
return err;
}
for (int i = 0; i < count-1; i++) {
err = cb(data, heads[i]);
if (err) {
return err;
}
}
head = heads[count-1];
index -= count;
}
}
/// Top level file operations ///
static int lfs2_file_rawopencfg(lfs2_t *lfs2, lfs2_file_t *file,
const char *path, int flags,
const struct lfs2_file_config *cfg) {
#ifndef LFS2_READONLY
// deorphan if we haven't yet, needed at most once after poweron
if ((flags & LFS2_O_WRONLY) == LFS2_O_WRONLY) {
int err = lfs2_fs_forceconsistency(lfs2);
if (err) {
return err;
}
}
#else
LFS2_ASSERT((flags & LFS2_O_RDONLY) == LFS2_O_RDONLY);
#endif
// setup simple file details
int err;
file->cfg = cfg;
file->flags = flags;
file->pos = 0;
file->off = 0;
file->cache.buffer = NULL;
// allocate entry for file if it doesn't exist
lfs2_stag_t tag = lfs2_dir_find(lfs2, &file->m, &path, &file->id);
if (tag < 0 && !(tag == LFS2_ERR_NOENT && file->id != 0x3ff)) {
err = tag;
goto cleanup;
}
// get id, add to list of mdirs to catch update changes
file->type = LFS2_TYPE_REG;
lfs2_mlist_append(lfs2, (struct lfs2_mlist *)file);
#ifdef LFS2_READONLY
if (tag == LFS2_ERR_NOENT) {
err = LFS2_ERR_NOENT;
goto cleanup;
#else
if (tag == LFS2_ERR_NOENT) {
if (!(flags & LFS2_O_CREAT)) {
err = LFS2_ERR_NOENT;
goto cleanup;
}
// check that name fits
lfs2_size_t nlen = strlen(path);
if (nlen > lfs2->name_max) {
err = LFS2_ERR_NAMETOOLONG;
goto cleanup;
}
// get next slot and create entry to remember name
err = lfs2_dir_commit(lfs2, &file->m, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_CREATE, file->id, 0), NULL},
{LFS2_MKTAG(LFS2_TYPE_REG, file->id, nlen), path},
{LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, file->id, 0), NULL}));
if (err) {
err = LFS2_ERR_NAMETOOLONG;
goto cleanup;
}
tag = LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, 0, 0);
} else if (flags & LFS2_O_EXCL) {
err = LFS2_ERR_EXIST;
goto cleanup;
#endif
} else if (lfs2_tag_type3(tag) != LFS2_TYPE_REG) {
err = LFS2_ERR_ISDIR;
goto cleanup;
#ifndef LFS2_READONLY
} else if (flags & LFS2_O_TRUNC) {
// truncate if requested
tag = LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, file->id, 0);
file->flags |= LFS2_F_DIRTY;
#endif
} else {
// try to load what's on disk, if it's inlined we'll fix it later
tag = lfs2_dir_get(lfs2, &file->m, LFS2_MKTAG(0x700, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, file->id, 8), &file->ctz);
if (tag < 0) {
err = tag;
goto cleanup;
}
lfs2_ctz_fromle32(&file->ctz);
}
// fetch attrs
for (unsigned i = 0; i < file->cfg->attr_count; i++) {
// if opened for read / read-write operations
if ((file->flags & LFS2_O_RDONLY) == LFS2_O_RDONLY) {
lfs2_stag_t res = lfs2_dir_get(lfs2, &file->m,
LFS2_MKTAG(0x7ff, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_USERATTR + file->cfg->attrs[i].type,
file->id, file->cfg->attrs[i].size),
file->cfg->attrs[i].buffer);
if (res < 0 && res != LFS2_ERR_NOENT) {
err = res;
goto cleanup;
}
}
#ifndef LFS2_READONLY
// if opened for write / read-write operations
if ((file->flags & LFS2_O_WRONLY) == LFS2_O_WRONLY) {
if (file->cfg->attrs[i].size > lfs2->attr_max) {
err = LFS2_ERR_NOSPC;
goto cleanup;
}
file->flags |= LFS2_F_DIRTY;
}
#endif
}
// allocate buffer if needed
if (file->cfg->buffer) {
file->cache.buffer = file->cfg->buffer;
} else {
file->cache.buffer = lfs2_malloc(lfs2->cfg->cache_size);
if (!file->cache.buffer) {
err = LFS2_ERR_NOMEM;
goto cleanup;
}
}
// zero to avoid information leak
lfs2_cache_zero(lfs2, &file->cache);
if (lfs2_tag_type3(tag) == LFS2_TYPE_INLINESTRUCT) {
// load inline files
file->ctz.head = LFS2_BLOCK_INLINE;
file->ctz.size = lfs2_tag_size(tag);
file->flags |= LFS2_F_INLINE;
file->cache.block = file->ctz.head;
file->cache.off = 0;
file->cache.size = lfs2->cfg->cache_size;
// don't always read (may be new/trunc file)
if (file->ctz.size > 0) {
lfs2_stag_t res = lfs2_dir_get(lfs2, &file->m,
LFS2_MKTAG(0x700, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, file->id,
lfs2_min(file->cache.size, 0x3fe)),
file->cache.buffer);
if (res < 0) {
err = res;
goto cleanup;
}
}
}
return 0;
cleanup:
// clean up lingering resources
#ifndef LFS2_READONLY
file->flags |= LFS2_F_ERRED;
#endif
lfs2_file_rawclose(lfs2, file);
return err;
}
static int lfs2_file_rawopen(lfs2_t *lfs2, lfs2_file_t *file,
const char *path, int flags) {
static const struct lfs2_file_config defaults = {0};
int err = lfs2_file_rawopencfg(lfs2, file, path, flags, &defaults);
return err;
}
static int lfs2_file_rawclose(lfs2_t *lfs2, lfs2_file_t *file) {
#ifndef LFS2_READONLY
int err = lfs2_file_rawsync(lfs2, file);
#else
int err = 0;
#endif
// remove from list of mdirs
lfs2_mlist_remove(lfs2, (struct lfs2_mlist*)file);
// clean up memory
if (!file->cfg->buffer) {
lfs2_free(file->cache.buffer);
}
return err;
}
#ifndef LFS2_READONLY
static int lfs2_file_relocate(lfs2_t *lfs2, lfs2_file_t *file) {
while (true) {
// just relocate what exists into new block
lfs2_block_t nblock;
int err = lfs2_alloc(lfs2, &nblock);
if (err) {
return err;
}
err = lfs2_bd_erase(lfs2, nblock);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
// either read from dirty cache or disk
for (lfs2_off_t i = 0; i < file->off; i++) {
uint8_t data;
if (file->flags & LFS2_F_INLINE) {
err = lfs2_dir_getread(lfs2, &file->m,
// note we evict inline files before they can be dirty
NULL, &file->cache, file->off-i,
LFS2_MKTAG(0xfff, 0x1ff, 0),
LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, file->id, 0),
i, &data, 1);
if (err) {
return err;
}
} else {
err = lfs2_bd_read(lfs2,
&file->cache, &lfs2->rcache, file->off-i,
file->block, i, &data, 1);
if (err) {
return err;
}
}
err = lfs2_bd_prog(lfs2,
&lfs2->pcache, &lfs2->rcache, true,
nblock, i, &data, 1);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
}
// copy over new state of file
memcpy(file->cache.buffer, lfs2->pcache.buffer, lfs2->cfg->cache_size);
file->cache.block = lfs2->pcache.block;
file->cache.off = lfs2->pcache.off;
file->cache.size = lfs2->pcache.size;
lfs2_cache_zero(lfs2, &lfs2->pcache);
file->block = nblock;
file->flags |= LFS2_F_WRITING;
return 0;
relocate:
LFS2_DEBUG("Bad block at 0x%"PRIx32, nblock);
// just clear cache and try a new block
lfs2_cache_drop(lfs2, &lfs2->pcache);
}
}
#endif
#ifndef LFS2_READONLY
static int lfs2_file_outline(lfs2_t *lfs2, lfs2_file_t *file) {
file->off = file->pos;
lfs2_alloc_ack(lfs2);
int err = lfs2_file_relocate(lfs2, file);
if (err) {
return err;
}
file->flags &= ~LFS2_F_INLINE;
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_file_flush(lfs2_t *lfs2, lfs2_file_t *file) {
if (file->flags & LFS2_F_READING) {
if (!(file->flags & LFS2_F_INLINE)) {
lfs2_cache_drop(lfs2, &file->cache);
}
file->flags &= ~LFS2_F_READING;
}
if (file->flags & LFS2_F_WRITING) {
lfs2_off_t pos = file->pos;
if (!(file->flags & LFS2_F_INLINE)) {
// copy over anything after current branch
lfs2_file_t orig = {
.ctz.head = file->ctz.head,
.ctz.size = file->ctz.size,
.flags = LFS2_O_RDONLY,
.pos = file->pos,
.cache = lfs2->rcache,
};
lfs2_cache_drop(lfs2, &lfs2->rcache);
while (file->pos < file->ctz.size) {
// copy over a byte at a time, leave it up to caching
// to make this efficient
uint8_t data;
lfs2_ssize_t res = lfs2_file_rawread(lfs2, &orig, &data, 1);
if (res < 0) {
return res;
}
res = lfs2_file_rawwrite(lfs2, file, &data, 1);
if (res < 0) {
return res;
}
// keep our reference to the rcache in sync
if (lfs2->rcache.block != LFS2_BLOCK_NULL) {
lfs2_cache_drop(lfs2, &orig.cache);
lfs2_cache_drop(lfs2, &lfs2->rcache);
}
}
// write out what we have
while (true) {
int err = lfs2_bd_flush(lfs2, &file->cache, &lfs2->rcache, true);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
return err;
}
break;
relocate:
LFS2_DEBUG("Bad block at 0x%"PRIx32, file->block);
err = lfs2_file_relocate(lfs2, file);
if (err) {
return err;
}
}
} else {
file->pos = lfs2_max(file->pos, file->ctz.size);
}
// actual file updates
file->ctz.head = file->block;
file->ctz.size = file->pos;
file->flags &= ~LFS2_F_WRITING;
file->flags |= LFS2_F_DIRTY;
file->pos = pos;
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_file_rawsync(lfs2_t *lfs2, lfs2_file_t *file) {
if (file->flags & LFS2_F_ERRED) {
// it's not safe to do anything if our file errored
return 0;
}
int err = lfs2_file_flush(lfs2, file);
if (err) {
file->flags |= LFS2_F_ERRED;
return err;
}
if ((file->flags & LFS2_F_DIRTY) &&
!lfs2_pair_isnull(file->m.pair)) {
// update dir entry
uint16_t type;
const void *buffer;
lfs2_size_t size;
struct lfs2_ctz ctz;
if (file->flags & LFS2_F_INLINE) {
// inline the whole file
type = LFS2_TYPE_INLINESTRUCT;
buffer = file->cache.buffer;
size = file->ctz.size;
} else {
// update the ctz reference
type = LFS2_TYPE_CTZSTRUCT;
// copy ctz so alloc will work during a relocate
ctz = file->ctz;
lfs2_ctz_tole32(&ctz);
buffer = &ctz;
size = sizeof(ctz);
}
// commit file data and attributes
err = lfs2_dir_commit(lfs2, &file->m, LFS2_MKATTRS(
{LFS2_MKTAG(type, file->id, size), buffer},
{LFS2_MKTAG(LFS2_FROM_USERATTRS, file->id,
file->cfg->attr_count), file->cfg->attrs}));
if (err) {
file->flags |= LFS2_F_ERRED;
return err;
}
file->flags &= ~LFS2_F_DIRTY;
}
return 0;
}
#endif
static lfs2_ssize_t lfs2_file_rawread(lfs2_t *lfs2, lfs2_file_t *file,
void *buffer, lfs2_size_t size) {
LFS2_ASSERT((file->flags & LFS2_O_RDONLY) == LFS2_O_RDONLY);
uint8_t *data = buffer;
lfs2_size_t nsize = size;
#ifndef LFS2_READONLY
if (file->flags & LFS2_F_WRITING) {
// flush out any writes
int err = lfs2_file_flush(lfs2, file);
if (err) {
return err;
}
}
#endif
if (file->pos >= file->ctz.size) {
// eof if past end
return 0;
}
size = lfs2_min(size, file->ctz.size - file->pos);
nsize = size;
while (nsize > 0) {
// check if we need a new block
if (!(file->flags & LFS2_F_READING) ||
file->off == lfs2->cfg->block_size) {
if (!(file->flags & LFS2_F_INLINE)) {
int err = lfs2_ctz_find(lfs2, NULL, &file->cache,
file->ctz.head, file->ctz.size,
file->pos, &file->block, &file->off);
if (err) {
return err;
}
} else {
file->block = LFS2_BLOCK_INLINE;
file->off = file->pos;
}
file->flags |= LFS2_F_READING;
}
// read as much as we can in current block
lfs2_size_t diff = lfs2_min(nsize, lfs2->cfg->block_size - file->off);
if (file->flags & LFS2_F_INLINE) {
int err = lfs2_dir_getread(lfs2, &file->m,
NULL, &file->cache, lfs2->cfg->block_size,
LFS2_MKTAG(0xfff, 0x1ff, 0),
LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, file->id, 0),
file->off, data, diff);
if (err) {
return err;
}
} else {
int err = lfs2_bd_read(lfs2,
NULL, &file->cache, lfs2->cfg->block_size,
file->block, file->off, data, diff);
if (err) {
return err;
}
}
file->pos += diff;
file->off += diff;
data += diff;
nsize -= diff;
}
return size;
}
#ifndef LFS2_READONLY
static lfs2_ssize_t lfs2_file_rawwrite(lfs2_t *lfs2, lfs2_file_t *file,
const void *buffer, lfs2_size_t size) {
LFS2_ASSERT((file->flags & LFS2_O_WRONLY) == LFS2_O_WRONLY);
const uint8_t *data = buffer;
lfs2_size_t nsize = size;
if (file->flags & LFS2_F_READING) {
// drop any reads
int err = lfs2_file_flush(lfs2, file);
if (err) {
return err;
}
}
if ((file->flags & LFS2_O_APPEND) && file->pos < file->ctz.size) {
file->pos = file->ctz.size;
}
if (file->pos + size > lfs2->file_max) {
// Larger than file limit?
return LFS2_ERR_FBIG;
}
if (!(file->flags & LFS2_F_WRITING) && file->pos > file->ctz.size) {
// fill with zeros
lfs2_off_t pos = file->pos;
file->pos = file->ctz.size;
while (file->pos < pos) {
lfs2_ssize_t res = lfs2_file_rawwrite(lfs2, file, &(uint8_t){0}, 1);
if (res < 0) {
return res;
}
}
}
if ((file->flags & LFS2_F_INLINE) &&
lfs2_max(file->pos+nsize, file->ctz.size) >
lfs2_min(0x3fe, lfs2_min(
lfs2->cfg->cache_size, lfs2->cfg->block_size/8))) {
// inline file doesn't fit anymore
int err = lfs2_file_outline(lfs2, file);
if (err) {
file->flags |= LFS2_F_ERRED;
return err;
}
}
while (nsize > 0) {
// check if we need a new block
if (!(file->flags & LFS2_F_WRITING) ||
file->off == lfs2->cfg->block_size) {
if (!(file->flags & LFS2_F_INLINE)) {
if (!(file->flags & LFS2_F_WRITING) && file->pos > 0) {
// find out which block we're extending from
int err = lfs2_ctz_find(lfs2, NULL, &file->cache,
file->ctz.head, file->ctz.size,
file->pos-1, &file->block, &file->off);
if (err) {
file->flags |= LFS2_F_ERRED;
return err;
}
// mark cache as dirty since we may have read data into it
lfs2_cache_zero(lfs2, &file->cache);
}
// extend file with new blocks
lfs2_alloc_ack(lfs2);
int err = lfs2_ctz_extend(lfs2, &file->cache, &lfs2->rcache,
file->block, file->pos,
&file->block, &file->off);
if (err) {
file->flags |= LFS2_F_ERRED;
return err;
}
} else {
file->block = LFS2_BLOCK_INLINE;
file->off = file->pos;
}
file->flags |= LFS2_F_WRITING;
}
// program as much as we can in current block
lfs2_size_t diff = lfs2_min(nsize, lfs2->cfg->block_size - file->off);
while (true) {
int err = lfs2_bd_prog(lfs2, &file->cache, &lfs2->rcache, true,
file->block, file->off, data, diff);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
goto relocate;
}
file->flags |= LFS2_F_ERRED;
return err;
}
break;
relocate:
err = lfs2_file_relocate(lfs2, file);
if (err) {
file->flags |= LFS2_F_ERRED;
return err;
}
}
file->pos += diff;
file->off += diff;
data += diff;
nsize -= diff;
lfs2_alloc_ack(lfs2);
}
file->flags &= ~LFS2_F_ERRED;
return size;
}
#endif
static lfs2_soff_t lfs2_file_rawseek(lfs2_t *lfs2, lfs2_file_t *file,
lfs2_soff_t off, int whence) {
#ifndef LFS2_READONLY
// write out everything beforehand, may be noop if rdonly
int err = lfs2_file_flush(lfs2, file);
if (err) {
return err;
}
#endif
// find new pos
lfs2_off_t npos = file->pos;
if (whence == LFS2_SEEK_SET) {
npos = off;
} else if (whence == LFS2_SEEK_CUR) {
npos = file->pos + off;
} else if (whence == LFS2_SEEK_END) {
npos = file->ctz.size + off;
}
if (npos > lfs2->file_max) {
// file position out of range
return LFS2_ERR_INVAL;
}
// update pos
file->pos = npos;
return npos;
}
#ifndef LFS2_READONLY
static int lfs2_file_rawtruncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t size) {
LFS2_ASSERT((file->flags & LFS2_O_WRONLY) == LFS2_O_WRONLY);
if (size > LFS2_FILE_MAX) {
return LFS2_ERR_INVAL;
}
lfs2_off_t pos = file->pos;
lfs2_off_t oldsize = lfs2_file_rawsize(lfs2, file);
if (size < oldsize) {
// need to flush since directly changing metadata
int err = lfs2_file_flush(lfs2, file);
if (err) {
return err;
}
// lookup new head in ctz skip list
err = lfs2_ctz_find(lfs2, NULL, &file->cache,
file->ctz.head, file->ctz.size,
size, &file->block, &file->off);
if (err) {
return err;
}
file->ctz.head = file->block;
file->ctz.size = size;
file->flags |= LFS2_F_DIRTY | LFS2_F_READING;
} else if (size > oldsize) {
// flush+seek if not already at end
if (file->pos != oldsize) {
lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, 0, LFS2_SEEK_END);
if (res < 0) {
return (int)res;
}
}
// fill with zeros
while (file->pos < size) {
lfs2_ssize_t res = lfs2_file_rawwrite(lfs2, file, &(uint8_t){0}, 1);
if (res < 0) {
return (int)res;
}
}
}
// restore pos
lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, pos, LFS2_SEEK_SET);
if (res < 0) {
return (int)res;
}
return 0;
}
#endif
static lfs2_soff_t lfs2_file_rawtell(lfs2_t *lfs2, lfs2_file_t *file) {
(void)lfs2;
return file->pos;
}
static int lfs2_file_rawrewind(lfs2_t *lfs2, lfs2_file_t *file) {
lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, 0, LFS2_SEEK_SET);
if (res < 0) {
return (int)res;
}
return 0;
}
static lfs2_soff_t lfs2_file_rawsize(lfs2_t *lfs2, lfs2_file_t *file) {
(void)lfs2;
#ifndef LFS2_READONLY
if (file->flags & LFS2_F_WRITING) {
return lfs2_max(file->pos, file->ctz.size);
}
#endif
return file->ctz.size;
}
/// General fs operations ///
static int lfs2_rawstat(lfs2_t *lfs2, const char *path, struct lfs2_info *info) {
lfs2_mdir_t cwd;
lfs2_stag_t tag = lfs2_dir_find(lfs2, &cwd, &path, NULL);
if (tag < 0) {
return (int)tag;
}
return lfs2_dir_getinfo(lfs2, &cwd, lfs2_tag_id(tag), info);
}
#ifndef LFS2_READONLY
static int lfs2_rawremove(lfs2_t *lfs2, const char *path) {
// deorphan if we haven't yet, needed at most once after poweron
int err = lfs2_fs_forceconsistency(lfs2);
if (err) {
return err;
}
lfs2_mdir_t cwd;
lfs2_stag_t tag = lfs2_dir_find(lfs2, &cwd, &path, NULL);
if (tag < 0 || lfs2_tag_id(tag) == 0x3ff) {
return (tag < 0) ? (int)tag : LFS2_ERR_INVAL;
}
struct lfs2_mlist dir;
dir.next = lfs2->mlist;
if (lfs2_tag_type3(tag) == LFS2_TYPE_DIR) {
// must be empty before removal
lfs2_block_t pair[2];
lfs2_stag_t res = lfs2_dir_get(lfs2, &cwd, LFS2_MKTAG(0x700, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, lfs2_tag_id(tag), 8), pair);
if (res < 0) {
return (int)res;
}
lfs2_pair_fromle32(pair);
err = lfs2_dir_fetch(lfs2, &dir.m, pair);
if (err) {
return err;
}
if (dir.m.count > 0 || dir.m.split) {
return LFS2_ERR_NOTEMPTY;
}
// mark fs as orphaned
lfs2_fs_preporphans(lfs2, +1);
// I know it's crazy but yes, dir can be changed by our parent's
// commit (if predecessor is child)
dir.type = 0;
dir.id = 0;
lfs2->mlist = &dir;
}
// delete the entry
err = lfs2_dir_commit(lfs2, &cwd, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_DELETE, lfs2_tag_id(tag), 0), NULL}));
if (err) {
lfs2->mlist = dir.next;
return err;
}
lfs2->mlist = dir.next;
if (lfs2_tag_type3(tag) == LFS2_TYPE_DIR) {
// fix orphan
lfs2_fs_preporphans(lfs2, -1);
err = lfs2_fs_pred(lfs2, dir.m.pair, &cwd);
if (err) {
return err;
}
err = lfs2_dir_drop(lfs2, &cwd, &dir.m);
if (err) {
return err;
}
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_rawrename(lfs2_t *lfs2, const char *oldpath, const char *newpath) {
// deorphan if we haven't yet, needed at most once after poweron
int err = lfs2_fs_forceconsistency(lfs2);
if (err) {
return err;
}
// find old entry
lfs2_mdir_t oldcwd;
lfs2_stag_t oldtag = lfs2_dir_find(lfs2, &oldcwd, &oldpath, NULL);
if (oldtag < 0 || lfs2_tag_id(oldtag) == 0x3ff) {
return (oldtag < 0) ? (int)oldtag : LFS2_ERR_INVAL;
}
// find new entry
lfs2_mdir_t newcwd;
uint16_t newid;
lfs2_stag_t prevtag = lfs2_dir_find(lfs2, &newcwd, &newpath, &newid);
if ((prevtag < 0 || lfs2_tag_id(prevtag) == 0x3ff) &&
!(prevtag == LFS2_ERR_NOENT && newid != 0x3ff)) {
return (prevtag < 0) ? (int)prevtag : LFS2_ERR_INVAL;
}
// if we're in the same pair there's a few special cases...
bool samepair = (lfs2_pair_cmp(oldcwd.pair, newcwd.pair) == 0);
uint16_t newoldid = lfs2_tag_id(oldtag);
struct lfs2_mlist prevdir;
prevdir.next = lfs2->mlist;
if (prevtag == LFS2_ERR_NOENT) {
// check that name fits
lfs2_size_t nlen = strlen(newpath);
if (nlen > lfs2->name_max) {
return LFS2_ERR_NAMETOOLONG;
}
// there is a small chance we are being renamed in the same
// directory/ to an id less than our old id, the global update
// to handle this is a bit messy
if (samepair && newid <= newoldid) {
newoldid += 1;
}
} else if (lfs2_tag_type3(prevtag) != lfs2_tag_type3(oldtag)) {
return LFS2_ERR_ISDIR;
} else if (samepair && newid == newoldid) {
// we're renaming to ourselves??
return 0;
} else if (lfs2_tag_type3(prevtag) == LFS2_TYPE_DIR) {
// must be empty before removal
lfs2_block_t prevpair[2];
lfs2_stag_t res = lfs2_dir_get(lfs2, &newcwd, LFS2_MKTAG(0x700, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, newid, 8), prevpair);
if (res < 0) {
return (int)res;
}
lfs2_pair_fromle32(prevpair);
// must be empty before removal
err = lfs2_dir_fetch(lfs2, &prevdir.m, prevpair);
if (err) {
return err;
}
if (prevdir.m.count > 0 || prevdir.m.split) {
return LFS2_ERR_NOTEMPTY;
}
// mark fs as orphaned
lfs2_fs_preporphans(lfs2, +1);
// I know it's crazy but yes, dir can be changed by our parent's
// commit (if predecessor is child)
prevdir.type = 0;
prevdir.id = 0;
lfs2->mlist = &prevdir;
}
if (!samepair) {
lfs2_fs_prepmove(lfs2, newoldid, oldcwd.pair);
}
// move over all attributes
err = lfs2_dir_commit(lfs2, &newcwd, LFS2_MKATTRS(
{LFS2_MKTAG_IF(prevtag != LFS2_ERR_NOENT,
LFS2_TYPE_DELETE, newid, 0), NULL},
{LFS2_MKTAG(LFS2_TYPE_CREATE, newid, 0), NULL},
{LFS2_MKTAG(lfs2_tag_type3(oldtag), newid, strlen(newpath)), newpath},
{LFS2_MKTAG(LFS2_FROM_MOVE, newid, lfs2_tag_id(oldtag)), &oldcwd},
{LFS2_MKTAG_IF(samepair,
LFS2_TYPE_DELETE, newoldid, 0), NULL}));
if (err) {
lfs2->mlist = prevdir.next;
return err;
}
// let commit clean up after move (if we're different! otherwise move
// logic already fixed it for us)
if (!samepair && lfs2_gstate_hasmove(&lfs2->gstate)) {
// prep gstate and delete move id
lfs2_fs_prepmove(lfs2, 0x3ff, NULL);
err = lfs2_dir_commit(lfs2, &oldcwd, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_DELETE, lfs2_tag_id(oldtag), 0), NULL}));
if (err) {
lfs2->mlist = prevdir.next;
return err;
}
}
lfs2->mlist = prevdir.next;
if (prevtag != LFS2_ERR_NOENT && lfs2_tag_type3(prevtag) == LFS2_TYPE_DIR) {
// fix orphan
lfs2_fs_preporphans(lfs2, -1);
err = lfs2_fs_pred(lfs2, prevdir.m.pair, &newcwd);
if (err) {
return err;
}
err = lfs2_dir_drop(lfs2, &newcwd, &prevdir.m);
if (err) {
return err;
}
}
return 0;
}
#endif
static lfs2_ssize_t lfs2_rawgetattr(lfs2_t *lfs2, const char *path,
uint8_t type, void *buffer, lfs2_size_t size) {
lfs2_mdir_t cwd;
lfs2_stag_t tag = lfs2_dir_find(lfs2, &cwd, &path, NULL);
if (tag < 0) {
return tag;
}
uint16_t id = lfs2_tag_id(tag);
if (id == 0x3ff) {
// special case for root
id = 0;
int err = lfs2_dir_fetch(lfs2, &cwd, lfs2->root);
if (err) {
return err;
}
}
tag = lfs2_dir_get(lfs2, &cwd, LFS2_MKTAG(0x7ff, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_USERATTR + type,
id, lfs2_min(size, lfs2->attr_max)),
buffer);
if (tag < 0) {
if (tag == LFS2_ERR_NOENT) {
return LFS2_ERR_NOATTR;
}
return tag;
}
return lfs2_tag_size(tag);
}
#ifndef LFS2_READONLY
static int lfs2_commitattr(lfs2_t *lfs2, const char *path,
uint8_t type, const void *buffer, lfs2_size_t size) {
lfs2_mdir_t cwd;
lfs2_stag_t tag = lfs2_dir_find(lfs2, &cwd, &path, NULL);
if (tag < 0) {
return tag;
}
uint16_t id = lfs2_tag_id(tag);
if (id == 0x3ff) {
// special case for root
id = 0;
int err = lfs2_dir_fetch(lfs2, &cwd, lfs2->root);
if (err) {
return err;
}
}
return lfs2_dir_commit(lfs2, &cwd, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_USERATTR + type, id, size), buffer}));
}
#endif
#ifndef LFS2_READONLY
static int lfs2_rawsetattr(lfs2_t *lfs2, const char *path,
uint8_t type, const void *buffer, lfs2_size_t size) {
if (size > lfs2->attr_max) {
return LFS2_ERR_NOSPC;
}
return lfs2_commitattr(lfs2, path, type, buffer, size);
}
#endif
#ifndef LFS2_READONLY
static int lfs2_rawremoveattr(lfs2_t *lfs2, const char *path, uint8_t type) {
return lfs2_commitattr(lfs2, path, type, NULL, 0x3ff);
}
#endif
/// Filesystem operations ///
static int lfs2_init(lfs2_t *lfs2, const struct lfs2_config *cfg) {
lfs2->cfg = cfg;
int err = 0;
// validate that the lfs2-cfg sizes were initiated properly before
// performing any arithmetic logics with them
LFS2_ASSERT(lfs2->cfg->read_size != 0);
LFS2_ASSERT(lfs2->cfg->prog_size != 0);
LFS2_ASSERT(lfs2->cfg->cache_size != 0);
// check that block size is a multiple of cache size is a multiple
// of prog and read sizes
LFS2_ASSERT(lfs2->cfg->cache_size % lfs2->cfg->read_size == 0);
LFS2_ASSERT(lfs2->cfg->cache_size % lfs2->cfg->prog_size == 0);
LFS2_ASSERT(lfs2->cfg->block_size % lfs2->cfg->cache_size == 0);
// check that the block size is large enough to fit ctz pointers
LFS2_ASSERT(4*lfs2_npw2(0xffffffff / (lfs2->cfg->block_size-2*4))
<= lfs2->cfg->block_size);
// block_cycles = 0 is no longer supported.
//
// block_cycles is the number of erase cycles before littlefs evicts
// metadata logs as a part of wear leveling. Suggested values are in the
// range of 100-1000, or set block_cycles to -1 to disable block-level
// wear-leveling.
LFS2_ASSERT(lfs2->cfg->block_cycles != 0);
// setup read cache
if (lfs2->cfg->read_buffer) {
lfs2->rcache.buffer = lfs2->cfg->read_buffer;
} else {
lfs2->rcache.buffer = lfs2_malloc(lfs2->cfg->cache_size);
if (!lfs2->rcache.buffer) {
err = LFS2_ERR_NOMEM;
goto cleanup;
}
}
// setup program cache
if (lfs2->cfg->prog_buffer) {
lfs2->pcache.buffer = lfs2->cfg->prog_buffer;
} else {
lfs2->pcache.buffer = lfs2_malloc(lfs2->cfg->cache_size);
if (!lfs2->pcache.buffer) {
err = LFS2_ERR_NOMEM;
goto cleanup;
}
}
// zero to avoid information leaks
lfs2_cache_zero(lfs2, &lfs2->rcache);
lfs2_cache_zero(lfs2, &lfs2->pcache);
// setup lookahead, must be multiple of 64-bits, 32-bit aligned
LFS2_ASSERT(lfs2->cfg->lookahead_size > 0);
LFS2_ASSERT(lfs2->cfg->lookahead_size % 8 == 0 &&
(uintptr_t)lfs2->cfg->lookahead_buffer % 4 == 0);
if (lfs2->cfg->lookahead_buffer) {
lfs2->free.buffer = lfs2->cfg->lookahead_buffer;
} else {
lfs2->free.buffer = lfs2_malloc(lfs2->cfg->lookahead_size);
if (!lfs2->free.buffer) {
err = LFS2_ERR_NOMEM;
goto cleanup;
}
}
// check that the size limits are sane
LFS2_ASSERT(lfs2->cfg->name_max <= LFS2_NAME_MAX);
lfs2->name_max = lfs2->cfg->name_max;
if (!lfs2->name_max) {
lfs2->name_max = LFS2_NAME_MAX;
}
LFS2_ASSERT(lfs2->cfg->file_max <= LFS2_FILE_MAX);
lfs2->file_max = lfs2->cfg->file_max;
if (!lfs2->file_max) {
lfs2->file_max = LFS2_FILE_MAX;
}
LFS2_ASSERT(lfs2->cfg->attr_max <= LFS2_ATTR_MAX);
lfs2->attr_max = lfs2->cfg->attr_max;
if (!lfs2->attr_max) {
lfs2->attr_max = LFS2_ATTR_MAX;
}
// setup default state
lfs2->root[0] = LFS2_BLOCK_NULL;
lfs2->root[1] = LFS2_BLOCK_NULL;
lfs2->mlist = NULL;
lfs2->seed = 0;
lfs2->gdisk = (lfs2_gstate_t){0};
lfs2->gstate = (lfs2_gstate_t){0};
lfs2->gdelta = (lfs2_gstate_t){0};
#ifdef LFS2_MIGRATE
lfs2->lfs21 = NULL;
#endif
return 0;
cleanup:
lfs2_deinit(lfs2);
return err;
}
static int lfs2_deinit(lfs2_t *lfs2) {
// free allocated memory
if (!lfs2->cfg->read_buffer) {
lfs2_free(lfs2->rcache.buffer);
}
if (!lfs2->cfg->prog_buffer) {
lfs2_free(lfs2->pcache.buffer);
}
if (!lfs2->cfg->lookahead_buffer) {
lfs2_free(lfs2->free.buffer);
}
return 0;
}
#ifndef LFS2_READONLY
static int lfs2_rawformat(lfs2_t *lfs2, const struct lfs2_config *cfg) {
int err = 0;
{
err = lfs2_init(lfs2, cfg);
if (err) {
return err;
}
// create free lookahead
memset(lfs2->free.buffer, 0, lfs2->cfg->lookahead_size);
lfs2->free.off = 0;
lfs2->free.size = lfs2_min(8*lfs2->cfg->lookahead_size,
lfs2->cfg->block_count);
lfs2->free.i = 0;
lfs2_alloc_ack(lfs2);
// create root dir
lfs2_mdir_t root;
err = lfs2_dir_alloc(lfs2, &root);
if (err) {
goto cleanup;
}
// write one superblock
lfs2_superblock_t superblock = {
.version = LFS2_DISK_VERSION,
.block_size = lfs2->cfg->block_size,
.block_count = lfs2->cfg->block_count,
.name_max = lfs2->name_max,
.file_max = lfs2->file_max,
.attr_max = lfs2->attr_max,
};
lfs2_superblock_tole32(&superblock);
err = lfs2_dir_commit(lfs2, &root, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_CREATE, 0, 0), NULL},
{LFS2_MKTAG(LFS2_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
{LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
&superblock}));
if (err) {
goto cleanup;
}
// sanity check that fetch works
err = lfs2_dir_fetch(lfs2, &root, (const lfs2_block_t[2]){0, 1});
if (err) {
goto cleanup;
}
// force compaction to prevent accidentally mounting any
// older version of littlefs that may live on disk
root.erased = false;
err = lfs2_dir_commit(lfs2, &root, NULL, 0);
if (err) {
goto cleanup;
}
}
cleanup:
lfs2_deinit(lfs2);
return err;
}
#endif
static int lfs2_rawmount(lfs2_t *lfs2, const struct lfs2_config *cfg) {
int err = lfs2_init(lfs2, cfg);
if (err) {
return err;
}
// scan directory blocks for superblock and any global updates
lfs2_mdir_t dir = {.tail = {0, 1}};
lfs2_block_t cycle = 0;
while (!lfs2_pair_isnull(dir.tail)) {
if (cycle >= lfs2->cfg->block_count/2) {
// loop detected
err = LFS2_ERR_CORRUPT;
goto cleanup;
}
cycle += 1;
// fetch next block in tail list
lfs2_stag_t tag = lfs2_dir_fetchmatch(lfs2, &dir, dir.tail,
LFS2_MKTAG(0x7ff, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_SUPERBLOCK, 0, 8),
NULL,
lfs2_dir_find_match, &(struct lfs2_dir_find_match){
lfs2, "littlefs", 8});
if (tag < 0) {
err = tag;
goto cleanup;
}
// has superblock?
if (tag && !lfs2_tag_isdelete(tag)) {
// update root
lfs2->root[0] = dir.pair[0];
lfs2->root[1] = dir.pair[1];
// grab superblock
lfs2_superblock_t superblock;
tag = lfs2_dir_get(lfs2, &dir, LFS2_MKTAG(0x7ff, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
&superblock);
if (tag < 0) {
err = tag;
goto cleanup;
}
lfs2_superblock_fromle32(&superblock);
// check version
uint16_t major_version = (0xffff & (superblock.version >> 16));
uint16_t minor_version = (0xffff & (superblock.version >> 0));
if ((major_version != LFS2_DISK_VERSION_MAJOR ||
minor_version > LFS2_DISK_VERSION_MINOR)) {
LFS2_ERROR("Invalid version v%"PRIu16".%"PRIu16,
major_version, minor_version);
err = LFS2_ERR_INVAL;
goto cleanup;
}
// check superblock configuration
if (superblock.name_max) {
if (superblock.name_max > lfs2->name_max) {
LFS2_ERROR("Unsupported name_max (%"PRIu32" > %"PRIu32")",
superblock.name_max, lfs2->name_max);
err = LFS2_ERR_INVAL;
goto cleanup;
}
lfs2->name_max = superblock.name_max;
}
if (superblock.file_max) {
if (superblock.file_max > lfs2->file_max) {
LFS2_ERROR("Unsupported file_max (%"PRIu32" > %"PRIu32")",
superblock.file_max, lfs2->file_max);
err = LFS2_ERR_INVAL;
goto cleanup;
}
lfs2->file_max = superblock.file_max;
}
if (superblock.attr_max) {
if (superblock.attr_max > lfs2->attr_max) {
LFS2_ERROR("Unsupported attr_max (%"PRIu32" > %"PRIu32")",
superblock.attr_max, lfs2->attr_max);
err = LFS2_ERR_INVAL;
goto cleanup;
}
lfs2->attr_max = superblock.attr_max;
}
}
// has gstate?
err = lfs2_dir_getgstate(lfs2, &dir, &lfs2->gstate);
if (err) {
goto cleanup;
}
}
// found superblock?
if (lfs2_pair_isnull(lfs2->root)) {
err = LFS2_ERR_INVAL;
goto cleanup;
}
// update littlefs with gstate
if (!lfs2_gstate_iszero(&lfs2->gstate)) {
LFS2_DEBUG("Found pending gstate 0x%08"PRIx32"%08"PRIx32"%08"PRIx32,
lfs2->gstate.tag,
lfs2->gstate.pair[0],
lfs2->gstate.pair[1]);
}
lfs2->gstate.tag += !lfs2_tag_isvalid(lfs2->gstate.tag);
lfs2->gdisk = lfs2->gstate;
// setup free lookahead, to distribute allocations uniformly across
// boots, we start the allocator at a random location
lfs2->free.off = lfs2->seed % lfs2->cfg->block_count;
lfs2_alloc_drop(lfs2);
return 0;
cleanup:
lfs2_rawunmount(lfs2);
return err;
}
static int lfs2_rawunmount(lfs2_t *lfs2) {
return lfs2_deinit(lfs2);
}
/// Filesystem filesystem operations ///
int lfs2_fs_rawtraverse(lfs2_t *lfs2,
int (*cb)(void *data, lfs2_block_t block), void *data,
bool includeorphans) {
// iterate over metadata pairs
lfs2_mdir_t dir = {.tail = {0, 1}};
#ifdef LFS2_MIGRATE
// also consider v1 blocks during migration
if (lfs2->lfs21) {
int err = lfs21_traverse(lfs2, cb, data);
if (err) {
return err;
}
dir.tail[0] = lfs2->root[0];
dir.tail[1] = lfs2->root[1];
}
#endif
lfs2_block_t cycle = 0;
while (!lfs2_pair_isnull(dir.tail)) {
if (cycle >= lfs2->cfg->block_count/2) {
// loop detected
return LFS2_ERR_CORRUPT;
}
cycle += 1;
for (int i = 0; i < 2; i++) {
int err = cb(data, dir.tail[i]);
if (err) {
return err;
}
}
// iterate through ids in directory
int err = lfs2_dir_fetch(lfs2, &dir, dir.tail);
if (err) {
return err;
}
for (uint16_t id = 0; id < dir.count; id++) {
struct lfs2_ctz ctz;
lfs2_stag_t tag = lfs2_dir_get(lfs2, &dir, LFS2_MKTAG(0x700, 0x3ff, 0),
LFS2_MKTAG(LFS2_TYPE_STRUCT, id, sizeof(ctz)), &ctz);
if (tag < 0) {
if (tag == LFS2_ERR_NOENT) {
continue;
}
return tag;
}
lfs2_ctz_fromle32(&ctz);
if (lfs2_tag_type3(tag) == LFS2_TYPE_CTZSTRUCT) {
err = lfs2_ctz_traverse(lfs2, NULL, &lfs2->rcache,
ctz.head, ctz.size, cb, data);
if (err) {
return err;
}
} else if (includeorphans &&
lfs2_tag_type3(tag) == LFS2_TYPE_DIRSTRUCT) {
for (int i = 0; i < 2; i++) {
err = cb(data, (&ctz.head)[i]);
if (err) {
return err;
}
}
}
}
}
#ifndef LFS2_READONLY
// iterate over any open files
for (lfs2_file_t *f = (lfs2_file_t*)lfs2->mlist; f; f = f->next) {
if (f->type != LFS2_TYPE_REG) {
continue;
}
if ((f->flags & LFS2_F_DIRTY) && !(f->flags & LFS2_F_INLINE)) {
int err = lfs2_ctz_traverse(lfs2, &f->cache, &lfs2->rcache,
f->ctz.head, f->ctz.size, cb, data);
if (err) {
return err;
}
}
if ((f->flags & LFS2_F_WRITING) && !(f->flags & LFS2_F_INLINE)) {
int err = lfs2_ctz_traverse(lfs2, &f->cache, &lfs2->rcache,
f->block, f->pos, cb, data);
if (err) {
return err;
}
}
}
#endif
return 0;
}
#ifndef LFS2_READONLY
static int lfs2_fs_pred(lfs2_t *lfs2,
const lfs2_block_t pair[2], lfs2_mdir_t *pdir) {
// iterate over all directory directory entries
pdir->tail[0] = 0;
pdir->tail[1] = 1;
lfs2_block_t cycle = 0;
while (!lfs2_pair_isnull(pdir->tail)) {
if (cycle >= lfs2->cfg->block_count/2) {
// loop detected
return LFS2_ERR_CORRUPT;
}
cycle += 1;
if (lfs2_pair_cmp(pdir->tail, pair) == 0) {
return 0;
}
int err = lfs2_dir_fetch(lfs2, pdir, pdir->tail);
if (err) {
return err;
}
}
return LFS2_ERR_NOENT;
}
#endif
#ifndef LFS2_READONLY
struct lfs2_fs_parent_match {
lfs2_t *lfs2;
const lfs2_block_t pair[2];
};
#endif
#ifndef LFS2_READONLY
static int lfs2_fs_parent_match(void *data,
lfs2_tag_t tag, const void *buffer) {
struct lfs2_fs_parent_match *find = data;
lfs2_t *lfs2 = find->lfs2;
const struct lfs2_diskoff *disk = buffer;
(void)tag;
lfs2_block_t child[2];
int err = lfs2_bd_read(lfs2,
&lfs2->pcache, &lfs2->rcache, lfs2->cfg->block_size,
disk->block, disk->off, &child, sizeof(child));
if (err) {
return err;
}
lfs2_pair_fromle32(child);
return (lfs2_pair_cmp(child, find->pair) == 0) ? LFS2_CMP_EQ : LFS2_CMP_LT;
}
#endif
#ifndef LFS2_READONLY
static lfs2_stag_t lfs2_fs_parent(lfs2_t *lfs2, const lfs2_block_t pair[2],
lfs2_mdir_t *parent) {
// use fetchmatch with callback to find pairs
parent->tail[0] = 0;
parent->tail[1] = 1;
lfs2_block_t cycle = 0;
while (!lfs2_pair_isnull(parent->tail)) {
if (cycle >= lfs2->cfg->block_count/2) {
// loop detected
return LFS2_ERR_CORRUPT;
}
cycle += 1;
lfs2_stag_t tag = lfs2_dir_fetchmatch(lfs2, parent, parent->tail,
LFS2_MKTAG(0x7ff, 0, 0x3ff),
LFS2_MKTAG(LFS2_TYPE_DIRSTRUCT, 0, 8),
NULL,
lfs2_fs_parent_match, &(struct lfs2_fs_parent_match){
lfs2, {pair[0], pair[1]}});
if (tag && tag != LFS2_ERR_NOENT) {
return tag;
}
}
return LFS2_ERR_NOENT;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_fs_relocate(lfs2_t *lfs2,
const lfs2_block_t oldpair[2], lfs2_block_t newpair[2]) {
// update internal root
if (lfs2_pair_cmp(oldpair, lfs2->root) == 0) {
lfs2->root[0] = newpair[0];
lfs2->root[1] = newpair[1];
}
// update internally tracked dirs
for (struct lfs2_mlist *d = lfs2->mlist; d; d = d->next) {
if (lfs2_pair_cmp(oldpair, d->m.pair) == 0) {
d->m.pair[0] = newpair[0];
d->m.pair[1] = newpair[1];
}
if (d->type == LFS2_TYPE_DIR &&
lfs2_pair_cmp(oldpair, ((lfs2_dir_t*)d)->head) == 0) {
((lfs2_dir_t*)d)->head[0] = newpair[0];
((lfs2_dir_t*)d)->head[1] = newpair[1];
}
}
// find parent
lfs2_mdir_t parent;
lfs2_stag_t tag = lfs2_fs_parent(lfs2, oldpair, &parent);
if (tag < 0 && tag != LFS2_ERR_NOENT) {
return tag;
}
if (tag != LFS2_ERR_NOENT) {
// update disk, this creates a desync
lfs2_fs_preporphans(lfs2, +1);
// fix pending move in this pair? this looks like an optimization but
// is in fact _required_ since relocating may outdate the move.
uint16_t moveid = 0x3ff;
if (lfs2_gstate_hasmovehere(&lfs2->gstate, parent.pair)) {
moveid = lfs2_tag_id(lfs2->gstate.tag);
LFS2_DEBUG("Fixing move while relocating "
"{0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16"\n",
parent.pair[0], parent.pair[1], moveid);
lfs2_fs_prepmove(lfs2, 0x3ff, NULL);
if (moveid < lfs2_tag_id(tag)) {
tag -= LFS2_MKTAG(0, 1, 0);
}
}
lfs2_pair_tole32(newpair);
int err = lfs2_dir_commit(lfs2, &parent, LFS2_MKATTRS(
{LFS2_MKTAG_IF(moveid != 0x3ff,
LFS2_TYPE_DELETE, moveid, 0), NULL},
{tag, newpair}));
lfs2_pair_fromle32(newpair);
if (err) {
return err;
}
// next step, clean up orphans
lfs2_fs_preporphans(lfs2, -1);
}
// find pred
int err = lfs2_fs_pred(lfs2, oldpair, &parent);
if (err && err != LFS2_ERR_NOENT) {
return err;
}
// if we can't find dir, it must be new
if (err != LFS2_ERR_NOENT) {
// fix pending move in this pair? this looks like an optimization but
// is in fact _required_ since relocating may outdate the move.
uint16_t moveid = 0x3ff;
if (lfs2_gstate_hasmovehere(&lfs2->gstate, parent.pair)) {
moveid = lfs2_tag_id(lfs2->gstate.tag);
LFS2_DEBUG("Fixing move while relocating "
"{0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16"\n",
parent.pair[0], parent.pair[1], moveid);
lfs2_fs_prepmove(lfs2, 0x3ff, NULL);
}
// replace bad pair, either we clean up desync, or no desync occured
lfs2_pair_tole32(newpair);
err = lfs2_dir_commit(lfs2, &parent, LFS2_MKATTRS(
{LFS2_MKTAG_IF(moveid != 0x3ff,
LFS2_TYPE_DELETE, moveid, 0), NULL},
{LFS2_MKTAG(LFS2_TYPE_TAIL + parent.split, 0x3ff, 8), newpair}));
lfs2_pair_fromle32(newpair);
if (err) {
return err;
}
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static void lfs2_fs_preporphans(lfs2_t *lfs2, int8_t orphans) {
LFS2_ASSERT(lfs2_tag_size(lfs2->gstate.tag) > 0 || orphans >= 0);
lfs2->gstate.tag += orphans;
lfs2->gstate.tag = ((lfs2->gstate.tag & ~LFS2_MKTAG(0x800, 0, 0)) |
((uint32_t)lfs2_gstate_hasorphans(&lfs2->gstate) << 31));
}
#endif
#ifndef LFS2_READONLY
static void lfs2_fs_prepmove(lfs2_t *lfs2,
uint16_t id, const lfs2_block_t pair[2]) {
lfs2->gstate.tag = ((lfs2->gstate.tag & ~LFS2_MKTAG(0x7ff, 0x3ff, 0)) |
((id != 0x3ff) ? LFS2_MKTAG(LFS2_TYPE_DELETE, id, 0) : 0));
lfs2->gstate.pair[0] = (id != 0x3ff) ? pair[0] : 0;
lfs2->gstate.pair[1] = (id != 0x3ff) ? pair[1] : 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_fs_demove(lfs2_t *lfs2) {
if (!lfs2_gstate_hasmove(&lfs2->gdisk)) {
return 0;
}
// Fix bad moves
LFS2_DEBUG("Fixing move {0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16,
lfs2->gdisk.pair[0],
lfs2->gdisk.pair[1],
lfs2_tag_id(lfs2->gdisk.tag));
// fetch and delete the moved entry
lfs2_mdir_t movedir;
int err = lfs2_dir_fetch(lfs2, &movedir, lfs2->gdisk.pair);
if (err) {
return err;
}
// prep gstate and delete move id
uint16_t moveid = lfs2_tag_id(lfs2->gdisk.tag);
lfs2_fs_prepmove(lfs2, 0x3ff, NULL);
err = lfs2_dir_commit(lfs2, &movedir, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_DELETE, moveid, 0), NULL}));
if (err) {
return err;
}
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_fs_deorphan(lfs2_t *lfs2) {
if (!lfs2_gstate_hasorphans(&lfs2->gstate)) {
return 0;
}
// Fix any orphans
lfs2_mdir_t pdir = {.split = true, .tail = {0, 1}};
lfs2_mdir_t dir;
// iterate over all directory directory entries
while (!lfs2_pair_isnull(pdir.tail)) {
int err = lfs2_dir_fetch(lfs2, &dir, pdir.tail);
if (err) {
return err;
}
// check head blocks for orphans
if (!pdir.split) {
// check if we have a parent
lfs2_mdir_t parent;
lfs2_stag_t tag = lfs2_fs_parent(lfs2, pdir.tail, &parent);
if (tag < 0 && tag != LFS2_ERR_NOENT) {
return tag;
}
if (tag == LFS2_ERR_NOENT) {
// we are an orphan
LFS2_DEBUG("Fixing orphan {0x%"PRIx32", 0x%"PRIx32"}",
pdir.tail[0], pdir.tail[1]);
err = lfs2_dir_drop(lfs2, &pdir, &dir);
if (err) {
return err;
}
// refetch tail
continue;
}
lfs2_block_t pair[2];
lfs2_stag_t res = lfs2_dir_get(lfs2, &parent,
LFS2_MKTAG(0x7ff, 0x3ff, 0), tag, pair);
if (res < 0) {
return res;
}
lfs2_pair_fromle32(pair);
if (!lfs2_pair_sync(pair, pdir.tail)) {
// we have desynced
LFS2_DEBUG("Fixing half-orphan {0x%"PRIx32", 0x%"PRIx32"} "
"-> {0x%"PRIx32", 0x%"PRIx32"}",
pdir.tail[0], pdir.tail[1], pair[0], pair[1]);
lfs2_pair_tole32(pair);
err = lfs2_dir_commit(lfs2, &pdir, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_SOFTTAIL, 0x3ff, 8), pair}));
lfs2_pair_fromle32(pair);
if (err) {
return err;
}
// refetch tail
continue;
}
}
pdir = dir;
}
// mark orphans as fixed
lfs2_fs_preporphans(lfs2, -lfs2_gstate_getorphans(&lfs2->gstate));
return 0;
}
#endif
#ifndef LFS2_READONLY
static int lfs2_fs_forceconsistency(lfs2_t *lfs2) {
int err = lfs2_fs_demove(lfs2);
if (err) {
return err;
}
err = lfs2_fs_deorphan(lfs2);
if (err) {
return err;
}
return 0;
}
#endif
static int lfs2_fs_size_count(void *p, lfs2_block_t block) {
(void)block;
lfs2_size_t *size = p;
*size += 1;
return 0;
}
static lfs2_ssize_t lfs2_fs_rawsize(lfs2_t *lfs2) {
lfs2_size_t size = 0;
int err = lfs2_fs_rawtraverse(lfs2, lfs2_fs_size_count, &size, false);
if (err) {
return err;
}
return size;
}
#ifdef LFS2_MIGRATE
////// Migration from littelfs v1 below this //////
/// Version info ///
// Software library version
// Major (top-nibble), incremented on backwards incompatible changes
// Minor (bottom-nibble), incremented on feature additions
#define LFS21_VERSION 0x00010007
#define LFS21_VERSION_MAJOR (0xffff & (LFS21_VERSION >> 16))
#define LFS21_VERSION_MINOR (0xffff & (LFS21_VERSION >> 0))
// Version of On-disk data structures
// Major (top-nibble), incremented on backwards incompatible changes
// Minor (bottom-nibble), incremented on feature additions
#define LFS21_DISK_VERSION 0x00010001
#define LFS21_DISK_VERSION_MAJOR (0xffff & (LFS21_DISK_VERSION >> 16))
#define LFS21_DISK_VERSION_MINOR (0xffff & (LFS21_DISK_VERSION >> 0))
/// v1 Definitions ///
// File types
enum lfs21_type {
LFS21_TYPE_REG = 0x11,
LFS21_TYPE_DIR = 0x22,
LFS21_TYPE_SUPERBLOCK = 0x2e,
};
typedef struct lfs21 {
lfs2_block_t root[2];
} lfs21_t;
typedef struct lfs21_entry {
lfs2_off_t off;
struct lfs21_disk_entry {
uint8_t type;
uint8_t elen;
uint8_t alen;
uint8_t nlen;
union {
struct {
lfs2_block_t head;
lfs2_size_t size;
} file;
lfs2_block_t dir[2];
} u;
} d;
} lfs21_entry_t;
typedef struct lfs21_dir {
struct lfs21_dir *next;
lfs2_block_t pair[2];
lfs2_off_t off;
lfs2_block_t head[2];
lfs2_off_t pos;
struct lfs21_disk_dir {
uint32_t rev;
lfs2_size_t size;
lfs2_block_t tail[2];
} d;
} lfs21_dir_t;
typedef struct lfs21_superblock {
lfs2_off_t off;
struct lfs21_disk_superblock {
uint8_t type;
uint8_t elen;
uint8_t alen;
uint8_t nlen;
lfs2_block_t root[2];
uint32_t block_size;
uint32_t block_count;
uint32_t version;
char magic[8];
} d;
} lfs21_superblock_t;
/// Low-level wrappers v1->v2 ///
static void lfs21_crc(uint32_t *crc, const void *buffer, size_t size) {
*crc = lfs2_crc(*crc, buffer, size);
}
static int lfs21_bd_read(lfs2_t *lfs2, lfs2_block_t block,
lfs2_off_t off, void *buffer, lfs2_size_t size) {
// if we ever do more than writes to alternating pairs,
// this may need to consider pcache
return lfs2_bd_read(lfs2, &lfs2->pcache, &lfs2->rcache, size,
block, off, buffer, size);
}
static int lfs21_bd_crc(lfs2_t *lfs2, lfs2_block_t block,
lfs2_off_t off, lfs2_size_t size, uint32_t *crc) {
for (lfs2_off_t i = 0; i < size; i++) {
uint8_t c;
int err = lfs21_bd_read(lfs2, block, off+i, &c, 1);
if (err) {
return err;
}
lfs21_crc(crc, &c, 1);
}
return 0;
}
/// Endian swapping functions ///
static void lfs21_dir_fromle32(struct lfs21_disk_dir *d) {
d->rev = lfs2_fromle32(d->rev);
d->size = lfs2_fromle32(d->size);
d->tail[0] = lfs2_fromle32(d->tail[0]);
d->tail[1] = lfs2_fromle32(d->tail[1]);
}
static void lfs21_dir_tole32(struct lfs21_disk_dir *d) {
d->rev = lfs2_tole32(d->rev);
d->size = lfs2_tole32(d->size);
d->tail[0] = lfs2_tole32(d->tail[0]);
d->tail[1] = lfs2_tole32(d->tail[1]);
}
static void lfs21_entry_fromle32(struct lfs21_disk_entry *d) {
d->u.dir[0] = lfs2_fromle32(d->u.dir[0]);
d->u.dir[1] = lfs2_fromle32(d->u.dir[1]);
}
static void lfs21_entry_tole32(struct lfs21_disk_entry *d) {
d->u.dir[0] = lfs2_tole32(d->u.dir[0]);
d->u.dir[1] = lfs2_tole32(d->u.dir[1]);
}
static void lfs21_superblock_fromle32(struct lfs21_disk_superblock *d) {
d->root[0] = lfs2_fromle32(d->root[0]);
d->root[1] = lfs2_fromle32(d->root[1]);
d->block_size = lfs2_fromle32(d->block_size);
d->block_count = lfs2_fromle32(d->block_count);
d->version = lfs2_fromle32(d->version);
}
///// Metadata pair and directory operations ///
static inline lfs2_size_t lfs21_entry_size(const lfs21_entry_t *entry) {
return 4 + entry->d.elen + entry->d.alen + entry->d.nlen;
}
static int lfs21_dir_fetch(lfs2_t *lfs2,
lfs21_dir_t *dir, const lfs2_block_t pair[2]) {
// copy out pair, otherwise may be aliasing dir
const lfs2_block_t tpair[2] = {pair[0], pair[1]};
bool valid = false;
// check both blocks for the most recent revision
for (int i = 0; i < 2; i++) {
struct lfs21_disk_dir test;
int err = lfs21_bd_read(lfs2, tpair[i], 0, &test, sizeof(test));
lfs21_dir_fromle32(&test);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
continue;
}
return err;
}
if (valid && lfs2_scmp(test.rev, dir->d.rev) < 0) {
continue;
}
if ((0x7fffffff & test.size) < sizeof(test)+4 ||
(0x7fffffff & test.size) > lfs2->cfg->block_size) {
continue;
}
uint32_t crc = 0xffffffff;
lfs21_dir_tole32(&test);
lfs21_crc(&crc, &test, sizeof(test));
lfs21_dir_fromle32(&test);
err = lfs21_bd_crc(lfs2, tpair[i], sizeof(test),
(0x7fffffff & test.size) - sizeof(test), &crc);
if (err) {
if (err == LFS2_ERR_CORRUPT) {
continue;
}
return err;
}
if (crc != 0) {
continue;
}
valid = true;
// setup dir in case it's valid
dir->pair[0] = tpair[(i+0) % 2];
dir->pair[1] = tpair[(i+1) % 2];
dir->off = sizeof(dir->d);
dir->d = test;
}
if (!valid) {
LFS2_ERROR("Corrupted dir pair at {0x%"PRIx32", 0x%"PRIx32"}",
tpair[0], tpair[1]);
return LFS2_ERR_CORRUPT;
}
return 0;
}
static int lfs21_dir_next(lfs2_t *lfs2, lfs21_dir_t *dir, lfs21_entry_t *entry) {
while (dir->off + sizeof(entry->d) > (0x7fffffff & dir->d.size)-4) {
if (!(0x80000000 & dir->d.size)) {
entry->off = dir->off;
return LFS2_ERR_NOENT;
}
int err = lfs21_dir_fetch(lfs2, dir, dir->d.tail);
if (err) {
return err;
}
dir->off = sizeof(dir->d);
dir->pos += sizeof(dir->d) + 4;
}
int err = lfs21_bd_read(lfs2, dir->pair[0], dir->off,
&entry->d, sizeof(entry->d));
lfs21_entry_fromle32(&entry->d);
if (err) {
return err;
}
entry->off = dir->off;
dir->off += lfs21_entry_size(entry);
dir->pos += lfs21_entry_size(entry);
return 0;
}
/// littlefs v1 specific operations ///
int lfs21_traverse(lfs2_t *lfs2, int (*cb)(void*, lfs2_block_t), void *data) {
if (lfs2_pair_isnull(lfs2->lfs21->root)) {
return 0;
}
// iterate over metadata pairs
lfs21_dir_t dir;
lfs21_entry_t entry;
lfs2_block_t cwd[2] = {0, 1};
while (true) {
for (int i = 0; i < 2; i++) {
int err = cb(data, cwd[i]);
if (err) {
return err;
}
}
int err = lfs21_dir_fetch(lfs2, &dir, cwd);
if (err) {
return err;
}
// iterate over contents
while (dir.off + sizeof(entry.d) <= (0x7fffffff & dir.d.size)-4) {
err = lfs21_bd_read(lfs2, dir.pair[0], dir.off,
&entry.d, sizeof(entry.d));
lfs21_entry_fromle32(&entry.d);
if (err) {
return err;
}
dir.off += lfs21_entry_size(&entry);
if ((0x70 & entry.d.type) == (0x70 & LFS21_TYPE_REG)) {
err = lfs2_ctz_traverse(lfs2, NULL, &lfs2->rcache,
entry.d.u.file.head, entry.d.u.file.size, cb, data);
if (err) {
return err;
}
}
}
// we also need to check if we contain a threaded v2 directory
lfs2_mdir_t dir2 = {.split=true, .tail={cwd[0], cwd[1]}};
while (dir2.split) {
err = lfs2_dir_fetch(lfs2, &dir2, dir2.tail);
if (err) {
break;
}
for (int i = 0; i < 2; i++) {
err = cb(data, dir2.pair[i]);
if (err) {
return err;
}
}
}
cwd[0] = dir.d.tail[0];
cwd[1] = dir.d.tail[1];
if (lfs2_pair_isnull(cwd)) {
break;
}
}
return 0;
}
static int lfs21_moved(lfs2_t *lfs2, const void *e) {
if (lfs2_pair_isnull(lfs2->lfs21->root)) {
return 0;
}
// skip superblock
lfs21_dir_t cwd;
int err = lfs21_dir_fetch(lfs2, &cwd, (const lfs2_block_t[2]){0, 1});
if (err) {
return err;
}
// iterate over all directory directory entries
lfs21_entry_t entry;
while (!lfs2_pair_isnull(cwd.d.tail)) {
err = lfs21_dir_fetch(lfs2, &cwd, cwd.d.tail);
if (err) {
return err;
}
while (true) {
err = lfs21_dir_next(lfs2, &cwd, &entry);
if (err && err != LFS2_ERR_NOENT) {
return err;
}
if (err == LFS2_ERR_NOENT) {
break;
}
if (!(0x80 & entry.d.type) &&
memcmp(&entry.d.u, e, sizeof(entry.d.u)) == 0) {
return true;
}
}
}
return false;
}
/// Filesystem operations ///
static int lfs21_mount(lfs2_t *lfs2, struct lfs21 *lfs21,
const struct lfs2_config *cfg) {
int err = 0;
{
err = lfs2_init(lfs2, cfg);
if (err) {
return err;
}
lfs2->lfs21 = lfs21;
lfs2->lfs21->root[0] = LFS2_BLOCK_NULL;
lfs2->lfs21->root[1] = LFS2_BLOCK_NULL;
// setup free lookahead
lfs2->free.off = 0;
lfs2->free.size = 0;
lfs2->free.i = 0;
lfs2_alloc_ack(lfs2);
// load superblock
lfs21_dir_t dir;
lfs21_superblock_t superblock;
err = lfs21_dir_fetch(lfs2, &dir, (const lfs2_block_t[2]){0, 1});
if (err && err != LFS2_ERR_CORRUPT) {
goto cleanup;
}
if (!err) {
err = lfs21_bd_read(lfs2, dir.pair[0], sizeof(dir.d),
&superblock.d, sizeof(superblock.d));
lfs21_superblock_fromle32(&superblock.d);
if (err) {
goto cleanup;
}
lfs2->lfs21->root[0] = superblock.d.root[0];
lfs2->lfs21->root[1] = superblock.d.root[1];
}
if (err || memcmp(superblock.d.magic, "littlefs", 8) != 0) {
LFS2_ERROR("Invalid superblock at {0x%"PRIx32", 0x%"PRIx32"}",
0, 1);
err = LFS2_ERR_CORRUPT;
goto cleanup;
}
uint16_t major_version = (0xffff & (superblock.d.version >> 16));
uint16_t minor_version = (0xffff & (superblock.d.version >> 0));
if ((major_version != LFS21_DISK_VERSION_MAJOR ||
minor_version > LFS21_DISK_VERSION_MINOR)) {
LFS2_ERROR("Invalid version v%d.%d", major_version, minor_version);
err = LFS2_ERR_INVAL;
goto cleanup;
}
return 0;
}
cleanup:
lfs2_deinit(lfs2);
return err;
}
static int lfs21_unmount(lfs2_t *lfs2) {
return lfs2_deinit(lfs2);
}
/// v1 migration ///
static int lfs2_rawmigrate(lfs2_t *lfs2, const struct lfs2_config *cfg) {
struct lfs21 lfs21;
int err = lfs21_mount(lfs2, &lfs21, cfg);
if (err) {
return err;
}
{
// iterate through each directory, copying over entries
// into new directory
lfs21_dir_t dir1;
lfs2_mdir_t dir2;
dir1.d.tail[0] = lfs2->lfs21->root[0];
dir1.d.tail[1] = lfs2->lfs21->root[1];
while (!lfs2_pair_isnull(dir1.d.tail)) {
// iterate old dir
err = lfs21_dir_fetch(lfs2, &dir1, dir1.d.tail);
if (err) {
goto cleanup;
}
// create new dir and bind as temporary pretend root
err = lfs2_dir_alloc(lfs2, &dir2);
if (err) {
goto cleanup;
}
dir2.rev = dir1.d.rev;
dir1.head[0] = dir1.pair[0];
dir1.head[1] = dir1.pair[1];
lfs2->root[0] = dir2.pair[0];
lfs2->root[1] = dir2.pair[1];
err = lfs2_dir_commit(lfs2, &dir2, NULL, 0);
if (err) {
goto cleanup;
}
while (true) {
lfs21_entry_t entry1;
err = lfs21_dir_next(lfs2, &dir1, &entry1);
if (err && err != LFS2_ERR_NOENT) {
goto cleanup;
}
if (err == LFS2_ERR_NOENT) {
break;
}
// check that entry has not been moved
if (entry1.d.type & 0x80) {
int moved = lfs21_moved(lfs2, &entry1.d.u);
if (moved < 0) {
err = moved;
goto cleanup;
}
if (moved) {
continue;
}
entry1.d.type &= ~0x80;
}
// also fetch name
char name[LFS2_NAME_MAX+1];
memset(name, 0, sizeof(name));
err = lfs21_bd_read(lfs2, dir1.pair[0],
entry1.off + 4+entry1.d.elen+entry1.d.alen,
name, entry1.d.nlen);
if (err) {
goto cleanup;
}
bool isdir = (entry1.d.type == LFS21_TYPE_DIR);
// create entry in new dir
err = lfs2_dir_fetch(lfs2, &dir2, lfs2->root);
if (err) {
goto cleanup;
}
uint16_t id;
err = lfs2_dir_find(lfs2, &dir2, &(const char*){name}, &id);
if (!(err == LFS2_ERR_NOENT && id != 0x3ff)) {
err = (err < 0) ? err : LFS2_ERR_EXIST;
goto cleanup;
}
lfs21_entry_tole32(&entry1.d);
err = lfs2_dir_commit(lfs2, &dir2, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_CREATE, id, 0)},
{LFS2_MKTAG_IF_ELSE(isdir,
LFS2_TYPE_DIR, id, entry1.d.nlen,
LFS2_TYPE_REG, id, entry1.d.nlen),
name},
{LFS2_MKTAG_IF_ELSE(isdir,
LFS2_TYPE_DIRSTRUCT, id, sizeof(entry1.d.u),
LFS2_TYPE_CTZSTRUCT, id, sizeof(entry1.d.u)),
&entry1.d.u}));
lfs21_entry_fromle32(&entry1.d);
if (err) {
goto cleanup;
}
}
if (!lfs2_pair_isnull(dir1.d.tail)) {
// find last block and update tail to thread into fs
err = lfs2_dir_fetch(lfs2, &dir2, lfs2->root);
if (err) {
goto cleanup;
}
while (dir2.split) {
err = lfs2_dir_fetch(lfs2, &dir2, dir2.tail);
if (err) {
goto cleanup;
}
}
lfs2_pair_tole32(dir2.pair);
err = lfs2_dir_commit(lfs2, &dir2, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_SOFTTAIL, 0x3ff, 8), dir1.d.tail}));
lfs2_pair_fromle32(dir2.pair);
if (err) {
goto cleanup;
}
}
// Copy over first block to thread into fs. Unfortunately
// if this fails there is not much we can do.
LFS2_DEBUG("Migrating {0x%"PRIx32", 0x%"PRIx32"} "
"-> {0x%"PRIx32", 0x%"PRIx32"}",
lfs2->root[0], lfs2->root[1], dir1.head[0], dir1.head[1]);
err = lfs2_bd_erase(lfs2, dir1.head[1]);
if (err) {
goto cleanup;
}
err = lfs2_dir_fetch(lfs2, &dir2, lfs2->root);
if (err) {
goto cleanup;
}
for (lfs2_off_t i = 0; i < dir2.off; i++) {
uint8_t dat;
err = lfs2_bd_read(lfs2,
NULL, &lfs2->rcache, dir2.off,
dir2.pair[0], i, &dat, 1);
if (err) {
goto cleanup;
}
err = lfs2_bd_prog(lfs2,
&lfs2->pcache, &lfs2->rcache, true,
dir1.head[1], i, &dat, 1);
if (err) {
goto cleanup;
}
}
err = lfs2_bd_flush(lfs2, &lfs2->pcache, &lfs2->rcache, true);
if (err) {
goto cleanup;
}
}
// Create new superblock. This marks a successful migration!
err = lfs21_dir_fetch(lfs2, &dir1, (const lfs2_block_t[2]){0, 1});
if (err) {
goto cleanup;
}
dir2.pair[0] = dir1.pair[0];
dir2.pair[1] = dir1.pair[1];
dir2.rev = dir1.d.rev;
dir2.off = sizeof(dir2.rev);
dir2.etag = 0xffffffff;
dir2.count = 0;
dir2.tail[0] = lfs2->lfs21->root[0];
dir2.tail[1] = lfs2->lfs21->root[1];
dir2.erased = false;
dir2.split = true;
lfs2_superblock_t superblock = {
.version = LFS2_DISK_VERSION,
.block_size = lfs2->cfg->block_size,
.block_count = lfs2->cfg->block_count,
.name_max = lfs2->name_max,
.file_max = lfs2->file_max,
.attr_max = lfs2->attr_max,
};
lfs2_superblock_tole32(&superblock);
err = lfs2_dir_commit(lfs2, &dir2, LFS2_MKATTRS(
{LFS2_MKTAG(LFS2_TYPE_CREATE, 0, 0)},
{LFS2_MKTAG(LFS2_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
{LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
&superblock}));
if (err) {
goto cleanup;
}
// sanity check that fetch works
err = lfs2_dir_fetch(lfs2, &dir2, (const lfs2_block_t[2]){0, 1});
if (err) {
goto cleanup;
}
// force compaction to prevent accidentally mounting v1
dir2.erased = false;
err = lfs2_dir_commit(lfs2, &dir2, NULL, 0);
if (err) {
goto cleanup;
}
}
cleanup:
lfs21_unmount(lfs2);
return err;
}
#endif
/// Public API wrappers ///
// Here we can add tracing/thread safety easily
// Thread-safe wrappers if enabled
#ifdef LFS2_THREADSAFE
#define LFS2_LOCK(cfg) cfg->lock(cfg)
#define LFS2_UNLOCK(cfg) cfg->unlock(cfg)
#else
#define LFS2_LOCK(cfg) ((void)cfg, 0)
#define LFS2_UNLOCK(cfg) ((void)cfg)
#endif
// Public API
#ifndef LFS2_READONLY
int lfs2_format(lfs2_t *lfs2, const struct lfs2_config *cfg) {
int err = LFS2_LOCK(cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_format(%p, %p {.context=%p, "
".read=%p, .prog=%p, .erase=%p, .sync=%p, "
".read_size=%"PRIu32", .prog_size=%"PRIu32", "
".block_size=%"PRIu32", .block_count=%"PRIu32", "
".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
".lookahead_size=%"PRIu32", .read_buffer=%p, "
".prog_buffer=%p, .lookahead_buffer=%p, "
".name_max=%"PRIu32", .file_max=%"PRIu32", "
".attr_max=%"PRIu32"})",
(void*)lfs2, (void*)cfg, cfg->context,
(void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
(void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
cfg->name_max, cfg->file_max, cfg->attr_max);
err = lfs2_rawformat(lfs2, cfg);
LFS2_TRACE("lfs2_format -> %d", err);
LFS2_UNLOCK(cfg);
return err;
}
#endif
int lfs2_mount(lfs2_t *lfs2, const struct lfs2_config *cfg) {
int err = LFS2_LOCK(cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_mount(%p, %p {.context=%p, "
".read=%p, .prog=%p, .erase=%p, .sync=%p, "
".read_size=%"PRIu32", .prog_size=%"PRIu32", "
".block_size=%"PRIu32", .block_count=%"PRIu32", "
".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
".lookahead_size=%"PRIu32", .read_buffer=%p, "
".prog_buffer=%p, .lookahead_buffer=%p, "
".name_max=%"PRIu32", .file_max=%"PRIu32", "
".attr_max=%"PRIu32"})",
(void*)lfs2, (void*)cfg, cfg->context,
(void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
(void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
cfg->name_max, cfg->file_max, cfg->attr_max);
err = lfs2_rawmount(lfs2, cfg);
LFS2_TRACE("lfs2_mount -> %d", err);
LFS2_UNLOCK(cfg);
return err;
}
int lfs2_unmount(lfs2_t *lfs2) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_unmount(%p)", (void*)lfs2);
err = lfs2_rawunmount(lfs2);
LFS2_TRACE("lfs2_unmount -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#ifndef LFS2_READONLY
int lfs2_remove(lfs2_t *lfs2, const char *path) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_remove(%p, \"%s\")", (void*)lfs2, path);
err = lfs2_rawremove(lfs2, path);
LFS2_TRACE("lfs2_remove -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#endif
#ifndef LFS2_READONLY
int lfs2_rename(lfs2_t *lfs2, const char *oldpath, const char *newpath) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_rename(%p, \"%s\", \"%s\")", (void*)lfs2, oldpath, newpath);
err = lfs2_rawrename(lfs2, oldpath, newpath);
LFS2_TRACE("lfs2_rename -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#endif
int lfs2_stat(lfs2_t *lfs2, const char *path, struct lfs2_info *info) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_stat(%p, \"%s\", %p)", (void*)lfs2, path, (void*)info);
err = lfs2_rawstat(lfs2, path, info);
LFS2_TRACE("lfs2_stat -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
lfs2_ssize_t lfs2_getattr(lfs2_t *lfs2, const char *path,
uint8_t type, void *buffer, lfs2_size_t size) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_getattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")",
(void*)lfs2, path, type, buffer, size);
lfs2_ssize_t res = lfs2_rawgetattr(lfs2, path, type, buffer, size);
LFS2_TRACE("lfs2_getattr -> %"PRId32, res);
LFS2_UNLOCK(lfs2->cfg);
return res;
}
#ifndef LFS2_READONLY
int lfs2_setattr(lfs2_t *lfs2, const char *path,
uint8_t type, const void *buffer, lfs2_size_t size) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_setattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")",
(void*)lfs2, path, type, buffer, size);
err = lfs2_rawsetattr(lfs2, path, type, buffer, size);
LFS2_TRACE("lfs2_setattr -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#endif
#ifndef LFS2_READONLY
int lfs2_removeattr(lfs2_t *lfs2, const char *path, uint8_t type) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_removeattr(%p, \"%s\", %"PRIu8")", (void*)lfs2, path, type);
err = lfs2_rawremoveattr(lfs2, path, type);
LFS2_TRACE("lfs2_removeattr -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#endif
int lfs2_file_open(lfs2_t *lfs2, lfs2_file_t *file, const char *path, int flags) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_open(%p, %p, \"%s\", %x)",
(void*)lfs2, (void*)file, path, flags);
LFS2_ASSERT(!lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
err = lfs2_file_rawopen(lfs2, file, path, flags);
LFS2_TRACE("lfs2_file_open -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
int lfs2_file_opencfg(lfs2_t *lfs2, lfs2_file_t *file,
const char *path, int flags,
const struct lfs2_file_config *cfg) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_opencfg(%p, %p, \"%s\", %x, %p {"
".buffer=%p, .attrs=%p, .attr_count=%"PRIu32"})",
(void*)lfs2, (void*)file, path, flags,
(void*)cfg, cfg->buffer, (void*)cfg->attrs, cfg->attr_count);
LFS2_ASSERT(!lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
err = lfs2_file_rawopencfg(lfs2, file, path, flags, cfg);
LFS2_TRACE("lfs2_file_opencfg -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
int lfs2_file_close(lfs2_t *lfs2, lfs2_file_t *file) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_close(%p, %p)", (void*)lfs2, (void*)file);
LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
err = lfs2_file_rawclose(lfs2, file);
LFS2_TRACE("lfs2_file_close -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#ifndef LFS2_READONLY
int lfs2_file_sync(lfs2_t *lfs2, lfs2_file_t *file) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_sync(%p, %p)", (void*)lfs2, (void*)file);
LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
err = lfs2_file_rawsync(lfs2, file);
LFS2_TRACE("lfs2_file_sync -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#endif
lfs2_ssize_t lfs2_file_read(lfs2_t *lfs2, lfs2_file_t *file,
void *buffer, lfs2_size_t size) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_read(%p, %p, %p, %"PRIu32")",
(void*)lfs2, (void*)file, buffer, size);
LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
lfs2_ssize_t res = lfs2_file_rawread(lfs2, file, buffer, size);
LFS2_TRACE("lfs2_file_read -> %"PRId32, res);
LFS2_UNLOCK(lfs2->cfg);
return res;
}
#ifndef LFS2_READONLY
lfs2_ssize_t lfs2_file_write(lfs2_t *lfs2, lfs2_file_t *file,
const void *buffer, lfs2_size_t size) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_write(%p, %p, %p, %"PRIu32")",
(void*)lfs2, (void*)file, buffer, size);
LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
lfs2_ssize_t res = lfs2_file_rawwrite(lfs2, file, buffer, size);
LFS2_TRACE("lfs2_file_write -> %"PRId32, res);
LFS2_UNLOCK(lfs2->cfg);
return res;
}
#endif
lfs2_soff_t lfs2_file_seek(lfs2_t *lfs2, lfs2_file_t *file,
lfs2_soff_t off, int whence) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_seek(%p, %p, %"PRId32", %d)",
(void*)lfs2, (void*)file, off, whence);
LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, off, whence);
LFS2_TRACE("lfs2_file_seek -> %"PRId32, res);
LFS2_UNLOCK(lfs2->cfg);
return res;
}
#ifndef LFS2_READONLY
int lfs2_file_truncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t size) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_truncate(%p, %p, %"PRIu32")",
(void*)lfs2, (void*)file, size);
LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
err = lfs2_file_rawtruncate(lfs2, file, size);
LFS2_TRACE("lfs2_file_truncate -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#endif
lfs2_soff_t lfs2_file_tell(lfs2_t *lfs2, lfs2_file_t *file) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_tell(%p, %p)", (void*)lfs2, (void*)file);
LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
lfs2_soff_t res = lfs2_file_rawtell(lfs2, file);
LFS2_TRACE("lfs2_file_tell -> %"PRId32, res);
LFS2_UNLOCK(lfs2->cfg);
return res;
}
int lfs2_file_rewind(lfs2_t *lfs2, lfs2_file_t *file) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_rewind(%p, %p)", (void*)lfs2, (void*)file);
err = lfs2_file_rawrewind(lfs2, file);
LFS2_TRACE("lfs2_file_rewind -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
lfs2_soff_t lfs2_file_size(lfs2_t *lfs2, lfs2_file_t *file) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_file_size(%p, %p)", (void*)lfs2, (void*)file);
LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file));
lfs2_soff_t res = lfs2_file_rawsize(lfs2, file);
LFS2_TRACE("lfs2_file_size -> %"PRId32, res);
LFS2_UNLOCK(lfs2->cfg);
return res;
}
#ifndef LFS2_READONLY
int lfs2_mkdir(lfs2_t *lfs2, const char *path) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_mkdir(%p, \"%s\")", (void*)lfs2, path);
err = lfs2_rawmkdir(lfs2, path);
LFS2_TRACE("lfs2_mkdir -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#endif
int lfs2_dir_open(lfs2_t *lfs2, lfs2_dir_t *dir, const char *path) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_dir_open(%p, %p, \"%s\")", (void*)lfs2, (void*)dir, path);
LFS2_ASSERT(!lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)dir));
err = lfs2_dir_rawopen(lfs2, dir, path);
LFS2_TRACE("lfs2_dir_open -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
int lfs2_dir_close(lfs2_t *lfs2, lfs2_dir_t *dir) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_dir_close(%p, %p)", (void*)lfs2, (void*)dir);
err = lfs2_dir_rawclose(lfs2, dir);
LFS2_TRACE("lfs2_dir_close -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
int lfs2_dir_read(lfs2_t *lfs2, lfs2_dir_t *dir, struct lfs2_info *info) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_dir_read(%p, %p, %p)",
(void*)lfs2, (void*)dir, (void*)info);
err = lfs2_dir_rawread(lfs2, dir, info);
LFS2_TRACE("lfs2_dir_read -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
int lfs2_dir_seek(lfs2_t *lfs2, lfs2_dir_t *dir, lfs2_off_t off) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_dir_seek(%p, %p, %"PRIu32")",
(void*)lfs2, (void*)dir, off);
err = lfs2_dir_rawseek(lfs2, dir, off);
LFS2_TRACE("lfs2_dir_seek -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
lfs2_soff_t lfs2_dir_tell(lfs2_t *lfs2, lfs2_dir_t *dir) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_dir_tell(%p, %p)", (void*)lfs2, (void*)dir);
lfs2_soff_t res = lfs2_dir_rawtell(lfs2, dir);
LFS2_TRACE("lfs2_dir_tell -> %"PRId32, res);
LFS2_UNLOCK(lfs2->cfg);
return res;
}
int lfs2_dir_rewind(lfs2_t *lfs2, lfs2_dir_t *dir) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_dir_rewind(%p, %p)", (void*)lfs2, (void*)dir);
err = lfs2_dir_rawrewind(lfs2, dir);
LFS2_TRACE("lfs2_dir_rewind -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
lfs2_ssize_t lfs2_fs_size(lfs2_t *lfs2) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_fs_size(%p)", (void*)lfs2);
lfs2_ssize_t res = lfs2_fs_rawsize(lfs2);
LFS2_TRACE("lfs2_fs_size -> %"PRId32, res);
LFS2_UNLOCK(lfs2->cfg);
return res;
}
int lfs2_fs_traverse(lfs2_t *lfs2, int (*cb)(void *, lfs2_block_t), void *data) {
int err = LFS2_LOCK(lfs2->cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_fs_traverse(%p, %p, %p)",
(void*)lfs2, (void*)(uintptr_t)cb, data);
err = lfs2_fs_rawtraverse(lfs2, cb, data, true);
LFS2_TRACE("lfs2_fs_traverse -> %d", err);
LFS2_UNLOCK(lfs2->cfg);
return err;
}
#ifdef LFS2_MIGRATE
int lfs2_migrate(lfs2_t *lfs2, const struct lfs2_config *cfg) {
int err = LFS2_LOCK(cfg);
if (err) {
return err;
}
LFS2_TRACE("lfs2_migrate(%p, %p {.context=%p, "
".read=%p, .prog=%p, .erase=%p, .sync=%p, "
".read_size=%"PRIu32", .prog_size=%"PRIu32", "
".block_size=%"PRIu32", .block_count=%"PRIu32", "
".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
".lookahead_size=%"PRIu32", .read_buffer=%p, "
".prog_buffer=%p, .lookahead_buffer=%p, "
".name_max=%"PRIu32", .file_max=%"PRIu32", "
".attr_max=%"PRIu32"})",
(void*)lfs2, (void*)cfg, cfg->context,
(void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
(void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
cfg->name_max, cfg->file_max, cfg->attr_max);
err = lfs2_rawmigrate(lfs2, cfg);
LFS2_TRACE("lfs2_migrate -> %d", err);
LFS2_UNLOCK(cfg);
return err;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/littlefs/lfs2.c | C | apache-2.0 | 163,048 |
/*
* The little filesystem
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef LFS2_H
#define LFS2_H
#include <stdint.h>
#include <stdbool.h>
#include "lfs2_util.h"
#ifdef __cplusplus
extern "C"
{
#endif
/// Version info ///
// Software library version
// Major (top-nibble), incremented on backwards incompatible changes
// Minor (bottom-nibble), incremented on feature additions
#define LFS2_VERSION 0x00020003
#define LFS2_VERSION_MAJOR (0xffff & (LFS2_VERSION >> 16))
#define LFS2_VERSION_MINOR (0xffff & (LFS2_VERSION >> 0))
// Version of On-disk data structures
// Major (top-nibble), incremented on backwards incompatible changes
// Minor (bottom-nibble), incremented on feature additions
#define LFS2_DISK_VERSION 0x00020000
#define LFS2_DISK_VERSION_MAJOR (0xffff & (LFS2_DISK_VERSION >> 16))
#define LFS2_DISK_VERSION_MINOR (0xffff & (LFS2_DISK_VERSION >> 0))
/// Definitions ///
// Type definitions
typedef uint32_t lfs2_size_t;
typedef uint32_t lfs2_off_t;
typedef int32_t lfs2_ssize_t;
typedef int32_t lfs2_soff_t;
typedef uint32_t lfs2_block_t;
// Maximum name size in bytes, may be redefined to reduce the size of the
// info struct. Limited to <= 1022. Stored in superblock and must be
// respected by other littlefs drivers.
#ifndef LFS2_NAME_MAX
#define LFS2_NAME_MAX 255
#endif
// Maximum size of a file in bytes, may be redefined to limit to support other
// drivers. Limited on disk to <= 4294967296. However, above 2147483647 the
// functions lfs2_file_seek, lfs2_file_size, and lfs2_file_tell will return
// incorrect values due to using signed integers. Stored in superblock and
// must be respected by other littlefs drivers.
#ifndef LFS2_FILE_MAX
#define LFS2_FILE_MAX 2147483647
#endif
// Maximum size of custom attributes in bytes, may be redefined, but there is
// no real benefit to using a smaller LFS2_ATTR_MAX. Limited to <= 1022.
#ifndef LFS2_ATTR_MAX
#define LFS2_ATTR_MAX 1022
#endif
// Possible error codes, these are negative to allow
// valid positive return values
enum lfs2_error {
LFS2_ERR_OK = 0, // No error
LFS2_ERR_IO = -5, // Error during device operation
LFS2_ERR_CORRUPT = -84, // Corrupted
LFS2_ERR_NOENT = -2, // No directory entry
LFS2_ERR_EXIST = -17, // Entry already exists
LFS2_ERR_NOTDIR = -20, // Entry is not a dir
LFS2_ERR_ISDIR = -21, // Entry is a dir
LFS2_ERR_NOTEMPTY = -39, // Dir is not empty
LFS2_ERR_BADF = -9, // Bad file number
LFS2_ERR_FBIG = -27, // File too large
LFS2_ERR_INVAL = -22, // Invalid parameter
LFS2_ERR_NOSPC = -28, // No space left on device
LFS2_ERR_NOMEM = -12, // No more memory available
LFS2_ERR_NOATTR = -61, // No data/attr available
LFS2_ERR_NAMETOOLONG = -36, // File name too long
};
// File types
enum lfs2_type {
// file types
LFS2_TYPE_REG = 0x001,
LFS2_TYPE_DIR = 0x002,
// internally used types
LFS2_TYPE_SPLICE = 0x400,
LFS2_TYPE_NAME = 0x000,
LFS2_TYPE_STRUCT = 0x200,
LFS2_TYPE_USERATTR = 0x300,
LFS2_TYPE_FROM = 0x100,
LFS2_TYPE_TAIL = 0x600,
LFS2_TYPE_GLOBALS = 0x700,
LFS2_TYPE_CRC = 0x500,
// internally used type specializations
LFS2_TYPE_CREATE = 0x401,
LFS2_TYPE_DELETE = 0x4ff,
LFS2_TYPE_SUPERBLOCK = 0x0ff,
LFS2_TYPE_DIRSTRUCT = 0x200,
LFS2_TYPE_CTZSTRUCT = 0x202,
LFS2_TYPE_INLINESTRUCT = 0x201,
LFS2_TYPE_SOFTTAIL = 0x600,
LFS2_TYPE_HARDTAIL = 0x601,
LFS2_TYPE_MOVESTATE = 0x7ff,
// internal chip sources
LFS2_FROM_NOOP = 0x000,
LFS2_FROM_MOVE = 0x101,
LFS2_FROM_USERATTRS = 0x102,
};
// File open flags
enum lfs2_open_flags {
// open flags
LFS2_O_RDONLY = 1, // Open a file as read only
#ifndef LFS2_READONLY
LFS2_O_WRONLY = 2, // Open a file as write only
LFS2_O_RDWR = 3, // Open a file as read and write
LFS2_O_CREAT = 0x0100, // Create a file if it does not exist
LFS2_O_EXCL = 0x0200, // Fail if a file already exists
LFS2_O_TRUNC = 0x0400, // Truncate the existing file to zero size
LFS2_O_APPEND = 0x0800, // Move to end of file on every write
#endif
// internally used flags
#ifndef LFS2_READONLY
LFS2_F_DIRTY = 0x010000, // File does not match storage
LFS2_F_WRITING = 0x020000, // File has been written since last flush
#endif
LFS2_F_READING = 0x040000, // File has been read since last flush
#ifndef LFS2_READONLY
LFS2_F_ERRED = 0x080000, // An error occurred during write
#endif
LFS2_F_INLINE = 0x100000, // Currently inlined in directory entry
};
// File seek flags
enum lfs2_whence_flags {
LFS2_SEEK_SET = 0, // Seek relative to an absolute position
LFS2_SEEK_CUR = 1, // Seek relative to the current file position
LFS2_SEEK_END = 2, // Seek relative to the end of the file
};
// Configuration provided during initialization of the littlefs
struct lfs2_config {
// Opaque user provided context that can be used to pass
// information to the block device operations
void *context;
// Read a region in a block. Negative error codes are propogated
// to the user.
int (*read)(const struct lfs2_config *c, lfs2_block_t block,
lfs2_off_t off, void *buffer, lfs2_size_t size);
// Program a region in a block. The block must have previously
// been erased. Negative error codes are propogated to the user.
// May return LFS2_ERR_CORRUPT if the block should be considered bad.
int (*prog)(const struct lfs2_config *c, lfs2_block_t block,
lfs2_off_t off, const void *buffer, lfs2_size_t size);
// Erase a block. A block must be erased before being programmed.
// The state of an erased block is undefined. Negative error codes
// are propogated to the user.
// May return LFS2_ERR_CORRUPT if the block should be considered bad.
int (*erase)(const struct lfs2_config *c, lfs2_block_t block);
// Sync the state of the underlying block device. Negative error codes
// are propogated to the user.
int (*sync)(const struct lfs2_config *c);
#ifdef LFS2_THREADSAFE
// Lock the underlying block device. Negative error codes
// are propogated to the user.
int (*lock)(const struct lfs2_config *c);
// Unlock the underlying block device. Negative error codes
// are propogated to the user.
int (*unlock)(const struct lfs2_config *c);
#endif
// Minimum size of a block read. All read operations will be a
// multiple of this value.
lfs2_size_t read_size;
// Minimum size of a block program. All program operations will be a
// multiple of this value.
lfs2_size_t prog_size;
// Size of an erasable block. This does not impact ram consumption and
// may be larger than the physical erase size. However, non-inlined files
// take up at minimum one block. Must be a multiple of the read
// and program sizes.
lfs2_size_t block_size;
// Number of erasable blocks on the device.
lfs2_size_t block_count;
// Number of erase cycles before littlefs evicts metadata logs and moves
// the metadata to another block. Suggested values are in the
// range 100-1000, with large values having better performance at the cost
// of less consistent wear distribution.
//
// Set to -1 to disable block-level wear-leveling.
int32_t block_cycles;
// Size of block caches. Each cache buffers a portion of a block in RAM.
// The littlefs needs a read cache, a program cache, and one additional
// cache per file. Larger caches can improve performance by storing more
// data and reducing the number of disk accesses. Must be a multiple of
// the read and program sizes, and a factor of the block size.
lfs2_size_t cache_size;
// Size of the lookahead buffer in bytes. A larger lookahead buffer
// increases the number of blocks found during an allocation pass. The
// lookahead buffer is stored as a compact bitmap, so each byte of RAM
// can track 8 blocks. Must be a multiple of 8.
lfs2_size_t lookahead_size;
// Optional statically allocated read buffer. Must be cache_size.
// By default lfs2_malloc is used to allocate this buffer.
void *read_buffer;
// Optional statically allocated program buffer. Must be cache_size.
// By default lfs2_malloc is used to allocate this buffer.
void *prog_buffer;
// Optional statically allocated lookahead buffer. Must be lookahead_size
// and aligned to a 32-bit boundary. By default lfs2_malloc is used to
// allocate this buffer.
void *lookahead_buffer;
// Optional upper limit on length of file names in bytes. No downside for
// larger names except the size of the info struct which is controlled by
// the LFS2_NAME_MAX define. Defaults to LFS2_NAME_MAX when zero. Stored in
// superblock and must be respected by other littlefs drivers.
lfs2_size_t name_max;
// Optional upper limit on files in bytes. No downside for larger files
// but must be <= LFS2_FILE_MAX. Defaults to LFS2_FILE_MAX when zero. Stored
// in superblock and must be respected by other littlefs drivers.
lfs2_size_t file_max;
// Optional upper limit on custom attributes in bytes. No downside for
// larger attributes size but must be <= LFS2_ATTR_MAX. Defaults to
// LFS2_ATTR_MAX when zero.
lfs2_size_t attr_max;
};
// File info structure
struct lfs2_info {
// Type of the file, either LFS2_TYPE_REG or LFS2_TYPE_DIR
uint8_t type;
// Size of the file, only valid for REG files. Limited to 32-bits.
lfs2_size_t size;
// Name of the file stored as a null-terminated string. Limited to
// LFS2_NAME_MAX+1, which can be changed by redefining LFS2_NAME_MAX to
// reduce RAM. LFS2_NAME_MAX is stored in superblock and must be
// respected by other littlefs drivers.
char name[LFS2_NAME_MAX+1];
};
// Custom attribute structure, used to describe custom attributes
// committed atomically during file writes.
struct lfs2_attr {
// 8-bit type of attribute, provided by user and used to
// identify the attribute
uint8_t type;
// Pointer to buffer containing the attribute
void *buffer;
// Size of attribute in bytes, limited to LFS2_ATTR_MAX
lfs2_size_t size;
};
// Optional configuration provided during lfs2_file_opencfg
struct lfs2_file_config {
// Optional statically allocated file buffer. Must be cache_size.
// By default lfs2_malloc is used to allocate this buffer.
void *buffer;
// Optional list of custom attributes related to the file. If the file
// is opened with read access, these attributes will be read from disk
// during the open call. If the file is opened with write access, the
// attributes will be written to disk every file sync or close. This
// write occurs atomically with update to the file's contents.
//
// Custom attributes are uniquely identified by an 8-bit type and limited
// to LFS2_ATTR_MAX bytes. When read, if the stored attribute is smaller
// than the buffer, it will be padded with zeros. If the stored attribute
// is larger, then it will be silently truncated. If the attribute is not
// found, it will be created implicitly.
struct lfs2_attr *attrs;
// Number of custom attributes in the list
lfs2_size_t attr_count;
};
/// internal littlefs data structures ///
typedef struct lfs2_cache {
lfs2_block_t block;
lfs2_off_t off;
lfs2_size_t size;
uint8_t *buffer;
} lfs2_cache_t;
typedef struct lfs2_mdir {
lfs2_block_t pair[2];
uint32_t rev;
lfs2_off_t off;
uint32_t etag;
uint16_t count;
bool erased;
bool split;
lfs2_block_t tail[2];
} lfs2_mdir_t;
// littlefs directory type
typedef struct lfs2_dir {
struct lfs2_dir *next;
uint16_t id;
uint8_t type;
lfs2_mdir_t m;
lfs2_off_t pos;
lfs2_block_t head[2];
} lfs2_dir_t;
// littlefs file type
typedef struct lfs2_file {
struct lfs2_file *next;
uint16_t id;
uint8_t type;
lfs2_mdir_t m;
struct lfs2_ctz {
lfs2_block_t head;
lfs2_size_t size;
} ctz;
uint32_t flags;
lfs2_off_t pos;
lfs2_block_t block;
lfs2_off_t off;
lfs2_cache_t cache;
const struct lfs2_file_config *cfg;
} lfs2_file_t;
typedef struct lfs2_superblock {
uint32_t version;
lfs2_size_t block_size;
lfs2_size_t block_count;
lfs2_size_t name_max;
lfs2_size_t file_max;
lfs2_size_t attr_max;
} lfs2_superblock_t;
typedef struct lfs2_gstate {
uint32_t tag;
lfs2_block_t pair[2];
} lfs2_gstate_t;
// The littlefs filesystem type
typedef struct lfs2 {
lfs2_cache_t rcache;
lfs2_cache_t pcache;
lfs2_block_t root[2];
struct lfs2_mlist {
struct lfs2_mlist *next;
uint16_t id;
uint8_t type;
lfs2_mdir_t m;
} *mlist;
uint32_t seed;
lfs2_gstate_t gstate;
lfs2_gstate_t gdisk;
lfs2_gstate_t gdelta;
struct lfs2_free {
lfs2_block_t off;
lfs2_block_t size;
lfs2_block_t i;
lfs2_block_t ack;
uint32_t *buffer;
} free;
const struct lfs2_config *cfg;
lfs2_size_t name_max;
lfs2_size_t file_max;
lfs2_size_t attr_max;
#ifdef LFS2_MIGRATE
struct lfs21 *lfs21;
#endif
} lfs2_t;
/// Filesystem functions ///
#ifndef LFS2_READONLY
// Format a block device with the littlefs
//
// Requires a littlefs object and config struct. This clobbers the littlefs
// object, and does not leave the filesystem mounted. The config struct must
// be zeroed for defaults and backwards compatibility.
//
// Returns a negative error code on failure.
int lfs2_format(lfs2_t *lfs2, const struct lfs2_config *config);
#endif
// Mounts a littlefs
//
// Requires a littlefs object and config struct. Multiple filesystems
// may be mounted simultaneously with multiple littlefs objects. Both
// lfs2 and config must be allocated while mounted. The config struct must
// be zeroed for defaults and backwards compatibility.
//
// Returns a negative error code on failure.
int lfs2_mount(lfs2_t *lfs2, const struct lfs2_config *config);
// Unmounts a littlefs
//
// Does nothing besides releasing any allocated resources.
// Returns a negative error code on failure.
int lfs2_unmount(lfs2_t *lfs2);
/// General operations ///
#ifndef LFS2_READONLY
// Removes a file or directory
//
// If removing a directory, the directory must be empty.
// Returns a negative error code on failure.
int lfs2_remove(lfs2_t *lfs2, const char *path);
#endif
#ifndef LFS2_READONLY
// Rename or move a file or directory
//
// If the destination exists, it must match the source in type.
// If the destination is a directory, the directory must be empty.
//
// Returns a negative error code on failure.
int lfs2_rename(lfs2_t *lfs2, const char *oldpath, const char *newpath);
#endif
// Find info about a file or directory
//
// Fills out the info structure, based on the specified file or directory.
// Returns a negative error code on failure.
int lfs2_stat(lfs2_t *lfs2, const char *path, struct lfs2_info *info);
// Get a custom attribute
//
// Custom attributes are uniquely identified by an 8-bit type and limited
// to LFS2_ATTR_MAX bytes. When read, if the stored attribute is smaller than
// the buffer, it will be padded with zeros. If the stored attribute is larger,
// then it will be silently truncated. If no attribute is found, the error
// LFS2_ERR_NOATTR is returned and the buffer is filled with zeros.
//
// Returns the size of the attribute, or a negative error code on failure.
// Note, the returned size is the size of the attribute on disk, irrespective
// of the size of the buffer. This can be used to dynamically allocate a buffer
// or check for existance.
lfs2_ssize_t lfs2_getattr(lfs2_t *lfs2, const char *path,
uint8_t type, void *buffer, lfs2_size_t size);
#ifndef LFS2_READONLY
// Set custom attributes
//
// Custom attributes are uniquely identified by an 8-bit type and limited
// to LFS2_ATTR_MAX bytes. If an attribute is not found, it will be
// implicitly created.
//
// Returns a negative error code on failure.
int lfs2_setattr(lfs2_t *lfs2, const char *path,
uint8_t type, const void *buffer, lfs2_size_t size);
#endif
#ifndef LFS2_READONLY
// Removes a custom attribute
//
// If an attribute is not found, nothing happens.
//
// Returns a negative error code on failure.
int lfs2_removeattr(lfs2_t *lfs2, const char *path, uint8_t type);
#endif
/// File operations ///
// Open a file
//
// The mode that the file is opened in is determined by the flags, which
// are values from the enum lfs2_open_flags that are bitwise-ored together.
//
// Returns a negative error code on failure.
int lfs2_file_open(lfs2_t *lfs2, lfs2_file_t *file,
const char *path, int flags);
// Open a file with extra configuration
//
// The mode that the file is opened in is determined by the flags, which
// are values from the enum lfs2_open_flags that are bitwise-ored together.
//
// The config struct provides additional config options per file as described
// above. The config struct must be allocated while the file is open, and the
// config struct must be zeroed for defaults and backwards compatibility.
//
// Returns a negative error code on failure.
int lfs2_file_opencfg(lfs2_t *lfs2, lfs2_file_t *file,
const char *path, int flags,
const struct lfs2_file_config *config);
// Close a file
//
// Any pending writes are written out to storage as though
// sync had been called and releases any allocated resources.
//
// Returns a negative error code on failure.
int lfs2_file_close(lfs2_t *lfs2, lfs2_file_t *file);
// Synchronize a file on storage
//
// Any pending writes are written out to storage.
// Returns a negative error code on failure.
int lfs2_file_sync(lfs2_t *lfs2, lfs2_file_t *file);
// Read data from file
//
// Takes a buffer and size indicating where to store the read data.
// Returns the number of bytes read, or a negative error code on failure.
lfs2_ssize_t lfs2_file_read(lfs2_t *lfs2, lfs2_file_t *file,
void *buffer, lfs2_size_t size);
#ifndef LFS2_READONLY
// Write data to file
//
// Takes a buffer and size indicating the data to write. The file will not
// actually be updated on the storage until either sync or close is called.
//
// Returns the number of bytes written, or a negative error code on failure.
lfs2_ssize_t lfs2_file_write(lfs2_t *lfs2, lfs2_file_t *file,
const void *buffer, lfs2_size_t size);
#endif
// Change the position of the file
//
// The change in position is determined by the offset and whence flag.
// Returns the new position of the file, or a negative error code on failure.
lfs2_soff_t lfs2_file_seek(lfs2_t *lfs2, lfs2_file_t *file,
lfs2_soff_t off, int whence);
#ifndef LFS2_READONLY
// Truncates the size of the file to the specified size
//
// Returns a negative error code on failure.
int lfs2_file_truncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t size);
#endif
// Return the position of the file
//
// Equivalent to lfs2_file_seek(lfs2, file, 0, LFS2_SEEK_CUR)
// Returns the position of the file, or a negative error code on failure.
lfs2_soff_t lfs2_file_tell(lfs2_t *lfs2, lfs2_file_t *file);
// Change the position of the file to the beginning of the file
//
// Equivalent to lfs2_file_seek(lfs2, file, 0, LFS2_SEEK_SET)
// Returns a negative error code on failure.
int lfs2_file_rewind(lfs2_t *lfs2, lfs2_file_t *file);
// Return the size of the file
//
// Similar to lfs2_file_seek(lfs2, file, 0, LFS2_SEEK_END)
// Returns the size of the file, or a negative error code on failure.
lfs2_soff_t lfs2_file_size(lfs2_t *lfs2, lfs2_file_t *file);
/// Directory operations ///
#ifndef LFS2_READONLY
// Create a directory
//
// Returns a negative error code on failure.
int lfs2_mkdir(lfs2_t *lfs2, const char *path);
#endif
// Open a directory
//
// Once open a directory can be used with read to iterate over files.
// Returns a negative error code on failure.
int lfs2_dir_open(lfs2_t *lfs2, lfs2_dir_t *dir, const char *path);
// Close a directory
//
// Releases any allocated resources.
// Returns a negative error code on failure.
int lfs2_dir_close(lfs2_t *lfs2, lfs2_dir_t *dir);
// Read an entry in the directory
//
// Fills out the info structure, based on the specified file or directory.
// Returns a positive value on success, 0 at the end of directory,
// or a negative error code on failure.
int lfs2_dir_read(lfs2_t *lfs2, lfs2_dir_t *dir, struct lfs2_info *info);
// Change the position of the directory
//
// The new off must be a value previous returned from tell and specifies
// an absolute offset in the directory seek.
//
// Returns a negative error code on failure.
int lfs2_dir_seek(lfs2_t *lfs2, lfs2_dir_t *dir, lfs2_off_t off);
// Return the position of the directory
//
// The returned offset is only meant to be consumed by seek and may not make
// sense, but does indicate the current position in the directory iteration.
//
// Returns the position of the directory, or a negative error code on failure.
lfs2_soff_t lfs2_dir_tell(lfs2_t *lfs2, lfs2_dir_t *dir);
// Change the position of the directory to the beginning of the directory
//
// Returns a negative error code on failure.
int lfs2_dir_rewind(lfs2_t *lfs2, lfs2_dir_t *dir);
/// Filesystem-level filesystem operations
// Finds the current size of the filesystem
//
// Note: Result is best effort. If files share COW structures, the returned
// size may be larger than the filesystem actually is.
//
// Returns the number of allocated blocks, or a negative error code on failure.
lfs2_ssize_t lfs2_fs_size(lfs2_t *lfs2);
// Traverse through all blocks in use by the filesystem
//
// The provided callback will be called with each block address that is
// currently in use by the filesystem. This can be used to determine which
// blocks are in use or how much of the storage is available.
//
// Returns a negative error code on failure.
int lfs2_fs_traverse(lfs2_t *lfs2, int (*cb)(void*, lfs2_block_t), void *data);
#ifndef LFS2_READONLY
#ifdef LFS2_MIGRATE
// Attempts to migrate a previous version of littlefs
//
// Behaves similarly to the lfs2_format function. Attempts to mount
// the previous version of littlefs and update the filesystem so it can be
// mounted with the current version of littlefs.
//
// Requires a littlefs object and config struct. This clobbers the littlefs
// object, and does not leave the filesystem mounted. The config struct must
// be zeroed for defaults and backwards compatibility.
//
// Returns a negative error code on failure.
int lfs2_migrate(lfs2_t *lfs2, const struct lfs2_config *cfg);
#endif
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/littlefs/lfs2.h | C | apache-2.0 | 23,145 |
/*
* lfs2 util functions
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "lfs2_util.h"
// Only compile if user does not provide custom config
#ifndef LFS2_CONFIG
// Software CRC implementation with small lookup table
uint32_t lfs2_crc(uint32_t crc, const void *buffer, size_t size) {
static const uint32_t rtable[16] = {
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c,
};
const uint8_t *data = buffer;
for (size_t i = 0; i < size; i++) {
crc = (crc >> 4) ^ rtable[(crc ^ (data[i] >> 0)) & 0xf];
crc = (crc >> 4) ^ rtable[(crc ^ (data[i] >> 4)) & 0xf];
}
return crc;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/littlefs/lfs2_util.c | C | apache-2.0 | 866 |
/*
* lfs2 utility functions
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef LFS2_UTIL_H
#define LFS2_UTIL_H
// Users can override lfs2_util.h with their own configuration by defining
// LFS2_CONFIG as a header file to include (-DLFS2_CONFIG=lfs2_config.h).
//
// If LFS2_CONFIG is used, none of the default utils will be emitted and must be
// provided by the config file. To start, I would suggest copying lfs2_util.h
// and modifying as needed.
#ifdef LFS2_CONFIG
#define LFS2_STRINGIZE(x) LFS2_STRINGIZE2(x)
#define LFS2_STRINGIZE2(x) #x
#include LFS2_STRINGIZE(LFS2_CONFIG)
#else
// System includes
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <inttypes.h>
#ifndef LFS2_NO_MALLOC
#include <stdlib.h>
#endif
#ifndef LFS2_NO_ASSERT
#include <assert.h>
#endif
#if !defined(LFS2_NO_DEBUG) || \
!defined(LFS2_NO_WARN) || \
!defined(LFS2_NO_ERROR) || \
defined(LFS2_YES_TRACE)
#include <stdio.h>
#endif
#ifdef __cplusplus
extern "C"
{
#endif
// Macros, may be replaced by system specific wrappers. Arguments to these
// macros must not have side-effects as the macros can be removed for a smaller
// code footprint
// Logging functions
#ifdef LFS2_YES_TRACE
#define LFS2_TRACE_(fmt, ...) \
printf("%s:%d:trace: " fmt "%s\n", __FILE__, __LINE__, __VA_ARGS__)
#define LFS2_TRACE(...) LFS2_TRACE_(__VA_ARGS__, "")
#else
#define LFS2_TRACE(...)
#endif
#ifndef LFS2_NO_DEBUG
#define LFS2_DEBUG_(fmt, ...) \
printf("%s:%d:debug: " fmt "%s\n", __FILE__, __LINE__, __VA_ARGS__)
#define LFS2_DEBUG(...) LFS2_DEBUG_(__VA_ARGS__, "")
#else
#define LFS2_DEBUG(...)
#endif
#ifndef LFS2_NO_WARN
#define LFS2_WARN_(fmt, ...) \
printf("%s:%d:warn: " fmt "%s\n", __FILE__, __LINE__, __VA_ARGS__)
#define LFS2_WARN(...) LFS2_WARN_(__VA_ARGS__, "")
#else
#define LFS2_WARN(...)
#endif
#ifndef LFS2_NO_ERROR
#define LFS2_ERROR_(fmt, ...) \
printf("%s:%d:error: " fmt "%s\n", __FILE__, __LINE__, __VA_ARGS__)
#define LFS2_ERROR(...) LFS2_ERROR_(__VA_ARGS__, "")
#else
#define LFS2_ERROR(...)
#endif
// Runtime assertions
#ifndef LFS2_NO_ASSERT
#define LFS2_ASSERT(test) assert(test)
#else
#define LFS2_ASSERT(test)
#endif
// Builtin functions, these may be replaced by more efficient
// toolchain-specific implementations. LFS2_NO_INTRINSICS falls back to a more
// expensive basic C implementation for debugging purposes
// Min/max functions for unsigned 32-bit numbers
static inline uint32_t lfs2_max(uint32_t a, uint32_t b) {
return (a > b) ? a : b;
}
static inline uint32_t lfs2_min(uint32_t a, uint32_t b) {
return (a < b) ? a : b;
}
// Align to nearest multiple of a size
static inline uint32_t lfs2_aligndown(uint32_t a, uint32_t alignment) {
return a - (a % alignment);
}
static inline uint32_t lfs2_alignup(uint32_t a, uint32_t alignment) {
return lfs2_aligndown(a + alignment-1, alignment);
}
// Find the smallest power of 2 greater than or equal to a
static inline uint32_t lfs2_npw2(uint32_t a) {
#if !defined(LFS2_NO_INTRINSICS) && (defined(__GNUC__) || defined(__CC_ARM))
return 32 - __builtin_clz(a-1);
#else
uint32_t r = 0;
uint32_t s;
a -= 1;
s = (a > 0xffff) << 4; a >>= s; r |= s;
s = (a > 0xff ) << 3; a >>= s; r |= s;
s = (a > 0xf ) << 2; a >>= s; r |= s;
s = (a > 0x3 ) << 1; a >>= s; r |= s;
return (r | (a >> 1)) + 1;
#endif
}
// Count the number of trailing binary zeros in a
// lfs2_ctz(0) may be undefined
static inline uint32_t lfs2_ctz(uint32_t a) {
#if !defined(LFS2_NO_INTRINSICS) && defined(__GNUC__)
return __builtin_ctz(a);
#else
return lfs2_npw2((a & -a) + 1) - 1;
#endif
}
// Count the number of binary ones in a
static inline uint32_t lfs2_popc(uint32_t a) {
#if !defined(LFS2_NO_INTRINSICS) && (defined(__GNUC__) || defined(__CC_ARM))
return __builtin_popcount(a);
#else
a = a - ((a >> 1) & 0x55555555);
a = (a & 0x33333333) + ((a >> 2) & 0x33333333);
return (((a + (a >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24;
#endif
}
// Find the sequence comparison of a and b, this is the distance
// between a and b ignoring overflow
static inline int lfs2_scmp(uint32_t a, uint32_t b) {
return (int)(unsigned)(a - b);
}
// Convert between 32-bit little-endian and native order
static inline uint32_t lfs2_fromle32(uint32_t a) {
#if !defined(LFS2_NO_INTRINSICS) && ( \
(defined( BYTE_ORDER ) && defined( ORDER_LITTLE_ENDIAN ) && BYTE_ORDER == ORDER_LITTLE_ENDIAN ) || \
(defined(__BYTE_ORDER ) && defined(__ORDER_LITTLE_ENDIAN ) && __BYTE_ORDER == __ORDER_LITTLE_ENDIAN ) || \
(defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
return a;
#elif !defined(LFS2_NO_INTRINSICS) && ( \
(defined( BYTE_ORDER ) && defined( ORDER_BIG_ENDIAN ) && BYTE_ORDER == ORDER_BIG_ENDIAN ) || \
(defined(__BYTE_ORDER ) && defined(__ORDER_BIG_ENDIAN ) && __BYTE_ORDER == __ORDER_BIG_ENDIAN ) || \
(defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
return __builtin_bswap32(a);
#else
return (((uint8_t*)&a)[0] << 0) |
(((uint8_t*)&a)[1] << 8) |
(((uint8_t*)&a)[2] << 16) |
(((uint8_t*)&a)[3] << 24);
#endif
}
static inline uint32_t lfs2_tole32(uint32_t a) {
return lfs2_fromle32(a);
}
// Convert between 32-bit big-endian and native order
static inline uint32_t lfs2_frombe32(uint32_t a) {
#if !defined(LFS2_NO_INTRINSICS) && ( \
(defined( BYTE_ORDER ) && defined( ORDER_LITTLE_ENDIAN ) && BYTE_ORDER == ORDER_LITTLE_ENDIAN ) || \
(defined(__BYTE_ORDER ) && defined(__ORDER_LITTLE_ENDIAN ) && __BYTE_ORDER == __ORDER_LITTLE_ENDIAN ) || \
(defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
return __builtin_bswap32(a);
#elif !defined(LFS2_NO_INTRINSICS) && ( \
(defined( BYTE_ORDER ) && defined( ORDER_BIG_ENDIAN ) && BYTE_ORDER == ORDER_BIG_ENDIAN ) || \
(defined(__BYTE_ORDER ) && defined(__ORDER_BIG_ENDIAN ) && __BYTE_ORDER == __ORDER_BIG_ENDIAN ) || \
(defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
return a;
#else
return (((uint8_t*)&a)[0] << 24) |
(((uint8_t*)&a)[1] << 16) |
(((uint8_t*)&a)[2] << 8) |
(((uint8_t*)&a)[3] << 0);
#endif
}
static inline uint32_t lfs2_tobe32(uint32_t a) {
return lfs2_frombe32(a);
}
// Calculate CRC-32 with polynomial = 0x04c11db7
uint32_t lfs2_crc(uint32_t crc, const void *buffer, size_t size);
// Allocate memory, only used if buffers are not provided to littlefs
// Note, memory must be 64-bit aligned
static inline void *lfs2_malloc(size_t size) {
#ifndef LFS2_NO_MALLOC
return malloc(size);
#else
(void)size;
return NULL;
#endif
}
// Deallocate memory, only used if buffers are not provided to littlefs
static inline void lfs2_free(void *p) {
#ifndef LFS2_NO_MALLOC
free(p);
#else
(void)p;
#endif
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/littlefs/lfs2_util.h | C | apache-2.0 | 7,182 |
# This file is to be given as "make USER_C_MODULES=..." when building Micropython port
include(${CMAKE_CURRENT_LIST_DIR}/mkrules.cmake)
# lvgl bindings depend on lvgl itself, pull it in
include(${LVGL_DIR}/CMakeLists.txt)
# lvgl bindings target (the mpy module)
add_library(usermod_lv_bindings INTERFACE)
target_sources(usermod_lv_bindings INTERFACE ${LV_SRC})
target_include_directories(usermod_lv_bindings INTERFACE ${LV_INCLUDE})
target_link_libraries(usermod_lv_bindings INTERFACE lvgl_interface)
# make usermod (target declared by Micropython for all user compiled modules) link to bindings
# this way the bindings (and transitively lvgl_interface) get proper compilation flags
target_link_libraries(usermod INTERFACE usermod_lv_bindings)
# create targets for generated files
all_lv_bindings()
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/bindings.cmake | CMake | apache-2.0 | 805 |
/**
* @file monitor.c
*
*/
/*********************
* INCLUDES
*********************/
#include "SDL_monitor.h"
#if USE_MONITOR
#ifndef MONITOR_SDL_INCLUDE_PATH
#define MONITOR_SDL_INCLUDE_PATH <SDL2/SDL.h>
#endif
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include MONITOR_SDL_INCLUDE_PATH
#include "SDL_mouse.h"
/*********************
* DEFINES
*********************/
#ifndef MONITOR_ZOOM
#define MONITOR_ZOOM 1
#endif
#if defined(__EMSCRIPTEN__)
# define MONITOR_EMSCRIPTEN
#endif
/***********************
* GLOBAL PROTOTYPES
***********************/
/**********************
* STATIC VARIABLES
**********************/
static SDL_Window * window;
static SDL_Renderer * renderer;
static SDL_Texture * texture;
static uint32_t* tft_fb;
static int monitor_w;
static int monitor_h;
static volatile bool sdl_inited = false;
static volatile bool sdl_refr_qry = false;
static volatile bool sdl_quit_qry = false;
static int quit_filter(void * userdata, SDL_Event * event);
/**********************
* GLOBAL FUNCTIONS
**********************/
bool monitor_active(void)
{
return sdl_inited && !sdl_quit_qry;
}
/**
* Flush a buffer to the display. Calls 'lv_flush_ready()' when finished
*/
void monitor_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
/*Return if the area is out the screen or the monitor is not active*/
if(area->x2 < 0 || area->y2 < 0 || area->x1 > MONITOR_HOR_RES - 1 || area->y1 > MONITOR_VER_RES - 1
|| !monitor_active()) {
lv_disp_flush_ready(disp_drv);
return;
}
int32_t y;
#if LV_COLOR_DEPTH != 24 && LV_COLOR_DEPTH != 32 /*32 is valid but support 24 for backward compatibility too*/
int32_t x;
for(y = area->y1; y <= area->y2; y++) {
for(x = area->x1; x <= area->x2; x++) {
tft_fb[y * MONITOR_HOR_RES + x] = lv_color_to32(*color_p);
color_p++;
}
}
#else
uint32_t w = area->x2 - area->x1 + 1;
for(y = area->y1; y <= area->y2; y++) {
memcpy(&tft_fb[y * MONITOR_HOR_RES + area->x1], color_p, w * sizeof(lv_color_t));
color_p += w;
}
#endif
sdl_refr_qry = true;
/*IMPORTANT! It must be called to tell the system the flush is ready*/
lv_disp_flush_ready(disp_drv);
}
/**
* Handle "quit" event
*/
static int quit_filter(void * userdata, SDL_Event * event)
{
(void)userdata;
if(event->type == SDL_QUIT) {
sdl_quit_qry = true;
}
return 1;
}
/**
* Initialize the monitor
*/
void monitor_init(int w, int h)
{
sdl_refr_qry = false;
sdl_quit_qry = false;
monitor_w = w;
monitor_h = h;
tft_fb = (uint32_t*)malloc(MONITOR_HOR_RES * MONITOR_VER_RES * sizeof(uint32_t));
/*Initialize the SDL*/
SDL_Init(SDL_INIT_VIDEO);
SDL_SetEventFilter(quit_filter, NULL);
window = SDL_CreateWindow("TFT Simulator",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
MONITOR_HOR_RES * MONITOR_ZOOM, MONITOR_VER_RES * MONITOR_ZOOM, 0); /*last param. SDL_WINDOW_BORDERLESS to hide borders*/
#if MONITOR_VIRTUAL_MACHINE || defined(MONITOR_EMSCRIPTEN)
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
#else
renderer = SDL_CreateRenderer(window, -1, 0);
#endif
texture = SDL_CreateTexture(renderer,
SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, MONITOR_HOR_RES, MONITOR_VER_RES);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
/*Initialize the frame buffer to gray (77 is an empirical value) */
memset(tft_fb, 77, MONITOR_HOR_RES * MONITOR_VER_RES * sizeof(uint32_t));
SDL_UpdateTexture(texture, NULL, tft_fb, MONITOR_HOR_RES * sizeof(uint32_t));
sdl_refr_qry = true;
sdl_inited = true;
}
/**
* Deinit the monitor and close SDL
*/
void monitor_deinit(void)
{
sdl_quit_qry = true;
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
free(tft_fb);
}
/**
* This is SDL main loop. It draws the screen and handle mouse events.
* It should be called periodically, from the same thread Micropython is running
* This is done by schduling it using mp_sched_schedule
*/
void monitor_sdl_refr_core(void)
{
if(sdl_refr_qry != false) {
sdl_refr_qry = false;
SDL_UpdateTexture(texture, NULL, tft_fb, MONITOR_HOR_RES * sizeof(uint32_t));
SDL_RenderClear(renderer);
/*Test: Draw a background to test transparent screens (LV_COLOR_SCREEN_TRANSP)*/
// SDL_SetRenderDrawColor(renderer, 0xff, 0, 0, 0xff);
// SDL_Rect r;
// r.x = 0; r.y = 0; r.w = MONITOR_HOR_RES; r.w = MONITOR_VER_RES;
// SDL_RenderDrawRect(renderer, &r);
/*Update the renderer with the texture containing the rendered image*/
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
SDL_Event event;
while(monitor_active() && SDL_PollEvent(&event)) {
#if USE_MOUSE != 0
mouse_handler(&event);
#endif
#if USE_MOUSEWHEEL != 0
mousewheel_handler(&event);
#endif
#if USE_KEYBOARD
keyboard_handler(&event);
#endif
if((&event)->type == SDL_WINDOWEVENT) {
switch((&event)->window.event) {
#if SDL_VERSION_ATLEAST(2, 0, 5)
case SDL_WINDOWEVENT_TAKE_FOCUS:
#endif
case SDL_WINDOWEVENT_EXPOSED:
SDL_UpdateTexture(texture, NULL, tft_fb, MONITOR_HOR_RES * sizeof(uint32_t));
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
break;
default:
break;
}
}
}
if (sdl_quit_qry) {
monitor_deinit();
}
}
#endif /*USE_MONITOR*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/SDL/SDL_monitor.c | C | apache-2.0 | 5,930 |
/**
* @file monitor.h
*
*/
#ifndef MONITOR_H
#define MONITOR_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#ifdef LV_CONF_INCLUDE_SIMPLE
#include "lv_drv_conf.h"
#else
#include "lv_drv_conf.h"
#endif
#if USE_MONITOR
#include "lvgl/src/misc/lv_color.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
void monitor_init(int w, int h);
void monitor_deinit(void);
bool monitor_active(void);
void monitor_sdl_refr_core(void);
void monitor_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p);
/**********************
* MACROS
**********************/
#endif /* USE_MONITOR */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MONITOR_H */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/SDL/SDL_monitor.h | C | apache-2.0 | 899 |
/**
* @file mouse.c
*
*/
/*********************
* INCLUDES
*********************/
#include "SDL_mouse.h"
#if USE_MOUSE != 0
/*********************
* DEFINES
*********************/
#ifndef MONITOR_ZOOM
#define MONITOR_ZOOM 1
#endif
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
static bool left_button_down = false;
static int16_t first_x = 0, last_x = 0;
static int16_t first_y = 0, last_y = 0;
static bool mouse_was_read = false;
static int16_t cached_clicks = 0;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Get the current position and state of the mouse
* @param data store the mouse data here
* @return false: because the points are not buffered, so no more data to be read
*/
void mouse_read(struct _lv_indev_drv_t * indev_drv, lv_indev_data_t * data)
{
/* Replay cached clicks on its original coordinates */
if (cached_clicks > 0) {
cached_clicks--;
data->point.x = first_x;
data->point.y = first_y;
data->state = (cached_clicks&1)==1 ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
data->continue_reading = true;
return;
}
/* Store the collected data */
data->point.x = last_x;
data->point.y = last_y;
data->state = left_button_down ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
mouse_was_read = true;
data->continue_reading = false;
return;
}
/**
* It will be called from the main SDL thread
*/
void mouse_handler(SDL_Event * event)
{
switch(event->type) {
case SDL_MOUSEBUTTONUP:
if(event->button.button == SDL_BUTTON_LEFT) {
left_button_down = false;
if (!mouse_was_read) cached_clicks+=2;
}
break;
case SDL_MOUSEBUTTONDOWN:
if(event->button.button == SDL_BUTTON_LEFT) {
left_button_down = true;
last_x = event->motion.x / MONITOR_ZOOM;
last_y = event->motion.y / MONITOR_ZOOM;
if (mouse_was_read) {
first_x = last_x;
first_y = last_y;
}
mouse_was_read = false;
}
break;
case SDL_MOUSEMOTION:
last_x = event->motion.x / MONITOR_ZOOM;
last_y = event->motion.y / MONITOR_ZOOM;
break;
}
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/SDL/SDL_mouse.c | C | apache-2.0 | 2,661 |
/**
* @file mouse.h
*
*/
#ifndef MOUSE_H
#define MOUSE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#ifdef LV_CONF_INCLUDE_SIMPLE
#include "lv_drv_conf.h"
#else
#include "lv_drv_conf.h"
#endif
#if USE_MOUSE
#include <stdint.h>
#include <stdbool.h>
#include <SDL2/SDL.h>
#include "lvgl/src/hal/lv_hal_indev.h"
#ifndef MONITOR_SDL_INCLUDE_PATH
#define MONITOR_SDL_INCLUDE_PATH <SDL2/SDL.h>
#endif
#include MONITOR_SDL_INCLUDE_PATH
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize the mouse
*/
void mouse_init(void);
/**
* Get the current position and state of the mouse
* @param data store the mouse data here
* @return false: because the points are not buffered, so no more data to be read
*/
void mouse_read(struct _lv_indev_drv_t * indev_drv, lv_indev_data_t * data);
/**
* It will be called from the main SDL thread
*/
void mouse_handler(SDL_Event *event);
/**********************
* MACROS
**********************/
#endif /* USE_MOUSE */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* MOUSE_H */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/SDL/SDL_mouse.h | C | apache-2.0 | 1,266 |
/**
* @file lv_drv_conf.h
*
*/
#ifndef LV_DRV_CONF_H
#define LV_DRV_CONF_H
/*
* COPY THIS FILE AS lv_drv_conf.h
*/
#if 1 /*Set it to "1" to enable the content*/
#include "../../lib/lv_bindings/lvgl/lvgl.h"
/*********************
* DELAY INTERFACE
*********************/
#define LV_DRV_DELAY_INCLUDE <stdint.h> /*Dummy include by default*/
#define LV_DRV_DELAY_US(us) /*delay_us(us)*/ /*Delay the given number of microseconds*/
#define LV_DRV_DELAY_MS(ms) /*delay_ms(ms)*/ /*Delay the given number of milliseconds*/
/*********************
* DISPLAY INTERFACE
*********************/
/*------------
* Common
*------------*/
#define LV_DRV_DISP_INCLUDE <stdint.h> /*Dummy include by default*/
#define LV_DRV_DISP_CMD_DATA(val) /*pin_x_set(val)*/ /*Set the command/data pin to 'val'*/
#define LV_DRV_DISP_RST(val) /*pin_x_set(val)*/ /*Set the reset pin to 'val'*/
/*---------
* SPI
*---------*/
#define LV_DRV_DISP_SPI_CS(val) /*spi_cs_set(val)*/ /*Set the SPI's Chip select to 'val'*/
#define LV_DRV_DISP_SPI_WR_BYTE(data) /*spi_wr(data)*/ /*Write a byte the SPI bus*/
#define LV_DRV_DISP_SPI_WR_ARRAY(adr, n) /*spi_wr_mem(adr, n)*/ /*Write 'n' bytes to SPI bus from 'adr'*/
/*------------------
* Parallel port
*-----------------*/
#define LV_DRV_DISP_PAR_CS(val) /*par_cs_set(val)*/ /*Set the Parallel port's Chip select to 'val'*/
#define LV_DRV_DISP_PAR_SLOW /*par_slow()*/ /*Set low speed on the parallel port*/
#define LV_DRV_DISP_PAR_FAST /*par_fast()*/ /*Set high speed on the parallel port*/
#define LV_DRV_DISP_PAR_WR_WORD(data) /*par_wr(data)*/ /*Write a word to the parallel port*/
#define LV_DRV_DISP_PAR_WR_ARRAY(adr, n) /*par_wr_mem(adr,n)*/ /*Write 'n' bytes to Parallel ports from 'adr'*/
/***************************
* INPUT DEVICE INTERFACE
***************************/
/*----------
* Common
*----------*/
#define LV_DRV_INDEV_INCLUDE <stdint.h> /*Dummy include by default*/
#define LV_DRV_INDEV_RST(val) /*pin_x_set(val)*/ /*Set the reset pin to 'val'*/
#define LV_DRV_INDEV_IRQ_READ 0 /*pn_x_read()*/ /*Read the IRQ pin*/
/*---------
* SPI
*---------*/
#define LV_DRV_INDEV_SPI_CS(val) /*spi_cs_set(val)*/ /*Set the SPI's Chip select to 'val'*/
#define LV_DRV_INDEV_SPI_XCHG_BYTE(data) 0 /*spi_xchg(val)*/ /*Write 'val' to SPI and give the read value*/
/*---------
* I2C
*---------*/
#define LV_DRV_INDEV_I2C_START /*i2c_start()*/ /*Make an I2C start*/
#define LV_DRV_INDEV_I2C_STOP /*i2c_stop()*/ /*Make an I2C stop*/
#define LV_DRV_INDEV_I2C_RESTART /*i2c_restart()*/ /*Make an I2C restart*/
#define LV_DRV_INDEV_I2C_WR(data) /*i2c_wr(data)*/ /*Write a byte to the I1C bus*/
#define LV_DRV_INDEV_I2C_READ(last_read) 0 /*i2c_rd()*/ /*Read a byte from the I2C bud*/
/*********************
* DISPLAY DRIVERS
*********************/
/*-------------------
* Monitor of PC
*-------------------*/
#define USE_MONITOR 1
#if USE_MONITOR
#define MONITOR_HOR_RES monitor_w
#define MONITOR_VER_RES monitor_h
#define MONITOR_ZOOM 1 /* Scale window by this factor (useful when simulating small screens) */
#define MONITOR_SDL_INCLUDE_PATH <SDL2/SDL.h> /*Eclipse: <SDL2/SDL.h> Visual Studio: <SDL.h>*/
#define MONITOR_VIRTUAL_MACHINE 0 /*Different rendering should be used if running in a Virtual machine*/
#endif
/*----------------
* SSD1963
*--------------*/
#define USE_SSD1963 0
#if USE_SSD1963
#define SSD1963_HOR_RES LV_HOR_RES
#define SSD1963_VER_RES LV_VER_RES
#define SSD1963_HT 531
#define SSD1963_HPS 43
#define SSD1963_LPS 8
#define SSD1963_HPW 10
#define SSD1963_VT 288
#define SSD1963_VPS 12
#define SSD1963_FPS 4
#define SSD1963_VPW 10
#define SSD1963_HS_NEG 0 /*Negative hsync*/
#define SSD1963_VS_NEG 0 /*Negative vsync*/
#define SSD1963_ORI 0 /*0, 90, 180, 270*/
#define SSD1963_COLOR_DEPTH 16
#endif
/*----------------
* R61581
*--------------*/
#define USE_R61581 0
#if USE_R61581 != 0
#define R61581_HOR_RES LV_HOR_RES
#define R61581_VER_RES LV_VER_RES
#define R61581_HSPL 0 /*HSYNC signal polarity*/
#define R61581_HSL 10 /*HSYNC length (Not Implemented)*/
#define R61581_HFP 10 /*Horitontal Front poarch (Not Implemented)*/
#define R61581_HBP 10 /*Horitontal Back poarch (Not Implemented */
#define R61581_VSPL 0 /*VSYNC signal polarity*/
#define R61581_VSL 10 /*VSYNC length (Not Implemented)*/
#define R61581_VFP 8 /*Vertical Front poarch*/
#define R61581_VBP 8 /*Vertical Back poarch */
#define R61581_DPL 0 /*DCLK signal polarity*/
#define R61581_EPL 1 /*ENABLE signal polarity*/
#define R61581_ORI 0 /*0, 180*/
#define R61581_LV_COLOR_DEPTH 16 /*Fix 16 bit*/
#endif
/*------------------------------
* ST7565 (Monochrome, low res.)
*-----------------------------*/
#define USE_ST7565 0
#if USE_ST7565 != 0
/*No settings*/
#endif /*USE_ST7565*/
/*-----------------------------------------
* Linux frame buffer device (/dev/fbx)
*-----------------------------------------*/
#define USE_FBDEV 1
#if USE_FBDEV != 0
#define FBDEV_PATH "/dev/fb0"
#endif
/*====================
* Input devices
*===================*/
/*--------------
* XPT2046
*--------------*/
#define USE_XPT2046 0
#if USE_XPT2046 != 0
#define XPT2046_HOR_RES 480
#define XPT2046_VER_RES 320
#define XPT2046_X_MIN 200
#define XPT2046_Y_MIN 200
#define XPT2046_X_MAX 3800
#define XPT2046_Y_MAX 3800
#define XPT2046_AVG 4
#define XPT2046_INV 0
#endif
/*-----------------
* FT5406EE8
*-----------------*/
#define USE_FT5406EE8 0
#if USE_FT5406EE8
#define FT5406EE8_I2C_ADR 0x38 /*7 bit address*/
#endif
/*---------------
* AD TOUCH
*--------------*/
#define USE_AD_TOUCH 0
#if USE_AD_TOUCH != 0
/*No settings*/
#endif
/*---------------------------------------
* Mouse or touchpad on PC (using SDL)
*-------------------------------------*/
#define USE_MOUSE 1
#if USE_MOUSE
/*No settings*/
#endif
/*-------------------------------------------
* Mousewheel as encoder on PC (using SDL)
*------------------------------------------*/
#define USE_MOUSEWHEEL 0
#if USE_MOUSEWHEEL
/*No settings*/
#endif
/*-------------------------------------------------
* Mouse or touchpad as evdev interface (for Linux based systems)
*------------------------------------------------*/
#define USE_EVDEV 0
#if USE_EVDEV
#define EVDEV_NAME "/dev/input/event0" /*You can use the "evtest" Linux tool to get the list of devices and test them*/
#define EVDEV_SWAP_AXES 0 /*Swap the x and y axes of the touchscreen*/
#define EVDEV_SCALE 0 /* Scale input, e.g. if touchscreen resolution does not match display resolution */
#if EVDEV_SCALE
#define EVDEV_SCALE_HOR_RES (4096) /* Horizontal resolution of touchscreen */
#define EVDEV_SCALE_VER_RES (4096) /* Vertical resolution of touchscreen */
#endif /*EVDEV_SCALE*/
#define EVDEV_CALIBRATE 0 /*Scale and offset the touchscreen coordinates by using maximum and minimum values for each axis*/
#if EVDEV_CALIBRATE
#define EVDEV_HOR_MIN 3800 /*If EVDEV_XXX_MIN > EVDEV_XXX_MAX the XXX axis is automatically inverted*/
#define EVDEV_HOR_MAX 200
#define EVDEV_VER_MIN 200
#define EVDEV_VER_MAX 3800
#endif /*EVDEV_SCALE*/
#endif /*USE_EVDEV*/
/*-------------------------------
* Keyboard of a PC (using SDL)
*------------------------------*/
#define USE_KEYBOARD 0
#if USE_KEYBOARD
/*No settings*/
#endif
#endif /*LV_DRV_CONF_H*/
#endif /*End of "Content enable"*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/SDL/lv_drv_conf.h | C | apache-2.0 | 8,173 |
#include "../include/common.h"
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#endif
#include <errno.h>
#include <signal.h>
#include <pthread.h>
#include "SDL_monitor.h"
#include "SDL_mouse.h"
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
/* Defines the LittlevGL tick rate in milliseconds. */
/* Increasing this value might help with CPU usage at the cost of lower
* responsiveness. */
#define LV_TICK_RATE 20
/* Default screen dimensions */
#define LV_HOR_RES_MAX (480)
#define LV_VER_RES_MAX (320)
//////////////////////////////////////////////////////////////////////////////
STATIC pthread_t mp_thread;
STATIC mp_obj_t mp_refresh_SDL()
{
if (monitor_active()) monitor_sdl_refr_core();
return mp_const_none;
}
STATIC mp_obj_t mp_lv_task_handler(mp_obj_t arg)
{
mp_refresh_SDL();
lv_task_handler();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_lv_task_handler_obj, mp_lv_task_handler);
#ifndef __EMSCRIPTEN__
STATIC int tick_thread(void * data)
{
(void)data;
Uint64 pfreq = SDL_GetPerformanceFrequency();
Uint64 tick_ms = (pfreq / 1000) * LV_TICK_RATE;
Uint64 delta, acc = 0;
while(monitor_active()) {
delta = SDL_GetPerformanceCounter();
SDL_Delay(LV_TICK_RATE); /*Sleep for LV_TICK_RATE millisecond*/
delta = SDL_GetPerformanceCounter() - delta;
acc += delta - tick_ms;
lv_tick_inc(LV_TICK_RATE); /*Tell LittelvGL that LV_TICK_RATE milliseconds were elapsed*/
if (acc >= tick_ms) {
lv_tick_inc(LV_TICK_RATE);
acc -= tick_ms;
}
mp_sched_schedule((mp_obj_t)&mp_lv_task_handler_obj, mp_const_none);
pthread_kill(mp_thread, SIGUSR1); // interrupt REPL blocking input. See handle_sigusr1
}
return 0;
}
#else
STATIC void mp_lv_main_loop(void)
{
mp_sched_schedule((mp_obj_t)&mp_lv_task_handler_obj, mp_const_none);
lv_tick_inc(LV_TICK_RATE);
}
#endif
static void handle_sigusr1(int signo)
{
// Let the signal pass. blocking function would return E_INTR.
// This would cause a call to "mp_handle_pending" even when
// waiting for user input.
// See https://github.com/micropython/micropython/pull/5723
}
STATIC mp_obj_t mp_init_SDL(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args)
{
enum { ARG_w, ARG_h, ARG_auto_refresh };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_w, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = LV_HOR_RES_MAX} },
{ MP_QSTR_h, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = LV_VER_RES_MAX} },
{ MP_QSTR_auto_refresh, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} },
};
// parse args
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
monitor_init(args[ARG_w].u_int, args[ARG_h].u_int);
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(mp_lv_main_loop, 1000 / LV_TICK_RATE, 0);
/* Required for HTML input elements to work */
SDL_EventState(SDL_TEXTINPUT, SDL_DISABLE);
SDL_EventState(SDL_KEYDOWN, SDL_DISABLE);
SDL_EventState(SDL_KEYUP, SDL_DISABLE);
#else
if (args[ARG_auto_refresh].u_bool) {
SDL_CreateThread(tick_thread, "tick", NULL);
}
#endif
if (args[ARG_auto_refresh].u_bool) {
mp_thread = pthread_self();
struct sigaction sa;
sa.sa_handler = handle_sigusr1;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
}
return mp_const_none;
}
STATIC mp_obj_t mp_deinit_SDL()
{
monitor_deinit();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mp_init_SDL_obj, 0, mp_init_SDL);
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_deinit_SDL_obj, mp_deinit_SDL);
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_refresh_SDL_obj, mp_refresh_SDL);
DEFINE_PTR_OBJ(monitor_flush);
DEFINE_PTR_OBJ(mouse_read);
STATIC const mp_rom_map_elem_t SDL_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_SDL) },
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&mp_init_SDL_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mp_deinit_SDL_obj) },
{ MP_ROM_QSTR(MP_QSTR_refresh), MP_ROM_PTR(&mp_refresh_SDL_obj) },
{ MP_ROM_QSTR(MP_QSTR_monitor_flush), MP_ROM_PTR(&PTR_OBJ(monitor_flush))},
{ MP_ROM_QSTR(MP_QSTR_mouse_read), MP_ROM_PTR(&PTR_OBJ(mouse_read))},
};
STATIC MP_DEFINE_CONST_DICT (
mp_module_SDL_globals,
SDL_globals_table
);
const mp_obj_module_t mp_module_SDL = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_SDL_globals
};
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/SDL/modSDL.c | C | apache-2.0 | 4,736 |
#include "../include/common.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/gc.h"
#include "py/stackctrl.h"
#include "mphalport.h"
#include "espidf.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "soc/cpu.h"
// ESP IDF has some functions that are declared but not implemented.
// To avoid linking errors, provide empty implementation
inline void gpio_pin_wakeup_disable(void){}
inline void gpio_pin_wakeup_enable(uint32_t i, GPIO_INT_TYPE intr_state){}
inline void gpio_intr_ack_high(uint32_t ack_mask){}
inline void gpio_intr_ack(uint32_t ack_mask){}
inline uint32_t gpio_intr_pending_high(void){return 0;}
inline uint32_t gpio_intr_pending(void){return 0;}
inline void gpio_intr_handler_register(gpio_intr_handler_fn_t fn, void *arg){}
inline void gpio_init(void){}
void task_delay_ms(int ms)
{
vTaskDelay(ms / portTICK_RATE_MS);
}
// ISR callbacks handling
// Can't use mp_sched_schedule because lvgl won't yield to give micropython a chance to run
// Must run Micropython in ISR itself.
DEFINE_PTR_OBJ_TYPE(spi_transaction_ptr_type, MP_QSTR_spi_transaction_ptr_t);
typedef struct{
mp_ptr_t spi_transaction_ptr;
mp_obj_t pre_cb;
mp_obj_t post_cb;
} mp_spi_device_callbacks_t;
void *spi_transaction_set_cb(mp_obj_t pre_cb, mp_obj_t post_cb)
{
mp_spi_device_callbacks_t *callbacks = m_new_obj(mp_spi_device_callbacks_t);
callbacks->spi_transaction_ptr.base.type = &spi_transaction_ptr_type;
callbacks->pre_cb = pre_cb != mp_const_none? pre_cb: NULL;
callbacks->post_cb = post_cb != mp_const_none? post_cb: NULL;
return callbacks;
}
STATIC void isr_print_strn(void *env, const char *str, size_t len) {
size_t i;
(void)env;
for (i=0; i<len; i++) ets_write_char_uart(str[i]);
}
static const mp_print_t mp_isr_print = {NULL, isr_print_strn};
// Called in ISR context!
//
static inline void cb_isr(mp_obj_t cb, mp_obj_t arg)
{
if (cb != NULL && cb != mp_const_none) {
volatile uint32_t sp = (uint32_t)get_sp();
// Calling micropython from ISR
// See: https://github.com/micropython/micropython/issues/4895
void *old_state = mp_thread_get_state();
mp_state_thread_t ts; // local thread state for the ISR
mp_thread_set_state(&ts);
mp_stack_set_top((void*)sp); // need to include in root-pointer scan
mp_stack_set_limit(configIDLE_TASK_STACK_SIZE - 1024); // tune based on ISR thread stack size
mp_locals_set(mp_state_ctx.thread.dict_locals); // use main thread's locals
mp_globals_set(mp_state_ctx.thread.dict_globals); // use main thread's globals
mp_sched_lock(); // prevent VM from switching to another MicroPython thread
gc_lock(); // prevent memory allocation
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_call_function_1(cb, arg);
nlr_pop();
} else {
ets_printf("Uncaught exception in IRQ callback handler!\n");
mp_obj_print_exception(&mp_isr_print, MP_OBJ_FROM_PTR(nlr.ret_val));
}
gc_unlock();
mp_sched_unlock();
mp_thread_set_state(old_state);
mp_hal_wake_main_task_from_isr();
}
}
// Called in ISR context!
void ex_spi_pre_cb_isr(spi_transaction_t *trans)
{
mp_spi_device_callbacks_t *self = (mp_spi_device_callbacks_t*)trans->user;
if (self) {
self->spi_transaction_ptr.ptr = trans;
cb_isr(self->pre_cb, MP_OBJ_FROM_PTR(self));
}
}
// Called in ISR context!
void ex_spi_post_cb_isr(spi_transaction_t *trans)
{
mp_spi_device_callbacks_t *self = (mp_spi_device_callbacks_t*)trans->user;
if (self) {
self->spi_transaction_ptr.ptr = trans;
cb_isr(self->post_cb, MP_OBJ_FROM_PTR(self));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ILI9xxx flush and ISR implementation in C
#include "lvgl/lvgl.h"
DMA_ATTR static uint8_t dma_buf[4] = {0};
DMA_ATTR static spi_transaction_t spi_trans = {0};
static void spi_send_value(const uint8_t *value, uint8_t size, spi_device_handle_t spi)
{
spi_trans.length = size*8;
spi_trans.tx_buffer = value;
spi_trans.user = NULL;
spi_device_polling_transmit(spi, &spi_trans);
}
static inline void ili9xxx_send_cmd(uint8_t cmd, int dc, spi_device_handle_t spi)
{
dma_buf[0] = cmd;
gpio_set_level(dc, 0);
spi_send_value(dma_buf, 1, spi);
}
static inline void ili9xxx_send_data(const uint8_t *value, int dc, spi_device_handle_t spi)
{
gpio_set_level(dc, 1);
spi_send_value(value, 4, spi);
}
static void ili9xxx_send_data_dma(void *disp_drv, void *data, size_t size, int dc, spi_device_handle_t spi)
{
gpio_set_level(dc, 1);
spi_trans.length = size*8;
spi_trans.tx_buffer = data;
spi_trans.user = disp_drv;
spi_device_queue_trans(spi, &spi_trans, -1);
}
void ili9xxx_post_cb_isr(spi_transaction_t *trans)
{
if (trans->user)
lv_disp_flush_ready(trans->user);
}
typedef struct {
uint8_t blue;
uint8_t green;
uint8_t red;
} color24_t;
#define DISPLAY_TYPE_ILI9341 1
#define DISPLAY_TYPE_ILI9488 2
void ili9xxx_flush(void *_disp_drv, const void *_area, void *_color_p)
{
lv_disp_drv_t *disp_drv = _disp_drv;
const lv_area_t *area = _area;
lv_color_t *color_p = _color_p;
// We use disp_drv->user_data to pass data from MP to C
// The following lines extract dc and spi
int dc = mp_obj_get_int(mp_obj_dict_get(disp_drv->user_data, MP_OBJ_NEW_QSTR(MP_QSTR_dc)));
int dt = mp_obj_get_int(mp_obj_dict_get(disp_drv->user_data, MP_OBJ_NEW_QSTR(MP_QSTR_dt)));
mp_buffer_info_t buffer_info;
mp_get_buffer_raise(mp_obj_dict_get(disp_drv->user_data, MP_OBJ_NEW_QSTR(MP_QSTR_spi)), &buffer_info, MP_BUFFER_READ);
spi_device_handle_t *spi_ptr = buffer_info.buf;
// Column addresses
ili9xxx_send_cmd(0x2A, dc, *spi_ptr);
dma_buf[0] = (area->x1 >> 8) & 0xFF;
dma_buf[1] = area->x1 & 0xFF;
dma_buf[2] = (area->x2 >> 8) & 0xFF;
dma_buf[3] = area->x2 & 0xFF;
ili9xxx_send_data(dma_buf, dc, *spi_ptr);
// Page addresses
ili9xxx_send_cmd(0x2B, dc, *spi_ptr);
dma_buf[0] = (area->y1 >> 8) & 0xFF;
dma_buf[1] = area->y1 & 0xFF;
dma_buf[2] = (area->y2 >> 8) & 0xFF;
dma_buf[3] = area->y2 & 0xFF;
ili9xxx_send_data(dma_buf, dc, *spi_ptr);
// Memory write by DMA, disp_flush_ready when finished
ili9xxx_send_cmd(0x2C, dc, *spi_ptr);
size_t size = (area->x2 - area->x1 + 1) * (area->y2 - area->y1 + 1);
uint8_t color_size = 2;
if ( dt == DISPLAY_TYPE_ILI9488 ) {
color_size = 3;
/*Convert ARGB to RGB is required (cut off A-byte)*/
size_t i;
lv_color32_t* tmp32 = (lv_color32_t*) color_p;
color24_t* tmp24 = (color24_t*) color_p;
for(i=0; i < size; i++) {
tmp24[i].red = tmp32[i].ch.red;
tmp24[i].green = tmp32[i].ch.green;
tmp24[i].blue = tmp32[i].ch.blue;
}
}
ili9xxx_send_data_dma(disp_drv, color_p, size * color_size, dc, *spi_ptr);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/espidf.c | C | apache-2.0 | 6,949 |
/**
* This file defines the Micorpython API to ESP-IDF
* It is used as input to gen_mpy.py to create a micropython module
**/
#if __has_include("esp_idf_version.h")
# include "esp_idf_version.h"
#endif
// Disable some macros and includes that make pycparser choke
#ifdef PYCPARSER
#define __attribute__(x)
#define _Static_assert(x,y)
#define __extension__
#define _SOC_IO_MUX_REG_H_
#define _SYS_REENT_H_
#define PORTMACRO_H
#define PORTABLE_H
#define INC_FREERTOS_H
#define QUEUE_H
#define SEMAPHORE_H
#define XTENSA_HAL_H
#define _SOC_I2S_STRUCT_H_
#define XTRUNTIME_H
#define _SOC_SPI_STRUCT_H_
#define _SOC_RTC_CNTL_STRUCT_H_
#define __XTENSA_API_H__
#define _SOC_GPIO_STRUCT_H_
#define _SOC_RTC_IO_STRUCT_H_
#define _SOC_PCNT_STRUCT_H_
#define _SYS_FCNTL_H_
#define __SYS_ARCH_H__
#define LIST_H
#define INC_TASK_H
#define LWIP_HDR_NETIF_H
#define ESP_EVENT_H_
#define __SNTP_H__
#define XTENSA_CONFIG_CORE_H
#define _SOC_SPI_MEM_STRUCT_H_
typedef int BaseType_t;
typedef unsigned int UBaseType_t;
typedef void* system_event_t;
typedef void *intr_handle_t;
// Exclude SOC just because it contains large structs that don't interest the user
#define _SOC_SPI_PERIPH_H_
typedef void *spi_dev_t;
// TODO: Check why lldesc_t causes inifinite recursion on gen_mpy.py
#define _ROM_LLDESC_H_
typedef void *lldesc_t;
// FreeRTOS definitions we want available on Micropython
#include <stdint.h>
typedef uint32_t TickType_t;
typedef void * TaskHandle_t;
static inline uint32_t xPortGetCoreID();
UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask );
// Micropython specific types
typedef void *mp_obj_t;
static inline void SPH0645_WORKAROUND(int i2s_num);
static inline void get_ccount(int *ccount);
// Memory management helper functions
void * memcpy ( void * destination, const void * source, size_t num );
void * memset ( void * ptr, int value, size_t num );
#else // PYCPARSER
/////////////////////////////////////////////////////////////////////////////////////////////
// A workaround for SPH0645 I2S, see:
// - https://hackaday.io/project/162059-street-sense/log/160705-new-i2s-microphone/discussion-124677
// - https://www.esp32.com/viewtopic.php?t=4997#p45366
// Since reg access is based on macros, this cannot currently be directly implemented in Micropython
#include "soc/i2s_reg.h" // for SPH0645_WORKAROUND
static inline void SPH0645_WORKAROUND(int i2s_num)
{
REG_SET_BIT( I2S_TIMING_REG(i2s_num), BIT(9));
REG_SET_BIT( I2S_CONF_REG(i2s_num), I2S_RX_MSB_SHIFT);
}
/////////////////////////////////////////////////////////////////////////////////////////////
// Helper function to measure CPU cycles
//
static inline void get_ccount(int *ccount)
{
asm volatile("rsr.ccount %0" : "=a"(*ccount));
}
#endif //PYCPARSER
// The following includes are the source of the esp-idf micropython module.
// All included files are API we want to include in the module
#if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 4
# if CONFIG_IDF_TARGET_ESP32
# include "esp32/clk.h"
# elif CONFIG_IDF_TARGET_ESP32S2
# include "esp32s2/clk.h"
# elif CONFIG_IDF_TARGET_ESP32S3
# include "esp32s3/clk.h"
# elif CONFIG_IDF_TARGET_ESP32C3
# include "esp32c3/clk.h"
# elif CONFIG_IDF_TARGET_ESP32H2
# include "esp32h2/clk.h"
# else // CONFIG_IDF_TARGET_* not defined
# include "esp32/clk.h"
# endif
#else
# include "esp_clk.h"
#endif
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "driver/adc.h"
#include "driver/i2s.h"
#include "driver/pcnt.h"
#include "mdns.h"
#include "esp_http_client.h"
#include "sh2lib.h"
/////////////////////////////////////////////////////////////////////////////////////////////
// Helper function to register HTTP event handler
// Needed to fulfill gen_mpy.py callback conventions
//
static inline void esp_http_client_register_event_handler(esp_http_client_config_t *config, http_event_handle_cb http_event_handler, void *user_data)
{
config->event_handler = http_event_handler;
config->user_data = user_data;
}
// We don't want the whole FreeRTOS, only selected functions
void task_delay_ms(int ms);
// The binding only publishes structs that are used in some function. We need spi_transaction_ext_t
// TOOD: Find some way to mark structs for binding export instead of new function.
static inline void set_spi_transaction_ext(
spi_transaction_ext_t *ext_trans,
spi_transaction_t *trans,
uint8_t command_bits,
uint8_t address_bits){
ext_trans->base = *trans;
ext_trans->command_bits = command_bits;
ext_trans->address_bits = address_bits;
}
// Wrapper for safe ISR callbacks from micropython
// Need to call both spi_transaction_set_cb and set spi_pre/post_cb_isr!
// Use this to set pre/post callbacks for spi transaction.
// pre_cb/post_cb should be either a callable object or "None".
// Result should be set to spi_transaction_t user field.
// Allocates RAM.
void *spi_transaction_set_cb(mp_obj_t pre_cb, mp_obj_t post_cb);
// These functions can be set into pre_cb/post_cb of spi_device_interface_config_t
void ex_spi_pre_cb_isr(spi_transaction_t *trans);
void ex_spi_post_cb_isr(spi_transaction_t *trans);
// Useful constants
#define EXPORT_CONST_INT(int_value) enum {ENUM_##int_value = int_value}
#if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 4
// SPI HOST enum was changed to macros on v4
enum {
ENUM_SPI_HOST = SPI_HOST,
ENUM_HSPI_HOST = HSPI_HOST,
ENUM_VSPI_HOST = VSPI_HOST,
};
#endif
enum {
ENUM_portMAX_DELAY = portMAX_DELAY
};
enum {
ENUM_I2S_PIN_NO_CHANGE = I2S_PIN_NO_CHANGE
};
enum {
ENUM_SPI_DEVICE_TXBIT_LSBFIRST = SPI_DEVICE_TXBIT_LSBFIRST,
ENUM_SPI_DEVICE_RXBIT_LSBFIRST = SPI_DEVICE_RXBIT_LSBFIRST,
ENUM_SPI_DEVICE_BIT_LSBFIRST = SPI_DEVICE_BIT_LSBFIRST,
ENUM_SPI_DEVICE_3WIRE = SPI_DEVICE_3WIRE,
ENUM_SPI_DEVICE_POSITIVE_CS = SPI_DEVICE_POSITIVE_CS,
ENUM_SPI_DEVICE_HALFDUPLEX = SPI_DEVICE_HALFDUPLEX,
ENUM_SPI_DEVICE_NO_DUMMY = SPI_DEVICE_NO_DUMMY,
ENUM_SPI_DEVICE_CLK_AS_CS = SPI_DEVICE_CLK_AS_CS,
};
enum {
ENUM_SPI_TRANS_MODE_DIO = SPI_TRANS_MODE_DIO,
ENUM_SPI_TRANS_MODE_QIO = SPI_TRANS_MODE_QIO,
ENUM_SPI_TRANS_MODE_DIOQIO_ADDR = SPI_TRANS_MODE_DIOQIO_ADDR,
ENUM_SPI_TRANS_USE_RXDATA = SPI_TRANS_USE_RXDATA,
ENUM_SPI_TRANS_USE_TXDATA = SPI_TRANS_USE_TXDATA,
ENUM_SPI_TRANS_VARIABLE_CMD = SPI_TRANS_VARIABLE_CMD,
ENUM_SPI_TRANS_VARIABLE_ADDR = SPI_TRANS_VARIABLE_ADDR,
};
enum {
ENUM_MALLOC_CAP_DMA = MALLOC_CAP_DMA,
ENUM_MALLOC_CAP_INTERNAL = MALLOC_CAP_INTERNAL,
ENUM_MALLOC_CAP_SPIRAM = MALLOC_CAP_SPIRAM,
};
enum {
ENUM_ESP_TASK_PRIO_MAX = ESP_TASK_PRIO_MAX,
ENUM_ESP_TASK_PRIO_MIN = ESP_TASK_PRIO_MIN,
};
/////////////////////////////////////////////////////////////////////////////////////////////
// ili9xxx flush and ISR in C
//
// disp_drv->user_data should be a dict that contains dc and spi, setup by micropython.
// like this: "self.disp_drv.user_data = {'dc': self.dc, 'spi': self.spi, 'dt': display_type}"
void ili9xxx_post_cb_isr(spi_transaction_t *trans);
void ili9xxx_flush(void *disp_drv, const void *area, void *color_p);
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/espidf.h | C | apache-2.0 | 7,212 |
##############################################################################
#
# Wrapper function for backward compatibility with new ILI9XXX library.
#
##############################################################################
print("""
***************************************
* This library is obsoled now!
* Please, use ili9XXX library instead:
*
* from ili9XXX import ili9341
*
***************************************
""")
from ili9XXX import ili9341
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/ili9341.py | Python | apache-2.0 | 466 |
##############################################################################
# Pure/Hybrid micropython lvgl display driver for ili9341 and ili9488 on ESP32
#
# For ili9341 display:
#
# Build micropython with
# LV_CFLAGS="-DLV_COLOR_DEPTH=16 -DLV_COLOR_16_SWAP=1"
# (make parameter) to configure LVGL use the same color format as ili9341
# and prevent the need to loop over all pixels to translate them.
#
# For ili9488 display:
#
# Build micropython with
# LV_CFLAGS="-DLV_COLOR_DEPTH=32"
# (make parameter) to configure LVGL use the ARGB color format, which can be
# easily converted to RGB format used by ili9488 display.
#
# Default SPI freq is set to 40MHz. This means cca 9fps of full screen
# redraw. to increase FPS, you can use 80MHz SPI - easily add parameter
# mhz=80 in initialization of driver.
#
# For gc9a01 display:
#
# Build micropython with
# LV_CFLAGS="-DLV_COLOR_DEPTH=16 -DLV_COLOR_16_SWAP=1"
# (make parameter) to configure LVGL use the same color format as ili9341
# and prevent the need to loop over all pixels to translate them.
#
# Default SPI freq is set to 60MHz as that is the maximum the tested dislay
# would suport despite the datasheet suggesting that higher freqs would be
# supported
#
# Critical function for high FPS are flush and ISR.
# when "hybrid=True", use C implementation for these functions instead of
# pure python implementation. This improves each frame in about 15ms!
#
# When hybrid=False driver is pure micropython.
# Pure Micropython could be viable when ESP32 supports Viper code emitter.
#
# ili9488 driver DO NOT support pure micropython now (because of required
# color convert). Pure micropython is only supported the for ili9341 and
# gc9a01 displays!
##############################################################################
import espidf as esp
import lvgl as lv
import lv_utils
import micropython
import gc
micropython.alloc_emergency_exception_buf(256)
# gc.threshold(0x10000) # leave enough room for SPI master TX DMA buffers
# Constants
COLOR_MODE_RGB = const(0x00)
COLOR_MODE_BGR = const(0x08)
MADCTL_MH = const(0x04)
MADCTL_ML = const(0x10)
MADCTL_MV = const(0x20)
MADCTL_MX = const(0x40)
MADCTL_MY = const(0x80)
PORTRAIT = MADCTL_MX
LANDSCAPE = MADCTL_MV
DISPLAY_TYPE_ILI9341 = const(1)
DISPLAY_TYPE_ILI9488 = const(2)
DISPLAY_TYPE_GC9A01 = const(3)
class ili9XXX:
TRANS_BUFFER_LEN = const(16)
display_name = 'ili9XXX'
display_type = 0
init_cmds = [ ]
# Default values of "power" and "backlight" are reversed logic! 0 means ON.
# You can change this by setting backlight_on and power_on arguments.
def __init__(self,
miso=5, mosi=18, clk=19, cs=13, dc=12, rst=4, power=14, backlight=15, backlight_on=0, power_on=0,
spihost=esp.HSPI_HOST, mhz=40, factor=4, hybrid=True, width=240, height=320,
colormode=COLOR_MODE_BGR, rot=PORTRAIT, invert=False, double_buffer=True, half_duplex=True, display_type=0,
asynchronous=False, initialize=True
):
# Initializations
if not lv.is_initialized():
lv.init()
self.asynchronous = asynchronous
self.initialize = initialize
self.width = width
self.height = height
self.miso = miso
self.mosi = mosi
self.clk = clk
self.cs = cs
self.dc = dc
self.rst = rst
self.power = power
self.backlight = backlight
self.backlight_on = backlight_on
self.power_on = power_on
self.spihost = spihost
self.mhz = mhz
self.factor = factor
self.hybrid = hybrid
self.half_duplex = half_duplex
self.buf_size = (self.width * self.height * lv.color_t.__SIZE__) // factor
if invert:
self.init_cmds.append({'cmd': 0x21})
# Register display driver
self.buf1 = esp.heap_caps_malloc(self.buf_size, esp.MALLOC_CAP.DMA)
self.buf2 = esp.heap_caps_malloc(self.buf_size, esp.MALLOC_CAP.DMA) if double_buffer else None
if self.buf1 and self.buf2:
print("Double buffer")
elif self.buf1:
print("Single buffer")
else:
raise RuntimeError("Not enough DMA-able memory to allocate display buffer")
self.disp_buf = lv.disp_draw_buf_t()
self.disp_drv = lv.disp_drv_t()
self.disp_buf.init(self.buf1, self.buf2, self.buf_size // lv.color_t.__SIZE__)
self.disp_drv.init()
self.disp_spi_init()
self.disp_drv.user_data = {'dc': self.dc, 'spi': self.spi, 'dt': self.display_type}
self.disp_drv.draw_buf = self.disp_buf
self.disp_drv.flush_cb = esp.ili9xxx_flush if hybrid and hasattr(esp, 'ili9xxx_flush') else self.flush
self.disp_drv.monitor_cb = self.monitor
self.disp_drv.hor_res = self.width
self.disp_drv.ver_res = self.height
if self.initialize:
self.init()
if not lv_utils.event_loop.is_running():
self.event_loop = lv_utils.event_loop(asynchronous=self.asynchronous)
######################################################
def disp_spi_init(self):
# TODO: Register finalizer callback to deinit SPI.
# That would get called on soft reset.
buscfg = esp.spi_bus_config_t({
"miso_io_num": self.miso,
"mosi_io_num": self.mosi,
"sclk_io_num": self.clk,
"quadwp_io_num": -1,
"quadhd_io_num": -1,
"max_transfer_sz": self.buf_size,
})
devcfg_flags = esp.SPI_DEVICE.NO_DUMMY
if self.half_duplex:
devcfg_flags |= esp.SPI_DEVICE.HALFDUPLEX
devcfg = esp.spi_device_interface_config_t({
"clock_speed_hz": self.mhz*1000*1000, # Clock out at DISP_SPI_MHZ MHz
"mode": 0, # SPI mode 0
"spics_io_num": self.cs, # CS pin
"queue_size": 2,
"flags": devcfg_flags,
"duty_cycle_pos": 128,
})
if self.hybrid and hasattr(esp, 'ili9xxx_post_cb_isr'):
devcfg.pre_cb = None
devcfg.post_cb = esp.ili9xxx_post_cb_isr
else:
devcfg.pre_cb = esp.ex_spi_pre_cb_isr
devcfg.post_cb = esp.ex_spi_post_cb_isr
esp.gpio_pad_select_gpio(self.cs)
# Initialize the SPI bus, if needed.
if buscfg.miso_io_num >= 0 and \
buscfg.mosi_io_num >= 0 and \
buscfg.sclk_io_num >= 0:
esp.gpio_pad_select_gpio(self.miso)
esp.gpio_pad_select_gpio(self.mosi)
esp.gpio_pad_select_gpio(self.clk)
esp.gpio_set_direction(self.miso, esp.GPIO_MODE.INPUT)
esp.gpio_set_pull_mode(self.miso, esp.GPIO.PULLUP_ONLY)
esp.gpio_set_direction(self.mosi, esp.GPIO_MODE.OUTPUT)
esp.gpio_set_direction(self.clk, esp.GPIO_MODE.OUTPUT)
ret = esp.spi_bus_initialize(self.spihost, buscfg, 1)
if ret != 0: raise RuntimeError("Failed initializing SPI bus")
self.trans_buffer = esp.heap_caps_malloc(TRANS_BUFFER_LEN, esp.MALLOC_CAP.DMA)
self.cmd_trans_data = self.trans_buffer.__dereference__(1)
self.word_trans_data = self.trans_buffer.__dereference__(4)
# Attach the LCD to the SPI bus
ptr_to_spi = esp.C_Pointer()
ret = esp.spi_bus_add_device(self.spihost, devcfg, ptr_to_spi)
if ret != 0: raise RuntimeError("Failed adding SPI device")
self.spi = ptr_to_spi.ptr_val
self.bytes_transmitted = 0
completed_spi_transaction = esp.spi_transaction_t()
cast_spi_transaction_instance = esp.spi_transaction_t.__cast_instance__
def post_isr(arg):
reported_transmitted = self.bytes_transmitted
if reported_transmitted > 0:
print('- Completed DMA of %d bytes (mem_free=0x%X)' % (reported_transmitted , gc.mem_free()))
self.bytes_transmitted -= reported_transmitted
# Called in ISR context!
def flush_isr(spi_transaction_ptr):
self.disp_drv.flush_ready()
# esp.spi_device_release_bus(self.spi)
esp.get_ccount(self.end_time_ptr)
# cast_spi_transaction_instance(completed_spi_transaction, spi_transaction_ptr)
# self.bytes_transmitted += completed_spi_transaction.length
# try:
# micropython.schedule(post_isr, None)
# except RuntimeError:
# pass
self.spi_callbacks = esp.spi_transaction_set_cb(None, flush_isr)
#
# Deinitialize SPI device and bus, and free memory
# This function is called from finilizer during gc sweep - therefore must not allocate memory!
#
trans_result_ptr = esp.C_Pointer()
def deinit(self):
print('Deinitializing {}..'.format(self.display_name))
# Prevent callbacks to lvgl, which refer to the buffers we are about to delete
if lv_utils.event_loop.is_running():
self.event_loop.deinit()
self.disp_drv.remove()
if self.spi:
# Pop all pending transaction results
ret = 0
while ret == 0:
ret = esp.spi_device_get_trans_result(self.spi, self.trans_result_ptr , 1)
# Remove device
esp.spi_bus_remove_device(self.spi)
self.spi = None
# Free SPI bus
esp.spi_bus_free(self.spihost)
self.spihost = None
# Free RAM
if self.buf1:
esp.heap_caps_free(self.buf1)
self.buf1 = None
if self.buf2:
esp.heap_caps_free(self.buf2)
self.buf2 = None
if self.trans_buffer:
esp.heap_caps_free(self.trans_buffer)
self.trans_buffer = None
######################################################
trans = esp.spi_transaction_t() # .__cast__(
# esp.heap_caps_malloc(
# esp.spi_transaction_t.__SIZE__, esp.MALLOC_CAP.DMA))
def spi_send(self, data):
self.trans.length = len(data) * 8 # Length is in bytes, transaction length is in bits.
self.trans.tx_buffer = data # data should be allocated as DMA-able memory
self.trans.user = None
esp.spi_device_polling_transmit(self.spi, self.trans)
def spi_send_dma(self, data):
self.trans.length = len(data) * 8 # Length is in bytes, transaction length is in bits.
self.trans.tx_buffer = data # data should be allocated as DMA-able memory
self.trans.user = self.spi_callbacks
esp.spi_device_queue_trans(self.spi, self.trans, -1)
######################################################
######################################################
def send_cmd(self, cmd):
esp.gpio_set_level(self.dc, 0) # Command mode
self.cmd_trans_data[0] = cmd
self.spi_send(self.cmd_trans_data)
def send_data(self, data):
esp.gpio_set_level(self.dc, 1) # Data mode
if len(data) > TRANS_BUFFER_LEN: raise RuntimeError('Data too long, please use DMA!')
trans_data = self.trans_buffer.__dereference__(len(data))
trans_data[:] = data[:]
self.spi_send(trans_data)
def send_trans_word(self):
esp.gpio_set_level(self.dc, 1) # Data mode
self.spi_send(self.word_trans_data)
def send_data_dma(self, data): # data should be allocated as DMA-able memory
esp.gpio_set_level(self.dc, 1) # Data mode
self.spi_send_dma(data)
######################################################
async def _init(self, sleep_func):
# Initialize non-SPI GPIOs
esp.gpio_pad_select_gpio(self.dc)
if self.rst != -1: esp.gpio_pad_select_gpio(self.rst)
if self.backlight != -1: esp.gpio_pad_select_gpio(self.backlight)
if self.power != -1: esp.gpio_pad_select_gpio(self.power)
esp.gpio_set_direction(self.dc, esp.GPIO_MODE.OUTPUT)
if self.rst != -1: esp.gpio_set_direction(self.rst, esp.GPIO_MODE.OUTPUT)
if self.backlight != -1: esp.gpio_set_direction(self.backlight, esp.GPIO_MODE.OUTPUT)
if self.power != -1: esp.gpio_set_direction(self.power, esp.GPIO_MODE.OUTPUT)
# Power the display
if self.power != -1:
esp.gpio_set_level(self.power, self.power_on)
await sleep_func(100)
# Reset the display
if self.rst != -1:
esp.gpio_set_level(self.rst, 0)
await sleep_func(100)
esp.gpio_set_level(self.rst, 1)
await sleep_func(100)
# Send all the commands
for cmd in self.init_cmds:
self.send_cmd(cmd['cmd'])
if 'data' in cmd:
self.send_data(cmd['data'])
if 'delay' in cmd:
await sleep_func(cmd['delay'])
print("{} initialization completed".format(self.display_name))
# Enable backlight
if self.backlight != -1:
print("Enable backlight")
esp.gpio_set_level(self.backlight, self.backlight_on)
# Register the driver
self.disp_drv.register()
def init(self):
import utime
generator = self._init(lambda ms:(yield ms))
try:
while True:
ms = next(generator)
utime.sleep_ms(ms)
except StopIteration:
pass
async def init_async(self):
import uasyncio
await self._init(uasyncio.sleep_ms)
def power_down(self):
if self.power != -1:
esp.gpio_set_level(self.power, 1 - self.power_on)
if self.backlight != -1:
esp.gpio_set_level(self.backlight, 1 - self.backlight_on)
######################################################
start_time_ptr = esp.C_Pointer()
end_time_ptr = esp.C_Pointer()
flush_acc_setup_cycles = 0
flush_acc_dma_cycles = 0
def flush(self, disp_drv, area, color_p):
if self.end_time_ptr.int_val and self.end_time_ptr.int_val > self.start_time_ptr.int_val:
self.flush_acc_dma_cycles += self.end_time_ptr.int_val - self.start_time_ptr.int_val
esp.get_ccount(self.start_time_ptr)
# esp.spi_device_acquire_bus(self.spi, esp.ESP.MAX_DELAY)
# Column addresses
self.send_cmd(0x2A);
self.word_trans_data[0] = (area.x1 >> 8) & 0xFF
self.word_trans_data[1] = area.x1 & 0xFF
self.word_trans_data[2] = (area.x2 >> 8) & 0xFF
self.word_trans_data[3] = area.x2 & 0xFF
self.send_trans_word()
# Page addresses
self.send_cmd(0x2B);
self.word_trans_data[0] = (area.y1 >> 8) & 0xFF
self.word_trans_data[1] = area.y1 & 0xFF
self.word_trans_data[2] = (area.y2 >> 8) & 0xFF
self.word_trans_data[3] = area.y2 & 0xFF
self.send_trans_word()
# Memory write by DMA, disp_flush_ready when finished
self.send_cmd(0x2C)
size = (area.x2 - area.x1 + 1) * (area.y2 - area.y1 + 1)
data_view = color_p.__dereference__(size * lv.color_t.__SIZE__)
esp.get_ccount(self.end_time_ptr)
if self.end_time_ptr.int_val > self.start_time_ptr.int_val:
self.flush_acc_setup_cycles += self.end_time_ptr.int_val - self.start_time_ptr.int_val
esp.get_ccount(self.start_time_ptr)
self.send_data_dma(data_view)
######################################################
monitor_acc_time = 0
monitor_acc_px = 0
monitor_count = 0
cycles_in_ms = esp.esp_clk_cpu_freq() // 1000
def monitor(self, disp_drv, time, px):
self.monitor_acc_time += time
self.monitor_acc_px += px
self.monitor_count += 1
def stat(self):
if self.monitor_count == 0:
return None
time = self.monitor_acc_time // self.monitor_count
setup = self.flush_acc_setup_cycles // (self.monitor_count * self.cycles_in_ms)
dma = self.flush_acc_dma_cycles // (self.monitor_count * self.cycles_in_ms)
px = self.monitor_acc_px // self.monitor_count
self.monitor_acc_time = 0
self.monitor_acc_px = 0
self.monitor_count = 0
self.flush_acc_setup_cycles = 0
self.flush_acc_dma_cycles = 0
return time, setup, dma, px
class ili9341(ili9XXX):
def __init__(self,
miso=5, mosi=18, clk=19, cs=13, dc=12, rst=4, power=14, backlight=15, backlight_on=0, power_on=0,
spihost=esp.HSPI_HOST, mhz=40, factor=4, hybrid=True, width=240, height=320,
colormode=COLOR_MODE_BGR, rot=PORTRAIT, invert=False, double_buffer=True, half_duplex=True,
asynchronous=False, initialize=True
):
# Make sure Micropython was built such that color won't require processing before DMA
if lv.color_t.__SIZE__ != 2:
raise RuntimeError('ili9341 micropython driver requires defining LV_COLOR_DEPTH=16')
if colormode == COLOR_MODE_BGR and not hasattr(lv.color_t().ch, 'green_l'):
raise RuntimeError('ili9341 BGR color mode requires defining LV_COLOR_16_SWAP=1')
self.display_name = 'ILI9341'
self.display_type = DISPLAY_TYPE_ILI9341
self.init_cmds = [
{'cmd': 0xCF, 'data': bytes([0x00, 0x83, 0X30])},
{'cmd': 0xED, 'data': bytes([0x64, 0x03, 0X12, 0X81])},
{'cmd': 0xE8, 'data': bytes([0x85, 0x01, 0x79])},
{'cmd': 0xCB, 'data': bytes([0x39, 0x2C, 0x00, 0x34, 0x02])},
{'cmd': 0xF7, 'data': bytes([0x20])},
{'cmd': 0xEA, 'data': bytes([0x00, 0x00])},
{'cmd': 0xC0, 'data': bytes([0x26])}, # Power control
{'cmd': 0xC1, 'data': bytes([0x11])}, # Power control
{'cmd': 0xC5, 'data': bytes([0x35, 0x3E])}, # VCOM control
{'cmd': 0xC7, 'data': bytes([0xBE])}, # VCOM control
{'cmd': 0x36, 'data': bytes([rot | colormode])}, # Memory Access Control
{'cmd': 0x3A, 'data': bytes([0x55])}, # Pixel Format Set
{'cmd': 0xB1, 'data': bytes([0x00, 0x1B])},
{'cmd': 0xF2, 'data': bytes([0x08])},
{'cmd': 0x26, 'data': bytes([0x01])},
{'cmd': 0xE0, 'data': bytes([0x1F, 0x1A, 0x18, 0x0A, 0x0F, 0x06, 0x45, 0X87, 0x32, 0x0A, 0x07, 0x02, 0x07, 0x05, 0x00])},
{'cmd': 0XE1, 'data': bytes([0x00, 0x25, 0x27, 0x05, 0x10, 0x09, 0x3A, 0x78, 0x4D, 0x05, 0x18, 0x0D, 0x38, 0x3A, 0x1F])},
{'cmd': 0x2A, 'data': bytes([0x00, 0x00, 0x00, 0xEF])},
{'cmd': 0x2B, 'data': bytes([0x00, 0x00, 0x01, 0x3f])},
{'cmd': 0x2C, 'data': bytes([0])},
{'cmd': 0xB7, 'data': bytes([0x07])},
{'cmd': 0xB6, 'data': bytes([0x0A, 0x82, 0x27, 0x00])},
{'cmd': 0x11, 'data': bytes([0]), 'delay':100},
{'cmd': 0x29, 'data': bytes([0]), 'delay':100}
]
super().__init__(miso, mosi, clk, cs, dc, rst, power, backlight, backlight_on, power_on,
spihost, mhz, factor, hybrid, width, height, colormode, rot, invert, double_buffer, half_duplex,
asynchronous=asynchronous, initialize=initialize)
class ili9488(ili9XXX):
def __init__(self,
miso=5, mosi=18, clk=19, cs=13, dc=12, rst=4, power=14, backlight=15, backlight_on=0, power_on=0,
spihost=esp.HSPI_HOST, mhz=40, factor=8, hybrid=True, width=320, height=480,
colormode=COLOR_MODE_RGB, rot=PORTRAIT, invert=False, double_buffer=True, half_duplex=True,
asynchronous=False, initialize=True
):
if lv.color_t.__SIZE__ != 4:
raise RuntimeError('ili9488 micropython driver requires defining LV_COLOR_DEPTH=32')
if not hybrid:
raise RuntimeError('ili9488 micropython driver do not support non-hybrid driver')
self.display_name = 'ILI9488'
self.display_type = DISPLAY_TYPE_ILI9488
self.init_cmds = [
{'cmd': 0x01, 'data': bytes([0]), 'delay': 200},
{'cmd': 0x11, 'data': bytes([0]), 'delay': 120},
{'cmd': 0xE0, 'data': bytes([0x00, 0x03, 0x09, 0x08, 0x16, 0x0A, 0x3F, 0x78, 0x4C, 0x09, 0x0A, 0x08, 0x16, 0x1A, 0x0F])},
{'cmd': 0xE1, 'data': bytes([0x00, 0x16, 0x19, 0x03, 0x0F, 0x05, 0x32, 0x45, 0x46, 0x04, 0x0E, 0x0D, 0x35, 0x37, 0x0F])},
{'cmd': 0xC0, 'data': bytes([0x17, 0x15])}, ### 0x13, 0x13
{'cmd': 0xC1, 'data': bytes([0x41])}, ###
{'cmd': 0xC2, 'data': bytes([0x44])}, ###
{'cmd': 0xC5, 'data': bytes([0x00, 0x12, 0x80])},
#{'cmd': 0xC5, 'data': bytes([0x00, 0x0, 0x0, 0x0])},
{'cmd': 0x36, 'data': bytes([rot | colormode])}, # Memory Access Control
{'cmd': 0x3A, 'data': bytes([0x66])},
{'cmd': 0xB0, 'data': bytes([0x00])},
{'cmd': 0xB1, 'data': bytes([0xA0])},
{'cmd': 0xB4, 'data': bytes([0x02])},
{'cmd': 0xB6, 'data': bytes([0x02, 0x02])},
{'cmd': 0xE9, 'data': bytes([0x00])},
{'cmd': 0x53, 'data': bytes([0x28])},
{'cmd': 0x51, 'data': bytes([0x7F])},
{'cmd': 0xF7, 'data': bytes([0xA9, 0x51, 0x2C, 0x02])},
{'cmd': 0x29, 'data': bytes([0]), 'delay': 120}
]
super().__init__(miso, mosi, clk, cs, dc, rst, power, backlight, backlight_on, power_on,
spihost, mhz, factor, hybrid, width, height, colormode, rot, invert, double_buffer, half_duplex, display_type=DISPLAY_TYPE_ILI9488,
asynchronous=asynchronous, initialize=initialize)
class gc9a01(ili9XXX):
# On the tested display the write direction and colormode appear to be
# reversed from how they are presented in the datasheet
def __init__(self,
miso=5, mosi=18, clk=19, cs=13, dc=12, rst=4, power=14, backlight=15, backlight_on=0, power_on=0,
spihost=esp.HSPI_HOST, mhz=60, factor=4, hybrid=True, width=240, height=240,
colormode=COLOR_MODE_RGB, rot=PORTRAIT, invert=False, double_buffer=True, half_duplex=True,
asynchronous=False, initialize=True
):
if lv.color_t.SIZE != 2:
raise RuntimeError('gc9a01 micropython driver requires defining LV_COLOR_DEPTH=16')
# This is included as the color mode appears to be reversed from the
# datasheet and the ili9XXX driver values
if colormode == COLOR_MODE_RGB:
self.colormode = COLOR_MODE_BGR
elif colormode == COLOR_MODE_BGR:
self.colormode = COLOR_MODE_RGB
self.display_name = 'GC9A01'
self.display_type = DISPLAY_TYPE_GC9A01
self.init_cmds = [
{'cmd': 0xEF, 'data': bytes([0])},
{'cmd': 0xEB, 'data': bytes([0x14])},
{'cmd': 0xFE, 'data': bytes([0])},
{'cmd': 0xEF, 'data': bytes([0])},
{'cmd': 0xEB, 'data': bytes([0x14])},
{'cmd': 0x84, 'data': bytes([0x40])},
{'cmd': 0x85, 'data': bytes([0xFF])},
{'cmd': 0x86, 'data': bytes([0xFF])},
{'cmd': 0x87, 'data': bytes([0xFF])},
{'cmd': 0x88, 'data': bytes([0x0A])},
{'cmd': 0x89, 'data': bytes([0x21])},
{'cmd': 0x8A, 'data': bytes([0x00])},
{'cmd': 0x8B, 'data': bytes([0x80])},
{'cmd': 0x8C, 'data': bytes([0x01])},
{'cmd': 0x8D, 'data': bytes([0x01])},
{'cmd': 0x8E, 'data': bytes([0xFF])},
{'cmd': 0x8F, 'data': bytes([0xFF])},
{'cmd': 0xB6, 'data': bytes([0x00, 0x00])},
{'cmd': 0x36, 'data': bytes([rot | self.colormode])},
{'cmd': 0x3A, 'data': bytes([0x05])},
{'cmd': 0x90, 'data': bytes([0x08, 0x08, 0x08, 0x08])},
{'cmd': 0xBD, 'data': bytes([0x06])},
{'cmd': 0xBC, 'data': bytes([0x00])},
{'cmd': 0xFF, 'data': bytes([0x60, 0x01, 0x04])},
{'cmd': 0xC3, 'data': bytes([0x13])},
{'cmd': 0xC4, 'data': bytes([0x13])},
{'cmd': 0xC9, 'data': bytes([0x22])},
{'cmd': 0xBE, 'data': bytes([0x11])},
{'cmd': 0xE1, 'data': bytes([0x10, 0x0E])},
{'cmd': 0xDF, 'data': bytes([0x21, 0x0c, 0x02])},
{'cmd': 0xF0, 'data': bytes([0x45, 0x09, 0x08, 0x08, 0x26, 0x2A])},
{'cmd': 0xF1, 'data': bytes([0x43, 0x70, 0x72, 0x36, 0x37, 0x6F])},
{'cmd': 0xF2, 'data': bytes([0x45, 0x09, 0x08, 0x08, 0x26, 0x2A])},
{'cmd': 0xF3, 'data': bytes([0x43, 0x70, 0x72, 0x36, 0x37, 0x6F])},
{'cmd': 0xED, 'data': bytes([0x1B, 0x0B])},
{'cmd': 0xAE, 'data': bytes([0x77])},
{'cmd': 0xCD, 'data': bytes([0x63])},
{'cmd': 0x70, 'data': bytes([0x07, 0x07, 0x04, 0x0E, 0x0F, 0x09, 0x07, 0x08, 0x03])},
{'cmd': 0xE8, 'data': bytes([0x34])},
{'cmd': 0x62, 'data': bytes([0x18, 0x0D, 0x71, 0xED, 0x70, 0x70, 0x18, 0x0F, 0x71, 0xEF, 0x70, 0x70])},
{'cmd': 0x63, 'data': bytes([0x18, 0x11, 0x71, 0xF1, 0x70, 0x70, 0x18, 0x13, 0x71, 0xF3, 0x70, 0x70])},
{'cmd': 0x64, 'data': bytes([0x28, 0x29, 0xF1, 0x01, 0xF1, 0x00, 0x07])},
{'cmd': 0x66, 'data': bytes([0x3C, 0x00, 0xCD, 0x67, 0x45, 0x45, 0x10, 0x00, 0x00, 0x00])},
{'cmd': 0x67, 'data': bytes([0x00, 0x3C, 0x00, 0x00, 0x00, 0x01, 0x54, 0x10, 0x32, 0x98])},
{'cmd': 0x74, 'data': bytes([0x10, 0x85, 0x80, 0x00, 0x00, 0x4E, 0x00])},
{'cmd': 0x98, 'data': bytes([0x3e, 0x07])},
{'cmd': 0x35, 'data': bytes([0])},
{'cmd': 0x21, 'data': bytes([0])},
{'cmd': 0x11, 'data': bytes([0]), 'delay': 20},
{'cmd': 0x29, 'data': bytes([0]), 'delay': 120}
]
super().__init__(miso, mosi, clk, cs, dc, rst, power, backlight, backlight_on, power_on,
spihost, mhz, factor, hybrid, width, height, self.colormode, rot, invert, double_buffer, half_duplex, display_type=self.display_type,
asynchronous=asynchronous, initialize=initialize)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/ili9XXX.py | Python | apache-2.0 | 26,285 |
//////////////////////////////////////////////////////////////////////////////
// Includes
//////////////////////////////////////////////////////////////////////////////
#include "../include/common.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "lvgl/src/lv_hal/lv_hal_disp.h"
//////////////////////////////////////////////////////////////////////////////
// ILI9341 requires specific lv_conf resolution and color depth
//////////////////////////////////////////////////////////////////////////////
#if LV_COLOR_DEPTH != 16
#error "modILI9341: LV_COLOR_DEPTH must be set to 16!"
#endif
//////////////////////////////////////////////////////////////////////////////
// ILI9341 Module definitions
//////////////////////////////////////////////////////////////////////////////
typedef struct {
mp_obj_base_t base;
spi_device_handle_t spi;
uint8_t mhz;
uint8_t spihost;
uint8_t miso;
uint8_t mosi;
uint8_t clk;
uint8_t cs;
uint8_t dc;
uint8_t rst;
uint8_t backlight;
} ILI9341_t;
// Unfortunately, lvgl doesnt pass user_data to callbacks, so we use this global.
// This means we can have only one active display driver instance, pointed by this global.
STATIC ILI9341_t *g_ILI9341 = NULL;
STATIC mp_obj_t ILI9341_make_new(const mp_obj_type_t *type,
size_t n_args,
size_t n_kw,
const mp_obj_t *all_args);
STATIC mp_obj_t mp_init_ILI9341(mp_obj_t self_in);
STATIC mp_obj_t mp_activate_ILI9341(mp_obj_t self_in)
{
ILI9341_t *self = MP_OBJ_TO_PTR(self_in);
g_ILI9341 = self;
return mp_const_none;
}
STATIC void ili9431_flush(struct _disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_init_ILI9341_obj, mp_init_ILI9341);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_activate_ILI9341_obj, mp_activate_ILI9341);
DEFINE_PTR_OBJ(ili9431_flush);
STATIC const mp_rom_map_elem_t ILI9341_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&mp_init_ILI9341_obj) },
{ MP_ROM_QSTR(MP_QSTR_activate), MP_ROM_PTR(&mp_activate_ILI9341_obj) },
{ MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&PTR_OBJ(ili9431_flush)) },
};
STATIC MP_DEFINE_CONST_DICT(ILI9341_locals_dict, ILI9341_locals_dict_table);
STATIC const mp_obj_type_t ILI9341_type = {
{ &mp_type_type },
.name = MP_QSTR_ILI9341,
//.print = ILI9341_print,
.make_new = ILI9341_make_new,
.locals_dict = (mp_obj_dict_t*)&ILI9341_locals_dict,
};
STATIC mp_obj_t ILI9341_make_new(const mp_obj_type_t *type,
size_t n_args,
size_t n_kw,
const mp_obj_t *all_args)
{
enum{
ARG_mhz,
ARG_spihost,
ARG_miso,
ARG_mosi,
ARG_clk,
ARG_cs,
ARG_dc,
ARG_rst,
ARG_backlight,
};
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_mhz,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=40}},
{ MP_QSTR_spihost,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=HSPI_HOST}},
{ MP_QSTR_miso,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_mosi,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_clk,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_cs,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_dc,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_rst,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_backlight,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
ILI9341_t *self = m_new_obj(ILI9341_t);
self->base.type = type;
self->spi = NULL;
self->mhz = args[ARG_mhz].u_int;
self->spihost = args[ARG_spihost].u_int;
self->miso = args[ARG_miso].u_int;
self->mosi = args[ARG_mosi].u_int;
self->clk = args[ARG_clk].u_int;
self->cs = args[ARG_cs].u_int;
self->dc = args[ARG_dc].u_int;
self->rst = args[ARG_rst].u_int;
self->backlight = args[ARG_backlight].u_int;
return MP_OBJ_FROM_PTR(self);
}
STATIC const mp_rom_map_elem_t ILI9341_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ILI9341) },
{ MP_ROM_QSTR(MP_QSTR_display), (mp_obj_t)&ILI9341_type},
};
STATIC MP_DEFINE_CONST_DICT (
mp_module_ILI9341_globals,
ILI9341_globals_table
);
const mp_obj_module_t mp_module_ILI9341 = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_ILI9341_globals
};
//////////////////////////////////////////////////////////////////////////////
// ILI9341 driver implementation
//////////////////////////////////////////////////////////////////////////////
STATIC void disp_spi_init(ILI9341_t *self)
{
esp_err_t ret;
spi_bus_config_t buscfg={
.miso_io_num=self->miso,
.mosi_io_num=self->mosi,
.sclk_io_num=self->clk,
.quadwp_io_num=-1,
.quadhd_io_num=-1,
.max_transfer_sz=128*1024,
};
spi_device_interface_config_t devcfg={
.clock_speed_hz=self->mhz*1000*1000, //Clock out at DISP_SPI_MHZ MHz
.mode=0, //SPI mode 0
.spics_io_num=self->cs, //CS pin
.queue_size=1,
.pre_cb=NULL,
.post_cb=NULL,
.flags=SPI_DEVICE_HALFDUPLEX,
.duty_cycle_pos=128,
};
gpio_pad_select_gpio(self->miso);
gpio_pad_select_gpio(self->mosi);
gpio_pad_select_gpio(self->clk);
gpio_set_direction(self->miso, GPIO_MODE_INPUT);
gpio_set_pull_mode(self->miso, GPIO_PULLUP_ONLY);
gpio_set_direction(self->mosi, GPIO_MODE_OUTPUT);
gpio_set_direction(self->clk, GPIO_MODE_OUTPUT);
gpio_pad_select_gpio(self->cs);
//Initialize the SPI bus
ret=spi_bus_initialize(self->spihost, &buscfg, 1);
if (ret != ESP_OK) nlr_raise(
mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("Failed initializing SPI bus")));
//Attach the LCD to the SPI bus
ret=spi_bus_add_device(self->spihost, &devcfg, &self->spi);
if (ret != ESP_OK) nlr_raise(
mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("Failed adding SPI device")));
}
STATIC void disp_spi_send(ILI9341_t *self, const uint8_t * data, uint16_t length)
{
if (length == 0) return; //no need to send anything
spi_transaction_t t;
memset(&t, 0, sizeof(t)); //Zero out the transaction
t.length = length * 8; //Length is in bytes, transaction length is in bits.
t.tx_buffer = data; //Data
// esp_err_t ret;
// ret=spi_device_transmit(spi, &t); //Transmit!
// assert(ret==ESP_OK); //Should have had no issues.
spi_device_queue_trans(self->spi, &t, portMAX_DELAY);
spi_transaction_t * rt;
spi_device_get_trans_result(self->spi, &rt, portMAX_DELAY);
}
STATIC void ili9441_send_cmd(ILI9341_t *self, uint8_t cmd)
{
gpio_set_level(self->dc, 0); /*Command mode*/
disp_spi_send(self, &cmd, 1);
}
STATIC void ili9341_send_data(ILI9341_t *self, const void * data, uint16_t length)
{
gpio_set_level(self->dc, 1); /*Data mode*/
disp_spi_send(self, data, length);
}
/*The LCD needs a bunch of command/argument values to be initialized. They are stored in this struct. */
typedef struct {
uint8_t cmd;
uint8_t data[16];
uint8_t databytes; //No of data in data; bit 7 = delay after set; 0xFF = end of cmds.
} lcd_init_cmd_t;
STATIC const lcd_init_cmd_t ili_init_cmds[]={
{0xCF, {0x00, 0x83, 0X30}, 3},
{0xED, {0x64, 0x03, 0X12, 0X81}, 4},
{0xE8, {0x85, 0x01, 0x79}, 3},
{0xCB, {0x39, 0x2C, 0x00, 0x34, 0x02}, 5},
{0xF7, {0x20}, 1},
{0xEA, {0x00, 0x00}, 2},
{0xC0, {0x26}, 1}, /*Power control*/
{0xC1, {0x11}, 1}, /*Power control */
{0xC5, {0x35, 0x3E}, 2}, /*VCOM control*/
{0xC7, {0xBE}, 1}, /*VCOM control*/
{0x36, {0x48}, 1}, /*Memory Access Control*/
{0x3A, {0x55}, 1}, /*Pixel Format Set*/
{0xB1, {0x00, 0x1B}, 2},
{0xF2, {0x08}, 1},
{0x26, {0x01}, 1},
{0xE0, {0x1F, 0x1A, 0x18, 0x0A, 0x0F, 0x06, 0x45, 0X87, 0x32, 0x0A, 0x07, 0x02, 0x07, 0x05, 0x00}, 15},
{0XE1, {0x00, 0x25, 0x27, 0x05, 0x10, 0x09, 0x3A, 0x78, 0x4D, 0x05, 0x18, 0x0D, 0x38, 0x3A, 0x1F}, 15},
{0x2A, {0x00, 0x00, 0x00, 0xEF}, 4},
{0x2B, {0x00, 0x00, 0x01, 0x3f}, 4},
{0x2C, {0}, 0},
{0xB7, {0x07}, 1},
{0xB6, {0x0A, 0x82, 0x27, 0x00}, 4},
{0x11, {0}, 0x80},
{0x29, {0}, 0x80},
{0, {0}, 0xff},
};
STATIC mp_obj_t mp_init_ILI9341(mp_obj_t self_in)
{
ILI9341_t *self = MP_OBJ_TO_PTR(self_in);
mp_activate_ILI9341(self_in);
disp_spi_init(self);
gpio_pad_select_gpio(self->dc);
//Initialize non-SPI GPIOs
gpio_set_direction(self->dc, GPIO_MODE_OUTPUT);
gpio_set_direction(self->rst, GPIO_MODE_OUTPUT);
if (self->backlight != -1) gpio_set_direction(self->backlight, GPIO_MODE_OUTPUT);
//Reset the display
gpio_set_level(self->rst, 0);
vTaskDelay(100 / portTICK_RATE_MS);
gpio_set_level(self->rst, 1);
vTaskDelay(100 / portTICK_RATE_MS);
// printf("ILI9341 initialization.\n");
//Send all the commands
uint16_t cmd = 0;
while (ili_init_cmds[cmd].databytes!=0xff) {
ili9441_send_cmd(self, ili_init_cmds[cmd].cmd);
ili9341_send_data(self, ili_init_cmds[cmd].data, ili_init_cmds[cmd].databytes & 0x1F);
if (ili_init_cmds[cmd].databytes & 0x80) {
vTaskDelay(100 / portTICK_RATE_MS);
}
cmd++;
}
///Enable backlight
//printf("Enable backlight.\n");
if (self->backlight != -1) gpio_set_level(self->backlight, 1);
return mp_const_none;
}
STATIC void ili9431_flush(struct _disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
uint8_t data[4];
ILI9341_t *self = g_ILI9341;
/*Column addresses*/
ili9441_send_cmd(self, 0x2A);
data[0] = (area->x1 >> 8) & 0xFF;
data[1] = area->x1 & 0xFF;
data[2] = (area->x2 >> 8) & 0xFF;
data[3] = area->x2 & 0xFF;
ili9341_send_data(self, data, 4);
/*Page addresses*/
ili9441_send_cmd(self, 0x2B);
data[0] = (area->y1 >> 8) & 0xFF;
data[1] = area->y1 & 0xFF;
data[2] = (area->y2 >> 8) & 0xFF;
data[3] = area->y2 & 0xFF;
ili9341_send_data(self, data, 4);
/*Memory write*/
ili9441_send_cmd(self, 0x2C);
uint32_t size = (area->x2 - area->x1 + 1) * (area->y2 - area->y1 + 1);
/*Byte swapping is required*/
uint32_t i;
uint8_t * color_u8 = (uint8_t *) color_p;
uint8_t color_tmp;
for(i = 0; i < size * 2; i += 2) {
color_tmp = color_u8[i + 1];
color_u8[i + 1] = color_u8[i];
color_u8[i] = color_tmp;
}
ili9341_send_data(self, (void*)color_p, size * 2);
/*
while(size > LV_HOR_RES) {
ili9341_send_data((void*)color_p, LV_HOR_RES * 2);
//vTaskDelay(10 / portTICK_PERIOD_MS);
size -= LV_HOR_RES;
color_p += LV_HOR_RES;
}
ili9341_send_data((void*)color_p, size * 2); */ /*Send the remaining data*/
lv_disp_flush_ready(disp_drv);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/modILI9341.c | C | apache-2.0 | 10,982 |
//////////////////////////////////////////////////////////////////////////////
// Includes
//////////////////////////////////////////////////////////////////////////////
// Uncomment the following line to see logs!
// #define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
#include "../include/common.h"
#include "driver/gpio.h"
#include "driver/adc.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_task.h"
#include "lvgl/src/hal/lv_hal_indev.h"
#include "lvgl/src/core/lv_disp.h"
#include "esp_log.h"
#include "soc/adc_channel.h"
//////////////////////////////////////////////////////////////////////////////
// Constants
//////////////////////////////////////////////////////////////////////////////
static const char TAG[] = "[RTCH]";
#define INVALID_MEASUREMENT INT32_MIN
#define RTCH_TASK_STACK_SIZE (4*1024)
#define RTCH_TASK_PRIORITY (ESP_TASK_PRIO_MIN + 2)
#ifndef RTCH_MAX_TOUCH_SAMPLES
#define RTCH_MAX_TOUCH_SAMPLES 16
#endif
#ifndef RTCH_SAMPLE_WAIT_MS
#define RTCH_SAMPLE_WAIT_MS 1
#endif
#ifndef RTCH_TOUCH_WAIT_MS
#define RTCH_TOUCH_WAIT_MS 10
#endif
#ifndef RTCH_INIT_ADC_WAIT_MS
#define RTCH_INIT_ADC_WAIT_MS 20
#endif
#ifndef CONCAT3
#define _CONCAT3(a,b,c) a ## b ## c
#define CONCAT3(a,b,c) _CONCAT3(a,b,c)
#endif
#define GPIO_TO_ADC_ELEMENT(x) [x] = CONCAT3(ADC1_GPIO, x, _CHANNEL)
static const int gpio_to_adc[] = {
GPIO_TO_ADC_ELEMENT(36),
GPIO_TO_ADC_ELEMENT(37),
GPIO_TO_ADC_ELEMENT(38),
GPIO_TO_ADC_ELEMENT(39),
GPIO_TO_ADC_ELEMENT(32),
GPIO_TO_ADC_ELEMENT(33),
GPIO_TO_ADC_ELEMENT(34),
GPIO_TO_ADC_ELEMENT(35),
};
//////////////////////////////////////////////////////////////////////////////
// Module definition
//////////////////////////////////////////////////////////////////////////////
typedef struct _rtch_info_t
{
int x;
int y;
bool touched;
} rtch_info_t;
typedef struct _rtch_t
{
mp_obj_base_t base;
gpio_num_t xp; // X+
gpio_num_t yp; // Y+
gpio_num_t xm; // X-
gpio_num_t ym; // Y-
gpio_num_t touch_rail; // pfet! 0 to enable.
gpio_num_t touch_sense; // Probably Y+ or Y-, when touch rail is enabled
uint32_t screen_width;
uint32_t screen_height;
uint32_t cal_x0, cal_y0;
uint32_t cal_x1, cal_y1;
uint32_t touch_samples; // number of samples to take on every touch measurement
uint32_t touch_samples_threshold; // max distance between touch sample measurements for a valid touch reading
rtch_info_t rtch_info;
xTaskHandle rtch_task_handle;
SemaphoreHandle_t rtch_info_mutex;
} rtch_t;
// Unfortunately, lvgl doesn't pass user_data to callbacks, so we use this global.
// This means we can have only one active touch driver instance, pointed by this global.
STATIC rtch_t *g_rtch = NULL;
STATIC bool touch_read(lv_indev_drv_t * indev_drv, lv_indev_data_t *data)
{
rtch_info_t *touch_info = &g_rtch->rtch_info;
xSemaphoreTake(g_rtch->rtch_info_mutex, portMAX_DELAY);
data->point = (lv_point_t){touch_info->x, touch_info->y};
data->state = touch_info->touched? LV_INDEV_STATE_PRESSED: LV_INDEV_STATE_RELEASED;
xSemaphoreGive(g_rtch->rtch_info_mutex);
return false;
}
STATIC mp_obj_t mp_activate_rtch(mp_obj_t self_in)
{
rtch_t *self = MP_OBJ_TO_PTR(self_in);
g_rtch = self;
return mp_const_none;
}
STATIC mp_obj_t rtch_make_new(const mp_obj_type_t *type,
size_t n_args,
size_t n_kw,
const mp_obj_t *all_args);
STATIC mp_obj_t mp_rtch_init(mp_obj_t self_in);
STATIC mp_obj_t mp_rtch_deinit(mp_obj_t self_in);
STATIC mp_obj_t calibrate(mp_uint_t n_args, const mp_obj_t *args);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_init_rtch_obj, mp_rtch_init);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_deinit_rtch_obj, mp_rtch_deinit);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_activate_rtch_obj, mp_activate_rtch);
DEFINE_PTR_OBJ(touch_read);
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(calibrate_obj, 5, 5, calibrate);
STATIC const mp_rom_map_elem_t rtch_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&mp_init_rtch_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mp_deinit_rtch_obj) },
{ MP_ROM_QSTR(MP_QSTR_activate), MP_ROM_PTR(&mp_activate_rtch_obj) },
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&PTR_OBJ(touch_read)) },
{ MP_ROM_QSTR(MP_QSTR_calibrate), MP_ROM_PTR(&calibrate_obj) },
};
STATIC MP_DEFINE_CONST_DICT(rtch_locals_dict, rtch_locals_dict_table);
STATIC const mp_obj_type_t rtch_type = {
{ &mp_type_type },
.name = MP_QSTR_rtch,
//.print = rtch_print,
.make_new = rtch_make_new,
.locals_dict = (mp_obj_dict_t*)&rtch_locals_dict,
};
STATIC const mp_rom_map_elem_t rtch_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_rtch) },
{ MP_ROM_QSTR(MP_QSTR_touch), (mp_obj_t)&rtch_type},
};
STATIC MP_DEFINE_CONST_DICT (
mp_module_rtch_globals,
rtch_globals_table
);
const mp_obj_module_t mp_module_rtch = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_rtch_globals
};
STATIC mp_obj_t rtch_make_new(const mp_obj_type_t *type,
size_t n_args,
size_t n_kw,
const mp_obj_t *all_args)
{
enum{
ARG_xp, // X+
ARG_yp, // Y+
ARG_xm, // X-
ARG_ym, // Y-
ARG_touch_rail, // pfet! 0 to enable.
ARG_touch_sense, // Probably Y+ or Y-, when touch rail is enabled
ARG_screen_width,
ARG_screen_height,
ARG_cal_x0,
ARG_cal_y0,
ARG_cal_x1,
ARG_cal_y1,
ARG_touch_samples, // number of samples to take on every touch measurement
ARG_touch_samples_threshold, // max distance between touch sample measurements for a valid touch reading
};
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_xp, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_yp, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_xm, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_ym, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_touch_rail, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_touch_sense, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_screen_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_screen_height, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=-1}},
{ MP_QSTR_cal_x0, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=400}},
{ MP_QSTR_cal_y0, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=200}},
{ MP_QSTR_cal_x1, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=3500}},
{ MP_QSTR_cal_y1, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=3470}},
{ MP_QSTR_touch_samples, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=9}},
{ MP_QSTR_touch_samples_threshold, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int=500}},
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
rtch_t *self = m_new_obj(rtch_t);
self->base.type = type;
self->xp = args[ARG_xp].u_int;
self->yp = args[ARG_yp].u_int;
self->xm = args[ARG_xm].u_int;
self->ym = args[ARG_ym].u_int;
self->touch_rail = args[ARG_touch_rail].u_int;
self->touch_sense = args[ARG_touch_sense].u_int;
self->screen_width = args[ARG_screen_width].u_int;
if (self->screen_width == -1) self->screen_width = LV_HOR_RES;
self->screen_height = args[ARG_screen_height].u_int;
if (self->screen_height == -1) self->screen_height = LV_VER_RES;
self->cal_x0 = args[ARG_cal_x0].u_int;
self->cal_y0 = args[ARG_cal_y0].u_int;
self->cal_x1 = args[ARG_cal_x1].u_int;
self->cal_y1 = args[ARG_cal_y1].u_int;
self->touch_samples = args[ARG_touch_samples].u_int;
self->touch_samples_threshold = args[ARG_touch_samples_threshold].u_int;
self->rtch_info = (rtch_info_t){0};
self->rtch_task_handle = NULL;
self->rtch_info_mutex = NULL;
return MP_OBJ_FROM_PTR(self);
}
STATIC mp_obj_t calibrate(mp_uint_t n_args, const mp_obj_t *args)
{
(void)n_args; // unused, we know it's 5
rtch_t *self = MP_OBJ_TO_PTR(args[0]);
self->cal_x0 = mp_obj_get_int(args[1]);
self->cal_y0 = mp_obj_get_int(args[2]);
self->cal_x1 = mp_obj_get_int(args[3]);
self->cal_y1 = mp_obj_get_int(args[4]);
return mp_const_none;
}
//////////////////////////////////////////////////////////////////////////////
// RTCH implemenation
//////////////////////////////////////////////////////////////////////////////
STATIC void rtch_task(void* arg);
STATIC void enable_touch_sense(rtch_t *self)
{
// Configure all touch pins to high impedance (input)
gpio_config(&(gpio_config_t){
.mode = GPIO_MODE_INPUT,
.pin_bit_mask =
(1ULL<<self->xp) |
(1ULL<<self->yp) |
(1ULL<<self->xm) |
(1ULL<<self->ym)
});
// Enable touch rail
gpio_config(&(gpio_config_t){
.mode = GPIO_MODE_OUTPUT,
.pin_bit_mask = (1ULL<<self->touch_rail),
});
gpio_set_level(self->touch_rail, 0);
// Configure touch sense and configure interrupt
gpio_config(&(gpio_config_t){
.intr_type = GPIO_PIN_INTR_POSEDGE,
.mode = GPIO_MODE_INPUT,
.pull_down_en = 1,
.pin_bit_mask = (1ULL<<self->touch_sense),
});
// Wait for touch rail to stabilize
vTaskDelay(RTCH_TOUCH_WAIT_MS / portTICK_RATE_MS);
}
STATIC mp_obj_t mp_rtch_init(mp_obj_t self_in)
{
rtch_t *self = MP_OBJ_TO_PTR(self_in);
esp_log_level_set(TAG, ESP_LOG_DEBUG);
esp_log_level_set("gpio", ESP_LOG_DEBUG);
esp_log_level_set("RTC_MODULE", ESP_LOG_DEBUG);
self->rtch_info_mutex = xSemaphoreCreateMutex();
adc_power_on();
enable_touch_sense(self);
// Install Interrupt
gpio_install_isr_service(0);
mp_activate_rtch(self_in);
BaseType_t xReturned = xTaskCreate(rtch_task, "RTCH Task", RTCH_TASK_STACK_SIZE, self, RTCH_TASK_PRIORITY, &self->rtch_task_handle);
if (xReturned != pdPASS){
ESP_LOGE(TAG, "Failed createing RTCH task!");
vTaskDelete(self->rtch_task_handle);
nlr_raise(
mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("Failed creating RTCH task")));
}
ESP_LOGD(TAG, "RTCH Initialized");
return mp_const_none;
}
STATIC mp_obj_t mp_rtch_deinit(mp_obj_t self_in)
{
rtch_t *self = MP_OBJ_TO_PTR(self_in);
vTaskDelete(self->rtch_task_handle);
adc_power_off();
gpio_isr_handler_remove(self->touch_sense);
// Configure all touch pins to high impedance (input)
gpio_config(&(gpio_config_t){
.mode = GPIO_MODE_INPUT,
.pin_bit_mask =
(1ULL<<self->xp) |
(1ULL<<self->yp) |
(1ULL<<self->xm) |
(1ULL<<self->ym) |
(1ULL<<self->touch_rail) |
(1ULL<<self->touch_sense)
});
return mp_const_none;
}
STATIC int compare_int(const void *_a, const void *_b)
{
int *a = (int*)_a;
int *b = (int*)_b;
return *a - *b;
}
STATIC int measure_axis(
rtch_t *self,
gpio_num_t plus,
gpio_num_t minus,
gpio_num_t measure,
gpio_num_t ignore)
{
// Set GPIOs:
// - Disable touch rail
gpio_set_level(self->touch_rail, 1);
// - Float "ignore" and "measure"
gpio_pad_select_gpio(ignore);
gpio_set_direction(ignore, GPIO_MODE_DISABLE);
gpio_set_pull_mode(ignore, GPIO_FLOATING);
gpio_pad_select_gpio(measure);
gpio_set_direction(measure, GPIO_MODE_DISABLE);
gpio_set_pull_mode(measure, GPIO_FLOATING);
// - Set "plus" to 1, "minus" to 0
gpio_config(&(gpio_config_t){
.mode = GPIO_MODE_OUTPUT,
.pin_bit_mask = (1ULL<<plus) | (1ULL<<minus)
});
gpio_set_level(plus, 1);
gpio_set_level(minus, 0);
// Init ADC
adc1_channel_t adc_channel = gpio_to_adc[measure];
adc_gpio_init(ADC_UNIT_1, adc_channel);
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(adc_channel,ADC_ATTEN_DB_11);
vTaskDelay(RTCH_INIT_ADC_WAIT_MS / portTICK_RATE_MS);
// Collect ADC samples and sort them
static int samples[RTCH_MAX_TOUCH_SAMPLES];
int sample_count = self->touch_samples;
for (int i=0; i<sample_count; i++)
{
//vTaskDelay(RTCH_SAMPLE_WAIT_MS / portTICK_RATE_MS);
samples[i] = adc1_get_raw(adc_channel);
}
qsort(samples, sample_count, sizeof(samples[0]), compare_int);
// Make sure samples are close to each other
int prevSample = INVALID_MEASUREMENT;
for (int i=0; i<sample_count; i++)
{
//ESP_LOGD(TAG, "RAW Sample %d: [%d]", i, samples[i]);
int sample = samples[i];
if (prevSample != INVALID_MEASUREMENT &&
abs(sample - prevSample) > self->touch_samples_threshold) {
return INVALID_MEASUREMENT;
}
prevSample = sample;
}
// return median
return samples[sample_count / 2];
}
STATIC void IRAM_ATTR rtch_isr_handler(void* arg)
{
rtch_t *self = (rtch_t*)arg;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
// Disable gpio interrupt
gpio_intr_disable(self->touch_sense);
// Notify the task
xTaskNotifyFromISR(
self->rtch_task_handle,
0,
eNoAction,
&xHigherPriorityTaskWoken);
if (xHigherPriorityTaskWoken) portYIELD_FROM_ISR();
}
STATIC void rtch_task(void* arg)
{
rtch_t *self = (rtch_t*)arg;
ESP_LOGD(TAG, "rtch_task started.");
for( ;; )
{
// Enable Interrupt
//gpio_intr_enable(self->touch_sense);
gpio_isr_handler_add(self->touch_sense, rtch_isr_handler, self);
// Wait for interrupt
ESP_LOGD(TAG, "Waiting for interrupt...");
xTaskNotifyWait(
0x00, /* Don't clear any notification bits on entry. */
0x00, /* Don't clear any notification bits on exit. */
NULL, /* Notified value ignored. */
portMAX_DELAY ); /* Block indefinitely. */
ESP_LOGD(TAG, "Touched!");
// Touch detected. Loop until untouched
while(gpio_get_level(self->touch_sense))
{
ESP_LOGD(TAG, "Measuring...");
// measure X and Y
int x = measure_axis(
self,
self->xp,
self->xm,
self->yp,
self->ym);
int y = measure_axis(
self,
self->yp,
self->ym,
self->xp,
self->xm);
ESP_LOGD(TAG, "RAW: [%d, %d]", x, y);
// If measurements valid, calculate calibrated X and Y
if (x != INVALID_MEASUREMENT && y != INVALID_MEASUREMENT)
{
x = ((x - self->cal_x0) * self->screen_width) / (self->cal_x1 - self->cal_x0);
y = ((y - self->cal_y0) * self->screen_height) / (self->cal_y1 - self->cal_y0);
if (1) // (x >= 0 && y >= 0 && x < self->screen_width && y < self->screen_height)
{
ESP_LOGD(TAG, "[%d, %d]", x, y);
// Update touch info
xSemaphoreTake(self->rtch_info_mutex, portMAX_DELAY);
self->rtch_info.touched = true;
self->rtch_info.x = x;
self->rtch_info.y = y;
xSemaphoreGive(self->rtch_info_mutex);
} else {
ESP_LOGD(TAG, "Overflow measurement [%d, %d]", x, y);
}
} else {
ESP_LOGD(TAG, "Invalid measurement");
}
enable_touch_sense(self);
}
ESP_LOGD(TAG, "Untouched!");
// Untouched. Update touch info
xSemaphoreTake(self->rtch_info_mutex, portMAX_DELAY);
self->rtch_info.touched = false;
xSemaphoreGive(self->rtch_info_mutex);
}
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/modrtch.c | C | apache-2.0 | 16,236 |
//////////////////////////////////////////////////////////////////////////////
// Includes
//////////////////////////////////////////////////////////////////////////////
#include "../include/common.h"
#include "lvgl/src/lv_hal/lv_hal_indev.h"
#include "lvgl/src/lv_core/lv_disp.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "esp_system.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
//////////////////////////////////////////////////////////////////////////////
// Defines
//////////////////////////////////////////////////////////////////////////////
#define XPT2046_AVG 4
#define CMD_X_READ 0b10010000
#define CMD_Y_READ 0b11010000
//////////////////////////////////////////////////////////////////////////////
// Module definition
//////////////////////////////////////////////////////////////////////////////
typedef struct _xpt2046_obj_t
{
mp_obj_base_t base;
uint8_t mhz;
uint8_t spihost;
uint8_t cs;
uint8_t irq;
int16_t x_min;
int16_t y_min;
int16_t x_max;
int16_t y_max;
bool x_inv;
bool y_inv;
bool xy_swap;
spi_device_handle_t spi;
int16_t avg_buf_x[XPT2046_AVG];
int16_t avg_buf_y[XPT2046_AVG];
uint8_t avg_last;
} xpt2046_obj_t;
// Unfortunately, lvgl doesn't pass user_data to callbacks, so we use this global.
// This means we can have only one active touch driver instance, pointed by this global.
STATIC xpt2046_obj_t *g_xpt2046 = NULL;
STATIC mp_obj_t mp_activate_xpt2046(mp_obj_t self_in)
{
xpt2046_obj_t *self = MP_OBJ_TO_PTR(self_in);
g_xpt2046 = self;
return mp_const_none;
}
STATIC mp_obj_t xpt2046_make_new(const mp_obj_type_t *type,
size_t n_args,
size_t n_kw,
const mp_obj_t *all_args)
{
enum{
ARG_mhz,
ARG_spihost,
ARG_cs,
ARG_irq,
ARG_x_min,
ARG_y_min,
ARG_x_max,
ARG_y_max,
ARG_x_inv,
ARG_y_inv,
ARG_xy_swap,
};
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_mhz, MP_ARG_INT, {.u_int = 20}},
{ MP_QSTR_spihost, MP_ARG_INT, {.u_int = HSPI_HOST}},
{ MP_QSTR_cs, MP_ARG_INT, {.u_int = 33}},
{ MP_QSTR_irq, MP_ARG_INT, {.u_int = 25}},
{ MP_QSTR_x_min, MP_ARG_INT, {.u_int = 1000}},
{ MP_QSTR_y_min, MP_ARG_INT, {.u_int = 1000}},
{ MP_QSTR_x_max, MP_ARG_INT, {.u_int = 3200}},
{ MP_QSTR_y_max, MP_ARG_INT, {.u_int = 2000}},
{ MP_QSTR_x_inv, MP_ARG_BOOL, {.u_obj = mp_const_true}},
{ MP_QSTR_y_inv, MP_ARG_BOOL, {.u_obj = mp_const_true}},
{ MP_QSTR_xy_swap, MP_ARG_BOOL, {.u_obj = mp_const_false}},
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
xpt2046_obj_t *self = m_new_obj(xpt2046_obj_t);
self->base.type = type;
self->mhz = args[ARG_mhz].u_int;
self->spihost = args[ARG_spihost].u_int;
self->cs = args[ARG_cs].u_int;
self->irq = args[ARG_irq].u_int;
self->x_min = args[ARG_x_min].u_int;
self->y_min = args[ARG_y_min].u_int;
self->x_max = args[ARG_x_max].u_int;
self->y_max = args[ARG_y_max].u_int;
self->x_inv = args[ARG_x_inv].u_bool;
self->y_inv = args[ARG_y_inv].u_bool;
self->xy_swap = args[ARG_xy_swap].u_bool;
return MP_OBJ_FROM_PTR(self);
}
STATIC mp_obj_t mp_xpt2046_init(mp_obj_t self_in);
STATIC mp_obj_t mp_xpt2046_deinit(mp_obj_t self_in);
STATIC bool xpt2046_read(lv_indev_drv_t * indev_drv, lv_indev_data_t *data);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_init_xpt2046_obj, mp_xpt2046_init);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_deinit_xpt2046_obj, mp_xpt2046_deinit);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_activate_xpt2046_obj, mp_activate_xpt2046);
DEFINE_PTR_OBJ(xpt2046_read);
STATIC const mp_rom_map_elem_t xpt2046_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&mp_init_xpt2046_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mp_deinit_xpt2046_obj) },
{ MP_ROM_QSTR(MP_QSTR_activate), MP_ROM_PTR(&mp_activate_xpt2046_obj) },
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&PTR_OBJ(xpt2046_read)) },
};
STATIC MP_DEFINE_CONST_DICT(xpt2046_locals_dict, xpt2046_locals_dict_table);
STATIC const mp_obj_type_t xpt2046_type = {
{ &mp_type_type },
.name = MP_QSTR_xpt2046,
//.print = xpt2046_print,
.make_new = xpt2046_make_new,
.locals_dict = (mp_obj_dict_t*)&xpt2046_locals_dict,
};
STATIC const mp_rom_map_elem_t xpt2046_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_xpt2046) },
{ MP_ROM_QSTR(MP_QSTR_xpt2046), (mp_obj_t)&xpt2046_type},
};
STATIC MP_DEFINE_CONST_DICT (
mp_module_xpt2046_globals,
xpt2046_globals_table
);
const mp_obj_module_t mp_module_xpt2046 = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_xpt2046_globals
};
//////////////////////////////////////////////////////////////////////////////
// Module implementation
//////////////////////////////////////////////////////////////////////////////
STATIC mp_obj_t mp_xpt2046_init(mp_obj_t self_in)
{
esp_err_t ret;
xpt2046_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_activate_xpt2046(self_in);
spi_device_interface_config_t devcfg={
.clock_speed_hz=self->mhz*1000*1000, //Clock out at DISP_SPI_MHZ MHz
.mode=0, //SPI mode 0
.spics_io_num=-1, //CS pin is set manually
.queue_size=1,
.pre_cb=NULL,
.post_cb=NULL,
.flags=SPI_DEVICE_HALFDUPLEX,
.duty_cycle_pos=128,
};
gpio_set_direction(self->irq, GPIO_MODE_INPUT);
gpio_set_direction(self->cs, GPIO_MODE_OUTPUT);
gpio_set_level(self->cs, 1);
//Attach the touch controller to the SPI bus
ret=spi_bus_add_device(self->spihost, &devcfg, &self->spi);
if (ret != ESP_OK) nlr_raise(
mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("Failed adding SPI device")));
return mp_const_none;
}
STATIC mp_obj_t mp_xpt2046_deinit(mp_obj_t self_in)
{
//xpt2046_obj_t *self = MP_OBJ_TO_PTR(self_in);
return mp_const_none;
}
static void xpt2046_corr(xpt2046_obj_t *self, int16_t * x, int16_t * y);
static void xpt2046_avg(xpt2046_obj_t *self, int16_t * x, int16_t * y);
static uint8_t tp_spi_xchg(xpt2046_obj_t *self, uint8_t data_send);
/**
* Get the current position and state of the touchpad
* @param indev_drv pointer to the caller input device driver
* @param data store the read data here
* @return false: because no ore data to be read
*/
static bool xpt2046_read(lv_indev_drv_t * indev_drv, lv_indev_data_t * data)
{
xpt2046_obj_t *self = MP_OBJ_TO_PTR(g_xpt2046 );
if (!self || (!self->spi)) nlr_raise(
mp_obj_new_exception_msg(
&mp_type_RuntimeError, MP_ERROR_TEXT("xpt2046 instance needs to be created before callback is called!")));
static int16_t last_x = 0;
static int16_t last_y = 0;
bool valid = true;
uint8_t buf;
int16_t x = 0;
int16_t y = 0;
uint8_t irq = gpio_get_level(self->irq);
if(irq == 0) {
gpio_set_level(self->cs, 0);
tp_spi_xchg(self, CMD_X_READ); /*Start x read*/
buf = tp_spi_xchg(self, 0); /*Read x MSB*/
x = buf << 8;
buf = tp_spi_xchg(self, CMD_Y_READ); /*Until x LSB converted y command can be sent*/
x += buf;
buf = tp_spi_xchg(self, 0); /*Read y MSB*/
y = buf << 8;
buf = tp_spi_xchg(self, 0); /*Read y LSB*/
y += buf;
gpio_set_level(self->cs, 1);
/*Normalize Data*/
x = x >> 3;
y = y >> 3;
xpt2046_corr(self, &x, &y);
xpt2046_avg(self, &x, &y);
last_x = x;
last_y = y;
} else {
x = last_x;
y = last_y;
self->avg_last = 0;
valid = false;
}
data->point.x = x;
data->point.y = y;
data->state = valid == false ? LV_INDEV_STATE_REL : LV_INDEV_STATE_PR;
return valid;
}
/**********************
* HELPER FUNCTIONS
**********************/
static uint8_t tp_spi_xchg(xpt2046_obj_t *self, uint8_t data_send)
{
uint8_t data_rec = 0;
spi_transaction_t t;
memset(&t, 0, sizeof(t)); //Zero out the transaction
t.length = 8; //Length is in bytes, transaction length is in bits.
t.tx_buffer = &data_send; //Data
t.rx_buffer = &data_rec;
spi_device_queue_trans(self->spi, &t, portMAX_DELAY);
spi_transaction_t * rt;
spi_device_get_trans_result(self->spi, &rt, portMAX_DELAY);
return data_rec;
}
static void xpt2046_corr(xpt2046_obj_t *self, int16_t * x, int16_t * y)
{
if (self->xy_swap){
int16_t swap_tmp;
swap_tmp = *x;
*x = *y;
*y = swap_tmp;
}
if((*x) > self->x_min)(*x) -= self->x_min;
else(*x) = 0;
if((*y) > self->y_min)(*y) -= self->y_min;
else(*y) = 0;
(*x) = (uint32_t)((uint32_t)(*x) * LV_HOR_RES) /
(self->x_max - self->x_min);
(*y) = (uint32_t)((uint32_t)(*y) * LV_VER_RES) /
(self->y_max - self->y_min);
if (self->x_inv){
(*x) = LV_HOR_RES - (*x);
}
if (self->y_inv){
(*y) = LV_VER_RES - (*y);
}
}
static void xpt2046_avg(xpt2046_obj_t *self, int16_t * x, int16_t * y)
{
/*Shift out the oldest data*/
uint8_t i;
for(i = XPT2046_AVG - 1; i > 0 ; i--) {
self->avg_buf_x[i] = self->avg_buf_x[i - 1];
self->avg_buf_y[i] = self->avg_buf_y[i - 1];
}
/*Insert the new point*/
self->avg_buf_x[0] = *x;
self->avg_buf_y[0] = *y;
if(self->avg_last < XPT2046_AVG) self->avg_last++;
/*Sum the x and y coordinates*/
int32_t x_sum = 0;
int32_t y_sum = 0;
for(i = 0; i < self->avg_last ; i++) {
x_sum += self->avg_buf_x[i];
y_sum += self->avg_buf_y[i];
}
/*Normalize the sums*/
(*x) = (int32_t)x_sum / self->avg_last;
(*y) = (int32_t)y_sum / self->avg_last;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/modxpt2046.c | C | apache-2.0 | 10,062 |
// Copyright 2017 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This is a modified sh2lib, for better integration with LVGL Micropython bindings.
#define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
#if __has_include("esp_idf_version.h")
# include "esp_idf_version.h"
#endif
#if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 4
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <netdb.h>
#include <esp_log.h>
#include <http_parser.h>
#include <esp_tls.h>
#include <nghttp2/nghttp2.h>
#include "sh2lib.h"
static const char *TAG = "sh2lib";
#define DBG_FRAME_SEND 1
#ifndef ESP_TLS_ERR_SSL_WANT_READ
#define ESP_TLS_ERR_SSL_WANT_READ MBEDTLS_ERR_SSL_WANT_READ
#endif
#ifndef ESP_TLS_ERR_SSL_WANT_WRITE
#define ESP_TLS_ERR_SSL_WANT_WRITE MBEDTLS_ERR_SSL_WANT_WRITE
#endif
#ifndef ESP_TLS_ERR_SSL_TIMEOUT
#define ESP_TLS_ERR_SSL_TIMEOUT MBEDTLS_ERR_SSL_TIMEOUT
#endif
/**
* Conversion between sh2lib name-value pairs and nghttp2 pairs
* sh2lib_nv arrays can be populated from Micropython
*/
static void shlib_load_nva(nghttp2_nv ng_nva[], const struct sh2lib_nv nva[], size_t nvlen)
{
for (size_t i = 0; i < nvlen; i++){
const struct sh2lib_nv *nv = &nva[i];
ng_nva[i] = (nghttp2_nv){
(uint8_t *)nv->name,
(uint8_t *)nv->value,
strlen(nv->name),
strlen(nv->value),
nv->flags
};
}
}
/*
* The implementation of nghttp2_send_callback type. Here we write
* |data| with size |length| to the network and return the number of
* bytes actually written. See the documentation of
* nghttp2_send_callback for the details.
*/
static ssize_t callback_send_inner(struct sh2lib_handle *hd, const uint8_t *data,
size_t length)
{
int rv = esp_tls_conn_write(hd->http2_tls, data, length);
if (rv < 0) {
if (rv == ESP_TLS_ERR_SSL_WANT_READ || rv == ESP_TLS_ERR_SSL_WANT_WRITE) {
rv = NGHTTP2_ERR_WOULDBLOCK;
} else {
ESP_LOGE(TAG, "[sh2-callback_send_inner] esp_tls_conn_write failed with error %d, (%s)", rv,
esp_err_to_name(esp_tls_get_and_clear_last_error(hd->http2_tls->error_handle, NULL, NULL)));
rv = NGHTTP2_ERR_CALLBACK_FAILURE;
}
}
return rv;
}
static ssize_t callback_send(nghttp2_session *session, const uint8_t *data,
size_t length, int flags, void *user_data)
{
int rv = 0;
struct sh2lib_handle *hd = user_data;
int copy_offset = 0;
int pending_data = length;
/* Send data in 1000 byte chunks */
while (copy_offset != length) {
int chunk_len = pending_data > 1000 ? 1000 : pending_data;
int subrv = callback_send_inner(hd, data + copy_offset, chunk_len);
if (subrv <= 0) {
if (copy_offset == 0) {
/* If no data is transferred, send the error code */
rv = subrv;
}
break;
}
copy_offset += subrv;
pending_data -= subrv;
rv += subrv;
}
return rv;
}
/*
* The implementation of nghttp2_recv_callback type. Here we read data
* from the network and write them in |buf|. The capacity of |buf| is
* |length| bytes. Returns the number of bytes stored in |buf|. See
* the documentation of nghttp2_recv_callback for the details.
*/
static ssize_t callback_recv(nghttp2_session *session, uint8_t *buf,
size_t length, int flags, void *user_data)
{
struct sh2lib_handle *hd = user_data;
int rv;
rv = esp_tls_conn_read(hd->http2_tls, (char *)buf, (int)length);
if (rv < 0) {
if (rv == ESP_TLS_ERR_SSL_WANT_READ || rv == ESP_TLS_ERR_SSL_WANT_WRITE) {
rv = NGHTTP2_ERR_WOULDBLOCK;
} else {
ESP_LOGE(TAG, "[sh2-callback_recv] esp_tls_conn_read failed with error %d (%s)", rv,
esp_err_to_name(esp_tls_get_and_clear_last_error(hd->http2_tls->error_handle, NULL, NULL)));
rv = NGHTTP2_ERR_CALLBACK_FAILURE;
}
} else if (rv == 0) {
rv = NGHTTP2_ERR_EOF;
}
return rv;
}
const char *sh2lib_frame_type_str(int type)
{
switch (type) {
case NGHTTP2_HEADERS:
return "HEADERS";
break;
case NGHTTP2_RST_STREAM:
return "RST_STREAM";
break;
case NGHTTP2_GOAWAY:
return "GOAWAY";
break;
case NGHTTP2_DATA:
return "DATA";
break;
case NGHTTP2_SETTINGS:
return "SETTINGS";
break;
case NGHTTP2_PUSH_PROMISE:
return "PUSH_PROMISE";
break;
case NGHTTP2_PING:
return "PING";
break;
default:
return "other";
break;
}
}
static int callback_on_frame_send(nghttp2_session *session,
const nghttp2_frame *frame, void *user_data)
{
ESP_LOGD(TAG, "[frame-send] frame type %s (%d)", sh2lib_frame_type_str(frame->hd.type), frame->hd.type);
switch (frame->hd.type) {
case NGHTTP2_HEADERS:
if (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id)) {
ESP_LOGD(TAG, "[frame-send] C ----------------------------> S (HEADERS)");
#if DBG_FRAME_SEND
ESP_LOGD(TAG, "[frame-send] headers nv-len = %d", frame->headers.nvlen);
const nghttp2_nv *nva = frame->headers.nva;
size_t i;
for (i = 0; i < frame->headers.nvlen; ++i) {
ESP_LOGD(TAG, "[frame-send] %s : %s", nva[i].name, nva[i].value);
}
#endif
}
break;
}
return 0;
}
static int callback_on_frame_recv(nghttp2_session *session,
const nghttp2_frame *frame, void *user_data)
{
ESP_LOGD(TAG, "[frame-recv][sid: %d] frame type %s (%d)", frame->hd.stream_id, sh2lib_frame_type_str(frame->hd.type), frame->hd.type);
if (frame->hd.type != NGHTTP2_DATA) {
return 0;
}
/* Subsequent processing only for data frame */
sh2lib_frame_data_recv_cb_t data_recv_cb = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
if (data_recv_cb) {
struct sh2lib_handle *h2 = user_data;
(*data_recv_cb)(h2, NULL, 0, SH2LIB_DATA_RECV_FRAME_COMPLETE);
}
return 0;
}
static int callback_on_stream_close(nghttp2_session *session, int32_t stream_id,
uint32_t error_code, void *user_data)
{
ESP_LOGD(TAG, "[stream-close][sid %d]", stream_id);
sh2lib_frame_data_recv_cb_t data_recv_cb = nghttp2_session_get_stream_user_data(session, stream_id);
if (data_recv_cb) {
struct sh2lib_handle *h2 = user_data;
(*data_recv_cb)(h2, NULL, 0, SH2LIB_DATA_RECV_RST_STREAM);
}
return 0;
}
static int callback_on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
int32_t stream_id, const uint8_t *data,
size_t len, void *user_data)
{
sh2lib_frame_data_recv_cb_t data_recv_cb;
ESP_LOGD(TAG, "[data-chunk][sid:%d]", stream_id);
data_recv_cb = nghttp2_session_get_stream_user_data(session, stream_id);
if (data_recv_cb) {
ESP_LOGD(TAG, "[data-chunk] C <---------------------------- S (DATA chunk)"
"%lu bytes",
(unsigned long int)len);
struct sh2lib_handle *h2 = user_data;
(*data_recv_cb)(h2, (char *)data, len, 0);
/* TODO: What to do with the return value: look for pause/abort */
}
return 0;
}
static int callback_on_header(nghttp2_session *session, const nghttp2_frame *frame,
const uint8_t *name, size_t namelen, const uint8_t *value,
size_t valuelen, uint8_t flags, void *user_data)
{
ESP_LOGD(TAG, "[hdr-recv][sid:%d] %s : %s", frame->hd.stream_id, name, value);
return 0;
}
static int callback_on_extension(nghttp2_session *session, const nghttp2_frame_hd *hd, const uint8_t *data, size_t len, void *user_data)
{
ESP_LOGD(TAG, "[extension-recv][sid:%d] len=%d", hd->stream_id, len);
return 0;
}
static int do_http2_connect(struct sh2lib_handle *hd)
{
int ret;
nghttp2_session_callbacks *callbacks;
nghttp2_session_callbacks_new(&callbacks);
nghttp2_session_callbacks_set_send_callback(callbacks, callback_send);
nghttp2_session_callbacks_set_recv_callback(callbacks, callback_recv);
nghttp2_session_callbacks_set_on_frame_send_callback(callbacks, callback_on_frame_send);
nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks, callback_on_frame_recv);
nghttp2_session_callbacks_set_on_stream_close_callback(callbacks, callback_on_stream_close);
nghttp2_session_callbacks_set_on_data_chunk_recv_callback(callbacks, callback_on_data_chunk_recv);
nghttp2_session_callbacks_set_on_header_callback(callbacks, callback_on_header);
nghttp2_session_callbacks_set_on_extension_chunk_recv_callback(callbacks, callback_on_extension);
ret = nghttp2_session_client_new(&hd->http2_sess, callbacks, hd);
if (ret != 0) {
ESP_LOGE(TAG, "[sh2-connect] New http2 session failed");
nghttp2_session_callbacks_del(callbacks);
return -1;
}
nghttp2_session_callbacks_del(callbacks);
/* Create the SETTINGS frame */
ret = nghttp2_submit_settings(hd->http2_sess, NGHTTP2_FLAG_NONE, NULL, 0);
if (ret != 0) {
ESP_LOGE(TAG, "[sh2-connect] Submit settings failed");
return -1;
}
return 0;
}
static void sh2lib_init_handle(struct sh2lib_handle *hd, const char *uri)
{
hd->connect_result = 0;
hd->connect_task_handle = NULL;
if (!hd->http2_tls) {
hd->http2_tls = esp_tls_init();
}
if (!hd->http2_tls_cfg) {
hd->http2_tls_cfg = malloc(sizeof(struct esp_tls_cfg));
static const char *proto[] = {"h2", NULL};
*hd->http2_tls_cfg = (struct esp_tls_cfg) {
.alpn_protos = proto,
.non_block = true,
.timeout_ms = 10 * 1000,
.skip_common_name = true
};
}
if (!hd->hostname) {
struct http_parser_url u;
http_parser_url_init(&u);
http_parser_parse_url(uri, strlen(uri), 0, &u);
hd->hostname = strndup(&uri[u.field_data[UF_HOST].off], u.field_data[UF_HOST].len);
}
}
static void sh2lib_connect_task_function(void *param)
{
struct sh2lib_handle *hd = param;
if (!hd->hostname) goto error;
int res = esp_tls_conn_new_sync(hd->hostname, strlen(hd->hostname), 443, hd->http2_tls_cfg, hd->http2_tls);
if (res != 1) {
ESP_LOGE(TAG, "[sh2-connect] esp-tls connection failed with error %d", res);
goto error;
}
/* HTTP/2 Connection */
if (do_http2_connect(hd) != 0) {
ESP_LOGE(TAG, "[sh2-connect] HTTP2 Connection failed");
goto error;
}
hd->connect_result = 1;
vTaskDelete(NULL);
error:
sh2lib_free(hd);
hd->connect_result = -1;
vTaskDelete(NULL);
}
int sh2lib_connect_task(struct sh2lib_handle *hd, const char *uri, int priority, int core_id)
{
sh2lib_init_handle(hd, uri);
BaseType_t res = xTaskCreatePinnedToCore(sh2lib_connect_task_function, "sh2lib connect task", 4096, hd, priority, hd->connect_task_handle, core_id);
return res == pdPASS? 0: -1;
}
int sh2lib_connect(struct sh2lib_handle *hd, const char *uri)
{
sh2lib_init_handle(hd, uri);
int res = esp_tls_conn_new_sync(hd->hostname, strlen(hd->hostname), 443, hd->http2_tls_cfg, hd->http2_tls);
if (res != 1) {
ESP_LOGE(TAG, "[sh2-connect] esp-tls connection failed with error %d", res);
goto error;
}
/* HTTP/2 Connection */
if (do_http2_connect(hd) != 0) {
ESP_LOGE(TAG, "[sh2-connect] HTTP2 Connection failed with %s", uri);
goto error;
}
hd->connect_result = 1;
return 0;
error:
sh2lib_free(hd);
hd->connect_result = -1;
return -1;
}
int sh2lib_connect_async(struct sh2lib_handle *hd, const char *uri)
{
sh2lib_init_handle(hd, uri);
int res = esp_tls_conn_new_async(hd->hostname, strlen(hd->hostname), 443, hd->http2_tls_cfg, hd->http2_tls);
if (res == -1) {
ESP_LOGE(TAG, "[sh2-async_connect] esp-tls connection failed");
goto error;
}
else if (res == 0) {
return 0;
}
/* HTTP/2 Connection */
if (do_http2_connect(hd) != 0) {
ESP_LOGE(TAG, "[sh2-async_connect] HTTP2 Connection failed with %s", uri);
goto error;
}
hd->connect_result = 1;
return 1;
error:
sh2lib_free(hd);
hd->connect_result = -1;
return -1;
}
void sh2lib_free(struct sh2lib_handle *hd)
{
if (hd->http2_sess) {
nghttp2_session_del(hd->http2_sess);
hd->http2_sess = NULL;
}
if (hd->http2_tls) {
esp_tls_conn_delete(hd->http2_tls);
hd->http2_tls = NULL;
}
if (hd->hostname) {
free(hd->hostname);
hd->hostname = NULL;
}
if (hd->http2_tls_cfg) {
free(hd->http2_tls_cfg);
hd->http2_tls_cfg = NULL;
}
if (hd->connect_task_handle) {
vTaskDelete(hd->connect_task_handle);
hd->connect_task_handle = NULL;
}
hd->connect_result = 0;
}
int sh2lib_execute(struct sh2lib_handle *hd)
{
int ret;
ret = nghttp2_session_send(hd->http2_sess);
if (ret != 0) {
ESP_LOGE(TAG, "[sh2-execute] HTTP2 session send failed %d", ret);
return -1;
}
ret = nghttp2_session_recv(hd->http2_sess);
if (ret != 0) {
ESP_LOGE(TAG, "[sh2-execute] HTTP2 session recv failed %d", ret);
return -1;
}
return 0;
}
int sh2lib_do_get_with_nv(struct sh2lib_handle *hd, const struct sh2lib_nv nva[], size_t nvlen, sh2lib_frame_data_recv_cb_t recv_cb)
{
nghttp2_nv ng_nva[nvlen];
shlib_load_nva(ng_nva, nva, nvlen);
int ret = nghttp2_submit_request(hd->http2_sess, NULL, ng_nva, nvlen, NULL, recv_cb);
if (ret < 0) {
ESP_LOGE(TAG, "[sh2-do-get] HEADERS call failed");
return -1;
}
return ret;
}
int sh2lib_do_get(struct sh2lib_handle *hd, const char *path, sh2lib_frame_data_recv_cb_t recv_cb)
{
const struct sh2lib_nv nva[] = { SH2LIB_MAKE_NV(":method", "GET"),
SH2LIB_MAKE_NV(":scheme", "https"),
SH2LIB_MAKE_NV(":authority", hd->hostname),
SH2LIB_MAKE_NV(":path", path),
};
return sh2lib_do_get_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), recv_cb);
}
ssize_t sh2lib_data_provider_cb(nghttp2_session *session, int32_t stream_id, uint8_t *buf,
size_t length, uint32_t *data_flags,
nghttp2_data_source *source, void *user_data)
{
struct sh2lib_handle *h2 = user_data;
sh2lib_putpost_data_cb_t data_cb = source->ptr;
return (*data_cb)(h2, (char *)buf, length, data_flags);
}
int sh2lib_do_putpost_with_nv(struct sh2lib_handle *hd, const struct sh2lib_nv nva[], size_t nvlen,
sh2lib_putpost_data_cb_t send_cb,
sh2lib_frame_data_recv_cb_t recv_cb)
{
nghttp2_nv ng_nva[nvlen];
shlib_load_nva(ng_nva, nva, nvlen);
nghttp2_data_provider sh2lib_data_provider;
sh2lib_data_provider.read_callback = sh2lib_data_provider_cb;
sh2lib_data_provider.source.ptr = send_cb;
int ret = nghttp2_submit_request(hd->http2_sess, NULL, ng_nva, nvlen, &sh2lib_data_provider, recv_cb);
if (ret < 0) {
ESP_LOGE(TAG, "[sh2-do-putpost] HEADERS call failed");
return -1;
}
return ret;
}
int sh2lib_do_post(struct sh2lib_handle *hd, const char *path,
sh2lib_putpost_data_cb_t send_cb,
sh2lib_frame_data_recv_cb_t recv_cb)
{
const struct sh2lib_nv nva[] = { SH2LIB_MAKE_NV(":method", "POST"),
SH2LIB_MAKE_NV(":scheme", "https"),
SH2LIB_MAKE_NV(":authority", hd->hostname),
SH2LIB_MAKE_NV(":path", path),
};
return sh2lib_do_putpost_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), send_cb, recv_cb);
}
int sh2lib_do_put(struct sh2lib_handle *hd, const char *path,
sh2lib_putpost_data_cb_t send_cb,
sh2lib_frame_data_recv_cb_t recv_cb)
{
const struct sh2lib_nv nva[] = { SH2LIB_MAKE_NV(":method", "PUT"),
SH2LIB_MAKE_NV(":scheme", "https"),
SH2LIB_MAKE_NV(":authority", hd->hostname),
SH2LIB_MAKE_NV(":path", path),
};
return sh2lib_do_putpost_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), send_cb, recv_cb);
}
int sh2lib_session_resume_data(struct sh2lib_handle *hd, int32_t stream_id)
{
return nghttp2_session_resume_data(hd->http2_sess, stream_id);
}
#endif // defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 4
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/sh2lib.c | C | apache-2.0 | 17,719 |
// Copyright 2017 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This is a modified sh2lib, for better integration with LVGL Micropython bindings.
// To prevent including the entire nghttp2 header, only selected enums where copied here.
#ifndef __ESP_EXAMPLE_SH2_LIB_H_
#define __ESP_EXAMPLE_SH2_LIB_H_
#if __has_include("esp_idf_version.h")
# include "esp_idf_version.h"
#endif
#if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 4
typedef struct nghttp2_session nghttp2_session;
typedef struct esp_tls esp_tls;
typedef struct esp_tls_cfg esp_tls_cfg;
/*
* This is a thin API wrapper over nghttp2 that offers simplified APIs for usage
* in the application. The intention of this wrapper is to act as a stepping
* stone to quickly get started with using the HTTP/2 client. Since the focus is
* on simplicity, not all the features of HTTP/2 are supported through this
* wrapper. Once you are fairly comfortable with nghttp2, feel free to directly
* use nghttp2 APIs or make changes to sh2lib.c for realising your objectives.
*
* TODO:
* - Allowing to query response code, content-type etc in the receive callback
* - A simple function for per-stream header callback
*/
/**
* @enum
*
* Error codes used in this library. The code range is [-999, -500],
* inclusive. The following values are defined:
*/
typedef enum {
/**
* Invalid argument passed.
*/
SH2LIB_ERR_INVALID_ARGUMENT = -501,
/**
* Out of buffer space.
*/
SH2LIB_ERR_BUFFER_ERROR = -502,
/**
* The specified protocol version is not supported.
*/
SH2LIB_ERR_UNSUPPORTED_VERSION = -503,
/**
* Used as a return value from :type:`nghttp2_send_callback`,
* :type:`nghttp2_recv_callback` and
* :type:`nghttp2_send_data_callback` to indicate that the operation
* would block.
*/
SH2LIB_ERR_WOULDBLOCK = -504,
/**
* General protocol error
*/
SH2LIB_ERR_PROTO = -505,
/**
* The frame is invalid.
*/
SH2LIB_ERR_INVALID_FRAME = -506,
/**
* The peer performed a shutdown on the connection.
*/
SH2LIB_ERR_EOF = -507,
/**
* Used as a return value from
* :func:`nghttp2_data_source_read_callback` to indicate that data
* transfer is postponed. See
* :func:`nghttp2_data_source_read_callback` for details.
*/
SH2LIB_ERR_DEFERRED = -508,
/**
* Stream ID has reached the maximum value. Therefore no stream ID
* is available.
*/
SH2LIB_ERR_STREAM_ID_NOT_AVAILABLE = -509,
/**
* The stream is already closed; or the stream ID is invalid.
*/
SH2LIB_ERR_STREAM_CLOSED = -510,
/**
* RST_STREAM has been added to the outbound queue. The stream is
* in closing state.
*/
SH2LIB_ERR_STREAM_CLOSING = -511,
/**
* The transmission is not allowed for this stream (e.g., a frame
* with END_STREAM flag set has already sent).
*/
SH2LIB_ERR_STREAM_SHUT_WR = -512,
/**
* The stream ID is invalid.
*/
SH2LIB_ERR_INVALID_STREAM_ID = -513,
/**
* The state of the stream is not valid (e.g., DATA cannot be sent
* to the stream if response HEADERS has not been sent).
*/
SH2LIB_ERR_INVALID_STREAM_STATE = -514,
/**
* Another DATA frame has already been deferred.
*/
SH2LIB_ERR_DEFERRED_DATA_EXIST = -515,
/**
* Starting new stream is not allowed (e.g., GOAWAY has been sent
* and/or received).
*/
SH2LIB_ERR_START_STREAM_NOT_ALLOWED = -516,
/**
* GOAWAY has already been sent.
*/
SH2LIB_ERR_GOAWAY_ALREADY_SENT = -517,
/**
* The received frame contains the invalid header block (e.g., There
* are duplicate header names; or the header names are not encoded
* in US-ASCII character set and not lower cased; or the header name
* is zero-length string; or the header value contains multiple
* in-sequence NUL bytes).
*/
SH2LIB_ERR_INVALID_HEADER_BLOCK = -518,
/**
* Indicates that the context is not suitable to perform the
* requested operation.
*/
SH2LIB_ERR_INVALID_STATE = -519,
/**
* The user callback function failed due to the temporal error.
*/
SH2LIB_ERR_TEMPORAL_CALLBACK_FAILURE = -521,
/**
* The length of the frame is invalid, either too large or too small.
*/
SH2LIB_ERR_FRAME_SIZE_ERROR = -522,
/**
* Header block inflate/deflate error.
*/
SH2LIB_ERR_HEADER_COMP = -523,
/**
* Flow control error
*/
SH2LIB_ERR_FLOW_CONTROL = -524,
/**
* Insufficient buffer size given to function.
*/
SH2LIB_ERR_INSUFF_BUFSIZE = -525,
/**
* Callback was paused by the application
*/
SH2LIB_ERR_PAUSE = -526,
/**
* There are too many in-flight SETTING frame and no more
* transmission of SETTINGS is allowed.
*/
SH2LIB_ERR_TOO_MANY_INFLIGHT_SETTINGS = -527,
/**
* The server push is disabled.
*/
SH2LIB_ERR_PUSH_DISABLED = -528,
/**
* DATA or HEADERS frame for a given stream has been already
* submitted and has not been fully processed yet. Application
* should wait for the transmission of the previously submitted
* frame before submitting another.
*/
SH2LIB_ERR_DATA_EXIST = -529,
/**
* The current session is closing due to a connection error or
* `nghttp2_session_terminate_session()` is called.
*/
SH2LIB_ERR_SESSION_CLOSING = -530,
/**
* Invalid HTTP header field was received and stream is going to be
* closed.
*/
SH2LIB_ERR_HTTP_HEADER = -531,
/**
* Violation in HTTP messaging rule.
*/
SH2LIB_ERR_HTTP_MESSAGING = -532,
/**
* Stream was refused.
*/
SH2LIB_ERR_REFUSED_STREAM = -533,
/**
* Unexpected internal error, but recovered.
*/
SH2LIB_ERR_INTERNAL = -534,
/**
* Indicates that a processing was canceled.
*/
SH2LIB_ERR_CANCEL = -535,
/**
* The errors < :enum:`SH2LIB_ERR_FATAL` mean that the library is
* under unexpected condition and processing was terminated (e.g.,
* out of memory). If application receives this error code, it must
* stop using that :type:`nghttp2_session` object and only allowed
* operation for that object is deallocate it using
* `nghttp2_session_del()`.
*/
SH2LIB_ERR_FATAL = -900,
/**
* Out of memory. This is a fatal error.
*/
SH2LIB_ERR_NOMEM = -901,
/**
* The user callback function failed. This is a fatal error.
*/
SH2LIB_ERR_CALLBACK_FAILURE = -902,
/**
* Invalid client magic (see :macro:`SH2LIB_CLIENT_MAGIC`) was
* received and further processing is not possible.
*/
SH2LIB_ERR_BAD_CLIENT_MAGIC = -903,
/**
* Possible flooding by peer was detected in this HTTP/2 session.
* Flooding is measured by how many PING and SETTINGS frames with
* ACK flag set are queued for transmission. These frames are
* response for the peer initiated frames, and peer can cause memory
* exhaustion on server side to send these frames forever and does
* not read network.
*/
SH2LIB_ERR_FLOODED = -904
} sh2lib_error;
/**
* @enum
*
* The flags for header field name/value pair.
*/
typedef enum {
/**
* No flag set.
*/
SH2LIB_NV_FLAG_NONE = 0,
/**
* Indicates that this name/value pair must not be indexed ("Literal
* Header Field never Indexed" representation must be used in HPACK
* encoding). Other implementation calls this bit as "sensitive".
*/
SH2LIB_NV_FLAG_NO_INDEX = 0x01,
/**
* This flag is set solely by application. If this flag is set, the
* library does not make a copy of header field name. This could
* improve performance.
*/
SH2LIB_NV_FLAG_NO_COPY_NAME = 0x02,
/**
* This flag is set solely by application. If this flag is set, the
* library does not make a copy of header field value. This could
* improve performance.
*/
SH2LIB_NV_FLAG_NO_COPY_VALUE = 0x04
} sh2lib_nv_flag;
/**
* @enum
*
* The flags used to set in |data_flags| output parameter in
* :type:`nghttp2_data_source_read_callback`.
*/
typedef enum {
/**
* No flag set.
*/
SH2LIB_DATA_FLAG_NONE = 0,
/**
* Indicates EOF was sensed.
*/
SH2LIB_DATA_FLAG_EOF = 0x01,
/**
* Indicates that END_STREAM flag must not be set even if
* SH2LIB_DATA_FLAG_EOF is set. Usually this flag is used to send
* trailer fields with `nghttp2_submit_request()` or
* `nghttp2_submit_response()`.
*/
SH2LIB_DATA_FLAG_NO_END_STREAM = 0x02,
/**
* Indicates that application will send complete DATA frame in
* :type:`nghttp2_send_data_callback`.
*/
SH2LIB_DATA_FLAG_NO_COPY = 0x04
} sh2lib_data_flag;
/**
* @brief Flag returned by data_recv_cb to indicate recieve status
*/
typedef enum {
SH2LIB_DATA_RECV_NONE,
SH2LIB_DATA_RECV_RST_STREAM, /*!< Flag indicating receive stream is reset */
SH2LIB_DATA_RECV_FRAME_COMPLETE /*!< Flag indicating frame is completely received */
} sh2lib_data_recv_flag;
/**
* @brief Handle for working with sh2lib APIs
*/
struct sh2lib_handle {
nghttp2_session *http2_sess; /*!< Pointer to the HTTP2 session handle */
char *hostname; /*!< The hostname we are connected to */
struct esp_tls *http2_tls; /*!< Pointer to the TLS session handle */
struct esp_tls_cfg *http2_tls_cfg; /*!< Pointer to the TLS session configuration */
void *user_data; /*!< Needed for Micropython binding */
TaskHandle_t connect_task_handle; /*!< Connection task handle */
int connect_result; /*!< Current result of the connection task */
};
/**
* @brief Wrapper for nghttp2_nv
*/
struct sh2lib_nv {
const char *name;
const char *value;
uint8_t flags;
};
/**
* @brief Function Prototype for data receive callback
*
* This function gets called whenever data is received on any stream. The
* function is also called for indicating events like frame receive complete, or
* end of stream. The function may get called multiple times as long as data is
* received on the stream.
*
* @param[in] handle Pointer to the sh2lib handle.
* @param[in] data Pointer to a buffer that contains the data received.
* @param[in] len The length of valid data stored at the 'data' pointer.
* @param[in] flags Flags indicating whether the stream is reset (DATA_RECV_RST_STREAM) or
* this particularly frame is completely received
* DATA_RECV_FRAME_COMPLETE).
*
* @return The function should return 0
*/
typedef int (*sh2lib_frame_data_recv_cb_t)(struct sh2lib_handle *handle, const void *data, size_t len, int flags);
/**
* @brief Function Prototype for callback to send data in PUT/POST
*
* This function gets called whenever nghttp2 wishes to send data, like for
* PUT/POST requests to the server. The function keeps getting called until this
* function sets the flag SH2LIB_DATA_FLAG_EOF to indicate end of data.
*
* @param[in] handle Pointer to the sh2lib handle.
* @param[out] data Pointer to a buffer that should contain the data to send.
* @param[in] len The maximum length of data that can be sent out by this function.
* @param[out] data_flags Pointer to the data flags. The SH2LIB_DATA_FLAG_EOF
* should be set in the data flags to indicate end of new data.
*
* @return The function should return the number of valid bytes stored in the
* data pointer
*/
typedef int (*sh2lib_putpost_data_cb_t)(struct sh2lib_handle *handle, void *data, size_t len, uint32_t *data_flags);
/**
* @brief Connect to a URI using HTTP/2
*
* This API opens an HTTP/2 connection with the provided URI. If successful, the
* hd pointer is populated with a valid handle for subsequent communication.
*
* Only 'https' URIs are supported.
*
* @param[out] hd Pointer to a variable of the type 'struct sh2lib_handle'.
* This struct is expected to be zeroed before passed as an argument!
* @param[in] uri Pointer to the URI that should be connected to.
*
* @return
* - ESP_OK if the connection was successful
* - ESP_FAIL if the connection fails
*/
int sh2lib_connect(struct sh2lib_handle *hd, const char *uri);
/**
* @brief Connect to a URI using HTTP/2 concurrently on a different task
*
* This API opens an HTTP/2 connection with the provided URI. If successful, the
* hd pointer is populated with a valid handle for subsequent communication.
*
* The connection task is created by this function, and deletes itself when done.
* The connection task updates hd->connect_result to indicate connection status.
* The caller should poll hd->connect_result
* hd->connect_result indicates: 0 in progress, 1 succeeded, -1 failed.
*
* Only 'https' URIs are supported.
*
* @param[out] hd Pointer to a variable of the type 'struct sh2lib_handle'.
* This struct is expected to be zeroed before passed as an argument!
* @param[in] uri Pointer to the URI that should be connected to.
* @param[in] priority Connection task priority
* @param[in] core_id Connection task core id
*
* @return
* - ESP_OK if the connection was successful
* - ESP_FAIL if the connection fails
*/
int sh2lib_connect_task(struct sh2lib_handle *hd, const char *uri, int priority, int core_id);
/**
* @brief Async connect to a URI using HTTP/2
*
* This API opens a non blocking HTTP/2 connection with the provided URI. If successful, the
* hd pointer is populated with a valid handle for subsequent communication.
* The user is expected to call this function repeatedly until it does not return 0.
*
* Only 'https' URIs are supported.
*
* @param[out] hd Pointer to a variable of the type 'struct sh2lib_handle'.
* This struct is expected to be zeroed before passed as an argument for the first time!
* When this function is called repeatedly, pass the same struct without change.
* @param[in] uri Pointer to the URI that should be connected to.
*
* @return
* - -1 If connection establishment fails.
* - 0 If connection establishment is in progress.
* - 1 If connection establishment is successful.
*/
int sh2lib_connect_async(struct sh2lib_handle *hd, const char *uri);
/**
* @brief Free a sh2lib handle
*
* This API frees-up an sh2lib handle, thus closing any open connections that
* may be associated with this handle, and freeing up any resources.
*
* @param[in] hd Pointer to a variable of the type 'struct sh2lib_handle'.
*
*/
void sh2lib_free(struct sh2lib_handle *hd);
/**
* @brief Setup an HTTP GET request stream
*
* This API sets up an HTTP GET request to be sent out to the server. A new
* stream is created for handling the request. Once the request is setup, the
* API sh2lib_execute() must be called to actually perform the socket I/O with
* the server.
*
* @param[in] hd Pointer to a variable of the type 'struct sh2lib_handle'.
* @param[in] path Pointer to the string that contains the resource to
* perform the HTTP GET operation on (for example, /users).
* @param[in] recv_cb The callback function that should be called for
* processing the request's response
*
* @return
* - ESP_OK if request setup is successful
* - ESP_FAIL if the request setup fails
*/
int sh2lib_do_get(struct sh2lib_handle *hd, const char *path, sh2lib_frame_data_recv_cb_t recv_cb);
/**
* @brief Setup an HTTP POST request stream
*
* This API sets up an HTTP POST request to be sent out to the server. A new
* stream is created for handling the request. Once the request is setup, the
* API sh2lib_execute() must be called to actually perform the socket I/O with
* the server.
*
* @param[in] hd Pointer to a variable of the type 'struct sh2lib_handle'.
* @param[in] path Pointer to the string that contains the resource to
* perform the HTTP POST operation on (for example, /users).
* @param[in] send_cb The callback function that should be called for
* sending data as part of this request.
* @param[in] recv_cb The callback function that should be called for
* processing the request's response
*
* @return
* - ESP_OK if request setup is successful
* - ESP_FAIL if the request setup fails
*/
int sh2lib_do_post(struct sh2lib_handle *hd, const char *path,
sh2lib_putpost_data_cb_t send_cb,
sh2lib_frame_data_recv_cb_t recv_cb);
/**
* @brief Setup an HTTP PUT request stream
*
* This API sets up an HTTP PUT request to be sent out to the server. A new
* stream is created for handling the request. Once the request is setup, the
* API sh2lib_execute() must be called to actually perform the socket I/O with
* the server.
*
* @param[in] hd Pointer to a variable of the type 'struct sh2lib_handle'.
* @param[in] path Pointer to the string that contains the resource to
* perform the HTTP PUT operation on (for example, /users).
* @param[in] send_cb The callback function that should be called for
* sending data as part of this request.
* @param[in] recv_cb The callback function that should be called for
* processing the request's response
*
* @return
* - ESP_OK if request setup is successful
* - ESP_FAIL if the request setup fails
*/
int sh2lib_do_put(struct sh2lib_handle *hd, const char *path,
sh2lib_putpost_data_cb_t send_cb,
sh2lib_frame_data_recv_cb_t recv_cb);
/**
* @brief Execute send/receive on an HTTP/2 connection
*
* While the API sh2lib_do_get(), sh2lib_do_post() setup the requests to be
* initiated with the server, this API performs the actual data send/receive
* operations on the HTTP/2 connection. The callback functions are accordingly
* called during the processing of these requests.
*
* @param[in] hd Pointer to a variable of the type 'struct sh2lib_handle'
*
* @return
* - ESP_OK if the connection was successful
* - ESP_FAIL if the connection fails
*/
int sh2lib_execute(struct sh2lib_handle *hd);
#define SH2LIB_MAKE_NV(NAME, VALUE) \
{ \
NAME, VALUE, SH2LIB_NV_FLAG_NONE \
}
/**
* @brief Setup an HTTP GET request stream with custom name-value pairs
*
* For a simpler version of the API, please refer to sh2lib_do_get().
*
* This API sets up an HTTP GET request to be sent out to the server. A new
* stream is created for handling the request. Once the request is setup, the
* API sh2lib_execute() must be called to actually perform the socket I/O with
* the server.
*
* Please note that the following name value pairs MUST be a part of the request
* - name:value
* - ":method":"GET"
* - ":scheme":"https"
* - ":path":<the-path-for-the-GET-operation> (for example, /users)
*
* @param[in] hd Pointer to a variable of the type 'struct sh2lib_handle'.
* @param[in] nva An array of name-value pairs that should be part of the request.
* @param[in] nvlen The number of elements in the array pointed to by 'nva'.
* @param[in] recv_cb The callback function that should be called for
* processing the request's response
*
* @return
* - ESP_OK if request setup is successful
* - ESP_FAIL if the request setup fails
*/
int sh2lib_do_get_with_nv(struct sh2lib_handle *hd, const struct sh2lib_nv nva[], size_t nvlen, sh2lib_frame_data_recv_cb_t recv_cb);
/**
* @brief Setup an HTTP PUT/POST request stream with custom name-value pairs
*
* For a simpler version of the API, please refer to sh2lib_do_put() or
* sh2lib_do_post().
*
* This API sets up an HTTP PUT/POST request to be sent out to the server. A new
* stream is created for handling the request. Once the request is setup, the
* API sh2lib_execute() must be called to actually perform the socket I/O with
* the server.
*
* Please note that the following name value pairs MUST be a part of the request
* - name:value
* - ":method":"PUT" (or POST)
* - ":scheme":"https"
* - ":path":<the-path-for-the-PUT-operation> (for example, /users)
*
* @param[in] hd Pointer to a variable of the type 'struct sh2lib_handle'.
* @param[in] nva An array of name-value pairs that should be part of the request.
* @param[in] nvlen The number of elements in the array pointed to by 'nva'.
* @param[in] send_cb The callback function that should be called for
* sending data as part of this request.
* @param[in] recv_cb The callback function that should be called for
* processing the request's response
*
* @return
* - ESP_OK if request setup is successful
* - ESP_FAIL if the request setup fails
*/
int sh2lib_do_putpost_with_nv(struct sh2lib_handle *hd, const struct sh2lib_nv nva[], size_t nvlen,
sh2lib_putpost_data_cb_t send_cb,
sh2lib_frame_data_recv_cb_t recv_cb);
/**
* @function
*
* Puts back previously deferred DATA frame in the stream |stream_id|
* to the outbound queue.
*
* This function returns 0 if it succeeds, or one of the following
* negative error codes:
*
* :enum:`SH2LIB_ERR_INVALID_ARGUMENT`
* The stream does not exist; or no deferred data exist.
* :enum:`SH2LIB_ERR_NOMEM`
* Out of memory.
*/
int sh2lib_session_resume_data(struct sh2lib_handle *hd, int32_t stream_id);
#endif // defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 4
#endif /* ! __ESP_EXAMPLE_SH2_LIB_H_ */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/sh2lib.h | C | apache-2.0 | 22,514 |
from machine import Pin
import espidf as esp
import lvgl as lv
# TODO: Viper/native emmitters don't behave well when module is frozen.
class xpt2046:
# Command is 8 bit, but we add another bit as a space before xpt2046 stats sending the response, See Figure 12 on the datasheet
CMD_X_READ = const(0b100100000)
CMD_Y_READ = const(0b110100000)
CMD_Z1_READ = const(0b101100000)
CMD_Z2_READ = const(0b110000000)
MAX_RAW_COORD = const((1<<12) - 1)
def __init__(self, miso=-1, mosi=-1, clk=-1, cs=25,
spihost=esp.HSPI_HOST, half_duplex=True, mhz=5, max_cmds=16,
cal_x0 = 3783, cal_y0 = 3948, cal_x1 = 242, cal_y1 = 423,
transpose = True, samples = 3):
# Initializations
if not lv.is_initialized():
lv.init()
disp = lv.disp_t.__cast__(None)
self.screen_width = disp.get_hor_res()
self.screen_height = disp.get_ver_res()
self.miso = miso
self.mosi = mosi
self.clk = clk
self.cs = cs
self.spihost = spihost
self.half_duplex = half_duplex
self.mhz = mhz
self.max_cmds = max_cmds
self.cal_x0 = cal_x0
self.cal_y0 = cal_y0
self.cal_x1 = cal_x1
self.cal_y1 = cal_y1
self.transpose = transpose
self.samples = samples
self.touch_count = 0
self.touch_cycles = 0
self.spi_init()
indev_drv = lv.indev_drv_t()
indev_drv.init()
indev_drv.type = lv.INDEV_TYPE.POINTER
indev_drv.read_cb = self.read
indev_drv.register()
def calibrate(self, x0, y0, x1, y1):
self.cal_x0 = x0
self.cal_y0 = y0
self.cal_x1 = x1
self.cal_y1 = y1
def spi_init(self):
buscfg = esp.spi_bus_config_t({
"miso_io_num": self.miso,
"mosi_io_num": self.mosi,
"sclk_io_num": self.clk,
"quadwp_io_num": -1,
"quadhd_io_num": -1,
"max_transfer_sz": 4,
})
devcfg_flags = 0 # esp.SPI_DEVICE.NO_DUMMY
if self.half_duplex:
devcfg_flags |= esp.SPI_DEVICE.HALFDUPLEX
devcfg = esp.spi_device_interface_config_t({
"command_bits": 9, # Actually 8, but need another cycle before xpt starts transmitting response, see Figure 12 on the datasheet.
"clock_speed_hz": self.mhz*1000*1000,
"mode": 0, # SPI mode 0
"spics_io_num": self.cs, # CS pin
"queue_size": self.max_cmds,
"flags": devcfg_flags,
"duty_cycle_pos": 128,
})
esp.gpio_pad_select_gpio(self.cs)
# Initialize the SPI bus, if needed
if buscfg.miso_io_num >= 0 and \
buscfg.mosi_io_num >= 0 and \
buscfg.sclk_io_num >= 0:
esp.gpio_pad_select_gpio(self.miso)
esp.gpio_pad_select_gpio(self.mosi)
esp.gpio_pad_select_gpio(self.clk)
esp.gpio_set_direction(self.miso, esp.GPIO_MODE.INPUT)
esp.gpio_set_pull_mode(self.miso, esp.GPIO.PULLUP_ONLY)
esp.gpio_set_direction(self.mosi, esp.GPIO_MODE.OUTPUT)
esp.gpio_set_direction(self.clk, esp.GPIO_MODE.OUTPUT)
ret = esp.spi_bus_initialize(self.spihost, buscfg, 1)
if ret != 0: raise RuntimeError("Failed initializing SPI bus")
# Attach the xpt2046 to the SPI bus
ptr_to_spi = esp.C_Pointer()
ret = esp.spi_bus_add_device(self.spihost, devcfg, ptr_to_spi)
if ret != 0: raise RuntimeError("Failed adding SPI device")
self.spi = ptr_to_spi.ptr_val
# Prepare transactions. Each response is 16bit long
self.trans = [esp.spi_transaction_t({
'rx_buffer': bytearray(2),
'length': 0 if self.half_duplex else 16,
'rxlength': 16
}) for i in range(0, self.max_cmds)]
trans_result_ptr = esp.C_Pointer()
#
# Deinitalize SPI device and bus
#
def deinit(self):
print('Deinitializing XPT2046...')
if self.spi:
# Pop all pending transaction results
ret = 0
while ret == 0:
ret = esp.spi_device_get_trans_result(self.spi, self.trans_result_ptr , 1)
# Remove device
esp.spi_bus_remove_device(self.spi)
# Free SPI bus
esp.spi_bus_free(self.spihost)
# @micropython.viper
def xpt_cmds(self, cmds):
cmd_count = int(len(cmds))
for i in range(0, cmd_count):
self.trans[i].cmd = cmds[i]
esp.spi_device_queue_trans(self.spi, self.trans[i], -1)
result = []
for i in range(0, cmd_count):
esp.spi_device_get_trans_result(self.spi, self.trans_result_ptr , -1)
buf = self.trans[i].rx_buffer.__dereference__(2)
value = (int(buf[0]) << 4) + (int(buf[1]) >> 4) # value is in the 12 higher bits, network order
if value == int(self.MAX_RAW_COORD):
value = 0
result.append(value)
return tuple(result)
# @micropython.viper
def get_med_coords(self, count : int):
mid = count//2
values = []
for i in range(0, count):
values.append(self.xpt_cmds([self.CMD_X_READ, self.CMD_Y_READ]))
# values = self.xpt_cmds([self.CMD_X_READ]*count + [self.CMD_Y_READ]*count)
# x_values = sorted(values[:count])
# y_values = sorted(values[count:])
x_values = sorted([x for x,y in values])
y_values = sorted([y for x,y in values])
if int(x_values[0]) == 0 or int(y_values[0]) == 0 : return None
return x_values[mid], y_values[mid]
# @micropython.viper
def get_coords(self):
med_coords = self.get_med_coords(int(self.samples))
if not med_coords: return None
if self.transpose:
raw_y, raw_x = med_coords
else:
raw_x, raw_y = med_coords
if int(raw_x) != 0 and int(raw_y) != 0:
x = ((int(raw_x) - int(self.cal_x0)) * int(self.screen_width)) // (int(self.cal_x1) - int(self.cal_x0))
y = ((int(raw_y) - int(self.cal_y0)) * int(self.screen_height)) // (int(self.cal_y1) - int(self.cal_y0))
# print('(%d, %d) ==> (%d, %d)' % (raw_x, raw_y, x, y))
return x,y
else: return None
# @micropython.native
def get_pressure(self, factor : int) -> int:
z1, z2, x = self.xpt_cmds([self.CMD_Z1_READ, self.CMD_Z2_READ, self.CMD_X_READ])
if int(z1) == 0: return -1
return ( (int(x)*factor) / 4096)*( int(z2)/int(z1) - 1)
start_time_ptr = esp.C_Pointer()
end_time_ptr = esp.C_Pointer()
cycles_in_ms = esp.esp_clk_cpu_freq() // 1000
# @micropython.native
def read(self, indev_drv, data) -> int:
esp.get_ccount(self.start_time_ptr)
coords = self.get_coords()
esp.get_ccount(self.end_time_ptr)
if self.end_time_ptr.int_val > self.start_time_ptr.int_val:
self.touch_cycles += self.end_time_ptr.int_val - self.start_time_ptr.int_val
self.touch_count += 1
if coords:
data.point.x ,data.point.y = coords
data.state = lv.INDEV_STATE.PRESSED
return False
data.state = lv.INDEV_STATE.RELEASED
return False
def stat(self):
return self.touch_cycles / (self.touch_count * self.cycles_in_ms)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/esp32/xpt2046.py | Python | apache-2.0 | 7,542 |
# Python driver for the AXP192 Power Management IC.
#
# https://gist.github.com/ropg/7216ba90a9d7697114d4ba8aea7bee3c
#
# Written in 2021 by Rop Gonggrijp.
#
# Some functionality inspired by C driver written by Mika Tuupola
# (https://github.com/tuupola/axp192) and a fork of that maintained by
# Brian Starkey (https://github.com/usedbytes/axp192)
#
# License: MIT
from machine import I2C, Pin
SDA = 21
SCL = 22
I2C_ADDRESS = 0x34
# Power control registers
POWER_STATUS = 0x00
CHARGE_STATUS = 0x01
OTG_VBUS_STATUS = 0x04
DATA_BUFFER0 = 0x06
DATA_BUFFER1 = 0x07
DATA_BUFFER2 = 0x08
DATA_BUFFER3 = 0x09
DATA_BUFFER4 = 0x0a
DATA_BUFFER5 = 0x0b
# Output control: 2 EXTEN, 0 DCDC2
EXTEN_DCDC2_CONTROL = 0x10
# Power output control: 6 EXTEN, 4 DCDC2, 3 LDO3, 2 LDO2, 1 DCDC3, 0 DCDC1
DCDC13_LDO23_CONTROL = 0x12
DCDC2_VOLTAGE = 0x23
DCDC2_SLOPE = 0x25
DCDC1_VOLTAGE = 0x26
DCDC3_VOLTAGE = 0x27
# Output voltage control: 7-4 LDO2, 3-0 LDO3
LDO23_VOLTAGE = 0x28
VBUS_IPSOUT_CHANNEL = 0x30
SHUTDOWN_VOLTAGE = 0x31
SHUTDOWN_BATTERY_CHGLED_CONTROL = 0x32
CHARGE_CONTROL_1 = 0x33
CHARGE_CONTROL_2 = 0x34
BATTERY_CHARGE_CONTROL = 0x35
PEK = 0x36
DCDC_FREQUENCY = 0x37
BATTERY_CHARGE_LOW_TEMP = 0x38
BATTERY_CHARGE_HIGH_TEMP = 0x39
APS_LOW_POWER1 = 0x3A
APS_LOW_POWER2 = 0x3B
BATTERY_DISCHARGE_LOW_TEMP = 0x3c
BATTERY_DISCHARGE_HIGH_TEMP = 0x3d
DCDC_MODE = 0x80
ADC_ENABLE_1 = 0x82
ADC_ENABLE_2 = 0x83
ADC_RATE_TS_PIN = 0x84
GPIO30_INPUT_RANGE = 0x85
GPIO0_ADC_IRQ_RISING = 0x86
GPIO0_ADC_IRQ_FALLING = 0x87
TIMER_CONTROL = 0x8a
VBUS_MONITOR = 0x8b
TEMP_SHUTDOWN_CONTROL = 0x8f
# GPIO control registers
GPIO0_CONTROL = 0x90
GPIO0_LDOIO0_VOLTAGE = 0x91
GPIO1_CONTROL = 0x92
GPIO2_CONTROL = 0x93
GPIO20_SIGNAL_STATUS = 0x94
GPIO40_FUNCTION_CONTROL = 0x95
GPIO40_SIGNAL_STATUS = 0x96
GPIO20_PULLDOWN_CONTROL = 0x97
PWM1_FREQUENCY = 0x98
PWM1_DUTY_CYCLE_1 = 0x99
PWM1_DUTY_CYCLE_2 = 0x9a
PWM2_FREQUENCY = 0x9b
PWM2_DUTY_CYCLE_1 = 0x9c
PWM2_DUTY_CYCLE_2 = 0x9d
N_RSTO_GPIO5_CONTROL = 0x9e
# Interrupt control registers
ENABLE_CONTROL_1 = 0x40
ENABLE_CONTROL_2 = 0x41
ENABLE_CONTROL_3 = 0x42
ENABLE_CONTROL_4 = 0x43
ENABLE_CONTROL_5 = 0x4a
IRQ_STATUS_1 = 0x44
IRQ_STATUS_2 = 0x45
IRQ_STATUS_3 = 0x46
IRQ_STATUS_4 = 0x47
IRQ_STATUS_5 = 0x4d
# ADC data registers
ACIN_VOLTAGE = 0x56
ACIN_CURRENT = 0x58
VBUS_VOLTAGE = 0x5a
VBUS_CURRENT = 0x5c
TEMP = 0x5e
TS_INPUT = 0x62
GPIO0_VOLTAGE = 0x64
GPIO1_VOLTAGE = 0x66
GPIO2_VOLTAGE = 0x68
GPIO3_VOLTAGE = 0x6a
BATTERY_POWER = 0x70
BATTERY_VOLTAGE = 0x78
CHARGE_CURRENT = 0x7a
DISCHARGE_CURRENT = 0x7c
APS_VOLTAGE = 0x7e
CHARGE_COULOMB = 0xb0
DISCHARGE_COULOMB = 0xb4
COULOMB_COUNTER_CONTROL = 0xb8
BIT_DCDC1_ENABLE = 0b00000001
BIT_DCDC2_ENABLE = 0b00010000
BIT_DCDC3_ENABLE = 0b00000010
BIT_LDO2_ENABLE = 0b00000100
BIT_LDO3_ENABLE = 0b00001000
BIT_EXTEN_ENABLE = 0b01000000
# These are not real registers, see read and write functions
LDO2_VOLTAGE = 0x0101
LDO3_VOLTAGE = 0x0102
class AXP192():
def __init__(self, i2c_dev, sda, scl, freq=400000, i2c_addr=I2C_ADDRESS):
self.i2c = I2C(i2c_dev, sda=Pin(sda), scl=Pin(scl), freq=freq)
self.i2c_addr = i2c_addr
def read_byte(self, reg_addr):
tmp = self.i2c.readfrom_mem(self.i2c_addr, reg_addr, 1)[0]
# print("read_byte: 0x{:x} from 0x{:x}".format(tmp, reg_addr))
return tmp
def write_byte(self, reg_addr, data):
# print("write_byte: 0x{:x} to 0x{:x}".format(data, reg_addr))
self.i2c.writeto_mem(self.i2c_addr, reg_addr, bytes([data]))
def twiddle(self, reg_addr, affects, value):
self.write_byte(reg_addr, (self.read_byte(reg_addr) & (affects ^ 0xff)) | (value & affects))
def write(self, reg_addr, data):
# print("write: {:x} with {}".format(reg_addr, data))
if reg_addr == DCDC1_VOLTAGE:
if data == 0:
self.twiddle(DCDC13_LDO23_CONTROL, BIT_DCDC1_ENABLE, 0)
return
if data < 0.7 or data > 3.5:
raise ValueError("Voltage out of range")
self.twiddle(reg_addr, 0b01111111, int((data - 0.7) / 0.025))
self.twiddle(DCDC13_LDO23_CONTROL, BIT_DCDC1_ENABLE, BIT_DCDC1_ENABLE)
return
elif reg_addr == DCDC2_VOLTAGE:
if data == 0:
self.twiddle(DCDC13_LDO23_CONTROL, BIT_DCDC2_ENABLE, 0)
return
if data < 0.7 or data > 2.275:
raise ValueError("Voltage out of range")
self.twiddle(reg_addr, 0b00111111, int((data - 0.7) / 0.025))
self.twiddle(DCDC13_LDO23_CONTROL, BIT_DCDC2_ENABLE, BIT_DCDC2_ENABLE)
return
if reg_addr == DCDC3_VOLTAGE:
if data == 0:
self.twiddle(DCDC13_LDO23_CONTROL, BIT_DCDC3_ENABLE, 0)
return
if data < 0.7 or data > 3.5:
raise ValueError("Voltage out of range")
self.twiddle(reg_addr, 0b01111111, int((data - 0.7) / 0.025))
self.twiddle(DCDC13_LDO23_CONTROL, BIT_DCDC3_ENABLE, BIT_DCDC3_ENABLE)
return
elif reg_addr == LDO2_VOLTAGE:
if data == 0:
self.twiddle(DCDC13_LDO23_CONTROL, BIT_LDO2_ENABLE, 0)
return
if data < 1.8 or data > 3.3:
raise ValueError("Voltage out of range")
val = int((data - 1.8) / 0.1)
self.twiddle(LDO23_VOLTAGE, 0xf0, val << 4)
self.twiddle(DCDC13_LDO23_CONTROL, BIT_LDO2_ENABLE, BIT_LDO2_ENABLE)
return
elif reg_addr == LDO3_VOLTAGE:
if data == 0:
self.twiddle(DCDC13_LDO23_CONTROL, BIT_LDO3_ENABLE, 0)
return
if data < 1.8 or data > 3.3:
raise ValueError("Voltage out of range")
val = int((data - 1.8) / 0.1)
self.twiddle(LDO23_VOLTAGE, 0x0f, val)
self.twiddle(DCDC13_LDO23_CONTROL, BIT_LDO3_ENABLE, BIT_LDO3_ENABLE)
return
if type(data) != "bytes":
self.write_byte(reg_addr, data)
else:
self.i2c.writeto_mem(self.i2c_addr, reg_addr, data)
def read(self, reg_addr, length=1):
if length != 1:
return self.i2c.readfrom_mem(self.i2c_addr, reg_addr, length)
sensitivity = 1.0
offset = 0.0
if reg_addr == ACIN_VOLTAGE or reg_addr == VBUS_VOLTAGE:
# 1.7mV per LSB
sensitivity = 1.7 / 1000
elif reg_addr == ACIN_CURRENT:
# 0.625mA per LSB
sensitivity = 0.625 / 1000
elif reg_addr == VBUS_CURRENT:
# 0.375mA per LSB
sensitivity = 0.375 / 1000
elif reg_addr == TEMP:
# 0.1C per LSB, 0x00 = -144.7C
sensitivity = 0.1
offset = -144.7
elif reg_addr == TS_INPUT:
# 0.8mV per LSB
sensitivity = 0.8 / 1000
elif reg_addr == BATTERY_POWER:
# 1.1mV * 0.5mA per LSB
return int.from_bytes(self.read(BATTERY_POWER, 3), "big") * (1.1 * 0.5 / 1000)
elif reg_addr == BATTERY_VOLTAGE:
# 1.1mV per LSB
sensitivity = 1.1 / 1000
elif reg_addr == CHARGE_CURRENT or reg_addr == DISCHARGE_CURRENT:
# 0.5mV per LSB
sensitivity = 0.5 / 1000
elif reg_addr == APS_VOLTAGE:
# 1.4mV per LSB
sensitivity = 1.4 / 1000
elif reg_addr == CHARGE_COULOMB or reg_addr == DISCHARGE_COULOMB:
return int.from_bytes(self.read(reg_addr, 4), "big")
elif reg_addr == DCDC1_VOLTAGE:
if self.read_byte(DCDC13_LDO23_CONTROL) & BIT_DCDC1_ENABLE == 0:
return 0
return (self.read_byte(reg_addr) & 0b01111111) * 0.25 + 0.7
elif reg_addr == DCDC2_VOLTAGE:
if self.read_byte(DCDC13_LDO23_CONTROL) & BIT_DCDC2_ENABLE == 0:
return 0
return (self.read_byte(reg_addr) & 0b00111111) * 0.25 + 0.7
elif reg_addr == DCDC3_VOLTAGE:
if self.read_byte(DCDC13_LDO23_CONTROL) & BIT_DCDC3_ENABLE == 0:
return 0
return (self.read_byte(reg_addr) & 0b01111111) * 0.25 + 0.7
elif reg_addr == LDO2_VOLTAGE:
if self.read_byte(DCDC13_LDO23_CONTROL) & BIT_LDO2_ENABLE == 0:
return 0
return ((self.read_byte(LDO23_VOLTAGE) & 0xf0) >> 4) * 0.1 + 1.8
elif reg_addr == LDO3_VOLTAGE:
if self.read_byte(DCDC13_LDO23_CONTROL) & BIT_LDO3_ENABLE == 0:
return 0
return ((self.read_byte(LDO23_VOLTAGE) & 0x0f)) * 0.1 + 1.8
# any values not listed will just read a single byte
else:
return self.read_byte(reg_addr)
# handle cases above that did not end in return
tmp = self.i2c.readfrom_mem(self.i2c_addr, reg_addr, 2)
return (((tmp[0] << 4) + tmp[1]) * sensitivity) + offset
def coulomb_counter(self):
# CmAh = 65536 * 0.5mA *(coin - cout) / 3600 / ADC sample rate
return 32768 * (self.read(CHARGE_COULOMB) - self.read(DISCHARGE_COULOMB)) / 3600 / 25
def coulomb_counter_enable(self):
self.write(COULOMB_COUNTER_CONTROL, 0b10000000)
def coulomb_counter_disable(self):
self.write(COULOMB_COUNTER_CONTROL, 0b00000000)
def coulomb_counter_suspend(self):
self.write(COULOMB_COUNTER_CONTROL, 0b11000000)
def coulomb_counter_clear(self):
self.write(COULOMB_COUNTER_CONTROL, 0b10100000)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/generic/axp192.py | Python | apache-2.0 | 10,553 |
# Pure Python LVGL indev driver for the FocalTech FT6X36 capacitive touch IC
#
# from ft6x36 import ft6x36
#
# touch = ft6x36(sda=<pin>, scl=<pin>)
#
# If you set the size of the touchpad, you have the option to invert each
# axis, and you'll get some extra robustness against occasional read errors
# as values outside the touchpad are quietly rejected. If you select to swap
# the axes, width and height as well as the inversions refer to the situation
# before the swap.
#
# The nice thing about this driver is that it allows access to the second
# finger, as the FT6X36 is multi-touch. (Two fingers max, with caveats on
# some boards.)
#
# The number of presses is in touch.presses, touch.points[0] and points[1]
# hold the positions. LVGL is not (yet) multi-touch, so all it sees is the
# position in points[0].
import lvgl as lv
from machine import I2C, Pin
class ft6x36:
def __init__(self, i2c_dev=0, sda=21, scl=22, freq=400000, addr=0x38, width=-1, height=-1,
inv_x=False, inv_y=False, swap_xy=False):
if not lv.is_initialized():
lv.init()
self.width, self.height = width, height
self.inv_x, self.inv_y, self.swap_xy = inv_x, inv_y, swap_xy
self.i2c = I2C(i2c_dev, sda=Pin(sda), scl=Pin(scl), freq=freq)
self.addr = addr
try:
print("FT6X36 touch IC ready (fw id 0x{0:X} rel {1:d}, lib {2:X})".format( \
int.from_bytes(self.i2c.readfrom_mem(self.addr, 0xA6, 1), "big"), \
int.from_bytes(self.i2c.readfrom_mem(self.addr, 0xAF, 1), "big"), \
int.from_bytes(self.i2c.readfrom_mem(self.addr, 0xA1, 2), "big") \
))
except:
print("FT6X36 touch IC not responding")
return
self.point = lv.point_t( {'x': 0, 'y': 0} )
self.points = [lv.point_t( {'x': 0, 'y': 0} ), lv.point_t( {'x': 0, 'y': 0} )]
self.state = lv.INDEV_STATE.RELEASED
self.indev_drv = lv.indev_drv_t()
self.indev_drv.init()
self.indev_drv.type = lv.INDEV_TYPE.POINTER
self.indev_drv.read_cb = self.callback
self.indev_drv.register()
def callback(self, driver, data):
def get_point(offset):
x = (sensorbytes[offset ] << 8 | sensorbytes[offset + 1]) & 0x0fff
y = (sensorbytes[offset + 2] << 8 | sensorbytes[offset + 3]) & 0x0fff
if (self.width != -1 and x >= self.width) or (self.height != -1 and y >= self.height):
raise ValueError
x = self.width - x - 1 if self.inv_x else x
y = self.height - y - 1 if self.inv_y else y
(x, y) = (y, x) if self.swap_xy else (x, y)
return { 'x': x, 'y': y }
data.point = self.points[0]
data.state = self.state
sensorbytes = self.i2c.readfrom_mem(self.addr, 2, 11)
self.presses = sensorbytes[0]
if self.presses > 2:
return False
try:
if self.presses:
self.points[0] = get_point(1)
if self.presses == 2:
self.points[1] = get_point(7)
except ValueError:
return False
if sensorbytes[3] >> 4:
self.points[0], self.points[1] = self.points[1], self.points[0]
data.point = self.points[0]
data.state = self.state = lv.INDEV_STATE.PRESSED if self.presses else lv.INDEV_STATE.RELEASED
return False
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/generic/ft6x36.py | Python | apache-2.0 | 3,453 |
# This is the minimal pure-python lvgl pointer-type driver. It does not read
# any hardware and instead just presses at location (50,100)
#
# In a real driver, always return the last position in data.point, even if
# the data.state goes to 'released' (lv.INDEV_STATE.RELEASED), so maybe keep
# that in self.point.
#
# The 'return False' just means there is no further data to read, which is
# what you want for a pointer-type driver.
#
# To use your driver (after you've made it read some real hardware):
#
# from my_indev import my_indev
# touch = my_indev()
import lvgl as lv
class my_indev:
def __init__(self):
self.indev_drv = lv.indev_drv_t()
self.indev_drv.init()
self.indev_drv.type = lv.INDEV_TYPE.POINTER
self.indev_drv.read_cb = self.callback
self.indev_drv.register()
def callback(self, driverptr, dataptr):
# This is where you need to get the actual position from
# the hardware. This just simulates pressed at 50, 100.
data.point = lv.point_t( {'x': 50, 'y': 100} )
data.state = lv.INDEV_STATE.PRESSED
return False
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/generic/indev_example.py | Python | apache-2.0 | 1,133 |
#ifndef __LVMP_DRV_COMMON_H
#define __LVMP_DRV_COMMON_H
#include "py/obj.h"
#include "py/runtime.h"
#include "py/binary.h"
//////////////////////////////////////////////////////////////////////////////
// A read-only buffer that contains a C pointer
// Used to communicate function pointers to lvgl Micropython bindings
//
typedef struct mp_ptr_t
{
mp_obj_base_t base;
void *ptr;
} mp_ptr_t;
STATIC mp_int_t mp_ptr_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags)
{
mp_ptr_t *self = MP_OBJ_TO_PTR(self_in);
if (flags & MP_BUFFER_WRITE) {
// read-only ptr
return 1;
}
bufinfo->buf = &self->ptr;
bufinfo->len = sizeof(self->ptr);
bufinfo->typecode = BYTEARRAY_TYPECODE;
return 0;
}
#define PTR_OBJ(ptr_global) ptr_global ## _obj
#define DEFINE_PTR_OBJ_TYPE(ptr_obj_type, ptr_type_qstr)\
STATIC const mp_obj_type_t ptr_obj_type = {\
{ &mp_type_type },\
.name = ptr_type_qstr,\
.buffer_p = { .get_buffer = mp_ptr_get_buffer }\
}
#define DEFINE_PTR_OBJ(ptr_global)\
DEFINE_PTR_OBJ_TYPE(ptr_global ## _type, MP_QSTR_ ## ptr_global);\
STATIC const mp_ptr_t PTR_OBJ(ptr_global) = {\
{ &ptr_global ## _type },\
&ptr_global\
}
#define NEW_PTR_OBJ(name, value)\
({\
DEFINE_PTR_OBJ_TYPE(ptr_obj_type, MP_QSTR_ ## name);\
mp_ptr_t *self = m_new_obj(mp_ptr_t);\
self->base.type = &ptr_obj_type;\
self->ptr = value;\
MP_OBJ_FROM_PTR(self);\
})
#endif // __LVMP_DRV_COMMON_H
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/include/common.h | C | apache-2.0 | 1,486 |
#
# Important:
# This is a JS specific version of imagetools.py
# without native emitter since JS port doesnt support
# "native" and "viper" decorators.
# Other ports should use the imagetools.py from /lib
#
#
# Library of functions for image manipulation.
# Can be used with lodepng to decode PNG images:
#
# from imagetools import get_png_info, open_png
# decoder = lv.img.decoder_create()
# decoder.info_cb = get_png_info
# decoder.open_cb = open_png
#
import lvgl as lv
import lodepng as png
import ustruct
COLOR_SIZE = lv.color_t.__SIZE__
COLOR_IS_SWAPPED = hasattr(lv.color_t().ch,'green_h')
class lodepng_error(RuntimeError):
def __init__(self, err):
if type(err) is int:
super().__init__(png.error_text(err))
else:
super().__init__(err)
# Parse PNG file header
# Taken from https://github.com/shibukawa/imagesize_py/blob/ffef30c1a4715c5acf90e8945ceb77f4a2ed2d45/imagesize.py#L63-L85
def get_png_info(decoder, src, header):
# Only handle variable image types
if lv.img.src_get_type(src) != lv.img.SRC.VARIABLE:
return lv.RES.INV
data = lv.img_dsc_t.__cast__(src).data
if data == None:
return lv.RES.INV
png_header = bytes(data.__dereference__(24))
if png_header.startswith(b'\211PNG\r\n\032\n'):
if png_header[12:16] == b'IHDR':
start = 16
# Maybe this is for an older PNG version.
else:
start = 8
try:
width, height = ustruct.unpack(">LL", png_header[start:start+8])
except ustruct.error:
return lv.RES.INV
else:
return lv.RES.INV
header.always_zero = 0
header.w = width
header.h = height
header.cf = lv.img.CF.TRUE_COLOR_ALPHA
return lv.RES.OK
def convert_rgba8888_to_bgra8888(img_view):
for i in range(0, len(img_view), lv.color_t.__SIZE__):
ch = lv.color_t.__cast__(img_view[i:i]).ch
ch.red, ch.blue = ch.blue, ch.red
# Read and parse PNG file
def open_png(decoder, dsc):
img_dsc = lv.img_dsc_t.__cast__(dsc.src)
png_data = img_dsc.data
png_size = img_dsc.data_size
png_decoded = png.C_Pointer()
png_width = png.C_Pointer()
png_height = png.C_Pointer()
error = png.decode32(png_decoded, png_width, png_height, png_data, png_size);
if error:
raise lodepng_error(error)
img_size = png_width.int_val * png_height.int_val * 4
img_data = png_decoded.ptr_val
img_view = img_data.__dereference__(img_size)
if COLOR_SIZE == 4:
convert_rgba8888_to_bgra8888(img_view)
else:
raise lodepng_error("Error: Color mode not supported yet!")
dsc.img_data = img_data
return lv.RES.OK
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/js/imagetools.py | Python | apache-2.0 | 2,721 |
# Stub Timer implementation for the JS port.
#
# This does absolutely nothing beyond provide a class, so it will
# not be suitable for any application which needs a timer.
#
# MIT license; Copyright (c) 2021 embeddedt
class Timer:
PERIODIC = 0
ONE_SHOT = 1
def __init__(self, id):
pass
def init(self, mode=PERIODIC, period=-1, callback=None):
pass
def deinit(self):
pass
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/js/lv_timer.py | Python | apache-2.0 | 421 |
# LVGL indev driver for evdev mouse device
# (for the unix micropython port)
import ustruct
import select
import lvgl as lv
# Default crosshair cursor
class crosshair_cursor:
def __init__(self, scr=None):
self.scr = scr if scr else lv.scr_act()
self.hor_res = self.scr.get_width()
self.ver_res = self.scr.get_height()
self.cursor_style = lv.style_t()
self.cursor_style.set_line_width(1)
self.cursor_style.set_line_dash_gap(5)
self.cursor_style.set_line_dash_width(1)
self.cursor_hor = lv.line(self.scr)
self.cursor_hor.add_style(self.cursor_style, lv.PART.MAIN)
self.cursor_ver = lv.line(self.scr)
self.cursor_ver.add_style(self.cursor_style, lv.PART.MAIN)
def __call__(self, data):
# print("%d : %d:%d" % (data.state, data.point.x, data.point.y))
self.cursor_hor.set_points([{'x':0,'y':data.point.y},{'x':self.hor_res,'y':data.point.y}],2)
self.cursor_ver.set_points([{'y':0,'x':data.point.x},{'y':self.ver_res,'x':data.point.x}],2)
def delete(self):
self.cursor_hor.delete()
self.cursor_ver.delete()
# evdev driver for mouse
class mouse_indev:
def __init__(self, scr=None, cursor=None, device='/dev/input/mice'):
# Open evdev and initialize members
self.evdev = open(device, 'rb')
self.poll = select.poll()
self.poll.register(self.evdev.fileno())
self.scr = scr if scr else lv.scr_act()
self.cursor = cursor if cursor else crosshair_cursor(self.scr)
self.hor_res = self.scr.get_width()
self.ver_res = self.scr.get_height()
# Register LVGL indev driver
self.indev_drv = lv.indev_drv_t()
self.indev_drv.init()
self.indev_drv.type = lv.INDEV_TYPE.POINTER
self.indev_drv.read_cb = self.mouse_read
self.indev = self.indev_drv.register()
def mouse_read(self, indev_drv, data) -> int:
# Check if there is input to be read from evdev
if not self.poll.poll()[0][1] & select.POLLIN:
return 0
# Read and parse evdev mouse data
mouse_data = ustruct.unpack('bbb',self.evdev.read(3))
# Data is relative, update coordinates
data.point.x += mouse_data[1]
data.point.y -= mouse_data[2]
# Handle coordinate overflow cases
data.point.x = min(data.point.x, self.hor_res - 1)
data.point.y = min(data.point.y, self.ver_res - 1)
data.point.x = max(data.point.x, 0)
data.point.y = max(data.point.y, 0)
# Update "pressed" status
data.state = lv.INDEV_STATE.PRESSED if ((mouse_data[0] & 1) == 1) else lv.INDEV_STATE.RELEASED
# Draw cursor, if needed
if self.cursor: self.cursor(data)
return 0
def delete(self):
self.evdev.close()
if self.cursor and hasattr(self.cursor, 'delete'):
self.cursor.delete()
self.indev.enable(False)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/linux/evdev.py | Python | apache-2.0 | 2,974 |
# Timer that matches machine.Timer (https://docs.micropython.org/en/latest/library/machine.Timer.html)
# for the unix port.
#
# MIT license; Copyright (c) 2021 Amir Gonnen
#
# Based on timer.py from micropython-lib (https://github.com/micropython/micropython-lib/blob/master/unix-ffi/machine/machine/timer.py)
import ffi
import uctypes
import array
import os
import sys
# FFI libraries
libc = ffi.open("libc.so.6")
librt = ffi.open("librt.so")
# C constants
CLOCK_REALTIME = 0
CLOCK_MONOTONIC = 1
SIGEV_SIGNAL = 0
# C structs
sigaction_t = {
"sa_handler" : (0 | uctypes.UINT64),
"sa_mask" : (8 | uctypes.ARRAY, 16 | uctypes.UINT64),
"sa_flags" : (136 | uctypes.INT32),
"sa_restorer": (144 |uctypes.PTR, uctypes.UINT8),
}
sigval_t = {
"sival_int": 0 | uctypes.INT32,
"sival_ptr": (0 | uctypes.PTR, uctypes.UINT8),
}
sigevent_t = {
"sigev_value": (0, sigval_t),
"sigev_signo": 8 | uctypes.INT32,
"sigev_notify": 12 | uctypes.INT32,
}
timespec_t = {
"tv_sec": 0 | uctypes.INT32,
"tv_nsec": 8 | uctypes.INT64,
}
itimerspec_t = {
"it_interval": (0, timespec_t),
"it_value": (16, timespec_t),
}
# C functions
__libc_current_sigrtmin = libc.func("i", "__libc_current_sigrtmin", "")
SIGRTMIN = __libc_current_sigrtmin()
timer_create_ = librt.func("i", "timer_create", "ipp")
timer_delete_ = librt.func("i", "timer_delete", "i")
timer_settime_ = librt.func("i", "timer_settime", "PiPp")
sigaction_ = libc.func("i", "sigaction", "iPp")
# Create a new C struct
def new(sdesc):
buf = bytearray(uctypes.sizeof(sdesc))
s = uctypes.struct(uctypes.addressof(buf), sdesc, uctypes.NATIVE)
return s
# Posix Signal handling
def sigaction(signum, handler, flags=0):
sa = new(sigaction_t)
sa_old = new(sigaction_t)
cb = ffi.callback("v", handler, "i", lock=True)
sa.sa_handler = cb.cfun()
sa.sa_flags = flags
r = sigaction_(signum, sa, sa_old)
if r != 0:
raise RuntimeError("sigaction_ error: %d (errno = %d)" % (r, os.errno()))
return cb # sa_old.sa_handler
# Posix Timer handling
def timer_create(sig_id):
sev = new(sigevent_t)
# print(sev)
sev.sigev_notify = SIGEV_SIGNAL
sev.sigev_signo = SIGRTMIN + sig_id
timerid = array.array("P", [0])
r = timer_create_(CLOCK_MONOTONIC, sev, timerid)
if r != 0:
raise RuntimeError("timer_create_ error: %d (errno = %d)" % (r, os.errno()))
# print("timerid", hex(timerid[0]))
return timerid[0]
def timer_delete(tid):
r = timer_delete_(tid)
if r != 0:
raise RuntimeError("timer_delete_ error: %d (errno = %d)" % (r, os.errno()))
def timer_settime(tid, period_ms, periodic):
period_ns = (period_ms * 1000000) % 1000000000
period_sec = (period_ms * 1000000) // 1000000000
new_val = new(itimerspec_t)
new_val.it_value.tv_sec = period_sec
new_val.it_value.tv_nsec = period_ns
if periodic:
new_val.it_interval.tv_sec = period_sec
new_val.it_interval.tv_nsec = period_ns
# print("new_val:", bytes(new_val))
old_val = new(itimerspec_t)
# print(new_val, old_val)
r = timer_settime_(tid, 0, new_val, old_val)
if r != 0:
raise RuntimeError("timer_settime_ error: %d (errno = %d)" % (r, os.errno()))
# print("old_val:", bytes(old_val))
# Timer class
class Timer:
PERIODIC = 0
ONE_SHOT = 1
def __init__(self, id):
self.id = id
self._valid = False
def init(self, mode=PERIODIC, period=-1, callback=None):
self.tid = timer_create(self.id)
self.mode = mode
self.period = period
self.cb = callback
timer_settime(self.tid, self.period, self.mode == Timer.PERIODIC)
self.handler_ref = self.handler
# print("Sig %d: %s" % (SIGRTMIN + self.id, self.org_sig))
self.action = sigaction(SIGRTMIN + self.id, self.handler_ref)
self._valid = True
def deinit(self):
if self._valid:
timer_settime(self.tid, 0, self.mode == Timer.PERIODIC)
# timer_delete(self.tid)
self._valid = False
def handler(self, signum=-1):
# print('Signal handler called with signal', signum)
try:
self.cb(self)
except:
self.deinit()
raise
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/linux/lv_timer.py | Python | apache-2.0 | 4,296 |
/*********************
* INCLUDES
*********************/
#include "../../lib/lv_bindings/lvgl/lvgl.h"
#include "../include/common.h"
#include <stdlib.h>
#include <unistd.h>
#include <stddef.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <signal.h>
/*********************
* DEFINES
*********************/
#ifndef FBDEV_PATH
#define FBDEV_PATH "/dev/fb0"
#endif
#define LV_TICK_RATE 20
/**********************
* FORWARD DECLARATIONS
**********************/
bool fbdev_init(void);
void fbdev_deinit(void);
void fbdev_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p);
/**********************
* STATIC VARIABLES
**********************/
static struct fb_var_screeninfo vinfo;
static struct fb_fix_screeninfo finfo;
static char * fbp = 0;
static long int screensize = 0;
static int fbfd = -1;
static pthread_t tid;
static pthread_t mp_thread;
static bool auto_refresh = true;
/**********************
* MODULE DEFINITION
**********************/
STATIC inline bool fbdev_active()
{
return fbfd >= 0;
}
STATIC mp_obj_t mp_lv_task_handler(mp_obj_t arg)
{
lv_task_handler();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_lv_task_handler_obj, mp_lv_task_handler);
STATIC void* tick_thread(void * data)
{
(void)data;
while(fbdev_active()) {
usleep(LV_TICK_RATE * 1000); /*Sleep for 1 millisecond*/
lv_tick_inc(LV_TICK_RATE); /*Tell LittelvGL that LV_TICK_RATE milliseconds were elapsed*/
mp_sched_schedule((mp_obj_t)&mp_lv_task_handler_obj, mp_const_none);
pthread_kill(mp_thread, SIGUSR1); // interrupt REPL blocking input. See handle_sigusr1
}
return NULL;
}
static void handle_sigusr1(int signo)
{
// Let the signal pass. blocking function would return E_INTR.
// This would cause a call to "mp_handle_pending" even when
// waiting for user input.
// See https://github.com/micropython/micropython/pull/5723
}
STATIC mp_obj_t mp_init_fb(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args)
{
enum { ARG_auto_refresh };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_auto_refresh, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} },
};
// parse args
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
bool init_succeeded = fbdev_init();
if (!init_succeeded) return mp_const_false;
int err = 0;
auto_refresh = args[ARG_auto_refresh].u_bool;
if (auto_refresh) {
err = pthread_create(&tid, NULL, &tick_thread, NULL);
mp_thread = pthread_self();
struct sigaction sa;
sa.sa_handler = handle_sigusr1;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
}
return err == 0? mp_const_true: mp_const_false;
}
STATIC mp_obj_t mp_deinit_fb()
{
fbdev_deinit();
if (auto_refresh) {
pthread_join(tid, NULL);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mp_init_fb_obj, 0, mp_init_fb);
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_deinit_fb_obj, mp_deinit_fb);
DEFINE_PTR_OBJ(fbdev_flush);
STATIC const mp_rom_map_elem_t fb_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_fb) },
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&mp_init_fb_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mp_deinit_fb_obj) },
{ MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&PTR_OBJ(fbdev_flush))},
};
STATIC MP_DEFINE_CONST_DICT (
mp_module_fb_globals,
fb_globals_table
);
const mp_obj_module_t mp_module_fb = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_fb_globals
};
/**********************
* IMPLEMENTATION
**********************/
bool fbdev_init(void)
{
// Open the file for reading and writing
fbfd = open(FBDEV_PATH, O_RDWR);
if(fbfd == -1) {
perror("Error: cannot open framebuffer device");
return false;
}
printf("The framebuffer device was opened successfully.\n");
// Get fixed screen information
if(ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo) == -1) {
perror("Error reading fixed information");
return false;
}
// Get variable screen information
if(ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo) == -1) {
perror("Error reading variable information");
return false;
}
printf("%dx%d, %dbpp\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel);
// Figure out the size of the screen in bytes
screensize = finfo.line_length * vinfo.yres;
// Map the device to memory
fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0);
if((intptr_t)fbp == -1) {
perror("Error: failed to map framebuffer device to memory");
return false;
}
printf("The framebuffer device was mapped to memory successfully.\n");
return true;
}
void fbdev_deinit(void)
{
close(fbfd);
fbfd = -1;
}
/**
* Flush a buffer to the marked area
* @param area->x1 left coordinate
* @param area->y1 top coordinate
* @param area->x2 right coordinate
* @param area->y2 bottom coordinate
* @param color_p an array of colors
*/
void fbdev_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
if(fbp == NULL ||
area->x2 < 0 ||
area->y2 < 0 ||
area->x1 > (int32_t)vinfo.xres - 1 ||
area->y1 > (int32_t)vinfo.yres - 1) {
lv_disp_flush_ready(disp_drv);
return;
}
/*Truncate the area to the screen*/
int32_t act_x1 = area->x1 < 0 ? 0 : area->x1;
int32_t act_y1 = area->y1 < 0 ? 0 : area->y1;
int32_t act_x2 = area->x2 > (int32_t)vinfo.xres - 1 ? (int32_t)vinfo.xres - 1 : area->x2;
int32_t act_y2 = area->y2 > (int32_t)vinfo.yres - 1 ? (int32_t)vinfo.yres - 1 : area->y2;
long int location = 0;
long int byte_location = 0;
unsigned char bit_location = 0;
/*32 or 24 bit per pixel*/
if(vinfo.bits_per_pixel == 32 || vinfo.bits_per_pixel == 24) {
uint32_t * fbp32 = (uint32_t *)fbp;
int32_t x;
int32_t y;
for(y = act_y1; y <= act_y2; y++) {
for(x = act_x1; x <= act_x2; x++) {
location = (x + vinfo.xoffset) + (y + vinfo.yoffset) * finfo.line_length / 4;
fbp32[location] = color_p->full;
color_p++;
}
color_p += area->x2 - act_x2;
}
}
/*16 bit per pixel*/
else if(vinfo.bits_per_pixel == 16) {
uint16_t * fbp16 = (uint16_t *)fbp;
int32_t x;
int32_t y;
for(y = act_y1; y <= act_y2; y++) {
for(x = act_x1; x <= act_x2; x++) {
location = (x + vinfo.xoffset) + (y + vinfo.yoffset) * finfo.line_length / 2;
fbp16[location] = color_p->full;
color_p++;
}
color_p += area->x2 - act_x2;
}
}
/*8 bit per pixel*/
else if(vinfo.bits_per_pixel == 8) {
uint8_t * fbp8 = (uint8_t *)fbp;
int32_t x;
int32_t y;
for(y = act_y1; y <= act_y2; y++) {
for(x = act_x1; x <= act_x2; x++) {
location = (x + vinfo.xoffset) + (y + vinfo.yoffset) * finfo.line_length;
fbp8[location] = color_p->full;
color_p++;
}
color_p += area->x2 - act_x2;
}
}
/*1 bit per pixel*/
else if(vinfo.bits_per_pixel == 1) {
uint8_t * fbp8 = (uint8_t *)fbp;
int32_t x;
int32_t y;
for(y = act_y1; y <= act_y2; y++) {
for(x = act_x1; x <= act_x2; x++) {
location = (x + vinfo.xoffset) + (y + vinfo.yoffset) * vinfo.xres;
byte_location = location / 8; /* find the byte we need to change */
bit_location = location % 8; /* inside the byte found, find the bit we need to change */
fbp8[byte_location] &= ~(((uint8_t)(1)) << bit_location);
fbp8[byte_location] |= ((uint8_t)(color_p->full)) << bit_location;
color_p++;
}
color_p += area->x2 - act_x2;
}
} else {
/*Not supported bit per pixel*/
}
//May be some direct update command is required
//ret = ioctl(state->fd, FBIO_UPDATE, (unsigned long)((uintptr_t)rect));
lv_disp_flush_ready(disp_drv);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/linux/modfb.c | C | apache-2.0 | 8,654 |
# This makefile only makes the unit test, benchmark and pngdetail and showpng
# utilities. It does not make the PNG codec itself as shared or static library.
# That is because:
# LodePNG itself has only 1 source file (lodepng.cpp, can be renamed to
# lodepng.c) and is intended to be included as source file in other projects and
# their build system directly.
CC ?= gcc
CXX ?= g++
override CFLAGS := -W -Wall -Wextra -ansi -pedantic -O3 -Wno-unused-function $(CFLAGS)
override CXXFLAGS := -W -Wall -Wextra -ansi -pedantic -O3 $(CXXFLAGS)
all: unittest benchmark pngdetail showpng
%.o: %.cpp
@mkdir -p `dirname $@`
$(CXX) -I ./ $(CXXFLAGS) -c $< -o $@
unittest: lodepng.o lodepng_util.o lodepng_unittest.o
$(CXX) $^ $(CXXFLAGS) -o $@
benchmark: lodepng.o lodepng_benchmark.o
$(CXX) $^ $(CXXFLAGS) -lSDL -o $@
pngdetail: lodepng.o lodepng_util.o pngdetail.o
$(CXX) $^ $(CXXFLAGS) -o $@
showpng: lodepng.o examples/example_sdl.o
$(CXX) -I ./ $^ $(CXXFLAGS) -lSDL -o $@
clean:
rm -f unittest benchmark pngdetail showpng lodepng_unittest.o lodepng_benchmark.o lodepng.o lodepng_util.o pngdetail.o examples/example_sdl.o
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/png/lodepng/Makefile | Makefile | apache-2.0 | 1,133 |
/*
LodePNG Examples
Copyright (c) 2005-2012 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
//g++ lodepng.cpp example_4bit_palette.cpp -ansi -pedantic -Wall -Wextra -O3
/*
LodePNG 4-bit palette example.
This example encodes a 511x511 PNG with a 4-bit palette.
Both image and palette contain sine waves, resulting in a sort of plasma.
The 511 (rather than power of two 512) size is of course chosen on purpose to
confirm that scanlines not filling up an entire byte size are working.
NOTE: a PNG image with a translucent palette is perfectly valid. However there
exist some programs that cannot correctly read those, including, surprisingly,
Gimp 2.8 image editor (until you set mode to RGB).
*/
#include <cmath>
#include <iostream>
#include "lodepng.h"
int main(int argc, char *argv[]) {
//check if user gave a filename
if(argc < 2) {
std::cout << "please provide a filename to save to" << std::endl;
return 0;
}
//create encoder and set settings and info (optional)
lodepng::State state;
//generate palette
for(int i = 0; i < 16; i++) {
unsigned char r = 127 * (1 + std::sin(5 * i * 6.28318531 / 16));
unsigned char g = 127 * (1 + std::sin(2 * i * 6.28318531 / 16));
unsigned char b = 127 * (1 + std::sin(3 * i * 6.28318531 / 16));
unsigned char a = 63 * (1 + std::sin(8 * i * 6.28318531 / 16)) + 128; /*alpha channel of the palette (tRNS chunk)*/
//palette must be added both to input and output color mode, because in this
//sample both the raw image and the expected PNG image use that palette.
lodepng_palette_add(&state.info_png.color, r, g, b, a);
lodepng_palette_add(&state.info_raw, r, g, b, a);
}
//both the raw image and the encoded image must get colorType 3 (palette)
state.info_png.color.colortype = LCT_PALETTE; //if you comment this line, and create the above palette in info_raw instead, then you get the same image in a RGBA PNG.
state.info_png.color.bitdepth = 4;
state.info_raw.colortype = LCT_PALETTE;
state.info_raw.bitdepth = 4;
state.encoder.auto_convert = 0; //we specify ourselves exactly what output PNG color mode we want
//generate some image
const unsigned w = 511;
const unsigned h = 511;
std::vector<unsigned char> image;
image.resize((w * h * 4 + 7) / 8, 0);
for(unsigned y = 0; y < h; y++)
for(unsigned x = 0; x < w; x++) {
size_t byte_index = (y * w + x) / 2;
bool byte_half = (y * w + x) % 2 == 1;
int color = (int)(4 * ((1 + std::sin(2.0 * 6.28318531 * x / (double)w))
+ (1 + std::sin(2.0 * 6.28318531 * y / (double)h))) );
image[byte_index] |= (unsigned char)(color << (byte_half ? 0 : 4));
}
//encode and save
std::vector<unsigned char> buffer;
unsigned error = lodepng::encode(buffer, image.empty() ? 0 : &image[0], w, h, state);
if(error) {
std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
return 0;
}
lodepng::save_file(buffer, argv[1]);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/png/lodepng/examples/example_4bit_palette.cpp | C++ | apache-2.0 | 3,796 |
/*
LodePNG Examples
Copyright (c) 2005-2010 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
Load a BMP image and convert it to a PNG image. This example also shows how
to use other data with the same memory structure as BMP, such as the image
format native to win32, GDI (HBITMAP, BITMAPINFO, ...) often encountered if
you're programming for Windows in Visual Studio.
This example only supports uncompressed 24-bit RGB or 32-bit RGBA bitmaps.
For other types of BMP's, use a full fledged BMP decoder, or convert the
bitmap to 24-bit or 32-bit format.
NOTE: it overwrites the output file without warning if it exists!
*/
//g++ lodepng.cpp example_bmp2png.cpp -ansi -pedantic -Wall -Wextra -O3
#include "lodepng.h"
#include <iostream>
//returns 0 if all went ok, non-0 if error
//output image is always given in RGBA (with alpha channel), even if it's a BMP without alpha channel
unsigned decodeBMP(std::vector<unsigned char>& image, unsigned& w, unsigned& h, const std::vector<unsigned char>& bmp) {
static const unsigned MINHEADER = 54; //minimum BMP header size
if(bmp.size() < MINHEADER) return -1;
if(bmp[0] != 'B' || bmp[1] != 'M') return 1; //It's not a BMP file if it doesn't start with marker 'BM'
unsigned pixeloffset = bmp[10] + 256 * bmp[11]; //where the pixel data starts
//read width and height from BMP header
w = bmp[18] + bmp[19] * 256;
h = bmp[22] + bmp[23] * 256;
//read number of channels from BMP header
if(bmp[28] != 24 && bmp[28] != 32) return 2; //only 24-bit and 32-bit BMPs are supported.
unsigned numChannels = bmp[28] / 8;
//The amount of scanline bytes is width of image times channels, with extra bytes added if needed
//to make it a multiple of 4 bytes.
unsigned scanlineBytes = w * numChannels;
if(scanlineBytes % 4 != 0) scanlineBytes = (scanlineBytes / 4) * 4 + 4;
unsigned dataSize = scanlineBytes * h;
if(bmp.size() < dataSize + pixeloffset) return 3; //BMP file too small to contain all pixels
image.resize(w * h * 4);
/*
There are 3 differences between BMP and the raw image buffer for LodePNG:
-it's upside down
-it's in BGR instead of RGB format (or BRGA instead of RGBA)
-each scanline has padding bytes to make it a multiple of 4 if needed
The 2D for loop below does all these 3 conversions at once.
*/
for(unsigned y = 0; y < h; y++)
for(unsigned x = 0; x < w; x++) {
//pixel start byte position in the BMP
unsigned bmpos = pixeloffset + (h - y - 1) * scanlineBytes + numChannels * x;
//pixel start byte position in the new raw image
unsigned newpos = 4 * y * w + 4 * x;
if(numChannels == 3) {
image[newpos + 0] = bmp[bmpos + 2]; //R
image[newpos + 1] = bmp[bmpos + 1]; //G
image[newpos + 2] = bmp[bmpos + 0]; //B
image[newpos + 3] = 255; //A
} else {
image[newpos + 0] = bmp[bmpos + 2]; //R
image[newpos + 1] = bmp[bmpos + 1]; //G
image[newpos + 2] = bmp[bmpos + 0]; //B
image[newpos + 3] = bmp[bmpos + 3]; //A
}
}
return 0;
}
int main(int argc, char *argv[]) {
if(argc < 3) {
std::cout << "Please provice input PNG and output BMP file names" << std::endl;
return 0;
}
std::vector<unsigned char> bmp;
lodepng::load_file(bmp, argv[1]);
std::vector<unsigned char> image;
unsigned w, h;
unsigned error = decodeBMP(image, w, h, bmp);
if(error) {
std::cout << "BMP decoding error " << error << std::endl;
return 0;
}
std::vector<unsigned char> png;
error = lodepng::encode(png, image, w, h);
if(error) {
std::cout << "PNG encoding error " << error << ": " << lodepng_error_text(error) << std::endl;
return 0;
}
lodepng::save_file(png, argv[2]);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/png/lodepng/examples/example_bmp2png.cpp | C++ | apache-2.0 | 4,514 |
/*
LodePNG Examples
Copyright (c) 2005-2012 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "lodepng.h"
#include <stdio.h>
#include <stdlib.h>
/*
3 ways to decode a PNG from a file to RGBA pixel data (and 2 in-memory ways).
*/
/*
Example 1
Decode from disk to raw pixels with a single function call
*/
void decodeOneStep(const char* filename) {
unsigned error;
unsigned char* image = 0;
unsigned width, height;
error = lodepng_decode32_file(&image, &width, &height, filename);
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
/*use image here*/
free(image);
}
/*
Example 2
Load PNG file from disk to memory first, then decode to raw pixels in memory.
*/
void decodeTwoSteps(const char* filename) {
unsigned error;
unsigned char* image = 0;
unsigned width, height;
unsigned char* png = 0;
size_t pngsize;
error = lodepng_load_file(&png, &pngsize, filename);
if(!error) error = lodepng_decode32(&image, &width, &height, png, pngsize);
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
free(png);
/*use image here*/
free(image);
}
/*
Example 3
Load PNG file from disk using a State, normally needed for more advanced usage.
*/
void decodeWithState(const char* filename) {
unsigned error;
unsigned char* image = 0;
unsigned width, height;
unsigned char* png = 0;
size_t pngsize;
LodePNGState state;
lodepng_state_init(&state);
/*optionally customize the state*/
error = lodepng_load_file(&png, &pngsize, filename);
if(!error) error = lodepng_decode(&image, &width, &height, &state, png, pngsize);
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
free(png);
/*use image here*/
/*state contains extra information about the PNG such as text chunks, ...*/
lodepng_state_cleanup(&state);
free(image);
}
int main(int argc, char *argv[]) {
const char* filename = argc > 1 ? argv[1] : "test.png";
decodeOneStep(filename);
return 0;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/png/lodepng/examples/example_decode.c | C | apache-2.0 | 2,802 |
/*
LodePNG Examples
Copyright (c) 2005-2012 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "lodepng.h"
#include <iostream>
/*
3 ways to decode a PNG from a file to RGBA pixel data (and 2 in-memory ways).
*/
//g++ lodepng.cpp example_decode.cpp -ansi -pedantic -Wall -Wextra -O3
//Example 1
//Decode from disk to raw pixels with a single function call
void decodeOneStep(const char* filename) {
std::vector<unsigned char> image; //the raw pixels
unsigned width, height;
//decode
unsigned error = lodepng::decode(image, width, height, filename);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}
//Example 2
//Load PNG file from disk to memory first, then decode to raw pixels in memory.
void decodeTwoSteps(const char* filename) {
std::vector<unsigned char> png;
std::vector<unsigned char> image; //the raw pixels
unsigned width, height;
//load and decode
unsigned error = lodepng::load_file(png, filename);
if(!error) error = lodepng::decode(image, width, height, png);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}
//Example 3
//Load PNG file from disk using a State, normally needed for more advanced usage.
void decodeWithState(const char* filename) {
std::vector<unsigned char> png;
std::vector<unsigned char> image; //the raw pixels
unsigned width, height;
lodepng::State state; //optionally customize this one
unsigned error = lodepng::load_file(png, filename); //load the image file with given filename
if(!error) error = lodepng::decode(image, width, height, state, png);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
//State state contains extra information about the PNG such as text chunks, ...
}
int main(int argc, char *argv[]) {
const char* filename = argc > 1 ? argv[1] : "test.png";
decodeOneStep(filename);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/png/lodepng/examples/example_decode.cpp | C++ | apache-2.0 | 3,235 |
/*
LodePNG Examples
Copyright (c) 2005-2012 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "lodepng.h"
#include <stdio.h>
#include <stdlib.h>
/*
3 ways to encode a PNG from RGBA pixel data to a file (and 2 in-memory ways).
NOTE: this samples overwrite the file or test.png without warning!
*/
/*
Example 1
Encode from raw pixels to disk with a single function call
The image argument has width * height RGBA pixels or width * height * 4 bytes
*/
void encodeOneStep(const char* filename, const unsigned char* image, unsigned width, unsigned height) {
/*Encode the image*/
unsigned error = lodepng_encode32_file(filename, image, width, height);
/*if there's an error, display it*/
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
}
/*
Example 2
Encode from raw pixels to an in-memory PNG file first, then write it to disk
The image argument has width * height RGBA pixels or width * height * 4 bytes
*/
void encodeTwoSteps(const char* filename, const unsigned char* image, unsigned width, unsigned height) {
unsigned char* png;
size_t pngsize;
unsigned error = lodepng_encode32(&png, &pngsize, image, width, height);
if(!error) lodepng_save_file(png, pngsize, filename);
/*if there's an error, display it*/
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
free(png);
}
/*
Example 3
Save a PNG file to disk using a State, normally needed for more advanced usage.
The image argument has width * height RGBA pixels or width * height * 4 bytes
*/
void encodeWithState(const char* filename, const unsigned char* image, unsigned width, unsigned height) {
unsigned error;
unsigned char* png;
size_t pngsize;
LodePNGState state;
lodepng_state_init(&state);
/*optionally customize the state*/
error = lodepng_encode(&png, &pngsize, image, width, height, &state);
if(!error) lodepng_save_file(png, pngsize, filename);
/*if there's an error, display it*/
if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
lodepng_state_cleanup(&state);
free(png);
}
int main(int argc, char *argv[]) {
const char* filename = argc > 1 ? argv[1] : "test.png";
/*generate some image*/
unsigned width = 512, height = 512;
unsigned char* image = malloc(width * height * 4);
unsigned x, y;
for(y = 0; y < height; y++)
for(x = 0; x < width; x++) {
image[4 * width * y + 4 * x + 0] = 255 * !(x & y);
image[4 * width * y + 4 * x + 1] = x ^ y;
image[4 * width * y + 4 * x + 2] = x | y;
image[4 * width * y + 4 * x + 3] = 255;
}
/*run an example*/
encodeOneStep(filename, image, width, height);
free(image);
return 0;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/png/lodepng/examples/example_encode.c | C | apache-2.0 | 3,467 |
/*
LodePNG Examples
Copyright (c) 2005-2012 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "lodepng.h"
#include <iostream>
/*
3 ways to encode a PNG from RGBA pixel data to a file (and 2 in-memory ways).
NOTE: this samples overwrite the file or test.png without warning!
*/
//g++ lodepng.cpp examples/example_encode.cpp -I./ -ansi -pedantic -Wall -Wextra -O3
//Example 1
//Encode from raw pixels to disk with a single function call
//The image argument has width * height RGBA pixels or width * height * 4 bytes
void encodeOneStep(const char* filename, std::vector<unsigned char>& image, unsigned width, unsigned height) {
//Encode the image
unsigned error = lodepng::encode(filename, image, width, height);
//if there's an error, display it
if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
}
//Example 2
//Encode from raw pixels to an in-memory PNG file first, then write it to disk
//The image argument has width * height RGBA pixels or width * height * 4 bytes
void encodeTwoSteps(const char* filename, std::vector<unsigned char>& image, unsigned width, unsigned height) {
std::vector<unsigned char> png;
unsigned error = lodepng::encode(png, image, width, height);
if(!error) lodepng::save_file(png, filename);
//if there's an error, display it
if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
}
//Example 3
//Save a PNG file to disk using a State, normally needed for more advanced usage.
//The image argument has width * height RGBA pixels or width * height * 4 bytes
void encodeWithState(const char* filename, std::vector<unsigned char>& image, unsigned width, unsigned height) {
std::vector<unsigned char> png;
lodepng::State state; //optionally customize this one
unsigned error = lodepng::encode(png, image, width, height, state);
if(!error) lodepng::save_file(png, filename);
//if there's an error, display it
if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
}
//saves image to filename given as argument. Warning, this overwrites the file without warning!
int main(int argc, char *argv[]) {
//NOTE: this sample will overwrite the file or test.png without warning!
const char* filename = argc > 1 ? argv[1] : "test.png";
//generate some image
unsigned width = 512, height = 512;
std::vector<unsigned char> image;
image.resize(width * height * 4);
for(unsigned y = 0; y < height; y++)
for(unsigned x = 0; x < width; x++) {
image[4 * width * y + 4 * x + 0] = 255 * !(x & y);
image[4 * width * y + 4 * x + 1] = x ^ y;
image[4 * width * y + 4 * x + 2] = x | y;
image[4 * width * y + 4 * x + 3] = 255;
}
encodeOneStep(filename, image, width, height);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/png/lodepng/examples/example_encode.cpp | C++ | apache-2.0 | 3,612 |
/*
LodePNG Examples
Copyright (c) 2005-2015 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
//g++ -I ./ lodepng.cpp examples/example_encode_type.cpp -ansi -pedantic -Wall -Wextra -O3
/*
This example shows how to enforce a certain color type of the PNG image when
encoding a PNG (because by default, LodePNG automatically chooses an optimal
color type, no matter what your raw data's color type is)
*/
#include <cmath>
#include <iostream>
#include "lodepng.h"
int main(int argc, char *argv[]) {
//check if user gave a filename
if(argc < 2) {
std::cout << "please provide a filename to save to" << std::endl;
return 0;
}
//generate some image
const unsigned w = 256;
const unsigned h = 256;
std::vector<unsigned char> image(w * h * 4);
for(unsigned y = 0; y < h; y++)
for(unsigned x = 0; x < w; x++) {
int index = y * w * 4 + x * 4;
image[index + 0] = 0;
image[index + 1] = 0;
image[index + 2] = 0;
image[index + 3] = 255;
}
// we're going to encode with a state rather than a convenient function, because enforcing a color type requires setting options
lodepng::State state;
// input color type
state.info_raw.colortype = LCT_RGBA;
state.info_raw.bitdepth = 8;
// output color type
state.info_png.color.colortype = LCT_RGBA;
state.info_png.color.bitdepth = 8;
state.encoder.auto_convert = 0; // without this, it would ignore the output color type specified above and choose an optimal one instead
//encode and save
std::vector<unsigned char> buffer;
unsigned error = lodepng::encode(buffer, &image[0], w, h, state);
if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
else lodepng::save_file(buffer, argv[1]);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/driver/png/lodepng/examples/example_encode_type.cpp | C++ | apache-2.0 | 2,557 |