repo_name
string
path
string
copies
string
size
string
content
string
license
string
tobid89/pilight
libs/pilight/events/operators/lt.c
8
1403
/* Copyright (C) 2013 - 2014 CurlyMo This file is part of pilight. pilight is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. pilight is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with pilight. If not, see <http://www.gnu.org/licenses/> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "../operator.h" #include "../../core/dso.h" #include "lt.h" static void operatorLtCallback(double a, double b, char **ret) { if(a < b) { strcpy(*ret, "1"); } else { strcpy(*ret, "0"); } } #if !defined(MODULE) && !defined(_WIN32) __attribute__((weak)) #endif void operatorLtInit(void) { event_operator_register(&operator_lt, "<"); operator_lt->callback_number = &operatorLtCallback; } #if defined(MODULE) && !defined(_WIN32) void compatibility(struct module_t *module) { module->name = "<"; module->version = "1.0"; module->reqversion = "5.0"; module->reqcommit = "87"; } void init(void) { operatorLtInit(); } #endif
gpl-3.0
DanielYS/JdeRobot
src/stable/components/visualHFSM/point.cpp
9
3190
/* * Copyright (C) 1997-2013 JDERobot Developers Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * Authors : Borja Menéndez Moreno <b.menendez.moreno@gmail.com> * José María Cañas Plaza <jmplaza@gsyc.es> * */ #include "point.h" /************************************************************* * CONSTRUCTOR *************************************************************/ Point::Point ( float x, float y ) { this->x = x; this->y = y; } /************************************************************* * DESTRUCTOR *************************************************************/ Point::~Point () {} /************************************************************* * SETTERS *************************************************************/ void Point::setX ( float x ) { this->x = x; } void Point::setY ( float y ) { this->y = y; } /************************************************************* * GETTERS *************************************************************/ float Point::getX () { return this->x; } float Point::getY () { return this->y; } /************************************************************* * ANOTHER FUNCTIONS *************************************************************/ void Point::move ( float dx, float dy ) { this->x += dx; this->y += dy; } bool Point::equals ( Point p ) { return ((this->x == p.getX()) && (this->y == p.getY())); } Point Point::calculateGoodArrowPosition ( Point p ) { float distance_op = this->y - p.getY(); float distance_ad = this->x - p.getX(); float alpha = atan(distance_op / distance_ad); float possible1_final_x = this->x + RADIUS_NORMAL * cos(alpha); float possible1_final_y = this->y + RADIUS_NORMAL * sin(alpha); float distance1 = sqrt(pow(possible1_final_x - p.getX(), 2.0) + pow(possible1_final_y - p.getY(), 2.0)); float possible2_final_x = this->x - RADIUS_NORMAL * cos(alpha); float possible2_final_y = this->y - RADIUS_NORMAL * sin(alpha); float distance2 = sqrt(pow(possible2_final_x - p.getX(), 2.0) + pow(possible2_final_y - p.getY(), 2.0)); if (distance1 < distance2) { Point point(possible1_final_x, possible1_final_y); return point; } else { Point point(possible2_final_x, possible2_final_y); return point; } } Point Point::midpoint ( Point p ) { Point point((this->x + p.getX()) / 2.0, (this->y + p.getY()) / 2.0); return point; } Point Point::copy () { Point p(this->x, this->y); return p; } Point* Point::copyAsPointer () { return (new Point(this->x, this->y)); }
gpl-3.0
Po-Jen/NTU_BeeBot
beebot_planners_master/anytimeRRTs/include/smp/costtogo/interface/_coder_costotogo_info.c
10
81477
/* * _coder_costotogo_info.c * * Code generation for function 'costotogo' * * C source code generated on: Wed Jun 11 17:43:10 2014 * */ /* Include files */ #include "_coder_costotogo_info.h" /* Function Declarations */ static void info_helper(const mxArray **info); static const mxArray *emlrt_marshallOut(const char * u); static const mxArray *b_emlrt_marshallOut(uint32_T u); static void b_info_helper(const mxArray **info); /* Function Definitions */ const mxArray *emlrtMexFcnResolvedFunctionsInfo(void) { const mxArray *nameCaptureInfo; nameCaptureInfo = NULL; emlrtAssign(&nameCaptureInfo, mxCreateStructMatrix(76, 1, 0, NULL)); info_helper(&nameCaptureInfo); b_info_helper(&nameCaptureInfo); emlrtNameCapturePostProcessR2013b(&nameCaptureInfo); return nameCaptureInfo; } static void info_helper(const mxArray **info) { const mxArray *rhs0 = NULL; const mxArray *lhs0 = NULL; const mxArray *rhs1 = NULL; const mxArray *lhs1 = NULL; const mxArray *rhs2 = NULL; const mxArray *lhs2 = NULL; const mxArray *rhs3 = NULL; const mxArray *lhs3 = NULL; const mxArray *rhs4 = NULL; const mxArray *lhs4 = NULL; const mxArray *rhs5 = NULL; const mxArray *lhs5 = NULL; const mxArray *rhs6 = NULL; const mxArray *lhs6 = NULL; const mxArray *rhs7 = NULL; const mxArray *lhs7 = NULL; const mxArray *rhs8 = NULL; const mxArray *lhs8 = NULL; const mxArray *rhs9 = NULL; const mxArray *lhs9 = NULL; const mxArray *rhs10 = NULL; const mxArray *lhs10 = NULL; const mxArray *rhs11 = NULL; const mxArray *lhs11 = NULL; const mxArray *rhs12 = NULL; const mxArray *lhs12 = NULL; const mxArray *rhs13 = NULL; const mxArray *lhs13 = NULL; const mxArray *rhs14 = NULL; const mxArray *lhs14 = NULL; const mxArray *rhs15 = NULL; const mxArray *lhs15 = NULL; const mxArray *rhs16 = NULL; const mxArray *lhs16 = NULL; const mxArray *rhs17 = NULL; const mxArray *lhs17 = NULL; const mxArray *rhs18 = NULL; const mxArray *lhs18 = NULL; const mxArray *rhs19 = NULL; const mxArray *lhs19 = NULL; const mxArray *rhs20 = NULL; const mxArray *lhs20 = NULL; const mxArray *rhs21 = NULL; const mxArray *lhs21 = NULL; const mxArray *rhs22 = NULL; const mxArray *lhs22 = NULL; const mxArray *rhs23 = NULL; const mxArray *lhs23 = NULL; const mxArray *rhs24 = NULL; const mxArray *lhs24 = NULL; const mxArray *rhs25 = NULL; const mxArray *lhs25 = NULL; const mxArray *rhs26 = NULL; const mxArray *lhs26 = NULL; const mxArray *rhs27 = NULL; const mxArray *lhs27 = NULL; const mxArray *rhs28 = NULL; const mxArray *lhs28 = NULL; const mxArray *rhs29 = NULL; const mxArray *lhs29 = NULL; const mxArray *rhs30 = NULL; const mxArray *lhs30 = NULL; const mxArray *rhs31 = NULL; const mxArray *lhs31 = NULL; const mxArray *rhs32 = NULL; const mxArray *lhs32 = NULL; const mxArray *rhs33 = NULL; const mxArray *lhs33 = NULL; const mxArray *rhs34 = NULL; const mxArray *lhs34 = NULL; const mxArray *rhs35 = NULL; const mxArray *lhs35 = NULL; const mxArray *rhs36 = NULL; const mxArray *lhs36 = NULL; const mxArray *rhs37 = NULL; const mxArray *lhs37 = NULL; const mxArray *rhs38 = NULL; const mxArray *lhs38 = NULL; const mxArray *rhs39 = NULL; const mxArray *lhs39 = NULL; const mxArray *rhs40 = NULL; const mxArray *lhs40 = NULL; const mxArray *rhs41 = NULL; const mxArray *lhs41 = NULL; const mxArray *rhs42 = NULL; const mxArray *lhs42 = NULL; const mxArray *rhs43 = NULL; const mxArray *lhs43 = NULL; const mxArray *rhs44 = NULL; const mxArray *lhs44 = NULL; const mxArray *rhs45 = NULL; const mxArray *lhs45 = NULL; const mxArray *rhs46 = NULL; const mxArray *lhs46 = NULL; const mxArray *rhs47 = NULL; const mxArray *lhs47 = NULL; const mxArray *rhs48 = NULL; const mxArray *lhs48 = NULL; const mxArray *rhs49 = NULL; const mxArray *lhs49 = NULL; const mxArray *rhs50 = NULL; const mxArray *lhs50 = NULL; const mxArray *rhs51 = NULL; const mxArray *lhs51 = NULL; const mxArray *rhs52 = NULL; const mxArray *lhs52 = NULL; const mxArray *rhs53 = NULL; const mxArray *lhs53 = NULL; const mxArray *rhs54 = NULL; const mxArray *lhs54 = NULL; const mxArray *rhs55 = NULL; const mxArray *lhs55 = NULL; const mxArray *rhs56 = NULL; const mxArray *lhs56 = NULL; const mxArray *rhs57 = NULL; const mxArray *lhs57 = NULL; const mxArray *rhs58 = NULL; const mxArray *lhs58 = NULL; const mxArray *rhs59 = NULL; const mxArray *lhs59 = NULL; const mxArray *rhs60 = NULL; const mxArray *lhs60 = NULL; const mxArray *rhs61 = NULL; const mxArray *lhs61 = NULL; const mxArray *rhs62 = NULL; const mxArray *lhs62 = NULL; const mxArray *rhs63 = NULL; const mxArray *lhs63 = NULL; emlrtAddField(*info, emlrt_marshallOut( "[E]/home/luigi/code/palmieri/learningcost2go/costotogo.m!mapminmax_apply"), "context", 0); emlrtAddField(*info, emlrt_marshallOut("bsxfun"), "name", 0); emlrtAddField(*info, emlrt_marshallOut("function_handle"), "dominantType", 0); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "resolved", 0); emlrtAddField(*info, b_emlrt_marshallOut(1356541494U), "fileTimeLo", 0); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 0); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 0); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 0); emlrtAssign(&rhs0, emlrtCreateCellArray(0)); emlrtAssign(&lhs0, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs0), "rhs", 0); emlrtAddField(*info, emlrtAliasP(lhs0), "lhs", 0); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "context", 1); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 1); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 1); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 1); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 1); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 1); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 1); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 1); emlrtAssign(&rhs1, emlrtCreateCellArray(0)); emlrtAssign(&lhs1, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs1), "rhs", 1); emlrtAddField(*info, emlrtAliasP(lhs1), "lhs", 1); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m!bsxfun_compatible"), "context", 2); emlrtAddField(*info, emlrt_marshallOut("min"), "name", 2); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 2); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/datafun/min.m"), "resolved", 2); emlrtAddField(*info, b_emlrt_marshallOut(1311255318U), "fileTimeLo", 2); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 2); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 2); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 2); emlrtAssign(&rhs2, emlrtCreateCellArray(0)); emlrtAssign(&lhs2, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs2), "rhs", 2); emlrtAddField(*info, emlrtAliasP(lhs2), "lhs", 2); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/datafun/min.m"), "context", 3); emlrtAddField(*info, emlrt_marshallOut("eml_min_or_max"), "name", 3); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 3); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_min_or_max.m"), "resolved", 3); emlrtAddField(*info, b_emlrt_marshallOut(1363713870U), "fileTimeLo", 3); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 3); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 3); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 3); emlrtAssign(&rhs3, emlrtCreateCellArray(0)); emlrtAssign(&lhs3, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs3), "rhs", 3); emlrtAddField(*info, emlrtAliasP(lhs3), "lhs", 3); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_min_or_max.m!eml_bin_extremum"), "context", 4); emlrtAddField(*info, emlrt_marshallOut("eml_scalar_eg"), "name", 4); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 4); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalar_eg.m"), "resolved", 4); emlrtAddField(*info, b_emlrt_marshallOut(1286818796U), "fileTimeLo", 4); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 4); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 4); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 4); emlrtAssign(&rhs4, emlrtCreateCellArray(0)); emlrtAssign(&lhs4, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs4), "rhs", 4); emlrtAddField(*info, emlrtAliasP(lhs4), "lhs", 4); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_min_or_max.m!eml_bin_extremum"), "context", 5); emlrtAddField(*info, emlrt_marshallOut("eml_scalexp_alloc"), "name", 5); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 5); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalexp_alloc.m"), "resolved", 5); emlrtAddField(*info, b_emlrt_marshallOut(1358186140U), "fileTimeLo", 5); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 5); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 5); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 5); emlrtAssign(&rhs5, emlrtCreateCellArray(0)); emlrtAssign(&lhs5, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs5), "rhs", 5); emlrtAddField(*info, emlrtAliasP(lhs5), "lhs", 5); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_min_or_max.m!eml_bin_extremum"), "context", 6); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 6); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 6); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 6); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 6); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 6); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 6); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 6); emlrtAssign(&rhs6, emlrtCreateCellArray(0)); emlrtAssign(&lhs6, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs6), "rhs", 6); emlrtAddField(*info, emlrtAliasP(lhs6), "lhs", 6); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_min_or_max.m!eml_scalar_bin_extremum"), "context", 7); emlrtAddField(*info, emlrt_marshallOut("eml_scalar_eg"), "name", 7); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 7); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalar_eg.m"), "resolved", 7); emlrtAddField(*info, b_emlrt_marshallOut(1286818796U), "fileTimeLo", 7); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 7); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 7); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 7); emlrtAssign(&rhs7, emlrtCreateCellArray(0)); emlrtAssign(&lhs7, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs7), "rhs", 7); emlrtAddField(*info, emlrtAliasP(lhs7), "lhs", 7); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_min_or_max.m!eml_scalar_bin_extremum"), "context", 8); emlrtAddField(*info, emlrt_marshallOut("coder.internal.isBuiltInNumeric"), "name", 8); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 8); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"), "resolved", 8); emlrtAddField(*info, b_emlrt_marshallOut(1363714556U), "fileTimeLo", 8); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 8); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 8); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 8); emlrtAssign(&rhs8, emlrtCreateCellArray(0)); emlrtAssign(&lhs8, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs8), "rhs", 8); emlrtAddField(*info, emlrtAliasP(lhs8), "lhs", 8); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "context", 9); emlrtAddField(*info, emlrt_marshallOut("max"), "name", 9); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 9); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/datafun/max.m"), "resolved", 9); emlrtAddField(*info, b_emlrt_marshallOut(1311255316U), "fileTimeLo", 9); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 9); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 9); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 9); emlrtAssign(&rhs9, emlrtCreateCellArray(0)); emlrtAssign(&lhs9, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs9), "rhs", 9); emlrtAddField(*info, emlrtAliasP(lhs9), "lhs", 9); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/datafun/max.m"), "context", 10); emlrtAddField(*info, emlrt_marshallOut("eml_min_or_max"), "name", 10); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 10); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_min_or_max.m"), "resolved", 10); emlrtAddField(*info, b_emlrt_marshallOut(1363713870U), "fileTimeLo", 10); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 10); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 10); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 10); emlrtAssign(&rhs10, emlrtCreateCellArray(0)); emlrtAssign(&lhs10, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs10), "rhs", 10); emlrtAddField(*info, emlrtAliasP(lhs10), "lhs", 10); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "context", 11); emlrtAddField(*info, emlrt_marshallOut("eml_index_minus"), "name", 11); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 11); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_minus.m"), "resolved", 11); emlrtAddField(*info, b_emlrt_marshallOut(1286818778U), "fileTimeLo", 11); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 11); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 11); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 11); emlrtAssign(&rhs11, emlrtCreateCellArray(0)); emlrtAssign(&lhs11, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs11), "rhs", 11); emlrtAddField(*info, emlrtAliasP(lhs11), "lhs", 11); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_minus.m"), "context", 12); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 12); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 12); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 12); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 12); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 12); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 12); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 12); emlrtAssign(&rhs12, emlrtCreateCellArray(0)); emlrtAssign(&lhs12, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs12), "rhs", 12); emlrtAddField(*info, emlrtAliasP(lhs12), "lhs", 12); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "context", 13); emlrtAddField(*info, emlrt_marshallOut("eml_scalar_eg"), "name", 13); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 13); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalar_eg.m"), "resolved", 13); emlrtAddField(*info, b_emlrt_marshallOut(1286818796U), "fileTimeLo", 13); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 13); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 13); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 13); emlrtAssign(&rhs13, emlrtCreateCellArray(0)); emlrtAssign(&lhs13, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs13), "rhs", 13); emlrtAddField(*info, emlrtAliasP(lhs13), "lhs", 13); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m!calc_page_back_vector"), "context", 14); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 14); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 14); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 14); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 14); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 14); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 14); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 14); emlrtAssign(&rhs14, emlrtCreateCellArray(0)); emlrtAssign(&lhs14, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs14), "rhs", 14); emlrtAddField(*info, emlrtAliasP(lhs14), "lhs", 14); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "context", 15); emlrtAddField(*info, emlrt_marshallOut("eml_int_forloop_overflow_check"), "name", 15); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 15); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_int_forloop_overflow_check.m"), "resolved", 15); emlrtAddField(*info, b_emlrt_marshallOut(1346510340U), "fileTimeLo", 15); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 15); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 15); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 15); emlrtAssign(&rhs15, emlrtCreateCellArray(0)); emlrtAssign(&lhs15, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs15), "rhs", 15); emlrtAddField(*info, emlrtAliasP(lhs15), "lhs", 15); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_int_forloop_overflow_check.m!eml_int_forloop_overflow_check_helper"), "context", 16); emlrtAddField(*info, emlrt_marshallOut("intmax"), "name", 16); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 16); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmax.m"), "resolved", 16); emlrtAddField(*info, b_emlrt_marshallOut(1362261882U), "fileTimeLo", 16); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 16); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 16); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 16); emlrtAssign(&rhs16, emlrtCreateCellArray(0)); emlrtAssign(&lhs16, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs16), "rhs", 16); emlrtAddField(*info, emlrtAliasP(lhs16), "lhs", 16); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "context", 17); emlrtAddField(*info, emlrt_marshallOut("eml_index_plus"), "name", 17); emlrtAddField(*info, emlrt_marshallOut("coder.internal.indexInt"), "dominantType", 17); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_plus.m"), "resolved", 17); emlrtAddField(*info, b_emlrt_marshallOut(1286818778U), "fileTimeLo", 17); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 17); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 17); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 17); emlrtAssign(&rhs17, emlrtCreateCellArray(0)); emlrtAssign(&lhs17, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs17), "rhs", 17); emlrtAddField(*info, emlrtAliasP(lhs17), "lhs", 17); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_plus.m"), "context", 18); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 18); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 18); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 18); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 18); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 18); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 18); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 18); emlrtAssign(&rhs18, emlrtCreateCellArray(0)); emlrtAssign(&lhs18, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs18), "rhs", 18); emlrtAddField(*info, emlrtAliasP(lhs18), "lhs", 18); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "context", 19); emlrtAddField(*info, emlrt_marshallOut("eml_index_plus"), "name", 19); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 19); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_plus.m"), "resolved", 19); emlrtAddField(*info, b_emlrt_marshallOut(1286818778U), "fileTimeLo", 19); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 19); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 19); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 19); emlrtAssign(&rhs19, emlrtCreateCellArray(0)); emlrtAssign(&lhs19, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs19), "rhs", 19); emlrtAddField(*info, emlrtAliasP(lhs19), "lhs", 19); emlrtAddField(*info, emlrt_marshallOut( "[E]/home/luigi/code/palmieri/learningcost2go/costotogo.m"), "context", 20); emlrtAddField(*info, emlrt_marshallOut("repmat"), "name", 20); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 20); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/repmat.m"), "resolved", 20); emlrtAddField(*info, b_emlrt_marshallOut(1352424860U), "fileTimeLo", 20); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 20); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 20); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 20); emlrtAssign(&rhs20, emlrtCreateCellArray(0)); emlrtAssign(&lhs20, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs20), "rhs", 20); emlrtAddField(*info, emlrtAliasP(lhs20), "lhs", 20); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/repmat.m"), "context", 21); emlrtAddField(*info, emlrt_marshallOut("eml_assert_valid_size_arg"), "name", 21); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 21); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m"), "resolved", 21); emlrtAddField(*info, b_emlrt_marshallOut(1368183030U), "fileTimeLo", 21); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 21); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 21); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 21); emlrtAssign(&rhs21, emlrtCreateCellArray(0)); emlrtAssign(&lhs21, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs21), "rhs", 21); emlrtAddField(*info, emlrtAliasP(lhs21), "lhs", 21); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m"), "context", 22); emlrtAddField(*info, emlrt_marshallOut("coder.internal.isBuiltInNumeric"), "name", 22); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 22); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"), "resolved", 22); emlrtAddField(*info, b_emlrt_marshallOut(1363714556U), "fileTimeLo", 22); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 22); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 22); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 22); emlrtAssign(&rhs22, emlrtCreateCellArray(0)); emlrtAssign(&lhs22, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs22), "rhs", 22); emlrtAddField(*info, emlrtAliasP(lhs22), "lhs", 22); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isintegral"), "context", 23); emlrtAddField(*info, emlrt_marshallOut("isinf"), "name", 23); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 23); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/isinf.m"), "resolved", 23); emlrtAddField(*info, b_emlrt_marshallOut(1363713856U), "fileTimeLo", 23); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 23); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 23); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 23); emlrtAssign(&rhs23, emlrtCreateCellArray(0)); emlrtAssign(&lhs23, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs23), "rhs", 23); emlrtAddField(*info, emlrtAliasP(lhs23), "lhs", 23); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/isinf.m"), "context", 24); emlrtAddField(*info, emlrt_marshallOut("coder.internal.isBuiltInNumeric"), "name", 24); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 24); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"), "resolved", 24); emlrtAddField(*info, b_emlrt_marshallOut(1363714556U), "fileTimeLo", 24); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 24); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 24); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 24); emlrtAssign(&rhs24, emlrtCreateCellArray(0)); emlrtAssign(&lhs24, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs24), "rhs", 24); emlrtAddField(*info, emlrtAliasP(lhs24), "lhs", 24); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isinbounds"), "context", 25); emlrtAddField(*info, emlrt_marshallOut("eml_is_integer_class"), "name", 25); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 25); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_is_integer_class.m"), "resolved", 25); emlrtAddField(*info, b_emlrt_marshallOut(1286818782U), "fileTimeLo", 25); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 25); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 25); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 25); emlrtAssign(&rhs25, emlrtCreateCellArray(0)); emlrtAssign(&lhs25, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs25), "rhs", 25); emlrtAddField(*info, emlrtAliasP(lhs25), "lhs", 25); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isinbounds"), "context", 26); emlrtAddField(*info, emlrt_marshallOut("intmax"), "name", 26); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 26); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmax.m"), "resolved", 26); emlrtAddField(*info, b_emlrt_marshallOut(1362261882U), "fileTimeLo", 26); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 26); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 26); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 26); emlrtAssign(&rhs26, emlrtCreateCellArray(0)); emlrtAssign(&lhs26, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs26), "rhs", 26); emlrtAddField(*info, emlrtAliasP(lhs26), "lhs", 26); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isinbounds"), "context", 27); emlrtAddField(*info, emlrt_marshallOut("intmin"), "name", 27); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 27); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmin.m"), "resolved", 27); emlrtAddField(*info, b_emlrt_marshallOut(1362261882U), "fileTimeLo", 27); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 27); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 27); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 27); emlrtAssign(&rhs27, emlrtCreateCellArray(0)); emlrtAssign(&lhs27, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs27), "rhs", 27); emlrtAddField(*info, emlrtAliasP(lhs27), "lhs", 27); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isinbounds"), "context", 28); emlrtAddField(*info, emlrt_marshallOut("coder.internal.indexIntRelop"), "name", 28); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 28); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/indexIntRelop.m"), "resolved", 28); emlrtAddField(*info, b_emlrt_marshallOut(1326728322U), "fileTimeLo", 28); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 28); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 28); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 28); emlrtAssign(&rhs28, emlrtCreateCellArray(0)); emlrtAssign(&lhs28, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs28), "rhs", 28); emlrtAddField(*info, emlrtAliasP(lhs28), "lhs", 28); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/indexIntRelop.m!float_class_contains_indexIntClass"), "context", 29); emlrtAddField(*info, emlrt_marshallOut("eml_float_model"), "name", 29); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 29); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_float_model.m"), "resolved", 29); emlrtAddField(*info, b_emlrt_marshallOut(1326727996U), "fileTimeLo", 29); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 29); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 29); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 29); emlrtAssign(&rhs29, emlrtCreateCellArray(0)); emlrtAssign(&lhs29, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs29), "rhs", 29); emlrtAddField(*info, emlrtAliasP(lhs29), "lhs", 29); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/indexIntRelop.m!is_signed_indexIntClass"), "context", 30); emlrtAddField(*info, emlrt_marshallOut("intmin"), "name", 30); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 30); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmin.m"), "resolved", 30); emlrtAddField(*info, b_emlrt_marshallOut(1362261882U), "fileTimeLo", 30); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 30); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 30); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 30); emlrtAssign(&rhs30, emlrtCreateCellArray(0)); emlrtAssign(&lhs30, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs30), "rhs", 30); emlrtAddField(*info, emlrtAliasP(lhs30), "lhs", 30); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!numel_for_size"), "context", 31); emlrtAddField(*info, emlrt_marshallOut("mtimes"), "name", 31); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 31); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m"), "resolved", 31); emlrtAddField(*info, b_emlrt_marshallOut(1363713878U), "fileTimeLo", 31); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 31); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 31); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 31); emlrtAssign(&rhs31, emlrtCreateCellArray(0)); emlrtAssign(&lhs31, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs31), "rhs", 31); emlrtAddField(*info, emlrtAliasP(lhs31), "lhs", 31); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m!common_checks"), "context", 32); emlrtAddField(*info, emlrt_marshallOut("coder.internal.isBuiltInNumeric"), "name", 32); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 32); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"), "resolved", 32); emlrtAddField(*info, b_emlrt_marshallOut(1363714556U), "fileTimeLo", 32); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 32); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 32); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 32); emlrtAssign(&rhs32, emlrtCreateCellArray(0)); emlrtAssign(&lhs32, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs32), "rhs", 32); emlrtAddField(*info, emlrtAliasP(lhs32), "lhs", 32); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m"), "context", 33); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 33); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 33); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 33); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 33); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 33); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 33); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 33); emlrtAssign(&rhs33, emlrtCreateCellArray(0)); emlrtAssign(&lhs33, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs33), "rhs", 33); emlrtAddField(*info, emlrtAliasP(lhs33), "lhs", 33); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m"), "context", 34); emlrtAddField(*info, emlrt_marshallOut("intmax"), "name", 34); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 34); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmax.m"), "resolved", 34); emlrtAddField(*info, b_emlrt_marshallOut(1362261882U), "fileTimeLo", 34); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 34); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 34); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 34); emlrtAssign(&rhs34, emlrtCreateCellArray(0)); emlrtAssign(&lhs34, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs34), "rhs", 34); emlrtAddField(*info, emlrtAliasP(lhs34), "lhs", 34); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/repmat.m"), "context", 35); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 35); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 35); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 35); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 35); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 35); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 35); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 35); emlrtAssign(&rhs35, emlrtCreateCellArray(0)); emlrtAssign(&lhs35, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs35), "rhs", 35); emlrtAddField(*info, emlrtAliasP(lhs35), "lhs", 35); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/repmat.m"), "context", 36); emlrtAddField(*info, emlrt_marshallOut("eml_index_minus"), "name", 36); emlrtAddField(*info, emlrt_marshallOut("coder.internal.indexInt"), "dominantType", 36); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_minus.m"), "resolved", 36); emlrtAddField(*info, b_emlrt_marshallOut(1286818778U), "fileTimeLo", 36); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 36); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 36); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 36); emlrtAssign(&rhs36, emlrtCreateCellArray(0)); emlrtAssign(&lhs36, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs36), "rhs", 36); emlrtAddField(*info, emlrtAliasP(lhs36), "lhs", 36); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/repmat.m"), "context", 37); emlrtAddField(*info, emlrt_marshallOut("eml_scalar_eg"), "name", 37); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 37); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalar_eg.m"), "resolved", 37); emlrtAddField(*info, b_emlrt_marshallOut(1286818796U), "fileTimeLo", 37); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 37); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 37); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 37); emlrtAssign(&rhs37, emlrtCreateCellArray(0)); emlrtAssign(&lhs37, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs37), "rhs", 37); emlrtAddField(*info, emlrtAliasP(lhs37), "lhs", 37); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/repmat.m"), "context", 38); emlrtAddField(*info, emlrt_marshallOut("eml_index_prod"), "name", 38); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 38); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_prod.m"), "resolved", 38); emlrtAddField(*info, b_emlrt_marshallOut(1286818780U), "fileTimeLo", 38); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 38); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 38); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 38); emlrtAssign(&rhs38, emlrtCreateCellArray(0)); emlrtAssign(&lhs38, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs38), "rhs", 38); emlrtAddField(*info, emlrtAliasP(lhs38), "lhs", 38); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_prod.m"), "context", 39); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 39); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 39); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 39); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 39); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 39); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 39); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 39); emlrtAssign(&rhs39, emlrtCreateCellArray(0)); emlrtAssign(&lhs39, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs39), "rhs", 39); emlrtAddField(*info, emlrtAliasP(lhs39), "lhs", 39); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_prod.m"), "context", 40); emlrtAddField(*info, emlrt_marshallOut("eml_index_times"), "name", 40); emlrtAddField(*info, emlrt_marshallOut("coder.internal.indexInt"), "dominantType", 40); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_times.m"), "resolved", 40); emlrtAddField(*info, b_emlrt_marshallOut(1286818780U), "fileTimeLo", 40); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 40); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 40); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 40); emlrtAssign(&rhs40, emlrtCreateCellArray(0)); emlrtAssign(&lhs40, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs40), "rhs", 40); emlrtAddField(*info, emlrtAliasP(lhs40), "lhs", 40); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_times.m"), "context", 41); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 41); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 41); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 41); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 41); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 41); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 41); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 41); emlrtAssign(&rhs41, emlrtCreateCellArray(0)); emlrtAssign(&lhs41, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs41), "rhs", 41); emlrtAddField(*info, emlrtAliasP(lhs41), "lhs", 41); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/repmat.m"), "context", 42); emlrtAddField(*info, emlrt_marshallOut("eml_int_forloop_overflow_check"), "name", 42); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 42); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_int_forloop_overflow_check.m"), "resolved", 42); emlrtAddField(*info, b_emlrt_marshallOut(1346510340U), "fileTimeLo", 42); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 42); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 42); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 42); emlrtAssign(&rhs42, emlrtCreateCellArray(0)); emlrtAssign(&lhs42, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs42), "rhs", 42); emlrtAddField(*info, emlrtAliasP(lhs42), "lhs", 42); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/repmat.m"), "context", 43); emlrtAddField(*info, emlrt_marshallOut("eml_index_plus"), "name", 43); emlrtAddField(*info, emlrt_marshallOut("coder.internal.indexInt"), "dominantType", 43); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_plus.m"), "resolved", 43); emlrtAddField(*info, b_emlrt_marshallOut(1286818778U), "fileTimeLo", 43); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 43); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 43); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 43); emlrtAssign(&rhs43, emlrtCreateCellArray(0)); emlrtAssign(&lhs43, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs43), "rhs", 43); emlrtAddField(*info, emlrtAliasP(lhs43), "lhs", 43); emlrtAddField(*info, emlrt_marshallOut( "[E]/home/luigi/code/palmieri/learningcost2go/costotogo.m"), "context", 44); emlrtAddField(*info, emlrt_marshallOut("mtimes"), "name", 44); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 44); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m"), "resolved", 44); emlrtAddField(*info, b_emlrt_marshallOut(1363713878U), "fileTimeLo", 44); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 44); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 44); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 44); emlrtAssign(&rhs44, emlrtCreateCellArray(0)); emlrtAssign(&lhs44, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs44), "rhs", 44); emlrtAddField(*info, emlrtAliasP(lhs44), "lhs", 44); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m"), "context", 45); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 45); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 45); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 45); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 45); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 45); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 45); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 45); emlrtAssign(&rhs45, emlrtCreateCellArray(0)); emlrtAssign(&lhs45, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs45), "rhs", 45); emlrtAddField(*info, emlrtAliasP(lhs45), "lhs", 45); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m"), "context", 46); emlrtAddField(*info, emlrt_marshallOut("eml_scalar_eg"), "name", 46); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 46); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalar_eg.m"), "resolved", 46); emlrtAddField(*info, b_emlrt_marshallOut(1286818796U), "fileTimeLo", 46); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 46); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 46); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 46); emlrtAssign(&rhs46, emlrtCreateCellArray(0)); emlrtAssign(&lhs46, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs46), "rhs", 46); emlrtAddField(*info, emlrtAliasP(lhs46), "lhs", 46); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m"), "context", 47); emlrtAddField(*info, emlrt_marshallOut("eml_xgemm"), "name", 47); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 47); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_xgemm.m"), "resolved", 47); emlrtAddField(*info, b_emlrt_marshallOut(1363713870U), "fileTimeLo", 47); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 47); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 47); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 47); emlrtAssign(&rhs47, emlrtCreateCellArray(0)); emlrtAssign(&lhs47, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs47), "rhs", 47); emlrtAddField(*info, emlrtAliasP(lhs47), "lhs", 47); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_xgemm.m"), "context", 48); emlrtAddField(*info, emlrt_marshallOut("eml_blas_inline"), "name", 48); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 48); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_blas_inline.m"), "resolved", 48); emlrtAddField(*info, b_emlrt_marshallOut(1299076768U), "fileTimeLo", 48); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 48); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 48); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 48); emlrtAssign(&rhs48, emlrtCreateCellArray(0)); emlrtAssign(&lhs48, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs48), "rhs", 48); emlrtAddField(*info, emlrtAliasP(lhs48), "lhs", 48); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/internal/eml_blas_xgemm.m"), "context", 49); emlrtAddField(*info, emlrt_marshallOut("eml_refblas_xgemm"), "name", 49); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 49); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xgemm.m"), "resolved", 49); emlrtAddField(*info, b_emlrt_marshallOut(1360282350U), "fileTimeLo", 49); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 49); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 49); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 49); emlrtAssign(&rhs49, emlrtCreateCellArray(0)); emlrtAssign(&lhs49, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs49), "rhs", 49); emlrtAddField(*info, emlrtAliasP(lhs49), "lhs", 49); emlrtAddField(*info, emlrt_marshallOut( "[E]/home/luigi/code/palmieri/learningcost2go/costotogo.m!tansig_apply"), "context", 50); emlrtAddField(*info, emlrt_marshallOut("mtimes"), "name", 50); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 50); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m"), "resolved", 50); emlrtAddField(*info, b_emlrt_marshallOut(1363713878U), "fileTimeLo", 50); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 50); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 50); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 50); emlrtAssign(&rhs50, emlrtCreateCellArray(0)); emlrtAssign(&lhs50, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs50), "rhs", 50); emlrtAddField(*info, emlrtAliasP(lhs50), "lhs", 50); emlrtAddField(*info, emlrt_marshallOut( "[E]/home/luigi/code/palmieri/learningcost2go/costotogo.m!tansig_apply"), "context", 51); emlrtAddField(*info, emlrt_marshallOut("exp"), "name", 51); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 51); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/exp.m"), "resolved", 51); emlrtAddField(*info, b_emlrt_marshallOut(1343830380U), "fileTimeLo", 51); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 51); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 51); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 51); emlrtAssign(&rhs51, emlrtCreateCellArray(0)); emlrtAssign(&lhs51, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs51), "rhs", 51); emlrtAddField(*info, emlrtAliasP(lhs51), "lhs", 51); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/exp.m"), "context", 52); emlrtAddField(*info, emlrt_marshallOut("eml_scalar_exp"), "name", 52); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 52); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/eml_scalar_exp.m"), "resolved", 52); emlrtAddField(*info, b_emlrt_marshallOut(1301328464U), "fileTimeLo", 52); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 52); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 52); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 52); emlrtAssign(&rhs52, emlrtCreateCellArray(0)); emlrtAssign(&lhs52, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs52), "rhs", 52); emlrtAddField(*info, emlrtAliasP(lhs52), "lhs", 52); emlrtAddField(*info, emlrt_marshallOut( "[E]/home/luigi/code/palmieri/learningcost2go/costotogo.m!tansig_apply"), "context", 53); emlrtAddField(*info, emlrt_marshallOut("rdivide"), "name", 53); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 53); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m"), "resolved", 53); emlrtAddField(*info, b_emlrt_marshallOut(1363713880U), "fileTimeLo", 53); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 53); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 53); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 53); emlrtAssign(&rhs53, emlrtCreateCellArray(0)); emlrtAssign(&lhs53, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs53), "rhs", 53); emlrtAddField(*info, emlrtAliasP(lhs53), "lhs", 53); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m"), "context", 54); emlrtAddField(*info, emlrt_marshallOut("coder.internal.isBuiltInNumeric"), "name", 54); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 54); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"), "resolved", 54); emlrtAddField(*info, b_emlrt_marshallOut(1363714556U), "fileTimeLo", 54); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 54); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 54); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 54); emlrtAssign(&rhs54, emlrtCreateCellArray(0)); emlrtAssign(&lhs54, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs54), "rhs", 54); emlrtAddField(*info, emlrtAliasP(lhs54), "lhs", 54); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m"), "context", 55); emlrtAddField(*info, emlrt_marshallOut("eml_scalexp_compatible"), "name", 55); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 55); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalexp_compatible.m"), "resolved", 55); emlrtAddField(*info, b_emlrt_marshallOut(1286818796U), "fileTimeLo", 55); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 55); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 55); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 55); emlrtAssign(&rhs55, emlrtCreateCellArray(0)); emlrtAssign(&lhs55, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs55), "rhs", 55); emlrtAddField(*info, emlrtAliasP(lhs55), "lhs", 55); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m"), "context", 56); emlrtAddField(*info, emlrt_marshallOut("eml_div"), "name", 56); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 56); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_div.m"), "resolved", 56); emlrtAddField(*info, b_emlrt_marshallOut(1363713866U), "fileTimeLo", 56); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 56); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 56); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 56); emlrtAssign(&rhs56, emlrtCreateCellArray(0)); emlrtAssign(&lhs56, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs56), "rhs", 56); emlrtAddField(*info, emlrtAliasP(lhs56), "lhs", 56); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m"), "context", 57); emlrtAddField(*info, emlrt_marshallOut("eml_xdotu"), "name", 57); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 57); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_xdotu.m"), "resolved", 57); emlrtAddField(*info, b_emlrt_marshallOut(1363713870U), "fileTimeLo", 57); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 57); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 57); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 57); emlrtAssign(&rhs57, emlrtCreateCellArray(0)); emlrtAssign(&lhs57, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs57), "rhs", 57); emlrtAddField(*info, emlrtAliasP(lhs57), "lhs", 57); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_xdotu.m"), "context", 58); emlrtAddField(*info, emlrt_marshallOut("eml_blas_inline"), "name", 58); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 58); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_blas_inline.m"), "resolved", 58); emlrtAddField(*info, b_emlrt_marshallOut(1299076768U), "fileTimeLo", 58); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 58); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 58); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 58); emlrtAssign(&rhs58, emlrtCreateCellArray(0)); emlrtAssign(&lhs58, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs58), "rhs", 58); emlrtAddField(*info, emlrtAliasP(lhs58), "lhs", 58); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_xdotu.m"), "context", 59); emlrtAddField(*info, emlrt_marshallOut("eml_xdot"), "name", 59); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 59); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_xdot.m"), "resolved", 59); emlrtAddField(*info, b_emlrt_marshallOut(1363713868U), "fileTimeLo", 59); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 59); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 59); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 59); emlrtAssign(&rhs59, emlrtCreateCellArray(0)); emlrtAssign(&lhs59, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs59), "rhs", 59); emlrtAddField(*info, emlrtAliasP(lhs59), "lhs", 59); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_xdot.m"), "context", 60); emlrtAddField(*info, emlrt_marshallOut("eml_blas_inline"), "name", 60); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 60); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/eml_blas_inline.m"), "resolved", 60); emlrtAddField(*info, b_emlrt_marshallOut(1299076768U), "fileTimeLo", 60); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 60); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 60); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 60); emlrtAssign(&rhs60, emlrtCreateCellArray(0)); emlrtAssign(&lhs60, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs60), "rhs", 60); emlrtAddField(*info, emlrtAliasP(lhs60), "lhs", 60); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/internal/eml_blas_xdot.m"), "context", 61); emlrtAddField(*info, emlrt_marshallOut("eml_refblas_xdot"), "name", 61); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 61); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdot.m"), "resolved", 61); emlrtAddField(*info, b_emlrt_marshallOut(1299076772U), "fileTimeLo", 61); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 61); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 61); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 61); emlrtAssign(&rhs61, emlrtCreateCellArray(0)); emlrtAssign(&lhs61, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs61), "rhs", 61); emlrtAddField(*info, emlrtAliasP(lhs61), "lhs", 61); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdot.m"), "context", 62); emlrtAddField(*info, emlrt_marshallOut("eml_refblas_xdotx"), "name", 62); emlrtAddField(*info, emlrt_marshallOut("char"), "dominantType", 62); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdotx.m"), "resolved", 62); emlrtAddField(*info, b_emlrt_marshallOut(1360282350U), "fileTimeLo", 62); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 62); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 62); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 62); emlrtAssign(&rhs62, emlrtCreateCellArray(0)); emlrtAssign(&lhs62, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs62), "rhs", 62); emlrtAddField(*info, emlrtAliasP(lhs62), "lhs", 62); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdotx.m"), "context", 63); emlrtAddField(*info, emlrt_marshallOut("eml_scalar_eg"), "name", 63); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 63); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalar_eg.m"), "resolved", 63); emlrtAddField(*info, b_emlrt_marshallOut(1286818796U), "fileTimeLo", 63); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 63); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 63); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 63); emlrtAssign(&rhs63, emlrtCreateCellArray(0)); emlrtAssign(&lhs63, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs63), "rhs", 63); emlrtAddField(*info, emlrtAliasP(lhs63), "lhs", 63); emlrtDestroyArray(&rhs0); emlrtDestroyArray(&lhs0); emlrtDestroyArray(&rhs1); emlrtDestroyArray(&lhs1); emlrtDestroyArray(&rhs2); emlrtDestroyArray(&lhs2); emlrtDestroyArray(&rhs3); emlrtDestroyArray(&lhs3); emlrtDestroyArray(&rhs4); emlrtDestroyArray(&lhs4); emlrtDestroyArray(&rhs5); emlrtDestroyArray(&lhs5); emlrtDestroyArray(&rhs6); emlrtDestroyArray(&lhs6); emlrtDestroyArray(&rhs7); emlrtDestroyArray(&lhs7); emlrtDestroyArray(&rhs8); emlrtDestroyArray(&lhs8); emlrtDestroyArray(&rhs9); emlrtDestroyArray(&lhs9); emlrtDestroyArray(&rhs10); emlrtDestroyArray(&lhs10); emlrtDestroyArray(&rhs11); emlrtDestroyArray(&lhs11); emlrtDestroyArray(&rhs12); emlrtDestroyArray(&lhs12); emlrtDestroyArray(&rhs13); emlrtDestroyArray(&lhs13); emlrtDestroyArray(&rhs14); emlrtDestroyArray(&lhs14); emlrtDestroyArray(&rhs15); emlrtDestroyArray(&lhs15); emlrtDestroyArray(&rhs16); emlrtDestroyArray(&lhs16); emlrtDestroyArray(&rhs17); emlrtDestroyArray(&lhs17); emlrtDestroyArray(&rhs18); emlrtDestroyArray(&lhs18); emlrtDestroyArray(&rhs19); emlrtDestroyArray(&lhs19); emlrtDestroyArray(&rhs20); emlrtDestroyArray(&lhs20); emlrtDestroyArray(&rhs21); emlrtDestroyArray(&lhs21); emlrtDestroyArray(&rhs22); emlrtDestroyArray(&lhs22); emlrtDestroyArray(&rhs23); emlrtDestroyArray(&lhs23); emlrtDestroyArray(&rhs24); emlrtDestroyArray(&lhs24); emlrtDestroyArray(&rhs25); emlrtDestroyArray(&lhs25); emlrtDestroyArray(&rhs26); emlrtDestroyArray(&lhs26); emlrtDestroyArray(&rhs27); emlrtDestroyArray(&lhs27); emlrtDestroyArray(&rhs28); emlrtDestroyArray(&lhs28); emlrtDestroyArray(&rhs29); emlrtDestroyArray(&lhs29); emlrtDestroyArray(&rhs30); emlrtDestroyArray(&lhs30); emlrtDestroyArray(&rhs31); emlrtDestroyArray(&lhs31); emlrtDestroyArray(&rhs32); emlrtDestroyArray(&lhs32); emlrtDestroyArray(&rhs33); emlrtDestroyArray(&lhs33); emlrtDestroyArray(&rhs34); emlrtDestroyArray(&lhs34); emlrtDestroyArray(&rhs35); emlrtDestroyArray(&lhs35); emlrtDestroyArray(&rhs36); emlrtDestroyArray(&lhs36); emlrtDestroyArray(&rhs37); emlrtDestroyArray(&lhs37); emlrtDestroyArray(&rhs38); emlrtDestroyArray(&lhs38); emlrtDestroyArray(&rhs39); emlrtDestroyArray(&lhs39); emlrtDestroyArray(&rhs40); emlrtDestroyArray(&lhs40); emlrtDestroyArray(&rhs41); emlrtDestroyArray(&lhs41); emlrtDestroyArray(&rhs42); emlrtDestroyArray(&lhs42); emlrtDestroyArray(&rhs43); emlrtDestroyArray(&lhs43); emlrtDestroyArray(&rhs44); emlrtDestroyArray(&lhs44); emlrtDestroyArray(&rhs45); emlrtDestroyArray(&lhs45); emlrtDestroyArray(&rhs46); emlrtDestroyArray(&lhs46); emlrtDestroyArray(&rhs47); emlrtDestroyArray(&lhs47); emlrtDestroyArray(&rhs48); emlrtDestroyArray(&lhs48); emlrtDestroyArray(&rhs49); emlrtDestroyArray(&lhs49); emlrtDestroyArray(&rhs50); emlrtDestroyArray(&lhs50); emlrtDestroyArray(&rhs51); emlrtDestroyArray(&lhs51); emlrtDestroyArray(&rhs52); emlrtDestroyArray(&lhs52); emlrtDestroyArray(&rhs53); emlrtDestroyArray(&lhs53); emlrtDestroyArray(&rhs54); emlrtDestroyArray(&lhs54); emlrtDestroyArray(&rhs55); emlrtDestroyArray(&lhs55); emlrtDestroyArray(&rhs56); emlrtDestroyArray(&lhs56); emlrtDestroyArray(&rhs57); emlrtDestroyArray(&lhs57); emlrtDestroyArray(&rhs58); emlrtDestroyArray(&lhs58); emlrtDestroyArray(&rhs59); emlrtDestroyArray(&lhs59); emlrtDestroyArray(&rhs60); emlrtDestroyArray(&lhs60); emlrtDestroyArray(&rhs61); emlrtDestroyArray(&lhs61); emlrtDestroyArray(&rhs62); emlrtDestroyArray(&lhs62); emlrtDestroyArray(&rhs63); emlrtDestroyArray(&lhs63); } static const mxArray *emlrt_marshallOut(const char * u) { const mxArray *y; const mxArray *m0; y = NULL; m0 = mxCreateString(u); emlrtAssign(&y, m0); return y; } static const mxArray *b_emlrt_marshallOut(uint32_T u) { const mxArray *y; const mxArray *m1; y = NULL; m1 = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL); *(uint32_T *)mxGetData(m1) = u; emlrtAssign(&y, m1); return y; } static void b_info_helper(const mxArray **info) { const mxArray *rhs64 = NULL; const mxArray *lhs64 = NULL; const mxArray *rhs65 = NULL; const mxArray *lhs65 = NULL; const mxArray *rhs66 = NULL; const mxArray *lhs66 = NULL; const mxArray *rhs67 = NULL; const mxArray *lhs67 = NULL; const mxArray *rhs68 = NULL; const mxArray *lhs68 = NULL; const mxArray *rhs69 = NULL; const mxArray *lhs69 = NULL; const mxArray *rhs70 = NULL; const mxArray *lhs70 = NULL; const mxArray *rhs71 = NULL; const mxArray *lhs71 = NULL; const mxArray *rhs72 = NULL; const mxArray *lhs72 = NULL; const mxArray *rhs73 = NULL; const mxArray *lhs73 = NULL; const mxArray *rhs74 = NULL; const mxArray *lhs74 = NULL; const mxArray *rhs75 = NULL; const mxArray *lhs75 = NULL; emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdotx.m"), "context", 64); emlrtAddField(*info, emlrt_marshallOut("eml_index_class"), "name", 64); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 64); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"), "resolved", 64); emlrtAddField(*info, b_emlrt_marshallOut(1323170578U), "fileTimeLo", 64); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 64); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 64); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 64); emlrtAssign(&rhs64, emlrtCreateCellArray(0)); emlrtAssign(&lhs64, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs64), "rhs", 64); emlrtAddField(*info, emlrtAliasP(lhs64), "lhs", 64); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdotx.m"), "context", 65); emlrtAddField(*info, emlrt_marshallOut("eml_index_minus"), "name", 65); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 65); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_minus.m"), "resolved", 65); emlrtAddField(*info, b_emlrt_marshallOut(1286818778U), "fileTimeLo", 65); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 65); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 65); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 65); emlrtAssign(&rhs65, emlrtCreateCellArray(0)); emlrtAssign(&lhs65, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs65), "rhs", 65); emlrtAddField(*info, emlrtAliasP(lhs65), "lhs", 65); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdotx.m"), "context", 66); emlrtAddField(*info, emlrt_marshallOut("eml_index_times"), "name", 66); emlrtAddField(*info, emlrt_marshallOut("coder.internal.indexInt"), "dominantType", 66); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_times.m"), "resolved", 66); emlrtAddField(*info, b_emlrt_marshallOut(1286818780U), "fileTimeLo", 66); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 66); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 66); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 66); emlrtAssign(&rhs66, emlrtCreateCellArray(0)); emlrtAssign(&lhs66, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs66), "rhs", 66); emlrtAddField(*info, emlrtAliasP(lhs66), "lhs", 66); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdotx.m"), "context", 67); emlrtAddField(*info, emlrt_marshallOut("eml_index_plus"), "name", 67); emlrtAddField(*info, emlrt_marshallOut("coder.internal.indexInt"), "dominantType", 67); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_plus.m"), "resolved", 67); emlrtAddField(*info, b_emlrt_marshallOut(1286818778U), "fileTimeLo", 67); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 67); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 67); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 67); emlrtAssign(&rhs67, emlrtCreateCellArray(0)); emlrtAssign(&lhs67, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs67), "rhs", 67); emlrtAddField(*info, emlrtAliasP(lhs67), "lhs", 67); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/blas/refblas/eml_refblas_xdotx.m"), "context", 68); emlrtAddField(*info, emlrt_marshallOut("eml_int_forloop_overflow_check"), "name", 68); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 68); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_int_forloop_overflow_check.m"), "resolved", 68); emlrtAddField(*info, b_emlrt_marshallOut(1346510340U), "fileTimeLo", 68); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 68); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 68); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 68); emlrtAssign(&rhs68, emlrtCreateCellArray(0)); emlrtAssign(&lhs68, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs68), "rhs", 68); emlrtAddField(*info, emlrtAliasP(lhs68), "lhs", 68); emlrtAddField(*info, emlrt_marshallOut( "[E]/home/luigi/code/palmieri/learningcost2go/costotogo.m!mapminmax_reverse"), "context", 69); emlrtAddField(*info, emlrt_marshallOut("bsxfun"), "name", 69); emlrtAddField(*info, emlrt_marshallOut("function_handle"), "dominantType", 69); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "resolved", 69); emlrtAddField(*info, b_emlrt_marshallOut(1356541494U), "fileTimeLo", 69); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 69); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 69); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 69); emlrtAssign(&rhs69, emlrtCreateCellArray(0)); emlrtAssign(&lhs69, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs69), "rhs", 69); emlrtAddField(*info, emlrtAliasP(lhs69), "lhs", 69); emlrtAddField(*info, emlrt_marshallOut( "[E]/home/luigi/code/palmieri/learningcost2go/costotogo.m!mapminmax_reverse"), "context", 70); emlrtAddField(*info, emlrt_marshallOut("rdivide"), "name", 70); emlrtAddField(*info, emlrt_marshallOut(""), "dominantType", 70); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m"), "resolved", 70); emlrtAddField(*info, b_emlrt_marshallOut(1363713880U), "fileTimeLo", 70); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 70); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 70); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 70); emlrtAssign(&rhs70, emlrtCreateCellArray(0)); emlrtAssign(&lhs70, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs70), "rhs", 70); emlrtAddField(*info, emlrtAliasP(lhs70), "lhs", 70); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/bsxfun.m"), "context", 71); emlrtAddField(*info, emlrt_marshallOut("rdivide"), "name", 71); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 71); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m"), "resolved", 71); emlrtAddField(*info, b_emlrt_marshallOut(1363713880U), "fileTimeLo", 71); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 71); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 71); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 71); emlrtAssign(&rhs71, emlrtCreateCellArray(0)); emlrtAssign(&lhs71, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs71), "rhs", 71); emlrtAddField(*info, emlrtAliasP(lhs71), "lhs", 71); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalexp_compatible.m"), "context", 72); emlrtAddField(*info, emlrt_marshallOut("isequal"), "name", 72); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 72); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/isequal.m"), "resolved", 72); emlrtAddField(*info, b_emlrt_marshallOut(1286818758U), "fileTimeLo", 72); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 72); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 72); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 72); emlrtAssign(&rhs72, emlrtCreateCellArray(0)); emlrtAssign(&lhs72, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs72), "rhs", 72); emlrtAddField(*info, emlrtAliasP(lhs72), "lhs", 72); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/isequal.m"), "context", 73); emlrtAddField(*info, emlrt_marshallOut("eml_isequal_core"), "name", 73); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 73); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_isequal_core.m"), "resolved", 73); emlrtAddField(*info, b_emlrt_marshallOut(1286818786U), "fileTimeLo", 73); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 73); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 73); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 73); emlrtAssign(&rhs73, emlrtCreateCellArray(0)); emlrtAssign(&lhs73, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs73), "rhs", 73); emlrtAddField(*info, emlrtAliasP(lhs73), "lhs", 73); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_isequal_core.m!isequal_scalar"), "context", 74); emlrtAddField(*info, emlrt_marshallOut("isnan"), "name", 74); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 74); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/isnan.m"), "resolved", 74); emlrtAddField(*info, b_emlrt_marshallOut(1363713858U), "fileTimeLo", 74); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 74); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 74); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 74); emlrtAssign(&rhs74, emlrtCreateCellArray(0)); emlrtAssign(&lhs74, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs74), "rhs", 74); emlrtAddField(*info, emlrtAliasP(lhs74), "lhs", 74); emlrtAddField(*info, emlrt_marshallOut( "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/isnan.m"), "context", 75); emlrtAddField(*info, emlrt_marshallOut("coder.internal.isBuiltInNumeric"), "name", 75); emlrtAddField(*info, emlrt_marshallOut("double"), "dominantType", 75); emlrtAddField(*info, emlrt_marshallOut( "[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"), "resolved", 75); emlrtAddField(*info, b_emlrt_marshallOut(1363714556U), "fileTimeLo", 75); emlrtAddField(*info, b_emlrt_marshallOut(0U), "fileTimeHi", 75); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeLo", 75); emlrtAddField(*info, b_emlrt_marshallOut(0U), "mFileTimeHi", 75); emlrtAssign(&rhs75, emlrtCreateCellArray(0)); emlrtAssign(&lhs75, emlrtCreateCellArray(0)); emlrtAddField(*info, emlrtAliasP(rhs75), "rhs", 75); emlrtAddField(*info, emlrtAliasP(lhs75), "lhs", 75); emlrtDestroyArray(&rhs64); emlrtDestroyArray(&lhs64); emlrtDestroyArray(&rhs65); emlrtDestroyArray(&lhs65); emlrtDestroyArray(&rhs66); emlrtDestroyArray(&lhs66); emlrtDestroyArray(&rhs67); emlrtDestroyArray(&lhs67); emlrtDestroyArray(&rhs68); emlrtDestroyArray(&lhs68); emlrtDestroyArray(&rhs69); emlrtDestroyArray(&lhs69); emlrtDestroyArray(&rhs70); emlrtDestroyArray(&lhs70); emlrtDestroyArray(&rhs71); emlrtDestroyArray(&lhs71); emlrtDestroyArray(&rhs72); emlrtDestroyArray(&lhs72); emlrtDestroyArray(&rhs73); emlrtDestroyArray(&lhs73); emlrtDestroyArray(&rhs74); emlrtDestroyArray(&lhs74); emlrtDestroyArray(&rhs75); emlrtDestroyArray(&lhs75); } MEXFUNCTION_LINKAGE mxArray *emlrtMexFcnProperties(void); mxArray *emlrtMexFcnProperties() { const char *mexProperties[] = { "Version", "ResolvedFunctions", "EntryPoints", "CoverageInfo", NULL }; const char *epProperties[] = { "Name", "NumberOfInputs", "NumberOfOutputs", "ConstantInputs" }; mxArray *xResult = mxCreateStructMatrix(1,1,4,mexProperties); mxArray *xEntryPoints = mxCreateStructMatrix(1,1,4,epProperties); mxArray *xInputs = NULL; xInputs = mxCreateLogicalMatrix(1, 1); mxSetFieldByNumber(xEntryPoints, 0, 0, mxCreateString("costotogo")); mxSetFieldByNumber(xEntryPoints, 0, 1, mxCreateDoubleScalar(1)); mxSetFieldByNumber(xEntryPoints, 0, 2, mxCreateDoubleScalar(1)); mxSetFieldByNumber(xEntryPoints, 0, 3, xInputs); mxSetFieldByNumber(xResult, 0, 0, mxCreateString("8.2.0.701 (R2013b)")); mxSetFieldByNumber(xResult, 0, 1, (mxArray*)emlrtMexFcnResolvedFunctionsInfo()); mxSetFieldByNumber(xResult, 0, 2, xEntryPoints); return xResult; } /* End of code generation (_coder_costotogo_info.c) */
gpl-3.0
Olegas/chinese_marlin
ConfigurationStore.cpp
11
9879
#include "Marlin.h" #include "planner.h" #include "temperature.h" #include "ultralcd.h" #include "ConfigurationStore.h" void _EEPROM_writeData(int &pos, uint8_t* value, uint8_t size) { do { eeprom_write_byte((unsigned char*)pos, *value); pos++; value++; }while(--size); } #define EEPROM_WRITE_VAR(pos, value) _EEPROM_writeData(pos, (uint8_t*)&value, sizeof(value)) void _EEPROM_readData(int &pos, uint8_t* value, uint8_t size) { do { *value = eeprom_read_byte((unsigned char*)pos); pos++; value++; }while(--size); } #define EEPROM_READ_VAR(pos, value) _EEPROM_readData(pos, (uint8_t*)&value, sizeof(value)) //====================================================================================== #define EEPROM_OFFSET 100 // IMPORTANT: Whenever there are changes made to the variables stored in EEPROM // in the functions below, also increment the version number. This makes sure that // the default values are used whenever there is a change to the data, to prevent // wrong data being written to the variables. // ALSO: always make sure the variables in the Store and retrieve sections are in the same order. #define EEPROM_VERSION "V10" #ifdef EEPROM_SETTINGS void Config_StoreSettings() { char ver[4]= "000"; int i=EEPROM_OFFSET; EEPROM_WRITE_VAR(i,ver); // invalidate data first EEPROM_WRITE_VAR(i,axis_steps_per_unit); EEPROM_WRITE_VAR(i,max_feedrate); EEPROM_WRITE_VAR(i,max_acceleration_units_per_sq_second); EEPROM_WRITE_VAR(i,acceleration); EEPROM_WRITE_VAR(i,retract_acceleration); EEPROM_WRITE_VAR(i,minimumfeedrate); EEPROM_WRITE_VAR(i,mintravelfeedrate); EEPROM_WRITE_VAR(i,minsegmenttime); EEPROM_WRITE_VAR(i,max_xy_jerk); EEPROM_WRITE_VAR(i,max_z_jerk); EEPROM_WRITE_VAR(i,max_e_jerk); EEPROM_WRITE_VAR(i,add_homeing); #ifdef DELTA EEPROM_WRITE_VAR(i,endstop_adj); #endif #ifndef ULTIPANEL int plaPreheatHotendTemp = PLA_PREHEAT_HOTEND_TEMP, plaPreheatHPBTemp = PLA_PREHEAT_HPB_TEMP, plaPreheatFanSpeed = PLA_PREHEAT_FAN_SPEED; int absPreheatHotendTemp = ABS_PREHEAT_HOTEND_TEMP, absPreheatHPBTemp = ABS_PREHEAT_HPB_TEMP, absPreheatFanSpeed = ABS_PREHEAT_FAN_SPEED; #endif EEPROM_WRITE_VAR(i,plaPreheatHotendTemp); EEPROM_WRITE_VAR(i,plaPreheatHPBTemp); EEPROM_WRITE_VAR(i,plaPreheatFanSpeed); EEPROM_WRITE_VAR(i,absPreheatHotendTemp); EEPROM_WRITE_VAR(i,absPreheatHPBTemp); EEPROM_WRITE_VAR(i,absPreheatFanSpeed); EEPROM_WRITE_VAR(i,zprobe_zoffset); #ifdef PIDTEMP EEPROM_WRITE_VAR(i,Kp); EEPROM_WRITE_VAR(i,Ki); EEPROM_WRITE_VAR(i,Kd); #else float dummy = 3000.0f; EEPROM_WRITE_VAR(i,dummy); dummy = 0.0f; EEPROM_WRITE_VAR(i,dummy); EEPROM_WRITE_VAR(i,dummy); #endif #ifndef DOGLCD int lcd_contrast = 32; #endif EEPROM_WRITE_VAR(i,lcd_contrast); char ver2[4]=EEPROM_VERSION; i=EEPROM_OFFSET; EEPROM_WRITE_VAR(i,ver2); // validate data SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Settings Stored"); } #endif //EEPROM_SETTINGS #ifndef DISABLE_M503 void Config_PrintSettings() { // Always have this function, even with EEPROM_SETTINGS disabled, the current values will be shown SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Steps per unit:"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M92 X",axis_steps_per_unit[0]); SERIAL_ECHOPAIR(" Y",axis_steps_per_unit[1]); SERIAL_ECHOPAIR(" Z",axis_steps_per_unit[2]); SERIAL_ECHOPAIR(" E",axis_steps_per_unit[3]); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Maximum feedrates (mm/s):"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M203 X",max_feedrate[0]); SERIAL_ECHOPAIR(" Y",max_feedrate[1] ); SERIAL_ECHOPAIR(" Z", max_feedrate[2] ); SERIAL_ECHOPAIR(" E", max_feedrate[3]); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Maximum Acceleration (mm/s2):"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M201 X" ,max_acceleration_units_per_sq_second[0] ); SERIAL_ECHOPAIR(" Y" , max_acceleration_units_per_sq_second[1] ); SERIAL_ECHOPAIR(" Z" ,max_acceleration_units_per_sq_second[2] ); SERIAL_ECHOPAIR(" E" ,max_acceleration_units_per_sq_second[3]); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Acceleration: S=acceleration, T=retract acceleration"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M204 S",acceleration ); SERIAL_ECHOPAIR(" T" ,retract_acceleration); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Advanced variables: S=Min feedrate (mm/s), T=Min travel feedrate (mm/s), B=minimum segment time (ms), X=maximum XY jerk (mm/s), Z=maximum Z jerk (mm/s), E=maximum E jerk (mm/s)"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M205 S",minimumfeedrate ); SERIAL_ECHOPAIR(" T" ,mintravelfeedrate ); SERIAL_ECHOPAIR(" B" ,minsegmenttime ); SERIAL_ECHOPAIR(" X" ,max_xy_jerk ); SERIAL_ECHOPAIR(" Z" ,max_z_jerk); SERIAL_ECHOPAIR(" E" ,max_e_jerk); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Home offset (mm):"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M206 X",add_homeing[0] ); SERIAL_ECHOPAIR(" Y" ,add_homeing[1] ); SERIAL_ECHOPAIR(" Z" ,add_homeing[2] ); SERIAL_ECHOLN(""); #ifdef DELTA SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Endstop adjustement (mm):"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M666 X",endstop_adj[0] ); SERIAL_ECHOPAIR(" Y" ,endstop_adj[1] ); SERIAL_ECHOPAIR(" Z" ,endstop_adj[2] ); SERIAL_ECHOLN(""); #endif #ifdef PIDTEMP SERIAL_ECHO_START; SERIAL_ECHOLNPGM("PID settings:"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M301 P",Kp); SERIAL_ECHOPAIR(" I" ,unscalePID_i(Ki)); SERIAL_ECHOPAIR(" D" ,unscalePID_d(Kd)); SERIAL_ECHOLN(""); #endif } #endif #ifdef EEPROM_SETTINGS void Config_RetrieveSettings() { int i=EEPROM_OFFSET; char stored_ver[4]; char ver[4]=EEPROM_VERSION; EEPROM_READ_VAR(i,stored_ver); //read stored version // SERIAL_ECHOLN("Version: [" << ver << "] Stored version: [" << stored_ver << "]"); if (strncmp(ver,stored_ver,3) == 0) { // version number match EEPROM_READ_VAR(i,axis_steps_per_unit); EEPROM_READ_VAR(i,max_feedrate); EEPROM_READ_VAR(i,max_acceleration_units_per_sq_second); // steps per sq second need to be updated to agree with the units per sq second (as they are what is used in the planner) reset_acceleration_rates(); EEPROM_READ_VAR(i,acceleration); EEPROM_READ_VAR(i,retract_acceleration); EEPROM_READ_VAR(i,minimumfeedrate); EEPROM_READ_VAR(i,mintravelfeedrate); EEPROM_READ_VAR(i,minsegmenttime); EEPROM_READ_VAR(i,max_xy_jerk); EEPROM_READ_VAR(i,max_z_jerk); EEPROM_READ_VAR(i,max_e_jerk); EEPROM_READ_VAR(i,add_homeing); #ifdef DELTA EEPROM_READ_VAR(i,endstop_adj); #endif #ifndef ULTIPANEL int plaPreheatHotendTemp, plaPreheatHPBTemp, plaPreheatFanSpeed; int absPreheatHotendTemp, absPreheatHPBTemp, absPreheatFanSpeed; #endif EEPROM_READ_VAR(i,plaPreheatHotendTemp); EEPROM_READ_VAR(i,plaPreheatHPBTemp); EEPROM_READ_VAR(i,plaPreheatFanSpeed); EEPROM_READ_VAR(i,absPreheatHotendTemp); EEPROM_READ_VAR(i,absPreheatHPBTemp); EEPROM_READ_VAR(i,absPreheatFanSpeed); EEPROM_READ_VAR(i,zprobe_zoffset); #ifndef PIDTEMP float Kp,Ki,Kd; #endif // do not need to scale PID values as the values in EEPROM are already scaled EEPROM_READ_VAR(i,Kp); EEPROM_READ_VAR(i,Ki); EEPROM_READ_VAR(i,Kd); #ifndef DOGLCD int lcd_contrast; #endif EEPROM_READ_VAR(i,lcd_contrast); // Call updatePID (similar to when we have processed M301) updatePID(); SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Stored settings retrieved"); } else { Config_ResetDefault(); } #ifdef EEPROM_CHITCHAT Config_PrintSettings(); #endif } #endif void Config_ResetDefault() { float tmp1[]=DEFAULT_AXIS_STEPS_PER_UNIT; float tmp2[]=DEFAULT_MAX_FEEDRATE; long tmp3[]=DEFAULT_MAX_ACCELERATION; for (short i=0;i<4;i++) { axis_steps_per_unit[i]=tmp1[i]; max_feedrate[i]=tmp2[i]; max_acceleration_units_per_sq_second[i]=tmp3[i]; } // steps per sq second need to be updated to agree with the units per sq second reset_acceleration_rates(); acceleration=DEFAULT_ACCELERATION; retract_acceleration=DEFAULT_RETRACT_ACCELERATION; minimumfeedrate=DEFAULT_MINIMUMFEEDRATE; minsegmenttime=DEFAULT_MINSEGMENTTIME; mintravelfeedrate=DEFAULT_MINTRAVELFEEDRATE; max_xy_jerk=DEFAULT_XYJERK; max_z_jerk=DEFAULT_ZJERK; max_e_jerk=DEFAULT_EJERK; add_homeing[0] = add_homeing[1] = add_homeing[2] = 0; #ifdef DELTA endstop_adj[0] = endstop_adj[1] = endstop_adj[2] = 0; #endif #ifdef ULTIPANEL plaPreheatHotendTemp = PLA_PREHEAT_HOTEND_TEMP; plaPreheatHPBTemp = PLA_PREHEAT_HPB_TEMP; plaPreheatFanSpeed = PLA_PREHEAT_FAN_SPEED; absPreheatHotendTemp = ABS_PREHEAT_HOTEND_TEMP; absPreheatHPBTemp = ABS_PREHEAT_HPB_TEMP; absPreheatFanSpeed = ABS_PREHEAT_FAN_SPEED; #endif #ifdef ENABLE_AUTO_BED_LEVELING zprobe_zoffset = -Z_PROBE_OFFSET_FROM_EXTRUDER; #endif #ifdef DOGLCD lcd_contrast = DEFAULT_LCD_CONTRAST; #endif #ifdef PIDTEMP Kp = DEFAULT_Kp; Ki = scalePID_i(DEFAULT_Ki); Kd = scalePID_d(DEFAULT_Kd); // call updatePID (similar to when we have processed M301) updatePID(); #ifdef PID_ADD_EXTRUSION_RATE Kc = DEFAULT_Kc; #endif//PID_ADD_EXTRUSION_RATE #endif//PIDTEMP SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Hardcoded Default Settings Loaded"); }
gpl-3.0
jlspyaozhongkai/Uter
third_party_backup/Python-2.7.9/PC/VS8.0/make_buildinfo.c
11
3241
#include <windows.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #define CMD_SIZE 500 /* This file creates the getbuildinfo.o object, by first invoking subwcrev.exe (if found), and then invoking cl.exe. As a side effect, it might generate PCBuild\getbuildinfo2.c also. If this isn't a subversion checkout, or subwcrev isn't found, it compiles ..\\..\\Modules\\getbuildinfo.c instead. Currently, subwcrev.exe is found from the registry entries of TortoiseSVN. No attempt is made to place getbuildinfo.o into the proper binary directory. This isn't necessary, as this tool is invoked as a pre-link step for pythoncore, so that overwrites any previous getbuildinfo.o. */ int make_buildinfo2() { struct _stat st; HKEY hTortoise; char command[CMD_SIZE+1]; DWORD type, size; if (_stat(".svn", &st) < 0) return 0; /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ if (_stat("no_subwcrev", &st) == 0) return 0; if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) /* Tortoise not installed */ return 0; command[0] = '"'; /* quote the path to the executable */ size = sizeof(command) - 1; if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || type != REG_SZ) /* Registry corrupted */ return 0; strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); if (_stat(command+1, &st) < 0) /* subwcrev.exe not part of the release */ return 0; strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); puts(command); fflush(stdout); if (system(command) < 0) return 0; return 1; } int main(int argc, char*argv[]) { char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; int do_unlink, result; if (argc != 2) { fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); return EXIT_FAILURE; } if (strcmp(argv[1], "Release") == 0) { strcat_s(command, CMD_SIZE, "-MD "); } else if (strcmp(argv[1], "Debug") == 0) { strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); } else if (strcmp(argv[1], "ReleaseItanium") == 0) { strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); } else if (strcmp(argv[1], "ReleaseAMD64") == 0) { strcat_s(command, CMD_SIZE, "-MD "); strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); } else { fprintf(stderr, "unsupported configuration %s\n", argv[1]); return EXIT_FAILURE; } if ((do_unlink = make_buildinfo2())) strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); else strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); puts(command); fflush(stdout); result = system(command); if (do_unlink) _unlink("getbuildinfo2.c"); if (result < 0) return EXIT_FAILURE; return 0; }
gpl-3.0
Matt07211/android_kernel_samsung_xcover3lte
drivers/media/usb/dvb-usb/dtt200u.c
4363
9648
/* DVB USB library compliant Linux driver for the WideView/ Yakumo/ Hama/ * Typhoon/ Yuan/ Miglia DVB-T USB2.0 receiver. * * Copyright (C) 2004-5 Patrick Boettcher (patrick.boettcher@desy.de) * * Thanks to Steve Chang from WideView for providing support for the WT-220U. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, version 2. * * see Documentation/dvb/README.dvb-usb for more information */ #include "dtt200u.h" /* debug */ int dvb_usb_dtt200u_debug; module_param_named(debug,dvb_usb_dtt200u_debug, int, 0644); MODULE_PARM_DESC(debug, "set debugging level (1=info,xfer=2 (or-able))." DVB_USB_DEBUG_STATUS); DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr); static int dtt200u_power_ctrl(struct dvb_usb_device *d, int onoff) { u8 b = SET_INIT; if (onoff) dvb_usb_generic_write(d,&b,2); return 0; } static int dtt200u_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff) { u8 b_streaming[2] = { SET_STREAMING, onoff }; u8 b_rst_pid = RESET_PID_FILTER; dvb_usb_generic_write(adap->dev, b_streaming, 2); if (onoff == 0) dvb_usb_generic_write(adap->dev, &b_rst_pid, 1); return 0; } static int dtt200u_pid_filter(struct dvb_usb_adapter *adap, int index, u16 pid, int onoff) { u8 b_pid[4]; pid = onoff ? pid : 0; b_pid[0] = SET_PID_FILTER; b_pid[1] = index; b_pid[2] = pid & 0xff; b_pid[3] = (pid >> 8) & 0x1f; return dvb_usb_generic_write(adap->dev, b_pid, 4); } /* remote control */ /* key list for the tiny remote control (Yakumo, don't know about the others) */ static struct rc_map_table rc_map_dtt200u_table[] = { { 0x8001, KEY_MUTE }, { 0x8002, KEY_CHANNELDOWN }, { 0x8003, KEY_VOLUMEDOWN }, { 0x8004, KEY_1 }, { 0x8005, KEY_2 }, { 0x8006, KEY_3 }, { 0x8007, KEY_4 }, { 0x8008, KEY_5 }, { 0x8009, KEY_6 }, { 0x800a, KEY_7 }, { 0x800c, KEY_ZOOM }, { 0x800d, KEY_0 }, { 0x800e, KEY_SELECT }, { 0x8012, KEY_POWER }, { 0x801a, KEY_CHANNELUP }, { 0x801b, KEY_8 }, { 0x801e, KEY_VOLUMEUP }, { 0x801f, KEY_9 }, }; static int dtt200u_rc_query(struct dvb_usb_device *d, u32 *event, int *state) { u8 key[5],cmd = GET_RC_CODE; dvb_usb_generic_rw(d,&cmd,1,key,5,0); dvb_usb_nec_rc_key_to_event(d,key,event,state); if (key[0] != 0) deb_info("key: %*ph\n", 5, key); return 0; } static int dtt200u_frontend_attach(struct dvb_usb_adapter *adap) { adap->fe_adap[0].fe = dtt200u_fe_attach(adap->dev); return 0; } static struct dvb_usb_device_properties dtt200u_properties; static struct dvb_usb_device_properties wt220u_fc_properties; static struct dvb_usb_device_properties wt220u_properties; static struct dvb_usb_device_properties wt220u_zl0353_properties; static struct dvb_usb_device_properties wt220u_miglia_properties; static int dtt200u_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { if (0 == dvb_usb_device_init(intf, &dtt200u_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &wt220u_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &wt220u_fc_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &wt220u_zl0353_properties, THIS_MODULE, NULL, adapter_nr) || 0 == dvb_usb_device_init(intf, &wt220u_miglia_properties, THIS_MODULE, NULL, adapter_nr)) return 0; return -ENODEV; } static struct usb_device_id dtt200u_usb_table [] = { { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_DTT200U_COLD) }, { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_DTT200U_WARM) }, { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_COLD) }, { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_WARM) }, { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_ZL0353_COLD) }, { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_ZL0353_WARM) }, { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_FC_COLD) }, { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_FC_WARM) }, { USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_ZAP250_COLD) }, { USB_DEVICE(USB_VID_MIGLIA, USB_PID_WT220U_ZAP250_COLD) }, { 0 }, }; MODULE_DEVICE_TABLE(usb, dtt200u_usb_table); static struct dvb_usb_device_properties dtt200u_properties = { .usb_ctrl = CYPRESS_FX2, .firmware = "dvb-usb-dtt200u-01.fw", .num_adapters = 1, .adapter = { { .num_frontends = 1, .fe = {{ .caps = DVB_USB_ADAP_HAS_PID_FILTER | DVB_USB_ADAP_NEED_PID_FILTERING, .pid_filter_count = 15, .streaming_ctrl = dtt200u_streaming_ctrl, .pid_filter = dtt200u_pid_filter, .frontend_attach = dtt200u_frontend_attach, /* parameter for the MPEG2-data transfer */ .stream = { .type = USB_BULK, .count = 7, .endpoint = 0x02, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .power_ctrl = dtt200u_power_ctrl, .rc.legacy = { .rc_interval = 300, .rc_map_table = rc_map_dtt200u_table, .rc_map_size = ARRAY_SIZE(rc_map_dtt200u_table), .rc_query = dtt200u_rc_query, }, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 1, .devices = { { .name = "WideView/Yuan/Yakumo/Hama/Typhoon DVB-T USB2.0 (WT-200U)", .cold_ids = { &dtt200u_usb_table[0], NULL }, .warm_ids = { &dtt200u_usb_table[1], NULL }, }, { NULL }, } }; static struct dvb_usb_device_properties wt220u_properties = { .usb_ctrl = CYPRESS_FX2, .firmware = "dvb-usb-wt220u-02.fw", .num_adapters = 1, .adapter = { { .num_frontends = 1, .fe = {{ .caps = DVB_USB_ADAP_HAS_PID_FILTER | DVB_USB_ADAP_NEED_PID_FILTERING, .pid_filter_count = 15, .streaming_ctrl = dtt200u_streaming_ctrl, .pid_filter = dtt200u_pid_filter, .frontend_attach = dtt200u_frontend_attach, /* parameter for the MPEG2-data transfer */ .stream = { .type = USB_BULK, .count = 7, .endpoint = 0x02, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .power_ctrl = dtt200u_power_ctrl, .rc.legacy = { .rc_interval = 300, .rc_map_table = rc_map_dtt200u_table, .rc_map_size = ARRAY_SIZE(rc_map_dtt200u_table), .rc_query = dtt200u_rc_query, }, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 1, .devices = { { .name = "WideView WT-220U PenType Receiver (Typhoon/Freecom)", .cold_ids = { &dtt200u_usb_table[2], &dtt200u_usb_table[8], NULL }, .warm_ids = { &dtt200u_usb_table[3], NULL }, }, { NULL }, } }; static struct dvb_usb_device_properties wt220u_fc_properties = { .usb_ctrl = CYPRESS_FX2, .firmware = "dvb-usb-wt220u-fc03.fw", .num_adapters = 1, .adapter = { { .num_frontends = 1, .fe = {{ .caps = DVB_USB_ADAP_HAS_PID_FILTER | DVB_USB_ADAP_NEED_PID_FILTERING, .pid_filter_count = 15, .streaming_ctrl = dtt200u_streaming_ctrl, .pid_filter = dtt200u_pid_filter, .frontend_attach = dtt200u_frontend_attach, /* parameter for the MPEG2-data transfer */ .stream = { .type = USB_BULK, .count = 7, .endpoint = 0x06, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .power_ctrl = dtt200u_power_ctrl, .rc.legacy = { .rc_interval = 300, .rc_map_table = rc_map_dtt200u_table, .rc_map_size = ARRAY_SIZE(rc_map_dtt200u_table), .rc_query = dtt200u_rc_query, }, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 1, .devices = { { .name = "WideView WT-220U PenType Receiver (Typhoon/Freecom)", .cold_ids = { &dtt200u_usb_table[6], NULL }, .warm_ids = { &dtt200u_usb_table[7], NULL }, }, { NULL }, } }; static struct dvb_usb_device_properties wt220u_zl0353_properties = { .usb_ctrl = CYPRESS_FX2, .firmware = "dvb-usb-wt220u-zl0353-01.fw", .num_adapters = 1, .adapter = { { .num_frontends = 1, .fe = {{ .caps = DVB_USB_ADAP_HAS_PID_FILTER | DVB_USB_ADAP_NEED_PID_FILTERING, .pid_filter_count = 15, .streaming_ctrl = dtt200u_streaming_ctrl, .pid_filter = dtt200u_pid_filter, .frontend_attach = dtt200u_frontend_attach, /* parameter for the MPEG2-data transfer */ .stream = { .type = USB_BULK, .count = 7, .endpoint = 0x02, .u = { .bulk = { .buffersize = 4096, } } }, }}, } }, .power_ctrl = dtt200u_power_ctrl, .rc.legacy = { .rc_interval = 300, .rc_map_table = rc_map_dtt200u_table, .rc_map_size = ARRAY_SIZE(rc_map_dtt200u_table), .rc_query = dtt200u_rc_query, }, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 1, .devices = { { .name = "WideView WT-220U PenType Receiver (based on ZL353)", .cold_ids = { &dtt200u_usb_table[4], NULL }, .warm_ids = { &dtt200u_usb_table[5], NULL }, }, { NULL }, } }; static struct dvb_usb_device_properties wt220u_miglia_properties = { .usb_ctrl = CYPRESS_FX2, .firmware = "dvb-usb-wt220u-miglia-01.fw", .num_adapters = 1, .generic_bulk_ctrl_endpoint = 0x01, .num_device_descs = 1, .devices = { { .name = "WideView WT-220U PenType Receiver (Miglia)", .cold_ids = { &dtt200u_usb_table[9], NULL }, /* This device turns into WT220U_ZL0353_WARM when fw has been uploaded */ .warm_ids = { NULL }, }, { NULL }, } }; /* usb specific object needed to register this driver with the usb subsystem */ static struct usb_driver dtt200u_usb_driver = { .name = "dvb_usb_dtt200u", .probe = dtt200u_usb_probe, .disconnect = dvb_usb_device_exit, .id_table = dtt200u_usb_table, }; module_usb_driver(dtt200u_usb_driver); MODULE_AUTHOR("Patrick Boettcher <patrick.boettcher@desy.de>"); MODULE_DESCRIPTION("Driver for the WideView/Yakumo/Hama/Typhoon/Club3D/Miglia DVB-T USB2.0 devices"); MODULE_VERSION("1.0"); MODULE_LICENSE("GPL");
gpl-3.0
AMDmi3/pingus
external/tinygettext/tinygettext/iconv.cpp
12
4073
// tinygettext - A gettext replacement that works directly on .po files // Copyright (C) 2009 Ingo Ruhnke <grumbel@gmx.de> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include <ctype.h> #include <assert.h> #include <sstream> #include <errno.h> #include <stdexcept> #include <string.h> #include <stdlib.h> #include "iconv.hpp" #include "log_stream.hpp" namespace tinygettext { #ifndef tinygettext_ICONV_CONST # define tinygettext_ICONV_CONST #endif IConv::IConv() : to_charset(), from_charset(), cd(0) {} IConv::IConv(const std::string& from_charset_, const std::string& to_charset_) : to_charset(), from_charset(), cd(0) { set_charsets(from_charset_, to_charset_); } IConv::~IConv() { if (cd) tinygettext_iconv_close(cd); } void IConv::set_charsets(const std::string& from_charset_, const std::string& to_charset_) { if (cd) tinygettext_iconv_close(cd); from_charset = from_charset_; to_charset = to_charset_; for(std::string::iterator i = to_charset.begin(); i != to_charset.end(); ++i) *i = static_cast<char>(toupper(*i)); for(std::string::iterator i = from_charset.begin(); i != from_charset.end(); ++i) *i = static_cast<char>(toupper(*i)); if (to_charset == from_charset) { cd = 0; } else { cd = tinygettext_iconv_open(to_charset.c_str(), from_charset.c_str()); if (cd == reinterpret_cast<tinygettext_iconv_t>(-1)) { if(errno == EINVAL) { std::ostringstream str; str << "IConv construction failed: conversion from '" << from_charset << "' to '" << to_charset << "' not available"; throw std::runtime_error(str.str()); } else { std::ostringstream str; str << "IConv: construction failed: " << strerror(errno); throw std::runtime_error(str.str()); } } } } /// Convert a string from encoding to another. std::string IConv::convert(const std::string& text) { if (!cd) { return text; } else { size_t inbytesleft = text.size(); size_t outbytesleft = 4*inbytesleft; // Worst case scenario: ASCII -> UTF-32? // We try to avoid to much copying around, so we write directly into // a std::string tinygettext_ICONV_CONST char* inbuf = const_cast<char*>(&text[0]); std::string result(outbytesleft, 'X'); char* outbuf = &result[0]; // Try to convert the text. size_t ret = tinygettext_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft); if (ret == static_cast<size_t>(-1)) { if (errno == EILSEQ || errno == EINVAL) { // invalid multibyte sequence tinygettext_iconv(cd, NULL, NULL, NULL, NULL); // reset state // FIXME: Could try to skip the invalid byte and continue log_error << "error: tinygettext:iconv: invalid multibyte sequence in: \"" << text << "\"" << std::endl; } else if (errno == E2BIG) { // output buffer to small assert(!"tinygettext/iconv.cpp: E2BIG: This should never be reached"); } else if (errno == EBADF) { assert(!"tinygettext/iconv.cpp: EBADF: This should never be reached"); } else { assert(!"tinygettext/iconv.cpp: <unknown>: This should never be reached"); } } result.resize(4*text.size() - outbytesleft); return result; } } } // namespace tinygettext /* EOF */
gpl-3.0
msrb/freeipa
asn1/asn1c/INTEGER.c
12
20381
/*- * Copyright (c) 2003, 2004, 2005, 2006 Lev Walkin <vlm@lionet.info>. * All rights reserved. * Redistribution and modifications are permitted subject to BSD license. */ #include <asn_internal.h> #include <INTEGER.h> #include <asn_codecs_prim.h> /* Encoder and decoder of a primitive type */ #include <errno.h> /* * INTEGER basic type description. */ static ber_tlv_tag_t asn_DEF_INTEGER_tags[] = { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) }; asn_TYPE_descriptor_t asn_DEF_INTEGER = { "INTEGER", "INTEGER", ASN__PRIMITIVE_TYPE_free, INTEGER_print, asn_generic_no_constraint, ber_decode_primitive, INTEGER_encode_der, INTEGER_decode_xer, INTEGER_encode_xer, INTEGER_decode_uper, /* Unaligned PER decoder */ INTEGER_encode_uper, /* Unaligned PER encoder */ 0, /* Use generic outmost tag fetcher */ asn_DEF_INTEGER_tags, sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]), asn_DEF_INTEGER_tags, /* Same as above */ sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]), 0, /* No PER visible constraints */ 0, 0, /* No members */ 0 /* No specifics */ }; /* * Encode INTEGER type using DER. */ asn_enc_rval_t INTEGER_encode_der(asn_TYPE_descriptor_t *td, void *sptr, int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb, void *app_key) { INTEGER_t *st = (INTEGER_t *)sptr; ASN_DEBUG("%s %s as INTEGER (tm=%d)", cb?"Encoding":"Estimating", td->name, tag_mode); /* * Canonicalize integer in the buffer. * (Remove too long sign extension, remove some first 0x00 bytes) */ if(st->buf) { uint8_t *buf = st->buf; uint8_t *end1 = buf + st->size - 1; int shift; /* Compute the number of superfluous leading bytes */ for(; buf < end1; buf++) { /* * If the contents octets of an integer value encoding * consist of more than one octet, then the bits of the * first octet and bit 8 of the second octet: * a) shall not all be ones; and * b) shall not all be zero. */ switch(*buf) { case 0x00: if((buf[1] & 0x80) == 0) continue; break; case 0xff: if((buf[1] & 0x80)) continue; break; } break; } /* Remove leading superfluous bytes from the integer */ shift = buf - st->buf; if(shift) { uint8_t *nb = st->buf; uint8_t *end; st->size -= shift; /* New size, minus bad bytes */ end = nb + st->size; for(; nb < end; nb++, buf++) *nb = *buf; } } /* if(1) */ return der_encode_primitive(td, sptr, tag_mode, tag, cb, app_key); } static const asn_INTEGER_enum_map_t *INTEGER_map_enum2value(asn_INTEGER_specifics_t *specs, const char *lstart, const char *lstop); /* * INTEGER specific human-readable output. */ static ssize_t INTEGER__dump(asn_TYPE_descriptor_t *td, const INTEGER_t *st, asn_app_consume_bytes_f *cb, void *app_key, int plainOrXER) { asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics; char scratch[32]; /* Enough for 64-bit integer */ uint8_t *buf = st->buf; uint8_t *buf_end = st->buf + st->size; signed long accum; ssize_t wrote = 0; char *p; int ret; /* * Advance buf pointer until the start of the value's body. * This will make us able to process large integers using simple case, * when the actual value is small * (0x0000000000abcdef would yield a fine 0x00abcdef) */ /* Skip the insignificant leading bytes */ for(; buf < buf_end-1; buf++) { switch(*buf) { case 0x00: if((buf[1] & 0x80) == 0) continue; break; case 0xff: if((buf[1] & 0x80) != 0) continue; break; } break; } /* Simple case: the integer size is small */ if((size_t)(buf_end - buf) <= sizeof(accum)) { const asn_INTEGER_enum_map_t *el; size_t scrsize; char *scr; if(buf == buf_end) { accum = 0; } else { accum = (*buf & 0x80) ? -1 : 0; for(; buf < buf_end; buf++) accum = (accum << 8) | *buf; } el = INTEGER_map_value2enum(specs, accum); if(el) { scrsize = el->enum_len + 32; scr = (char *)alloca(scrsize); if(plainOrXER == 0) ret = snprintf(scr, scrsize, "%ld (%s)", accum, el->enum_name); else ret = snprintf(scr, scrsize, "<%s/>", el->enum_name); } else if(plainOrXER && specs && specs->strict_enumeration) { ASN_DEBUG("ASN.1 forbids dealing with " "unknown value of ENUMERATED type"); errno = EPERM; return -1; } else { scrsize = sizeof(scratch); scr = scratch; ret = snprintf(scr, scrsize, "%ld", accum); } assert(ret > 0 && (size_t)ret < scrsize); return (cb(scr, ret, app_key) < 0) ? -1 : ret; } else if(plainOrXER && specs && specs->strict_enumeration) { /* * Here and earlier, we cannot encode the ENUMERATED values * if there is no corresponding identifier. */ ASN_DEBUG("ASN.1 forbids dealing with " "unknown value of ENUMERATED type"); errno = EPERM; return -1; } /* Output in the long xx:yy:zz... format */ /* TODO: replace with generic algorithm (Knuth TAOCP Vol 2, 4.3.1) */ for(p = scratch; buf < buf_end; buf++) { static const char *h2c = "0123456789ABCDEF"; if((p - scratch) >= (ssize_t)(sizeof(scratch) - 4)) { /* Flush buffer */ if(cb(scratch, p - scratch, app_key) < 0) return -1; wrote += p - scratch; p = scratch; } *p++ = h2c[*buf >> 4]; *p++ = h2c[*buf & 0x0F]; *p++ = 0x3a; /* ":" */ } if(p != scratch) p--; /* Remove the last ":" */ wrote += p - scratch; return (cb(scratch, p - scratch, app_key) < 0) ? -1 : wrote; } /* * INTEGER specific human-readable output. */ int INTEGER_print(asn_TYPE_descriptor_t *td, const void *sptr, int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { const INTEGER_t *st = (const INTEGER_t *)sptr; ssize_t ret; (void)td; (void)ilevel; if(!st || !st->buf) ret = cb("<absent>", 8, app_key); else ret = INTEGER__dump(td, st, cb, app_key, 0); return (ret < 0) ? -1 : 0; } struct e2v_key { const char *start; const char *stop; asn_INTEGER_enum_map_t *vemap; unsigned int *evmap; }; static int INTEGER__compar_enum2value(const void *kp, const void *am) { const struct e2v_key *key = (const struct e2v_key *)kp; const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am; const char *ptr, *end, *name; /* Remap the element (sort by different criterion) */ el = key->vemap + key->evmap[el - key->vemap]; /* Compare strings */ for(ptr = key->start, end = key->stop, name = el->enum_name; ptr < end; ptr++, name++) { if(*ptr != *name) return *(const unsigned char *)ptr - *(const unsigned char *)name; } return name[0] ? -1 : 0; } static const asn_INTEGER_enum_map_t * INTEGER_map_enum2value(asn_INTEGER_specifics_t *specs, const char *lstart, const char *lstop) { asn_INTEGER_enum_map_t *el_found; int count = specs ? specs->map_count : 0; struct e2v_key key; const char *lp; if(!count) return NULL; /* Guaranteed: assert(lstart < lstop); */ /* Figure out the tag name */ for(lstart++, lp = lstart; lp < lstop; lp++) { switch(*lp) { case 9: case 10: case 11: case 12: case 13: case 32: /* WSP */ case 0x2f: /* '/' */ case 0x3e: /* '>' */ break; default: continue; } break; } if(lp == lstop) return NULL; /* No tag found */ lstop = lp; key.start = lstart; key.stop = lstop; key.vemap = specs->value2enum; key.evmap = specs->enum2value; el_found = (asn_INTEGER_enum_map_t *)bsearch(&key, specs->value2enum, count, sizeof(specs->value2enum[0]), INTEGER__compar_enum2value); if(el_found) { /* Remap enum2value into value2enum */ el_found = key.vemap + key.evmap[el_found - key.vemap]; } return el_found; } static int INTEGER__compar_value2enum(const void *kp, const void *am) { long a = *(const long *)kp; const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am; long b = el->nat_value; if(a < b) return -1; else if(a == b) return 0; else return 1; } const asn_INTEGER_enum_map_t * INTEGER_map_value2enum(asn_INTEGER_specifics_t *specs, long value) { int count = specs ? specs->map_count : 0; if(!count) return 0; return (asn_INTEGER_enum_map_t *)bsearch(&value, specs->value2enum, count, sizeof(specs->value2enum[0]), INTEGER__compar_value2enum); } static int INTEGER_st_prealloc(INTEGER_t *st, int min_size) { void *p = MALLOC(min_size + 1); if(p) { void *b = st->buf; st->size = 0; st->buf = p; FREEMEM(b); return 0; } else { return -1; } } /* * Decode the chunk of XML text encoding INTEGER. */ static enum xer_pbd_rval INTEGER__xer_body_decode(asn_TYPE_descriptor_t *td, void *sptr, const void *chunk_buf, size_t chunk_size) { INTEGER_t *st = (INTEGER_t *)sptr; long sign = 1; long value; const char *lp; const char *lstart = (const char *)chunk_buf; const char *lstop = lstart + chunk_size; enum { ST_SKIPSPACE, ST_SKIPSPHEX, ST_WAITDIGITS, ST_DIGITS, ST_HEXDIGIT1, ST_HEXDIGIT2, ST_HEXCOLON, ST_EXTRASTUFF } state = ST_SKIPSPACE; if(chunk_size) ASN_DEBUG("INTEGER body %d 0x%2x..0x%2x", chunk_size, *lstart, lstop[-1]); /* * We may have received a tag here. It will be processed inline. * Use strtoul()-like code and serialize the result. */ for(value = 0, lp = lstart; lp < lstop; lp++) { int lv = *lp; switch(lv) { case 0x09: case 0x0a: case 0x0d: case 0x20: switch(state) { case ST_SKIPSPACE: case ST_SKIPSPHEX: continue; case ST_HEXCOLON: if(xer_is_whitespace(lp, lstop - lp)) { lp = lstop - 1; continue; } break; default: break; } break; case 0x2d: /* '-' */ if(state == ST_SKIPSPACE) { sign = -1; state = ST_WAITDIGITS; continue; } break; case 0x2b: /* '+' */ if(state == ST_SKIPSPACE) { state = ST_WAITDIGITS; continue; } break; case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: switch(state) { case ST_DIGITS: break; case ST_SKIPSPHEX: /* Fall through */ case ST_HEXDIGIT1: value = (lv - 0x30) << 4; state = ST_HEXDIGIT2; continue; case ST_HEXDIGIT2: value += (lv - 0x30); state = ST_HEXCOLON; st->buf[st->size++] = value; continue; case ST_HEXCOLON: return XPBD_BROKEN_ENCODING; default: state = ST_DIGITS; break; } { long new_value = value * 10; if(new_value / 10 != value) /* Overflow */ return XPBD_DECODER_LIMIT; value = new_value + (lv - 0x30); /* Check for two's complement overflow */ if(value < 0) { /* Check whether it is a LONG_MIN */ if(sign == -1 && (unsigned long)value == ~((unsigned long)-1 >> 1)) { sign = 1; } else { /* Overflow */ return XPBD_DECODER_LIMIT; } } } continue; case 0x3c: /* '<' */ if(state == ST_SKIPSPACE) { const asn_INTEGER_enum_map_t *el; el = INTEGER_map_enum2value( (asn_INTEGER_specifics_t *) td->specifics, lstart, lstop); if(el) { ASN_DEBUG("Found \"%s\" => %ld", el->enum_name, el->nat_value); state = ST_DIGITS; value = el->nat_value; lp = lstop - 1; continue; } ASN_DEBUG("Unknown identifier for INTEGER"); } return XPBD_BROKEN_ENCODING; case 0x3a: /* ':' */ if(state == ST_HEXCOLON) { /* This colon is expected */ state = ST_HEXDIGIT1; continue; } else if(state == ST_DIGITS) { /* The colon here means that we have * decoded the first two hexadecimal * places as a decimal value. * Switch decoding mode. */ ASN_DEBUG("INTEGER re-evaluate as hex form"); if(INTEGER_st_prealloc(st, (chunk_size/3) + 1)) return XPBD_SYSTEM_FAILURE; state = ST_SKIPSPHEX; lp = lstart - 1; continue; } else { ASN_DEBUG("state %d at %d", state, lp - lstart); break; } /* [A-Fa-f] */ case 0x41:case 0x42:case 0x43:case 0x44:case 0x45:case 0x46: case 0x61:case 0x62:case 0x63:case 0x64:case 0x65:case 0x66: switch(state) { case ST_SKIPSPHEX: case ST_SKIPSPACE: /* Fall through */ case ST_HEXDIGIT1: value = lv - ((lv < 0x61) ? 0x41 : 0x61); value += 10; value <<= 4; state = ST_HEXDIGIT2; continue; case ST_HEXDIGIT2: value += lv - ((lv < 0x61) ? 0x41 : 0x61); value += 10; st->buf[st->size++] = value; state = ST_HEXCOLON; continue; case ST_DIGITS: ASN_DEBUG("INTEGER re-evaluate as hex form"); if(INTEGER_st_prealloc(st, (chunk_size/3) + 1)) return XPBD_SYSTEM_FAILURE; state = ST_SKIPSPHEX; lp = lstart - 1; continue; default: break; } break; } /* Found extra non-numeric stuff */ ASN_DEBUG("Found non-numeric 0x%2x at %d", lv, lp - lstart); state = ST_EXTRASTUFF; break; } switch(state) { case ST_DIGITS: /* Everything is cool */ break; case ST_HEXCOLON: st->buf[st->size] = 0; /* Just in case termination */ return XPBD_BODY_CONSUMED; case ST_HEXDIGIT1: case ST_HEXDIGIT2: case ST_SKIPSPHEX: return XPBD_BROKEN_ENCODING; default: if(xer_is_whitespace(lp, lstop - lp)) { if(state != ST_EXTRASTUFF) return XPBD_NOT_BODY_IGNORE; break; } else { ASN_DEBUG("INTEGER: No useful digits (state %d)", state); return XPBD_BROKEN_ENCODING; /* No digits */ } break; } value *= sign; /* Change sign, if needed */ if(asn_long2INTEGER(st, value)) return XPBD_SYSTEM_FAILURE; return XPBD_BODY_CONSUMED; } asn_dec_rval_t INTEGER_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **sptr, const char *opt_mname, const void *buf_ptr, size_t size) { return xer_decode_primitive(opt_codec_ctx, td, sptr, sizeof(INTEGER_t), opt_mname, buf_ptr, size, INTEGER__xer_body_decode); } asn_enc_rval_t INTEGER_encode_xer(asn_TYPE_descriptor_t *td, void *sptr, int ilevel, enum xer_encoder_flags_e flags, asn_app_consume_bytes_f *cb, void *app_key) { const INTEGER_t *st = (const INTEGER_t *)sptr; asn_enc_rval_t er; (void)ilevel; (void)flags; if(!st || !st->buf) _ASN_ENCODE_FAILED; er.encoded = INTEGER__dump(td, st, cb, app_key, 1); if(er.encoded < 0) _ASN_ENCODE_FAILED; _ASN_ENCODED_OK(er); } asn_dec_rval_t INTEGER_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) { asn_dec_rval_t rval = { RC_OK, 0 }; INTEGER_t *st = (INTEGER_t *)*sptr; asn_per_constraint_t *ct; int repeat; (void)opt_codec_ctx; if(!st) { st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st))); if(!st) _ASN_DECODE_FAILED; } if(!constraints) constraints = td->per_constraints; ct = constraints ? &constraints->value : 0; if(ct && ct->flags & APC_EXTENSIBLE) { int inext = per_get_few_bits(pd, 1); if(inext < 0) _ASN_DECODE_STARVED; if(inext) ct = 0; } FREEMEM(st->buf); if(ct) { if(ct->flags & APC_SEMI_CONSTRAINED) { st->buf = (uint8_t *)CALLOC(1, 2); if(!st->buf) _ASN_DECODE_FAILED; st->size = 1; } else if(ct->flags & APC_CONSTRAINED && ct->range_bits >= 0) { size_t size = (ct->range_bits + 7) >> 3; st->buf = (uint8_t *)MALLOC(1 + size + 1); if(!st->buf) _ASN_DECODE_FAILED; st->size = size; } else { st->size = 0; } } else { st->size = 0; } /* X.691, #12.2.2 */ if(ct && ct->flags != APC_UNCONSTRAINED) { /* #10.5.6 */ ASN_DEBUG("Integer with range %d bits", ct->range_bits); if(ct->range_bits >= 0) { long value = per_get_few_bits(pd, ct->range_bits); if(value < 0) _ASN_DECODE_STARVED; ASN_DEBUG("Got value %ld + low %ld", value, ct->lower_bound); value += ct->lower_bound; if(asn_long2INTEGER(st, value)) _ASN_DECODE_FAILED; return rval; } } else { ASN_DEBUG("Decoding unconstrained integer %s", td->name); } /* X.691, #12.2.3, #12.2.4 */ do { ssize_t len; void *p; int ret; /* Get the PER length */ len = uper_get_length(pd, -1, &repeat); if(len < 0) _ASN_DECODE_STARVED; p = REALLOC(st->buf, st->size + len + 1); if(!p) _ASN_DECODE_FAILED; st->buf = (uint8_t *)p; ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len); if(ret < 0) _ASN_DECODE_STARVED; st->size += len; } while(repeat); st->buf[st->size] = 0; /* JIC */ /* #12.2.3 */ if(ct && ct->lower_bound) { /* * TODO: replace by in-place arithmetics. */ long value; if(asn_INTEGER2long(st, &value)) _ASN_DECODE_FAILED; if(asn_long2INTEGER(st, value + ct->lower_bound)) _ASN_DECODE_FAILED; } return rval; } asn_enc_rval_t INTEGER_encode_uper(asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) { asn_enc_rval_t er; INTEGER_t *st = (INTEGER_t *)sptr; const uint8_t *buf; const uint8_t *end; asn_per_constraint_t *ct; long value = 0; if(!st || st->size == 0) _ASN_ENCODE_FAILED; if(!constraints) constraints = td->per_constraints; ct = constraints ? &constraints->value : 0; er.encoded = 0; if(ct) { int inext = 0; if(asn_INTEGER2long(st, &value)) _ASN_ENCODE_FAILED; /* Check proper range */ if(ct->flags & APC_SEMI_CONSTRAINED) { if(value < ct->lower_bound) inext = 1; } else if(ct->range_bits >= 0) { if(value < ct->lower_bound || value > ct->upper_bound) inext = 1; } ASN_DEBUG("Value %ld (%02x/%d) lb %ld ub %ld %s", value, st->buf[0], st->size, ct->lower_bound, ct->upper_bound, inext ? "ext" : "fix"); if(ct->flags & APC_EXTENSIBLE) { if(per_put_few_bits(po, inext, 1)) _ASN_ENCODE_FAILED; if(inext) ct = 0; } else if(inext) { _ASN_ENCODE_FAILED; } } /* X.691, #12.2.2 */ if(ct && ct->range_bits >= 0) { /* #10.5.6 */ ASN_DEBUG("Encoding integer with range %d bits", ct->range_bits); if(per_put_few_bits(po, value - ct->lower_bound, ct->range_bits)) _ASN_ENCODE_FAILED; _ASN_ENCODED_OK(er); } if(ct && ct->lower_bound) { ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound); /* TODO: adjust lower bound */ _ASN_ENCODE_FAILED; } for(buf = st->buf, end = st->buf + st->size; buf < end;) { ssize_t mayEncode = uper_put_length(po, end - buf); if(mayEncode < 0) _ASN_ENCODE_FAILED; if(per_put_many_bits(po, buf, 8 * mayEncode)) _ASN_ENCODE_FAILED; buf += mayEncode; } _ASN_ENCODED_OK(er); } int asn_INTEGER2long(const INTEGER_t *iptr, long *lptr) { uint8_t *b, *end; size_t size; long l; /* Sanity checking */ if(!iptr || !iptr->buf || !lptr) { errno = EINVAL; return -1; } /* Cache the begin/end of the buffer */ b = iptr->buf; /* Start of the INTEGER buffer */ size = iptr->size; end = b + size; /* Where to stop */ if(size > sizeof(long)) { uint8_t *end1 = end - 1; /* * Slightly more advanced processing, * able to >sizeof(long) bytes, * when the actual value is small * (0x0000000000abcdef would yield a fine 0x00abcdef) */ /* Skip out the insignificant leading bytes */ for(; b < end1; b++) { switch(*b) { case 0x00: if((b[1] & 0x80) == 0) continue; break; case 0xff: if((b[1] & 0x80) != 0) continue; break; } break; } size = end - b; if(size > sizeof(long)) { /* Still cannot fit the long */ errno = ERANGE; return -1; } } /* Shortcut processing of a corner case */ if(end == b) { *lptr = 0; return 0; } /* Perform the sign initialization */ /* Actually l = -(*b >> 7); gains nothing, yet unreadable! */ if((*b >> 7)) l = -1; else l = 0; /* Conversion engine */ for(; b < end; b++) l = (l << 8) | *b; *lptr = l; return 0; } int asn_long2INTEGER(INTEGER_t *st, long value) { uint8_t *buf, *bp; uint8_t *p; uint8_t *pstart; uint8_t *pend1; int littleEndian = 1; /* Run-time detection */ int add; if(!st) { errno = EINVAL; return -1; } buf = (uint8_t *)MALLOC(sizeof(value)); if(!buf) return -1; if(*(char *)&littleEndian) { pstart = (uint8_t *)&value + sizeof(value) - 1; pend1 = (uint8_t *)&value; add = -1; } else { pstart = (uint8_t *)&value; pend1 = pstart + sizeof(value) - 1; add = 1; } /* * If the contents octet consists of more than one octet, * then bits of the first octet and bit 8 of the second octet: * a) shall not all be ones; and * b) shall not all be zero. */ for(p = pstart; p != pend1; p += add) { switch(*p) { case 0x00: if((*(p+add) & 0x80) == 0) continue; break; case 0xff: if((*(p+add) & 0x80)) continue; break; } break; } /* Copy the integer body */ for(pstart = p, bp = buf, pend1 += add; p != pend1; p += add) *bp++ = *p; if(st->buf) FREEMEM(st->buf); st->buf = buf; st->size = bp - buf; return 0; }
gpl-3.0
yonahbox/ardupilot
libraries/AP_HAL_F4Light/RC_NRF_parser.cpp
13
19215
/* (c) 2017 night_ghost@ykoctpa.ru based on: BetaFlight NRF driver */ #include <exti.h> #include <timer.h> #include "RCInput.h" #include <pwm_in.h> #include <AP_HAL/utility/dsm.h> #include "sbus.h" #include "GPIO.h" #include "ring_buffer_pulse.h" #include "RC_NRF_parser.h" using namespace F4Light; extern const AP_HAL::HAL& hal; #if defined(BOARD_NRF_CS_PIN) && defined(BOARD_NRF_NAME) static uint8_t NRF_Buffer[NRF_MAX_PAYLOAD_SIZE]; static uint8_t ackPayload[NRF24L01_MAX_PAYLOAD_SIZE]; NRF_parser::uint8_t rxTxAddr[RX_TX_ADDR_LEN] = {0x4b,0x5c,0x6d,0x7e,0x8f}; static const uint8_t inavRfChannelHoppingCount = INAV_RF_CHANNEL_HOPPING_COUNT_DEFAULT; static uint8_t inavRfChannelCount; static uint8_t inavRfChannelIndex; static uint8_t inavRfChannels[INAV_RF_CHANNEL_COUNT_MAX]; void NRF_parser::init(uint8_t ch){ memset((void *)&val[0], 0, sizeof(val)); _last_signal=0; _last_change =0; GPIO::_pinMode(BOARD_NRF24_CS_PIN, OUTPUT); GPIO::_write(BOARD_NRF24_CS_PIN, 1); nrf = hal.spi->get_device(BOARD_NRF_NAME); nrf->register_periodic_callback(FUNCTOR_BIND_MEMBER(&NRF_parser::_timer, bool), 100); } void NRF_parser::_timer() { uint32_t timeNowUs; switch (protocolState) { case STATE_BIND: if (NRF24L01_ReadPayloadIfAvailable(NRF_Buffer, NRF_MAX_PAYLOAD_SIZE)) { whitenPayload(NRF_Buffer, NRF_MAX_PAYLOAD_SIZE); const bool bindPacket = checkBindPacket(NRF_Buffer); if (bindPacket) { state = RX_SPI_RECEIVED_BIND; writeBindAckPayload(NRF_Buffer); // got a bind packet, so set the hopping channels and the rxTxAddr and start listening for data inavSetBound(); } } break; case STATE_DATA: timeNowUs = micros(); // read the payload, processing of payload is deferred if (NRF24L01_ReadPayloadIfAvailable(NRF_Buffer, NRF_MAX_PAYLOAD_SIZE)) { whitenPayload(NRF_Buffer, NRF_MAX_PAYLOAD_SIZE); receivedPowerSnapshot = NRF24L01_ReadReg(NRF24L01_09_RPD); // set to 1 if received power > -64dBm const bool bindPacket = checkBindPacket(NRF_Buffer); if (bindPacket) { // transmitter may still continue to transmit bind packets after we have switched to data mode state = RX_SPI_RECEIVED_BIND; writeBindAckPayload(NRF_Buffer); } else { state = RX_SPI_RECEIVED_DATA; writeTelemetryAckPayload(); } } if ((state == RX_SPI_RECEIVED_DATA) || (timeNowUs > timeOfLastHop + hopTimeout)) { inavHopToNextChannel(); timeOfLastHop = timeNowUs; } break; } } bool NRF_parser::checkBindPacket(const uint8_t *payload) { bool bindPacket = false; if (payload[0] == BIND_PAYLOAD0 && payload[1] == BIND_PAYLOAD1) { bindPacket = true; if (protocolState ==STATE_BIND) { rxTxAddr[0] = payload[2]; rxTxAddr[1] = payload[3]; rxTxAddr[2] = payload[4]; rxTxAddr[3] = payload[5]; rxTxAddr[4] = payload[6]; /*inavRfChannelHoppingCount = payload[7]; // !!TODO not yet implemented on transmitter if (inavRfChannelHoppingCount > INAV_RF_CHANNEL_COUNT_MAX) { inavRfChannelHoppingCount = INAV_RF_CHANNEL_COUNT_MAX; }*/ if (fixedIdPtr != NULL && *fixedIdPtr == 0) { // copy the rxTxAddr so it can be saved memcpy(fixedIdPtr, rxTxAddr, sizeof(uint32_t)); } } } return bindPacket; } void NRF_parser::whitenPayload(uint8_t *payload, uint8_t len) { #ifdef USE_WHITENING uint8_t whitenCoeff = 0x6b; // 01101011 while (len--) { for (uint8_t m = 1; m; m <<= 1) { if (whitenCoeff & 0x80) { whitenCoeff ^= 0x11; (*payload) ^= m; } whitenCoeff <<= 1; } payload++; } #else UNUSED(payload); UNUSED(len); #endif } void NRF_parser::inavSetBound(void) { protocolState = STATE_DATA; NRF24L01_WriteRegisterMulti(NRF24L01_0A_RX_ADDR_P0, rxTxAddr, RX_TX_ADDR_LEN); NRF24L01_WriteRegisterMulti(NRF24L01_10_TX_ADDR, rxTxAddr, RX_TX_ADDR_LEN); timeOfLastHop = micros(); inavRfChannelIndex = 0; inavSetHoppingChannels(); NRF24L01_SetChannel(inavRfChannels[0]); #ifdef DEBUG_NRF24_INAV debug[0] = inavRfChannels[inavRfChannelIndex]; #endif } void NRF_parser::writeAckPayload(uint8_t *data, uint8_t length) { whitenPayload(data, length); NRF24L01_WriteReg(NRF24L01_07_STATUS, BV(NRF24L01_07_STATUS_MAX_RT)); NRF24L01_WriteAckPayload(data, length, NRF24L01_PIPE0); } void NRF_parser::writeTelemetryAckPayload(void) { #ifdef TELEMETRY_NRF24_LTM // set up telemetry data, send back telemetry data in the ACK packet static uint8_t sequenceNumber = 0; static ltm_frame_e ltmFrameType = LTM_FRAME_START; ackPayload[0] = TELEMETRY_ACK_PAYLOAD0; ackPayload[1] = sequenceNumber++; const int ackPayloadSize = getLtmFrame(&ackPayload[2], ltmFrameType) + 2; ++ltmFrameType; if (ltmFrameType > LTM_FRAME_COUNT) { ltmFrameType = LTM_FRAME_START; } writeAckPayload(ackPayload, ackPayloadSize); #ifdef DEBUG_NRF24_INAV debug[1] = ackPayload[1]; // sequenceNumber debug[2] = ackPayload[2]; // frame type, 'A', 'S' etc debug[3] = ackPayload[3]; // pitch for AFrame #endif #endif } void NRF_parser::writeBindAckPayload(uint8_t *payload) { #ifdef USE_AUTO_ACKKNOWLEDGEMENT memcpy(ackPayload, payload, BIND_PAYLOAD_SIZE); // send back the payload with the first two bytes set to zero as the ack ackPayload[0] = BIND_ACK_PAYLOAD0; ackPayload[1] = BIND_ACK_PAYLOAD1; // respond to request for rfChannelCount; ackPayload[7] = inavRfChannelHoppingCount; // respond to request for payloadSize switch (payloadSize) { case INAV_PROTOCOL_PAYLOAD_SIZE_MIN: case INAV_PROTOCOL_PAYLOAD_SIZE_DEFAULT: case INAV_PROTOCOL_PAYLOAD_SIZE_MAX: ackPayload[8] = payloadSize; break; default: ackPayload[8] = INAV_PROTOCOL_PAYLOAD_SIZE_DEFAULT; break; } writeAckPayload(ackPayload, BIND_PAYLOAD_SIZE); #else UNUSED(payload); #endif } void NRF_parser::inavHopToNextChannel(void) { ++inavRfChannelIndex; if (inavRfChannelIndex >= inavRfChannelCount) { inavRfChannelIndex = 0; } NRF24L01_SetChannel(inavRfChannels[inavRfChannelIndex]); #ifdef DEBUG_NRF24_INAV debug[0] = inavRfChannels[inavRfChannelIndex]; #endif } // The hopping channels are determined by the low bits of rxTxAddr void NRF_parser::inavSetHoppingChannels(void) { #ifdef NO_RF_CHANNEL_HOPPING // just stay on bind channel, useful for debugging inavRfChannelCount = 1; inavRfChannels[0] = INAV_RF_BIND_CHANNEL; #else inavRfChannelCount = inavRfChannelHoppingCount; const uint8_t addr = rxTxAddr[0]; uint8_t ch = 0x10 + (addr & 0x07); for (int ii = 0; ii < INAV_RF_CHANNEL_COUNT_MAX; ++ii) { inavRfChannels[ii] = ch; ch += 0x0c; } #endif } void NRF_parser::set_val(uint8_t ch, uint16_t val){ if(_val[ch] != val) { _val[ch] = val; _last_change = systick_uptime(); } } void NRF_parser::inavNrf24SetRcDataFromPayload(uint16_t *rcData, const uint8_t *payload) { memset(_val, 0, sizeof(_val)); // payload[0] and payload[1] are zero in DATA state // the AETR channels have 10 bit resolution uint8_t lowBits = payload[6]; // least significant bits for AETR set_val(RC_SPI_ROLL, PWM_RANGE_MIN + ((payload[2] << 2) | (lowBits & 0x03)) ); // Aileron lowBits >>= 2; set_val(RC_SPI_PITCH, PWM_RANGE_MIN + ((payload[3] << 2) | (lowBits & 0x03)) ); // Elevator lowBits >>= 2; set_val(RC_SPI_THROTTLE, PWM_RANGE_MIN + ((payload[4] << 2) | (lowBits & 0x03)) ); // Throttle lowBits >>= 2; set_val(RC_SPI_YAW, PWM_RANGE_MIN + ((payload[5] << 2) | (lowBits & 0x03)) ); // Rudder if (payloadSize == INAV_PROTOCOL_PAYLOAD_SIZE_MIN) { // small payload variant of protocol, supports 6 channels set_val(RC_SPI_AUX1, PWM_RANGE_MIN + (payload[7] << 2) ); set_val(RC_SPI_AUX2, PWM_RANGE_MIN + (payload[1] << 2) ); _channels = RC_SPI_AUX2+1; } else { // channel AUX1 is used for rate, as per the deviation convention const uint8_t rate = payload[7]; // AUX1 if (rate == RATE_HIGH) { set_val(RC_CHANNEL_RATE, PWM_RANGE_MAX); } else if (rate == RATE_MID) { set_val(RC_CHANNEL_RATE, PWM_RANGE_MIDDLE); } else { set_val(RC_CHANNEL_RATE, PWM_RANGE_MIN); } // channels AUX2 to AUX7 use the deviation convention const uint8_t flags = payload[8]; set_val(RC_CHANNEL_FLIP, (flags & FLAG_FLIP) ? PWM_RANGE_MAX : PWM_RANGE_MIN ); // AUX2 set_val(RC_CHANNEL_PICTURE, (flags & FLAG_PICTURE) ? PWM_RANGE_MAX : PWM_RANGE_MIN ); // AUX3 set_val(RC_CHANNEL_VIDEO, (flags & FLAG_VIDEO) ? PWM_RANGE_MAX : PWM_RANGE_MIN ); // AUX4 set_val(RC_CHANNEL_HEADLESS, (flags & FLAG_HEADLESS) ? PWM_RANGE_MAX : PWM_RANGE_MIN ); //AUX5 set_val(RC_CHANNEL_RTH, (flags & FLAG_RTH) ? PWM_RANGE_MAX : PWM_RANGE_MIN ); // AUX6 // channels AUX7 to AUX10 have 10 bit resolution lowBits = payload[13]; // least significant bits for AUX7 to AUX10 set_val(RC_SPI_AUX7, PWM_RANGE_MIN + ((payload[9] << 2) | (lowBits & 0x03)) ); lowBits >>= 2; set_val(RC_SPI_AUX8, PWM_RANGE_MIN + ((payload[10] << 2) | (lowBits & 0x03)) ); lowBits >>= 2; set_val(RC_SPI_AUX9, PWM_RANGE_MIN + ((payload[11] << 2) | (lowBits & 0x03)) ); lowBits >>= 2; set_val(RC_SPI_AUX10, PWM_RANGE_MIN + ((payload[12] << 2) | (lowBits & 0x03)) ); lowBits >>= 2; // channels AUX11 and AUX12 have 8 bit resolution set_val(RC_SPI_AUX11, PWM_RANGE_MIN + (payload[14] << 2) ); set_val(RC_SPI_AUX12, PWM_RANGE_MIN + (payload[15] << 2) ); _channels = RC_SPI_AUX12+1; } if (payloadSize == INAV_PROTOCOL_PAYLOAD_SIZE_MAX) { // large payload variant of protocol // channels AUX13 to AUX16 have 8 bit resolution set_val(RC_SPI_AUX13, PWM_RANGE_MIN + (payload[16] << 2) ); set_val(RC_SPI_AUX14, PWM_RANGE_MIN + (payload[17] << 2) ); _channels = RC_SPI_AUX14+1; } _last_signal = systick_uptime(); } void NRF_parser::inavNrf24Setup(const uint32_t *fixedId) { // sets PWR_UP, EN_CRC, CRCO - 2 byte CRC, only get IRQ pin interrupt on RX_DR NRF24L01_Initialize(BV(NRF24L01_00_CONFIG_EN_CRC) | BV(NRF24L01_00_CONFIG_CRCO) | BV(NRF24L01_00_CONFIG_MASK_MAX_RT) | BV(NRF24L01_00_CONFIG_MASK_TX_DS)); #ifdef USE_AUTO_ACKKNOWLEDGEMENT NRF24L01_WriteReg(NRF24L01_01_EN_AA, BV(NRF24L01_01_EN_AA_ENAA_P0)); // auto acknowledgment on P0 NRF24L01_WriteReg(NRF24L01_02_EN_RXADDR, BV(NRF24L01_02_EN_RXADDR_ERX_P0)); NRF24L01_WriteReg(NRF24L01_03_SETUP_AW, NRF24L01_03_SETUP_AW_5BYTES); // 5-byte RX/TX address NRF24L01_WriteReg(NRF24L01_04_SETUP_RETR, 0); NRF24L01_Activate(0x73); // activate R_RX_PL_WID, W_ACK_PAYLOAD, and W_TX_PAYLOAD_NOACK registers NRF24L01_WriteReg(NRF24L01_1D_FEATURE, BV(NRF24L01_1D_FEATURE_EN_ACK_PAY) | BV(NRF24L01_1D_FEATURE_EN_DPL)); NRF24L01_WriteReg(NRF24L01_1C_DYNPD, BV(NRF24L01_1C_DYNPD_DPL_P0)); // enable dynamic payload length on P0 //NRF24L01_Activate(0x73); // deactivate R_RX_PL_WID, W_ACK_PAYLOAD, and W_TX_PAYLOAD_NOACK registers NRF24L01_WriteRegisterMulti(NRF24L01_10_TX_ADDR, rxTxAddr, RX_TX_ADDR_LEN); #else NRF24L01_SetupBasic(); #endif NRF24L01_WriteReg(NRF24L01_06_RF_SETUP, NRF24L01_06_RF_SETUP_RF_DR_250Kbps | NRF24L01_06_RF_SETUP_RF_PWR_n12dbm); // RX_ADDR for pipes P1-P5 are left at default values NRF24L01_WriteRegisterMulti(NRF24L01_0A_RX_ADDR_P0, rxTxAddr, RX_TX_ADDR_LEN); NRF24L01_WriteReg(NRF24L01_11_RX_PW_P0, payloadSize); #ifdef USE_BIND_ADDRESS_FOR_DATA_STATE inavSetBound(); UNUSED(fixedId); #else fixedId = NULL; // !!TODO remove this once configurator supports setting rx_id if (fixedId == NULL || *fixedId == 0) { fixedIdPtr = NULL; protocolState = STATE_BIND; inavRfChannelCount = 1; inavRfChannelIndex = 0; NRF24L01_SetChannel(INAV_RF_BIND_CHANNEL); } else { fixedIdPtr = (uint32_t*)fixedId; // use the rxTxAddr provided and go straight into DATA_STATE memcpy(rxTxAddr, fixedId, sizeof(uint32_t)); rxTxAddr[4] = RX_TX_ADDR_4; inavSetBound(); } #endif NRF24L01_SetRxMode(); // enter receive mode to start listening for packets // put a null packet in the transmit buffer to be sent as ACK on first receive writeAckPayload(ackPayload, payloadSize); } /////////////////////// #define NRF24_CE_HI() cs_assert() #define NRF24_CE_LO() cs_release() // Instruction Mnemonics // nRF24L01: Table 16. Command set for the nRF24L01 SPI. Product Specification, p46 // nRF24L01+: Table 20. Command set for the nRF24L01+ SPI. Product Specification, p51 #define R_REGISTER 0x00 #define W_REGISTER 0x20 #define REGISTER_MASK 0x1F #define ACTIVATE 0x50 #define R_RX_PL_WID 0x60 #define R_RX_PAYLOAD 0x61 #define W_TX_PAYLOAD 0xA0 #define W_ACK_PAYLOAD 0xA8 #define FLUSH_TX 0xE1 #define FLUSH_RX 0xE2 #define REUSE_TX_PL 0xE3 #define NOP 0xFF uint8_t rxSpiTransferByte(uint8_t data){ uint8_t bt; // const uint8_t *send, uint32_t send_len, uint8_t *recv, uint32_t recv_len nrf->transfer(&data,1,&bt,1); return bt; } uint8_t rxSpiWriteByte(uint8_t data) { ENABLE_RX(); const uint8_t ret = rxSpiTransferByte(data); DISABLE_RX(); return ret; } void rxSpiWriteCommand(uint8_t reg, uint8_t data){ uint8_t bt[2] = {reg, data }; nrf->transfer(&bt,2,NULL,0); } void rxSpiWriteCommandMulti(uint8_t reg, const uint8_t *data, uint8_t length){ uint8_t bt[length+1]; bt[0]=reg; for(uint8_t i=0;i<length;i++) { bt[i+1] = data[i]; } nrf->transfer(&bt,length,NULL,0); } void rxSpiReadCommand(uint8_t reg, uint8_t bt){ nrf->transfer(reg); return nrf->transfer(bt); } bool rxSpiReadCommandMulti(uint8_t reg, uint8_t op, uint8_t *data, uint8_t length) const uint8_t ret = rxSpiTransferByte(reg); for (uint8_t i = 0; i < length; i++) { data[i] = rxSpiTransferByte(op); } return ret; } void NRF24L01_WriteReg(uint8_t reg, uint8_t data) { rxSpiWriteCommand(W_REGISTER | (REGISTER_MASK & reg), data); } void NRF24L01_WriteRegisterMulti(uint8_t reg, const uint8_t *data, uint8_t length) { rxSpiWriteCommandMulti(W_REGISTER | ( REGISTER_MASK & reg), data, length); } /* * Transfer the payload to the nRF24L01 TX FIFO * Packets in the TX FIFO are transmitted when the * nRF24L01 next enters TX mode */ uint8_t NRF24L01_WritePayload(const uint8_t *data, uint8_t length) { return rxSpiWriteCommandMulti(W_TX_PAYLOAD, data, length); } uint8_t NRF24L01_WriteAckPayload(const uint8_t *data, uint8_t length, uint8_t pipe) { return rxSpiWriteCommandMulti(W_ACK_PAYLOAD | (pipe & 0x07), data, length); } uint8_t NRF24L01_ReadReg(uint8_t reg) { return rxSpiReadCommand(R_REGISTER | (REGISTER_MASK & reg), NOP); } uint8_t NRF24L01_ReadRegisterMulti(uint8_t reg, uint8_t *data, uint8_t length) { return rxSpiReadCommandMulti(R_REGISTER | (REGISTER_MASK & reg), NOP, data, length); } /* * Read a packet from the nRF24L01 RX FIFO. */ uint8_t NRF24L01_ReadPayload(uint8_t *data, uint8_t length) { return rxSpiReadCommandMulti(R_RX_PAYLOAD, NOP, data, length); } /* * Empty the transmit FIFO buffer. */ void NRF24L01_FlushTx() { rxSpiWriteByte(FLUSH_TX); } /* * Empty the receive FIFO buffer. */ void NRF24L01_FlushRx() { rxSpiWriteByte(FLUSH_RX); } uint8_t NRF24L01_Activate(uint8_t code) { return rxSpiWriteCommand(ACTIVATE, code); } // standby configuration, used to simplify switching between RX, TX, and Standby modes static uint8_t standbyConfig; void NRF24L01_Initialize(uint8_t baseConfig) { standbyConfig = BV(NRF24L01_00_CONFIG_PWR_UP) | baseConfig; NRF24_CE_LO(); // nRF24L01+ needs 100 milliseconds settling time from PowerOnReset to PowerDown mode static const timeUs_t settlingTimeUs = 100000; const timeUs_t currentTimeUs = micros(); if (currentTimeUs < settlingTimeUs) { delayMicroseconds(settlingTimeUs - currentTimeUs); } // now in PowerDown mode NRF24L01_WriteReg(NRF24L01_00_CONFIG, standbyConfig); // set PWR_UP to enter Standby mode // nRF24L01+ needs 4500 microseconds from PowerDown mode to Standby mode, for crystal oscillator startup delayMicroseconds(4500); // now in Standby mode } /* * Common setup of registers */ void NRF24L01_SetupBasic(void) { NRF24L01_WriteReg(NRF24L01_01_EN_AA, 0x00); // No auto acknowledgment NRF24L01_WriteReg(NRF24L01_02_EN_RXADDR, BV(NRF24L01_02_EN_RXADDR_ERX_P0)); NRF24L01_WriteReg(NRF24L01_03_SETUP_AW, NRF24L01_03_SETUP_AW_5BYTES); // 5-byte RX/TX address NRF24L01_WriteReg(NRF24L01_1C_DYNPD, 0x00); // Disable dynamic payload length on all pipes } /* * Enter standby mode */ void NRF24L01_SetStandbyMode(void) { // set CE low and clear the PRIM_RX bit to enter standby mode NRF24_CE_LO(); NRF24L01_WriteReg(NRF24L01_00_CONFIG, standbyConfig); } /* * Enter receive mode */ void NRF24L01_SetRxMode(void) { NRF24_CE_LO(); // drop into standby mode // set the PRIM_RX bit NRF24L01_WriteReg(NRF24L01_00_CONFIG, standbyConfig | BV(NRF24L01_00_CONFIG_PRIM_RX)); NRF24L01_ClearAllInterrupts(); // finally set CE high to start enter RX mode NRF24_CE_HI(); // nRF24L01+ will now transition from Standby mode to RX mode after 130 microseconds settling time } /* * Enter transmit mode. Anything in the transmit FIFO will be transmitted. */ void NRF24L01_SetTxMode(void) { // Ensure in standby mode, since can only enter TX mode from standby mode NRF24L01_SetStandbyMode(); NRF24L01_ClearAllInterrupts(); // pulse CE for 10 microseconds to enter TX mode NRF24_CE_HI(); delayMicroseconds(10); NRF24_CE_LO(); // nRF24L01+ will now transition from Standby mode to TX mode after 130 microseconds settling time. // Transmission will then begin and continue until TX FIFO is empty. } void NRF24L01_ClearAllInterrupts(void) { // Writing to the STATUS register clears the specified interrupt bits NRF24L01_WriteReg(NRF24L01_07_STATUS, BV(NRF24L01_07_STATUS_RX_DR) | BV(NRF24L01_07_STATUS_TX_DS) | BV(NRF24L01_07_STATUS_MAX_RT)); } bool NRF24L01_ReadPayloadIfAvailable(uint8_t *data, uint8_t length) { if (NRF24L01_ReadReg(NRF24L01_17_FIFO_STATUS) & BV(NRF24L01_17_FIFO_STATUS_RX_EMPTY)) { return false; } NRF24L01_ReadPayload(data, length); return true; } #endif // BOARD_NRF24_CS_PIN
gpl-3.0
r0mai/metashell
3rd/templight/clang/test/Sema/address_space_print_macro.c
14
3020
// RUN: %clang_cc1 %s -fsyntax-only -verify #define AS1 __attribute__((address_space(1))) #define AS2 __attribute__((address_space(2), annotate("foo"))) #define AS_ND __attribute__((address_space(2), noderef)) #define AS(i) address_space(i) #define AS3 __attribute__((AS(3))) #define AS5 __attribute__((address_space(5))) char void normal_case() { int *p = 0; __attribute__((address_space(1))) int *q = p; // expected-error{{initializing '__attribute__((address_space(1))) int *' with an expression of type 'int *' changes address space of pointer}} } char *cmp(AS1 char *x, AS2 char *y) { return x < y ? x : y; // expected-error{{conditional operator with the second and third operands of type ('AS1 char *' and 'AS2 char *') which are pointers to non-overlapping address spaces}} } __attribute__((address_space(1))) char test_array[10]; void test3(void) { extern void test3_helper(char *p); // expected-note{{passing argument to parameter 'p' here}} test3_helper(test_array); // expected-error{{passing '__attribute__((address_space(1))) char *' to parameter of type 'char *' changes address space of pointer}} } char AS2 *test4_array; void test4(void) { extern void test3_helper(char *p); // expected-note{{passing argument to parameter 'p' here}} test3_helper(test4_array); // expected-error{{passing 'AS2 char *' to parameter of type 'char *' changes address space of pointer}} } void func() { char AS1 *x; char AS3 *x2; AS5 *x3; char *y; y = x; // expected-error{{assigning 'AS1 char *' to 'char *' changes address space of pointer}} y = x2; // expected-error{{assigning 'AS3 char *' to 'char *' changes address space of pointer}} y = x3; // expected-error{{assigning '__attribute__((address_space(5))) char *' to 'char *' changes address space of pointer}} } void multiple_attrs(AS_ND int *x) { __attribute__((address_space(2))) int *y = x; // expected-warning{{casting to dereferenceable pointer removes 'noderef' attribute}} } void override_macro_name() { #define ATTRS __attribute__((noderef)) // expected-note{{previous definition is here}} ATTRS #define ATTRS __attribute__((address_space(1))) // expected-warning{{'ATTRS' macro redefined}} ATTRS int *x; int AS_ND *y = x; // expected-error{{initializing 'AS_ND int *' with an expression of type 'ATTRS int *' changes address space of pointer}} } void partial_macro_declaration() { #define ATTRS2 __attribute__((noderef)) ATTRS2 __attribute__((address_space(1))) int *x; int AS_ND *y = x; // expected-error{{initializing 'AS_ND int *' with an expression of type 'ATTRS2 int __attribute__((address_space(1))) *' changes address space of pointer}} // The attribute not wrapped with a macro should be printed regularly. #define ATTRS3 __attribute__((address_space(1))) ATTRS3 __attribute__((noderef)) int *x2; int AS_ND *y2 = x2; // expected-error{{initializing 'AS_ND int *' with an expression of type 'ATTRS3 int * __attribute__((noderef))' changes address space of pointer}} }
gpl-3.0
caguado/boinc-v2
lib/mfile.cpp
15
4307
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. #if defined(_WIN32) && !defined(__STDWX_H__) #include "boinc_win.h" #elif defined(_WIN32) && defined(__STDWX_H__) #include "stdwx.h" #else #include "config.h" #include <cstdio> #include <cstdlib> #include <cstdarg> #include <cstring> #include <string> #include <cerrno> #include <unistd.h> #endif #include "error_numbers.h" #include "filesys.h" #include "mfile.h" MFILE::MFILE() { buf = (char*)malloc(64*1024); len = 0; } MFILE::~MFILE() { if (buf) free(buf); } int MFILE::open(const char* path, const char* mode) { f = boinc_fopen(path, mode); if (!f) return ERR_FOPEN; if (!buf) buf = (char*)malloc(64*1024); return 0; } // seems like Win's realloc is stupid, Make it smart. // static inline char* realloc_aux(char* p, size_t len) { if (!p) { return (char*)malloc(64*1024); } #ifdef _WIN32 if (_msize(p) >= (unsigned int)len) return p; return (char*) realloc(p, len*2); #else return (char*) realloc(p, len); #endif } #define BUFSIZE 100000 int MFILE::vprintf(const char* format, va_list ap) { char buf2[BUFSIZE]; int n, k; k = vsnprintf(buf2, BUFSIZE, format, ap); if (k<=-1 || k>=BUFSIZE) { fprintf(stderr, "ERROR: buffer too small in MFILE::vprintf()\n"); fprintf(stderr, "ERROR: format: %s\n", format); fprintf(stderr, "ERROR: k=%d, BUFSIZE=%d\n", k, BUFSIZE); return -1; } n = (int)strlen(buf2); buf = (char*)realloc_aux(buf, len+n+1); if (!buf) { fprintf(stderr, "ERROR: realloc() failed in MFILE::vprintf(); len %d n %d\n", len, n ); exit(1); } strncpy(buf+len, buf2, n); len += n; buf[len] = 0; return k; } int MFILE::printf(const char* format, ...) { int n; va_list ap; va_start(ap, format); n = MFILE::vprintf(format, ap); va_end(ap); return n; } size_t MFILE::write(const void *ptr, size_t size, size_t nitems) { buf = (char *)realloc_aux( buf, len+(size*nitems)+1 ); if (!buf) { fprintf(stderr, "ERROR: realloc() failed in MFILE::write(); len %d size %lu nitems %lu\n", len, size, nitems ); exit(1); } memcpy( buf+len, ptr, size*nitems ); len += (int)size*(int)nitems; buf[len] = 0; return nitems; } int MFILE::_putchar(char c) { buf = (char*)realloc_aux(buf, len+1+1); if (!buf) { fprintf(stderr, "ERROR: realloc() failed in MFILE::_putchar(); len %d\n", len ); exit(1); } buf[len] = c; len++; buf[len] = 0; return c; } int MFILE::puts(const char* p) { int n = (int)strlen(p); buf = (char*)realloc_aux(buf, len+n+1); if (!buf) { fprintf(stderr, "ERROR: realloc() failed in MFILE::puts() len %d n %d\n", len, n ); exit(1); } strncpy(buf+len, p, n); len += n; buf[len] = 0; return n; } int MFILE::close() { int retval = 0; if (f) { flush(); fclose(f); f = NULL; } if (buf) { free(buf); buf = NULL; } return retval; } int MFILE::flush() { int n, old_len = len; n = (int)fwrite(buf, 1, len, f); len = 0; if (n != old_len) return ERR_FWRITE; if (fflush(f)) return ERR_FFLUSH; #ifndef _WIN32 if (fsync(fileno(f)) < 0) return ERR_FSYNC; #endif return 0; } long MFILE::tell() const { return f ? ftell(f) : -1; } void MFILE::get_buf(char*& b, int& l) { b = buf; l = len; buf = 0; len = 0; }
gpl-3.0
1151637/ivmultiplayer
Network/Core/RakNet/LogCommandParser.cpp
16
7503
#include "NativeFeatureIncludes.h" #if _RAKNET_SUPPORT_LogCommandParser==1 #include "LogCommandParser.h" #include "TransportInterface.h" #include <memory.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include "LinuxStrings.h" #ifdef _MSC_VER #pragma warning( push ) #endif using namespace RakNet; STATIC_FACTORY_DEFINITIONS(LogCommandParser,LogCommandParser); LogCommandParser::LogCommandParser() { RegisterCommand(CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS,"Subscribe","[<ChannelName>] - Subscribes to a named channel, or all channels"); RegisterCommand(CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS,"Unsubscribe","[<ChannelName>] - Unsubscribes from a named channel, or all channels"); memset(channelNames,0,sizeof(channelNames)); } LogCommandParser::~LogCommandParser() { } bool LogCommandParser::OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString) { (void) originalString; if (strcmp(command, "Subscribe")==0) { unsigned channelIndex; if (numParameters==0) { Subscribe(systemAddress, 0); transport->Send(systemAddress, "Subscribed to all channels.\r\n"); } else if (numParameters==1) { if ((channelIndex=Subscribe(systemAddress, parameterList[0]))!=(unsigned)-1) { transport->Send(systemAddress, "You are now subscribed to channel %s.\r\n", channelNames[channelIndex]); } else { transport->Send(systemAddress, "Cannot find channel %s.\r\n", parameterList[0]); PrintChannels(systemAddress, transport); } } else { transport->Send(systemAddress, "Subscribe takes either 0 or 1 parameters.\r\n"); } } else if (strcmp(command, "Unsubscribe")==0) { unsigned channelIndex; if (numParameters==0) { Unsubscribe(systemAddress, 0); transport->Send(systemAddress, "Unsubscribed from all channels.\r\n"); } else if (numParameters==1) { if ((channelIndex=Unsubscribe(systemAddress, parameterList[0]))!=(unsigned)-1) { transport->Send(systemAddress, "You are now unsubscribed from channel %s.\r\n", channelNames[channelIndex]); } else { transport->Send(systemAddress, "Cannot find channel %s.\r\n", parameterList[0]); PrintChannels(systemAddress, transport); } } else { transport->Send(systemAddress, "Unsubscribe takes either 0 or 1 parameters.\r\n"); } } return true; } const char *LogCommandParser::GetName(void) const { return "Logger"; } void LogCommandParser::SendHelp(TransportInterface *transport, const SystemAddress &systemAddress) { transport->Send(systemAddress, "The logger will accept user log data via the Log(...) function.\r\n"); transport->Send(systemAddress, "Each log is associated with a named channel.\r\n"); transport->Send(systemAddress, "You can subscribe to or unsubscribe from named channels.\r\n"); PrintChannels(systemAddress, transport); } void LogCommandParser::AddChannel(const char *channelName) { unsigned channelIndex=0; channelIndex = GetChannelIndexFromName(channelName); // Each channel can only be added once. RakAssert(channelIndex==(unsigned)-1); unsigned i; for (i=0; i < 32; i++) { if (channelNames[i]==0) { // Assuming a persistent static string. channelNames[i]=channelName; return; } } // No more available channels - max 32 with this implementation where I save subscribed channels with bit operations RakAssert(0); } void LogCommandParser::WriteLog(const char *channelName, const char *format, ...) { if (channelName==0 || format==0) return; unsigned channelIndex; channelIndex = GetChannelIndexFromName(channelName); if (channelIndex==(unsigned)-1) { AddChannel(channelName); } char text[REMOTE_MAX_TEXT_INPUT]; va_list ap; va_start(ap, format); _vsnprintf(text, REMOTE_MAX_TEXT_INPUT, format, ap); va_end(ap); text[REMOTE_MAX_TEXT_INPUT-1]=0; // Make sure that text ends in \r\n int textLen; textLen=(int)strlen(text); if (textLen==0) return; if (text[textLen-1]=='\n') { text[textLen-1]=0; } if (textLen < REMOTE_MAX_TEXT_INPUT-4) strcat(text, "\r\n"); else { text[textLen-3]='\r'; text[textLen-2]='\n'; text[textLen-1]=0; } // For each user that subscribes to this channel, send to them. unsigned i; for (i=0; i < remoteUsers.Size(); i++) { if (remoteUsers[i].channels & (1 << channelIndex)) { trans->Send(remoteUsers[i].systemAddress, text); } } } void LogCommandParser::PrintChannels(const SystemAddress &systemAddress, TransportInterface *transport) const { unsigned i; bool anyChannels=false; transport->Send(systemAddress, "CHANNELS:\r\n"); for (i=0; i < 32; i++) { if (channelNames[i]) { transport->Send(systemAddress, "%i. %s\r\n", i+1,channelNames[i]); anyChannels=true; } } if (anyChannels==false) transport->Send(systemAddress, "None.\r\n"); } void LogCommandParser::OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport) { (void) systemAddress; (void) transport; } void LogCommandParser::OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport) { (void) transport; Unsubscribe(systemAddress, 0); } unsigned LogCommandParser::Unsubscribe(const SystemAddress &systemAddress, const char *channelName) { unsigned i; for (i=0; i < remoteUsers.Size(); i++) { if (remoteUsers[i].systemAddress==systemAddress) { if (channelName==0) { // Unsubscribe from all and delete this user. remoteUsers[i]=remoteUsers[remoteUsers.Size()-1]; remoteUsers.RemoveFromEnd(); return 0; } else { unsigned channelIndex; channelIndex = GetChannelIndexFromName(channelName); if (channelIndex!=(unsigned)-1) { remoteUsers[i].channels&=0xFFFF ^ (1<<channelIndex); // Unset this bit } return channelIndex; } } } return (unsigned)-1; } unsigned LogCommandParser::Subscribe(const SystemAddress &systemAddress, const char *channelName) { unsigned i; unsigned channelIndex=(unsigned)-1; if (channelName) { channelIndex = GetChannelIndexFromName(channelName); if (channelIndex==(unsigned)-1) return channelIndex; } for (i=0; i < remoteUsers.Size(); i++) { if (remoteUsers[i].systemAddress==systemAddress) { if (channelName) remoteUsers[i].channels|=1<<channelIndex; // Set this bit for an existing user else remoteUsers[i].channels=0xFFFF; return channelIndex; } } // Make a new user SystemAddressAndChannel newUser; newUser.systemAddress = systemAddress; if (channelName) newUser.channels=1<<channelIndex; else newUser.channels=0xFFFF; remoteUsers.Insert(newUser, _FILE_AND_LINE_); return channelIndex; } unsigned LogCommandParser::GetChannelIndexFromName(const char *channelName) { unsigned i; for (i=0; i < 32; i++) { if (channelNames[i]==0) return (unsigned) -1; if (_stricmp(channelNames[i], channelName)==0) return i; } return (unsigned)-1; } void LogCommandParser::OnTransportChange(TransportInterface *transport) { // I don't want users to have to pass TransportInterface *transport to Log. trans=transport; } #ifdef _MSC_VER #pragma warning( pop ) #endif #endif // _RAKNET_SUPPORT_*
gpl-3.0
ymattw/rsyslog
runtime/ratelimit.c
16
10800
/* ratelimit.c * support for rate-limiting sources, including "last message * repeated n times" processing. * * Copyright 2012 Rainer Gerhards and Adiscon GmbH. * * This file is part of the rsyslog runtime library. * * 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 * -or- * see COPYING.ASL20 in the source distribution * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include "rsyslog.h" #include "errmsg.h" #include "ratelimit.h" #include "datetime.h" #include "parser.h" #include "unicode-helper.h" #include "msg.h" #include "rsconf.h" #include "dirty.h" /* definitions for objects we access */ DEFobjStaticHelpers DEFobjCurrIf(errmsg) DEFobjCurrIf(glbl) DEFobjCurrIf(datetime) DEFobjCurrIf(parser) /* static data */ /* generate a "repeated n times" message */ static inline msg_t * ratelimitGenRepMsg(ratelimit_t *ratelimit) { msg_t *repMsg; size_t lenRepMsg; uchar szRepMsg[1024]; if(ratelimit->nsupp == 1) { /* we simply use the original message! */ repMsg = MsgAddRef(ratelimit->pMsg); } else {/* we need to duplicate, original message may still be in use in other * parts of the system! */ if((repMsg = MsgDup(ratelimit->pMsg)) == NULL) { DBGPRINTF("Message duplication failed, dropping repeat message.\n"); goto done; } lenRepMsg = snprintf((char*)szRepMsg, sizeof(szRepMsg), " message repeated %d times: [%.800s]", ratelimit->nsupp, getMSG(ratelimit->pMsg)); MsgReplaceMSG(repMsg, szRepMsg, lenRepMsg); } done: return repMsg; } static inline rsRetVal doLastMessageRepeatedNTimes(ratelimit_t *ratelimit, msg_t *pMsg, msg_t **ppRepMsg) { int bNeedUnlockMutex = 0; DEFiRet; if(ratelimit->bThreadSafe) { pthread_mutex_lock(&ratelimit->mut); bNeedUnlockMutex = 1; } if( ratelimit->pMsg != NULL && getMSGLen(pMsg) == getMSGLen(ratelimit->pMsg) && !ustrcmp(getMSG(pMsg), getMSG(ratelimit->pMsg)) && !strcmp(getHOSTNAME(pMsg), getHOSTNAME(ratelimit->pMsg)) && !strcmp(getPROCID(pMsg, LOCK_MUTEX), getPROCID(ratelimit->pMsg, LOCK_MUTEX)) && !strcmp(getAPPNAME(pMsg, LOCK_MUTEX), getAPPNAME(ratelimit->pMsg, LOCK_MUTEX))) { ratelimit->nsupp++; DBGPRINTF("msg repeated %d times\n", ratelimit->nsupp); /* use current message, so we have the new timestamp * (means we need to discard previous one) */ msgDestruct(&ratelimit->pMsg); ratelimit->pMsg = pMsg; ABORT_FINALIZE(RS_RET_DISCARDMSG); } else {/* new message, do "repeat processing" & save it */ if(ratelimit->pMsg != NULL) { if(ratelimit->nsupp > 0) { *ppRepMsg = ratelimitGenRepMsg(ratelimit); ratelimit->nsupp = 0; } msgDestruct(&ratelimit->pMsg); } ratelimit->pMsg = MsgAddRef(pMsg); } finalize_it: if(bNeedUnlockMutex) pthread_mutex_unlock(&ratelimit->mut); RETiRet; } /* helper: tell how many messages we lost due to linux-like ratelimiting */ static inline void tellLostCnt(ratelimit_t *ratelimit) { uchar msgbuf[1024]; if(ratelimit->missed) { snprintf((char*)msgbuf, sizeof(msgbuf), "%s: %u messages lost due to rate-limiting", ratelimit->name, ratelimit->missed); ratelimit->missed = 0; logmsgInternal(RS_RET_RATE_LIMITED, LOG_SYSLOG|LOG_INFO, msgbuf, 0); } } /* Linux-like ratelimiting, modelled after the linux kernel * returns 1 if message is within rate limit and shall be * processed, 0 otherwise. * This implementation is NOT THREAD-SAFE and must not * be called concurrently. */ static inline int withinRatelimit(ratelimit_t *ratelimit, time_t tt) { int ret; uchar msgbuf[1024]; if(ratelimit->interval == 0) { ret = 1; goto finalize_it; } /* we primarily need "NoTimeCache" mode for imjournal, as it * sets the message generation time to the journal timestamp. * As such, we do not get a proper indication of the actual * message rate. To prevent this, we need to query local * system time ourselvs. */ if(ratelimit->bNoTimeCache) tt = time(NULL); assert(ratelimit->burst != 0); if(ratelimit->begin == 0) ratelimit->begin = tt; /* resume if we go out of time window */ if(tt > ratelimit->begin + ratelimit->interval) { ratelimit->begin = 0; ratelimit->done = 0; tellLostCnt(ratelimit); } /* do actual limit check */ if(ratelimit->burst > ratelimit->done) { ratelimit->done++; ret = 1; } else { ratelimit->missed++; if(ratelimit->missed == 1) { snprintf((char*)msgbuf, sizeof(msgbuf), "%s: begin to drop messages due to rate-limiting", ratelimit->name); logmsgInternal(RS_RET_RATE_LIMITED, LOG_SYSLOG|LOG_INFO, msgbuf, 0); } ret = 0; } finalize_it: return ret; } /* ratelimit a message, that means: * - handle "last message repeated n times" logic * - handle actual (discarding) rate-limiting * This function returns RS_RET_OK, if the caller shall process * the message regularly and RS_RET_DISCARD if the caller must * discard the message. The caller should also discard the message * if another return status occurs. This places some burden on the * caller logic, but provides best performance. Demanding this * cooperative mode can enable a faulty caller to thrash up part * of the system, but we accept that risk (a faulty caller can * always do all sorts of evil, so...) * If *ppRepMsg != NULL on return, the caller must enqueue that * message before the original message. */ rsRetVal ratelimitMsg(ratelimit_t *ratelimit, msg_t *pMsg, msg_t **ppRepMsg) { DEFiRet; rsRetVal localRet; *ppRepMsg = NULL; if((pMsg->msgFlags & NEEDS_PARSING) != 0) { if((localRet = parser.ParseMsg(pMsg)) != RS_RET_OK) { DBGPRINTF("Message discarded, parsing error %d\n", localRet); ABORT_FINALIZE(RS_RET_DISCARDMSG); } } /* Only the messages having severity level at or below the * treshold (the value is >=) are subject to ratelimiting. */ if(ratelimit->interval && (pMsg->iSeverity >= ratelimit->severity)) { if(withinRatelimit(ratelimit, pMsg->ttGenTime) == 0) { msgDestruct(&pMsg); ABORT_FINALIZE(RS_RET_DISCARDMSG); } } if(ratelimit->bReduceRepeatMsgs) { CHKiRet(doLastMessageRepeatedNTimes(ratelimit, pMsg, ppRepMsg)); } finalize_it: if(Debug) { if(iRet == RS_RET_DISCARDMSG) dbgprintf("message discarded by ratelimiting\n"); } RETiRet; } /* returns 1, if the ratelimiter performs any checks and 0 otherwise */ int ratelimitChecked(ratelimit_t *ratelimit) { return ratelimit->interval || ratelimit->bReduceRepeatMsgs; } /* add a message to a ratelimiter/multisubmit structure. * ratelimiting is automatically handled according to the ratelimit * settings. * if pMultiSub == NULL, a single-message enqueue happens (under reconsideration) */ rsRetVal ratelimitAddMsg(ratelimit_t *ratelimit, multi_submit_t *pMultiSub, msg_t *pMsg) { rsRetVal localRet; msg_t *repMsg; DEFiRet; if(pMultiSub == NULL) { localRet = ratelimitMsg(ratelimit, pMsg, &repMsg); if(repMsg != NULL) CHKiRet(submitMsg2(repMsg)); if(localRet == RS_RET_OK) CHKiRet(submitMsg2(pMsg)); } else { localRet = ratelimitMsg(ratelimit, pMsg, &repMsg); if(repMsg != NULL) { pMultiSub->ppMsgs[pMultiSub->nElem++] = repMsg; if(pMultiSub->nElem == pMultiSub->maxElem) CHKiRet(multiSubmitMsg2(pMultiSub)); } if(localRet == RS_RET_OK) { pMultiSub->ppMsgs[pMultiSub->nElem++] = pMsg; if(pMultiSub->nElem == pMultiSub->maxElem) CHKiRet(multiSubmitMsg2(pMultiSub)); } } finalize_it: RETiRet; } /* modname must be a static name (usually expected to be the module * name and MUST be present. dynname may be NULL and can be used for * dynamic information, e.g. PID or listener IP, ... * Both values should be kept brief. */ rsRetVal ratelimitNew(ratelimit_t **ppThis, char *modname, char *dynname) { ratelimit_t *pThis; char namebuf[256]; DEFiRet; CHKmalloc(pThis = calloc(1, sizeof(ratelimit_t))); if(modname == NULL) modname ="*ERROR:MODULE NAME MISSING*"; if(dynname == NULL) { pThis->name = strdup(modname); } else { snprintf(namebuf, sizeof(namebuf), "%s[%s]", modname, dynname); namebuf[sizeof(namebuf)-1] = '\0'; /* to be on safe side */ pThis->name = strdup(namebuf); } /* pThis->severity == 0 - all messages are ratelimited */ pThis->bReduceRepeatMsgs = loadConf->globals.bReduceRepeatMsgs; DBGPRINTF("ratelimit:%s:new ratelimiter:bReduceRepeatMsgs %d\n", pThis->name, pThis->bReduceRepeatMsgs); *ppThis = pThis; finalize_it: RETiRet; } /* enable linux-like ratelimiting */ void ratelimitSetLinuxLike(ratelimit_t *ratelimit, unsigned short interval, unsigned short burst) { ratelimit->interval = interval; ratelimit->burst = burst; ratelimit->done = 0; ratelimit->missed = 0; ratelimit->begin = 0; } /* enable thread-safe operations mode. This make sure that * a single ratelimiter can be called from multiple threads. As * this causes some overhead and is not always required, it needs * to be explicitely enabled. This operation cannot be undone * (think: why should one do that???) */ void ratelimitSetThreadSafe(ratelimit_t *ratelimit) { ratelimit->bThreadSafe = 1; pthread_mutex_init(&ratelimit->mut, NULL); } void ratelimitSetNoTimeCache(ratelimit_t *ratelimit) { ratelimit->bNoTimeCache = 1; pthread_mutex_init(&ratelimit->mut, NULL); } /* Severity level determines which messages are subject to * ratelimiting. Default (no value set) is all messages. */ void ratelimitSetSeverity(ratelimit_t *ratelimit, intTiny severity) { ratelimit->severity = severity; } void ratelimitDestruct(ratelimit_t *ratelimit) { msg_t *pMsg; if(ratelimit->pMsg != NULL) { if(ratelimit->nsupp > 0) { pMsg = ratelimitGenRepMsg(ratelimit); if(pMsg != NULL) submitMsg2(pMsg); } msgDestruct(&ratelimit->pMsg); } tellLostCnt(ratelimit); if(ratelimit->bThreadSafe) pthread_mutex_destroy(&ratelimit->mut); free(ratelimit->name); free(ratelimit); } void ratelimitModExit(void) { objRelease(datetime, CORE_COMPONENT); objRelease(glbl, CORE_COMPONENT); objRelease(errmsg, CORE_COMPONENT); objRelease(parser, CORE_COMPONENT); } rsRetVal ratelimitModInit(void) { DEFiRet; CHKiRet(objGetObjInterface(&obj)); CHKiRet(objUse(glbl, CORE_COMPONENT)); CHKiRet(objUse(datetime, CORE_COMPONENT)); CHKiRet(objUse(errmsg, CORE_COMPONENT)); CHKiRet(objUse(parser, CORE_COMPONENT)); finalize_it: RETiRet; }
gpl-3.0
linuxmcu/ardupilot
libraries/AP_HAL/examples/UART_test/UART_test.cpp
18
1453
/* simple test of UART interfaces */ #include <AP_HAL/AP_HAL.h> #if HAL_OS_POSIX_IO #include <stdio.h> #endif const AP_HAL::HAL& hal = AP_HAL::get_HAL(); /* setup one UART at 57600 */ static void setup_uart(AP_HAL::UARTDriver *uart, const char *name) { if (uart == nullptr) { // that UART doesn't exist on this platform return; } uart->begin(57600); } void setup(void) { /* start all UARTs at 57600 with default buffer sizes */ setup_uart(hal.uartA, "uartA"); // console setup_uart(hal.uartB, "uartB"); // 1st GPS setup_uart(hal.uartC, "uartC"); // telemetry 1 setup_uart(hal.uartD, "uartD"); // telemetry 2 setup_uart(hal.uartE, "uartE"); // 2nd GPS } static void test_uart(AP_HAL::UARTDriver *uart, const char *name) { if (uart == nullptr) { // that UART doesn't exist on this platform return; } uart->printf("Hello on UART %s at %.3f seconds\n", name, AP_HAL::millis()*0.001f); } void loop(void) { test_uart(hal.uartA, "uartA"); test_uart(hal.uartB, "uartB"); test_uart(hal.uartC, "uartC"); test_uart(hal.uartD, "uartD"); test_uart(hal.uartE, "uartE"); // also do a raw printf() on some platforms, which prints to the // debug console #if HAL_OS_POSIX_IO ::printf("Hello on debug console at %.3f seconds\n", AP_HAL::millis()*0.001f); #endif hal.scheduler->delay(1000); } AP_HAL_MAIN();
gpl-3.0
MattDevo/stk-code
lib/irrlicht/tests/fast_atof.cpp
22
8699
// Copyright (C) 2008-2012 Colin MacDonald // No rights reserved: this software is in the public domain. #include "testUtils.h" using namespace irr; using namespace core; //! This was an older Irrlicht implementation, tested against for reference. static inline u32 old_strtol10(const char* in, const char** out=0) { u32 value = 0; while ( ( *in >= '0') && ( *in <= '9' )) { value = ( value * 10 ) + ( *in - '0' ); ++in; } if (out) *out = in; return value; } //! This was an older Irrlicht implementation, tested against for reference. static inline const char* old_fast_atof_move( const char* c, float& out) { bool inv = false; const char *t; float f; if (*c=='-') { ++c; inv = true; } //f = (float)strtol(c, &t, 10); f = (float) old_strtol10 ( c, &c ); if (*c == '.') { ++c; //float pl = (float)strtol(c, &t, 10); float pl = (float) old_strtol10 ( c, &t ); pl *= fast_atof_table[t-c]; f += pl; c = t; if (*c == 'e') { ++c; //float exp = (float)strtol(c, &t, 10); bool einv = (*c=='-'); if (einv) ++c; float exp = (float)old_strtol10(c, &c); if (einv) exp *= -1.0f; f *= (float)pow(10.0f, exp); } } if (inv) f *= -1.0f; out = f; return c; } //! This was an older Irrlicht implementation, tested against for reference. static inline float old_fast_atof(const char* c) { float ret; old_fast_atof_move(c, ret); return ret; } static bool testCalculation_atof(const char * valueString) { const f32 newFastValue = fast_atof(valueString); const f32 oldFastValue = old_fast_atof(valueString); const f32 atofValue = (f32)atof(valueString); logTestString("\n String '%s'\n New fast %.40f\n Old fast %.40f\n atof %.40f\n", valueString, newFastValue, oldFastValue, atofValue); const f32 diffNew = fabs(newFastValue - atofValue) ; const f32 diffOld = fabs(newFastValue - atofValue) ; bool accurate = diffNew <= diffOld || equalsByUlp(diffNew, diffOld, 1); if(!accurate) logTestString("*** ERROR - less accurate than old method ***\n\n"); return accurate; } static bool testCalculation_strtol(const char * valueString) { const s32 newFastValue = strtol10(valueString); const s32 oldFastValue = old_strtol10(valueString); const s32 strtolValue = (s32)clamp(strtol(valueString, 0, 10), (long int)INT_MIN, (long int)INT_MAX); logTestString("\n String '%s'\n New fast %d\n Old fast %d\n strtol %d\n", valueString, newFastValue, oldFastValue, strtolValue); bool accurate = (newFastValue == strtolValue) || (oldFastValue != strtolValue); if (!accurate) logTestString("*** ERROR - wrong calculation in new method ***\n\n"); return accurate; } //! Test both the accuracy and speed of Irrlicht's fast_atof() implementation. bool test_fast_atof(void) { bool accurate = true; accurate &= testCalculation_atof("340282346638528859811704183484516925440.000000"); accurate &= testCalculation_atof("3.402823466e+38F"); accurate &= testCalculation_atof("3402823466e+29F"); accurate &= testCalculation_atof("-340282346638528859811704183484516925440.000000"); accurate &= testCalculation_atof("-3.402823466e+38F"); accurate &= testCalculation_atof("-3402823466e+29F"); accurate &= testCalculation_atof("34028234663852885981170418348451692544.000000"); accurate &= testCalculation_atof("3.402823466e+37F"); accurate &= testCalculation_atof("3402823466e+28F"); accurate &= testCalculation_atof("-34028234663852885981170418348451692544.000000"); accurate &= testCalculation_atof("-3.402823466e+37F"); accurate &= testCalculation_atof("-3402823466e+28F"); accurate &= testCalculation_atof(".00234567"); accurate &= testCalculation_atof("-.00234567"); accurate &= testCalculation_atof("0.00234567"); accurate &= testCalculation_atof("-0.00234567"); accurate &= testCalculation_atof("1.175494351e-38F"); accurate &= testCalculation_atof("1175494351e-47F"); accurate &= testCalculation_atof("1.175494351e-37F"); accurate &= testCalculation_atof("1.175494351e-36F"); accurate &= testCalculation_atof("-1.175494351e-36F"); accurate &= testCalculation_atof("123456.789"); accurate &= testCalculation_atof("-123456.789"); accurate &= testCalculation_atof("0000123456.789"); accurate &= testCalculation_atof("-0000123456.789"); accurate &= testCalculation_atof("-0.0690462109446526"); if (!accurate) { logTestString("Calculation is not accurate, so the speed is irrelevant\n"); return false; } #ifndef _DEBUG // it's only faster in release IrrlichtDevice* device = createDevice(video::EDT_NULL); if (!device) return false; ITimer* timer = device->getTimer(); const int ITERATIONS = 100000; int i; f32 value; u32 then = timer->getRealTime(); for(i = 0; i < ITERATIONS; ++i) value = (f32)atof("-340282346638528859811704183484516925440.000000"); const u32 atofTime = timer->getRealTime() - then; then += atofTime; for(i = 0; i < ITERATIONS; ++i) value = fast_atof("-340282346638528859811704183484516925440.000000"); const u32 fastAtofTime = timer->getRealTime() - then; then += fastAtofTime; for(i = 0; i < ITERATIONS; ++i) value = old_fast_atof("-340282346638528859811704183484516925440.000000"); const u32 oldFastAtofTime = timer->getRealTime() - then; logTestString("Speed test\n atof time = %d\n fast_atof Time = %d\nold fast_atof time = %d\n", atofTime, fastAtofTime, oldFastAtofTime); device->closeDevice(); device->run(); device->drop(); if(fastAtofTime > (1.2f*atofTime)) { logTestString("The fast method is slower than atof()\n"); return false; } #endif // #ifndef _DEBUG return true; } //! Test both the accuracy and speed of Irrlicht's strtol10() implementation. bool test_strtol(void) { bool accurate = true; accurate &= testCalculation_strtol("340282346638528859811704183484516925440"); accurate &= testCalculation_strtol("3402823466"); accurate &= testCalculation_strtol("3402823466e+29F"); accurate &= testCalculation_strtol("-340282346638528859811704183484516925440"); accurate &= testCalculation_strtol("-3402823466"); accurate &= testCalculation_strtol("-3402823466e+29F"); accurate &= testCalculation_strtol("402823466385288598117"); accurate &= testCalculation_strtol("402823466"); accurate &= testCalculation_strtol("402823466e+28F"); accurate &= testCalculation_strtol("402823466385288598117"); accurate &= testCalculation_strtol("-402823466"); accurate &= testCalculation_strtol("-402823466e+28F"); accurate &= testCalculation_strtol(".00234567"); accurate &= testCalculation_strtol("-234567"); accurate &= testCalculation_strtol("234567"); accurate &= testCalculation_strtol("-234567"); accurate &= testCalculation_strtol("1175494351"); accurate &= testCalculation_strtol("11754943512"); accurate &= testCalculation_strtol("11754943513"); accurate &= testCalculation_strtol("11754943514"); accurate &= testCalculation_strtol("-1175494351"); accurate &= testCalculation_strtol("123456789"); accurate &= testCalculation_strtol("-123456789"); accurate &= testCalculation_strtol("123456.789"); accurate &= testCalculation_strtol("-123456.789"); accurate &= testCalculation_strtol("-109446526"); if(!accurate) { logTestString("Calculation is not accurate, so the speed is irrelevant\n"); return false; } #ifndef _DEBUG // it's only faster in release IrrlichtDevice* device = createDevice(video::EDT_NULL); if (!device) return false; ITimer* timer = device->getTimer(); const int ITERATIONS = 1000000; int i; s32 value; u32 then = timer->getRealTime(); for(i = 0; i < ITERATIONS; ++i) value = strtol("-3402823466", 0, 10); const u32 strtolTime = timer->getRealTime() - then; then += strtolTime; for(i = 0; i < ITERATIONS; ++i) value = strtol10("-3402823466"); const u32 strtol10Time = timer->getRealTime() - then; then += strtol10Time; for(i = 0; i < ITERATIONS; ++i) value = old_strtol10("-3402823466"); const u32 oldstrtol10Time = timer->getRealTime() - then; logTestString("Speed test\n strtol time = %d\n strtol10 time = %d\nold strtol10 time = %d\n", strtolTime, strtol10Time, oldstrtol10Time); device->closeDevice(); device->run(); device->drop(); if (strtol10Time > (1.2f*strtolTime)) { logTestString("The fast method is slower than strtol()\n"); return false; } #endif // #ifndef _DEBUG return true; } bool fast_atof(void) { bool ok = true; ok &= test_fast_atof() ; ok &= test_strtol(); return ok; }
gpl-3.0
fhedberg/ardupilot
libraries/RC_Channel/examples/RC_UART/RC_UART.cpp
23
3100
/* take RC channels in from UART and put out as PWM */ #include <AP_HAL/AP_HAL.h> #include <GCS_MAVLink/include/mavlink/v2.0/checksum.h> const AP_HAL::HAL& hal = AP_HAL::get_HAL(); #define NUM_CHANNELS 4 #define ESC_MAGIC 0xF7 #define RC_SPEED 490 #define UART serial(4) class RC_UART : public AP_HAL::HAL::Callbacks { public: // HAL::Callbacks implementation. void setup() override; void loop() override; private: uint8_t read_wait(void); uint8_t enable_mask; const uint32_t baudrate = 115200; uint32_t counter; }; void RC_UART::setup() { hal.scheduler->delay(1000); hal.console->printf("RC_UART starting\n"); hal.UART->begin(baudrate, 512, 512); hal.rcout->set_freq(0xFF, RC_SPEED); } uint8_t RC_UART::read_wait(void) { while (true) { int16_t c = hal.UART->read(); if (c != -1) { // hal.console->printf("c=0x%02x\n", (unsigned)c); return c; } hal.scheduler->delay_microseconds(100); } } void RC_UART::loop() { union { uint16_t period[NUM_CHANNELS]; uint8_t bytes[NUM_CHANNELS*2]; } u; // wait for magic while (true) { uint8_t c = read_wait(); if (c == ESC_MAGIC) break; // hal.console->printf("c=0x%02x\n", (unsigned)c); } uint8_t nbytes=0; // wait for periods while (nbytes < NUM_CHANNELS*2) { u.bytes[nbytes++] = read_wait(); } // and CRC union { uint8_t crc[2]; uint16_t crc16; } u2; u2.crc[0] = read_wait(); u2.crc[1] = read_wait(); uint16_t crc2 = crc_calculate(u.bytes, NUM_CHANNELS*2); if (crc2 != u2.crc16) { hal.console->printf("bad CRC 0x%04x should be 0x%04x\n", (unsigned)crc2, (unsigned)u2.crc16); return; } // and output for (uint8_t i=0; i<NUM_CHANNELS; i++) { if (u.period[i] == 0) { continue; } if (!(enable_mask & 1U<<i)) { if (enable_mask == 0) { hal.rcout->force_safety_off(); } hal.rcout->enable_ch(i); enable_mask |= 1U<<i; } hal.rcout->write(i, u.period[i]); } // report periods to console for debug counter++; if (counter % 100 == 0) { hal.console->printf("%4u %4u %4u %4u\n", (unsigned)u.period[0], (unsigned)u.period[1], (unsigned)u.period[2], (unsigned)u.period[3]); } // every 10th frame give an RCInput frame if possible if (counter % 10 == 0) { struct PACKED { uint8_t magic = 0xf6; uint16_t rcin[8]; uint16_t crc; } rcin; uint16_t rcval[8]; if (hal.rcin->new_input() && hal.rcin->read(rcval, 8) == 8) { memcpy(rcin.rcin, rcval, sizeof(rcval)); rcin.crc = crc_calculate((uint8_t*)&rcin.rcin[0], 16); hal.UART->write((uint8_t*)&rcin, sizeof(rcin)); } } } RC_UART rc_uart; AP_HAL_MAIN_CALLBACKS(&rc_uart);
gpl-3.0
basdelfos/betaflight
lib/main/DSP_Lib/Source/MatrixFunctions/arm_mat_init_f32.c
280
3115
/* ---------------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_mat_init_f32.c * * Description: Floating-point matrix initialization. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------------- */ #include "arm_math.h" /** * @ingroup groupMatrix */ /** * @defgroup MatrixInit Matrix Initialization * * Initializes the underlying matrix data structure. * The functions set the <code>numRows</code>, * <code>numCols</code>, and <code>pData</code> fields * of the matrix data structure. */ /** * @addtogroup MatrixInit * @{ */ /** * @brief Floating-point matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_f32( arm_matrix_instance_f32 * S, uint16_t nRows, uint16_t nColumns, float32_t * pData) { /* Assign Number of Rows */ S->numRows = nRows; /* Assign Number of Columns */ S->numCols = nColumns; /* Assign Data pointer */ S->pData = pData; } /** * @} end of MatrixInit group */
gpl-3.0
jswxdzc/shadowsocks-android
src/main/jni/openssl/crypto/ec/ecp_nistp521.c
537
63240
/* crypto/ec/ecp_nistp521.c */ /* * Written by Adam Langley (Google) for the OpenSSL project */ /* Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * A 64-bit implementation of the NIST P-521 elliptic curve point multiplication * * OpenSSL integration was taken from Emilia Kasper's work in ecp_nistp224.c. * Otherwise based on Emilia's P224 work, which was inspired by my curve25519 * work which got its smarts from Daniel J. Bernstein's work on the same. */ #include <openssl/opensslconf.h> #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 #ifndef OPENSSL_SYS_VMS #include <stdint.h> #else #include <inttypes.h> #endif #include <string.h> #include <openssl/err.h> #include "ec_lcl.h" #if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) /* even with gcc, the typedef won't work for 32-bit platforms */ typedef __uint128_t uint128_t; /* nonstandard; implemented by gcc on 64-bit platforms */ #else #error "Need GCC 3.1 or later to define type uint128_t" #endif typedef uint8_t u8; typedef uint64_t u64; typedef int64_t s64; /* The underlying field. * * P521 operates over GF(2^521-1). We can serialise an element of this field * into 66 bytes where the most significant byte contains only a single bit. We * call this an felem_bytearray. */ typedef u8 felem_bytearray[66]; /* These are the parameters of P521, taken from FIPS 186-3, section D.1.2.5. * These values are big-endian. */ static const felem_bytearray nistp521_curve_params[5] = { {0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* p */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* a = -3 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}, {0x00, 0x51, 0x95, 0x3e, 0xb9, 0x61, 0x8e, 0x1c, /* b */ 0x9a, 0x1f, 0x92, 0x9a, 0x21, 0xa0, 0xb6, 0x85, 0x40, 0xee, 0xa2, 0xda, 0x72, 0x5b, 0x99, 0xb3, 0x15, 0xf3, 0xb8, 0xb4, 0x89, 0x91, 0x8e, 0xf1, 0x09, 0xe1, 0x56, 0x19, 0x39, 0x51, 0xec, 0x7e, 0x93, 0x7b, 0x16, 0x52, 0xc0, 0xbd, 0x3b, 0xb1, 0xbf, 0x07, 0x35, 0x73, 0xdf, 0x88, 0x3d, 0x2c, 0x34, 0xf1, 0xef, 0x45, 0x1f, 0xd4, 0x6b, 0x50, 0x3f, 0x00}, {0x00, 0xc6, 0x85, 0x8e, 0x06, 0xb7, 0x04, 0x04, /* x */ 0xe9, 0xcd, 0x9e, 0x3e, 0xcb, 0x66, 0x23, 0x95, 0xb4, 0x42, 0x9c, 0x64, 0x81, 0x39, 0x05, 0x3f, 0xb5, 0x21, 0xf8, 0x28, 0xaf, 0x60, 0x6b, 0x4d, 0x3d, 0xba, 0xa1, 0x4b, 0x5e, 0x77, 0xef, 0xe7, 0x59, 0x28, 0xfe, 0x1d, 0xc1, 0x27, 0xa2, 0xff, 0xa8, 0xde, 0x33, 0x48, 0xb3, 0xc1, 0x85, 0x6a, 0x42, 0x9b, 0xf9, 0x7e, 0x7e, 0x31, 0xc2, 0xe5, 0xbd, 0x66}, {0x01, 0x18, 0x39, 0x29, 0x6a, 0x78, 0x9a, 0x3b, /* y */ 0xc0, 0x04, 0x5c, 0x8a, 0x5f, 0xb4, 0x2c, 0x7d, 0x1b, 0xd9, 0x98, 0xf5, 0x44, 0x49, 0x57, 0x9b, 0x44, 0x68, 0x17, 0xaf, 0xbd, 0x17, 0x27, 0x3e, 0x66, 0x2c, 0x97, 0xee, 0x72, 0x99, 0x5e, 0xf4, 0x26, 0x40, 0xc5, 0x50, 0xb9, 0x01, 0x3f, 0xad, 0x07, 0x61, 0x35, 0x3c, 0x70, 0x86, 0xa2, 0x72, 0xc2, 0x40, 0x88, 0xbe, 0x94, 0x76, 0x9f, 0xd1, 0x66, 0x50} }; /* The representation of field elements. * ------------------------------------ * * We represent field elements with nine values. These values are either 64 or * 128 bits and the field element represented is: * v[0]*2^0 + v[1]*2^58 + v[2]*2^116 + ... + v[8]*2^464 (mod p) * Each of the nine values is called a 'limb'. Since the limbs are spaced only * 58 bits apart, but are greater than 58 bits in length, the most significant * bits of each limb overlap with the least significant bits of the next. * * A field element with 64-bit limbs is an 'felem'. One with 128-bit limbs is a * 'largefelem' */ #define NLIMBS 9 typedef uint64_t limb; typedef limb felem[NLIMBS]; typedef uint128_t largefelem[NLIMBS]; static const limb bottom57bits = 0x1ffffffffffffff; static const limb bottom58bits = 0x3ffffffffffffff; /* bin66_to_felem takes a little-endian byte array and converts it into felem * form. This assumes that the CPU is little-endian. */ static void bin66_to_felem(felem out, const u8 in[66]) { out[0] = (*((limb*) &in[0])) & bottom58bits; out[1] = (*((limb*) &in[7]) >> 2) & bottom58bits; out[2] = (*((limb*) &in[14]) >> 4) & bottom58bits; out[3] = (*((limb*) &in[21]) >> 6) & bottom58bits; out[4] = (*((limb*) &in[29])) & bottom58bits; out[5] = (*((limb*) &in[36]) >> 2) & bottom58bits; out[6] = (*((limb*) &in[43]) >> 4) & bottom58bits; out[7] = (*((limb*) &in[50]) >> 6) & bottom58bits; out[8] = (*((limb*) &in[58])) & bottom57bits; } /* felem_to_bin66 takes an felem and serialises into a little endian, 66 byte * array. This assumes that the CPU is little-endian. */ static void felem_to_bin66(u8 out[66], const felem in) { memset(out, 0, 66); (*((limb*) &out[0])) = in[0]; (*((limb*) &out[7])) |= in[1] << 2; (*((limb*) &out[14])) |= in[2] << 4; (*((limb*) &out[21])) |= in[3] << 6; (*((limb*) &out[29])) = in[4]; (*((limb*) &out[36])) |= in[5] << 2; (*((limb*) &out[43])) |= in[6] << 4; (*((limb*) &out[50])) |= in[7] << 6; (*((limb*) &out[58])) = in[8]; } /* To preserve endianness when using BN_bn2bin and BN_bin2bn */ static void flip_endian(u8 *out, const u8 *in, unsigned len) { unsigned i; for (i = 0; i < len; ++i) out[i] = in[len-1-i]; } /* BN_to_felem converts an OpenSSL BIGNUM into an felem */ static int BN_to_felem(felem out, const BIGNUM *bn) { felem_bytearray b_in; felem_bytearray b_out; unsigned num_bytes; /* BN_bn2bin eats leading zeroes */ memset(b_out, 0, sizeof b_out); num_bytes = BN_num_bytes(bn); if (num_bytes > sizeof b_out) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } if (BN_is_negative(bn)) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } num_bytes = BN_bn2bin(bn, b_in); flip_endian(b_out, b_in, num_bytes); bin66_to_felem(out, b_out); return 1; } /* felem_to_BN converts an felem into an OpenSSL BIGNUM */ static BIGNUM *felem_to_BN(BIGNUM *out, const felem in) { felem_bytearray b_in, b_out; felem_to_bin66(b_in, in); flip_endian(b_out, b_in, sizeof b_out); return BN_bin2bn(b_out, sizeof b_out, out); } /* Field operations * ---------------- */ static void felem_one(felem out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 0; } static void felem_assign(felem out, const felem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; out[4] = in[4]; out[5] = in[5]; out[6] = in[6]; out[7] = in[7]; out[8] = in[8]; } /* felem_sum64 sets out = out + in. */ static void felem_sum64(felem out, const felem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; out[4] += in[4]; out[5] += in[5]; out[6] += in[6]; out[7] += in[7]; out[8] += in[8]; } /* felem_scalar sets out = in * scalar */ static void felem_scalar(felem out, const felem in, limb scalar) { out[0] = in[0] * scalar; out[1] = in[1] * scalar; out[2] = in[2] * scalar; out[3] = in[3] * scalar; out[4] = in[4] * scalar; out[5] = in[5] * scalar; out[6] = in[6] * scalar; out[7] = in[7] * scalar; out[8] = in[8] * scalar; } /* felem_scalar64 sets out = out * scalar */ static void felem_scalar64(felem out, limb scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; out[4] *= scalar; out[5] *= scalar; out[6] *= scalar; out[7] *= scalar; out[8] *= scalar; } /* felem_scalar128 sets out = out * scalar */ static void felem_scalar128(largefelem out, limb scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; out[4] *= scalar; out[5] *= scalar; out[6] *= scalar; out[7] *= scalar; out[8] *= scalar; } /* felem_neg sets |out| to |-in| * On entry: * in[i] < 2^59 + 2^14 * On exit: * out[i] < 2^62 */ static void felem_neg(felem out, const felem in) { /* In order to prevent underflow, we subtract from 0 mod p. */ static const limb two62m3 = (((limb)1) << 62) - (((limb)1) << 5); static const limb two62m2 = (((limb)1) << 62) - (((limb)1) << 4); out[0] = two62m3 - in[0]; out[1] = two62m2 - in[1]; out[2] = two62m2 - in[2]; out[3] = two62m2 - in[3]; out[4] = two62m2 - in[4]; out[5] = two62m2 - in[5]; out[6] = two62m2 - in[6]; out[7] = two62m2 - in[7]; out[8] = two62m2 - in[8]; } /* felem_diff64 subtracts |in| from |out| * On entry: * in[i] < 2^59 + 2^14 * On exit: * out[i] < out[i] + 2^62 */ static void felem_diff64(felem out, const felem in) { /* In order to prevent underflow, we add 0 mod p before subtracting. */ static const limb two62m3 = (((limb)1) << 62) - (((limb)1) << 5); static const limb two62m2 = (((limb)1) << 62) - (((limb)1) << 4); out[0] += two62m3 - in[0]; out[1] += two62m2 - in[1]; out[2] += two62m2 - in[2]; out[3] += two62m2 - in[3]; out[4] += two62m2 - in[4]; out[5] += two62m2 - in[5]; out[6] += two62m2 - in[6]; out[7] += two62m2 - in[7]; out[8] += two62m2 - in[8]; } /* felem_diff_128_64 subtracts |in| from |out| * On entry: * in[i] < 2^62 + 2^17 * On exit: * out[i] < out[i] + 2^63 */ static void felem_diff_128_64(largefelem out, const felem in) { /* In order to prevent underflow, we add 0 mod p before subtracting. */ static const limb two63m6 = (((limb)1) << 62) - (((limb)1) << 5); static const limb two63m5 = (((limb)1) << 62) - (((limb)1) << 4); out[0] += two63m6 - in[0]; out[1] += two63m5 - in[1]; out[2] += two63m5 - in[2]; out[3] += two63m5 - in[3]; out[4] += two63m5 - in[4]; out[5] += two63m5 - in[5]; out[6] += two63m5 - in[6]; out[7] += two63m5 - in[7]; out[8] += two63m5 - in[8]; } /* felem_diff_128_64 subtracts |in| from |out| * On entry: * in[i] < 2^126 * On exit: * out[i] < out[i] + 2^127 - 2^69 */ static void felem_diff128(largefelem out, const largefelem in) { /* In order to prevent underflow, we add 0 mod p before subtracting. */ static const uint128_t two127m70 = (((uint128_t)1) << 127) - (((uint128_t)1) << 70); static const uint128_t two127m69 = (((uint128_t)1) << 127) - (((uint128_t)1) << 69); out[0] += (two127m70 - in[0]); out[1] += (two127m69 - in[1]); out[2] += (two127m69 - in[2]); out[3] += (two127m69 - in[3]); out[4] += (two127m69 - in[4]); out[5] += (two127m69 - in[5]); out[6] += (two127m69 - in[6]); out[7] += (two127m69 - in[7]); out[8] += (two127m69 - in[8]); } /* felem_square sets |out| = |in|^2 * On entry: * in[i] < 2^62 * On exit: * out[i] < 17 * max(in[i]) * max(in[i]) */ static void felem_square(largefelem out, const felem in) { felem inx2, inx4; felem_scalar(inx2, in, 2); felem_scalar(inx4, in, 4); /* We have many cases were we want to do * in[x] * in[y] + * in[y] * in[x] * This is obviously just * 2 * in[x] * in[y] * However, rather than do the doubling on the 128 bit result, we * double one of the inputs to the multiplication by reading from * |inx2| */ out[0] = ((uint128_t) in[0]) * in[0]; out[1] = ((uint128_t) in[0]) * inx2[1]; out[2] = ((uint128_t) in[0]) * inx2[2] + ((uint128_t) in[1]) * in[1]; out[3] = ((uint128_t) in[0]) * inx2[3] + ((uint128_t) in[1]) * inx2[2]; out[4] = ((uint128_t) in[0]) * inx2[4] + ((uint128_t) in[1]) * inx2[3] + ((uint128_t) in[2]) * in[2]; out[5] = ((uint128_t) in[0]) * inx2[5] + ((uint128_t) in[1]) * inx2[4] + ((uint128_t) in[2]) * inx2[3]; out[6] = ((uint128_t) in[0]) * inx2[6] + ((uint128_t) in[1]) * inx2[5] + ((uint128_t) in[2]) * inx2[4] + ((uint128_t) in[3]) * in[3]; out[7] = ((uint128_t) in[0]) * inx2[7] + ((uint128_t) in[1]) * inx2[6] + ((uint128_t) in[2]) * inx2[5] + ((uint128_t) in[3]) * inx2[4]; out[8] = ((uint128_t) in[0]) * inx2[8] + ((uint128_t) in[1]) * inx2[7] + ((uint128_t) in[2]) * inx2[6] + ((uint128_t) in[3]) * inx2[5] + ((uint128_t) in[4]) * in[4]; /* The remaining limbs fall above 2^521, with the first falling at * 2^522. They correspond to locations one bit up from the limbs * produced above so we would have to multiply by two to align them. * Again, rather than operate on the 128-bit result, we double one of * the inputs to the multiplication. If we want to double for both this * reason, and the reason above, then we end up multiplying by four. */ /* 9 */ out[0] += ((uint128_t) in[1]) * inx4[8] + ((uint128_t) in[2]) * inx4[7] + ((uint128_t) in[3]) * inx4[6] + ((uint128_t) in[4]) * inx4[5]; /* 10 */ out[1] += ((uint128_t) in[2]) * inx4[8] + ((uint128_t) in[3]) * inx4[7] + ((uint128_t) in[4]) * inx4[6] + ((uint128_t) in[5]) * inx2[5]; /* 11 */ out[2] += ((uint128_t) in[3]) * inx4[8] + ((uint128_t) in[4]) * inx4[7] + ((uint128_t) in[5]) * inx4[6]; /* 12 */ out[3] += ((uint128_t) in[4]) * inx4[8] + ((uint128_t) in[5]) * inx4[7] + ((uint128_t) in[6]) * inx2[6]; /* 13 */ out[4] += ((uint128_t) in[5]) * inx4[8] + ((uint128_t) in[6]) * inx4[7]; /* 14 */ out[5] += ((uint128_t) in[6]) * inx4[8] + ((uint128_t) in[7]) * inx2[7]; /* 15 */ out[6] += ((uint128_t) in[7]) * inx4[8]; /* 16 */ out[7] += ((uint128_t) in[8]) * inx2[8]; } /* felem_mul sets |out| = |in1| * |in2| * On entry: * in1[i] < 2^64 * in2[i] < 2^63 * On exit: * out[i] < 17 * max(in1[i]) * max(in2[i]) */ static void felem_mul(largefelem out, const felem in1, const felem in2) { felem in2x2; felem_scalar(in2x2, in2, 2); out[0] = ((uint128_t) in1[0]) * in2[0]; out[1] = ((uint128_t) in1[0]) * in2[1] + ((uint128_t) in1[1]) * in2[0]; out[2] = ((uint128_t) in1[0]) * in2[2] + ((uint128_t) in1[1]) * in2[1] + ((uint128_t) in1[2]) * in2[0]; out[3] = ((uint128_t) in1[0]) * in2[3] + ((uint128_t) in1[1]) * in2[2] + ((uint128_t) in1[2]) * in2[1] + ((uint128_t) in1[3]) * in2[0]; out[4] = ((uint128_t) in1[0]) * in2[4] + ((uint128_t) in1[1]) * in2[3] + ((uint128_t) in1[2]) * in2[2] + ((uint128_t) in1[3]) * in2[1] + ((uint128_t) in1[4]) * in2[0]; out[5] = ((uint128_t) in1[0]) * in2[5] + ((uint128_t) in1[1]) * in2[4] + ((uint128_t) in1[2]) * in2[3] + ((uint128_t) in1[3]) * in2[2] + ((uint128_t) in1[4]) * in2[1] + ((uint128_t) in1[5]) * in2[0]; out[6] = ((uint128_t) in1[0]) * in2[6] + ((uint128_t) in1[1]) * in2[5] + ((uint128_t) in1[2]) * in2[4] + ((uint128_t) in1[3]) * in2[3] + ((uint128_t) in1[4]) * in2[2] + ((uint128_t) in1[5]) * in2[1] + ((uint128_t) in1[6]) * in2[0]; out[7] = ((uint128_t) in1[0]) * in2[7] + ((uint128_t) in1[1]) * in2[6] + ((uint128_t) in1[2]) * in2[5] + ((uint128_t) in1[3]) * in2[4] + ((uint128_t) in1[4]) * in2[3] + ((uint128_t) in1[5]) * in2[2] + ((uint128_t) in1[6]) * in2[1] + ((uint128_t) in1[7]) * in2[0]; out[8] = ((uint128_t) in1[0]) * in2[8] + ((uint128_t) in1[1]) * in2[7] + ((uint128_t) in1[2]) * in2[6] + ((uint128_t) in1[3]) * in2[5] + ((uint128_t) in1[4]) * in2[4] + ((uint128_t) in1[5]) * in2[3] + ((uint128_t) in1[6]) * in2[2] + ((uint128_t) in1[7]) * in2[1] + ((uint128_t) in1[8]) * in2[0]; /* See comment in felem_square about the use of in2x2 here */ out[0] += ((uint128_t) in1[1]) * in2x2[8] + ((uint128_t) in1[2]) * in2x2[7] + ((uint128_t) in1[3]) * in2x2[6] + ((uint128_t) in1[4]) * in2x2[5] + ((uint128_t) in1[5]) * in2x2[4] + ((uint128_t) in1[6]) * in2x2[3] + ((uint128_t) in1[7]) * in2x2[2] + ((uint128_t) in1[8]) * in2x2[1]; out[1] += ((uint128_t) in1[2]) * in2x2[8] + ((uint128_t) in1[3]) * in2x2[7] + ((uint128_t) in1[4]) * in2x2[6] + ((uint128_t) in1[5]) * in2x2[5] + ((uint128_t) in1[6]) * in2x2[4] + ((uint128_t) in1[7]) * in2x2[3] + ((uint128_t) in1[8]) * in2x2[2]; out[2] += ((uint128_t) in1[3]) * in2x2[8] + ((uint128_t) in1[4]) * in2x2[7] + ((uint128_t) in1[5]) * in2x2[6] + ((uint128_t) in1[6]) * in2x2[5] + ((uint128_t) in1[7]) * in2x2[4] + ((uint128_t) in1[8]) * in2x2[3]; out[3] += ((uint128_t) in1[4]) * in2x2[8] + ((uint128_t) in1[5]) * in2x2[7] + ((uint128_t) in1[6]) * in2x2[6] + ((uint128_t) in1[7]) * in2x2[5] + ((uint128_t) in1[8]) * in2x2[4]; out[4] += ((uint128_t) in1[5]) * in2x2[8] + ((uint128_t) in1[6]) * in2x2[7] + ((uint128_t) in1[7]) * in2x2[6] + ((uint128_t) in1[8]) * in2x2[5]; out[5] += ((uint128_t) in1[6]) * in2x2[8] + ((uint128_t) in1[7]) * in2x2[7] + ((uint128_t) in1[8]) * in2x2[6]; out[6] += ((uint128_t) in1[7]) * in2x2[8] + ((uint128_t) in1[8]) * in2x2[7]; out[7] += ((uint128_t) in1[8]) * in2x2[8]; } static const limb bottom52bits = 0xfffffffffffff; /* felem_reduce converts a largefelem to an felem. * On entry: * in[i] < 2^128 * On exit: * out[i] < 2^59 + 2^14 */ static void felem_reduce(felem out, const largefelem in) { u64 overflow1, overflow2; out[0] = ((limb) in[0]) & bottom58bits; out[1] = ((limb) in[1]) & bottom58bits; out[2] = ((limb) in[2]) & bottom58bits; out[3] = ((limb) in[3]) & bottom58bits; out[4] = ((limb) in[4]) & bottom58bits; out[5] = ((limb) in[5]) & bottom58bits; out[6] = ((limb) in[6]) & bottom58bits; out[7] = ((limb) in[7]) & bottom58bits; out[8] = ((limb) in[8]) & bottom58bits; /* out[i] < 2^58 */ out[1] += ((limb) in[0]) >> 58; out[1] += (((limb) (in[0] >> 64)) & bottom52bits) << 6; /* out[1] < 2^58 + 2^6 + 2^58 * = 2^59 + 2^6 */ out[2] += ((limb) (in[0] >> 64)) >> 52; out[2] += ((limb) in[1]) >> 58; out[2] += (((limb) (in[1] >> 64)) & bottom52bits) << 6; out[3] += ((limb) (in[1] >> 64)) >> 52; out[3] += ((limb) in[2]) >> 58; out[3] += (((limb) (in[2] >> 64)) & bottom52bits) << 6; out[4] += ((limb) (in[2] >> 64)) >> 52; out[4] += ((limb) in[3]) >> 58; out[4] += (((limb) (in[3] >> 64)) & bottom52bits) << 6; out[5] += ((limb) (in[3] >> 64)) >> 52; out[5] += ((limb) in[4]) >> 58; out[5] += (((limb) (in[4] >> 64)) & bottom52bits) << 6; out[6] += ((limb) (in[4] >> 64)) >> 52; out[6] += ((limb) in[5]) >> 58; out[6] += (((limb) (in[5] >> 64)) & bottom52bits) << 6; out[7] += ((limb) (in[5] >> 64)) >> 52; out[7] += ((limb) in[6]) >> 58; out[7] += (((limb) (in[6] >> 64)) & bottom52bits) << 6; out[8] += ((limb) (in[6] >> 64)) >> 52; out[8] += ((limb) in[7]) >> 58; out[8] += (((limb) (in[7] >> 64)) & bottom52bits) << 6; /* out[x > 1] < 2^58 + 2^6 + 2^58 + 2^12 * < 2^59 + 2^13 */ overflow1 = ((limb) (in[7] >> 64)) >> 52; overflow1 += ((limb) in[8]) >> 58; overflow1 += (((limb) (in[8] >> 64)) & bottom52bits) << 6; overflow2 = ((limb) (in[8] >> 64)) >> 52; overflow1 <<= 1; /* overflow1 < 2^13 + 2^7 + 2^59 */ overflow2 <<= 1; /* overflow2 < 2^13 */ out[0] += overflow1; /* out[0] < 2^60 */ out[1] += overflow2; /* out[1] < 2^59 + 2^6 + 2^13 */ out[1] += out[0] >> 58; out[0] &= bottom58bits; /* out[0] < 2^58 * out[1] < 2^59 + 2^6 + 2^13 + 2^2 * < 2^59 + 2^14 */ } static void felem_square_reduce(felem out, const felem in) { largefelem tmp; felem_square(tmp, in); felem_reduce(out, tmp); } static void felem_mul_reduce(felem out, const felem in1, const felem in2) { largefelem tmp; felem_mul(tmp, in1, in2); felem_reduce(out, tmp); } /* felem_inv calculates |out| = |in|^{-1} * * Based on Fermat's Little Theorem: * a^p = a (mod p) * a^{p-1} = 1 (mod p) * a^{p-2} = a^{-1} (mod p) */ static void felem_inv(felem out, const felem in) { felem ftmp, ftmp2, ftmp3, ftmp4; largefelem tmp; unsigned i; felem_square(tmp, in); felem_reduce(ftmp, tmp); /* 2^1 */ felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); /* 2^2 - 2^0 */ felem_assign(ftmp2, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^3 - 2^1 */ felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); /* 2^3 - 2^0 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^4 - 2^1 */ felem_square(tmp, ftmp2); felem_reduce(ftmp3, tmp); /* 2^3 - 2^1 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^4 - 2^2 */ felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^4 - 2^0 */ felem_assign(ftmp2, ftmp3); felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^5 - 2^1 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^6 - 2^2 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^7 - 2^3 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^8 - 2^4 */ felem_assign(ftmp4, ftmp3); felem_mul(tmp, ftmp3, ftmp); felem_reduce(ftmp4, tmp); /* 2^8 - 2^1 */ felem_square(tmp, ftmp4); felem_reduce(ftmp4, tmp); /* 2^9 - 2^2 */ felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^8 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 8; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^16 - 2^8 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^16 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 16; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^32 - 2^16 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^32 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 32; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^64 - 2^32 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^64 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 64; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^128 - 2^64 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^128 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 128; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^256 - 2^128 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^256 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 256; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^512 - 2^256 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^512 - 2^0 */ for (i = 0; i < 9; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^521 - 2^9 */ } felem_mul(tmp, ftmp3, ftmp4); felem_reduce(ftmp3, tmp); /* 2^512 - 2^2 */ felem_mul(tmp, ftmp3, in); felem_reduce(out, tmp); /* 2^512 - 3 */ } /* This is 2^521-1, expressed as an felem */ static const felem kPrime = { 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x01ffffffffffffff }; /* felem_is_zero returns a limb with all bits set if |in| == 0 (mod p) and 0 * otherwise. * On entry: * in[i] < 2^59 + 2^14 */ static limb felem_is_zero(const felem in) { felem ftmp; limb is_zero, is_p; felem_assign(ftmp, in); ftmp[0] += ftmp[8] >> 57; ftmp[8] &= bottom57bits; /* ftmp[8] < 2^57 */ ftmp[1] += ftmp[0] >> 58; ftmp[0] &= bottom58bits; ftmp[2] += ftmp[1] >> 58; ftmp[1] &= bottom58bits; ftmp[3] += ftmp[2] >> 58; ftmp[2] &= bottom58bits; ftmp[4] += ftmp[3] >> 58; ftmp[3] &= bottom58bits; ftmp[5] += ftmp[4] >> 58; ftmp[4] &= bottom58bits; ftmp[6] += ftmp[5] >> 58; ftmp[5] &= bottom58bits; ftmp[7] += ftmp[6] >> 58; ftmp[6] &= bottom58bits; ftmp[8] += ftmp[7] >> 58; ftmp[7] &= bottom58bits; /* ftmp[8] < 2^57 + 4 */ /* The ninth limb of 2*(2^521-1) is 0x03ffffffffffffff, which is * greater than our bound for ftmp[8]. Therefore we only have to check * if the zero is zero or 2^521-1. */ is_zero = 0; is_zero |= ftmp[0]; is_zero |= ftmp[1]; is_zero |= ftmp[2]; is_zero |= ftmp[3]; is_zero |= ftmp[4]; is_zero |= ftmp[5]; is_zero |= ftmp[6]; is_zero |= ftmp[7]; is_zero |= ftmp[8]; is_zero--; /* We know that ftmp[i] < 2^63, therefore the only way that the top bit * can be set is if is_zero was 0 before the decrement. */ is_zero = ((s64) is_zero) >> 63; is_p = ftmp[0] ^ kPrime[0]; is_p |= ftmp[1] ^ kPrime[1]; is_p |= ftmp[2] ^ kPrime[2]; is_p |= ftmp[3] ^ kPrime[3]; is_p |= ftmp[4] ^ kPrime[4]; is_p |= ftmp[5] ^ kPrime[5]; is_p |= ftmp[6] ^ kPrime[6]; is_p |= ftmp[7] ^ kPrime[7]; is_p |= ftmp[8] ^ kPrime[8]; is_p--; is_p = ((s64) is_p) >> 63; is_zero |= is_p; return is_zero; } static int felem_is_zero_int(const felem in) { return (int) (felem_is_zero(in) & ((limb)1)); } /* felem_contract converts |in| to its unique, minimal representation. * On entry: * in[i] < 2^59 + 2^14 */ static void felem_contract(felem out, const felem in) { limb is_p, is_greater, sign; static const limb two58 = ((limb)1) << 58; felem_assign(out, in); out[0] += out[8] >> 57; out[8] &= bottom57bits; /* out[8] < 2^57 */ out[1] += out[0] >> 58; out[0] &= bottom58bits; out[2] += out[1] >> 58; out[1] &= bottom58bits; out[3] += out[2] >> 58; out[2] &= bottom58bits; out[4] += out[3] >> 58; out[3] &= bottom58bits; out[5] += out[4] >> 58; out[4] &= bottom58bits; out[6] += out[5] >> 58; out[5] &= bottom58bits; out[7] += out[6] >> 58; out[6] &= bottom58bits; out[8] += out[7] >> 58; out[7] &= bottom58bits; /* out[8] < 2^57 + 4 */ /* If the value is greater than 2^521-1 then we have to subtract * 2^521-1 out. See the comments in felem_is_zero regarding why we * don't test for other multiples of the prime. */ /* First, if |out| is equal to 2^521-1, we subtract it out to get zero. */ is_p = out[0] ^ kPrime[0]; is_p |= out[1] ^ kPrime[1]; is_p |= out[2] ^ kPrime[2]; is_p |= out[3] ^ kPrime[3]; is_p |= out[4] ^ kPrime[4]; is_p |= out[5] ^ kPrime[5]; is_p |= out[6] ^ kPrime[6]; is_p |= out[7] ^ kPrime[7]; is_p |= out[8] ^ kPrime[8]; is_p--; is_p &= is_p << 32; is_p &= is_p << 16; is_p &= is_p << 8; is_p &= is_p << 4; is_p &= is_p << 2; is_p &= is_p << 1; is_p = ((s64) is_p) >> 63; is_p = ~is_p; /* is_p is 0 iff |out| == 2^521-1 and all ones otherwise */ out[0] &= is_p; out[1] &= is_p; out[2] &= is_p; out[3] &= is_p; out[4] &= is_p; out[5] &= is_p; out[6] &= is_p; out[7] &= is_p; out[8] &= is_p; /* In order to test that |out| >= 2^521-1 we need only test if out[8] * >> 57 is greater than zero as (2^521-1) + x >= 2^522 */ is_greater = out[8] >> 57; is_greater |= is_greater << 32; is_greater |= is_greater << 16; is_greater |= is_greater << 8; is_greater |= is_greater << 4; is_greater |= is_greater << 2; is_greater |= is_greater << 1; is_greater = ((s64) is_greater) >> 63; out[0] -= kPrime[0] & is_greater; out[1] -= kPrime[1] & is_greater; out[2] -= kPrime[2] & is_greater; out[3] -= kPrime[3] & is_greater; out[4] -= kPrime[4] & is_greater; out[5] -= kPrime[5] & is_greater; out[6] -= kPrime[6] & is_greater; out[7] -= kPrime[7] & is_greater; out[8] -= kPrime[8] & is_greater; /* Eliminate negative coefficients */ sign = -(out[0] >> 63); out[0] += (two58 & sign); out[1] -= (1 & sign); sign = -(out[1] >> 63); out[1] += (two58 & sign); out[2] -= (1 & sign); sign = -(out[2] >> 63); out[2] += (two58 & sign); out[3] -= (1 & sign); sign = -(out[3] >> 63); out[3] += (two58 & sign); out[4] -= (1 & sign); sign = -(out[4] >> 63); out[4] += (two58 & sign); out[5] -= (1 & sign); sign = -(out[0] >> 63); out[5] += (two58 & sign); out[6] -= (1 & sign); sign = -(out[6] >> 63); out[6] += (two58 & sign); out[7] -= (1 & sign); sign = -(out[7] >> 63); out[7] += (two58 & sign); out[8] -= (1 & sign); sign = -(out[5] >> 63); out[5] += (two58 & sign); out[6] -= (1 & sign); sign = -(out[6] >> 63); out[6] += (two58 & sign); out[7] -= (1 & sign); sign = -(out[7] >> 63); out[7] += (two58 & sign); out[8] -= (1 & sign); } /* Group operations * ---------------- * * Building on top of the field operations we have the operations on the * elliptic curve group itself. Points on the curve are represented in Jacobian * coordinates */ /* point_double calcuates 2*(x_in, y_in, z_in) * * The method is taken from: * http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b * * Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed. * while x_out == y_in is not (maybe this works, but it's not tested). */ static void point_double(felem x_out, felem y_out, felem z_out, const felem x_in, const felem y_in, const felem z_in) { largefelem tmp, tmp2; felem delta, gamma, beta, alpha, ftmp, ftmp2; felem_assign(ftmp, x_in); felem_assign(ftmp2, x_in); /* delta = z^2 */ felem_square(tmp, z_in); felem_reduce(delta, tmp); /* delta[i] < 2^59 + 2^14 */ /* gamma = y^2 */ felem_square(tmp, y_in); felem_reduce(gamma, tmp); /* gamma[i] < 2^59 + 2^14 */ /* beta = x*gamma */ felem_mul(tmp, x_in, gamma); felem_reduce(beta, tmp); /* beta[i] < 2^59 + 2^14 */ /* alpha = 3*(x-delta)*(x+delta) */ felem_diff64(ftmp, delta); /* ftmp[i] < 2^61 */ felem_sum64(ftmp2, delta); /* ftmp2[i] < 2^60 + 2^15 */ felem_scalar64(ftmp2, 3); /* ftmp2[i] < 3*2^60 + 3*2^15 */ felem_mul(tmp, ftmp, ftmp2); /* tmp[i] < 17(3*2^121 + 3*2^76) * = 61*2^121 + 61*2^76 * < 64*2^121 + 64*2^76 * = 2^127 + 2^82 * < 2^128 */ felem_reduce(alpha, tmp); /* x' = alpha^2 - 8*beta */ felem_square(tmp, alpha); /* tmp[i] < 17*2^120 * < 2^125 */ felem_assign(ftmp, beta); felem_scalar64(ftmp, 8); /* ftmp[i] < 2^62 + 2^17 */ felem_diff_128_64(tmp, ftmp); /* tmp[i] < 2^125 + 2^63 + 2^62 + 2^17 */ felem_reduce(x_out, tmp); /* z' = (y + z)^2 - gamma - delta */ felem_sum64(delta, gamma); /* delta[i] < 2^60 + 2^15 */ felem_assign(ftmp, y_in); felem_sum64(ftmp, z_in); /* ftmp[i] < 2^60 + 2^15 */ felem_square(tmp, ftmp); /* tmp[i] < 17(2^122) * < 2^127 */ felem_diff_128_64(tmp, delta); /* tmp[i] < 2^127 + 2^63 */ felem_reduce(z_out, tmp); /* y' = alpha*(4*beta - x') - 8*gamma^2 */ felem_scalar64(beta, 4); /* beta[i] < 2^61 + 2^16 */ felem_diff64(beta, x_out); /* beta[i] < 2^61 + 2^60 + 2^16 */ felem_mul(tmp, alpha, beta); /* tmp[i] < 17*((2^59 + 2^14)(2^61 + 2^60 + 2^16)) * = 17*(2^120 + 2^75 + 2^119 + 2^74 + 2^75 + 2^30) * = 17*(2^120 + 2^119 + 2^76 + 2^74 + 2^30) * < 2^128 */ felem_square(tmp2, gamma); /* tmp2[i] < 17*(2^59 + 2^14)^2 * = 17*(2^118 + 2^74 + 2^28) */ felem_scalar128(tmp2, 8); /* tmp2[i] < 8*17*(2^118 + 2^74 + 2^28) * = 2^125 + 2^121 + 2^81 + 2^77 + 2^35 + 2^31 * < 2^126 */ felem_diff128(tmp, tmp2); /* tmp[i] < 2^127 - 2^69 + 17(2^120 + 2^119 + 2^76 + 2^74 + 2^30) * = 2^127 + 2^124 + 2^122 + 2^120 + 2^118 + 2^80 + 2^78 + 2^76 + * 2^74 + 2^69 + 2^34 + 2^30 * < 2^128 */ felem_reduce(y_out, tmp); } /* copy_conditional copies in to out iff mask is all ones. */ static void copy_conditional(felem out, const felem in, limb mask) { unsigned i; for (i = 0; i < NLIMBS; ++i) { const limb tmp = mask & (in[i] ^ out[i]); out[i] ^= tmp; } } /* point_add calcuates (x1, y1, z1) + (x2, y2, z2) * * The method is taken from * http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl, * adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity). * * This function includes a branch for checking whether the two input points * are equal (while not equal to the point at infinity). This case never * happens during single point multiplication, so there is no timing leak for * ECDH or ECDSA signing. */ static void point_add(felem x3, felem y3, felem z3, const felem x1, const felem y1, const felem z1, const int mixed, const felem x2, const felem y2, const felem z2) { felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, ftmp6, x_out, y_out, z_out; largefelem tmp, tmp2; limb x_equal, y_equal, z1_is_zero, z2_is_zero; z1_is_zero = felem_is_zero(z1); z2_is_zero = felem_is_zero(z2); /* ftmp = z1z1 = z1**2 */ felem_square(tmp, z1); felem_reduce(ftmp, tmp); if (!mixed) { /* ftmp2 = z2z2 = z2**2 */ felem_square(tmp, z2); felem_reduce(ftmp2, tmp); /* u1 = ftmp3 = x1*z2z2 */ felem_mul(tmp, x1, ftmp2); felem_reduce(ftmp3, tmp); /* ftmp5 = z1 + z2 */ felem_assign(ftmp5, z1); felem_sum64(ftmp5, z2); /* ftmp5[i] < 2^61 */ /* ftmp5 = (z1 + z2)**2 - z1z1 - z2z2 = 2*z1z2 */ felem_square(tmp, ftmp5); /* tmp[i] < 17*2^122 */ felem_diff_128_64(tmp, ftmp); /* tmp[i] < 17*2^122 + 2^63 */ felem_diff_128_64(tmp, ftmp2); /* tmp[i] < 17*2^122 + 2^64 */ felem_reduce(ftmp5, tmp); /* ftmp2 = z2 * z2z2 */ felem_mul(tmp, ftmp2, z2); felem_reduce(ftmp2, tmp); /* s1 = ftmp6 = y1 * z2**3 */ felem_mul(tmp, y1, ftmp2); felem_reduce(ftmp6, tmp); } else { /* We'll assume z2 = 1 (special case z2 = 0 is handled later) */ /* u1 = ftmp3 = x1*z2z2 */ felem_assign(ftmp3, x1); /* ftmp5 = 2*z1z2 */ felem_scalar(ftmp5, z1, 2); /* s1 = ftmp6 = y1 * z2**3 */ felem_assign(ftmp6, y1); } /* u2 = x2*z1z1 */ felem_mul(tmp, x2, ftmp); /* tmp[i] < 17*2^120 */ /* h = ftmp4 = u2 - u1 */ felem_diff_128_64(tmp, ftmp3); /* tmp[i] < 17*2^120 + 2^63 */ felem_reduce(ftmp4, tmp); x_equal = felem_is_zero(ftmp4); /* z_out = ftmp5 * h */ felem_mul(tmp, ftmp5, ftmp4); felem_reduce(z_out, tmp); /* ftmp = z1 * z1z1 */ felem_mul(tmp, ftmp, z1); felem_reduce(ftmp, tmp); /* s2 = tmp = y2 * z1**3 */ felem_mul(tmp, y2, ftmp); /* tmp[i] < 17*2^120 */ /* r = ftmp5 = (s2 - s1)*2 */ felem_diff_128_64(tmp, ftmp6); /* tmp[i] < 17*2^120 + 2^63 */ felem_reduce(ftmp5, tmp); y_equal = felem_is_zero(ftmp5); felem_scalar64(ftmp5, 2); /* ftmp5[i] < 2^61 */ if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) { point_double(x3, y3, z3, x1, y1, z1); return; } /* I = ftmp = (2h)**2 */ felem_assign(ftmp, ftmp4); felem_scalar64(ftmp, 2); /* ftmp[i] < 2^61 */ felem_square(tmp, ftmp); /* tmp[i] < 17*2^122 */ felem_reduce(ftmp, tmp); /* J = ftmp2 = h * I */ felem_mul(tmp, ftmp4, ftmp); felem_reduce(ftmp2, tmp); /* V = ftmp4 = U1 * I */ felem_mul(tmp, ftmp3, ftmp); felem_reduce(ftmp4, tmp); /* x_out = r**2 - J - 2V */ felem_square(tmp, ftmp5); /* tmp[i] < 17*2^122 */ felem_diff_128_64(tmp, ftmp2); /* tmp[i] < 17*2^122 + 2^63 */ felem_assign(ftmp3, ftmp4); felem_scalar64(ftmp4, 2); /* ftmp4[i] < 2^61 */ felem_diff_128_64(tmp, ftmp4); /* tmp[i] < 17*2^122 + 2^64 */ felem_reduce(x_out, tmp); /* y_out = r(V-x_out) - 2 * s1 * J */ felem_diff64(ftmp3, x_out); /* ftmp3[i] < 2^60 + 2^60 * = 2^61 */ felem_mul(tmp, ftmp5, ftmp3); /* tmp[i] < 17*2^122 */ felem_mul(tmp2, ftmp6, ftmp2); /* tmp2[i] < 17*2^120 */ felem_scalar128(tmp2, 2); /* tmp2[i] < 17*2^121 */ felem_diff128(tmp, tmp2); /* tmp[i] < 2^127 - 2^69 + 17*2^122 * = 2^126 - 2^122 - 2^6 - 2^2 - 1 * < 2^127 */ felem_reduce(y_out, tmp); copy_conditional(x_out, x2, z1_is_zero); copy_conditional(x_out, x1, z2_is_zero); copy_conditional(y_out, y2, z1_is_zero); copy_conditional(y_out, y1, z2_is_zero); copy_conditional(z_out, z2, z1_is_zero); copy_conditional(z_out, z1, z2_is_zero); felem_assign(x3, x_out); felem_assign(y3, y_out); felem_assign(z3, z_out); } /* Base point pre computation * -------------------------- * * Two different sorts of precomputed tables are used in the following code. * Each contain various points on the curve, where each point is three field * elements (x, y, z). * * For the base point table, z is usually 1 (0 for the point at infinity). * This table has 16 elements: * index | bits | point * ------+---------+------------------------------ * 0 | 0 0 0 0 | 0G * 1 | 0 0 0 1 | 1G * 2 | 0 0 1 0 | 2^130G * 3 | 0 0 1 1 | (2^130 + 1)G * 4 | 0 1 0 0 | 2^260G * 5 | 0 1 0 1 | (2^260 + 1)G * 6 | 0 1 1 0 | (2^260 + 2^130)G * 7 | 0 1 1 1 | (2^260 + 2^130 + 1)G * 8 | 1 0 0 0 | 2^390G * 9 | 1 0 0 1 | (2^390 + 1)G * 10 | 1 0 1 0 | (2^390 + 2^130)G * 11 | 1 0 1 1 | (2^390 + 2^130 + 1)G * 12 | 1 1 0 0 | (2^390 + 2^260)G * 13 | 1 1 0 1 | (2^390 + 2^260 + 1)G * 14 | 1 1 1 0 | (2^390 + 2^260 + 2^130)G * 15 | 1 1 1 1 | (2^390 + 2^260 + 2^130 + 1)G * * The reason for this is so that we can clock bits into four different * locations when doing simple scalar multiplies against the base point. * * Tables for other points have table[i] = iG for i in 0 .. 16. */ /* gmul is the table of precomputed base points */ static const felem gmul[16][3] = {{{0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x017e7e31c2e5bd66, 0x022cf0615a90a6fe, 0x00127a2ffa8de334, 0x01dfbf9d64a3f877, 0x006b4d3dbaa14b5e, 0x014fed487e0a2bd8, 0x015b4429c6481390, 0x03a73678fb2d988e, 0x00c6858e06b70404}, {0x00be94769fd16650, 0x031c21a89cb09022, 0x039013fad0761353, 0x02657bd099031542, 0x03273e662c97ee72, 0x01e6d11a05ebef45, 0x03d1bd998f544495, 0x03001172297ed0b1, 0x011839296a789a3b}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x0373faacbc875bae, 0x00f325023721c671, 0x00f666fd3dbde5ad, 0x01a6932363f88ea7, 0x01fc6d9e13f9c47b, 0x03bcbffc2bbf734e, 0x013ee3c3647f3a92, 0x029409fefe75d07d, 0x00ef9199963d85e5}, {0x011173743ad5b178, 0x02499c7c21bf7d46, 0x035beaeabb8b1a58, 0x00f989c4752ea0a3, 0x0101e1de48a9c1a3, 0x01a20076be28ba6c, 0x02f8052e5eb2de95, 0x01bfe8f82dea117c, 0x0160074d3c36ddb7}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x012f3fc373393b3b, 0x03d3d6172f1419fa, 0x02adc943c0b86873, 0x00d475584177952b, 0x012a4d1673750ee2, 0x00512517a0f13b0c, 0x02b184671a7b1734, 0x0315b84236f1a50a, 0x00a4afc472edbdb9}, {0x00152a7077f385c4, 0x03044007d8d1c2ee, 0x0065829d61d52b52, 0x00494ff6b6631d0d, 0x00a11d94d5f06bcf, 0x02d2f89474d9282e, 0x0241c5727c06eeb9, 0x0386928710fbdb9d, 0x01f883f727b0dfbe}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x019b0c3c9185544d, 0x006243a37c9d97db, 0x02ee3cbe030a2ad2, 0x00cfdd946bb51e0d, 0x0271c00932606b91, 0x03f817d1ec68c561, 0x03f37009806a369c, 0x03c1f30baf184fd5, 0x01091022d6d2f065}, {0x0292c583514c45ed, 0x0316fca51f9a286c, 0x00300af507c1489a, 0x0295f69008298cf1, 0x02c0ed8274943d7b, 0x016509b9b47a431e, 0x02bc9de9634868ce, 0x005b34929bffcb09, 0x000c1a0121681524}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x0286abc0292fb9f2, 0x02665eee9805b3f7, 0x01ed7455f17f26d6, 0x0346355b83175d13, 0x006284944cd0a097, 0x0191895bcdec5e51, 0x02e288370afda7d9, 0x03b22312bfefa67a, 0x01d104d3fc0613fe}, {0x0092421a12f7e47f, 0x0077a83fa373c501, 0x03bd25c5f696bd0d, 0x035c41e4d5459761, 0x01ca0d1742b24f53, 0x00aaab27863a509c, 0x018b6de47df73917, 0x025c0b771705cd01, 0x01fd51d566d760a7}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x01dd92ff6b0d1dbd, 0x039c5e2e8f8afa69, 0x0261ed13242c3b27, 0x0382c6e67026e6a0, 0x01d60b10be2089f9, 0x03c15f3dce86723f, 0x03c764a32d2a062d, 0x017307eac0fad056, 0x018207c0b96c5256}, {0x0196a16d60e13154, 0x03e6ce74c0267030, 0x00ddbf2b4e52a5aa, 0x012738241bbf31c8, 0x00ebe8dc04685a28, 0x024c2ad6d380d4a2, 0x035ee062a6e62d0e, 0x0029ed74af7d3a0f, 0x00eef32aec142ebd}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x00c31ec398993b39, 0x03a9f45bcda68253, 0x00ac733c24c70890, 0x00872b111401ff01, 0x01d178c23195eafb, 0x03bca2c816b87f74, 0x0261a9af46fbad7a, 0x0324b2a8dd3d28f9, 0x00918121d8f24e23}, {0x032bc8c1ca983cd7, 0x00d869dfb08fc8c6, 0x01693cb61fce1516, 0x012a5ea68f4e88a8, 0x010869cab88d7ae3, 0x009081ad277ceee1, 0x033a77166d064cdc, 0x03955235a1fb3a95, 0x01251a4a9b25b65e}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x00148a3a1b27f40b, 0x0123186df1b31fdc, 0x00026e7beaad34ce, 0x01db446ac1d3dbba, 0x0299c1a33437eaec, 0x024540610183cbb7, 0x0173bb0e9ce92e46, 0x02b937e43921214b, 0x01ab0436a9bf01b5}, {0x0383381640d46948, 0x008dacbf0e7f330f, 0x03602122bcc3f318, 0x01ee596b200620d6, 0x03bd0585fda430b3, 0x014aed77fd123a83, 0x005ace749e52f742, 0x0390fe041da2b842, 0x0189a8ceb3299242}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x012a19d6b3282473, 0x00c0915918b423ce, 0x023a954eb94405ae, 0x00529f692be26158, 0x0289fa1b6fa4b2aa, 0x0198ae4ceea346ef, 0x0047d8cdfbdedd49, 0x00cc8c8953f0f6b8, 0x001424abbff49203}, {0x0256732a1115a03a, 0x0351bc38665c6733, 0x03f7b950fb4a6447, 0x000afffa94c22155, 0x025763d0a4dab540, 0x000511e92d4fc283, 0x030a7e9eda0ee96c, 0x004c3cd93a28bf0a, 0x017edb3a8719217f}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x011de5675a88e673, 0x031d7d0f5e567fbe, 0x0016b2062c970ae5, 0x03f4a2be49d90aa7, 0x03cef0bd13822866, 0x03f0923dcf774a6c, 0x0284bebc4f322f72, 0x016ab2645302bb2c, 0x01793f95dace0e2a}, {0x010646e13527a28f, 0x01ca1babd59dc5e7, 0x01afedfd9a5595df, 0x01f15785212ea6b1, 0x0324e5d64f6ae3f4, 0x02d680f526d00645, 0x0127920fadf627a7, 0x03b383f75df4f684, 0x0089e0057e783b0a}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x00f334b9eb3c26c6, 0x0298fdaa98568dce, 0x01c2d24843a82292, 0x020bcb24fa1b0711, 0x02cbdb3d2b1875e6, 0x0014907598f89422, 0x03abe3aa43b26664, 0x02cbf47f720bc168, 0x0133b5e73014b79b}, {0x034aab5dab05779d, 0x00cdc5d71fee9abb, 0x0399f16bd4bd9d30, 0x03582fa592d82647, 0x02be1cdfb775b0e9, 0x0034f7cea32e94cb, 0x0335a7f08f56f286, 0x03b707e9565d1c8b, 0x0015c946ea5b614f}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x024676f6cff72255, 0x00d14625cac96378, 0x00532b6008bc3767, 0x01fc16721b985322, 0x023355ea1b091668, 0x029de7afdc0317c3, 0x02fc8a7ca2da037c, 0x02de1217d74a6f30, 0x013f7173175b73bf}, {0x0344913f441490b5, 0x0200f9e272b61eca, 0x0258a246b1dd55d2, 0x03753db9ea496f36, 0x025e02937a09c5ef, 0x030cbd3d14012692, 0x01793a67e70dc72a, 0x03ec1d37048a662e, 0x006550f700c32a8d}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x00d3f48a347eba27, 0x008e636649b61bd8, 0x00d3b93716778fb3, 0x004d1915757bd209, 0x019d5311a3da44e0, 0x016d1afcbbe6aade, 0x0241bf5f73265616, 0x0384672e5d50d39b, 0x005009fee522b684}, {0x029b4fab064435fe, 0x018868ee095bbb07, 0x01ea3d6936cc92b8, 0x000608b00f78a2f3, 0x02db911073d1c20f, 0x018205938470100a, 0x01f1e4964cbe6ff2, 0x021a19a29eed4663, 0x01414485f42afa81}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x01612b3a17f63e34, 0x03813992885428e6, 0x022b3c215b5a9608, 0x029b4057e19f2fcb, 0x0384059a587af7e6, 0x02d6400ace6fe610, 0x029354d896e8e331, 0x00c047ee6dfba65e, 0x0037720542e9d49d}, {0x02ce9eed7c5e9278, 0x0374ed703e79643b, 0x01316c54c4072006, 0x005aaa09054b2ee8, 0x002824000c840d57, 0x03d4eba24771ed86, 0x0189c50aabc3bdae, 0x0338c01541e15510, 0x00466d56e38eed42}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x007efd8330ad8bd6, 0x02465ed48047710b, 0x0034c6606b215e0c, 0x016ae30c53cbf839, 0x01fa17bd37161216, 0x018ead4e61ce8ab9, 0x005482ed5f5dee46, 0x037543755bba1d7f, 0x005e5ac7e70a9d0f}, {0x0117e1bb2fdcb2a2, 0x03deea36249f40c4, 0x028d09b4a6246cb7, 0x03524b8855bcf756, 0x023d7d109d5ceb58, 0x0178e43e3223ef9c, 0x0154536a0c6e966a, 0x037964d1286ee9fe, 0x0199bcd90e125055}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}}; /* select_point selects the |idx|th point from a precomputation table and * copies it to out. */ static void select_point(const limb idx, unsigned int size, const felem pre_comp[/* size */][3], felem out[3]) { unsigned i, j; limb *outlimbs = &out[0][0]; memset(outlimbs, 0, 3 * sizeof(felem)); for (i = 0; i < size; i++) { const limb *inlimbs = &pre_comp[i][0][0]; limb mask = i ^ idx; mask |= mask >> 4; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < NLIMBS * 3; j++) outlimbs[j] |= inlimbs[j] & mask; } } /* get_bit returns the |i|th bit in |in| */ static char get_bit(const felem_bytearray in, int i) { if (i < 0) return 0; return (in[i >> 3] >> (i & 7)) & 1; } /* Interleaved point multiplication using precomputed point multiples: * The small point multiples 0*P, 1*P, ..., 16*P are in pre_comp[], * the scalars in scalars[]. If g_scalar is non-NULL, we also add this multiple * of the generator, using certain (large) precomputed multiples in g_pre_comp. * Output point (X, Y, Z) is stored in x_out, y_out, z_out */ static void batch_mul(felem x_out, felem y_out, felem z_out, const felem_bytearray scalars[], const unsigned num_points, const u8 *g_scalar, const int mixed, const felem pre_comp[][17][3], const felem g_pre_comp[16][3]) { int i, skip; unsigned num, gen_mul = (g_scalar != NULL); felem nq[3], tmp[4]; limb bits; u8 sign, digit; /* set nq to the point at infinity */ memset(nq, 0, 3 * sizeof(felem)); /* Loop over all scalars msb-to-lsb, interleaving additions * of multiples of the generator (last quarter of rounds) * and additions of other points multiples (every 5th round). */ skip = 1; /* save two point operations in the first round */ for (i = (num_points ? 520 : 130); i >= 0; --i) { /* double */ if (!skip) point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); /* add multiples of the generator */ if (gen_mul && (i <= 130)) { bits = get_bit(g_scalar, i + 390) << 3; if (i < 130) { bits |= get_bit(g_scalar, i + 260) << 2; bits |= get_bit(g_scalar, i + 130) << 1; bits |= get_bit(g_scalar, i); } /* select the point to add, in constant time */ select_point(bits, 16, g_pre_comp, tmp); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0], tmp[1], tmp[2]); } else { memcpy(nq, tmp, 3 * sizeof(felem)); skip = 0; } } /* do other additions every 5 doublings */ if (num_points && (i % 5 == 0)) { /* loop over all scalars */ for (num = 0; num < num_points; ++num) { bits = get_bit(scalars[num], i + 4) << 5; bits |= get_bit(scalars[num], i + 3) << 4; bits |= get_bit(scalars[num], i + 2) << 3; bits |= get_bit(scalars[num], i + 1) << 2; bits |= get_bit(scalars[num], i) << 1; bits |= get_bit(scalars[num], i - 1); ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); /* select the point to add or subtract, in constant time */ select_point(digit, 17, pre_comp[num], tmp); felem_neg(tmp[3], tmp[1]); /* (X, -Y, Z) is the negative point */ copy_conditional(tmp[1], tmp[3], (-(limb) sign)); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], mixed, tmp[0], tmp[1], tmp[2]); } else { memcpy(nq, tmp, 3 * sizeof(felem)); skip = 0; } } } } felem_assign(x_out, nq[0]); felem_assign(y_out, nq[1]); felem_assign(z_out, nq[2]); } /* Precomputation for the group generator. */ typedef struct { felem g_pre_comp[16][3]; int references; } NISTP521_PRE_COMP; const EC_METHOD *EC_GFp_nistp521_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ec_GFp_nistp521_group_init, ec_GFp_simple_group_finish, ec_GFp_simple_group_clear_finish, ec_GFp_nist_group_copy, ec_GFp_nistp521_group_set_curve, ec_GFp_simple_group_get_curve, ec_GFp_simple_group_get_degree, ec_GFp_simple_group_check_discriminant, ec_GFp_simple_point_init, ec_GFp_simple_point_finish, ec_GFp_simple_point_clear_finish, ec_GFp_simple_point_copy, ec_GFp_simple_point_set_to_infinity, ec_GFp_simple_set_Jprojective_coordinates_GFp, ec_GFp_simple_get_Jprojective_coordinates_GFp, ec_GFp_simple_point_set_affine_coordinates, ec_GFp_nistp521_point_get_affine_coordinates, 0 /* point_set_compressed_coordinates */, 0 /* point2oct */, 0 /* oct2point */, ec_GFp_simple_add, ec_GFp_simple_dbl, ec_GFp_simple_invert, ec_GFp_simple_is_at_infinity, ec_GFp_simple_is_on_curve, ec_GFp_simple_cmp, ec_GFp_simple_make_affine, ec_GFp_simple_points_make_affine, ec_GFp_nistp521_points_mul, ec_GFp_nistp521_precompute_mult, ec_GFp_nistp521_have_precompute_mult, ec_GFp_nist_field_mul, ec_GFp_nist_field_sqr, 0 /* field_div */, 0 /* field_encode */, 0 /* field_decode */, 0 /* field_set_to_one */ }; return &ret; } /******************************************************************************/ /* FUNCTIONS TO MANAGE PRECOMPUTATION */ static NISTP521_PRE_COMP *nistp521_pre_comp_new() { NISTP521_PRE_COMP *ret = NULL; ret = (NISTP521_PRE_COMP *)OPENSSL_malloc(sizeof(NISTP521_PRE_COMP)); if (!ret) { ECerr(EC_F_NISTP521_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE); return ret; } memset(ret->g_pre_comp, 0, sizeof(ret->g_pre_comp)); ret->references = 1; return ret; } static void *nistp521_pre_comp_dup(void *src_) { NISTP521_PRE_COMP *src = src_; /* no need to actually copy, these objects never change! */ CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP); return src_; } static void nistp521_pre_comp_free(void *pre_) { int i; NISTP521_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_free(pre); } static void nistp521_pre_comp_clear_free(void *pre_) { int i; NISTP521_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_cleanse(pre, sizeof(*pre)); OPENSSL_free(pre); } /******************************************************************************/ /* OPENSSL EC_METHOD FUNCTIONS */ int ec_GFp_nistp521_group_init(EC_GROUP *group) { int ret; ret = ec_GFp_simple_group_init(group); group->a_is_minus3 = 1; return ret; } int ec_GFp_nistp521_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BN_CTX *new_ctx = NULL; BIGNUM *curve_p, *curve_a, *curve_b; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((curve_p = BN_CTX_get(ctx)) == NULL) || ((curve_a = BN_CTX_get(ctx)) == NULL) || ((curve_b = BN_CTX_get(ctx)) == NULL)) goto err; BN_bin2bn(nistp521_curve_params[0], sizeof(felem_bytearray), curve_p); BN_bin2bn(nistp521_curve_params[1], sizeof(felem_bytearray), curve_a); BN_bin2bn(nistp521_curve_params[2], sizeof(felem_bytearray), curve_b); if ((BN_cmp(curve_p, p)) || (BN_cmp(curve_a, a)) || (BN_cmp(curve_b, b))) { ECerr(EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE, EC_R_WRONG_CURVE_PARAMETERS); goto err; } group->field_mod_func = BN_nist_mod_521; ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx); err: BN_CTX_end(ctx); if (new_ctx != NULL) BN_CTX_free(new_ctx); return ret; } /* Takes the Jacobian coordinates (X, Y, Z) of a point and returns * (X', Y') = (X/Z^2, Y/Z^3) */ int ec_GFp_nistp521_point_get_affine_coordinates(const EC_GROUP *group, const EC_POINT *point, BIGNUM *x, BIGNUM *y, BN_CTX *ctx) { felem z1, z2, x_in, y_in, x_out, y_out; largefelem tmp; if (EC_POINT_is_at_infinity(group, point)) { ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES, EC_R_POINT_AT_INFINITY); return 0; } if ((!BN_to_felem(x_in, &point->X)) || (!BN_to_felem(y_in, &point->Y)) || (!BN_to_felem(z1, &point->Z))) return 0; felem_inv(z2, z1); felem_square(tmp, z2); felem_reduce(z1, tmp); felem_mul(tmp, x_in, z1); felem_reduce(x_in, tmp); felem_contract(x_out, x_in); if (x != NULL) { if (!felem_to_BN(x, x_out)) { ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } felem_mul(tmp, z1, z2); felem_reduce(z1, tmp); felem_mul(tmp, y_in, z1); felem_reduce(y_in, tmp); felem_contract(y_out, y_in); if (y != NULL) { if (!felem_to_BN(y, y_out)) { ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } return 1; } static void make_points_affine(size_t num, felem points[/* num */][3], felem tmp_felems[/* num+1 */]) { /* Runs in constant time, unless an input is the point at infinity * (which normally shouldn't happen). */ ec_GFp_nistp_points_make_affine_internal( num, points, sizeof(felem), tmp_felems, (void (*)(void *)) felem_one, (int (*)(const void *)) felem_is_zero_int, (void (*)(void *, const void *)) felem_assign, (void (*)(void *, const void *)) felem_square_reduce, (void (*)(void *, const void *, const void *)) felem_mul_reduce, (void (*)(void *, const void *)) felem_inv, (void (*)(void *, const void *)) felem_contract); } /* Computes scalar*generator + \sum scalars[i]*points[i], ignoring NULL values * Result is stored in r (r can equal one of the inputs). */ int ec_GFp_nistp521_points_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx) { int ret = 0; int j; int mixed = 0; BN_CTX *new_ctx = NULL; BIGNUM *x, *y, *z, *tmp_scalar; felem_bytearray g_secret; felem_bytearray *secrets = NULL; felem (*pre_comp)[17][3] = NULL; felem *tmp_felems = NULL; felem_bytearray tmp; unsigned i, num_bytes; int have_pre_comp = 0; size_t num_points = num; felem x_in, y_in, z_in, x_out, y_out, z_out; NISTP521_PRE_COMP *pre = NULL; felem (*g_pre_comp)[3] = NULL; EC_POINT *generator = NULL; const EC_POINT *p = NULL; const BIGNUM *p_scalar = NULL; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL) || ((z = BN_CTX_get(ctx)) == NULL) || ((tmp_scalar = BN_CTX_get(ctx)) == NULL)) goto err; if (scalar != NULL) { pre = EC_EX_DATA_get_data(group->extra_data, nistp521_pre_comp_dup, nistp521_pre_comp_free, nistp521_pre_comp_clear_free); if (pre) /* we have precomputation, try to use it */ g_pre_comp = &pre->g_pre_comp[0]; else /* try to use the standard precomputation */ g_pre_comp = (felem (*)[3]) gmul; generator = EC_POINT_new(group); if (generator == NULL) goto err; /* get the generator from precomputation */ if (!felem_to_BN(x, g_pre_comp[1][0]) || !felem_to_BN(y, g_pre_comp[1][1]) || !felem_to_BN(z, g_pre_comp[1][2])) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB); goto err; } if (!EC_POINT_set_Jprojective_coordinates_GFp(group, generator, x, y, z, ctx)) goto err; if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) /* precomputation matches generator */ have_pre_comp = 1; else /* we don't have valid precomputation: * treat the generator as a random point */ num_points++; } if (num_points > 0) { if (num_points >= 2) { /* unless we precompute multiples for just one point, * converting those into affine form is time well spent */ mixed = 1; } secrets = OPENSSL_malloc(num_points * sizeof(felem_bytearray)); pre_comp = OPENSSL_malloc(num_points * 17 * 3 * sizeof(felem)); if (mixed) tmp_felems = OPENSSL_malloc((num_points * 17 + 1) * sizeof(felem)); if ((secrets == NULL) || (pre_comp == NULL) || (mixed && (tmp_felems == NULL))) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_MALLOC_FAILURE); goto err; } /* we treat NULL scalars as 0, and NULL points as points at infinity, * i.e., they contribute nothing to the linear combination */ memset(secrets, 0, num_points * sizeof(felem_bytearray)); memset(pre_comp, 0, num_points * 17 * 3 * sizeof(felem)); for (i = 0; i < num_points; ++i) { if (i == num) /* we didn't have a valid precomputation, so we pick * the generator */ { p = EC_GROUP_get0_generator(group); p_scalar = scalar; } else /* the i^th point */ { p = points[i]; p_scalar = scalars[i]; } if ((p_scalar != NULL) && (p != NULL)) { /* reduce scalar to 0 <= scalar < 2^521 */ if ((BN_num_bits(p_scalar) > 521) || (BN_is_negative(p_scalar))) { /* this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(p_scalar, tmp); flip_endian(secrets[i], tmp, num_bytes); /* precompute multiples */ if ((!BN_to_felem(x_out, &p->X)) || (!BN_to_felem(y_out, &p->Y)) || (!BN_to_felem(z_out, &p->Z))) goto err; memcpy(pre_comp[i][1][0], x_out, sizeof(felem)); memcpy(pre_comp[i][1][1], y_out, sizeof(felem)); memcpy(pre_comp[i][1][2], z_out, sizeof(felem)); for (j = 2; j <= 16; ++j) { if (j & 1) { point_add( pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][1][0], pre_comp[i][1][1], pre_comp[i][1][2], 0, pre_comp[i][j-1][0], pre_comp[i][j-1][1], pre_comp[i][j-1][2]); } else { point_double( pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][j/2][0], pre_comp[i][j/2][1], pre_comp[i][j/2][2]); } } } } if (mixed) make_points_affine(num_points * 17, pre_comp[0], tmp_felems); } /* the scalar for the generator */ if ((scalar != NULL) && (have_pre_comp)) { memset(g_secret, 0, sizeof(g_secret)); /* reduce scalar to 0 <= scalar < 2^521 */ if ((BN_num_bits(scalar) > 521) || (BN_is_negative(scalar))) { /* this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(scalar, tmp); flip_endian(g_secret, tmp, num_bytes); /* do the multiplication with generator precomputation*/ batch_mul(x_out, y_out, z_out, (const felem_bytearray (*)) secrets, num_points, g_secret, mixed, (const felem (*)[17][3]) pre_comp, (const felem (*)[3]) g_pre_comp); } else /* do the multiplication without generator precomputation */ batch_mul(x_out, y_out, z_out, (const felem_bytearray (*)) secrets, num_points, NULL, mixed, (const felem (*)[17][3]) pre_comp, NULL); /* reduce the output to its unique minimal representation */ felem_contract(x_in, x_out); felem_contract(y_in, y_out); felem_contract(z_in, z_out); if ((!felem_to_BN(x, x_in)) || (!felem_to_BN(y, y_in)) || (!felem_to_BN(z, z_in))) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB); goto err; } ret = EC_POINT_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx); err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (secrets != NULL) OPENSSL_free(secrets); if (pre_comp != NULL) OPENSSL_free(pre_comp); if (tmp_felems != NULL) OPENSSL_free(tmp_felems); return ret; } int ec_GFp_nistp521_precompute_mult(EC_GROUP *group, BN_CTX *ctx) { int ret = 0; NISTP521_PRE_COMP *pre = NULL; int i, j; BN_CTX *new_ctx = NULL; BIGNUM *x, *y; EC_POINT *generator = NULL; felem tmp_felems[16]; /* throw away old precomputation */ EC_EX_DATA_free_data(&group->extra_data, nistp521_pre_comp_dup, nistp521_pre_comp_free, nistp521_pre_comp_clear_free); if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL)) goto err; /* get the generator */ if (group->generator == NULL) goto err; generator = EC_POINT_new(group); if (generator == NULL) goto err; BN_bin2bn(nistp521_curve_params[3], sizeof (felem_bytearray), x); BN_bin2bn(nistp521_curve_params[4], sizeof (felem_bytearray), y); if (!EC_POINT_set_affine_coordinates_GFp(group, generator, x, y, ctx)) goto err; if ((pre = nistp521_pre_comp_new()) == NULL) goto err; /* if the generator is the standard one, use built-in precomputation */ if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) { memcpy(pre->g_pre_comp, gmul, sizeof(pre->g_pre_comp)); ret = 1; goto err; } if ((!BN_to_felem(pre->g_pre_comp[1][0], &group->generator->X)) || (!BN_to_felem(pre->g_pre_comp[1][1], &group->generator->Y)) || (!BN_to_felem(pre->g_pre_comp[1][2], &group->generator->Z))) goto err; /* compute 2^130*G, 2^260*G, 2^390*G */ for (i = 1; i <= 4; i <<= 1) { point_double(pre->g_pre_comp[2*i][0], pre->g_pre_comp[2*i][1], pre->g_pre_comp[2*i][2], pre->g_pre_comp[i][0], pre->g_pre_comp[i][1], pre->g_pre_comp[i][2]); for (j = 0; j < 129; ++j) { point_double(pre->g_pre_comp[2*i][0], pre->g_pre_comp[2*i][1], pre->g_pre_comp[2*i][2], pre->g_pre_comp[2*i][0], pre->g_pre_comp[2*i][1], pre->g_pre_comp[2*i][2]); } } /* g_pre_comp[0] is the point at infinity */ memset(pre->g_pre_comp[0], 0, sizeof(pre->g_pre_comp[0])); /* the remaining multiples */ /* 2^130*G + 2^260*G */ point_add(pre->g_pre_comp[6][0], pre->g_pre_comp[6][1], pre->g_pre_comp[6][2], pre->g_pre_comp[4][0], pre->g_pre_comp[4][1], pre->g_pre_comp[4][2], 0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1], pre->g_pre_comp[2][2]); /* 2^130*G + 2^390*G */ point_add(pre->g_pre_comp[10][0], pre->g_pre_comp[10][1], pre->g_pre_comp[10][2], pre->g_pre_comp[8][0], pre->g_pre_comp[8][1], pre->g_pre_comp[8][2], 0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1], pre->g_pre_comp[2][2]); /* 2^260*G + 2^390*G */ point_add(pre->g_pre_comp[12][0], pre->g_pre_comp[12][1], pre->g_pre_comp[12][2], pre->g_pre_comp[8][0], pre->g_pre_comp[8][1], pre->g_pre_comp[8][2], 0, pre->g_pre_comp[4][0], pre->g_pre_comp[4][1], pre->g_pre_comp[4][2]); /* 2^130*G + 2^260*G + 2^390*G */ point_add(pre->g_pre_comp[14][0], pre->g_pre_comp[14][1], pre->g_pre_comp[14][2], pre->g_pre_comp[12][0], pre->g_pre_comp[12][1], pre->g_pre_comp[12][2], 0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1], pre->g_pre_comp[2][2]); for (i = 1; i < 8; ++i) { /* odd multiples: add G */ point_add(pre->g_pre_comp[2*i+1][0], pre->g_pre_comp[2*i+1][1], pre->g_pre_comp[2*i+1][2], pre->g_pre_comp[2*i][0], pre->g_pre_comp[2*i][1], pre->g_pre_comp[2*i][2], 0, pre->g_pre_comp[1][0], pre->g_pre_comp[1][1], pre->g_pre_comp[1][2]); } make_points_affine(15, &(pre->g_pre_comp[1]), tmp_felems); if (!EC_EX_DATA_set_data(&group->extra_data, pre, nistp521_pre_comp_dup, nistp521_pre_comp_free, nistp521_pre_comp_clear_free)) goto err; ret = 1; pre = NULL; err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (pre) nistp521_pre_comp_free(pre); return ret; } int ec_GFp_nistp521_have_precompute_mult(const EC_GROUP *group) { if (EC_EX_DATA_get_data(group->extra_data, nistp521_pre_comp_dup, nistp521_pre_comp_free, nistp521_pre_comp_clear_free) != NULL) return 1; else return 0; } #else static void *dummy=&dummy; #endif
gpl-3.0
maexlich/boinc-igemathome
client/auto_update.cpp
27
8805
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. #include "cpp.h" #ifdef _WIN32 #include "boinc_win.h" #else #include "config.h" #include <cstring> #endif #include "parse.h" #include "error_numbers.h" #include "filesys.h" #include "util.h" #include "client_msgs.h" #include "file_names.h" #include "client_state.h" #include "log_flags.h" #include "auto_update.h" // while an update is being downloaded, // it's treated like other project files, // except that a version directory is prepended to filenames. // // When the download is complete, // the version directory is moved to the top level dir. AUTO_UPDATE::AUTO_UPDATE() { present = false; install_failed = false; } void AUTO_UPDATE::init() { if (!present) return; // if we (the core client) were run by the updater, // and we're not the same as the new version, // the install must have failed. // Mark it as such so we don't try it again. // if (version.greater_than(gstate.core_client_version)) { if (gstate.run_by_updater) { install_failed = true; msg_printf(0, MSG_INTERNAL_ERROR, "Client auto-update failed; keeping existing version" ); gstate.set_client_state_dirty("auto update init"); } } } int AUTO_UPDATE::parse(MIOFILE& in) { char buf[256]; int retval; while (in.fgets(buf, 256)) { if (match_tag(buf, "</auto_update>")) { return 0; } else if (parse_bool(buf, "install_failed", install_failed)) { continue; } else if (match_tag(buf, "<version>")) { version.parse(in); } else if (match_tag(buf, "<file_ref>")) { FILE_REF fref; retval = fref.parse(in); if (retval) return retval; file_refs.push_back(fref); } else { if (log_flags.unparsed_xml) { msg_printf(NULL, MSG_INFO, "unparsed in boinc_update: %s", buf); } } } return ERR_XML_PARSE; } void AUTO_UPDATE::write(MIOFILE& out) { out.printf( "<auto_update>\n" ); version.write(out); if (install_failed) { out.printf("<install_failed>1</install_failed>\n"); } for (unsigned int i=0; i<file_refs.size(); i++) { file_refs[i].write(out); } out.printf( "</auto_update>\n" ); } // Check whether this <auto_update> is valid, // and if so link it up. // int AUTO_UPDATE::validate_and_link(PROJECT* proj) { char dir[256]; int retval; unsigned int i; FILE_INFO* fip; if (!version.greater_than(gstate.core_client_version)) { msg_printf(NULL, MSG_INFO, "Got request to update to %d.%d.%d; already running %d.%d.%d", version.major, version.minor, version.release, gstate.core_client_version.major, gstate.core_client_version.minor, gstate.core_client_version.release ); return ERR_INVALID_PARAM; } if (gstate.auto_update.present) { if (!version.greater_than(gstate.auto_update.version)) { msg_printf(NULL, MSG_INFO, "Got request to update to %d.%d.%d; already updating to %d.%d.%d", version.major, version.minor, version.release, gstate.auto_update.version.major, gstate.auto_update.version.minor, gstate.auto_update.version.release ); return ERR_INVALID_PARAM; } // TODO: abort in-progress update (and delete files) here } project = proj; int nmain = 0; for (i=0; i<file_refs.size(); i++) { FILE_REF& fref = file_refs[i]; fip = gstate.lookup_file_info(project, fref.file_name); if (!fip) { msg_printf(project, MSG_INTERNAL_ERROR, "missing update file %s", fref.file_name ); return ERR_INVALID_PARAM; } fref.file_info = fip; fip->is_auto_update_file = true; if (fref.main_program) nmain++; } if (nmain != 1) { msg_printf(project, MSG_INTERNAL_ERROR, "Auto update has %d main programs", nmain ); return ERR_INVALID_PARAM; } // create version directory // boinc_version_dir(*project, version, dir); retval = boinc_mkdir(dir); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Couldn't make version dir %s", dir); return retval; } gstate.auto_update = *this; return 0; } void AUTO_UPDATE::install() { unsigned int i; FILE_INFO* fip=0; char version_dir[1024]; char cwd[256]; char *argv[10]; int retval, argc; #ifdef _WIN32 HANDLE pid; #else int pid; #endif msg_printf(NULL, MSG_INFO, "Installing new version of BOINC: %d.%d.%d", version.major, version.minor, version.release ); for (i=0; i<file_refs.size(); i++) { FILE_REF& fref = file_refs[i]; if (fref.main_program) { fip = fref.file_info; break; } } if (!fip) { msg_printf(NULL, MSG_INTERNAL_ERROR, "Main program not found"); return; } boinc_version_dir(*project, version, version_dir); boinc_getcwd(cwd); argv[0] = fip->name; argv[1] = "--install_dir"; argv[2] = cwd; argv[3] = "--run_core"; argv[4] = 0; argc = 4; retval = run_program(version_dir, fip->name, argc, argv, 5, pid); if (retval) { msg_printf(NULL, MSG_INTERNAL_ERROR, "Couldn't launch updater; staying with current version" ); install_failed = true; gstate.set_client_state_dirty("auto update install"); } else { gstate.requested_exit = true; } } // When an update is ready to install, we may need to wait a little: // 1) If there's a GUI RPC connection from a local screensaver // (i.e. that has done a get_screensaver_mode()) // wait for the next get_screensaver_mode() and send it SS_STATUS_QUIT // 2) If there's a GUI RPC connection from a GUI // (i.e. that has done a get_cc_status()) // wait for the next get_cc_status() and return manager_must_quit = true. // Wait an additional 10 seconds in any case void AUTO_UPDATE::poll() { #ifndef SIM if (!present) return; static double last_time = 0; static bool ready_to_install = false; static double quits_sent = 0; if (install_failed) return; if (gstate.now - last_time < 10) return; last_time = gstate.now; if (ready_to_install) { if (quits_sent) { if (gstate.now - quits_sent >= 10) { install(); } } else { if (gstate.gui_rpcs.quits_sent()) { quits_sent = gstate.now; } } } else { for (unsigned int i=0; i<file_refs.size(); i++) { FILE_REF& fref = file_refs[i]; FILE_INFO* fip = fref.file_info; if (fip->status != FILE_PRESENT) return; } ready_to_install = true; gstate.gui_rpcs.send_quits(); } #endif } int VERSION_INFO::parse(MIOFILE& in) { char buf[256]; while (in.fgets(buf, 256)) { if (match_tag(buf, "</version>")) return 0; if (parse_int(buf, "<major>", major)) continue; if (parse_int(buf, "<minor>", minor)) continue; if (parse_int(buf, "<release>", release)) continue; if (parse_bool(buf, "<prerelease>", prerelease)) continue; } return ERR_XML_PARSE; } void VERSION_INFO::write(MIOFILE& out) { out.printf( "<version>\n" " <major>%d</major>\n" " <minor>%d</minor>\n" " <release>%d</release>\n" " <prerelease>%d</prerelease>\n" "</version>\n", major, minor, release, prerelease ); } bool VERSION_INFO::greater_than(VERSION_INFO& vi) { if (major > vi.major) return true; if (major < vi.major) return false; if (minor > vi.minor) return true; if (minor < vi.minor) return false; if (release > vi.release) return true; return false; }
gpl-3.0
dipspb/ardupilot
libraries/AP_HAL/examples/Printf/Printf.cpp
30
2640
#include <AP_Common/AP_Common.h> #include <AP_HAL/AP_HAL.h> const AP_HAL::HAL& hal = AP_HAL::get_HAL(); void setup(void) { hal.console->println("Starting Printf test"); } static const struct { const char *fmt; float v; const char *result; } float_tests[] = { { "%f", 3.71f, "3.710000" }, { "%.1f", 3.71f, "3.7" }, { "%.1f", 3.75f, "3.8" }, { "%.2f", 3.75f, "3.75" }, { "%.7f", 3.75f, "3.750000" }, { "%f", 10.4f, "10.40000" }, { "%f", 10.6f, "10.60000" }, { "%f", 1020.4f, "1020.400" }, { "%f", 1030.6f, "1030.600" }, { "%f", 10.123456f, "10.12346" }, { "%f", 102.123456f, "102.1235" }, { "%f", 1020.123456f, "1020.123" }, { "%.6f", 10.123456f, "10.12346" }, { "%.6f", 102.123456f, "102.1235" }, { "%.6f", 1020.123456f, "1020.123" }, { "%f", 10304052.6f, "1.030405e+07" }, { "%f", 103040501.6f, "1.030405e+08" }, { "%f", 1030405023.6f, "1.030405e+09" }, { "%f", -1030.6f, "-1030.600" }, { "%f", -10304052.6f, "-1.030405e+07" }, { "%f", -103040501.6f, "-1.030405e+08" }, { "%f", -1030405023.6f, "-1.030405e+09" }, { "%e", 103040501.6f, "1.030405e+08" }, { "%g", 103040501.6f, "1.03041e+08" }, { "%e", -103040501.6f, "-1.030405e+08" }, { "%g", -103040501.6f, "-1.03041e+08" }, { "%.0f", 10.4f, "10" }, { "%.0f", 10.6f, "11" }, { "%.1f", 10.4f, "10.4" }, { "%.1f", 10.6f, "10.6" }, }; static void test_printf(void) { uint8_t i; char buf[30]; uint8_t failures = 0; hal.console->printf("Running printf tests\n"); for (i=0; i < ARRAY_SIZE(float_tests); i++) { int ret = hal.util->snprintf(buf, sizeof(buf), float_tests[i].fmt, float_tests[i].v); if (strcmp(buf, float_tests[i].result) != 0) { hal.console->printf("Failed float_tests[%u] '%s' -> '%s' should be '%s'\n", (unsigned)i, float_tests[i].fmt, buf, float_tests[i].result); failures++; } if (ret != (int)strlen(float_tests[i].result)) { hal.console->printf("Failed float_tests[%u] ret=%d/%d '%s' should be '%s'\n", (unsigned)i, ret, (int)strlen(float_tests[i].result), float_tests[i].fmt, float_tests[i].result); failures++; } } hal.console->printf("%u failures\n", (unsigned)failures); } void loop(void) { test_printf(); hal.scheduler->delay(1000); } AP_HAL_MAIN();
gpl-3.0
jeffreysanti/AdventurePlatform
angelscript/as_outputbuffer.cpp
32
2773
/* AngelCode Scripting Library Copyright (c) 2003-2012 Andreas Jonsson 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. The original version of this library can be located at: http://www.angelcode.com/angelscript/ Andreas Jonsson andreas@angelcode.com */ // // as_outputbuffer.cpp // // This class appends strings to one large buffer that can later // be sent to the real output stream // #include "as_config.h" #ifndef AS_NO_COMPILER #include "as_outputbuffer.h" #include "as_scriptengine.h" BEGIN_AS_NAMESPACE asCOutputBuffer::~asCOutputBuffer() { Clear(); } void asCOutputBuffer::Clear() { for( asUINT n = 0; n < messages.GetLength(); n++ ) { if( messages[n] ) { asDELETE(messages[n],message_t); } } messages.SetLength(0); } void asCOutputBuffer::Callback(asSMessageInfo *msg) { message_t *msgInfo = asNEW(message_t); if( msgInfo == 0 ) return; msgInfo->section = msg->section; msgInfo->row = msg->row; msgInfo->col = msg->col; msgInfo->type = msg->type; msgInfo->msg = msg->message; messages.PushLast(msgInfo); } void asCOutputBuffer::Append(asCOutputBuffer &in) { for( asUINT n = 0; n < in.messages.GetLength(); n++ ) messages.PushLast(in.messages[n]); in.messages.SetLength(0); } void asCOutputBuffer::SendToCallback(asCScriptEngine *engine, asSSystemFunctionInterface *func, void *obj) { for( asUINT n = 0; n < messages.GetLength(); n++ ) { asSMessageInfo msg; msg.section = messages[n]->section.AddressOf(); msg.row = messages[n]->row; msg.col = messages[n]->col; msg.type = messages[n]->type; msg.message = messages[n]->msg.AddressOf(); if( func->callConv < ICC_THISCALL ) engine->CallGlobalFunction(&msg, obj, func, 0); else engine->CallObjectMethod(obj, &msg, func, 0); } Clear(); } END_AS_NAMESPACE #endif // AS_NO_COMPILER
gpl-3.0
chibitronics/ltc-os
os/various/cpp_wrappers/ch.cpp
32
16150
/* ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @file ch.cpp * @brief C++ wrapper code. * * @addtogroup cpp_library * @{ */ #include "ch.hpp" namespace chibios_rt { /*------------------------------------------------------------------------* * chibios_rt::Timer * *------------------------------------------------------------------------*/ void Timer::setI(systime_t time, vtfunc_t vtfunc, void *par) { chVTSetI(&timer_ref, time, vtfunc, par); } void Timer::resetI() { if (chVTIsArmedI(&timer_ref)) chVTDoResetI(&timer_ref); } bool Timer::isArmedI(void) { return chVTIsArmedI(&timer_ref); } /*------------------------------------------------------------------------* * chibios_rt::ThreadStayPoint * *------------------------------------------------------------------------*/ msg_t ThreadStayPoint::suspendS(void) { return chThdSuspendS(&thread_ref); } msg_t ThreadStayPoint::suspendS(systime_t timeout) { return chThdSuspendTimeoutS(&thread_ref, timeout); } void ThreadStayPoint::resumeI(msg_t msg) { chThdResumeI(&thread_ref, msg); } void ThreadStayPoint::resumeS(msg_t msg) { chThdResumeS(&thread_ref, msg); } /*------------------------------------------------------------------------* * chibios_rt::ThreadReference * *------------------------------------------------------------------------*/ void ThreadReference::stop(void) { chSysHalt("invoked unimplemented method stop()"); } void ThreadReference::requestTerminate(void) { chDbgAssert(thread_ref != NULL, "not referenced"); chThdTerminate(thread_ref); } #if CH_CFG_USE_WAITEXIT msg_t ThreadReference::wait(void) { chDbgAssert(thread_ref != NULL, "not referenced"); msg_t msg = chThdWait(thread_ref); thread_ref = NULL; return msg; } #endif /* CH_CFG_USE_WAITEXIT */ #if CH_CFG_USE_MESSAGES msg_t ThreadReference::sendMessage(msg_t msg) { chDbgAssert(thread_ref != NULL, "not referenced"); return chMsgSend(thread_ref, msg); } bool ThreadReference::isPendingMessage(void) { chDbgAssert(thread_ref != NULL, "not referenced"); return chMsgIsPendingI(thread_ref); } msg_t ThreadReference::getMessage(void) { chDbgAssert(thread_ref != NULL, "not referenced"); return chMsgGet(thread_ref); } void ThreadReference::releaseMessage(msg_t msg) { chDbgAssert(thread_ref != NULL, "not referenced"); chMsgRelease(thread_ref, msg); } #endif /* CH_CFG_USE_MESSAGES */ #if CH_CFG_USE_EVENTS void ThreadReference::signalEvents(eventmask_t mask) { chDbgAssert(thread_ref != NULL, "not referenced"); chEvtSignal(thread_ref, mask); } void ThreadReference::signalEventsI(eventmask_t mask) { chDbgAssert(thread_ref != NULL, "not referenced"); chEvtSignalI(thread_ref, mask); } #endif /* CH_CFG_USE_EVENTS */ #if CH_CFG_USE_DYNAMIC #endif /* CH_CFG_USE_DYNAMIC */ /*------------------------------------------------------------------------* * chibios_rt::BaseThread * *------------------------------------------------------------------------*/ BaseThread::BaseThread() : ThreadReference(NULL) { } void BaseThread::main(void) { } ThreadReference BaseThread::start(tprio_t prio) { (void)prio; return *this; }; void _thd_start(void *arg) { ((BaseThread *)arg)->main(); } void BaseThread::setName(const char *tname) { chRegSetThreadName(tname); } tprio_t BaseThread::setPriority(tprio_t newprio) { return chThdSetPriority(newprio); } void BaseThread::exit(msg_t msg) { chThdExit(msg); } void BaseThread::exitS(msg_t msg) { chThdExitS(msg); } bool BaseThread::shouldTerminate(void) { return chThdShouldTerminateX(); } void BaseThread::sleep(systime_t interval){ chThdSleep(interval); } void BaseThread::sleepUntil(systime_t time) { chThdSleepUntil(time); } void BaseThread::yield(void) { chThdYield(); } #if CH_CFG_USE_MESSAGES ThreadReference BaseThread::waitMessage(void) { ThreadReference tr(chMsgWait()); return tr; } #endif /* CH_CFG_USE_MESSAGES */ #if CH_CFG_USE_EVENTS eventmask_t BaseThread::getAndClearEvents(eventmask_t mask) { return chEvtGetAndClearEvents(mask); } eventmask_t BaseThread::addEvents(eventmask_t mask) { return chEvtAddEvents(mask); } eventmask_t BaseThread::waitOneEvent(eventmask_t ewmask) { return chEvtWaitOne(ewmask); } eventmask_t BaseThread::waitAnyEvent(eventmask_t ewmask) { return chEvtWaitAny(ewmask); } eventmask_t BaseThread::waitAllEvents(eventmask_t ewmask) { return chEvtWaitAll(ewmask); } #if CH_CFG_USE_EVENTS_TIMEOUT eventmask_t BaseThread::waitOneEventTimeout(eventmask_t ewmask, systime_t time) { return chEvtWaitOneTimeout(ewmask, time); } eventmask_t BaseThread::waitAnyEventTimeout(eventmask_t ewmask, systime_t time) { return chEvtWaitAnyTimeout(ewmask, time); } eventmask_t BaseThread::waitAllEventsTimeout(eventmask_t ewmask, systime_t time) { return chEvtWaitAllTimeout(ewmask, time); } #endif /* CH_CFG_USE_EVENTS_TIMEOUT */ void BaseThread::dispatchEvents(const evhandler_t handlers[], eventmask_t mask) { chEvtDispatch(handlers, mask); } #endif /* CH_CFG_USE_EVENTS */ #if CH_CFG_USE_MUTEXES void BaseThread::unlockMutex(Mutex *mp) { chMtxUnlock(&mp->mutex); } void BaseThread::unlockMutexS(Mutex *mp) { chMtxUnlockS(&mp->mutex); } void BaseThread::unlockAllMutexes(void) { chMtxUnlockAll(); } #endif /* CH_CFG_USE_MUTEXES */ #if CH_CFG_USE_SEMAPHORES /*------------------------------------------------------------------------* * chibios_rt::CounterSemaphore * *------------------------------------------------------------------------*/ CounterSemaphore::CounterSemaphore(cnt_t n) { chSemObjectInit(&sem, n); } void CounterSemaphore::reset(cnt_t n) { chSemReset(&sem, n); } void CounterSemaphore::resetI(cnt_t n) { chSemResetI(&sem, n); } msg_t CounterSemaphore::wait(void) { return chSemWait(&sem); } msg_t CounterSemaphore::waitS(void) { return chSemWaitS(&sem); } msg_t CounterSemaphore::wait(systime_t time) { return chSemWaitTimeout(&sem, time); } msg_t CounterSemaphore::waitS(systime_t time) { return chSemWaitTimeoutS(&sem, time); } void CounterSemaphore::signal(void) { chSemSignal(&sem); } void CounterSemaphore::signalI(void) { chSemSignalI(&sem); } void CounterSemaphore::addCounterI(cnt_t n) { chSemAddCounterI(&sem, n); } cnt_t CounterSemaphore::getCounterI(void) { return chSemGetCounterI(&sem); } msg_t CounterSemaphore::signalWait(CounterSemaphore *ssem, CounterSemaphore *wsem) { return chSemSignalWait(&ssem->sem, &wsem->sem); } /*------------------------------------------------------------------------* * chibios_rt::BinarySemaphore * *------------------------------------------------------------------------*/ BinarySemaphore::BinarySemaphore(bool taken) { chBSemObjectInit(&bsem, taken); } msg_t BinarySemaphore::wait(void) { return chBSemWait(&bsem); } msg_t BinarySemaphore::waitS(void) { return chBSemWaitS(&bsem); } msg_t BinarySemaphore::wait(systime_t time) { return chBSemWaitTimeout(&bsem, time); } msg_t BinarySemaphore::waitS(systime_t time) { return chBSemWaitTimeoutS(&bsem, time); } void BinarySemaphore::reset(bool taken) { chBSemReset(&bsem, taken); } void BinarySemaphore::resetI(bool taken) { chBSemResetI(&bsem, taken); } void BinarySemaphore::signal(void) { chBSemSignal(&bsem); } void BinarySemaphore::signalI(void) { chBSemSignalI(&bsem); } bool BinarySemaphore::getStateI(void) { return (bool)chBSemGetStateI(&bsem); } #endif /* CH_CFG_USE_SEMAPHORES */ #if CH_CFG_USE_MUTEXES /*------------------------------------------------------------------------* * chibios_rt::Mutex * *------------------------------------------------------------------------*/ Mutex::Mutex(void) { chMtxObjectInit(&mutex); } bool Mutex::tryLock(void) { return chMtxTryLock(&mutex); } bool Mutex::tryLockS(void) { return chMtxTryLockS(&mutex); } void Mutex::lock(void) { chMtxLock(&mutex); } void Mutex::lockS(void) { chMtxLockS(&mutex); } void Mutex::unlock(void) { chMtxUnlock(&mutex); } void Mutex::unlockS(void) { chMtxUnlockS(&mutex); } #if CH_CFG_USE_CONDVARS /*------------------------------------------------------------------------* * chibios_rt::CondVar * *------------------------------------------------------------------------*/ CondVar::CondVar(void) { chCondObjectInit(&condvar); } void CondVar::signal(void) { chCondSignal(&condvar); } void CondVar::signalI(void) { chCondSignalI(&condvar); } void CondVar::broadcast(void) { chCondBroadcast(&condvar); } void CondVar::broadcastI(void) { chCondBroadcastI(&condvar); } msg_t CondVar::wait(void) { return chCondWait(&condvar); } msg_t CondVar::waitS(void) { return chCondWaitS(&condvar); } #if CH_CFG_USE_CONDVARS_TIMEOUT msg_t CondVar::wait(systime_t time) { return chCondWaitTimeout(&condvar, time); } #endif /* CH_CFG_USE_CONDVARS_TIMEOUT */ #endif /* CH_CFG_USE_CONDVARS */ #endif /* CH_CFG_USE_MUTEXES */ #if CH_CFG_USE_EVENTS /*------------------------------------------------------------------------* * chibios_rt::EvtListener * *------------------------------------------------------------------------*/ eventflags_t EvtListener::getAndClearFlags(void) { return chEvtGetAndClearFlags(&ev_listener); } eventflags_t EvtListener::getAndClearFlagsI(void) { return chEvtGetAndClearFlagsI(&ev_listener); } /*------------------------------------------------------------------------* * chibios_rt::EvtSource * *------------------------------------------------------------------------*/ EvtSource::EvtSource(void) { chEvtObjectInit(&ev_source); } void EvtSource::registerOne(chibios_rt::EvtListener *elp, eventid_t eid) { chEvtRegister(&ev_source, &elp->ev_listener, eid); } void EvtSource::registerMask(chibios_rt::EvtListener *elp, eventmask_t emask) { chEvtRegisterMask(&ev_source, &elp->ev_listener, emask); } void EvtSource::unregister(chibios_rt::EvtListener *elp) { chEvtUnregister(&ev_source, &elp->ev_listener); } void EvtSource::broadcastFlags(eventflags_t flags) { chEvtBroadcastFlags(&ev_source, flags); } void EvtSource::broadcastFlagsI(eventflags_t flags) { chEvtBroadcastFlagsI(&ev_source, flags); } #endif /* CH_CFG_USE_EVENTS */ #if CH_CFG_USE_QUEUES /*------------------------------------------------------------------------* * chibios_rt::InQueue * *------------------------------------------------------------------------*/ InQueue::InQueue(uint8_t *bp, size_t size, qnotify_t infy, void *link) { chIQObjectInit(&iq, bp, size, infy, link); } size_t InQueue::getFullI(void) { return chIQGetFullI(&iq); } size_t InQueue::getEmptyI(void) { return chIQGetEmptyI(&iq); } bool InQueue::isEmptyI(void) { return (bool)chIQIsEmptyI(&iq); } bool InQueue::isFullI(void) { return (bool)chIQIsFullI(&iq); } void InQueue::resetI(void) { chIQResetI(&iq); } msg_t InQueue::putI(uint8_t b) { return chIQPutI(&iq, b); } msg_t InQueue::get() { return chIQGet(&iq); } msg_t InQueue::get(systime_t time) { return chIQGetTimeout(&iq, time); } size_t InQueue::read(uint8_t *bp, size_t n, systime_t time) { return chIQReadTimeout(&iq, bp, n, time); } /*------------------------------------------------------------------------* * chibios_rt::OutQueue * *------------------------------------------------------------------------*/ OutQueue::OutQueue(uint8_t *bp, size_t size, qnotify_t onfy, void *link) { chOQObjectInit(&oq, bp, size, onfy, link); } size_t OutQueue::getFullI(void) { return chOQGetFullI(&oq); } size_t OutQueue::getEmptyI(void) { return chOQGetEmptyI(&oq); } bool OutQueue::isEmptyI(void) { return (bool)chOQIsEmptyI(&oq); } bool OutQueue::isFullI(void) { return (bool)chOQIsFullI(&oq); } void OutQueue::resetI(void) { chOQResetI(&oq); } msg_t OutQueue::put(uint8_t b) { return chOQPut(&oq, b); } msg_t OutQueue::put(uint8_t b, systime_t time) { return chOQPutTimeout(&oq, b, time); } msg_t OutQueue::getI(void) { return chOQGetI(&oq); } size_t OutQueue::write(const uint8_t *bp, size_t n, systime_t time) { return chOQWriteTimeout(&oq, bp, n, time); } #endif /* CH_CFG_USE_QUEUES */ #if CH_CFG_USE_MEMPOOLS /*------------------------------------------------------------------------* * chibios_rt::MemoryPool * *------------------------------------------------------------------------*/ MemoryPool::MemoryPool(size_t size, memgetfunc_t provider) { chPoolObjectInit(&pool, size, provider); } MemoryPool::MemoryPool(size_t size, memgetfunc_t provider, void* p, size_t n) { chPoolObjectInit(&pool, size, provider); chPoolLoadArray(&pool, p, n); } void MemoryPool::loadArray(void *p, size_t n) { chPoolLoadArray(&pool, p, n); } void *MemoryPool::allocI(void) { return chPoolAllocI(&pool); } void *MemoryPool::alloc(void) { return chPoolAlloc(&pool); } void MemoryPool::free(void *objp) { chPoolFree(&pool, objp); } void MemoryPool::freeI(void *objp) { chPoolFreeI(&pool, objp); } #endif /* CH_CFG_USE_MEMPOOLS */ } /** @} */
gpl-3.0
fw867/ntopng
third-party/rrdtool-1.4.8/src/hash_32.c
35
4381
/* * hash_32 - 32 bit Fowler/Noll/Vo hash code * * *** * * Fowler/Noll/Vo hash * * The basis of this hash algorithm was taken from an idea sent * as reviewer comments to the IEEE POSIX P1003.2 committee by: * * Phong Vo (http://www.research.att.com/info/kpv/) * Glenn Fowler (http://www.research.att.com/~gsf/) * * In a subsequent ballot round: * * Landon Curt Noll (http://reality.sgi.com/chongo/) * * improved on their algorithm. Some people tried this hash * and found that it worked rather well. In an EMail message * to Landon, they named it the ``Fowler/Noll/Vo'' or FNV hash. * * FNV hashes are architected to be fast while maintaining a low * collision rate. The FNV speed allows one to quickly hash lots * of data while maintaining a reasonable collision rate. See: * * http://reality.sgi.com/chongo/tech/comp/fnv/ * * for more details as well as other forms of the FNV hash. *** * * NOTE: The FNV-0 historic hash is not recommended. One should use * the FNV-1 hash instead. * * To use the 32 bit FNV-0 historic hash, pass FNV0_32_INIT as the * Fnv32_t hashval argument to fnv_32_buf() or fnv_32_str(). * * To use the recommended 32 bit FNV-1 hash, pass FNV1_32_INIT as the * Fnv32_t hashval argument to fnv_32_buf() or fnv_32_str(). * *** * * Please do not copyright this code. This code is in the public domain. * * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. * * By: * chongo <Landon Curt Noll> /\oo/\ * http://reality.sgi.com/chongo/ * EMail: chongo_fnv at prime dot engr dot sgi dot com * * Share and Enjoy! :-) */ #include <stdlib.h> #include "fnv.h" /* * 32 bit magic FNV-0 and FNV-1 prime */ #define FNV_32_PRIME ((Fnv32_t)0x01000193) /* * fnv_32_buf - perform a 32 bit Fowler/Noll/Vo hash on a buffer * * input: * buf - start of buffer to hash * len - length of buffer in octets * hval - previous hash value or 0 if first call * * returns: * 32 bit hash as a static hash type * * NOTE: To use the 32 bit FNV-0 historic hash, use FNV0_32_INIT as the hval * argument on the first call to either fnv_32_buf() or fnv_32_str(). * * NOTE: To use the recommended 32 bit FNV-1 hash, use FNV1_32_INIT as the hval * argument on the first call to either fnv_32_buf() or fnv_32_str(). */ Fnv32_t fnv_32_buf( const void *buf, size_t len, Fnv32_t hval) { const unsigned char *bp = (const unsigned char *) buf; /* start of buffer */ const unsigned char *be = bp + len; /* beyond end of buffer */ /* * FNV-1 hash each octet in the buffer */ while (bp < be) { /* multiply by the 32 bit FNV magic prime mod 2^64 */ hval *= FNV_32_PRIME; /* xor the bottom with the current octet */ hval ^= (Fnv32_t) *bp++; } /* return our new hash value */ return hval; } /* * fnv_32_str - perform a 32 bit Fowler/Noll/Vo hash on a string * * input: * str - string to hash * hval - previous hash value or 0 if first call * * returns: * 32 bit hash as a static hash type * * NOTE: To use the 32 bit FNV-0 historic hash, use FNV0_32_INIT as the hval * argument on the first call to either fnv_32_buf() or fnv_32_str(). * * NOTE: To use the recommended 32 bit FNV-1 hash, use FNV1_32_INIT as the hval * argument on the first call to either fnv_32_buf() or fnv_32_str(). */ Fnv32_t fnv_32_str( const char *str, Fnv32_t hval) { const unsigned char *s = (const unsigned char *) str; /* unsigned string */ /* * FNV-1 hash each octet in the buffer */ while (*s) { /* multiply by the 32 bit FNV magic prime mod 2^64 */ hval *= FNV_32_PRIME; /* xor the bottom with the current octet */ hval ^= (Fnv32_t) *s++; } /* return our new hash value */ return hval; } /* a wrapper function for fnv_32_str */ unsigned long FnvHash( const char *str) { return fnv_32_str(str, FNV1_32_INIT); }
gpl-3.0
victorzhao/miniblink49
third_party/skia/src/effects/SkDropShadowImageFilter.cpp
36
5675
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkDropShadowImageFilter.h" #include "SkBitmap.h" #include "SkBlurImageFilter.h" #include "SkCanvas.h" #include "SkColorMatrixFilter.h" #include "SkDevice.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" SkDropShadowImageFilter::SkDropShadowImageFilter(SkScalar dx, SkScalar dy, SkScalar sigmaX, SkScalar sigmaY, SkColor color, ShadowMode shadowMode, SkImageFilter* input, const CropRect* cropRect) : INHERITED(1, &input, cropRect) , fDx(dx) , fDy(dy) , fSigmaX(sigmaX) , fSigmaY(sigmaY) , fColor(color) , fShadowMode(shadowMode) { } SkFlattenable* SkDropShadowImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1); SkScalar dx = buffer.readScalar(); SkScalar dy = buffer.readScalar(); SkScalar sigmaX = buffer.readScalar(); SkScalar sigmaY = buffer.readScalar(); SkColor color = buffer.readColor(); ShadowMode shadowMode = buffer.isVersionLT(SkReadBuffer::kDropShadowMode_Version) ? kDrawShadowAndForeground_ShadowMode : static_cast<ShadowMode>(buffer.readInt()); return Create(dx, dy, sigmaX, sigmaY, color, shadowMode, common.getInput(0), &common.cropRect()); } void SkDropShadowImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fDx); buffer.writeScalar(fDy); buffer.writeScalar(fSigmaX); buffer.writeScalar(fSigmaY); buffer.writeColor(fColor); buffer.writeInt(static_cast<int>(fShadowMode)); } bool SkDropShadowImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const Context& ctx, SkBitmap* result, SkIPoint* offset) const { SkBitmap src = source; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (getInput(0) && !getInput(0)->filterImage(proxy, source, ctx, &src, &srcOffset)) return false; SkIRect bounds; if (!this->applyCropRect(ctx, src, srcOffset, &bounds)) { return false; } SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); if (NULL == device.get()) { return false; } SkCanvas canvas(device.get()); SkVector sigma = SkVector::Make(fSigmaX, fSigmaY); ctx.ctm().mapVectors(&sigma, 1); sigma.fX = SkMaxScalar(0, sigma.fX); sigma.fY = SkMaxScalar(0, sigma.fY); SkAutoTUnref<SkImageFilter> blurFilter(SkBlurImageFilter::Create(sigma.fX, sigma.fY)); SkAutoTUnref<SkColorFilter> colorFilter( SkColorFilter::CreateModeFilter(fColor, SkXfermode::kSrcIn_Mode)); SkPaint paint; paint.setImageFilter(blurFilter.get()); paint.setColorFilter(colorFilter.get()); paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); SkVector offsetVec = SkVector::Make(fDx, fDy); ctx.ctm().mapVectors(&offsetVec, 1); canvas.translate(SkIntToScalar(srcOffset.fX - bounds.fLeft), SkIntToScalar(srcOffset.fY - bounds.fTop)); canvas.drawBitmap(src, offsetVec.fX, offsetVec.fY, &paint); if (fShadowMode == kDrawShadowAndForeground_ShadowMode) { canvas.drawBitmap(src, 0, 0); } *result = device->accessBitmap(false); offset->fX = bounds.fLeft; offset->fY = bounds.fTop; return true; } void SkDropShadowImageFilter::computeFastBounds(const SkRect& src, SkRect* dst) const { if (getInput(0)) { getInput(0)->computeFastBounds(src, dst); } else { *dst = src; } SkRect shadowBounds = *dst; shadowBounds.offset(fDx, fDy); shadowBounds.outset(SkScalarMul(fSigmaX, SkIntToScalar(3)), SkScalarMul(fSigmaY, SkIntToScalar(3))); if (fShadowMode == kDrawShadowAndForeground_ShadowMode) { dst->join(shadowBounds); } else { *dst = shadowBounds; } } bool SkDropShadowImageFilter::onFilterBounds(const SkIRect& src, const SkMatrix& ctm, SkIRect* dst) const { SkIRect bounds = src; SkVector offsetVec = SkVector::Make(fDx, fDy); ctm.mapVectors(&offsetVec, 1); bounds.offset(-SkScalarCeilToInt(offsetVec.x()), -SkScalarCeilToInt(offsetVec.y())); SkVector sigma = SkVector::Make(fSigmaX, fSigmaY); ctm.mapVectors(&sigma, 1); bounds.outset(SkScalarCeilToInt(SkScalarMul(sigma.x(), SkIntToScalar(3))), SkScalarCeilToInt(SkScalarMul(sigma.y(), SkIntToScalar(3)))); if (fShadowMode == kDrawShadowAndForeground_ShadowMode) { bounds.join(src); } if (getInput(0) && !getInput(0)->filterBounds(bounds, ctm, &bounds)) { return false; } *dst = bounds; return true; } #ifndef SK_IGNORE_TO_STRING void SkDropShadowImageFilter::toString(SkString* str) const { str->appendf("SkDropShadowImageFilter: ("); str->appendf("dX: %f ", fDx); str->appendf("dY: %f ", fDy); str->appendf("sigmaX: %f ", fSigmaX); str->appendf("sigmaY: %f ", fSigmaY); str->append("Color: "); str->appendHex(fColor); static const char* gModeStrings[] = { "kDrawShadowAndForeground", "kDrawShadowOnly" }; SK_COMPILE_ASSERT(kShadowModeCount == SK_ARRAY_COUNT(gModeStrings), enum_mismatch); str->appendf(" mode: %s", gModeStrings[fShadowMode]); str->append(")"); } #endif
gpl-3.0
parallaxinc/propgcc
gcc/gcc/testsuite/gfortran.dg/function_types_2.f90
38
1620
! { dg-do compile } ! Tests the fix for PR34431 in which function TYPEs that were ! USE associated would cause an error. ! ! Contributed by Tobias Burnus <burnus@gcc.gnu.org> ! module m1 integer :: hh type t real :: r end type t end module m1 module m2 type t integer :: k end type t end module m2 module m3 contains type(t) function func() use m2 func%k = 77 end function func end module m3 type(t) function a() use m1, only: hh type t2 integer :: j end type t2 type t logical :: b end type t a%b = .true. end function a type(t) function b() use m1, only: hh use m2 use m3 b = func () b%k = 5 end function b type(t) function c() use m1, only: hh type t2 integer :: j end type t2 type t logical :: b end type t c%b = .true. end function c program main type t integer :: m end type t contains type(t) function a1() use m1, only: hh type t2 integer :: j end type t2 type t logical :: b end type t a1%b = .true. end function a1 type(t) function b1() use m1, only: hh use m2, only: t ! NAG f95 believes that the host-associated type(t) ! should be used: ! b1%m = 5 ! However, I (Tobias Burnus) believe that the use-associated one should ! be used: b1%k = 5 end function b1 type(t) function c1() use m1, only: hh type t2 integer :: j end type t2 type t logical :: b end type t c1%b = .true. end function c1 type(t) function d1() d1%m = 55 end function d1 end program main ! { dg-final { cleanup-modules "m1 m2 m3" } }
gpl-3.0
Lazydevs/THUG
includes/FreeImage/LibOpenJPEG/raw.c
39
2815
/* * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2007, Professor Benoit Macq * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /* ========================================================== local functions ========================================================== */ /* ========================================================== RAW encoding interface ========================================================== */ opj_raw_t* opj_raw_create(void) { opj_raw_t *raw = (opj_raw_t*)opj_malloc(sizeof(opj_raw_t)); return raw; } void opj_raw_destroy(opj_raw_t *raw) { if(raw) { opj_free(raw); } } OPJ_UINT32 opj_raw_numbytes(opj_raw_t *raw) { const ptrdiff_t diff = raw->bp - raw->start; assert( diff <= (ptrdiff_t)0xffffffff && diff >= 0 ); /* UINT32_MAX */ return (OPJ_UINT32)diff; } void opj_raw_init_dec(opj_raw_t *raw, OPJ_BYTE *bp, OPJ_UINT32 len) { raw->start = bp; raw->lenmax = len; raw->len = 0; raw->c = 0; raw->ct = 0; } OPJ_UINT32 opj_raw_decode(opj_raw_t *raw) { OPJ_UINT32 d; if (raw->ct == 0) { raw->ct = 8; if (raw->len == raw->lenmax) { raw->c = 0xff; } else { if (raw->c == 0xff) { raw->ct = 7; } raw->c = *(raw->start + raw->len); raw->len++; } } raw->ct--; d = (raw->c >> raw->ct) & 0x01; return d; }
gpl-3.0
ppelleti/gnutls
gl/getopt.c
39
40772
/* Getopt for GNU. NOTE: getopt is part of the C library, so if you don't know what "Keep this file name-space clean" means, talk to drepper@gnu.org before changing it! Copyright (C) 1987-1996, 1998-2004, 2006, 2008-2011 Free Software Foundation, Inc. This file is part of the GNU C Library. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _LIBC # include <config.h> #endif #include "getopt.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifdef _LIBC # include <libintl.h> #else # include "gettext.h" # define _(msgid) gettext (msgid) #endif #if defined _LIBC && defined USE_IN_LIBIO # include <wchar.h> #endif /* This version of `getopt' appears to the caller like standard Unix `getopt' but it behaves differently for the user, since it allows the user to intersperse the options with the other arguments. As `getopt_long' works, it permutes the elements of ARGV so that, when it is done, all the options precede everything else. Thus all application programs are extended to handle flexible argument order. Using `getopt' or setting the environment variable POSIXLY_CORRECT disables permutation. Then the behavior is completely standard. GNU application programs can use a third alternative mode in which they can distinguish the relative order of options and other arguments. */ #include "getopt_int.h" /* For communication from `getopt' to the caller. When `getopt' finds an option that takes an argument, the argument value is returned here. Also, when `ordering' is RETURN_IN_ORDER, each non-option ARGV-element is returned here. */ char *optarg; /* Index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to `getopt'. On entry to `getopt', zero means this is the first call; initialize. When `getopt' returns -1, this is the index of the first of the non-option elements that the caller should itself scan. Otherwise, `optind' communicates from one call to the next how much of ARGV has been scanned so far. */ /* 1003.2 says this must be 1 before any call. */ int optind = 1; /* Callers store zero here to inhibit the error message for unrecognized options. */ int opterr = 1; /* Set to an option character which was unrecognized. This must be initialized on some systems to avoid linking in the system's own getopt implementation. */ int optopt = '?'; /* Keep a global copy of all internal members of getopt_data. */ static struct _getopt_data getopt_data; #if defined HAVE_DECL_GETENV && !HAVE_DECL_GETENV extern char *getenv (); #endif #ifdef _LIBC /* Stored original parameters. XXX This is no good solution. We should rather copy the args so that we can compare them later. But we must not use malloc(3). */ extern int __libc_argc; extern char **__libc_argv; /* Bash 2.0 gives us an environment variable containing flags indicating ARGV elements that should not be considered arguments. */ # ifdef USE_NONOPTION_FLAGS /* Defined in getopt_init.c */ extern char *__getopt_nonoption_flags; # endif # ifdef USE_NONOPTION_FLAGS # define SWAP_FLAGS(ch1, ch2) \ if (d->__nonoption_flags_len > 0) \ { \ char __tmp = __getopt_nonoption_flags[ch1]; \ __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ __getopt_nonoption_flags[ch2] = __tmp; \ } # else # define SWAP_FLAGS(ch1, ch2) # endif #else /* !_LIBC */ # define SWAP_FLAGS(ch1, ch2) #endif /* _LIBC */ /* Exchange two adjacent subsequences of ARGV. One subsequence is elements [first_nonopt,last_nonopt) which contains all the non-options that have been skipped so far. The other is elements [last_nonopt,optind), which contains all the options processed since those non-options were skipped. `first_nonopt' and `last_nonopt' are relocated so that they describe the new indices of the non-options in ARGV after they are moved. */ static void exchange (char **argv, struct _getopt_data *d) { int bottom = d->__first_nonopt; int middle = d->__last_nonopt; int top = d->optind; char *tem; /* Exchange the shorter segment with the far end of the longer segment. That puts the shorter segment into the right place. It leaves the longer segment in the right place overall, but it consists of two parts that need to be swapped next. */ #if defined _LIBC && defined USE_NONOPTION_FLAGS /* First make sure the handling of the `__getopt_nonoption_flags' string can work normally. Our top argument must be in the range of the string. */ if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len) { /* We must extend the array. The user plays games with us and presents new arguments. */ char *new_str = malloc (top + 1); if (new_str == NULL) d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0; else { memset (__mempcpy (new_str, __getopt_nonoption_flags, d->__nonoption_flags_max_len), '\0', top + 1 - d->__nonoption_flags_max_len); d->__nonoption_flags_max_len = top + 1; __getopt_nonoption_flags = new_str; } } #endif while (top > middle && middle > bottom) { if (top - middle > middle - bottom) { /* Bottom segment is the short one. */ int len = middle - bottom; register int i; /* Swap it with the top part of the top segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[top - (middle - bottom) + i]; argv[top - (middle - bottom) + i] = tem; SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); } /* Exclude the moved bottom segment from further swapping. */ top -= len; } else { /* Top segment is the short one. */ int len = top - middle; register int i; /* Swap it with the bottom part of the bottom segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[middle + i]; argv[middle + i] = tem; SWAP_FLAGS (bottom + i, middle + i); } /* Exclude the moved top segment from further swapping. */ bottom += len; } } /* Update records for the slots the non-options now occupy. */ d->__first_nonopt += (d->optind - d->__last_nonopt); d->__last_nonopt = d->optind; } /* Initialize the internal data when the first call is made. */ static const char * _getopt_initialize (int argc _GL_UNUSED, char **argv _GL_UNUSED, const char *optstring, struct _getopt_data *d, int posixly_correct) { /* Start processing options with ARGV-element 1 (since ARGV-element 0 is the program name); the sequence of previously skipped non-option ARGV-elements is empty. */ d->__first_nonopt = d->__last_nonopt = d->optind; d->__nextchar = NULL; d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT"); /* Determine how to handle the ordering of options and nonoptions. */ if (optstring[0] == '-') { d->__ordering = RETURN_IN_ORDER; ++optstring; } else if (optstring[0] == '+') { d->__ordering = REQUIRE_ORDER; ++optstring; } else if (d->__posixly_correct) d->__ordering = REQUIRE_ORDER; else d->__ordering = PERMUTE; #if defined _LIBC && defined USE_NONOPTION_FLAGS if (!d->__posixly_correct && argc == __libc_argc && argv == __libc_argv) { if (d->__nonoption_flags_max_len == 0) { if (__getopt_nonoption_flags == NULL || __getopt_nonoption_flags[0] == '\0') d->__nonoption_flags_max_len = -1; else { const char *orig_str = __getopt_nonoption_flags; int len = d->__nonoption_flags_max_len = strlen (orig_str); if (d->__nonoption_flags_max_len < argc) d->__nonoption_flags_max_len = argc; __getopt_nonoption_flags = (char *) malloc (d->__nonoption_flags_max_len); if (__getopt_nonoption_flags == NULL) d->__nonoption_flags_max_len = -1; else memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), '\0', d->__nonoption_flags_max_len - len); } } d->__nonoption_flags_len = d->__nonoption_flags_max_len; } else d->__nonoption_flags_len = 0; #endif return optstring; } /* Scan elements of ARGV (whose length is ARGC) for option characters given in OPTSTRING. If an element of ARGV starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If `getopt' is called repeatedly, it returns successively each of the option characters from each of the option elements. If `getopt' finds another option character, it returns that character, updating `optind' and `nextchar' so that the next call to `getopt' can resume the scan with the following option character or ARGV-element. If there are no more option characters, `getopt' returns -1. Then `optind' is the index in ARGV of the first ARGV-element that is not an option. (The ARGV-elements have been permuted so that those that are not options now come last.) OPTSTRING is a string containing the legitimate option characters. If an option character is seen that is not listed in OPTSTRING, return '?' after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return '?'. If a char in OPTSTRING is followed by a colon, that means it wants an arg, so the following text in the same ARGV-element, or the text of the following ARGV-element, is returned in `optarg'. Two colons mean an option that wants an optional arg; if there is text in the current ARGV-element, it is returned in `optarg', otherwise `optarg' is set to zero. If OPTSTRING starts with `-' or `+', it requests different methods of handling the non-option ARGV-elements. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. Long-named options begin with `--' instead of `-'. Their names may be abbreviated as long as the abbreviation is unique or is an exact match for some defined option. If they have an argument, it follows the option name in the same ARGV-element, separated from the option name by a `=', or else the in next ARGV-element. When `getopt' finds a long-named option, it returns 0 if that option's `flag' field is nonzero, the value of the option's `val' field if the `flag' field is zero. The elements of ARGV aren't really const, because we permute them. But we pretend they're const in the prototype to be compatible with other systems. LONGOPTS is a vector of `struct option' terminated by an element containing a name which is zero. LONGIND returns the index in LONGOPT of the long-named option found. It is only valid when a long-named option has been found by the most recent call. If LONG_ONLY is nonzero, '-' as well as '--' can introduce long-named options. */ int _getopt_internal_r (int argc, char **argv, const char *optstring, const struct option *longopts, int *longind, int long_only, struct _getopt_data *d, int posixly_correct) { int print_errors = d->opterr; if (argc < 1) return -1; d->optarg = NULL; if (d->optind == 0 || !d->__initialized) { if (d->optind == 0) d->optind = 1; /* Don't scan ARGV[0], the program name. */ optstring = _getopt_initialize (argc, argv, optstring, d, posixly_correct); d->__initialized = 1; } else if (optstring[0] == '-' || optstring[0] == '+') optstring++; if (optstring[0] == ':') print_errors = 0; /* Test whether ARGV[optind] points to a non-option argument. Either it does not have option syntax, or there is an environment flag from the shell indicating it is not an option. The later information is only used when the used in the GNU libc. */ #if defined _LIBC && defined USE_NONOPTION_FLAGS # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \ || (d->optind < d->__nonoption_flags_len \ && __getopt_nonoption_flags[d->optind] == '1')) #else # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0') #endif if (d->__nextchar == NULL || *d->__nextchar == '\0') { /* Advance to the next ARGV-element. */ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been moved back by the user (who may also have changed the arguments). */ if (d->__last_nonopt > d->optind) d->__last_nonopt = d->optind; if (d->__first_nonopt > d->optind) d->__first_nonopt = d->optind; if (d->__ordering == PERMUTE) { /* If we have just processed some options following some non-options, exchange them so that the options come first. */ if (d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind) exchange ((char **) argv, d); else if (d->__last_nonopt != d->optind) d->__first_nonopt = d->optind; /* Skip any additional non-options and extend the range of non-options previously skipped. */ while (d->optind < argc && NONOPTION_P) d->optind++; d->__last_nonopt = d->optind; } /* The special ARGV-element `--' means premature end of options. Skip it like a null option, then exchange with previous non-options as if it were an option, then skip everything else like a non-option. */ if (d->optind != argc && !strcmp (argv[d->optind], "--")) { d->optind++; if (d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind) exchange ((char **) argv, d); else if (d->__first_nonopt == d->__last_nonopt) d->__first_nonopt = d->optind; d->__last_nonopt = argc; d->optind = argc; } /* If we have done all the ARGV-elements, stop the scan and back over any non-options that we skipped and permuted. */ if (d->optind == argc) { /* Set the next-arg-index to point at the non-options that we previously skipped, so the caller will digest them. */ if (d->__first_nonopt != d->__last_nonopt) d->optind = d->__first_nonopt; return -1; } /* If we have come to a non-option and did not permute it, either stop the scan or describe it to the caller and pass it by. */ if (NONOPTION_P) { if (d->__ordering == REQUIRE_ORDER) return -1; d->optarg = argv[d->optind++]; return 1; } /* We have found another option-ARGV-element. Skip the initial punctuation. */ d->__nextchar = (argv[d->optind] + 1 + (longopts != NULL && argv[d->optind][1] == '-')); } /* Decode the current option-ARGV-element. */ /* Check whether the ARGV-element is a long option. If long_only and the ARGV-element has the form "-f", where f is a valid short option, don't consider it an abbreviated form of a long option that starts with f. Otherwise there would be no way to give the -f short option. On the other hand, if there's a long option "fubar" and the ARGV-element is "-fu", do consider that an abbreviation of the long option, just like "--fu", and not "-f" with arg "u". This distinction seems to be the most useful approach. */ if (longopts != NULL && (argv[d->optind][1] == '-' || (long_only && (argv[d->optind][2] || !strchr (optstring, argv[d->optind][1]))))) { char *nameend; unsigned int namelen; const struct option *p; const struct option *pfound = NULL; struct option_list { const struct option *p; struct option_list *next; } *ambig_list = NULL; int exact = 0; int indfound = -1; int option_index; for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; namelen = nameend - d->__nextchar; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, d->__nextchar, namelen)) { if (namelen == (unsigned int) strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val) { /* Second or later nonexact match found. */ struct option_list *newp = malloc (sizeof (*newp)); newp->p = p; newp->next = ambig_list; ambig_list = newp; } } if (ambig_list != NULL && !exact) { if (print_errors) { struct option_list first; first.p = pfound; first.next = ambig_list; ambig_list = &first; #if defined _LIBC && defined USE_IN_LIBIO char *buf = NULL; size_t buflen = 0; FILE *fp = open_memstream (&buf, &buflen); if (fp != NULL) { fprintf (fp, _("%s: option '%s' is ambiguous; possibilities:"), argv[0], argv[d->optind]); do { fprintf (fp, " '--%s'", ambig_list->p->name); ambig_list = ambig_list->next; } while (ambig_list != NULL); fputc_unlocked ('\n', fp); if (__builtin_expect (fclose (fp) != EOF, 1)) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } } #else fprintf (stderr, _("%s: option '%s' is ambiguous; possibilities:"), argv[0], argv[d->optind]); do { fprintf (stderr, " '--%s'", ambig_list->p->name); ambig_list = ambig_list->next; } while (ambig_list != NULL); fputc ('\n', stderr); #endif } d->__nextchar += strlen (d->__nextchar); d->optind++; d->optopt = 0; return '?'; } while (ambig_list != NULL) { struct option_list *pn = ambig_list->next; free (ambig_list); ambig_list = pn; } if (pfound != NULL) { option_index = indfound; d->optind++; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) d->optarg = nameend + 1; else { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; int n; #endif if (argv[d->optind - 1][1] == '-') { /* --option */ #if defined _LIBC && defined USE_IN_LIBIO n = __asprintf (&buf, _("\ %s: option '--%s' doesn't allow an argument\n"), argv[0], pfound->name); #else fprintf (stderr, _("\ %s: option '--%s' doesn't allow an argument\n"), argv[0], pfound->name); #endif } else { /* +option or -option */ #if defined _LIBC && defined USE_IN_LIBIO n = __asprintf (&buf, _("\ %s: option '%c%s' doesn't allow an argument\n"), argv[0], argv[d->optind - 1][0], pfound->name); #else fprintf (stderr, _("\ %s: option '%c%s' doesn't allow an argument\n"), argv[0], argv[d->optind - 1][0], pfound->name); #endif } #if defined _LIBC && defined USE_IN_LIBIO if (n >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #endif } d->__nextchar += strlen (d->__nextchar); d->optopt = pfound->val; return '?'; } } else if (pfound->has_arg == 1) { if (d->optind < argc) d->optarg = argv[d->optind++]; else { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; if (__asprintf (&buf, _("\ %s: option '--%s' requires an argument\n"), argv[0], pfound->name) >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #else fprintf (stderr, _("%s: option '--%s' requires an argument\n"), argv[0], pfound->name); #endif } d->__nextchar += strlen (d->__nextchar); d->optopt = pfound->val; return optstring[0] == ':' ? ':' : '?'; } } d->__nextchar += strlen (d->__nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } /* Can't find it as a long option. If this is not getopt_long_only, or the option starts with '--' or is not a valid short option, then it's an error. Otherwise interpret it as a short option. */ if (!long_only || argv[d->optind][1] == '-' || strchr (optstring, *d->__nextchar) == NULL) { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; int n; #endif if (argv[d->optind][1] == '-') { /* --option */ #if defined _LIBC && defined USE_IN_LIBIO n = __asprintf (&buf, _("%s: unrecognized option '--%s'\n"), argv[0], d->__nextchar); #else fprintf (stderr, _("%s: unrecognized option '--%s'\n"), argv[0], d->__nextchar); #endif } else { /* +option or -option */ #if defined _LIBC && defined USE_IN_LIBIO n = __asprintf (&buf, _("%s: unrecognized option '%c%s'\n"), argv[0], argv[d->optind][0], d->__nextchar); #else fprintf (stderr, _("%s: unrecognized option '%c%s'\n"), argv[0], argv[d->optind][0], d->__nextchar); #endif } #if defined _LIBC && defined USE_IN_LIBIO if (n >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #endif } d->__nextchar = (char *) ""; d->optind++; d->optopt = 0; return '?'; } } /* Look at and handle the next short option-character. */ { char c = *d->__nextchar++; const char *temp = strchr (optstring, c); /* Increment `optind' when we start to process its last character. */ if (*d->__nextchar == '\0') ++d->optind; if (temp == NULL || c == ':' || c == ';') { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; int n; #endif #if defined _LIBC && defined USE_IN_LIBIO n = __asprintf (&buf, _("%s: invalid option -- '%c'\n"), argv[0], c); #else fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c); #endif #if defined _LIBC && defined USE_IN_LIBIO if (n >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #endif } d->optopt = c; return '?'; } /* Convenience. Treat POSIX -W foo same as long option --foo */ if (temp[0] == 'W' && temp[1] == ';') { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = 0; int option_index; if (longopts == NULL) goto no_longs; /* This is an option that requires an argument. */ if (*d->__nextchar != '\0') { d->optarg = d->__nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ d->optind++; } else if (d->optind == argc) { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; if (__asprintf (&buf, _("%s: option requires an argument -- '%c'\n"), argv[0], c) >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #else fprintf (stderr, _("%s: option requires an argument -- '%c'\n"), argv[0], c); #endif } d->optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; return c; } else /* We already incremented `d->optind' once; increment it again when taking next ARGV-elt as argument. */ d->optarg = argv[d->optind++]; /* optarg is now the argument, see if it's in the table of longopts. */ for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar)) { if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val) /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; if (__asprintf (&buf, _("%s: option '-W %s' is ambiguous\n"), argv[0], d->optarg) >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #else fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"), argv[0], d->optarg); #endif } d->__nextchar += strlen (d->__nextchar); d->optind++; return '?'; } if (pfound != NULL) { option_index = indfound; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) d->optarg = nameend + 1; else { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; if (__asprintf (&buf, _("\ %s: option '-W %s' doesn't allow an argument\n"), argv[0], pfound->name) >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #else fprintf (stderr, _("\ %s: option '-W %s' doesn't allow an argument\n"), argv[0], pfound->name); #endif } d->__nextchar += strlen (d->__nextchar); return '?'; } } else if (pfound->has_arg == 1) { if (d->optind < argc) d->optarg = argv[d->optind++]; else { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; if (__asprintf (&buf, _("\ %s: option '-W %s' requires an argument\n"), argv[0], pfound->name) >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #else fprintf (stderr, _("\ %s: option '-W %s' requires an argument\n"), argv[0], pfound->name); #endif } d->__nextchar += strlen (d->__nextchar); return optstring[0] == ':' ? ':' : '?'; } } else d->optarg = NULL; d->__nextchar += strlen (d->__nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } no_longs: d->__nextchar = NULL; return 'W'; /* Let the application handle it. */ } if (temp[1] == ':') { if (temp[2] == ':') { /* This is an option that accepts an argument optionally. */ if (*d->__nextchar != '\0') { d->optarg = d->__nextchar; d->optind++; } else d->optarg = NULL; d->__nextchar = NULL; } else { /* This is an option that requires an argument. */ if (*d->__nextchar != '\0') { d->optarg = d->__nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ d->optind++; } else if (d->optind == argc) { if (print_errors) { #if defined _LIBC && defined USE_IN_LIBIO char *buf; if (__asprintf (&buf, _("\ %s: option requires an argument -- '%c'\n"), argv[0], c) >= 0) { _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; __fxprintf (NULL, "%s", buf); ((_IO_FILE *) stderr)->_flags2 = old_flags2; _IO_funlockfile (stderr); free (buf); } #else fprintf (stderr, _("%s: option requires an argument -- '%c'\n"), argv[0], c); #endif } d->optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ d->optarg = argv[d->optind++]; d->__nextchar = NULL; } } return c; } } int _getopt_internal (int argc, char **argv, const char *optstring, const struct option *longopts, int *longind, int long_only, int posixly_correct) { int result; getopt_data.optind = optind; getopt_data.opterr = opterr; result = _getopt_internal_r (argc, argv, optstring, longopts, longind, long_only, &getopt_data, posixly_correct); optind = getopt_data.optind; optarg = getopt_data.optarg; optopt = getopt_data.optopt; return result; } /* glibc gets a LSB-compliant getopt. Standalone applications get a POSIX-compliant getopt. */ #if _LIBC enum { POSIXLY_CORRECT = 0 }; #else enum { POSIXLY_CORRECT = 1 }; #endif int getopt (int argc, char *const *argv, const char *optstring) { return _getopt_internal (argc, (char **) argv, optstring, (const struct option *) 0, (int *) 0, 0, POSIXLY_CORRECT); } #ifdef _LIBC int __posix_getopt (int argc, char *const *argv, const char *optstring) { return _getopt_internal (argc, argv, optstring, (const struct option *) 0, (int *) 0, 0, 1); } #endif #ifdef TEST /* Compile with -DTEST to make an executable for use in testing the above definition of `getopt'. */ int main (int argc, char **argv) { int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; c = getopt (argc, argv, "abc:d:0123456789"); if (c == -1) break; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (digit_optind != 0 && digit_optind != this_option_optind) printf ("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf ("option %c\n", c); break; case 'a': printf ("option a\n"); break; case 'b': printf ("option b\n"); break; case 'c': printf ("option c with value '%s'\n", optarg); break; case '?': break; default: printf ("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); } exit (0); } #endif /* TEST */
gpl-3.0
ih24n69/android_kernel_samsung_young23g
net/batman-adv/vis.c
2087
25846
/* Copyright (C) 2008-2013 B.A.T.M.A.N. contributors: * * Simon Wunderlich * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA */ #include "main.h" #include "send.h" #include "translation-table.h" #include "vis.h" #include "soft-interface.h" #include "hard-interface.h" #include "hash.h" #include "originator.h" #define BATADV_MAX_VIS_PACKET_SIZE 1000 /* hash class keys */ static struct lock_class_key batadv_vis_hash_lock_class_key; /* free the info */ static void batadv_free_info(struct kref *ref) { struct batadv_vis_info *info; struct batadv_priv *bat_priv; struct batadv_vis_recvlist_node *entry, *tmp; info = container_of(ref, struct batadv_vis_info, refcount); bat_priv = info->bat_priv; list_del_init(&info->send_list); spin_lock_bh(&bat_priv->vis.list_lock); list_for_each_entry_safe(entry, tmp, &info->recv_list, list) { list_del(&entry->list); kfree(entry); } spin_unlock_bh(&bat_priv->vis.list_lock); kfree_skb(info->skb_packet); kfree(info); } /* Compare two vis packets, used by the hashing algorithm */ static int batadv_vis_info_cmp(const struct hlist_node *node, const void *data2) { const struct batadv_vis_info *d1, *d2; const struct batadv_vis_packet *p1, *p2; d1 = container_of(node, struct batadv_vis_info, hash_entry); d2 = data2; p1 = (struct batadv_vis_packet *)d1->skb_packet->data; p2 = (struct batadv_vis_packet *)d2->skb_packet->data; return batadv_compare_eth(p1->vis_orig, p2->vis_orig); } /* hash function to choose an entry in a hash table of given size * hash algorithm from http://en.wikipedia.org/wiki/Hash_table */ static uint32_t batadv_vis_info_choose(const void *data, uint32_t size) { const struct batadv_vis_info *vis_info = data; const struct batadv_vis_packet *packet; const unsigned char *key; uint32_t hash = 0; size_t i; packet = (struct batadv_vis_packet *)vis_info->skb_packet->data; key = packet->vis_orig; for (i = 0; i < ETH_ALEN; i++) { hash += key[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash % size; } static struct batadv_vis_info * batadv_vis_hash_find(struct batadv_priv *bat_priv, const void *data) { struct batadv_hashtable *hash = bat_priv->vis.hash; struct hlist_head *head; struct batadv_vis_info *vis_info, *vis_info_tmp = NULL; uint32_t index; if (!hash) return NULL; index = batadv_vis_info_choose(data, hash->size); head = &hash->table[index]; rcu_read_lock(); hlist_for_each_entry_rcu(vis_info, head, hash_entry) { if (!batadv_vis_info_cmp(&vis_info->hash_entry, data)) continue; vis_info_tmp = vis_info; break; } rcu_read_unlock(); return vis_info_tmp; } /* insert interface to the list of interfaces of one originator, if it * does not already exist in the list */ static void batadv_vis_data_insert_interface(const uint8_t *interface, struct hlist_head *if_list, bool primary) { struct batadv_vis_if_list_entry *entry; hlist_for_each_entry(entry, if_list, list) { if (batadv_compare_eth(entry->addr, interface)) return; } /* it's a new address, add it to the list */ entry = kmalloc(sizeof(*entry), GFP_ATOMIC); if (!entry) return; memcpy(entry->addr, interface, ETH_ALEN); entry->primary = primary; hlist_add_head(&entry->list, if_list); } static void batadv_vis_data_read_prim_sec(struct seq_file *seq, const struct hlist_head *if_list) { struct batadv_vis_if_list_entry *entry; hlist_for_each_entry(entry, if_list, list) { if (entry->primary) seq_puts(seq, "PRIMARY, "); else seq_printf(seq, "SEC %pM, ", entry->addr); } } /* read an entry */ static ssize_t batadv_vis_data_read_entry(struct seq_file *seq, const struct batadv_vis_info_entry *entry, const uint8_t *src, bool primary) { if (primary && entry->quality == 0) return seq_printf(seq, "TT %pM, ", entry->dest); else if (batadv_compare_eth(entry->src, src)) return seq_printf(seq, "TQ %pM %d, ", entry->dest, entry->quality); return 0; } static void batadv_vis_data_insert_interfaces(struct hlist_head *list, struct batadv_vis_packet *packet, struct batadv_vis_info_entry *entries) { int i; for (i = 0; i < packet->entries; i++) { if (entries[i].quality == 0) continue; if (batadv_compare_eth(entries[i].src, packet->vis_orig)) continue; batadv_vis_data_insert_interface(entries[i].src, list, false); } } static void batadv_vis_data_read_entries(struct seq_file *seq, struct hlist_head *list, struct batadv_vis_packet *packet, struct batadv_vis_info_entry *entries) { int i; struct batadv_vis_if_list_entry *entry; hlist_for_each_entry(entry, list, list) { seq_printf(seq, "%pM,", entry->addr); for (i = 0; i < packet->entries; i++) batadv_vis_data_read_entry(seq, &entries[i], entry->addr, entry->primary); /* add primary/secondary records */ if (batadv_compare_eth(entry->addr, packet->vis_orig)) batadv_vis_data_read_prim_sec(seq, list); seq_puts(seq, "\n"); } } static void batadv_vis_seq_print_text_bucket(struct seq_file *seq, const struct hlist_head *head) { struct batadv_vis_info *info; struct batadv_vis_packet *packet; uint8_t *entries_pos; struct batadv_vis_info_entry *entries; struct batadv_vis_if_list_entry *entry; struct hlist_node *n; HLIST_HEAD(vis_if_list); hlist_for_each_entry_rcu(info, head, hash_entry) { packet = (struct batadv_vis_packet *)info->skb_packet->data; entries_pos = (uint8_t *)packet + sizeof(*packet); entries = (struct batadv_vis_info_entry *)entries_pos; batadv_vis_data_insert_interface(packet->vis_orig, &vis_if_list, true); batadv_vis_data_insert_interfaces(&vis_if_list, packet, entries); batadv_vis_data_read_entries(seq, &vis_if_list, packet, entries); hlist_for_each_entry_safe(entry, n, &vis_if_list, list) { hlist_del(&entry->list); kfree(entry); } } } int batadv_vis_seq_print_text(struct seq_file *seq, void *offset) { struct batadv_hard_iface *primary_if; struct hlist_head *head; struct net_device *net_dev = (struct net_device *)seq->private; struct batadv_priv *bat_priv = netdev_priv(net_dev); struct batadv_hashtable *hash = bat_priv->vis.hash; uint32_t i; int ret = 0; int vis_server = atomic_read(&bat_priv->vis_mode); primary_if = batadv_primary_if_get_selected(bat_priv); if (!primary_if) goto out; if (vis_server == BATADV_VIS_TYPE_CLIENT_UPDATE) goto out; spin_lock_bh(&bat_priv->vis.hash_lock); for (i = 0; i < hash->size; i++) { head = &hash->table[i]; batadv_vis_seq_print_text_bucket(seq, head); } spin_unlock_bh(&bat_priv->vis.hash_lock); out: if (primary_if) batadv_hardif_free_ref(primary_if); return ret; } /* add the info packet to the send list, if it was not * already linked in. */ static void batadv_send_list_add(struct batadv_priv *bat_priv, struct batadv_vis_info *info) { if (list_empty(&info->send_list)) { kref_get(&info->refcount); list_add_tail(&info->send_list, &bat_priv->vis.send_list); } } /* delete the info packet from the send list, if it was * linked in. */ static void batadv_send_list_del(struct batadv_vis_info *info) { if (!list_empty(&info->send_list)) { list_del_init(&info->send_list); kref_put(&info->refcount, batadv_free_info); } } /* tries to add one entry to the receive list. */ static void batadv_recv_list_add(struct batadv_priv *bat_priv, struct list_head *recv_list, const char *mac) { struct batadv_vis_recvlist_node *entry; entry = kmalloc(sizeof(*entry), GFP_ATOMIC); if (!entry) return; memcpy(entry->mac, mac, ETH_ALEN); spin_lock_bh(&bat_priv->vis.list_lock); list_add_tail(&entry->list, recv_list); spin_unlock_bh(&bat_priv->vis.list_lock); } /* returns 1 if this mac is in the recv_list */ static int batadv_recv_list_is_in(struct batadv_priv *bat_priv, const struct list_head *recv_list, const char *mac) { const struct batadv_vis_recvlist_node *entry; spin_lock_bh(&bat_priv->vis.list_lock); list_for_each_entry(entry, recv_list, list) { if (batadv_compare_eth(entry->mac, mac)) { spin_unlock_bh(&bat_priv->vis.list_lock); return 1; } } spin_unlock_bh(&bat_priv->vis.list_lock); return 0; } /* try to add the packet to the vis_hash. return NULL if invalid (e.g. too old, * broken.. ). vis hash must be locked outside. is_new is set when the packet * is newer than old entries in the hash. */ static struct batadv_vis_info * batadv_add_packet(struct batadv_priv *bat_priv, struct batadv_vis_packet *vis_packet, int vis_info_len, int *is_new, int make_broadcast) { struct batadv_vis_info *info, *old_info; struct batadv_vis_packet *search_packet, *old_packet; struct batadv_vis_info search_elem; struct batadv_vis_packet *packet; struct sk_buff *tmp_skb; int hash_added; size_t len; size_t max_entries; *is_new = 0; /* sanity check */ if (!bat_priv->vis.hash) return NULL; /* see if the packet is already in vis_hash */ search_elem.skb_packet = dev_alloc_skb(sizeof(*search_packet)); if (!search_elem.skb_packet) return NULL; len = sizeof(*search_packet); tmp_skb = search_elem.skb_packet; search_packet = (struct batadv_vis_packet *)skb_put(tmp_skb, len); memcpy(search_packet->vis_orig, vis_packet->vis_orig, ETH_ALEN); old_info = batadv_vis_hash_find(bat_priv, &search_elem); kfree_skb(search_elem.skb_packet); if (old_info) { tmp_skb = old_info->skb_packet; old_packet = (struct batadv_vis_packet *)tmp_skb->data; if (!batadv_seq_after(ntohl(vis_packet->seqno), ntohl(old_packet->seqno))) { if (old_packet->seqno == vis_packet->seqno) { batadv_recv_list_add(bat_priv, &old_info->recv_list, vis_packet->sender_orig); return old_info; } else { /* newer packet is already in hash. */ return NULL; } } /* remove old entry */ batadv_hash_remove(bat_priv->vis.hash, batadv_vis_info_cmp, batadv_vis_info_choose, old_info); batadv_send_list_del(old_info); kref_put(&old_info->refcount, batadv_free_info); } info = kmalloc(sizeof(*info), GFP_ATOMIC); if (!info) return NULL; len = sizeof(*packet) + vis_info_len; info->skb_packet = dev_alloc_skb(len + ETH_HLEN + NET_IP_ALIGN); if (!info->skb_packet) { kfree(info); return NULL; } skb_reserve(info->skb_packet, ETH_HLEN + NET_IP_ALIGN); packet = (struct batadv_vis_packet *)skb_put(info->skb_packet, len); kref_init(&info->refcount); INIT_LIST_HEAD(&info->send_list); INIT_LIST_HEAD(&info->recv_list); info->first_seen = jiffies; info->bat_priv = bat_priv; memcpy(packet, vis_packet, len); /* initialize and add new packet. */ *is_new = 1; /* Make it a broadcast packet, if required */ if (make_broadcast) memcpy(packet->target_orig, batadv_broadcast_addr, ETH_ALEN); /* repair if entries is longer than packet. */ max_entries = vis_info_len / sizeof(struct batadv_vis_info_entry); if (packet->entries > max_entries) packet->entries = max_entries; batadv_recv_list_add(bat_priv, &info->recv_list, packet->sender_orig); /* try to add it */ hash_added = batadv_hash_add(bat_priv->vis.hash, batadv_vis_info_cmp, batadv_vis_info_choose, info, &info->hash_entry); if (hash_added != 0) { /* did not work (for some reason) */ kref_put(&info->refcount, batadv_free_info); info = NULL; } return info; } /* handle the server sync packet, forward if needed. */ void batadv_receive_server_sync_packet(struct batadv_priv *bat_priv, struct batadv_vis_packet *vis_packet, int vis_info_len) { struct batadv_vis_info *info; int is_new, make_broadcast; int vis_server = atomic_read(&bat_priv->vis_mode); make_broadcast = (vis_server == BATADV_VIS_TYPE_SERVER_SYNC); spin_lock_bh(&bat_priv->vis.hash_lock); info = batadv_add_packet(bat_priv, vis_packet, vis_info_len, &is_new, make_broadcast); if (!info) goto end; /* only if we are server ourselves and packet is newer than the one in * hash. */ if (vis_server == BATADV_VIS_TYPE_SERVER_SYNC && is_new) batadv_send_list_add(bat_priv, info); end: spin_unlock_bh(&bat_priv->vis.hash_lock); } /* handle an incoming client update packet and schedule forward if needed. */ void batadv_receive_client_update_packet(struct batadv_priv *bat_priv, struct batadv_vis_packet *vis_packet, int vis_info_len) { struct batadv_vis_info *info; struct batadv_vis_packet *packet; int is_new; int vis_server = atomic_read(&bat_priv->vis_mode); int are_target = 0; /* clients shall not broadcast. */ if (is_broadcast_ether_addr(vis_packet->target_orig)) return; /* Are we the target for this VIS packet? */ if (vis_server == BATADV_VIS_TYPE_SERVER_SYNC && batadv_is_my_mac(bat_priv, vis_packet->target_orig)) are_target = 1; spin_lock_bh(&bat_priv->vis.hash_lock); info = batadv_add_packet(bat_priv, vis_packet, vis_info_len, &is_new, are_target); if (!info) goto end; /* note that outdated packets will be dropped at this point. */ packet = (struct batadv_vis_packet *)info->skb_packet->data; /* send only if we're the target server or ... */ if (are_target && is_new) { packet->vis_type = BATADV_VIS_TYPE_SERVER_SYNC; /* upgrade! */ batadv_send_list_add(bat_priv, info); /* ... we're not the recipient (and thus need to forward). */ } else if (!batadv_is_my_mac(bat_priv, packet->target_orig)) { batadv_send_list_add(bat_priv, info); } end: spin_unlock_bh(&bat_priv->vis.hash_lock); } /* Walk the originators and find the VIS server with the best tq. Set the packet * address to its address and return the best_tq. * * Must be called with the originator hash locked */ static int batadv_find_best_vis_server(struct batadv_priv *bat_priv, struct batadv_vis_info *info) { struct batadv_hashtable *hash = bat_priv->orig_hash; struct batadv_neigh_node *router; struct hlist_head *head; struct batadv_orig_node *orig_node; struct batadv_vis_packet *packet; int best_tq = -1; uint32_t i; packet = (struct batadv_vis_packet *)info->skb_packet->data; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, head, hash_entry) { router = batadv_orig_node_get_router(orig_node); if (!router) continue; if ((orig_node->flags & BATADV_VIS_SERVER) && (router->tq_avg > best_tq)) { best_tq = router->tq_avg; memcpy(packet->target_orig, orig_node->orig, ETH_ALEN); } batadv_neigh_node_free_ref(router); } rcu_read_unlock(); } return best_tq; } /* Return true if the vis packet is full. */ static bool batadv_vis_packet_full(const struct batadv_vis_info *info) { const struct batadv_vis_packet *packet; size_t num; packet = (struct batadv_vis_packet *)info->skb_packet->data; num = BATADV_MAX_VIS_PACKET_SIZE / sizeof(struct batadv_vis_info_entry); if (num < packet->entries + 1) return true; return false; } /* generates a packet of own vis data, * returns 0 on success, -1 if no packet could be generated */ static int batadv_generate_vis_packet(struct batadv_priv *bat_priv) { struct batadv_hashtable *hash = bat_priv->orig_hash; struct hlist_head *head; struct batadv_orig_node *orig_node; struct batadv_neigh_node *router; struct batadv_vis_info *info = bat_priv->vis.my_info; struct batadv_vis_packet *packet; struct batadv_vis_info_entry *entry; struct batadv_tt_common_entry *tt_common_entry; uint8_t *packet_pos; int best_tq = -1; uint32_t i; info->first_seen = jiffies; packet = (struct batadv_vis_packet *)info->skb_packet->data; packet->vis_type = atomic_read(&bat_priv->vis_mode); memcpy(packet->target_orig, batadv_broadcast_addr, ETH_ALEN); packet->header.ttl = BATADV_TTL; packet->seqno = htonl(ntohl(packet->seqno) + 1); packet->entries = 0; packet->reserved = 0; skb_trim(info->skb_packet, sizeof(*packet)); if (packet->vis_type == BATADV_VIS_TYPE_CLIENT_UPDATE) { best_tq = batadv_find_best_vis_server(bat_priv, info); if (best_tq < 0) return best_tq; } for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, head, hash_entry) { router = batadv_orig_node_get_router(orig_node); if (!router) continue; if (!batadv_compare_eth(router->addr, orig_node->orig)) goto next; if (router->if_incoming->if_status != BATADV_IF_ACTIVE) goto next; if (router->tq_avg < 1) goto next; /* fill one entry into buffer. */ packet_pos = skb_put(info->skb_packet, sizeof(*entry)); entry = (struct batadv_vis_info_entry *)packet_pos; memcpy(entry->src, router->if_incoming->net_dev->dev_addr, ETH_ALEN); memcpy(entry->dest, orig_node->orig, ETH_ALEN); entry->quality = router->tq_avg; packet->entries++; next: batadv_neigh_node_free_ref(router); if (batadv_vis_packet_full(info)) goto unlock; } rcu_read_unlock(); } hash = bat_priv->tt.local_hash; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(tt_common_entry, head, hash_entry) { packet_pos = skb_put(info->skb_packet, sizeof(*entry)); entry = (struct batadv_vis_info_entry *)packet_pos; memset(entry->src, 0, ETH_ALEN); memcpy(entry->dest, tt_common_entry->addr, ETH_ALEN); entry->quality = 0; /* 0 means TT */ packet->entries++; if (batadv_vis_packet_full(info)) goto unlock; } rcu_read_unlock(); } return 0; unlock: rcu_read_unlock(); return 0; } /* free old vis packets. Must be called with this vis_hash_lock * held */ static void batadv_purge_vis_packets(struct batadv_priv *bat_priv) { uint32_t i; struct batadv_hashtable *hash = bat_priv->vis.hash; struct hlist_node *node_tmp; struct hlist_head *head; struct batadv_vis_info *info; for (i = 0; i < hash->size; i++) { head = &hash->table[i]; hlist_for_each_entry_safe(info, node_tmp, head, hash_entry) { /* never purge own data. */ if (info == bat_priv->vis.my_info) continue; if (batadv_has_timed_out(info->first_seen, BATADV_VIS_TIMEOUT)) { hlist_del(&info->hash_entry); batadv_send_list_del(info); kref_put(&info->refcount, batadv_free_info); } } } } static void batadv_broadcast_vis_packet(struct batadv_priv *bat_priv, struct batadv_vis_info *info) { struct batadv_hashtable *hash = bat_priv->orig_hash; struct hlist_head *head; struct batadv_orig_node *orig_node; struct batadv_vis_packet *packet; struct sk_buff *skb; uint32_t i; packet = (struct batadv_vis_packet *)info->skb_packet->data; /* send to all routers in range. */ for (i = 0; i < hash->size; i++) { head = &hash->table[i]; rcu_read_lock(); hlist_for_each_entry_rcu(orig_node, head, hash_entry) { /* if it's a vis server and reachable, send it. */ if (!(orig_node->flags & BATADV_VIS_SERVER)) continue; /* don't send it if we already received the packet from * this node. */ if (batadv_recv_list_is_in(bat_priv, &info->recv_list, orig_node->orig)) continue; memcpy(packet->target_orig, orig_node->orig, ETH_ALEN); skb = skb_clone(info->skb_packet, GFP_ATOMIC); if (!skb) continue; if (!batadv_send_skb_to_orig(skb, orig_node, NULL)) kfree_skb(skb); } rcu_read_unlock(); } } static void batadv_unicast_vis_packet(struct batadv_priv *bat_priv, struct batadv_vis_info *info) { struct batadv_orig_node *orig_node; struct sk_buff *skb; struct batadv_vis_packet *packet; packet = (struct batadv_vis_packet *)info->skb_packet->data; orig_node = batadv_orig_hash_find(bat_priv, packet->target_orig); if (!orig_node) goto out; skb = skb_clone(info->skb_packet, GFP_ATOMIC); if (!skb) goto out; if (!batadv_send_skb_to_orig(skb, orig_node, NULL)) kfree_skb(skb); out: if (orig_node) batadv_orig_node_free_ref(orig_node); } /* only send one vis packet. called from batadv_send_vis_packets() */ static void batadv_send_vis_packet(struct batadv_priv *bat_priv, struct batadv_vis_info *info) { struct batadv_hard_iface *primary_if; struct batadv_vis_packet *packet; primary_if = batadv_primary_if_get_selected(bat_priv); if (!primary_if) goto out; packet = (struct batadv_vis_packet *)info->skb_packet->data; if (packet->header.ttl < 2) { pr_debug("Error - can't send vis packet: ttl exceeded\n"); goto out; } memcpy(packet->sender_orig, primary_if->net_dev->dev_addr, ETH_ALEN); packet->header.ttl--; if (is_broadcast_ether_addr(packet->target_orig)) batadv_broadcast_vis_packet(bat_priv, info); else batadv_unicast_vis_packet(bat_priv, info); packet->header.ttl++; /* restore TTL */ out: if (primary_if) batadv_hardif_free_ref(primary_if); } /* called from timer; send (and maybe generate) vis packet. */ static void batadv_send_vis_packets(struct work_struct *work) { struct delayed_work *delayed_work; struct batadv_priv *bat_priv; struct batadv_priv_vis *priv_vis; struct batadv_vis_info *info; delayed_work = container_of(work, struct delayed_work, work); priv_vis = container_of(delayed_work, struct batadv_priv_vis, work); bat_priv = container_of(priv_vis, struct batadv_priv, vis); spin_lock_bh(&bat_priv->vis.hash_lock); batadv_purge_vis_packets(bat_priv); if (batadv_generate_vis_packet(bat_priv) == 0) { /* schedule if generation was successful */ batadv_send_list_add(bat_priv, bat_priv->vis.my_info); } while (!list_empty(&bat_priv->vis.send_list)) { info = list_first_entry(&bat_priv->vis.send_list, typeof(*info), send_list); kref_get(&info->refcount); spin_unlock_bh(&bat_priv->vis.hash_lock); batadv_send_vis_packet(bat_priv, info); spin_lock_bh(&bat_priv->vis.hash_lock); batadv_send_list_del(info); kref_put(&info->refcount, batadv_free_info); } spin_unlock_bh(&bat_priv->vis.hash_lock); queue_delayed_work(batadv_event_workqueue, &bat_priv->vis.work, msecs_to_jiffies(BATADV_VIS_INTERVAL)); } /* init the vis server. this may only be called when if_list is already * initialized (e.g. bat0 is initialized, interfaces have been added) */ int batadv_vis_init(struct batadv_priv *bat_priv) { struct batadv_vis_packet *packet; int hash_added; unsigned int len; unsigned long first_seen; struct sk_buff *tmp_skb; if (bat_priv->vis.hash) return 0; spin_lock_bh(&bat_priv->vis.hash_lock); bat_priv->vis.hash = batadv_hash_new(256); if (!bat_priv->vis.hash) { pr_err("Can't initialize vis_hash\n"); goto err; } batadv_hash_set_lock_class(bat_priv->vis.hash, &batadv_vis_hash_lock_class_key); bat_priv->vis.my_info = kmalloc(BATADV_MAX_VIS_PACKET_SIZE, GFP_ATOMIC); if (!bat_priv->vis.my_info) goto err; len = sizeof(*packet) + BATADV_MAX_VIS_PACKET_SIZE; len += ETH_HLEN + NET_IP_ALIGN; bat_priv->vis.my_info->skb_packet = dev_alloc_skb(len); if (!bat_priv->vis.my_info->skb_packet) goto free_info; skb_reserve(bat_priv->vis.my_info->skb_packet, ETH_HLEN + NET_IP_ALIGN); tmp_skb = bat_priv->vis.my_info->skb_packet; packet = (struct batadv_vis_packet *)skb_put(tmp_skb, sizeof(*packet)); /* prefill the vis info */ first_seen = jiffies - msecs_to_jiffies(BATADV_VIS_INTERVAL); bat_priv->vis.my_info->first_seen = first_seen; INIT_LIST_HEAD(&bat_priv->vis.my_info->recv_list); INIT_LIST_HEAD(&bat_priv->vis.my_info->send_list); kref_init(&bat_priv->vis.my_info->refcount); bat_priv->vis.my_info->bat_priv = bat_priv; packet->header.version = BATADV_COMPAT_VERSION; packet->header.packet_type = BATADV_VIS; packet->header.ttl = BATADV_TTL; packet->seqno = 0; packet->reserved = 0; packet->entries = 0; INIT_LIST_HEAD(&bat_priv->vis.send_list); hash_added = batadv_hash_add(bat_priv->vis.hash, batadv_vis_info_cmp, batadv_vis_info_choose, bat_priv->vis.my_info, &bat_priv->vis.my_info->hash_entry); if (hash_added != 0) { pr_err("Can't add own vis packet into hash\n"); /* not in hash, need to remove it manually. */ kref_put(&bat_priv->vis.my_info->refcount, batadv_free_info); goto err; } spin_unlock_bh(&bat_priv->vis.hash_lock); INIT_DELAYED_WORK(&bat_priv->vis.work, batadv_send_vis_packets); queue_delayed_work(batadv_event_workqueue, &bat_priv->vis.work, msecs_to_jiffies(BATADV_VIS_INTERVAL)); return 0; free_info: kfree(bat_priv->vis.my_info); bat_priv->vis.my_info = NULL; err: spin_unlock_bh(&bat_priv->vis.hash_lock); batadv_vis_quit(bat_priv); return -ENOMEM; } /* Decrease the reference count on a hash item info */ static void batadv_free_info_ref(struct hlist_node *node, void *arg) { struct batadv_vis_info *info; info = container_of(node, struct batadv_vis_info, hash_entry); batadv_send_list_del(info); kref_put(&info->refcount, batadv_free_info); } /* shutdown vis-server */ void batadv_vis_quit(struct batadv_priv *bat_priv) { if (!bat_priv->vis.hash) return; cancel_delayed_work_sync(&bat_priv->vis.work); spin_lock_bh(&bat_priv->vis.hash_lock); /* properly remove, kill timers ... */ batadv_hash_delete(bat_priv->vis.hash, batadv_free_info_ref, NULL); bat_priv->vis.hash = NULL; bat_priv->vis.my_info = NULL; spin_unlock_bh(&bat_priv->vis.hash_lock); }
gpl-3.0
jason-liew/shadowsocks-android
src/main/jni/openssl/crypto/bf/bf_ofb64.c
808
4197
/* crypto/bf/bf_ofb64.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <openssl/blowfish.h> #include "bf_locl.h" /* The input and output encrypted as though 64bit ofb mode is being * used. The extra state information to record how much of the * 64bit block we have used is contained in *num; */ void BF_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int *num) { register BF_LONG v0,v1,t; register int n= *num; register long l=length; unsigned char d[8]; register char *dp; BF_LONG ti[2]; unsigned char *iv; int save=0; iv=(unsigned char *)ivec; n2l(iv,v0); n2l(iv,v1); ti[0]=v0; ti[1]=v1; dp=(char *)d; l2n(v0,dp); l2n(v1,dp); while (l--) { if (n == 0) { BF_encrypt((BF_LONG *)ti,schedule); dp=(char *)d; t=ti[0]; l2n(t,dp); t=ti[1]; l2n(t,dp); save++; } *(out++)= *(in++)^d[n]; n=(n+1)&0x07; } if (save) { v0=ti[0]; v1=ti[1]; iv=(unsigned char *)ivec; l2n(v0,iv); l2n(v1,iv); } t=v0=v1=ti[0]=ti[1]=0; *num=n; }
gpl-3.0
orlov-vo/mtasa
vendor/ehs/sslerror.cpp
41
1762
/* EHS is a library for adding web server support to a C++ application Copyright (C) 2001, 2002 Zac Hansen This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License only. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. or see http://www.gnu.org/licenses/gpl.html Zac Hansen ( xaxxon@slackworks.com ) */ // must be outside COMPILE_WITH_SSL check #include "config.h" #ifdef COMPILE_WITH_SSL #include "sslerror.h" int SslError::nErrorMessagesLoaded = 0; int SslError::GetError ( std::string & irsReport, int inPeek ) { // get the error code unsigned long nError = ERR_get_error ( ); // if there is no error, or we don't want full text, return the error // code now if ( nError == 0 || irsReport == "noreport" ) { irsReport = ""; return nError; } // do we need to load the strings? if ( !nErrorMessagesLoaded ) { SSL_load_error_strings ( ); nErrorMessagesLoaded = 1; } char psBuffer [ 256 ]; ERR_error_string_n ( nError, psBuffer, 256 ); irsReport = psBuffer; return nError; } int SslError::PeekError ( std::string & irsReport ) { return GetError ( irsReport, 1 ); } #endif // COMPILE_WITH_SSL
gpl-3.0
zhaozoz/stardict-3
tools/src/degb2utf.cpp
41
9461
/* * This file is part of StarDict. * * StarDict is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * StarDict is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with StarDict. If not, see <http://www.gnu.org/licenses/>. */ // Some Germany-Chinese dictionary data files are encoded both in Germany and Chinese, that is, Windows-1252 and GBK, this program try to convert these data files to UTF-8 format. #include "stdio.h" #include "stdlib.h" #include <locale.h> #include <string.h> #include <sys/stat.h> #include <ctype.h> #include <string> #include <gtk/gtk.h> #include <glib.h> bool isde(guchar c) { if (c==0xFC || c==0xF6 || c==0xE4 || c==0xDF || c==0xDC || c==0xD6 || c==0xC4) return true; return false; } gchar *convert_de_first(gchar *p, GIConv *gb2utf) { gchar *str; std::string string; while (*p) { if (isascii(*p)) { string+=*p; } else { if ((guchar)*p==0xFC && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ü"; } else if ((guchar)*p==0xF6 && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ö"; } else if ((guchar)*p==0xE4 && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ä"; } else if ((guchar)*p==0xDF && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ß"; } else if ((guchar)*p==0xDC && isascii(*(p+1))) { string+="Ü"; } else if ((guchar)*p==0xD6 && isascii(*(p+1))) { string+="Ö"; } else if ((guchar)*p==0xC4 && isascii(*(p+1))) { string+="Ä"; } else if ((guchar)*p>=0x81 && (guchar)*p<=0xFE && (guchar)*(p+1)>=0x40 && (guchar)*(p+1)<=0xFE) { str = g_convert_with_iconv(p, 2, *gb2utf, NULL, NULL, NULL); if (str) { string+=str; } else { return NULL; } p++; } else { return NULL; } } p++; } return g_strdup(string.c_str()); } gchar *convert_de_first2(gchar *p, GIConv *gb2utf) { gchar *str; std::string string; while (*p) { if (isascii(*p)) { string+=*p; } else { if ((guchar)*p==0xFC) { string+="ü"; } else if ((guchar)*p==0xF6) { string+="ö"; } else if ((guchar)*p==0xE4) { string+="ä"; } else if ((guchar)*p==0xDF) { string+="ß"; } else if ((guchar)*p==0xDC) { string+="Ü"; } else if ((guchar)*p==0xD6) { string+="Ö"; } else if ((guchar)*p==0xC4) { string+="Ä"; } else if ((guchar)*p>=0x81 && (guchar)*p<=0xFE && (guchar)*(p+1)>=0x40 && (guchar)*(p+1)<=0xFE) { str = g_convert_with_iconv(p, 2, *gb2utf, NULL, NULL, NULL); if (str) { string+=str; } else { return NULL; } p++; } else { return NULL; } } p++; } return g_strdup(string.c_str()); } gchar *convert_gb_first(gchar *p, GIConv *gb2utf) { gchar *str; std::string string; while (*p) { if (isascii(*p)) { string+=*p; } else { if ((guchar)*p>=0x81 && (guchar)*p<=0xFE && (guchar)*(p+1)>=0x40 && (guchar)*(p+1)<=0xFE) { str = g_convert_with_iconv(p, 2, *gb2utf, NULL, NULL, NULL); if (str) { string+=str; } else { return NULL; } p++; } else if ((guchar)*p==0xFC && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ü"; } else if ((guchar)*p==0xF6 && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ö"; } else if ((guchar)*p==0xE4 && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ä"; } else if ((guchar)*p==0xDF && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ß"; } else if ((guchar)*p==0xDC && isascii(*(p+1))) { string+="Ü"; } else if ((guchar)*p==0xD6 && isascii(*(p+1))) { string+="Ö"; } else if ((guchar)*p==0xC4 && isascii(*(p+1))) { string+="Ä"; } else { return NULL; } } p++; } return g_strdup(string.c_str()); } gchar *convert_gb_first2(gchar *p, GIConv *gb2utf) { gchar *str; std::string string; while (*p) { if (isascii(*p)) { string+=*p; } else { if ((guchar)*p>=0x81 && (guchar)*p<=0xFE && (guchar)*(p+1)>=0x40 && (guchar)*(p+1)<=0xFE) { str = g_convert_with_iconv(p, 2, *gb2utf, NULL, NULL, NULL); if (str) { string+=str; } else { return NULL; } p++; } else if ((guchar)*p==0xFC && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ü"; } else if ((guchar)*p==0xF6 && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ö"; } else if ((guchar)*p==0xE4 && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ä"; } else if ((guchar)*p==0xDF && (isascii(*(p+1)) || isde(*(p+1)))) { string+="ß"; } else if ((guchar)*p==0xDC && isascii(*(p+1))) { string+="Ü"; } else if ((guchar)*p==0xD6 && isascii(*(p+1))) { string+="Ö"; } else if ((guchar)*p==0xC4 && isascii(*(p+1))) { string+="Ä"; } else { } } p++; } return g_strdup(string.c_str()); } void convert(char *filename) { struct stat stats; if (stat (filename, &stats) == -1) { printf("file not exist!\n"); return; } gchar *basefilename = g_path_get_basename(filename); FILE *degbfile; degbfile = fopen(filename,"r"); gchar *buffer = (gchar *)g_malloc (stats.st_size + 1); size_t fread_size; fread_size = fread (buffer, 1, stats.st_size, degbfile); if (fread_size != (size_t)stats.st_size) { g_print("fread error!\n"); } fclose (degbfile); buffer[stats.st_size] = '\0'; gchar utffilename[256]; sprintf(utffilename, "%s.utf", basefilename); FILE *utffile = fopen(utffilename,"w"); GIConv gb2utf = g_iconv_open("UTF-8", "GBK"); gchar *p, *p1, *p2; p=buffer; gchar *str; int linenum = 1; while (true) { if (*p=='\0') break; p1 = strchr(p, '\n'); if (!p1) { g_print("Error, no ending new line.\n"); return; } *p1='\0'; p2 = strchr(p, '\t'); if (p2) { *p2='\0'; str = convert_de_first(p ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_gb_first(p ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_de_first2(p ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_gb_first2(p ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); g_print("Warning: %d\n", linenum); } else { g_print("Error1: %d\n", linenum); } } } } fwrite("\t", 1, 1, utffile); p2++; str = convert_de_first(p2 ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_gb_first(p2 ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_de_first2(p2 ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_gb_first2(p2 ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); g_print("Warning: %d\n", linenum); } else { g_print("Error2: %d\n", linenum); } } } } } else { str = convert_de_first(p ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_gb_first(p ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_de_first2(p ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); } else { str = convert_gb_first2(p ,&gb2utf); if (str) { fwrite(str, strlen(str), 1, utffile); g_free(str); g_print("Warning: %d\n", linenum); } else { g_print("Error: %d\n", linenum); } } } } } fwrite("\n", 1, 1, utffile); p=p1+1; linenum++; } g_iconv_close(gb2utf); fclose(utffile); g_free(buffer); g_free(basefilename); } int main(int argc,char * argv []) { if (argc<2) { printf("please type this:\n./degb2utf fundset.txt\n"); return FALSE; } setlocale(LC_ALL, ""); for (int i=1; i< argc; i++) convert (argv[i]); return FALSE; }
gpl-3.0
geminy/aidear
oss/linux/linux-4.7/drivers/net/wireless/ath/ath9k/dynack.c
48
8994
/* * Copyright (c) 2014, Lorenzo Bianconi <lorenzo.bianconi83@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "ath9k.h" #include "hw.h" #include "dynack.h" #define COMPUTE_TO (5 * HZ) #define LATEACK_DELAY (10 * HZ) #define LATEACK_TO 256 #define MAX_DELAY 300 #define EWMA_LEVEL 96 #define EWMA_DIV 128 /** * ath_dynack_ewma - EWMA (Exponentially Weighted Moving Average) calculation * */ static inline u32 ath_dynack_ewma(u32 old, u32 new) { return (new * (EWMA_DIV - EWMA_LEVEL) + old * EWMA_LEVEL) / EWMA_DIV; } /** * ath_dynack_get_sifs - get sifs time based on phy used * @ah: ath hw * @phy: phy used * */ static inline u32 ath_dynack_get_sifs(struct ath_hw *ah, int phy) { u32 sifs = CCK_SIFS_TIME; if (phy == WLAN_RC_PHY_OFDM) { if (IS_CHAN_QUARTER_RATE(ah->curchan)) sifs = OFDM_SIFS_TIME_QUARTER; else if (IS_CHAN_HALF_RATE(ah->curchan)) sifs = OFDM_SIFS_TIME_HALF; else sifs = OFDM_SIFS_TIME; } return sifs; } /** * ath_dynack_bssidmask - filter out ACK frames based on BSSID mask * @ah: ath hw * @mac: receiver address */ static inline bool ath_dynack_bssidmask(struct ath_hw *ah, const u8 *mac) { int i; struct ath_common *common = ath9k_hw_common(ah); for (i = 0; i < ETH_ALEN; i++) { if ((common->macaddr[i] & common->bssidmask[i]) != (mac[i] & common->bssidmask[i])) return false; } return true; } /** * ath_dynack_compute_ackto - compute ACK timeout as the maximum STA timeout * @ah: ath hw * * should be called while holding qlock */ static void ath_dynack_compute_ackto(struct ath_hw *ah) { struct ath_node *an; u32 to = 0; struct ath_dynack *da = &ah->dynack; struct ath_common *common = ath9k_hw_common(ah); list_for_each_entry(an, &da->nodes, list) if (an->ackto > to) to = an->ackto; if (to && da->ackto != to) { u32 slottime; slottime = (to - 3) / 2; da->ackto = to; ath_dbg(common, DYNACK, "ACK timeout %u slottime %u\n", da->ackto, slottime); ath9k_hw_setslottime(ah, slottime); ath9k_hw_set_ack_timeout(ah, da->ackto); ath9k_hw_set_cts_timeout(ah, da->ackto); } } /** * ath_dynack_compute_to - compute STA ACK timeout * @ah: ath hw * * should be called while holding qlock */ static void ath_dynack_compute_to(struct ath_hw *ah) { u32 ackto, ack_ts; u8 *dst, *src; struct ieee80211_sta *sta; struct ath_node *an; struct ts_info *st_ts; struct ath_dynack *da = &ah->dynack; rcu_read_lock(); while (da->st_rbf.h_rb != da->st_rbf.t_rb && da->ack_rbf.h_rb != da->ack_rbf.t_rb) { ack_ts = da->ack_rbf.tstamp[da->ack_rbf.h_rb]; st_ts = &da->st_rbf.ts[da->st_rbf.h_rb]; dst = da->st_rbf.addr[da->st_rbf.h_rb].h_dest; src = da->st_rbf.addr[da->st_rbf.h_rb].h_src; ath_dbg(ath9k_hw_common(ah), DYNACK, "ack_ts %u st_ts %u st_dur %u [%u-%u]\n", ack_ts, st_ts->tstamp, st_ts->dur, da->ack_rbf.h_rb, da->st_rbf.h_rb); if (ack_ts > st_ts->tstamp + st_ts->dur) { ackto = ack_ts - st_ts->tstamp - st_ts->dur; if (ackto < MAX_DELAY) { sta = ieee80211_find_sta_by_ifaddr(ah->hw, dst, src); if (sta) { an = (struct ath_node *)sta->drv_priv; an->ackto = ath_dynack_ewma(an->ackto, ackto); ath_dbg(ath9k_hw_common(ah), DYNACK, "%pM to %u\n", dst, an->ackto); if (time_is_before_jiffies(da->lto)) { ath_dynack_compute_ackto(ah); da->lto = jiffies + COMPUTE_TO; } } INCR(da->ack_rbf.h_rb, ATH_DYN_BUF); } INCR(da->st_rbf.h_rb, ATH_DYN_BUF); } else { INCR(da->ack_rbf.h_rb, ATH_DYN_BUF); } } rcu_read_unlock(); } /** * ath_dynack_sample_tx_ts - status timestamp sampling method * @ah: ath hw * @skb: socket buffer * @ts: tx status info * */ void ath_dynack_sample_tx_ts(struct ath_hw *ah, struct sk_buff *skb, struct ath_tx_status *ts) { u8 ridx; struct ieee80211_hdr *hdr; struct ath_dynack *da = &ah->dynack; struct ath_common *common = ath9k_hw_common(ah); struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); if ((info->flags & IEEE80211_TX_CTL_NO_ACK) || !da->enabled) return; spin_lock_bh(&da->qlock); hdr = (struct ieee80211_hdr *)skb->data; /* late ACK */ if (ts->ts_status & ATH9K_TXERR_XRETRY) { if (ieee80211_is_assoc_req(hdr->frame_control) || ieee80211_is_assoc_resp(hdr->frame_control)) { ath_dbg(common, DYNACK, "late ack\n"); ath9k_hw_setslottime(ah, (LATEACK_TO - 3) / 2); ath9k_hw_set_ack_timeout(ah, LATEACK_TO); ath9k_hw_set_cts_timeout(ah, LATEACK_TO); da->lto = jiffies + LATEACK_DELAY; } spin_unlock_bh(&da->qlock); return; } ridx = ts->ts_rateindex; da->st_rbf.ts[da->st_rbf.t_rb].tstamp = ts->ts_tstamp; da->st_rbf.ts[da->st_rbf.t_rb].dur = ts->duration; ether_addr_copy(da->st_rbf.addr[da->st_rbf.t_rb].h_dest, hdr->addr1); ether_addr_copy(da->st_rbf.addr[da->st_rbf.t_rb].h_src, hdr->addr2); if (!(info->status.rates[ridx].flags & IEEE80211_TX_RC_MCS)) { u32 phy, sifs; const struct ieee80211_rate *rate; struct ieee80211_tx_rate *rates = info->status.rates; rate = &common->sbands[info->band].bitrates[rates[ridx].idx]; if (info->band == NL80211_BAND_2GHZ && !(rate->flags & IEEE80211_RATE_ERP_G)) phy = WLAN_RC_PHY_CCK; else phy = WLAN_RC_PHY_OFDM; sifs = ath_dynack_get_sifs(ah, phy); da->st_rbf.ts[da->st_rbf.t_rb].dur -= sifs; } ath_dbg(common, DYNACK, "{%pM} tx sample %u [dur %u][h %u-t %u]\n", hdr->addr1, da->st_rbf.ts[da->st_rbf.t_rb].tstamp, da->st_rbf.ts[da->st_rbf.t_rb].dur, da->st_rbf.h_rb, (da->st_rbf.t_rb + 1) % ATH_DYN_BUF); INCR(da->st_rbf.t_rb, ATH_DYN_BUF); if (da->st_rbf.t_rb == da->st_rbf.h_rb) INCR(da->st_rbf.h_rb, ATH_DYN_BUF); ath_dynack_compute_to(ah); spin_unlock_bh(&da->qlock); } EXPORT_SYMBOL(ath_dynack_sample_tx_ts); /** * ath_dynack_sample_ack_ts - ACK timestamp sampling method * @ah: ath hw * @skb: socket buffer * @ts: rx timestamp * */ void ath_dynack_sample_ack_ts(struct ath_hw *ah, struct sk_buff *skb, u32 ts) { struct ath_dynack *da = &ah->dynack; struct ath_common *common = ath9k_hw_common(ah); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data; if (!ath_dynack_bssidmask(ah, hdr->addr1) || !da->enabled) return; spin_lock_bh(&da->qlock); da->ack_rbf.tstamp[da->ack_rbf.t_rb] = ts; ath_dbg(common, DYNACK, "rx sample %u [h %u-t %u]\n", da->ack_rbf.tstamp[da->ack_rbf.t_rb], da->ack_rbf.h_rb, (da->ack_rbf.t_rb + 1) % ATH_DYN_BUF); INCR(da->ack_rbf.t_rb, ATH_DYN_BUF); if (da->ack_rbf.t_rb == da->ack_rbf.h_rb) INCR(da->ack_rbf.h_rb, ATH_DYN_BUF); ath_dynack_compute_to(ah); spin_unlock_bh(&da->qlock); } EXPORT_SYMBOL(ath_dynack_sample_ack_ts); /** * ath_dynack_node_init - init ath_node related info * @ah: ath hw * @an: ath node * */ void ath_dynack_node_init(struct ath_hw *ah, struct ath_node *an) { /* ackto = slottime + sifs + air delay */ u32 ackto = ATH9K_SLOT_TIME_9 + 16 + 64; struct ath_dynack *da = &ah->dynack; an->ackto = ackto; spin_lock(&da->qlock); list_add_tail(&an->list, &da->nodes); spin_unlock(&da->qlock); } EXPORT_SYMBOL(ath_dynack_node_init); /** * ath_dynack_node_deinit - deinit ath_node related info * @ah: ath hw * @an: ath node * */ void ath_dynack_node_deinit(struct ath_hw *ah, struct ath_node *an) { struct ath_dynack *da = &ah->dynack; spin_lock(&da->qlock); list_del(&an->list); spin_unlock(&da->qlock); } EXPORT_SYMBOL(ath_dynack_node_deinit); /** * ath_dynack_reset - reset dynack processing * @ah: ath hw * */ void ath_dynack_reset(struct ath_hw *ah) { /* ackto = slottime + sifs + air delay */ u32 ackto = ATH9K_SLOT_TIME_9 + 16 + 64; struct ath_dynack *da = &ah->dynack; da->lto = jiffies; da->ackto = ackto; da->st_rbf.t_rb = 0; da->st_rbf.h_rb = 0; da->ack_rbf.t_rb = 0; da->ack_rbf.h_rb = 0; /* init acktimeout */ ath9k_hw_setslottime(ah, (ackto - 3) / 2); ath9k_hw_set_ack_timeout(ah, ackto); ath9k_hw_set_cts_timeout(ah, ackto); } EXPORT_SYMBOL(ath_dynack_reset); /** * ath_dynack_init - init dynack data structure * @ah: ath hw * */ void ath_dynack_init(struct ath_hw *ah) { struct ath_dynack *da = &ah->dynack; memset(da, 0, sizeof(struct ath_dynack)); spin_lock_init(&da->qlock); INIT_LIST_HEAD(&da->nodes); ah->hw->wiphy->features |= NL80211_FEATURE_ACKTO_ESTIMATION; }
gpl-3.0
RiverSeed/gsl
cblas/test_sbmv.c
49
9917
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "tests.h" void test_sbmv (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int uplo = 121; float alpha = 1.0f; float beta = 0.0f; int N = 3; int k = 1; int lda = 3; float A[] = { 0.627f, -0.312f, 0.031f, 0.308f, 0.323f, -0.578f, 0.797f, 0.545f, -0.476f }; float X[] = { -0.542f, 0.606f, 0.727f }; int incX = -1; float Y[] = { 0.755f, 0.268f, -0.99f }; int incY = -1; float y_expected[] = { -0.236236f, -0.215242f, 0.266757f }; cblas_ssbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "ssbmv(case 1102)"); } }; }; { int order = 101; int uplo = 121; float alpha = 1.0f; float beta = 0.0f; int N = 3; int k = 1; int lda = 3; float A[] = { 0.627f, -0.312f, 0.031f, 0.308f, 0.323f, -0.578f, 0.797f, 0.545f, -0.476f }; float X[] = { -0.542f, 0.606f, 0.727f }; int incX = -1; float Y[] = { 0.755f, 0.268f, -0.99f }; int incY = -1; float y_expected[] = { -0.236236f, -0.215242f, 0.266757f }; cblas_ssbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "ssbmv(case 1103)"); } }; }; { int order = 101; int uplo = 122; float alpha = 1.0f; float beta = 0.0f; int N = 3; int k = 1; int lda = 3; float A[] = { 0.627f, -0.312f, 0.031f, 0.308f, 0.323f, -0.578f, 0.797f, 0.545f, -0.476f }; float X[] = { -0.542f, 0.606f, 0.727f }; int incX = -1; float Y[] = { 0.755f, 0.268f, -0.99f }; int incY = -1; float y_expected[] = { 0.187592f, -0.01232f, -0.040176f }; cblas_ssbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "ssbmv(case 1104)"); } }; }; { int order = 101; int uplo = 122; float alpha = 1.0f; float beta = 0.0f; int N = 3; int k = 1; int lda = 3; float A[] = { 0.627f, -0.312f, 0.031f, 0.308f, 0.323f, -0.578f, 0.797f, 0.545f, -0.476f }; float X[] = { -0.542f, 0.606f, 0.727f }; int incX = -1; float Y[] = { 0.755f, 0.268f, -0.99f }; int incY = -1; float y_expected[] = { 0.187592f, -0.01232f, -0.040176f }; cblas_ssbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "ssbmv(case 1105)"); } }; }; { int order = 102; int uplo = 121; float alpha = 1.0f; float beta = 0.0f; int N = 3; int k = 1; int lda = 3; float A[] = { 0.627f, -0.312f, 0.031f, 0.308f, 0.323f, -0.578f, 0.797f, 0.545f, -0.476f }; float X[] = { -0.542f, 0.606f, 0.727f }; int incX = -1; float Y[] = { 0.755f, 0.268f, -0.99f }; int incY = -1; float y_expected[] = { 0.187592f, -0.01232f, -0.040176f }; cblas_ssbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "ssbmv(case 1106)"); } }; }; { int order = 102; int uplo = 121; float alpha = 1.0f; float beta = 0.0f; int N = 3; int k = 1; int lda = 3; float A[] = { 0.627f, -0.312f, 0.031f, 0.308f, 0.323f, -0.578f, 0.797f, 0.545f, -0.476f }; float X[] = { -0.542f, 0.606f, 0.727f }; int incX = -1; float Y[] = { 0.755f, 0.268f, -0.99f }; int incY = -1; float y_expected[] = { 0.187592f, -0.01232f, -0.040176f }; cblas_ssbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "ssbmv(case 1107)"); } }; }; { int order = 102; int uplo = 122; float alpha = 1.0f; float beta = 0.0f; int N = 3; int k = 1; int lda = 3; float A[] = { 0.627f, -0.312f, 0.031f, 0.308f, 0.323f, -0.578f, 0.797f, 0.545f, -0.476f }; float X[] = { -0.542f, 0.606f, 0.727f }; int incX = -1; float Y[] = { 0.755f, 0.268f, -0.99f }; int incY = -1; float y_expected[] = { -0.236236f, -0.215242f, 0.266757f }; cblas_ssbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "ssbmv(case 1108)"); } }; }; { int order = 102; int uplo = 122; float alpha = 1.0f; float beta = 0.0f; int N = 3; int k = 1; int lda = 3; float A[] = { 0.627f, -0.312f, 0.031f, 0.308f, 0.323f, -0.578f, 0.797f, 0.545f, -0.476f }; float X[] = { -0.542f, 0.606f, 0.727f }; int incX = -1; float Y[] = { 0.755f, 0.268f, -0.99f }; int incY = -1; float y_expected[] = { -0.236236f, -0.215242f, 0.266757f }; cblas_ssbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "ssbmv(case 1109)"); } }; }; { int order = 101; int uplo = 121; double alpha = 0; double beta = 1; int N = 3; int k = 1; int lda = 3; double A[] = { 0.83, -0.568, -0.888, 0.281, -0.779, -0.148, 0.138, 0.053, -0.757 }; double X[] = { 0.166, 0.808, 0.723 }; int incX = -1; double Y[] = { 0.9, 0.99, -0.578 }; int incY = -1; double y_expected[] = { 0.9, 0.99, -0.578 }; cblas_dsbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dsbmv(case 1110)"); } }; }; { int order = 101; int uplo = 121; double alpha = 0; double beta = 1; int N = 3; int k = 1; int lda = 3; double A[] = { 0.83, -0.568, -0.888, 0.281, -0.779, -0.148, 0.138, 0.053, -0.757 }; double X[] = { 0.166, 0.808, 0.723 }; int incX = -1; double Y[] = { 0.9, 0.99, -0.578 }; int incY = -1; double y_expected[] = { 0.9, 0.99, -0.578 }; cblas_dsbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dsbmv(case 1111)"); } }; }; { int order = 101; int uplo = 122; double alpha = 0; double beta = 1; int N = 3; int k = 1; int lda = 3; double A[] = { 0.83, -0.568, -0.888, 0.281, -0.779, -0.148, 0.138, 0.053, -0.757 }; double X[] = { 0.166, 0.808, 0.723 }; int incX = -1; double Y[] = { 0.9, 0.99, -0.578 }; int incY = -1; double y_expected[] = { 0.9, 0.99, -0.578 }; cblas_dsbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dsbmv(case 1112)"); } }; }; { int order = 101; int uplo = 122; double alpha = 0; double beta = 1; int N = 3; int k = 1; int lda = 3; double A[] = { 0.83, -0.568, -0.888, 0.281, -0.779, -0.148, 0.138, 0.053, -0.757 }; double X[] = { 0.166, 0.808, 0.723 }; int incX = -1; double Y[] = { 0.9, 0.99, -0.578 }; int incY = -1; double y_expected[] = { 0.9, 0.99, -0.578 }; cblas_dsbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dsbmv(case 1113)"); } }; }; { int order = 102; int uplo = 121; double alpha = 0; double beta = 1; int N = 3; int k = 1; int lda = 3; double A[] = { 0.83, -0.568, -0.888, 0.281, -0.779, -0.148, 0.138, 0.053, -0.757 }; double X[] = { 0.166, 0.808, 0.723 }; int incX = -1; double Y[] = { 0.9, 0.99, -0.578 }; int incY = -1; double y_expected[] = { 0.9, 0.99, -0.578 }; cblas_dsbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dsbmv(case 1114)"); } }; }; { int order = 102; int uplo = 121; double alpha = 0; double beta = 1; int N = 3; int k = 1; int lda = 3; double A[] = { 0.83, -0.568, -0.888, 0.281, -0.779, -0.148, 0.138, 0.053, -0.757 }; double X[] = { 0.166, 0.808, 0.723 }; int incX = -1; double Y[] = { 0.9, 0.99, -0.578 }; int incY = -1; double y_expected[] = { 0.9, 0.99, -0.578 }; cblas_dsbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dsbmv(case 1115)"); } }; }; { int order = 102; int uplo = 122; double alpha = 0; double beta = 1; int N = 3; int k = 1; int lda = 3; double A[] = { 0.83, -0.568, -0.888, 0.281, -0.779, -0.148, 0.138, 0.053, -0.757 }; double X[] = { 0.166, 0.808, 0.723 }; int incX = -1; double Y[] = { 0.9, 0.99, -0.578 }; int incY = -1; double y_expected[] = { 0.9, 0.99, -0.578 }; cblas_dsbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dsbmv(case 1116)"); } }; }; { int order = 102; int uplo = 122; double alpha = 0; double beta = 1; int N = 3; int k = 1; int lda = 3; double A[] = { 0.83, -0.568, -0.888, 0.281, -0.779, -0.148, 0.138, 0.053, -0.757 }; double X[] = { 0.166, 0.808, 0.723 }; int incX = -1; double Y[] = { 0.9, 0.99, -0.578 }; int incY = -1; double y_expected[] = { 0.9, 0.99, -0.578 }; cblas_dsbmv(order, uplo, N, k, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dsbmv(case 1117)"); } }; }; }
gpl-3.0
insflow/shadowsocks-android
src/main/jni/openssl/crypto/asn1/a_bytes.c
822
7918
/* crypto/asn1/a_bytes.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include "cryptlib.h" #include <openssl/asn1.h> static int asn1_collate_primitive(ASN1_STRING *a, ASN1_const_CTX *c); /* type is a 'bitmap' of acceptable string types. */ ASN1_STRING *d2i_ASN1_type_bytes(ASN1_STRING **a, const unsigned char **pp, long length, int type) { ASN1_STRING *ret=NULL; const unsigned char *p; unsigned char *s; long len; int inf,tag,xclass; int i=0; p= *pp; inf=ASN1_get_object(&p,&len,&tag,&xclass,length); if (inf & 0x80) goto err; if (tag >= 32) { i=ASN1_R_TAG_VALUE_TOO_HIGH; goto err; } if (!(ASN1_tag2bit(tag) & type)) { i=ASN1_R_WRONG_TYPE; goto err; } /* If a bit-string, exit early */ if (tag == V_ASN1_BIT_STRING) return(d2i_ASN1_BIT_STRING(a,pp,length)); if ((a == NULL) || ((*a) == NULL)) { if ((ret=ASN1_STRING_new()) == NULL) return(NULL); } else ret=(*a); if (len != 0) { s=(unsigned char *)OPENSSL_malloc((int)len+1); if (s == NULL) { i=ERR_R_MALLOC_FAILURE; goto err; } memcpy(s,p,(int)len); s[len]='\0'; p+=len; } else s=NULL; if (ret->data != NULL) OPENSSL_free(ret->data); ret->length=(int)len; ret->data=s; ret->type=tag; if (a != NULL) (*a)=ret; *pp=p; return(ret); err: ASN1err(ASN1_F_D2I_ASN1_TYPE_BYTES,i); if ((ret != NULL) && ((a == NULL) || (*a != ret))) ASN1_STRING_free(ret); return(NULL); } int i2d_ASN1_bytes(ASN1_STRING *a, unsigned char **pp, int tag, int xclass) { int ret,r,constructed; unsigned char *p; if (a == NULL) return(0); if (tag == V_ASN1_BIT_STRING) return(i2d_ASN1_BIT_STRING(a,pp)); ret=a->length; r=ASN1_object_size(0,ret,tag); if (pp == NULL) return(r); p= *pp; if ((tag == V_ASN1_SEQUENCE) || (tag == V_ASN1_SET)) constructed=1; else constructed=0; ASN1_put_object(&p,constructed,ret,tag,xclass); memcpy(p,a->data,a->length); p+=a->length; *pp= p; return(r); } ASN1_STRING *d2i_ASN1_bytes(ASN1_STRING **a, const unsigned char **pp, long length, int Ptag, int Pclass) { ASN1_STRING *ret=NULL; const unsigned char *p; unsigned char *s; long len; int inf,tag,xclass; int i=0; if ((a == NULL) || ((*a) == NULL)) { if ((ret=ASN1_STRING_new()) == NULL) return(NULL); } else ret=(*a); p= *pp; inf=ASN1_get_object(&p,&len,&tag,&xclass,length); if (inf & 0x80) { i=ASN1_R_BAD_OBJECT_HEADER; goto err; } if (tag != Ptag) { i=ASN1_R_WRONG_TAG; goto err; } if (inf & V_ASN1_CONSTRUCTED) { ASN1_const_CTX c; c.pp=pp; c.p=p; c.inf=inf; c.slen=len; c.tag=Ptag; c.xclass=Pclass; c.max=(length == 0)?0:(p+length); if (!asn1_collate_primitive(ret,&c)) goto err; else { p=c.p; } } else { if (len != 0) { if ((ret->length < len) || (ret->data == NULL)) { if (ret->data != NULL) OPENSSL_free(ret->data); s=(unsigned char *)OPENSSL_malloc((int)len + 1); if (s == NULL) { i=ERR_R_MALLOC_FAILURE; goto err; } } else s=ret->data; memcpy(s,p,(int)len); s[len] = '\0'; p+=len; } else { s=NULL; if (ret->data != NULL) OPENSSL_free(ret->data); } ret->length=(int)len; ret->data=s; ret->type=Ptag; } if (a != NULL) (*a)=ret; *pp=p; return(ret); err: if ((ret != NULL) && ((a == NULL) || (*a != ret))) ASN1_STRING_free(ret); ASN1err(ASN1_F_D2I_ASN1_BYTES,i); return(NULL); } /* We are about to parse 0..n d2i_ASN1_bytes objects, we are to collapse * them into the one structure that is then returned */ /* There have been a few bug fixes for this function from * Paul Keogh <paul.keogh@sse.ie>, many thanks to him */ static int asn1_collate_primitive(ASN1_STRING *a, ASN1_const_CTX *c) { ASN1_STRING *os=NULL; BUF_MEM b; int num; b.length=0; b.max=0; b.data=NULL; if (a == NULL) { c->error=ERR_R_PASSED_NULL_PARAMETER; goto err; } num=0; for (;;) { if (c->inf & 1) { c->eos=ASN1_const_check_infinite_end(&c->p, (long)(c->max-c->p)); if (c->eos) break; } else { if (c->slen <= 0) break; } c->q=c->p; if (d2i_ASN1_bytes(&os,&c->p,c->max-c->p,c->tag,c->xclass) == NULL) { c->error=ERR_R_ASN1_LIB; goto err; } if (!BUF_MEM_grow_clean(&b,num+os->length)) { c->error=ERR_R_BUF_LIB; goto err; } memcpy(&(b.data[num]),os->data,os->length); if (!(c->inf & 1)) c->slen-=(c->p-c->q); num+=os->length; } if (!asn1_const_Finish(c)) goto err; a->length=num; if (a->data != NULL) OPENSSL_free(a->data); a->data=(unsigned char *)b.data; if (os != NULL) ASN1_STRING_free(os); return(1); err: ASN1err(ASN1_F_ASN1_COLLATE_PRIMITIVE,c->error); if (os != NULL) ASN1_STRING_free(os); if (b.data != NULL) OPENSSL_free(b.data); return(0); }
gpl-3.0
constantine001/DOOM-3
neo/sys/linux/sound.cpp
57
14235
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <malloc.h> #include <sys/ioctl.h> #include <sys/mman.h> // OSS sound interface // http://www.opensound.com/ #include <sys/soundcard.h> #include "../../idlib/precompiled.h" #include "../../sound/snd_local.h" #include "../posix/posix_public.h" #include "sound.h" const char *s_driverArgs[] = { "best", "oss", "alsa", NULL }; #ifndef NO_ALSA static idCVar s_driver( "s_driver", s_driverArgs[0], CVAR_SYSTEM | CVAR_ARCHIVE, "sound driver. 'best' will attempt to use alsa and fallback to OSS if not available", s_driverArgs, idCmdSystem::ArgCompletion_String<s_driverArgs> ); #else static idCVar s_driver( "s_driver", "oss", CVAR_SYSTEM | CVAR_ARCHIVE | CVAR_ROM, "sound driver. only OSS is supported in this build" ); #endif idAudioHardware *idAudioHardware::Alloc() { #ifndef NO_ALSA if ( !strcmp( s_driver.GetString(), "best" ) ) { idAudioHardwareALSA *test = new idAudioHardwareALSA; if ( test->DLOpen() ) { common->Printf( "Alsa is available\n" ); return test; } common->Printf( "Alsa is not available\n" ); delete test; return new idAudioHardwareOSS; } if ( !strcmp( s_driver.GetString(), "alsa" ) ) { return new idAudioHardwareALSA; } #endif return new idAudioHardwareOSS; } // OSS sound ---------------------------------------------------- /* =============== idAudioHardware::~idAudioHardware =============== */ idAudioHardware::~idAudioHardware() { } /* ================= idAudioHardwareOSS::~idAudioHardwareOSS ================= */ idAudioHardwareOSS::~idAudioHardwareOSS() { Release(); } /* ================= idAudioHardwareOSS::Release ================= */ void idAudioHardwareOSS::Release( bool bSilent ) { if (m_audio_fd) { if (!bSilent) { common->Printf("------ OSS Sound Shutdown ------\n"); } if (m_buffer) { free( m_buffer ); m_buffer = NULL; m_buffer_size = 0; } common->Printf("close sound device\n"); if (close(m_audio_fd) == -1) { common->Warning( "failed to close sound device: %s", strerror(errno) ); } m_audio_fd = 0; if (!bSilent) { common->Printf("--------------------------------\n"); } } } /* ================= idAudioHardwareOSS::InitFailed ================= */ void idAudioHardwareOSS::InitFailed() { Release( true ); cvarSystem->SetCVarBool( "s_noSound", true ); common->Warning( "sound subsystem disabled" ); common->Printf( "--------------------------------------\n" ); } /* ================= idAudioHardwareOSS::ExtractOSSVersion ================= */ void idAudioHardwareOSS::ExtractOSSVersion( int version, idStr &str ) const { sprintf( str, "%d.%d.%d", ( version & 0xFF0000 ) >> 16, ( version & 0xFF00 ) >> 8, version & 0xFF ); } /* ================= idAudioHardwareOSS::Initialize http://www.4front-tech.com/pguide/index.html though OSS API docs (1.1) advertise AFMT_S32_LE, AFMT_S16_LE is the only output format I've found in kernel emu10k1 headers BSD NOTE: With the GNU library, you can use free to free the blocks that memalign, posix_memalign, and valloc return. That does not work in BSD, however--BSD does not provide any way to free such blocks. ================= */ idCVar s_device( "s_dsp", "/dev/dsp", CVAR_SYSTEM | CVAR_ARCHIVE, "" ); bool idAudioHardwareOSS::Initialize( ) { common->Printf("------ OSS Sound Initialization ------\n"); int requested_sample_format, caps, oss_version; idStr s_compiled_oss_version, s_oss_version; struct audio_buf_info info; memset( &info, 0, sizeof( info ) ); if (m_audio_fd) { Release(); } // open device ------------------------------------------------ if ((m_audio_fd = open( s_device.GetString(), O_WRONLY | O_NONBLOCK, 0)) == -1) { m_audio_fd = 0; common->Warning( "failed to open sound device '%s': %s", s_device.GetString(), strerror(errno) ); InitFailed(); return false; } // make it blocking - so write overruns don't fail with 'Resource temporarily unavailable' int flags; if ( ( flags = fcntl( m_audio_fd, F_GETFL ) ) == -1 ) { common->Warning( "failed fcntl F_GETFL on sound device '%s': %s", s_device.GetString(), strerror( errno ) ); InitFailed(); return false; } flags &= ~O_NONBLOCK; if ( fcntl( m_audio_fd, F_SETFL, flags ) == -1 ) { common->Warning( "failed to clear O_NONBLOCK on sound device '%s': %s", s_device.GetString(), strerror( errno ) ); InitFailed(); return false; } common->Printf("opened sound device '%s'\n", s_device.GetString()); // verify capabilities ----------------------------------------- // may only be available starting with OSS API v4.0 // http://www.fi.opensound.com/developer/SNDCTL_SYSINFO.html // NOTE: at OSS API 4.0 headers, replace OSS_SYSINFO with SNDCTL_SYSINFO oss_sysinfo si; if ( ioctl( m_audio_fd, OSS_SYSINFO, &si ) == -1 ) { common->Printf( "ioctl SNDCTL_SYSINFO failed: %s\nthis ioctl is only available in OSS/Linux implementation. If you run OSS/Free, don't bother.", strerror( errno ) ); } else { common->Printf( "%s: %s %s\n", s_device.GetString(), si.product, si.version ); } if ( ioctl( m_audio_fd, SNDCTL_DSP_GETCAPS, &caps ) == -1 ) { common->Warning( "ioctl SNDCTL_DSP_GETCAPS failed - driver too old?" ); InitFailed(); return false; } common->DPrintf("driver rev %d - capabilities %d\n", caps & DSP_CAP_REVISION, caps); if (ioctl( m_audio_fd, OSS_GETVERSION, &oss_version ) == -1) { common->Warning( "ioctl OSS_GETVERSION failed" ); InitFailed(); return false; } ExtractOSSVersion( oss_version, s_oss_version ); ExtractOSSVersion( SOUND_VERSION, s_compiled_oss_version ); common->DPrintf( "OSS interface version %s - compile time %s\n", s_oss_version.c_str(), s_compiled_oss_version.c_str() ); if (!(caps & DSP_CAP_MMAP)) { common->Warning( "driver doesn't have DSP_CAP_MMAP capability" ); InitFailed(); return false; } if (!(caps & DSP_CAP_TRIGGER)) { common->Warning( "driver doesn't have DSP_CAP_TRIGGER capability" ); InitFailed(); return false; } // sample format ----------------------------------------------- requested_sample_format = AFMT_S16_LE; m_sample_format = requested_sample_format; if (ioctl(m_audio_fd, SNDCTL_DSP_SETFMT, &m_sample_format) == -1) { common->Warning( "ioctl SNDCTL_DSP_SETFMT %d failed: %s", requested_sample_format, strerror(errno) ); InitFailed(); return false; } if ( m_sample_format != requested_sample_format ) { common->Warning( "ioctl SNDCTL_DSP_SETFMT failed to get the requested sample format %d, got %d", requested_sample_format, m_sample_format ); InitFailed(); return false; } // channels ---------------------------------------------------- // sanity over number of speakers if ( idSoundSystemLocal::s_numberOfSpeakers.GetInteger() != 6 && idSoundSystemLocal::s_numberOfSpeakers.GetInteger() != 2 ) { common->Warning( "invalid value for s_numberOfSpeakers. Use either 2 or 6" ); idSoundSystemLocal::s_numberOfSpeakers.SetInteger( 2 ); } m_channels = idSoundSystemLocal::s_numberOfSpeakers.GetInteger(); if ( ioctl( m_audio_fd, SNDCTL_DSP_CHANNELS, &m_channels ) == -1 ) { common->Warning( "ioctl SNDCTL_DSP_CHANNELS %d failed: %s", idSoundSystemLocal::s_numberOfSpeakers.GetInteger(), strerror(errno) ); InitFailed(); return false; } if ( m_channels != (unsigned int)idSoundSystemLocal::s_numberOfSpeakers.GetInteger() ) { common->Warning( "ioctl SNDCTL_DSP_CHANNELS failed to get the %d requested channels, got %d", idSoundSystemLocal::s_numberOfSpeakers.GetInteger(), m_channels ); if ( m_channels != 2 && idSoundSystemLocal::s_numberOfSpeakers.GetInteger() != 2 ) { // we didn't request 2 channels, some drivers reply 1 channel on error but may still let us still get 2 if properly asked m_channels = 2; if ( ioctl( m_audio_fd, SNDCTL_DSP_CHANNELS, &m_channels ) == -1 ) { common->Warning( "ioctl SNDCTL_DSP_CHANNELS fallback to 2 failed: %s", strerror(errno) ); InitFailed(); return false; } } if ( m_channels == 2 ) { // tell the system to mix 2 channels common->Warning( "falling back to stereo" ); idSoundSystemLocal::s_numberOfSpeakers.SetInteger( 2 ); } else { // disable sound InitFailed(); return false; } } assert( (int)m_channels == idSoundSystemLocal::s_numberOfSpeakers.GetInteger() ); // sampling rate ------------------------------------------------ m_speed = PRIMARYFREQ; if ( ioctl( m_audio_fd, SNDCTL_DSP_SPEED, &m_speed ) == -1 ) { common->Warning( "ioctl SNDCTL_DSP_SPEED %d failed: %s", PRIMARYFREQ, strerror(errno) ); InitFailed(); return false; } // instead of an exact match, do a very close to // there is some horrible Ensonic ES1371 which replies 44101 for a 44100 request if ( abs( m_speed - PRIMARYFREQ ) > 5 ) { common->Warning( "ioctl SNDCTL_DSP_SPEED failed to get the requested frequency %d, got %d", PRIMARYFREQ, m_speed ); InitFailed(); return false; } common->Printf("%s - bit rate: %d, channels: %d, frequency: %d\n", s_device.GetString(), m_sample_format, m_channels, m_speed); // output buffer ------------------------------------------------ // allocate a final buffer target, the sound engine locks, writes, and we write back to the device // we want m_buffer_size ( will have to rename those ) // ROOM_SLICES_IN_BUFFER is fixed ( system default, 10 ) // MIXBUFFER_SAMPLES is the number of samples found in a slice // each sample is m_channels * sizeof( float ) bytes // in AsyncUpdate we only write one block at a time, so we'd only need to have a final mix buffer sized of a single block m_buffer_size = MIXBUFFER_SAMPLES * m_channels * 2; m_buffer = malloc( m_buffer_size ); common->Printf( "allocated a mix buffer of %d bytes\n", m_buffer_size ); // toggle sound ------------------------------------------------- // toggle off before toggling on. that's what OSS source code samples recommends int flag = 0; if (ioctl(m_audio_fd, SNDCTL_DSP_SETTRIGGER, &flag) == -1) { common->Warning( "ioctl SNDCTL_DSP_SETTRIGGER 0 failed: %s", strerror(errno) ); } flag = PCM_ENABLE_OUTPUT; if (ioctl(m_audio_fd, SNDCTL_DSP_SETTRIGGER, &flag) == -1) { common->Warning( "ioctl SNDCTL_DSP_SETTRIGGER PCM_ENABLE_OUTPUT failed: %s", strerror(errno) ); } common->Printf("--------------------------------------\n"); return true; } /* =============== idAudioHardwareOSS::Flush =============== */ bool idAudioHardwareOSS::Flush( void ) { audio_buf_info ospace; if ( ioctl( m_audio_fd, SNDCTL_DSP_GETOSPACE, &ospace ) == -1 ) { Sys_Printf( "ioctl SNDCTL_DSP_GETOSPACE failed: %s\n", strerror( errno ) ); return false; } // how many chunks can we write to the audio device right now m_freeWriteChunks = ( ospace.bytes * MIXBUFFER_CHUNKS ) / ( MIXBUFFER_SAMPLES * m_channels * 2 ); if ( m_writeChunks ) { // flush out any remaining chunks we could now Write( true ); } return ( m_freeWriteChunks > 0 ); } /* ================= idAudioHardwareOSS::GetMixBufferSize ================= */ int idAudioHardwareOSS::GetMixBufferSize() { // return MIXBUFFER_SAMPLES * 2 * m_channels; return m_buffer_size; } /* ================= idAudioHardwareOSS::GetMixBuffer ================= */ short* idAudioHardwareOSS::GetMixBuffer() { return (short *)m_buffer; } /* =============== idAudioHardwareOSS::Write rely on m_freeWriteChunks which has been set in Flush() before engine did the mixing for this MIXBUFFER_SAMPLE =============== */ void idAudioHardwareOSS::Write( bool flushing ) { assert( m_audio_fd ); int ret; if ( !flushing && m_writeChunks ) { // if we write after a new mixing loop, we should have m_writeChunk == 0 // otherwise that last remaining chunk that was never flushed out to the audio device has just been overwritten Sys_Printf( "idAudioHardwareOSS::Write: %d samples were overflowed and dropped\n", m_writeChunks * MIXBUFFER_SAMPLES / MIXBUFFER_CHUNKS ); } if ( !flushing ) { // if running after the mix loop, then we have a full buffer to write out m_writeChunks = MIXBUFFER_CHUNKS; } if ( m_freeWriteChunks == 0 ) { return; } // what to write and how much int pos = (int)m_buffer + ( MIXBUFFER_CHUNKS - m_writeChunks ) * m_channels * 2 * MIXBUFFER_SAMPLES / MIXBUFFER_CHUNKS; int len = Min( m_writeChunks, m_freeWriteChunks ) * m_channels * 2 * MIXBUFFER_SAMPLES / MIXBUFFER_CHUNKS; assert( len > 0 ); if ( ( ret = write( m_audio_fd, (void*)pos, len ) ) == -1 ) { Sys_Printf( "write to audio fd failed: %s\n", strerror( errno ) ); return; } if ( len != ret ) { Sys_Printf( "short write to audio fd: wrote %d out of %d\n", ret, m_buffer_size ); return; } m_writeChunks -= Min( m_writeChunks, m_freeWriteChunks ); } /* =============== Sys_LoadOpenAL -=============== */ bool Sys_LoadOpenAL( void ) { return false; }
gpl-3.0
hankbao/shadowsocks-android
src/main/jni/openssl/crypto/x509v3/tabtest.c
829
3519
/* tabtest.c */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project 1999. */ /* ==================================================================== * Copyright (c) 1999 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* Simple program to check the ext_dat.h is correct and print out * problems if it is not. */ #include <stdio.h> #include <openssl/x509v3.h> #include "ext_dat.h" main() { int i, prev = -1, bad = 0; X509V3_EXT_METHOD **tmp; i = sizeof(standard_exts) / sizeof(X509V3_EXT_METHOD *); if(i != STANDARD_EXTENSION_COUNT) fprintf(stderr, "Extension number invalid expecting %d\n", i); tmp = standard_exts; for(i = 0; i < STANDARD_EXTENSION_COUNT; i++, tmp++) { if((*tmp)->ext_nid < prev) bad = 1; prev = (*tmp)->ext_nid; } if(bad) { tmp = standard_exts; fprintf(stderr, "Extensions out of order!\n"); for(i = 0; i < STANDARD_EXTENSION_COUNT; i++, tmp++) printf("%d : %s\n", (*tmp)->ext_nid, OBJ_nid2sn((*tmp)->ext_nid)); } else fprintf(stderr, "Order OK\n"); }
gpl-3.0
Distrotech/libunistring
gnulib/lib/close.c
64
1479
/* close replacement. Copyright (C) 2008-2013 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> /* Specification. */ #include <unistd.h> #include <errno.h> #include "fd-hook.h" #include "msvc-inval.h" #undef close #if HAVE_MSVC_INVALID_PARAMETER_HANDLER static int close_nothrow (int fd) { int result; TRY_MSVC_INVAL { result = close (fd); } CATCH_MSVC_INVAL { result = -1; errno = EBADF; } DONE_MSVC_INVAL; return result; } #else # define close_nothrow close #endif /* Override close() to call into other gnulib modules. */ int rpl_close (int fd) { #if WINDOWS_SOCKETS int retval = execute_all_close_hooks (close_nothrow, fd); #else int retval = close_nothrow (fd); #endif #if REPLACE_FCHDIR if (retval >= 0) _gl_unregister_fd (fd); #endif return retval; }
gpl-3.0
moypray/ardupilot
libraries/AP_Compass/examples/AP_Compass_test/AP_Compass_test.cpp
68
3739
/* * Example of APM_Compass library (HMC5843 sensor). * Code by Jordi MuÒoz and Jose Julio. DIYDrones.com */ #include <AP_Common/AP_Common.h> #include <AP_Progmem/AP_Progmem.h> #include <AP_Param/AP_Param.h> #include <StorageManager/StorageManager.h> #include <AP_HAL/AP_HAL.h> #include <AP_HAL_AVR/AP_HAL_AVR.h> #include <AP_HAL_PX4/AP_HAL_PX4.h> #include <AP_HAL_Linux/AP_HAL_Linux.h> #include <AP_HAL_FLYMAPLE/AP_HAL_FLYMAPLE.h> #include <AP_HAL_Empty/AP_HAL_Empty.h> #include <AP_HAL_VRBRAIN/AP_HAL_VRBRAIN.h> #include <AP_Math/AP_Math.h> // ArduPilot Mega Vector/Matrix math Library #include <AP_Declination/AP_Declination.h> #include <AP_Compass/AP_Compass.h> // Compass Library #include <GCS_MAVLink/GCS_MAVLink.h> #include <AP_Scheduler/AP_Scheduler.h> #include <DataFlash/DataFlash.h> #include <AP_GPS/AP_GPS.h> #include <AP_Vehicle/AP_Vehicle.h> #include <AP_InertialSensor/AP_InertialSensor.h> #include <Filter/Filter.h> #include <AP_Baro/AP_Baro.h> #include <AP_AHRS/AP_AHRS.h> #include <AP_Airspeed/AP_Airspeed.h> #include <AP_NavEKF/AP_NavEKF.h> #include <AP_ADC/AP_ADC.h> #include <AP_ADC_AnalogSource/AP_ADC_AnalogSource.h> #include <AP_Notify/AP_Notify.h> #include <AP_Mission/AP_Mission.h> #include <AP_Terrain/AP_Terrain.h> #include <AP_Rally/AP_Rally.h> #include <AP_BattMonitor/AP_BattMonitor.h> #include <AP_RangeFinder/AP_RangeFinder.h> const AP_HAL::HAL& hal = AP_HAL_BOARD_DRIVER; static Compass compass; uint32_t timer; void setup() { hal.console->println("Compass library test"); if (!compass.init()) { hal.console->println("compass initialisation failed!"); while (1) ; } hal.console->printf("init done - %u compasses detected\n", compass.get_count()); compass.set_and_save_offsets(0,0,0,0); // set offsets to account for surrounding interference compass.set_declination(ToRad(0.0f)); // set local difference between magnetic north and true north hal.scheduler->delay(1000); timer = hal.scheduler->micros(); } void loop() { static float min[3], max[3], offset[3]; compass.accumulate(); if((hal.scheduler->micros()- timer) > 100000L) { timer = hal.scheduler->micros(); compass.read(); unsigned long read_time = hal.scheduler->micros() - timer; float heading; if (!compass.healthy()) { hal.console->println("not healthy"); return; } Matrix3f dcm_matrix; // use roll = 0, pitch = 0 for this example dcm_matrix.from_euler(0, 0, 0); heading = compass.calculate_heading(dcm_matrix); compass.learn_offsets(); // capture min const Vector3f &mag = compass.get_field(); if( mag.x < min[0] ) min[0] = mag.x; if( mag.y < min[1] ) min[1] = mag.y; if( mag.z < min[2] ) min[2] = mag.z; // capture max if( mag.x > max[0] ) max[0] = mag.x; if( mag.y > max[1] ) max[1] = mag.y; if( mag.z > max[2] ) max[2] = mag.z; // calculate offsets offset[0] = -(max[0]+min[0])/2; offset[1] = -(max[1]+min[1])/2; offset[2] = -(max[2]+min[2])/2; // display all to user hal.console->printf("Heading: %.2f (%3d,%3d,%3d) i2c error: %u", ToDeg(heading), (int)mag.x, (int)mag.y, (int)mag.z, (unsigned)hal.i2c->lockup_count()); // display offsets hal.console->printf(" offsets(%.2f, %.2f, %.2f)", offset[0], offset[1], offset[2]); hal.console->printf(" t=%u", (unsigned)read_time); hal.console->println(); } else { hal.scheduler->delay(1); } } AP_HAL_MAIN();
gpl-3.0
TonyBazz/betaflight
lib/main/STM32F4/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rng.c
71
16965
/** ****************************************************************************** * @file stm32f4xx_hal_rng.c * @author MCD Application Team * @version V1.7.1 * @date 14-April-2017 * @brief RNG HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Random Number Generator (RNG) peripheral: * + Initialization/de-initialization functions * + Peripheral Control functions * + Peripheral State functions * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] The RNG HAL driver can be used as follows: (#) Enable the RNG controller clock using __HAL_RCC_RNG_CLK_ENABLE() macro in HAL_RNG_MspInit(). (#) Activate the RNG peripheral using HAL_RNG_Init() function. (#) Wait until the 32 bit Random Number Generator contains a valid random data using (polling/interrupt) mode. (#) Get the 32 bit random number using HAL_RNG_GenerateRandomNumber() function. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RNG * @{ */ #ifdef HAL_RNG_MODULE_ENABLED #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F469xx) ||\ defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) || defined(STM32F412Rx) ||\ defined(STM32F412Cx) || defined(STM32F413xx) || defined(STM32F423xx) /* Private types -------------------------------------------------------------*/ /* Private defines -----------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @addtogroup RNG_Private_Constants * @{ */ #define RNG_TIMEOUT_VALUE 2U /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private functions prototypes ----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RNG_Exported_Functions * @{ */ /** @addtogroup RNG_Exported_Functions_Group1 * @brief Initialization and de-initialization functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Initialize the RNG according to the specified parameters in the RNG_InitTypeDef and create the associated handle (+) DeInitialize the RNG peripheral (+) Initialize the RNG MSP (+) DeInitialize RNG MSP @endverbatim * @{ */ /** * @brief Initializes the RNG peripheral and creates the associated handle. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval HAL status */ HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng) { /* Check the RNG handle allocation */ if(hrng == NULL) { return HAL_ERROR; } __HAL_LOCK(hrng); if(hrng->State == HAL_RNG_STATE_RESET) { /* Allocate lock resource and initialize it */ hrng->Lock = HAL_UNLOCKED; /* Init the low level hardware */ HAL_RNG_MspInit(hrng); } /* Change RNG peripheral state */ hrng->State = HAL_RNG_STATE_BUSY; /* Enable the RNG Peripheral */ __HAL_RNG_ENABLE(hrng); /* Initialize the RNG state */ hrng->State = HAL_RNG_STATE_READY; __HAL_UNLOCK(hrng); /* Return function status */ return HAL_OK; } /** * @brief DeInitializes the RNG peripheral. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval HAL status */ HAL_StatusTypeDef HAL_RNG_DeInit(RNG_HandleTypeDef *hrng) { /* Check the RNG handle allocation */ if(hrng == NULL) { return HAL_ERROR; } /* Disable the RNG Peripheral */ CLEAR_BIT(hrng->Instance->CR, RNG_CR_IE | RNG_CR_RNGEN); /* Clear RNG interrupt status flags */ CLEAR_BIT(hrng->Instance->SR, RNG_SR_CEIS | RNG_SR_SEIS); /* DeInit the low level hardware */ HAL_RNG_MspDeInit(hrng); /* Update the RNG state */ hrng->State = HAL_RNG_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(hrng); /* Return the function status */ return HAL_OK; } /** * @brief Initializes the RNG MSP. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval None */ __weak void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrng); /* NOTE : This function should not be modified. When the callback is needed, function HAL_RNG_MspInit must be implemented in the user file. */ } /** * @brief DeInitializes the RNG MSP. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval None */ __weak void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrng); /* NOTE : This function should not be modified. When the callback is needed, function HAL_RNG_MspDeInit must be implemented in the user file. */ } /** * @} */ /** @addtogroup RNG_Exported_Functions_Group2 * @brief Peripheral Control functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Get the 32 bit Random number (+) Get the 32 bit Random number with interrupt enabled (+) Handle RNG interrupt request @endverbatim * @{ */ /** * @brief Generates a 32-bit random number. * @note Each time the random number data is read the RNG_FLAG_DRDY flag * is automatically cleared. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @param random32bit: pointer to generated random number variable if successful. * @retval HAL status */ HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit) { uint32_t tickstart = 0U; HAL_StatusTypeDef status = HAL_OK; /* Process Locked */ __HAL_LOCK(hrng); /* Check RNG peripheral state */ if(hrng->State == HAL_RNG_STATE_READY) { /* Change RNG peripheral state */ hrng->State = HAL_RNG_STATE_BUSY; /* Get tick */ tickstart = HAL_GetTick(); /* Check if data register contains valid random data */ while(__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) == RESET) { if((HAL_GetTick() - tickstart ) > RNG_TIMEOUT_VALUE) { hrng->State = HAL_RNG_STATE_ERROR; /* Process Unlocked */ __HAL_UNLOCK(hrng); return HAL_TIMEOUT; } } /* Get a 32bit Random number */ hrng->RandomNumber = hrng->Instance->DR; *random32bit = hrng->RandomNumber; hrng->State = HAL_RNG_STATE_READY; } else { status = HAL_ERROR; } /* Process Unlocked */ __HAL_UNLOCK(hrng); return status; } /** * @brief Generates a 32-bit random number in interrupt mode. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval HAL status */ HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber_IT(RNG_HandleTypeDef *hrng) { HAL_StatusTypeDef status = HAL_OK; /* Process Locked */ __HAL_LOCK(hrng); /* Check RNG peripheral state */ if(hrng->State == HAL_RNG_STATE_READY) { /* Change RNG peripheral state */ hrng->State = HAL_RNG_STATE_BUSY; /* Process Unlocked */ __HAL_UNLOCK(hrng); /* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */ __HAL_RNG_ENABLE_IT(hrng); } else { /* Process Unlocked */ __HAL_UNLOCK(hrng); status = HAL_ERROR; } return status; } /** * @brief Handles RNG interrupt request. * @note In the case of a clock error, the RNG is no more able to generate * random numbers because the PLL48CLK clock is not correct. User has * to check that the clock controller is correctly configured to provide * the RNG clock and clear the CEIS bit using __HAL_RNG_CLEAR_IT(). * The clock error has no impact on the previously generated * random numbers, and the RNG_DR register contents can be used. * @note In the case of a seed error, the generation of random numbers is * interrupted as long as the SECS bit is '1'. If a number is * available in the RNG_DR register, it must not be used because it may * not have enough entropy. In this case, it is recommended to clear the * SEIS bit using __HAL_RNG_CLEAR_IT(), then disable and enable * the RNG peripheral to reinitialize and restart the RNG. * @note User-written HAL_RNG_ErrorCallback() API is called once whether SEIS * or CEIS are set. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval None */ void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng) { /* RNG clock error interrupt occurred */ if((__HAL_RNG_GET_IT(hrng, RNG_IT_CEI) != RESET) || (__HAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET)) { /* Change RNG peripheral state */ hrng->State = HAL_RNG_STATE_ERROR; HAL_RNG_ErrorCallback(hrng); /* Clear the clock error flag */ __HAL_RNG_CLEAR_IT(hrng, RNG_IT_CEI|RNG_IT_SEI); } /* Check RNG data ready interrupt occurred */ if(__HAL_RNG_GET_IT(hrng, RNG_IT_DRDY) != RESET) { /* Generate random number once, so disable the IT */ __HAL_RNG_DISABLE_IT(hrng); /* Get the 32bit Random number (DRDY flag automatically cleared) */ hrng->RandomNumber = hrng->Instance->DR; if(hrng->State != HAL_RNG_STATE_ERROR) { /* Change RNG peripheral state */ hrng->State = HAL_RNG_STATE_READY; /* Data Ready callback */ HAL_RNG_ReadyDataCallback(hrng, hrng->RandomNumber); } } } /** * @brief Returns generated random number in polling mode (Obsolete) * Use HAL_RNG_GenerateRandomNumber() API instead. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval Random value */ uint32_t HAL_RNG_GetRandomNumber(RNG_HandleTypeDef *hrng) { if(HAL_RNG_GenerateRandomNumber(hrng, &(hrng->RandomNumber)) == HAL_OK) { return hrng->RandomNumber; } else { return 0U; } } /** * @brief Returns a 32-bit random number with interrupt enabled (Obsolete), * Use HAL_RNG_GenerateRandomNumber_IT() API instead. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval 32-bit random number */ uint32_t HAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng) { uint32_t random32bit = 0U; /* Process locked */ __HAL_LOCK(hrng); /* Change RNG peripheral state */ hrng->State = HAL_RNG_STATE_BUSY; /* Get a 32bit Random number */ random32bit = hrng->Instance->DR; /* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */ __HAL_RNG_ENABLE_IT(hrng); /* Return the 32 bit random number */ return random32bit; } /** * @brief Read latest generated random number. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval random value */ uint32_t HAL_RNG_ReadLastRandomNumber(RNG_HandleTypeDef *hrng) { return(hrng->RandomNumber); } /** * @brief Data Ready callback in non-blocking mode. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @param random32bit: generated random number. * @retval None */ __weak void HAL_RNG_ReadyDataCallback(RNG_HandleTypeDef *hrng, uint32_t random32bit) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrng); UNUSED(random32bit); /* NOTE : This function should not be modified. When the callback is needed, function HAL_RNG_ReadyDataCallback must be implemented in the user file. */ } /** * @brief RNG error callbacks. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval None */ __weak void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrng); /* NOTE : This function should not be modified. When the callback is needed, function HAL_RNG_ErrorCallback must be implemented in the user file. */ } /** * @} */ /** @addtogroup RNG_Exported_Functions_Group3 * @brief Peripheral State functions * @verbatim =============================================================================== ##### Peripheral State functions ##### =============================================================================== [..] This subsection permits to get in run-time the status of the peripheral and the data flow. @endverbatim * @{ */ /** * @brief Returns the RNG state. * @param hrng: pointer to a RNG_HandleTypeDef structure that contains * the configuration information for RNG. * @retval HAL state */ HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng) { return hrng->State; } /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F410xx || STM32F469xx || STM32F479xx || STM32F412Zx ||\ STM32F412Vx || STM32F412Rx || STM32F412Cx || STM32F413xx || STM32F423xx */ #endif /* HAL_RNG_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
gpl-3.0
ZeroInfinityXDA/HelixKernel-EAS-HTC10
arch/x86/kernel/cpu/mtrr/main.c
77
22687
/* Generic MTRR (Memory Type Range Register) driver. Copyright (C) 1997-2000 Richard Gooch Copyright (c) 2002 Patrick Mochel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Richard Gooch may be reached by email at rgooch@atnf.csiro.au The postal address is: Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia. Source: "Pentium Pro Family Developer's Manual, Volume 3: Operating System Writer's Guide" (Intel document number 242692), section 11.11.7 This was cleaned and made readable by Patrick Mochel <mochel@osdl.org> on 6-7 March 2002. Source: Intel Architecture Software Developers Manual, Volume 3: System Programming Guide; Section 9.11. (1997 edition - PPro). */ #define DEBUG #include <linux/types.h> /* FIXME: kvm_para.h needs this */ #include <linux/stop_machine.h> #include <linux/kvm_para.h> #include <linux/uaccess.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/init.h> #include <linux/sort.h> #include <linux/cpu.h> #include <linux/pci.h> #include <linux/smp.h> #include <linux/syscore_ops.h> #include <asm/processor.h> #include <asm/e820.h> #include <asm/mtrr.h> #include <asm/msr.h> #include <asm/pat.h> #include "mtrr.h" /* arch_phys_wc_add returns an MTRR register index plus this offset. */ #define MTRR_TO_PHYS_WC_OFFSET 1000 u32 num_var_ranges; unsigned int mtrr_usage_table[MTRR_MAX_VAR_RANGES]; static DEFINE_MUTEX(mtrr_mutex); u64 size_or_mask, size_and_mask; static bool mtrr_aps_delayed_init; static const struct mtrr_ops *mtrr_ops[X86_VENDOR_NUM]; const struct mtrr_ops *mtrr_if; static void set_mtrr(unsigned int reg, unsigned long base, unsigned long size, mtrr_type type); void set_mtrr_ops(const struct mtrr_ops *ops) { if (ops->vendor && ops->vendor < X86_VENDOR_NUM) mtrr_ops[ops->vendor] = ops; } /* Returns non-zero if we have the write-combining memory type */ static int have_wrcomb(void) { struct pci_dev *dev; dev = pci_get_class(PCI_CLASS_BRIDGE_HOST << 8, NULL); if (dev != NULL) { /* * ServerWorks LE chipsets < rev 6 have problems with * write-combining. Don't allow it and leave room for other * chipsets to be tagged */ if (dev->vendor == PCI_VENDOR_ID_SERVERWORKS && dev->device == PCI_DEVICE_ID_SERVERWORKS_LE && dev->revision <= 5) { pr_info("mtrr: Serverworks LE rev < 6 detected. Write-combining disabled.\n"); pci_dev_put(dev); return 0; } /* * Intel 450NX errata # 23. Non ascending cacheline evictions to * write combining memory may resulting in data corruption */ if (dev->vendor == PCI_VENDOR_ID_INTEL && dev->device == PCI_DEVICE_ID_INTEL_82451NX) { pr_info("mtrr: Intel 450NX MMC detected. Write-combining disabled.\n"); pci_dev_put(dev); return 0; } pci_dev_put(dev); } return mtrr_if->have_wrcomb ? mtrr_if->have_wrcomb() : 0; } /* This function returns the number of variable MTRRs */ static void __init set_num_var_ranges(void) { unsigned long config = 0, dummy; if (use_intel()) rdmsr(MSR_MTRRcap, config, dummy); else if (is_cpu(AMD)) config = 2; else if (is_cpu(CYRIX) || is_cpu(CENTAUR)) config = 8; num_var_ranges = config & 0xff; } static void __init init_table(void) { int i, max; max = num_var_ranges; for (i = 0; i < max; i++) mtrr_usage_table[i] = 1; } struct set_mtrr_data { unsigned long smp_base; unsigned long smp_size; unsigned int smp_reg; mtrr_type smp_type; }; /** * mtrr_rendezvous_handler - Work done in the synchronization handler. Executed * by all the CPUs. * @info: pointer to mtrr configuration data * * Returns nothing. */ static int mtrr_rendezvous_handler(void *info) { struct set_mtrr_data *data = info; /* * We use this same function to initialize the mtrrs during boot, * resume, runtime cpu online and on an explicit request to set a * specific MTRR. * * During boot or suspend, the state of the boot cpu's mtrrs has been * saved, and we want to replicate that across all the cpus that come * online (either at the end of boot or resume or during a runtime cpu * online). If we're doing that, @reg is set to something special and on * all the cpu's we do mtrr_if->set_all() (On the logical cpu that * started the boot/resume sequence, this might be a duplicate * set_all()). */ if (data->smp_reg != ~0U) { mtrr_if->set(data->smp_reg, data->smp_base, data->smp_size, data->smp_type); } else if (mtrr_aps_delayed_init || !cpu_online(smp_processor_id())) { mtrr_if->set_all(); } return 0; } static inline int types_compatible(mtrr_type type1, mtrr_type type2) { return type1 == MTRR_TYPE_UNCACHABLE || type2 == MTRR_TYPE_UNCACHABLE || (type1 == MTRR_TYPE_WRTHROUGH && type2 == MTRR_TYPE_WRBACK) || (type1 == MTRR_TYPE_WRBACK && type2 == MTRR_TYPE_WRTHROUGH); } /** * set_mtrr - update mtrrs on all processors * @reg: mtrr in question * @base: mtrr base * @size: mtrr size * @type: mtrr type * * This is kinda tricky, but fortunately, Intel spelled it out for us cleanly: * * 1. Queue work to do the following on all processors: * 2. Disable Interrupts * 3. Wait for all procs to do so * 4. Enter no-fill cache mode * 5. Flush caches * 6. Clear PGE bit * 7. Flush all TLBs * 8. Disable all range registers * 9. Update the MTRRs * 10. Enable all range registers * 11. Flush all TLBs and caches again * 12. Enter normal cache mode and reenable caching * 13. Set PGE * 14. Wait for buddies to catch up * 15. Enable interrupts. * * What does that mean for us? Well, stop_machine() will ensure that * the rendezvous handler is started on each CPU. And in lockstep they * do the state transition of disabling interrupts, updating MTRR's * (the CPU vendors may each do it differently, so we call mtrr_if->set() * callback and let them take care of it.) and enabling interrupts. * * Note that the mechanism is the same for UP systems, too; all the SMP stuff * becomes nops. */ static void set_mtrr(unsigned int reg, unsigned long base, unsigned long size, mtrr_type type) { struct set_mtrr_data data = { .smp_reg = reg, .smp_base = base, .smp_size = size, .smp_type = type }; stop_machine(mtrr_rendezvous_handler, &data, cpu_online_mask); } static void set_mtrr_from_inactive_cpu(unsigned int reg, unsigned long base, unsigned long size, mtrr_type type) { struct set_mtrr_data data = { .smp_reg = reg, .smp_base = base, .smp_size = size, .smp_type = type }; stop_machine_from_inactive_cpu(mtrr_rendezvous_handler, &data, cpu_callout_mask); } /** * mtrr_add_page - Add a memory type region * @base: Physical base address of region in pages (in units of 4 kB!) * @size: Physical size of region in pages (4 kB) * @type: Type of MTRR desired * @increment: If this is true do usage counting on the region * * Memory type region registers control the caching on newer Intel and * non Intel processors. This function allows drivers to request an * MTRR is added. The details and hardware specifics of each processor's * implementation are hidden from the caller, but nevertheless the * caller should expect to need to provide a power of two size on an * equivalent power of two boundary. * * If the region cannot be added either because all regions are in use * or the CPU cannot support it a negative value is returned. On success * the register number for this entry is returned, but should be treated * as a cookie only. * * On a multiprocessor machine the changes are made to all processors. * This is required on x86 by the Intel processors. * * The available types are * * %MTRR_TYPE_UNCACHABLE - No caching * * %MTRR_TYPE_WRBACK - Write data back in bursts whenever * * %MTRR_TYPE_WRCOMB - Write data back soon but allow bursts * * %MTRR_TYPE_WRTHROUGH - Cache reads but not writes * * BUGS: Needs a quiet flag for the cases where drivers do not mind * failures and do not wish system log messages to be sent. */ int mtrr_add_page(unsigned long base, unsigned long size, unsigned int type, bool increment) { unsigned long lbase, lsize; int i, replace, error; mtrr_type ltype; if (!mtrr_if) return -ENXIO; error = mtrr_if->validate_add_page(base, size, type); if (error) return error; if (type >= MTRR_NUM_TYPES) { pr_warning("mtrr: type: %u invalid\n", type); return -EINVAL; } /* If the type is WC, check that this processor supports it */ if ((type == MTRR_TYPE_WRCOMB) && !have_wrcomb()) { pr_warning("mtrr: your processor doesn't support write-combining\n"); return -ENOSYS; } if (!size) { pr_warning("mtrr: zero sized request\n"); return -EINVAL; } if ((base | (base + size - 1)) >> (boot_cpu_data.x86_phys_bits - PAGE_SHIFT)) { pr_warning("mtrr: base or size exceeds the MTRR width\n"); return -EINVAL; } error = -EINVAL; replace = -1; /* No CPU hotplug when we change MTRR entries */ get_online_cpus(); /* Search for existing MTRR */ mutex_lock(&mtrr_mutex); for (i = 0; i < num_var_ranges; ++i) { mtrr_if->get(i, &lbase, &lsize, &ltype); if (!lsize || base > lbase + lsize - 1 || base + size - 1 < lbase) continue; /* * At this point we know there is some kind of * overlap/enclosure */ if (base < lbase || base + size - 1 > lbase + lsize - 1) { if (base <= lbase && base + size - 1 >= lbase + lsize - 1) { /* New region encloses an existing region */ if (type == ltype) { replace = replace == -1 ? i : -2; continue; } else if (types_compatible(type, ltype)) continue; } pr_warning("mtrr: 0x%lx000,0x%lx000 overlaps existing" " 0x%lx000,0x%lx000\n", base, size, lbase, lsize); goto out; } /* New region is enclosed by an existing region */ if (ltype != type) { if (types_compatible(type, ltype)) continue; pr_warning("mtrr: type mismatch for %lx000,%lx000 old: %s new: %s\n", base, size, mtrr_attrib_to_str(ltype), mtrr_attrib_to_str(type)); goto out; } if (increment) ++mtrr_usage_table[i]; error = i; goto out; } /* Search for an empty MTRR */ i = mtrr_if->get_free_region(base, size, replace); if (i >= 0) { set_mtrr(i, base, size, type); if (likely(replace < 0)) { mtrr_usage_table[i] = 1; } else { mtrr_usage_table[i] = mtrr_usage_table[replace]; if (increment) mtrr_usage_table[i]++; if (unlikely(replace != i)) { set_mtrr(replace, 0, 0, 0); mtrr_usage_table[replace] = 0; } } } else { pr_info("mtrr: no more MTRRs available\n"); } error = i; out: mutex_unlock(&mtrr_mutex); put_online_cpus(); return error; } static int mtrr_check(unsigned long base, unsigned long size) { if ((base & (PAGE_SIZE - 1)) || (size & (PAGE_SIZE - 1))) { pr_warning("mtrr: size and base must be multiples of 4 kiB\n"); pr_debug("mtrr: size: 0x%lx base: 0x%lx\n", size, base); dump_stack(); return -1; } return 0; } /** * mtrr_add - Add a memory type region * @base: Physical base address of region * @size: Physical size of region * @type: Type of MTRR desired * @increment: If this is true do usage counting on the region * * Memory type region registers control the caching on newer Intel and * non Intel processors. This function allows drivers to request an * MTRR is added. The details and hardware specifics of each processor's * implementation are hidden from the caller, but nevertheless the * caller should expect to need to provide a power of two size on an * equivalent power of two boundary. * * If the region cannot be added either because all regions are in use * or the CPU cannot support it a negative value is returned. On success * the register number for this entry is returned, but should be treated * as a cookie only. * * On a multiprocessor machine the changes are made to all processors. * This is required on x86 by the Intel processors. * * The available types are * * %MTRR_TYPE_UNCACHABLE - No caching * * %MTRR_TYPE_WRBACK - Write data back in bursts whenever * * %MTRR_TYPE_WRCOMB - Write data back soon but allow bursts * * %MTRR_TYPE_WRTHROUGH - Cache reads but not writes * * BUGS: Needs a quiet flag for the cases where drivers do not mind * failures and do not wish system log messages to be sent. */ int mtrr_add(unsigned long base, unsigned long size, unsigned int type, bool increment) { if (mtrr_check(base, size)) return -EINVAL; return mtrr_add_page(base >> PAGE_SHIFT, size >> PAGE_SHIFT, type, increment); } EXPORT_SYMBOL(mtrr_add); /** * mtrr_del_page - delete a memory type region * @reg: Register returned by mtrr_add * @base: Physical base address * @size: Size of region * * If register is supplied then base and size are ignored. This is * how drivers should call it. * * Releases an MTRR region. If the usage count drops to zero the * register is freed and the region returns to default state. * On success the register is returned, on failure a negative error * code. */ int mtrr_del_page(int reg, unsigned long base, unsigned long size) { int i, max; mtrr_type ltype; unsigned long lbase, lsize; int error = -EINVAL; if (!mtrr_if) return -ENXIO; max = num_var_ranges; /* No CPU hotplug when we change MTRR entries */ get_online_cpus(); mutex_lock(&mtrr_mutex); if (reg < 0) { /* Search for existing MTRR */ for (i = 0; i < max; ++i) { mtrr_if->get(i, &lbase, &lsize, &ltype); if (lbase == base && lsize == size) { reg = i; break; } } if (reg < 0) { pr_debug("mtrr: no MTRR for %lx000,%lx000 found\n", base, size); goto out; } } if (reg >= max) { pr_warning("mtrr: register: %d too big\n", reg); goto out; } mtrr_if->get(reg, &lbase, &lsize, &ltype); if (lsize < 1) { pr_warning("mtrr: MTRR %d not used\n", reg); goto out; } if (mtrr_usage_table[reg] < 1) { pr_warning("mtrr: reg: %d has count=0\n", reg); goto out; } if (--mtrr_usage_table[reg] < 1) set_mtrr(reg, 0, 0, 0); error = reg; out: mutex_unlock(&mtrr_mutex); put_online_cpus(); return error; } /** * mtrr_del - delete a memory type region * @reg: Register returned by mtrr_add * @base: Physical base address * @size: Size of region * * If register is supplied then base and size are ignored. This is * how drivers should call it. * * Releases an MTRR region. If the usage count drops to zero the * register is freed and the region returns to default state. * On success the register is returned, on failure a negative error * code. */ int mtrr_del(int reg, unsigned long base, unsigned long size) { if (mtrr_check(base, size)) return -EINVAL; return mtrr_del_page(reg, base >> PAGE_SHIFT, size >> PAGE_SHIFT); } EXPORT_SYMBOL(mtrr_del); /** * arch_phys_wc_add - add a WC MTRR and handle errors if PAT is unavailable * @base: Physical base address * @size: Size of region * * If PAT is available, this does nothing. If PAT is unavailable, it * attempts to add a WC MTRR covering size bytes starting at base and * logs an error if this fails. * * Drivers must store the return value to pass to mtrr_del_wc_if_needed, * but drivers should not try to interpret that return value. */ int arch_phys_wc_add(unsigned long base, unsigned long size) { int ret; if (pat_enabled) return 0; /* Success! (We don't need to do anything.) */ ret = mtrr_add(base, size, MTRR_TYPE_WRCOMB, true); if (ret < 0) { pr_warn("Failed to add WC MTRR for [%p-%p]; performance may suffer.", (void *)base, (void *)(base + size - 1)); return ret; } return ret + MTRR_TO_PHYS_WC_OFFSET; } EXPORT_SYMBOL(arch_phys_wc_add); /* * arch_phys_wc_del - undoes arch_phys_wc_add * @handle: Return value from arch_phys_wc_add * * This cleans up after mtrr_add_wc_if_needed. * * The API guarantees that mtrr_del_wc_if_needed(error code) and * mtrr_del_wc_if_needed(0) do nothing. */ void arch_phys_wc_del(int handle) { if (handle >= 1) { WARN_ON(handle < MTRR_TO_PHYS_WC_OFFSET); mtrr_del(handle - MTRR_TO_PHYS_WC_OFFSET, 0, 0); } } EXPORT_SYMBOL(arch_phys_wc_del); /* * arch_phys_wc_index - translates arch_phys_wc_add's return value * @handle: Return value from arch_phys_wc_add * * This will turn the return value from arch_phys_wc_add into an mtrr * index suitable for debugging. * * Note: There is no legitimate use for this function, except possibly * in printk line. Alas there is an illegitimate use in some ancient * drm ioctls. */ int arch_phys_wc_index(int handle) { if (handle < MTRR_TO_PHYS_WC_OFFSET) return -1; else return handle - MTRR_TO_PHYS_WC_OFFSET; } EXPORT_SYMBOL_GPL(arch_phys_wc_index); /* * HACK ALERT! * These should be called implicitly, but we can't yet until all the initcall * stuff is done... */ static void __init init_ifs(void) { #ifndef CONFIG_X86_64 amd_init_mtrr(); cyrix_init_mtrr(); centaur_init_mtrr(); #endif } /* The suspend/resume methods are only for CPU without MTRR. CPU using generic * MTRR driver doesn't require this */ struct mtrr_value { mtrr_type ltype; unsigned long lbase; unsigned long lsize; }; static struct mtrr_value mtrr_value[MTRR_MAX_VAR_RANGES]; static int mtrr_save(void) { int i; for (i = 0; i < num_var_ranges; i++) { mtrr_if->get(i, &mtrr_value[i].lbase, &mtrr_value[i].lsize, &mtrr_value[i].ltype); } return 0; } static void mtrr_restore(void) { int i; for (i = 0; i < num_var_ranges; i++) { if (mtrr_value[i].lsize) { set_mtrr(i, mtrr_value[i].lbase, mtrr_value[i].lsize, mtrr_value[i].ltype); } } } static struct syscore_ops mtrr_syscore_ops = { .suspend = mtrr_save, .resume = mtrr_restore, }; int __initdata changed_by_mtrr_cleanup; #define SIZE_OR_MASK_BITS(n) (~((1ULL << ((n) - PAGE_SHIFT)) - 1)) /** * mtrr_bp_init - initialize mtrrs on the boot CPU * * This needs to be called early; before any of the other CPUs are * initialized (i.e. before smp_init()). * */ void __init mtrr_bp_init(void) { u32 phys_addr; init_ifs(); phys_addr = 32; if (cpu_has_mtrr) { mtrr_if = &generic_mtrr_ops; size_or_mask = SIZE_OR_MASK_BITS(36); size_and_mask = 0x00f00000; phys_addr = 36; /* * This is an AMD specific MSR, but we assume(hope?) that * Intel will implement it too when they extend the address * bus of the Xeon. */ if (cpuid_eax(0x80000000) >= 0x80000008) { phys_addr = cpuid_eax(0x80000008) & 0xff; /* CPUID workaround for Intel 0F33/0F34 CPU */ if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL && boot_cpu_data.x86 == 0xF && boot_cpu_data.x86_model == 0x3 && (boot_cpu_data.x86_mask == 0x3 || boot_cpu_data.x86_mask == 0x4)) phys_addr = 36; size_or_mask = SIZE_OR_MASK_BITS(phys_addr); size_and_mask = ~size_or_mask & 0xfffff00000ULL; } else if (boot_cpu_data.x86_vendor == X86_VENDOR_CENTAUR && boot_cpu_data.x86 == 6) { /* * VIA C* family have Intel style MTRRs, * but don't support PAE */ size_or_mask = SIZE_OR_MASK_BITS(32); size_and_mask = 0; phys_addr = 32; } } else { switch (boot_cpu_data.x86_vendor) { case X86_VENDOR_AMD: if (cpu_feature_enabled(X86_FEATURE_K6_MTRR)) { /* Pre-Athlon (K6) AMD CPU MTRRs */ mtrr_if = mtrr_ops[X86_VENDOR_AMD]; size_or_mask = SIZE_OR_MASK_BITS(32); size_and_mask = 0; } break; case X86_VENDOR_CENTAUR: if (cpu_feature_enabled(X86_FEATURE_CENTAUR_MCR)) { mtrr_if = mtrr_ops[X86_VENDOR_CENTAUR]; size_or_mask = SIZE_OR_MASK_BITS(32); size_and_mask = 0; } break; case X86_VENDOR_CYRIX: if (cpu_feature_enabled(X86_FEATURE_CYRIX_ARR)) { mtrr_if = mtrr_ops[X86_VENDOR_CYRIX]; size_or_mask = SIZE_OR_MASK_BITS(32); size_and_mask = 0; } break; default: break; } } if (mtrr_if) { set_num_var_ranges(); init_table(); if (use_intel()) { get_mtrr_state(); if (mtrr_cleanup(phys_addr)) { changed_by_mtrr_cleanup = 1; mtrr_if->set_all(); } } } } void mtrr_ap_init(void) { if (!use_intel() || mtrr_aps_delayed_init) return; /* * Ideally we should hold mtrr_mutex here to avoid mtrr entries * changed, but this routine will be called in cpu boot time, * holding the lock breaks it. * * This routine is called in two cases: * * 1. very earily time of software resume, when there absolutely * isn't mtrr entry changes; * * 2. cpu hotadd time. We let mtrr_add/del_page hold cpuhotplug * lock to prevent mtrr entry changes */ set_mtrr_from_inactive_cpu(~0U, 0, 0, 0); } /** * Save current fixed-range MTRR state of the first cpu in cpu_online_mask. */ void mtrr_save_state(void) { int first_cpu; get_online_cpus(); first_cpu = cpumask_first(cpu_online_mask); smp_call_function_single(first_cpu, mtrr_save_fixed_ranges, NULL, 1); put_online_cpus(); } void set_mtrr_aps_delayed_init(void) { if (!use_intel()) return; mtrr_aps_delayed_init = true; } /* * Delayed MTRR initialization for all AP's */ void mtrr_aps_init(void) { if (!use_intel()) return; /* * Check if someone has requested the delay of AP MTRR initialization, * by doing set_mtrr_aps_delayed_init(), prior to this point. If not, * then we are done. */ if (!mtrr_aps_delayed_init) return; set_mtrr(~0U, 0, 0, 0); mtrr_aps_delayed_init = false; } void mtrr_bp_restore(void) { if (!use_intel()) return; mtrr_if->set_all(); } static int __init mtrr_init_finialize(void) { if (!mtrr_if) return 0; if (use_intel()) { if (!changed_by_mtrr_cleanup) mtrr_state_warn(); return 0; } /* * The CPU has no MTRR and seems to not support SMP. They have * specific drivers, we use a tricky method to support * suspend/resume for them. * * TBD: is there any system with such CPU which supports * suspend/resume? If no, we should remove the code. */ register_syscore_ops(&mtrr_syscore_ops); return 0; } subsys_initcall(mtrr_init_finialize);
gpl-3.0
flounderscore/ardupilot
libraries/AP_HAL_AVR/Scheduler_Timer.cpp
79
4933
#include <AP_HAL/AP_HAL.h> #if (CONFIG_HAL_BOARD == HAL_BOARD_APM1 || CONFIG_HAL_BOARD == HAL_BOARD_APM2) #include <avr/io.h> #include <avr/interrupt.h> #include "Scheduler.h" using namespace AP_HAL_AVR; #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #if (CONFIG_HAL_BOARD == HAL_BOARD_APM1 ) #define AVR_TIMER_OVF_VECT TIMER4_OVF_vect #define AVR_TIMER_TCNT TCNT4 #define AVR_TIMER_TIFR TIFR4 #define AVR_TIMER_TCCRA TCCR4A #define AVR_TIMER_TCCRB TCCR4B #define AVR_TIMER_OCRA OCR4A #define AVR_TIMER_TIMSK TIMSK4 #define AVR_TIMER_TOIE TOIE4 #define AVR_TIMER_WGM0 WGM40 #define AVR_TIMER_WGM1 WGM41 #define AVR_TIMER_WGM2 WGM42 #define AVR_TIMER_WGM3 WGM43 #define AVR_TIMER_CS1 CS41 #elif (CONFIG_HAL_BOARD == HAL_BOARD_APM2 ) #define AVR_TIMER_OVF_VECT TIMER5_OVF_vect #define AVR_TIMER_TCNT TCNT5 #define AVR_TIMER_TIFR TIFR5 #define AVR_TIMER_TCCRA TCCR5A #define AVR_TIMER_TCCRB TCCR5B #define AVR_TIMER_OCRA OCR5A #define AVR_TIMER_TIMSK TIMSK5 #define AVR_TIMER_TOIE TOIE5 #define AVR_TIMER_WGM0 WGM50 #define AVR_TIMER_WGM1 WGM51 #define AVR_TIMER_WGM2 WGM52 #define AVR_TIMER_WGM3 WGM53 #define AVR_TIMER_CS1 CS51 #endif static volatile uint32_t timer_micros_counter = 0; static volatile uint32_t timer_millis_counter = 0; void AVRTimer::init() { uint8_t oldSREG = SREG; cli(); // Timer cleanup before configuring AVR_TIMER_TCNT = 0; AVR_TIMER_TIFR = 0; // Set timer 8x prescaler fast PWM mode toggle compare at OCRA AVR_TIMER_TCCRA = _BV( AVR_TIMER_WGM0 ) | _BV( AVR_TIMER_WGM1 ); AVR_TIMER_TCCRB |= _BV( AVR_TIMER_WGM3 ) | _BV( AVR_TIMER_WGM2 ) | _BV( AVR_TIMER_CS1 ); AVR_TIMER_OCRA = 40000 - 1; // -1 to correct for wrap // Enable overflow interrupt AVR_TIMER_TIMSK |= _BV( AVR_TIMER_TOIE ); // set a2d prescale factor to 128 // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range. // XXX: this will not work properly for other clock speeds, and // this code should use F_CPU to determine the prescale factor. sbi(ADCSRA, ADPS2); sbi(ADCSRA, ADPS1); sbi(ADCSRA, ADPS0); // enable a2d conversions sbi(ADCSRA, ADEN); // the bootloader connects pins 0 and 1 to the USART; disconnect them // here so they can be used as normal digital i/o; they will be // reconnected in Serial.begin() UCSR0B = 0; SREG = oldSREG; } SIGNAL( AVR_TIMER_OVF_VECT) { // Hardcoded for AVR@16MHZ and 8x pre-scale 16-bit timer overflow at 40000 timer_micros_counter += 40000 / 2; // 20000us each overflow timer_millis_counter += 40000 / 2000; // 20ms each overlflow } uint32_t AVRTimer::micros() { uint8_t oldSREG = SREG; cli(); // Hardcoded for AVR@16MHZ and 8x pre-scale 16-bit timer //uint32_t time_micros = timer_micros_counter + (AVR_TIMER_TCNT / 2); //uint32_t time_micros = timer_micros_counter + (AVR_TIMER_TCNT >> 1); uint32_t time_micros = timer_micros_counter; uint16_t tcnt = AVR_TIMER_TCNT; // Check for imminent timer overflow interrupt and pre-increment counter if ( AVR_TIMER_TIFR & 1 && tcnt < 39999 ) { time_micros += 40000 / 2; } SREG = oldSREG; return time_micros + (tcnt >> 1); } uint32_t AVRTimer::millis() { uint8_t oldSREG = SREG; cli(); // Hardcoded for AVR@16MHZ and 8x pre-scale 16-bit timer //uint32_t time_millis = timer_millis_counter + (AVR_TIMER_TCNT / 2000) ; //uint32_t time_millis = timer_millis_counter + (AVR_TIMER_TCNT >> 11); // AVR_TIMER_CNT / 2048 is close enough (24us counter delay) uint32_t time_millis = timer_millis_counter; uint16_t tcnt = AVR_TIMER_TCNT; // Check for imminent timer overflow interrupt and pre-increment counter if ( AVR_TIMER_TIFR & 1 && tcnt < 39999 ) { time_millis += 40000 / 2000; } SREG = oldSREG; return time_millis + (tcnt >> 11); } /* Delay for the given number of microseconds. Assumes a 16 MHz clock. */ void AVRTimer::delay_microseconds(uint16_t us) { // for the 16 MHz clock on most Arduino boards // for a one-microsecond delay, simply return. the overhead // of the function call yields a delay of approximately 1 1/8 us. if (--us == 0) return; // the following loop takes a quarter of a microsecond (4 cycles) // per iteration, so execute it four times for each microsecond of // delay requested. us <<= 2; // account for the time taken in the preceeding commands. us -= 2; // busy wait __asm__ __volatile__ ( "1: sbiw %0,1" "\n\t" // 2 cycles "brne 1b" : "=w" (us) : "0" (us) // 2 cycles ); } #endif
gpl-3.0
qinmenghua/shadowsocks-android
src/main/jni/openssl/crypto/pkcs7/pkcs7err.c
592
9769
/* crypto/pkcs7/pkcs7err.c */ /* ==================================================================== * Copyright (c) 1999-2007 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* NOTE: this file was auto generated by the mkerr.pl script: any changes * made to it will be overwritten when the script next updates this file, * only reason strings will be preserved. */ #include <stdio.h> #include <openssl/err.h> #include <openssl/pkcs7.h> /* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR #define ERR_FUNC(func) ERR_PACK(ERR_LIB_PKCS7,func,0) #define ERR_REASON(reason) ERR_PACK(ERR_LIB_PKCS7,0,reason) static ERR_STRING_DATA PKCS7_str_functs[]= { {ERR_FUNC(PKCS7_F_B64_READ_PKCS7), "B64_READ_PKCS7"}, {ERR_FUNC(PKCS7_F_B64_WRITE_PKCS7), "B64_WRITE_PKCS7"}, {ERR_FUNC(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB), "DO_PKCS7_SIGNED_ATTRIB"}, {ERR_FUNC(PKCS7_F_I2D_PKCS7_BIO_STREAM), "i2d_PKCS7_bio_stream"}, {ERR_FUNC(PKCS7_F_PKCS7_ADD0_ATTRIB_SIGNING_TIME), "PKCS7_add0_attrib_signing_time"}, {ERR_FUNC(PKCS7_F_PKCS7_ADD_ATTRIB_SMIMECAP), "PKCS7_add_attrib_smimecap"}, {ERR_FUNC(PKCS7_F_PKCS7_ADD_CERTIFICATE), "PKCS7_add_certificate"}, {ERR_FUNC(PKCS7_F_PKCS7_ADD_CRL), "PKCS7_add_crl"}, {ERR_FUNC(PKCS7_F_PKCS7_ADD_RECIPIENT_INFO), "PKCS7_add_recipient_info"}, {ERR_FUNC(PKCS7_F_PKCS7_ADD_SIGNATURE), "PKCS7_add_signature"}, {ERR_FUNC(PKCS7_F_PKCS7_ADD_SIGNER), "PKCS7_add_signer"}, {ERR_FUNC(PKCS7_F_PKCS7_BIO_ADD_DIGEST), "PKCS7_BIO_ADD_DIGEST"}, {ERR_FUNC(PKCS7_F_PKCS7_COPY_EXISTING_DIGEST), "PKCS7_COPY_EXISTING_DIGEST"}, {ERR_FUNC(PKCS7_F_PKCS7_CTRL), "PKCS7_ctrl"}, {ERR_FUNC(PKCS7_F_PKCS7_DATADECODE), "PKCS7_dataDecode"}, {ERR_FUNC(PKCS7_F_PKCS7_DATAFINAL), "PKCS7_dataFinal"}, {ERR_FUNC(PKCS7_F_PKCS7_DATAINIT), "PKCS7_dataInit"}, {ERR_FUNC(PKCS7_F_PKCS7_DATASIGN), "PKCS7_DATASIGN"}, {ERR_FUNC(PKCS7_F_PKCS7_DATAVERIFY), "PKCS7_dataVerify"}, {ERR_FUNC(PKCS7_F_PKCS7_DECRYPT), "PKCS7_decrypt"}, {ERR_FUNC(PKCS7_F_PKCS7_DECRYPT_RINFO), "PKCS7_DECRYPT_RINFO"}, {ERR_FUNC(PKCS7_F_PKCS7_ENCODE_RINFO), "PKCS7_ENCODE_RINFO"}, {ERR_FUNC(PKCS7_F_PKCS7_ENCRYPT), "PKCS7_encrypt"}, {ERR_FUNC(PKCS7_F_PKCS7_FINAL), "PKCS7_final"}, {ERR_FUNC(PKCS7_F_PKCS7_FIND_DIGEST), "PKCS7_FIND_DIGEST"}, {ERR_FUNC(PKCS7_F_PKCS7_GET0_SIGNERS), "PKCS7_get0_signers"}, {ERR_FUNC(PKCS7_F_PKCS7_RECIP_INFO_SET), "PKCS7_RECIP_INFO_set"}, {ERR_FUNC(PKCS7_F_PKCS7_SET_CIPHER), "PKCS7_set_cipher"}, {ERR_FUNC(PKCS7_F_PKCS7_SET_CONTENT), "PKCS7_set_content"}, {ERR_FUNC(PKCS7_F_PKCS7_SET_DIGEST), "PKCS7_set_digest"}, {ERR_FUNC(PKCS7_F_PKCS7_SET_TYPE), "PKCS7_set_type"}, {ERR_FUNC(PKCS7_F_PKCS7_SIGN), "PKCS7_sign"}, {ERR_FUNC(PKCS7_F_PKCS7_SIGNATUREVERIFY), "PKCS7_signatureVerify"}, {ERR_FUNC(PKCS7_F_PKCS7_SIGNER_INFO_SET), "PKCS7_SIGNER_INFO_set"}, {ERR_FUNC(PKCS7_F_PKCS7_SIGNER_INFO_SIGN), "PKCS7_SIGNER_INFO_sign"}, {ERR_FUNC(PKCS7_F_PKCS7_SIGN_ADD_SIGNER), "PKCS7_sign_add_signer"}, {ERR_FUNC(PKCS7_F_PKCS7_SIMPLE_SMIMECAP), "PKCS7_simple_smimecap"}, {ERR_FUNC(PKCS7_F_PKCS7_VERIFY), "PKCS7_verify"}, {ERR_FUNC(PKCS7_F_SMIME_READ_PKCS7), "SMIME_read_PKCS7"}, {ERR_FUNC(PKCS7_F_SMIME_TEXT), "SMIME_text"}, {0,NULL} }; static ERR_STRING_DATA PKCS7_str_reasons[]= { {ERR_REASON(PKCS7_R_CERTIFICATE_VERIFY_ERROR),"certificate verify error"}, {ERR_REASON(PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER),"cipher has no object identifier"}, {ERR_REASON(PKCS7_R_CIPHER_NOT_INITIALIZED),"cipher not initialized"}, {ERR_REASON(PKCS7_R_CONTENT_AND_DATA_PRESENT),"content and data present"}, {ERR_REASON(PKCS7_R_CTRL_ERROR) ,"ctrl error"}, {ERR_REASON(PKCS7_R_DECODE_ERROR) ,"decode error"}, {ERR_REASON(PKCS7_R_DECRYPTED_KEY_IS_WRONG_LENGTH),"decrypted key is wrong length"}, {ERR_REASON(PKCS7_R_DECRYPT_ERROR) ,"decrypt error"}, {ERR_REASON(PKCS7_R_DIGEST_FAILURE) ,"digest failure"}, {ERR_REASON(PKCS7_R_ENCRYPTION_CTRL_FAILURE),"encryption ctrl failure"}, {ERR_REASON(PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE),"encryption not supported for this key type"}, {ERR_REASON(PKCS7_R_ERROR_ADDING_RECIPIENT),"error adding recipient"}, {ERR_REASON(PKCS7_R_ERROR_SETTING_CIPHER),"error setting cipher"}, {ERR_REASON(PKCS7_R_INVALID_MIME_TYPE) ,"invalid mime type"}, {ERR_REASON(PKCS7_R_INVALID_NULL_POINTER),"invalid null pointer"}, {ERR_REASON(PKCS7_R_MIME_NO_CONTENT_TYPE),"mime no content type"}, {ERR_REASON(PKCS7_R_MIME_PARSE_ERROR) ,"mime parse error"}, {ERR_REASON(PKCS7_R_MIME_SIG_PARSE_ERROR),"mime sig parse error"}, {ERR_REASON(PKCS7_R_MISSING_CERIPEND_INFO),"missing ceripend info"}, {ERR_REASON(PKCS7_R_NO_CONTENT) ,"no content"}, {ERR_REASON(PKCS7_R_NO_CONTENT_TYPE) ,"no content type"}, {ERR_REASON(PKCS7_R_NO_DEFAULT_DIGEST) ,"no default digest"}, {ERR_REASON(PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND),"no matching digest type found"}, {ERR_REASON(PKCS7_R_NO_MULTIPART_BODY_FAILURE),"no multipart body failure"}, {ERR_REASON(PKCS7_R_NO_MULTIPART_BOUNDARY),"no multipart boundary"}, {ERR_REASON(PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE),"no recipient matches certificate"}, {ERR_REASON(PKCS7_R_NO_RECIPIENT_MATCHES_KEY),"no recipient matches key"}, {ERR_REASON(PKCS7_R_NO_SIGNATURES_ON_DATA),"no signatures on data"}, {ERR_REASON(PKCS7_R_NO_SIGNERS) ,"no signers"}, {ERR_REASON(PKCS7_R_NO_SIG_CONTENT_TYPE) ,"no sig content type"}, {ERR_REASON(PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE),"operation not supported on this type"}, {ERR_REASON(PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR),"pkcs7 add signature error"}, {ERR_REASON(PKCS7_R_PKCS7_ADD_SIGNER_ERROR),"pkcs7 add signer error"}, {ERR_REASON(PKCS7_R_PKCS7_DATAFINAL) ,"pkcs7 datafinal"}, {ERR_REASON(PKCS7_R_PKCS7_DATAFINAL_ERROR),"pkcs7 datafinal error"}, {ERR_REASON(PKCS7_R_PKCS7_DATASIGN) ,"pkcs7 datasign"}, {ERR_REASON(PKCS7_R_PKCS7_PARSE_ERROR) ,"pkcs7 parse error"}, {ERR_REASON(PKCS7_R_PKCS7_SIG_PARSE_ERROR),"pkcs7 sig parse error"}, {ERR_REASON(PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE),"private key does not match certificate"}, {ERR_REASON(PKCS7_R_SIGNATURE_FAILURE) ,"signature failure"}, {ERR_REASON(PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND),"signer certificate not found"}, {ERR_REASON(PKCS7_R_SIGNING_CTRL_FAILURE),"signing ctrl failure"}, {ERR_REASON(PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE),"signing not supported for this key type"}, {ERR_REASON(PKCS7_R_SIG_INVALID_MIME_TYPE),"sig invalid mime type"}, {ERR_REASON(PKCS7_R_SMIME_TEXT_ERROR) ,"smime text error"}, {ERR_REASON(PKCS7_R_UNABLE_TO_FIND_CERTIFICATE),"unable to find certificate"}, {ERR_REASON(PKCS7_R_UNABLE_TO_FIND_MEM_BIO),"unable to find mem bio"}, {ERR_REASON(PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST),"unable to find message digest"}, {ERR_REASON(PKCS7_R_UNKNOWN_DIGEST_TYPE) ,"unknown digest type"}, {ERR_REASON(PKCS7_R_UNKNOWN_OPERATION) ,"unknown operation"}, {ERR_REASON(PKCS7_R_UNSUPPORTED_CIPHER_TYPE),"unsupported cipher type"}, {ERR_REASON(PKCS7_R_UNSUPPORTED_CONTENT_TYPE),"unsupported content type"}, {ERR_REASON(PKCS7_R_WRONG_CONTENT_TYPE) ,"wrong content type"}, {ERR_REASON(PKCS7_R_WRONG_PKCS7_TYPE) ,"wrong pkcs7 type"}, {0,NULL} }; #endif void ERR_load_PKCS7_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_func_error_string(PKCS7_str_functs[0].error) == NULL) { ERR_load_strings(0,PKCS7_str_functs); ERR_load_strings(0,PKCS7_str_reasons); } #endif }
gpl-3.0
dreamsxin/mangler
android/jni/speex/libspeex/preprocess.c
593
41693
/* Copyright (C) 2003 Epic Games (written by Jean-Marc Valin) Copyright (C) 2004-2006 Epic Games File: preprocess.c Preprocessor with denoising based on the algorithm by Ephraim and Malah Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Recommended papers: Y. Ephraim and D. Malah, "Speech enhancement using minimum mean-square error short-time spectral amplitude estimator". IEEE Transactions on Acoustics, Speech and Signal Processing, vol. ASSP-32, no. 6, pp. 1109-1121, 1984. Y. Ephraim and D. Malah, "Speech enhancement using minimum mean-square error log-spectral amplitude estimator". IEEE Transactions on Acoustics, Speech and Signal Processing, vol. ASSP-33, no. 2, pp. 443-445, 1985. I. Cohen and B. Berdugo, "Speech enhancement for non-stationary noise environments". Signal Processing, vol. 81, no. 2, pp. 2403-2418, 2001. Stefan Gustafsson, Rainer Martin, Peter Jax, and Peter Vary. "A psychoacoustic approach to combined acoustic echo cancellation and noise reduction". IEEE Transactions on Speech and Audio Processing, 2002. J.-M. Valin, J. Rouat, and F. Michaud, "Microphone array post-filter for separation of simultaneous non-stationary sources". In Proceedings IEEE International Conference on Acoustics, Speech, and Signal Processing, 2004. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include "speex/speex_preprocess.h" #include "speex/speex_echo.h" #include "arch.h" #include "fftwrap.h" #include "filterbank.h" #include "math_approx.h" #include "os_support.h" #ifndef M_PI #define M_PI 3.14159263 #endif #define LOUDNESS_EXP 5.f #define AMP_SCALE .001f #define AMP_SCALE_1 1000.f #define NB_BANDS 24 #define SPEECH_PROB_START_DEFAULT QCONST16(0.35f,15) #define SPEECH_PROB_CONTINUE_DEFAULT QCONST16(0.20f,15) #define NOISE_SUPPRESS_DEFAULT -15 #define ECHO_SUPPRESS_DEFAULT -40 #define ECHO_SUPPRESS_ACTIVE_DEFAULT -15 #ifndef NULL #define NULL 0 #endif #define SQR(x) ((x)*(x)) #define SQR16(x) (MULT16_16((x),(x))) #define SQR16_Q15(x) (MULT16_16_Q15((x),(x))) #ifdef FIXED_POINT static inline spx_word16_t DIV32_16_Q8(spx_word32_t a, spx_word32_t b) { if (SHR32(a,7) >= b) { return 32767; } else { if (b>=QCONST32(1,23)) { a = SHR32(a,8); b = SHR32(b,8); } if (b>=QCONST32(1,19)) { a = SHR32(a,4); b = SHR32(b,4); } if (b>=QCONST32(1,15)) { a = SHR32(a,4); b = SHR32(b,4); } a = SHL32(a,8); return PDIV32_16(a,b); } } static inline spx_word16_t DIV32_16_Q15(spx_word32_t a, spx_word32_t b) { if (SHR32(a,15) >= b) { return 32767; } else { if (b>=QCONST32(1,23)) { a = SHR32(a,8); b = SHR32(b,8); } if (b>=QCONST32(1,19)) { a = SHR32(a,4); b = SHR32(b,4); } if (b>=QCONST32(1,15)) { a = SHR32(a,4); b = SHR32(b,4); } a = SHL32(a,15)-a; return DIV32_16(a,b); } } #define SNR_SCALING 256.f #define SNR_SCALING_1 0.0039062f #define SNR_SHIFT 8 #define FRAC_SCALING 32767.f #define FRAC_SCALING_1 3.0518e-05 #define FRAC_SHIFT 1 #define EXPIN_SCALING 2048.f #define EXPIN_SCALING_1 0.00048828f #define EXPIN_SHIFT 11 #define EXPOUT_SCALING_1 1.5259e-05 #define NOISE_SHIFT 7 #else #define DIV32_16_Q8(a,b) ((a)/(b)) #define DIV32_16_Q15(a,b) ((a)/(b)) #define SNR_SCALING 1.f #define SNR_SCALING_1 1.f #define SNR_SHIFT 0 #define FRAC_SCALING 1.f #define FRAC_SCALING_1 1.f #define FRAC_SHIFT 0 #define NOISE_SHIFT 0 #define EXPIN_SCALING 1.f #define EXPIN_SCALING_1 1.f #define EXPOUT_SCALING_1 1.f #endif /** Speex pre-processor state. */ struct SpeexPreprocessState_ { /* Basic info */ int frame_size; /**< Number of samples processed each time */ int ps_size; /**< Number of points in the power spectrum */ int sampling_rate; /**< Sampling rate of the input/output */ int nbands; FilterBank *bank; /* Parameters */ int denoise_enabled; int vad_enabled; int dereverb_enabled; spx_word16_t reverb_decay; spx_word16_t reverb_level; spx_word16_t speech_prob_start; spx_word16_t speech_prob_continue; int noise_suppress; int echo_suppress; int echo_suppress_active; SpeexEchoState *echo_state; spx_word16_t speech_prob; /**< Probability last frame was speech */ /* DSP-related arrays */ spx_word16_t *frame; /**< Processing frame (2*ps_size) */ spx_word16_t *ft; /**< Processing frame in freq domain (2*ps_size) */ spx_word32_t *ps; /**< Current power spectrum */ spx_word16_t *gain2; /**< Adjusted gains */ spx_word16_t *gain_floor; /**< Minimum gain allowed */ spx_word16_t *window; /**< Analysis/Synthesis window */ spx_word32_t *noise; /**< Noise estimate */ spx_word32_t *reverb_estimate; /**< Estimate of reverb energy */ spx_word32_t *old_ps; /**< Power spectrum for last frame */ spx_word16_t *gain; /**< Ephraim Malah gain */ spx_word16_t *prior; /**< A-priori SNR */ spx_word16_t *post; /**< A-posteriori SNR */ spx_word32_t *S; /**< Smoothed power spectrum */ spx_word32_t *Smin; /**< See Cohen paper */ spx_word32_t *Stmp; /**< See Cohen paper */ int *update_prob; /**< Probability of speech presence for noise update */ spx_word16_t *zeta; /**< Smoothed a priori SNR */ spx_word32_t *echo_noise; spx_word32_t *residual_echo; /* Misc */ spx_word16_t *inbuf; /**< Input buffer (overlapped analysis) */ spx_word16_t *outbuf; /**< Output buffer (for overlap and add) */ /* AGC stuff, only for floating point for now */ #ifndef FIXED_POINT int agc_enabled; float agc_level; float loudness_accum; float *loudness_weight; /**< Perceptual loudness curve */ float loudness; /**< Loudness estimate */ float agc_gain; /**< Current AGC gain */ float max_gain; /**< Maximum gain allowed */ float max_increase_step; /**< Maximum increase in gain from one frame to another */ float max_decrease_step; /**< Maximum decrease in gain from one frame to another */ float prev_loudness; /**< Loudness of previous frame */ float init_max; /**< Current gain limit during initialisation */ #endif int nb_adapt; /**< Number of frames used for adaptation so far */ int was_speech; int min_count; /**< Number of frames processed so far */ void *fft_lookup; /**< Lookup table for the FFT */ #ifdef FIXED_POINT int frame_shift; #endif }; static void conj_window(spx_word16_t *w, int len) { int i; for (i=0;i<len;i++) { spx_word16_t tmp; #ifdef FIXED_POINT spx_word16_t x = DIV32_16(MULT16_16(32767,i),len); #else spx_word16_t x = DIV32_16(MULT16_16(QCONST16(4.f,13),i),len); #endif int inv=0; if (x<QCONST16(1.f,13)) { } else if (x<QCONST16(2.f,13)) { x=QCONST16(2.f,13)-x; inv=1; } else if (x<QCONST16(3.f,13)) { x=x-QCONST16(2.f,13); inv=1; } else { x=QCONST16(2.f,13)-x+QCONST16(2.f,13); /* 4 - x */ } x = MULT16_16_Q14(QCONST16(1.271903f,14), x); tmp = SQR16_Q15(QCONST16(.5f,15)-MULT16_16_P15(QCONST16(.5f,15),spx_cos_norm(SHL32(EXTEND32(x),2)))); if (inv) tmp=SUB16(Q15_ONE,tmp); w[i]=spx_sqrt(SHL32(EXTEND32(tmp),15)); } } #ifdef FIXED_POINT /* This function approximates the gain function y = gamma(1.25)^2 * M(-.25;1;-x) / sqrt(x) which multiplied by xi/(1+xi) is the optimal gain in the loudness domain ( sqrt[amplitude] ) Input in Q11 format, output in Q15 */ static inline spx_word32_t hypergeom_gain(spx_word32_t xx) { int ind; spx_word16_t frac; /* Q13 table */ static const spx_word16_t table[21] = { 6730, 8357, 9868, 11267, 12563, 13770, 14898, 15959, 16961, 17911, 18816, 19682, 20512, 21311, 22082, 22827, 23549, 24250, 24931, 25594, 26241}; ind = SHR32(xx,10); if (ind<0) return Q15_ONE; if (ind>19) return ADD32(EXTEND32(Q15_ONE),EXTEND32(DIV32_16(QCONST32(.1296,23), SHR32(xx,EXPIN_SHIFT-SNR_SHIFT)))); frac = SHL32(xx-SHL32(ind,10),5); return SHL32(DIV32_16(PSHR32(MULT16_16(Q15_ONE-frac,table[ind]) + MULT16_16(frac,table[ind+1]),7),(spx_sqrt(SHL32(xx,15)+6711))),7); } static inline spx_word16_t qcurve(spx_word16_t x) { x = MAX16(x, 1); return DIV32_16(SHL32(EXTEND32(32767),9),ADD16(512,MULT16_16_Q15(QCONST16(.60f,15),DIV32_16(32767,x)))); } /* Compute the gain floor based on different floors for the background noise and residual echo */ static void compute_gain_floor(int noise_suppress, int effective_echo_suppress, spx_word32_t *noise, spx_word32_t *echo, spx_word16_t *gain_floor, int len) { int i; if (noise_suppress > effective_echo_suppress) { spx_word16_t noise_gain, gain_ratio; noise_gain = EXTRACT16(MIN32(Q15_ONE,SHR32(spx_exp(MULT16_16(QCONST16(0.11513,11),noise_suppress)),1))); gain_ratio = EXTRACT16(MIN32(Q15_ONE,SHR32(spx_exp(MULT16_16(QCONST16(.2302585f,11),effective_echo_suppress-noise_suppress)),1))); /* gain_floor = sqrt [ (noise*noise_floor + echo*echo_floor) / (noise+echo) ] */ for (i=0;i<len;i++) gain_floor[i] = MULT16_16_Q15(noise_gain, spx_sqrt(SHL32(EXTEND32(DIV32_16_Q15(PSHR32(noise[i],NOISE_SHIFT) + MULT16_32_Q15(gain_ratio,echo[i]), (1+PSHR32(noise[i],NOISE_SHIFT) + echo[i]) )),15))); } else { spx_word16_t echo_gain, gain_ratio; echo_gain = EXTRACT16(MIN32(Q15_ONE,SHR32(spx_exp(MULT16_16(QCONST16(0.11513,11),effective_echo_suppress)),1))); gain_ratio = EXTRACT16(MIN32(Q15_ONE,SHR32(spx_exp(MULT16_16(QCONST16(.2302585f,11),noise_suppress-effective_echo_suppress)),1))); /* gain_floor = sqrt [ (noise*noise_floor + echo*echo_floor) / (noise+echo) ] */ for (i=0;i<len;i++) gain_floor[i] = MULT16_16_Q15(echo_gain, spx_sqrt(SHL32(EXTEND32(DIV32_16_Q15(MULT16_32_Q15(gain_ratio,PSHR32(noise[i],NOISE_SHIFT)) + echo[i], (1+PSHR32(noise[i],NOISE_SHIFT) + echo[i]) )),15))); } } #else /* This function approximates the gain function y = gamma(1.25)^2 * M(-.25;1;-x) / sqrt(x) which multiplied by xi/(1+xi) is the optimal gain in the loudness domain ( sqrt[amplitude] ) */ static inline spx_word32_t hypergeom_gain(spx_word32_t xx) { int ind; float integer, frac; float x; static const float table[21] = { 0.82157f, 1.02017f, 1.20461f, 1.37534f, 1.53363f, 1.68092f, 1.81865f, 1.94811f, 2.07038f, 2.18638f, 2.29688f, 2.40255f, 2.50391f, 2.60144f, 2.69551f, 2.78647f, 2.87458f, 2.96015f, 3.04333f, 3.12431f, 3.20326f}; x = EXPIN_SCALING_1*xx; integer = floor(2*x); ind = (int)integer; if (ind<0) return FRAC_SCALING; if (ind>19) return FRAC_SCALING*(1+.1296/x); frac = 2*x-integer; return FRAC_SCALING*((1-frac)*table[ind] + frac*table[ind+1])/sqrt(x+.0001f); } static inline spx_word16_t qcurve(spx_word16_t x) { return 1.f/(1.f+.15f/(SNR_SCALING_1*x)); } static void compute_gain_floor(int noise_suppress, int effective_echo_suppress, spx_word32_t *noise, spx_word32_t *echo, spx_word16_t *gain_floor, int len) { int i; float echo_floor; float noise_floor; noise_floor = exp(.2302585f*noise_suppress); echo_floor = exp(.2302585f*effective_echo_suppress); /* Compute the gain floor based on different floors for the background noise and residual echo */ for (i=0;i<len;i++) gain_floor[i] = FRAC_SCALING*sqrt(noise_floor*PSHR32(noise[i],NOISE_SHIFT) + echo_floor*echo[i])/sqrt(1+PSHR32(noise[i],NOISE_SHIFT) + echo[i]); } #endif EXPORT SpeexPreprocessState *speex_preprocess_state_init(int frame_size, int sampling_rate) { int i; int N, N3, N4, M; SpeexPreprocessState *st = (SpeexPreprocessState *)speex_alloc(sizeof(SpeexPreprocessState)); st->frame_size = frame_size; /* Round ps_size down to the nearest power of two */ #if 0 i=1; st->ps_size = st->frame_size; while(1) { if (st->ps_size & ~i) { st->ps_size &= ~i; i<<=1; } else { break; } } if (st->ps_size < 3*st->frame_size/4) st->ps_size = st->ps_size * 3 / 2; #else st->ps_size = st->frame_size; #endif N = st->ps_size; N3 = 2*N - st->frame_size; N4 = st->frame_size - N3; st->sampling_rate = sampling_rate; st->denoise_enabled = 1; st->vad_enabled = 0; st->dereverb_enabled = 0; st->reverb_decay = 0; st->reverb_level = 0; st->noise_suppress = NOISE_SUPPRESS_DEFAULT; st->echo_suppress = ECHO_SUPPRESS_DEFAULT; st->echo_suppress_active = ECHO_SUPPRESS_ACTIVE_DEFAULT; st->speech_prob_start = SPEECH_PROB_START_DEFAULT; st->speech_prob_continue = SPEECH_PROB_CONTINUE_DEFAULT; st->echo_state = NULL; st->nbands = NB_BANDS; M = st->nbands; st->bank = filterbank_new(M, sampling_rate, N, 1); st->frame = (spx_word16_t*)speex_alloc(2*N*sizeof(spx_word16_t)); st->window = (spx_word16_t*)speex_alloc(2*N*sizeof(spx_word16_t)); st->ft = (spx_word16_t*)speex_alloc(2*N*sizeof(spx_word16_t)); st->ps = (spx_word32_t*)speex_alloc((N+M)*sizeof(spx_word32_t)); st->noise = (spx_word32_t*)speex_alloc((N+M)*sizeof(spx_word32_t)); st->echo_noise = (spx_word32_t*)speex_alloc((N+M)*sizeof(spx_word32_t)); st->residual_echo = (spx_word32_t*)speex_alloc((N+M)*sizeof(spx_word32_t)); st->reverb_estimate = (spx_word32_t*)speex_alloc((N+M)*sizeof(spx_word32_t)); st->old_ps = (spx_word32_t*)speex_alloc((N+M)*sizeof(spx_word32_t)); st->prior = (spx_word16_t*)speex_alloc((N+M)*sizeof(spx_word16_t)); st->post = (spx_word16_t*)speex_alloc((N+M)*sizeof(spx_word16_t)); st->gain = (spx_word16_t*)speex_alloc((N+M)*sizeof(spx_word16_t)); st->gain2 = (spx_word16_t*)speex_alloc((N+M)*sizeof(spx_word16_t)); st->gain_floor = (spx_word16_t*)speex_alloc((N+M)*sizeof(spx_word16_t)); st->zeta = (spx_word16_t*)speex_alloc((N+M)*sizeof(spx_word16_t)); st->S = (spx_word32_t*)speex_alloc(N*sizeof(spx_word32_t)); st->Smin = (spx_word32_t*)speex_alloc(N*sizeof(spx_word32_t)); st->Stmp = (spx_word32_t*)speex_alloc(N*sizeof(spx_word32_t)); st->update_prob = (int*)speex_alloc(N*sizeof(int)); st->inbuf = (spx_word16_t*)speex_alloc(N3*sizeof(spx_word16_t)); st->outbuf = (spx_word16_t*)speex_alloc(N3*sizeof(spx_word16_t)); conj_window(st->window, 2*N3); for (i=2*N3;i<2*st->ps_size;i++) st->window[i]=Q15_ONE; if (N4>0) { for (i=N3-1;i>=0;i--) { st->window[i+N3+N4]=st->window[i+N3]; st->window[i+N3]=1; } } for (i=0;i<N+M;i++) { st->noise[i]=QCONST32(1.f,NOISE_SHIFT); st->reverb_estimate[i]=0; st->old_ps[i]=1; st->gain[i]=Q15_ONE; st->post[i]=SHL16(1, SNR_SHIFT); st->prior[i]=SHL16(1, SNR_SHIFT); } for (i=0;i<N;i++) st->update_prob[i] = 1; for (i=0;i<N3;i++) { st->inbuf[i]=0; st->outbuf[i]=0; } #ifndef FIXED_POINT st->agc_enabled = 0; st->agc_level = 8000; st->loudness_weight = (float*)speex_alloc(N*sizeof(float)); for (i=0;i<N;i++) { float ff=((float)i)*.5*sampling_rate/((float)N); /*st->loudness_weight[i] = .5f*(1.f/(1.f+ff/8000.f))+1.f*exp(-.5f*(ff-3800.f)*(ff-3800.f)/9e5f);*/ st->loudness_weight[i] = .35f-.35f*ff/16000.f+.73f*exp(-.5f*(ff-3800)*(ff-3800)/9e5f); if (st->loudness_weight[i]<.01f) st->loudness_weight[i]=.01f; st->loudness_weight[i] *= st->loudness_weight[i]; } /*st->loudness = pow(AMP_SCALE*st->agc_level,LOUDNESS_EXP);*/ st->loudness = 1e-15; st->agc_gain = 1; st->max_gain = 30; st->max_increase_step = exp(0.11513f * 12.*st->frame_size / st->sampling_rate); st->max_decrease_step = exp(-0.11513f * 40.*st->frame_size / st->sampling_rate); st->prev_loudness = 1; st->init_max = 1; #endif st->was_speech = 0; st->fft_lookup = spx_fft_init(2*N); st->nb_adapt=0; st->min_count=0; return st; } EXPORT void speex_preprocess_state_destroy(SpeexPreprocessState *st) { speex_free(st->frame); speex_free(st->ft); speex_free(st->ps); speex_free(st->gain2); speex_free(st->gain_floor); speex_free(st->window); speex_free(st->noise); speex_free(st->reverb_estimate); speex_free(st->old_ps); speex_free(st->gain); speex_free(st->prior); speex_free(st->post); #ifndef FIXED_POINT speex_free(st->loudness_weight); #endif speex_free(st->echo_noise); speex_free(st->residual_echo); speex_free(st->S); speex_free(st->Smin); speex_free(st->Stmp); speex_free(st->update_prob); speex_free(st->zeta); speex_free(st->inbuf); speex_free(st->outbuf); spx_fft_destroy(st->fft_lookup); filterbank_destroy(st->bank); speex_free(st); } /* FIXME: The AGC doesn't work yet with fixed-point*/ #ifndef FIXED_POINT static void speex_compute_agc(SpeexPreprocessState *st, spx_word16_t Pframe, spx_word16_t *ft) { int i; int N = st->ps_size; float target_gain; float loudness=1.f; float rate; for (i=2;i<N;i++) { loudness += 2.f*N*st->ps[i]* st->loudness_weight[i]; } loudness=sqrt(loudness); /*if (loudness < 2*pow(st->loudness, 1.0/LOUDNESS_EXP) && loudness*2 > pow(st->loudness, 1.0/LOUDNESS_EXP))*/ if (Pframe>.3f) { /*rate=2.0f*Pframe*Pframe/(1+st->nb_loudness_adapt);*/ rate = .03*Pframe*Pframe; st->loudness = (1-rate)*st->loudness + (rate)*pow(AMP_SCALE*loudness, LOUDNESS_EXP); st->loudness_accum = (1-rate)*st->loudness_accum + rate; if (st->init_max < st->max_gain && st->nb_adapt > 20) st->init_max *= 1.f + .1f*Pframe*Pframe; } /*printf ("%f %f %f %f\n", Pframe, loudness, pow(st->loudness, 1.0f/LOUDNESS_EXP), st->loudness2);*/ target_gain = AMP_SCALE*st->agc_level*pow(st->loudness/(1e-4+st->loudness_accum), -1.0f/LOUDNESS_EXP); if ((Pframe>.5 && st->nb_adapt > 20) || target_gain < st->agc_gain) { if (target_gain > st->max_increase_step*st->agc_gain) target_gain = st->max_increase_step*st->agc_gain; if (target_gain < st->max_decrease_step*st->agc_gain && loudness < 10*st->prev_loudness) target_gain = st->max_decrease_step*st->agc_gain; if (target_gain > st->max_gain) target_gain = st->max_gain; if (target_gain > st->init_max) target_gain = st->init_max; st->agc_gain = target_gain; } /*fprintf (stderr, "%f %f %f\n", loudness, (float)AMP_SCALE_1*pow(st->loudness, 1.0f/LOUDNESS_EXP), st->agc_gain);*/ for (i=0;i<2*N;i++) ft[i] *= st->agc_gain; st->prev_loudness = loudness; } #endif static void preprocess_analysis(SpeexPreprocessState *st, spx_int16_t *x) { int i; int N = st->ps_size; int N3 = 2*N - st->frame_size; int N4 = st->frame_size - N3; spx_word32_t *ps=st->ps; /* 'Build' input frame */ for (i=0;i<N3;i++) st->frame[i]=st->inbuf[i]; for (i=0;i<st->frame_size;i++) st->frame[N3+i]=x[i]; /* Update inbuf */ for (i=0;i<N3;i++) st->inbuf[i]=x[N4+i]; /* Windowing */ for (i=0;i<2*N;i++) st->frame[i] = MULT16_16_Q15(st->frame[i], st->window[i]); #ifdef FIXED_POINT { spx_word16_t max_val=0; for (i=0;i<2*N;i++) max_val = MAX16(max_val, ABS16(st->frame[i])); st->frame_shift = 14-spx_ilog2(EXTEND32(max_val)); for (i=0;i<2*N;i++) st->frame[i] = SHL16(st->frame[i], st->frame_shift); } #endif /* Perform FFT */ spx_fft(st->fft_lookup, st->frame, st->ft); /* Power spectrum */ ps[0]=MULT16_16(st->ft[0],st->ft[0]); for (i=1;i<N;i++) ps[i]=MULT16_16(st->ft[2*i-1],st->ft[2*i-1]) + MULT16_16(st->ft[2*i],st->ft[2*i]); for (i=0;i<N;i++) st->ps[i] = PSHR32(st->ps[i], 2*st->frame_shift); filterbank_compute_bank32(st->bank, ps, ps+N); } static void update_noise_prob(SpeexPreprocessState *st) { int i; int min_range; int N = st->ps_size; for (i=1;i<N-1;i++) st->S[i] = MULT16_32_Q15(QCONST16(.8f,15),st->S[i]) + MULT16_32_Q15(QCONST16(.05f,15),st->ps[i-1]) + MULT16_32_Q15(QCONST16(.1f,15),st->ps[i]) + MULT16_32_Q15(QCONST16(.05f,15),st->ps[i+1]); st->S[0] = MULT16_32_Q15(QCONST16(.8f,15),st->S[0]) + MULT16_32_Q15(QCONST16(.2f,15),st->ps[0]); st->S[N-1] = MULT16_32_Q15(QCONST16(.8f,15),st->S[N-1]) + MULT16_32_Q15(QCONST16(.2f,15),st->ps[N-1]); if (st->nb_adapt==1) { for (i=0;i<N;i++) st->Smin[i] = st->Stmp[i] = 0; } if (st->nb_adapt < 100) min_range = 15; else if (st->nb_adapt < 1000) min_range = 50; else if (st->nb_adapt < 10000) min_range = 150; else min_range = 300; if (st->min_count > min_range) { st->min_count = 0; for (i=0;i<N;i++) { st->Smin[i] = MIN32(st->Stmp[i], st->S[i]); st->Stmp[i] = st->S[i]; } } else { for (i=0;i<N;i++) { st->Smin[i] = MIN32(st->Smin[i], st->S[i]); st->Stmp[i] = MIN32(st->Stmp[i], st->S[i]); } } for (i=0;i<N;i++) { if (MULT16_32_Q15(QCONST16(.4f,15),st->S[i]) > st->Smin[i]) st->update_prob[i] = 1; else st->update_prob[i] = 0; /*fprintf (stderr, "%f ", st->S[i]/st->Smin[i]);*/ /*fprintf (stderr, "%f ", st->update_prob[i]);*/ } } #define NOISE_OVERCOMPENS 1. void speex_echo_get_residual(SpeexEchoState *st, spx_word32_t *Yout, int len); EXPORT int speex_preprocess(SpeexPreprocessState *st, spx_int16_t *x, spx_int32_t *echo) { return speex_preprocess_run(st, x); } EXPORT int speex_preprocess_run(SpeexPreprocessState *st, spx_int16_t *x) { int i; int M; int N = st->ps_size; int N3 = 2*N - st->frame_size; int N4 = st->frame_size - N3; spx_word32_t *ps=st->ps; spx_word32_t Zframe; spx_word16_t Pframe; spx_word16_t beta, beta_1; spx_word16_t effective_echo_suppress; st->nb_adapt++; if (st->nb_adapt>20000) st->nb_adapt = 20000; st->min_count++; beta = MAX16(QCONST16(.03,15),DIV32_16(Q15_ONE,st->nb_adapt)); beta_1 = Q15_ONE-beta; M = st->nbands; /* Deal with residual echo if provided */ if (st->echo_state) { speex_echo_get_residual(st->echo_state, st->residual_echo, N); #ifndef FIXED_POINT /* If there are NaNs or ridiculous values, it'll show up in the DC and we just reset everything to zero */ if (!(st->residual_echo[0] >=0 && st->residual_echo[0]<N*1e9f)) { for (i=0;i<N;i++) st->residual_echo[i] = 0; } #endif for (i=0;i<N;i++) st->echo_noise[i] = MAX32(MULT16_32_Q15(QCONST16(.6f,15),st->echo_noise[i]), st->residual_echo[i]); filterbank_compute_bank32(st->bank, st->echo_noise, st->echo_noise+N); } else { for (i=0;i<N+M;i++) st->echo_noise[i] = 0; } preprocess_analysis(st, x); update_noise_prob(st); /* Noise estimation always updated for the 10 first frames */ /*if (st->nb_adapt<10) { for (i=1;i<N-1;i++) st->update_prob[i] = 0; } */ /* Update the noise estimate for the frequencies where it can be */ for (i=0;i<N;i++) { if (!st->update_prob[i] || st->ps[i] < PSHR32(st->noise[i], NOISE_SHIFT)) st->noise[i] = MAX32(EXTEND32(0),MULT16_32_Q15(beta_1,st->noise[i]) + MULT16_32_Q15(beta,SHL32(st->ps[i],NOISE_SHIFT))); } filterbank_compute_bank32(st->bank, st->noise, st->noise+N); /* Special case for first frame */ if (st->nb_adapt==1) for (i=0;i<N+M;i++) st->old_ps[i] = ps[i]; /* Compute a posteriori SNR */ for (i=0;i<N+M;i++) { spx_word16_t gamma; /* Total noise estimate including residual echo and reverberation */ spx_word32_t tot_noise = ADD32(ADD32(ADD32(EXTEND32(1), PSHR32(st->noise[i],NOISE_SHIFT)) , st->echo_noise[i]) , st->reverb_estimate[i]); /* A posteriori SNR = ps/noise - 1*/ st->post[i] = SUB16(DIV32_16_Q8(ps[i],tot_noise), QCONST16(1.f,SNR_SHIFT)); st->post[i]=MIN16(st->post[i], QCONST16(100.f,SNR_SHIFT)); /* Computing update gamma = .1 + .9*(old/(old+noise))^2 */ gamma = QCONST16(.1f,15)+MULT16_16_Q15(QCONST16(.89f,15),SQR16_Q15(DIV32_16_Q15(st->old_ps[i],ADD32(st->old_ps[i],tot_noise)))); /* A priori SNR update = gamma*max(0,post) + (1-gamma)*old/noise */ st->prior[i] = EXTRACT16(PSHR32(ADD32(MULT16_16(gamma,MAX16(0,st->post[i])), MULT16_16(Q15_ONE-gamma,DIV32_16_Q8(st->old_ps[i],tot_noise))), 15)); st->prior[i]=MIN16(st->prior[i], QCONST16(100.f,SNR_SHIFT)); } /*print_vec(st->post, N+M, "");*/ /* Recursive average of the a priori SNR. A bit smoothed for the psd components */ st->zeta[0] = PSHR32(ADD32(MULT16_16(QCONST16(.7f,15),st->zeta[0]), MULT16_16(QCONST16(.3f,15),st->prior[0])),15); for (i=1;i<N-1;i++) st->zeta[i] = PSHR32(ADD32(ADD32(ADD32(MULT16_16(QCONST16(.7f,15),st->zeta[i]), MULT16_16(QCONST16(.15f,15),st->prior[i])), MULT16_16(QCONST16(.075f,15),st->prior[i-1])), MULT16_16(QCONST16(.075f,15),st->prior[i+1])),15); for (i=N-1;i<N+M;i++) st->zeta[i] = PSHR32(ADD32(MULT16_16(QCONST16(.7f,15),st->zeta[i]), MULT16_16(QCONST16(.3f,15),st->prior[i])),15); /* Speech probability of presence for the entire frame is based on the average filterbank a priori SNR */ Zframe = 0; for (i=N;i<N+M;i++) Zframe = ADD32(Zframe, EXTEND32(st->zeta[i])); Pframe = QCONST16(.1f,15)+MULT16_16_Q15(QCONST16(.899f,15),qcurve(DIV32_16(Zframe,st->nbands))); effective_echo_suppress = EXTRACT16(PSHR32(ADD32(MULT16_16(SUB16(Q15_ONE,Pframe), st->echo_suppress), MULT16_16(Pframe, st->echo_suppress_active)),15)); compute_gain_floor(st->noise_suppress, effective_echo_suppress, st->noise+N, st->echo_noise+N, st->gain_floor+N, M); /* Compute Ephraim & Malah gain speech probability of presence for each critical band (Bark scale) Technically this is actually wrong because the EM gaim assumes a slightly different probability distribution */ for (i=N;i<N+M;i++) { /* See EM and Cohen papers*/ spx_word32_t theta; /* Gain from hypergeometric function */ spx_word32_t MM; /* Weiner filter gain */ spx_word16_t prior_ratio; /* a priority probability of speech presence based on Bark sub-band alone */ spx_word16_t P1; /* Speech absence a priori probability (considering sub-band and frame) */ spx_word16_t q; #ifdef FIXED_POINT spx_word16_t tmp; #endif prior_ratio = PDIV32_16(SHL32(EXTEND32(st->prior[i]), 15), ADD16(st->prior[i], SHL32(1,SNR_SHIFT))); theta = MULT16_32_P15(prior_ratio, QCONST32(1.f,EXPIN_SHIFT)+SHL32(EXTEND32(st->post[i]),EXPIN_SHIFT-SNR_SHIFT)); MM = hypergeom_gain(theta); /* Gain with bound */ st->gain[i] = EXTRACT16(MIN32(Q15_ONE, MULT16_32_Q15(prior_ratio, MM))); /* Save old Bark power spectrum */ st->old_ps[i] = MULT16_32_P15(QCONST16(.2f,15),st->old_ps[i]) + MULT16_32_P15(MULT16_16_P15(QCONST16(.8f,15),SQR16_Q15(st->gain[i])),ps[i]); P1 = QCONST16(.199f,15)+MULT16_16_Q15(QCONST16(.8f,15),qcurve (st->zeta[i])); q = Q15_ONE-MULT16_16_Q15(Pframe,P1); #ifdef FIXED_POINT theta = MIN32(theta, EXTEND32(32767)); /*Q8*/tmp = MULT16_16_Q15((SHL32(1,SNR_SHIFT)+st->prior[i]),EXTRACT16(MIN32(Q15ONE,SHR32(spx_exp(-EXTRACT16(theta)),1)))); tmp = MIN16(QCONST16(3.,SNR_SHIFT), tmp); /* Prevent overflows in the next line*/ /*Q8*/tmp = EXTRACT16(PSHR32(MULT16_16(PDIV32_16(SHL32(EXTEND32(q),8),(Q15_ONE-q)),tmp),8)); st->gain2[i]=DIV32_16(SHL32(EXTEND32(32767),SNR_SHIFT), ADD16(256,tmp)); #else st->gain2[i]=1/(1.f + (q/(1.f-q))*(1+st->prior[i])*exp(-theta)); #endif } /* Convert the EM gains and speech prob to linear frequency */ filterbank_compute_psd16(st->bank,st->gain2+N, st->gain2); filterbank_compute_psd16(st->bank,st->gain+N, st->gain); /* Use 1 for linear gain resolution (best) or 0 for Bark gain resolution (faster) */ if (1) { filterbank_compute_psd16(st->bank,st->gain_floor+N, st->gain_floor); /* Compute gain according to the Ephraim-Malah algorithm -- linear frequency */ for (i=0;i<N;i++) { spx_word32_t MM; spx_word32_t theta; spx_word16_t prior_ratio; spx_word16_t tmp; spx_word16_t p; spx_word16_t g; /* Wiener filter gain */ prior_ratio = PDIV32_16(SHL32(EXTEND32(st->prior[i]), 15), ADD16(st->prior[i], SHL32(1,SNR_SHIFT))); theta = MULT16_32_P15(prior_ratio, QCONST32(1.f,EXPIN_SHIFT)+SHL32(EXTEND32(st->post[i]),EXPIN_SHIFT-SNR_SHIFT)); /* Optimal estimator for loudness domain */ MM = hypergeom_gain(theta); /* EM gain with bound */ g = EXTRACT16(MIN32(Q15_ONE, MULT16_32_Q15(prior_ratio, MM))); /* Interpolated speech probability of presence */ p = st->gain2[i]; /* Constrain the gain to be close to the Bark scale gain */ if (MULT16_16_Q15(QCONST16(.333f,15),g) > st->gain[i]) g = MULT16_16(3,st->gain[i]); st->gain[i] = g; /* Save old power spectrum */ st->old_ps[i] = MULT16_32_P15(QCONST16(.2f,15),st->old_ps[i]) + MULT16_32_P15(MULT16_16_P15(QCONST16(.8f,15),SQR16_Q15(st->gain[i])),ps[i]); /* Apply gain floor */ if (st->gain[i] < st->gain_floor[i]) st->gain[i] = st->gain_floor[i]; /* Exponential decay model for reverberation (unused) */ /*st->reverb_estimate[i] = st->reverb_decay*st->reverb_estimate[i] + st->reverb_decay*st->reverb_level*st->gain[i]*st->gain[i]*st->ps[i];*/ /* Take into account speech probability of presence (loudness domain MMSE estimator) */ /* gain2 = [p*sqrt(gain)+(1-p)*sqrt(gain _floor) ]^2 */ tmp = MULT16_16_P15(p,spx_sqrt(SHL32(EXTEND32(st->gain[i]),15))) + MULT16_16_P15(SUB16(Q15_ONE,p),spx_sqrt(SHL32(EXTEND32(st->gain_floor[i]),15))); st->gain2[i]=SQR16_Q15(tmp); /* Use this if you want a log-domain MMSE estimator instead */ /*st->gain2[i] = pow(st->gain[i], p) * pow(st->gain_floor[i],1.f-p);*/ } } else { for (i=N;i<N+M;i++) { spx_word16_t tmp; spx_word16_t p = st->gain2[i]; st->gain[i] = MAX16(st->gain[i], st->gain_floor[i]); tmp = MULT16_16_P15(p,spx_sqrt(SHL32(EXTEND32(st->gain[i]),15))) + MULT16_16_P15(SUB16(Q15_ONE,p),spx_sqrt(SHL32(EXTEND32(st->gain_floor[i]),15))); st->gain2[i]=SQR16_Q15(tmp); } filterbank_compute_psd16(st->bank,st->gain2+N, st->gain2); } /* If noise suppression is off, don't apply the gain (but then why call this in the first place!) */ if (!st->denoise_enabled) { for (i=0;i<N+M;i++) st->gain2[i]=Q15_ONE; } /* Apply computed gain */ for (i=1;i<N;i++) { st->ft[2*i-1] = MULT16_16_P15(st->gain2[i],st->ft[2*i-1]); st->ft[2*i] = MULT16_16_P15(st->gain2[i],st->ft[2*i]); } st->ft[0] = MULT16_16_P15(st->gain2[0],st->ft[0]); st->ft[2*N-1] = MULT16_16_P15(st->gain2[N-1],st->ft[2*N-1]); /*FIXME: This *will* not work for fixed-point */ #ifndef FIXED_POINT if (st->agc_enabled) speex_compute_agc(st, Pframe, st->ft); #endif /* Inverse FFT with 1/N scaling */ spx_ifft(st->fft_lookup, st->ft, st->frame); /* Scale back to original (lower) amplitude */ for (i=0;i<2*N;i++) st->frame[i] = PSHR16(st->frame[i], st->frame_shift); /*FIXME: This *will* not work for fixed-point */ #ifndef FIXED_POINT if (st->agc_enabled) { float max_sample=0; for (i=0;i<2*N;i++) if (fabs(st->frame[i])>max_sample) max_sample = fabs(st->frame[i]); if (max_sample>28000.f) { float damp = 28000.f/max_sample; for (i=0;i<2*N;i++) st->frame[i] *= damp; } } #endif /* Synthesis window (for WOLA) */ for (i=0;i<2*N;i++) st->frame[i] = MULT16_16_Q15(st->frame[i], st->window[i]); /* Perform overlap and add */ for (i=0;i<N3;i++) x[i] = st->outbuf[i] + st->frame[i]; for (i=0;i<N4;i++) x[N3+i] = st->frame[N3+i]; /* Update outbuf */ for (i=0;i<N3;i++) st->outbuf[i] = st->frame[st->frame_size+i]; /* FIXME: This VAD is a kludge */ st->speech_prob = Pframe; if (st->vad_enabled) { if (st->speech_prob > st->speech_prob_start || (st->was_speech && st->speech_prob > st->speech_prob_continue)) { st->was_speech=1; return 1; } else { st->was_speech=0; return 0; } } else { return 1; } } EXPORT void speex_preprocess_estimate_update(SpeexPreprocessState *st, spx_int16_t *x) { int i; int N = st->ps_size; int N3 = 2*N - st->frame_size; int M; spx_word32_t *ps=st->ps; M = st->nbands; st->min_count++; preprocess_analysis(st, x); update_noise_prob(st); for (i=1;i<N-1;i++) { if (!st->update_prob[i] || st->ps[i] < PSHR32(st->noise[i],NOISE_SHIFT)) { st->noise[i] = MULT16_32_Q15(QCONST16(.95f,15),st->noise[i]) + MULT16_32_Q15(QCONST16(.05f,15),SHL32(st->ps[i],NOISE_SHIFT)); } } for (i=0;i<N3;i++) st->outbuf[i] = MULT16_16_Q15(x[st->frame_size-N3+i],st->window[st->frame_size+i]); /* Save old power spectrum */ for (i=0;i<N+M;i++) st->old_ps[i] = ps[i]; for (i=0;i<N;i++) st->reverb_estimate[i] = MULT16_32_Q15(st->reverb_decay, st->reverb_estimate[i]); } EXPORT int speex_preprocess_ctl(SpeexPreprocessState *state, int request, void *ptr) { int i; SpeexPreprocessState *st; st=(SpeexPreprocessState*)state; switch(request) { case SPEEX_PREPROCESS_SET_DENOISE: st->denoise_enabled = (*(spx_int32_t*)ptr); break; case SPEEX_PREPROCESS_GET_DENOISE: (*(spx_int32_t*)ptr) = st->denoise_enabled; break; #ifndef FIXED_POINT case SPEEX_PREPROCESS_SET_AGC: st->agc_enabled = (*(spx_int32_t*)ptr); break; case SPEEX_PREPROCESS_GET_AGC: (*(spx_int32_t*)ptr) = st->agc_enabled; break; #ifndef DISABLE_FLOAT_API case SPEEX_PREPROCESS_SET_AGC_LEVEL: st->agc_level = (*(float*)ptr); if (st->agc_level<1) st->agc_level=1; if (st->agc_level>32768) st->agc_level=32768; break; case SPEEX_PREPROCESS_GET_AGC_LEVEL: (*(float*)ptr) = st->agc_level; break; #endif /* #ifndef DISABLE_FLOAT_API */ case SPEEX_PREPROCESS_SET_AGC_INCREMENT: st->max_increase_step = exp(0.11513f * (*(spx_int32_t*)ptr)*st->frame_size / st->sampling_rate); break; case SPEEX_PREPROCESS_GET_AGC_INCREMENT: (*(spx_int32_t*)ptr) = floor(.5+8.6858*log(st->max_increase_step)*st->sampling_rate/st->frame_size); break; case SPEEX_PREPROCESS_SET_AGC_DECREMENT: st->max_decrease_step = exp(0.11513f * (*(spx_int32_t*)ptr)*st->frame_size / st->sampling_rate); break; case SPEEX_PREPROCESS_GET_AGC_DECREMENT: (*(spx_int32_t*)ptr) = floor(.5+8.6858*log(st->max_decrease_step)*st->sampling_rate/st->frame_size); break; case SPEEX_PREPROCESS_SET_AGC_MAX_GAIN: st->max_gain = exp(0.11513f * (*(spx_int32_t*)ptr)); break; case SPEEX_PREPROCESS_GET_AGC_MAX_GAIN: (*(spx_int32_t*)ptr) = floor(.5+8.6858*log(st->max_gain)); break; #endif case SPEEX_PREPROCESS_SET_VAD: speex_warning("The VAD has been replaced by a hack pending a complete rewrite"); st->vad_enabled = (*(spx_int32_t*)ptr); break; case SPEEX_PREPROCESS_GET_VAD: (*(spx_int32_t*)ptr) = st->vad_enabled; break; case SPEEX_PREPROCESS_SET_DEREVERB: st->dereverb_enabled = (*(spx_int32_t*)ptr); for (i=0;i<st->ps_size;i++) st->reverb_estimate[i]=0; break; case SPEEX_PREPROCESS_GET_DEREVERB: (*(spx_int32_t*)ptr) = st->dereverb_enabled; break; case SPEEX_PREPROCESS_SET_DEREVERB_LEVEL: /* FIXME: Re-enable when de-reverberation is actually enabled again */ /*st->reverb_level = (*(float*)ptr);*/ break; case SPEEX_PREPROCESS_GET_DEREVERB_LEVEL: /* FIXME: Re-enable when de-reverberation is actually enabled again */ /*(*(float*)ptr) = st->reverb_level;*/ break; case SPEEX_PREPROCESS_SET_DEREVERB_DECAY: /* FIXME: Re-enable when de-reverberation is actually enabled again */ /*st->reverb_decay = (*(float*)ptr);*/ break; case SPEEX_PREPROCESS_GET_DEREVERB_DECAY: /* FIXME: Re-enable when de-reverberation is actually enabled again */ /*(*(float*)ptr) = st->reverb_decay;*/ break; case SPEEX_PREPROCESS_SET_PROB_START: *(spx_int32_t*)ptr = MIN32(100,MAX32(0, *(spx_int32_t*)ptr)); st->speech_prob_start = DIV32_16(MULT16_16(Q15ONE,*(spx_int32_t*)ptr), 100); break; case SPEEX_PREPROCESS_GET_PROB_START: (*(spx_int32_t*)ptr) = MULT16_16_Q15(st->speech_prob_start, 100); break; case SPEEX_PREPROCESS_SET_PROB_CONTINUE: *(spx_int32_t*)ptr = MIN32(100,MAX32(0, *(spx_int32_t*)ptr)); st->speech_prob_continue = DIV32_16(MULT16_16(Q15ONE,*(spx_int32_t*)ptr), 100); break; case SPEEX_PREPROCESS_GET_PROB_CONTINUE: (*(spx_int32_t*)ptr) = MULT16_16_Q15(st->speech_prob_continue, 100); break; case SPEEX_PREPROCESS_SET_NOISE_SUPPRESS: st->noise_suppress = -ABS(*(spx_int32_t*)ptr); break; case SPEEX_PREPROCESS_GET_NOISE_SUPPRESS: (*(spx_int32_t*)ptr) = st->noise_suppress; break; case SPEEX_PREPROCESS_SET_ECHO_SUPPRESS: st->echo_suppress = -ABS(*(spx_int32_t*)ptr); break; case SPEEX_PREPROCESS_GET_ECHO_SUPPRESS: (*(spx_int32_t*)ptr) = st->echo_suppress; break; case SPEEX_PREPROCESS_SET_ECHO_SUPPRESS_ACTIVE: st->echo_suppress_active = -ABS(*(spx_int32_t*)ptr); break; case SPEEX_PREPROCESS_GET_ECHO_SUPPRESS_ACTIVE: (*(spx_int32_t*)ptr) = st->echo_suppress_active; break; case SPEEX_PREPROCESS_SET_ECHO_STATE: st->echo_state = (SpeexEchoState*)ptr; break; case SPEEX_PREPROCESS_GET_ECHO_STATE: (*(SpeexEchoState**)ptr) = (SpeexEchoState*)st->echo_state; break; #ifndef FIXED_POINT case SPEEX_PREPROCESS_GET_AGC_LOUDNESS: (*(spx_int32_t*)ptr) = pow(st->loudness, 1.0/LOUDNESS_EXP); break; case SPEEX_PREPROCESS_GET_AGC_GAIN: (*(spx_int32_t*)ptr) = floor(.5+8.6858*log(st->agc_gain)); break; #endif case SPEEX_PREPROCESS_GET_PSD_SIZE: case SPEEX_PREPROCESS_GET_NOISE_PSD_SIZE: (*(spx_int32_t*)ptr) = st->ps_size; break; case SPEEX_PREPROCESS_GET_PSD: for(i=0;i<st->ps_size;i++) ((spx_int32_t *)ptr)[i] = (spx_int32_t) st->ps[i]; break; case SPEEX_PREPROCESS_GET_NOISE_PSD: for(i=0;i<st->ps_size;i++) ((spx_int32_t *)ptr)[i] = (spx_int32_t) PSHR32(st->noise[i], NOISE_SHIFT); break; case SPEEX_PREPROCESS_GET_PROB: (*(spx_int32_t*)ptr) = MULT16_16_Q15(st->speech_prob, 100); break; #ifndef FIXED_POINT case SPEEX_PREPROCESS_SET_AGC_TARGET: st->agc_level = (*(spx_int32_t*)ptr); if (st->agc_level<1) st->agc_level=1; if (st->agc_level>32768) st->agc_level=32768; break; case SPEEX_PREPROCESS_GET_AGC_TARGET: (*(spx_int32_t*)ptr) = st->agc_level; break; #endif default: speex_warning_int("Unknown speex_preprocess_ctl request: ", request); return -1; } return 0; } #ifdef FIXED_DEBUG long long spx_mips=0; #endif
gpl-3.0
tazdij/odingine
src/odingine/lua/lfunc.c
338
4270
/* ** $Id: lfunc.c,v 2.30.1.1 2013/04/12 18:48:47 roberto Exp $ ** Auxiliary functions to manipulate prototypes and closures ** See Copyright Notice in lua.h */ #include <stddef.h> #define lfunc_c #define LUA_CORE #include "lua.h" #include "lfunc.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" Closure *luaF_newCclosure (lua_State *L, int n) { Closure *c = &luaC_newobj(L, LUA_TCCL, sizeCclosure(n), NULL, 0)->cl; c->c.nupvalues = cast_byte(n); return c; } Closure *luaF_newLclosure (lua_State *L, int n) { Closure *c = &luaC_newobj(L, LUA_TLCL, sizeLclosure(n), NULL, 0)->cl; c->l.p = NULL; c->l.nupvalues = cast_byte(n); while (n--) c->l.upvals[n] = NULL; return c; } UpVal *luaF_newupval (lua_State *L) { UpVal *uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), NULL, 0)->uv; uv->v = &uv->u.value; setnilvalue(uv->v); return uv; } UpVal *luaF_findupval (lua_State *L, StkId level) { global_State *g = G(L); GCObject **pp = &L->openupval; UpVal *p; UpVal *uv; while (*pp != NULL && (p = gco2uv(*pp))->v >= level) { GCObject *o = obj2gco(p); lua_assert(p->v != &p->u.value); lua_assert(!isold(o) || isold(obj2gco(L))); if (p->v == level) { /* found a corresponding upvalue? */ if (isdead(g, o)) /* is it dead? */ changewhite(o); /* resurrect it */ return p; } pp = &p->next; } /* not found: create a new one */ uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), pp, 0)->uv; uv->v = level; /* current value lives in the stack */ uv->u.l.prev = &g->uvhead; /* double link it in `uvhead' list */ uv->u.l.next = g->uvhead.u.l.next; uv->u.l.next->u.l.prev = uv; g->uvhead.u.l.next = uv; lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); return uv; } static void unlinkupval (UpVal *uv) { lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); uv->u.l.next->u.l.prev = uv->u.l.prev; /* remove from `uvhead' list */ uv->u.l.prev->u.l.next = uv->u.l.next; } void luaF_freeupval (lua_State *L, UpVal *uv) { if (uv->v != &uv->u.value) /* is it open? */ unlinkupval(uv); /* remove from open list */ luaM_free(L, uv); /* free upvalue */ } void luaF_close (lua_State *L, StkId level) { UpVal *uv; global_State *g = G(L); while (L->openupval != NULL && (uv = gco2uv(L->openupval))->v >= level) { GCObject *o = obj2gco(uv); lua_assert(!isblack(o) && uv->v != &uv->u.value); L->openupval = uv->next; /* remove from `open' list */ if (isdead(g, o)) luaF_freeupval(L, uv); /* free upvalue */ else { unlinkupval(uv); /* remove upvalue from 'uvhead' list */ setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */ uv->v = &uv->u.value; /* now current value lives here */ gch(o)->next = g->allgc; /* link upvalue into 'allgc' list */ g->allgc = o; luaC_checkupvalcolor(g, uv); } } } Proto *luaF_newproto (lua_State *L) { Proto *f = &luaC_newobj(L, LUA_TPROTO, sizeof(Proto), NULL, 0)->p; f->k = NULL; f->sizek = 0; f->p = NULL; f->sizep = 0; f->code = NULL; f->cache = NULL; f->sizecode = 0; f->lineinfo = NULL; f->sizelineinfo = 0; f->upvalues = NULL; f->sizeupvalues = 0; f->numparams = 0; f->is_vararg = 0; f->maxstacksize = 0; f->locvars = NULL; f->sizelocvars = 0; f->linedefined = 0; f->lastlinedefined = 0; f->source = NULL; return f; } void luaF_freeproto (lua_State *L, Proto *f) { luaM_freearray(L, f->code, f->sizecode); luaM_freearray(L, f->p, f->sizep); luaM_freearray(L, f->k, f->sizek); luaM_freearray(L, f->lineinfo, f->sizelineinfo); luaM_freearray(L, f->locvars, f->sizelocvars); luaM_freearray(L, f->upvalues, f->sizeupvalues); luaM_free(L, f); } /* ** Look for n-th local variable at line `line' in function `func'. ** Returns NULL if not found. */ const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { int i; for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) { if (pc < f->locvars[i].endpc) { /* is variable active? */ local_number--; if (local_number == 0) return getstr(f->locvars[i].varname); } } return NULL; /* not found */ }
gpl-3.0
WisniaPL/LeEco-Le1S-Kernel
drivers/ide/ide-cs.c
5202
12339
/*====================================================================== A driver for PCMCIA IDE/ATA disk cards The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The initial developer of the original code is David A. Hinds <dahinds@users.sourceforge.net>. Portions created by David A. Hinds are Copyright (C) 1999 David A. Hinds. All Rights Reserved. Alternatively, the contents of this file may be used under the terms of the GNU General Public License version 2 (the "GPL"), in which case the provisions of the GPL are applicable instead of the above. If you wish to allow the use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. ======================================================================*/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/ioport.h> #include <linux/ide.h> #include <linux/major.h> #include <linux/delay.h> #include <asm/io.h> #include <pcmcia/cistpl.h> #include <pcmcia/ds.h> #include <pcmcia/cisreg.h> #include <pcmcia/ciscode.h> #define DRV_NAME "ide-cs" /*====================================================================*/ /* Module parameters */ MODULE_AUTHOR("David Hinds <dahinds@users.sourceforge.net>"); MODULE_DESCRIPTION("PCMCIA ATA/IDE card driver"); MODULE_LICENSE("Dual MPL/GPL"); /*====================================================================*/ typedef struct ide_info_t { struct pcmcia_device *p_dev; struct ide_host *host; int ndev; } ide_info_t; static void ide_release(struct pcmcia_device *); static int ide_config(struct pcmcia_device *); static void ide_detach(struct pcmcia_device *p_dev); static int ide_probe(struct pcmcia_device *link) { ide_info_t *info; dev_dbg(&link->dev, "ide_attach()\n"); /* Create new ide device */ info = kzalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; info->p_dev = link; link->priv = info; link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO | CONF_AUTO_SET_VPP | CONF_AUTO_CHECK_VCC; return ide_config(link); } /* ide_attach */ static void ide_detach(struct pcmcia_device *link) { ide_info_t *info = link->priv; dev_dbg(&link->dev, "ide_detach(0x%p)\n", link); ide_release(link); kfree(info); } /* ide_detach */ static const struct ide_port_ops idecs_port_ops = { .quirkproc = ide_undecoded_slave, }; static const struct ide_port_info idecs_port_info = { .port_ops = &idecs_port_ops, .host_flags = IDE_HFLAG_NO_DMA, .irq_flags = IRQF_SHARED, .chipset = ide_pci, }; static struct ide_host *idecs_register(unsigned long io, unsigned long ctl, unsigned long irq, struct pcmcia_device *handle) { struct ide_host *host; ide_hwif_t *hwif; int i, rc; struct ide_hw hw, *hws[] = { &hw }; if (!request_region(io, 8, DRV_NAME)) { printk(KERN_ERR "%s: I/O resource 0x%lX-0x%lX not free.\n", DRV_NAME, io, io + 7); return NULL; } if (!request_region(ctl, 1, DRV_NAME)) { printk(KERN_ERR "%s: I/O resource 0x%lX not free.\n", DRV_NAME, ctl); release_region(io, 8); return NULL; } memset(&hw, 0, sizeof(hw)); ide_std_init_ports(&hw, io, ctl); hw.irq = irq; hw.dev = &handle->dev; rc = ide_host_add(&idecs_port_info, hws, 1, &host); if (rc) goto out_release; hwif = host->ports[0]; if (hwif->present) return host; /* retry registration in case device is still spinning up */ for (i = 0; i < 10; i++) { msleep(100); ide_port_scan(hwif); if (hwif->present) return host; } return host; out_release: release_region(ctl, 1); release_region(io, 8); return NULL; } static int pcmcia_check_one_config(struct pcmcia_device *pdev, void *priv_data) { int *is_kme = priv_data; if ((pdev->resource[0]->flags & IO_DATA_PATH_WIDTH) != IO_DATA_PATH_WIDTH_8) { pdev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH; pdev->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO; } pdev->resource[1]->flags &= ~IO_DATA_PATH_WIDTH; pdev->resource[1]->flags |= IO_DATA_PATH_WIDTH_8; if (pdev->resource[1]->end) { pdev->resource[0]->end = 8; pdev->resource[1]->end = (*is_kme) ? 2 : 1; } else { if (pdev->resource[0]->end < 16) return -ENODEV; } return pcmcia_request_io(pdev); } static int ide_config(struct pcmcia_device *link) { ide_info_t *info = link->priv; int ret = 0, is_kme = 0; unsigned long io_base, ctl_base; struct ide_host *host; dev_dbg(&link->dev, "ide_config(0x%p)\n", link); is_kme = ((link->manf_id == MANFID_KME) && ((link->card_id == PRODID_KME_KXLC005_A) || (link->card_id == PRODID_KME_KXLC005_B))); if (pcmcia_loop_config(link, pcmcia_check_one_config, &is_kme)) { link->config_flags &= ~CONF_AUTO_CHECK_VCC; if (pcmcia_loop_config(link, pcmcia_check_one_config, &is_kme)) goto failed; /* No suitable config found */ } io_base = link->resource[0]->start; if (link->resource[1]->end) ctl_base = link->resource[1]->start; else ctl_base = link->resource[0]->start + 0x0e; if (!link->irq) goto failed; ret = pcmcia_enable_device(link); if (ret) goto failed; /* disable drive interrupts during IDE probe */ outb(0x02, ctl_base); /* special setup for KXLC005 card */ if (is_kme) outb(0x81, ctl_base+1); host = idecs_register(io_base, ctl_base, link->irq, link); if (host == NULL && resource_size(link->resource[0]) == 0x20) { outb(0x02, ctl_base + 0x10); host = idecs_register(io_base + 0x10, ctl_base + 0x10, link->irq, link); } if (host == NULL) goto failed; info->ndev = 1; info->host = host; dev_info(&link->dev, "ide-cs: hd%c: Vpp = %d.%d\n", 'a' + host->ports[0]->index * 2, link->vpp / 10, link->vpp % 10); return 0; failed: ide_release(link); return -ENODEV; } /* ide_config */ static void ide_release(struct pcmcia_device *link) { ide_info_t *info = link->priv; struct ide_host *host = info->host; dev_dbg(&link->dev, "ide_release(0x%p)\n", link); if (info->ndev) { ide_hwif_t *hwif = host->ports[0]; unsigned long data_addr, ctl_addr; data_addr = hwif->io_ports.data_addr; ctl_addr = hwif->io_ports.ctl_addr; ide_host_remove(host); info->ndev = 0; release_region(ctl_addr, 1); release_region(data_addr, 8); } pcmcia_disable_device(link); } /* ide_release */ static const struct pcmcia_device_id ide_ids[] = { PCMCIA_DEVICE_FUNC_ID(4), PCMCIA_DEVICE_MANF_CARD(0x0000, 0x0000), /* Corsair */ PCMCIA_DEVICE_MANF_CARD(0x0007, 0x0000), /* Hitachi */ PCMCIA_DEVICE_MANF_CARD(0x000a, 0x0000), /* I-O Data CFA */ PCMCIA_DEVICE_MANF_CARD(0x001c, 0x0001), /* Mitsubishi CFA */ PCMCIA_DEVICE_MANF_CARD(0x0032, 0x0704), PCMCIA_DEVICE_MANF_CARD(0x0032, 0x2904), PCMCIA_DEVICE_MANF_CARD(0x0045, 0x0401), /* SanDisk CFA */ PCMCIA_DEVICE_MANF_CARD(0x004f, 0x0000), /* Kingston */ PCMCIA_DEVICE_MANF_CARD(0x0097, 0x1620), /* TI emulated */ PCMCIA_DEVICE_MANF_CARD(0x0098, 0x0000), /* Toshiba */ PCMCIA_DEVICE_MANF_CARD(0x00a4, 0x002d), PCMCIA_DEVICE_MANF_CARD(0x00ce, 0x0000), /* Samsung */ PCMCIA_DEVICE_MANF_CARD(0x0319, 0x0000), /* Hitachi */ PCMCIA_DEVICE_MANF_CARD(0x2080, 0x0001), PCMCIA_DEVICE_MANF_CARD(0x4e01, 0x0100), /* Viking CFA */ PCMCIA_DEVICE_MANF_CARD(0x4e01, 0x0200), /* Lexar, Viking CFA */ PCMCIA_DEVICE_PROD_ID123("Caravelle", "PSC-IDE ", "PSC000", 0x8c36137c, 0xd0693ab8, 0x2768a9f0), PCMCIA_DEVICE_PROD_ID123("CDROM", "IDE", "MCD-601p", 0x1b9179ca, 0xede88951, 0x0d902f74), PCMCIA_DEVICE_PROD_ID123("PCMCIA", "IDE CARD", "F1", 0x281f1c5d, 0x1907960c, 0xf7fde8b9), PCMCIA_DEVICE_PROD_ID12("ARGOSY", "CD-ROM", 0x78f308dc, 0x66536591), PCMCIA_DEVICE_PROD_ID12("ARGOSY", "PnPIDE", 0x78f308dc, 0x0c694728), PCMCIA_DEVICE_PROD_ID12("CNF ", "CD-ROM", 0x46d7db81, 0x66536591), PCMCIA_DEVICE_PROD_ID12("CNF CD-M", "CD-ROM", 0x7d93b852, 0x66536591), PCMCIA_DEVICE_PROD_ID12("Creative Technology Ltd.", "PCMCIA CD-ROM Interface Card", 0xff8c8a45, 0xfe8020c4), PCMCIA_DEVICE_PROD_ID12("Digital Equipment Corporation.", "Digital Mobile Media CD-ROM", 0x17692a66, 0xef1dcbde), PCMCIA_DEVICE_PROD_ID12("EXP", "CD+GAME", 0x6f58c983, 0x63c13aaf), PCMCIA_DEVICE_PROD_ID12("EXP ", "CD-ROM", 0x0a5c52fd, 0x66536591), PCMCIA_DEVICE_PROD_ID12("EXP ", "PnPIDE", 0x0a5c52fd, 0x0c694728), PCMCIA_DEVICE_PROD_ID12("FREECOM", "PCCARD-IDE", 0x5714cbf7, 0x48e0ab8e), PCMCIA_DEVICE_PROD_ID12("HITACHI", "FLASH", 0xf4f43949, 0x9eb86aae), PCMCIA_DEVICE_PROD_ID12("HITACHI", "microdrive", 0xf4f43949, 0xa6d76178), PCMCIA_DEVICE_PROD_ID12("Hyperstone", "Model1", 0x3d5b9ef5, 0xca6ab420), PCMCIA_DEVICE_PROD_ID12("IBM", "microdrive", 0xb569a6e5, 0xa6d76178), PCMCIA_DEVICE_PROD_ID12("IBM", "IBM17JSSFP20", 0xb569a6e5, 0xf2508753), PCMCIA_DEVICE_PROD_ID12("KINGSTON", "CF CARD 1GB", 0x2e6d1829, 0x55d5bffb), PCMCIA_DEVICE_PROD_ID12("KINGSTON", "CF CARD 4GB", 0x2e6d1829, 0x531e7d10), PCMCIA_DEVICE_PROD_ID12("KINGSTON", "CF8GB", 0x2e6d1829, 0xacbe682e), PCMCIA_DEVICE_PROD_ID12("IO DATA", "CBIDE2 ", 0x547e66dc, 0x8671043b), PCMCIA_DEVICE_PROD_ID12("IO DATA", "PCIDE", 0x547e66dc, 0x5c5ab149), PCMCIA_DEVICE_PROD_ID12("IO DATA", "PCIDEII", 0x547e66dc, 0xb3662674), PCMCIA_DEVICE_PROD_ID12("LOOKMEET", "CBIDE2 ", 0xe37be2b5, 0x8671043b), PCMCIA_DEVICE_PROD_ID12("M-Systems", "CF300", 0x7ed2ad87, 0x7e9e78ee), PCMCIA_DEVICE_PROD_ID12("M-Systems", "CF500", 0x7ed2ad87, 0x7a13045c), PCMCIA_DEVICE_PROD_ID2("NinjaATA-", 0xebe0bd79), PCMCIA_DEVICE_PROD_ID12("PCMCIA", "CD-ROM", 0x281f1c5d, 0x66536591), PCMCIA_DEVICE_PROD_ID12("PCMCIA", "PnPIDE", 0x281f1c5d, 0x0c694728), PCMCIA_DEVICE_PROD_ID12("SHUTTLE TECHNOLOGY LTD.", "PCCARD-IDE/ATAPI Adapter", 0x4a3f0ba0, 0x322560e1), PCMCIA_DEVICE_PROD_ID12("SEAGATE", "ST1", 0x87c1b330, 0xe1f30883), PCMCIA_DEVICE_PROD_ID12("SAMSUNG", "04/05/06", 0x43d74cb4, 0x6a22777d), PCMCIA_DEVICE_PROD_ID12("SMI VENDOR", "SMI PRODUCT", 0x30896c92, 0x703cc5f6), PCMCIA_DEVICE_PROD_ID12("TOSHIBA", "MK2001MPL", 0xb4585a1a, 0x3489e003), PCMCIA_DEVICE_PROD_ID1("TRANSCEND 512M ", 0xd0909443), PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS1GCF45", 0x709b1bf1, 0xf68b6f32), PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS1GCF80", 0x709b1bf1, 0x2a54d4b1), PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS2GCF120", 0x709b1bf1, 0x969aa4f2), PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS4GCF120", 0x709b1bf1, 0xf54a91c8), PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS4GCF133", 0x709b1bf1, 0x7558f133), PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS8GCF133", 0x709b1bf1, 0xb2f89b47), PCMCIA_DEVICE_PROD_ID12("WIT", "IDE16", 0x244e5994, 0x3e232852), PCMCIA_DEVICE_PROD_ID12("WEIDA", "TWTTI", 0xcc7cf69c, 0x212bb918), PCMCIA_DEVICE_PROD_ID1("STI Flash", 0xe4a13209), PCMCIA_DEVICE_PROD_ID12("STI", "Flash 5.0", 0xbf2df18d, 0x8cb57a0e), PCMCIA_MFC_DEVICE_PROD_ID12(1, "SanDisk", "ConnectPlus", 0x7a954bd9, 0x74be00c6), PCMCIA_DEVICE_PROD_ID2("Flash Card", 0x5a362506), PCMCIA_DEVICE_NULL, }; MODULE_DEVICE_TABLE(pcmcia, ide_ids); static struct pcmcia_driver ide_cs_driver = { .owner = THIS_MODULE, .name = "ide-cs", .probe = ide_probe, .remove = ide_detach, .id_table = ide_ids, }; static int __init init_ide_cs(void) { return pcmcia_register_driver(&ide_cs_driver); } static void __exit exit_ide_cs(void) { pcmcia_unregister_driver(&ide_cs_driver); } late_initcall(init_ide_cs); module_exit(exit_ide_cs);
gpl-3.0
cat9/shadowsocks-android
src/main/jni/openssl/crypto/dh/dh_ameth.c
598
11158
/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project 2006. */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/dh.h> #include <openssl/bn.h> #include "asn1_locl.h" static void int_dh_free(EVP_PKEY *pkey) { DH_free(pkey->pkey.dh); } static int dh_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *public_key = NULL; DH *dh = NULL; if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (ptype != V_ASN1_SEQUENCE) { DHerr(DH_F_DH_PUB_DECODE, DH_R_PARAMETER_ENCODING_ERROR); goto err; } pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dh = d2i_DHparams(NULL, &pm, pmlen))) { DHerr(DH_F_DH_PUB_DECODE, DH_R_DECODE_ERROR); goto err; } if (!(public_key=d2i_ASN1_INTEGER(NULL, &p, pklen))) { DHerr(DH_F_DH_PUB_DECODE, DH_R_DECODE_ERROR); goto err; } /* We have parameters now set public key */ if (!(dh->pub_key = ASN1_INTEGER_to_BN(public_key, NULL))) { DHerr(DH_F_DH_PUB_DECODE, DH_R_BN_DECODE_ERROR); goto err; } ASN1_INTEGER_free(public_key); EVP_PKEY_assign_DH(pkey, dh); return 1; err: if (public_key) ASN1_INTEGER_free(public_key); if (dh) DH_free(dh); return 0; } static int dh_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { DH *dh; void *pval = NULL; int ptype; unsigned char *penc = NULL; int penclen; ASN1_STRING *str; ASN1_INTEGER *pub_key = NULL; dh=pkey->pkey.dh; str = ASN1_STRING_new(); str->length = i2d_DHparams(dh, &str->data); if (str->length <= 0) { DHerr(DH_F_DH_PUB_ENCODE, ERR_R_MALLOC_FAILURE); goto err; } pval = str; ptype = V_ASN1_SEQUENCE; pub_key = BN_to_ASN1_INTEGER(dh->pub_key, NULL); if (!pub_key) goto err; penclen = i2d_ASN1_INTEGER(pub_key, &penc); ASN1_INTEGER_free(pub_key); if (penclen <= 0) { DHerr(DH_F_DH_PUB_ENCODE, ERR_R_MALLOC_FAILURE); goto err; } if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_DH), ptype, pval, penc, penclen)) return 1; err: if (penc) OPENSSL_free(penc); if (pval) ASN1_STRING_free(pval); return 0; } /* PKCS#8 DH is defined in PKCS#11 of all places. It is similar to DH in * that the AlgorithmIdentifier contains the paramaters, the private key * is explcitly included and the pubkey must be recalculated. */ static int dh_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *privkey = NULL; DH *dh = NULL; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (ptype != V_ASN1_SEQUENCE) goto decerr; if (!(privkey=d2i_ASN1_INTEGER(NULL, &p, pklen))) goto decerr; pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dh = d2i_DHparams(NULL, &pm, pmlen))) goto decerr; /* We have parameters now set private key */ if (!(dh->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) { DHerr(DH_F_DH_PRIV_DECODE,DH_R_BN_ERROR); goto dherr; } /* Calculate public key */ if (!DH_generate_key(dh)) goto dherr; EVP_PKEY_assign_DH(pkey, dh); ASN1_INTEGER_free(privkey); return 1; decerr: DHerr(DH_F_DH_PRIV_DECODE, EVP_R_DECODE_ERROR); dherr: DH_free(dh); return 0; } static int dh_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) { ASN1_STRING *params = NULL; ASN1_INTEGER *prkey = NULL; unsigned char *dp = NULL; int dplen; params = ASN1_STRING_new(); if (!params) { DHerr(DH_F_DH_PRIV_ENCODE,ERR_R_MALLOC_FAILURE); goto err; } params->length = i2d_DHparams(pkey->pkey.dh, &params->data); if (params->length <= 0) { DHerr(DH_F_DH_PRIV_ENCODE,ERR_R_MALLOC_FAILURE); goto err; } params->type = V_ASN1_SEQUENCE; /* Get private key into integer */ prkey = BN_to_ASN1_INTEGER(pkey->pkey.dh->priv_key, NULL); if (!prkey) { DHerr(DH_F_DH_PRIV_ENCODE,DH_R_BN_ERROR); goto err; } dplen = i2d_ASN1_INTEGER(prkey, &dp); ASN1_INTEGER_free(prkey); if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_dhKeyAgreement), 0, V_ASN1_SEQUENCE, params, dp, dplen)) goto err; return 1; err: if (dp != NULL) OPENSSL_free(dp); if (params != NULL) ASN1_STRING_free(params); if (prkey != NULL) ASN1_INTEGER_free(prkey); return 0; } static void update_buflen(const BIGNUM *b, size_t *pbuflen) { size_t i; if (!b) return; if (*pbuflen < (i = (size_t)BN_num_bytes(b))) *pbuflen = i; } static int dh_param_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { DH *dh; if (!(dh = d2i_DHparams(NULL, pder, derlen))) { DHerr(DH_F_DH_PARAM_DECODE, ERR_R_DH_LIB); return 0; } EVP_PKEY_assign_DH(pkey, dh); return 1; } static int dh_param_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_DHparams(pkey->pkey.dh, pder); } static int do_dh_print(BIO *bp, const DH *x, int indent, ASN1_PCTX *ctx, int ptype) { unsigned char *m=NULL; int reason=ERR_R_BUF_LIB,ret=0; size_t buf_len=0; const char *ktype = NULL; BIGNUM *priv_key, *pub_key; if (ptype == 2) priv_key = x->priv_key; else priv_key = NULL; if (ptype > 0) pub_key = x->pub_key; else pub_key = NULL; update_buflen(x->p, &buf_len); if (buf_len == 0) { reason = ERR_R_PASSED_NULL_PARAMETER; goto err; } update_buflen(x->g, &buf_len); update_buflen(pub_key, &buf_len); update_buflen(priv_key, &buf_len); if (ptype == 2) ktype = "PKCS#3 DH Private-Key"; else if (ptype == 1) ktype = "PKCS#3 DH Public-Key"; else ktype = "PKCS#3 DH Parameters"; m= OPENSSL_malloc(buf_len+10); if (m == NULL) { reason=ERR_R_MALLOC_FAILURE; goto err; } BIO_indent(bp, indent, 128); if (BIO_printf(bp,"%s: (%d bit)\n", ktype, BN_num_bits(x->p)) <= 0) goto err; indent += 4; if (!ASN1_bn_print(bp,"private-key:",priv_key,m,indent)) goto err; if (!ASN1_bn_print(bp,"public-key:",pub_key,m,indent)) goto err; if (!ASN1_bn_print(bp,"prime:",x->p,m,indent)) goto err; if (!ASN1_bn_print(bp,"generator:",x->g,m,indent)) goto err; if (x->length != 0) { BIO_indent(bp, indent, 128); if (BIO_printf(bp,"recommended-private-length: %d bits\n", (int)x->length) <= 0) goto err; } ret=1; if (0) { err: DHerr(DH_F_DO_DH_PRINT,reason); } if (m != NULL) OPENSSL_free(m); return(ret); } static int int_dh_size(const EVP_PKEY *pkey) { return(DH_size(pkey->pkey.dh)); } static int dh_bits(const EVP_PKEY *pkey) { return BN_num_bits(pkey->pkey.dh->p); } static int dh_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { if ( BN_cmp(a->pkey.dh->p,b->pkey.dh->p) || BN_cmp(a->pkey.dh->g,b->pkey.dh->g)) return 0; else return 1; } static int dh_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { BIGNUM *a; if ((a=BN_dup(from->pkey.dh->p)) == NULL) return 0; if (to->pkey.dh->p != NULL) BN_free(to->pkey.dh->p); to->pkey.dh->p=a; if ((a=BN_dup(from->pkey.dh->g)) == NULL) return 0; if (to->pkey.dh->g != NULL) BN_free(to->pkey.dh->g); to->pkey.dh->g=a; return 1; } static int dh_missing_parameters(const EVP_PKEY *a) { if (!a->pkey.dh->p || !a->pkey.dh->g) return 1; return 0; } static int dh_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { if (dh_cmp_parameters(a, b) == 0) return 0; if (BN_cmp(b->pkey.dh->pub_key,a->pkey.dh->pub_key) != 0) return 0; else return 1; } static int dh_param_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dh_print(bp, pkey->pkey.dh, indent, ctx, 0); } static int dh_public_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dh_print(bp, pkey->pkey.dh, indent, ctx, 1); } static int dh_private_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dh_print(bp, pkey->pkey.dh, indent, ctx, 2); } int DHparams_print(BIO *bp, const DH *x) { return do_dh_print(bp, x, 4, NULL, 0); } const EVP_PKEY_ASN1_METHOD dh_asn1_meth = { EVP_PKEY_DH, EVP_PKEY_DH, 0, "DH", "OpenSSL PKCS#3 DH method", dh_pub_decode, dh_pub_encode, dh_pub_cmp, dh_public_print, dh_priv_decode, dh_priv_encode, dh_private_print, int_dh_size, dh_bits, dh_param_decode, dh_param_encode, dh_missing_parameters, dh_copy_parameters, dh_cmp_parameters, dh_param_print, 0, int_dh_free, 0 };
gpl-3.0
KubaKaszycki/kubux
gcc/gcc/testsuite/gfortran.dg/matmul_9.f90
90
1527
! { dg-do run } ! { dg-options "-fdump-tree-original" } ! ! PR fortran/56318 ! ! Contributed by Alberto Luaces ! SUBROUTINE mass_matrix DOUBLE PRECISION,PARAMETER::m1=1.d0 DOUBLE PRECISION,DIMENSION(3,2),PARAMETER::A1=reshape([1.d0,0.d0, 0.d0, & 0.d0,1.d0, 0.d0],[3,2]) DOUBLE PRECISION,DIMENSION(2,2),PARAMETER::Mel=reshape([1.d0/3.d0, 0.d0, & 0.d0, 1.d0/3.d0],[2,2]) DOUBLE PRECISION,DIMENSION(3,3)::MM1 MM1=m1*matmul(A1,matmul(Mel,transpose(A1))) !print '(3f8.3)', MM1 if (any (abs (MM1 & - reshape ([1.d0/3.d0, 0.d0, 0.d0, & 0.d0, 1.d0/3.d0, 0.d0, & 0.d0, 0.d0, 0.d0], & [3,3])) > epsilon(1.0d0))) & call abort () END SUBROUTINE mass_matrix program name implicit none integer, parameter :: A(3,2) = reshape([1,2,3,4,5,6],[3,2]) integer, parameter :: B(2,3) = reshape([3,17,23,31,43,71],[2,3]) integer, parameter :: C(3) = [-5,-7,-21] integer, parameter :: m1 = 1 ! print *, matmul(B,C) if (any (matmul(B,C) /= [-1079, -1793])) call abort() ! print *, matmul(C,A) if (any (matmul(C,A) /= [-82, -181])) call abort() ! print '(3i5)', m1*matmul(A,B) if (any (m1*matmul(A,B) /= reshape([71,91,111, 147,201,255, 327,441,555],& [3,3]))) & call abort() call mass_matrix end program name ! { dg-final { scan-tree-dump-times "matmul" 0 "original" } } ! { dg-final { cleanup-tree-dump "original" } }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtlocation/src/3rdparty/mapbox-gl-native/src/3rd_party/rapidjson/test/unittest/pointertest.cpp
91
55407
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include "unittest.h" #include "rapidjson/pointer.h" #include "rapidjson/stringbuffer.h" #include <sstream> using namespace rapidjson; static const char kJson[] = "{\n" " \"foo\":[\"bar\", \"baz\"],\n" " \"\" : 0,\n" " \"a/b\" : 1,\n" " \"c%d\" : 2,\n" " \"e^f\" : 3,\n" " \"g|h\" : 4,\n" " \"i\\\\j\" : 5,\n" " \"k\\\"l\" : 6,\n" " \" \" : 7,\n" " \"m~n\" : 8\n" "}"; TEST(Pointer, DefaultConstructor) { Pointer p; EXPECT_TRUE(p.IsValid()); EXPECT_EQ(0u, p.GetTokenCount()); } TEST(Pointer, Parse) { { Pointer p(""); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(0u, p.GetTokenCount()); } { Pointer p("/"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(0u, p.GetTokens()[0].length); EXPECT_STREQ("", p.GetTokens()[0].name); EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); } { Pointer p("/foo"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("foo", p.GetTokens()[0].name); EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); } #if RAPIDJSON_HAS_STDSTRING { Pointer p(std::string("/foo")); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("foo", p.GetTokens()[0].name); EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); } #endif { Pointer p("/foo/0"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(2u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("foo", p.GetTokens()[0].name); EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); EXPECT_EQ(1u, p.GetTokens()[1].length); EXPECT_STREQ("0", p.GetTokens()[1].name); EXPECT_EQ(0u, p.GetTokens()[1].index); } { // Unescape ~1 Pointer p("/a~1b"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("a/b", p.GetTokens()[0].name); } { // Unescape ~0 Pointer p("/m~0n"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("m~n", p.GetTokens()[0].name); } { // empty name Pointer p("/"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(0u, p.GetTokens()[0].length); EXPECT_STREQ("", p.GetTokens()[0].name); } { // empty and non-empty name Pointer p("//a"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(2u, p.GetTokenCount()); EXPECT_EQ(0u, p.GetTokens()[0].length); EXPECT_STREQ("", p.GetTokens()[0].name); EXPECT_EQ(1u, p.GetTokens()[1].length); EXPECT_STREQ("a", p.GetTokens()[1].name); } { // Null characters Pointer p("/\0\0", 3); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(2u, p.GetTokens()[0].length); EXPECT_EQ('\0', p.GetTokens()[0].name[0]); EXPECT_EQ('\0', p.GetTokens()[0].name[1]); EXPECT_EQ('\0', p.GetTokens()[0].name[2]); } { // Valid index Pointer p("/123"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_STREQ("123", p.GetTokens()[0].name); EXPECT_EQ(123u, p.GetTokens()[0].index); } { // Invalid index (with leading zero) Pointer p("/01"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_STREQ("01", p.GetTokens()[0].name); EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); } if (sizeof(SizeType) == 4) { // Invalid index (overflow) Pointer p("/4294967296"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_STREQ("4294967296", p.GetTokens()[0].name); EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); } { // kPointerParseErrorTokenMustBeginWithSolidus Pointer p(" "); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorTokenMustBeginWithSolidus, p.GetParseErrorCode()); EXPECT_EQ(0u, p.GetParseErrorOffset()); } { // kPointerParseErrorInvalidEscape Pointer p("/~"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorInvalidEscape, p.GetParseErrorCode()); EXPECT_EQ(2u, p.GetParseErrorOffset()); } { // kPointerParseErrorInvalidEscape Pointer p("/~2"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorInvalidEscape, p.GetParseErrorCode()); EXPECT_EQ(2u, p.GetParseErrorOffset()); } } TEST(Pointer, Parse_URIFragment) { { Pointer p("#"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(0u, p.GetTokenCount()); } { Pointer p("#/foo"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("foo", p.GetTokens()[0].name); } { Pointer p("#/foo/0"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(2u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("foo", p.GetTokens()[0].name); EXPECT_EQ(1u, p.GetTokens()[1].length); EXPECT_STREQ("0", p.GetTokens()[1].name); EXPECT_EQ(0u, p.GetTokens()[1].index); } { // Unescape ~1 Pointer p("#/a~1b"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("a/b", p.GetTokens()[0].name); } { // Unescape ~0 Pointer p("#/m~0n"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("m~n", p.GetTokens()[0].name); } { // empty name Pointer p("#/"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(0u, p.GetTokens()[0].length); EXPECT_STREQ("", p.GetTokens()[0].name); } { // empty and non-empty name Pointer p("#//a"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(2u, p.GetTokenCount()); EXPECT_EQ(0u, p.GetTokens()[0].length); EXPECT_STREQ("", p.GetTokens()[0].name); EXPECT_EQ(1u, p.GetTokens()[1].length); EXPECT_STREQ("a", p.GetTokens()[1].name); } { // Null characters Pointer p("#/%00%00"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(2u, p.GetTokens()[0].length); EXPECT_EQ('\0', p.GetTokens()[0].name[0]); EXPECT_EQ('\0', p.GetTokens()[0].name[1]); EXPECT_EQ('\0', p.GetTokens()[0].name[2]); } { // Percentage Escapes EXPECT_STREQ("c%d", Pointer("#/c%25d").GetTokens()[0].name); EXPECT_STREQ("e^f", Pointer("#/e%5Ef").GetTokens()[0].name); EXPECT_STREQ("g|h", Pointer("#/g%7Ch").GetTokens()[0].name); EXPECT_STREQ("i\\j", Pointer("#/i%5Cj").GetTokens()[0].name); EXPECT_STREQ("k\"l", Pointer("#/k%22l").GetTokens()[0].name); EXPECT_STREQ(" ", Pointer("#/%20").GetTokens()[0].name); } { // Valid index Pointer p("#/123"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_STREQ("123", p.GetTokens()[0].name); EXPECT_EQ(123u, p.GetTokens()[0].index); } { // Invalid index (with leading zero) Pointer p("#/01"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_STREQ("01", p.GetTokens()[0].name); EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); } if (sizeof(SizeType) == 4) { // Invalid index (overflow) Pointer p("#/4294967296"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_STREQ("4294967296", p.GetTokens()[0].name); EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); } { // Decode UTF-8 perecent encoding to UTF-8 Pointer p("#/%C2%A2"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_STREQ("\xC2\xA2", p.GetTokens()[0].name); } { // Decode UTF-8 perecent encoding to UTF-16 GenericPointer<GenericValue<UTF16<> > > p(L"#/%C2%A2"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(static_cast<UTF16<>::Ch>(0x00A2), p.GetTokens()[0].name[0]); EXPECT_EQ(1u, p.GetTokens()[0].length); } { // Decode UTF-8 perecent encoding to UTF-16 GenericPointer<GenericValue<UTF16<> > > p(L"#/%E2%82%AC"); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(1u, p.GetTokenCount()); EXPECT_EQ(static_cast<UTF16<>::Ch>(0x20AC), p.GetTokens()[0].name[0]); EXPECT_EQ(1u, p.GetTokens()[0].length); } { // kPointerParseErrorTokenMustBeginWithSolidus Pointer p("# "); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorTokenMustBeginWithSolidus, p.GetParseErrorCode()); EXPECT_EQ(1u, p.GetParseErrorOffset()); } { // kPointerParseErrorInvalidEscape Pointer p("#/~"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorInvalidEscape, p.GetParseErrorCode()); EXPECT_EQ(3u, p.GetParseErrorOffset()); } { // kPointerParseErrorInvalidEscape Pointer p("#/~2"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorInvalidEscape, p.GetParseErrorCode()); EXPECT_EQ(3u, p.GetParseErrorOffset()); } { // kPointerParseErrorInvalidPercentEncoding Pointer p("#/%"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorInvalidPercentEncoding, p.GetParseErrorCode()); EXPECT_EQ(2u, p.GetParseErrorOffset()); } { // kPointerParseErrorInvalidPercentEncoding (invalid hex) Pointer p("#/%g0"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorInvalidPercentEncoding, p.GetParseErrorCode()); EXPECT_EQ(2u, p.GetParseErrorOffset()); } { // kPointerParseErrorInvalidPercentEncoding (invalid hex) Pointer p("#/%0g"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorInvalidPercentEncoding, p.GetParseErrorCode()); EXPECT_EQ(2u, p.GetParseErrorOffset()); } { // kPointerParseErrorInvalidPercentEncoding (incomplete UTF-8 sequence) Pointer p("#/%C2"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorInvalidPercentEncoding, p.GetParseErrorCode()); EXPECT_EQ(2u, p.GetParseErrorOffset()); } { // kPointerParseErrorCharacterMustPercentEncode Pointer p("#/ "); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorCharacterMustPercentEncode, p.GetParseErrorCode()); EXPECT_EQ(2u, p.GetParseErrorOffset()); } { // kPointerParseErrorCharacterMustPercentEncode Pointer p("#/\n"); EXPECT_FALSE(p.IsValid()); EXPECT_EQ(kPointerParseErrorCharacterMustPercentEncode, p.GetParseErrorCode()); EXPECT_EQ(2u, p.GetParseErrorOffset()); } } TEST(Pointer, Stringify) { // Test by roundtrip const char* sources[] = { "", "/foo", "/foo/0", "/", "/a~1b", "/c%d", "/e^f", "/g|h", "/i\\j", "/k\"l", "/ ", "/m~0n", "/\xC2\xA2", "/\xE2\x82\xAC", "/\xF0\x9D\x84\x9E" }; for (size_t i = 0; i < sizeof(sources) / sizeof(sources[0]); i++) { Pointer p(sources[i]); StringBuffer s; EXPECT_TRUE(p.Stringify(s)); EXPECT_STREQ(sources[i], s.GetString()); // Stringify to URI fragment StringBuffer s2; EXPECT_TRUE(p.StringifyUriFragment(s2)); Pointer p2(s2.GetString(), s2.GetSize()); EXPECT_TRUE(p2.IsValid()); EXPECT_TRUE(p == p2); } { // Strigify to URI fragment with an invalid UTF-8 sequence Pointer p("/\xC2"); StringBuffer s; EXPECT_FALSE(p.StringifyUriFragment(s)); } } // Construct a Pointer with static tokens, no dynamic allocation involved. #define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex } #define INDEX(i) { #i, sizeof(#i) - 1, i } static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(0) }; // equivalent to "/foo/0" #undef NAME #undef INDEX TEST(Pointer, ConstructorWithToken) { Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); EXPECT_TRUE(p.IsValid()); EXPECT_EQ(2u, p.GetTokenCount()); EXPECT_EQ(3u, p.GetTokens()[0].length); EXPECT_STREQ("foo", p.GetTokens()[0].name); EXPECT_EQ(1u, p.GetTokens()[1].length); EXPECT_STREQ("0", p.GetTokens()[1].name); EXPECT_EQ(0u, p.GetTokens()[1].index); } TEST(Pointer, CopyConstructor) { { Pointer p("/foo/0"); Pointer q(p); EXPECT_TRUE(q.IsValid()); EXPECT_EQ(2u, q.GetTokenCount()); EXPECT_EQ(3u, q.GetTokens()[0].length); EXPECT_STREQ("foo", q.GetTokens()[0].name); EXPECT_EQ(1u, q.GetTokens()[1].length); EXPECT_STREQ("0", q.GetTokens()[1].name); EXPECT_EQ(0u, q.GetTokens()[1].index); } // Static tokens { Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); Pointer q(p); EXPECT_TRUE(q.IsValid()); EXPECT_EQ(2u, q.GetTokenCount()); EXPECT_EQ(3u, q.GetTokens()[0].length); EXPECT_STREQ("foo", q.GetTokens()[0].name); EXPECT_EQ(1u, q.GetTokens()[1].length); EXPECT_STREQ("0", q.GetTokens()[1].name); EXPECT_EQ(0u, q.GetTokens()[1].index); } } TEST(Pointer, Assignment) { { Pointer p("/foo/0"); Pointer q; q = p; EXPECT_TRUE(q.IsValid()); EXPECT_EQ(2u, q.GetTokenCount()); EXPECT_EQ(3u, q.GetTokens()[0].length); EXPECT_STREQ("foo", q.GetTokens()[0].name); EXPECT_EQ(1u, q.GetTokens()[1].length); EXPECT_STREQ("0", q.GetTokens()[1].name); EXPECT_EQ(0u, q.GetTokens()[1].index); q = q; EXPECT_TRUE(q.IsValid()); EXPECT_EQ(2u, q.GetTokenCount()); EXPECT_EQ(3u, q.GetTokens()[0].length); EXPECT_STREQ("foo", q.GetTokens()[0].name); EXPECT_EQ(1u, q.GetTokens()[1].length); EXPECT_STREQ("0", q.GetTokens()[1].name); EXPECT_EQ(0u, q.GetTokens()[1].index); } // Static tokens { Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); Pointer q; q = p; EXPECT_TRUE(q.IsValid()); EXPECT_EQ(2u, q.GetTokenCount()); EXPECT_EQ(3u, q.GetTokens()[0].length); EXPECT_STREQ("foo", q.GetTokens()[0].name); EXPECT_EQ(1u, q.GetTokens()[1].length); EXPECT_STREQ("0", q.GetTokens()[1].name); EXPECT_EQ(0u, q.GetTokens()[1].index); } } TEST(Pointer, Append) { { Pointer p; Pointer q = p.Append("foo"); EXPECT_TRUE(Pointer("/foo") == q); q = q.Append(1234); EXPECT_TRUE(Pointer("/foo/1234") == q); q = q.Append(""); EXPECT_TRUE(Pointer("/foo/1234/") == q); } { Pointer p; Pointer q = p.Append(Value("foo").Move()); EXPECT_TRUE(Pointer("/foo") == q); q = q.Append(Value(1234).Move()); EXPECT_TRUE(Pointer("/foo/1234") == q); q = q.Append(Value(kStringType).Move()); EXPECT_TRUE(Pointer("/foo/1234/") == q); } #if RAPIDJSON_HAS_STDSTRING { Pointer p; Pointer q = p.Append(std::string("foo")); EXPECT_TRUE(Pointer("/foo") == q); } #endif } TEST(Pointer, Equality) { EXPECT_TRUE(Pointer("/foo/0") == Pointer("/foo/0")); EXPECT_FALSE(Pointer("/foo/0") == Pointer("/foo/1")); EXPECT_FALSE(Pointer("/foo/0") == Pointer("/foo/0/1")); EXPECT_FALSE(Pointer("/foo/0") == Pointer("a")); EXPECT_FALSE(Pointer("a") == Pointer("a")); // Invalid always not equal } TEST(Pointer, Inequality) { EXPECT_FALSE(Pointer("/foo/0") != Pointer("/foo/0")); EXPECT_TRUE(Pointer("/foo/0") != Pointer("/foo/1")); EXPECT_TRUE(Pointer("/foo/0") != Pointer("/foo/0/1")); EXPECT_TRUE(Pointer("/foo/0") != Pointer("a")); EXPECT_TRUE(Pointer("a") != Pointer("a")); // Invalid always not equal } TEST(Pointer, Create) { Document d; { Value* v = &Pointer("").Create(d, d.GetAllocator()); EXPECT_EQ(&d, v); } { Value* v = &Pointer("/foo").Create(d, d.GetAllocator()); EXPECT_EQ(&d["foo"], v); } { Value* v = &Pointer("/foo/0").Create(d, d.GetAllocator()); EXPECT_EQ(&d["foo"][0], v); } { Value* v = &Pointer("/foo/-").Create(d, d.GetAllocator()); EXPECT_EQ(&d["foo"][1], v); } { Value* v = &Pointer("/foo/-/-").Create(d, d.GetAllocator()); // "foo/-" is a newly created null value x. // "foo/-/-" finds that x is not an array, it converts x to empty object // and treats - as "-" member name EXPECT_EQ(&d["foo"][2]["-"], v); } { // Document with no allocator Value* v = &Pointer("/foo/-").Create(d); EXPECT_EQ(&d["foo"][3], v); } { // Value (not document) must give allocator Value* v = &Pointer("/-").Create(d["foo"], d.GetAllocator()); EXPECT_EQ(&d["foo"][4], v); } } TEST(Pointer, Get) { Document d; d.Parse(kJson); EXPECT_EQ(&d, Pointer("").Get(d)); EXPECT_EQ(&d["foo"], Pointer("/foo").Get(d)); EXPECT_EQ(&d["foo"][0], Pointer("/foo/0").Get(d)); EXPECT_EQ(&d[""], Pointer("/").Get(d)); EXPECT_EQ(&d["a/b"], Pointer("/a~1b").Get(d)); EXPECT_EQ(&d["c%d"], Pointer("/c%d").Get(d)); EXPECT_EQ(&d["e^f"], Pointer("/e^f").Get(d)); EXPECT_EQ(&d["g|h"], Pointer("/g|h").Get(d)); EXPECT_EQ(&d["i\\j"], Pointer("/i\\j").Get(d)); EXPECT_EQ(&d["k\"l"], Pointer("/k\"l").Get(d)); EXPECT_EQ(&d[" "], Pointer("/ ").Get(d)); EXPECT_EQ(&d["m~n"], Pointer("/m~0n").Get(d)); EXPECT_TRUE(Pointer("/abc").Get(d) == 0); size_t unresolvedTokenIndex; EXPECT_TRUE(Pointer("/foo/2").Get(d, &unresolvedTokenIndex) == 0); // Out of boundary EXPECT_EQ(1, unresolvedTokenIndex); EXPECT_TRUE(Pointer("/foo/a").Get(d, &unresolvedTokenIndex) == 0); // "/foo" is an array, cannot query by "a" EXPECT_EQ(1, unresolvedTokenIndex); EXPECT_TRUE(Pointer("/foo/0/0").Get(d, &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query EXPECT_EQ(2, unresolvedTokenIndex); EXPECT_TRUE(Pointer("/foo/0/a").Get(d, &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query EXPECT_EQ(2, unresolvedTokenIndex); } TEST(Pointer, GetWithDefault) { Document d; d.Parse(kJson); // Value version Document::AllocatorType& a = d.GetAllocator(); const Value v("qux"); EXPECT_TRUE(Value("bar") == Pointer("/foo/0").GetWithDefault(d, v, a)); EXPECT_TRUE(Value("baz") == Pointer("/foo/1").GetWithDefault(d, v, a)); EXPECT_TRUE(Value("qux") == Pointer("/foo/2").GetWithDefault(d, v, a)); EXPECT_TRUE(Value("last") == Pointer("/foo/-").GetWithDefault(d, Value("last").Move(), a)); EXPECT_STREQ("last", d["foo"][3].GetString()); EXPECT_TRUE(Pointer("/foo/null").GetWithDefault(d, Value().Move(), a).IsNull()); EXPECT_TRUE(Pointer("/foo/null").GetWithDefault(d, "x", a).IsNull()); // Generic version EXPECT_EQ(-1, Pointer("/foo/int").GetWithDefault(d, -1, a).GetInt()); EXPECT_EQ(-1, Pointer("/foo/int").GetWithDefault(d, -2, a).GetInt()); EXPECT_EQ(0x87654321, Pointer("/foo/uint").GetWithDefault(d, 0x87654321, a).GetUint()); EXPECT_EQ(0x87654321, Pointer("/foo/uint").GetWithDefault(d, 0x12345678, a).GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); EXPECT_EQ(i64, Pointer("/foo/int64").GetWithDefault(d, i64, a).GetInt64()); EXPECT_EQ(i64, Pointer("/foo/int64").GetWithDefault(d, i64 + 1, a).GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); EXPECT_EQ(u64, Pointer("/foo/uint64").GetWithDefault(d, u64, a).GetUint64()); EXPECT_EQ(u64, Pointer("/foo/uint64").GetWithDefault(d, u64 - 1, a).GetUint64()); EXPECT_TRUE(Pointer("/foo/true").GetWithDefault(d, true, a).IsTrue()); EXPECT_TRUE(Pointer("/foo/true").GetWithDefault(d, false, a).IsTrue()); EXPECT_TRUE(Pointer("/foo/false").GetWithDefault(d, false, a).IsFalse()); EXPECT_TRUE(Pointer("/foo/false").GetWithDefault(d, true, a).IsFalse()); // StringRef version EXPECT_STREQ("Hello", Pointer("/foo/hello").GetWithDefault(d, "Hello", a).GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); EXPECT_STREQ("World", Pointer("/foo/world").GetWithDefault(d, buffer, a).GetString()); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING EXPECT_STREQ("C++", Pointer("/foo/C++").GetWithDefault(d, std::string("C++"), a).GetString()); #endif } TEST(Pointer, GetWithDefault_NoAllocator) { Document d; d.Parse(kJson); // Value version const Value v("qux"); EXPECT_TRUE(Value("bar") == Pointer("/foo/0").GetWithDefault(d, v)); EXPECT_TRUE(Value("baz") == Pointer("/foo/1").GetWithDefault(d, v)); EXPECT_TRUE(Value("qux") == Pointer("/foo/2").GetWithDefault(d, v)); EXPECT_TRUE(Value("last") == Pointer("/foo/-").GetWithDefault(d, Value("last").Move())); EXPECT_STREQ("last", d["foo"][3].GetString()); EXPECT_TRUE(Pointer("/foo/null").GetWithDefault(d, Value().Move()).IsNull()); EXPECT_TRUE(Pointer("/foo/null").GetWithDefault(d, "x").IsNull()); // Generic version EXPECT_EQ(-1, Pointer("/foo/int").GetWithDefault(d, -1).GetInt()); EXPECT_EQ(-1, Pointer("/foo/int").GetWithDefault(d, -2).GetInt()); EXPECT_EQ(0x87654321, Pointer("/foo/uint").GetWithDefault(d, 0x87654321).GetUint()); EXPECT_EQ(0x87654321, Pointer("/foo/uint").GetWithDefault(d, 0x12345678).GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); EXPECT_EQ(i64, Pointer("/foo/int64").GetWithDefault(d, i64).GetInt64()); EXPECT_EQ(i64, Pointer("/foo/int64").GetWithDefault(d, i64 + 1).GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); EXPECT_EQ(u64, Pointer("/foo/uint64").GetWithDefault(d, u64).GetUint64()); EXPECT_EQ(u64, Pointer("/foo/uint64").GetWithDefault(d, u64 - 1).GetUint64()); EXPECT_TRUE(Pointer("/foo/true").GetWithDefault(d, true).IsTrue()); EXPECT_TRUE(Pointer("/foo/true").GetWithDefault(d, false).IsTrue()); EXPECT_TRUE(Pointer("/foo/false").GetWithDefault(d, false).IsFalse()); EXPECT_TRUE(Pointer("/foo/false").GetWithDefault(d, true).IsFalse()); // StringRef version EXPECT_STREQ("Hello", Pointer("/foo/hello").GetWithDefault(d, "Hello").GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); EXPECT_STREQ("World", Pointer("/foo/world").GetWithDefault(d, buffer).GetString()); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING EXPECT_STREQ("C++", Pointer("/foo/C++").GetWithDefault(d, std::string("C++")).GetString()); #endif } TEST(Pointer, Set) { Document d; d.Parse(kJson); Document::AllocatorType& a = d.GetAllocator(); // Value version Pointer("/foo/0").Set(d, Value(123).Move(), a); EXPECT_EQ(123, d["foo"][0].GetInt()); Pointer("/foo/-").Set(d, Value(456).Move(), a); EXPECT_EQ(456, d["foo"][2].GetInt()); Pointer("/foo/null").Set(d, Value().Move(), a); EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); // Const Value version const Value foo(d["foo"], a); Pointer("/clone").Set(d, foo, a); EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); // Generic version Pointer("/foo/int").Set(d, -1, a); EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); Pointer("/foo/uint").Set(d, 0x87654321, a); EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); Pointer("/foo/int64").Set(d, i64, a); EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); Pointer("/foo/uint64").Set(d, u64, a); EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); Pointer("/foo/true").Set(d, true, a); EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); Pointer("/foo/false").Set(d, false, a); EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); // StringRef version Pointer("/foo/hello").Set(d, "Hello", a); EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); Pointer("/foo/world").Set(d, buffer, a); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING Pointer("/foo/c++").Set(d, std::string("C++"), a); EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); #endif } TEST(Pointer, Set_NoAllocator) { Document d; d.Parse(kJson); // Value version Pointer("/foo/0").Set(d, Value(123).Move()); EXPECT_EQ(123, d["foo"][0].GetInt()); Pointer("/foo/-").Set(d, Value(456).Move()); EXPECT_EQ(456, d["foo"][2].GetInt()); Pointer("/foo/null").Set(d, Value().Move()); EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); // Const Value version const Value foo(d["foo"], d.GetAllocator()); Pointer("/clone").Set(d, foo); EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); // Generic version Pointer("/foo/int").Set(d, -1); EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); Pointer("/foo/uint").Set(d, 0x87654321); EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); Pointer("/foo/int64").Set(d, i64); EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); Pointer("/foo/uint64").Set(d, u64); EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); Pointer("/foo/true").Set(d, true); EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); Pointer("/foo/false").Set(d, false); EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); // StringRef version Pointer("/foo/hello").Set(d, "Hello"); EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); Pointer("/foo/world").Set(d, buffer); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING Pointer("/foo/c++").Set(d, std::string("C++")); EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); #endif } TEST(Pointer, Swap) { Document d; d.Parse(kJson); Document::AllocatorType& a = d.GetAllocator(); Pointer("/foo/0").Swap(d, *Pointer("/foo/1").Get(d), a); EXPECT_STREQ("baz", d["foo"][0].GetString()); EXPECT_STREQ("bar", d["foo"][1].GetString()); } TEST(Pointer, Swap_NoAllocator) { Document d; d.Parse(kJson); Pointer("/foo/0").Swap(d, *Pointer("/foo/1").Get(d)); EXPECT_STREQ("baz", d["foo"][0].GetString()); EXPECT_STREQ("bar", d["foo"][1].GetString()); } TEST(Pointer, Erase) { Document d; d.Parse(kJson); EXPECT_FALSE(Pointer("").Erase(d)); EXPECT_FALSE(Pointer("/nonexist").Erase(d)); EXPECT_FALSE(Pointer("/nonexist/nonexist").Erase(d)); EXPECT_FALSE(Pointer("/foo/nonexist").Erase(d)); EXPECT_FALSE(Pointer("/foo/nonexist/nonexist").Erase(d)); EXPECT_FALSE(Pointer("/foo/0/nonexist").Erase(d)); EXPECT_FALSE(Pointer("/foo/0/nonexist/nonexist").Erase(d)); EXPECT_FALSE(Pointer("/foo/2/nonexist").Erase(d)); EXPECT_TRUE(Pointer("/foo/0").Erase(d)); EXPECT_EQ(1u, d["foo"].Size()); EXPECT_STREQ("baz", d["foo"][0].GetString()); EXPECT_TRUE(Pointer("/foo/0").Erase(d)); EXPECT_TRUE(d["foo"].Empty()); EXPECT_TRUE(Pointer("/foo").Erase(d)); EXPECT_TRUE(Pointer("/foo").Get(d) == 0); Pointer("/a/0/b/0").Create(d); EXPECT_TRUE(Pointer("/a/0/b/0").Get(d) != 0); EXPECT_TRUE(Pointer("/a/0/b/0").Erase(d)); EXPECT_TRUE(Pointer("/a/0/b/0").Get(d) == 0); EXPECT_TRUE(Pointer("/a/0/b").Get(d) != 0); EXPECT_TRUE(Pointer("/a/0/b").Erase(d)); EXPECT_TRUE(Pointer("/a/0/b").Get(d) == 0); EXPECT_TRUE(Pointer("/a/0").Get(d) != 0); EXPECT_TRUE(Pointer("/a/0").Erase(d)); EXPECT_TRUE(Pointer("/a/0").Get(d) == 0); EXPECT_TRUE(Pointer("/a").Get(d) != 0); EXPECT_TRUE(Pointer("/a").Erase(d)); EXPECT_TRUE(Pointer("/a").Get(d) == 0); } TEST(Pointer, CreateValueByPointer) { Document d; Document::AllocatorType& a = d.GetAllocator(); { Value& v = CreateValueByPointer(d, Pointer("/foo/0"), a); EXPECT_EQ(&d["foo"][0], &v); } { Value& v = CreateValueByPointer(d, "/foo/1", a); EXPECT_EQ(&d["foo"][1], &v); } } TEST(Pointer, CreateValueByPointer_NoAllocator) { Document d; { Value& v = CreateValueByPointer(d, Pointer("/foo/0")); EXPECT_EQ(&d["foo"][0], &v); } { Value& v = CreateValueByPointer(d, "/foo/1"); EXPECT_EQ(&d["foo"][1], &v); } } TEST(Pointer, GetValueByPointer) { Document d; d.Parse(kJson); EXPECT_EQ(&d["foo"][0], GetValueByPointer(d, Pointer("/foo/0"))); EXPECT_EQ(&d["foo"][0], GetValueByPointer(d, "/foo/0")); size_t unresolvedTokenIndex; EXPECT_TRUE(GetValueByPointer(d, "/foo/2", &unresolvedTokenIndex) == 0); // Out of boundary EXPECT_EQ(1, unresolvedTokenIndex); EXPECT_TRUE(GetValueByPointer(d, "/foo/a", &unresolvedTokenIndex) == 0); // "/foo" is an array, cannot query by "a" EXPECT_EQ(1, unresolvedTokenIndex); EXPECT_TRUE(GetValueByPointer(d, "/foo/0/0", &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query EXPECT_EQ(2, unresolvedTokenIndex); EXPECT_TRUE(GetValueByPointer(d, "/foo/0/a", &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query EXPECT_EQ(2, unresolvedTokenIndex); // const version const Value& v = d; EXPECT_EQ(&d["foo"][0], GetValueByPointer(v, Pointer("/foo/0"))); EXPECT_EQ(&d["foo"][0], GetValueByPointer(v, "/foo/0")); EXPECT_TRUE(GetValueByPointer(v, "/foo/2", &unresolvedTokenIndex) == 0); // Out of boundary EXPECT_EQ(1, unresolvedTokenIndex); EXPECT_TRUE(GetValueByPointer(v, "/foo/a", &unresolvedTokenIndex) == 0); // "/foo" is an array, cannot query by "a" EXPECT_EQ(1, unresolvedTokenIndex); EXPECT_TRUE(GetValueByPointer(v, "/foo/0/0", &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query EXPECT_EQ(2, unresolvedTokenIndex); EXPECT_TRUE(GetValueByPointer(v, "/foo/0/a", &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query EXPECT_EQ(2, unresolvedTokenIndex); } TEST(Pointer, GetValueByPointerWithDefault_Pointer) { Document d; d.Parse(kJson); Document::AllocatorType& a = d.GetAllocator(); const Value v("qux"); EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, Pointer("/foo/0"), v, a)); EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, Pointer("/foo/0"), v, a)); EXPECT_TRUE(Value("baz") == GetValueByPointerWithDefault(d, Pointer("/foo/1"), v, a)); EXPECT_TRUE(Value("qux") == GetValueByPointerWithDefault(d, Pointer("/foo/2"), v, a)); EXPECT_TRUE(Value("last") == GetValueByPointerWithDefault(d, Pointer("/foo/-"), Value("last").Move(), a)); EXPECT_STREQ("last", d["foo"][3].GetString()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/null"), Value().Move(), a).IsNull()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/null"), "x", a).IsNull()); // Generic version EXPECT_EQ(-1, GetValueByPointerWithDefault(d, Pointer("/foo/int"), -1, a).GetInt()); EXPECT_EQ(-1, GetValueByPointerWithDefault(d, Pointer("/foo/int"), -2, a).GetInt()); EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, Pointer("/foo/uint"), 0x87654321, a).GetUint()); EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, Pointer("/foo/uint"), 0x12345678, a).GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); EXPECT_EQ(i64, GetValueByPointerWithDefault(d, Pointer("/foo/int64"), i64, a).GetInt64()); EXPECT_EQ(i64, GetValueByPointerWithDefault(d, Pointer("/foo/int64"), i64 + 1, a).GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); EXPECT_EQ(u64, GetValueByPointerWithDefault(d, Pointer("/foo/uint64"), u64, a).GetUint64()); EXPECT_EQ(u64, GetValueByPointerWithDefault(d, Pointer("/foo/uint64"), u64 - 1, a).GetUint64()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/true"), true, a).IsTrue()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/true"), false, a).IsTrue()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/false"), false, a).IsFalse()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/false"), true, a).IsFalse()); // StringRef version EXPECT_STREQ("Hello", GetValueByPointerWithDefault(d, Pointer("/foo/hello"), "Hello", a).GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); EXPECT_STREQ("World", GetValueByPointerWithDefault(d, Pointer("/foo/world"), buffer, a).GetString()); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, Pointer("/foo/world"))->GetString()); #if RAPIDJSON_HAS_STDSTRING EXPECT_STREQ("C++", GetValueByPointerWithDefault(d, Pointer("/foo/C++"), std::string("C++"), a).GetString()); #endif } TEST(Pointer, GetValueByPointerWithDefault_String) { Document d; d.Parse(kJson); Document::AllocatorType& a = d.GetAllocator(); const Value v("qux"); EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, "/foo/0", v, a)); EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, "/foo/0", v, a)); EXPECT_TRUE(Value("baz") == GetValueByPointerWithDefault(d, "/foo/1", v, a)); EXPECT_TRUE(Value("qux") == GetValueByPointerWithDefault(d, "/foo/2", v, a)); EXPECT_TRUE(Value("last") == GetValueByPointerWithDefault(d, "/foo/-", Value("last").Move(), a)); EXPECT_STREQ("last", d["foo"][3].GetString()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/null", Value().Move(), a).IsNull()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/null", "x", a).IsNull()); // Generic version EXPECT_EQ(-1, GetValueByPointerWithDefault(d, "/foo/int", -1, a).GetInt()); EXPECT_EQ(-1, GetValueByPointerWithDefault(d, "/foo/int", -2, a).GetInt()); EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, "/foo/uint", 0x87654321, a).GetUint()); EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, "/foo/uint", 0x12345678, a).GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); EXPECT_EQ(i64, GetValueByPointerWithDefault(d, "/foo/int64", i64, a).GetInt64()); EXPECT_EQ(i64, GetValueByPointerWithDefault(d, "/foo/int64", i64 + 1, a).GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); EXPECT_EQ(u64, GetValueByPointerWithDefault(d, "/foo/uint64", u64, a).GetUint64()); EXPECT_EQ(u64, GetValueByPointerWithDefault(d, "/foo/uint64", u64 - 1, a).GetUint64()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/true", true, a).IsTrue()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/true", false, a).IsTrue()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/false", false, a).IsFalse()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/false", true, a).IsFalse()); // StringRef version EXPECT_STREQ("Hello", GetValueByPointerWithDefault(d, "/foo/hello", "Hello", a).GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); EXPECT_STREQ("World", GetValueByPointerWithDefault(d, "/foo/world", buffer, a).GetString()); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING EXPECT_STREQ("C++", GetValueByPointerWithDefault(d, "/foo/C++", std::string("C++"), a).GetString()); #endif } TEST(Pointer, GetValueByPointerWithDefault_Pointer_NoAllocator) { Document d; d.Parse(kJson); const Value v("qux"); EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, Pointer("/foo/0"), v)); EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, Pointer("/foo/0"), v)); EXPECT_TRUE(Value("baz") == GetValueByPointerWithDefault(d, Pointer("/foo/1"), v)); EXPECT_TRUE(Value("qux") == GetValueByPointerWithDefault(d, Pointer("/foo/2"), v)); EXPECT_TRUE(Value("last") == GetValueByPointerWithDefault(d, Pointer("/foo/-"), Value("last").Move())); EXPECT_STREQ("last", d["foo"][3].GetString()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/null"), Value().Move()).IsNull()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/null"), "x").IsNull()); // Generic version EXPECT_EQ(-1, GetValueByPointerWithDefault(d, Pointer("/foo/int"), -1).GetInt()); EXPECT_EQ(-1, GetValueByPointerWithDefault(d, Pointer("/foo/int"), -2).GetInt()); EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, Pointer("/foo/uint"), 0x87654321).GetUint()); EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, Pointer("/foo/uint"), 0x12345678).GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); EXPECT_EQ(i64, GetValueByPointerWithDefault(d, Pointer("/foo/int64"), i64).GetInt64()); EXPECT_EQ(i64, GetValueByPointerWithDefault(d, Pointer("/foo/int64"), i64 + 1).GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); EXPECT_EQ(u64, GetValueByPointerWithDefault(d, Pointer("/foo/uint64"), u64).GetUint64()); EXPECT_EQ(u64, GetValueByPointerWithDefault(d, Pointer("/foo/uint64"), u64 - 1).GetUint64()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/true"), true).IsTrue()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/true"), false).IsTrue()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/false"), false).IsFalse()); EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/false"), true).IsFalse()); // StringRef version EXPECT_STREQ("Hello", GetValueByPointerWithDefault(d, Pointer("/foo/hello"), "Hello").GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); EXPECT_STREQ("World", GetValueByPointerWithDefault(d, Pointer("/foo/world"), buffer).GetString()); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, Pointer("/foo/world"))->GetString()); #if RAPIDJSON_HAS_STDSTRING EXPECT_STREQ("C++", GetValueByPointerWithDefault(d, Pointer("/foo/C++"), std::string("C++")).GetString()); #endif } TEST(Pointer, GetValueByPointerWithDefault_String_NoAllocator) { Document d; d.Parse(kJson); const Value v("qux"); EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, "/foo/0", v)); EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, "/foo/0", v)); EXPECT_TRUE(Value("baz") == GetValueByPointerWithDefault(d, "/foo/1", v)); EXPECT_TRUE(Value("qux") == GetValueByPointerWithDefault(d, "/foo/2", v)); EXPECT_TRUE(Value("last") == GetValueByPointerWithDefault(d, "/foo/-", Value("last").Move())); EXPECT_STREQ("last", d["foo"][3].GetString()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/null", Value().Move()).IsNull()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/null", "x").IsNull()); // Generic version EXPECT_EQ(-1, GetValueByPointerWithDefault(d, "/foo/int", -1).GetInt()); EXPECT_EQ(-1, GetValueByPointerWithDefault(d, "/foo/int", -2).GetInt()); EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, "/foo/uint", 0x87654321).GetUint()); EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, "/foo/uint", 0x12345678).GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); EXPECT_EQ(i64, GetValueByPointerWithDefault(d, "/foo/int64", i64).GetInt64()); EXPECT_EQ(i64, GetValueByPointerWithDefault(d, "/foo/int64", i64 + 1).GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); EXPECT_EQ(u64, GetValueByPointerWithDefault(d, "/foo/uint64", u64).GetUint64()); EXPECT_EQ(u64, GetValueByPointerWithDefault(d, "/foo/uint64", u64 - 1).GetUint64()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/true", true).IsTrue()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/true", false).IsTrue()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/false", false).IsFalse()); EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/false", true).IsFalse()); // StringRef version EXPECT_STREQ("Hello", GetValueByPointerWithDefault(d, "/foo/hello", "Hello").GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); EXPECT_STREQ("World", GetValueByPointerWithDefault(d, "/foo/world", buffer).GetString()); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING EXPECT_STREQ("C++", GetValueByPointerWithDefault(d, Pointer("/foo/C++"), std::string("C++")).GetString()); #endif } TEST(Pointer, SetValueByPointer_Pointer) { Document d; d.Parse(kJson); Document::AllocatorType& a = d.GetAllocator(); // Value version SetValueByPointer(d, Pointer("/foo/0"), Value(123).Move(), a); EXPECT_EQ(123, d["foo"][0].GetInt()); SetValueByPointer(d, Pointer("/foo/null"), Value().Move(), a); EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); // Const Value version const Value foo(d["foo"], d.GetAllocator()); SetValueByPointer(d, Pointer("/clone"), foo, a); EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); // Generic version SetValueByPointer(d, Pointer("/foo/int"), -1, a); EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); SetValueByPointer(d, Pointer("/foo/uint"), 0x87654321, a); EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); SetValueByPointer(d, Pointer("/foo/int64"), i64, a); EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); SetValueByPointer(d, Pointer("/foo/uint64"), u64, a); EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); SetValueByPointer(d, Pointer("/foo/true"), true, a); EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); SetValueByPointer(d, Pointer("/foo/false"), false, a); EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); // StringRef version SetValueByPointer(d, Pointer("/foo/hello"), "Hello", a); EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); SetValueByPointer(d, Pointer("/foo/world"), buffer, a); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING SetValueByPointer(d, Pointer("/foo/c++"), std::string("C++"), a); EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); #endif } TEST(Pointer, SetValueByPointer_String) { Document d; d.Parse(kJson); Document::AllocatorType& a = d.GetAllocator(); // Value version SetValueByPointer(d, "/foo/0", Value(123).Move(), a); EXPECT_EQ(123, d["foo"][0].GetInt()); SetValueByPointer(d, "/foo/null", Value().Move(), a); EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); // Const Value version const Value foo(d["foo"], d.GetAllocator()); SetValueByPointer(d, "/clone", foo, a); EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); // Generic version SetValueByPointer(d, "/foo/int", -1, a); EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); SetValueByPointer(d, "/foo/uint", 0x87654321, a); EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); SetValueByPointer(d, "/foo/int64", i64, a); EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); SetValueByPointer(d, "/foo/uint64", u64, a); EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); SetValueByPointer(d, "/foo/true", true, a); EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); SetValueByPointer(d, "/foo/false", false, a); EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); // StringRef version SetValueByPointer(d, "/foo/hello", "Hello", a); EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); SetValueByPointer(d, "/foo/world", buffer, a); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING SetValueByPointer(d, "/foo/c++", std::string("C++"), a); EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); #endif } TEST(Pointer, SetValueByPointer_Pointer_NoAllocator) { Document d; d.Parse(kJson); // Value version SetValueByPointer(d, Pointer("/foo/0"), Value(123).Move()); EXPECT_EQ(123, d["foo"][0].GetInt()); SetValueByPointer(d, Pointer("/foo/null"), Value().Move()); EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); // Const Value version const Value foo(d["foo"], d.GetAllocator()); SetValueByPointer(d, Pointer("/clone"), foo); EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); // Generic version SetValueByPointer(d, Pointer("/foo/int"), -1); EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); SetValueByPointer(d, Pointer("/foo/uint"), 0x87654321); EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); SetValueByPointer(d, Pointer("/foo/int64"), i64); EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); SetValueByPointer(d, Pointer("/foo/uint64"), u64); EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); SetValueByPointer(d, Pointer("/foo/true"), true); EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); SetValueByPointer(d, Pointer("/foo/false"), false); EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); // StringRef version SetValueByPointer(d, Pointer("/foo/hello"), "Hello"); EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); SetValueByPointer(d, Pointer("/foo/world"), buffer); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING SetValueByPointer(d, Pointer("/foo/c++"), std::string("C++")); EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); #endif } TEST(Pointer, SetValueByPointer_String_NoAllocator) { Document d; d.Parse(kJson); // Value version SetValueByPointer(d, "/foo/0", Value(123).Move()); EXPECT_EQ(123, d["foo"][0].GetInt()); SetValueByPointer(d, "/foo/null", Value().Move()); EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); // Const Value version const Value foo(d["foo"], d.GetAllocator()); SetValueByPointer(d, "/clone", foo); EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); // Generic version SetValueByPointer(d, "/foo/int", -1); EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); SetValueByPointer(d, "/foo/uint", 0x87654321); EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); const int64_t i64 = static_cast<int64_t>(RAPIDJSON_UINT64_C2(0x80000000, 0)); SetValueByPointer(d, "/foo/int64", i64); EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); SetValueByPointer(d, "/foo/uint64", u64); EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); SetValueByPointer(d, "/foo/true", true); EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); SetValueByPointer(d, "/foo/false", false); EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); // StringRef version SetValueByPointer(d, "/foo/hello", "Hello"); EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); // Copy string version { char buffer[256]; strcpy(buffer, "World"); SetValueByPointer(d, "/foo/world", buffer); memset(buffer, 0, sizeof(buffer)); } EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); #if RAPIDJSON_HAS_STDSTRING SetValueByPointer(d, "/foo/c++", std::string("C++")); EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); #endif } TEST(Pointer, SwapValueByPointer) { Document d; d.Parse(kJson); Document::AllocatorType& a = d.GetAllocator(); SwapValueByPointer(d, Pointer("/foo/0"), *GetValueByPointer(d, "/foo/1"), a); EXPECT_STREQ("baz", d["foo"][0].GetString()); EXPECT_STREQ("bar", d["foo"][1].GetString()); SwapValueByPointer(d, "/foo/0", *GetValueByPointer(d, "/foo/1"), a); EXPECT_STREQ("bar", d["foo"][0].GetString()); EXPECT_STREQ("baz", d["foo"][1].GetString()); } TEST(Pointer, SwapValueByPointer_NoAllocator) { Document d; d.Parse(kJson); SwapValueByPointer(d, Pointer("/foo/0"), *GetValueByPointer(d, "/foo/1")); EXPECT_STREQ("baz", d["foo"][0].GetString()); EXPECT_STREQ("bar", d["foo"][1].GetString()); SwapValueByPointer(d, "/foo/0", *GetValueByPointer(d, "/foo/1")); EXPECT_STREQ("bar", d["foo"][0].GetString()); EXPECT_STREQ("baz", d["foo"][1].GetString()); } TEST(Pointer, EraseValueByPointer_Pointer) { Document d; d.Parse(kJson); EXPECT_FALSE(EraseValueByPointer(d, Pointer(""))); EXPECT_FALSE(Pointer("/foo/nonexist").Erase(d)); EXPECT_TRUE(EraseValueByPointer(d, Pointer("/foo/0"))); EXPECT_EQ(1u, d["foo"].Size()); EXPECT_STREQ("baz", d["foo"][0].GetString()); EXPECT_TRUE(EraseValueByPointer(d, Pointer("/foo/0"))); EXPECT_TRUE(d["foo"].Empty()); EXPECT_TRUE(EraseValueByPointer(d, Pointer("/foo"))); EXPECT_TRUE(Pointer("/foo").Get(d) == 0); } TEST(Pointer, EraseValueByPointer_String) { Document d; d.Parse(kJson); EXPECT_FALSE(EraseValueByPointer(d, "")); EXPECT_FALSE(Pointer("/foo/nonexist").Erase(d)); EXPECT_TRUE(EraseValueByPointer(d, "/foo/0")); EXPECT_EQ(1u, d["foo"].Size()); EXPECT_STREQ("baz", d["foo"][0].GetString()); EXPECT_TRUE(EraseValueByPointer(d, "/foo/0")); EXPECT_TRUE(d["foo"].Empty()); EXPECT_TRUE(EraseValueByPointer(d, "/foo")); EXPECT_TRUE(Pointer("/foo").Get(d) == 0); } TEST(Pointer, Ambiguity) { { Document d; d.Parse("{\"0\" : [123]}"); EXPECT_EQ(123, Pointer("/0/0").Get(d)->GetInt()); Pointer("/0/a").Set(d, 456); // Change array [123] to object {456} EXPECT_EQ(456, Pointer("/0/a").Get(d)->GetInt()); } { Document d; EXPECT_FALSE(d.Parse("[{\"0\": 123}]").HasParseError()); EXPECT_EQ(123, Pointer("/0/0").Get(d)->GetInt()); Pointer("/0/1").Set(d, 456); // 1 is treated as "1" to index object EXPECT_EQ(123, Pointer("/0/0").Get(d)->GetInt()); EXPECT_EQ(456, Pointer("/0/1").Get(d)->GetInt()); } } // https://github.com/miloyip/rapidjson/issues/483 namespace myjson { class MyAllocator { public: static const bool kNeedFree = true; void * Malloc(size_t _size) { return malloc(_size); } void * Realloc(void *_org_p, size_t _org_size, size_t _new_size) { (void)_org_size; return realloc(_org_p, _new_size); } static void Free(void *_p) { return free(_p); } }; typedef rapidjson::GenericDocument< rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator< MyAllocator >, MyAllocator > Document; typedef rapidjson::GenericPointer< ::myjson::Document::ValueType, MyAllocator > Pointer; typedef ::myjson::Document::ValueType Value; } TEST(Pointer, Issue483) { std::string mystr, path; myjson::Document document; myjson::Value value(rapidjson::kStringType); value.SetString(mystr.c_str(), static_cast<SizeType>(mystr.length()), document.GetAllocator()); myjson::Pointer(path.c_str()).Set(document, value, document.GetAllocator()); }
gpl-3.0
wciq1208/shadowsocks-android
src/main/jni/pdnsd/src/rr_types.c
353
4336
/* rr_types.c - Tables with information for handling all rr types known to pdnsd, plus some helper functions useful for turning binary RR data into text or vice versa. Copyright (C) 2000, 2001 Thomas Moestl Copyright (C) 2003, 2004, 2007, 2010, 2011 Paul A. Rombouts This file is part of the pdnsd package. pdnsd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. pdnsd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with pdnsd; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <string.h> #include <stdio.h> #define DEFINE_RR_TYPE_ARRAYS 1 #include "helpers.h" #include "dns.h" #include "rr_types.h" /* * OK, this is inefficient. But it is used _really_ seldom (only in some cases while parsing the * config file or by pdnsd-ctl), so it is much more effective to sort by id. */ int rr_tp_byname(char *name) { int i; for (i=0;i<T_NUM;i++) { if (strcmp(name, rrnames[i])==0) return i+T_MIN; } return -1; /* invalid */ } /* The following is not needed by pdnsd-ctl. */ #ifndef CLIENT_ONLY static const unsigned int poweroften[8] = {1, 10, 100, 1000, 10000, 100000, 1000000,10000000}; #define NPRECSIZE (sizeof "90000000") /* takes an XeY precision/size value, returns a string representation. This is an adapted version of the function of the same name that can be found in the BIND 9 source. */ static const char *precsize_ntoa(uint8_t prec,char *retbuf) { unsigned int mantissa, exponent; mantissa = (prec >> 4); exponent = (prec & 0x0f); if(mantissa>=10 || exponent>=10) return NULL; if (exponent>= 2) sprintf(retbuf, "%u", mantissa * poweroften[exponent-2]); else sprintf(retbuf, "0.%.2u", mantissa * poweroften[exponent]); return (retbuf); } /* takes an on-the-wire LOC RR and formats it in a human readable format. This is an adapted version of the loc_ntoa function that can be found in the BIND 9 source. */ const char *loc2str(const void *binary, char *ascii, size_t asclen) { const unsigned char *cp = binary; int latdeg, latmin, latsec, latsecfrac; int longdeg, longmin, longsec, longsecfrac; char northsouth, eastwest; const char *altsign; int altmeters, altfrac; const uint32_t referencealt = 100000 * 100; int32_t latval, longval, altval; uint32_t templ; uint8_t sizeval, hpval, vpval, versionval; char sizestr[NPRECSIZE],hpstr[NPRECSIZE],vpstr[NPRECSIZE]; versionval = *cp++; if (versionval) { /* unknown LOC RR version */ return NULL; } sizeval = *cp++; hpval = *cp++; vpval = *cp++; GETINT32(templ, cp); latval = (templ - ((unsigned)1<<31)); GETINT32(templ, cp); longval = (templ - ((unsigned)1<<31)); GETINT32(templ, cp); if (templ < referencealt) { /* below WGS 84 spheroid */ altval = referencealt - templ; altsign = "-"; } else { altval = templ - referencealt; altsign = ""; } if (latval < 0) { northsouth = 'S'; latval = -latval; } else northsouth = 'N'; latsecfrac = latval % 1000; latval /= 1000; latsec = latval % 60; latval /= 60; latmin = latval % 60; latval /= 60; latdeg = latval; if (longval < 0) { eastwest = 'W'; longval = -longval; } else eastwest = 'E'; longsecfrac = longval % 1000; longval /= 1000; longsec = longval % 60; longval /= 60; longmin = longval % 60; longval /= 60; longdeg = longval; altfrac = altval % 100; altmeters = (altval / 100); if(!precsize_ntoa(sizeval,sizestr) || !precsize_ntoa(hpval,hpstr) || !precsize_ntoa(vpval,vpstr)) return NULL; { int n=snprintf(ascii,asclen, "%d %.2d %.2d.%.3d %c %d %.2d %.2d.%.3d %c %s%d.%.2dm %sm %sm %sm", latdeg, latmin, latsec, latsecfrac, northsouth, longdeg, longmin, longsec, longsecfrac, eastwest, altsign, altmeters, altfrac, sizestr, hpstr, vpstr); if(n<0 || n>=asclen) return NULL; } return (ascii); } #endif
gpl-3.0
xyb/shadowsocks-android
src/main/jni/openssl/crypto/bio/bss_conn.c
869
14935
/* crypto/bio/bss_conn.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <errno.h> #define USE_SOCKETS #include "cryptlib.h" #include <openssl/bio.h> #ifndef OPENSSL_NO_SOCK #ifdef OPENSSL_SYS_WIN16 #define SOCKET_PROTOCOL 0 /* more microsoft stupidity */ #else #define SOCKET_PROTOCOL IPPROTO_TCP #endif #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000) /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */ #undef FIONBIO #endif typedef struct bio_connect_st { int state; char *param_hostname; char *param_port; int nbio; unsigned char ip[4]; unsigned short port; struct sockaddr_in them; /* int socket; this will be kept in bio->num so that it is * compatible with the bss_sock bio */ /* called when the connection is initially made * callback(BIO,state,ret); The callback should return * 'ret'. state is for compatibility with the ssl info_callback */ int (*info_callback)(const BIO *bio,int state,int ret); } BIO_CONNECT; static int conn_write(BIO *h, const char *buf, int num); static int conn_read(BIO *h, char *buf, int size); static int conn_puts(BIO *h, const char *str); static long conn_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int conn_new(BIO *h); static int conn_free(BIO *data); static long conn_callback_ctrl(BIO *h, int cmd, bio_info_cb *); static int conn_state(BIO *b, BIO_CONNECT *c); static void conn_close_socket(BIO *data); BIO_CONNECT *BIO_CONNECT_new(void ); void BIO_CONNECT_free(BIO_CONNECT *a); static BIO_METHOD methods_connectp= { BIO_TYPE_CONNECT, "socket connect", conn_write, conn_read, conn_puts, NULL, /* connect_gets, */ conn_ctrl, conn_new, conn_free, conn_callback_ctrl, }; static int conn_state(BIO *b, BIO_CONNECT *c) { int ret= -1,i; unsigned long l; char *p,*q; int (*cb)(const BIO *,int,int)=NULL; if (c->info_callback != NULL) cb=c->info_callback; for (;;) { switch (c->state) { case BIO_CONN_S_BEFORE: p=c->param_hostname; if (p == NULL) { BIOerr(BIO_F_CONN_STATE,BIO_R_NO_HOSTNAME_SPECIFIED); goto exit_loop; } for ( ; *p != '\0'; p++) { if ((*p == ':') || (*p == '/')) break; } i= *p; if ((i == ':') || (i == '/')) { *(p++)='\0'; if (i == ':') { for (q=p; *q; q++) if (*q == '/') { *q='\0'; break; } if (c->param_port != NULL) OPENSSL_free(c->param_port); c->param_port=BUF_strdup(p); } } if (c->param_port == NULL) { BIOerr(BIO_F_CONN_STATE,BIO_R_NO_PORT_SPECIFIED); ERR_add_error_data(2,"host=",c->param_hostname); goto exit_loop; } c->state=BIO_CONN_S_GET_IP; break; case BIO_CONN_S_GET_IP: if (BIO_get_host_ip(c->param_hostname,&(c->ip[0])) <= 0) goto exit_loop; c->state=BIO_CONN_S_GET_PORT; break; case BIO_CONN_S_GET_PORT: if (c->param_port == NULL) { /* abort(); */ goto exit_loop; } else if (BIO_get_port(c->param_port,&c->port) <= 0) goto exit_loop; c->state=BIO_CONN_S_CREATE_SOCKET; break; case BIO_CONN_S_CREATE_SOCKET: /* now setup address */ memset((char *)&c->them,0,sizeof(c->them)); c->them.sin_family=AF_INET; c->them.sin_port=htons((unsigned short)c->port); l=(unsigned long) ((unsigned long)c->ip[0]<<24L)| ((unsigned long)c->ip[1]<<16L)| ((unsigned long)c->ip[2]<< 8L)| ((unsigned long)c->ip[3]); c->them.sin_addr.s_addr=htonl(l); c->state=BIO_CONN_S_CREATE_SOCKET; ret=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL); if (ret == INVALID_SOCKET) { SYSerr(SYS_F_SOCKET,get_last_socket_error()); ERR_add_error_data(4,"host=",c->param_hostname, ":",c->param_port); BIOerr(BIO_F_CONN_STATE,BIO_R_UNABLE_TO_CREATE_SOCKET); goto exit_loop; } b->num=ret; c->state=BIO_CONN_S_NBIO; break; case BIO_CONN_S_NBIO: if (c->nbio) { if (!BIO_socket_nbio(b->num,1)) { BIOerr(BIO_F_CONN_STATE,BIO_R_ERROR_SETTING_NBIO); ERR_add_error_data(4,"host=", c->param_hostname, ":",c->param_port); goto exit_loop; } } c->state=BIO_CONN_S_CONNECT; #if defined(SO_KEEPALIVE) && !defined(OPENSSL_SYS_MPE) i=1; i=setsockopt(b->num,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i)); if (i < 0) { SYSerr(SYS_F_SOCKET,get_last_socket_error()); ERR_add_error_data(4,"host=",c->param_hostname, ":",c->param_port); BIOerr(BIO_F_CONN_STATE,BIO_R_KEEPALIVE); goto exit_loop; } #endif break; case BIO_CONN_S_CONNECT: BIO_clear_retry_flags(b); ret=connect(b->num, (struct sockaddr *)&c->them, sizeof(c->them)); b->retry_reason=0; if (ret < 0) { if (BIO_sock_should_retry(ret)) { BIO_set_retry_special(b); c->state=BIO_CONN_S_BLOCKED_CONNECT; b->retry_reason=BIO_RR_CONNECT; } else { SYSerr(SYS_F_CONNECT,get_last_socket_error()); ERR_add_error_data(4,"host=", c->param_hostname, ":",c->param_port); BIOerr(BIO_F_CONN_STATE,BIO_R_CONNECT_ERROR); } goto exit_loop; } else c->state=BIO_CONN_S_OK; break; case BIO_CONN_S_BLOCKED_CONNECT: i=BIO_sock_error(b->num); if (i) { BIO_clear_retry_flags(b); SYSerr(SYS_F_CONNECT,i); ERR_add_error_data(4,"host=", c->param_hostname, ":",c->param_port); BIOerr(BIO_F_CONN_STATE,BIO_R_NBIO_CONNECT_ERROR); ret=0; goto exit_loop; } else c->state=BIO_CONN_S_OK; break; case BIO_CONN_S_OK: ret=1; goto exit_loop; default: /* abort(); */ goto exit_loop; } if (cb != NULL) { if (!(ret=cb((BIO *)b,c->state,ret))) goto end; } } /* Loop does not exit */ exit_loop: if (cb != NULL) ret=cb((BIO *)b,c->state,ret); end: return(ret); } BIO_CONNECT *BIO_CONNECT_new(void) { BIO_CONNECT *ret; if ((ret=(BIO_CONNECT *)OPENSSL_malloc(sizeof(BIO_CONNECT))) == NULL) return(NULL); ret->state=BIO_CONN_S_BEFORE; ret->param_hostname=NULL; ret->param_port=NULL; ret->info_callback=NULL; ret->nbio=0; ret->ip[0]=0; ret->ip[1]=0; ret->ip[2]=0; ret->ip[3]=0; ret->port=0; memset((char *)&ret->them,0,sizeof(ret->them)); return(ret); } void BIO_CONNECT_free(BIO_CONNECT *a) { if(a == NULL) return; if (a->param_hostname != NULL) OPENSSL_free(a->param_hostname); if (a->param_port != NULL) OPENSSL_free(a->param_port); OPENSSL_free(a); } BIO_METHOD *BIO_s_connect(void) { return(&methods_connectp); } static int conn_new(BIO *bi) { bi->init=0; bi->num=INVALID_SOCKET; bi->flags=0; if ((bi->ptr=(char *)BIO_CONNECT_new()) == NULL) return(0); else return(1); } static void conn_close_socket(BIO *bio) { BIO_CONNECT *c; c=(BIO_CONNECT *)bio->ptr; if (bio->num != INVALID_SOCKET) { /* Only do a shutdown if things were established */ if (c->state == BIO_CONN_S_OK) shutdown(bio->num,2); closesocket(bio->num); bio->num=INVALID_SOCKET; } } static int conn_free(BIO *a) { BIO_CONNECT *data; if (a == NULL) return(0); data=(BIO_CONNECT *)a->ptr; if (a->shutdown) { conn_close_socket(a); BIO_CONNECT_free(data); a->ptr=NULL; a->flags=0; a->init=0; } return(1); } static int conn_read(BIO *b, char *out, int outl) { int ret=0; BIO_CONNECT *data; data=(BIO_CONNECT *)b->ptr; if (data->state != BIO_CONN_S_OK) { ret=conn_state(b,data); if (ret <= 0) return(ret); } if (out != NULL) { clear_socket_error(); ret=readsocket(b->num,out,outl); BIO_clear_retry_flags(b); if (ret <= 0) { if (BIO_sock_should_retry(ret)) BIO_set_retry_read(b); } } return(ret); } static int conn_write(BIO *b, const char *in, int inl) { int ret; BIO_CONNECT *data; data=(BIO_CONNECT *)b->ptr; if (data->state != BIO_CONN_S_OK) { ret=conn_state(b,data); if (ret <= 0) return(ret); } clear_socket_error(); ret=writesocket(b->num,in,inl); BIO_clear_retry_flags(b); if (ret <= 0) { if (BIO_sock_should_retry(ret)) BIO_set_retry_write(b); } return(ret); } static long conn_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO *dbio; int *ip; const char **pptr; long ret=1; BIO_CONNECT *data; data=(BIO_CONNECT *)b->ptr; switch (cmd) { case BIO_CTRL_RESET: ret=0; data->state=BIO_CONN_S_BEFORE; conn_close_socket(b); b->flags=0; break; case BIO_C_DO_STATE_MACHINE: /* use this one to start the connection */ if (data->state != BIO_CONN_S_OK) ret=(long)conn_state(b,data); else ret=1; break; case BIO_C_GET_CONNECT: if (ptr != NULL) { pptr=(const char **)ptr; if (num == 0) { *pptr=data->param_hostname; } else if (num == 1) { *pptr=data->param_port; } else if (num == 2) { *pptr= (char *)&(data->ip[0]); } else if (num == 3) { *((int *)ptr)=data->port; } if ((!b->init) || (ptr == NULL)) *pptr="not initialized"; ret=1; } break; case BIO_C_SET_CONNECT: if (ptr != NULL) { b->init=1; if (num == 0) { if (data->param_hostname != NULL) OPENSSL_free(data->param_hostname); data->param_hostname=BUF_strdup(ptr); } else if (num == 1) { if (data->param_port != NULL) OPENSSL_free(data->param_port); data->param_port=BUF_strdup(ptr); } else if (num == 2) { char buf[16]; unsigned char *p = ptr; BIO_snprintf(buf,sizeof buf,"%d.%d.%d.%d", p[0],p[1],p[2],p[3]); if (data->param_hostname != NULL) OPENSSL_free(data->param_hostname); data->param_hostname=BUF_strdup(buf); memcpy(&(data->ip[0]),ptr,4); } else if (num == 3) { char buf[DECIMAL_SIZE(int)+1]; BIO_snprintf(buf,sizeof buf,"%d",*(int *)ptr); if (data->param_port != NULL) OPENSSL_free(data->param_port); data->param_port=BUF_strdup(buf); data->port= *(int *)ptr; } } break; case BIO_C_SET_NBIO: data->nbio=(int)num; break; case BIO_C_GET_FD: if (b->init) { ip=(int *)ptr; if (ip != NULL) *ip=b->num; ret=b->num; } else ret= -1; break; case BIO_CTRL_GET_CLOSE: ret=b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown=(int)num; break; case BIO_CTRL_PENDING: case BIO_CTRL_WPENDING: ret=0; break; case BIO_CTRL_FLUSH: break; case BIO_CTRL_DUP: { dbio=(BIO *)ptr; if (data->param_port) BIO_set_conn_port(dbio,data->param_port); if (data->param_hostname) BIO_set_conn_hostname(dbio,data->param_hostname); BIO_set_nbio(dbio,data->nbio); /* FIXME: the cast of the function seems unlikely to be a good idea */ (void)BIO_set_info_callback(dbio,(bio_info_cb *)data->info_callback); } break; case BIO_CTRL_SET_CALLBACK: { #if 0 /* FIXME: Should this be used? -- Richard Levitte */ BIOerr(BIO_F_CONN_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); ret = -1; #else ret=0; #endif } break; case BIO_CTRL_GET_CALLBACK: { int (**fptr)(const BIO *bio,int state,int xret); fptr=(int (**)(const BIO *bio,int state,int xret))ptr; *fptr=data->info_callback; } break; default: ret=0; break; } return(ret); } static long conn_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp) { long ret=1; BIO_CONNECT *data; data=(BIO_CONNECT *)b->ptr; switch (cmd) { case BIO_CTRL_SET_CALLBACK: { data->info_callback=(int (*)(const struct bio_st *, int, int))fp; } break; default: ret=0; break; } return(ret); } static int conn_puts(BIO *bp, const char *str) { int n,ret; n=strlen(str); ret=conn_write(bp,str,n); return(ret); } BIO *BIO_new_connect(char *str) { BIO *ret; ret=BIO_new(BIO_s_connect()); if (ret == NULL) return(NULL); if (BIO_set_conn_hostname(ret,str)) return(ret); else { BIO_free(ret); return(NULL); } } #endif
gpl-3.0
phenix3443/shadowsocks-android
src/main/jni/badvpn/ncd/modules/list.c
360
22041
/** * @file list.c * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * * List construction module. * * Synopsis: * list(elem1, ..., elemN) * list listfrom(list l1, ..., list lN) * * Description: * The first form creates a list with the given elements. * The second form creates a list by concatenating the given * lists. * * Variables: * (empty) - list containing elem1, ..., elemN * length - number of elements in list * * Synopsis: list::append(arg) * * Synopsis: list::appendv(list arg) * Description: Appends the elements of arg to the list. * * Synopsis: list::length() * Variables: * (empty) - number of elements in list at the time of initialization * of this method * * Synopsis: list::get(string index) * Variables: * (empty) - element of list at position index (starting from zero) at the time of initialization * * Synopsis: list::shift() * * Synopsis: list::contains(value) * Variables: * (empty) - "true" if list contains value, "false" if not * * Synopsis: * list::find(start_pos, value) * Description: * finds the first occurrence of 'value' in the list at position >='start_pos'. * Variables: * pos - position of element, or "none" if not found * found - "true" if found, "false" if not * * Sysnopsis: * list::remove_at(remove_pos) * Description: * Removes the element at position 'remove_pos', which must refer to an existing element. * * Synopsis: * list::remove(value) * Description: * Removes the first occurrence of value in the list, which must be in the list. * * Synopsis: * list::set(list l1, ..., list lN) * Description: * Replaces the list with the concatenation of given lists. */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <inttypes.h> #include <misc/offset.h> #include <misc/parse_number.h> #include <structure/IndexedList.h> #include <ncd/NCDModule.h> #include <ncd/extra/value_utils.h> #include <generated/blog_channel_ncd_list.h> #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__) struct elem { IndexedListNode il_node; NCDValMem mem; NCDValRef val; }; struct instance { NCDModuleInst *i; IndexedList il; }; struct length_instance { NCDModuleInst *i; uint64_t length; }; struct get_instance { NCDModuleInst *i; NCDValMem mem; NCDValRef val; }; struct contains_instance { NCDModuleInst *i; int contains; }; struct find_instance { NCDModuleInst *i; int is_found; uint64_t found_pos; }; static uint64_t list_count (struct instance *o) { return IndexedList_Count(&o->il); } static struct elem * insert_value (NCDModuleInst *i, struct instance *o, NCDValRef val, uint64_t idx) { ASSERT(idx <= list_count(o)) ASSERT(!NCDVal_IsInvalid(val)) struct elem *e = malloc(sizeof(*e)); if (!e) { ModuleLog(i, BLOG_ERROR, "malloc failed"); goto fail0; } NCDValMem_Init(&e->mem); e->val = NCDVal_NewCopy(&e->mem, val); if (NCDVal_IsInvalid(e->val)) { goto fail1; } IndexedList_InsertAt(&o->il, &e->il_node, idx); return e; fail1: NCDValMem_Free(&e->mem); free(e); fail0: return NULL; } static void remove_elem (struct instance *o, struct elem *e) { IndexedList_Remove(&o->il, &e->il_node); NCDValMem_Free(&e->mem); free(e); } static struct elem * get_elem_at (struct instance *o, uint64_t idx) { ASSERT(idx < list_count(o)) IndexedListNode *iln = IndexedList_GetAt(&o->il, idx); struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); return e; } static struct elem * get_first_elem (struct instance *o) { ASSERT(list_count(o) > 0) IndexedListNode *iln = IndexedList_GetFirst(&o->il); struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); return e; } static struct elem * get_last_elem (struct instance *o) { ASSERT(list_count(o) > 0) IndexedListNode *iln = IndexedList_GetLast(&o->il); struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); return e; } static void cut_list_front (struct instance *o, uint64_t count) { while (list_count(o) > count) { remove_elem(o, get_first_elem(o)); } } static void cut_list_back (struct instance *o, uint64_t count) { while (list_count(o) > count) { remove_elem(o, get_last_elem(o)); } } static int append_list_contents (NCDModuleInst *i, struct instance *o, NCDValRef args) { ASSERT(NCDVal_IsList(args)) uint64_t orig_count = list_count(o); size_t append_count = NCDVal_ListCount(args); for (size_t j = 0; j < append_count; j++) { NCDValRef elem = NCDVal_ListGet(args, j); if (!insert_value(i, o, elem, list_count(o))) { goto fail; } } return 1; fail: cut_list_back(o, orig_count); return 0; } static int append_list_contents_contents (NCDModuleInst *i, struct instance *o, NCDValRef args) { ASSERT(NCDVal_IsList(args)) uint64_t orig_count = list_count(o); size_t append_count = NCDVal_ListCount(args); for (size_t j = 0; j < append_count; j++) { NCDValRef elem = NCDVal_ListGet(args, j); if (!NCDVal_IsList(elem)) { ModuleLog(i, BLOG_ERROR, "wrong type"); goto fail; } if (!append_list_contents(i, o, elem)) { goto fail; } } return 1; fail: cut_list_back(o, orig_count); return 0; } static struct elem * find_elem (struct instance *o, NCDValRef val, uint64_t start_idx, uint64_t *out_idx) { if (start_idx >= list_count(o)) { return NULL; } for (IndexedListNode *iln = IndexedList_GetAt(&o->il, start_idx); iln; iln = IndexedList_GetNext(&o->il, iln)) { struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); if (NCDVal_Compare(e->val, val) == 0) { if (out_idx) { *out_idx = start_idx; } return e; } start_idx++; } return NULL; } static int list_to_value (NCDModuleInst *i, struct instance *o, NCDValMem *mem, NCDValRef *out_val) { *out_val = NCDVal_NewList(mem, IndexedList_Count(&o->il)); if (NCDVal_IsInvalid(*out_val)) { goto fail; } for (IndexedListNode *iln = IndexedList_GetFirst(&o->il); iln; iln = IndexedList_GetNext(&o->il, iln)) { struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); NCDValRef copy = NCDVal_NewCopy(mem, e->val); if (NCDVal_IsInvalid(copy)) { goto fail; } if (!NCDVal_ListAppend(*out_val, copy)) { goto fail; } } return 1; fail: return 0; } static void func_new_list (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct instance *o = vo; o->i = i; // init list IndexedList_Init(&o->il); // append contents if (!append_list_contents(i, o, params->args)) { goto fail1; } // signal up NCDModuleInst_Backend_Up(o->i); return; fail1: cut_list_front(o, 0); NCDModuleInst_Backend_DeadError(i); } static void func_new_listfrom (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct instance *o = vo; o->i = i; // init list IndexedList_Init(&o->il); // append contents contents if (!append_list_contents_contents(i, o, params->args)) { goto fail1; } // signal up NCDModuleInst_Backend_Up(o->i); return; fail1: cut_list_front(o, 0); NCDModuleInst_Backend_DeadError(i); } static void func_die (void *vo) { struct instance *o = vo; // free list elements cut_list_front(o, 0); NCDModuleInst_Backend_Dead(o->i); } static int func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct instance *o = vo; if (!strcmp(name, "")) { if (!list_to_value(o->i, o, mem, out)) { return 0; } return 1; } if (!strcmp(name, "length")) { *out = ncd_make_uintmax(mem, list_count(o)); return 1; } return 0; } static void append_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // check arguments NCDValRef arg; if (!NCDVal_ListRead(params->args, 1, &arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // append if (!insert_value(i, mo, arg, list_count(mo))) { goto fail0; } // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void appendv_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // check arguments NCDValRef arg; if (!NCDVal_ListRead(params->args, 1, &arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsList(arg)) { ModuleLog(i, BLOG_ERROR, "wrong type"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // append if (!append_list_contents(i, mo, arg)) { goto fail0; } // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void length_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct length_instance *o = vo; o->i = i; // check arguments if (!NCDVal_ListRead(params->args, 0)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // remember length o->length = list_count(mo); // signal up NCDModuleInst_Backend_Up(o->i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void length_func_die (void *vo) { struct length_instance *o = vo; NCDModuleInst_Backend_Dead(o->i); } static int length_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct length_instance *o = vo; if (!strcmp(name, "")) { *out = ncd_make_uintmax(mem, o->length); return 1; } return 0; } static void get_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct get_instance *o = vo; o->i = i; // check arguments NCDValRef index_arg; if (!NCDVal_ListRead(params->args, 1, &index_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(index_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong type"); goto fail0; } uintmax_t index; if (!ncd_read_uintmax(index_arg, &index)) { ModuleLog(o->i, BLOG_ERROR, "wrong value"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // check index if (index >= list_count(mo)) { ModuleLog(o->i, BLOG_ERROR, "no element at index %"PRIuMAX, index); goto fail0; } // get element struct elem *e = get_elem_at(mo, index); // init mem NCDValMem_Init(&o->mem); // copy value o->val = NCDVal_NewCopy(&o->mem, e->val); if (NCDVal_IsInvalid(o->val)) { goto fail1; } // signal up NCDModuleInst_Backend_Up(o->i); return; fail1: NCDValMem_Free(&o->mem); fail0: NCDModuleInst_Backend_DeadError(i); } static void get_func_die (void *vo) { struct get_instance *o = vo; // free mem NCDValMem_Free(&o->mem); NCDModuleInst_Backend_Dead(o->i); } static int get_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct get_instance *o = vo; if (!strcmp(name, "")) { *out = NCDVal_NewCopy(mem, o->val); return 1; } return 0; } static void shift_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // check arguments if (!NCDVal_ListRead(params->args, 0)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // check first if (list_count(mo) == 0) { ModuleLog(i, BLOG_ERROR, "list has no elements"); goto fail0; } // remove first remove_elem(mo, get_first_elem(mo)); // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void contains_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct contains_instance *o = vo; o->i = i; // read arguments NCDValRef value_arg; if (!NCDVal_ListRead(params->args, 1, &value_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // search o->contains = !!find_elem(mo, value_arg, 0, NULL); // signal up NCDModuleInst_Backend_Up(o->i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void contains_func_die (void *vo) { struct contains_instance *o = vo; NCDModuleInst_Backend_Dead(o->i); } static int contains_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct contains_instance *o = vo; if (!strcmp(name, "")) { *out = ncd_make_boolean(mem, o->contains, o->i->params->iparams->string_index); return 1; } return 0; } static void find_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct find_instance *o = vo; o->i = i; // read arguments NCDValRef start_pos_arg; NCDValRef value_arg; if (!NCDVal_ListRead(params->args, 2, &start_pos_arg, &value_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(start_pos_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong type"); goto fail0; } // read start position uintmax_t start_pos; if (!ncd_read_uintmax(start_pos_arg, &start_pos) || start_pos > UINT64_MAX) { ModuleLog(o->i, BLOG_ERROR, "wrong start pos"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // find o->is_found = !!find_elem(mo, value_arg, start_pos, &o->found_pos); // signal up NCDModuleInst_Backend_Up(o->i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void find_func_die (void *vo) { struct find_instance *o = vo; NCDModuleInst_Backend_Dead(o->i); } static int find_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct find_instance *o = vo; if (!strcmp(name, "pos")) { char value[64] = "none"; if (o->is_found) { generate_decimal_repr_string(o->found_pos, value); } *out = NCDVal_NewString(mem, value); return 1; } if (!strcmp(name, "found")) { *out = ncd_make_boolean(mem, o->is_found, o->i->params->iparams->string_index); return 1; } return 0; } static void removeat_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // read arguments NCDValRef remove_pos_arg; if (!NCDVal_ListRead(params->args, 1, &remove_pos_arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(remove_pos_arg)) { ModuleLog(i, BLOG_ERROR, "wrong type"); goto fail0; } // read position uintmax_t remove_pos; if (!ncd_read_uintmax(remove_pos_arg, &remove_pos)) { ModuleLog(i, BLOG_ERROR, "wrong pos"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // check position if (remove_pos >= list_count(mo)) { ModuleLog(i, BLOG_ERROR, "pos out of range"); goto fail0; } // remove remove_elem(mo, get_elem_at(mo, remove_pos)); // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void remove_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // read arguments NCDValRef value_arg; if (!NCDVal_ListRead(params->args, 1, &value_arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // find element struct elem *e = find_elem(mo, value_arg, 0, NULL); if (!e) { ModuleLog(i, BLOG_ERROR, "value does not exist"); goto fail0; } // remove element remove_elem(mo, e); // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void set_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // remember old count uint64_t old_count = list_count(mo); // append contents of our lists if (!append_list_contents_contents(i, mo, params->args)) { goto fail0; } // remove old elements cut_list_front(mo, list_count(mo) - old_count); // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static struct NCDModule modules[] = { { .type = "list", .func_new2 = func_new_list, .func_die = func_die, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = "listfrom", .base_type = "list", .func_new2 = func_new_listfrom, .func_die = func_die, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = "concatlist", // alias for listfrom .base_type = "list", .func_new2 = func_new_listfrom, .func_die = func_die, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = "list::append", .func_new2 = append_func_new }, { .type = "list::appendv", .func_new2 = appendv_func_new }, { .type = "list::length", .func_new2 = length_func_new, .func_die = length_func_die, .func_getvar = length_func_getvar, .alloc_size = sizeof(struct length_instance) }, { .type = "list::get", .func_new2 = get_func_new, .func_die = get_func_die, .func_getvar = get_func_getvar, .alloc_size = sizeof(struct get_instance) }, { .type = "list::shift", .func_new2 = shift_func_new }, { .type = "list::contains", .func_new2 = contains_func_new, .func_die = contains_func_die, .func_getvar = contains_func_getvar, .alloc_size = sizeof(struct contains_instance) }, { .type = "list::find", .func_new2 = find_func_new, .func_die = find_func_die, .func_getvar = find_func_getvar, .alloc_size = sizeof(struct find_instance) }, { .type = "list::remove_at", .func_new2 = removeat_func_new }, { .type = "list::remove", .func_new2 = remove_func_new }, { .type = "list::set", .func_new2 = set_func_new }, { .type = NULL } }; const struct NCDModuleGroup ncdmodule_list = { .modules = modules };
gpl-3.0
psycho-source/Psycho-Kernel
arch/ia64/kernel/smpboot.c
1896
20804
/* * SMP boot-related support * * Copyright (C) 1998-2003, 2005 Hewlett-Packard Co * David Mosberger-Tang <davidm@hpl.hp.com> * Copyright (C) 2001, 2004-2005 Intel Corp * Rohit Seth <rohit.seth@intel.com> * Suresh Siddha <suresh.b.siddha@intel.com> * Gordon Jin <gordon.jin@intel.com> * Ashok Raj <ashok.raj@intel.com> * * 01/05/16 Rohit Seth <rohit.seth@intel.com> Moved SMP booting functions from smp.c to here. * 01/04/27 David Mosberger <davidm@hpl.hp.com> Added ITC synching code. * 02/07/31 David Mosberger <davidm@hpl.hp.com> Switch over to hotplug-CPU boot-sequence. * smp_boot_cpus()/smp_commence() is replaced by * smp_prepare_cpus()/__cpu_up()/smp_cpus_done(). * 04/06/21 Ashok Raj <ashok.raj@intel.com> Added CPU Hotplug Support * 04/12/26 Jin Gordon <gordon.jin@intel.com> * 04/12/26 Rohit Seth <rohit.seth@intel.com> * Add multi-threading and multi-core detection * 05/01/30 Suresh Siddha <suresh.b.siddha@intel.com> * Setup cpu_sibling_map and cpu_core_map */ #include <linux/module.h> #include <linux/acpi.h> #include <linux/bootmem.h> #include <linux/cpu.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/kernel.h> #include <linux/kernel_stat.h> #include <linux/mm.h> #include <linux/notifier.h> #include <linux/smp.h> #include <linux/spinlock.h> #include <linux/efi.h> #include <linux/percpu.h> #include <linux/bitops.h> #include <linux/atomic.h> #include <asm/cache.h> #include <asm/current.h> #include <asm/delay.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/machvec.h> #include <asm/mca.h> #include <asm/page.h> #include <asm/paravirt.h> #include <asm/pgalloc.h> #include <asm/pgtable.h> #include <asm/processor.h> #include <asm/ptrace.h> #include <asm/sal.h> #include <asm/tlbflush.h> #include <asm/unistd.h> #include <asm/sn/arch.h> #define SMP_DEBUG 0 #if SMP_DEBUG #define Dprintk(x...) printk(x) #else #define Dprintk(x...) #endif #ifdef CONFIG_HOTPLUG_CPU #ifdef CONFIG_PERMIT_BSP_REMOVE #define bsp_remove_ok 1 #else #define bsp_remove_ok 0 #endif /* * Global array allocated for NR_CPUS at boot time */ struct sal_to_os_boot sal_boot_rendez_state[NR_CPUS]; /* * start_ap in head.S uses this to store current booting cpu * info. */ struct sal_to_os_boot *sal_state_for_booting_cpu = &sal_boot_rendez_state[0]; #define set_brendez_area(x) (sal_state_for_booting_cpu = &sal_boot_rendez_state[(x)]); #else #define set_brendez_area(x) #endif /* * ITC synchronization related stuff: */ #define MASTER (0) #define SLAVE (SMP_CACHE_BYTES/8) #define NUM_ROUNDS 64 /* magic value */ #define NUM_ITERS 5 /* likewise */ static DEFINE_SPINLOCK(itc_sync_lock); static volatile unsigned long go[SLAVE + 1]; #define DEBUG_ITC_SYNC 0 extern void start_ap (void); extern unsigned long ia64_iobase; struct task_struct *task_for_booting_cpu; /* * State for each CPU */ DEFINE_PER_CPU(int, cpu_state); cpumask_t cpu_core_map[NR_CPUS] __cacheline_aligned; EXPORT_SYMBOL(cpu_core_map); DEFINE_PER_CPU_SHARED_ALIGNED(cpumask_t, cpu_sibling_map); EXPORT_PER_CPU_SYMBOL(cpu_sibling_map); int smp_num_siblings = 1; /* which logical CPU number maps to which CPU (physical APIC ID) */ volatile int ia64_cpu_to_sapicid[NR_CPUS]; EXPORT_SYMBOL(ia64_cpu_to_sapicid); static volatile cpumask_t cpu_callin_map; struct smp_boot_data smp_boot_data __initdata; unsigned long ap_wakeup_vector = -1; /* External Int use to wakeup APs */ char __initdata no_int_routing; unsigned char smp_int_redirect; /* are INT and IPI redirectable by the chipset? */ #ifdef CONFIG_FORCE_CPEI_RETARGET #define CPEI_OVERRIDE_DEFAULT (1) #else #define CPEI_OVERRIDE_DEFAULT (0) #endif unsigned int force_cpei_retarget = CPEI_OVERRIDE_DEFAULT; static int __init cmdl_force_cpei(char *str) { int value=0; get_option (&str, &value); force_cpei_retarget = value; return 1; } __setup("force_cpei=", cmdl_force_cpei); static int __init nointroute (char *str) { no_int_routing = 1; printk ("no_int_routing on\n"); return 1; } __setup("nointroute", nointroute); static void fix_b0_for_bsp(void) { #ifdef CONFIG_HOTPLUG_CPU int cpuid; static int fix_bsp_b0 = 1; cpuid = smp_processor_id(); /* * Cache the b0 value on the first AP that comes up */ if (!(fix_bsp_b0 && cpuid)) return; sal_boot_rendez_state[0].br[0] = sal_boot_rendez_state[cpuid].br[0]; printk ("Fixed BSP b0 value from CPU %d\n", cpuid); fix_bsp_b0 = 0; #endif } void sync_master (void *arg) { unsigned long flags, i; go[MASTER] = 0; local_irq_save(flags); { for (i = 0; i < NUM_ROUNDS*NUM_ITERS; ++i) { while (!go[MASTER]) cpu_relax(); go[MASTER] = 0; go[SLAVE] = ia64_get_itc(); } } local_irq_restore(flags); } /* * Return the number of cycles by which our itc differs from the itc on the master * (time-keeper) CPU. A positive number indicates our itc is ahead of the master, * negative that it is behind. */ static inline long get_delta (long *rt, long *master) { unsigned long best_t0 = 0, best_t1 = ~0UL, best_tm = 0; unsigned long tcenter, t0, t1, tm; long i; for (i = 0; i < NUM_ITERS; ++i) { t0 = ia64_get_itc(); go[MASTER] = 1; while (!(tm = go[SLAVE])) cpu_relax(); go[SLAVE] = 0; t1 = ia64_get_itc(); if (t1 - t0 < best_t1 - best_t0) best_t0 = t0, best_t1 = t1, best_tm = tm; } *rt = best_t1 - best_t0; *master = best_tm - best_t0; /* average best_t0 and best_t1 without overflow: */ tcenter = (best_t0/2 + best_t1/2); if (best_t0 % 2 + best_t1 % 2 == 2) ++tcenter; return tcenter - best_tm; } /* * Synchronize ar.itc of the current (slave) CPU with the ar.itc of the MASTER CPU * (normally the time-keeper CPU). We use a closed loop to eliminate the possibility of * unaccounted-for errors (such as getting a machine check in the middle of a calibration * step). The basic idea is for the slave to ask the master what itc value it has and to * read its own itc before and after the master responds. Each iteration gives us three * timestamps: * * slave master * * t0 ---\ * ---\ * ---> * tm * /--- * /--- * t1 <--- * * * The goal is to adjust the slave's ar.itc such that tm falls exactly half-way between t0 * and t1. If we achieve this, the clocks are synchronized provided the interconnect * between the slave and the master is symmetric. Even if the interconnect were * asymmetric, we would still know that the synchronization error is smaller than the * roundtrip latency (t0 - t1). * * When the interconnect is quiet and symmetric, this lets us synchronize the itc to * within one or two cycles. However, we can only *guarantee* that the synchronization is * accurate to within a round-trip time, which is typically in the range of several * hundred cycles (e.g., ~500 cycles). In practice, this means that the itc's are usually * almost perfectly synchronized, but we shouldn't assume that the accuracy is much better * than half a micro second or so. */ void ia64_sync_itc (unsigned int master) { long i, delta, adj, adjust_latency = 0, done = 0; unsigned long flags, rt, master_time_stamp, bound; #if DEBUG_ITC_SYNC struct { long rt; /* roundtrip time */ long master; /* master's timestamp */ long diff; /* difference between midpoint and master's timestamp */ long lat; /* estimate of itc adjustment latency */ } t[NUM_ROUNDS]; #endif /* * Make sure local timer ticks are disabled while we sync. If * they were enabled, we'd have to worry about nasty issues * like setting the ITC ahead of (or a long time before) the * next scheduled tick. */ BUG_ON((ia64_get_itv() & (1 << 16)) == 0); go[MASTER] = 1; if (smp_call_function_single(master, sync_master, NULL, 0) < 0) { printk(KERN_ERR "sync_itc: failed to get attention of CPU %u!\n", master); return; } while (go[MASTER]) cpu_relax(); /* wait for master to be ready */ spin_lock_irqsave(&itc_sync_lock, flags); { for (i = 0; i < NUM_ROUNDS; ++i) { delta = get_delta(&rt, &master_time_stamp); if (delta == 0) { done = 1; /* let's lock on to this... */ bound = rt; } if (!done) { if (i > 0) { adjust_latency += -delta; adj = -delta + adjust_latency/4; } else adj = -delta; ia64_set_itc(ia64_get_itc() + adj); } #if DEBUG_ITC_SYNC t[i].rt = rt; t[i].master = master_time_stamp; t[i].diff = delta; t[i].lat = adjust_latency/4; #endif } } spin_unlock_irqrestore(&itc_sync_lock, flags); #if DEBUG_ITC_SYNC for (i = 0; i < NUM_ROUNDS; ++i) printk("rt=%5ld master=%5ld diff=%5ld adjlat=%5ld\n", t[i].rt, t[i].master, t[i].diff, t[i].lat); #endif printk(KERN_INFO "CPU %d: synchronized ITC with CPU %u (last diff %ld cycles, " "maxerr %lu cycles)\n", smp_processor_id(), master, delta, rt); } /* * Ideally sets up per-cpu profiling hooks. Doesn't do much now... */ static inline void smp_setup_percpu_timer(void) { } static void __cpuinit smp_callin (void) { int cpuid, phys_id, itc_master; struct cpuinfo_ia64 *last_cpuinfo, *this_cpuinfo; extern void ia64_init_itm(void); extern volatile int time_keeper_id; #ifdef CONFIG_PERFMON extern void pfm_init_percpu(void); #endif cpuid = smp_processor_id(); phys_id = hard_smp_processor_id(); itc_master = time_keeper_id; if (cpu_online(cpuid)) { printk(KERN_ERR "huh, phys CPU#0x%x, CPU#0x%x already present??\n", phys_id, cpuid); BUG(); } fix_b0_for_bsp(); /* * numa_node_id() works after this. */ set_numa_node(cpu_to_node_map[cpuid]); set_numa_mem(local_memory_node(cpu_to_node_map[cpuid])); spin_lock(&vector_lock); /* Setup the per cpu irq handling data structures */ __setup_vector_irq(cpuid); notify_cpu_starting(cpuid); set_cpu_online(cpuid, true); per_cpu(cpu_state, cpuid) = CPU_ONLINE; spin_unlock(&vector_lock); smp_setup_percpu_timer(); ia64_mca_cmc_vector_setup(); /* Setup vector on AP */ #ifdef CONFIG_PERFMON pfm_init_percpu(); #endif local_irq_enable(); if (!(sal_platform_features & IA64_SAL_PLATFORM_FEATURE_ITC_DRIFT)) { /* * Synchronize the ITC with the BP. Need to do this after irqs are * enabled because ia64_sync_itc() calls smp_call_function_single(), which * calls spin_unlock_bh(), which calls spin_unlock_bh(), which calls * local_bh_enable(), which bugs out if irqs are not enabled... */ Dprintk("Going to syncup ITC with ITC Master.\n"); ia64_sync_itc(itc_master); } /* * Get our bogomips. */ ia64_init_itm(); /* * Delay calibration can be skipped if new processor is identical to the * previous processor. */ last_cpuinfo = cpu_data(cpuid - 1); this_cpuinfo = local_cpu_data; if (last_cpuinfo->itc_freq != this_cpuinfo->itc_freq || last_cpuinfo->proc_freq != this_cpuinfo->proc_freq || last_cpuinfo->features != this_cpuinfo->features || last_cpuinfo->revision != this_cpuinfo->revision || last_cpuinfo->family != this_cpuinfo->family || last_cpuinfo->archrev != this_cpuinfo->archrev || last_cpuinfo->model != this_cpuinfo->model) calibrate_delay(); local_cpu_data->loops_per_jiffy = loops_per_jiffy; /* * Allow the master to continue. */ cpu_set(cpuid, cpu_callin_map); Dprintk("Stack on CPU %d at about %p\n",cpuid, &cpuid); } /* * Activate a secondary processor. head.S calls this. */ int __cpuinit start_secondary (void *unused) { /* Early console may use I/O ports */ ia64_set_kr(IA64_KR_IO_BASE, __pa(ia64_iobase)); #ifndef CONFIG_PRINTK_TIME Dprintk("start_secondary: starting CPU 0x%x\n", hard_smp_processor_id()); #endif efi_map_pal_code(); cpu_init(); preempt_disable(); smp_callin(); cpu_startup_entry(CPUHP_ONLINE); return 0; } static int __cpuinit do_boot_cpu (int sapicid, int cpu, struct task_struct *idle) { int timeout; task_for_booting_cpu = idle; Dprintk("Sending wakeup vector %lu to AP 0x%x/0x%x.\n", ap_wakeup_vector, cpu, sapicid); set_brendez_area(cpu); platform_send_ipi(cpu, ap_wakeup_vector, IA64_IPI_DM_INT, 0); /* * Wait 10s total for the AP to start */ Dprintk("Waiting on callin_map ..."); for (timeout = 0; timeout < 100000; timeout++) { if (cpu_isset(cpu, cpu_callin_map)) break; /* It has booted */ udelay(100); } Dprintk("\n"); if (!cpu_isset(cpu, cpu_callin_map)) { printk(KERN_ERR "Processor 0x%x/0x%x is stuck.\n", cpu, sapicid); ia64_cpu_to_sapicid[cpu] = -1; set_cpu_online(cpu, false); /* was set in smp_callin() */ return -EINVAL; } return 0; } static int __init decay (char *str) { int ticks; get_option (&str, &ticks); return 1; } __setup("decay=", decay); /* * Initialize the logical CPU number to SAPICID mapping */ void __init smp_build_cpu_map (void) { int sapicid, cpu, i; int boot_cpu_id = hard_smp_processor_id(); for (cpu = 0; cpu < NR_CPUS; cpu++) { ia64_cpu_to_sapicid[cpu] = -1; } ia64_cpu_to_sapicid[0] = boot_cpu_id; init_cpu_present(cpumask_of(0)); set_cpu_possible(0, true); for (cpu = 1, i = 0; i < smp_boot_data.cpu_count; i++) { sapicid = smp_boot_data.cpu_phys_id[i]; if (sapicid == boot_cpu_id) continue; set_cpu_present(cpu, true); set_cpu_possible(cpu, true); ia64_cpu_to_sapicid[cpu] = sapicid; cpu++; } } /* * Cycle through the APs sending Wakeup IPIs to boot each. */ void __init smp_prepare_cpus (unsigned int max_cpus) { int boot_cpu_id = hard_smp_processor_id(); /* * Initialize the per-CPU profiling counter/multiplier */ smp_setup_percpu_timer(); cpu_set(0, cpu_callin_map); local_cpu_data->loops_per_jiffy = loops_per_jiffy; ia64_cpu_to_sapicid[0] = boot_cpu_id; printk(KERN_INFO "Boot processor id 0x%x/0x%x\n", 0, boot_cpu_id); current_thread_info()->cpu = 0; /* * If SMP should be disabled, then really disable it! */ if (!max_cpus) { printk(KERN_INFO "SMP mode deactivated.\n"); init_cpu_online(cpumask_of(0)); init_cpu_present(cpumask_of(0)); init_cpu_possible(cpumask_of(0)); return; } } void smp_prepare_boot_cpu(void) { set_cpu_online(smp_processor_id(), true); cpu_set(smp_processor_id(), cpu_callin_map); set_numa_node(cpu_to_node_map[smp_processor_id()]); per_cpu(cpu_state, smp_processor_id()) = CPU_ONLINE; paravirt_post_smp_prepare_boot_cpu(); } #ifdef CONFIG_HOTPLUG_CPU static inline void clear_cpu_sibling_map(int cpu) { int i; for_each_cpu_mask(i, per_cpu(cpu_sibling_map, cpu)) cpu_clear(cpu, per_cpu(cpu_sibling_map, i)); for_each_cpu_mask(i, cpu_core_map[cpu]) cpu_clear(cpu, cpu_core_map[i]); per_cpu(cpu_sibling_map, cpu) = cpu_core_map[cpu] = CPU_MASK_NONE; } static void remove_siblinginfo(int cpu) { int last = 0; if (cpu_data(cpu)->threads_per_core == 1 && cpu_data(cpu)->cores_per_socket == 1) { cpu_clear(cpu, cpu_core_map[cpu]); cpu_clear(cpu, per_cpu(cpu_sibling_map, cpu)); return; } last = (cpus_weight(cpu_core_map[cpu]) == 1 ? 1 : 0); /* remove it from all sibling map's */ clear_cpu_sibling_map(cpu); } extern void fixup_irqs(void); int migrate_platform_irqs(unsigned int cpu) { int new_cpei_cpu; struct irq_data *data = NULL; const struct cpumask *mask; int retval = 0; /* * dont permit CPEI target to removed. */ if (cpe_vector > 0 && is_cpu_cpei_target(cpu)) { printk ("CPU (%d) is CPEI Target\n", cpu); if (can_cpei_retarget()) { /* * Now re-target the CPEI to a different processor */ new_cpei_cpu = cpumask_any(cpu_online_mask); mask = cpumask_of(new_cpei_cpu); set_cpei_target_cpu(new_cpei_cpu); data = irq_get_irq_data(ia64_cpe_irq); /* * Switch for now, immediately, we need to do fake intr * as other interrupts, but need to study CPEI behaviour with * polling before making changes. */ if (data && data->chip) { data->chip->irq_disable(data); data->chip->irq_set_affinity(data, mask, false); data->chip->irq_enable(data); printk ("Re-targeting CPEI to cpu %d\n", new_cpei_cpu); } } if (!data) { printk ("Unable to retarget CPEI, offline cpu [%d] failed\n", cpu); retval = -EBUSY; } } return retval; } /* must be called with cpucontrol mutex held */ int __cpu_disable(void) { int cpu = smp_processor_id(); /* * dont permit boot processor for now */ if (cpu == 0 && !bsp_remove_ok) { printk ("Your platform does not support removal of BSP\n"); return (-EBUSY); } if (ia64_platform_is("sn2")) { if (!sn_cpu_disable_allowed(cpu)) return -EBUSY; } set_cpu_online(cpu, false); if (migrate_platform_irqs(cpu)) { set_cpu_online(cpu, true); return -EBUSY; } remove_siblinginfo(cpu); fixup_irqs(); local_flush_tlb_all(); cpu_clear(cpu, cpu_callin_map); return 0; } void __cpu_die(unsigned int cpu) { unsigned int i; for (i = 0; i < 100; i++) { /* They ack this in play_dead by setting CPU_DEAD */ if (per_cpu(cpu_state, cpu) == CPU_DEAD) { printk ("CPU %d is now offline\n", cpu); return; } msleep(100); } printk(KERN_ERR "CPU %u didn't die...\n", cpu); } #endif /* CONFIG_HOTPLUG_CPU */ void smp_cpus_done (unsigned int dummy) { int cpu; unsigned long bogosum = 0; /* * Allow the user to impress friends. */ for_each_online_cpu(cpu) { bogosum += cpu_data(cpu)->loops_per_jiffy; } printk(KERN_INFO "Total of %d processors activated (%lu.%02lu BogoMIPS).\n", (int)num_online_cpus(), bogosum/(500000/HZ), (bogosum/(5000/HZ))%100); } static inline void set_cpu_sibling_map(int cpu) { int i; for_each_online_cpu(i) { if ((cpu_data(cpu)->socket_id == cpu_data(i)->socket_id)) { cpu_set(i, cpu_core_map[cpu]); cpu_set(cpu, cpu_core_map[i]); if (cpu_data(cpu)->core_id == cpu_data(i)->core_id) { cpu_set(i, per_cpu(cpu_sibling_map, cpu)); cpu_set(cpu, per_cpu(cpu_sibling_map, i)); } } } } int __cpuinit __cpu_up(unsigned int cpu, struct task_struct *tidle) { int ret; int sapicid; sapicid = ia64_cpu_to_sapicid[cpu]; if (sapicid == -1) return -EINVAL; /* * Already booted cpu? not valid anymore since we dont * do idle loop tightspin anymore. */ if (cpu_isset(cpu, cpu_callin_map)) return -EINVAL; per_cpu(cpu_state, cpu) = CPU_UP_PREPARE; /* Processor goes to start_secondary(), sets online flag */ ret = do_boot_cpu(sapicid, cpu, tidle); if (ret < 0) return ret; if (cpu_data(cpu)->threads_per_core == 1 && cpu_data(cpu)->cores_per_socket == 1) { cpu_set(cpu, per_cpu(cpu_sibling_map, cpu)); cpu_set(cpu, cpu_core_map[cpu]); return 0; } set_cpu_sibling_map(cpu); return 0; } /* * Assume that CPUs have been discovered by some platform-dependent interface. For * SoftSDV/Lion, that would be ACPI. * * Setup of the IPI irq handler is done in irq.c:init_IRQ_SMP(). */ void __init init_smp_config(void) { struct fptr { unsigned long fp; unsigned long gp; } *ap_startup; long sal_ret; /* Tell SAL where to drop the APs. */ ap_startup = (struct fptr *) start_ap; sal_ret = ia64_sal_set_vectors(SAL_VECTOR_OS_BOOT_RENDEZ, ia64_tpa(ap_startup->fp), ia64_tpa(ap_startup->gp), 0, 0, 0, 0); if (sal_ret < 0) printk(KERN_ERR "SMP: Can't set SAL AP Boot Rendezvous: %s\n", ia64_sal_strerror(sal_ret)); } /* * identify_siblings(cpu) gets called from identify_cpu. This populates the * information related to logical execution units in per_cpu_data structure. */ void identify_siblings(struct cpuinfo_ia64 *c) { long status; u16 pltid; pal_logical_to_physical_t info; status = ia64_pal_logical_to_phys(-1, &info); if (status != PAL_STATUS_SUCCESS) { if (status != PAL_STATUS_UNIMPLEMENTED) { printk(KERN_ERR "ia64_pal_logical_to_phys failed with %ld\n", status); return; } info.overview_ppid = 0; info.overview_cpp = 1; info.overview_tpc = 1; } status = ia64_sal_physical_id_info(&pltid); if (status != PAL_STATUS_SUCCESS) { if (status != PAL_STATUS_UNIMPLEMENTED) printk(KERN_ERR "ia64_sal_pltid failed with %ld\n", status); return; } c->socket_id = (pltid << 8) | info.overview_ppid; if (info.overview_cpp == 1 && info.overview_tpc == 1) return; c->cores_per_socket = info.overview_cpp; c->threads_per_core = info.overview_tpc; c->num_log = info.overview_num_log; c->core_id = info.log1_cid; c->thread_id = info.log1_tid; } /* * returns non zero, if multi-threading is enabled * on at least one physical package. Due to hotplug cpu * and (maxcpus=), all threads may not necessarily be enabled * even though the processor supports multi-threading. */ int is_multithreading_enabled(void) { int i, j; for_each_present_cpu(i) { for_each_present_cpu(j) { if (j == i) continue; if ((cpu_data(j)->socket_id == cpu_data(i)->socket_id)) { if (cpu_data(j)->core_id == cpu_data(i)->core_id) return 1; } } } return 0; } EXPORT_SYMBOL_GPL(is_multithreading_enabled);
gpl-3.0
raptorz/shadowsocks-android
src/main/jni/openssl/crypto/bio/bss_null.c
877
4724
/* crypto/bio/bss_null.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <errno.h> #include "cryptlib.h" #include <openssl/bio.h> static int null_write(BIO *h, const char *buf, int num); static int null_read(BIO *h, char *buf, int size); static int null_puts(BIO *h, const char *str); static int null_gets(BIO *h, char *str, int size); static long null_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int null_new(BIO *h); static int null_free(BIO *data); static BIO_METHOD null_method= { BIO_TYPE_NULL, "NULL", null_write, null_read, null_puts, null_gets, null_ctrl, null_new, null_free, NULL, }; BIO_METHOD *BIO_s_null(void) { return(&null_method); } static int null_new(BIO *bi) { bi->init=1; bi->num=0; bi->ptr=(NULL); return(1); } static int null_free(BIO *a) { if (a == NULL) return(0); return(1); } static int null_read(BIO *b, char *out, int outl) { return(0); } static int null_write(BIO *b, const char *in, int inl) { return(inl); } static long null_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret=1; switch (cmd) { case BIO_CTRL_RESET: case BIO_CTRL_EOF: case BIO_CTRL_SET: case BIO_CTRL_SET_CLOSE: case BIO_CTRL_FLUSH: case BIO_CTRL_DUP: ret=1; break; case BIO_CTRL_GET_CLOSE: case BIO_CTRL_INFO: case BIO_CTRL_GET: case BIO_CTRL_PENDING: case BIO_CTRL_WPENDING: default: ret=0; break; } return(ret); } static int null_gets(BIO *bp, char *buf, int size) { return(0); } static int null_puts(BIO *bp, const char *str) { if (str == NULL) return(0); return(strlen(str)); }
gpl-3.0
FabianKnapp/nexmon
utilities/gettext/gettext-tools/gnulib-lib/libxml/c14n.c
111
71073
/* * "Canonical XML" implementation * http://www.w3.org/TR/xml-c14n * * "Exclusive XML Canonicalization" implementation * http://www.w3.org/TR/xml-exc-c14n * * See Copyright for the status of this software. * * Author: Aleksey Sanin <aleksey@aleksey.com> */ #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_C14N_ENABLED #ifdef LIBXML_OUTPUT_ENABLED #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <string.h> #include <libxml/tree.h> #include <libxml/parser.h> #include <libxml/uri.h> #include <libxml/xmlerror.h> #include <libxml/globals.h> #include <libxml/xpathInternals.h> #include <libxml/c14n.h> #include "buf.h" /************************************************************************ * * * Some declaration better left private ATM * * * ************************************************************************/ typedef enum { XMLC14N_BEFORE_DOCUMENT_ELEMENT = 0, XMLC14N_INSIDE_DOCUMENT_ELEMENT = 1, XMLC14N_AFTER_DOCUMENT_ELEMENT = 2 } xmlC14NPosition; typedef struct _xmlC14NVisibleNsStack { int nsCurEnd; /* number of nodes in the set */ int nsPrevStart; /* the begginning of the stack for previous visible node */ int nsPrevEnd; /* the end of the stack for previous visible node */ int nsMax; /* size of the array as allocated */ xmlNsPtr *nsTab; /* array of ns in no particular order */ xmlNodePtr *nodeTab; /* array of nodes in no particular order */ } xmlC14NVisibleNsStack, *xmlC14NVisibleNsStackPtr; typedef struct _xmlC14NCtx { /* input parameters */ xmlDocPtr doc; xmlC14NIsVisibleCallback is_visible_callback; void* user_data; int with_comments; xmlOutputBufferPtr buf; /* position in the XML document */ xmlC14NPosition pos; int parent_is_doc; xmlC14NVisibleNsStackPtr ns_rendered; /* C14N mode */ xmlC14NMode mode; /* exclusive canonicalization */ xmlChar **inclusive_ns_prefixes; /* error number */ int error; } xmlC14NCtx, *xmlC14NCtxPtr; static xmlC14NVisibleNsStackPtr xmlC14NVisibleNsStackCreate (void); static void xmlC14NVisibleNsStackDestroy (xmlC14NVisibleNsStackPtr cur); static void xmlC14NVisibleNsStackAdd (xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlNodePtr node); static void xmlC14NVisibleNsStackSave (xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state); static void xmlC14NVisibleNsStackRestore (xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state); static void xmlC14NVisibleNsStackShift (xmlC14NVisibleNsStackPtr cur); static int xmlC14NVisibleNsStackFind (xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns); static int xmlExcC14NVisibleNsStackFind (xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlC14NCtxPtr ctx); static int xmlC14NIsNodeInNodeset (xmlNodeSetPtr nodes, xmlNodePtr node, xmlNodePtr parent); static int xmlC14NProcessNode(xmlC14NCtxPtr ctx, xmlNodePtr cur); static int xmlC14NProcessNodeList(xmlC14NCtxPtr ctx, xmlNodePtr cur); typedef enum { XMLC14N_NORMALIZE_ATTR = 0, XMLC14N_NORMALIZE_COMMENT = 1, XMLC14N_NORMALIZE_PI = 2, XMLC14N_NORMALIZE_TEXT = 3 } xmlC14NNormalizationMode; static xmlChar *xmlC11NNormalizeString(const xmlChar * input, xmlC14NNormalizationMode mode); #define xmlC11NNormalizeAttr( a ) \ xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_ATTR) #define xmlC11NNormalizeComment( a ) \ xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_COMMENT) #define xmlC11NNormalizePI( a ) \ xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_PI) #define xmlC11NNormalizeText( a ) \ xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_TEXT) #define xmlC14NIsVisible( ctx, node, parent ) \ (((ctx)->is_visible_callback != NULL) ? \ (ctx)->is_visible_callback((ctx)->user_data, \ (xmlNodePtr)(node), (xmlNodePtr)(parent)) : 1) #define xmlC14NIsExclusive( ctx ) \ ( (ctx)->mode == XML_C14N_EXCLUSIVE_1_0 ) /************************************************************************ * * * Some factorized error routines * * * ************************************************************************/ /** * xmlC14NErrMemory: * @extra: extra informations * * Handle a redefinition of memory error */ static void xmlC14NErrMemory(const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_ERR_NO_MEMORY, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Memory allocation failed : %s\n", extra); } /** * xmlC14NErrParam: * @extra: extra informations * * Handle a redefinition of param error */ static void xmlC14NErrParam(const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_ERR_INTERNAL_ERROR, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Invalid parameter : %s\n", extra); } /** * xmlC14NErrInternal: * @extra: extra informations * * Handle a redefinition of internal error */ static void xmlC14NErrInternal(const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_ERR_INTERNAL_ERROR, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Internal error : %s\n", extra); } /** * xmlC14NErrInvalidNode: * @extra: extra informations * * Handle a redefinition of invalid node error */ static void xmlC14NErrInvalidNode(const char *node_type, const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_C14N_INVALID_NODE, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Node %s is invalid here : %s\n", node_type, extra); } /** * xmlC14NErrUnknownNode: * @extra: extra informations * * Handle a redefinition of unknown node error */ static void xmlC14NErrUnknownNode(int node_type, const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_C14N_UNKNOW_NODE, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Unknown node type %d found : %s\n", node_type, extra); } /** * xmlC14NErrRelativeNamespace: * @extra: extra informations * * Handle a redefinition of relative namespace error */ static void xmlC14NErrRelativeNamespace(const char *ns_uri) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_C14N_RELATIVE_NAMESPACE, XML_ERR_ERROR, NULL, 0, NULL, NULL, NULL, 0, 0, "Relative namespace UR is invalid here : %s\n", ns_uri); } /** * xmlC14NErr: * @ctxt: a C14N evaluation context * @node: the context node * @error: the erorr code * @msg: the message * @extra: extra informations * * Handle a redefinition of attribute error */ static void xmlC14NErr(xmlC14NCtxPtr ctxt, xmlNodePtr node, int error, const char * msg) { if (ctxt != NULL) ctxt->error = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, node, XML_FROM_C14N, error, XML_ERR_ERROR, NULL, 0, NULL, NULL, NULL, 0, 0, "%s", msg); } /************************************************************************ * * * The implementation internals * * * ************************************************************************/ #define XML_NAMESPACES_DEFAULT 16 static int xmlC14NIsNodeInNodeset(xmlNodeSetPtr nodes, xmlNodePtr node, xmlNodePtr parent) { if((nodes != NULL) && (node != NULL)) { if(node->type != XML_NAMESPACE_DECL) { return(xmlXPathNodeSetContains(nodes, node)); } else { xmlNs ns; memcpy(&ns, node, sizeof(ns)); /* this is a libxml hack! check xpath.c for details */ if((parent != NULL) && (parent->type == XML_ATTRIBUTE_NODE)) { ns.next = (xmlNsPtr)parent->parent; } else { ns.next = (xmlNsPtr)parent; } /* * If the input is an XPath node-set, then the node-set must explicitly * contain every node to be rendered to the canonical form. */ return(xmlXPathNodeSetContains(nodes, (xmlNodePtr)&ns)); } } return(1); } static xmlC14NVisibleNsStackPtr xmlC14NVisibleNsStackCreate(void) { xmlC14NVisibleNsStackPtr ret; ret = (xmlC14NVisibleNsStackPtr) xmlMalloc(sizeof(xmlC14NVisibleNsStack)); if (ret == NULL) { xmlC14NErrMemory("creating namespaces stack"); return(NULL); } memset(ret, 0 , (size_t) sizeof(xmlC14NVisibleNsStack)); return(ret); } static void xmlC14NVisibleNsStackDestroy(xmlC14NVisibleNsStackPtr cur) { if(cur == NULL) { xmlC14NErrParam("destroying namespaces stack"); return; } if(cur->nsTab != NULL) { memset(cur->nsTab, 0, cur->nsMax * sizeof(xmlNsPtr)); xmlFree(cur->nsTab); } if(cur->nodeTab != NULL) { memset(cur->nodeTab, 0, cur->nsMax * sizeof(xmlNodePtr)); xmlFree(cur->nodeTab); } memset(cur, 0, sizeof(xmlC14NVisibleNsStack)); xmlFree(cur); } static void xmlC14NVisibleNsStackAdd(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlNodePtr node) { if((cur == NULL) || ((cur->nsTab == NULL) && (cur->nodeTab != NULL)) || ((cur->nsTab != NULL) && (cur->nodeTab == NULL))) { xmlC14NErrParam("adding namespace to stack"); return; } if ((cur->nsTab == NULL) && (cur->nodeTab == NULL)) { cur->nsTab = (xmlNsPtr*) xmlMalloc(XML_NAMESPACES_DEFAULT * sizeof(xmlNsPtr)); cur->nodeTab = (xmlNodePtr*) xmlMalloc(XML_NAMESPACES_DEFAULT * sizeof(xmlNodePtr)); if ((cur->nsTab == NULL) || (cur->nodeTab == NULL)) { xmlC14NErrMemory("adding node to stack"); return; } memset(cur->nsTab, 0 , XML_NAMESPACES_DEFAULT * sizeof(xmlNsPtr)); memset(cur->nodeTab, 0 , XML_NAMESPACES_DEFAULT * sizeof(xmlNodePtr)); cur->nsMax = XML_NAMESPACES_DEFAULT; } else if(cur->nsMax == cur->nsCurEnd) { void *tmp; int tmpSize; tmpSize = 2 * cur->nsMax; tmp = xmlRealloc(cur->nsTab, tmpSize * sizeof(xmlNsPtr)); if (tmp == NULL) { xmlC14NErrMemory("adding node to stack"); return; } cur->nsTab = (xmlNsPtr*)tmp; tmp = xmlRealloc(cur->nodeTab, tmpSize * sizeof(xmlNodePtr)); if (tmp == NULL) { xmlC14NErrMemory("adding node to stack"); return; } cur->nodeTab = (xmlNodePtr*)tmp; cur->nsMax = tmpSize; } cur->nsTab[cur->nsCurEnd] = ns; cur->nodeTab[cur->nsCurEnd] = node; ++cur->nsCurEnd; } static void xmlC14NVisibleNsStackSave(xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state) { if((cur == NULL) || (state == NULL)) { xmlC14NErrParam("saving namespaces stack"); return; } state->nsCurEnd = cur->nsCurEnd; state->nsPrevStart = cur->nsPrevStart; state->nsPrevEnd = cur->nsPrevEnd; } static void xmlC14NVisibleNsStackRestore(xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state) { if((cur == NULL) || (state == NULL)) { xmlC14NErrParam("restoring namespaces stack"); return; } cur->nsCurEnd = state->nsCurEnd; cur->nsPrevStart = state->nsPrevStart; cur->nsPrevEnd = state->nsPrevEnd; } static void xmlC14NVisibleNsStackShift(xmlC14NVisibleNsStackPtr cur) { if(cur == NULL) { xmlC14NErrParam("shifting namespaces stack"); return; } cur->nsPrevStart = cur->nsPrevEnd; cur->nsPrevEnd = cur->nsCurEnd; } static int xmlC14NStrEqual(const xmlChar *str1, const xmlChar *str2) { if (str1 == str2) return(1); if (str1 == NULL) return((*str2) == '\0'); if (str2 == NULL) return((*str1) == '\0'); do { if (*str1++ != *str2) return(0); } while (*str2++); return(1); } /** * xmlC14NVisibleNsStackFind: * @ctx: the C14N context * @ns: the namespace to check * * Checks whether the given namespace was already rendered or not * * Returns 1 if we already wrote this namespace or 0 otherwise */ static int xmlC14NVisibleNsStackFind(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns) { int i; const xmlChar *prefix; const xmlChar *href; int has_empty_ns; if(cur == NULL) { xmlC14NErrParam("searching namespaces stack (c14n)"); return (0); } /* * if the default namespace xmlns="" is not defined yet then * we do not want to print it out */ prefix = ((ns == NULL) || (ns->prefix == NULL)) ? BAD_CAST "" : ns->prefix; href = ((ns == NULL) || (ns->href == NULL)) ? BAD_CAST "" : ns->href; has_empty_ns = (xmlC14NStrEqual(prefix, NULL) && xmlC14NStrEqual(href, NULL)); if (cur->nsTab != NULL) { int start = (has_empty_ns) ? 0 : cur->nsPrevStart; for (i = cur->nsCurEnd - 1; i >= start; --i) { xmlNsPtr ns1 = cur->nsTab[i]; if(xmlC14NStrEqual(prefix, (ns1 != NULL) ? ns1->prefix : NULL)) { return(xmlC14NStrEqual(href, (ns1 != NULL) ? ns1->href : NULL)); } } } return(has_empty_ns); } static int xmlExcC14NVisibleNsStackFind(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlC14NCtxPtr ctx) { int i; const xmlChar *prefix; const xmlChar *href; int has_empty_ns; if(cur == NULL) { xmlC14NErrParam("searching namespaces stack (exc c14n)"); return (0); } /* * if the default namespace xmlns="" is not defined yet then * we do not want to print it out */ prefix = ((ns == NULL) || (ns->prefix == NULL)) ? BAD_CAST "" : ns->prefix; href = ((ns == NULL) || (ns->href == NULL)) ? BAD_CAST "" : ns->href; has_empty_ns = (xmlC14NStrEqual(prefix, NULL) && xmlC14NStrEqual(href, NULL)); if (cur->nsTab != NULL) { int start = 0; for (i = cur->nsCurEnd - 1; i >= start; --i) { xmlNsPtr ns1 = cur->nsTab[i]; if(xmlC14NStrEqual(prefix, (ns1 != NULL) ? ns1->prefix : NULL)) { if(xmlC14NStrEqual(href, (ns1 != NULL) ? ns1->href : NULL)) { return(xmlC14NIsVisible(ctx, ns1, cur->nodeTab[i])); } else { return(0); } } } } return(has_empty_ns); } /** * xmlC14NIsXmlNs: * @ns: the namespace to check * * Checks whether the given namespace is a default "xml:" namespace * with href="http://www.w3.org/XML/1998/namespace" * * Returns 1 if the node is default or 0 otherwise */ /* todo: make it a define? */ static int xmlC14NIsXmlNs(xmlNsPtr ns) { return ((ns != NULL) && (xmlStrEqual(ns->prefix, BAD_CAST "xml")) && (xmlStrEqual(ns->href, XML_XML_NAMESPACE))); } /** * xmlC14NNsCompare: * @ns1: the pointer to first namespace * @ns2: the pointer to second namespace * * Compares the namespaces by names (prefixes). * * Returns -1 if ns1 < ns2, 0 if ns1 == ns2 or 1 if ns1 > ns2. */ static int xmlC14NNsCompare(xmlNsPtr ns1, xmlNsPtr ns2) { if (ns1 == ns2) return (0); if (ns1 == NULL) return (-1); if (ns2 == NULL) return (1); return (xmlStrcmp(ns1->prefix, ns2->prefix)); } /** * xmlC14NPrintNamespaces: * @ns: the pointer to namespace * @ctx: the C14N context * * Prints the given namespace to the output buffer from C14N context. * * Returns 1 on success or 0 on fail. */ static int xmlC14NPrintNamespaces(const xmlNsPtr ns, xmlC14NCtxPtr ctx) { if ((ns == NULL) || (ctx == NULL)) { xmlC14NErrParam("writing namespaces"); return 0; } if (ns->prefix != NULL) { xmlOutputBufferWriteString(ctx->buf, " xmlns:"); xmlOutputBufferWriteString(ctx->buf, (const char *) ns->prefix); xmlOutputBufferWriteString(ctx->buf, "="); } else { xmlOutputBufferWriteString(ctx->buf, " xmlns="); } if(ns->href != NULL) { xmlBufWriteQuotedString(ctx->buf->buffer, ns->href); } else { xmlOutputBufferWriteString(ctx->buf, "\"\""); } return (1); } /** * xmlC14NProcessNamespacesAxis: * @ctx: the C14N context * @node: the current node * * Prints out canonical namespace axis of the current node to the * buffer from C14N context as follows * * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n) * * Namespace Axis * Consider a list L containing only namespace nodes in the * axis and in the node-set in lexicographic order (ascending). To begin * processing L, if the first node is not the default namespace node (a node * with no namespace URI and no local name), then generate a space followed * by xmlns="" if and only if the following conditions are met: * - the element E that owns the axis is in the node-set * - The nearest ancestor element of E in the node-set has a default * namespace node in the node-set (default namespace nodes always * have non-empty values in XPath) * The latter condition eliminates unnecessary occurrences of xmlns="" in * the canonical form since an element only receives an xmlns="" if its * default namespace is empty and if it has an immediate parent in the * canonical form that has a non-empty default namespace. To finish * processing L, simply process every namespace node in L, except omit * namespace node with local name xml, which defines the xml prefix, * if its string value is http://www.w3.org/XML/1998/namespace. * * Exclusive XML Canonicalization v 1.0 (http://www.w3.org/TR/xml-exc-c14n) * Canonical XML applied to a document subset requires the search of the * ancestor nodes of each orphan element node for attributes in the xml * namespace, such as xml:lang and xml:space. These are copied into the * element node except if a declaration of the same attribute is already * in the attribute axis of the element (whether or not it is included in * the document subset). This search and copying are omitted from the * Exclusive XML Canonicalization method. * * Returns 0 on success or -1 on fail. */ static int xmlC14NProcessNamespacesAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible) { xmlNodePtr n; xmlNsPtr ns, tmp; xmlListPtr list; int already_rendered; int has_empty_ns = 0; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("processing namespaces axis (c14n)"); return (-1); } /* * Create a sorted list to store element namespaces */ list = xmlListCreate(NULL, (xmlListDataCompare) xmlC14NNsCompare); if (list == NULL) { xmlC14NErrInternal("creating namespaces list (c14n)"); return (-1); } /* check all namespaces */ for(n = cur; n != NULL; n = n->parent) { for(ns = n->nsDef; ns != NULL; ns = ns->next) { tmp = xmlSearchNs(cur->doc, cur, ns->prefix); if((tmp == ns) && !xmlC14NIsXmlNs(ns) && xmlC14NIsVisible(ctx, ns, cur)) { already_rendered = xmlC14NVisibleNsStackFind(ctx->ns_rendered, ns); if(visible) { xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur); } if(!already_rendered) { xmlListInsert(list, ns); } if(xmlStrlen(ns->prefix) == 0) { has_empty_ns = 1; } } } } /** * if the first node is not the default namespace node (a node with no * namespace URI and no local name), then generate a space followed by * xmlns="" if and only if the following conditions are met: * - the element E that owns the axis is in the node-set * - the nearest ancestor element of E in the node-set has a default * namespace node in the node-set (default namespace nodes always * have non-empty values in XPath) */ if(visible && !has_empty_ns) { static xmlNs ns_default; memset(&ns_default, 0, sizeof(ns_default)); if(!xmlC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default)) { xmlC14NPrintNamespaces(&ns_default, ctx); } } /* * print out all elements from list */ xmlListWalk(list, (xmlListWalker) xmlC14NPrintNamespaces, (const void *) ctx); /* * Cleanup */ xmlListDelete(list); return (0); } /** * xmlExcC14NProcessNamespacesAxis: * @ctx: the C14N context * @node: the current node * * Prints out exclusive canonical namespace axis of the current node to the * buffer from C14N context as follows * * Exclusive XML Canonicalization * http://www.w3.org/TR/xml-exc-c14n * * If the element node is in the XPath subset then output the node in * accordance with Canonical XML except for namespace nodes which are * rendered as follows: * * 1. Render each namespace node iff: * * it is visibly utilized by the immediate parent element or one of * its attributes, or is present in InclusiveNamespaces PrefixList, and * * its prefix and value do not appear in ns_rendered. ns_rendered is * obtained by popping the state stack in order to obtain a list of * prefixes and their values which have already been rendered by * an output ancestor of the namespace node's parent element. * 2. Append the rendered namespace node to the list ns_rendered of namespace * nodes rendered by output ancestors. Push ns_rendered on state stack and * recurse. * 3. After the recursion returns, pop thestate stack. * * * Returns 0 on success or -1 on fail. */ static int xmlExcC14NProcessNamespacesAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible) { xmlNsPtr ns; xmlListPtr list; xmlAttrPtr attr; int already_rendered; int has_empty_ns = 0; int has_visibly_utilized_empty_ns = 0; int has_empty_ns_in_inclusive_list = 0; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("processing namespaces axis (exc c14n)"); return (-1); } if(!xmlC14NIsExclusive(ctx)) { xmlC14NErrParam("processing namespaces axis (exc c14n)"); return (-1); } /* * Create a sorted list to store element namespaces */ list = xmlListCreate(NULL, (xmlListDataCompare) xmlC14NNsCompare); if (list == NULL) { xmlC14NErrInternal("creating namespaces list (exc c14n)"); return (-1); } /* * process inclusive namespaces: * All namespace nodes appearing on inclusive ns list are * handled as provided in Canonical XML */ if(ctx->inclusive_ns_prefixes != NULL) { xmlChar *prefix; int i; for (i = 0; ctx->inclusive_ns_prefixes[i] != NULL; ++i) { prefix = ctx->inclusive_ns_prefixes[i]; /* * Special values for namespace with empty prefix */ if (xmlStrEqual(prefix, BAD_CAST "#default") || xmlStrEqual(prefix, BAD_CAST "")) { prefix = NULL; has_empty_ns_in_inclusive_list = 1; } ns = xmlSearchNs(cur->doc, cur, prefix); if((ns != NULL) && !xmlC14NIsXmlNs(ns) && xmlC14NIsVisible(ctx, ns, cur)) { already_rendered = xmlC14NVisibleNsStackFind(ctx->ns_rendered, ns); if(visible) { xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur); } if(!already_rendered) { xmlListInsert(list, ns); } if(xmlStrlen(ns->prefix) == 0) { has_empty_ns = 1; } } } } /* add node namespace */ if(cur->ns != NULL) { ns = cur->ns; } else { ns = xmlSearchNs(cur->doc, cur, NULL); has_visibly_utilized_empty_ns = 1; } if((ns != NULL) && !xmlC14NIsXmlNs(ns)) { if(visible && xmlC14NIsVisible(ctx, ns, cur)) { if(!xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, ns, ctx)) { xmlListInsert(list, ns); } } if(visible) { xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur); } if(xmlStrlen(ns->prefix) == 0) { has_empty_ns = 1; } } /* add attributes */ for(attr = cur->properties; attr != NULL; attr = attr->next) { /* * we need to check that attribute is visible and has non * default namespace (XML Namespaces: "default namespaces * do not apply directly to attributes") */ if((attr->ns != NULL) && !xmlC14NIsXmlNs(attr->ns) && xmlC14NIsVisible(ctx, attr, cur)) { already_rendered = xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, attr->ns, ctx); xmlC14NVisibleNsStackAdd(ctx->ns_rendered, attr->ns, cur); if(!already_rendered && visible) { xmlListInsert(list, attr->ns); } if(xmlStrlen(attr->ns->prefix) == 0) { has_empty_ns = 1; } } else if((attr->ns != NULL) && (xmlStrlen(attr->ns->prefix) == 0) && (xmlStrlen(attr->ns->href) == 0)) { has_visibly_utilized_empty_ns = 1; } } /* * Process xmlns="" */ if(visible && has_visibly_utilized_empty_ns && !has_empty_ns && !has_empty_ns_in_inclusive_list) { static xmlNs ns_default; memset(&ns_default, 0, sizeof(ns_default)); already_rendered = xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default, ctx); if(!already_rendered) { xmlC14NPrintNamespaces(&ns_default, ctx); } } else if(visible && !has_empty_ns && has_empty_ns_in_inclusive_list) { static xmlNs ns_default; memset(&ns_default, 0, sizeof(ns_default)); if(!xmlC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default)) { xmlC14NPrintNamespaces(&ns_default, ctx); } } /* * print out all elements from list */ xmlListWalk(list, (xmlListWalker) xmlC14NPrintNamespaces, (const void *) ctx); /* * Cleanup */ xmlListDelete(list); return (0); } /** * xmlC14NIsXmlAttr: * @attr: the attr to check * * Checks whether the given attribute is a default "xml:" namespace * with href="http://www.w3.org/XML/1998/namespace" * * Returns 1 if the node is default or 0 otherwise */ /* todo: make it a define? */ static int xmlC14NIsXmlAttr(xmlAttrPtr attr) { return ((attr->ns != NULL) && (xmlC14NIsXmlNs(attr->ns) != 0)); } /** * xmlC14NAttrsCompare: * @attr1: the pointer tls o first attr * @attr2: the pointer to second attr * * Prints the given attribute to the output buffer from C14N context. * * Returns -1 if attr1 < attr2, 0 if attr1 == attr2 or 1 if attr1 > attr2. */ static int xmlC14NAttrsCompare(xmlAttrPtr attr1, xmlAttrPtr attr2) { int ret = 0; /* * Simple cases */ if (attr1 == attr2) return (0); if (attr1 == NULL) return (-1); if (attr2 == NULL) return (1); if (attr1->ns == attr2->ns) { return (xmlStrcmp(attr1->name, attr2->name)); } /* * Attributes in the default namespace are first * because the default namespace is not applied to * unqualified attributes */ if (attr1->ns == NULL) return (-1); if (attr2->ns == NULL) return (1); if (attr1->ns->prefix == NULL) return (-1); if (attr2->ns->prefix == NULL) return (1); ret = xmlStrcmp(attr1->ns->href, attr2->ns->href); if (ret == 0) { ret = xmlStrcmp(attr1->name, attr2->name); } return (ret); } /** * xmlC14NPrintAttrs: * @attr: the pointer to attr * @ctx: the C14N context * * Prints out canonical attribute urrent node to the * buffer from C14N context as follows * * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n) * * Returns 1 on success or 0 on fail. */ static int xmlC14NPrintAttrs(const xmlAttrPtr attr, xmlC14NCtxPtr ctx) { xmlChar *value; xmlChar *buffer; if ((attr == NULL) || (ctx == NULL)) { xmlC14NErrParam("writing attributes"); return (0); } xmlOutputBufferWriteString(ctx->buf, " "); if (attr->ns != NULL && xmlStrlen(attr->ns->prefix) > 0) { xmlOutputBufferWriteString(ctx->buf, (const char *) attr->ns->prefix); xmlOutputBufferWriteString(ctx->buf, ":"); } xmlOutputBufferWriteString(ctx->buf, (const char *) attr->name); xmlOutputBufferWriteString(ctx->buf, "=\""); value = xmlNodeListGetString(ctx->doc, attr->children, 1); /* todo: should we log an error if value==NULL ? */ if (value != NULL) { buffer = xmlC11NNormalizeAttr(value); xmlFree(value); if (buffer != NULL) { xmlOutputBufferWriteString(ctx->buf, (const char *) buffer); xmlFree(buffer); } else { xmlC14NErrInternal("normalizing attributes axis"); return (0); } } xmlOutputBufferWriteString(ctx->buf, "\""); return (1); } /** * xmlC14NFindHiddenParentAttr: * * Finds an attribute in a hidden parent node. * * Returns a pointer to the attribute node (if found) or NULL otherwise. */ static xmlAttrPtr xmlC14NFindHiddenParentAttr(xmlC14NCtxPtr ctx, xmlNodePtr cur, const xmlChar * name, const xmlChar * ns) { xmlAttrPtr res; while((cur != NULL) && (!xmlC14NIsVisible(ctx, cur, cur->parent))) { res = xmlHasNsProp(cur, name, ns); if(res != NULL) { return res; } cur = cur->parent; } return NULL; } /** * xmlC14NFixupBaseAttr: * * Fixes up the xml:base attribute * * Returns the newly created attribute or NULL */ static xmlAttrPtr xmlC14NFixupBaseAttr(xmlC14NCtxPtr ctx, xmlAttrPtr xml_base_attr) { xmlChar * res = NULL; xmlNodePtr cur; xmlAttrPtr attr; xmlChar * tmp_str; xmlChar * tmp_str2; int tmp_str_len; if ((ctx == NULL) || (xml_base_attr == NULL) || (xml_base_attr->parent == NULL)) { xmlC14NErrParam("processing xml:base attribute"); return (NULL); } /* start from current value */ res = xmlNodeListGetString(ctx->doc, xml_base_attr->children, 1); if(res == NULL) { xmlC14NErrInternal("processing xml:base attribute - can't get attr value"); return (NULL); } /* go up the stack until we find a node that we rendered already */ cur = xml_base_attr->parent->parent; while((cur != NULL) && (!xmlC14NIsVisible(ctx, cur, cur->parent))) { attr = xmlHasNsProp(cur, BAD_CAST "base", XML_XML_NAMESPACE); if(attr != NULL) { /* get attr value */ tmp_str = xmlNodeListGetString(ctx->doc, attr->children, 1); if(tmp_str == NULL) { xmlFree(res); xmlC14NErrInternal("processing xml:base attribute - can't get attr value"); return (NULL); } /* we need to add '/' if our current base uri ends with '..' or '.' to ensure that we are forced to go "up" all the time */ tmp_str_len = xmlStrlen(tmp_str); if(tmp_str_len > 1 && tmp_str[tmp_str_len - 2] == '.') { tmp_str2 = xmlStrcat(tmp_str, BAD_CAST "/"); if(tmp_str2 == NULL) { xmlFree(tmp_str); xmlFree(res); xmlC14NErrInternal("processing xml:base attribute - can't modify uri"); return (NULL); } tmp_str = tmp_str2; } /* build uri */ tmp_str2 = xmlBuildURI(res, tmp_str); if(tmp_str2 == NULL) { xmlFree(tmp_str); xmlFree(res); xmlC14NErrInternal("processing xml:base attribute - can't construct uri"); return (NULL); } /* cleanup and set the new res */ xmlFree(tmp_str); xmlFree(res); res = tmp_str2; } /* next */ cur = cur->parent; } /* check if result uri is empty or not */ if((res == NULL) || xmlStrEqual(res, BAD_CAST "")) { xmlFree(res); return (NULL); } /* create and return the new attribute node */ attr = xmlNewNsProp(NULL, xml_base_attr->ns, BAD_CAST "base", res); if(attr == NULL) { xmlFree(res); xmlC14NErrInternal("processing xml:base attribute - can't construct attribute"); return (NULL); } /* done */ xmlFree(res); return (attr); } /** * xmlC14NProcessAttrsAxis: * @ctx: the C14N context * @cur: the current node * @parent_visible: the visibility of parent node * @all_parents_visible: the visibility of all parent nodes * * Prints out canonical attribute axis of the current node to the * buffer from C14N context as follows * * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n) * * Attribute Axis * In lexicographic order (ascending), process each node that * is in the element's attribute axis and in the node-set. * * The processing of an element node E MUST be modified slightly * when an XPath node-set is given as input and the element's * parent is omitted from the node-set. * * * Exclusive XML Canonicalization v 1.0 (http://www.w3.org/TR/xml-exc-c14n) * * Canonical XML applied to a document subset requires the search of the * ancestor nodes of each orphan element node for attributes in the xml * namespace, such as xml:lang and xml:space. These are copied into the * element node except if a declaration of the same attribute is already * in the attribute axis of the element (whether or not it is included in * the document subset). This search and copying are omitted from the * Exclusive XML Canonicalization method. * * Returns 0 on success or -1 on fail. */ static int xmlC14NProcessAttrsAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int parent_visible) { xmlAttrPtr attr; xmlListPtr list; xmlAttrPtr attrs_to_delete = NULL; /* special processing for 1.1 spec */ xmlAttrPtr xml_base_attr = NULL; xmlAttrPtr xml_lang_attr = NULL; xmlAttrPtr xml_space_attr = NULL; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("processing attributes axis"); return (-1); } /* * Create a sorted list to store element attributes */ list = xmlListCreate(NULL, (xmlListDataCompare) xmlC14NAttrsCompare); if (list == NULL) { xmlC14NErrInternal("creating attributes list"); return (-1); } switch(ctx->mode) { case XML_C14N_1_0: /* The processing of an element node E MUST be modified slightly when an XPath node-set is * given as input and the element's parent is omitted from the node-set. The method for processing * the attribute axis of an element E in the node-set is enhanced. All element nodes along E's * ancestor axis are examined for nearest occurrences of attributes in the xml namespace, such * as xml:lang and xml:space (whether or not they are in the node-set). From this list of attributes, * remove any that are in E's attribute axis (whether or not they are in the node-set). Then, * lexicographically merge this attribute list with the nodes of E's attribute axis that are in * the node-set. The result of visiting the attribute axis is computed by processing the attribute * nodes in this merged attribute list. */ /* * Add all visible attributes from current node. */ attr = cur->properties; while (attr != NULL) { /* check that attribute is visible */ if (xmlC14NIsVisible(ctx, attr, cur)) { xmlListInsert(list, attr); } attr = attr->next; } /* * Handle xml attributes */ if (parent_visible && (cur->parent != NULL) && (!xmlC14NIsVisible(ctx, cur->parent, cur->parent->parent))) { xmlNodePtr tmp; /* * If XPath node-set is not specified then the parent is always * visible! */ tmp = cur->parent; while (tmp != NULL) { attr = tmp->properties; while (attr != NULL) { if (xmlC14NIsXmlAttr(attr) != 0) { if (xmlListSearch(list, attr) == NULL) { xmlListInsert(list, attr); } } attr = attr->next; } tmp = tmp->parent; } } /* done */ break; case XML_C14N_EXCLUSIVE_1_0: /* attributes in the XML namespace, such as xml:lang and xml:space * are not imported into orphan nodes of the document subset */ /* * Add all visible attributes from current node. */ attr = cur->properties; while (attr != NULL) { /* check that attribute is visible */ if (xmlC14NIsVisible(ctx, attr, cur)) { xmlListInsert(list, attr); } attr = attr->next; } /* do nothing special for xml attributes */ break; case XML_C14N_1_1: /* The processing of an element node E MUST be modified slightly when an XPath node-set is * given as input and some of the element's ancestors are omitted from the node-set. * * Simple inheritable attributes are attributes that have a value that requires at most a simple * redeclaration. This redeclaration is done by supplying a new value in the child axis. The * redeclaration of a simple inheritable attribute A contained in one of E's ancestors is done * by supplying a value to an attribute Ae inside E with the same name. Simple inheritable attributes * are xml:lang and xml:space. * * The method for processing the attribute axis of an element E in the node-set is hence enhanced. * All element nodes along E's ancestor axis are examined for the nearest occurrences of simple * inheritable attributes in the xml namespace, such as xml:lang and xml:space (whether or not they * are in the node-set). From this list of attributes, any simple inheritable attributes that are * already in E's attribute axis (whether or not they are in the node-set) are removed. Then, * lexicographically merge this attribute list with the nodes of E's attribute axis that are in * the node-set. The result of visiting the attribute axis is computed by processing the attribute * nodes in this merged attribute list. * * The xml:id attribute is not a simple inheritable attribute and no processing of these attributes is * performed. * * The xml:base attribute is not a simple inheritable attribute and requires special processing beyond * a simple redeclaration. * * Attributes in the XML namespace other than xml:base, xml:id, xml:lang, and xml:space MUST be processed * as ordinary attributes. */ /* * Add all visible attributes from current node. */ attr = cur->properties; while (attr != NULL) { /* special processing for XML attribute kiks in only when we have invisible parents */ if ((!parent_visible) || (xmlC14NIsXmlAttr(attr) == 0)) { /* check that attribute is visible */ if (xmlC14NIsVisible(ctx, attr, cur)) { xmlListInsert(list, attr); } } else { int matched = 0; /* check for simple inheritance attributes */ if((!matched) && (xml_lang_attr == NULL) && xmlStrEqual(attr->name, BAD_CAST "lang")) { xml_lang_attr = attr; matched = 1; } if((!matched) && (xml_space_attr == NULL) && xmlStrEqual(attr->name, BAD_CAST "space")) { xml_space_attr = attr; matched = 1; } /* check for base attr */ if((!matched) && (xml_base_attr == NULL) && xmlStrEqual(attr->name, BAD_CAST "base")) { xml_base_attr = attr; matched = 1; } /* otherwise, it is a normal attribute, so just check if it is visible */ if((!matched) && xmlC14NIsVisible(ctx, attr, cur)) { xmlListInsert(list, attr); } } /* move to the next one */ attr = attr->next; } /* special processing for XML attribute kiks in only when we have invisible parents */ if ((parent_visible)) { /* simple inheritance attributes - copy */ if(xml_lang_attr == NULL) { xml_lang_attr = xmlC14NFindHiddenParentAttr(ctx, cur->parent, BAD_CAST "lang", XML_XML_NAMESPACE); } if(xml_lang_attr != NULL) { xmlListInsert(list, xml_lang_attr); } if(xml_space_attr == NULL) { xml_space_attr = xmlC14NFindHiddenParentAttr(ctx, cur->parent, BAD_CAST "space", XML_XML_NAMESPACE); } if(xml_space_attr != NULL) { xmlListInsert(list, xml_space_attr); } /* base uri attribute - fix up */ if(xml_base_attr == NULL) { /* if we don't have base uri attribute, check if we have a "hidden" one above */ xml_base_attr = xmlC14NFindHiddenParentAttr(ctx, cur->parent, BAD_CAST "base", XML_XML_NAMESPACE); } if(xml_base_attr != NULL) { xml_base_attr = xmlC14NFixupBaseAttr(ctx, xml_base_attr); if(xml_base_attr != NULL) { xmlListInsert(list, xml_base_attr); /* note that we MUST delete returned attr node ourselves! */ xml_base_attr->next = attrs_to_delete; attrs_to_delete = xml_base_attr; } } } /* done */ break; } /* * print out all elements from list */ xmlListWalk(list, (xmlListWalker) xmlC14NPrintAttrs, (const void *) ctx); /* * Cleanup */ xmlFreePropList(attrs_to_delete); xmlListDelete(list); return (0); } /** * xmlC14NCheckForRelativeNamespaces: * @ctx: the C14N context * @cur: the current element node * * Checks that current element node has no relative namespaces defined * * Returns 0 if the node has no relative namespaces or -1 otherwise. */ static int xmlC14NCheckForRelativeNamespaces(xmlC14NCtxPtr ctx, xmlNodePtr cur) { xmlNsPtr ns; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("checking for relative namespaces"); return (-1); } ns = cur->nsDef; while (ns != NULL) { if (xmlStrlen(ns->href) > 0) { xmlURIPtr uri; uri = xmlParseURI((const char *) ns->href); if (uri == NULL) { xmlC14NErrInternal("parsing namespace uri"); return (-1); } if (xmlStrlen((const xmlChar *) uri->scheme) == 0) { xmlC14NErrRelativeNamespace(uri->scheme); xmlFreeURI(uri); return (-1); } if ((xmlStrcasecmp((const xmlChar *) uri->scheme, BAD_CAST "urn") != 0) && (xmlStrcasecmp((const xmlChar *) uri->scheme, BAD_CAST "dav") !=0) && (xmlStrlen((const xmlChar *) uri->server) == 0)) { xmlC14NErrRelativeNamespace(uri->scheme); xmlFreeURI(uri); return (-1); } xmlFreeURI(uri); } ns = ns->next; } return (0); } /** * xmlC14NProcessElementNode: * @ctx: the pointer to C14N context object * @cur: the node to process * @visible: this node is visible * @all_parents_visible: whether all the parents of this node are visible * * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n) * * Element Nodes * If the element is not in the node-set, then the result is obtained * by processing the namespace axis, then the attribute axis, then * processing the child nodes of the element that are in the node-set * (in document order). If the element is in the node-set, then the result * is an open angle bracket (<), the element QName, the result of * processing the namespace axis, the result of processing the attribute * axis, a close angle bracket (>), the result of processing the child * nodes of the element that are in the node-set (in document order), an * open angle bracket, a forward slash (/), the element QName, and a close * angle bracket. * * Returns non-negative value on success or negative value on fail */ static int xmlC14NProcessElementNode(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible) { int ret; xmlC14NVisibleNsStack state; int parent_is_doc = 0; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("processing element node"); return (-1); } /* * Check relative relative namespaces: * implementations of XML canonicalization MUST report an operation * failure on documents containing relative namespace URIs. */ if (xmlC14NCheckForRelativeNamespaces(ctx, cur) < 0) { xmlC14NErrInternal("checking for relative namespaces"); return (-1); } /* * Save ns_rendered stack position */ memset(&state, 0, sizeof(state)); xmlC14NVisibleNsStackSave(ctx->ns_rendered, &state); if (visible) { if (ctx->parent_is_doc) { /* save this flag into the stack */ parent_is_doc = ctx->parent_is_doc; ctx->parent_is_doc = 0; ctx->pos = XMLC14N_INSIDE_DOCUMENT_ELEMENT; } xmlOutputBufferWriteString(ctx->buf, "<"); if ((cur->ns != NULL) && (xmlStrlen(cur->ns->prefix) > 0)) { xmlOutputBufferWriteString(ctx->buf, (const char *) cur->ns->prefix); xmlOutputBufferWriteString(ctx->buf, ":"); } xmlOutputBufferWriteString(ctx->buf, (const char *) cur->name); } if (!xmlC14NIsExclusive(ctx)) { ret = xmlC14NProcessNamespacesAxis(ctx, cur, visible); } else { ret = xmlExcC14NProcessNamespacesAxis(ctx, cur, visible); } if (ret < 0) { xmlC14NErrInternal("processing namespaces axis"); return (-1); } /* todo: shouldn't this go to "visible only"? */ if(visible) { xmlC14NVisibleNsStackShift(ctx->ns_rendered); } ret = xmlC14NProcessAttrsAxis(ctx, cur, visible); if (ret < 0) { xmlC14NErrInternal("processing attributes axis"); return (-1); } if (visible) { xmlOutputBufferWriteString(ctx->buf, ">"); } if (cur->children != NULL) { ret = xmlC14NProcessNodeList(ctx, cur->children); if (ret < 0) { xmlC14NErrInternal("processing childrens list"); return (-1); } } if (visible) { xmlOutputBufferWriteString(ctx->buf, "</"); if ((cur->ns != NULL) && (xmlStrlen(cur->ns->prefix) > 0)) { xmlOutputBufferWriteString(ctx->buf, (const char *) cur->ns->prefix); xmlOutputBufferWriteString(ctx->buf, ":"); } xmlOutputBufferWriteString(ctx->buf, (const char *) cur->name); xmlOutputBufferWriteString(ctx->buf, ">"); if (parent_is_doc) { /* restore this flag from the stack for next node */ ctx->parent_is_doc = parent_is_doc; ctx->pos = XMLC14N_AFTER_DOCUMENT_ELEMENT; } } /* * Restore ns_rendered stack position */ xmlC14NVisibleNsStackRestore(ctx->ns_rendered, &state); return (0); } /** * xmlC14NProcessNode: * @ctx: the pointer to C14N context object * @cur: the node to process * * Processes the given node * * Returns non-negative value on success or negative value on fail */ static int xmlC14NProcessNode(xmlC14NCtxPtr ctx, xmlNodePtr cur) { int ret = 0; int visible; if ((ctx == NULL) || (cur == NULL)) { xmlC14NErrParam("processing node"); return (-1); } visible = xmlC14NIsVisible(ctx, cur, cur->parent); switch (cur->type) { case XML_ELEMENT_NODE: ret = xmlC14NProcessElementNode(ctx, cur, visible); break; case XML_CDATA_SECTION_NODE: case XML_TEXT_NODE: /* * Text Nodes * the string value, except all ampersands are replaced * by &amp;, all open angle brackets (<) are replaced by &lt;, all closing * angle brackets (>) are replaced by &gt;, and all #xD characters are * replaced by &#xD;. */ /* cdata sections are processed as text nodes */ /* todo: verify that cdata sections are included in XPath nodes set */ if ((visible) && (cur->content != NULL)) { xmlChar *buffer; buffer = xmlC11NNormalizeText(cur->content); if (buffer != NULL) { xmlOutputBufferWriteString(ctx->buf, (const char *) buffer); xmlFree(buffer); } else { xmlC14NErrInternal("normalizing text node"); return (-1); } } break; case XML_PI_NODE: /* * Processing Instruction (PI) Nodes- * The opening PI symbol (<?), the PI target name of the node, * a leading space and the string value if it is not empty, and * the closing PI symbol (?>). If the string value is empty, * then the leading space is not added. Also, a trailing #xA is * rendered after the closing PI symbol for PI children of the * root node with a lesser document order than the document * element, and a leading #xA is rendered before the opening PI * symbol of PI children of the root node with a greater document * order than the document element. */ if (visible) { if (ctx->pos == XMLC14N_AFTER_DOCUMENT_ELEMENT) { xmlOutputBufferWriteString(ctx->buf, "\x0A<?"); } else { xmlOutputBufferWriteString(ctx->buf, "<?"); } xmlOutputBufferWriteString(ctx->buf, (const char *) cur->name); if ((cur->content != NULL) && (*(cur->content) != '\0')) { xmlChar *buffer; xmlOutputBufferWriteString(ctx->buf, " "); /* todo: do we need to normalize pi? */ buffer = xmlC11NNormalizePI(cur->content); if (buffer != NULL) { xmlOutputBufferWriteString(ctx->buf, (const char *) buffer); xmlFree(buffer); } else { xmlC14NErrInternal("normalizing pi node"); return (-1); } } if (ctx->pos == XMLC14N_BEFORE_DOCUMENT_ELEMENT) { xmlOutputBufferWriteString(ctx->buf, "?>\x0A"); } else { xmlOutputBufferWriteString(ctx->buf, "?>"); } } break; case XML_COMMENT_NODE: /* * Comment Nodes * Nothing if generating canonical XML without comments. For * canonical XML with comments, generate the opening comment * symbol (<!--), the string value of the node, and the * closing comment symbol (-->). Also, a trailing #xA is rendered * after the closing comment symbol for comment children of the * root node with a lesser document order than the document * element, and a leading #xA is rendered before the opening * comment symbol of comment children of the root node with a * greater document order than the document element. (Comment * children of the root node represent comments outside of the * top-level document element and outside of the document type * declaration). */ if (visible && ctx->with_comments) { if (ctx->pos == XMLC14N_AFTER_DOCUMENT_ELEMENT) { xmlOutputBufferWriteString(ctx->buf, "\x0A<!--"); } else { xmlOutputBufferWriteString(ctx->buf, "<!--"); } if (cur->content != NULL) { xmlChar *buffer; /* todo: do we need to normalize comment? */ buffer = xmlC11NNormalizeComment(cur->content); if (buffer != NULL) { xmlOutputBufferWriteString(ctx->buf, (const char *) buffer); xmlFree(buffer); } else { xmlC14NErrInternal("normalizing comment node"); return (-1); } } if (ctx->pos == XMLC14N_BEFORE_DOCUMENT_ELEMENT) { xmlOutputBufferWriteString(ctx->buf, "-->\x0A"); } else { xmlOutputBufferWriteString(ctx->buf, "-->"); } } break; case XML_DOCUMENT_NODE: case XML_DOCUMENT_FRAG_NODE: /* should be processed as document? */ #ifdef LIBXML_DOCB_ENABLED case XML_DOCB_DOCUMENT_NODE: /* should be processed as document? */ #endif #ifdef LIBXML_HTML_ENABLED case XML_HTML_DOCUMENT_NODE: /* should be processed as document? */ #endif if (cur->children != NULL) { ctx->pos = XMLC14N_BEFORE_DOCUMENT_ELEMENT; ctx->parent_is_doc = 1; ret = xmlC14NProcessNodeList(ctx, cur->children); } break; case XML_ATTRIBUTE_NODE: xmlC14NErrInvalidNode("XML_ATTRIBUTE_NODE", "processing node"); return (-1); case XML_NAMESPACE_DECL: xmlC14NErrInvalidNode("XML_NAMESPACE_DECL", "processing node"); return (-1); case XML_ENTITY_REF_NODE: xmlC14NErrInvalidNode("XML_ENTITY_REF_NODE", "processing node"); return (-1); case XML_ENTITY_NODE: xmlC14NErrInvalidNode("XML_ENTITY_NODE", "processing node"); return (-1); case XML_DOCUMENT_TYPE_NODE: case XML_NOTATION_NODE: case XML_DTD_NODE: case XML_ELEMENT_DECL: case XML_ATTRIBUTE_DECL: case XML_ENTITY_DECL: #ifdef LIBXML_XINCLUDE_ENABLED case XML_XINCLUDE_START: case XML_XINCLUDE_END: #endif /* * should be ignored according to "W3C Canonical XML" */ break; default: xmlC14NErrUnknownNode(cur->type, "processing node"); return (-1); } return (ret); } /** * xmlC14NProcessNodeList: * @ctx: the pointer to C14N context object * @cur: the node to start from * * Processes all nodes in the row starting from cur. * * Returns non-negative value on success or negative value on fail */ static int xmlC14NProcessNodeList(xmlC14NCtxPtr ctx, xmlNodePtr cur) { int ret; if (ctx == NULL) { xmlC14NErrParam("processing node list"); return (-1); } for (ret = 0; cur != NULL && ret >= 0; cur = cur->next) { ret = xmlC14NProcessNode(ctx, cur); } return (ret); } /** * xmlC14NFreeCtx: * @ctx: the pointer to C14N context object * * Cleanups the C14N context object. */ static void xmlC14NFreeCtx(xmlC14NCtxPtr ctx) { if (ctx == NULL) { xmlC14NErrParam("freeing context"); return; } if (ctx->ns_rendered != NULL) { xmlC14NVisibleNsStackDestroy(ctx->ns_rendered); } xmlFree(ctx); } /** * xmlC14NNewCtx: * @doc: the XML document for canonization * @is_visible_callback:the function to use to determine is node visible * or not * @user_data: the first parameter for @is_visible_callback function * (in most cases, it is nodes set) * @mode: the c14n mode (see @xmlC14NMode) * @inclusive_ns_prefixe the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for ` * canonicalization) * @with_comments: include comments in the result (!=0) or not (==0) * @buf: the output buffer to store canonical XML; this * buffer MUST have encoder==NULL because C14N requires * UTF-8 output * * Creates new C14N context object to store C14N parameters. * * Returns pointer to newly created object (success) or NULL (fail) */ static xmlC14NCtxPtr xmlC14NNewCtx(xmlDocPtr doc, xmlC14NIsVisibleCallback is_visible_callback, void* user_data, xmlC14NMode mode, xmlChar ** inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf) { xmlC14NCtxPtr ctx = NULL; if ((doc == NULL) || (buf == NULL)) { xmlC14NErrParam("creating new context"); return (NULL); } /* * Validate the encoding output buffer encoding */ if (buf->encoder != NULL) { xmlC14NErr(ctx, (xmlNodePtr) doc, XML_C14N_REQUIRES_UTF8, "xmlC14NNewCtx: output buffer encoder != NULL but C14N requires UTF8 output\n"); return (NULL); } /* * Validate the XML document encoding value, if provided. */ if (doc->charset != XML_CHAR_ENCODING_UTF8) { xmlC14NErr(ctx, (xmlNodePtr) doc, XML_C14N_REQUIRES_UTF8, "xmlC14NNewCtx: source document not in UTF8\n"); return (NULL); } /* * Allocate a new xmlC14NCtxPtr and fill the fields. */ ctx = (xmlC14NCtxPtr) xmlMalloc(sizeof(xmlC14NCtx)); if (ctx == NULL) { xmlC14NErrMemory("creating context"); return (NULL); } memset(ctx, 0, sizeof(xmlC14NCtx)); /* * initialize C14N context */ ctx->doc = doc; ctx->with_comments = with_comments; ctx->is_visible_callback = is_visible_callback; ctx->user_data = user_data; ctx->buf = buf; ctx->parent_is_doc = 1; ctx->pos = XMLC14N_BEFORE_DOCUMENT_ELEMENT; ctx->ns_rendered = xmlC14NVisibleNsStackCreate(); if(ctx->ns_rendered == NULL) { xmlC14NErr(ctx, (xmlNodePtr) doc, XML_C14N_CREATE_STACK, "xmlC14NNewCtx: xmlC14NVisibleNsStackCreate failed\n"); xmlC14NFreeCtx(ctx); return (NULL); } /* * Set "mode" flag and remember list of incluseve prefixes * for exclusive c14n */ ctx->mode = mode; if(xmlC14NIsExclusive(ctx)) { ctx->inclusive_ns_prefixes = inclusive_ns_prefixes; } return (ctx); } /** * xmlC14NExecute: * @doc: the XML document for canonization * @is_visible_callback:the function to use to determine is node visible * or not * @user_data: the first parameter for @is_visible_callback function * (in most cases, it is nodes set) * @mode: the c14n mode (see @xmlC14NMode) * @inclusive_ns_prefixes: the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization, ignored otherwise) * @with_comments: include comments in the result (!=0) or not (==0) * @buf: the output buffer to store canonical XML; this * buffer MUST have encoder==NULL because C14N requires * UTF-8 output * * Dumps the canonized image of given XML document into the provided buffer. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n) * * Returns non-negative value on success or a negative value on fail */ int xmlC14NExecute(xmlDocPtr doc, xmlC14NIsVisibleCallback is_visible_callback, void* user_data, int mode, xmlChar **inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf) { xmlC14NCtxPtr ctx; xmlC14NMode c14n_mode = XML_C14N_1_0; int ret; if ((buf == NULL) || (doc == NULL)) { xmlC14NErrParam("executing c14n"); return (-1); } /* for backward compatibility, we have to have "mode" as "int" and here we check that user gives valid value */ switch(mode) { case XML_C14N_1_0: case XML_C14N_EXCLUSIVE_1_0: case XML_C14N_1_1: c14n_mode = (xmlC14NMode)mode; break; default: xmlC14NErrParam("invalid mode for executing c14n"); return (-1); } /* * Validate the encoding output buffer encoding */ if (buf->encoder != NULL) { xmlC14NErr(NULL, (xmlNodePtr) doc, XML_C14N_REQUIRES_UTF8, "xmlC14NExecute: output buffer encoder != NULL but C14N requires UTF8 output\n"); return (-1); } ctx = xmlC14NNewCtx(doc, is_visible_callback, user_data, c14n_mode, inclusive_ns_prefixes, with_comments, buf); if (ctx == NULL) { xmlC14NErr(NULL, (xmlNodePtr) doc, XML_C14N_CREATE_CTXT, "xmlC14NExecute: unable to create C14N context\n"); return (-1); } /* * Root Node * The root node is the parent of the top-level document element. The * result of processing each of its child nodes that is in the node-set * in document order. The root node does not generate a byte order mark, * XML declaration, nor anything from within the document type * declaration. */ if (doc->children != NULL) { ret = xmlC14NProcessNodeList(ctx, doc->children); if (ret < 0) { xmlC14NErrInternal("processing docs children list"); xmlC14NFreeCtx(ctx); return (-1); } } /* * Flush buffer to get number of bytes written */ ret = xmlOutputBufferFlush(buf); if (ret < 0) { xmlC14NErrInternal("flushing output buffer"); xmlC14NFreeCtx(ctx); return (-1); } /* * Cleanup */ xmlC14NFreeCtx(ctx); return (ret); } /** * xmlC14NDocSaveTo: * @doc: the XML document for canonization * @nodes: the nodes set to be included in the canonized image * or NULL if all document nodes should be included * @mode: the c14n mode (see @xmlC14NMode) * @inclusive_ns_prefixes: the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization, ignored otherwise) * @with_comments: include comments in the result (!=0) or not (==0) * @buf: the output buffer to store canonical XML; this * buffer MUST have encoder==NULL because C14N requires * UTF-8 output * * Dumps the canonized image of given XML document into the provided buffer. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n) * * Returns non-negative value on success or a negative value on fail */ int xmlC14NDocSaveTo(xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, xmlChar ** inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf) { return(xmlC14NExecute(doc, (xmlC14NIsVisibleCallback)xmlC14NIsNodeInNodeset, nodes, mode, inclusive_ns_prefixes, with_comments, buf)); } /** * xmlC14NDocDumpMemory: * @doc: the XML document for canonization * @nodes: the nodes set to be included in the canonized image * or NULL if all document nodes should be included * @mode: the c14n mode (see @xmlC14NMode) * @inclusive_ns_prefixes: the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization, ignored otherwise) * @with_comments: include comments in the result (!=0) or not (==0) * @doc_txt_ptr: the memory pointer for allocated canonical XML text; * the caller of this functions is responsible for calling * xmlFree() to free allocated memory * * Dumps the canonized image of given XML document into memory. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n) * * Returns the number of bytes written on success or a negative value on fail */ int xmlC14NDocDumpMemory(xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, xmlChar ** inclusive_ns_prefixes, int with_comments, xmlChar ** doc_txt_ptr) { int ret; xmlOutputBufferPtr buf; if (doc_txt_ptr == NULL) { xmlC14NErrParam("dumping doc to memory"); return (-1); } *doc_txt_ptr = NULL; /* * create memory buffer with UTF8 (default) encoding */ buf = xmlAllocOutputBuffer(NULL); if (buf == NULL) { xmlC14NErrMemory("creating output buffer"); return (-1); } /* * canonize document and write to buffer */ ret = xmlC14NDocSaveTo(doc, nodes, mode, inclusive_ns_prefixes, with_comments, buf); if (ret < 0) { xmlC14NErrInternal("saving doc to output buffer"); (void) xmlOutputBufferClose(buf); return (-1); } ret = xmlBufUse(buf->buffer); if (ret > 0) { *doc_txt_ptr = xmlStrndup(xmlBufContent(buf->buffer), ret); } (void) xmlOutputBufferClose(buf); if ((*doc_txt_ptr == NULL) && (ret > 0)) { xmlC14NErrMemory("coping canonicanized document"); return (-1); } return (ret); } /** * xmlC14NDocSave: * @doc: the XML document for canonization * @nodes: the nodes set to be included in the canonized image * or NULL if all document nodes should be included * @mode: the c14n mode (see @xmlC14NMode) * @inclusive_ns_prefixes: the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization, ignored otherwise) * @with_comments: include comments in the result (!=0) or not (==0) * @filename: the filename to store canonical XML image * @compression: the compression level (zlib requred): * -1 - libxml default, * 0 - uncompressed, * >0 - compression level * * Dumps the canonized image of given XML document into the file. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n) * * Returns the number of bytes written success or a negative value on fail */ int xmlC14NDocSave(xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, xmlChar ** inclusive_ns_prefixes, int with_comments, const char *filename, int compression) { xmlOutputBufferPtr buf; int ret; if (filename == NULL) { xmlC14NErrParam("saving doc"); return (-1); } #ifdef HAVE_ZLIB_H if (compression < 0) compression = xmlGetCompressMode(); #endif /* * save the content to a temp buffer, use default UTF8 encoding. */ buf = xmlOutputBufferCreateFilename(filename, NULL, compression); if (buf == NULL) { xmlC14NErrInternal("creating temporary filename"); return (-1); } /* * canonize document and write to buffer */ ret = xmlC14NDocSaveTo(doc, nodes, mode, inclusive_ns_prefixes, with_comments, buf); if (ret < 0) { xmlC14NErrInternal("cannicanize document to buffer"); (void) xmlOutputBufferClose(buf); return (-1); } /* * get the numbers of bytes written */ ret = xmlOutputBufferClose(buf); return (ret); } /* * Macro used to grow the current buffer. */ #define growBufferReentrant() { \ buffer_size *= 2; \ buffer = (xmlChar *) \ xmlRealloc(buffer, buffer_size * sizeof(xmlChar)); \ if (buffer == NULL) { \ xmlC14NErrMemory("growing buffer"); \ return(NULL); \ } \ } /** * xmlC11NNormalizeString: * @input: the input string * @mode: the normalization mode (attribute, comment, PI or text) * * Converts a string to a canonical (normalized) format. The code is stolen * from xmlEncodeEntitiesReentrant(). Added normalization of \x09, \x0a, \x0A * and the @mode parameter * * Returns a normalized string (caller is responsible for calling xmlFree()) * or NULL if an error occurs */ static xmlChar * xmlC11NNormalizeString(const xmlChar * input, xmlC14NNormalizationMode mode) { const xmlChar *cur = input; xmlChar *buffer = NULL; xmlChar *out = NULL; int buffer_size = 0; if (input == NULL) return (NULL); /* * allocate an translation buffer. */ buffer_size = 1000; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) { xmlC14NErrMemory("allocating buffer"); return (NULL); } out = buffer; while (*cur != '\0') { if ((out - buffer) > (buffer_size - 10)) { int indx = out - buffer; growBufferReentrant(); out = &buffer[indx]; } if ((*cur == '<') && ((mode == XMLC14N_NORMALIZE_ATTR) || (mode == XMLC14N_NORMALIZE_TEXT))) { *out++ = '&'; *out++ = 'l'; *out++ = 't'; *out++ = ';'; } else if ((*cur == '>') && (mode == XMLC14N_NORMALIZE_TEXT)) { *out++ = '&'; *out++ = 'g'; *out++ = 't'; *out++ = ';'; } else if ((*cur == '&') && ((mode == XMLC14N_NORMALIZE_ATTR) || (mode == XMLC14N_NORMALIZE_TEXT))) { *out++ = '&'; *out++ = 'a'; *out++ = 'm'; *out++ = 'p'; *out++ = ';'; } else if ((*cur == '"') && (mode == XMLC14N_NORMALIZE_ATTR)) { *out++ = '&'; *out++ = 'q'; *out++ = 'u'; *out++ = 'o'; *out++ = 't'; *out++ = ';'; } else if ((*cur == '\x09') && (mode == XMLC14N_NORMALIZE_ATTR)) { *out++ = '&'; *out++ = '#'; *out++ = 'x'; *out++ = '9'; *out++ = ';'; } else if ((*cur == '\x0A') && (mode == XMLC14N_NORMALIZE_ATTR)) { *out++ = '&'; *out++ = '#'; *out++ = 'x'; *out++ = 'A'; *out++ = ';'; } else if ((*cur == '\x0D') && ((mode == XMLC14N_NORMALIZE_ATTR) || (mode == XMLC14N_NORMALIZE_TEXT) || (mode == XMLC14N_NORMALIZE_COMMENT) || (mode == XMLC14N_NORMALIZE_PI))) { *out++ = '&'; *out++ = '#'; *out++ = 'x'; *out++ = 'D'; *out++ = ';'; } else { /* * Works because on UTF-8, all extended sequences cannot * result in bytes in the ASCII range. */ *out++ = *cur; } cur++; } *out = 0; return (buffer); } #endif /* LIBXML_OUTPUT_ENABLED */ #define bottom_c14n #include "elfgcchack.h" #endif /* LIBXML_C14N_ENABLED */
gpl-3.0
danbi/sgminer
ccan/typesafe_cb/test/run.c
112
2419
#include <ccan/typesafe_cb/typesafe_cb.h> #include <string.h> #include <stdint.h> #include <ccan/tap/tap.h> static char dummy = 0; /* The example usage. */ static void _set_some_value(void *val) { ok1(val == &dummy); } #define set_some_value(expr) \ _set_some_value(typesafe_cb_cast(void *, unsigned long, (expr))) static void _callback_onearg(void (*fn)(void *arg), void *arg) { fn(arg); } static void _callback_preargs(void (*fn)(int a, int b, void *arg), void *arg) { fn(1, 2, arg); } static void _callback_postargs(void (*fn)(void *arg, int a, int b), void *arg) { fn(arg, 1, 2); } #define callback_onearg(cb, arg) \ _callback_onearg(typesafe_cb(void, void *, (cb), (arg)), (arg)) #define callback_preargs(cb, arg) \ _callback_preargs(typesafe_cb_preargs(void, void *, (cb), (arg), int, int), (arg)) #define callback_postargs(cb, arg) \ _callback_postargs(typesafe_cb_postargs(void, void *, (cb), (arg), int, int), (arg)) static void my_callback_onearg(char *p) { ok1(strcmp(p, "hello world") == 0); } static void my_callback_preargs(int a, int b, char *p) { ok1(a == 1); ok1(b == 2); ok1(strcmp(p, "hello world") == 0); } static void my_callback_postargs(char *p, int a, int b) { ok1(a == 1); ok1(b == 2); ok1(strcmp(p, "hello world") == 0); } /* This is simply a compile test; we promised typesafe_cb_cast can be in a * static initializer. */ struct callback_onearg { void (*fn)(void *arg); const void *arg; }; struct callback_onearg cb_onearg = { typesafe_cb(void, void *, my_callback_onearg, (char *)(intptr_t)"hello world"), "hello world" }; struct callback_preargs { void (*fn)(int a, int b, void *arg); const void *arg; }; struct callback_preargs cb_preargs = { typesafe_cb_preargs(void, void *, my_callback_preargs, (char *)(intptr_t)"hi", int, int), "hi" }; struct callback_postargs { void (*fn)(void *arg, int a, int b); const void *arg; }; struct callback_postargs cb_postargs = { typesafe_cb_postargs(void, void *, my_callback_postargs, (char *)(intptr_t)"hi", int, int), "hi" }; int main(int argc, char *argv[]) { void *p = &dummy; unsigned long l = (unsigned long)p; char str[] = "hello world"; plan_tests(2 + 1 + 3 + 3); set_some_value(p); set_some_value(l); callback_onearg(my_callback_onearg, str); callback_preargs(my_callback_preargs, str); callback_postargs(my_callback_postargs, str); return exit_status(); }
gpl-3.0
zcchen/shadowsocks-android
src/main/jni/badvpn/dostest/StreamBuffer.c
368
4968
/** * @file StreamBuffer.c * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <misc/balloc.h> #include <misc/minmax.h> #include "StreamBuffer.h" // called when receive operation is complete static void input_handler_done (void *vo, int data_len) { StreamBuffer *o = (StreamBuffer *)vo; ASSERT(data_len > 0) ASSERT(data_len <= o->buf_size - (o->buf_start + o->buf_used)) // remember if buffer was empty int was_empty = (o->buf_used == 0); // increment buf_used by the amount that was received o->buf_used += data_len; // start another receive operation unless buffer is full if (o->buf_used < o->buf_size - o->buf_start) { int end = o->buf_start + o->buf_used; StreamRecvInterface_Receiver_Recv(o->input, o->buf + end, o->buf_size - end); } else if (o->buf_used < o->buf_size) { // wrap around StreamRecvInterface_Receiver_Recv(o->input, o->buf, o->buf_start); } // if buffer was empty before, start send operation if (was_empty) { StreamPassInterface_Sender_Send(o->output, o->buf + o->buf_start, o->buf_used); } } // called when send operation is complete static void output_handler_done (void *vo, int data_len) { StreamBuffer *o = (StreamBuffer *)vo; ASSERT(data_len > 0) ASSERT(data_len <= o->buf_used) ASSERT(data_len <= o->buf_size - o->buf_start) // remember if buffer was full int was_full = (o->buf_used == o->buf_size); // increment buf_start and decrement buf_used by the // amount that was sent o->buf_start += data_len; o->buf_used -= data_len; // wrap around buf_start if (o->buf_start == o->buf_size) { o->buf_start = 0; } // start receive operation if buffer was full if (was_full) { int end; int avail; if (o->buf_used >= o->buf_size - o->buf_start) { end = o->buf_used - (o->buf_size - o->buf_start); avail = o->buf_start - end; } else { end = o->buf_start + o->buf_used; avail = o->buf_size - end; } StreamRecvInterface_Receiver_Recv(o->input, o->buf + end, avail); } // start another receive send unless buffer is empty if (o->buf_used > 0) { int to_send = bmin_int(o->buf_used, o->buf_size - o->buf_start); StreamPassInterface_Sender_Send(o->output, o->buf + o->buf_start, to_send); } } int StreamBuffer_Init (StreamBuffer *o, int buf_size, StreamRecvInterface *input, StreamPassInterface *output) { ASSERT(buf_size > 0) ASSERT(input) ASSERT(output) // remember arguments o->buf_size = buf_size; o->input = input; o->output = output; // allocate buffer memory o->buf = (uint8_t *)BAllocSize(bsize_fromint(o->buf_size)); if (!o->buf) { goto fail0; } // set initial buffer state o->buf_start = 0; o->buf_used = 0; // set receive and send done callbacks StreamRecvInterface_Receiver_Init(o->input, input_handler_done, o); StreamPassInterface_Sender_Init(o->output, output_handler_done, o); // start receive operation StreamRecvInterface_Receiver_Recv(o->input, o->buf, o->buf_size); DebugObject_Init(&o->d_obj); return 1; fail0: return 0; } void StreamBuffer_Free (StreamBuffer *o) { DebugObject_Free(&o->d_obj); // free buffer memory BFree(o->buf); }
gpl-3.0
heihei1252/shadowsocks-android
src/main/jni/badvpn/client/client.c
368
93905
/** * @file client.c * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <protocol/msgproto.h> #include <protocol/addr.h> #include <protocol/dataproto.h> #include <misc/version.h> #include <misc/debug.h> #include <misc/offset.h> #include <misc/byteorder.h> #include <misc/nsskey.h> #include <misc/loglevel.h> #include <misc/loggers_string.h> #include <misc/string_begins_with.h> #include <misc/open_standard_streams.h> #include <structure/LinkedList1.h> #include <base/DebugObject.h> #include <base/BLog.h> #include <security/BSecurity.h> #include <security/BRandom.h> #include <system/BSignal.h> #include <system/BTime.h> #include <system/BNetwork.h> #include <nspr_support/DummyPRFileDesc.h> #include <nspr_support/BSSLConnection.h> #include <server_connection/ServerConnection.h> #include <tuntap/BTap.h> #include <threadwork/BThreadWork.h> #ifndef BADVPN_USE_WINAPI #include <base/BLog_syslog.h> #endif #include <client/client.h> #include <generated/blog_channel_client.h> #define TRANSPORT_MODE_UDP 0 #define TRANSPORT_MODE_TCP 1 #define LOGGER_STDOUT 1 #define LOGGER_SYSLOG 2 // command-line options struct ext_addr_option { char *addr; char *scope; }; struct bind_addr_option { char *addr; int num_ports; int num_ext_addrs; struct ext_addr_option ext_addrs[MAX_EXT_ADDRS]; }; struct { int help; int version; int logger; #ifndef BADVPN_USE_WINAPI char *logger_syslog_facility; char *logger_syslog_ident; #endif int loglevel; int loglevels[BLOG_NUM_CHANNELS]; int threads; int use_threads_for_ssl_handshake; int use_threads_for_ssl_data; int ssl; char *nssdb; char *client_cert_name; char *server_name; char *server_addr; char *tapdev; int num_scopes; char *scopes[MAX_SCOPES]; int num_bind_addrs; struct bind_addr_option bind_addrs[MAX_BIND_ADDRS]; int transport_mode; int encryption_mode; int hash_mode; int otp_mode; int otp_num; int otp_num_warn; int fragmentation_latency; int peer_ssl; int peer_tcp_socket_sndbuf; int send_buffer_size; int send_buffer_relay_size; int max_macs; int max_groups; int igmp_group_membership_interval; int igmp_last_member_query_time; int allow_peer_talk_without_ssl; int max_peers; } options; // bind addresses struct ext_addr { int server_reported_port; BAddr addr; // if server_reported_port>=0, defined only after hello received char scope[64]; }; struct bind_addr { BAddr addr; int num_ports; int num_ext_addrs; struct ext_addr ext_addrs[MAX_EXT_ADDRS]; }; int num_bind_addrs; struct bind_addr bind_addrs[MAX_BIND_ADDRS]; // TCP listeners PasswordListener listeners[MAX_BIND_ADDRS]; // SPProto parameters (UDP only) struct spproto_security_params sp_params; // server address we connect to BAddr server_addr; // server name to use for SSL char server_name[256]; // reactor BReactor ss; // thread work dispatcher BThreadWorkDispatcher twd; // client certificate if using SSL CERTCertificate *client_cert; // client private key if using SSL SECKEYPrivateKey *client_key; // device BTap device; int device_mtu; // DataProtoSource for device input (reading) DataProtoSource device_dpsource; // DPReceiveDevice for device output (writing) DPReceiveDevice device_output_dprd; // data communication MTU int data_mtu; // peers list LinkedList1 peers; int num_peers; // frame decider FrameDecider frame_decider; // peers that can be user as relays LinkedList1 relays; // peers than need a relay LinkedList1 waiting_relay_peers; // server connection ServerConnection server; // my ID, defined only after server_ready peerid_t my_id; // fair queue for sending peer messages to the server PacketPassFairQueue server_queue; // whether server is ready int server_ready; // dying server flow struct server_flow *dying_server_flow; // stops event processing, causing the program to exit static void terminate (void); // prints program name and version to standard output static void print_help (const char *name); // prints program name and version to standard output static void print_version (void); // parses the command line static int parse_arguments (int argc, char *argv[]); // processes certain command line options static int process_arguments (void); static int ssl_flags (void); // handler for program termination request static void signal_handler (void *unused); // adds a new peer static void peer_add (peerid_t id, int flags, const uint8_t *cert, int cert_len); // removes a peer static void peer_remove (struct peer_data *peer, int exiting); // appends the peer log prefix to the logger static void peer_logfunc (struct peer_data *peer); // passes a message to the logger, prepending it info about the peer static void peer_log (struct peer_data *peer, int level, const char *fmt, ...); // see if we are the master relative to this peer static int peer_am_master (struct peer_data *peer); // frees PeerChat, disconnecting it from the server flow static void peer_free_chat (struct peer_data *peer); // initializes the link static int peer_init_link (struct peer_data *peer); // frees link resources static void peer_free_link (struct peer_data *peer); // frees link, relaying, waiting relaying static void peer_cleanup_connections (struct peer_data *peer); // registers the peer as a relay provider static void peer_enable_relay_provider (struct peer_data *peer); // unregisters the peer as a relay provider static void peer_disable_relay_provider (struct peer_data *peer); // install relaying for a peer static void peer_install_relaying (struct peer_data *peer, struct peer_data *relay); // uninstall relaying for a peer static void peer_free_relaying (struct peer_data *peer); // handle a peer that needs a relay static void peer_need_relay (struct peer_data *peer); // inserts the peer into the need relay list static void peer_register_need_relay (struct peer_data *peer); // removes the peer from the need relay list static void peer_unregister_need_relay (struct peer_data *peer); // handle a link setup failure static void peer_reset (struct peer_data *peer); // fees chat and sends resetpeer static void peer_resetpeer (struct peer_data *peer); // chat handlers static void peer_chat_handler_error (struct peer_data *peer); static void peer_chat_handler_message (struct peer_data *peer, uint8_t *data, int data_len); // handlers for different message types static void peer_msg_youconnect (struct peer_data *peer, uint8_t *data, int data_len); static void peer_msg_cannotconnect (struct peer_data *peer, uint8_t *data, int data_len); static void peer_msg_cannotbind (struct peer_data *peer, uint8_t *data, int data_len); static void peer_msg_seed (struct peer_data *peer, uint8_t *data, int data_len); static void peer_msg_confirmseed (struct peer_data *peer, uint8_t *data, int data_len); static void peer_msg_youretry (struct peer_data *peer, uint8_t *data, int data_len); // handler from DatagramPeerIO when we should generate a new OTP send seed static void peer_udp_pio_handler_seed_warning (struct peer_data *peer); // handler from DatagramPeerIO when a new OTP seed can be recognized once it was provided to it static void peer_udp_pio_handler_seed_ready (struct peer_data *peer); // handler from DatagramPeerIO when an error occurs on the connection static void peer_udp_pio_handler_error (struct peer_data *peer); // handler from StreamPeerIO when an error occurs on the connection static void peer_tcp_pio_handler_error (struct peer_data *peer); // peer retry timer handler. The timer is used only on the master side, // wither when we detect an error, or the peer reports an error. static void peer_reset_timer_handler (struct peer_data *peer); // start binding, according to the protocol static void peer_start_binding (struct peer_data *peer); // tries binding on one address, according to the protocol static void peer_bind (struct peer_data *peer); static void peer_bind_one_address (struct peer_data *peer, int addr_index, int *cont); static void peer_connect (struct peer_data *peer, BAddr addr, uint8_t *encryption_key, uint64_t password); static int peer_start_msg (struct peer_data *peer, void **data, int type, int len); static void peer_end_msg (struct peer_data *peer); // sends a message with no payload to the peer static void peer_send_simple (struct peer_data *peer, int msgid); static void peer_send_conectinfo (struct peer_data *peer, int addr_index, int port_adjust, uint8_t *enckey, uint64_t pass); static void peer_send_confirmseed (struct peer_data *peer, uint16_t seed_id); // handler for peer DataProto up state changes static void peer_dataproto_handler (struct peer_data *peer, int up); // looks for a peer with the given ID static struct peer_data * find_peer_by_id (peerid_t id); // device error handler static void device_error_handler (void *unused); // DataProtoSource handler for packets from the device static void device_dpsource_handler (void *unused, const uint8_t *frame, int frame_len); // assign relays to clients waiting for them static void assign_relays (void); // checks if the given address scope is known (i.e. we can connect to an address in it) static char * address_scope_known (uint8_t *name, int name_len); // handlers for server messages static void server_handler_error (void *user); static void server_handler_ready (void *user, peerid_t param_my_id, uint32_t ext_ip); static void server_handler_newclient (void *user, peerid_t peer_id, int flags, const uint8_t *cert, int cert_len); static void server_handler_endclient (void *user, peerid_t peer_id); static void server_handler_message (void *user, peerid_t peer_id, uint8_t *data, int data_len); // jobs static void peer_job_send_seed (struct peer_data *peer); static void peer_job_init (struct peer_data *peer); // server flows static struct server_flow * server_flow_init (void); static void server_flow_free (struct server_flow *flow); static void server_flow_die (struct server_flow *flow); static void server_flow_qflow_handler_busy (struct server_flow *flow); static void server_flow_connect (struct server_flow *flow, PacketRecvInterface *input); static void server_flow_disconnect (struct server_flow *flow); int main (int argc, char *argv[]) { if (argc <= 0) { return 1; } // open standard streams open_standard_streams(); // parse command-line arguments if (!parse_arguments(argc, argv)) { fprintf(stderr, "Failed to parse arguments\n"); print_help(argv[0]); goto fail0; } // handle --help and --version if (options.help) { print_version(); print_help(argv[0]); return 0; } if (options.version) { print_version(); return 0; } // initialize logger switch (options.logger) { case LOGGER_STDOUT: BLog_InitStdout(); break; #ifndef BADVPN_USE_WINAPI case LOGGER_SYSLOG: if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) { fprintf(stderr, "Failed to initialize syslog logger\n"); goto fail0; } break; #endif default: ASSERT(0); } // configure logger channels for (int i = 0; i < BLOG_NUM_CHANNELS; i++) { if (options.loglevels[i] >= 0) { BLog_SetChannelLoglevel(i, options.loglevels[i]); } else if (options.loglevel >= 0) { BLog_SetChannelLoglevel(i, options.loglevel); } } BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION); if (options.ssl) { // init NSPR PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); // register local NSPR file types if (!DummyPRFileDesc_GlobalInit()) { BLog(BLOG_ERROR, "DummyPRFileDesc_GlobalInit failed"); goto fail01; } if (!BSSLConnection_GlobalInit()) { BLog(BLOG_ERROR, "BSSLConnection_GlobalInit failed"); goto fail01; } // init NSS if (NSS_Init(options.nssdb) != SECSuccess) { BLog(BLOG_ERROR, "NSS_Init failed (%d)", (int)PR_GetError()); goto fail01; } // set cipher policy if (NSS_SetDomesticPolicy() != SECSuccess) { BLog(BLOG_ERROR, "NSS_SetDomesticPolicy failed (%d)", (int)PR_GetError()); goto fail02; } // init server cache if (SSL_ConfigServerSessionIDCache(0, 0, 0, NULL) != SECSuccess) { BLog(BLOG_ERROR, "SSL_ConfigServerSessionIDCache failed (%d)", (int)PR_GetError()); goto fail02; } // open server certificate and private key if (!open_nss_cert_and_key(options.client_cert_name, &client_cert, &client_key)) { BLog(BLOG_ERROR, "Cannot open certificate and key"); goto fail03; } } // initialize network if (!BNetwork_GlobalInit()) { BLog(BLOG_ERROR, "BNetwork_GlobalInit failed"); goto fail1; } // init time BTime_Init(); // process arguments if (!process_arguments()) { BLog(BLOG_ERROR, "Failed to process arguments"); goto fail1; } // init reactor if (!BReactor_Init(&ss)) { BLog(BLOG_ERROR, "BReactor_Init failed"); goto fail1; } // setup signal handler if (!BSignal_Init(&ss, signal_handler, NULL)) { BLog(BLOG_ERROR, "BSignal_Init failed"); goto fail2; } // init thread work dispatcher if (!BThreadWorkDispatcher_Init(&twd, &ss, options.threads)) { BLog(BLOG_ERROR, "BThreadWorkDispatcher_Init failed"); goto fail3; } // init BSecurity if (BThreadWorkDispatcher_UsingThreads(&twd)) { if (!BSecurity_GlobalInitThreadSafe()) { BLog(BLOG_ERROR, "BSecurity_GlobalInitThreadSafe failed"); goto fail4; } } // init listeners int num_listeners = 0; if (options.transport_mode == TRANSPORT_MODE_TCP) { while (num_listeners < num_bind_addrs) { struct bind_addr *addr = &bind_addrs[num_listeners]; if (!PasswordListener_Init(&listeners[num_listeners], &ss, &twd, addr->addr, TCP_MAX_PASSWORD_LISTENER_CLIENTS, options.peer_ssl, ssl_flags(), client_cert, client_key)) { BLog(BLOG_ERROR, "PasswordListener_Init failed"); goto fail8; } num_listeners++; } } // init device if (!BTap_Init(&device, &ss, options.tapdev, device_error_handler, NULL, 0)) { BLog(BLOG_ERROR, "BTap_Init failed"); goto fail8; } // remember device MTU device_mtu = BTap_GetMTU(&device); BLog(BLOG_INFO, "device MTU is %d", device_mtu); // calculate data MTU if (device_mtu > INT_MAX - DATAPROTO_MAX_OVERHEAD) { BLog(BLOG_ERROR, "Device MTU is too large"); goto fail9; } data_mtu = DATAPROTO_MAX_OVERHEAD + device_mtu; // init device input if (!DataProtoSource_Init(&device_dpsource, BTap_GetOutput(&device), device_dpsource_handler, NULL, &ss)) { BLog(BLOG_ERROR, "DataProtoSource_Init failed"); goto fail9; } // init device output if (!DPReceiveDevice_Init(&device_output_dprd, device_mtu, (DPReceiveDevice_output_func)BTap_Send, &device, &ss, options.send_buffer_relay_size, PEER_RELAY_FLOW_INACTIVITY_TIME)) { BLog(BLOG_ERROR, "DPReceiveDevice_Init failed"); goto fail10; } // init peers list LinkedList1_Init(&peers); num_peers = 0; // init frame decider FrameDecider_Init(&frame_decider, options.max_macs, options.max_groups, options.igmp_group_membership_interval, options.igmp_last_member_query_time, &ss); // init relays list LinkedList1_Init(&relays); // init need relay list LinkedList1_Init(&waiting_relay_peers); // start connecting to server if (!ServerConnection_Init(&server, &ss, &twd, server_addr, SC_KEEPALIVE_INTERVAL, SERVER_BUFFER_MIN_PACKETS, options.ssl, ssl_flags(), client_cert, client_key, server_name, NULL, server_handler_error, server_handler_ready, server_handler_newclient, server_handler_endclient, server_handler_message )) { BLog(BLOG_ERROR, "ServerConnection_Init failed"); goto fail11; } // set server not ready server_ready = 0; // set no dying flow dying_server_flow = NULL; // enter event loop BLog(BLOG_NOTICE, "entering event loop"); BReactor_Exec(&ss); if (server_ready) { // allow freeing server queue flows PacketPassFairQueue_PrepareFree(&server_queue); // make ServerConnection stop using buffers from peers before they are freed ServerConnection_ReleaseBuffers(&server); } // free peers LinkedList1Node *node; while (node = LinkedList1_GetFirst(&peers)) { struct peer_data *peer = UPPER_OBJECT(node, struct peer_data, list_node); peer_remove(peer, 1); } // free dying server flow if (dying_server_flow) { server_flow_free(dying_server_flow); } if (server_ready) { PacketPassFairQueue_Free(&server_queue); } ServerConnection_Free(&server); fail11: FrameDecider_Free(&frame_decider); DPReceiveDevice_Free(&device_output_dprd); fail10: DataProtoSource_Free(&device_dpsource); fail9: BTap_Free(&device); fail8: if (options.transport_mode == TRANSPORT_MODE_TCP) { while (num_listeners-- > 0) { PasswordListener_Free(&listeners[num_listeners]); } } if (BThreadWorkDispatcher_UsingThreads(&twd)) { BSecurity_GlobalFreeThreadSafe(); } fail4: // NOTE: BThreadWorkDispatcher must be freed before NSPR and stuff BThreadWorkDispatcher_Free(&twd); fail3: BSignal_Finish(); fail2: BReactor_Free(&ss); fail1: if (options.ssl) { CERT_DestroyCertificate(client_cert); SECKEY_DestroyPrivateKey(client_key); fail03: ASSERT_FORCE(SSL_ShutdownServerSessionIDCache() == SECSuccess) fail02: SSL_ClearSessionCache(); ASSERT_FORCE(NSS_Shutdown() == SECSuccess) fail01: ASSERT_FORCE(PR_Cleanup() == PR_SUCCESS) PL_ArenaFinish(); } BLog(BLOG_NOTICE, "exiting"); BLog_Free(); fail0: // finish objects DebugObjectGlobal_Finish(); return 1; } void terminate (void) { BLog(BLOG_NOTICE, "tearing down"); // exit event loop BReactor_Quit(&ss, 0); } void print_help (const char *name) { printf( "Usage:\n" " %s\n" " [--help]\n" " [--version]\n" " [--logger <"LOGGERS_STRING">]\n" #ifndef BADVPN_USE_WINAPI " (logger=syslog?\n" " [--syslog-facility <string>]\n" " [--syslog-ident <string>]\n" " )\n" #endif " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n" " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n" " [--threads <integer>]\n" " [--use-threads-for-ssl-handshake]\n" " [--use-threads-for-ssl-data]\n" " [--ssl --nssdb <string> --client-cert-name <string>]\n" " [--server-name <string>]\n" " --server-addr <addr>\n" " [--tapdev <name>]\n" " [--scope <scope_name>] ...\n" " [\n" " --bind-addr <addr>\n" " (transport-mode=udp? --num-ports <num>)\n" " [--ext-addr <addr / {server_reported}:port> <scope_name>] ...\n" " ] ...\n" " --transport-mode <udp/tcp>\n" " (transport-mode=udp?\n" " --encryption-mode <blowfish/aes/none>\n" " --hash-mode <md5/sha1/none>\n" " [--otp <blowfish/aes> <num> <num-warn>]\n" " [--fragmentation-latency <milliseconds>]\n" " )\n" " (transport-mode=tcp?\n" " (ssl? [--peer-ssl])\n" " [--peer-tcp-socket-sndbuf <bytes / 0>]\n" " )\n" " [--send-buffer-size <num-packets>]\n" " [--send-buffer-relay-size <num-packets>]\n" " [--max-macs <num>]\n" " [--max-groups <num>]\n" " [--igmp-group-membership-interval <ms>]\n" " [--igmp-last-member-query-time <ms>]\n" " [--allow-peer-talk-without-ssl]\n" " [--max-peers <number>]\n" "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n", name ); } void print_version (void) { printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n"); } int parse_arguments (int argc, char *argv[]) { if (argc <= 0) { return 0; } options.help = 0; options.version = 0; options.logger = LOGGER_STDOUT; #ifndef BADVPN_USE_WINAPI options.logger_syslog_facility = "daemon"; options.logger_syslog_ident = argv[0]; #endif options.loglevel = -1; for (int i = 0; i < BLOG_NUM_CHANNELS; i++) { options.loglevels[i] = -1; } options.threads = 0; options.use_threads_for_ssl_handshake = 0; options.use_threads_for_ssl_data = 0; options.ssl = 0; options.nssdb = NULL; options.client_cert_name = NULL; options.server_name = NULL; options.server_addr = NULL; options.tapdev = NULL; options.num_scopes = 0; options.num_bind_addrs = 0; options.transport_mode = -1; options.encryption_mode = -1; options.hash_mode = -1; options.otp_mode = SPPROTO_OTP_MODE_NONE; options.fragmentation_latency = PEER_DEFAULT_UDP_FRAGMENTATION_LATENCY; options.peer_ssl = 0; options.peer_tcp_socket_sndbuf = -1; options.send_buffer_size = PEER_DEFAULT_SEND_BUFFER_SIZE; options.send_buffer_relay_size = PEER_DEFAULT_SEND_BUFFER_RELAY_SIZE; options.max_macs = PEER_DEFAULT_MAX_MACS; options.max_groups = PEER_DEFAULT_MAX_GROUPS; options.igmp_group_membership_interval = DEFAULT_IGMP_GROUP_MEMBERSHIP_INTERVAL; options.igmp_last_member_query_time = DEFAULT_IGMP_LAST_MEMBER_QUERY_TIME; options.allow_peer_talk_without_ssl = 0; options.max_peers = DEFAULT_MAX_PEERS; int have_fragmentation_latency = 0; int i; for (i = 1; i < argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "--help")) { options.help = 1; } else if (!strcmp(arg, "--version")) { options.version = 1; } else if (!strcmp(arg, "--logger")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } char *arg2 = argv[i + 1]; if (!strcmp(arg2, "stdout")) { options.logger = LOGGER_STDOUT; } #ifndef BADVPN_USE_WINAPI else if (!strcmp(arg2, "syslog")) { options.logger = LOGGER_SYSLOG; } #endif else { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } #ifndef BADVPN_USE_WINAPI else if (!strcmp(arg, "--syslog-facility")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.logger_syslog_facility = argv[i + 1]; i++; } else if (!strcmp(arg, "--syslog-ident")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.logger_syslog_ident = argv[i + 1]; i++; } #endif else if (!strcmp(arg, "--loglevel")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--channel-loglevel")) { if (2 >= argc - i) { fprintf(stderr, "%s: requires two arguments\n", arg); return 0; } int channel = BLogGlobal_GetChannelByName(argv[i + 1]); if (channel < 0) { fprintf(stderr, "%s: wrong channel argument\n", arg); return 0; } int loglevel = parse_loglevel(argv[i + 2]); if (loglevel < 0) { fprintf(stderr, "%s: wrong loglevel argument\n", arg); return 0; } options.loglevels[channel] = loglevel; i += 2; } else if (!strcmp(arg, "--threads")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.threads = atoi(argv[i + 1]); i++; } else if (!strcmp(arg, "--use-threads-for-ssl-handshake")) { options.use_threads_for_ssl_handshake = 1; } else if (!strcmp(arg, "--use-threads-for-ssl-data")) { options.use_threads_for_ssl_data = 1; } else if (!strcmp(arg, "--ssl")) { options.ssl = 1; } else if (!strcmp(arg, "--nssdb")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.nssdb = argv[i + 1]; i++; } else if (!strcmp(arg, "--client-cert-name")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.client_cert_name = argv[i + 1]; i++; } else if (!strcmp(arg, "--server-name")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.server_name = argv[i + 1]; i++; } else if (!strcmp(arg, "--server-addr")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.server_addr = argv[i + 1]; i++; } else if (!strcmp(arg, "--tapdev")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.tapdev = argv[i + 1]; i++; } else if (!strcmp(arg, "--scope")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if (options.num_scopes == MAX_SCOPES) { fprintf(stderr, "%s: too many\n", arg); return 0; } options.scopes[options.num_scopes] = argv[i + 1]; options.num_scopes++; i++; } else if (!strcmp(arg, "--bind-addr")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if (options.num_bind_addrs == MAX_BIND_ADDRS) { fprintf(stderr, "%s: too many\n", arg); return 0; } struct bind_addr_option *addr = &options.bind_addrs[options.num_bind_addrs]; addr->addr = argv[i + 1]; addr->num_ports = -1; addr->num_ext_addrs = 0; options.num_bind_addrs++; i++; } else if (!strcmp(arg, "--num-ports")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if (options.num_bind_addrs == 0) { fprintf(stderr, "%s: must folow --bind-addr\n", arg); return 0; } struct bind_addr_option *addr = &options.bind_addrs[options.num_bind_addrs - 1]; if ((addr->num_ports = atoi(argv[i + 1])) < 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--ext-addr")) { if (2 >= argc - i) { fprintf(stderr, "%s: requires two arguments\n", arg); return 0; } if (options.num_bind_addrs == 0) { fprintf(stderr, "%s: must folow --bind-addr\n", arg); return 0; } struct bind_addr_option *addr = &options.bind_addrs[options.num_bind_addrs - 1]; if (addr->num_ext_addrs == MAX_EXT_ADDRS) { fprintf(stderr, "%s: too many\n", arg); return 0; } struct ext_addr_option *eaddr = &addr->ext_addrs[addr->num_ext_addrs]; eaddr->addr = argv[i + 1]; eaddr->scope = argv[i + 2]; addr->num_ext_addrs++; i += 2; } else if (!strcmp(arg, "--transport-mode")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } char *arg2 = argv[i + 1]; if (!strcmp(arg2, "udp")) { options.transport_mode = TRANSPORT_MODE_UDP; } else if (!strcmp(arg2, "tcp")) { options.transport_mode = TRANSPORT_MODE_TCP; } else { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--encryption-mode")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } char *arg2 = argv[i + 1]; if (!strcmp(arg2, "none")) { options.encryption_mode = SPPROTO_ENCRYPTION_MODE_NONE; } else if (!strcmp(arg2, "blowfish")) { options.encryption_mode = BENCRYPTION_CIPHER_BLOWFISH; } else if (!strcmp(arg2, "aes")) { options.encryption_mode = BENCRYPTION_CIPHER_AES; } else { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--hash-mode")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } char *arg2 = argv[i + 1]; if (!strcmp(arg2, "none")) { options.hash_mode = SPPROTO_HASH_MODE_NONE; } else if (!strcmp(arg2, "md5")) { options.hash_mode = BHASH_TYPE_MD5; } else if (!strcmp(arg2, "sha1")) { options.hash_mode = BHASH_TYPE_SHA1; } else { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--otp")) { if (3 >= argc - i) { fprintf(stderr, "%s: requires three arguments\n", arg); return 0; } char *otp_mode = argv[i + 1]; char *otp_num = argv[i + 2]; char *otp_num_warn = argv[i + 3]; if (!strcmp(otp_mode, "blowfish")) { options.otp_mode = BENCRYPTION_CIPHER_BLOWFISH; } else if (!strcmp(otp_mode, "aes")) { options.otp_mode = BENCRYPTION_CIPHER_AES; } else { fprintf(stderr, "%s: wrong mode\n", arg); return 0; } if ((options.otp_num = atoi(otp_num)) <= 0) { fprintf(stderr, "%s: wrong num\n", arg); return 0; } options.otp_num_warn = atoi(otp_num_warn); if (options.otp_num_warn <= 0 || options.otp_num_warn > options.otp_num) { fprintf(stderr, "%s: wrong num warn\n", arg); return 0; } i += 3; } else if (!strcmp(arg, "--fragmentation-latency")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } options.fragmentation_latency = atoi(argv[i + 1]); have_fragmentation_latency = 1; i++; } else if (!strcmp(arg, "--peer-ssl")) { options.peer_ssl = 1; } else if (!strcmp(arg, "--peer-tcp-socket-sndbuf")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.peer_tcp_socket_sndbuf = atoi(argv[i + 1])) < 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--send-buffer-size")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.send_buffer_size = atoi(argv[i + 1])) <= 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--send-buffer-relay-size")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.send_buffer_relay_size = atoi(argv[i + 1])) <= 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--max-macs")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.max_macs = atoi(argv[i + 1])) <= 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--max-groups")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.max_groups = atoi(argv[i + 1])) <= 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--igmp-group-membership-interval")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.igmp_group_membership_interval = atoi(argv[i + 1])) <= 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--igmp-last-member-query-time")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.igmp_last_member_query_time = atoi(argv[i + 1])) <= 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--max-peers")) { if (1 >= argc - i) { fprintf(stderr, "%s: requires an argument\n", arg); return 0; } if ((options.max_peers = atoi(argv[i + 1])) <= 0) { fprintf(stderr, "%s: wrong argument\n", arg); return 0; } i++; } else if (!strcmp(arg, "--allow-peer-talk-without-ssl")) { options.allow_peer_talk_without_ssl = 1; } else { fprintf(stderr, "unknown option: %s\n", arg); return 0; } } if (options.help || options.version) { return 1; } if (options.ssl != !!options.nssdb) { fprintf(stderr, "False: --ssl <=> --nssdb\n"); return 0; } if (options.ssl != !!options.client_cert_name) { fprintf(stderr, "False: --ssl <=> --client-cert-name\n"); return 0; } if (!options.server_addr) { fprintf(stderr, "False: --server-addr\n"); return 0; } if (options.transport_mode < 0) { fprintf(stderr, "False: --transport-mode\n"); return 0; } if ((options.transport_mode == TRANSPORT_MODE_UDP) != (options.encryption_mode >= 0)) { fprintf(stderr, "False: UDP <=> --encryption-mode\n"); return 0; } if ((options.transport_mode == TRANSPORT_MODE_UDP) != (options.hash_mode >= 0)) { fprintf(stderr, "False: UDP <=> --hash-mode\n"); return 0; } if (!(!(options.otp_mode != SPPROTO_OTP_MODE_NONE) || (options.transport_mode == TRANSPORT_MODE_UDP))) { fprintf(stderr, "False: --otp => UDP\n"); return 0; } if (!(!have_fragmentation_latency || (options.transport_mode == TRANSPORT_MODE_UDP))) { fprintf(stderr, "False: --fragmentation-latency => UDP\n"); return 0; } if (!(!options.peer_ssl || (options.ssl && options.transport_mode == TRANSPORT_MODE_TCP))) { fprintf(stderr, "False: --peer-ssl => (--ssl && TCP)\n"); return 0; } if (!(!(options.peer_tcp_socket_sndbuf >= 0) || options.transport_mode == TRANSPORT_MODE_TCP)) { fprintf(stderr, "False: --peer-tcp-socket-sndbuf => TCP\n"); return 0; } return 1; } int process_arguments (void) { // resolve server address ASSERT(options.server_addr) if (!BAddr_Parse(&server_addr, options.server_addr, server_name, sizeof(server_name))) { BLog(BLOG_ERROR, "server addr: BAddr_Parse failed"); return 0; } // override server name if requested if (options.server_name) { if (strlen(options.server_name) >= sizeof(server_name)) { BLog(BLOG_ERROR, "server name: too long"); return 0; } strcpy(server_name, options.server_name); } // resolve bind addresses and external addresses num_bind_addrs = 0; for (int i = 0; i < options.num_bind_addrs; i++) { struct bind_addr_option *addr = &options.bind_addrs[i]; struct bind_addr *out = &bind_addrs[num_bind_addrs]; // read addr if (!BAddr_Parse(&out->addr, addr->addr, NULL, 0)) { BLog(BLOG_ERROR, "bind addr: BAddr_Parse failed"); return 0; } // read num ports if (options.transport_mode == TRANSPORT_MODE_UDP) { if (addr->num_ports < 0) { BLog(BLOG_ERROR, "bind addr: num ports missing"); return 0; } out->num_ports = addr->num_ports; } else if (addr->num_ports >= 0) { BLog(BLOG_ERROR, "bind addr: num ports given, but not using UDP"); return 0; } // read ext addrs out->num_ext_addrs = 0; for (int j = 0; j < addr->num_ext_addrs; j++) { struct ext_addr_option *eaddr = &addr->ext_addrs[j]; struct ext_addr *eout = &out->ext_addrs[out->num_ext_addrs]; // read addr if (string_begins_with(eaddr->addr, "{server_reported}:")) { char *colon = strstr(eaddr->addr, ":"); if ((eout->server_reported_port = atoi(colon + 1)) < 0) { BLog(BLOG_ERROR, "ext addr: wrong port"); return 0; } } else { eout->server_reported_port = -1; if (!BAddr_Parse(&eout->addr, eaddr->addr, NULL, 0)) { BLog(BLOG_ERROR, "ext addr: BAddr_Parse failed"); return 0; } if (!addr_supported(eout->addr)) { BLog(BLOG_ERROR, "ext addr: addr_supported failed"); return 0; } } // read scope if (strlen(eaddr->scope) >= sizeof(eout->scope)) { BLog(BLOG_ERROR, "ext addr: too long"); return 0; } strcpy(eout->scope, eaddr->scope); out->num_ext_addrs++; } num_bind_addrs++; } // initialize SPProto parameters if (options.transport_mode == TRANSPORT_MODE_UDP) { sp_params.encryption_mode = options.encryption_mode; sp_params.hash_mode = options.hash_mode; sp_params.otp_mode = options.otp_mode; if (options.otp_mode > 0) { sp_params.otp_num = options.otp_num; } } return 1; } int ssl_flags (void) { int flags = 0; if (options.use_threads_for_ssl_handshake) { flags |= BSSLCONNECTION_FLAG_THREADWORK_HANDSHAKE; } if (options.use_threads_for_ssl_data) { flags |= BSSLCONNECTION_FLAG_THREADWORK_IO; } return flags; } void signal_handler (void *unused) { BLog(BLOG_NOTICE, "termination requested"); terminate(); } void peer_add (peerid_t id, int flags, const uint8_t *cert, int cert_len) { ASSERT(server_ready) ASSERT(num_peers < options.max_peers) ASSERT(!find_peer_by_id(id)) ASSERT(id != my_id) ASSERT(cert_len >= 0) ASSERT(cert_len <= SCID_NEWCLIENT_MAX_CERT_LEN) // allocate structure struct peer_data *peer = (struct peer_data *)malloc(sizeof(*peer)); if (!peer) { BLog(BLOG_ERROR, "peer %d: failed to allocate memory", (int)id); goto fail0; } // remember id peer->id = id; // remember flags peer->flags = flags; // set no common name peer->common_name = NULL; if (options.ssl) { // remember certificate memcpy(peer->cert, cert, cert_len); peer->cert_len = cert_len; // make sure that CERT_DecodeCertFromPackage will interpretet the input as raw DER and not base64, // in which case following workaroud wouldn't help if (!(cert_len > 0 && (cert[0] & 0x1f) == 0x10)) { peer_log(peer, BLOG_ERROR, "certificate does not look like DER"); goto fail1; } // copy the certificate and append it a good load of zero bytes, // hopefully preventing the crappy CERT_DecodeCertFromPackage from crashing // by reading past the of its input uint8_t *certbuf = (uint8_t *)malloc(cert_len + 100); if (!certbuf) { peer_log(peer, BLOG_ERROR, "malloc failed"); goto fail1; } memcpy(certbuf, cert, cert_len); memset(certbuf + cert_len, 0, 100); // decode certificate, so we can extract the common name CERTCertificate *nsscert = CERT_DecodeCertFromPackage((char *)certbuf, cert_len); if (!nsscert) { peer_log(peer, BLOG_ERROR, "CERT_DecodeCertFromPackage failed (%d)", PORT_GetError()); free(certbuf); goto fail1; } free(certbuf); // remember common name if (!(peer->common_name = CERT_GetCommonName(&nsscert->subject))) { peer_log(peer, BLOG_ERROR, "CERT_GetCommonName failed"); CERT_DestroyCertificate(nsscert); goto fail1; } CERT_DestroyCertificate(nsscert); } // init and set init job (must be before initing server flow so we can send) BPending_Init(&peer->job_init, BReactor_PendingGroup(&ss), (BPending_handler)peer_job_init, peer); BPending_Set(&peer->job_init); // init server flow if (!(peer->server_flow = server_flow_init())) { peer_log(peer, BLOG_ERROR, "server_flow_init failed"); goto fail2; } if ((peer->flags & SCID_NEWCLIENT_FLAG_SSL) && !options.ssl) { peer_log(peer, BLOG_ERROR, "peer requires talking with SSL, but we're not using SSL!?"); goto fail3; } if (options.ssl && !(peer->flags & SCID_NEWCLIENT_FLAG_SSL) && !options.allow_peer_talk_without_ssl) { peer_log(peer, BLOG_ERROR, "peer requires talking without SSL, but we don't allow that"); goto fail3; } // choose chat SSL mode int chat_ssl_mode = PEERCHAT_SSL_NONE; if ((peer->flags & SCID_NEWCLIENT_FLAG_SSL)) { chat_ssl_mode = (peer_am_master(peer) ? PEERCHAT_SSL_SERVER : PEERCHAT_SSL_CLIENT); } // init chat if (!PeerChat_Init(&peer->chat, peer->id, chat_ssl_mode, ssl_flags(), client_cert, client_key, peer->cert, peer->cert_len, BReactor_PendingGroup(&ss), &twd, peer, (BLog_logfunc)peer_logfunc, (PeerChat_handler_error)peer_chat_handler_error, (PeerChat_handler_message)peer_chat_handler_message )) { peer_log(peer, BLOG_ERROR, "PeerChat_Init failed"); goto fail3; } // set no message peer->chat_send_msg_len = -1; // connect server flow to chat server_flow_connect(peer->server_flow, PeerChat_GetSendOutput(&peer->chat)); // set have chat peer->have_chat = 1; // set have no resetpeer peer->have_resetpeer = 0; // init local flow if (!DataProtoFlow_Init(&peer->local_dpflow, &device_dpsource, my_id, peer->id, options.send_buffer_size, -1, NULL, NULL)) { peer_log(peer, BLOG_ERROR, "DataProtoFlow_Init failed"); goto fail4; } // init frame decider peer if (!FrameDeciderPeer_Init(&peer->decider_peer, &frame_decider, peer, (BLog_logfunc)peer_logfunc)) { peer_log(peer, BLOG_ERROR, "FrameDeciderPeer_Init failed"); goto fail5; } // init receive peer DPReceivePeer_Init(&peer->receive_peer, &device_output_dprd, peer->id, &peer->decider_peer, !!(peer->flags & SCID_NEWCLIENT_FLAG_RELAY_CLIENT)); // have no link peer->have_link = 0; // have no relaying peer->relaying_peer = NULL; // not waiting for relay peer->waiting_relay = 0; // init reset timer BTimer_Init(&peer->reset_timer, PEER_RETRY_TIME, (BTimer_handler)peer_reset_timer_handler, peer); // is not relay server peer->is_relay = 0; // init binding peer->binding = 0; // add to peers list LinkedList1_Append(&peers, &peer->list_node); num_peers++; switch (chat_ssl_mode) { case PEERCHAT_SSL_NONE: peer_log(peer, BLOG_INFO, "initialized; talking to peer in plaintext mode"); break; case PEERCHAT_SSL_CLIENT: peer_log(peer, BLOG_INFO, "initialized; talking to peer in SSL client mode"); break; case PEERCHAT_SSL_SERVER: peer_log(peer, BLOG_INFO, "initialized; talking to peer in SSL server mode"); break; } return; fail5: DataProtoFlow_Free(&peer->local_dpflow); fail4: server_flow_disconnect(peer->server_flow); PeerChat_Free(&peer->chat); fail3: server_flow_free(peer->server_flow); fail2: BPending_Free(&peer->job_init); if (peer->common_name) { PORT_Free(peer->common_name); } fail1: free(peer); fail0: return; } void peer_remove (struct peer_data *peer, int exiting) { peer_log(peer, BLOG_INFO, "removing"); // cleanup connections peer_cleanup_connections(peer); ASSERT(!peer->have_link) ASSERT(!peer->relaying_peer) ASSERT(!peer->waiting_relay) ASSERT(!peer->is_relay) // remove from peers list LinkedList1_Remove(&peers, &peer->list_node); num_peers--; // free reset timer BReactor_RemoveTimer(&ss, &peer->reset_timer); // free receive peer DPReceivePeer_Free(&peer->receive_peer); // free frame decider FrameDeciderPeer_Free(&peer->decider_peer); // free local flow DataProtoFlow_Free(&peer->local_dpflow); // free chat if (peer->have_chat) { peer_free_chat(peer); } // free resetpeer if (peer->have_resetpeer) { // disconnect resetpeer source from server flow server_flow_disconnect(peer->server_flow); // free resetpeer source SinglePacketSource_Free(&peer->resetpeer_source); } // free/die server flow if (exiting || !PacketPassFairQueueFlow_IsBusy(&peer->server_flow->qflow)) { server_flow_free(peer->server_flow); } else { server_flow_die(peer->server_flow); } // free jobs BPending_Free(&peer->job_init); // free common name if (peer->common_name) { PORT_Free(peer->common_name); } // free peer structure free(peer); } void peer_logfunc (struct peer_data *peer) { BLog_Append("peer %d", (int)peer->id); if (peer->common_name) { BLog_Append(" (%s)", peer->common_name); } BLog_Append(": "); } void peer_log (struct peer_data *peer, int level, const char *fmt, ...) { va_list vl; va_start(vl, fmt); BLog_LogViaFuncVarArg((BLog_logfunc)peer_logfunc, peer, BLOG_CURRENT_CHANNEL, level, fmt, vl); va_end(vl); } int peer_am_master (struct peer_data *peer) { return (my_id > peer->id); } void peer_free_chat (struct peer_data *peer) { ASSERT(peer->have_chat) // disconnect chat from server flow server_flow_disconnect(peer->server_flow); // free chat PeerChat_Free(&peer->chat); // set have no chat peer->have_chat = 0; } int peer_init_link (struct peer_data *peer) { ASSERT(!peer->have_link) ASSERT(!peer->relaying_peer) ASSERT(!peer->waiting_relay) ASSERT(!peer->is_relay) // init receive receiver DPReceiveReceiver_Init(&peer->receive_receiver, &peer->receive_peer); PacketPassInterface *recv_if = DPReceiveReceiver_GetInput(&peer->receive_receiver); // init transport-specific link objects PacketPassInterface *link_if; if (options.transport_mode == TRANSPORT_MODE_UDP) { // init DatagramPeerIO if (!DatagramPeerIO_Init( &peer->pio.udp.pio, &ss, data_mtu, CLIENT_UDP_MTU, sp_params, options.fragmentation_latency, PEER_UDP_ASSEMBLER_NUM_FRAMES, recv_if, options.otp_num_warn, &twd, peer, (BLog_logfunc)peer_logfunc, (DatagramPeerIO_handler_error)peer_udp_pio_handler_error, (DatagramPeerIO_handler_otp_warning)peer_udp_pio_handler_seed_warning, (DatagramPeerIO_handler_otp_ready)peer_udp_pio_handler_seed_ready )) { peer_log(peer, BLOG_ERROR, "DatagramPeerIO_Init failed"); goto fail1; } if (SPPROTO_HAVE_OTP(sp_params)) { // init send seed state peer->pio.udp.sendseed_nextid = 0; peer->pio.udp.sendseed_sent = 0; // init send seed job BPending_Init(&peer->pio.udp.job_send_seed, BReactor_PendingGroup(&ss), (BPending_handler)peer_job_send_seed, peer); } link_if = DatagramPeerIO_GetSendInput(&peer->pio.udp.pio); } else { // init StreamPeerIO if (!StreamPeerIO_Init( &peer->pio.tcp.pio, &ss, &twd, options.peer_ssl, ssl_flags(), (options.peer_ssl ? peer->cert : NULL), (options.peer_ssl ? peer->cert_len : -1), data_mtu, (options.peer_tcp_socket_sndbuf >= 0 ? options.peer_tcp_socket_sndbuf : PEER_DEFAULT_TCP_SOCKET_SNDBUF), recv_if, (BLog_logfunc)peer_logfunc, (StreamPeerIO_handler_error)peer_tcp_pio_handler_error, peer )) { peer_log(peer, BLOG_ERROR, "StreamPeerIO_Init failed"); goto fail1; } link_if = StreamPeerIO_GetSendInput(&peer->pio.tcp.pio); } // init sending if (!DataProtoSink_Init(&peer->send_dp, &ss, link_if, PEER_KEEPALIVE_INTERVAL, PEER_KEEPALIVE_RECEIVE_TIMER, (DataProtoSink_handler)peer_dataproto_handler, peer)) { peer_log(peer, BLOG_ERROR, "DataProto_Init failed"); goto fail2; } // attach local flow to our DataProtoSink DataProtoFlow_Attach(&peer->local_dpflow, &peer->send_dp); // attach receive peer to our DataProtoSink DPReceivePeer_AttachSink(&peer->receive_peer, &peer->send_dp); // set have link peer->have_link = 1; return 1; fail2: if (options.transport_mode == TRANSPORT_MODE_UDP) { if (SPPROTO_HAVE_OTP(sp_params)) { BPending_Free(&peer->pio.udp.job_send_seed); } DatagramPeerIO_Free(&peer->pio.udp.pio); } else { StreamPeerIO_Free(&peer->pio.tcp.pio); } fail1: DPReceiveReceiver_Free(&peer->receive_receiver); return 0; } void peer_free_link (struct peer_data *peer) { ASSERT(peer->have_link) ASSERT(!peer->is_relay) ASSERT(!peer->relaying_peer) ASSERT(!peer->waiting_relay) // detach receive peer from our DataProtoSink DPReceivePeer_DetachSink(&peer->receive_peer); // detach local flow from our DataProtoSink DataProtoFlow_Detach(&peer->local_dpflow); // free sending DataProtoSink_Free(&peer->send_dp); // free transport-specific link objects if (options.transport_mode == TRANSPORT_MODE_UDP) { if (SPPROTO_HAVE_OTP(sp_params)) { BPending_Free(&peer->pio.udp.job_send_seed); } DatagramPeerIO_Free(&peer->pio.udp.pio); } else { StreamPeerIO_Free(&peer->pio.tcp.pio); } // free receive receiver DPReceiveReceiver_Free(&peer->receive_receiver); // set have no link peer->have_link = 0; } void peer_cleanup_connections (struct peer_data *peer) { if (peer->have_link) { if (peer->is_relay) { peer_disable_relay_provider(peer); } peer_free_link(peer); } else if (peer->relaying_peer) { peer_free_relaying(peer); } else if (peer->waiting_relay) { peer_unregister_need_relay(peer); } ASSERT(!peer->have_link) ASSERT(!peer->relaying_peer) ASSERT(!peer->waiting_relay) ASSERT(!peer->is_relay) } void peer_enable_relay_provider (struct peer_data *peer) { ASSERT(peer->have_link) ASSERT(!peer->is_relay) ASSERT(!peer->relaying_peer) ASSERT(!peer->waiting_relay) // add to relays list LinkedList1_Append(&relays, &peer->relay_list_node); // init users list LinkedList1_Init(&peer->relay_users); // set is relay peer->is_relay = 1; // assign relays assign_relays(); } void peer_disable_relay_provider (struct peer_data *peer) { ASSERT(peer->is_relay) ASSERT(peer->have_link) ASSERT(!peer->relaying_peer) ASSERT(!peer->waiting_relay) // disconnect relay users LinkedList1Node *list_node; while (list_node = LinkedList1_GetFirst(&peer->relay_users)) { struct peer_data *relay_user = UPPER_OBJECT(list_node, struct peer_data, relaying_list_node); ASSERT(relay_user->relaying_peer == peer) // disconnect relay user peer_free_relaying(relay_user); // add it to need relay list peer_register_need_relay(relay_user); } // remove from relays list LinkedList1_Remove(&relays, &peer->relay_list_node); // set is not relay peer->is_relay = 0; // assign relays assign_relays(); } void peer_install_relaying (struct peer_data *peer, struct peer_data *relay) { ASSERT(!peer->relaying_peer) ASSERT(!peer->have_link) ASSERT(!peer->waiting_relay) ASSERT(relay->is_relay) ASSERT(!peer->is_relay) ASSERT(relay->have_link) peer_log(peer, BLOG_INFO, "installing relaying through %d", (int)relay->id); // add to relay's users list LinkedList1_Append(&relay->relay_users, &peer->relaying_list_node); // attach local flow to relay DataProtoFlow_Attach(&peer->local_dpflow, &relay->send_dp); // set relaying peer->relaying_peer = relay; } void peer_free_relaying (struct peer_data *peer) { ASSERT(peer->relaying_peer) ASSERT(!peer->have_link) ASSERT(!peer->waiting_relay) struct peer_data *relay = peer->relaying_peer; ASSERT(relay->is_relay) ASSERT(relay->have_link) peer_log(peer, BLOG_INFO, "uninstalling relaying through %d", (int)relay->id); // detach local flow from relay DataProtoFlow_Detach(&peer->local_dpflow); // remove from relay's users list LinkedList1_Remove(&relay->relay_users, &peer->relaying_list_node); // set not relaying peer->relaying_peer = NULL; } void peer_need_relay (struct peer_data *peer) { ASSERT(!peer->is_relay) if (peer->waiting_relay) { // already waiting for relay, do nothing return; } if (peer->have_link) { peer_free_link(peer); } else if (peer->relaying_peer) { peer_free_relaying(peer); } // register the peer as needing a relay peer_register_need_relay(peer); // assign relays assign_relays(); } void peer_register_need_relay (struct peer_data *peer) { ASSERT(!peer->waiting_relay) ASSERT(!peer->have_link) ASSERT(!peer->relaying_peer) ASSERT(!peer->is_relay) // add to need relay list LinkedList1_Append(&waiting_relay_peers, &peer->waiting_relay_list_node); // set waiting relay peer->waiting_relay = 1; } void peer_unregister_need_relay (struct peer_data *peer) { ASSERT(peer->waiting_relay) ASSERT(!peer->have_link) ASSERT(!peer->relaying_peer) ASSERT(!peer->is_relay) // remove from need relay list LinkedList1_Remove(&waiting_relay_peers, &peer->waiting_relay_list_node); // set not waiting relay peer->waiting_relay = 0; } void peer_reset (struct peer_data *peer) { peer_log(peer, BLOG_NOTICE, "resetting"); // cleanup connections peer_cleanup_connections(peer); if (peer_am_master(peer)) { // if we're the master, schedule retry BReactor_SetTimer(&ss, &peer->reset_timer); } else { // if we're the slave, report to master peer_send_simple(peer, MSGID_YOURETRY); } } void peer_resetpeer (struct peer_data *peer) { ASSERT(peer->have_chat) ASSERT(!peer->have_resetpeer) // free chat peer_free_chat(peer); // build resetpeer packet struct packetproto_header pp_header; struct sc_header sc_header; struct sc_client_resetpeer sc_resetpeer; pp_header.len = htol16(sizeof(struct sc_header) + sizeof(struct sc_client_resetpeer)); sc_header.type = htol8(SCID_RESETPEER); sc_resetpeer.clientid = htol16(peer->id); memcpy(peer->resetpeer_packet, &pp_header, sizeof(pp_header)); memcpy(peer->resetpeer_packet + sizeof(pp_header), &sc_header, sizeof(sc_header)); memcpy(peer->resetpeer_packet + sizeof(pp_header) + sizeof(sc_header), &sc_resetpeer, sizeof(sc_resetpeer)); // init resetpeer sourse SinglePacketSource_Init(&peer->resetpeer_source, peer->resetpeer_packet, sizeof(peer->resetpeer_packet), BReactor_PendingGroup(&ss)); // connect server flow to resetpeer source server_flow_connect(peer->server_flow, SinglePacketSource_GetOutput(&peer->resetpeer_source)); // set have resetpeer peer->have_resetpeer = 1; } void peer_chat_handler_error (struct peer_data *peer) { ASSERT(peer->have_chat) ASSERT(!peer->have_resetpeer) peer_log(peer, BLOG_ERROR, "chat error, sending resetpeer"); peer_resetpeer(peer); } void peer_chat_handler_message (struct peer_data *peer, uint8_t *data, int data_len) { ASSERT(peer->have_chat) ASSERT(data_len >= 0) ASSERT(data_len <= SC_MAX_MSGLEN) // parse message msgParser parser; if (!msgParser_Init(&parser, data, data_len)) { peer_log(peer, BLOG_NOTICE, "msg: failed to parse"); return; } // read message uint16_t type = 0; // to remove warning ASSERT_EXECUTE(msgParser_Gettype(&parser, &type)) uint8_t *payload = NULL; // to remove warning int payload_len = 0; // to remove warning ASSERT_EXECUTE(msgParser_Getpayload(&parser, &payload, &payload_len)) // dispatch according to message type switch (type) { case MSGID_YOUCONNECT: peer_msg_youconnect(peer, payload, payload_len); return; case MSGID_CANNOTCONNECT: peer_msg_cannotconnect(peer, payload, payload_len); return; case MSGID_CANNOTBIND: peer_msg_cannotbind(peer, payload, payload_len); return; case MSGID_YOURETRY: peer_msg_youretry(peer, payload, payload_len); return; case MSGID_SEED: peer_msg_seed(peer, payload, payload_len); return; case MSGID_CONFIRMSEED: peer_msg_confirmseed(peer, payload, payload_len); return; default: BLog(BLOG_NOTICE, "msg: unknown type"); return; } } void peer_msg_youconnect (struct peer_data *peer, uint8_t *data, int data_len) { // init parser msg_youconnectParser parser; if (!msg_youconnectParser_Init(&parser, data, data_len)) { peer_log(peer, BLOG_WARNING, "msg_youconnect: failed to parse"); return; } // try addresses BAddr addr; while (1) { // get address message uint8_t *addrmsg_data; int addrmsg_len; if (!msg_youconnectParser_Getaddr(&parser, &addrmsg_data, &addrmsg_len)) { peer_log(peer, BLOG_NOTICE, "msg_youconnect: no usable addresses"); peer_send_simple(peer, MSGID_CANNOTCONNECT); return; } // parse address message msg_youconnect_addrParser aparser; if (!msg_youconnect_addrParser_Init(&aparser, addrmsg_data, addrmsg_len)) { peer_log(peer, BLOG_WARNING, "msg_youconnect: failed to parse address message"); return; } // check if the address scope is known uint8_t *name_data = NULL; // to remove warning int name_len = 0; // to remove warning ASSERT_EXECUTE(msg_youconnect_addrParser_Getname(&aparser, &name_data, &name_len)) char *name; if (!(name = address_scope_known(name_data, name_len))) { continue; } // read address uint8_t *addr_data = NULL; // to remove warning int addr_len = 0; // to remove warning ASSERT_EXECUTE(msg_youconnect_addrParser_Getaddr(&aparser, &addr_data, &addr_len)) if (!addr_read(addr_data, addr_len, &addr)) { peer_log(peer, BLOG_WARNING, "msg_youconnect: failed to read address"); continue; } peer_log(peer, BLOG_NOTICE, "msg_youconnect: using address in scope '%s'", name); break; } // discard further addresses msg_youconnectParser_Forwardaddr(&parser); uint8_t *key = NULL; uint64_t password = 0; // read additonal parameters if (options.transport_mode == TRANSPORT_MODE_UDP) { if (SPPROTO_HAVE_ENCRYPTION(sp_params)) { int key_len; if (!msg_youconnectParser_Getkey(&parser, &key, &key_len)) { peer_log(peer, BLOG_WARNING, "msg_youconnect: no key"); return; } if (key_len != BEncryption_cipher_key_size(sp_params.encryption_mode)) { peer_log(peer, BLOG_WARNING, "msg_youconnect: wrong key size"); return; } } } else { if (!msg_youconnectParser_Getpassword(&parser, &password)) { peer_log(peer, BLOG_WARNING, "msg_youconnect: no password"); return; } } if (!msg_youconnectParser_GotEverything(&parser)) { peer_log(peer, BLOG_WARNING, "msg_youconnect: stray data"); return; } peer_log(peer, BLOG_INFO, "connecting"); peer_connect(peer, addr, key, password); } void peer_msg_cannotconnect (struct peer_data *peer, uint8_t *data, int data_len) { if (data_len != 0) { peer_log(peer, BLOG_WARNING, "msg_cannotconnect: invalid length"); return; } if (!peer->binding) { peer_log(peer, BLOG_WARNING, "msg_cannotconnect: not binding"); return; } peer_log(peer, BLOG_INFO, "peer could not connect"); // continue trying bind addresses peer_bind(peer); return; } void peer_msg_cannotbind (struct peer_data *peer, uint8_t *data, int data_len) { if (data_len != 0) { peer_log(peer, BLOG_WARNING, "msg_cannotbind: invalid length"); return; } peer_log(peer, BLOG_INFO, "peer cannot bind"); if (!peer_am_master(peer)) { peer_start_binding(peer); } else { if (!peer->is_relay) { peer_need_relay(peer); } } } void peer_msg_seed (struct peer_data *peer, uint8_t *data, int data_len) { msg_seedParser parser; if (!msg_seedParser_Init(&parser, data, data_len)) { peer_log(peer, BLOG_WARNING, "msg_seed: failed to parse"); return; } // read message uint16_t seed_id = 0; // to remove warning ASSERT_EXECUTE(msg_seedParser_Getseed_id(&parser, &seed_id)) uint8_t *key = NULL; // to remove warning int key_len = 0; // to remove warning ASSERT_EXECUTE(msg_seedParser_Getkey(&parser, &key, &key_len)) uint8_t *iv = NULL; // to remove warning int iv_len = 0; // to remove warning ASSERT_EXECUTE(msg_seedParser_Getiv(&parser, &iv, &iv_len)) if (options.transport_mode != TRANSPORT_MODE_UDP) { peer_log(peer, BLOG_WARNING, "msg_seed: not in UDP mode"); return; } if (!SPPROTO_HAVE_OTP(sp_params)) { peer_log(peer, BLOG_WARNING, "msg_seed: OTPs disabled"); return; } if (key_len != BEncryption_cipher_key_size(sp_params.otp_mode)) { peer_log(peer, BLOG_WARNING, "msg_seed: wrong key length"); return; } if (iv_len != BEncryption_cipher_block_size(sp_params.otp_mode)) { peer_log(peer, BLOG_WARNING, "msg_seed: wrong IV length"); return; } if (!peer->have_link) { peer_log(peer, BLOG_WARNING, "msg_seed: have no link"); return; } peer_log(peer, BLOG_DEBUG, "received OTP receive seed"); // add receive seed DatagramPeerIO_AddOTPRecvSeed(&peer->pio.udp.pio, seed_id, key, iv); // remember seed ID so we can confirm it from peer_udp_pio_handler_seed_ready peer->pio.udp.pending_recvseed_id = seed_id; } void peer_msg_confirmseed (struct peer_data *peer, uint8_t *data, int data_len) { msg_confirmseedParser parser; if (!msg_confirmseedParser_Init(&parser, data, data_len)) { peer_log(peer, BLOG_WARNING, "msg_confirmseed: failed to parse"); return; } // read message uint16_t seed_id = 0; // to remove warning ASSERT_EXECUTE(msg_confirmseedParser_Getseed_id(&parser, &seed_id)) if (options.transport_mode != TRANSPORT_MODE_UDP) { peer_log(peer, BLOG_WARNING, "msg_confirmseed: not in UDP mode"); return; } if (!SPPROTO_HAVE_OTP(sp_params)) { peer_log(peer, BLOG_WARNING, "msg_confirmseed: OTPs disabled"); return; } if (!peer->have_link) { peer_log(peer, BLOG_WARNING, "msg_confirmseed: have no link"); return; } if (!peer->pio.udp.sendseed_sent) { peer_log(peer, BLOG_WARNING, "msg_confirmseed: no seed has been sent"); return; } if (seed_id != peer->pio.udp.sendseed_sent_id) { peer_log(peer, BLOG_WARNING, "msg_confirmseed: invalid seed: expecting %d, received %d", (int)peer->pio.udp.sendseed_sent_id, (int)seed_id); return; } peer_log(peer, BLOG_DEBUG, "OTP send seed confirmed"); // no longer waiting for confirmation peer->pio.udp.sendseed_sent = 0; // start using the seed DatagramPeerIO_SetOTPSendSeed(&peer->pio.udp.pio, peer->pio.udp.sendseed_sent_id, peer->pio.udp.sendseed_sent_key, peer->pio.udp.sendseed_sent_iv); } void peer_msg_youretry (struct peer_data *peer, uint8_t *data, int data_len) { if (data_len != 0) { peer_log(peer, BLOG_WARNING, "msg_youretry: invalid length"); return; } if (!peer_am_master(peer)) { peer_log(peer, BLOG_WARNING, "msg_youretry: we are not master"); return; } peer_log(peer, BLOG_NOTICE, "requests reset"); peer_reset(peer); } void peer_udp_pio_handler_seed_warning (struct peer_data *peer) { ASSERT(options.transport_mode == TRANSPORT_MODE_UDP) ASSERT(SPPROTO_HAVE_OTP(sp_params)) ASSERT(peer->have_link) // generate and send a new seed if (!peer->pio.udp.sendseed_sent) { BPending_Set(&peer->pio.udp.job_send_seed); } } void peer_udp_pio_handler_seed_ready (struct peer_data *peer) { ASSERT(options.transport_mode == TRANSPORT_MODE_UDP) ASSERT(SPPROTO_HAVE_OTP(sp_params)) ASSERT(peer->have_link) // send confirmation peer_send_confirmseed(peer, peer->pio.udp.pending_recvseed_id); } void peer_udp_pio_handler_error (struct peer_data *peer) { ASSERT(options.transport_mode == TRANSPORT_MODE_UDP) ASSERT(peer->have_link) peer_log(peer, BLOG_NOTICE, "UDP connection failed"); peer_reset(peer); return; } void peer_tcp_pio_handler_error (struct peer_data *peer) { ASSERT(options.transport_mode == TRANSPORT_MODE_TCP) ASSERT(peer->have_link) peer_log(peer, BLOG_NOTICE, "TCP connection failed"); peer_reset(peer); return; } void peer_reset_timer_handler (struct peer_data *peer) { ASSERT(peer_am_master(peer)) BLog(BLOG_NOTICE, "retry timer expired"); // start setup process peer_start_binding(peer); } void peer_start_binding (struct peer_data *peer) { peer->binding = 1; peer->binding_addrpos = 0; peer_bind(peer); } void peer_bind (struct peer_data *peer) { ASSERT(peer->binding) ASSERT(peer->binding_addrpos >= 0) ASSERT(peer->binding_addrpos <= num_bind_addrs) while (peer->binding_addrpos < num_bind_addrs) { // if there are no external addresses, skip bind address if (bind_addrs[peer->binding_addrpos].num_ext_addrs == 0) { peer->binding_addrpos++; continue; } // try to bind int cont; peer_bind_one_address(peer, peer->binding_addrpos, &cont); // increment address counter peer->binding_addrpos++; if (!cont) { return; } } peer_log(peer, BLOG_NOTICE, "no more addresses to bind to"); // no longer binding peer->binding = 0; // tell the peer we failed to bind peer_send_simple(peer, MSGID_CANNOTBIND); // if we are the slave, setup relaying if (!peer_am_master(peer)) { if (!peer->is_relay) { peer_need_relay(peer); } } } void peer_bind_one_address (struct peer_data *peer, int addr_index, int *cont) { ASSERT(addr_index >= 0) ASSERT(addr_index < num_bind_addrs) ASSERT(bind_addrs[addr_index].num_ext_addrs > 0) // get a fresh link peer_cleanup_connections(peer); if (!peer_init_link(peer)) { peer_log(peer, BLOG_ERROR, "cannot get link"); *cont = 0; peer_reset(peer); return; } if (options.transport_mode == TRANSPORT_MODE_UDP) { // get addr struct bind_addr *addr = &bind_addrs[addr_index]; // try binding to all ports in the range int port_add; for (port_add = 0; port_add < addr->num_ports; port_add++) { BAddr tryaddr = addr->addr; BAddr_SetPort(&tryaddr, hton16(ntoh16(BAddr_GetPort(&tryaddr)) + port_add)); if (DatagramPeerIO_Bind(&peer->pio.udp.pio, tryaddr)) { break; } } if (port_add == addr->num_ports) { BLog(BLOG_NOTICE, "failed to bind to any port"); *cont = 1; return; } uint8_t key[BENCRYPTION_MAX_KEY_SIZE]; // generate and set encryption key if (SPPROTO_HAVE_ENCRYPTION(sp_params)) { BRandom_randomize(key, BEncryption_cipher_key_size(sp_params.encryption_mode)); DatagramPeerIO_SetEncryptionKey(&peer->pio.udp.pio, key); } // schedule sending OTP seed if (SPPROTO_HAVE_OTP(sp_params)) { BPending_Set(&peer->pio.udp.job_send_seed); } // send connectinfo peer_send_conectinfo(peer, addr_index, port_add, key, 0); } else { // order StreamPeerIO to listen uint64_t pass; StreamPeerIO_Listen(&peer->pio.tcp.pio, &listeners[addr_index], &pass); // send connectinfo peer_send_conectinfo(peer, addr_index, 0, NULL, pass); } peer_log(peer, BLOG_NOTICE, "bound to address number %d", addr_index); *cont = 0; } void peer_connect (struct peer_data *peer, BAddr addr, uint8_t* encryption_key, uint64_t password) { // get a fresh link peer_cleanup_connections(peer); if (!peer_init_link(peer)) { peer_log(peer, BLOG_ERROR, "cannot get link"); peer_reset(peer); return; } if (options.transport_mode == TRANSPORT_MODE_UDP) { // order DatagramPeerIO to connect if (!DatagramPeerIO_Connect(&peer->pio.udp.pio, addr)) { peer_log(peer, BLOG_NOTICE, "DatagramPeerIO_Connect failed"); peer_reset(peer); return; } // set encryption key if (SPPROTO_HAVE_ENCRYPTION(sp_params)) { DatagramPeerIO_SetEncryptionKey(&peer->pio.udp.pio, encryption_key); } // generate and send a send seed if (SPPROTO_HAVE_OTP(sp_params)) { BPending_Set(&peer->pio.udp.job_send_seed); } } else { // order StreamPeerIO to connect if (!StreamPeerIO_Connect(&peer->pio.tcp.pio, addr, password, client_cert, client_key)) { peer_log(peer, BLOG_NOTICE, "StreamPeerIO_Connect failed"); peer_reset(peer); return; } } } static int peer_start_msg (struct peer_data *peer, void **data, int type, int len) { ASSERT(len >= 0) ASSERT(len <= MSG_MAX_PAYLOAD) ASSERT(!(len > 0) || data) ASSERT(peer->chat_send_msg_len == -1) // make sure we have chat if (!peer->have_chat) { peer_log(peer, BLOG_ERROR, "cannot send message, chat is down"); return 0; } #ifdef SIMULATE_PEER_OUT_OF_BUFFER uint8_t x; BRandom_randomize(&x, sizeof(x)); if (x < SIMULATE_PEER_OUT_OF_BUFFER) { peer_log(peer, BLOG_ERROR, "simulating out of buffer, sending resetpeer"); peer_resetpeer(peer); return 0; } #endif // obtain buffer location uint8_t *packet; if (!PeerChat_StartMessage(&peer->chat, &packet)) { peer_log(peer, BLOG_ERROR, "cannot send message, out of buffer, sending resetpeer"); peer_resetpeer(peer); return 0; } // write fields msgWriter writer; msgWriter_Init(&writer, packet); msgWriter_Addtype(&writer, type); uint8_t *payload_dst = msgWriter_Addpayload(&writer, len); msgWriter_Finish(&writer); // set have message peer->chat_send_msg_len = len; if (data) { *data = payload_dst; } return 1; } static void peer_end_msg (struct peer_data *peer) { ASSERT(peer->chat_send_msg_len >= 0) ASSERT(peer->have_chat) // submit packet to buffer PeerChat_EndMessage(&peer->chat, msg_SIZEtype + msg_SIZEpayload(peer->chat_send_msg_len)); // set no message peer->chat_send_msg_len = -1; } void peer_send_simple (struct peer_data *peer, int msgid) { if (!peer_start_msg(peer, NULL, msgid, 0)) { return; } peer_end_msg(peer); } void peer_send_conectinfo (struct peer_data *peer, int addr_index, int port_adjust, uint8_t *enckey, uint64_t pass) { ASSERT(addr_index >= 0) ASSERT(addr_index < num_bind_addrs) ASSERT(bind_addrs[addr_index].num_ext_addrs > 0) // get address struct bind_addr *bind_addr = &bind_addrs[addr_index]; // remember encryption key size int key_size = 0; // to remove warning if (options.transport_mode == TRANSPORT_MODE_UDP && SPPROTO_HAVE_ENCRYPTION(sp_params)) { key_size = BEncryption_cipher_key_size(sp_params.encryption_mode); } // calculate message length .. int msg_len = 0; // addresses for (int i = 0; i < bind_addr->num_ext_addrs; i++) { int addrmsg_len = msg_youconnect_addr_SIZEname(strlen(bind_addr->ext_addrs[i].scope)) + msg_youconnect_addr_SIZEaddr(addr_size(bind_addr->ext_addrs[i].addr)); msg_len += msg_youconnect_SIZEaddr(addrmsg_len); } // encryption key if (options.transport_mode == TRANSPORT_MODE_UDP && SPPROTO_HAVE_ENCRYPTION(sp_params)) { msg_len += msg_youconnect_SIZEkey(key_size); } // password if (options.transport_mode == TRANSPORT_MODE_TCP) { msg_len += msg_youconnect_SIZEpassword; } // check if it's too big (because of the addresses) if (msg_len > MSG_MAX_PAYLOAD) { BLog(BLOG_ERROR, "cannot send too big youconnect message"); return; } // start message uint8_t *msg; if (!peer_start_msg(peer, (void **)&msg, MSGID_YOUCONNECT, msg_len)) { return; } // init writer msg_youconnectWriter writer; msg_youconnectWriter_Init(&writer, msg); // write addresses for (int i = 0; i < bind_addr->num_ext_addrs; i++) { int name_len = strlen(bind_addr->ext_addrs[i].scope); int addr_len = addr_size(bind_addr->ext_addrs[i].addr); // get a pointer for writing the address int addrmsg_len = msg_youconnect_addr_SIZEname(name_len) + msg_youconnect_addr_SIZEaddr(addr_len); uint8_t *addrmsg_dst = msg_youconnectWriter_Addaddr(&writer, addrmsg_len); // init address writer msg_youconnect_addrWriter awriter; msg_youconnect_addrWriter_Init(&awriter, addrmsg_dst); // write scope uint8_t *name_dst = msg_youconnect_addrWriter_Addname(&awriter, name_len); memcpy(name_dst, bind_addr->ext_addrs[i].scope, name_len); // write address with adjusted port BAddr addr = bind_addr->ext_addrs[i].addr; BAddr_SetPort(&addr, hton16(ntoh16(BAddr_GetPort(&addr)) + port_adjust)); uint8_t *addr_dst = msg_youconnect_addrWriter_Addaddr(&awriter, addr_len); addr_write(addr_dst, addr); // finish address writer msg_youconnect_addrWriter_Finish(&awriter); } // write encryption key if (options.transport_mode == TRANSPORT_MODE_UDP && SPPROTO_HAVE_ENCRYPTION(sp_params)) { uint8_t *key_dst = msg_youconnectWriter_Addkey(&writer, key_size); memcpy(key_dst, enckey, key_size); } // write password if (options.transport_mode == TRANSPORT_MODE_TCP) { msg_youconnectWriter_Addpassword(&writer, pass); } // finish writer msg_youconnectWriter_Finish(&writer); // end message peer_end_msg(peer); } void peer_send_confirmseed (struct peer_data *peer, uint16_t seed_id) { ASSERT(options.transport_mode == TRANSPORT_MODE_UDP) ASSERT(SPPROTO_HAVE_OTP(sp_params)) // send confirmation int msg_len = msg_confirmseed_SIZEseed_id; uint8_t *msg; if (!peer_start_msg(peer, (void **)&msg, MSGID_CONFIRMSEED, msg_len)) { return; } msg_confirmseedWriter writer; msg_confirmseedWriter_Init(&writer, msg); msg_confirmseedWriter_Addseed_id(&writer, seed_id); msg_confirmseedWriter_Finish(&writer); peer_end_msg(peer); } void peer_dataproto_handler (struct peer_data *peer, int up) { ASSERT(peer->have_link) if (up) { peer_log(peer, BLOG_INFO, "up"); // if it can be a relay provided, enable it if ((peer->flags & SCID_NEWCLIENT_FLAG_RELAY_SERVER) && !peer->is_relay) { peer_enable_relay_provider(peer); } } else { peer_log(peer, BLOG_INFO, "down"); // if it is a relay provider, disable it if (peer->is_relay) { peer_disable_relay_provider(peer); } } } struct peer_data * find_peer_by_id (peerid_t id) { for (LinkedList1Node *node = LinkedList1_GetFirst(&peers); node; node = LinkedList1Node_Next(node)) { struct peer_data *peer = UPPER_OBJECT(node, struct peer_data, list_node); if (peer->id == id) { return peer; } } return NULL; } void device_error_handler (void *unused) { BLog(BLOG_ERROR, "device error"); terminate(); } void device_dpsource_handler (void *unused, const uint8_t *frame, int frame_len) { ASSERT(frame_len >= 0) ASSERT(frame_len <= device_mtu) // give frame to decider FrameDecider_AnalyzeAndDecide(&frame_decider, frame, frame_len); // forward frame to peers FrameDeciderPeer *decider_peer = FrameDecider_NextDestination(&frame_decider); while (decider_peer) { FrameDeciderPeer *next = FrameDecider_NextDestination(&frame_decider); struct peer_data *peer = UPPER_OBJECT(decider_peer, struct peer_data, decider_peer); DataProtoFlow_Route(&peer->local_dpflow, !!next); decider_peer = next; } } void assign_relays (void) { LinkedList1Node *list_node; while (list_node = LinkedList1_GetFirst(&waiting_relay_peers)) { struct peer_data *peer = UPPER_OBJECT(list_node, struct peer_data, waiting_relay_list_node); ASSERT(peer->waiting_relay) ASSERT(!peer->relaying_peer) ASSERT(!peer->have_link) // get a relay LinkedList1Node *list_node2 = LinkedList1_GetFirst(&relays); if (!list_node2) { BLog(BLOG_NOTICE, "no relays"); return; } struct peer_data *relay = UPPER_OBJECT(list_node2, struct peer_data, relay_list_node); ASSERT(relay->is_relay) // no longer waiting for relay peer_unregister_need_relay(peer); // install the relay peer_install_relaying(peer, relay); } } char * address_scope_known (uint8_t *name, int name_len) { ASSERT(name_len >= 0) for (int i = 0; i < options.num_scopes; i++) { if (name_len == strlen(options.scopes[i]) && !memcmp(name, options.scopes[i], name_len)) { return options.scopes[i]; } } return NULL; } void server_handler_error (void *user) { BLog(BLOG_ERROR, "server connection failed, exiting"); terminate(); } void server_handler_ready (void *user, peerid_t param_my_id, uint32_t ext_ip) { ASSERT(!server_ready) // remember our ID my_id = param_my_id; // store server reported addresses for (int i = 0; i < num_bind_addrs; i++) { struct bind_addr *addr = &bind_addrs[i]; for (int j = 0; j < addr->num_ext_addrs; j++) { struct ext_addr *eaddr = &addr->ext_addrs[j]; if (eaddr->server_reported_port >= 0) { if (ext_ip == 0) { BLog(BLOG_ERROR, "server did not provide our address"); terminate(); return; } BAddr_InitIPv4(&eaddr->addr, ext_ip, hton16(eaddr->server_reported_port)); char str[BADDR_MAX_PRINT_LEN]; BAddr_Print(&eaddr->addr, str); BLog(BLOG_INFO, "external address (%d,%d): server reported %s", i, j, str); } } } // give receive device the ID DPReceiveDevice_SetPeerID(&device_output_dprd, my_id); // init server queue if (!PacketPassFairQueue_Init(&server_queue, ServerConnection_GetSendInterface(&server), BReactor_PendingGroup(&ss), 0, 1)) { BLog(BLOG_ERROR, "PacketPassFairQueue_Init failed"); terminate(); return; } // set server ready server_ready = 1; BLog(BLOG_INFO, "server: ready, my ID is %d", (int)my_id); } void server_handler_newclient (void *user, peerid_t peer_id, int flags, const uint8_t *cert, int cert_len) { ASSERT(server_ready) ASSERT(cert_len >= 0) ASSERT(cert_len <= SCID_NEWCLIENT_MAX_CERT_LEN) // check if the peer already exists if (find_peer_by_id(peer_id)) { BLog(BLOG_WARNING, "server: newclient: peer already known"); return; } // make sure it's not the same ID as us if (peer_id == my_id) { BLog(BLOG_WARNING, "server: newclient: peer has our ID"); return; } // check if there is spece for the peer if (num_peers >= options.max_peers) { BLog(BLOG_WARNING, "server: newclient: no space for new peer (maximum number reached)"); return; } if (!options.ssl && cert_len > 0) { BLog(BLOG_WARNING, "server: newclient: certificate supplied, but not using TLS"); return; } peer_add(peer_id, flags, cert, cert_len); } void server_handler_endclient (void *user, peerid_t peer_id) { ASSERT(server_ready) // find peer struct peer_data *peer = find_peer_by_id(peer_id); if (!peer) { BLog(BLOG_WARNING, "server: endclient: peer %d not known", (int)peer_id); return; } // remove peer peer_remove(peer, 0); } void server_handler_message (void *user, peerid_t peer_id, uint8_t *data, int data_len) { ASSERT(server_ready) ASSERT(data_len >= 0) ASSERT(data_len <= SC_MAX_MSGLEN) // find peer struct peer_data *peer = find_peer_by_id(peer_id); if (!peer) { BLog(BLOG_WARNING, "server: message: peer not known"); return; } // make sure we have chat if (!peer->have_chat) { peer_log(peer, BLOG_ERROR, "cannot process message, chat is down"); return; } // pass message to chat PeerChat_InputReceived(&peer->chat, data, data_len); } void peer_job_send_seed (struct peer_data *peer) { ASSERT(options.transport_mode == TRANSPORT_MODE_UDP) ASSERT(SPPROTO_HAVE_OTP(sp_params)) ASSERT(peer->have_link) ASSERT(!peer->pio.udp.sendseed_sent) peer_log(peer, BLOG_DEBUG, "sending OTP send seed"); int key_len = BEncryption_cipher_key_size(sp_params.otp_mode); int iv_len = BEncryption_cipher_block_size(sp_params.otp_mode); // generate seed peer->pio.udp.sendseed_sent_id = peer->pio.udp.sendseed_nextid; BRandom_randomize(peer->pio.udp.sendseed_sent_key, key_len); BRandom_randomize(peer->pio.udp.sendseed_sent_iv, iv_len); // set as sent, increment next seed ID peer->pio.udp.sendseed_sent = 1; peer->pio.udp.sendseed_nextid++; // send seed to the peer int msg_len = msg_seed_SIZEseed_id + msg_seed_SIZEkey(key_len) + msg_seed_SIZEiv(iv_len); if (msg_len > MSG_MAX_PAYLOAD) { peer_log(peer, BLOG_ERROR, "OTP send seed message too big"); return; } uint8_t *msg; if (!peer_start_msg(peer, (void **)&msg, MSGID_SEED, msg_len)) { return; } msg_seedWriter writer; msg_seedWriter_Init(&writer, msg); msg_seedWriter_Addseed_id(&writer, peer->pio.udp.sendseed_sent_id); uint8_t *key_dst = msg_seedWriter_Addkey(&writer, key_len); memcpy(key_dst, peer->pio.udp.sendseed_sent_key, key_len); uint8_t *iv_dst = msg_seedWriter_Addiv(&writer, iv_len); memcpy(iv_dst, peer->pio.udp.sendseed_sent_iv, iv_len); msg_seedWriter_Finish(&writer); peer_end_msg(peer); } void peer_job_init (struct peer_data *peer) { // start setup process if (peer_am_master(peer)) { peer_start_binding(peer); } } struct server_flow * server_flow_init (void) { ASSERT(server_ready) // allocate structure struct server_flow *flow = (struct server_flow *)malloc(sizeof(*flow)); if (!flow) { BLog(BLOG_ERROR, "malloc failed"); goto fail0; } // init queue flow PacketPassFairQueueFlow_Init(&flow->qflow, &server_queue); // init connector PacketRecvConnector_Init(&flow->connector, sizeof(struct packetproto_header) + SC_MAX_ENC, BReactor_PendingGroup(&ss)); // init encoder buffer if (!SinglePacketBuffer_Init(&flow->encoder_buffer, PacketRecvConnector_GetOutput(&flow->connector), PacketPassFairQueueFlow_GetInput(&flow->qflow), BReactor_PendingGroup(&ss))) { BLog(BLOG_ERROR, "SinglePacketBuffer_Init failed"); goto fail1; } // set not connected flow->connected = 0; return flow; fail1: PacketRecvConnector_Free(&flow->connector); PacketPassFairQueueFlow_Free(&flow->qflow); free(flow); fail0: return NULL; } void server_flow_free (struct server_flow *flow) { PacketPassFairQueueFlow_AssertFree(&flow->qflow); ASSERT(!flow->connected) // remove dying flow reference if (flow == dying_server_flow) { dying_server_flow = NULL; } // free encoder buffer SinglePacketBuffer_Free(&flow->encoder_buffer); // free connector PacketRecvConnector_Free(&flow->connector); // free queue flow PacketPassFairQueueFlow_Free(&flow->qflow); // free structure free(flow); } void server_flow_die (struct server_flow *flow) { ASSERT(PacketPassFairQueueFlow_IsBusy(&flow->qflow)) ASSERT(!flow->connected) ASSERT(!dying_server_flow) // request notification when flow is done PacketPassFairQueueFlow_SetBusyHandler(&flow->qflow, (PacketPassFairQueue_handler_busy)server_flow_qflow_handler_busy, flow); // set dying flow dying_server_flow = flow; } void server_flow_qflow_handler_busy (struct server_flow *flow) { ASSERT(flow == dying_server_flow) ASSERT(!flow->connected) PacketPassFairQueueFlow_AssertFree(&flow->qflow); // finally free flow server_flow_free(flow); } void server_flow_connect (struct server_flow *flow, PacketRecvInterface *input) { ASSERT(!flow->connected) ASSERT(flow != dying_server_flow) // connect input PacketRecvConnector_ConnectInput(&flow->connector, input); // set connected flow->connected = 1; } void server_flow_disconnect (struct server_flow *flow) { ASSERT(flow->connected) ASSERT(flow != dying_server_flow) // disconnect input PacketRecvConnector_DisconnectInput(&flow->connector); // set not connected flow->connected = 0; }
gpl-3.0
pihao/shadowsocks-android
src/main/jni/badvpn/tests/bproto_test.c
368
2003
#include <string.h> #include <stdint.h> #include <stdio.h> #include <misc/debug.h> #include <misc/balloc.h> #include <generated/bproto_bproto_test.h> int main () { uint16_t a = 17501; uint64_t c = 82688926; uint16_t d1 = 1517; uint16_t d2 = 1518; uint8_t e = 72; const char *f = "hello world"; const char *g = "helo"; // encode message int len = msg1_SIZEa + msg1_SIZEc + msg1_SIZEd + msg1_SIZEd + msg1_SIZEe + msg1_SIZEf(strlen(f)) + msg1_SIZEg; uint8_t *msg = (uint8_t *)BAlloc(len); ASSERT_FORCE(msg) msg1Writer writer; msg1Writer_Init(&writer, msg); msg1Writer_Adda(&writer, a); msg1Writer_Addc(&writer, c); msg1Writer_Addd(&writer, d1); msg1Writer_Addd(&writer, d2); msg1Writer_Adde(&writer, e); uint8_t *f_dst = msg1Writer_Addf(&writer, strlen(f)); memcpy(f_dst, f, strlen(f)); uint8_t *g_dst = msg1Writer_Addg(&writer); memcpy(g_dst, g, strlen(g)); int len2 = msg1Writer_Finish(&writer); ASSERT_EXECUTE(len2 == len) // parse message msg1Parser parser; ASSERT_EXECUTE(msg1Parser_Init(&parser, msg, len)) // check parse results uint16_t p_a; uint64_t p_c; uint16_t p_d1; uint16_t p_d2; uint8_t p_e; uint8_t *p_f; int p_f_len; uint8_t *p_g; ASSERT_EXECUTE(msg1Parser_Geta(&parser, &p_a)) ASSERT_EXECUTE(msg1Parser_Getc(&parser, &p_c)) ASSERT_EXECUTE(msg1Parser_Getd(&parser, &p_d1)) ASSERT_EXECUTE(msg1Parser_Getd(&parser, &p_d2)) ASSERT_EXECUTE(msg1Parser_Gete(&parser, &p_e)) ASSERT_EXECUTE(msg1Parser_Getf(&parser, &p_f, &p_f_len)) ASSERT_EXECUTE(msg1Parser_Getg(&parser, &p_g)) ASSERT(p_a == a) ASSERT(p_c == c) ASSERT(p_d1 == d1) ASSERT(p_d2 == d2) ASSERT(p_e == e) ASSERT(p_f_len == strlen(f) && !memcmp(p_f, f, p_f_len)) ASSERT(!memcmp(p_g, g, strlen(g))) ASSERT(msg1Parser_GotEverything(&parser)) BFree(msg); return 0; }
gpl-3.0
Matt07211/android_kernel_samsung_xcover3lte
drivers/net/ethernet/chelsio/cxgb3/sge.c
391
93615
/* * Copyright (c) 2005-2008 Chelsio, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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 <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/if_vlan.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/dma-mapping.h> #include <linux/slab.h> #include <linux/prefetch.h> #include <net/arp.h> #include "common.h" #include "regs.h" #include "sge_defs.h" #include "t3_cpl.h" #include "firmware_exports.h" #include "cxgb3_offload.h" #define USE_GTS 0 #define SGE_RX_SM_BUF_SIZE 1536 #define SGE_RX_COPY_THRES 256 #define SGE_RX_PULL_LEN 128 #define SGE_PG_RSVD SMP_CACHE_BYTES /* * Page chunk size for FL0 buffers if FL0 is to be populated with page chunks. * It must be a divisor of PAGE_SIZE. If set to 0 FL0 will use sk_buffs * directly. */ #define FL0_PG_CHUNK_SIZE 2048 #define FL0_PG_ORDER 0 #define FL0_PG_ALLOC_SIZE (PAGE_SIZE << FL0_PG_ORDER) #define FL1_PG_CHUNK_SIZE (PAGE_SIZE > 8192 ? 16384 : 8192) #define FL1_PG_ORDER (PAGE_SIZE > 8192 ? 0 : 1) #define FL1_PG_ALLOC_SIZE (PAGE_SIZE << FL1_PG_ORDER) #define SGE_RX_DROP_THRES 16 #define RX_RECLAIM_PERIOD (HZ/4) /* * Max number of Rx buffers we replenish at a time. */ #define MAX_RX_REFILL 16U /* * Period of the Tx buffer reclaim timer. This timer does not need to run * frequently as Tx buffers are usually reclaimed by new Tx packets. */ #define TX_RECLAIM_PERIOD (HZ / 4) #define TX_RECLAIM_TIMER_CHUNK 64U #define TX_RECLAIM_CHUNK 16U /* WR size in bytes */ #define WR_LEN (WR_FLITS * 8) /* * Types of Tx queues in each queue set. Order here matters, do not change. */ enum { TXQ_ETH, TXQ_OFLD, TXQ_CTRL }; /* Values for sge_txq.flags */ enum { TXQ_RUNNING = 1 << 0, /* fetch engine is running */ TXQ_LAST_PKT_DB = 1 << 1, /* last packet rang the doorbell */ }; struct tx_desc { __be64 flit[TX_DESC_FLITS]; }; struct rx_desc { __be32 addr_lo; __be32 len_gen; __be32 gen2; __be32 addr_hi; }; struct tx_sw_desc { /* SW state per Tx descriptor */ struct sk_buff *skb; u8 eop; /* set if last descriptor for packet */ u8 addr_idx; /* buffer index of first SGL entry in descriptor */ u8 fragidx; /* first page fragment associated with descriptor */ s8 sflit; /* start flit of first SGL entry in descriptor */ }; struct rx_sw_desc { /* SW state per Rx descriptor */ union { struct sk_buff *skb; struct fl_pg_chunk pg_chunk; }; DEFINE_DMA_UNMAP_ADDR(dma_addr); }; struct rsp_desc { /* response queue descriptor */ struct rss_header rss_hdr; __be32 flags; __be32 len_cq; u8 imm_data[47]; u8 intr_gen; }; /* * Holds unmapping information for Tx packets that need deferred unmapping. * This structure lives at skb->head and must be allocated by callers. */ struct deferred_unmap_info { struct pci_dev *pdev; dma_addr_t addr[MAX_SKB_FRAGS + 1]; }; /* * Maps a number of flits to the number of Tx descriptors that can hold them. * The formula is * * desc = 1 + (flits - 2) / (WR_FLITS - 1). * * HW allows up to 4 descriptors to be combined into a WR. */ static u8 flit_desc_map[] = { 0, #if SGE_NUM_GENBITS == 1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 #elif SGE_NUM_GENBITS == 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, #else # error "SGE_NUM_GENBITS must be 1 or 2" #endif }; static inline struct sge_qset *fl_to_qset(const struct sge_fl *q, int qidx) { return container_of(q, struct sge_qset, fl[qidx]); } static inline struct sge_qset *rspq_to_qset(const struct sge_rspq *q) { return container_of(q, struct sge_qset, rspq); } static inline struct sge_qset *txq_to_qset(const struct sge_txq *q, int qidx) { return container_of(q, struct sge_qset, txq[qidx]); } /** * refill_rspq - replenish an SGE response queue * @adapter: the adapter * @q: the response queue to replenish * @credits: how many new responses to make available * * Replenishes a response queue by making the supplied number of responses * available to HW. */ static inline void refill_rspq(struct adapter *adapter, const struct sge_rspq *q, unsigned int credits) { rmb(); t3_write_reg(adapter, A_SG_RSPQ_CREDIT_RETURN, V_RSPQ(q->cntxt_id) | V_CREDITS(credits)); } /** * need_skb_unmap - does the platform need unmapping of sk_buffs? * * Returns true if the platform needs sk_buff unmapping. The compiler * optimizes away unnecessary code if this returns true. */ static inline int need_skb_unmap(void) { #ifdef CONFIG_NEED_DMA_MAP_STATE return 1; #else return 0; #endif } /** * unmap_skb - unmap a packet main body and its page fragments * @skb: the packet * @q: the Tx queue containing Tx descriptors for the packet * @cidx: index of Tx descriptor * @pdev: the PCI device * * Unmap the main body of an sk_buff and its page fragments, if any. * Because of the fairly complicated structure of our SGLs and the desire * to conserve space for metadata, the information necessary to unmap an * sk_buff is spread across the sk_buff itself (buffer lengths), the HW Tx * descriptors (the physical addresses of the various data buffers), and * the SW descriptor state (assorted indices). The send functions * initialize the indices for the first packet descriptor so we can unmap * the buffers held in the first Tx descriptor here, and we have enough * information at this point to set the state for the next Tx descriptor. * * Note that it is possible to clean up the first descriptor of a packet * before the send routines have written the next descriptors, but this * race does not cause any problem. We just end up writing the unmapping * info for the descriptor first. */ static inline void unmap_skb(struct sk_buff *skb, struct sge_txq *q, unsigned int cidx, struct pci_dev *pdev) { const struct sg_ent *sgp; struct tx_sw_desc *d = &q->sdesc[cidx]; int nfrags, frag_idx, curflit, j = d->addr_idx; sgp = (struct sg_ent *)&q->desc[cidx].flit[d->sflit]; frag_idx = d->fragidx; if (frag_idx == 0 && skb_headlen(skb)) { pci_unmap_single(pdev, be64_to_cpu(sgp->addr[0]), skb_headlen(skb), PCI_DMA_TODEVICE); j = 1; } curflit = d->sflit + 1 + j; nfrags = skb_shinfo(skb)->nr_frags; while (frag_idx < nfrags && curflit < WR_FLITS) { pci_unmap_page(pdev, be64_to_cpu(sgp->addr[j]), skb_frag_size(&skb_shinfo(skb)->frags[frag_idx]), PCI_DMA_TODEVICE); j ^= 1; if (j == 0) { sgp++; curflit++; } curflit++; frag_idx++; } if (frag_idx < nfrags) { /* SGL continues into next Tx descriptor */ d = cidx + 1 == q->size ? q->sdesc : d + 1; d->fragidx = frag_idx; d->addr_idx = j; d->sflit = curflit - WR_FLITS - j; /* sflit can be -1 */ } } /** * free_tx_desc - reclaims Tx descriptors and their buffers * @adapter: the adapter * @q: the Tx queue to reclaim descriptors from * @n: the number of descriptors to reclaim * * Reclaims Tx descriptors from an SGE Tx queue and frees the associated * Tx buffers. Called with the Tx queue lock held. */ static void free_tx_desc(struct adapter *adapter, struct sge_txq *q, unsigned int n) { struct tx_sw_desc *d; struct pci_dev *pdev = adapter->pdev; unsigned int cidx = q->cidx; const int need_unmap = need_skb_unmap() && q->cntxt_id >= FW_TUNNEL_SGEEC_START; d = &q->sdesc[cidx]; while (n--) { if (d->skb) { /* an SGL is present */ if (need_unmap) unmap_skb(d->skb, q, cidx, pdev); if (d->eop) { kfree_skb(d->skb); d->skb = NULL; } } ++d; if (++cidx == q->size) { cidx = 0; d = q->sdesc; } } q->cidx = cidx; } /** * reclaim_completed_tx - reclaims completed Tx descriptors * @adapter: the adapter * @q: the Tx queue to reclaim completed descriptors from * @chunk: maximum number of descriptors to reclaim * * Reclaims Tx descriptors that the SGE has indicated it has processed, * and frees the associated buffers if possible. Called with the Tx * queue's lock held. */ static inline unsigned int reclaim_completed_tx(struct adapter *adapter, struct sge_txq *q, unsigned int chunk) { unsigned int reclaim = q->processed - q->cleaned; reclaim = min(chunk, reclaim); if (reclaim) { free_tx_desc(adapter, q, reclaim); q->cleaned += reclaim; q->in_use -= reclaim; } return q->processed - q->cleaned; } /** * should_restart_tx - are there enough resources to restart a Tx queue? * @q: the Tx queue * * Checks if there are enough descriptors to restart a suspended Tx queue. */ static inline int should_restart_tx(const struct sge_txq *q) { unsigned int r = q->processed - q->cleaned; return q->in_use - r < (q->size >> 1); } static void clear_rx_desc(struct pci_dev *pdev, const struct sge_fl *q, struct rx_sw_desc *d) { if (q->use_pages && d->pg_chunk.page) { (*d->pg_chunk.p_cnt)--; if (!*d->pg_chunk.p_cnt) pci_unmap_page(pdev, d->pg_chunk.mapping, q->alloc_size, PCI_DMA_FROMDEVICE); put_page(d->pg_chunk.page); d->pg_chunk.page = NULL; } else { pci_unmap_single(pdev, dma_unmap_addr(d, dma_addr), q->buf_size, PCI_DMA_FROMDEVICE); kfree_skb(d->skb); d->skb = NULL; } } /** * free_rx_bufs - free the Rx buffers on an SGE free list * @pdev: the PCI device associated with the adapter * @rxq: the SGE free list to clean up * * Release the buffers on an SGE free-buffer Rx queue. HW fetching from * this queue should be stopped before calling this function. */ static void free_rx_bufs(struct pci_dev *pdev, struct sge_fl *q) { unsigned int cidx = q->cidx; while (q->credits--) { struct rx_sw_desc *d = &q->sdesc[cidx]; clear_rx_desc(pdev, q, d); if (++cidx == q->size) cidx = 0; } if (q->pg_chunk.page) { __free_pages(q->pg_chunk.page, q->order); q->pg_chunk.page = NULL; } } /** * add_one_rx_buf - add a packet buffer to a free-buffer list * @va: buffer start VA * @len: the buffer length * @d: the HW Rx descriptor to write * @sd: the SW Rx descriptor to write * @gen: the generation bit value * @pdev: the PCI device associated with the adapter * * Add a buffer of the given length to the supplied HW and SW Rx * descriptors. */ static inline int add_one_rx_buf(void *va, unsigned int len, struct rx_desc *d, struct rx_sw_desc *sd, unsigned int gen, struct pci_dev *pdev) { dma_addr_t mapping; mapping = pci_map_single(pdev, va, len, PCI_DMA_FROMDEVICE); if (unlikely(pci_dma_mapping_error(pdev, mapping))) return -ENOMEM; dma_unmap_addr_set(sd, dma_addr, mapping); d->addr_lo = cpu_to_be32(mapping); d->addr_hi = cpu_to_be32((u64) mapping >> 32); wmb(); d->len_gen = cpu_to_be32(V_FLD_GEN1(gen)); d->gen2 = cpu_to_be32(V_FLD_GEN2(gen)); return 0; } static inline int add_one_rx_chunk(dma_addr_t mapping, struct rx_desc *d, unsigned int gen) { d->addr_lo = cpu_to_be32(mapping); d->addr_hi = cpu_to_be32((u64) mapping >> 32); wmb(); d->len_gen = cpu_to_be32(V_FLD_GEN1(gen)); d->gen2 = cpu_to_be32(V_FLD_GEN2(gen)); return 0; } static int alloc_pg_chunk(struct adapter *adapter, struct sge_fl *q, struct rx_sw_desc *sd, gfp_t gfp, unsigned int order) { if (!q->pg_chunk.page) { dma_addr_t mapping; q->pg_chunk.page = alloc_pages(gfp, order); if (unlikely(!q->pg_chunk.page)) return -ENOMEM; q->pg_chunk.va = page_address(q->pg_chunk.page); q->pg_chunk.p_cnt = q->pg_chunk.va + (PAGE_SIZE << order) - SGE_PG_RSVD; q->pg_chunk.offset = 0; mapping = pci_map_page(adapter->pdev, q->pg_chunk.page, 0, q->alloc_size, PCI_DMA_FROMDEVICE); q->pg_chunk.mapping = mapping; } sd->pg_chunk = q->pg_chunk; prefetch(sd->pg_chunk.p_cnt); q->pg_chunk.offset += q->buf_size; if (q->pg_chunk.offset == (PAGE_SIZE << order)) q->pg_chunk.page = NULL; else { q->pg_chunk.va += q->buf_size; get_page(q->pg_chunk.page); } if (sd->pg_chunk.offset == 0) *sd->pg_chunk.p_cnt = 1; else *sd->pg_chunk.p_cnt += 1; return 0; } static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q) { if (q->pend_cred >= q->credits / 4) { q->pend_cred = 0; wmb(); t3_write_reg(adap, A_SG_KDOORBELL, V_EGRCNTX(q->cntxt_id)); } } /** * refill_fl - refill an SGE free-buffer list * @adapter: the adapter * @q: the free-list to refill * @n: the number of new buffers to allocate * @gfp: the gfp flags for allocating new buffers * * (Re)populate an SGE free-buffer list with up to @n new packet buffers, * allocated with the supplied gfp flags. The caller must assure that * @n does not exceed the queue's capacity. */ static int refill_fl(struct adapter *adap, struct sge_fl *q, int n, gfp_t gfp) { struct rx_sw_desc *sd = &q->sdesc[q->pidx]; struct rx_desc *d = &q->desc[q->pidx]; unsigned int count = 0; while (n--) { dma_addr_t mapping; int err; if (q->use_pages) { if (unlikely(alloc_pg_chunk(adap, q, sd, gfp, q->order))) { nomem: q->alloc_failed++; break; } mapping = sd->pg_chunk.mapping + sd->pg_chunk.offset; dma_unmap_addr_set(sd, dma_addr, mapping); add_one_rx_chunk(mapping, d, q->gen); pci_dma_sync_single_for_device(adap->pdev, mapping, q->buf_size - SGE_PG_RSVD, PCI_DMA_FROMDEVICE); } else { void *buf_start; struct sk_buff *skb = alloc_skb(q->buf_size, gfp); if (!skb) goto nomem; sd->skb = skb; buf_start = skb->data; err = add_one_rx_buf(buf_start, q->buf_size, d, sd, q->gen, adap->pdev); if (unlikely(err)) { clear_rx_desc(adap->pdev, q, sd); break; } } d++; sd++; if (++q->pidx == q->size) { q->pidx = 0; q->gen ^= 1; sd = q->sdesc; d = q->desc; } count++; } q->credits += count; q->pend_cred += count; ring_fl_db(adap, q); return count; } static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl) { refill_fl(adap, fl, min(MAX_RX_REFILL, fl->size - fl->credits), GFP_ATOMIC | __GFP_COMP); } /** * recycle_rx_buf - recycle a receive buffer * @adapter: the adapter * @q: the SGE free list * @idx: index of buffer to recycle * * Recycles the specified buffer on the given free list by adding it at * the next available slot on the list. */ static void recycle_rx_buf(struct adapter *adap, struct sge_fl *q, unsigned int idx) { struct rx_desc *from = &q->desc[idx]; struct rx_desc *to = &q->desc[q->pidx]; q->sdesc[q->pidx] = q->sdesc[idx]; to->addr_lo = from->addr_lo; /* already big endian */ to->addr_hi = from->addr_hi; /* likewise */ wmb(); to->len_gen = cpu_to_be32(V_FLD_GEN1(q->gen)); to->gen2 = cpu_to_be32(V_FLD_GEN2(q->gen)); if (++q->pidx == q->size) { q->pidx = 0; q->gen ^= 1; } q->credits++; q->pend_cred++; ring_fl_db(adap, q); } /** * alloc_ring - allocate resources for an SGE descriptor ring * @pdev: the PCI device * @nelem: the number of descriptors * @elem_size: the size of each descriptor * @sw_size: the size of the SW state associated with each ring element * @phys: the physical address of the allocated ring * @metadata: address of the array holding the SW state for the ring * * Allocates resources for an SGE descriptor ring, such as Tx queues, * free buffer lists, or response queues. Each SGE ring requires * space for its HW descriptors plus, optionally, space for the SW state * associated with each HW entry (the metadata). The function returns * three values: the virtual address for the HW ring (the return value * of the function), the physical address of the HW ring, and the address * of the SW ring. */ static void *alloc_ring(struct pci_dev *pdev, size_t nelem, size_t elem_size, size_t sw_size, dma_addr_t * phys, void *metadata) { size_t len = nelem * elem_size; void *s = NULL; void *p = dma_alloc_coherent(&pdev->dev, len, phys, GFP_KERNEL); if (!p) return NULL; if (sw_size && metadata) { s = kcalloc(nelem, sw_size, GFP_KERNEL); if (!s) { dma_free_coherent(&pdev->dev, len, p, *phys); return NULL; } *(void **)metadata = s; } memset(p, 0, len); return p; } /** * t3_reset_qset - reset a sge qset * @q: the queue set * * Reset the qset structure. * the NAPI structure is preserved in the event of * the qset's reincarnation, for example during EEH recovery. */ static void t3_reset_qset(struct sge_qset *q) { if (q->adap && !(q->adap->flags & NAPI_INIT)) { memset(q, 0, sizeof(*q)); return; } q->adap = NULL; memset(&q->rspq, 0, sizeof(q->rspq)); memset(q->fl, 0, sizeof(struct sge_fl) * SGE_RXQ_PER_SET); memset(q->txq, 0, sizeof(struct sge_txq) * SGE_TXQ_PER_SET); q->txq_stopped = 0; q->tx_reclaim_timer.function = NULL; /* for t3_stop_sge_timers() */ q->rx_reclaim_timer.function = NULL; q->nomem = 0; napi_free_frags(&q->napi); } /** * free_qset - free the resources of an SGE queue set * @adapter: the adapter owning the queue set * @q: the queue set * * Release the HW and SW resources associated with an SGE queue set, such * as HW contexts, packet buffers, and descriptor rings. Traffic to the * queue set must be quiesced prior to calling this. */ static void t3_free_qset(struct adapter *adapter, struct sge_qset *q) { int i; struct pci_dev *pdev = adapter->pdev; for (i = 0; i < SGE_RXQ_PER_SET; ++i) if (q->fl[i].desc) { spin_lock_irq(&adapter->sge.reg_lock); t3_sge_disable_fl(adapter, q->fl[i].cntxt_id); spin_unlock_irq(&adapter->sge.reg_lock); free_rx_bufs(pdev, &q->fl[i]); kfree(q->fl[i].sdesc); dma_free_coherent(&pdev->dev, q->fl[i].size * sizeof(struct rx_desc), q->fl[i].desc, q->fl[i].phys_addr); } for (i = 0; i < SGE_TXQ_PER_SET; ++i) if (q->txq[i].desc) { spin_lock_irq(&adapter->sge.reg_lock); t3_sge_enable_ecntxt(adapter, q->txq[i].cntxt_id, 0); spin_unlock_irq(&adapter->sge.reg_lock); if (q->txq[i].sdesc) { free_tx_desc(adapter, &q->txq[i], q->txq[i].in_use); kfree(q->txq[i].sdesc); } dma_free_coherent(&pdev->dev, q->txq[i].size * sizeof(struct tx_desc), q->txq[i].desc, q->txq[i].phys_addr); __skb_queue_purge(&q->txq[i].sendq); } if (q->rspq.desc) { spin_lock_irq(&adapter->sge.reg_lock); t3_sge_disable_rspcntxt(adapter, q->rspq.cntxt_id); spin_unlock_irq(&adapter->sge.reg_lock); dma_free_coherent(&pdev->dev, q->rspq.size * sizeof(struct rsp_desc), q->rspq.desc, q->rspq.phys_addr); } t3_reset_qset(q); } /** * init_qset_cntxt - initialize an SGE queue set context info * @qs: the queue set * @id: the queue set id * * Initializes the TIDs and context ids for the queues of a queue set. */ static void init_qset_cntxt(struct sge_qset *qs, unsigned int id) { qs->rspq.cntxt_id = id; qs->fl[0].cntxt_id = 2 * id; qs->fl[1].cntxt_id = 2 * id + 1; qs->txq[TXQ_ETH].cntxt_id = FW_TUNNEL_SGEEC_START + id; qs->txq[TXQ_ETH].token = FW_TUNNEL_TID_START + id; qs->txq[TXQ_OFLD].cntxt_id = FW_OFLD_SGEEC_START + id; qs->txq[TXQ_CTRL].cntxt_id = FW_CTRL_SGEEC_START + id; qs->txq[TXQ_CTRL].token = FW_CTRL_TID_START + id; } /** * sgl_len - calculates the size of an SGL of the given capacity * @n: the number of SGL entries * * Calculates the number of flits needed for a scatter/gather list that * can hold the given number of entries. */ static inline unsigned int sgl_len(unsigned int n) { /* alternatively: 3 * (n / 2) + 2 * (n & 1) */ return (3 * n) / 2 + (n & 1); } /** * flits_to_desc - returns the num of Tx descriptors for the given flits * @n: the number of flits * * Calculates the number of Tx descriptors needed for the supplied number * of flits. */ static inline unsigned int flits_to_desc(unsigned int n) { BUG_ON(n >= ARRAY_SIZE(flit_desc_map)); return flit_desc_map[n]; } /** * get_packet - return the next ingress packet buffer from a free list * @adap: the adapter that received the packet * @fl: the SGE free list holding the packet * @len: the packet length including any SGE padding * @drop_thres: # of remaining buffers before we start dropping packets * * Get the next packet from a free list and complete setup of the * sk_buff. If the packet is small we make a copy and recycle the * original buffer, otherwise we use the original buffer itself. If a * positive drop threshold is supplied packets are dropped and their * buffers recycled if (a) the number of remaining buffers is under the * threshold and the packet is too big to copy, or (b) the packet should * be copied but there is no memory for the copy. */ static struct sk_buff *get_packet(struct adapter *adap, struct sge_fl *fl, unsigned int len, unsigned int drop_thres) { struct sk_buff *skb = NULL; struct rx_sw_desc *sd = &fl->sdesc[fl->cidx]; prefetch(sd->skb->data); fl->credits--; if (len <= SGE_RX_COPY_THRES) { skb = alloc_skb(len, GFP_ATOMIC); if (likely(skb != NULL)) { __skb_put(skb, len); pci_dma_sync_single_for_cpu(adap->pdev, dma_unmap_addr(sd, dma_addr), len, PCI_DMA_FROMDEVICE); memcpy(skb->data, sd->skb->data, len); pci_dma_sync_single_for_device(adap->pdev, dma_unmap_addr(sd, dma_addr), len, PCI_DMA_FROMDEVICE); } else if (!drop_thres) goto use_orig_buf; recycle: recycle_rx_buf(adap, fl, fl->cidx); return skb; } if (unlikely(fl->credits < drop_thres) && refill_fl(adap, fl, min(MAX_RX_REFILL, fl->size - fl->credits - 1), GFP_ATOMIC | __GFP_COMP) == 0) goto recycle; use_orig_buf: pci_unmap_single(adap->pdev, dma_unmap_addr(sd, dma_addr), fl->buf_size, PCI_DMA_FROMDEVICE); skb = sd->skb; skb_put(skb, len); __refill_fl(adap, fl); return skb; } /** * get_packet_pg - return the next ingress packet buffer from a free list * @adap: the adapter that received the packet * @fl: the SGE free list holding the packet * @len: the packet length including any SGE padding * @drop_thres: # of remaining buffers before we start dropping packets * * Get the next packet from a free list populated with page chunks. * If the packet is small we make a copy and recycle the original buffer, * otherwise we attach the original buffer as a page fragment to a fresh * sk_buff. If a positive drop threshold is supplied packets are dropped * and their buffers recycled if (a) the number of remaining buffers is * under the threshold and the packet is too big to copy, or (b) there's * no system memory. * * Note: this function is similar to @get_packet but deals with Rx buffers * that are page chunks rather than sk_buffs. */ static struct sk_buff *get_packet_pg(struct adapter *adap, struct sge_fl *fl, struct sge_rspq *q, unsigned int len, unsigned int drop_thres) { struct sk_buff *newskb, *skb; struct rx_sw_desc *sd = &fl->sdesc[fl->cidx]; dma_addr_t dma_addr = dma_unmap_addr(sd, dma_addr); newskb = skb = q->pg_skb; if (!skb && (len <= SGE_RX_COPY_THRES)) { newskb = alloc_skb(len, GFP_ATOMIC); if (likely(newskb != NULL)) { __skb_put(newskb, len); pci_dma_sync_single_for_cpu(adap->pdev, dma_addr, len, PCI_DMA_FROMDEVICE); memcpy(newskb->data, sd->pg_chunk.va, len); pci_dma_sync_single_for_device(adap->pdev, dma_addr, len, PCI_DMA_FROMDEVICE); } else if (!drop_thres) return NULL; recycle: fl->credits--; recycle_rx_buf(adap, fl, fl->cidx); q->rx_recycle_buf++; return newskb; } if (unlikely(q->rx_recycle_buf || (!skb && fl->credits <= drop_thres))) goto recycle; prefetch(sd->pg_chunk.p_cnt); if (!skb) newskb = alloc_skb(SGE_RX_PULL_LEN, GFP_ATOMIC); if (unlikely(!newskb)) { if (!drop_thres) return NULL; goto recycle; } pci_dma_sync_single_for_cpu(adap->pdev, dma_addr, len, PCI_DMA_FROMDEVICE); (*sd->pg_chunk.p_cnt)--; if (!*sd->pg_chunk.p_cnt && sd->pg_chunk.page != fl->pg_chunk.page) pci_unmap_page(adap->pdev, sd->pg_chunk.mapping, fl->alloc_size, PCI_DMA_FROMDEVICE); if (!skb) { __skb_put(newskb, SGE_RX_PULL_LEN); memcpy(newskb->data, sd->pg_chunk.va, SGE_RX_PULL_LEN); skb_fill_page_desc(newskb, 0, sd->pg_chunk.page, sd->pg_chunk.offset + SGE_RX_PULL_LEN, len - SGE_RX_PULL_LEN); newskb->len = len; newskb->data_len = len - SGE_RX_PULL_LEN; newskb->truesize += newskb->data_len; } else { skb_fill_page_desc(newskb, skb_shinfo(newskb)->nr_frags, sd->pg_chunk.page, sd->pg_chunk.offset, len); newskb->len += len; newskb->data_len += len; newskb->truesize += len; } fl->credits--; /* * We do not refill FLs here, we let the caller do it to overlap a * prefetch. */ return newskb; } /** * get_imm_packet - return the next ingress packet buffer from a response * @resp: the response descriptor containing the packet data * * Return a packet containing the immediate data of the given response. */ static inline struct sk_buff *get_imm_packet(const struct rsp_desc *resp) { struct sk_buff *skb = alloc_skb(IMMED_PKT_SIZE, GFP_ATOMIC); if (skb) { __skb_put(skb, IMMED_PKT_SIZE); skb_copy_to_linear_data(skb, resp->imm_data, IMMED_PKT_SIZE); } return skb; } /** * calc_tx_descs - calculate the number of Tx descriptors for a packet * @skb: the packet * * Returns the number of Tx descriptors needed for the given Ethernet * packet. Ethernet packets require addition of WR and CPL headers. */ static inline unsigned int calc_tx_descs(const struct sk_buff *skb) { unsigned int flits; if (skb->len <= WR_LEN - sizeof(struct cpl_tx_pkt)) return 1; flits = sgl_len(skb_shinfo(skb)->nr_frags + 1) + 2; if (skb_shinfo(skb)->gso_size) flits++; return flits_to_desc(flits); } /** * make_sgl - populate a scatter/gather list for a packet * @skb: the packet * @sgp: the SGL to populate * @start: start address of skb main body data to include in the SGL * @len: length of skb main body data to include in the SGL * @pdev: the PCI device * * Generates a scatter/gather list for the buffers that make up a packet * and returns the SGL size in 8-byte words. The caller must size the SGL * appropriately. */ static inline unsigned int make_sgl(const struct sk_buff *skb, struct sg_ent *sgp, unsigned char *start, unsigned int len, struct pci_dev *pdev) { dma_addr_t mapping; unsigned int i, j = 0, nfrags; if (len) { mapping = pci_map_single(pdev, start, len, PCI_DMA_TODEVICE); sgp->len[0] = cpu_to_be32(len); sgp->addr[0] = cpu_to_be64(mapping); j = 1; } nfrags = skb_shinfo(skb)->nr_frags; for (i = 0; i < nfrags; i++) { const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; mapping = skb_frag_dma_map(&pdev->dev, frag, 0, skb_frag_size(frag), DMA_TO_DEVICE); sgp->len[j] = cpu_to_be32(skb_frag_size(frag)); sgp->addr[j] = cpu_to_be64(mapping); j ^= 1; if (j == 0) ++sgp; } if (j) sgp->len[j] = 0; return ((nfrags + (len != 0)) * 3) / 2 + j; } /** * check_ring_tx_db - check and potentially ring a Tx queue's doorbell * @adap: the adapter * @q: the Tx queue * * Ring the doorbel if a Tx queue is asleep. There is a natural race, * where the HW is going to sleep just after we checked, however, * then the interrupt handler will detect the outstanding TX packet * and ring the doorbell for us. * * When GTS is disabled we unconditionally ring the doorbell. */ static inline void check_ring_tx_db(struct adapter *adap, struct sge_txq *q) { #if USE_GTS clear_bit(TXQ_LAST_PKT_DB, &q->flags); if (test_and_set_bit(TXQ_RUNNING, &q->flags) == 0) { set_bit(TXQ_LAST_PKT_DB, &q->flags); t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id)); } #else wmb(); /* write descriptors before telling HW */ t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id)); #endif } static inline void wr_gen2(struct tx_desc *d, unsigned int gen) { #if SGE_NUM_GENBITS == 2 d->flit[TX_DESC_FLITS - 1] = cpu_to_be64(gen); #endif } /** * write_wr_hdr_sgl - write a WR header and, optionally, SGL * @ndesc: number of Tx descriptors spanned by the SGL * @skb: the packet corresponding to the WR * @d: first Tx descriptor to be written * @pidx: index of above descriptors * @q: the SGE Tx queue * @sgl: the SGL * @flits: number of flits to the start of the SGL in the first descriptor * @sgl_flits: the SGL size in flits * @gen: the Tx descriptor generation * @wr_hi: top 32 bits of WR header based on WR type (big endian) * @wr_lo: low 32 bits of WR header based on WR type (big endian) * * Write a work request header and an associated SGL. If the SGL is * small enough to fit into one Tx descriptor it has already been written * and we just need to write the WR header. Otherwise we distribute the * SGL across the number of descriptors it spans. */ static void write_wr_hdr_sgl(unsigned int ndesc, struct sk_buff *skb, struct tx_desc *d, unsigned int pidx, const struct sge_txq *q, const struct sg_ent *sgl, unsigned int flits, unsigned int sgl_flits, unsigned int gen, __be32 wr_hi, __be32 wr_lo) { struct work_request_hdr *wrp = (struct work_request_hdr *)d; struct tx_sw_desc *sd = &q->sdesc[pidx]; sd->skb = skb; if (need_skb_unmap()) { sd->fragidx = 0; sd->addr_idx = 0; sd->sflit = flits; } if (likely(ndesc == 1)) { sd->eop = 1; wrp->wr_hi = htonl(F_WR_SOP | F_WR_EOP | V_WR_DATATYPE(1) | V_WR_SGLSFLT(flits)) | wr_hi; wmb(); wrp->wr_lo = htonl(V_WR_LEN(flits + sgl_flits) | V_WR_GEN(gen)) | wr_lo; wr_gen2(d, gen); } else { unsigned int ogen = gen; const u64 *fp = (const u64 *)sgl; struct work_request_hdr *wp = wrp; wrp->wr_hi = htonl(F_WR_SOP | V_WR_DATATYPE(1) | V_WR_SGLSFLT(flits)) | wr_hi; while (sgl_flits) { unsigned int avail = WR_FLITS - flits; if (avail > sgl_flits) avail = sgl_flits; memcpy(&d->flit[flits], fp, avail * sizeof(*fp)); sgl_flits -= avail; ndesc--; if (!sgl_flits) break; fp += avail; d++; sd->eop = 0; sd++; if (++pidx == q->size) { pidx = 0; gen ^= 1; d = q->desc; sd = q->sdesc; } sd->skb = skb; wrp = (struct work_request_hdr *)d; wrp->wr_hi = htonl(V_WR_DATATYPE(1) | V_WR_SGLSFLT(1)) | wr_hi; wrp->wr_lo = htonl(V_WR_LEN(min(WR_FLITS, sgl_flits + 1)) | V_WR_GEN(gen)) | wr_lo; wr_gen2(d, gen); flits = 1; } sd->eop = 1; wrp->wr_hi |= htonl(F_WR_EOP); wmb(); wp->wr_lo = htonl(V_WR_LEN(WR_FLITS) | V_WR_GEN(ogen)) | wr_lo; wr_gen2((struct tx_desc *)wp, ogen); WARN_ON(ndesc != 0); } } /** * write_tx_pkt_wr - write a TX_PKT work request * @adap: the adapter * @skb: the packet to send * @pi: the egress interface * @pidx: index of the first Tx descriptor to write * @gen: the generation value to use * @q: the Tx queue * @ndesc: number of descriptors the packet will occupy * @compl: the value of the COMPL bit to use * * Generate a TX_PKT work request to send the supplied packet. */ static void write_tx_pkt_wr(struct adapter *adap, struct sk_buff *skb, const struct port_info *pi, unsigned int pidx, unsigned int gen, struct sge_txq *q, unsigned int ndesc, unsigned int compl) { unsigned int flits, sgl_flits, cntrl, tso_info; struct sg_ent *sgp, sgl[MAX_SKB_FRAGS / 2 + 1]; struct tx_desc *d = &q->desc[pidx]; struct cpl_tx_pkt *cpl = (struct cpl_tx_pkt *)d; cpl->len = htonl(skb->len); cntrl = V_TXPKT_INTF(pi->port_id); if (vlan_tx_tag_present(skb)) cntrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(vlan_tx_tag_get(skb)); tso_info = V_LSO_MSS(skb_shinfo(skb)->gso_size); if (tso_info) { int eth_type; struct cpl_tx_pkt_lso *hdr = (struct cpl_tx_pkt_lso *)cpl; d->flit[2] = 0; cntrl |= V_TXPKT_OPCODE(CPL_TX_PKT_LSO); hdr->cntrl = htonl(cntrl); eth_type = skb_network_offset(skb) == ETH_HLEN ? CPL_ETH_II : CPL_ETH_II_VLAN; tso_info |= V_LSO_ETH_TYPE(eth_type) | V_LSO_IPHDR_WORDS(ip_hdr(skb)->ihl) | V_LSO_TCPHDR_WORDS(tcp_hdr(skb)->doff); hdr->lso_info = htonl(tso_info); flits = 3; } else { cntrl |= V_TXPKT_OPCODE(CPL_TX_PKT); cntrl |= F_TXPKT_IPCSUM_DIS; /* SW calculates IP csum */ cntrl |= V_TXPKT_L4CSUM_DIS(skb->ip_summed != CHECKSUM_PARTIAL); cpl->cntrl = htonl(cntrl); if (skb->len <= WR_LEN - sizeof(*cpl)) { q->sdesc[pidx].skb = NULL; if (!skb->data_len) skb_copy_from_linear_data(skb, &d->flit[2], skb->len); else skb_copy_bits(skb, 0, &d->flit[2], skb->len); flits = (skb->len + 7) / 8 + 2; cpl->wr.wr_hi = htonl(V_WR_BCNTLFLT(skb->len & 7) | V_WR_OP(FW_WROPCODE_TUNNEL_TX_PKT) | F_WR_SOP | F_WR_EOP | compl); wmb(); cpl->wr.wr_lo = htonl(V_WR_LEN(flits) | V_WR_GEN(gen) | V_WR_TID(q->token)); wr_gen2(d, gen); kfree_skb(skb); return; } flits = 2; } sgp = ndesc == 1 ? (struct sg_ent *)&d->flit[flits] : sgl; sgl_flits = make_sgl(skb, sgp, skb->data, skb_headlen(skb), adap->pdev); write_wr_hdr_sgl(ndesc, skb, d, pidx, q, sgl, flits, sgl_flits, gen, htonl(V_WR_OP(FW_WROPCODE_TUNNEL_TX_PKT) | compl), htonl(V_WR_TID(q->token))); } static inline void t3_stop_tx_queue(struct netdev_queue *txq, struct sge_qset *qs, struct sge_txq *q) { netif_tx_stop_queue(txq); set_bit(TXQ_ETH, &qs->txq_stopped); q->stops++; } /** * eth_xmit - add a packet to the Ethernet Tx queue * @skb: the packet * @dev: the egress net device * * Add a packet to an SGE Tx queue. Runs with softirqs disabled. */ netdev_tx_t t3_eth_xmit(struct sk_buff *skb, struct net_device *dev) { int qidx; unsigned int ndesc, pidx, credits, gen, compl; const struct port_info *pi = netdev_priv(dev); struct adapter *adap = pi->adapter; struct netdev_queue *txq; struct sge_qset *qs; struct sge_txq *q; /* * The chip min packet length is 9 octets but play safe and reject * anything shorter than an Ethernet header. */ if (unlikely(skb->len < ETH_HLEN)) { dev_kfree_skb(skb); return NETDEV_TX_OK; } qidx = skb_get_queue_mapping(skb); qs = &pi->qs[qidx]; q = &qs->txq[TXQ_ETH]; txq = netdev_get_tx_queue(dev, qidx); reclaim_completed_tx(adap, q, TX_RECLAIM_CHUNK); credits = q->size - q->in_use; ndesc = calc_tx_descs(skb); if (unlikely(credits < ndesc)) { t3_stop_tx_queue(txq, qs, q); dev_err(&adap->pdev->dev, "%s: Tx ring %u full while queue awake!\n", dev->name, q->cntxt_id & 7); return NETDEV_TX_BUSY; } q->in_use += ndesc; if (unlikely(credits - ndesc < q->stop_thres)) { t3_stop_tx_queue(txq, qs, q); if (should_restart_tx(q) && test_and_clear_bit(TXQ_ETH, &qs->txq_stopped)) { q->restarts++; netif_tx_start_queue(txq); } } gen = q->gen; q->unacked += ndesc; compl = (q->unacked & 8) << (S_WR_COMPL - 3); q->unacked &= 7; pidx = q->pidx; q->pidx += ndesc; if (q->pidx >= q->size) { q->pidx -= q->size; q->gen ^= 1; } /* update port statistics */ if (skb->ip_summed == CHECKSUM_PARTIAL) qs->port_stats[SGE_PSTAT_TX_CSUM]++; if (skb_shinfo(skb)->gso_size) qs->port_stats[SGE_PSTAT_TSO]++; if (vlan_tx_tag_present(skb)) qs->port_stats[SGE_PSTAT_VLANINS]++; /* * We do not use Tx completion interrupts to free DMAd Tx packets. * This is good for performance but means that we rely on new Tx * packets arriving to run the destructors of completed packets, * which open up space in their sockets' send queues. Sometimes * we do not get such new packets causing Tx to stall. A single * UDP transmitter is a good example of this situation. We have * a clean up timer that periodically reclaims completed packets * but it doesn't run often enough (nor do we want it to) to prevent * lengthy stalls. A solution to this problem is to run the * destructor early, after the packet is queued but before it's DMAd. * A cons is that we lie to socket memory accounting, but the amount * of extra memory is reasonable (limited by the number of Tx * descriptors), the packets do actually get freed quickly by new * packets almost always, and for protocols like TCP that wait for * acks to really free up the data the extra memory is even less. * On the positive side we run the destructors on the sending CPU * rather than on a potentially different completing CPU, usually a * good thing. We also run them without holding our Tx queue lock, * unlike what reclaim_completed_tx() would otherwise do. * * Run the destructor before telling the DMA engine about the packet * to make sure it doesn't complete and get freed prematurely. */ if (likely(!skb_shared(skb))) skb_orphan(skb); write_tx_pkt_wr(adap, skb, pi, pidx, gen, q, ndesc, compl); check_ring_tx_db(adap, q); return NETDEV_TX_OK; } /** * write_imm - write a packet into a Tx descriptor as immediate data * @d: the Tx descriptor to write * @skb: the packet * @len: the length of packet data to write as immediate data * @gen: the generation bit value to write * * Writes a packet as immediate data into a Tx descriptor. The packet * contains a work request at its beginning. We must write the packet * carefully so the SGE doesn't read it accidentally before it's written * in its entirety. */ static inline void write_imm(struct tx_desc *d, struct sk_buff *skb, unsigned int len, unsigned int gen) { struct work_request_hdr *from = (struct work_request_hdr *)skb->data; struct work_request_hdr *to = (struct work_request_hdr *)d; if (likely(!skb->data_len)) memcpy(&to[1], &from[1], len - sizeof(*from)); else skb_copy_bits(skb, sizeof(*from), &to[1], len - sizeof(*from)); to->wr_hi = from->wr_hi | htonl(F_WR_SOP | F_WR_EOP | V_WR_BCNTLFLT(len & 7)); wmb(); to->wr_lo = from->wr_lo | htonl(V_WR_GEN(gen) | V_WR_LEN((len + 7) / 8)); wr_gen2(d, gen); kfree_skb(skb); } /** * check_desc_avail - check descriptor availability on a send queue * @adap: the adapter * @q: the send queue * @skb: the packet needing the descriptors * @ndesc: the number of Tx descriptors needed * @qid: the Tx queue number in its queue set (TXQ_OFLD or TXQ_CTRL) * * Checks if the requested number of Tx descriptors is available on an * SGE send queue. If the queue is already suspended or not enough * descriptors are available the packet is queued for later transmission. * Must be called with the Tx queue locked. * * Returns 0 if enough descriptors are available, 1 if there aren't * enough descriptors and the packet has been queued, and 2 if the caller * needs to retry because there weren't enough descriptors at the * beginning of the call but some freed up in the mean time. */ static inline int check_desc_avail(struct adapter *adap, struct sge_txq *q, struct sk_buff *skb, unsigned int ndesc, unsigned int qid) { if (unlikely(!skb_queue_empty(&q->sendq))) { addq_exit:__skb_queue_tail(&q->sendq, skb); return 1; } if (unlikely(q->size - q->in_use < ndesc)) { struct sge_qset *qs = txq_to_qset(q, qid); set_bit(qid, &qs->txq_stopped); smp_mb__after_clear_bit(); if (should_restart_tx(q) && test_and_clear_bit(qid, &qs->txq_stopped)) return 2; q->stops++; goto addq_exit; } return 0; } /** * reclaim_completed_tx_imm - reclaim completed control-queue Tx descs * @q: the SGE control Tx queue * * This is a variant of reclaim_completed_tx() that is used for Tx queues * that send only immediate data (presently just the control queues) and * thus do not have any sk_buffs to release. */ static inline void reclaim_completed_tx_imm(struct sge_txq *q) { unsigned int reclaim = q->processed - q->cleaned; q->in_use -= reclaim; q->cleaned += reclaim; } static inline int immediate(const struct sk_buff *skb) { return skb->len <= WR_LEN; } /** * ctrl_xmit - send a packet through an SGE control Tx queue * @adap: the adapter * @q: the control queue * @skb: the packet * * Send a packet through an SGE control Tx queue. Packets sent through * a control queue must fit entirely as immediate data in a single Tx * descriptor and have no page fragments. */ static int ctrl_xmit(struct adapter *adap, struct sge_txq *q, struct sk_buff *skb) { int ret; struct work_request_hdr *wrp = (struct work_request_hdr *)skb->data; if (unlikely(!immediate(skb))) { WARN_ON(1); dev_kfree_skb(skb); return NET_XMIT_SUCCESS; } wrp->wr_hi |= htonl(F_WR_SOP | F_WR_EOP); wrp->wr_lo = htonl(V_WR_TID(q->token)); spin_lock(&q->lock); again:reclaim_completed_tx_imm(q); ret = check_desc_avail(adap, q, skb, 1, TXQ_CTRL); if (unlikely(ret)) { if (ret == 1) { spin_unlock(&q->lock); return NET_XMIT_CN; } goto again; } write_imm(&q->desc[q->pidx], skb, skb->len, q->gen); q->in_use++; if (++q->pidx >= q->size) { q->pidx = 0; q->gen ^= 1; } spin_unlock(&q->lock); wmb(); t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id)); return NET_XMIT_SUCCESS; } /** * restart_ctrlq - restart a suspended control queue * @qs: the queue set cotaining the control queue * * Resumes transmission on a suspended Tx control queue. */ static void restart_ctrlq(unsigned long data) { struct sk_buff *skb; struct sge_qset *qs = (struct sge_qset *)data; struct sge_txq *q = &qs->txq[TXQ_CTRL]; spin_lock(&q->lock); again:reclaim_completed_tx_imm(q); while (q->in_use < q->size && (skb = __skb_dequeue(&q->sendq)) != NULL) { write_imm(&q->desc[q->pidx], skb, skb->len, q->gen); if (++q->pidx >= q->size) { q->pidx = 0; q->gen ^= 1; } q->in_use++; } if (!skb_queue_empty(&q->sendq)) { set_bit(TXQ_CTRL, &qs->txq_stopped); smp_mb__after_clear_bit(); if (should_restart_tx(q) && test_and_clear_bit(TXQ_CTRL, &qs->txq_stopped)) goto again; q->stops++; } spin_unlock(&q->lock); wmb(); t3_write_reg(qs->adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id)); } /* * Send a management message through control queue 0 */ int t3_mgmt_tx(struct adapter *adap, struct sk_buff *skb) { int ret; local_bh_disable(); ret = ctrl_xmit(adap, &adap->sge.qs[0].txq[TXQ_CTRL], skb); local_bh_enable(); return ret; } /** * deferred_unmap_destructor - unmap a packet when it is freed * @skb: the packet * * This is the packet destructor used for Tx packets that need to remain * mapped until they are freed rather than until their Tx descriptors are * freed. */ static void deferred_unmap_destructor(struct sk_buff *skb) { int i; const dma_addr_t *p; const struct skb_shared_info *si; const struct deferred_unmap_info *dui; dui = (struct deferred_unmap_info *)skb->head; p = dui->addr; if (skb_tail_pointer(skb) - skb_transport_header(skb)) pci_unmap_single(dui->pdev, *p++, skb_tail_pointer(skb) - skb_transport_header(skb), PCI_DMA_TODEVICE); si = skb_shinfo(skb); for (i = 0; i < si->nr_frags; i++) pci_unmap_page(dui->pdev, *p++, skb_frag_size(&si->frags[i]), PCI_DMA_TODEVICE); } static void setup_deferred_unmapping(struct sk_buff *skb, struct pci_dev *pdev, const struct sg_ent *sgl, int sgl_flits) { dma_addr_t *p; struct deferred_unmap_info *dui; dui = (struct deferred_unmap_info *)skb->head; dui->pdev = pdev; for (p = dui->addr; sgl_flits >= 3; sgl++, sgl_flits -= 3) { *p++ = be64_to_cpu(sgl->addr[0]); *p++ = be64_to_cpu(sgl->addr[1]); } if (sgl_flits) *p = be64_to_cpu(sgl->addr[0]); } /** * write_ofld_wr - write an offload work request * @adap: the adapter * @skb: the packet to send * @q: the Tx queue * @pidx: index of the first Tx descriptor to write * @gen: the generation value to use * @ndesc: number of descriptors the packet will occupy * * Write an offload work request to send the supplied packet. The packet * data already carry the work request with most fields populated. */ static void write_ofld_wr(struct adapter *adap, struct sk_buff *skb, struct sge_txq *q, unsigned int pidx, unsigned int gen, unsigned int ndesc) { unsigned int sgl_flits, flits; struct work_request_hdr *from; struct sg_ent *sgp, sgl[MAX_SKB_FRAGS / 2 + 1]; struct tx_desc *d = &q->desc[pidx]; if (immediate(skb)) { q->sdesc[pidx].skb = NULL; write_imm(d, skb, skb->len, gen); return; } /* Only TX_DATA builds SGLs */ from = (struct work_request_hdr *)skb->data; memcpy(&d->flit[1], &from[1], skb_transport_offset(skb) - sizeof(*from)); flits = skb_transport_offset(skb) / 8; sgp = ndesc == 1 ? (struct sg_ent *)&d->flit[flits] : sgl; sgl_flits = make_sgl(skb, sgp, skb_transport_header(skb), skb_tail_pointer(skb) - skb_transport_header(skb), adap->pdev); if (need_skb_unmap()) { setup_deferred_unmapping(skb, adap->pdev, sgp, sgl_flits); skb->destructor = deferred_unmap_destructor; } write_wr_hdr_sgl(ndesc, skb, d, pidx, q, sgl, flits, sgl_flits, gen, from->wr_hi, from->wr_lo); } /** * calc_tx_descs_ofld - calculate # of Tx descriptors for an offload packet * @skb: the packet * * Returns the number of Tx descriptors needed for the given offload * packet. These packets are already fully constructed. */ static inline unsigned int calc_tx_descs_ofld(const struct sk_buff *skb) { unsigned int flits, cnt; if (skb->len <= WR_LEN) return 1; /* packet fits as immediate data */ flits = skb_transport_offset(skb) / 8; /* headers */ cnt = skb_shinfo(skb)->nr_frags; if (skb_tail_pointer(skb) != skb_transport_header(skb)) cnt++; return flits_to_desc(flits + sgl_len(cnt)); } /** * ofld_xmit - send a packet through an offload queue * @adap: the adapter * @q: the Tx offload queue * @skb: the packet * * Send an offload packet through an SGE offload queue. */ static int ofld_xmit(struct adapter *adap, struct sge_txq *q, struct sk_buff *skb) { int ret; unsigned int ndesc = calc_tx_descs_ofld(skb), pidx, gen; spin_lock(&q->lock); again: reclaim_completed_tx(adap, q, TX_RECLAIM_CHUNK); ret = check_desc_avail(adap, q, skb, ndesc, TXQ_OFLD); if (unlikely(ret)) { if (ret == 1) { skb->priority = ndesc; /* save for restart */ spin_unlock(&q->lock); return NET_XMIT_CN; } goto again; } gen = q->gen; q->in_use += ndesc; pidx = q->pidx; q->pidx += ndesc; if (q->pidx >= q->size) { q->pidx -= q->size; q->gen ^= 1; } spin_unlock(&q->lock); write_ofld_wr(adap, skb, q, pidx, gen, ndesc); check_ring_tx_db(adap, q); return NET_XMIT_SUCCESS; } /** * restart_offloadq - restart a suspended offload queue * @qs: the queue set cotaining the offload queue * * Resumes transmission on a suspended Tx offload queue. */ static void restart_offloadq(unsigned long data) { struct sk_buff *skb; struct sge_qset *qs = (struct sge_qset *)data; struct sge_txq *q = &qs->txq[TXQ_OFLD]; const struct port_info *pi = netdev_priv(qs->netdev); struct adapter *adap = pi->adapter; spin_lock(&q->lock); again: reclaim_completed_tx(adap, q, TX_RECLAIM_CHUNK); while ((skb = skb_peek(&q->sendq)) != NULL) { unsigned int gen, pidx; unsigned int ndesc = skb->priority; if (unlikely(q->size - q->in_use < ndesc)) { set_bit(TXQ_OFLD, &qs->txq_stopped); smp_mb__after_clear_bit(); if (should_restart_tx(q) && test_and_clear_bit(TXQ_OFLD, &qs->txq_stopped)) goto again; q->stops++; break; } gen = q->gen; q->in_use += ndesc; pidx = q->pidx; q->pidx += ndesc; if (q->pidx >= q->size) { q->pidx -= q->size; q->gen ^= 1; } __skb_unlink(skb, &q->sendq); spin_unlock(&q->lock); write_ofld_wr(adap, skb, q, pidx, gen, ndesc); spin_lock(&q->lock); } spin_unlock(&q->lock); #if USE_GTS set_bit(TXQ_RUNNING, &q->flags); set_bit(TXQ_LAST_PKT_DB, &q->flags); #endif wmb(); t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(q->cntxt_id)); } /** * queue_set - return the queue set a packet should use * @skb: the packet * * Maps a packet to the SGE queue set it should use. The desired queue * set is carried in bits 1-3 in the packet's priority. */ static inline int queue_set(const struct sk_buff *skb) { return skb->priority >> 1; } /** * is_ctrl_pkt - return whether an offload packet is a control packet * @skb: the packet * * Determines whether an offload packet should use an OFLD or a CTRL * Tx queue. This is indicated by bit 0 in the packet's priority. */ static inline int is_ctrl_pkt(const struct sk_buff *skb) { return skb->priority & 1; } /** * t3_offload_tx - send an offload packet * @tdev: the offload device to send to * @skb: the packet * * Sends an offload packet. We use the packet priority to select the * appropriate Tx queue as follows: bit 0 indicates whether the packet * should be sent as regular or control, bits 1-3 select the queue set. */ int t3_offload_tx(struct t3cdev *tdev, struct sk_buff *skb) { struct adapter *adap = tdev2adap(tdev); struct sge_qset *qs = &adap->sge.qs[queue_set(skb)]; if (unlikely(is_ctrl_pkt(skb))) return ctrl_xmit(adap, &qs->txq[TXQ_CTRL], skb); return ofld_xmit(adap, &qs->txq[TXQ_OFLD], skb); } /** * offload_enqueue - add an offload packet to an SGE offload receive queue * @q: the SGE response queue * @skb: the packet * * Add a new offload packet to an SGE response queue's offload packet * queue. If the packet is the first on the queue it schedules the RX * softirq to process the queue. */ static inline void offload_enqueue(struct sge_rspq *q, struct sk_buff *skb) { int was_empty = skb_queue_empty(&q->rx_queue); __skb_queue_tail(&q->rx_queue, skb); if (was_empty) { struct sge_qset *qs = rspq_to_qset(q); napi_schedule(&qs->napi); } } /** * deliver_partial_bundle - deliver a (partial) bundle of Rx offload pkts * @tdev: the offload device that will be receiving the packets * @q: the SGE response queue that assembled the bundle * @skbs: the partial bundle * @n: the number of packets in the bundle * * Delivers a (partial) bundle of Rx offload packets to an offload device. */ static inline void deliver_partial_bundle(struct t3cdev *tdev, struct sge_rspq *q, struct sk_buff *skbs[], int n) { if (n) { q->offload_bundles++; tdev->recv(tdev, skbs, n); } } /** * ofld_poll - NAPI handler for offload packets in interrupt mode * @dev: the network device doing the polling * @budget: polling budget * * The NAPI handler for offload packets when a response queue is serviced * by the hard interrupt handler, i.e., when it's operating in non-polling * mode. Creates small packet batches and sends them through the offload * receive handler. Batches need to be of modest size as we do prefetches * on the packets in each. */ static int ofld_poll(struct napi_struct *napi, int budget) { struct sge_qset *qs = container_of(napi, struct sge_qset, napi); struct sge_rspq *q = &qs->rspq; struct adapter *adapter = qs->adap; int work_done = 0; while (work_done < budget) { struct sk_buff *skb, *tmp, *skbs[RX_BUNDLE_SIZE]; struct sk_buff_head queue; int ngathered; spin_lock_irq(&q->lock); __skb_queue_head_init(&queue); skb_queue_splice_init(&q->rx_queue, &queue); if (skb_queue_empty(&queue)) { napi_complete(napi); spin_unlock_irq(&q->lock); return work_done; } spin_unlock_irq(&q->lock); ngathered = 0; skb_queue_walk_safe(&queue, skb, tmp) { if (work_done >= budget) break; work_done++; __skb_unlink(skb, &queue); prefetch(skb->data); skbs[ngathered] = skb; if (++ngathered == RX_BUNDLE_SIZE) { q->offload_bundles++; adapter->tdev.recv(&adapter->tdev, skbs, ngathered); ngathered = 0; } } if (!skb_queue_empty(&queue)) { /* splice remaining packets back onto Rx queue */ spin_lock_irq(&q->lock); skb_queue_splice(&queue, &q->rx_queue); spin_unlock_irq(&q->lock); } deliver_partial_bundle(&adapter->tdev, q, skbs, ngathered); } return work_done; } /** * rx_offload - process a received offload packet * @tdev: the offload device receiving the packet * @rq: the response queue that received the packet * @skb: the packet * @rx_gather: a gather list of packets if we are building a bundle * @gather_idx: index of the next available slot in the bundle * * Process an ingress offload pakcet and add it to the offload ingress * queue. Returns the index of the next available slot in the bundle. */ static inline int rx_offload(struct t3cdev *tdev, struct sge_rspq *rq, struct sk_buff *skb, struct sk_buff *rx_gather[], unsigned int gather_idx) { skb_reset_mac_header(skb); skb_reset_network_header(skb); skb_reset_transport_header(skb); if (rq->polling) { rx_gather[gather_idx++] = skb; if (gather_idx == RX_BUNDLE_SIZE) { tdev->recv(tdev, rx_gather, RX_BUNDLE_SIZE); gather_idx = 0; rq->offload_bundles++; } } else offload_enqueue(rq, skb); return gather_idx; } /** * restart_tx - check whether to restart suspended Tx queues * @qs: the queue set to resume * * Restarts suspended Tx queues of an SGE queue set if they have enough * free resources to resume operation. */ static void restart_tx(struct sge_qset *qs) { if (test_bit(TXQ_ETH, &qs->txq_stopped) && should_restart_tx(&qs->txq[TXQ_ETH]) && test_and_clear_bit(TXQ_ETH, &qs->txq_stopped)) { qs->txq[TXQ_ETH].restarts++; if (netif_running(qs->netdev)) netif_tx_wake_queue(qs->tx_q); } if (test_bit(TXQ_OFLD, &qs->txq_stopped) && should_restart_tx(&qs->txq[TXQ_OFLD]) && test_and_clear_bit(TXQ_OFLD, &qs->txq_stopped)) { qs->txq[TXQ_OFLD].restarts++; tasklet_schedule(&qs->txq[TXQ_OFLD].qresume_tsk); } if (test_bit(TXQ_CTRL, &qs->txq_stopped) && should_restart_tx(&qs->txq[TXQ_CTRL]) && test_and_clear_bit(TXQ_CTRL, &qs->txq_stopped)) { qs->txq[TXQ_CTRL].restarts++; tasklet_schedule(&qs->txq[TXQ_CTRL].qresume_tsk); } } /** * cxgb3_arp_process - process an ARP request probing a private IP address * @adapter: the adapter * @skb: the skbuff containing the ARP request * * Check if the ARP request is probing the private IP address * dedicated to iSCSI, generate an ARP reply if so. */ static void cxgb3_arp_process(struct port_info *pi, struct sk_buff *skb) { struct net_device *dev = skb->dev; struct arphdr *arp; unsigned char *arp_ptr; unsigned char *sha; __be32 sip, tip; if (!dev) return; skb_reset_network_header(skb); arp = arp_hdr(skb); if (arp->ar_op != htons(ARPOP_REQUEST)) return; arp_ptr = (unsigned char *)(arp + 1); sha = arp_ptr; arp_ptr += dev->addr_len; memcpy(&sip, arp_ptr, sizeof(sip)); arp_ptr += sizeof(sip); arp_ptr += dev->addr_len; memcpy(&tip, arp_ptr, sizeof(tip)); if (tip != pi->iscsi_ipv4addr) return; arp_send(ARPOP_REPLY, ETH_P_ARP, sip, dev, tip, sha, pi->iscsic.mac_addr, sha); } static inline int is_arp(struct sk_buff *skb) { return skb->protocol == htons(ETH_P_ARP); } static void cxgb3_process_iscsi_prov_pack(struct port_info *pi, struct sk_buff *skb) { if (is_arp(skb)) { cxgb3_arp_process(pi, skb); return; } if (pi->iscsic.recv) pi->iscsic.recv(pi, skb); } /** * rx_eth - process an ingress ethernet packet * @adap: the adapter * @rq: the response queue that received the packet * @skb: the packet * @pad: amount of padding at the start of the buffer * * Process an ingress ethernet pakcet and deliver it to the stack. * The padding is 2 if the packet was delivered in an Rx buffer and 0 * if it was immediate data in a response. */ static void rx_eth(struct adapter *adap, struct sge_rspq *rq, struct sk_buff *skb, int pad, int lro) { struct cpl_rx_pkt *p = (struct cpl_rx_pkt *)(skb->data + pad); struct sge_qset *qs = rspq_to_qset(rq); struct port_info *pi; skb_pull(skb, sizeof(*p) + pad); skb->protocol = eth_type_trans(skb, adap->port[p->iff]); pi = netdev_priv(skb->dev); if ((skb->dev->features & NETIF_F_RXCSUM) && p->csum_valid && p->csum == htons(0xffff) && !p->fragment) { qs->port_stats[SGE_PSTAT_RX_CSUM_GOOD]++; skb->ip_summed = CHECKSUM_UNNECESSARY; } else skb_checksum_none_assert(skb); skb_record_rx_queue(skb, qs - &adap->sge.qs[pi->first_qset]); if (p->vlan_valid) { qs->port_stats[SGE_PSTAT_VLANEX]++; __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(p->vlan)); } if (rq->polling) { if (lro) napi_gro_receive(&qs->napi, skb); else { if (unlikely(pi->iscsic.flags)) cxgb3_process_iscsi_prov_pack(pi, skb); netif_receive_skb(skb); } } else netif_rx(skb); } static inline int is_eth_tcp(u32 rss) { return G_HASHTYPE(ntohl(rss)) == RSS_HASH_4_TUPLE; } /** * lro_add_page - add a page chunk to an LRO session * @adap: the adapter * @qs: the associated queue set * @fl: the free list containing the page chunk to add * @len: packet length * @complete: Indicates the last fragment of a frame * * Add a received packet contained in a page chunk to an existing LRO * session. */ static void lro_add_page(struct adapter *adap, struct sge_qset *qs, struct sge_fl *fl, int len, int complete) { struct rx_sw_desc *sd = &fl->sdesc[fl->cidx]; struct port_info *pi = netdev_priv(qs->netdev); struct sk_buff *skb = NULL; struct cpl_rx_pkt *cpl; struct skb_frag_struct *rx_frag; int nr_frags; int offset = 0; if (!qs->nomem) { skb = napi_get_frags(&qs->napi); qs->nomem = !skb; } fl->credits--; pci_dma_sync_single_for_cpu(adap->pdev, dma_unmap_addr(sd, dma_addr), fl->buf_size - SGE_PG_RSVD, PCI_DMA_FROMDEVICE); (*sd->pg_chunk.p_cnt)--; if (!*sd->pg_chunk.p_cnt && sd->pg_chunk.page != fl->pg_chunk.page) pci_unmap_page(adap->pdev, sd->pg_chunk.mapping, fl->alloc_size, PCI_DMA_FROMDEVICE); if (!skb) { put_page(sd->pg_chunk.page); if (complete) qs->nomem = 0; return; } rx_frag = skb_shinfo(skb)->frags; nr_frags = skb_shinfo(skb)->nr_frags; if (!nr_frags) { offset = 2 + sizeof(struct cpl_rx_pkt); cpl = qs->lro_va = sd->pg_chunk.va + 2; if ((qs->netdev->features & NETIF_F_RXCSUM) && cpl->csum_valid && cpl->csum == htons(0xffff)) { skb->ip_summed = CHECKSUM_UNNECESSARY; qs->port_stats[SGE_PSTAT_RX_CSUM_GOOD]++; } else skb->ip_summed = CHECKSUM_NONE; } else cpl = qs->lro_va; len -= offset; rx_frag += nr_frags; __skb_frag_set_page(rx_frag, sd->pg_chunk.page); rx_frag->page_offset = sd->pg_chunk.offset + offset; skb_frag_size_set(rx_frag, len); skb->len += len; skb->data_len += len; skb->truesize += len; skb_shinfo(skb)->nr_frags++; if (!complete) return; skb_record_rx_queue(skb, qs - &adap->sge.qs[pi->first_qset]); if (cpl->vlan_valid) { qs->port_stats[SGE_PSTAT_VLANEX]++; __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(cpl->vlan)); } napi_gro_frags(&qs->napi); } /** * handle_rsp_cntrl_info - handles control information in a response * @qs: the queue set corresponding to the response * @flags: the response control flags * * Handles the control information of an SGE response, such as GTS * indications and completion credits for the queue set's Tx queues. * HW coalesces credits, we don't do any extra SW coalescing. */ static inline void handle_rsp_cntrl_info(struct sge_qset *qs, u32 flags) { unsigned int credits; #if USE_GTS if (flags & F_RSPD_TXQ0_GTS) clear_bit(TXQ_RUNNING, &qs->txq[TXQ_ETH].flags); #endif credits = G_RSPD_TXQ0_CR(flags); if (credits) qs->txq[TXQ_ETH].processed += credits; credits = G_RSPD_TXQ2_CR(flags); if (credits) qs->txq[TXQ_CTRL].processed += credits; # if USE_GTS if (flags & F_RSPD_TXQ1_GTS) clear_bit(TXQ_RUNNING, &qs->txq[TXQ_OFLD].flags); # endif credits = G_RSPD_TXQ1_CR(flags); if (credits) qs->txq[TXQ_OFLD].processed += credits; } /** * check_ring_db - check if we need to ring any doorbells * @adapter: the adapter * @qs: the queue set whose Tx queues are to be examined * @sleeping: indicates which Tx queue sent GTS * * Checks if some of a queue set's Tx queues need to ring their doorbells * to resume transmission after idling while they still have unprocessed * descriptors. */ static void check_ring_db(struct adapter *adap, struct sge_qset *qs, unsigned int sleeping) { if (sleeping & F_RSPD_TXQ0_GTS) { struct sge_txq *txq = &qs->txq[TXQ_ETH]; if (txq->cleaned + txq->in_use != txq->processed && !test_and_set_bit(TXQ_LAST_PKT_DB, &txq->flags)) { set_bit(TXQ_RUNNING, &txq->flags); t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(txq->cntxt_id)); } } if (sleeping & F_RSPD_TXQ1_GTS) { struct sge_txq *txq = &qs->txq[TXQ_OFLD]; if (txq->cleaned + txq->in_use != txq->processed && !test_and_set_bit(TXQ_LAST_PKT_DB, &txq->flags)) { set_bit(TXQ_RUNNING, &txq->flags); t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(txq->cntxt_id)); } } } /** * is_new_response - check if a response is newly written * @r: the response descriptor * @q: the response queue * * Returns true if a response descriptor contains a yet unprocessed * response. */ static inline int is_new_response(const struct rsp_desc *r, const struct sge_rspq *q) { return (r->intr_gen & F_RSPD_GEN2) == q->gen; } static inline void clear_rspq_bufstate(struct sge_rspq * const q) { q->pg_skb = NULL; q->rx_recycle_buf = 0; } #define RSPD_GTS_MASK (F_RSPD_TXQ0_GTS | F_RSPD_TXQ1_GTS) #define RSPD_CTRL_MASK (RSPD_GTS_MASK | \ V_RSPD_TXQ0_CR(M_RSPD_TXQ0_CR) | \ V_RSPD_TXQ1_CR(M_RSPD_TXQ1_CR) | \ V_RSPD_TXQ2_CR(M_RSPD_TXQ2_CR)) /* How long to delay the next interrupt in case of memory shortage, in 0.1us. */ #define NOMEM_INTR_DELAY 2500 /** * process_responses - process responses from an SGE response queue * @adap: the adapter * @qs: the queue set to which the response queue belongs * @budget: how many responses can be processed in this round * * Process responses from an SGE response queue up to the supplied budget. * Responses include received packets as well as credits and other events * for the queues that belong to the response queue's queue set. * A negative budget is effectively unlimited. * * Additionally choose the interrupt holdoff time for the next interrupt * on this queue. If the system is under memory shortage use a fairly * long delay to help recovery. */ static int process_responses(struct adapter *adap, struct sge_qset *qs, int budget) { struct sge_rspq *q = &qs->rspq; struct rsp_desc *r = &q->desc[q->cidx]; int budget_left = budget; unsigned int sleeping = 0; struct sk_buff *offload_skbs[RX_BUNDLE_SIZE]; int ngathered = 0; q->next_holdoff = q->holdoff_tmr; while (likely(budget_left && is_new_response(r, q))) { int packet_complete, eth, ethpad = 2; int lro = !!(qs->netdev->features & NETIF_F_GRO); struct sk_buff *skb = NULL; u32 len, flags; __be32 rss_hi, rss_lo; rmb(); eth = r->rss_hdr.opcode == CPL_RX_PKT; rss_hi = *(const __be32 *)r; rss_lo = r->rss_hdr.rss_hash_val; flags = ntohl(r->flags); if (unlikely(flags & F_RSPD_ASYNC_NOTIF)) { skb = alloc_skb(AN_PKT_SIZE, GFP_ATOMIC); if (!skb) goto no_mem; memcpy(__skb_put(skb, AN_PKT_SIZE), r, AN_PKT_SIZE); skb->data[0] = CPL_ASYNC_NOTIF; rss_hi = htonl(CPL_ASYNC_NOTIF << 24); q->async_notif++; } else if (flags & F_RSPD_IMM_DATA_VALID) { skb = get_imm_packet(r); if (unlikely(!skb)) { no_mem: q->next_holdoff = NOMEM_INTR_DELAY; q->nomem++; /* consume one credit since we tried */ budget_left--; break; } q->imm_data++; ethpad = 0; } else if ((len = ntohl(r->len_cq)) != 0) { struct sge_fl *fl; lro &= eth && is_eth_tcp(rss_hi); fl = (len & F_RSPD_FLQ) ? &qs->fl[1] : &qs->fl[0]; if (fl->use_pages) { void *addr = fl->sdesc[fl->cidx].pg_chunk.va; prefetch(addr); #if L1_CACHE_BYTES < 128 prefetch(addr + L1_CACHE_BYTES); #endif __refill_fl(adap, fl); if (lro > 0) { lro_add_page(adap, qs, fl, G_RSPD_LEN(len), flags & F_RSPD_EOP); goto next_fl; } skb = get_packet_pg(adap, fl, q, G_RSPD_LEN(len), eth ? SGE_RX_DROP_THRES : 0); q->pg_skb = skb; } else skb = get_packet(adap, fl, G_RSPD_LEN(len), eth ? SGE_RX_DROP_THRES : 0); if (unlikely(!skb)) { if (!eth) goto no_mem; q->rx_drops++; } else if (unlikely(r->rss_hdr.opcode == CPL_TRACE_PKT)) __skb_pull(skb, 2); next_fl: if (++fl->cidx == fl->size) fl->cidx = 0; } else q->pure_rsps++; if (flags & RSPD_CTRL_MASK) { sleeping |= flags & RSPD_GTS_MASK; handle_rsp_cntrl_info(qs, flags); } r++; if (unlikely(++q->cidx == q->size)) { q->cidx = 0; q->gen ^= 1; r = q->desc; } prefetch(r); if (++q->credits >= (q->size / 4)) { refill_rspq(adap, q, q->credits); q->credits = 0; } packet_complete = flags & (F_RSPD_EOP | F_RSPD_IMM_DATA_VALID | F_RSPD_ASYNC_NOTIF); if (skb != NULL && packet_complete) { if (eth) rx_eth(adap, q, skb, ethpad, lro); else { q->offload_pkts++; /* Preserve the RSS info in csum & priority */ skb->csum = rss_hi; skb->priority = rss_lo; ngathered = rx_offload(&adap->tdev, q, skb, offload_skbs, ngathered); } if (flags & F_RSPD_EOP) clear_rspq_bufstate(q); } --budget_left; } deliver_partial_bundle(&adap->tdev, q, offload_skbs, ngathered); if (sleeping) check_ring_db(adap, qs, sleeping); smp_mb(); /* commit Tx queue .processed updates */ if (unlikely(qs->txq_stopped != 0)) restart_tx(qs); budget -= budget_left; return budget; } static inline int is_pure_response(const struct rsp_desc *r) { __be32 n = r->flags & htonl(F_RSPD_ASYNC_NOTIF | F_RSPD_IMM_DATA_VALID); return (n | r->len_cq) == 0; } /** * napi_rx_handler - the NAPI handler for Rx processing * @napi: the napi instance * @budget: how many packets we can process in this round * * Handler for new data events when using NAPI. */ static int napi_rx_handler(struct napi_struct *napi, int budget) { struct sge_qset *qs = container_of(napi, struct sge_qset, napi); struct adapter *adap = qs->adap; int work_done = process_responses(adap, qs, budget); if (likely(work_done < budget)) { napi_complete(napi); /* * Because we don't atomically flush the following * write it is possible that in very rare cases it can * reach the device in a way that races with a new * response being written plus an error interrupt * causing the NAPI interrupt handler below to return * unhandled status to the OS. To protect against * this would require flushing the write and doing * both the write and the flush with interrupts off. * Way too expensive and unjustifiable given the * rarity of the race. * * The race cannot happen at all with MSI-X. */ t3_write_reg(adap, A_SG_GTS, V_RSPQ(qs->rspq.cntxt_id) | V_NEWTIMER(qs->rspq.next_holdoff) | V_NEWINDEX(qs->rspq.cidx)); } return work_done; } /* * Returns true if the device is already scheduled for polling. */ static inline int napi_is_scheduled(struct napi_struct *napi) { return test_bit(NAPI_STATE_SCHED, &napi->state); } /** * process_pure_responses - process pure responses from a response queue * @adap: the adapter * @qs: the queue set owning the response queue * @r: the first pure response to process * * A simpler version of process_responses() that handles only pure (i.e., * non data-carrying) responses. Such respones are too light-weight to * justify calling a softirq under NAPI, so we handle them specially in * the interrupt handler. The function is called with a pointer to a * response, which the caller must ensure is a valid pure response. * * Returns 1 if it encounters a valid data-carrying response, 0 otherwise. */ static int process_pure_responses(struct adapter *adap, struct sge_qset *qs, struct rsp_desc *r) { struct sge_rspq *q = &qs->rspq; unsigned int sleeping = 0; do { u32 flags = ntohl(r->flags); r++; if (unlikely(++q->cidx == q->size)) { q->cidx = 0; q->gen ^= 1; r = q->desc; } prefetch(r); if (flags & RSPD_CTRL_MASK) { sleeping |= flags & RSPD_GTS_MASK; handle_rsp_cntrl_info(qs, flags); } q->pure_rsps++; if (++q->credits >= (q->size / 4)) { refill_rspq(adap, q, q->credits); q->credits = 0; } if (!is_new_response(r, q)) break; rmb(); } while (is_pure_response(r)); if (sleeping) check_ring_db(adap, qs, sleeping); smp_mb(); /* commit Tx queue .processed updates */ if (unlikely(qs->txq_stopped != 0)) restart_tx(qs); return is_new_response(r, q); } /** * handle_responses - decide what to do with new responses in NAPI mode * @adap: the adapter * @q: the response queue * * This is used by the NAPI interrupt handlers to decide what to do with * new SGE responses. If there are no new responses it returns -1. If * there are new responses and they are pure (i.e., non-data carrying) * it handles them straight in hard interrupt context as they are very * cheap and don't deliver any packets. Finally, if there are any data * signaling responses it schedules the NAPI handler. Returns 1 if it * schedules NAPI, 0 if all new responses were pure. * * The caller must ascertain NAPI is not already running. */ static inline int handle_responses(struct adapter *adap, struct sge_rspq *q) { struct sge_qset *qs = rspq_to_qset(q); struct rsp_desc *r = &q->desc[q->cidx]; if (!is_new_response(r, q)) return -1; rmb(); if (is_pure_response(r) && process_pure_responses(adap, qs, r) == 0) { t3_write_reg(adap, A_SG_GTS, V_RSPQ(q->cntxt_id) | V_NEWTIMER(q->holdoff_tmr) | V_NEWINDEX(q->cidx)); return 0; } napi_schedule(&qs->napi); return 1; } /* * The MSI-X interrupt handler for an SGE response queue for the non-NAPI case * (i.e., response queue serviced in hard interrupt). */ static irqreturn_t t3_sge_intr_msix(int irq, void *cookie) { struct sge_qset *qs = cookie; struct adapter *adap = qs->adap; struct sge_rspq *q = &qs->rspq; spin_lock(&q->lock); if (process_responses(adap, qs, -1) == 0) q->unhandled_irqs++; t3_write_reg(adap, A_SG_GTS, V_RSPQ(q->cntxt_id) | V_NEWTIMER(q->next_holdoff) | V_NEWINDEX(q->cidx)); spin_unlock(&q->lock); return IRQ_HANDLED; } /* * The MSI-X interrupt handler for an SGE response queue for the NAPI case * (i.e., response queue serviced by NAPI polling). */ static irqreturn_t t3_sge_intr_msix_napi(int irq, void *cookie) { struct sge_qset *qs = cookie; struct sge_rspq *q = &qs->rspq; spin_lock(&q->lock); if (handle_responses(qs->adap, q) < 0) q->unhandled_irqs++; spin_unlock(&q->lock); return IRQ_HANDLED; } /* * The non-NAPI MSI interrupt handler. This needs to handle data events from * SGE response queues as well as error and other async events as they all use * the same MSI vector. We use one SGE response queue per port in this mode * and protect all response queues with queue 0's lock. */ static irqreturn_t t3_intr_msi(int irq, void *cookie) { int new_packets = 0; struct adapter *adap = cookie; struct sge_rspq *q = &adap->sge.qs[0].rspq; spin_lock(&q->lock); if (process_responses(adap, &adap->sge.qs[0], -1)) { t3_write_reg(adap, A_SG_GTS, V_RSPQ(q->cntxt_id) | V_NEWTIMER(q->next_holdoff) | V_NEWINDEX(q->cidx)); new_packets = 1; } if (adap->params.nports == 2 && process_responses(adap, &adap->sge.qs[1], -1)) { struct sge_rspq *q1 = &adap->sge.qs[1].rspq; t3_write_reg(adap, A_SG_GTS, V_RSPQ(q1->cntxt_id) | V_NEWTIMER(q1->next_holdoff) | V_NEWINDEX(q1->cidx)); new_packets = 1; } if (!new_packets && t3_slow_intr_handler(adap) == 0) q->unhandled_irqs++; spin_unlock(&q->lock); return IRQ_HANDLED; } static int rspq_check_napi(struct sge_qset *qs) { struct sge_rspq *q = &qs->rspq; if (!napi_is_scheduled(&qs->napi) && is_new_response(&q->desc[q->cidx], q)) { napi_schedule(&qs->napi); return 1; } return 0; } /* * The MSI interrupt handler for the NAPI case (i.e., response queues serviced * by NAPI polling). Handles data events from SGE response queues as well as * error and other async events as they all use the same MSI vector. We use * one SGE response queue per port in this mode and protect all response * queues with queue 0's lock. */ static irqreturn_t t3_intr_msi_napi(int irq, void *cookie) { int new_packets; struct adapter *adap = cookie; struct sge_rspq *q = &adap->sge.qs[0].rspq; spin_lock(&q->lock); new_packets = rspq_check_napi(&adap->sge.qs[0]); if (adap->params.nports == 2) new_packets += rspq_check_napi(&adap->sge.qs[1]); if (!new_packets && t3_slow_intr_handler(adap) == 0) q->unhandled_irqs++; spin_unlock(&q->lock); return IRQ_HANDLED; } /* * A helper function that processes responses and issues GTS. */ static inline int process_responses_gts(struct adapter *adap, struct sge_rspq *rq) { int work; work = process_responses(adap, rspq_to_qset(rq), -1); t3_write_reg(adap, A_SG_GTS, V_RSPQ(rq->cntxt_id) | V_NEWTIMER(rq->next_holdoff) | V_NEWINDEX(rq->cidx)); return work; } /* * The legacy INTx interrupt handler. This needs to handle data events from * SGE response queues as well as error and other async events as they all use * the same interrupt pin. We use one SGE response queue per port in this mode * and protect all response queues with queue 0's lock. */ static irqreturn_t t3_intr(int irq, void *cookie) { int work_done, w0, w1; struct adapter *adap = cookie; struct sge_rspq *q0 = &adap->sge.qs[0].rspq; struct sge_rspq *q1 = &adap->sge.qs[1].rspq; spin_lock(&q0->lock); w0 = is_new_response(&q0->desc[q0->cidx], q0); w1 = adap->params.nports == 2 && is_new_response(&q1->desc[q1->cidx], q1); if (likely(w0 | w1)) { t3_write_reg(adap, A_PL_CLI, 0); t3_read_reg(adap, A_PL_CLI); /* flush */ if (likely(w0)) process_responses_gts(adap, q0); if (w1) process_responses_gts(adap, q1); work_done = w0 | w1; } else work_done = t3_slow_intr_handler(adap); spin_unlock(&q0->lock); return IRQ_RETVAL(work_done != 0); } /* * Interrupt handler for legacy INTx interrupts for T3B-based cards. * Handles data events from SGE response queues as well as error and other * async events as they all use the same interrupt pin. We use one SGE * response queue per port in this mode and protect all response queues with * queue 0's lock. */ static irqreturn_t t3b_intr(int irq, void *cookie) { u32 map; struct adapter *adap = cookie; struct sge_rspq *q0 = &adap->sge.qs[0].rspq; t3_write_reg(adap, A_PL_CLI, 0); map = t3_read_reg(adap, A_SG_DATA_INTR); if (unlikely(!map)) /* shared interrupt, most likely */ return IRQ_NONE; spin_lock(&q0->lock); if (unlikely(map & F_ERRINTR)) t3_slow_intr_handler(adap); if (likely(map & 1)) process_responses_gts(adap, q0); if (map & 2) process_responses_gts(adap, &adap->sge.qs[1].rspq); spin_unlock(&q0->lock); return IRQ_HANDLED; } /* * NAPI interrupt handler for legacy INTx interrupts for T3B-based cards. * Handles data events from SGE response queues as well as error and other * async events as they all use the same interrupt pin. We use one SGE * response queue per port in this mode and protect all response queues with * queue 0's lock. */ static irqreturn_t t3b_intr_napi(int irq, void *cookie) { u32 map; struct adapter *adap = cookie; struct sge_qset *qs0 = &adap->sge.qs[0]; struct sge_rspq *q0 = &qs0->rspq; t3_write_reg(adap, A_PL_CLI, 0); map = t3_read_reg(adap, A_SG_DATA_INTR); if (unlikely(!map)) /* shared interrupt, most likely */ return IRQ_NONE; spin_lock(&q0->lock); if (unlikely(map & F_ERRINTR)) t3_slow_intr_handler(adap); if (likely(map & 1)) napi_schedule(&qs0->napi); if (map & 2) napi_schedule(&adap->sge.qs[1].napi); spin_unlock(&q0->lock); return IRQ_HANDLED; } /** * t3_intr_handler - select the top-level interrupt handler * @adap: the adapter * @polling: whether using NAPI to service response queues * * Selects the top-level interrupt handler based on the type of interrupts * (MSI-X, MSI, or legacy) and whether NAPI will be used to service the * response queues. */ irq_handler_t t3_intr_handler(struct adapter *adap, int polling) { if (adap->flags & USING_MSIX) return polling ? t3_sge_intr_msix_napi : t3_sge_intr_msix; if (adap->flags & USING_MSI) return polling ? t3_intr_msi_napi : t3_intr_msi; if (adap->params.rev > 0) return polling ? t3b_intr_napi : t3b_intr; return t3_intr; } #define SGE_PARERR (F_CPPARITYERROR | F_OCPARITYERROR | F_RCPARITYERROR | \ F_IRPARITYERROR | V_ITPARITYERROR(M_ITPARITYERROR) | \ V_FLPARITYERROR(M_FLPARITYERROR) | F_LODRBPARITYERROR | \ F_HIDRBPARITYERROR | F_LORCQPARITYERROR | \ F_HIRCQPARITYERROR) #define SGE_FRAMINGERR (F_UC_REQ_FRAMINGERROR | F_R_REQ_FRAMINGERROR) #define SGE_FATALERR (SGE_PARERR | SGE_FRAMINGERR | F_RSPQCREDITOVERFOW | \ F_RSPQDISABLED) /** * t3_sge_err_intr_handler - SGE async event interrupt handler * @adapter: the adapter * * Interrupt handler for SGE asynchronous (non-data) events. */ void t3_sge_err_intr_handler(struct adapter *adapter) { unsigned int v, status = t3_read_reg(adapter, A_SG_INT_CAUSE) & ~F_FLEMPTY; if (status & SGE_PARERR) CH_ALERT(adapter, "SGE parity error (0x%x)\n", status & SGE_PARERR); if (status & SGE_FRAMINGERR) CH_ALERT(adapter, "SGE framing error (0x%x)\n", status & SGE_FRAMINGERR); if (status & F_RSPQCREDITOVERFOW) CH_ALERT(adapter, "SGE response queue credit overflow\n"); if (status & F_RSPQDISABLED) { v = t3_read_reg(adapter, A_SG_RSPQ_FL_STATUS); CH_ALERT(adapter, "packet delivered to disabled response queue " "(0x%x)\n", (v >> S_RSPQ0DISABLED) & 0xff); } if (status & (F_HIPIODRBDROPERR | F_LOPIODRBDROPERR)) queue_work(cxgb3_wq, &adapter->db_drop_task); if (status & (F_HIPRIORITYDBFULL | F_LOPRIORITYDBFULL)) queue_work(cxgb3_wq, &adapter->db_full_task); if (status & (F_HIPRIORITYDBEMPTY | F_LOPRIORITYDBEMPTY)) queue_work(cxgb3_wq, &adapter->db_empty_task); t3_write_reg(adapter, A_SG_INT_CAUSE, status); if (status & SGE_FATALERR) t3_fatal_err(adapter); } /** * sge_timer_tx - perform periodic maintenance of an SGE qset * @data: the SGE queue set to maintain * * Runs periodically from a timer to perform maintenance of an SGE queue * set. It performs two tasks: * * Cleans up any completed Tx descriptors that may still be pending. * Normal descriptor cleanup happens when new packets are added to a Tx * queue so this timer is relatively infrequent and does any cleanup only * if the Tx queue has not seen any new packets in a while. We make a * best effort attempt to reclaim descriptors, in that we don't wait * around if we cannot get a queue's lock (which most likely is because * someone else is queueing new packets and so will also handle the clean * up). Since control queues use immediate data exclusively we don't * bother cleaning them up here. * */ static void sge_timer_tx(unsigned long data) { struct sge_qset *qs = (struct sge_qset *)data; struct port_info *pi = netdev_priv(qs->netdev); struct adapter *adap = pi->adapter; unsigned int tbd[SGE_TXQ_PER_SET] = {0, 0}; unsigned long next_period; if (__netif_tx_trylock(qs->tx_q)) { tbd[TXQ_ETH] = reclaim_completed_tx(adap, &qs->txq[TXQ_ETH], TX_RECLAIM_TIMER_CHUNK); __netif_tx_unlock(qs->tx_q); } if (spin_trylock(&qs->txq[TXQ_OFLD].lock)) { tbd[TXQ_OFLD] = reclaim_completed_tx(adap, &qs->txq[TXQ_OFLD], TX_RECLAIM_TIMER_CHUNK); spin_unlock(&qs->txq[TXQ_OFLD].lock); } next_period = TX_RECLAIM_PERIOD >> (max(tbd[TXQ_ETH], tbd[TXQ_OFLD]) / TX_RECLAIM_TIMER_CHUNK); mod_timer(&qs->tx_reclaim_timer, jiffies + next_period); } /** * sge_timer_rx - perform periodic maintenance of an SGE qset * @data: the SGE queue set to maintain * * a) Replenishes Rx queues that have run out due to memory shortage. * Normally new Rx buffers are added when existing ones are consumed but * when out of memory a queue can become empty. We try to add only a few * buffers here, the queue will be replenished fully as these new buffers * are used up if memory shortage has subsided. * * b) Return coalesced response queue credits in case a response queue is * starved. * */ static void sge_timer_rx(unsigned long data) { spinlock_t *lock; struct sge_qset *qs = (struct sge_qset *)data; struct port_info *pi = netdev_priv(qs->netdev); struct adapter *adap = pi->adapter; u32 status; lock = adap->params.rev > 0 ? &qs->rspq.lock : &adap->sge.qs[0].rspq.lock; if (!spin_trylock_irq(lock)) goto out; if (napi_is_scheduled(&qs->napi)) goto unlock; if (adap->params.rev < 4) { status = t3_read_reg(adap, A_SG_RSPQ_FL_STATUS); if (status & (1 << qs->rspq.cntxt_id)) { qs->rspq.starved++; if (qs->rspq.credits) { qs->rspq.credits--; refill_rspq(adap, &qs->rspq, 1); qs->rspq.restarted++; t3_write_reg(adap, A_SG_RSPQ_FL_STATUS, 1 << qs->rspq.cntxt_id); } } } if (qs->fl[0].credits < qs->fl[0].size) __refill_fl(adap, &qs->fl[0]); if (qs->fl[1].credits < qs->fl[1].size) __refill_fl(adap, &qs->fl[1]); unlock: spin_unlock_irq(lock); out: mod_timer(&qs->rx_reclaim_timer, jiffies + RX_RECLAIM_PERIOD); } /** * t3_update_qset_coalesce - update coalescing settings for a queue set * @qs: the SGE queue set * @p: new queue set parameters * * Update the coalescing settings for an SGE queue set. Nothing is done * if the queue set is not initialized yet. */ void t3_update_qset_coalesce(struct sge_qset *qs, const struct qset_params *p) { qs->rspq.holdoff_tmr = max(p->coalesce_usecs * 10, 1U);/* can't be 0 */ qs->rspq.polling = p->polling; qs->napi.poll = p->polling ? napi_rx_handler : ofld_poll; } /** * t3_sge_alloc_qset - initialize an SGE queue set * @adapter: the adapter * @id: the queue set id * @nports: how many Ethernet ports will be using this queue set * @irq_vec_idx: the IRQ vector index for response queue interrupts * @p: configuration parameters for this queue set * @ntxq: number of Tx queues for the queue set * @netdev: net device associated with this queue set * @netdevq: net device TX queue associated with this queue set * * Allocate resources and initialize an SGE queue set. A queue set * comprises a response queue, two Rx free-buffer queues, and up to 3 * Tx queues. The Tx queues are assigned roles in the order Ethernet * queue, offload queue, and control queue. */ int t3_sge_alloc_qset(struct adapter *adapter, unsigned int id, int nports, int irq_vec_idx, const struct qset_params *p, int ntxq, struct net_device *dev, struct netdev_queue *netdevq) { int i, avail, ret = -ENOMEM; struct sge_qset *q = &adapter->sge.qs[id]; init_qset_cntxt(q, id); setup_timer(&q->tx_reclaim_timer, sge_timer_tx, (unsigned long)q); setup_timer(&q->rx_reclaim_timer, sge_timer_rx, (unsigned long)q); q->fl[0].desc = alloc_ring(adapter->pdev, p->fl_size, sizeof(struct rx_desc), sizeof(struct rx_sw_desc), &q->fl[0].phys_addr, &q->fl[0].sdesc); if (!q->fl[0].desc) goto err; q->fl[1].desc = alloc_ring(adapter->pdev, p->jumbo_size, sizeof(struct rx_desc), sizeof(struct rx_sw_desc), &q->fl[1].phys_addr, &q->fl[1].sdesc); if (!q->fl[1].desc) goto err; q->rspq.desc = alloc_ring(adapter->pdev, p->rspq_size, sizeof(struct rsp_desc), 0, &q->rspq.phys_addr, NULL); if (!q->rspq.desc) goto err; for (i = 0; i < ntxq; ++i) { /* * The control queue always uses immediate data so does not * need to keep track of any sk_buffs. */ size_t sz = i == TXQ_CTRL ? 0 : sizeof(struct tx_sw_desc); q->txq[i].desc = alloc_ring(adapter->pdev, p->txq_size[i], sizeof(struct tx_desc), sz, &q->txq[i].phys_addr, &q->txq[i].sdesc); if (!q->txq[i].desc) goto err; q->txq[i].gen = 1; q->txq[i].size = p->txq_size[i]; spin_lock_init(&q->txq[i].lock); skb_queue_head_init(&q->txq[i].sendq); } tasklet_init(&q->txq[TXQ_OFLD].qresume_tsk, restart_offloadq, (unsigned long)q); tasklet_init(&q->txq[TXQ_CTRL].qresume_tsk, restart_ctrlq, (unsigned long)q); q->fl[0].gen = q->fl[1].gen = 1; q->fl[0].size = p->fl_size; q->fl[1].size = p->jumbo_size; q->rspq.gen = 1; q->rspq.size = p->rspq_size; spin_lock_init(&q->rspq.lock); skb_queue_head_init(&q->rspq.rx_queue); q->txq[TXQ_ETH].stop_thres = nports * flits_to_desc(sgl_len(MAX_SKB_FRAGS + 1) + 3); #if FL0_PG_CHUNK_SIZE > 0 q->fl[0].buf_size = FL0_PG_CHUNK_SIZE; #else q->fl[0].buf_size = SGE_RX_SM_BUF_SIZE + sizeof(struct cpl_rx_data); #endif #if FL1_PG_CHUNK_SIZE > 0 q->fl[1].buf_size = FL1_PG_CHUNK_SIZE; #else q->fl[1].buf_size = is_offload(adapter) ? (16 * 1024) - SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) : MAX_FRAME_SIZE + 2 + sizeof(struct cpl_rx_pkt); #endif q->fl[0].use_pages = FL0_PG_CHUNK_SIZE > 0; q->fl[1].use_pages = FL1_PG_CHUNK_SIZE > 0; q->fl[0].order = FL0_PG_ORDER; q->fl[1].order = FL1_PG_ORDER; q->fl[0].alloc_size = FL0_PG_ALLOC_SIZE; q->fl[1].alloc_size = FL1_PG_ALLOC_SIZE; spin_lock_irq(&adapter->sge.reg_lock); /* FL threshold comparison uses < */ ret = t3_sge_init_rspcntxt(adapter, q->rspq.cntxt_id, irq_vec_idx, q->rspq.phys_addr, q->rspq.size, q->fl[0].buf_size - SGE_PG_RSVD, 1, 0); if (ret) goto err_unlock; for (i = 0; i < SGE_RXQ_PER_SET; ++i) { ret = t3_sge_init_flcntxt(adapter, q->fl[i].cntxt_id, 0, q->fl[i].phys_addr, q->fl[i].size, q->fl[i].buf_size - SGE_PG_RSVD, p->cong_thres, 1, 0); if (ret) goto err_unlock; } ret = t3_sge_init_ecntxt(adapter, q->txq[TXQ_ETH].cntxt_id, USE_GTS, SGE_CNTXT_ETH, id, q->txq[TXQ_ETH].phys_addr, q->txq[TXQ_ETH].size, q->txq[TXQ_ETH].token, 1, 0); if (ret) goto err_unlock; if (ntxq > 1) { ret = t3_sge_init_ecntxt(adapter, q->txq[TXQ_OFLD].cntxt_id, USE_GTS, SGE_CNTXT_OFLD, id, q->txq[TXQ_OFLD].phys_addr, q->txq[TXQ_OFLD].size, 0, 1, 0); if (ret) goto err_unlock; } if (ntxq > 2) { ret = t3_sge_init_ecntxt(adapter, q->txq[TXQ_CTRL].cntxt_id, 0, SGE_CNTXT_CTRL, id, q->txq[TXQ_CTRL].phys_addr, q->txq[TXQ_CTRL].size, q->txq[TXQ_CTRL].token, 1, 0); if (ret) goto err_unlock; } spin_unlock_irq(&adapter->sge.reg_lock); q->adap = adapter; q->netdev = dev; q->tx_q = netdevq; t3_update_qset_coalesce(q, p); avail = refill_fl(adapter, &q->fl[0], q->fl[0].size, GFP_KERNEL | __GFP_COMP); if (!avail) { CH_ALERT(adapter, "free list queue 0 initialization failed\n"); goto err; } if (avail < q->fl[0].size) CH_WARN(adapter, "free list queue 0 enabled with %d credits\n", avail); avail = refill_fl(adapter, &q->fl[1], q->fl[1].size, GFP_KERNEL | __GFP_COMP); if (avail < q->fl[1].size) CH_WARN(adapter, "free list queue 1 enabled with %d credits\n", avail); refill_rspq(adapter, &q->rspq, q->rspq.size - 1); t3_write_reg(adapter, A_SG_GTS, V_RSPQ(q->rspq.cntxt_id) | V_NEWTIMER(q->rspq.holdoff_tmr)); return 0; err_unlock: spin_unlock_irq(&adapter->sge.reg_lock); err: t3_free_qset(adapter, q); return ret; } /** * t3_start_sge_timers - start SGE timer call backs * @adap: the adapter * * Starts each SGE queue set's timer call back */ void t3_start_sge_timers(struct adapter *adap) { int i; for (i = 0; i < SGE_QSETS; ++i) { struct sge_qset *q = &adap->sge.qs[i]; if (q->tx_reclaim_timer.function) mod_timer(&q->tx_reclaim_timer, jiffies + TX_RECLAIM_PERIOD); if (q->rx_reclaim_timer.function) mod_timer(&q->rx_reclaim_timer, jiffies + RX_RECLAIM_PERIOD); } } /** * t3_stop_sge_timers - stop SGE timer call backs * @adap: the adapter * * Stops each SGE queue set's timer call back */ void t3_stop_sge_timers(struct adapter *adap) { int i; for (i = 0; i < SGE_QSETS; ++i) { struct sge_qset *q = &adap->sge.qs[i]; if (q->tx_reclaim_timer.function) del_timer_sync(&q->tx_reclaim_timer); if (q->rx_reclaim_timer.function) del_timer_sync(&q->rx_reclaim_timer); } } /** * t3_free_sge_resources - free SGE resources * @adap: the adapter * * Frees resources used by the SGE queue sets. */ void t3_free_sge_resources(struct adapter *adap) { int i; for (i = 0; i < SGE_QSETS; ++i) t3_free_qset(adap, &adap->sge.qs[i]); } /** * t3_sge_start - enable SGE * @adap: the adapter * * Enables the SGE for DMAs. This is the last step in starting packet * transfers. */ void t3_sge_start(struct adapter *adap) { t3_set_reg_field(adap, A_SG_CONTROL, F_GLOBALENABLE, F_GLOBALENABLE); } /** * t3_sge_stop - disable SGE operation * @adap: the adapter * * Disables the DMA engine. This can be called in emeregencies (e.g., * from error interrupts) or from normal process context. In the latter * case it also disables any pending queue restart tasklets. Note that * if it is called in interrupt context it cannot disable the restart * tasklets as it cannot wait, however the tasklets will have no effect * since the doorbells are disabled and the driver will call this again * later from process context, at which time the tasklets will be stopped * if they are still running. */ void t3_sge_stop(struct adapter *adap) { t3_set_reg_field(adap, A_SG_CONTROL, F_GLOBALENABLE, 0); if (!in_interrupt()) { int i; for (i = 0; i < SGE_QSETS; ++i) { struct sge_qset *qs = &adap->sge.qs[i]; tasklet_kill(&qs->txq[TXQ_OFLD].qresume_tsk); tasklet_kill(&qs->txq[TXQ_CTRL].qresume_tsk); } } } /** * t3_sge_init - initialize SGE * @adap: the adapter * @p: the SGE parameters * * Performs SGE initialization needed every time after a chip reset. * We do not initialize any of the queue sets here, instead the driver * top-level must request those individually. We also do not enable DMA * here, that should be done after the queues have been set up. */ void t3_sge_init(struct adapter *adap, struct sge_params *p) { unsigned int ctrl, ups = ffs(pci_resource_len(adap->pdev, 2) >> 12); ctrl = F_DROPPKT | V_PKTSHIFT(2) | F_FLMODE | F_AVOIDCQOVFL | F_CQCRDTCTRL | F_CONGMODE | F_TNLFLMODE | F_FATLPERREN | V_HOSTPAGESIZE(PAGE_SHIFT - 11) | F_BIGENDIANINGRESS | V_USERSPACESIZE(ups ? ups - 1 : 0) | F_ISCSICOALESCING; #if SGE_NUM_GENBITS == 1 ctrl |= F_EGRGENCTRL; #endif if (adap->params.rev > 0) { if (!(adap->flags & (USING_MSIX | USING_MSI))) ctrl |= F_ONEINTMULTQ | F_OPTONEINTMULTQ; } t3_write_reg(adap, A_SG_CONTROL, ctrl); t3_write_reg(adap, A_SG_EGR_RCQ_DRB_THRSH, V_HIRCQDRBTHRSH(512) | V_LORCQDRBTHRSH(512)); t3_write_reg(adap, A_SG_TIMER_TICK, core_ticks_per_usec(adap) / 10); t3_write_reg(adap, A_SG_CMDQ_CREDIT_TH, V_THRESHOLD(32) | V_TIMEOUT(200 * core_ticks_per_usec(adap))); t3_write_reg(adap, A_SG_HI_DRB_HI_THRSH, adap->params.rev < T3_REV_C ? 1000 : 500); t3_write_reg(adap, A_SG_HI_DRB_LO_THRSH, 256); t3_write_reg(adap, A_SG_LO_DRB_HI_THRSH, 1000); t3_write_reg(adap, A_SG_LO_DRB_LO_THRSH, 256); t3_write_reg(adap, A_SG_OCO_BASE, V_BASE1(0xfff)); t3_write_reg(adap, A_SG_DRB_PRI_THRESH, 63 * 1024); } /** * t3_sge_prep - one-time SGE initialization * @adap: the associated adapter * @p: SGE parameters * * Performs one-time initialization of SGE SW state. Includes determining * defaults for the assorted SGE parameters, which admins can change until * they are used to initialize the SGE. */ void t3_sge_prep(struct adapter *adap, struct sge_params *p) { int i; p->max_pkt_size = (16 * 1024) - sizeof(struct cpl_rx_data) - SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); for (i = 0; i < SGE_QSETS; ++i) { struct qset_params *q = p->qset + i; q->polling = adap->params.rev > 0; q->coalesce_usecs = 5; q->rspq_size = 1024; q->fl_size = 1024; q->jumbo_size = 512; q->txq_size[TXQ_ETH] = 1024; q->txq_size[TXQ_OFLD] = 1024; q->txq_size[TXQ_CTRL] = 256; q->cong_thres = 0; } spin_lock_init(&adap->sge.reg_lock); }
gpl-3.0
agate/shadowsocks-android
src/main/jni/iptables/extensions/libxt_osf.c
403
3652
/* * Copyright (c) 2003+ Evgeniy Polyakov <zbr@ioremap.net> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * xtables interface for OS fingerprint matching module. */ #include <stdio.h> #include <string.h> #include <xtables.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <linux/netfilter/xt_osf.h> enum { O_GENRE = 0, O_TTL, O_LOGLEVEL, }; static void osf_help(void) { printf("OS fingerprint match options:\n" "[!] --genre string Match a OS genre by passive fingerprinting.\n" "--ttl level Use some TTL check extensions to determine OS:\n" " 0 true ip and fingerprint TTL comparison. Works for LAN.\n" " 1 check if ip TTL is less than fingerprint one. Works for global addresses.\n" " 2 do not compare TTL at all. Allows to detect NMAP, but can produce false results.\n" "--log level Log determined genres into dmesg even if they do not match desired one:\n" " 0 log all matched or unknown signatures.\n" " 1 log only first one.\n" " 2 log all known matched signatures.\n" ); } #define s struct xt_osf_info static const struct xt_option_entry osf_opts[] = { {.name = "genre", .id = O_GENRE, .type = XTTYPE_STRING, .flags = XTOPT_MAND | XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, genre)}, {.name = "ttl", .id = O_TTL, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, ttl), .min = 0, .max = 2}, {.name = "log", .id = O_LOGLEVEL, .type = XTTYPE_UINT32, .flags = XTOPT_PUT, XTOPT_POINTER(s, loglevel), .min = 0, .max = 2}, XTOPT_TABLEEND, }; #undef s static void osf_parse(struct xt_option_call *cb) { struct xt_osf_info *info = cb->data; xtables_option_parse(cb); switch (cb->entry->id) { case O_GENRE: if (cb->invert) info->flags |= XT_OSF_INVERT; info->len = strlen(info->genre); break; case O_TTL: info->flags |= XT_OSF_TTL; break; case O_LOGLEVEL: info->flags |= XT_OSF_LOG; break; } } static void osf_print(const void *ip, const struct xt_entry_match *match, int numeric) { const struct xt_osf_info *info = (const struct xt_osf_info*) match->data; printf(" OS fingerprint match %s%s", (info->flags & XT_OSF_INVERT) ? "! " : "", info->genre); } static void osf_save(const void *ip, const struct xt_entry_match *match) { const struct xt_osf_info *info = (const struct xt_osf_info*) match->data; printf(" --genre %s%s", (info->flags & XT_OSF_INVERT) ? "! ": "", info->genre); } static struct xtables_match osf_match = { .name = "osf", .version = XTABLES_VERSION, .size = XT_ALIGN(sizeof(struct xt_osf_info)), .userspacesize = XT_ALIGN(sizeof(struct xt_osf_info)), .help = osf_help, .x6_parse = osf_parse, .print = osf_print, .save = osf_save, .x6_options = osf_opts, .family = NFPROTO_IPV4, }; void _init(void) { xtables_register_match(&osf_match); }
gpl-3.0
disdi/MMC-DMA-Linux-performance
linux-3.15-rc8/drivers/acpi/bgrt.c
1946
2810
/* * Copyright 2012 Red Hat, Inc <mjg@redhat.com> * Copyright 2012 Intel Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/device.h> #include <linux/sysfs.h> #include <linux/efi-bgrt.h> static struct kobject *bgrt_kobj; static ssize_t show_version(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", bgrt_tab->version); } static DEVICE_ATTR(version, S_IRUGO, show_version, NULL); static ssize_t show_status(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", bgrt_tab->status); } static DEVICE_ATTR(status, S_IRUGO, show_status, NULL); static ssize_t show_type(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", bgrt_tab->image_type); } static DEVICE_ATTR(type, S_IRUGO, show_type, NULL); static ssize_t show_xoffset(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", bgrt_tab->image_offset_x); } static DEVICE_ATTR(xoffset, S_IRUGO, show_xoffset, NULL); static ssize_t show_yoffset(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", bgrt_tab->image_offset_y); } static DEVICE_ATTR(yoffset, S_IRUGO, show_yoffset, NULL); static ssize_t image_read(struct file *file, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { memcpy(buf, attr->private + off, count); return count; } static BIN_ATTR_RO(image, 0); /* size gets filled in later */ static struct attribute *bgrt_attributes[] = { &dev_attr_version.attr, &dev_attr_status.attr, &dev_attr_type.attr, &dev_attr_xoffset.attr, &dev_attr_yoffset.attr, NULL, }; static struct bin_attribute *bgrt_bin_attributes[] = { &bin_attr_image, NULL, }; static struct attribute_group bgrt_attribute_group = { .attrs = bgrt_attributes, .bin_attrs = bgrt_bin_attributes, }; static int __init bgrt_init(void) { int ret; if (!bgrt_image) return -ENODEV; bin_attr_image.private = bgrt_image; bin_attr_image.size = bgrt_image_size; bgrt_kobj = kobject_create_and_add("bgrt", acpi_kobj); if (!bgrt_kobj) return -EINVAL; ret = sysfs_create_group(bgrt_kobj, &bgrt_attribute_group); if (ret) goto out_kobject; return 0; out_kobject: kobject_put(bgrt_kobj); return ret; } module_init(bgrt_init); MODULE_AUTHOR("Matthew Garrett, Josh Triplett <josh@joshtriplett.org>"); MODULE_DESCRIPTION("BGRT boot graphic support"); MODULE_LICENSE("GPL");
gpl-3.0
SamWanng/ShadowVPN-iOS
Pods/libsodium/src/libsodium/crypto_shorthash/siphash24/ref/shorthash_siphash24.c
412
2197
#include "api.h" #include "crypto_uint64.h" #include "crypto_uint32.h" #include "crypto_uint8.h" typedef crypto_uint64 u64; typedef crypto_uint32 u32; typedef crypto_uint8 u8; #define ROTL(x,b) (u64)( ((x) << (b)) | ( (x) >> (64 - (b))) ) #define U32TO8_LE(p, v) \ (p)[0] = (u8)((v) ); (p)[1] = (u8)((v) >> 8); \ (p)[2] = (u8)((v) >> 16); (p)[3] = (u8)((v) >> 24); #define U64TO8_LE(p, v) \ U32TO8_LE((p), (u32)((v) )); \ U32TO8_LE((p) + 4, (u32)((v) >> 32)); #define U8TO64_LE(p) \ (((u64)((p)[0]) ) | \ ((u64)((p)[1]) << 8) | \ ((u64)((p)[2]) << 16) | \ ((u64)((p)[3]) << 24) | \ ((u64)((p)[4]) << 32) | \ ((u64)((p)[5]) << 40) | \ ((u64)((p)[6]) << 48) | \ ((u64)((p)[7]) << 56)) #define SIPROUND \ do { \ v0 += v1; v1=ROTL(v1,13); v1 ^= v0; v0=ROTL(v0,32); \ v2 += v3; v3=ROTL(v3,16); v3 ^= v2; \ v0 += v3; v3=ROTL(v3,21); v3 ^= v0; \ v2 += v1; v1=ROTL(v1,17); v1 ^= v2; v2=ROTL(v2,32); \ } while(0) int crypto_shorthash(unsigned char *out,const unsigned char *in,unsigned long long inlen,const unsigned char *k) { /* "somepseudorandomlygeneratedbytes" */ u64 v0 = 0x736f6d6570736575ULL; u64 v1 = 0x646f72616e646f6dULL; u64 v2 = 0x6c7967656e657261ULL; u64 v3 = 0x7465646279746573ULL; u64 b; u64 k0 = U8TO64_LE( k ); u64 k1 = U8TO64_LE( k + 8 ); u64 m; const u8 *end = in + inlen - ( inlen % sizeof( u64 ) ); const int left = inlen & 7; b = ( ( u64 )inlen ) << 56; v3 ^= k1; v2 ^= k0; v1 ^= k1; v0 ^= k0; for ( ; in != end; in += 8 ) { m = U8TO64_LE( in ); v3 ^= m; SIPROUND; SIPROUND; v0 ^= m; } switch( left ) { case 7: b |= ( ( u64 )in[ 6] ) << 48; case 6: b |= ( ( u64 )in[ 5] ) << 40; case 5: b |= ( ( u64 )in[ 4] ) << 32; case 4: b |= ( ( u64 )in[ 3] ) << 24; case 3: b |= ( ( u64 )in[ 2] ) << 16; case 2: b |= ( ( u64 )in[ 1] ) << 8; case 1: b |= ( ( u64 )in[ 0] ); break; case 0: break; } v3 ^= b; SIPROUND; SIPROUND; v0 ^= b; v2 ^= 0xff; SIPROUND; SIPROUND; SIPROUND; SIPROUND; b = v0 ^ v1 ^ v2 ^ v3; U64TO8_LE( out, b ); return 0; }
gpl-3.0
SHAU-LOK/shadowsocks-android
src/main/jni/openssl/crypto/asn1/x_long.c
674
5845
/* x_long.c */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project 2000. */ /* ==================================================================== * Copyright (c) 2000 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/asn1t.h> #include <openssl/bn.h> /* Custom primitive type for long handling. This converts between an ASN1_INTEGER * and a long directly. */ static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it); static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it); static int long_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it); static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it); static int long_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx); static ASN1_PRIMITIVE_FUNCS long_pf = { NULL, 0, long_new, long_free, long_free, /* Clear should set to initial value */ long_c2i, long_i2c, long_print }; ASN1_ITEM_start(LONG) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &long_pf, ASN1_LONG_UNDEF, "LONG" ASN1_ITEM_end(LONG) ASN1_ITEM_start(ZLONG) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &long_pf, 0, "ZLONG" ASN1_ITEM_end(ZLONG) static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { *(long *)pval = it->size; return 1; } static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { *(long *)pval = it->size; } static int long_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it) { long ltmp; unsigned long utmp; int clen, pad, i; /* this exists to bypass broken gcc optimization */ char *cp = (char *)pval; /* use memcpy, because we may not be long aligned */ memcpy(&ltmp, cp, sizeof(long)); if(ltmp == it->size) return -1; /* Convert the long to positive: we subtract one if negative so * we can cleanly handle the padding if only the MSB of the leading * octet is set. */ if(ltmp < 0) utmp = -ltmp - 1; else utmp = ltmp; clen = BN_num_bits_word(utmp); /* If MSB of leading octet set we need to pad */ if(!(clen & 0x7)) pad = 1; else pad = 0; /* Convert number of bits to number of octets */ clen = (clen + 7) >> 3; if(cont) { if(pad) *cont++ = (ltmp < 0) ? 0xff : 0; for(i = clen - 1; i >= 0; i--) { cont[i] = (unsigned char)(utmp & 0xff); if(ltmp < 0) cont[i] ^= 0xff; utmp >>= 8; } } return clen + pad; } static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { int neg, i; long ltmp; unsigned long utmp = 0; char *cp = (char *)pval; if(len > (int)sizeof(long)) { ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } /* Is it negative? */ if(len && (cont[0] & 0x80)) neg = 1; else neg = 0; utmp = 0; for(i = 0; i < len; i++) { utmp <<= 8; if(neg) utmp |= cont[i] ^ 0xff; else utmp |= cont[i]; } ltmp = (long)utmp; if(neg) { ltmp++; ltmp = -ltmp; } if(ltmp == it->size) { ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } memcpy(cp, &ltmp, sizeof(long)); return 1; } static int long_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx) { return BIO_printf(out, "%ld\n", *(long *)pval); }
gpl-3.0
fatedier/studies
codis-2.0.13/extern/redis-2.8.21/deps/jemalloc/test/unit/rb.c
423
7430
#include "test/jemalloc_test.h" #define rbtn_black_height(a_type, a_field, a_rbt, r_height) do { \ a_type *rbp_bh_t; \ for (rbp_bh_t = (a_rbt)->rbt_root, (r_height) = 0; \ rbp_bh_t != &(a_rbt)->rbt_nil; \ rbp_bh_t = rbtn_left_get(a_type, a_field, rbp_bh_t)) { \ if (rbtn_red_get(a_type, a_field, rbp_bh_t) == false) { \ (r_height)++; \ } \ } \ } while (0) typedef struct node_s node_t; struct node_s { #define NODE_MAGIC 0x9823af7e uint32_t magic; rb_node(node_t) link; uint64_t key; }; static int node_cmp(node_t *a, node_t *b) { int ret; assert_u32_eq(a->magic, NODE_MAGIC, "Bad magic"); assert_u32_eq(b->magic, NODE_MAGIC, "Bad magic"); ret = (a->key > b->key) - (a->key < b->key); if (ret == 0) { /* * Duplicates are not allowed in the tree, so force an * arbitrary ordering for non-identical items with equal keys. */ ret = (((uintptr_t)a) > ((uintptr_t)b)) - (((uintptr_t)a) < ((uintptr_t)b)); } return (ret); } typedef rb_tree(node_t) tree_t; rb_gen(static, tree_, tree_t, node_t, link, node_cmp); TEST_BEGIN(test_rb_empty) { tree_t tree; node_t key; tree_new(&tree); assert_ptr_null(tree_first(&tree), "Unexpected node"); assert_ptr_null(tree_last(&tree), "Unexpected node"); key.key = 0; key.magic = NODE_MAGIC; assert_ptr_null(tree_search(&tree, &key), "Unexpected node"); key.key = 0; key.magic = NODE_MAGIC; assert_ptr_null(tree_nsearch(&tree, &key), "Unexpected node"); key.key = 0; key.magic = NODE_MAGIC; assert_ptr_null(tree_psearch(&tree, &key), "Unexpected node"); } TEST_END static unsigned tree_recurse(node_t *node, unsigned black_height, unsigned black_depth, node_t *nil) { unsigned ret = 0; node_t *left_node = rbtn_left_get(node_t, link, node); node_t *right_node = rbtn_right_get(node_t, link, node); if (rbtn_red_get(node_t, link, node) == false) black_depth++; /* Red nodes must be interleaved with black nodes. */ if (rbtn_red_get(node_t, link, node)) { assert_false(rbtn_red_get(node_t, link, left_node), "Node should be black"); assert_false(rbtn_red_get(node_t, link, right_node), "Node should be black"); } if (node == nil) return (ret); /* Self. */ assert_u32_eq(node->magic, NODE_MAGIC, "Bad magic"); /* Left subtree. */ if (left_node != nil) ret += tree_recurse(left_node, black_height, black_depth, nil); else ret += (black_depth != black_height); /* Right subtree. */ if (right_node != nil) ret += tree_recurse(right_node, black_height, black_depth, nil); else ret += (black_depth != black_height); return (ret); } static node_t * tree_iterate_cb(tree_t *tree, node_t *node, void *data) { unsigned *i = (unsigned *)data; node_t *search_node; assert_u32_eq(node->magic, NODE_MAGIC, "Bad magic"); /* Test rb_search(). */ search_node = tree_search(tree, node); assert_ptr_eq(search_node, node, "tree_search() returned unexpected node"); /* Test rb_nsearch(). */ search_node = tree_nsearch(tree, node); assert_ptr_eq(search_node, node, "tree_nsearch() returned unexpected node"); /* Test rb_psearch(). */ search_node = tree_psearch(tree, node); assert_ptr_eq(search_node, node, "tree_psearch() returned unexpected node"); (*i)++; return (NULL); } static unsigned tree_iterate(tree_t *tree) { unsigned i; i = 0; tree_iter(tree, NULL, tree_iterate_cb, (void *)&i); return (i); } static unsigned tree_iterate_reverse(tree_t *tree) { unsigned i; i = 0; tree_reverse_iter(tree, NULL, tree_iterate_cb, (void *)&i); return (i); } static void node_remove(tree_t *tree, node_t *node, unsigned nnodes) { node_t *search_node; unsigned black_height, imbalances; tree_remove(tree, node); /* Test rb_nsearch(). */ search_node = tree_nsearch(tree, node); if (search_node != NULL) { assert_u64_ge(search_node->key, node->key, "Key ordering error"); } /* Test rb_psearch(). */ search_node = tree_psearch(tree, node); if (search_node != NULL) { assert_u64_le(search_node->key, node->key, "Key ordering error"); } node->magic = 0; rbtn_black_height(node_t, link, tree, black_height); imbalances = tree_recurse(tree->rbt_root, black_height, 0, &(tree->rbt_nil)); assert_u_eq(imbalances, 0, "Tree is unbalanced"); assert_u_eq(tree_iterate(tree), nnodes-1, "Unexpected node iteration count"); assert_u_eq(tree_iterate_reverse(tree), nnodes-1, "Unexpected node iteration count"); } static node_t * remove_iterate_cb(tree_t *tree, node_t *node, void *data) { unsigned *nnodes = (unsigned *)data; node_t *ret = tree_next(tree, node); node_remove(tree, node, *nnodes); return (ret); } static node_t * remove_reverse_iterate_cb(tree_t *tree, node_t *node, void *data) { unsigned *nnodes = (unsigned *)data; node_t *ret = tree_prev(tree, node); node_remove(tree, node, *nnodes); return (ret); } TEST_BEGIN(test_rb_random) { #define NNODES 25 #define NBAGS 250 #define SEED 42 sfmt_t *sfmt; uint64_t bag[NNODES]; tree_t tree; node_t nodes[NNODES]; unsigned i, j, k, black_height, imbalances; sfmt = init_gen_rand(SEED); for (i = 0; i < NBAGS; i++) { switch (i) { case 0: /* Insert in order. */ for (j = 0; j < NNODES; j++) bag[j] = j; break; case 1: /* Insert in reverse order. */ for (j = 0; j < NNODES; j++) bag[j] = NNODES - j - 1; break; default: for (j = 0; j < NNODES; j++) bag[j] = gen_rand64_range(sfmt, NNODES); } for (j = 1; j <= NNODES; j++) { /* Initialize tree and nodes. */ tree_new(&tree); tree.rbt_nil.magic = 0; for (k = 0; k < j; k++) { nodes[k].magic = NODE_MAGIC; nodes[k].key = bag[k]; } /* Insert nodes. */ for (k = 0; k < j; k++) { tree_insert(&tree, &nodes[k]); rbtn_black_height(node_t, link, &tree, black_height); imbalances = tree_recurse(tree.rbt_root, black_height, 0, &(tree.rbt_nil)); assert_u_eq(imbalances, 0, "Tree is unbalanced"); assert_u_eq(tree_iterate(&tree), k+1, "Unexpected node iteration count"); assert_u_eq(tree_iterate_reverse(&tree), k+1, "Unexpected node iteration count"); assert_ptr_not_null(tree_first(&tree), "Tree should not be empty"); assert_ptr_not_null(tree_last(&tree), "Tree should not be empty"); tree_next(&tree, &nodes[k]); tree_prev(&tree, &nodes[k]); } /* Remove nodes. */ switch (i % 4) { case 0: for (k = 0; k < j; k++) node_remove(&tree, &nodes[k], j - k); break; case 1: for (k = j; k > 0; k--) node_remove(&tree, &nodes[k-1], k); break; case 2: { node_t *start; unsigned nnodes = j; start = NULL; do { start = tree_iter(&tree, start, remove_iterate_cb, (void *)&nnodes); nnodes--; } while (start != NULL); assert_u_eq(nnodes, 0, "Removal terminated early"); break; } case 3: { node_t *start; unsigned nnodes = j; start = NULL; do { start = tree_reverse_iter(&tree, start, remove_reverse_iterate_cb, (void *)&nnodes); nnodes--; } while (start != NULL); assert_u_eq(nnodes, 0, "Removal terminated early"); break; } default: not_reached(); } } } fini_gen_rand(sfmt); #undef NNODES #undef NBAGS #undef SEED } TEST_END int main(void) { return (test( test_rb_empty, test_rb_random)); }
gpl-3.0
CertifiedBlyndGuy/ewok-onyx
crypto/ahash.c
1215
13006
/* * Asynchronous Cryptographic Hash operations. * * This is the asynchronous version of hash.c with notification of * completion via a callback. * * Copyright (c) 2008 Loc Ho <lho@amcc.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/hash.h> #include <crypto/scatterwalk.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include "internal.h" struct ahash_request_priv { crypto_completion_t complete; void *data; u8 *result; void *ubuf[] CRYPTO_MINALIGN_ATTR; }; static inline struct ahash_alg *crypto_ahash_alg(struct crypto_ahash *hash) { return container_of(crypto_hash_alg_common(hash), struct ahash_alg, halg); } static int hash_walk_next(struct crypto_hash_walk *walk) { unsigned int alignmask = walk->alignmask; unsigned int offset = walk->offset; unsigned int nbytes = min(walk->entrylen, ((unsigned int)(PAGE_SIZE)) - offset); walk->data = kmap_atomic(walk->pg); walk->data += offset; if (offset & alignmask) { unsigned int unaligned = alignmask + 1 - (offset & alignmask); if (nbytes > unaligned) nbytes = unaligned; } walk->entrylen -= nbytes; return nbytes; } static int hash_walk_new_entry(struct crypto_hash_walk *walk) { struct scatterlist *sg; sg = walk->sg; walk->pg = sg_page(sg); walk->offset = sg->offset; walk->entrylen = sg->length; if (walk->entrylen > walk->total) walk->entrylen = walk->total; walk->total -= walk->entrylen; return hash_walk_next(walk); } int crypto_hash_walk_done(struct crypto_hash_walk *walk, int err) { unsigned int alignmask = walk->alignmask; unsigned int nbytes = walk->entrylen; walk->data -= walk->offset; if (nbytes && walk->offset & alignmask && !err) { walk->offset = ALIGN(walk->offset, alignmask + 1); walk->data += walk->offset; nbytes = min(nbytes, ((unsigned int)(PAGE_SIZE)) - walk->offset); walk->entrylen -= nbytes; return nbytes; } kunmap_atomic(walk->data); crypto_yield(walk->flags); if (err) return err; if (nbytes) { walk->offset = 0; walk->pg++; return hash_walk_next(walk); } if (!walk->total) return 0; walk->sg = scatterwalk_sg_next(walk->sg); return hash_walk_new_entry(walk); } EXPORT_SYMBOL_GPL(crypto_hash_walk_done); int crypto_hash_walk_first(struct ahash_request *req, struct crypto_hash_walk *walk) { walk->total = req->nbytes; if (!walk->total) return 0; walk->alignmask = crypto_ahash_alignmask(crypto_ahash_reqtfm(req)); walk->sg = req->src; walk->flags = req->base.flags; return hash_walk_new_entry(walk); } EXPORT_SYMBOL_GPL(crypto_hash_walk_first); int crypto_hash_walk_first_compat(struct hash_desc *hdesc, struct crypto_hash_walk *walk, struct scatterlist *sg, unsigned int len) { walk->total = len; if (!walk->total) return 0; walk->alignmask = crypto_hash_alignmask(hdesc->tfm); walk->sg = sg; walk->flags = hdesc->flags; return hash_walk_new_entry(walk); } static int ahash_setkey_unaligned(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { unsigned long alignmask = crypto_ahash_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_KERNEL); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = tfm->setkey(tfm, alignbuffer, keylen); kzfree(buffer); return ret; } int crypto_ahash_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { unsigned long alignmask = crypto_ahash_alignmask(tfm); if ((unsigned long)key & alignmask) return ahash_setkey_unaligned(tfm, key, keylen); return tfm->setkey(tfm, key, keylen); } EXPORT_SYMBOL_GPL(crypto_ahash_setkey); static int ahash_nosetkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { return -ENOSYS; } static inline unsigned int ahash_align_buffer_size(unsigned len, unsigned long mask) { return len + (mask & ~(crypto_tfm_ctx_alignment() - 1)); } static void ahash_op_unaligned_finish(struct ahash_request *req, int err) { struct ahash_request_priv *priv = req->priv; if (err == -EINPROGRESS) return; if (!err) memcpy(priv->result, req->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(req))); kzfree(priv); } static void ahash_op_unaligned_done(struct crypto_async_request *req, int err) { struct ahash_request *areq = req->data; struct ahash_request_priv *priv = areq->priv; crypto_completion_t complete = priv->complete; void *data = priv->data; ahash_op_unaligned_finish(areq, err); complete(data, err); } static int ahash_op_unaligned(struct ahash_request *req, int (*op)(struct ahash_request *)) { struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); unsigned long alignmask = crypto_ahash_alignmask(tfm); unsigned int ds = crypto_ahash_digestsize(tfm); struct ahash_request_priv *priv; int err; priv = kmalloc(sizeof(*priv) + ahash_align_buffer_size(ds, alignmask), (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP) ? GFP_KERNEL : GFP_ATOMIC); if (!priv) return -ENOMEM; priv->result = req->result; priv->complete = req->base.complete; priv->data = req->base.data; req->result = PTR_ALIGN((u8 *)priv->ubuf, alignmask + 1); req->base.complete = ahash_op_unaligned_done; req->base.data = req; req->priv = priv; err = op(req); ahash_op_unaligned_finish(req, err); return err; } static int crypto_ahash_op(struct ahash_request *req, int (*op)(struct ahash_request *)) { struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); unsigned long alignmask = crypto_ahash_alignmask(tfm); if ((unsigned long)req->result & alignmask) return ahash_op_unaligned(req, op); return op(req); } int crypto_ahash_final(struct ahash_request *req) { return crypto_ahash_op(req, crypto_ahash_reqtfm(req)->final); } EXPORT_SYMBOL_GPL(crypto_ahash_final); int crypto_ahash_finup(struct ahash_request *req) { return crypto_ahash_op(req, crypto_ahash_reqtfm(req)->finup); } EXPORT_SYMBOL_GPL(crypto_ahash_finup); int crypto_ahash_digest(struct ahash_request *req) { return crypto_ahash_op(req, crypto_ahash_reqtfm(req)->digest); } EXPORT_SYMBOL_GPL(crypto_ahash_digest); static void ahash_def_finup_finish2(struct ahash_request *req, int err) { struct ahash_request_priv *priv = req->priv; if (err == -EINPROGRESS) return; if (!err) memcpy(priv->result, req->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(req))); kzfree(priv); } static void ahash_def_finup_done2(struct crypto_async_request *req, int err) { struct ahash_request *areq = req->data; struct ahash_request_priv *priv = areq->priv; crypto_completion_t complete = priv->complete; void *data = priv->data; ahash_def_finup_finish2(areq, err); complete(data, err); } static int ahash_def_finup_finish1(struct ahash_request *req, int err) { if (err) goto out; req->base.complete = ahash_def_finup_done2; req->base.flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; err = crypto_ahash_reqtfm(req)->final(req); out: ahash_def_finup_finish2(req, err); return err; } static void ahash_def_finup_done1(struct crypto_async_request *req, int err) { struct ahash_request *areq = req->data; struct ahash_request_priv *priv = areq->priv; crypto_completion_t complete = priv->complete; void *data = priv->data; err = ahash_def_finup_finish1(areq, err); complete(data, err); } static int ahash_def_finup(struct ahash_request *req) { struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); unsigned long alignmask = crypto_ahash_alignmask(tfm); unsigned int ds = crypto_ahash_digestsize(tfm); struct ahash_request_priv *priv; priv = kmalloc(sizeof(*priv) + ahash_align_buffer_size(ds, alignmask), (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP) ? GFP_KERNEL : GFP_ATOMIC); if (!priv) return -ENOMEM; priv->result = req->result; priv->complete = req->base.complete; priv->data = req->base.data; req->result = PTR_ALIGN((u8 *)priv->ubuf, alignmask + 1); req->base.complete = ahash_def_finup_done1; req->base.data = req; req->priv = priv; return ahash_def_finup_finish1(req, tfm->update(req)); } static int ahash_no_export(struct ahash_request *req, void *out) { return -ENOSYS; } static int ahash_no_import(struct ahash_request *req, const void *in) { return -ENOSYS; } static int crypto_ahash_init_tfm(struct crypto_tfm *tfm) { struct crypto_ahash *hash = __crypto_ahash_cast(tfm); struct ahash_alg *alg = crypto_ahash_alg(hash); hash->setkey = ahash_nosetkey; hash->export = ahash_no_export; hash->import = ahash_no_import; if (tfm->__crt_alg->cra_type != &crypto_ahash_type) return crypto_init_shash_ops_async(tfm); hash->init = alg->init; hash->update = alg->update; hash->final = alg->final; hash->finup = alg->finup ?: ahash_def_finup; hash->digest = alg->digest; if (alg->setkey) hash->setkey = alg->setkey; if (alg->export) hash->export = alg->export; if (alg->import) hash->import = alg->import; return 0; } static unsigned int crypto_ahash_extsize(struct crypto_alg *alg) { if (alg->cra_type == &crypto_ahash_type) return alg->cra_ctxsize; return sizeof(struct crypto_shash *); } #ifdef CONFIG_NET static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_hash rhash; strncpy(rhash.type, "ahash", sizeof(rhash.type)); rhash.blocksize = alg->cra_blocksize; rhash.digestsize = __crypto_hash_alg_common(alg)->digestsize; NLA_PUT(skb, CRYPTOCFGA_REPORT_HASH, sizeof(struct crypto_report_hash), &rhash); return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_ahash_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_ahash_show(struct seq_file *m, struct crypto_alg *alg) { seq_printf(m, "type : ahash\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "digestsize : %u\n", __crypto_hash_alg_common(alg)->digestsize); } const struct crypto_type crypto_ahash_type = { .extsize = crypto_ahash_extsize, .init_tfm = crypto_ahash_init_tfm, #ifdef CONFIG_PROC_FS .show = crypto_ahash_show, #endif .report = crypto_ahash_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_AHASH_MASK, .type = CRYPTO_ALG_TYPE_AHASH, .tfmsize = offsetof(struct crypto_ahash, base), }; EXPORT_SYMBOL_GPL(crypto_ahash_type); struct crypto_ahash *crypto_alloc_ahash(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_ahash_type, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_ahash); static int ahash_prepare_alg(struct ahash_alg *alg) { struct crypto_alg *base = &alg->halg.base; if (alg->halg.digestsize > PAGE_SIZE / 8 || alg->halg.statesize > PAGE_SIZE / 8) return -EINVAL; base->cra_type = &crypto_ahash_type; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_AHASH; return 0; } int crypto_register_ahash(struct ahash_alg *alg) { struct crypto_alg *base = &alg->halg.base; int err; err = ahash_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_ahash); int crypto_unregister_ahash(struct ahash_alg *alg) { return crypto_unregister_alg(&alg->halg.base); } EXPORT_SYMBOL_GPL(crypto_unregister_ahash); int ahash_register_instance(struct crypto_template *tmpl, struct ahash_instance *inst) { int err; err = ahash_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, ahash_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(ahash_register_instance); void ahash_free_instance(struct crypto_instance *inst) { crypto_drop_spawn(crypto_instance_ctx(inst)); kfree(ahash_instance(inst)); } EXPORT_SYMBOL_GPL(ahash_free_instance); int crypto_init_ahash_spawn(struct crypto_ahash_spawn *spawn, struct hash_alg_common *alg, struct crypto_instance *inst) { return crypto_init_spawn2(&spawn->base, &alg->base, inst, &crypto_ahash_type); } EXPORT_SYMBOL_GPL(crypto_init_ahash_spawn); struct hash_alg_common *ahash_attr_alg(struct rtattr *rta, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_attr_alg2(rta, &crypto_ahash_type, type, mask); return IS_ERR(alg) ? ERR_CAST(alg) : __crypto_hash_alg_common(alg); } EXPORT_SYMBOL_GPL(ahash_attr_alg); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Asynchronous cryptographic hash type");
gpl-3.0
williamkosasih19/SM-T331-KERNEL-TOAD
drivers/net/wireless/orinoco/fw.c
5057
9917
/* Firmware file reading and download helpers * * See copyright notice in main.c */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/firmware.h> #include <linux/device.h> #include <linux/module.h> #include "hermes.h" #include "hermes_dld.h" #include "orinoco.h" #include "fw.h" /* End markers (for Symbol firmware only) */ #define TEXT_END 0x1A /* End of text header */ struct fw_info { char *pri_fw; char *sta_fw; char *ap_fw; u32 pda_addr; u16 pda_size; }; static const struct fw_info orinoco_fw[] = { { NULL, "agere_sta_fw.bin", "agere_ap_fw.bin", 0x00390000, 1000 }, { NULL, "prism_sta_fw.bin", "prism_ap_fw.bin", 0, 1024 }, { "symbol_sp24t_prim_fw", "symbol_sp24t_sec_fw", NULL, 0x00003100, 512 } }; MODULE_FIRMWARE("agere_sta_fw.bin"); MODULE_FIRMWARE("agere_ap_fw.bin"); MODULE_FIRMWARE("prism_sta_fw.bin"); MODULE_FIRMWARE("prism_ap_fw.bin"); MODULE_FIRMWARE("symbol_sp24t_prim_fw"); MODULE_FIRMWARE("symbol_sp24t_sec_fw"); /* Structure used to access fields in FW * Make sure LE decoding macros are used */ struct orinoco_fw_header { char hdr_vers[6]; /* ASCII string for header version */ __le16 headersize; /* Total length of header */ __le32 entry_point; /* NIC entry point */ __le32 blocks; /* Number of blocks to program */ __le32 block_offset; /* Offset of block data from eof header */ __le32 pdr_offset; /* Offset to PDR data from eof header */ __le32 pri_offset; /* Offset to primary plug data */ __le32 compat_offset; /* Offset to compatibility data*/ char signature[0]; /* FW signature length headersize-20 */ } __packed; /* Check the range of various header entries. Return a pointer to a * description of the problem, or NULL if everything checks out. */ static const char *validate_fw(const struct orinoco_fw_header *hdr, size_t len) { u16 hdrsize; if (len < sizeof(*hdr)) return "image too small"; if (memcmp(hdr->hdr_vers, "HFW", 3) != 0) return "format not recognised"; hdrsize = le16_to_cpu(hdr->headersize); if (hdrsize > len) return "bad headersize"; if ((hdrsize + le32_to_cpu(hdr->block_offset)) > len) return "bad block offset"; if ((hdrsize + le32_to_cpu(hdr->pdr_offset)) > len) return "bad PDR offset"; if ((hdrsize + le32_to_cpu(hdr->pri_offset)) > len) return "bad PRI offset"; if ((hdrsize + le32_to_cpu(hdr->compat_offset)) > len) return "bad compat offset"; /* TODO: consider adding a checksum or CRC to the firmware format */ return NULL; } #if defined(CONFIG_HERMES_CACHE_FW_ON_INIT) || defined(CONFIG_PM_SLEEP) static inline const struct firmware * orinoco_cached_fw_get(struct orinoco_private *priv, bool primary) { if (primary) return priv->cached_pri_fw; else return priv->cached_fw; } #else #define orinoco_cached_fw_get(priv, primary) (NULL) #endif /* Download either STA or AP firmware into the card. */ static int orinoco_dl_firmware(struct orinoco_private *priv, const struct fw_info *fw, int ap) { /* Plug Data Area (PDA) */ __le16 *pda; struct hermes *hw = &priv->hw; const struct firmware *fw_entry; const struct orinoco_fw_header *hdr; const unsigned char *first_block; const void *end; const char *firmware; const char *fw_err; struct device *dev = priv->dev; int err = 0; pda = kzalloc(fw->pda_size, GFP_KERNEL); if (!pda) return -ENOMEM; if (ap) firmware = fw->ap_fw; else firmware = fw->sta_fw; dev_dbg(dev, "Attempting to download firmware %s\n", firmware); /* Read current plug data */ err = hw->ops->read_pda(hw, pda, fw->pda_addr, fw->pda_size); dev_dbg(dev, "Read PDA returned %d\n", err); if (err) goto free; if (!orinoco_cached_fw_get(priv, false)) { err = request_firmware(&fw_entry, firmware, priv->dev); if (err) { dev_err(dev, "Cannot find firmware %s\n", firmware); err = -ENOENT; goto free; } } else fw_entry = orinoco_cached_fw_get(priv, false); hdr = (const struct orinoco_fw_header *) fw_entry->data; fw_err = validate_fw(hdr, fw_entry->size); if (fw_err) { dev_warn(dev, "Invalid firmware image detected (%s). " "Aborting download\n", fw_err); err = -EINVAL; goto abort; } /* Enable aux port to allow programming */ err = hw->ops->program_init(hw, le32_to_cpu(hdr->entry_point)); dev_dbg(dev, "Program init returned %d\n", err); if (err != 0) goto abort; /* Program data */ first_block = (fw_entry->data + le16_to_cpu(hdr->headersize) + le32_to_cpu(hdr->block_offset)); end = fw_entry->data + fw_entry->size; err = hermes_program(hw, first_block, end); dev_dbg(dev, "Program returned %d\n", err); if (err != 0) goto abort; /* Update production data */ first_block = (fw_entry->data + le16_to_cpu(hdr->headersize) + le32_to_cpu(hdr->pdr_offset)); err = hermes_apply_pda_with_defaults(hw, first_block, end, pda, &pda[fw->pda_size / sizeof(*pda)]); dev_dbg(dev, "Apply PDA returned %d\n", err); if (err) goto abort; /* Tell card we've finished */ err = hw->ops->program_end(hw); dev_dbg(dev, "Program end returned %d\n", err); if (err != 0) goto abort; /* Check if we're running */ dev_dbg(dev, "hermes_present returned %d\n", hermes_present(hw)); abort: /* If we requested the firmware, release it. */ if (!orinoco_cached_fw_get(priv, false)) release_firmware(fw_entry); free: kfree(pda); return err; } /* * Process a firmware image - stop the card, load the firmware, reset * the card and make sure it responds. For the secondary firmware take * care of the PDA - read it and then write it on top of the firmware. */ static int symbol_dl_image(struct orinoco_private *priv, const struct fw_info *fw, const unsigned char *image, const void *end, int secondary) { struct hermes *hw = &priv->hw; int ret = 0; const unsigned char *ptr; const unsigned char *first_block; /* Plug Data Area (PDA) */ __le16 *pda = NULL; /* Binary block begins after the 0x1A marker */ ptr = image; while (*ptr++ != TEXT_END); first_block = ptr; /* Read the PDA from EEPROM */ if (secondary) { pda = kzalloc(fw->pda_size, GFP_KERNEL); if (!pda) return -ENOMEM; ret = hw->ops->read_pda(hw, pda, fw->pda_addr, fw->pda_size); if (ret) goto free; } /* Stop the firmware, so that it can be safely rewritten */ if (priv->stop_fw) { ret = priv->stop_fw(priv, 1); if (ret) goto free; } /* Program the adapter with new firmware */ ret = hermes_program(hw, first_block, end); if (ret) goto free; /* Write the PDA to the adapter */ if (secondary) { size_t len = hermes_blocks_length(first_block, end); ptr = first_block + len; ret = hermes_apply_pda(hw, ptr, end, pda, &pda[fw->pda_size / sizeof(*pda)]); kfree(pda); if (ret) return ret; } /* Run the firmware */ if (priv->stop_fw) { ret = priv->stop_fw(priv, 0); if (ret) return ret; } /* Reset hermes chip and make sure it responds */ ret = hw->ops->init(hw); /* hermes_reset() should return 0 with the secondary firmware */ if (secondary && ret != 0) return -ENODEV; /* And this should work with any firmware */ if (!hermes_present(hw)) return -ENODEV; return 0; free: kfree(pda); return ret; } /* * Download the firmware into the card, this also does a PCMCIA soft * reset on the card, to make sure it's in a sane state. */ static int symbol_dl_firmware(struct orinoco_private *priv, const struct fw_info *fw) { struct device *dev = priv->dev; int ret; const struct firmware *fw_entry; if (!orinoco_cached_fw_get(priv, true)) { if (request_firmware(&fw_entry, fw->pri_fw, priv->dev) != 0) { dev_err(dev, "Cannot find firmware: %s\n", fw->pri_fw); return -ENOENT; } } else fw_entry = orinoco_cached_fw_get(priv, true); /* Load primary firmware */ ret = symbol_dl_image(priv, fw, fw_entry->data, fw_entry->data + fw_entry->size, 0); if (!orinoco_cached_fw_get(priv, true)) release_firmware(fw_entry); if (ret) { dev_err(dev, "Primary firmware download failed\n"); return ret; } if (!orinoco_cached_fw_get(priv, false)) { if (request_firmware(&fw_entry, fw->sta_fw, priv->dev) != 0) { dev_err(dev, "Cannot find firmware: %s\n", fw->sta_fw); return -ENOENT; } } else fw_entry = orinoco_cached_fw_get(priv, false); /* Load secondary firmware */ ret = symbol_dl_image(priv, fw, fw_entry->data, fw_entry->data + fw_entry->size, 1); if (!orinoco_cached_fw_get(priv, false)) release_firmware(fw_entry); if (ret) dev_err(dev, "Secondary firmware download failed\n"); return ret; } int orinoco_download(struct orinoco_private *priv) { int err = 0; /* Reload firmware */ switch (priv->firmware_type) { case FIRMWARE_TYPE_AGERE: /* case FIRMWARE_TYPE_INTERSIL: */ err = orinoco_dl_firmware(priv, &orinoco_fw[priv->firmware_type], 0); break; case FIRMWARE_TYPE_SYMBOL: err = symbol_dl_firmware(priv, &orinoco_fw[priv->firmware_type]); break; case FIRMWARE_TYPE_INTERSIL: break; } /* TODO: if we fail we probably need to reinitialise * the driver */ return err; } #if defined(CONFIG_HERMES_CACHE_FW_ON_INIT) || defined(CONFIG_PM_SLEEP) void orinoco_cache_fw(struct orinoco_private *priv, int ap) { const struct firmware *fw_entry = NULL; const char *pri_fw; const char *fw; pri_fw = orinoco_fw[priv->firmware_type].pri_fw; if (ap) fw = orinoco_fw[priv->firmware_type].ap_fw; else fw = orinoco_fw[priv->firmware_type].sta_fw; if (pri_fw) { if (request_firmware(&fw_entry, pri_fw, priv->dev) == 0) priv->cached_pri_fw = fw_entry; } if (fw) { if (request_firmware(&fw_entry, fw, priv->dev) == 0) priv->cached_fw = fw_entry; } } void orinoco_uncache_fw(struct orinoco_private *priv) { if (priv->cached_pri_fw) release_firmware(priv->cached_pri_fw); if (priv->cached_fw) release_firmware(priv->cached_fw); priv->cached_pri_fw = NULL; priv->cached_fw = NULL; } #endif
gpl-3.0
ganluo/shadowsocks-android
src/main/jni/openssl/crypto/engine/eng_table.c
714
10125
/* ==================================================================== * Copyright (c) 2001 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include "cryptlib.h" #include <openssl/evp.h> #include <openssl/lhash.h> #include "eng_int.h" /* The type of the items in the table */ typedef struct st_engine_pile { /* The 'nid' of this algorithm/mode */ int nid; /* ENGINEs that implement this algorithm/mode. */ STACK_OF(ENGINE) *sk; /* The default ENGINE to perform this algorithm/mode. */ ENGINE *funct; /* Zero if 'sk' is newer than the cached 'funct', non-zero otherwise */ int uptodate; } ENGINE_PILE; DECLARE_LHASH_OF(ENGINE_PILE); /* The type exposed in eng_int.h */ struct st_engine_table { LHASH_OF(ENGINE_PILE) piles; }; /* ENGINE_TABLE */ typedef struct st_engine_pile_doall { engine_table_doall_cb *cb; void *arg; } ENGINE_PILE_DOALL; /* Global flags (ENGINE_TABLE_FLAG_***). */ static unsigned int table_flags = 0; /* API function manipulating 'table_flags' */ unsigned int ENGINE_get_table_flags(void) { return table_flags; } void ENGINE_set_table_flags(unsigned int flags) { table_flags = flags; } /* Internal functions for the "piles" hash table */ static unsigned long engine_pile_hash(const ENGINE_PILE *c) { return c->nid; } static int engine_pile_cmp(const ENGINE_PILE *a, const ENGINE_PILE *b) { return a->nid - b->nid; } static IMPLEMENT_LHASH_HASH_FN(engine_pile, ENGINE_PILE) static IMPLEMENT_LHASH_COMP_FN(engine_pile, ENGINE_PILE) static int int_table_check(ENGINE_TABLE **t, int create) { LHASH_OF(ENGINE_PILE) *lh; if(*t) return 1; if(!create) return 0; if((lh = lh_ENGINE_PILE_new()) == NULL) return 0; *t = (ENGINE_TABLE *)lh; return 1; } /* Privately exposed (via eng_int.h) functions for adding and/or removing * ENGINEs from the implementation table */ int engine_table_register(ENGINE_TABLE **table, ENGINE_CLEANUP_CB *cleanup, ENGINE *e, const int *nids, int num_nids, int setdefault) { int ret = 0, added = 0; ENGINE_PILE tmplate, *fnd; CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); if(!(*table)) added = 1; if(!int_table_check(table, 1)) goto end; if(added) /* The cleanup callback needs to be added */ engine_cleanup_add_first(cleanup); while(num_nids--) { tmplate.nid = *nids; fnd = lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate); if(!fnd) { fnd = OPENSSL_malloc(sizeof(ENGINE_PILE)); if(!fnd) goto end; fnd->uptodate = 1; fnd->nid = *nids; fnd->sk = sk_ENGINE_new_null(); if(!fnd->sk) { OPENSSL_free(fnd); goto end; } fnd->funct = NULL; (void)lh_ENGINE_PILE_insert(&(*table)->piles, fnd); } /* A registration shouldn't add duplciate entries */ (void)sk_ENGINE_delete_ptr(fnd->sk, e); /* if 'setdefault', this ENGINE goes to the head of the list */ if(!sk_ENGINE_push(fnd->sk, e)) goto end; /* "touch" this ENGINE_PILE */ fnd->uptodate = 0; if(setdefault) { if(!engine_unlocked_init(e)) { ENGINEerr(ENGINE_F_ENGINE_TABLE_REGISTER, ENGINE_R_INIT_FAILED); goto end; } if(fnd->funct) engine_unlocked_finish(fnd->funct, 0); fnd->funct = e; fnd->uptodate = 1; } nids++; } ret = 1; end: CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); return ret; } static void int_unregister_cb_doall_arg(ENGINE_PILE *pile, ENGINE *e) { int n; /* Iterate the 'c->sk' stack removing any occurance of 'e' */ while((n = sk_ENGINE_find(pile->sk, e)) >= 0) { (void)sk_ENGINE_delete(pile->sk, n); pile->uptodate = 0; } if(pile->funct == e) { engine_unlocked_finish(e, 0); pile->funct = NULL; } } static IMPLEMENT_LHASH_DOALL_ARG_FN(int_unregister_cb, ENGINE_PILE, ENGINE) void engine_table_unregister(ENGINE_TABLE **table, ENGINE *e) { CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); if(int_table_check(table, 0)) lh_ENGINE_PILE_doall_arg(&(*table)->piles, LHASH_DOALL_ARG_FN(int_unregister_cb), ENGINE, e); CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); } static void int_cleanup_cb_doall(ENGINE_PILE *p) { sk_ENGINE_free(p->sk); if(p->funct) engine_unlocked_finish(p->funct, 0); OPENSSL_free(p); } static IMPLEMENT_LHASH_DOALL_FN(int_cleanup_cb, ENGINE_PILE) void engine_table_cleanup(ENGINE_TABLE **table) { CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); if(*table) { lh_ENGINE_PILE_doall(&(*table)->piles, LHASH_DOALL_FN(int_cleanup_cb)); lh_ENGINE_PILE_free(&(*table)->piles); *table = NULL; } CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); } /* return a functional reference for a given 'nid' */ #ifndef ENGINE_TABLE_DEBUG ENGINE *engine_table_select(ENGINE_TABLE **table, int nid) #else ENGINE *engine_table_select_tmp(ENGINE_TABLE **table, int nid, const char *f, int l) #endif { ENGINE *ret = NULL; ENGINE_PILE tmplate, *fnd=NULL; int initres, loop = 0; if(!(*table)) { #ifdef ENGINE_TABLE_DEBUG fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, nothing " "registered!\n", f, l, nid); #endif return NULL; } ERR_set_mark(); CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); /* Check again inside the lock otherwise we could race against cleanup * operations. But don't worry about a fprintf(stderr). */ if(!int_table_check(table, 0)) goto end; tmplate.nid = nid; fnd = lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate); if(!fnd) goto end; if(fnd->funct && engine_unlocked_init(fnd->funct)) { #ifdef ENGINE_TABLE_DEBUG fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, using " "ENGINE '%s' cached\n", f, l, nid, fnd->funct->id); #endif ret = fnd->funct; goto end; } if(fnd->uptodate) { ret = fnd->funct; goto end; } trynext: ret = sk_ENGINE_value(fnd->sk, loop++); if(!ret) { #ifdef ENGINE_TABLE_DEBUG fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, no " "registered implementations would initialise\n", f, l, nid); #endif goto end; } /* Try to initialise the ENGINE? */ if((ret->funct_ref > 0) || !(table_flags & ENGINE_TABLE_FLAG_NOINIT)) initres = engine_unlocked_init(ret); else initres = 0; if(initres) { /* Update 'funct' */ if((fnd->funct != ret) && engine_unlocked_init(ret)) { /* If there was a previous default we release it. */ if(fnd->funct) engine_unlocked_finish(fnd->funct, 0); fnd->funct = ret; #ifdef ENGINE_TABLE_DEBUG fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, " "setting default to '%s'\n", f, l, nid, ret->id); #endif } #ifdef ENGINE_TABLE_DEBUG fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, using " "newly initialised '%s'\n", f, l, nid, ret->id); #endif goto end; } goto trynext; end: /* If it failed, it is unlikely to succeed again until some future * registrations have taken place. In all cases, we cache. */ if(fnd) fnd->uptodate = 1; #ifdef ENGINE_TABLE_DEBUG if(ret) fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, caching " "ENGINE '%s'\n", f, l, nid, ret->id); else fprintf(stderr, "engine_table_dbg: %s:%d, nid=%d, caching " "'no matching ENGINE'\n", f, l, nid); #endif CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); /* Whatever happened, any failed init()s are not failures in this * context, so clear our error state. */ ERR_pop_to_mark(); return ret; } /* Table enumeration */ static void int_cb_doall_arg(ENGINE_PILE *pile, ENGINE_PILE_DOALL *dall) { dall->cb(pile->nid, pile->sk, pile->funct, dall->arg); } static IMPLEMENT_LHASH_DOALL_ARG_FN(int_cb, ENGINE_PILE,ENGINE_PILE_DOALL) void engine_table_doall(ENGINE_TABLE *table, engine_table_doall_cb *cb, void *arg) { ENGINE_PILE_DOALL dall; dall.cb = cb; dall.arg = arg; lh_ENGINE_PILE_doall_arg(&table->piles, LHASH_DOALL_ARG_FN(int_cb), ENGINE_PILE_DOALL, &dall); }
gpl-3.0
bwrenn/dart-mx6-linux-2.6-imx
fs/dlm/lock.c
1229
161379
/****************************************************************************** ******************************************************************************* ** ** Copyright (C) 2005-2010 Red Hat, Inc. All rights reserved. ** ** This copyrighted material is made available to anyone wishing to use, ** modify, copy, or redistribute it subject to the terms and conditions ** of the GNU General Public License v.2. ** ******************************************************************************* ******************************************************************************/ /* Central locking logic has four stages: dlm_lock() dlm_unlock() request_lock(ls, lkb) convert_lock(ls, lkb) unlock_lock(ls, lkb) cancel_lock(ls, lkb) _request_lock(r, lkb) _convert_lock(r, lkb) _unlock_lock(r, lkb) _cancel_lock(r, lkb) do_request(r, lkb) do_convert(r, lkb) do_unlock(r, lkb) do_cancel(r, lkb) Stage 1 (lock, unlock) is mainly about checking input args and splitting into one of the four main operations: dlm_lock = request_lock dlm_lock+CONVERT = convert_lock dlm_unlock = unlock_lock dlm_unlock+CANCEL = cancel_lock Stage 2, xxxx_lock(), just finds and locks the relevant rsb which is provided to the next stage. Stage 3, _xxxx_lock(), determines if the operation is local or remote. When remote, it calls send_xxxx(), when local it calls do_xxxx(). Stage 4, do_xxxx(), is the guts of the operation. It manipulates the given rsb and lkb and queues callbacks. For remote operations, send_xxxx() results in the corresponding do_xxxx() function being executed on the remote node. The connecting send/receive calls on local (L) and remote (R) nodes: L: send_xxxx() -> R: receive_xxxx() R: do_xxxx() L: receive_xxxx_reply() <- R: send_xxxx_reply() */ #include <linux/types.h> #include <linux/rbtree.h> #include <linux/slab.h> #include "dlm_internal.h" #include <linux/dlm_device.h> #include "memory.h" #include "lowcomms.h" #include "requestqueue.h" #include "util.h" #include "dir.h" #include "member.h" #include "lockspace.h" #include "ast.h" #include "lock.h" #include "rcom.h" #include "recover.h" #include "lvb_table.h" #include "user.h" #include "config.h" static int send_request(struct dlm_rsb *r, struct dlm_lkb *lkb); static int send_convert(struct dlm_rsb *r, struct dlm_lkb *lkb); static int send_unlock(struct dlm_rsb *r, struct dlm_lkb *lkb); static int send_cancel(struct dlm_rsb *r, struct dlm_lkb *lkb); static int send_grant(struct dlm_rsb *r, struct dlm_lkb *lkb); static int send_bast(struct dlm_rsb *r, struct dlm_lkb *lkb, int mode); static int send_lookup(struct dlm_rsb *r, struct dlm_lkb *lkb); static int send_remove(struct dlm_rsb *r); static int _request_lock(struct dlm_rsb *r, struct dlm_lkb *lkb); static int _cancel_lock(struct dlm_rsb *r, struct dlm_lkb *lkb); static void __receive_convert_reply(struct dlm_rsb *r, struct dlm_lkb *lkb, struct dlm_message *ms); static int receive_extralen(struct dlm_message *ms); static void do_purge(struct dlm_ls *ls, int nodeid, int pid); static void del_timeout(struct dlm_lkb *lkb); static void toss_rsb(struct kref *kref); /* * Lock compatibilty matrix - thanks Steve * UN = Unlocked state. Not really a state, used as a flag * PD = Padding. Used to make the matrix a nice power of two in size * Other states are the same as the VMS DLM. * Usage: matrix[grmode+1][rqmode+1] (although m[rq+1][gr+1] is the same) */ static const int __dlm_compat_matrix[8][8] = { /* UN NL CR CW PR PW EX PD */ {1, 1, 1, 1, 1, 1, 1, 0}, /* UN */ {1, 1, 1, 1, 1, 1, 1, 0}, /* NL */ {1, 1, 1, 1, 1, 1, 0, 0}, /* CR */ {1, 1, 1, 1, 0, 0, 0, 0}, /* CW */ {1, 1, 1, 0, 1, 0, 0, 0}, /* PR */ {1, 1, 1, 0, 0, 0, 0, 0}, /* PW */ {1, 1, 0, 0, 0, 0, 0, 0}, /* EX */ {0, 0, 0, 0, 0, 0, 0, 0} /* PD */ }; /* * This defines the direction of transfer of LVB data. * Granted mode is the row; requested mode is the column. * Usage: matrix[grmode+1][rqmode+1] * 1 = LVB is returned to the caller * 0 = LVB is written to the resource * -1 = nothing happens to the LVB */ const int dlm_lvb_operations[8][8] = { /* UN NL CR CW PR PW EX PD*/ { -1, 1, 1, 1, 1, 1, 1, -1 }, /* UN */ { -1, 1, 1, 1, 1, 1, 1, 0 }, /* NL */ { -1, -1, 1, 1, 1, 1, 1, 0 }, /* CR */ { -1, -1, -1, 1, 1, 1, 1, 0 }, /* CW */ { -1, -1, -1, -1, 1, 1, 1, 0 }, /* PR */ { -1, 0, 0, 0, 0, 0, 1, 0 }, /* PW */ { -1, 0, 0, 0, 0, 0, 0, 0 }, /* EX */ { -1, 0, 0, 0, 0, 0, 0, 0 } /* PD */ }; #define modes_compat(gr, rq) \ __dlm_compat_matrix[(gr)->lkb_grmode + 1][(rq)->lkb_rqmode + 1] int dlm_modes_compat(int mode1, int mode2) { return __dlm_compat_matrix[mode1 + 1][mode2 + 1]; } /* * Compatibility matrix for conversions with QUECVT set. * Granted mode is the row; requested mode is the column. * Usage: matrix[grmode+1][rqmode+1] */ static const int __quecvt_compat_matrix[8][8] = { /* UN NL CR CW PR PW EX PD */ {0, 0, 0, 0, 0, 0, 0, 0}, /* UN */ {0, 0, 1, 1, 1, 1, 1, 0}, /* NL */ {0, 0, 0, 1, 1, 1, 1, 0}, /* CR */ {0, 0, 0, 0, 1, 1, 1, 0}, /* CW */ {0, 0, 0, 1, 0, 1, 1, 0}, /* PR */ {0, 0, 0, 0, 0, 0, 1, 0}, /* PW */ {0, 0, 0, 0, 0, 0, 0, 0}, /* EX */ {0, 0, 0, 0, 0, 0, 0, 0} /* PD */ }; void dlm_print_lkb(struct dlm_lkb *lkb) { printk(KERN_ERR "lkb: nodeid %d id %x remid %x exflags %x flags %x " "sts %d rq %d gr %d wait_type %d wait_nodeid %d seq %llu\n", lkb->lkb_nodeid, lkb->lkb_id, lkb->lkb_remid, lkb->lkb_exflags, lkb->lkb_flags, lkb->lkb_status, lkb->lkb_rqmode, lkb->lkb_grmode, lkb->lkb_wait_type, lkb->lkb_wait_nodeid, (unsigned long long)lkb->lkb_recover_seq); } static void dlm_print_rsb(struct dlm_rsb *r) { printk(KERN_ERR "rsb: nodeid %d master %d dir %d flags %lx first %x " "rlc %d name %s\n", r->res_nodeid, r->res_master_nodeid, r->res_dir_nodeid, r->res_flags, r->res_first_lkid, r->res_recover_locks_count, r->res_name); } void dlm_dump_rsb(struct dlm_rsb *r) { struct dlm_lkb *lkb; dlm_print_rsb(r); printk(KERN_ERR "rsb: root_list empty %d recover_list empty %d\n", list_empty(&r->res_root_list), list_empty(&r->res_recover_list)); printk(KERN_ERR "rsb lookup list\n"); list_for_each_entry(lkb, &r->res_lookup, lkb_rsb_lookup) dlm_print_lkb(lkb); printk(KERN_ERR "rsb grant queue:\n"); list_for_each_entry(lkb, &r->res_grantqueue, lkb_statequeue) dlm_print_lkb(lkb); printk(KERN_ERR "rsb convert queue:\n"); list_for_each_entry(lkb, &r->res_convertqueue, lkb_statequeue) dlm_print_lkb(lkb); printk(KERN_ERR "rsb wait queue:\n"); list_for_each_entry(lkb, &r->res_waitqueue, lkb_statequeue) dlm_print_lkb(lkb); } /* Threads cannot use the lockspace while it's being recovered */ static inline void dlm_lock_recovery(struct dlm_ls *ls) { down_read(&ls->ls_in_recovery); } void dlm_unlock_recovery(struct dlm_ls *ls) { up_read(&ls->ls_in_recovery); } int dlm_lock_recovery_try(struct dlm_ls *ls) { return down_read_trylock(&ls->ls_in_recovery); } static inline int can_be_queued(struct dlm_lkb *lkb) { return !(lkb->lkb_exflags & DLM_LKF_NOQUEUE); } static inline int force_blocking_asts(struct dlm_lkb *lkb) { return (lkb->lkb_exflags & DLM_LKF_NOQUEUEBAST); } static inline int is_demoted(struct dlm_lkb *lkb) { return (lkb->lkb_sbflags & DLM_SBF_DEMOTED); } static inline int is_altmode(struct dlm_lkb *lkb) { return (lkb->lkb_sbflags & DLM_SBF_ALTMODE); } static inline int is_granted(struct dlm_lkb *lkb) { return (lkb->lkb_status == DLM_LKSTS_GRANTED); } static inline int is_remote(struct dlm_rsb *r) { DLM_ASSERT(r->res_nodeid >= 0, dlm_print_rsb(r);); return !!r->res_nodeid; } static inline int is_process_copy(struct dlm_lkb *lkb) { return (lkb->lkb_nodeid && !(lkb->lkb_flags & DLM_IFL_MSTCPY)); } static inline int is_master_copy(struct dlm_lkb *lkb) { return (lkb->lkb_flags & DLM_IFL_MSTCPY) ? 1 : 0; } static inline int middle_conversion(struct dlm_lkb *lkb) { if ((lkb->lkb_grmode==DLM_LOCK_PR && lkb->lkb_rqmode==DLM_LOCK_CW) || (lkb->lkb_rqmode==DLM_LOCK_PR && lkb->lkb_grmode==DLM_LOCK_CW)) return 1; return 0; } static inline int down_conversion(struct dlm_lkb *lkb) { return (!middle_conversion(lkb) && lkb->lkb_rqmode < lkb->lkb_grmode); } static inline int is_overlap_unlock(struct dlm_lkb *lkb) { return lkb->lkb_flags & DLM_IFL_OVERLAP_UNLOCK; } static inline int is_overlap_cancel(struct dlm_lkb *lkb) { return lkb->lkb_flags & DLM_IFL_OVERLAP_CANCEL; } static inline int is_overlap(struct dlm_lkb *lkb) { return (lkb->lkb_flags & (DLM_IFL_OVERLAP_UNLOCK | DLM_IFL_OVERLAP_CANCEL)); } static void queue_cast(struct dlm_rsb *r, struct dlm_lkb *lkb, int rv) { if (is_master_copy(lkb)) return; del_timeout(lkb); DLM_ASSERT(lkb->lkb_lksb, dlm_print_lkb(lkb);); /* if the operation was a cancel, then return -DLM_ECANCEL, if a timeout caused the cancel then return -ETIMEDOUT */ if (rv == -DLM_ECANCEL && (lkb->lkb_flags & DLM_IFL_TIMEOUT_CANCEL)) { lkb->lkb_flags &= ~DLM_IFL_TIMEOUT_CANCEL; rv = -ETIMEDOUT; } if (rv == -DLM_ECANCEL && (lkb->lkb_flags & DLM_IFL_DEADLOCK_CANCEL)) { lkb->lkb_flags &= ~DLM_IFL_DEADLOCK_CANCEL; rv = -EDEADLK; } dlm_add_cb(lkb, DLM_CB_CAST, lkb->lkb_grmode, rv, lkb->lkb_sbflags); } static inline void queue_cast_overlap(struct dlm_rsb *r, struct dlm_lkb *lkb) { queue_cast(r, lkb, is_overlap_unlock(lkb) ? -DLM_EUNLOCK : -DLM_ECANCEL); } static void queue_bast(struct dlm_rsb *r, struct dlm_lkb *lkb, int rqmode) { if (is_master_copy(lkb)) { send_bast(r, lkb, rqmode); } else { dlm_add_cb(lkb, DLM_CB_BAST, rqmode, 0, 0); } } /* * Basic operations on rsb's and lkb's */ /* This is only called to add a reference when the code already holds a valid reference to the rsb, so there's no need for locking. */ static inline void hold_rsb(struct dlm_rsb *r) { kref_get(&r->res_ref); } void dlm_hold_rsb(struct dlm_rsb *r) { hold_rsb(r); } /* When all references to the rsb are gone it's transferred to the tossed list for later disposal. */ static void put_rsb(struct dlm_rsb *r) { struct dlm_ls *ls = r->res_ls; uint32_t bucket = r->res_bucket; spin_lock(&ls->ls_rsbtbl[bucket].lock); kref_put(&r->res_ref, toss_rsb); spin_unlock(&ls->ls_rsbtbl[bucket].lock); } void dlm_put_rsb(struct dlm_rsb *r) { put_rsb(r); } static int pre_rsb_struct(struct dlm_ls *ls) { struct dlm_rsb *r1, *r2; int count = 0; spin_lock(&ls->ls_new_rsb_spin); if (ls->ls_new_rsb_count > dlm_config.ci_new_rsb_count / 2) { spin_unlock(&ls->ls_new_rsb_spin); return 0; } spin_unlock(&ls->ls_new_rsb_spin); r1 = dlm_allocate_rsb(ls); r2 = dlm_allocate_rsb(ls); spin_lock(&ls->ls_new_rsb_spin); if (r1) { list_add(&r1->res_hashchain, &ls->ls_new_rsb); ls->ls_new_rsb_count++; } if (r2) { list_add(&r2->res_hashchain, &ls->ls_new_rsb); ls->ls_new_rsb_count++; } count = ls->ls_new_rsb_count; spin_unlock(&ls->ls_new_rsb_spin); if (!count) return -ENOMEM; return 0; } /* If ls->ls_new_rsb is empty, return -EAGAIN, so the caller can unlock any spinlocks, go back and call pre_rsb_struct again. Otherwise, take an rsb off the list and return it. */ static int get_rsb_struct(struct dlm_ls *ls, char *name, int len, struct dlm_rsb **r_ret) { struct dlm_rsb *r; int count; spin_lock(&ls->ls_new_rsb_spin); if (list_empty(&ls->ls_new_rsb)) { count = ls->ls_new_rsb_count; spin_unlock(&ls->ls_new_rsb_spin); log_debug(ls, "find_rsb retry %d %d %s", count, dlm_config.ci_new_rsb_count, name); return -EAGAIN; } r = list_first_entry(&ls->ls_new_rsb, struct dlm_rsb, res_hashchain); list_del(&r->res_hashchain); /* Convert the empty list_head to a NULL rb_node for tree usage: */ memset(&r->res_hashnode, 0, sizeof(struct rb_node)); ls->ls_new_rsb_count--; spin_unlock(&ls->ls_new_rsb_spin); r->res_ls = ls; r->res_length = len; memcpy(r->res_name, name, len); mutex_init(&r->res_mutex); INIT_LIST_HEAD(&r->res_lookup); INIT_LIST_HEAD(&r->res_grantqueue); INIT_LIST_HEAD(&r->res_convertqueue); INIT_LIST_HEAD(&r->res_waitqueue); INIT_LIST_HEAD(&r->res_root_list); INIT_LIST_HEAD(&r->res_recover_list); *r_ret = r; return 0; } static int rsb_cmp(struct dlm_rsb *r, const char *name, int nlen) { char maxname[DLM_RESNAME_MAXLEN]; memset(maxname, 0, DLM_RESNAME_MAXLEN); memcpy(maxname, name, nlen); return memcmp(r->res_name, maxname, DLM_RESNAME_MAXLEN); } int dlm_search_rsb_tree(struct rb_root *tree, char *name, int len, struct dlm_rsb **r_ret) { struct rb_node *node = tree->rb_node; struct dlm_rsb *r; int rc; while (node) { r = rb_entry(node, struct dlm_rsb, res_hashnode); rc = rsb_cmp(r, name, len); if (rc < 0) node = node->rb_left; else if (rc > 0) node = node->rb_right; else goto found; } *r_ret = NULL; return -EBADR; found: *r_ret = r; return 0; } static int rsb_insert(struct dlm_rsb *rsb, struct rb_root *tree) { struct rb_node **newn = &tree->rb_node; struct rb_node *parent = NULL; int rc; while (*newn) { struct dlm_rsb *cur = rb_entry(*newn, struct dlm_rsb, res_hashnode); parent = *newn; rc = rsb_cmp(cur, rsb->res_name, rsb->res_length); if (rc < 0) newn = &parent->rb_left; else if (rc > 0) newn = &parent->rb_right; else { log_print("rsb_insert match"); dlm_dump_rsb(rsb); dlm_dump_rsb(cur); return -EEXIST; } } rb_link_node(&rsb->res_hashnode, parent, newn); rb_insert_color(&rsb->res_hashnode, tree); return 0; } /* * Find rsb in rsbtbl and potentially create/add one * * Delaying the release of rsb's has a similar benefit to applications keeping * NL locks on an rsb, but without the guarantee that the cached master value * will still be valid when the rsb is reused. Apps aren't always smart enough * to keep NL locks on an rsb that they may lock again shortly; this can lead * to excessive master lookups and removals if we don't delay the release. * * Searching for an rsb means looking through both the normal list and toss * list. When found on the toss list the rsb is moved to the normal list with * ref count of 1; when found on normal list the ref count is incremented. * * rsb's on the keep list are being used locally and refcounted. * rsb's on the toss list are not being used locally, and are not refcounted. * * The toss list rsb's were either * - previously used locally but not any more (were on keep list, then * moved to toss list when last refcount dropped) * - created and put on toss list as a directory record for a lookup * (we are the dir node for the res, but are not using the res right now, * but some other node is) * * The purpose of find_rsb() is to return a refcounted rsb for local use. * So, if the given rsb is on the toss list, it is moved to the keep list * before being returned. * * toss_rsb() happens when all local usage of the rsb is done, i.e. no * more refcounts exist, so the rsb is moved from the keep list to the * toss list. * * rsb's on both keep and toss lists are used for doing a name to master * lookups. rsb's that are in use locally (and being refcounted) are on * the keep list, rsb's that are not in use locally (not refcounted) and * only exist for name/master lookups are on the toss list. * * rsb's on the toss list who's dir_nodeid is not local can have stale * name/master mappings. So, remote requests on such rsb's can potentially * return with an error, which means the mapping is stale and needs to * be updated with a new lookup. (The idea behind MASTER UNCERTAIN and * first_lkid is to keep only a single outstanding request on an rsb * while that rsb has a potentially stale master.) */ static int find_rsb_dir(struct dlm_ls *ls, char *name, int len, uint32_t hash, uint32_t b, int dir_nodeid, int from_nodeid, unsigned int flags, struct dlm_rsb **r_ret) { struct dlm_rsb *r = NULL; int our_nodeid = dlm_our_nodeid(); int from_local = 0; int from_other = 0; int from_dir = 0; int create = 0; int error; if (flags & R_RECEIVE_REQUEST) { if (from_nodeid == dir_nodeid) from_dir = 1; else from_other = 1; } else if (flags & R_REQUEST) { from_local = 1; } /* * flags & R_RECEIVE_RECOVER is from dlm_recover_master_copy, so * from_nodeid has sent us a lock in dlm_recover_locks, believing * we're the new master. Our local recovery may not have set * res_master_nodeid to our_nodeid yet, so allow either. Don't * create the rsb; dlm_recover_process_copy() will handle EBADR * by resending. * * If someone sends us a request, we are the dir node, and we do * not find the rsb anywhere, then recreate it. This happens if * someone sends us a request after we have removed/freed an rsb * from our toss list. (They sent a request instead of lookup * because they are using an rsb from their toss list.) */ if (from_local || from_dir || (from_other && (dir_nodeid == our_nodeid))) { create = 1; } retry: if (create) { error = pre_rsb_struct(ls); if (error < 0) goto out; } spin_lock(&ls->ls_rsbtbl[b].lock); error = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].keep, name, len, &r); if (error) goto do_toss; /* * rsb is active, so we can't check master_nodeid without lock_rsb. */ kref_get(&r->res_ref); error = 0; goto out_unlock; do_toss: error = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].toss, name, len, &r); if (error) goto do_new; /* * rsb found inactive (master_nodeid may be out of date unless * we are the dir_nodeid or were the master) No other thread * is using this rsb because it's on the toss list, so we can * look at or update res_master_nodeid without lock_rsb. */ if ((r->res_master_nodeid != our_nodeid) && from_other) { /* our rsb was not master, and another node (not the dir node) has sent us a request */ log_debug(ls, "find_rsb toss from_other %d master %d dir %d %s", from_nodeid, r->res_master_nodeid, dir_nodeid, r->res_name); error = -ENOTBLK; goto out_unlock; } if ((r->res_master_nodeid != our_nodeid) && from_dir) { /* don't think this should ever happen */ log_error(ls, "find_rsb toss from_dir %d master %d", from_nodeid, r->res_master_nodeid); dlm_print_rsb(r); /* fix it and go on */ r->res_master_nodeid = our_nodeid; r->res_nodeid = 0; rsb_clear_flag(r, RSB_MASTER_UNCERTAIN); r->res_first_lkid = 0; } if (from_local && (r->res_master_nodeid != our_nodeid)) { /* Because we have held no locks on this rsb, res_master_nodeid could have become stale. */ rsb_set_flag(r, RSB_MASTER_UNCERTAIN); r->res_first_lkid = 0; } rb_erase(&r->res_hashnode, &ls->ls_rsbtbl[b].toss); error = rsb_insert(r, &ls->ls_rsbtbl[b].keep); goto out_unlock; do_new: /* * rsb not found */ if (error == -EBADR && !create) goto out_unlock; error = get_rsb_struct(ls, name, len, &r); if (error == -EAGAIN) { spin_unlock(&ls->ls_rsbtbl[b].lock); goto retry; } if (error) goto out_unlock; r->res_hash = hash; r->res_bucket = b; r->res_dir_nodeid = dir_nodeid; kref_init(&r->res_ref); if (from_dir) { /* want to see how often this happens */ log_debug(ls, "find_rsb new from_dir %d recreate %s", from_nodeid, r->res_name); r->res_master_nodeid = our_nodeid; r->res_nodeid = 0; goto out_add; } if (from_other && (dir_nodeid != our_nodeid)) { /* should never happen */ log_error(ls, "find_rsb new from_other %d dir %d our %d %s", from_nodeid, dir_nodeid, our_nodeid, r->res_name); dlm_free_rsb(r); r = NULL; error = -ENOTBLK; goto out_unlock; } if (from_other) { log_debug(ls, "find_rsb new from_other %d dir %d %s", from_nodeid, dir_nodeid, r->res_name); } if (dir_nodeid == our_nodeid) { /* When we are the dir nodeid, we can set the master node immediately */ r->res_master_nodeid = our_nodeid; r->res_nodeid = 0; } else { /* set_master will send_lookup to dir_nodeid */ r->res_master_nodeid = 0; r->res_nodeid = -1; } out_add: error = rsb_insert(r, &ls->ls_rsbtbl[b].keep); out_unlock: spin_unlock(&ls->ls_rsbtbl[b].lock); out: *r_ret = r; return error; } /* During recovery, other nodes can send us new MSTCPY locks (from dlm_recover_locks) before we've made ourself master (in dlm_recover_masters). */ static int find_rsb_nodir(struct dlm_ls *ls, char *name, int len, uint32_t hash, uint32_t b, int dir_nodeid, int from_nodeid, unsigned int flags, struct dlm_rsb **r_ret) { struct dlm_rsb *r = NULL; int our_nodeid = dlm_our_nodeid(); int recover = (flags & R_RECEIVE_RECOVER); int error; retry: error = pre_rsb_struct(ls); if (error < 0) goto out; spin_lock(&ls->ls_rsbtbl[b].lock); error = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].keep, name, len, &r); if (error) goto do_toss; /* * rsb is active, so we can't check master_nodeid without lock_rsb. */ kref_get(&r->res_ref); goto out_unlock; do_toss: error = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].toss, name, len, &r); if (error) goto do_new; /* * rsb found inactive. No other thread is using this rsb because * it's on the toss list, so we can look at or update * res_master_nodeid without lock_rsb. */ if (!recover && (r->res_master_nodeid != our_nodeid) && from_nodeid) { /* our rsb is not master, and another node has sent us a request; this should never happen */ log_error(ls, "find_rsb toss from_nodeid %d master %d dir %d", from_nodeid, r->res_master_nodeid, dir_nodeid); dlm_print_rsb(r); error = -ENOTBLK; goto out_unlock; } if (!recover && (r->res_master_nodeid != our_nodeid) && (dir_nodeid == our_nodeid)) { /* our rsb is not master, and we are dir; may as well fix it; this should never happen */ log_error(ls, "find_rsb toss our %d master %d dir %d", our_nodeid, r->res_master_nodeid, dir_nodeid); dlm_print_rsb(r); r->res_master_nodeid = our_nodeid; r->res_nodeid = 0; } rb_erase(&r->res_hashnode, &ls->ls_rsbtbl[b].toss); error = rsb_insert(r, &ls->ls_rsbtbl[b].keep); goto out_unlock; do_new: /* * rsb not found */ error = get_rsb_struct(ls, name, len, &r); if (error == -EAGAIN) { spin_unlock(&ls->ls_rsbtbl[b].lock); goto retry; } if (error) goto out_unlock; r->res_hash = hash; r->res_bucket = b; r->res_dir_nodeid = dir_nodeid; r->res_master_nodeid = dir_nodeid; r->res_nodeid = (dir_nodeid == our_nodeid) ? 0 : dir_nodeid; kref_init(&r->res_ref); error = rsb_insert(r, &ls->ls_rsbtbl[b].keep); out_unlock: spin_unlock(&ls->ls_rsbtbl[b].lock); out: *r_ret = r; return error; } static int find_rsb(struct dlm_ls *ls, char *name, int len, int from_nodeid, unsigned int flags, struct dlm_rsb **r_ret) { uint32_t hash, b; int dir_nodeid; if (len > DLM_RESNAME_MAXLEN) return -EINVAL; hash = jhash(name, len, 0); b = hash & (ls->ls_rsbtbl_size - 1); dir_nodeid = dlm_hash2nodeid(ls, hash); if (dlm_no_directory(ls)) return find_rsb_nodir(ls, name, len, hash, b, dir_nodeid, from_nodeid, flags, r_ret); else return find_rsb_dir(ls, name, len, hash, b, dir_nodeid, from_nodeid, flags, r_ret); } /* we have received a request and found that res_master_nodeid != our_nodeid, so we need to return an error or make ourself the master */ static int validate_master_nodeid(struct dlm_ls *ls, struct dlm_rsb *r, int from_nodeid) { if (dlm_no_directory(ls)) { log_error(ls, "find_rsb keep from_nodeid %d master %d dir %d", from_nodeid, r->res_master_nodeid, r->res_dir_nodeid); dlm_print_rsb(r); return -ENOTBLK; } if (from_nodeid != r->res_dir_nodeid) { /* our rsb is not master, and another node (not the dir node) has sent us a request. this is much more common when our master_nodeid is zero, so limit debug to non-zero. */ if (r->res_master_nodeid) { log_debug(ls, "validate master from_other %d master %d " "dir %d first %x %s", from_nodeid, r->res_master_nodeid, r->res_dir_nodeid, r->res_first_lkid, r->res_name); } return -ENOTBLK; } else { /* our rsb is not master, but the dir nodeid has sent us a request; this could happen with master 0 / res_nodeid -1 */ if (r->res_master_nodeid) { log_error(ls, "validate master from_dir %d master %d " "first %x %s", from_nodeid, r->res_master_nodeid, r->res_first_lkid, r->res_name); } r->res_master_nodeid = dlm_our_nodeid(); r->res_nodeid = 0; return 0; } } /* * We're the dir node for this res and another node wants to know the * master nodeid. During normal operation (non recovery) this is only * called from receive_lookup(); master lookups when the local node is * the dir node are done by find_rsb(). * * normal operation, we are the dir node for a resource * . _request_lock * . set_master * . send_lookup * . receive_lookup * . dlm_master_lookup flags 0 * * recover directory, we are rebuilding dir for all resources * . dlm_recover_directory * . dlm_rcom_names * remote node sends back the rsb names it is master of and we are dir of * . dlm_master_lookup RECOVER_DIR (fix_master 0, from_master 1) * we either create new rsb setting remote node as master, or find existing * rsb and set master to be the remote node. * * recover masters, we are finding the new master for resources * . dlm_recover_masters * . recover_master * . dlm_send_rcom_lookup * . receive_rcom_lookup * . dlm_master_lookup RECOVER_MASTER (fix_master 1, from_master 0) */ int dlm_master_lookup(struct dlm_ls *ls, int from_nodeid, char *name, int len, unsigned int flags, int *r_nodeid, int *result) { struct dlm_rsb *r = NULL; uint32_t hash, b; int from_master = (flags & DLM_LU_RECOVER_DIR); int fix_master = (flags & DLM_LU_RECOVER_MASTER); int our_nodeid = dlm_our_nodeid(); int dir_nodeid, error, toss_list = 0; if (len > DLM_RESNAME_MAXLEN) return -EINVAL; if (from_nodeid == our_nodeid) { log_error(ls, "dlm_master_lookup from our_nodeid %d flags %x", our_nodeid, flags); return -EINVAL; } hash = jhash(name, len, 0); b = hash & (ls->ls_rsbtbl_size - 1); dir_nodeid = dlm_hash2nodeid(ls, hash); if (dir_nodeid != our_nodeid) { log_error(ls, "dlm_master_lookup from %d dir %d our %d h %x %d", from_nodeid, dir_nodeid, our_nodeid, hash, ls->ls_num_nodes); *r_nodeid = -1; return -EINVAL; } retry: error = pre_rsb_struct(ls); if (error < 0) return error; spin_lock(&ls->ls_rsbtbl[b].lock); error = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].keep, name, len, &r); if (!error) { /* because the rsb is active, we need to lock_rsb before checking/changing re_master_nodeid */ hold_rsb(r); spin_unlock(&ls->ls_rsbtbl[b].lock); lock_rsb(r); goto found; } error = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].toss, name, len, &r); if (error) goto not_found; /* because the rsb is inactive (on toss list), it's not refcounted and lock_rsb is not used, but is protected by the rsbtbl lock */ toss_list = 1; found: if (r->res_dir_nodeid != our_nodeid) { /* should not happen, but may as well fix it and carry on */ log_error(ls, "dlm_master_lookup res_dir %d our %d %s", r->res_dir_nodeid, our_nodeid, r->res_name); r->res_dir_nodeid = our_nodeid; } if (fix_master && dlm_is_removed(ls, r->res_master_nodeid)) { /* Recovery uses this function to set a new master when the previous master failed. Setting NEW_MASTER will force dlm_recover_masters to call recover_master on this rsb even though the res_nodeid is no longer removed. */ r->res_master_nodeid = from_nodeid; r->res_nodeid = from_nodeid; rsb_set_flag(r, RSB_NEW_MASTER); if (toss_list) { /* I don't think we should ever find it on toss list. */ log_error(ls, "dlm_master_lookup fix_master on toss"); dlm_dump_rsb(r); } } if (from_master && (r->res_master_nodeid != from_nodeid)) { /* this will happen if from_nodeid became master during a previous recovery cycle, and we aborted the previous cycle before recovering this master value */ log_limit(ls, "dlm_master_lookup from_master %d " "master_nodeid %d res_nodeid %d first %x %s", from_nodeid, r->res_master_nodeid, r->res_nodeid, r->res_first_lkid, r->res_name); if (r->res_master_nodeid == our_nodeid) { log_error(ls, "from_master %d our_master", from_nodeid); dlm_dump_rsb(r); dlm_send_rcom_lookup_dump(r, from_nodeid); goto out_found; } r->res_master_nodeid = from_nodeid; r->res_nodeid = from_nodeid; rsb_set_flag(r, RSB_NEW_MASTER); } if (!r->res_master_nodeid) { /* this will happen if recovery happens while we're looking up the master for this rsb */ log_debug(ls, "dlm_master_lookup master 0 to %d first %x %s", from_nodeid, r->res_first_lkid, r->res_name); r->res_master_nodeid = from_nodeid; r->res_nodeid = from_nodeid; } if (!from_master && !fix_master && (r->res_master_nodeid == from_nodeid)) { /* this can happen when the master sends remove, the dir node finds the rsb on the keep list and ignores the remove, and the former master sends a lookup */ log_limit(ls, "dlm_master_lookup from master %d flags %x " "first %x %s", from_nodeid, flags, r->res_first_lkid, r->res_name); } out_found: *r_nodeid = r->res_master_nodeid; if (result) *result = DLM_LU_MATCH; if (toss_list) { r->res_toss_time = jiffies; /* the rsb was inactive (on toss list) */ spin_unlock(&ls->ls_rsbtbl[b].lock); } else { /* the rsb was active */ unlock_rsb(r); put_rsb(r); } return 0; not_found: error = get_rsb_struct(ls, name, len, &r); if (error == -EAGAIN) { spin_unlock(&ls->ls_rsbtbl[b].lock); goto retry; } if (error) goto out_unlock; r->res_hash = hash; r->res_bucket = b; r->res_dir_nodeid = our_nodeid; r->res_master_nodeid = from_nodeid; r->res_nodeid = from_nodeid; kref_init(&r->res_ref); r->res_toss_time = jiffies; error = rsb_insert(r, &ls->ls_rsbtbl[b].toss); if (error) { /* should never happen */ dlm_free_rsb(r); spin_unlock(&ls->ls_rsbtbl[b].lock); goto retry; } if (result) *result = DLM_LU_ADD; *r_nodeid = from_nodeid; error = 0; out_unlock: spin_unlock(&ls->ls_rsbtbl[b].lock); return error; } static void dlm_dump_rsb_hash(struct dlm_ls *ls, uint32_t hash) { struct rb_node *n; struct dlm_rsb *r; int i; for (i = 0; i < ls->ls_rsbtbl_size; i++) { spin_lock(&ls->ls_rsbtbl[i].lock); for (n = rb_first(&ls->ls_rsbtbl[i].keep); n; n = rb_next(n)) { r = rb_entry(n, struct dlm_rsb, res_hashnode); if (r->res_hash == hash) dlm_dump_rsb(r); } spin_unlock(&ls->ls_rsbtbl[i].lock); } } void dlm_dump_rsb_name(struct dlm_ls *ls, char *name, int len) { struct dlm_rsb *r = NULL; uint32_t hash, b; int error; hash = jhash(name, len, 0); b = hash & (ls->ls_rsbtbl_size - 1); spin_lock(&ls->ls_rsbtbl[b].lock); error = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].keep, name, len, &r); if (!error) goto out_dump; error = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].toss, name, len, &r); if (error) goto out; out_dump: dlm_dump_rsb(r); out: spin_unlock(&ls->ls_rsbtbl[b].lock); } static void toss_rsb(struct kref *kref) { struct dlm_rsb *r = container_of(kref, struct dlm_rsb, res_ref); struct dlm_ls *ls = r->res_ls; DLM_ASSERT(list_empty(&r->res_root_list), dlm_print_rsb(r);); kref_init(&r->res_ref); rb_erase(&r->res_hashnode, &ls->ls_rsbtbl[r->res_bucket].keep); rsb_insert(r, &ls->ls_rsbtbl[r->res_bucket].toss); r->res_toss_time = jiffies; ls->ls_rsbtbl[r->res_bucket].flags |= DLM_RTF_SHRINK; if (r->res_lvbptr) { dlm_free_lvb(r->res_lvbptr); r->res_lvbptr = NULL; } } /* See comment for unhold_lkb */ static void unhold_rsb(struct dlm_rsb *r) { int rv; rv = kref_put(&r->res_ref, toss_rsb); DLM_ASSERT(!rv, dlm_dump_rsb(r);); } static void kill_rsb(struct kref *kref) { struct dlm_rsb *r = container_of(kref, struct dlm_rsb, res_ref); /* All work is done after the return from kref_put() so we can release the write_lock before the remove and free. */ DLM_ASSERT(list_empty(&r->res_lookup), dlm_dump_rsb(r);); DLM_ASSERT(list_empty(&r->res_grantqueue), dlm_dump_rsb(r);); DLM_ASSERT(list_empty(&r->res_convertqueue), dlm_dump_rsb(r);); DLM_ASSERT(list_empty(&r->res_waitqueue), dlm_dump_rsb(r);); DLM_ASSERT(list_empty(&r->res_root_list), dlm_dump_rsb(r);); DLM_ASSERT(list_empty(&r->res_recover_list), dlm_dump_rsb(r);); } /* Attaching/detaching lkb's from rsb's is for rsb reference counting. The rsb must exist as long as any lkb's for it do. */ static void attach_lkb(struct dlm_rsb *r, struct dlm_lkb *lkb) { hold_rsb(r); lkb->lkb_resource = r; } static void detach_lkb(struct dlm_lkb *lkb) { if (lkb->lkb_resource) { put_rsb(lkb->lkb_resource); lkb->lkb_resource = NULL; } } static int create_lkb(struct dlm_ls *ls, struct dlm_lkb **lkb_ret) { struct dlm_lkb *lkb; int rv; lkb = dlm_allocate_lkb(ls); if (!lkb) return -ENOMEM; lkb->lkb_nodeid = -1; lkb->lkb_grmode = DLM_LOCK_IV; kref_init(&lkb->lkb_ref); INIT_LIST_HEAD(&lkb->lkb_ownqueue); INIT_LIST_HEAD(&lkb->lkb_rsb_lookup); INIT_LIST_HEAD(&lkb->lkb_time_list); INIT_LIST_HEAD(&lkb->lkb_cb_list); mutex_init(&lkb->lkb_cb_mutex); INIT_WORK(&lkb->lkb_cb_work, dlm_callback_work); idr_preload(GFP_NOFS); spin_lock(&ls->ls_lkbidr_spin); rv = idr_alloc(&ls->ls_lkbidr, lkb, 1, 0, GFP_NOWAIT); if (rv >= 0) lkb->lkb_id = rv; spin_unlock(&ls->ls_lkbidr_spin); idr_preload_end(); if (rv < 0) { log_error(ls, "create_lkb idr error %d", rv); return rv; } *lkb_ret = lkb; return 0; } static int find_lkb(struct dlm_ls *ls, uint32_t lkid, struct dlm_lkb **lkb_ret) { struct dlm_lkb *lkb; spin_lock(&ls->ls_lkbidr_spin); lkb = idr_find(&ls->ls_lkbidr, lkid); if (lkb) kref_get(&lkb->lkb_ref); spin_unlock(&ls->ls_lkbidr_spin); *lkb_ret = lkb; return lkb ? 0 : -ENOENT; } static void kill_lkb(struct kref *kref) { struct dlm_lkb *lkb = container_of(kref, struct dlm_lkb, lkb_ref); /* All work is done after the return from kref_put() so we can release the write_lock before the detach_lkb */ DLM_ASSERT(!lkb->lkb_status, dlm_print_lkb(lkb);); } /* __put_lkb() is used when an lkb may not have an rsb attached to it so we need to provide the lockspace explicitly */ static int __put_lkb(struct dlm_ls *ls, struct dlm_lkb *lkb) { uint32_t lkid = lkb->lkb_id; spin_lock(&ls->ls_lkbidr_spin); if (kref_put(&lkb->lkb_ref, kill_lkb)) { idr_remove(&ls->ls_lkbidr, lkid); spin_unlock(&ls->ls_lkbidr_spin); detach_lkb(lkb); /* for local/process lkbs, lvbptr points to caller's lksb */ if (lkb->lkb_lvbptr && is_master_copy(lkb)) dlm_free_lvb(lkb->lkb_lvbptr); dlm_free_lkb(lkb); return 1; } else { spin_unlock(&ls->ls_lkbidr_spin); return 0; } } int dlm_put_lkb(struct dlm_lkb *lkb) { struct dlm_ls *ls; DLM_ASSERT(lkb->lkb_resource, dlm_print_lkb(lkb);); DLM_ASSERT(lkb->lkb_resource->res_ls, dlm_print_lkb(lkb);); ls = lkb->lkb_resource->res_ls; return __put_lkb(ls, lkb); } /* This is only called to add a reference when the code already holds a valid reference to the lkb, so there's no need for locking. */ static inline void hold_lkb(struct dlm_lkb *lkb) { kref_get(&lkb->lkb_ref); } /* This is called when we need to remove a reference and are certain it's not the last ref. e.g. del_lkb is always called between a find_lkb/put_lkb and is always the inverse of a previous add_lkb. put_lkb would work fine, but would involve unnecessary locking */ static inline void unhold_lkb(struct dlm_lkb *lkb) { int rv; rv = kref_put(&lkb->lkb_ref, kill_lkb); DLM_ASSERT(!rv, dlm_print_lkb(lkb);); } static void lkb_add_ordered(struct list_head *new, struct list_head *head, int mode) { struct dlm_lkb *lkb = NULL; list_for_each_entry(lkb, head, lkb_statequeue) if (lkb->lkb_rqmode < mode) break; __list_add(new, lkb->lkb_statequeue.prev, &lkb->lkb_statequeue); } /* add/remove lkb to rsb's grant/convert/wait queue */ static void add_lkb(struct dlm_rsb *r, struct dlm_lkb *lkb, int status) { kref_get(&lkb->lkb_ref); DLM_ASSERT(!lkb->lkb_status, dlm_print_lkb(lkb);); lkb->lkb_timestamp = ktime_get(); lkb->lkb_status = status; switch (status) { case DLM_LKSTS_WAITING: if (lkb->lkb_exflags & DLM_LKF_HEADQUE) list_add(&lkb->lkb_statequeue, &r->res_waitqueue); else list_add_tail(&lkb->lkb_statequeue, &r->res_waitqueue); break; case DLM_LKSTS_GRANTED: /* convention says granted locks kept in order of grmode */ lkb_add_ordered(&lkb->lkb_statequeue, &r->res_grantqueue, lkb->lkb_grmode); break; case DLM_LKSTS_CONVERT: if (lkb->lkb_exflags & DLM_LKF_HEADQUE) list_add(&lkb->lkb_statequeue, &r->res_convertqueue); else list_add_tail(&lkb->lkb_statequeue, &r->res_convertqueue); break; default: DLM_ASSERT(0, dlm_print_lkb(lkb); printk("sts=%d\n", status);); } } static void del_lkb(struct dlm_rsb *r, struct dlm_lkb *lkb) { lkb->lkb_status = 0; list_del(&lkb->lkb_statequeue); unhold_lkb(lkb); } static void move_lkb(struct dlm_rsb *r, struct dlm_lkb *lkb, int sts) { hold_lkb(lkb); del_lkb(r, lkb); add_lkb(r, lkb, sts); unhold_lkb(lkb); } static int msg_reply_type(int mstype) { switch (mstype) { case DLM_MSG_REQUEST: return DLM_MSG_REQUEST_REPLY; case DLM_MSG_CONVERT: return DLM_MSG_CONVERT_REPLY; case DLM_MSG_UNLOCK: return DLM_MSG_UNLOCK_REPLY; case DLM_MSG_CANCEL: return DLM_MSG_CANCEL_REPLY; case DLM_MSG_LOOKUP: return DLM_MSG_LOOKUP_REPLY; } return -1; } static int nodeid_warned(int nodeid, int num_nodes, int *warned) { int i; for (i = 0; i < num_nodes; i++) { if (!warned[i]) { warned[i] = nodeid; return 0; } if (warned[i] == nodeid) return 1; } return 0; } void dlm_scan_waiters(struct dlm_ls *ls) { struct dlm_lkb *lkb; ktime_t zero = ktime_set(0, 0); s64 us; s64 debug_maxus = 0; u32 debug_scanned = 0; u32 debug_expired = 0; int num_nodes = 0; int *warned = NULL; if (!dlm_config.ci_waitwarn_us) return; mutex_lock(&ls->ls_waiters_mutex); list_for_each_entry(lkb, &ls->ls_waiters, lkb_wait_reply) { if (ktime_equal(lkb->lkb_wait_time, zero)) continue; debug_scanned++; us = ktime_to_us(ktime_sub(ktime_get(), lkb->lkb_wait_time)); if (us < dlm_config.ci_waitwarn_us) continue; lkb->lkb_wait_time = zero; debug_expired++; if (us > debug_maxus) debug_maxus = us; if (!num_nodes) { num_nodes = ls->ls_num_nodes; warned = kzalloc(num_nodes * sizeof(int), GFP_KERNEL); } if (!warned) continue; if (nodeid_warned(lkb->lkb_wait_nodeid, num_nodes, warned)) continue; log_error(ls, "waitwarn %x %lld %d us check connection to " "node %d", lkb->lkb_id, (long long)us, dlm_config.ci_waitwarn_us, lkb->lkb_wait_nodeid); } mutex_unlock(&ls->ls_waiters_mutex); kfree(warned); if (debug_expired) log_debug(ls, "scan_waiters %u warn %u over %d us max %lld us", debug_scanned, debug_expired, dlm_config.ci_waitwarn_us, (long long)debug_maxus); } /* add/remove lkb from global waiters list of lkb's waiting for a reply from a remote node */ static int add_to_waiters(struct dlm_lkb *lkb, int mstype, int to_nodeid) { struct dlm_ls *ls = lkb->lkb_resource->res_ls; int error = 0; mutex_lock(&ls->ls_waiters_mutex); if (is_overlap_unlock(lkb) || (is_overlap_cancel(lkb) && (mstype == DLM_MSG_CANCEL))) { error = -EINVAL; goto out; } if (lkb->lkb_wait_type || is_overlap_cancel(lkb)) { switch (mstype) { case DLM_MSG_UNLOCK: lkb->lkb_flags |= DLM_IFL_OVERLAP_UNLOCK; break; case DLM_MSG_CANCEL: lkb->lkb_flags |= DLM_IFL_OVERLAP_CANCEL; break; default: error = -EBUSY; goto out; } lkb->lkb_wait_count++; hold_lkb(lkb); log_debug(ls, "addwait %x cur %d overlap %d count %d f %x", lkb->lkb_id, lkb->lkb_wait_type, mstype, lkb->lkb_wait_count, lkb->lkb_flags); goto out; } DLM_ASSERT(!lkb->lkb_wait_count, dlm_print_lkb(lkb); printk("wait_count %d\n", lkb->lkb_wait_count);); lkb->lkb_wait_count++; lkb->lkb_wait_type = mstype; lkb->lkb_wait_time = ktime_get(); lkb->lkb_wait_nodeid = to_nodeid; /* for debugging */ hold_lkb(lkb); list_add(&lkb->lkb_wait_reply, &ls->ls_waiters); out: if (error) log_error(ls, "addwait error %x %d flags %x %d %d %s", lkb->lkb_id, error, lkb->lkb_flags, mstype, lkb->lkb_wait_type, lkb->lkb_resource->res_name); mutex_unlock(&ls->ls_waiters_mutex); return error; } /* We clear the RESEND flag because we might be taking an lkb off the waiters list as part of process_requestqueue (e.g. a lookup that has an optimized request reply on the requestqueue) between dlm_recover_waiters_pre() which set RESEND and dlm_recover_waiters_post() */ static int _remove_from_waiters(struct dlm_lkb *lkb, int mstype, struct dlm_message *ms) { struct dlm_ls *ls = lkb->lkb_resource->res_ls; int overlap_done = 0; if (is_overlap_unlock(lkb) && (mstype == DLM_MSG_UNLOCK_REPLY)) { log_debug(ls, "remwait %x unlock_reply overlap", lkb->lkb_id); lkb->lkb_flags &= ~DLM_IFL_OVERLAP_UNLOCK; overlap_done = 1; goto out_del; } if (is_overlap_cancel(lkb) && (mstype == DLM_MSG_CANCEL_REPLY)) { log_debug(ls, "remwait %x cancel_reply overlap", lkb->lkb_id); lkb->lkb_flags &= ~DLM_IFL_OVERLAP_CANCEL; overlap_done = 1; goto out_del; } /* Cancel state was preemptively cleared by a successful convert, see next comment, nothing to do. */ if ((mstype == DLM_MSG_CANCEL_REPLY) && (lkb->lkb_wait_type != DLM_MSG_CANCEL)) { log_debug(ls, "remwait %x cancel_reply wait_type %d", lkb->lkb_id, lkb->lkb_wait_type); return -1; } /* Remove for the convert reply, and premptively remove for the cancel reply. A convert has been granted while there's still an outstanding cancel on it (the cancel is moot and the result in the cancel reply should be 0). We preempt the cancel reply because the app gets the convert result and then can follow up with another op, like convert. This subsequent op would see the lingering state of the cancel and fail with -EBUSY. */ if ((mstype == DLM_MSG_CONVERT_REPLY) && (lkb->lkb_wait_type == DLM_MSG_CONVERT) && is_overlap_cancel(lkb) && ms && !ms->m_result) { log_debug(ls, "remwait %x convert_reply zap overlap_cancel", lkb->lkb_id); lkb->lkb_wait_type = 0; lkb->lkb_flags &= ~DLM_IFL_OVERLAP_CANCEL; lkb->lkb_wait_count--; goto out_del; } /* N.B. type of reply may not always correspond to type of original msg due to lookup->request optimization, verify others? */ if (lkb->lkb_wait_type) { lkb->lkb_wait_type = 0; goto out_del; } log_error(ls, "remwait error %x remote %d %x msg %d flags %x no wait", lkb->lkb_id, ms ? ms->m_header.h_nodeid : 0, lkb->lkb_remid, mstype, lkb->lkb_flags); return -1; out_del: /* the force-unlock/cancel has completed and we haven't recvd a reply to the op that was in progress prior to the unlock/cancel; we give up on any reply to the earlier op. FIXME: not sure when/how this would happen */ if (overlap_done && lkb->lkb_wait_type) { log_error(ls, "remwait error %x reply %d wait_type %d overlap", lkb->lkb_id, mstype, lkb->lkb_wait_type); lkb->lkb_wait_count--; lkb->lkb_wait_type = 0; } DLM_ASSERT(lkb->lkb_wait_count, dlm_print_lkb(lkb);); lkb->lkb_flags &= ~DLM_IFL_RESEND; lkb->lkb_wait_count--; if (!lkb->lkb_wait_count) list_del_init(&lkb->lkb_wait_reply); unhold_lkb(lkb); return 0; } static int remove_from_waiters(struct dlm_lkb *lkb, int mstype) { struct dlm_ls *ls = lkb->lkb_resource->res_ls; int error; mutex_lock(&ls->ls_waiters_mutex); error = _remove_from_waiters(lkb, mstype, NULL); mutex_unlock(&ls->ls_waiters_mutex); return error; } /* Handles situations where we might be processing a "fake" or "stub" reply in which we can't try to take waiters_mutex again. */ static int remove_from_waiters_ms(struct dlm_lkb *lkb, struct dlm_message *ms) { struct dlm_ls *ls = lkb->lkb_resource->res_ls; int error; if (ms->m_flags != DLM_IFL_STUB_MS) mutex_lock(&ls->ls_waiters_mutex); error = _remove_from_waiters(lkb, ms->m_type, ms); if (ms->m_flags != DLM_IFL_STUB_MS) mutex_unlock(&ls->ls_waiters_mutex); return error; } /* If there's an rsb for the same resource being removed, ensure that the remove message is sent before the new lookup message. It should be rare to need a delay here, but if not, then it may be worthwhile to add a proper wait mechanism rather than a delay. */ static void wait_pending_remove(struct dlm_rsb *r) { struct dlm_ls *ls = r->res_ls; restart: spin_lock(&ls->ls_remove_spin); if (ls->ls_remove_len && !rsb_cmp(r, ls->ls_remove_name, ls->ls_remove_len)) { log_debug(ls, "delay lookup for remove dir %d %s", r->res_dir_nodeid, r->res_name); spin_unlock(&ls->ls_remove_spin); msleep(1); goto restart; } spin_unlock(&ls->ls_remove_spin); } /* * ls_remove_spin protects ls_remove_name and ls_remove_len which are * read by other threads in wait_pending_remove. ls_remove_names * and ls_remove_lens are only used by the scan thread, so they do * not need protection. */ static void shrink_bucket(struct dlm_ls *ls, int b) { struct rb_node *n, *next; struct dlm_rsb *r; char *name; int our_nodeid = dlm_our_nodeid(); int remote_count = 0; int need_shrink = 0; int i, len, rv; memset(&ls->ls_remove_lens, 0, sizeof(int) * DLM_REMOVE_NAMES_MAX); spin_lock(&ls->ls_rsbtbl[b].lock); if (!(ls->ls_rsbtbl[b].flags & DLM_RTF_SHRINK)) { spin_unlock(&ls->ls_rsbtbl[b].lock); return; } for (n = rb_first(&ls->ls_rsbtbl[b].toss); n; n = next) { next = rb_next(n); r = rb_entry(n, struct dlm_rsb, res_hashnode); /* If we're the directory record for this rsb, and we're not the master of it, then we need to wait for the master node to send us a dir remove for before removing the dir record. */ if (!dlm_no_directory(ls) && (r->res_master_nodeid != our_nodeid) && (dlm_dir_nodeid(r) == our_nodeid)) { continue; } need_shrink = 1; if (!time_after_eq(jiffies, r->res_toss_time + dlm_config.ci_toss_secs * HZ)) { continue; } if (!dlm_no_directory(ls) && (r->res_master_nodeid == our_nodeid) && (dlm_dir_nodeid(r) != our_nodeid)) { /* We're the master of this rsb but we're not the directory record, so we need to tell the dir node to remove the dir record. */ ls->ls_remove_lens[remote_count] = r->res_length; memcpy(ls->ls_remove_names[remote_count], r->res_name, DLM_RESNAME_MAXLEN); remote_count++; if (remote_count >= DLM_REMOVE_NAMES_MAX) break; continue; } if (!kref_put(&r->res_ref, kill_rsb)) { log_error(ls, "tossed rsb in use %s", r->res_name); continue; } rb_erase(&r->res_hashnode, &ls->ls_rsbtbl[b].toss); dlm_free_rsb(r); } if (need_shrink) ls->ls_rsbtbl[b].flags |= DLM_RTF_SHRINK; else ls->ls_rsbtbl[b].flags &= ~DLM_RTF_SHRINK; spin_unlock(&ls->ls_rsbtbl[b].lock); /* * While searching for rsb's to free, we found some that require * remote removal. We leave them in place and find them again here * so there is a very small gap between removing them from the toss * list and sending the removal. Keeping this gap small is * important to keep us (the master node) from being out of sync * with the remote dir node for very long. * * From the time the rsb is removed from toss until just after * send_remove, the rsb name is saved in ls_remove_name. A new * lookup checks this to ensure that a new lookup message for the * same resource name is not sent just before the remove message. */ for (i = 0; i < remote_count; i++) { name = ls->ls_remove_names[i]; len = ls->ls_remove_lens[i]; spin_lock(&ls->ls_rsbtbl[b].lock); rv = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].toss, name, len, &r); if (rv) { spin_unlock(&ls->ls_rsbtbl[b].lock); log_debug(ls, "remove_name not toss %s", name); continue; } if (r->res_master_nodeid != our_nodeid) { spin_unlock(&ls->ls_rsbtbl[b].lock); log_debug(ls, "remove_name master %d dir %d our %d %s", r->res_master_nodeid, r->res_dir_nodeid, our_nodeid, name); continue; } if (r->res_dir_nodeid == our_nodeid) { /* should never happen */ spin_unlock(&ls->ls_rsbtbl[b].lock); log_error(ls, "remove_name dir %d master %d our %d %s", r->res_dir_nodeid, r->res_master_nodeid, our_nodeid, name); continue; } if (!time_after_eq(jiffies, r->res_toss_time + dlm_config.ci_toss_secs * HZ)) { spin_unlock(&ls->ls_rsbtbl[b].lock); log_debug(ls, "remove_name toss_time %lu now %lu %s", r->res_toss_time, jiffies, name); continue; } if (!kref_put(&r->res_ref, kill_rsb)) { spin_unlock(&ls->ls_rsbtbl[b].lock); log_error(ls, "remove_name in use %s", name); continue; } rb_erase(&r->res_hashnode, &ls->ls_rsbtbl[b].toss); /* block lookup of same name until we've sent remove */ spin_lock(&ls->ls_remove_spin); ls->ls_remove_len = len; memcpy(ls->ls_remove_name, name, DLM_RESNAME_MAXLEN); spin_unlock(&ls->ls_remove_spin); spin_unlock(&ls->ls_rsbtbl[b].lock); send_remove(r); /* allow lookup of name again */ spin_lock(&ls->ls_remove_spin); ls->ls_remove_len = 0; memset(ls->ls_remove_name, 0, DLM_RESNAME_MAXLEN); spin_unlock(&ls->ls_remove_spin); dlm_free_rsb(r); } } void dlm_scan_rsbs(struct dlm_ls *ls) { int i; for (i = 0; i < ls->ls_rsbtbl_size; i++) { shrink_bucket(ls, i); if (dlm_locking_stopped(ls)) break; cond_resched(); } } static void add_timeout(struct dlm_lkb *lkb) { struct dlm_ls *ls = lkb->lkb_resource->res_ls; if (is_master_copy(lkb)) return; if (test_bit(LSFL_TIMEWARN, &ls->ls_flags) && !(lkb->lkb_exflags & DLM_LKF_NODLCKWT)) { lkb->lkb_flags |= DLM_IFL_WATCH_TIMEWARN; goto add_it; } if (lkb->lkb_exflags & DLM_LKF_TIMEOUT) goto add_it; return; add_it: DLM_ASSERT(list_empty(&lkb->lkb_time_list), dlm_print_lkb(lkb);); mutex_lock(&ls->ls_timeout_mutex); hold_lkb(lkb); list_add_tail(&lkb->lkb_time_list, &ls->ls_timeout); mutex_unlock(&ls->ls_timeout_mutex); } static void del_timeout(struct dlm_lkb *lkb) { struct dlm_ls *ls = lkb->lkb_resource->res_ls; mutex_lock(&ls->ls_timeout_mutex); if (!list_empty(&lkb->lkb_time_list)) { list_del_init(&lkb->lkb_time_list); unhold_lkb(lkb); } mutex_unlock(&ls->ls_timeout_mutex); } /* FIXME: is it safe to look at lkb_exflags, lkb_flags, lkb_timestamp, and lkb_lksb_timeout without lock_rsb? Note: we can't lock timeout_mutex and then lock rsb because of lock ordering in add_timeout. We may need to specify some special timeout-related bits in the lkb that are just to be accessed under the timeout_mutex. */ void dlm_scan_timeout(struct dlm_ls *ls) { struct dlm_rsb *r; struct dlm_lkb *lkb; int do_cancel, do_warn; s64 wait_us; for (;;) { if (dlm_locking_stopped(ls)) break; do_cancel = 0; do_warn = 0; mutex_lock(&ls->ls_timeout_mutex); list_for_each_entry(lkb, &ls->ls_timeout, lkb_time_list) { wait_us = ktime_to_us(ktime_sub(ktime_get(), lkb->lkb_timestamp)); if ((lkb->lkb_exflags & DLM_LKF_TIMEOUT) && wait_us >= (lkb->lkb_timeout_cs * 10000)) do_cancel = 1; if ((lkb->lkb_flags & DLM_IFL_WATCH_TIMEWARN) && wait_us >= dlm_config.ci_timewarn_cs * 10000) do_warn = 1; if (!do_cancel && !do_warn) continue; hold_lkb(lkb); break; } mutex_unlock(&ls->ls_timeout_mutex); if (!do_cancel && !do_warn) break; r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); if (do_warn) { /* clear flag so we only warn once */ lkb->lkb_flags &= ~DLM_IFL_WATCH_TIMEWARN; if (!(lkb->lkb_exflags & DLM_LKF_TIMEOUT)) del_timeout(lkb); dlm_timeout_warn(lkb); } if (do_cancel) { log_debug(ls, "timeout cancel %x node %d %s", lkb->lkb_id, lkb->lkb_nodeid, r->res_name); lkb->lkb_flags &= ~DLM_IFL_WATCH_TIMEWARN; lkb->lkb_flags |= DLM_IFL_TIMEOUT_CANCEL; del_timeout(lkb); _cancel_lock(r, lkb); } unlock_rsb(r); unhold_rsb(r); dlm_put_lkb(lkb); } } /* This is only called by dlm_recoverd, and we rely on dlm_ls_stop() stopping dlm_recoverd before checking/setting ls_recover_begin. */ void dlm_adjust_timeouts(struct dlm_ls *ls) { struct dlm_lkb *lkb; u64 adj_us = jiffies_to_usecs(jiffies - ls->ls_recover_begin); ls->ls_recover_begin = 0; mutex_lock(&ls->ls_timeout_mutex); list_for_each_entry(lkb, &ls->ls_timeout, lkb_time_list) lkb->lkb_timestamp = ktime_add_us(lkb->lkb_timestamp, adj_us); mutex_unlock(&ls->ls_timeout_mutex); if (!dlm_config.ci_waitwarn_us) return; mutex_lock(&ls->ls_waiters_mutex); list_for_each_entry(lkb, &ls->ls_waiters, lkb_wait_reply) { if (ktime_to_us(lkb->lkb_wait_time)) lkb->lkb_wait_time = ktime_get(); } mutex_unlock(&ls->ls_waiters_mutex); } /* lkb is master or local copy */ static void set_lvb_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { int b, len = r->res_ls->ls_lvblen; /* b=1 lvb returned to caller b=0 lvb written to rsb or invalidated b=-1 do nothing */ b = dlm_lvb_operations[lkb->lkb_grmode + 1][lkb->lkb_rqmode + 1]; if (b == 1) { if (!lkb->lkb_lvbptr) return; if (!(lkb->lkb_exflags & DLM_LKF_VALBLK)) return; if (!r->res_lvbptr) return; memcpy(lkb->lkb_lvbptr, r->res_lvbptr, len); lkb->lkb_lvbseq = r->res_lvbseq; } else if (b == 0) { if (lkb->lkb_exflags & DLM_LKF_IVVALBLK) { rsb_set_flag(r, RSB_VALNOTVALID); return; } if (!lkb->lkb_lvbptr) return; if (!(lkb->lkb_exflags & DLM_LKF_VALBLK)) return; if (!r->res_lvbptr) r->res_lvbptr = dlm_allocate_lvb(r->res_ls); if (!r->res_lvbptr) return; memcpy(r->res_lvbptr, lkb->lkb_lvbptr, len); r->res_lvbseq++; lkb->lkb_lvbseq = r->res_lvbseq; rsb_clear_flag(r, RSB_VALNOTVALID); } if (rsb_flag(r, RSB_VALNOTVALID)) lkb->lkb_sbflags |= DLM_SBF_VALNOTVALID; } static void set_lvb_unlock(struct dlm_rsb *r, struct dlm_lkb *lkb) { if (lkb->lkb_grmode < DLM_LOCK_PW) return; if (lkb->lkb_exflags & DLM_LKF_IVVALBLK) { rsb_set_flag(r, RSB_VALNOTVALID); return; } if (!lkb->lkb_lvbptr) return; if (!(lkb->lkb_exflags & DLM_LKF_VALBLK)) return; if (!r->res_lvbptr) r->res_lvbptr = dlm_allocate_lvb(r->res_ls); if (!r->res_lvbptr) return; memcpy(r->res_lvbptr, lkb->lkb_lvbptr, r->res_ls->ls_lvblen); r->res_lvbseq++; rsb_clear_flag(r, RSB_VALNOTVALID); } /* lkb is process copy (pc) */ static void set_lvb_lock_pc(struct dlm_rsb *r, struct dlm_lkb *lkb, struct dlm_message *ms) { int b; if (!lkb->lkb_lvbptr) return; if (!(lkb->lkb_exflags & DLM_LKF_VALBLK)) return; b = dlm_lvb_operations[lkb->lkb_grmode + 1][lkb->lkb_rqmode + 1]; if (b == 1) { int len = receive_extralen(ms); if (len > r->res_ls->ls_lvblen) len = r->res_ls->ls_lvblen; memcpy(lkb->lkb_lvbptr, ms->m_extra, len); lkb->lkb_lvbseq = ms->m_lvbseq; } } /* Manipulate lkb's on rsb's convert/granted/waiting queues remove_lock -- used for unlock, removes lkb from granted revert_lock -- used for cancel, moves lkb from convert to granted grant_lock -- used for request and convert, adds lkb to granted or moves lkb from convert or waiting to granted Each of these is used for master or local copy lkb's. There is also a _pc() variation used to make the corresponding change on a process copy (pc) lkb. */ static void _remove_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { del_lkb(r, lkb); lkb->lkb_grmode = DLM_LOCK_IV; /* this unhold undoes the original ref from create_lkb() so this leads to the lkb being freed */ unhold_lkb(lkb); } static void remove_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { set_lvb_unlock(r, lkb); _remove_lock(r, lkb); } static void remove_lock_pc(struct dlm_rsb *r, struct dlm_lkb *lkb) { _remove_lock(r, lkb); } /* returns: 0 did nothing 1 moved lock to granted -1 removed lock */ static int revert_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { int rv = 0; lkb->lkb_rqmode = DLM_LOCK_IV; switch (lkb->lkb_status) { case DLM_LKSTS_GRANTED: break; case DLM_LKSTS_CONVERT: move_lkb(r, lkb, DLM_LKSTS_GRANTED); rv = 1; break; case DLM_LKSTS_WAITING: del_lkb(r, lkb); lkb->lkb_grmode = DLM_LOCK_IV; /* this unhold undoes the original ref from create_lkb() so this leads to the lkb being freed */ unhold_lkb(lkb); rv = -1; break; default: log_print("invalid status for revert %d", lkb->lkb_status); } return rv; } static int revert_lock_pc(struct dlm_rsb *r, struct dlm_lkb *lkb) { return revert_lock(r, lkb); } static void _grant_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { if (lkb->lkb_grmode != lkb->lkb_rqmode) { lkb->lkb_grmode = lkb->lkb_rqmode; if (lkb->lkb_status) move_lkb(r, lkb, DLM_LKSTS_GRANTED); else add_lkb(r, lkb, DLM_LKSTS_GRANTED); } lkb->lkb_rqmode = DLM_LOCK_IV; lkb->lkb_highbast = 0; } static void grant_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { set_lvb_lock(r, lkb); _grant_lock(r, lkb); } static void grant_lock_pc(struct dlm_rsb *r, struct dlm_lkb *lkb, struct dlm_message *ms) { set_lvb_lock_pc(r, lkb, ms); _grant_lock(r, lkb); } /* called by grant_pending_locks() which means an async grant message must be sent to the requesting node in addition to granting the lock if the lkb belongs to a remote node. */ static void grant_lock_pending(struct dlm_rsb *r, struct dlm_lkb *lkb) { grant_lock(r, lkb); if (is_master_copy(lkb)) send_grant(r, lkb); else queue_cast(r, lkb, 0); } /* The special CONVDEADLK, ALTPR and ALTCW flags allow the master to change the granted/requested modes. We're munging things accordingly in the process copy. CONVDEADLK: our grmode may have been forced down to NL to resolve a conversion deadlock ALTPR/ALTCW: our rqmode may have been changed to PR or CW to become compatible with other granted locks */ static void munge_demoted(struct dlm_lkb *lkb) { if (lkb->lkb_rqmode == DLM_LOCK_IV || lkb->lkb_grmode == DLM_LOCK_IV) { log_print("munge_demoted %x invalid modes gr %d rq %d", lkb->lkb_id, lkb->lkb_grmode, lkb->lkb_rqmode); return; } lkb->lkb_grmode = DLM_LOCK_NL; } static void munge_altmode(struct dlm_lkb *lkb, struct dlm_message *ms) { if (ms->m_type != DLM_MSG_REQUEST_REPLY && ms->m_type != DLM_MSG_GRANT) { log_print("munge_altmode %x invalid reply type %d", lkb->lkb_id, ms->m_type); return; } if (lkb->lkb_exflags & DLM_LKF_ALTPR) lkb->lkb_rqmode = DLM_LOCK_PR; else if (lkb->lkb_exflags & DLM_LKF_ALTCW) lkb->lkb_rqmode = DLM_LOCK_CW; else { log_print("munge_altmode invalid exflags %x", lkb->lkb_exflags); dlm_print_lkb(lkb); } } static inline int first_in_list(struct dlm_lkb *lkb, struct list_head *head) { struct dlm_lkb *first = list_entry(head->next, struct dlm_lkb, lkb_statequeue); if (lkb->lkb_id == first->lkb_id) return 1; return 0; } /* Check if the given lkb conflicts with another lkb on the queue. */ static int queue_conflict(struct list_head *head, struct dlm_lkb *lkb) { struct dlm_lkb *this; list_for_each_entry(this, head, lkb_statequeue) { if (this == lkb) continue; if (!modes_compat(this, lkb)) return 1; } return 0; } /* * "A conversion deadlock arises with a pair of lock requests in the converting * queue for one resource. The granted mode of each lock blocks the requested * mode of the other lock." * * Part 2: if the granted mode of lkb is preventing an earlier lkb in the * convert queue from being granted, then deadlk/demote lkb. * * Example: * Granted Queue: empty * Convert Queue: NL->EX (first lock) * PR->EX (second lock) * * The first lock can't be granted because of the granted mode of the second * lock and the second lock can't be granted because it's not first in the * list. We either cancel lkb's conversion (PR->EX) and return EDEADLK, or we * demote the granted mode of lkb (from PR to NL) if it has the CONVDEADLK * flag set and return DEMOTED in the lksb flags. * * Originally, this function detected conv-deadlk in a more limited scope: * - if !modes_compat(lkb1, lkb2) && !modes_compat(lkb2, lkb1), or * - if lkb1 was the first entry in the queue (not just earlier), and was * blocked by the granted mode of lkb2, and there was nothing on the * granted queue preventing lkb1 from being granted immediately, i.e. * lkb2 was the only thing preventing lkb1 from being granted. * * That second condition meant we'd only say there was conv-deadlk if * resolving it (by demotion) would lead to the first lock on the convert * queue being granted right away. It allowed conversion deadlocks to exist * between locks on the convert queue while they couldn't be granted anyway. * * Now, we detect and take action on conversion deadlocks immediately when * they're created, even if they may not be immediately consequential. If * lkb1 exists anywhere in the convert queue and lkb2 comes in with a granted * mode that would prevent lkb1's conversion from being granted, we do a * deadlk/demote on lkb2 right away and don't let it onto the convert queue. * I think this means that the lkb_is_ahead condition below should always * be zero, i.e. there will never be conv-deadlk between two locks that are * both already on the convert queue. */ static int conversion_deadlock_detect(struct dlm_rsb *r, struct dlm_lkb *lkb2) { struct dlm_lkb *lkb1; int lkb_is_ahead = 0; list_for_each_entry(lkb1, &r->res_convertqueue, lkb_statequeue) { if (lkb1 == lkb2) { lkb_is_ahead = 1; continue; } if (!lkb_is_ahead) { if (!modes_compat(lkb2, lkb1)) return 1; } else { if (!modes_compat(lkb2, lkb1) && !modes_compat(lkb1, lkb2)) return 1; } } return 0; } /* * Return 1 if the lock can be granted, 0 otherwise. * Also detect and resolve conversion deadlocks. * * lkb is the lock to be granted * * now is 1 if the function is being called in the context of the * immediate request, it is 0 if called later, after the lock has been * queued. * * recover is 1 if dlm_recover_grant() is trying to grant conversions * after recovery. * * References are from chapter 6 of "VAXcluster Principles" by Roy Davis */ static int _can_be_granted(struct dlm_rsb *r, struct dlm_lkb *lkb, int now, int recover) { int8_t conv = (lkb->lkb_grmode != DLM_LOCK_IV); /* * 6-10: Version 5.4 introduced an option to address the phenomenon of * a new request for a NL mode lock being blocked. * * 6-11: If the optional EXPEDITE flag is used with the new NL mode * request, then it would be granted. In essence, the use of this flag * tells the Lock Manager to expedite theis request by not considering * what may be in the CONVERTING or WAITING queues... As of this * writing, the EXPEDITE flag can be used only with new requests for NL * mode locks. This flag is not valid for conversion requests. * * A shortcut. Earlier checks return an error if EXPEDITE is used in a * conversion or used with a non-NL requested mode. We also know an * EXPEDITE request is always granted immediately, so now must always * be 1. The full condition to grant an expedite request: (now && * !conv && lkb->rqmode == DLM_LOCK_NL && (flags & EXPEDITE)) can * therefore be shortened to just checking the flag. */ if (lkb->lkb_exflags & DLM_LKF_EXPEDITE) return 1; /* * A shortcut. Without this, !queue_conflict(grantqueue, lkb) would be * added to the remaining conditions. */ if (queue_conflict(&r->res_grantqueue, lkb)) return 0; /* * 6-3: By default, a conversion request is immediately granted if the * requested mode is compatible with the modes of all other granted * locks */ if (queue_conflict(&r->res_convertqueue, lkb)) return 0; /* * The RECOVER_GRANT flag means dlm_recover_grant() is granting * locks for a recovered rsb, on which lkb's have been rebuilt. * The lkb's may have been rebuilt on the queues in a different * order than they were in on the previous master. So, granting * queued conversions in order after recovery doesn't make sense * since the order hasn't been preserved anyway. The new order * could also have created a new "in place" conversion deadlock. * (e.g. old, failed master held granted EX, with PR->EX, NL->EX. * After recovery, there would be no granted locks, and possibly * NL->EX, PR->EX, an in-place conversion deadlock.) So, after * recovery, grant conversions without considering order. */ if (conv && recover) return 1; /* * 6-5: But the default algorithm for deciding whether to grant or * queue conversion requests does not by itself guarantee that such * requests are serviced on a "first come first serve" basis. This, in * turn, can lead to a phenomenon known as "indefinate postponement". * * 6-7: This issue is dealt with by using the optional QUECVT flag with * the system service employed to request a lock conversion. This flag * forces certain conversion requests to be queued, even if they are * compatible with the granted modes of other locks on the same * resource. Thus, the use of this flag results in conversion requests * being ordered on a "first come first servce" basis. * * DCT: This condition is all about new conversions being able to occur * "in place" while the lock remains on the granted queue (assuming * nothing else conflicts.) IOW if QUECVT isn't set, a conversion * doesn't _have_ to go onto the convert queue where it's processed in * order. The "now" variable is necessary to distinguish converts * being received and processed for the first time now, because once a * convert is moved to the conversion queue the condition below applies * requiring fifo granting. */ if (now && conv && !(lkb->lkb_exflags & DLM_LKF_QUECVT)) return 1; /* * Even if the convert is compat with all granted locks, * QUECVT forces it behind other locks on the convert queue. */ if (now && conv && (lkb->lkb_exflags & DLM_LKF_QUECVT)) { if (list_empty(&r->res_convertqueue)) return 1; else return 0; } /* * The NOORDER flag is set to avoid the standard vms rules on grant * order. */ if (lkb->lkb_exflags & DLM_LKF_NOORDER) return 1; /* * 6-3: Once in that queue [CONVERTING], a conversion request cannot be * granted until all other conversion requests ahead of it are granted * and/or canceled. */ if (!now && conv && first_in_list(lkb, &r->res_convertqueue)) return 1; /* * 6-4: By default, a new request is immediately granted only if all * three of the following conditions are satisfied when the request is * issued: * - The queue of ungranted conversion requests for the resource is * empty. * - The queue of ungranted new requests for the resource is empty. * - The mode of the new request is compatible with the most * restrictive mode of all granted locks on the resource. */ if (now && !conv && list_empty(&r->res_convertqueue) && list_empty(&r->res_waitqueue)) return 1; /* * 6-4: Once a lock request is in the queue of ungranted new requests, * it cannot be granted until the queue of ungranted conversion * requests is empty, all ungranted new requests ahead of it are * granted and/or canceled, and it is compatible with the granted mode * of the most restrictive lock granted on the resource. */ if (!now && !conv && list_empty(&r->res_convertqueue) && first_in_list(lkb, &r->res_waitqueue)) return 1; return 0; } static int can_be_granted(struct dlm_rsb *r, struct dlm_lkb *lkb, int now, int recover, int *err) { int rv; int8_t alt = 0, rqmode = lkb->lkb_rqmode; int8_t is_convert = (lkb->lkb_grmode != DLM_LOCK_IV); if (err) *err = 0; rv = _can_be_granted(r, lkb, now, recover); if (rv) goto out; /* * The CONVDEADLK flag is non-standard and tells the dlm to resolve * conversion deadlocks by demoting grmode to NL, otherwise the dlm * cancels one of the locks. */ if (is_convert && can_be_queued(lkb) && conversion_deadlock_detect(r, lkb)) { if (lkb->lkb_exflags & DLM_LKF_CONVDEADLK) { lkb->lkb_grmode = DLM_LOCK_NL; lkb->lkb_sbflags |= DLM_SBF_DEMOTED; } else if (!(lkb->lkb_exflags & DLM_LKF_NODLCKWT)) { if (err) *err = -EDEADLK; else { log_print("can_be_granted deadlock %x now %d", lkb->lkb_id, now); dlm_dump_rsb(r); } } goto out; } /* * The ALTPR and ALTCW flags are non-standard and tell the dlm to try * to grant a request in a mode other than the normal rqmode. It's a * simple way to provide a big optimization to applications that can * use them. */ if (rqmode != DLM_LOCK_PR && (lkb->lkb_exflags & DLM_LKF_ALTPR)) alt = DLM_LOCK_PR; else if (rqmode != DLM_LOCK_CW && (lkb->lkb_exflags & DLM_LKF_ALTCW)) alt = DLM_LOCK_CW; if (alt) { lkb->lkb_rqmode = alt; rv = _can_be_granted(r, lkb, now, 0); if (rv) lkb->lkb_sbflags |= DLM_SBF_ALTMODE; else lkb->lkb_rqmode = rqmode; } out: return rv; } /* FIXME: I don't think that can_be_granted() can/will demote or find deadlock for locks pending on the convert list. Once verified (watch for these log_prints), we should be able to just call _can_be_granted() and not bother with the demote/deadlk cases here (and there's no easy way to deal with a deadlk here, we'd have to generate something like grant_lock with the deadlk error.) */ /* Returns the highest requested mode of all blocked conversions; sets cw if there's a blocked conversion to DLM_LOCK_CW. */ static int grant_pending_convert(struct dlm_rsb *r, int high, int *cw, unsigned int *count) { struct dlm_lkb *lkb, *s; int recover = rsb_flag(r, RSB_RECOVER_GRANT); int hi, demoted, quit, grant_restart, demote_restart; int deadlk; quit = 0; restart: grant_restart = 0; demote_restart = 0; hi = DLM_LOCK_IV; list_for_each_entry_safe(lkb, s, &r->res_convertqueue, lkb_statequeue) { demoted = is_demoted(lkb); deadlk = 0; if (can_be_granted(r, lkb, 0, recover, &deadlk)) { grant_lock_pending(r, lkb); grant_restart = 1; if (count) (*count)++; continue; } if (!demoted && is_demoted(lkb)) { log_print("WARN: pending demoted %x node %d %s", lkb->lkb_id, lkb->lkb_nodeid, r->res_name); demote_restart = 1; continue; } if (deadlk) { log_print("WARN: pending deadlock %x node %d %s", lkb->lkb_id, lkb->lkb_nodeid, r->res_name); dlm_dump_rsb(r); continue; } hi = max_t(int, lkb->lkb_rqmode, hi); if (cw && lkb->lkb_rqmode == DLM_LOCK_CW) *cw = 1; } if (grant_restart) goto restart; if (demote_restart && !quit) { quit = 1; goto restart; } return max_t(int, high, hi); } static int grant_pending_wait(struct dlm_rsb *r, int high, int *cw, unsigned int *count) { struct dlm_lkb *lkb, *s; list_for_each_entry_safe(lkb, s, &r->res_waitqueue, lkb_statequeue) { if (can_be_granted(r, lkb, 0, 0, NULL)) { grant_lock_pending(r, lkb); if (count) (*count)++; } else { high = max_t(int, lkb->lkb_rqmode, high); if (lkb->lkb_rqmode == DLM_LOCK_CW) *cw = 1; } } return high; } /* cw of 1 means there's a lock with a rqmode of DLM_LOCK_CW that's blocked on either the convert or waiting queue. high is the largest rqmode of all locks blocked on the convert or waiting queue. */ static int lock_requires_bast(struct dlm_lkb *gr, int high, int cw) { if (gr->lkb_grmode == DLM_LOCK_PR && cw) { if (gr->lkb_highbast < DLM_LOCK_EX) return 1; return 0; } if (gr->lkb_highbast < high && !__dlm_compat_matrix[gr->lkb_grmode+1][high+1]) return 1; return 0; } static void grant_pending_locks(struct dlm_rsb *r, unsigned int *count) { struct dlm_lkb *lkb, *s; int high = DLM_LOCK_IV; int cw = 0; if (!is_master(r)) { log_print("grant_pending_locks r nodeid %d", r->res_nodeid); dlm_dump_rsb(r); return; } high = grant_pending_convert(r, high, &cw, count); high = grant_pending_wait(r, high, &cw, count); if (high == DLM_LOCK_IV) return; /* * If there are locks left on the wait/convert queue then send blocking * ASTs to granted locks based on the largest requested mode (high) * found above. */ list_for_each_entry_safe(lkb, s, &r->res_grantqueue, lkb_statequeue) { if (lkb->lkb_bastfn && lock_requires_bast(lkb, high, cw)) { if (cw && high == DLM_LOCK_PR && lkb->lkb_grmode == DLM_LOCK_PR) queue_bast(r, lkb, DLM_LOCK_CW); else queue_bast(r, lkb, high); lkb->lkb_highbast = high; } } } static int modes_require_bast(struct dlm_lkb *gr, struct dlm_lkb *rq) { if ((gr->lkb_grmode == DLM_LOCK_PR && rq->lkb_rqmode == DLM_LOCK_CW) || (gr->lkb_grmode == DLM_LOCK_CW && rq->lkb_rqmode == DLM_LOCK_PR)) { if (gr->lkb_highbast < DLM_LOCK_EX) return 1; return 0; } if (gr->lkb_highbast < rq->lkb_rqmode && !modes_compat(gr, rq)) return 1; return 0; } static void send_bast_queue(struct dlm_rsb *r, struct list_head *head, struct dlm_lkb *lkb) { struct dlm_lkb *gr; list_for_each_entry(gr, head, lkb_statequeue) { /* skip self when sending basts to convertqueue */ if (gr == lkb) continue; if (gr->lkb_bastfn && modes_require_bast(gr, lkb)) { queue_bast(r, gr, lkb->lkb_rqmode); gr->lkb_highbast = lkb->lkb_rqmode; } } } static void send_blocking_asts(struct dlm_rsb *r, struct dlm_lkb *lkb) { send_bast_queue(r, &r->res_grantqueue, lkb); } static void send_blocking_asts_all(struct dlm_rsb *r, struct dlm_lkb *lkb) { send_bast_queue(r, &r->res_grantqueue, lkb); send_bast_queue(r, &r->res_convertqueue, lkb); } /* set_master(r, lkb) -- set the master nodeid of a resource The purpose of this function is to set the nodeid field in the given lkb using the nodeid field in the given rsb. If the rsb's nodeid is known, it can just be copied to the lkb and the function will return 0. If the rsb's nodeid is _not_ known, it needs to be looked up before it can be copied to the lkb. When the rsb nodeid is being looked up remotely, the initial lkb causing the lookup is kept on the ls_waiters list waiting for the lookup reply. Other lkb's waiting for the same rsb lookup are kept on the rsb's res_lookup list until the master is verified. Return values: 0: nodeid is set in rsb/lkb and the caller should go ahead and use it 1: the rsb master is not available and the lkb has been placed on a wait queue */ static int set_master(struct dlm_rsb *r, struct dlm_lkb *lkb) { int our_nodeid = dlm_our_nodeid(); if (rsb_flag(r, RSB_MASTER_UNCERTAIN)) { rsb_clear_flag(r, RSB_MASTER_UNCERTAIN); r->res_first_lkid = lkb->lkb_id; lkb->lkb_nodeid = r->res_nodeid; return 0; } if (r->res_first_lkid && r->res_first_lkid != lkb->lkb_id) { list_add_tail(&lkb->lkb_rsb_lookup, &r->res_lookup); return 1; } if (r->res_master_nodeid == our_nodeid) { lkb->lkb_nodeid = 0; return 0; } if (r->res_master_nodeid) { lkb->lkb_nodeid = r->res_master_nodeid; return 0; } if (dlm_dir_nodeid(r) == our_nodeid) { /* This is a somewhat unusual case; find_rsb will usually have set res_master_nodeid when dir nodeid is local, but there are cases where we become the dir node after we've past find_rsb and go through _request_lock again. confirm_master() or process_lookup_list() needs to be called after this. */ log_debug(r->res_ls, "set_master %x self master %d dir %d %s", lkb->lkb_id, r->res_master_nodeid, r->res_dir_nodeid, r->res_name); r->res_master_nodeid = our_nodeid; r->res_nodeid = 0; lkb->lkb_nodeid = 0; return 0; } wait_pending_remove(r); r->res_first_lkid = lkb->lkb_id; send_lookup(r, lkb); return 1; } static void process_lookup_list(struct dlm_rsb *r) { struct dlm_lkb *lkb, *safe; list_for_each_entry_safe(lkb, safe, &r->res_lookup, lkb_rsb_lookup) { list_del_init(&lkb->lkb_rsb_lookup); _request_lock(r, lkb); schedule(); } } /* confirm_master -- confirm (or deny) an rsb's master nodeid */ static void confirm_master(struct dlm_rsb *r, int error) { struct dlm_lkb *lkb; if (!r->res_first_lkid) return; switch (error) { case 0: case -EINPROGRESS: r->res_first_lkid = 0; process_lookup_list(r); break; case -EAGAIN: case -EBADR: case -ENOTBLK: /* the remote request failed and won't be retried (it was a NOQUEUE, or has been canceled/unlocked); make a waiting lkb the first_lkid */ r->res_first_lkid = 0; if (!list_empty(&r->res_lookup)) { lkb = list_entry(r->res_lookup.next, struct dlm_lkb, lkb_rsb_lookup); list_del_init(&lkb->lkb_rsb_lookup); r->res_first_lkid = lkb->lkb_id; _request_lock(r, lkb); } break; default: log_error(r->res_ls, "confirm_master unknown error %d", error); } } static int set_lock_args(int mode, struct dlm_lksb *lksb, uint32_t flags, int namelen, unsigned long timeout_cs, void (*ast) (void *astparam), void *astparam, void (*bast) (void *astparam, int mode), struct dlm_args *args) { int rv = -EINVAL; /* check for invalid arg usage */ if (mode < 0 || mode > DLM_LOCK_EX) goto out; if (!(flags & DLM_LKF_CONVERT) && (namelen > DLM_RESNAME_MAXLEN)) goto out; if (flags & DLM_LKF_CANCEL) goto out; if (flags & DLM_LKF_QUECVT && !(flags & DLM_LKF_CONVERT)) goto out; if (flags & DLM_LKF_CONVDEADLK && !(flags & DLM_LKF_CONVERT)) goto out; if (flags & DLM_LKF_CONVDEADLK && flags & DLM_LKF_NOQUEUE) goto out; if (flags & DLM_LKF_EXPEDITE && flags & DLM_LKF_CONVERT) goto out; if (flags & DLM_LKF_EXPEDITE && flags & DLM_LKF_QUECVT) goto out; if (flags & DLM_LKF_EXPEDITE && flags & DLM_LKF_NOQUEUE) goto out; if (flags & DLM_LKF_EXPEDITE && mode != DLM_LOCK_NL) goto out; if (!ast || !lksb) goto out; if (flags & DLM_LKF_VALBLK && !lksb->sb_lvbptr) goto out; if (flags & DLM_LKF_CONVERT && !lksb->sb_lkid) goto out; /* these args will be copied to the lkb in validate_lock_args, it cannot be done now because when converting locks, fields in an active lkb cannot be modified before locking the rsb */ args->flags = flags; args->astfn = ast; args->astparam = astparam; args->bastfn = bast; args->timeout = timeout_cs; args->mode = mode; args->lksb = lksb; rv = 0; out: return rv; } static int set_unlock_args(uint32_t flags, void *astarg, struct dlm_args *args) { if (flags & ~(DLM_LKF_CANCEL | DLM_LKF_VALBLK | DLM_LKF_IVVALBLK | DLM_LKF_FORCEUNLOCK)) return -EINVAL; if (flags & DLM_LKF_CANCEL && flags & DLM_LKF_FORCEUNLOCK) return -EINVAL; args->flags = flags; args->astparam = astarg; return 0; } static int validate_lock_args(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_args *args) { int rv = -EINVAL; if (args->flags & DLM_LKF_CONVERT) { if (lkb->lkb_flags & DLM_IFL_MSTCPY) goto out; if (args->flags & DLM_LKF_QUECVT && !__quecvt_compat_matrix[lkb->lkb_grmode+1][args->mode+1]) goto out; rv = -EBUSY; if (lkb->lkb_status != DLM_LKSTS_GRANTED) goto out; if (lkb->lkb_wait_type) goto out; if (is_overlap(lkb)) goto out; } lkb->lkb_exflags = args->flags; lkb->lkb_sbflags = 0; lkb->lkb_astfn = args->astfn; lkb->lkb_astparam = args->astparam; lkb->lkb_bastfn = args->bastfn; lkb->lkb_rqmode = args->mode; lkb->lkb_lksb = args->lksb; lkb->lkb_lvbptr = args->lksb->sb_lvbptr; lkb->lkb_ownpid = (int) current->pid; lkb->lkb_timeout_cs = args->timeout; rv = 0; out: if (rv) log_debug(ls, "validate_lock_args %d %x %x %x %d %d %s", rv, lkb->lkb_id, lkb->lkb_flags, args->flags, lkb->lkb_status, lkb->lkb_wait_type, lkb->lkb_resource->res_name); return rv; } /* when dlm_unlock() sees -EBUSY with CANCEL/FORCEUNLOCK it returns 0 for success */ /* note: it's valid for lkb_nodeid/res_nodeid to be -1 when we get here because there may be a lookup in progress and it's valid to do cancel/unlockf on it */ static int validate_unlock_args(struct dlm_lkb *lkb, struct dlm_args *args) { struct dlm_ls *ls = lkb->lkb_resource->res_ls; int rv = -EINVAL; if (lkb->lkb_flags & DLM_IFL_MSTCPY) { log_error(ls, "unlock on MSTCPY %x", lkb->lkb_id); dlm_print_lkb(lkb); goto out; } /* an lkb may still exist even though the lock is EOL'ed due to a cancel, unlock or failed noqueue request; an app can't use these locks; return same error as if the lkid had not been found at all */ if (lkb->lkb_flags & DLM_IFL_ENDOFLIFE) { log_debug(ls, "unlock on ENDOFLIFE %x", lkb->lkb_id); rv = -ENOENT; goto out; } /* an lkb may be waiting for an rsb lookup to complete where the lookup was initiated by another lock */ if (!list_empty(&lkb->lkb_rsb_lookup)) { if (args->flags & (DLM_LKF_CANCEL | DLM_LKF_FORCEUNLOCK)) { log_debug(ls, "unlock on rsb_lookup %x", lkb->lkb_id); list_del_init(&lkb->lkb_rsb_lookup); queue_cast(lkb->lkb_resource, lkb, args->flags & DLM_LKF_CANCEL ? -DLM_ECANCEL : -DLM_EUNLOCK); unhold_lkb(lkb); /* undoes create_lkb() */ } /* caller changes -EBUSY to 0 for CANCEL and FORCEUNLOCK */ rv = -EBUSY; goto out; } /* cancel not allowed with another cancel/unlock in progress */ if (args->flags & DLM_LKF_CANCEL) { if (lkb->lkb_exflags & DLM_LKF_CANCEL) goto out; if (is_overlap(lkb)) goto out; /* don't let scand try to do a cancel */ del_timeout(lkb); if (lkb->lkb_flags & DLM_IFL_RESEND) { lkb->lkb_flags |= DLM_IFL_OVERLAP_CANCEL; rv = -EBUSY; goto out; } /* there's nothing to cancel */ if (lkb->lkb_status == DLM_LKSTS_GRANTED && !lkb->lkb_wait_type) { rv = -EBUSY; goto out; } switch (lkb->lkb_wait_type) { case DLM_MSG_LOOKUP: case DLM_MSG_REQUEST: lkb->lkb_flags |= DLM_IFL_OVERLAP_CANCEL; rv = -EBUSY; goto out; case DLM_MSG_UNLOCK: case DLM_MSG_CANCEL: goto out; } /* add_to_waiters() will set OVERLAP_CANCEL */ goto out_ok; } /* do we need to allow a force-unlock if there's a normal unlock already in progress? in what conditions could the normal unlock fail such that we'd want to send a force-unlock to be sure? */ if (args->flags & DLM_LKF_FORCEUNLOCK) { if (lkb->lkb_exflags & DLM_LKF_FORCEUNLOCK) goto out; if (is_overlap_unlock(lkb)) goto out; /* don't let scand try to do a cancel */ del_timeout(lkb); if (lkb->lkb_flags & DLM_IFL_RESEND) { lkb->lkb_flags |= DLM_IFL_OVERLAP_UNLOCK; rv = -EBUSY; goto out; } switch (lkb->lkb_wait_type) { case DLM_MSG_LOOKUP: case DLM_MSG_REQUEST: lkb->lkb_flags |= DLM_IFL_OVERLAP_UNLOCK; rv = -EBUSY; goto out; case DLM_MSG_UNLOCK: goto out; } /* add_to_waiters() will set OVERLAP_UNLOCK */ goto out_ok; } /* normal unlock not allowed if there's any op in progress */ rv = -EBUSY; if (lkb->lkb_wait_type || lkb->lkb_wait_count) goto out; out_ok: /* an overlapping op shouldn't blow away exflags from other op */ lkb->lkb_exflags |= args->flags; lkb->lkb_sbflags = 0; lkb->lkb_astparam = args->astparam; rv = 0; out: if (rv) log_debug(ls, "validate_unlock_args %d %x %x %x %x %d %s", rv, lkb->lkb_id, lkb->lkb_flags, lkb->lkb_exflags, args->flags, lkb->lkb_wait_type, lkb->lkb_resource->res_name); return rv; } /* * Four stage 4 varieties: * do_request(), do_convert(), do_unlock(), do_cancel() * These are called on the master node for the given lock and * from the central locking logic. */ static int do_request(struct dlm_rsb *r, struct dlm_lkb *lkb) { int error = 0; if (can_be_granted(r, lkb, 1, 0, NULL)) { grant_lock(r, lkb); queue_cast(r, lkb, 0); goto out; } if (can_be_queued(lkb)) { error = -EINPROGRESS; add_lkb(r, lkb, DLM_LKSTS_WAITING); add_timeout(lkb); goto out; } error = -EAGAIN; queue_cast(r, lkb, -EAGAIN); out: return error; } static void do_request_effects(struct dlm_rsb *r, struct dlm_lkb *lkb, int error) { switch (error) { case -EAGAIN: if (force_blocking_asts(lkb)) send_blocking_asts_all(r, lkb); break; case -EINPROGRESS: send_blocking_asts(r, lkb); break; } } static int do_convert(struct dlm_rsb *r, struct dlm_lkb *lkb) { int error = 0; int deadlk = 0; /* changing an existing lock may allow others to be granted */ if (can_be_granted(r, lkb, 1, 0, &deadlk)) { grant_lock(r, lkb); queue_cast(r, lkb, 0); goto out; } /* can_be_granted() detected that this lock would block in a conversion deadlock, so we leave it on the granted queue and return EDEADLK in the ast for the convert. */ if (deadlk) { /* it's left on the granted queue */ revert_lock(r, lkb); queue_cast(r, lkb, -EDEADLK); error = -EDEADLK; goto out; } /* is_demoted() means the can_be_granted() above set the grmode to NL, and left us on the granted queue. This auto-demotion (due to CONVDEADLK) might mean other locks, and/or this lock, are now grantable. We have to try to grant other converting locks before we try again to grant this one. */ if (is_demoted(lkb)) { grant_pending_convert(r, DLM_LOCK_IV, NULL, NULL); if (_can_be_granted(r, lkb, 1, 0)) { grant_lock(r, lkb); queue_cast(r, lkb, 0); goto out; } /* else fall through and move to convert queue */ } if (can_be_queued(lkb)) { error = -EINPROGRESS; del_lkb(r, lkb); add_lkb(r, lkb, DLM_LKSTS_CONVERT); add_timeout(lkb); goto out; } error = -EAGAIN; queue_cast(r, lkb, -EAGAIN); out: return error; } static void do_convert_effects(struct dlm_rsb *r, struct dlm_lkb *lkb, int error) { switch (error) { case 0: grant_pending_locks(r, NULL); /* grant_pending_locks also sends basts */ break; case -EAGAIN: if (force_blocking_asts(lkb)) send_blocking_asts_all(r, lkb); break; case -EINPROGRESS: send_blocking_asts(r, lkb); break; } } static int do_unlock(struct dlm_rsb *r, struct dlm_lkb *lkb) { remove_lock(r, lkb); queue_cast(r, lkb, -DLM_EUNLOCK); return -DLM_EUNLOCK; } static void do_unlock_effects(struct dlm_rsb *r, struct dlm_lkb *lkb, int error) { grant_pending_locks(r, NULL); } /* returns: 0 did nothing, -DLM_ECANCEL canceled lock */ static int do_cancel(struct dlm_rsb *r, struct dlm_lkb *lkb) { int error; error = revert_lock(r, lkb); if (error) { queue_cast(r, lkb, -DLM_ECANCEL); return -DLM_ECANCEL; } return 0; } static void do_cancel_effects(struct dlm_rsb *r, struct dlm_lkb *lkb, int error) { if (error) grant_pending_locks(r, NULL); } /* * Four stage 3 varieties: * _request_lock(), _convert_lock(), _unlock_lock(), _cancel_lock() */ /* add a new lkb to a possibly new rsb, called by requesting process */ static int _request_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { int error; /* set_master: sets lkb nodeid from r */ error = set_master(r, lkb); if (error < 0) goto out; if (error) { error = 0; goto out; } if (is_remote(r)) { /* receive_request() calls do_request() on remote node */ error = send_request(r, lkb); } else { error = do_request(r, lkb); /* for remote locks the request_reply is sent between do_request and do_request_effects */ do_request_effects(r, lkb, error); } out: return error; } /* change some property of an existing lkb, e.g. mode */ static int _convert_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { int error; if (is_remote(r)) { /* receive_convert() calls do_convert() on remote node */ error = send_convert(r, lkb); } else { error = do_convert(r, lkb); /* for remote locks the convert_reply is sent between do_convert and do_convert_effects */ do_convert_effects(r, lkb, error); } return error; } /* remove an existing lkb from the granted queue */ static int _unlock_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { int error; if (is_remote(r)) { /* receive_unlock() calls do_unlock() on remote node */ error = send_unlock(r, lkb); } else { error = do_unlock(r, lkb); /* for remote locks the unlock_reply is sent between do_unlock and do_unlock_effects */ do_unlock_effects(r, lkb, error); } return error; } /* remove an existing lkb from the convert or wait queue */ static int _cancel_lock(struct dlm_rsb *r, struct dlm_lkb *lkb) { int error; if (is_remote(r)) { /* receive_cancel() calls do_cancel() on remote node */ error = send_cancel(r, lkb); } else { error = do_cancel(r, lkb); /* for remote locks the cancel_reply is sent between do_cancel and do_cancel_effects */ do_cancel_effects(r, lkb, error); } return error; } /* * Four stage 2 varieties: * request_lock(), convert_lock(), unlock_lock(), cancel_lock() */ static int request_lock(struct dlm_ls *ls, struct dlm_lkb *lkb, char *name, int len, struct dlm_args *args) { struct dlm_rsb *r; int error; error = validate_lock_args(ls, lkb, args); if (error) return error; error = find_rsb(ls, name, len, 0, R_REQUEST, &r); if (error) return error; lock_rsb(r); attach_lkb(r, lkb); lkb->lkb_lksb->sb_lkid = lkb->lkb_id; error = _request_lock(r, lkb); unlock_rsb(r); put_rsb(r); return error; } static int convert_lock(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_args *args) { struct dlm_rsb *r; int error; r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_lock_args(ls, lkb, args); if (error) goto out; error = _convert_lock(r, lkb); out: unlock_rsb(r); put_rsb(r); return error; } static int unlock_lock(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_args *args) { struct dlm_rsb *r; int error; r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_unlock_args(lkb, args); if (error) goto out; error = _unlock_lock(r, lkb); out: unlock_rsb(r); put_rsb(r); return error; } static int cancel_lock(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_args *args) { struct dlm_rsb *r; int error; r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_unlock_args(lkb, args); if (error) goto out; error = _cancel_lock(r, lkb); out: unlock_rsb(r); put_rsb(r); return error; } /* * Two stage 1 varieties: dlm_lock() and dlm_unlock() */ int dlm_lock(dlm_lockspace_t *lockspace, int mode, struct dlm_lksb *lksb, uint32_t flags, void *name, unsigned int namelen, uint32_t parent_lkid, void (*ast) (void *astarg), void *astarg, void (*bast) (void *astarg, int mode)) { struct dlm_ls *ls; struct dlm_lkb *lkb; struct dlm_args args; int error, convert = flags & DLM_LKF_CONVERT; ls = dlm_find_lockspace_local(lockspace); if (!ls) return -EINVAL; dlm_lock_recovery(ls); if (convert) error = find_lkb(ls, lksb->sb_lkid, &lkb); else error = create_lkb(ls, &lkb); if (error) goto out; error = set_lock_args(mode, lksb, flags, namelen, 0, ast, astarg, bast, &args); if (error) goto out_put; if (convert) error = convert_lock(ls, lkb, &args); else error = request_lock(ls, lkb, name, namelen, &args); if (error == -EINPROGRESS) error = 0; out_put: if (convert || error) __put_lkb(ls, lkb); if (error == -EAGAIN || error == -EDEADLK) error = 0; out: dlm_unlock_recovery(ls); dlm_put_lockspace(ls); return error; } int dlm_unlock(dlm_lockspace_t *lockspace, uint32_t lkid, uint32_t flags, struct dlm_lksb *lksb, void *astarg) { struct dlm_ls *ls; struct dlm_lkb *lkb; struct dlm_args args; int error; ls = dlm_find_lockspace_local(lockspace); if (!ls) return -EINVAL; dlm_lock_recovery(ls); error = find_lkb(ls, lkid, &lkb); if (error) goto out; error = set_unlock_args(flags, astarg, &args); if (error) goto out_put; if (flags & DLM_LKF_CANCEL) error = cancel_lock(ls, lkb, &args); else error = unlock_lock(ls, lkb, &args); if (error == -DLM_EUNLOCK || error == -DLM_ECANCEL) error = 0; if (error == -EBUSY && (flags & (DLM_LKF_CANCEL | DLM_LKF_FORCEUNLOCK))) error = 0; out_put: dlm_put_lkb(lkb); out: dlm_unlock_recovery(ls); dlm_put_lockspace(ls); return error; } /* * send/receive routines for remote operations and replies * * send_args * send_common * send_request receive_request * send_convert receive_convert * send_unlock receive_unlock * send_cancel receive_cancel * send_grant receive_grant * send_bast receive_bast * send_lookup receive_lookup * send_remove receive_remove * * send_common_reply * receive_request_reply send_request_reply * receive_convert_reply send_convert_reply * receive_unlock_reply send_unlock_reply * receive_cancel_reply send_cancel_reply * receive_lookup_reply send_lookup_reply */ static int _create_message(struct dlm_ls *ls, int mb_len, int to_nodeid, int mstype, struct dlm_message **ms_ret, struct dlm_mhandle **mh_ret) { struct dlm_message *ms; struct dlm_mhandle *mh; char *mb; /* get_buffer gives us a message handle (mh) that we need to pass into lowcomms_commit and a message buffer (mb) that we write our data into */ mh = dlm_lowcomms_get_buffer(to_nodeid, mb_len, GFP_NOFS, &mb); if (!mh) return -ENOBUFS; memset(mb, 0, mb_len); ms = (struct dlm_message *) mb; ms->m_header.h_version = (DLM_HEADER_MAJOR | DLM_HEADER_MINOR); ms->m_header.h_lockspace = ls->ls_global_id; ms->m_header.h_nodeid = dlm_our_nodeid(); ms->m_header.h_length = mb_len; ms->m_header.h_cmd = DLM_MSG; ms->m_type = mstype; *mh_ret = mh; *ms_ret = ms; return 0; } static int create_message(struct dlm_rsb *r, struct dlm_lkb *lkb, int to_nodeid, int mstype, struct dlm_message **ms_ret, struct dlm_mhandle **mh_ret) { int mb_len = sizeof(struct dlm_message); switch (mstype) { case DLM_MSG_REQUEST: case DLM_MSG_LOOKUP: case DLM_MSG_REMOVE: mb_len += r->res_length; break; case DLM_MSG_CONVERT: case DLM_MSG_UNLOCK: case DLM_MSG_REQUEST_REPLY: case DLM_MSG_CONVERT_REPLY: case DLM_MSG_GRANT: if (lkb && lkb->lkb_lvbptr) mb_len += r->res_ls->ls_lvblen; break; } return _create_message(r->res_ls, mb_len, to_nodeid, mstype, ms_ret, mh_ret); } /* further lowcomms enhancements or alternate implementations may make the return value from this function useful at some point */ static int send_message(struct dlm_mhandle *mh, struct dlm_message *ms) { dlm_message_out(ms); dlm_lowcomms_commit_buffer(mh); return 0; } static void send_args(struct dlm_rsb *r, struct dlm_lkb *lkb, struct dlm_message *ms) { ms->m_nodeid = lkb->lkb_nodeid; ms->m_pid = lkb->lkb_ownpid; ms->m_lkid = lkb->lkb_id; ms->m_remid = lkb->lkb_remid; ms->m_exflags = lkb->lkb_exflags; ms->m_sbflags = lkb->lkb_sbflags; ms->m_flags = lkb->lkb_flags; ms->m_lvbseq = lkb->lkb_lvbseq; ms->m_status = lkb->lkb_status; ms->m_grmode = lkb->lkb_grmode; ms->m_rqmode = lkb->lkb_rqmode; ms->m_hash = r->res_hash; /* m_result and m_bastmode are set from function args, not from lkb fields */ if (lkb->lkb_bastfn) ms->m_asts |= DLM_CB_BAST; if (lkb->lkb_astfn) ms->m_asts |= DLM_CB_CAST; /* compare with switch in create_message; send_remove() doesn't use send_args() */ switch (ms->m_type) { case DLM_MSG_REQUEST: case DLM_MSG_LOOKUP: memcpy(ms->m_extra, r->res_name, r->res_length); break; case DLM_MSG_CONVERT: case DLM_MSG_UNLOCK: case DLM_MSG_REQUEST_REPLY: case DLM_MSG_CONVERT_REPLY: case DLM_MSG_GRANT: if (!lkb->lkb_lvbptr) break; memcpy(ms->m_extra, lkb->lkb_lvbptr, r->res_ls->ls_lvblen); break; } } static int send_common(struct dlm_rsb *r, struct dlm_lkb *lkb, int mstype) { struct dlm_message *ms; struct dlm_mhandle *mh; int to_nodeid, error; to_nodeid = r->res_nodeid; error = add_to_waiters(lkb, mstype, to_nodeid); if (error) return error; error = create_message(r, lkb, to_nodeid, mstype, &ms, &mh); if (error) goto fail; send_args(r, lkb, ms); error = send_message(mh, ms); if (error) goto fail; return 0; fail: remove_from_waiters(lkb, msg_reply_type(mstype)); return error; } static int send_request(struct dlm_rsb *r, struct dlm_lkb *lkb) { return send_common(r, lkb, DLM_MSG_REQUEST); } static int send_convert(struct dlm_rsb *r, struct dlm_lkb *lkb) { int error; error = send_common(r, lkb, DLM_MSG_CONVERT); /* down conversions go without a reply from the master */ if (!error && down_conversion(lkb)) { remove_from_waiters(lkb, DLM_MSG_CONVERT_REPLY); r->res_ls->ls_stub_ms.m_flags = DLM_IFL_STUB_MS; r->res_ls->ls_stub_ms.m_type = DLM_MSG_CONVERT_REPLY; r->res_ls->ls_stub_ms.m_result = 0; __receive_convert_reply(r, lkb, &r->res_ls->ls_stub_ms); } return error; } /* FIXME: if this lkb is the only lock we hold on the rsb, then set MASTER_UNCERTAIN to force the next request on the rsb to confirm that the master is still correct. */ static int send_unlock(struct dlm_rsb *r, struct dlm_lkb *lkb) { return send_common(r, lkb, DLM_MSG_UNLOCK); } static int send_cancel(struct dlm_rsb *r, struct dlm_lkb *lkb) { return send_common(r, lkb, DLM_MSG_CANCEL); } static int send_grant(struct dlm_rsb *r, struct dlm_lkb *lkb) { struct dlm_message *ms; struct dlm_mhandle *mh; int to_nodeid, error; to_nodeid = lkb->lkb_nodeid; error = create_message(r, lkb, to_nodeid, DLM_MSG_GRANT, &ms, &mh); if (error) goto out; send_args(r, lkb, ms); ms->m_result = 0; error = send_message(mh, ms); out: return error; } static int send_bast(struct dlm_rsb *r, struct dlm_lkb *lkb, int mode) { struct dlm_message *ms; struct dlm_mhandle *mh; int to_nodeid, error; to_nodeid = lkb->lkb_nodeid; error = create_message(r, NULL, to_nodeid, DLM_MSG_BAST, &ms, &mh); if (error) goto out; send_args(r, lkb, ms); ms->m_bastmode = mode; error = send_message(mh, ms); out: return error; } static int send_lookup(struct dlm_rsb *r, struct dlm_lkb *lkb) { struct dlm_message *ms; struct dlm_mhandle *mh; int to_nodeid, error; to_nodeid = dlm_dir_nodeid(r); error = add_to_waiters(lkb, DLM_MSG_LOOKUP, to_nodeid); if (error) return error; error = create_message(r, NULL, to_nodeid, DLM_MSG_LOOKUP, &ms, &mh); if (error) goto fail; send_args(r, lkb, ms); error = send_message(mh, ms); if (error) goto fail; return 0; fail: remove_from_waiters(lkb, DLM_MSG_LOOKUP_REPLY); return error; } static int send_remove(struct dlm_rsb *r) { struct dlm_message *ms; struct dlm_mhandle *mh; int to_nodeid, error; to_nodeid = dlm_dir_nodeid(r); error = create_message(r, NULL, to_nodeid, DLM_MSG_REMOVE, &ms, &mh); if (error) goto out; memcpy(ms->m_extra, r->res_name, r->res_length); ms->m_hash = r->res_hash; error = send_message(mh, ms); out: return error; } static int send_common_reply(struct dlm_rsb *r, struct dlm_lkb *lkb, int mstype, int rv) { struct dlm_message *ms; struct dlm_mhandle *mh; int to_nodeid, error; to_nodeid = lkb->lkb_nodeid; error = create_message(r, lkb, to_nodeid, mstype, &ms, &mh); if (error) goto out; send_args(r, lkb, ms); ms->m_result = rv; error = send_message(mh, ms); out: return error; } static int send_request_reply(struct dlm_rsb *r, struct dlm_lkb *lkb, int rv) { return send_common_reply(r, lkb, DLM_MSG_REQUEST_REPLY, rv); } static int send_convert_reply(struct dlm_rsb *r, struct dlm_lkb *lkb, int rv) { return send_common_reply(r, lkb, DLM_MSG_CONVERT_REPLY, rv); } static int send_unlock_reply(struct dlm_rsb *r, struct dlm_lkb *lkb, int rv) { return send_common_reply(r, lkb, DLM_MSG_UNLOCK_REPLY, rv); } static int send_cancel_reply(struct dlm_rsb *r, struct dlm_lkb *lkb, int rv) { return send_common_reply(r, lkb, DLM_MSG_CANCEL_REPLY, rv); } static int send_lookup_reply(struct dlm_ls *ls, struct dlm_message *ms_in, int ret_nodeid, int rv) { struct dlm_rsb *r = &ls->ls_stub_rsb; struct dlm_message *ms; struct dlm_mhandle *mh; int error, nodeid = ms_in->m_header.h_nodeid; error = create_message(r, NULL, nodeid, DLM_MSG_LOOKUP_REPLY, &ms, &mh); if (error) goto out; ms->m_lkid = ms_in->m_lkid; ms->m_result = rv; ms->m_nodeid = ret_nodeid; error = send_message(mh, ms); out: return error; } /* which args we save from a received message depends heavily on the type of message, unlike the send side where we can safely send everything about the lkb for any type of message */ static void receive_flags(struct dlm_lkb *lkb, struct dlm_message *ms) { lkb->lkb_exflags = ms->m_exflags; lkb->lkb_sbflags = ms->m_sbflags; lkb->lkb_flags = (lkb->lkb_flags & 0xFFFF0000) | (ms->m_flags & 0x0000FFFF); } static void receive_flags_reply(struct dlm_lkb *lkb, struct dlm_message *ms) { if (ms->m_flags == DLM_IFL_STUB_MS) return; lkb->lkb_sbflags = ms->m_sbflags; lkb->lkb_flags = (lkb->lkb_flags & 0xFFFF0000) | (ms->m_flags & 0x0000FFFF); } static int receive_extralen(struct dlm_message *ms) { return (ms->m_header.h_length - sizeof(struct dlm_message)); } static int receive_lvb(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_message *ms) { int len; if (lkb->lkb_exflags & DLM_LKF_VALBLK) { if (!lkb->lkb_lvbptr) lkb->lkb_lvbptr = dlm_allocate_lvb(ls); if (!lkb->lkb_lvbptr) return -ENOMEM; len = receive_extralen(ms); if (len > ls->ls_lvblen) len = ls->ls_lvblen; memcpy(lkb->lkb_lvbptr, ms->m_extra, len); } return 0; } static void fake_bastfn(void *astparam, int mode) { log_print("fake_bastfn should not be called"); } static void fake_astfn(void *astparam) { log_print("fake_astfn should not be called"); } static int receive_request_args(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_message *ms) { lkb->lkb_nodeid = ms->m_header.h_nodeid; lkb->lkb_ownpid = ms->m_pid; lkb->lkb_remid = ms->m_lkid; lkb->lkb_grmode = DLM_LOCK_IV; lkb->lkb_rqmode = ms->m_rqmode; lkb->lkb_bastfn = (ms->m_asts & DLM_CB_BAST) ? &fake_bastfn : NULL; lkb->lkb_astfn = (ms->m_asts & DLM_CB_CAST) ? &fake_astfn : NULL; if (lkb->lkb_exflags & DLM_LKF_VALBLK) { /* lkb was just created so there won't be an lvb yet */ lkb->lkb_lvbptr = dlm_allocate_lvb(ls); if (!lkb->lkb_lvbptr) return -ENOMEM; } return 0; } static int receive_convert_args(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_message *ms) { if (lkb->lkb_status != DLM_LKSTS_GRANTED) return -EBUSY; if (receive_lvb(ls, lkb, ms)) return -ENOMEM; lkb->lkb_rqmode = ms->m_rqmode; lkb->lkb_lvbseq = ms->m_lvbseq; return 0; } static int receive_unlock_args(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_message *ms) { if (receive_lvb(ls, lkb, ms)) return -ENOMEM; return 0; } /* We fill in the stub-lkb fields with the info that send_xxxx_reply() uses to send a reply and that the remote end uses to process the reply. */ static void setup_stub_lkb(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb = &ls->ls_stub_lkb; lkb->lkb_nodeid = ms->m_header.h_nodeid; lkb->lkb_remid = ms->m_lkid; } /* This is called after the rsb is locked so that we can safely inspect fields in the lkb. */ static int validate_message(struct dlm_lkb *lkb, struct dlm_message *ms) { int from = ms->m_header.h_nodeid; int error = 0; switch (ms->m_type) { case DLM_MSG_CONVERT: case DLM_MSG_UNLOCK: case DLM_MSG_CANCEL: if (!is_master_copy(lkb) || lkb->lkb_nodeid != from) error = -EINVAL; break; case DLM_MSG_CONVERT_REPLY: case DLM_MSG_UNLOCK_REPLY: case DLM_MSG_CANCEL_REPLY: case DLM_MSG_GRANT: case DLM_MSG_BAST: if (!is_process_copy(lkb) || lkb->lkb_nodeid != from) error = -EINVAL; break; case DLM_MSG_REQUEST_REPLY: if (!is_process_copy(lkb)) error = -EINVAL; else if (lkb->lkb_nodeid != -1 && lkb->lkb_nodeid != from) error = -EINVAL; break; default: error = -EINVAL; } if (error) log_error(lkb->lkb_resource->res_ls, "ignore invalid message %d from %d %x %x %x %d", ms->m_type, from, lkb->lkb_id, lkb->lkb_remid, lkb->lkb_flags, lkb->lkb_nodeid); return error; } static void send_repeat_remove(struct dlm_ls *ls, char *ms_name, int len) { char name[DLM_RESNAME_MAXLEN + 1]; struct dlm_message *ms; struct dlm_mhandle *mh; struct dlm_rsb *r; uint32_t hash, b; int rv, dir_nodeid; memset(name, 0, sizeof(name)); memcpy(name, ms_name, len); hash = jhash(name, len, 0); b = hash & (ls->ls_rsbtbl_size - 1); dir_nodeid = dlm_hash2nodeid(ls, hash); log_error(ls, "send_repeat_remove dir %d %s", dir_nodeid, name); spin_lock(&ls->ls_rsbtbl[b].lock); rv = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].keep, name, len, &r); if (!rv) { spin_unlock(&ls->ls_rsbtbl[b].lock); log_error(ls, "repeat_remove on keep %s", name); return; } rv = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].toss, name, len, &r); if (!rv) { spin_unlock(&ls->ls_rsbtbl[b].lock); log_error(ls, "repeat_remove on toss %s", name); return; } /* use ls->remove_name2 to avoid conflict with shrink? */ spin_lock(&ls->ls_remove_spin); ls->ls_remove_len = len; memcpy(ls->ls_remove_name, name, DLM_RESNAME_MAXLEN); spin_unlock(&ls->ls_remove_spin); spin_unlock(&ls->ls_rsbtbl[b].lock); rv = _create_message(ls, sizeof(struct dlm_message) + len, dir_nodeid, DLM_MSG_REMOVE, &ms, &mh); if (rv) return; memcpy(ms->m_extra, name, len); ms->m_hash = hash; send_message(mh, ms); spin_lock(&ls->ls_remove_spin); ls->ls_remove_len = 0; memset(ls->ls_remove_name, 0, DLM_RESNAME_MAXLEN); spin_unlock(&ls->ls_remove_spin); } static int receive_request(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; struct dlm_rsb *r; int from_nodeid; int error, namelen = 0; from_nodeid = ms->m_header.h_nodeid; error = create_lkb(ls, &lkb); if (error) goto fail; receive_flags(lkb, ms); lkb->lkb_flags |= DLM_IFL_MSTCPY; error = receive_request_args(ls, lkb, ms); if (error) { __put_lkb(ls, lkb); goto fail; } /* The dir node is the authority on whether we are the master for this rsb or not, so if the master sends us a request, we should recreate the rsb if we've destroyed it. This race happens when we send a remove message to the dir node at the same time that the dir node sends us a request for the rsb. */ namelen = receive_extralen(ms); error = find_rsb(ls, ms->m_extra, namelen, from_nodeid, R_RECEIVE_REQUEST, &r); if (error) { __put_lkb(ls, lkb); goto fail; } lock_rsb(r); if (r->res_master_nodeid != dlm_our_nodeid()) { error = validate_master_nodeid(ls, r, from_nodeid); if (error) { unlock_rsb(r); put_rsb(r); __put_lkb(ls, lkb); goto fail; } } attach_lkb(r, lkb); error = do_request(r, lkb); send_request_reply(r, lkb, error); do_request_effects(r, lkb, error); unlock_rsb(r); put_rsb(r); if (error == -EINPROGRESS) error = 0; if (error) dlm_put_lkb(lkb); return 0; fail: /* TODO: instead of returning ENOTBLK, add the lkb to res_lookup and do this receive_request again from process_lookup_list once we get the lookup reply. This would avoid a many repeated ENOTBLK request failures when the lookup reply designating us as master is delayed. */ /* We could repeatedly return -EBADR here if our send_remove() is delayed in being sent/arriving/being processed on the dir node. Another node would repeatedly lookup up the master, and the dir node would continue returning our nodeid until our send_remove took effect. We send another remove message in case our previous send_remove was lost/ignored/missed somehow. */ if (error != -ENOTBLK) { log_limit(ls, "receive_request %x from %d %d", ms->m_lkid, from_nodeid, error); } if (namelen && error == -EBADR) { send_repeat_remove(ls, ms->m_extra, namelen); msleep(1000); } setup_stub_lkb(ls, ms); send_request_reply(&ls->ls_stub_rsb, &ls->ls_stub_lkb, error); return error; } static int receive_convert(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; struct dlm_rsb *r; int error, reply = 1; error = find_lkb(ls, ms->m_remid, &lkb); if (error) goto fail; if (lkb->lkb_remid != ms->m_lkid) { log_error(ls, "receive_convert %x remid %x recover_seq %llu " "remote %d %x", lkb->lkb_id, lkb->lkb_remid, (unsigned long long)lkb->lkb_recover_seq, ms->m_header.h_nodeid, ms->m_lkid); error = -ENOENT; goto fail; } r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; receive_flags(lkb, ms); error = receive_convert_args(ls, lkb, ms); if (error) { send_convert_reply(r, lkb, error); goto out; } reply = !down_conversion(lkb); error = do_convert(r, lkb); if (reply) send_convert_reply(r, lkb, error); do_convert_effects(r, lkb, error); out: unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); return 0; fail: setup_stub_lkb(ls, ms); send_convert_reply(&ls->ls_stub_rsb, &ls->ls_stub_lkb, error); return error; } static int receive_unlock(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; struct dlm_rsb *r; int error; error = find_lkb(ls, ms->m_remid, &lkb); if (error) goto fail; if (lkb->lkb_remid != ms->m_lkid) { log_error(ls, "receive_unlock %x remid %x remote %d %x", lkb->lkb_id, lkb->lkb_remid, ms->m_header.h_nodeid, ms->m_lkid); error = -ENOENT; goto fail; } r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; receive_flags(lkb, ms); error = receive_unlock_args(ls, lkb, ms); if (error) { send_unlock_reply(r, lkb, error); goto out; } error = do_unlock(r, lkb); send_unlock_reply(r, lkb, error); do_unlock_effects(r, lkb, error); out: unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); return 0; fail: setup_stub_lkb(ls, ms); send_unlock_reply(&ls->ls_stub_rsb, &ls->ls_stub_lkb, error); return error; } static int receive_cancel(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; struct dlm_rsb *r; int error; error = find_lkb(ls, ms->m_remid, &lkb); if (error) goto fail; receive_flags(lkb, ms); r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; error = do_cancel(r, lkb); send_cancel_reply(r, lkb, error); do_cancel_effects(r, lkb, error); out: unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); return 0; fail: setup_stub_lkb(ls, ms); send_cancel_reply(&ls->ls_stub_rsb, &ls->ls_stub_lkb, error); return error; } static int receive_grant(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; struct dlm_rsb *r; int error; error = find_lkb(ls, ms->m_remid, &lkb); if (error) return error; r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; receive_flags_reply(lkb, ms); if (is_altmode(lkb)) munge_altmode(lkb, ms); grant_lock_pc(r, lkb, ms); queue_cast(r, lkb, 0); out: unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); return 0; } static int receive_bast(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; struct dlm_rsb *r; int error; error = find_lkb(ls, ms->m_remid, &lkb); if (error) return error; r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; queue_bast(r, lkb, ms->m_bastmode); lkb->lkb_highbast = ms->m_bastmode; out: unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); return 0; } static void receive_lookup(struct dlm_ls *ls, struct dlm_message *ms) { int len, error, ret_nodeid, from_nodeid, our_nodeid; from_nodeid = ms->m_header.h_nodeid; our_nodeid = dlm_our_nodeid(); len = receive_extralen(ms); error = dlm_master_lookup(ls, from_nodeid, ms->m_extra, len, 0, &ret_nodeid, NULL); /* Optimization: we're master so treat lookup as a request */ if (!error && ret_nodeid == our_nodeid) { receive_request(ls, ms); return; } send_lookup_reply(ls, ms, ret_nodeid, error); } static void receive_remove(struct dlm_ls *ls, struct dlm_message *ms) { char name[DLM_RESNAME_MAXLEN+1]; struct dlm_rsb *r; uint32_t hash, b; int rv, len, dir_nodeid, from_nodeid; from_nodeid = ms->m_header.h_nodeid; len = receive_extralen(ms); if (len > DLM_RESNAME_MAXLEN) { log_error(ls, "receive_remove from %d bad len %d", from_nodeid, len); return; } dir_nodeid = dlm_hash2nodeid(ls, ms->m_hash); if (dir_nodeid != dlm_our_nodeid()) { log_error(ls, "receive_remove from %d bad nodeid %d", from_nodeid, dir_nodeid); return; } /* Look for name on rsbtbl.toss, if it's there, kill it. If it's on rsbtbl.keep, it's being used, and we should ignore this message. This is an expected race between the dir node sending a request to the master node at the same time as the master node sends a remove to the dir node. The resolution to that race is for the dir node to ignore the remove message, and the master node to recreate the master rsb when it gets a request from the dir node for an rsb it doesn't have. */ memset(name, 0, sizeof(name)); memcpy(name, ms->m_extra, len); hash = jhash(name, len, 0); b = hash & (ls->ls_rsbtbl_size - 1); spin_lock(&ls->ls_rsbtbl[b].lock); rv = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].toss, name, len, &r); if (rv) { /* verify the rsb is on keep list per comment above */ rv = dlm_search_rsb_tree(&ls->ls_rsbtbl[b].keep, name, len, &r); if (rv) { /* should not happen */ log_error(ls, "receive_remove from %d not found %s", from_nodeid, name); spin_unlock(&ls->ls_rsbtbl[b].lock); return; } if (r->res_master_nodeid != from_nodeid) { /* should not happen */ log_error(ls, "receive_remove keep from %d master %d", from_nodeid, r->res_master_nodeid); dlm_print_rsb(r); spin_unlock(&ls->ls_rsbtbl[b].lock); return; } log_debug(ls, "receive_remove from %d master %d first %x %s", from_nodeid, r->res_master_nodeid, r->res_first_lkid, name); spin_unlock(&ls->ls_rsbtbl[b].lock); return; } if (r->res_master_nodeid != from_nodeid) { log_error(ls, "receive_remove toss from %d master %d", from_nodeid, r->res_master_nodeid); dlm_print_rsb(r); spin_unlock(&ls->ls_rsbtbl[b].lock); return; } if (kref_put(&r->res_ref, kill_rsb)) { rb_erase(&r->res_hashnode, &ls->ls_rsbtbl[b].toss); spin_unlock(&ls->ls_rsbtbl[b].lock); dlm_free_rsb(r); } else { log_error(ls, "receive_remove from %d rsb ref error", from_nodeid); dlm_print_rsb(r); spin_unlock(&ls->ls_rsbtbl[b].lock); } } static void receive_purge(struct dlm_ls *ls, struct dlm_message *ms) { do_purge(ls, ms->m_nodeid, ms->m_pid); } static int receive_request_reply(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; struct dlm_rsb *r; int error, mstype, result; int from_nodeid = ms->m_header.h_nodeid; error = find_lkb(ls, ms->m_remid, &lkb); if (error) return error; r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; mstype = lkb->lkb_wait_type; error = remove_from_waiters(lkb, DLM_MSG_REQUEST_REPLY); if (error) { log_error(ls, "receive_request_reply %x remote %d %x result %d", lkb->lkb_id, from_nodeid, ms->m_lkid, ms->m_result); dlm_dump_rsb(r); goto out; } /* Optimization: the dir node was also the master, so it took our lookup as a request and sent request reply instead of lookup reply */ if (mstype == DLM_MSG_LOOKUP) { r->res_master_nodeid = from_nodeid; r->res_nodeid = from_nodeid; lkb->lkb_nodeid = from_nodeid; } /* this is the value returned from do_request() on the master */ result = ms->m_result; switch (result) { case -EAGAIN: /* request would block (be queued) on remote master */ queue_cast(r, lkb, -EAGAIN); confirm_master(r, -EAGAIN); unhold_lkb(lkb); /* undoes create_lkb() */ break; case -EINPROGRESS: case 0: /* request was queued or granted on remote master */ receive_flags_reply(lkb, ms); lkb->lkb_remid = ms->m_lkid; if (is_altmode(lkb)) munge_altmode(lkb, ms); if (result) { add_lkb(r, lkb, DLM_LKSTS_WAITING); add_timeout(lkb); } else { grant_lock_pc(r, lkb, ms); queue_cast(r, lkb, 0); } confirm_master(r, result); break; case -EBADR: case -ENOTBLK: /* find_rsb failed to find rsb or rsb wasn't master */ log_limit(ls, "receive_request_reply %x from %d %d " "master %d dir %d first %x %s", lkb->lkb_id, from_nodeid, result, r->res_master_nodeid, r->res_dir_nodeid, r->res_first_lkid, r->res_name); if (r->res_dir_nodeid != dlm_our_nodeid() && r->res_master_nodeid != dlm_our_nodeid()) { /* cause _request_lock->set_master->send_lookup */ r->res_master_nodeid = 0; r->res_nodeid = -1; lkb->lkb_nodeid = -1; } if (is_overlap(lkb)) { /* we'll ignore error in cancel/unlock reply */ queue_cast_overlap(r, lkb); confirm_master(r, result); unhold_lkb(lkb); /* undoes create_lkb() */ } else { _request_lock(r, lkb); if (r->res_master_nodeid == dlm_our_nodeid()) confirm_master(r, 0); } break; default: log_error(ls, "receive_request_reply %x error %d", lkb->lkb_id, result); } if (is_overlap_unlock(lkb) && (result == 0 || result == -EINPROGRESS)) { log_debug(ls, "receive_request_reply %x result %d unlock", lkb->lkb_id, result); lkb->lkb_flags &= ~DLM_IFL_OVERLAP_UNLOCK; lkb->lkb_flags &= ~DLM_IFL_OVERLAP_CANCEL; send_unlock(r, lkb); } else if (is_overlap_cancel(lkb) && (result == -EINPROGRESS)) { log_debug(ls, "receive_request_reply %x cancel", lkb->lkb_id); lkb->lkb_flags &= ~DLM_IFL_OVERLAP_UNLOCK; lkb->lkb_flags &= ~DLM_IFL_OVERLAP_CANCEL; send_cancel(r, lkb); } else { lkb->lkb_flags &= ~DLM_IFL_OVERLAP_CANCEL; lkb->lkb_flags &= ~DLM_IFL_OVERLAP_UNLOCK; } out: unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); return 0; } static void __receive_convert_reply(struct dlm_rsb *r, struct dlm_lkb *lkb, struct dlm_message *ms) { /* this is the value returned from do_convert() on the master */ switch (ms->m_result) { case -EAGAIN: /* convert would block (be queued) on remote master */ queue_cast(r, lkb, -EAGAIN); break; case -EDEADLK: receive_flags_reply(lkb, ms); revert_lock_pc(r, lkb); queue_cast(r, lkb, -EDEADLK); break; case -EINPROGRESS: /* convert was queued on remote master */ receive_flags_reply(lkb, ms); if (is_demoted(lkb)) munge_demoted(lkb); del_lkb(r, lkb); add_lkb(r, lkb, DLM_LKSTS_CONVERT); add_timeout(lkb); break; case 0: /* convert was granted on remote master */ receive_flags_reply(lkb, ms); if (is_demoted(lkb)) munge_demoted(lkb); grant_lock_pc(r, lkb, ms); queue_cast(r, lkb, 0); break; default: log_error(r->res_ls, "receive_convert_reply %x remote %d %x %d", lkb->lkb_id, ms->m_header.h_nodeid, ms->m_lkid, ms->m_result); dlm_print_rsb(r); dlm_print_lkb(lkb); } } static void _receive_convert_reply(struct dlm_lkb *lkb, struct dlm_message *ms) { struct dlm_rsb *r = lkb->lkb_resource; int error; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; /* stub reply can happen with waiters_mutex held */ error = remove_from_waiters_ms(lkb, ms); if (error) goto out; __receive_convert_reply(r, lkb, ms); out: unlock_rsb(r); put_rsb(r); } static int receive_convert_reply(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; int error; error = find_lkb(ls, ms->m_remid, &lkb); if (error) return error; _receive_convert_reply(lkb, ms); dlm_put_lkb(lkb); return 0; } static void _receive_unlock_reply(struct dlm_lkb *lkb, struct dlm_message *ms) { struct dlm_rsb *r = lkb->lkb_resource; int error; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; /* stub reply can happen with waiters_mutex held */ error = remove_from_waiters_ms(lkb, ms); if (error) goto out; /* this is the value returned from do_unlock() on the master */ switch (ms->m_result) { case -DLM_EUNLOCK: receive_flags_reply(lkb, ms); remove_lock_pc(r, lkb); queue_cast(r, lkb, -DLM_EUNLOCK); break; case -ENOENT: break; default: log_error(r->res_ls, "receive_unlock_reply %x error %d", lkb->lkb_id, ms->m_result); } out: unlock_rsb(r); put_rsb(r); } static int receive_unlock_reply(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; int error; error = find_lkb(ls, ms->m_remid, &lkb); if (error) return error; _receive_unlock_reply(lkb, ms); dlm_put_lkb(lkb); return 0; } static void _receive_cancel_reply(struct dlm_lkb *lkb, struct dlm_message *ms) { struct dlm_rsb *r = lkb->lkb_resource; int error; hold_rsb(r); lock_rsb(r); error = validate_message(lkb, ms); if (error) goto out; /* stub reply can happen with waiters_mutex held */ error = remove_from_waiters_ms(lkb, ms); if (error) goto out; /* this is the value returned from do_cancel() on the master */ switch (ms->m_result) { case -DLM_ECANCEL: receive_flags_reply(lkb, ms); revert_lock_pc(r, lkb); queue_cast(r, lkb, -DLM_ECANCEL); break; case 0: break; default: log_error(r->res_ls, "receive_cancel_reply %x error %d", lkb->lkb_id, ms->m_result); } out: unlock_rsb(r); put_rsb(r); } static int receive_cancel_reply(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; int error; error = find_lkb(ls, ms->m_remid, &lkb); if (error) return error; _receive_cancel_reply(lkb, ms); dlm_put_lkb(lkb); return 0; } static void receive_lookup_reply(struct dlm_ls *ls, struct dlm_message *ms) { struct dlm_lkb *lkb; struct dlm_rsb *r; int error, ret_nodeid; int do_lookup_list = 0; error = find_lkb(ls, ms->m_lkid, &lkb); if (error) { log_error(ls, "receive_lookup_reply no lkid %x", ms->m_lkid); return; } /* ms->m_result is the value returned by dlm_master_lookup on dir node FIXME: will a non-zero error ever be returned? */ r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = remove_from_waiters(lkb, DLM_MSG_LOOKUP_REPLY); if (error) goto out; ret_nodeid = ms->m_nodeid; /* We sometimes receive a request from the dir node for this rsb before we've received the dir node's loookup_reply for it. The request from the dir node implies we're the master, so we set ourself as master in receive_request_reply, and verify here that we are indeed the master. */ if (r->res_master_nodeid && (r->res_master_nodeid != ret_nodeid)) { /* This should never happen */ log_error(ls, "receive_lookup_reply %x from %d ret %d " "master %d dir %d our %d first %x %s", lkb->lkb_id, ms->m_header.h_nodeid, ret_nodeid, r->res_master_nodeid, r->res_dir_nodeid, dlm_our_nodeid(), r->res_first_lkid, r->res_name); } if (ret_nodeid == dlm_our_nodeid()) { r->res_master_nodeid = ret_nodeid; r->res_nodeid = 0; do_lookup_list = 1; r->res_first_lkid = 0; } else if (ret_nodeid == -1) { /* the remote node doesn't believe it's the dir node */ log_error(ls, "receive_lookup_reply %x from %d bad ret_nodeid", lkb->lkb_id, ms->m_header.h_nodeid); r->res_master_nodeid = 0; r->res_nodeid = -1; lkb->lkb_nodeid = -1; } else { /* set_master() will set lkb_nodeid from r */ r->res_master_nodeid = ret_nodeid; r->res_nodeid = ret_nodeid; } if (is_overlap(lkb)) { log_debug(ls, "receive_lookup_reply %x unlock %x", lkb->lkb_id, lkb->lkb_flags); queue_cast_overlap(r, lkb); unhold_lkb(lkb); /* undoes create_lkb() */ goto out_list; } _request_lock(r, lkb); out_list: if (do_lookup_list) process_lookup_list(r); out: unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); } static void _receive_message(struct dlm_ls *ls, struct dlm_message *ms, uint32_t saved_seq) { int error = 0, noent = 0; if (!dlm_is_member(ls, ms->m_header.h_nodeid)) { log_limit(ls, "receive %d from non-member %d %x %x %d", ms->m_type, ms->m_header.h_nodeid, ms->m_lkid, ms->m_remid, ms->m_result); return; } switch (ms->m_type) { /* messages sent to a master node */ case DLM_MSG_REQUEST: error = receive_request(ls, ms); break; case DLM_MSG_CONVERT: error = receive_convert(ls, ms); break; case DLM_MSG_UNLOCK: error = receive_unlock(ls, ms); break; case DLM_MSG_CANCEL: noent = 1; error = receive_cancel(ls, ms); break; /* messages sent from a master node (replies to above) */ case DLM_MSG_REQUEST_REPLY: error = receive_request_reply(ls, ms); break; case DLM_MSG_CONVERT_REPLY: error = receive_convert_reply(ls, ms); break; case DLM_MSG_UNLOCK_REPLY: error = receive_unlock_reply(ls, ms); break; case DLM_MSG_CANCEL_REPLY: error = receive_cancel_reply(ls, ms); break; /* messages sent from a master node (only two types of async msg) */ case DLM_MSG_GRANT: noent = 1; error = receive_grant(ls, ms); break; case DLM_MSG_BAST: noent = 1; error = receive_bast(ls, ms); break; /* messages sent to a dir node */ case DLM_MSG_LOOKUP: receive_lookup(ls, ms); break; case DLM_MSG_REMOVE: receive_remove(ls, ms); break; /* messages sent from a dir node (remove has no reply) */ case DLM_MSG_LOOKUP_REPLY: receive_lookup_reply(ls, ms); break; /* other messages */ case DLM_MSG_PURGE: receive_purge(ls, ms); break; default: log_error(ls, "unknown message type %d", ms->m_type); } /* * When checking for ENOENT, we're checking the result of * find_lkb(m_remid): * * The lock id referenced in the message wasn't found. This may * happen in normal usage for the async messages and cancel, so * only use log_debug for them. * * Some errors are expected and normal. */ if (error == -ENOENT && noent) { log_debug(ls, "receive %d no %x remote %d %x saved_seq %u", ms->m_type, ms->m_remid, ms->m_header.h_nodeid, ms->m_lkid, saved_seq); } else if (error == -ENOENT) { log_error(ls, "receive %d no %x remote %d %x saved_seq %u", ms->m_type, ms->m_remid, ms->m_header.h_nodeid, ms->m_lkid, saved_seq); if (ms->m_type == DLM_MSG_CONVERT) dlm_dump_rsb_hash(ls, ms->m_hash); } if (error == -EINVAL) { log_error(ls, "receive %d inval from %d lkid %x remid %x " "saved_seq %u", ms->m_type, ms->m_header.h_nodeid, ms->m_lkid, ms->m_remid, saved_seq); } } /* If the lockspace is in recovery mode (locking stopped), then normal messages are saved on the requestqueue for processing after recovery is done. When not in recovery mode, we wait for dlm_recoverd to drain saved messages off the requestqueue before we process new ones. This occurs right after recovery completes when we transition from saving all messages on requestqueue, to processing all the saved messages, to processing new messages as they arrive. */ static void dlm_receive_message(struct dlm_ls *ls, struct dlm_message *ms, int nodeid) { if (dlm_locking_stopped(ls)) { /* If we were a member of this lockspace, left, and rejoined, other nodes may still be sending us messages from the lockspace generation before we left. */ if (!ls->ls_generation) { log_limit(ls, "receive %d from %d ignore old gen", ms->m_type, nodeid); return; } dlm_add_requestqueue(ls, nodeid, ms); } else { dlm_wait_requestqueue(ls); _receive_message(ls, ms, 0); } } /* This is called by dlm_recoverd to process messages that were saved on the requestqueue. */ void dlm_receive_message_saved(struct dlm_ls *ls, struct dlm_message *ms, uint32_t saved_seq) { _receive_message(ls, ms, saved_seq); } /* This is called by the midcomms layer when something is received for the lockspace. It could be either a MSG (normal message sent as part of standard locking activity) or an RCOM (recovery message sent as part of lockspace recovery). */ void dlm_receive_buffer(union dlm_packet *p, int nodeid) { struct dlm_header *hd = &p->header; struct dlm_ls *ls; int type = 0; switch (hd->h_cmd) { case DLM_MSG: dlm_message_in(&p->message); type = p->message.m_type; break; case DLM_RCOM: dlm_rcom_in(&p->rcom); type = p->rcom.rc_type; break; default: log_print("invalid h_cmd %d from %u", hd->h_cmd, nodeid); return; } if (hd->h_nodeid != nodeid) { log_print("invalid h_nodeid %d from %d lockspace %x", hd->h_nodeid, nodeid, hd->h_lockspace); return; } ls = dlm_find_lockspace_global(hd->h_lockspace); if (!ls) { if (dlm_config.ci_log_debug) { printk_ratelimited(KERN_DEBUG "dlm: invalid lockspace " "%u from %d cmd %d type %d\n", hd->h_lockspace, nodeid, hd->h_cmd, type); } if (hd->h_cmd == DLM_RCOM && type == DLM_RCOM_STATUS) dlm_send_ls_not_ready(nodeid, &p->rcom); return; } /* this rwsem allows dlm_ls_stop() to wait for all dlm_recv threads to be inactive (in this ls) before transitioning to recovery mode */ down_read(&ls->ls_recv_active); if (hd->h_cmd == DLM_MSG) dlm_receive_message(ls, &p->message, nodeid); else dlm_receive_rcom(ls, &p->rcom, nodeid); up_read(&ls->ls_recv_active); dlm_put_lockspace(ls); } static void recover_convert_waiter(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_message *ms_stub) { if (middle_conversion(lkb)) { hold_lkb(lkb); memset(ms_stub, 0, sizeof(struct dlm_message)); ms_stub->m_flags = DLM_IFL_STUB_MS; ms_stub->m_type = DLM_MSG_CONVERT_REPLY; ms_stub->m_result = -EINPROGRESS; ms_stub->m_header.h_nodeid = lkb->lkb_nodeid; _receive_convert_reply(lkb, ms_stub); /* Same special case as in receive_rcom_lock_args() */ lkb->lkb_grmode = DLM_LOCK_IV; rsb_set_flag(lkb->lkb_resource, RSB_RECOVER_CONVERT); unhold_lkb(lkb); } else if (lkb->lkb_rqmode >= lkb->lkb_grmode) { lkb->lkb_flags |= DLM_IFL_RESEND; } /* lkb->lkb_rqmode < lkb->lkb_grmode shouldn't happen since down conversions are async; there's no reply from the remote master */ } /* A waiting lkb needs recovery if the master node has failed, or the master node is changing (only when no directory is used) */ static int waiter_needs_recovery(struct dlm_ls *ls, struct dlm_lkb *lkb, int dir_nodeid) { if (dlm_no_directory(ls)) return 1; if (dlm_is_removed(ls, lkb->lkb_wait_nodeid)) return 1; return 0; } /* Recovery for locks that are waiting for replies from nodes that are now gone. We can just complete unlocks and cancels by faking a reply from the dead node. Requests and up-conversions we flag to be resent after recovery. Down-conversions can just be completed with a fake reply like unlocks. Conversions between PR and CW need special attention. */ void dlm_recover_waiters_pre(struct dlm_ls *ls) { struct dlm_lkb *lkb, *safe; struct dlm_message *ms_stub; int wait_type, stub_unlock_result, stub_cancel_result; int dir_nodeid; ms_stub = kmalloc(sizeof(struct dlm_message), GFP_KERNEL); if (!ms_stub) { log_error(ls, "dlm_recover_waiters_pre no mem"); return; } mutex_lock(&ls->ls_waiters_mutex); list_for_each_entry_safe(lkb, safe, &ls->ls_waiters, lkb_wait_reply) { dir_nodeid = dlm_dir_nodeid(lkb->lkb_resource); /* exclude debug messages about unlocks because there can be so many and they aren't very interesting */ if (lkb->lkb_wait_type != DLM_MSG_UNLOCK) { log_debug(ls, "waiter %x remote %x msg %d r_nodeid %d " "lkb_nodeid %d wait_nodeid %d dir_nodeid %d", lkb->lkb_id, lkb->lkb_remid, lkb->lkb_wait_type, lkb->lkb_resource->res_nodeid, lkb->lkb_nodeid, lkb->lkb_wait_nodeid, dir_nodeid); } /* all outstanding lookups, regardless of destination will be resent after recovery is done */ if (lkb->lkb_wait_type == DLM_MSG_LOOKUP) { lkb->lkb_flags |= DLM_IFL_RESEND; continue; } if (!waiter_needs_recovery(ls, lkb, dir_nodeid)) continue; wait_type = lkb->lkb_wait_type; stub_unlock_result = -DLM_EUNLOCK; stub_cancel_result = -DLM_ECANCEL; /* Main reply may have been received leaving a zero wait_type, but a reply for the overlapping op may not have been received. In that case we need to fake the appropriate reply for the overlap op. */ if (!wait_type) { if (is_overlap_cancel(lkb)) { wait_type = DLM_MSG_CANCEL; if (lkb->lkb_grmode == DLM_LOCK_IV) stub_cancel_result = 0; } if (is_overlap_unlock(lkb)) { wait_type = DLM_MSG_UNLOCK; if (lkb->lkb_grmode == DLM_LOCK_IV) stub_unlock_result = -ENOENT; } log_debug(ls, "rwpre overlap %x %x %d %d %d", lkb->lkb_id, lkb->lkb_flags, wait_type, stub_cancel_result, stub_unlock_result); } switch (wait_type) { case DLM_MSG_REQUEST: lkb->lkb_flags |= DLM_IFL_RESEND; break; case DLM_MSG_CONVERT: recover_convert_waiter(ls, lkb, ms_stub); break; case DLM_MSG_UNLOCK: hold_lkb(lkb); memset(ms_stub, 0, sizeof(struct dlm_message)); ms_stub->m_flags = DLM_IFL_STUB_MS; ms_stub->m_type = DLM_MSG_UNLOCK_REPLY; ms_stub->m_result = stub_unlock_result; ms_stub->m_header.h_nodeid = lkb->lkb_nodeid; _receive_unlock_reply(lkb, ms_stub); dlm_put_lkb(lkb); break; case DLM_MSG_CANCEL: hold_lkb(lkb); memset(ms_stub, 0, sizeof(struct dlm_message)); ms_stub->m_flags = DLM_IFL_STUB_MS; ms_stub->m_type = DLM_MSG_CANCEL_REPLY; ms_stub->m_result = stub_cancel_result; ms_stub->m_header.h_nodeid = lkb->lkb_nodeid; _receive_cancel_reply(lkb, ms_stub); dlm_put_lkb(lkb); break; default: log_error(ls, "invalid lkb wait_type %d %d", lkb->lkb_wait_type, wait_type); } schedule(); } mutex_unlock(&ls->ls_waiters_mutex); kfree(ms_stub); } static struct dlm_lkb *find_resend_waiter(struct dlm_ls *ls) { struct dlm_lkb *lkb; int found = 0; mutex_lock(&ls->ls_waiters_mutex); list_for_each_entry(lkb, &ls->ls_waiters, lkb_wait_reply) { if (lkb->lkb_flags & DLM_IFL_RESEND) { hold_lkb(lkb); found = 1; break; } } mutex_unlock(&ls->ls_waiters_mutex); if (!found) lkb = NULL; return lkb; } /* Deal with lookups and lkb's marked RESEND from _pre. We may now be the master or dir-node for r. Processing the lkb may result in it being placed back on waiters. */ /* We do this after normal locking has been enabled and any saved messages (in requestqueue) have been processed. We should be confident that at this point we won't get or process a reply to any of these waiting operations. But, new ops may be coming in on the rsbs/locks here from userspace or remotely. */ /* there may have been an overlap unlock/cancel prior to recovery or after recovery. if before, the lkb may still have a pos wait_count; if after, the overlap flag would just have been set and nothing new sent. we can be confident here than any replies to either the initial op or overlap ops prior to recovery have been received. */ int dlm_recover_waiters_post(struct dlm_ls *ls) { struct dlm_lkb *lkb; struct dlm_rsb *r; int error = 0, mstype, err, oc, ou; while (1) { if (dlm_locking_stopped(ls)) { log_debug(ls, "recover_waiters_post aborted"); error = -EINTR; break; } lkb = find_resend_waiter(ls); if (!lkb) break; r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); mstype = lkb->lkb_wait_type; oc = is_overlap_cancel(lkb); ou = is_overlap_unlock(lkb); err = 0; log_debug(ls, "waiter %x remote %x msg %d r_nodeid %d " "lkb_nodeid %d wait_nodeid %d dir_nodeid %d " "overlap %d %d", lkb->lkb_id, lkb->lkb_remid, mstype, r->res_nodeid, lkb->lkb_nodeid, lkb->lkb_wait_nodeid, dlm_dir_nodeid(r), oc, ou); /* At this point we assume that we won't get a reply to any previous op or overlap op on this lock. First, do a big remove_from_waiters() for all previous ops. */ lkb->lkb_flags &= ~DLM_IFL_RESEND; lkb->lkb_flags &= ~DLM_IFL_OVERLAP_UNLOCK; lkb->lkb_flags &= ~DLM_IFL_OVERLAP_CANCEL; lkb->lkb_wait_type = 0; lkb->lkb_wait_count = 0; mutex_lock(&ls->ls_waiters_mutex); list_del_init(&lkb->lkb_wait_reply); mutex_unlock(&ls->ls_waiters_mutex); unhold_lkb(lkb); /* for waiters list */ if (oc || ou) { /* do an unlock or cancel instead of resending */ switch (mstype) { case DLM_MSG_LOOKUP: case DLM_MSG_REQUEST: queue_cast(r, lkb, ou ? -DLM_EUNLOCK : -DLM_ECANCEL); unhold_lkb(lkb); /* undoes create_lkb() */ break; case DLM_MSG_CONVERT: if (oc) { queue_cast(r, lkb, -DLM_ECANCEL); } else { lkb->lkb_exflags |= DLM_LKF_FORCEUNLOCK; _unlock_lock(r, lkb); } break; default: err = 1; } } else { switch (mstype) { case DLM_MSG_LOOKUP: case DLM_MSG_REQUEST: _request_lock(r, lkb); if (is_master(r)) confirm_master(r, 0); break; case DLM_MSG_CONVERT: _convert_lock(r, lkb); break; default: err = 1; } } if (err) { log_error(ls, "waiter %x msg %d r_nodeid %d " "dir_nodeid %d overlap %d %d", lkb->lkb_id, mstype, r->res_nodeid, dlm_dir_nodeid(r), oc, ou); } unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); } return error; } static void purge_mstcpy_list(struct dlm_ls *ls, struct dlm_rsb *r, struct list_head *list) { struct dlm_lkb *lkb, *safe; list_for_each_entry_safe(lkb, safe, list, lkb_statequeue) { if (!is_master_copy(lkb)) continue; /* don't purge lkbs we've added in recover_master_copy for the current recovery seq */ if (lkb->lkb_recover_seq == ls->ls_recover_seq) continue; del_lkb(r, lkb); /* this put should free the lkb */ if (!dlm_put_lkb(lkb)) log_error(ls, "purged mstcpy lkb not released"); } } void dlm_purge_mstcpy_locks(struct dlm_rsb *r) { struct dlm_ls *ls = r->res_ls; purge_mstcpy_list(ls, r, &r->res_grantqueue); purge_mstcpy_list(ls, r, &r->res_convertqueue); purge_mstcpy_list(ls, r, &r->res_waitqueue); } static void purge_dead_list(struct dlm_ls *ls, struct dlm_rsb *r, struct list_head *list, int nodeid_gone, unsigned int *count) { struct dlm_lkb *lkb, *safe; list_for_each_entry_safe(lkb, safe, list, lkb_statequeue) { if (!is_master_copy(lkb)) continue; if ((lkb->lkb_nodeid == nodeid_gone) || dlm_is_removed(ls, lkb->lkb_nodeid)) { /* tell recover_lvb to invalidate the lvb because a node holding EX/PW failed */ if ((lkb->lkb_exflags & DLM_LKF_VALBLK) && (lkb->lkb_grmode >= DLM_LOCK_PW)) { rsb_set_flag(r, RSB_RECOVER_LVB_INVAL); } del_lkb(r, lkb); /* this put should free the lkb */ if (!dlm_put_lkb(lkb)) log_error(ls, "purged dead lkb not released"); rsb_set_flag(r, RSB_RECOVER_GRANT); (*count)++; } } } /* Get rid of locks held by nodes that are gone. */ void dlm_recover_purge(struct dlm_ls *ls) { struct dlm_rsb *r; struct dlm_member *memb; int nodes_count = 0; int nodeid_gone = 0; unsigned int lkb_count = 0; /* cache one removed nodeid to optimize the common case of a single node removed */ list_for_each_entry(memb, &ls->ls_nodes_gone, list) { nodes_count++; nodeid_gone = memb->nodeid; } if (!nodes_count) return; down_write(&ls->ls_root_sem); list_for_each_entry(r, &ls->ls_root_list, res_root_list) { hold_rsb(r); lock_rsb(r); if (is_master(r)) { purge_dead_list(ls, r, &r->res_grantqueue, nodeid_gone, &lkb_count); purge_dead_list(ls, r, &r->res_convertqueue, nodeid_gone, &lkb_count); purge_dead_list(ls, r, &r->res_waitqueue, nodeid_gone, &lkb_count); } unlock_rsb(r); unhold_rsb(r); cond_resched(); } up_write(&ls->ls_root_sem); if (lkb_count) log_rinfo(ls, "dlm_recover_purge %u locks for %u nodes", lkb_count, nodes_count); } static struct dlm_rsb *find_grant_rsb(struct dlm_ls *ls, int bucket) { struct rb_node *n; struct dlm_rsb *r; spin_lock(&ls->ls_rsbtbl[bucket].lock); for (n = rb_first(&ls->ls_rsbtbl[bucket].keep); n; n = rb_next(n)) { r = rb_entry(n, struct dlm_rsb, res_hashnode); if (!rsb_flag(r, RSB_RECOVER_GRANT)) continue; if (!is_master(r)) { rsb_clear_flag(r, RSB_RECOVER_GRANT); continue; } hold_rsb(r); spin_unlock(&ls->ls_rsbtbl[bucket].lock); return r; } spin_unlock(&ls->ls_rsbtbl[bucket].lock); return NULL; } /* * Attempt to grant locks on resources that we are the master of. * Locks may have become grantable during recovery because locks * from departed nodes have been purged (or not rebuilt), allowing * previously blocked locks to now be granted. The subset of rsb's * we are interested in are those with lkb's on either the convert or * waiting queues. * * Simplest would be to go through each master rsb and check for non-empty * convert or waiting queues, and attempt to grant on those rsbs. * Checking the queues requires lock_rsb, though, for which we'd need * to release the rsbtbl lock. This would make iterating through all * rsb's very inefficient. So, we rely on earlier recovery routines * to set RECOVER_GRANT on any rsb's that we should attempt to grant * locks for. */ void dlm_recover_grant(struct dlm_ls *ls) { struct dlm_rsb *r; int bucket = 0; unsigned int count = 0; unsigned int rsb_count = 0; unsigned int lkb_count = 0; while (1) { r = find_grant_rsb(ls, bucket); if (!r) { if (bucket == ls->ls_rsbtbl_size - 1) break; bucket++; continue; } rsb_count++; count = 0; lock_rsb(r); /* the RECOVER_GRANT flag is checked in the grant path */ grant_pending_locks(r, &count); rsb_clear_flag(r, RSB_RECOVER_GRANT); lkb_count += count; confirm_master(r, 0); unlock_rsb(r); put_rsb(r); cond_resched(); } if (lkb_count) log_rinfo(ls, "dlm_recover_grant %u locks on %u resources", lkb_count, rsb_count); } static struct dlm_lkb *search_remid_list(struct list_head *head, int nodeid, uint32_t remid) { struct dlm_lkb *lkb; list_for_each_entry(lkb, head, lkb_statequeue) { if (lkb->lkb_nodeid == nodeid && lkb->lkb_remid == remid) return lkb; } return NULL; } static struct dlm_lkb *search_remid(struct dlm_rsb *r, int nodeid, uint32_t remid) { struct dlm_lkb *lkb; lkb = search_remid_list(&r->res_grantqueue, nodeid, remid); if (lkb) return lkb; lkb = search_remid_list(&r->res_convertqueue, nodeid, remid); if (lkb) return lkb; lkb = search_remid_list(&r->res_waitqueue, nodeid, remid); if (lkb) return lkb; return NULL; } /* needs at least dlm_rcom + rcom_lock */ static int receive_rcom_lock_args(struct dlm_ls *ls, struct dlm_lkb *lkb, struct dlm_rsb *r, struct dlm_rcom *rc) { struct rcom_lock *rl = (struct rcom_lock *) rc->rc_buf; lkb->lkb_nodeid = rc->rc_header.h_nodeid; lkb->lkb_ownpid = le32_to_cpu(rl->rl_ownpid); lkb->lkb_remid = le32_to_cpu(rl->rl_lkid); lkb->lkb_exflags = le32_to_cpu(rl->rl_exflags); lkb->lkb_flags = le32_to_cpu(rl->rl_flags) & 0x0000FFFF; lkb->lkb_flags |= DLM_IFL_MSTCPY; lkb->lkb_lvbseq = le32_to_cpu(rl->rl_lvbseq); lkb->lkb_rqmode = rl->rl_rqmode; lkb->lkb_grmode = rl->rl_grmode; /* don't set lkb_status because add_lkb wants to itself */ lkb->lkb_bastfn = (rl->rl_asts & DLM_CB_BAST) ? &fake_bastfn : NULL; lkb->lkb_astfn = (rl->rl_asts & DLM_CB_CAST) ? &fake_astfn : NULL; if (lkb->lkb_exflags & DLM_LKF_VALBLK) { int lvblen = rc->rc_header.h_length - sizeof(struct dlm_rcom) - sizeof(struct rcom_lock); if (lvblen > ls->ls_lvblen) return -EINVAL; lkb->lkb_lvbptr = dlm_allocate_lvb(ls); if (!lkb->lkb_lvbptr) return -ENOMEM; memcpy(lkb->lkb_lvbptr, rl->rl_lvb, lvblen); } /* Conversions between PR and CW (middle modes) need special handling. The real granted mode of these converting locks cannot be determined until all locks have been rebuilt on the rsb (recover_conversion) */ if (rl->rl_wait_type == cpu_to_le16(DLM_MSG_CONVERT) && middle_conversion(lkb)) { rl->rl_status = DLM_LKSTS_CONVERT; lkb->lkb_grmode = DLM_LOCK_IV; rsb_set_flag(r, RSB_RECOVER_CONVERT); } return 0; } /* This lkb may have been recovered in a previous aborted recovery so we need to check if the rsb already has an lkb with the given remote nodeid/lkid. If so we just send back a standard reply. If not, we create a new lkb with the given values and send back our lkid. We send back our lkid by sending back the rcom_lock struct we got but with the remid field filled in. */ /* needs at least dlm_rcom + rcom_lock */ int dlm_recover_master_copy(struct dlm_ls *ls, struct dlm_rcom *rc) { struct rcom_lock *rl = (struct rcom_lock *) rc->rc_buf; struct dlm_rsb *r; struct dlm_lkb *lkb; uint32_t remid = 0; int from_nodeid = rc->rc_header.h_nodeid; int error; if (rl->rl_parent_lkid) { error = -EOPNOTSUPP; goto out; } remid = le32_to_cpu(rl->rl_lkid); /* In general we expect the rsb returned to be R_MASTER, but we don't have to require it. Recovery of masters on one node can overlap recovery of locks on another node, so one node can send us MSTCPY locks before we've made ourselves master of this rsb. We can still add new MSTCPY locks that we receive here without any harm; when we make ourselves master, dlm_recover_masters() won't touch the MSTCPY locks we've received early. */ error = find_rsb(ls, rl->rl_name, le16_to_cpu(rl->rl_namelen), from_nodeid, R_RECEIVE_RECOVER, &r); if (error) goto out; lock_rsb(r); if (dlm_no_directory(ls) && (dlm_dir_nodeid(r) != dlm_our_nodeid())) { log_error(ls, "dlm_recover_master_copy remote %d %x not dir", from_nodeid, remid); error = -EBADR; goto out_unlock; } lkb = search_remid(r, from_nodeid, remid); if (lkb) { error = -EEXIST; goto out_remid; } error = create_lkb(ls, &lkb); if (error) goto out_unlock; error = receive_rcom_lock_args(ls, lkb, r, rc); if (error) { __put_lkb(ls, lkb); goto out_unlock; } attach_lkb(r, lkb); add_lkb(r, lkb, rl->rl_status); error = 0; ls->ls_recover_locks_in++; if (!list_empty(&r->res_waitqueue) || !list_empty(&r->res_convertqueue)) rsb_set_flag(r, RSB_RECOVER_GRANT); out_remid: /* this is the new value returned to the lock holder for saving in its process-copy lkb */ rl->rl_remid = cpu_to_le32(lkb->lkb_id); lkb->lkb_recover_seq = ls->ls_recover_seq; out_unlock: unlock_rsb(r); put_rsb(r); out: if (error && error != -EEXIST) log_rinfo(ls, "dlm_recover_master_copy remote %d %x error %d", from_nodeid, remid, error); rl->rl_result = cpu_to_le32(error); return error; } /* needs at least dlm_rcom + rcom_lock */ int dlm_recover_process_copy(struct dlm_ls *ls, struct dlm_rcom *rc) { struct rcom_lock *rl = (struct rcom_lock *) rc->rc_buf; struct dlm_rsb *r; struct dlm_lkb *lkb; uint32_t lkid, remid; int error, result; lkid = le32_to_cpu(rl->rl_lkid); remid = le32_to_cpu(rl->rl_remid); result = le32_to_cpu(rl->rl_result); error = find_lkb(ls, lkid, &lkb); if (error) { log_error(ls, "dlm_recover_process_copy no %x remote %d %x %d", lkid, rc->rc_header.h_nodeid, remid, result); return error; } r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); if (!is_process_copy(lkb)) { log_error(ls, "dlm_recover_process_copy bad %x remote %d %x %d", lkid, rc->rc_header.h_nodeid, remid, result); dlm_dump_rsb(r); unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); return -EINVAL; } switch (result) { case -EBADR: /* There's a chance the new master received our lock before dlm_recover_master_reply(), this wouldn't happen if we did a barrier between recover_masters and recover_locks. */ log_debug(ls, "dlm_recover_process_copy %x remote %d %x %d", lkid, rc->rc_header.h_nodeid, remid, result); dlm_send_rcom_lock(r, lkb); goto out; case -EEXIST: case 0: lkb->lkb_remid = remid; break; default: log_error(ls, "dlm_recover_process_copy %x remote %d %x %d unk", lkid, rc->rc_header.h_nodeid, remid, result); } /* an ack for dlm_recover_locks() which waits for replies from all the locks it sends to new masters */ dlm_recovered_lock(r); out: unlock_rsb(r); put_rsb(r); dlm_put_lkb(lkb); return 0; } int dlm_user_request(struct dlm_ls *ls, struct dlm_user_args *ua, int mode, uint32_t flags, void *name, unsigned int namelen, unsigned long timeout_cs) { struct dlm_lkb *lkb; struct dlm_args args; int error; dlm_lock_recovery(ls); error = create_lkb(ls, &lkb); if (error) { kfree(ua); goto out; } if (flags & DLM_LKF_VALBLK) { ua->lksb.sb_lvbptr = kzalloc(DLM_USER_LVB_LEN, GFP_NOFS); if (!ua->lksb.sb_lvbptr) { kfree(ua); __put_lkb(ls, lkb); error = -ENOMEM; goto out; } } /* After ua is attached to lkb it will be freed by dlm_free_lkb(). When DLM_IFL_USER is set, the dlm knows that this is a userspace lock and that lkb_astparam is the dlm_user_args structure. */ error = set_lock_args(mode, &ua->lksb, flags, namelen, timeout_cs, fake_astfn, ua, fake_bastfn, &args); lkb->lkb_flags |= DLM_IFL_USER; if (error) { __put_lkb(ls, lkb); goto out; } error = request_lock(ls, lkb, name, namelen, &args); switch (error) { case 0: break; case -EINPROGRESS: error = 0; break; case -EAGAIN: error = 0; /* fall through */ default: __put_lkb(ls, lkb); goto out; } /* add this new lkb to the per-process list of locks */ spin_lock(&ua->proc->locks_spin); hold_lkb(lkb); list_add_tail(&lkb->lkb_ownqueue, &ua->proc->locks); spin_unlock(&ua->proc->locks_spin); out: dlm_unlock_recovery(ls); return error; } int dlm_user_convert(struct dlm_ls *ls, struct dlm_user_args *ua_tmp, int mode, uint32_t flags, uint32_t lkid, char *lvb_in, unsigned long timeout_cs) { struct dlm_lkb *lkb; struct dlm_args args; struct dlm_user_args *ua; int error; dlm_lock_recovery(ls); error = find_lkb(ls, lkid, &lkb); if (error) goto out; /* user can change the params on its lock when it converts it, or add an lvb that didn't exist before */ ua = lkb->lkb_ua; if (flags & DLM_LKF_VALBLK && !ua->lksb.sb_lvbptr) { ua->lksb.sb_lvbptr = kzalloc(DLM_USER_LVB_LEN, GFP_NOFS); if (!ua->lksb.sb_lvbptr) { error = -ENOMEM; goto out_put; } } if (lvb_in && ua->lksb.sb_lvbptr) memcpy(ua->lksb.sb_lvbptr, lvb_in, DLM_USER_LVB_LEN); ua->xid = ua_tmp->xid; ua->castparam = ua_tmp->castparam; ua->castaddr = ua_tmp->castaddr; ua->bastparam = ua_tmp->bastparam; ua->bastaddr = ua_tmp->bastaddr; ua->user_lksb = ua_tmp->user_lksb; error = set_lock_args(mode, &ua->lksb, flags, 0, timeout_cs, fake_astfn, ua, fake_bastfn, &args); if (error) goto out_put; error = convert_lock(ls, lkb, &args); if (error == -EINPROGRESS || error == -EAGAIN || error == -EDEADLK) error = 0; out_put: dlm_put_lkb(lkb); out: dlm_unlock_recovery(ls); kfree(ua_tmp); return error; } /* * The caller asks for an orphan lock on a given resource with a given mode. * If a matching lock exists, it's moved to the owner's list of locks and * the lkid is returned. */ int dlm_user_adopt_orphan(struct dlm_ls *ls, struct dlm_user_args *ua_tmp, int mode, uint32_t flags, void *name, unsigned int namelen, unsigned long timeout_cs, uint32_t *lkid) { struct dlm_lkb *lkb; struct dlm_user_args *ua; int found_other_mode = 0; int found = 0; int rv = 0; mutex_lock(&ls->ls_orphans_mutex); list_for_each_entry(lkb, &ls->ls_orphans, lkb_ownqueue) { if (lkb->lkb_resource->res_length != namelen) continue; if (memcmp(lkb->lkb_resource->res_name, name, namelen)) continue; if (lkb->lkb_grmode != mode) { found_other_mode = 1; continue; } found = 1; list_del_init(&lkb->lkb_ownqueue); lkb->lkb_flags &= ~DLM_IFL_ORPHAN; *lkid = lkb->lkb_id; break; } mutex_unlock(&ls->ls_orphans_mutex); if (!found && found_other_mode) { rv = -EAGAIN; goto out; } if (!found) { rv = -ENOENT; goto out; } lkb->lkb_exflags = flags; lkb->lkb_ownpid = (int) current->pid; ua = lkb->lkb_ua; ua->proc = ua_tmp->proc; ua->xid = ua_tmp->xid; ua->castparam = ua_tmp->castparam; ua->castaddr = ua_tmp->castaddr; ua->bastparam = ua_tmp->bastparam; ua->bastaddr = ua_tmp->bastaddr; ua->user_lksb = ua_tmp->user_lksb; /* * The lkb reference from the ls_orphans list was not * removed above, and is now considered the reference * for the proc locks list. */ spin_lock(&ua->proc->locks_spin); list_add_tail(&lkb->lkb_ownqueue, &ua->proc->locks); spin_unlock(&ua->proc->locks_spin); out: kfree(ua_tmp); return rv; } int dlm_user_unlock(struct dlm_ls *ls, struct dlm_user_args *ua_tmp, uint32_t flags, uint32_t lkid, char *lvb_in) { struct dlm_lkb *lkb; struct dlm_args args; struct dlm_user_args *ua; int error; dlm_lock_recovery(ls); error = find_lkb(ls, lkid, &lkb); if (error) goto out; ua = lkb->lkb_ua; if (lvb_in && ua->lksb.sb_lvbptr) memcpy(ua->lksb.sb_lvbptr, lvb_in, DLM_USER_LVB_LEN); if (ua_tmp->castparam) ua->castparam = ua_tmp->castparam; ua->user_lksb = ua_tmp->user_lksb; error = set_unlock_args(flags, ua, &args); if (error) goto out_put; error = unlock_lock(ls, lkb, &args); if (error == -DLM_EUNLOCK) error = 0; /* from validate_unlock_args() */ if (error == -EBUSY && (flags & DLM_LKF_FORCEUNLOCK)) error = 0; if (error) goto out_put; spin_lock(&ua->proc->locks_spin); /* dlm_user_add_cb() may have already taken lkb off the proc list */ if (!list_empty(&lkb->lkb_ownqueue)) list_move(&lkb->lkb_ownqueue, &ua->proc->unlocking); spin_unlock(&ua->proc->locks_spin); out_put: dlm_put_lkb(lkb); out: dlm_unlock_recovery(ls); kfree(ua_tmp); return error; } int dlm_user_cancel(struct dlm_ls *ls, struct dlm_user_args *ua_tmp, uint32_t flags, uint32_t lkid) { struct dlm_lkb *lkb; struct dlm_args args; struct dlm_user_args *ua; int error; dlm_lock_recovery(ls); error = find_lkb(ls, lkid, &lkb); if (error) goto out; ua = lkb->lkb_ua; if (ua_tmp->castparam) ua->castparam = ua_tmp->castparam; ua->user_lksb = ua_tmp->user_lksb; error = set_unlock_args(flags, ua, &args); if (error) goto out_put; error = cancel_lock(ls, lkb, &args); if (error == -DLM_ECANCEL) error = 0; /* from validate_unlock_args() */ if (error == -EBUSY) error = 0; out_put: dlm_put_lkb(lkb); out: dlm_unlock_recovery(ls); kfree(ua_tmp); return error; } int dlm_user_deadlock(struct dlm_ls *ls, uint32_t flags, uint32_t lkid) { struct dlm_lkb *lkb; struct dlm_args args; struct dlm_user_args *ua; struct dlm_rsb *r; int error; dlm_lock_recovery(ls); error = find_lkb(ls, lkid, &lkb); if (error) goto out; ua = lkb->lkb_ua; error = set_unlock_args(flags, ua, &args); if (error) goto out_put; /* same as cancel_lock(), but set DEADLOCK_CANCEL after lock_rsb */ r = lkb->lkb_resource; hold_rsb(r); lock_rsb(r); error = validate_unlock_args(lkb, &args); if (error) goto out_r; lkb->lkb_flags |= DLM_IFL_DEADLOCK_CANCEL; error = _cancel_lock(r, lkb); out_r: unlock_rsb(r); put_rsb(r); if (error == -DLM_ECANCEL) error = 0; /* from validate_unlock_args() */ if (error == -EBUSY) error = 0; out_put: dlm_put_lkb(lkb); out: dlm_unlock_recovery(ls); return error; } /* lkb's that are removed from the waiters list by revert are just left on the orphans list with the granted orphan locks, to be freed by purge */ static int orphan_proc_lock(struct dlm_ls *ls, struct dlm_lkb *lkb) { struct dlm_args args; int error; hold_lkb(lkb); /* reference for the ls_orphans list */ mutex_lock(&ls->ls_orphans_mutex); list_add_tail(&lkb->lkb_ownqueue, &ls->ls_orphans); mutex_unlock(&ls->ls_orphans_mutex); set_unlock_args(0, lkb->lkb_ua, &args); error = cancel_lock(ls, lkb, &args); if (error == -DLM_ECANCEL) error = 0; return error; } /* The FORCEUNLOCK flag allows the unlock to go ahead even if the lkb isn't granted. Regardless of what rsb queue the lock is on, it's removed and freed. The IVVALBLK flag causes the lvb on the resource to be invalidated if our lock is PW/EX (it's ignored if our granted mode is smaller.) */ static int unlock_proc_lock(struct dlm_ls *ls, struct dlm_lkb *lkb) { struct dlm_args args; int error; set_unlock_args(DLM_LKF_FORCEUNLOCK | DLM_LKF_IVVALBLK, lkb->lkb_ua, &args); error = unlock_lock(ls, lkb, &args); if (error == -DLM_EUNLOCK) error = 0; return error; } /* We have to release clear_proc_locks mutex before calling unlock_proc_lock() (which does lock_rsb) due to deadlock with receiving a message that does lock_rsb followed by dlm_user_add_cb() */ static struct dlm_lkb *del_proc_lock(struct dlm_ls *ls, struct dlm_user_proc *proc) { struct dlm_lkb *lkb = NULL; mutex_lock(&ls->ls_clear_proc_locks); if (list_empty(&proc->locks)) goto out; lkb = list_entry(proc->locks.next, struct dlm_lkb, lkb_ownqueue); list_del_init(&lkb->lkb_ownqueue); if (lkb->lkb_exflags & DLM_LKF_PERSISTENT) lkb->lkb_flags |= DLM_IFL_ORPHAN; else lkb->lkb_flags |= DLM_IFL_DEAD; out: mutex_unlock(&ls->ls_clear_proc_locks); return lkb; } /* The ls_clear_proc_locks mutex protects against dlm_user_add_cb() which 1) references lkb->ua which we free here and 2) adds lkbs to proc->asts, which we clear here. */ /* proc CLOSING flag is set so no more device_reads should look at proc->asts list, and no more device_writes should add lkb's to proc->locks list; so we shouldn't need to take asts_spin or locks_spin here. this assumes that device reads/writes/closes are serialized -- FIXME: we may need to serialize them ourself. */ void dlm_clear_proc_locks(struct dlm_ls *ls, struct dlm_user_proc *proc) { struct dlm_lkb *lkb, *safe; dlm_lock_recovery(ls); while (1) { lkb = del_proc_lock(ls, proc); if (!lkb) break; del_timeout(lkb); if (lkb->lkb_exflags & DLM_LKF_PERSISTENT) orphan_proc_lock(ls, lkb); else unlock_proc_lock(ls, lkb); /* this removes the reference for the proc->locks list added by dlm_user_request, it may result in the lkb being freed */ dlm_put_lkb(lkb); } mutex_lock(&ls->ls_clear_proc_locks); /* in-progress unlocks */ list_for_each_entry_safe(lkb, safe, &proc->unlocking, lkb_ownqueue) { list_del_init(&lkb->lkb_ownqueue); lkb->lkb_flags |= DLM_IFL_DEAD; dlm_put_lkb(lkb); } list_for_each_entry_safe(lkb, safe, &proc->asts, lkb_cb_list) { memset(&lkb->lkb_callbacks, 0, sizeof(struct dlm_callback) * DLM_CALLBACKS_SIZE); list_del_init(&lkb->lkb_cb_list); dlm_put_lkb(lkb); } mutex_unlock(&ls->ls_clear_proc_locks); dlm_unlock_recovery(ls); } static void purge_proc_locks(struct dlm_ls *ls, struct dlm_user_proc *proc) { struct dlm_lkb *lkb, *safe; while (1) { lkb = NULL; spin_lock(&proc->locks_spin); if (!list_empty(&proc->locks)) { lkb = list_entry(proc->locks.next, struct dlm_lkb, lkb_ownqueue); list_del_init(&lkb->lkb_ownqueue); } spin_unlock(&proc->locks_spin); if (!lkb) break; lkb->lkb_flags |= DLM_IFL_DEAD; unlock_proc_lock(ls, lkb); dlm_put_lkb(lkb); /* ref from proc->locks list */ } spin_lock(&proc->locks_spin); list_for_each_entry_safe(lkb, safe, &proc->unlocking, lkb_ownqueue) { list_del_init(&lkb->lkb_ownqueue); lkb->lkb_flags |= DLM_IFL_DEAD; dlm_put_lkb(lkb); } spin_unlock(&proc->locks_spin); spin_lock(&proc->asts_spin); list_for_each_entry_safe(lkb, safe, &proc->asts, lkb_cb_list) { memset(&lkb->lkb_callbacks, 0, sizeof(struct dlm_callback) * DLM_CALLBACKS_SIZE); list_del_init(&lkb->lkb_cb_list); dlm_put_lkb(lkb); } spin_unlock(&proc->asts_spin); } /* pid of 0 means purge all orphans */ static void do_purge(struct dlm_ls *ls, int nodeid, int pid) { struct dlm_lkb *lkb, *safe; mutex_lock(&ls->ls_orphans_mutex); list_for_each_entry_safe(lkb, safe, &ls->ls_orphans, lkb_ownqueue) { if (pid && lkb->lkb_ownpid != pid) continue; unlock_proc_lock(ls, lkb); list_del_init(&lkb->lkb_ownqueue); dlm_put_lkb(lkb); } mutex_unlock(&ls->ls_orphans_mutex); } static int send_purge(struct dlm_ls *ls, int nodeid, int pid) { struct dlm_message *ms; struct dlm_mhandle *mh; int error; error = _create_message(ls, sizeof(struct dlm_message), nodeid, DLM_MSG_PURGE, &ms, &mh); if (error) return error; ms->m_nodeid = nodeid; ms->m_pid = pid; return send_message(mh, ms); } int dlm_user_purge(struct dlm_ls *ls, struct dlm_user_proc *proc, int nodeid, int pid) { int error = 0; if (nodeid && (nodeid != dlm_our_nodeid())) { error = send_purge(ls, nodeid, pid); } else { dlm_lock_recovery(ls); if (pid == current->pid) purge_proc_locks(ls, proc); else do_purge(ls, nodeid, pid); dlm_unlock_recovery(ls); } return error; }
gpl-3.0
luckypoem/shadowsocks-android
src/main/jni/openssl/crypto/ts/ts_rsp_verify.c
467
21702
/* crypto/ts/ts_resp_verify.c */ /* Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL * project 2002. */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/objects.h> #include <openssl/ts.h> #include <openssl/pkcs7.h> /* Private function declarations. */ static int TS_verify_cert(X509_STORE *store, STACK_OF(X509) *untrusted, X509 *signer, STACK_OF(X509) **chain); static int TS_check_signing_certs(PKCS7_SIGNER_INFO *si, STACK_OF(X509) *chain); static ESS_SIGNING_CERT *ESS_get_signing_cert(PKCS7_SIGNER_INFO *si); static int TS_find_cert(STACK_OF(ESS_CERT_ID) *cert_ids, X509 *cert); static int TS_issuer_serial_cmp(ESS_ISSUER_SERIAL *is, X509_CINF *cinfo); static int int_TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token, TS_TST_INFO *tst_info); static int TS_check_status_info(TS_RESP *response); static char *TS_get_status_text(STACK_OF(ASN1_UTF8STRING) *text); static int TS_check_policy(ASN1_OBJECT *req_oid, TS_TST_INFO *tst_info); static int TS_compute_imprint(BIO *data, TS_TST_INFO *tst_info, X509_ALGOR **md_alg, unsigned char **imprint, unsigned *imprint_len); static int TS_check_imprints(X509_ALGOR *algor_a, unsigned char *imprint_a, unsigned len_a, TS_TST_INFO *tst_info); static int TS_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info); static int TS_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer); static int TS_find_name(STACK_OF(GENERAL_NAME) *gen_names, GENERAL_NAME *name); /* * Local mapping between response codes and descriptions. * Don't forget to change TS_STATUS_BUF_SIZE when modifying * the elements of this array. */ static const char *TS_status_text[] = { "granted", "grantedWithMods", "rejection", "waiting", "revocationWarning", "revocationNotification" }; #define TS_STATUS_TEXT_SIZE (sizeof(TS_status_text)/sizeof(*TS_status_text)) /* * This must be greater or equal to the sum of the strings in TS_status_text * plus the number of its elements. */ #define TS_STATUS_BUF_SIZE 256 static struct { int code; const char *text; } TS_failure_info[] = { { TS_INFO_BAD_ALG, "badAlg" }, { TS_INFO_BAD_REQUEST, "badRequest" }, { TS_INFO_BAD_DATA_FORMAT, "badDataFormat" }, { TS_INFO_TIME_NOT_AVAILABLE, "timeNotAvailable" }, { TS_INFO_UNACCEPTED_POLICY, "unacceptedPolicy" }, { TS_INFO_UNACCEPTED_EXTENSION, "unacceptedExtension" }, { TS_INFO_ADD_INFO_NOT_AVAILABLE, "addInfoNotAvailable" }, { TS_INFO_SYSTEM_FAILURE, "systemFailure" } }; #define TS_FAILURE_INFO_SIZE (sizeof(TS_failure_info) / \ sizeof(*TS_failure_info)) /* Functions for verifying a signed TS_TST_INFO structure. */ /* * This function carries out the following tasks: * - Checks if there is one and only one signer. * - Search for the signing certificate in 'certs' and in the response. * - Check the extended key usage and key usage fields of the signer * certificate (done by the path validation). * - Build and validate the certificate path. * - Check if the certificate path meets the requirements of the * SigningCertificate ESS signed attribute. * - Verify the signature value. * - Returns the signer certificate in 'signer', if 'signer' is not NULL. */ int TS_RESP_verify_signature(PKCS7 *token, STACK_OF(X509) *certs, X509_STORE *store, X509 **signer_out) { STACK_OF(PKCS7_SIGNER_INFO) *sinfos = NULL; PKCS7_SIGNER_INFO *si; STACK_OF(X509) *signers = NULL; X509 *signer; STACK_OF(X509) *chain = NULL; char buf[4096]; int i, j = 0, ret = 0; BIO *p7bio = NULL; /* Some sanity checks first. */ if (!token) { TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_INVALID_NULL_POINTER); goto err; } /* Check for the correct content type */ if(!PKCS7_type_is_signed(token)) { TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_WRONG_CONTENT_TYPE); goto err; } /* Check if there is one and only one signer. */ sinfos = PKCS7_get_signer_info(token); if (!sinfos || sk_PKCS7_SIGNER_INFO_num(sinfos) != 1) { TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_THERE_MUST_BE_ONE_SIGNER); goto err; } si = sk_PKCS7_SIGNER_INFO_value(sinfos, 0); /* Check for no content: no data to verify signature. */ if (PKCS7_get_detached(token)) { TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_NO_CONTENT); goto err; } /* Get hold of the signer certificate, search only internal certificates if it was requested. */ signers = PKCS7_get0_signers(token, certs, 0); if (!signers || sk_X509_num(signers) != 1) goto err; signer = sk_X509_value(signers, 0); /* Now verify the certificate. */ if (!TS_verify_cert(store, certs, signer, &chain)) goto err; /* Check if the signer certificate is consistent with the ESS extension. */ if (!TS_check_signing_certs(si, chain)) goto err; /* Creating the message digest. */ p7bio = PKCS7_dataInit(token, NULL); /* We now have to 'read' from p7bio to calculate digests etc. */ while ((i = BIO_read(p7bio,buf,sizeof(buf))) > 0); /* Verifying the signature. */ j = PKCS7_signatureVerify(p7bio, token, si, signer); if (j <= 0) { TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_SIGNATURE_FAILURE); goto err; } /* Return the signer certificate if needed. */ if (signer_out) { *signer_out = signer; CRYPTO_add(&signer->references, 1, CRYPTO_LOCK_X509); } ret = 1; err: BIO_free_all(p7bio); sk_X509_pop_free(chain, X509_free); sk_X509_free(signers); return ret; } /* * The certificate chain is returned in chain. Caller is responsible for * freeing the vector. */ static int TS_verify_cert(X509_STORE *store, STACK_OF(X509) *untrusted, X509 *signer, STACK_OF(X509) **chain) { X509_STORE_CTX cert_ctx; int i; int ret = 1; /* chain is an out argument. */ *chain = NULL; X509_STORE_CTX_init(&cert_ctx, store, signer, untrusted); X509_STORE_CTX_set_purpose(&cert_ctx, X509_PURPOSE_TIMESTAMP_SIGN); i = X509_verify_cert(&cert_ctx); if (i <= 0) { int j = X509_STORE_CTX_get_error(&cert_ctx); TSerr(TS_F_TS_VERIFY_CERT, TS_R_CERTIFICATE_VERIFY_ERROR); ERR_add_error_data(2, "Verify error:", X509_verify_cert_error_string(j)); ret = 0; } else { /* Get a copy of the certificate chain. */ *chain = X509_STORE_CTX_get1_chain(&cert_ctx); } X509_STORE_CTX_cleanup(&cert_ctx); return ret; } static int TS_check_signing_certs(PKCS7_SIGNER_INFO *si, STACK_OF(X509) *chain) { ESS_SIGNING_CERT *ss = ESS_get_signing_cert(si); STACK_OF(ESS_CERT_ID) *cert_ids = NULL; X509 *cert; int i = 0; int ret = 0; if (!ss) goto err; cert_ids = ss->cert_ids; /* The signer certificate must be the first in cert_ids. */ cert = sk_X509_value(chain, 0); if (TS_find_cert(cert_ids, cert) != 0) goto err; /* Check the other certificates of the chain if there are more than one certificate ids in cert_ids. */ if (sk_ESS_CERT_ID_num(cert_ids) > 1) { /* All the certificates of the chain must be in cert_ids. */ for (i = 1; i < sk_X509_num(chain); ++i) { cert = sk_X509_value(chain, i); if (TS_find_cert(cert_ids, cert) < 0) goto err; } } ret = 1; err: if (!ret) TSerr(TS_F_TS_CHECK_SIGNING_CERTS, TS_R_ESS_SIGNING_CERTIFICATE_ERROR); ESS_SIGNING_CERT_free(ss); return ret; } static ESS_SIGNING_CERT *ESS_get_signing_cert(PKCS7_SIGNER_INFO *si) { ASN1_TYPE *attr; const unsigned char *p; attr = PKCS7_get_signed_attribute(si, NID_id_smime_aa_signingCertificate); if (!attr) return NULL; p = attr->value.sequence->data; return d2i_ESS_SIGNING_CERT(NULL, &p, attr->value.sequence->length); } /* Returns < 0 if certificate is not found, certificate index otherwise. */ static int TS_find_cert(STACK_OF(ESS_CERT_ID) *cert_ids, X509 *cert) { int i; if (!cert_ids || !cert) return -1; /* Recompute SHA1 hash of certificate if necessary (side effect). */ X509_check_purpose(cert, -1, 0); /* Look for cert in the cert_ids vector. */ for (i = 0; i < sk_ESS_CERT_ID_num(cert_ids); ++i) { ESS_CERT_ID *cid = sk_ESS_CERT_ID_value(cert_ids, i); /* Check the SHA-1 hash first. */ if (cid->hash->length == sizeof(cert->sha1_hash) && !memcmp(cid->hash->data, cert->sha1_hash, sizeof(cert->sha1_hash))) { /* Check the issuer/serial as well if specified. */ ESS_ISSUER_SERIAL *is = cid->issuer_serial; if (!is || !TS_issuer_serial_cmp(is, cert->cert_info)) return i; } } return -1; } static int TS_issuer_serial_cmp(ESS_ISSUER_SERIAL *is, X509_CINF *cinfo) { GENERAL_NAME *issuer; if (!is || !cinfo || sk_GENERAL_NAME_num(is->issuer) != 1) return -1; /* Check the issuer first. It must be a directory name. */ issuer = sk_GENERAL_NAME_value(is->issuer, 0); if (issuer->type != GEN_DIRNAME || X509_NAME_cmp(issuer->d.dirn, cinfo->issuer)) return -1; /* Check the serial number, too. */ if (ASN1_INTEGER_cmp(is->serial, cinfo->serialNumber)) return -1; return 0; } /* * Verifies whether 'response' contains a valid response with regards * to the settings of the context: * - Gives an error message if the TS_TST_INFO is not present. * - Calls _TS_RESP_verify_token to verify the token content. */ int TS_RESP_verify_response(TS_VERIFY_CTX *ctx, TS_RESP *response) { PKCS7 *token = TS_RESP_get_token(response); TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response); int ret = 0; /* Check if we have a successful TS_TST_INFO object in place. */ if (!TS_check_status_info(response)) goto err; /* Check the contents of the time stamp token. */ if (!int_TS_RESP_verify_token(ctx, token, tst_info)) goto err; ret = 1; err: return ret; } /* * Tries to extract a TS_TST_INFO structure from the PKCS7 token and * calls the internal int_TS_RESP_verify_token function for verifying it. */ int TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token) { TS_TST_INFO *tst_info = PKCS7_to_TS_TST_INFO(token); int ret = 0; if (tst_info) { ret = int_TS_RESP_verify_token(ctx, token, tst_info); TS_TST_INFO_free(tst_info); } return ret; } /* * Verifies whether the 'token' contains a valid time stamp token * with regards to the settings of the context. Only those checks are * carried out that are specified in the context: * - Verifies the signature of the TS_TST_INFO. * - Checks the version number of the response. * - Check if the requested and returned policies math. * - Check if the message imprints are the same. * - Check if the nonces are the same. * - Check if the TSA name matches the signer. * - Check if the TSA name is the expected TSA. */ static int int_TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token, TS_TST_INFO *tst_info) { X509 *signer = NULL; GENERAL_NAME *tsa_name = TS_TST_INFO_get_tsa(tst_info); X509_ALGOR *md_alg = NULL; unsigned char *imprint = NULL; unsigned imprint_len = 0; int ret = 0; /* Verify the signature. */ if ((ctx->flags & TS_VFY_SIGNATURE) && !TS_RESP_verify_signature(token, ctx->certs, ctx->store, &signer)) goto err; /* Check version number of response. */ if ((ctx->flags & TS_VFY_VERSION) && TS_TST_INFO_get_version(tst_info) != 1) { TSerr(TS_F_INT_TS_RESP_VERIFY_TOKEN, TS_R_UNSUPPORTED_VERSION); goto err; } /* Check policies. */ if ((ctx->flags & TS_VFY_POLICY) && !TS_check_policy(ctx->policy, tst_info)) goto err; /* Check message imprints. */ if ((ctx->flags & TS_VFY_IMPRINT) && !TS_check_imprints(ctx->md_alg, ctx->imprint, ctx->imprint_len, tst_info)) goto err; /* Compute and check message imprints. */ if ((ctx->flags & TS_VFY_DATA) && (!TS_compute_imprint(ctx->data, tst_info, &md_alg, &imprint, &imprint_len) || !TS_check_imprints(md_alg, imprint, imprint_len, tst_info))) goto err; /* Check nonces. */ if ((ctx->flags & TS_VFY_NONCE) && !TS_check_nonces(ctx->nonce, tst_info)) goto err; /* Check whether TSA name and signer certificate match. */ if ((ctx->flags & TS_VFY_SIGNER) && tsa_name && !TS_check_signer_name(tsa_name, signer)) { TSerr(TS_F_INT_TS_RESP_VERIFY_TOKEN, TS_R_TSA_NAME_MISMATCH); goto err; } /* Check whether the TSA is the expected one. */ if ((ctx->flags & TS_VFY_TSA_NAME) && !TS_check_signer_name(ctx->tsa_name, signer)) { TSerr(TS_F_INT_TS_RESP_VERIFY_TOKEN, TS_R_TSA_UNTRUSTED); goto err; } ret = 1; err: X509_free(signer); X509_ALGOR_free(md_alg); OPENSSL_free(imprint); return ret; } static int TS_check_status_info(TS_RESP *response) { TS_STATUS_INFO *info = TS_RESP_get_status_info(response); long status = ASN1_INTEGER_get(info->status); const char *status_text = NULL; char *embedded_status_text = NULL; char failure_text[TS_STATUS_BUF_SIZE] = ""; /* Check if everything went fine. */ if (status == 0 || status == 1) return 1; /* There was an error, get the description in status_text. */ if (0 <= status && status < (long)TS_STATUS_TEXT_SIZE) status_text = TS_status_text[status]; else status_text = "unknown code"; /* Set the embedded_status_text to the returned description. */ if (sk_ASN1_UTF8STRING_num(info->text) > 0 && !(embedded_status_text = TS_get_status_text(info->text))) return 0; /* Filling in failure_text with the failure information. */ if (info->failure_info) { int i; int first = 1; for (i = 0; i < (int)TS_FAILURE_INFO_SIZE; ++i) { if (ASN1_BIT_STRING_get_bit(info->failure_info, TS_failure_info[i].code)) { if (!first) strcpy(failure_text, ","); else first = 0; strcat(failure_text, TS_failure_info[i].text); } } } if (failure_text[0] == '\0') strcpy(failure_text, "unspecified"); /* Making up the error string. */ TSerr(TS_F_TS_CHECK_STATUS_INFO, TS_R_NO_TIME_STAMP_TOKEN); ERR_add_error_data(6, "status code: ", status_text, ", status text: ", embedded_status_text ? embedded_status_text : "unspecified", ", failure codes: ", failure_text); OPENSSL_free(embedded_status_text); return 0; } static char *TS_get_status_text(STACK_OF(ASN1_UTF8STRING) *text) { int i; unsigned int length = 0; char *result = NULL; char *p; /* Determine length first. */ for (i = 0; i < sk_ASN1_UTF8STRING_num(text); ++i) { ASN1_UTF8STRING *current = sk_ASN1_UTF8STRING_value(text, i); length += ASN1_STRING_length(current); length += 1; /* separator character */ } /* Allocate memory (closing '\0' included). */ if (!(result = OPENSSL_malloc(length))) { TSerr(TS_F_TS_GET_STATUS_TEXT, ERR_R_MALLOC_FAILURE); return NULL; } /* Concatenate the descriptions. */ for (i = 0, p = result; i < sk_ASN1_UTF8STRING_num(text); ++i) { ASN1_UTF8STRING *current = sk_ASN1_UTF8STRING_value(text, i); length = ASN1_STRING_length(current); if (i > 0) *p++ = '/'; strncpy(p, (const char *)ASN1_STRING_data(current), length); p += length; } /* We do have space for this, too. */ *p = '\0'; return result; } static int TS_check_policy(ASN1_OBJECT *req_oid, TS_TST_INFO *tst_info) { ASN1_OBJECT *resp_oid = TS_TST_INFO_get_policy_id(tst_info); if (OBJ_cmp(req_oid, resp_oid) != 0) { TSerr(TS_F_TS_CHECK_POLICY, TS_R_POLICY_MISMATCH); return 0; } return 1; } static int TS_compute_imprint(BIO *data, TS_TST_INFO *tst_info, X509_ALGOR **md_alg, unsigned char **imprint, unsigned *imprint_len) { TS_MSG_IMPRINT *msg_imprint = TS_TST_INFO_get_msg_imprint(tst_info); X509_ALGOR *md_alg_resp = TS_MSG_IMPRINT_get_algo(msg_imprint); const EVP_MD *md; EVP_MD_CTX md_ctx; unsigned char buffer[4096]; int length; *md_alg = NULL; *imprint = NULL; /* Return the MD algorithm of the response. */ if (!(*md_alg = X509_ALGOR_dup(md_alg_resp))) goto err; /* Getting the MD object. */ if (!(md = EVP_get_digestbyobj((*md_alg)->algorithm))) { TSerr(TS_F_TS_COMPUTE_IMPRINT, TS_R_UNSUPPORTED_MD_ALGORITHM); goto err; } /* Compute message digest. */ length = EVP_MD_size(md); if (length < 0) goto err; *imprint_len = length; if (!(*imprint = OPENSSL_malloc(*imprint_len))) { TSerr(TS_F_TS_COMPUTE_IMPRINT, ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_DigestInit(&md_ctx, md)) goto err; while ((length = BIO_read(data, buffer, sizeof(buffer))) > 0) { if (!EVP_DigestUpdate(&md_ctx, buffer, length)) goto err; } if (!EVP_DigestFinal(&md_ctx, *imprint, NULL)) goto err; return 1; err: X509_ALGOR_free(*md_alg); OPENSSL_free(*imprint); *imprint_len = 0; return 0; } static int TS_check_imprints(X509_ALGOR *algor_a, unsigned char *imprint_a, unsigned len_a, TS_TST_INFO *tst_info) { TS_MSG_IMPRINT *b = TS_TST_INFO_get_msg_imprint(tst_info); X509_ALGOR *algor_b = TS_MSG_IMPRINT_get_algo(b); int ret = 0; /* algor_a is optional. */ if (algor_a) { /* Compare algorithm OIDs. */ if (OBJ_cmp(algor_a->algorithm, algor_b->algorithm)) goto err; /* The parameter must be NULL in both. */ if ((algor_a->parameter && ASN1_TYPE_get(algor_a->parameter) != V_ASN1_NULL) || (algor_b->parameter && ASN1_TYPE_get(algor_b->parameter) != V_ASN1_NULL)) goto err; } /* Compare octet strings. */ ret = len_a == (unsigned) ASN1_STRING_length(b->hashed_msg) && memcmp(imprint_a, ASN1_STRING_data(b->hashed_msg), len_a) == 0; err: if (!ret) TSerr(TS_F_TS_CHECK_IMPRINTS, TS_R_MESSAGE_IMPRINT_MISMATCH); return ret; } static int TS_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info) { const ASN1_INTEGER *b = TS_TST_INFO_get_nonce(tst_info); /* Error if nonce is missing. */ if (!b) { TSerr(TS_F_TS_CHECK_NONCES, TS_R_NONCE_NOT_RETURNED); return 0; } /* No error if a nonce is returned without being requested. */ if (ASN1_INTEGER_cmp(a, b) != 0) { TSerr(TS_F_TS_CHECK_NONCES, TS_R_NONCE_MISMATCH); return 0; } return 1; } /* Check if the specified TSA name matches either the subject or one of the subject alternative names of the TSA certificate. */ static int TS_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer) { STACK_OF(GENERAL_NAME) *gen_names = NULL; int idx = -1; int found = 0; /* Check the subject name first. */ if (tsa_name->type == GEN_DIRNAME && X509_name_cmp(tsa_name->d.dirn, signer->cert_info->subject) == 0) return 1; /* Check all the alternative names. */ gen_names = X509_get_ext_d2i(signer, NID_subject_alt_name, NULL, &idx); while (gen_names != NULL && !(found = TS_find_name(gen_names, tsa_name) >= 0)) { /* Get the next subject alternative name, although there should be no more than one. */ GENERAL_NAMES_free(gen_names); gen_names = X509_get_ext_d2i(signer, NID_subject_alt_name, NULL, &idx); } if (gen_names) GENERAL_NAMES_free(gen_names); return found; } /* Returns 1 if name is in gen_names, 0 otherwise. */ static int TS_find_name(STACK_OF(GENERAL_NAME) *gen_names, GENERAL_NAME *name) { int i, found; for (i = 0, found = 0; !found && i < sk_GENERAL_NAME_num(gen_names); ++i) { GENERAL_NAME *current = sk_GENERAL_NAME_value(gen_names, i); found = GENERAL_NAME_cmp(current, name) == 0; } return found ? i - 1 : -1; }
gpl-3.0
VeilsideGX/Hercules
3rdparty/mt19937ar/mtTest.c
215
2539
/* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Copyright (C) 2005, Mutsuo Saito, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any feedback is very welcome. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) */ #include <stdio.h> #include "mt19937ar.h" int main(void) { int i; unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4; init_by_array(init, length); printf("1000 outputs of genrand_int32()\n"); for (i=0; i<1000; i++) { printf("%10lu ", genrand_int32()); if (i%5==4) printf("\n"); } printf("\n1000 outputs of genrand_real2()\n"); for (i=0; i<1000; i++) { printf("%10.8f ", genrand_real2()); if (i%5==4) printf("\n"); } return 0; }
gpl-3.0
CertifiedBlyndGuy/ewok-onyx
drivers/staging/rts_pstor/rtsx_transport.c
4830
19955
/* Driver for Realtek PCI-Express card reader * * Copyright(c) 2009 Realtek Semiconductor Corp. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/>. * * Author: * wwang (wei_wang@realsil.com.cn) * No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China */ #include <linux/blkdev.h> #include <linux/kthread.h> #include <linux/sched.h> #include "rtsx.h" #include "rtsx_scsi.h" #include "rtsx_transport.h" #include "rtsx_chip.h" #include "rtsx_card.h" #include "debug.h" /*********************************************************************** * Scatter-gather transfer buffer access routines ***********************************************************************/ /* Copy a buffer of length buflen to/from the srb's transfer buffer. * (Note: for scatter-gather transfers (srb->use_sg > 0), srb->request_buffer * points to a list of s-g entries and we ignore srb->request_bufflen. * For non-scatter-gather transfers, srb->request_buffer points to the * transfer buffer itself and srb->request_bufflen is the buffer's length.) * Update the *index and *offset variables so that the next copy will * pick up from where this one left off. */ unsigned int rtsx_stor_access_xfer_buf(unsigned char *buffer, unsigned int buflen, struct scsi_cmnd *srb, unsigned int *index, unsigned int *offset, enum xfer_buf_dir dir) { unsigned int cnt; /* If not using scatter-gather, just transfer the data directly. * Make certain it will fit in the available buffer space. */ if (scsi_sg_count(srb) == 0) { if (*offset >= scsi_bufflen(srb)) return 0; cnt = min(buflen, scsi_bufflen(srb) - *offset); if (dir == TO_XFER_BUF) memcpy((unsigned char *) scsi_sglist(srb) + *offset, buffer, cnt); else memcpy(buffer, (unsigned char *) scsi_sglist(srb) + *offset, cnt); *offset += cnt; /* Using scatter-gather. We have to go through the list one entry * at a time. Each s-g entry contains some number of pages, and * each page has to be kmap()'ed separately. If the page is already * in kernel-addressable memory then kmap() will return its address. * If the page is not directly accessible -- such as a user buffer * located in high memory -- then kmap() will map it to a temporary * position in the kernel's virtual address space. */ } else { struct scatterlist *sg = (struct scatterlist *) scsi_sglist(srb) + *index; /* This loop handles a single s-g list entry, which may * include multiple pages. Find the initial page structure * and the starting offset within the page, and update * the *offset and *index values for the next loop. */ cnt = 0; while (cnt < buflen && *index < scsi_sg_count(srb)) { struct page *page = sg_page(sg) + ((sg->offset + *offset) >> PAGE_SHIFT); unsigned int poff = (sg->offset + *offset) & (PAGE_SIZE-1); unsigned int sglen = sg->length - *offset; if (sglen > buflen - cnt) { /* Transfer ends within this s-g entry */ sglen = buflen - cnt; *offset += sglen; } else { /* Transfer continues to next s-g entry */ *offset = 0; ++*index; ++sg; } /* Transfer the data for all the pages in this * s-g entry. For each page: call kmap(), do the * transfer, and call kunmap() immediately after. */ while (sglen > 0) { unsigned int plen = min(sglen, (unsigned int) PAGE_SIZE - poff); unsigned char *ptr = kmap(page); if (dir == TO_XFER_BUF) memcpy(ptr + poff, buffer + cnt, plen); else memcpy(buffer + cnt, ptr + poff, plen); kunmap(page); /* Start at the beginning of the next page */ poff = 0; ++page; cnt += plen; sglen -= plen; } } } /* Return the amount actually transferred */ return cnt; } /* Store the contents of buffer into srb's transfer buffer and set the * SCSI residue. */ void rtsx_stor_set_xfer_buf(unsigned char *buffer, unsigned int buflen, struct scsi_cmnd *srb) { unsigned int index = 0, offset = 0; rtsx_stor_access_xfer_buf(buffer, buflen, srb, &index, &offset, TO_XFER_BUF); if (buflen < scsi_bufflen(srb)) scsi_set_resid(srb, scsi_bufflen(srb) - buflen); } void rtsx_stor_get_xfer_buf(unsigned char *buffer, unsigned int buflen, struct scsi_cmnd *srb) { unsigned int index = 0, offset = 0; rtsx_stor_access_xfer_buf(buffer, buflen, srb, &index, &offset, FROM_XFER_BUF); if (buflen < scsi_bufflen(srb)) scsi_set_resid(srb, scsi_bufflen(srb) - buflen); } /*********************************************************************** * Transport routines ***********************************************************************/ /* Invoke the transport and basic error-handling/recovery methods * * This is used to send the message to the device and receive the response. */ void rtsx_invoke_transport(struct scsi_cmnd *srb, struct rtsx_chip *chip) { int result; result = rtsx_scsi_handler(srb, chip); /* if the command gets aborted by the higher layers, we need to * short-circuit all other processing */ if (rtsx_chk_stat(chip, RTSX_STAT_ABORT)) { RTSX_DEBUGP("-- command was aborted\n"); srb->result = DID_ABORT << 16; goto Handle_Errors; } /* if there is a transport error, reset and don't auto-sense */ if (result == TRANSPORT_ERROR) { RTSX_DEBUGP("-- transport indicates error, resetting\n"); srb->result = DID_ERROR << 16; goto Handle_Errors; } srb->result = SAM_STAT_GOOD; /* * If we have a failure, we're going to do a REQUEST_SENSE * automatically. Note that we differentiate between a command * "failure" and an "error" in the transport mechanism. */ if (result == TRANSPORT_FAILED) { /* set the result so the higher layers expect this data */ srb->result = SAM_STAT_CHECK_CONDITION; memcpy(srb->sense_buffer, (unsigned char *)&(chip->sense_buffer[SCSI_LUN(srb)]), sizeof(struct sense_data_t)); } return; /* Error and abort processing: try to resynchronize with the device * by issuing a port reset. If that fails, try a class-specific * device reset. */ Handle_Errors: return; } void rtsx_add_cmd(struct rtsx_chip *chip, u8 cmd_type, u16 reg_addr, u8 mask, u8 data) { u32 *cb = (u32 *)(chip->host_cmds_ptr); u32 val = 0; val |= (u32)(cmd_type & 0x03) << 30; val |= (u32)(reg_addr & 0x3FFF) << 16; val |= (u32)mask << 8; val |= (u32)data; spin_lock_irq(&chip->rtsx->reg_lock); if (chip->ci < (HOST_CMDS_BUF_LEN / 4)) { cb[(chip->ci)++] = cpu_to_le32(val); } spin_unlock_irq(&chip->rtsx->reg_lock); } void rtsx_send_cmd_no_wait(struct rtsx_chip *chip) { u32 val = 1 << 31; rtsx_writel(chip, RTSX_HCBAR, chip->host_cmds_addr); val |= (u32)(chip->ci * 4) & 0x00FFFFFF; /* Hardware Auto Response */ val |= 0x40000000; rtsx_writel(chip, RTSX_HCBCTLR, val); } int rtsx_send_cmd(struct rtsx_chip *chip, u8 card, int timeout) { struct rtsx_dev *rtsx = chip->rtsx; struct completion trans_done; u32 val = 1 << 31; long timeleft; int err = 0; if (card == SD_CARD) { rtsx->check_card_cd = SD_EXIST; } else if (card == MS_CARD) { rtsx->check_card_cd = MS_EXIST; } else if (card == XD_CARD) { rtsx->check_card_cd = XD_EXIST; } else { rtsx->check_card_cd = 0; } spin_lock_irq(&rtsx->reg_lock); /* set up data structures for the wakeup system */ rtsx->done = &trans_done; rtsx->trans_result = TRANS_NOT_READY; init_completion(&trans_done); rtsx->trans_state = STATE_TRANS_CMD; rtsx_writel(chip, RTSX_HCBAR, chip->host_cmds_addr); val |= (u32)(chip->ci * 4) & 0x00FFFFFF; /* Hardware Auto Response */ val |= 0x40000000; rtsx_writel(chip, RTSX_HCBCTLR, val); spin_unlock_irq(&rtsx->reg_lock); /* Wait for TRANS_OK_INT */ timeleft = wait_for_completion_interruptible_timeout( &trans_done, timeout * HZ / 1000); if (timeleft <= 0) { RTSX_DEBUGP("chip->int_reg = 0x%x\n", chip->int_reg); err = -ETIMEDOUT; TRACE_GOTO(chip, finish_send_cmd); } spin_lock_irq(&rtsx->reg_lock); if (rtsx->trans_result == TRANS_RESULT_FAIL) { err = -EIO; } else if (rtsx->trans_result == TRANS_RESULT_OK) { err = 0; } spin_unlock_irq(&rtsx->reg_lock); finish_send_cmd: rtsx->done = NULL; rtsx->trans_state = STATE_TRANS_NONE; if (err < 0) rtsx_stop_cmd(chip, card); return err; } static inline void rtsx_add_sg_tbl( struct rtsx_chip *chip, u32 addr, u32 len, u8 option) { u64 *sgb = (u64 *)(chip->host_sg_tbl_ptr); u64 val = 0; u32 temp_len = 0; u8 temp_opt = 0; do { if (len > 0x80000) { temp_len = 0x80000; temp_opt = option & (~SG_END); } else { temp_len = len; temp_opt = option; } val = ((u64)addr << 32) | ((u64)temp_len << 12) | temp_opt; if (chip->sgi < (HOST_SG_TBL_BUF_LEN / 8)) sgb[(chip->sgi)++] = cpu_to_le64(val); len -= temp_len; addr += temp_len; } while (len); } static int rtsx_transfer_sglist_adma_partial(struct rtsx_chip *chip, u8 card, struct scatterlist *sg, int num_sg, unsigned int *index, unsigned int *offset, int size, enum dma_data_direction dma_dir, int timeout) { struct rtsx_dev *rtsx = chip->rtsx; struct completion trans_done; u8 dir; int sg_cnt, i, resid; int err = 0; long timeleft; struct scatterlist *sg_ptr; u32 val = TRIG_DMA; if ((sg == NULL) || (num_sg <= 0) || !offset || !index) return -EIO; if (dma_dir == DMA_TO_DEVICE) { dir = HOST_TO_DEVICE; } else if (dma_dir == DMA_FROM_DEVICE) { dir = DEVICE_TO_HOST; } else { return -ENXIO; } if (card == SD_CARD) { rtsx->check_card_cd = SD_EXIST; } else if (card == MS_CARD) { rtsx->check_card_cd = MS_EXIST; } else if (card == XD_CARD) { rtsx->check_card_cd = XD_EXIST; } else { rtsx->check_card_cd = 0; } spin_lock_irq(&rtsx->reg_lock); /* set up data structures for the wakeup system */ rtsx->done = &trans_done; rtsx->trans_state = STATE_TRANS_SG; rtsx->trans_result = TRANS_NOT_READY; spin_unlock_irq(&rtsx->reg_lock); sg_cnt = dma_map_sg(&(rtsx->pci->dev), sg, num_sg, dma_dir); resid = size; sg_ptr = sg; chip->sgi = 0; /* Usually the next entry will be @sg@ + 1, but if this sg element * is part of a chained scatterlist, it could jump to the start of * a new scatterlist array. So here we use sg_next to move to * the proper sg */ for (i = 0; i < *index; i++) sg_ptr = sg_next(sg_ptr); for (i = *index; i < sg_cnt; i++) { dma_addr_t addr; unsigned int len; u8 option; addr = sg_dma_address(sg_ptr); len = sg_dma_len(sg_ptr); RTSX_DEBUGP("DMA addr: 0x%x, Len: 0x%x\n", (unsigned int)addr, len); RTSX_DEBUGP("*index = %d, *offset = %d\n", *index, *offset); addr += *offset; if ((len - *offset) > resid) { *offset += resid; len = resid; resid = 0; } else { resid -= (len - *offset); len -= *offset; *offset = 0; *index = *index + 1; } if ((i == (sg_cnt - 1)) || !resid) { option = SG_VALID | SG_END | SG_TRANS_DATA; } else { option = SG_VALID | SG_TRANS_DATA; } rtsx_add_sg_tbl(chip, (u32)addr, (u32)len, option); if (!resid) break; sg_ptr = sg_next(sg_ptr); } RTSX_DEBUGP("SG table count = %d\n", chip->sgi); val |= (u32)(dir & 0x01) << 29; val |= ADMA_MODE; spin_lock_irq(&rtsx->reg_lock); init_completion(&trans_done); rtsx_writel(chip, RTSX_HDBAR, chip->host_sg_tbl_addr); rtsx_writel(chip, RTSX_HDBCTLR, val); spin_unlock_irq(&rtsx->reg_lock); timeleft = wait_for_completion_interruptible_timeout( &trans_done, timeout * HZ / 1000); if (timeleft <= 0) { RTSX_DEBUGP("Timeout (%s %d)\n", __func__, __LINE__); RTSX_DEBUGP("chip->int_reg = 0x%x\n", chip->int_reg); err = -ETIMEDOUT; goto out; } spin_lock_irq(&rtsx->reg_lock); if (rtsx->trans_result == TRANS_RESULT_FAIL) { err = -EIO; spin_unlock_irq(&rtsx->reg_lock); goto out; } spin_unlock_irq(&rtsx->reg_lock); /* Wait for TRANS_OK_INT */ spin_lock_irq(&rtsx->reg_lock); if (rtsx->trans_result == TRANS_NOT_READY) { init_completion(&trans_done); spin_unlock_irq(&rtsx->reg_lock); timeleft = wait_for_completion_interruptible_timeout( &trans_done, timeout * HZ / 1000); if (timeleft <= 0) { RTSX_DEBUGP("Timeout (%s %d)\n", __func__, __LINE__); RTSX_DEBUGP("chip->int_reg = 0x%x\n", chip->int_reg); err = -ETIMEDOUT; goto out; } } else { spin_unlock_irq(&rtsx->reg_lock); } spin_lock_irq(&rtsx->reg_lock); if (rtsx->trans_result == TRANS_RESULT_FAIL) { err = -EIO; } else if (rtsx->trans_result == TRANS_RESULT_OK) { err = 0; } spin_unlock_irq(&rtsx->reg_lock); out: rtsx->done = NULL; rtsx->trans_state = STATE_TRANS_NONE; dma_unmap_sg(&(rtsx->pci->dev), sg, num_sg, dma_dir); if (err < 0) rtsx_stop_cmd(chip, card); return err; } static int rtsx_transfer_sglist_adma(struct rtsx_chip *chip, u8 card, struct scatterlist *sg, int num_sg, enum dma_data_direction dma_dir, int timeout) { struct rtsx_dev *rtsx = chip->rtsx; struct completion trans_done; u8 dir; int buf_cnt, i; int err = 0; long timeleft; struct scatterlist *sg_ptr; if ((sg == NULL) || (num_sg <= 0)) return -EIO; if (dma_dir == DMA_TO_DEVICE) { dir = HOST_TO_DEVICE; } else if (dma_dir == DMA_FROM_DEVICE) { dir = DEVICE_TO_HOST; } else { return -ENXIO; } if (card == SD_CARD) { rtsx->check_card_cd = SD_EXIST; } else if (card == MS_CARD) { rtsx->check_card_cd = MS_EXIST; } else if (card == XD_CARD) { rtsx->check_card_cd = XD_EXIST; } else { rtsx->check_card_cd = 0; } spin_lock_irq(&rtsx->reg_lock); /* set up data structures for the wakeup system */ rtsx->done = &trans_done; rtsx->trans_state = STATE_TRANS_SG; rtsx->trans_result = TRANS_NOT_READY; spin_unlock_irq(&rtsx->reg_lock); buf_cnt = dma_map_sg(&(rtsx->pci->dev), sg, num_sg, dma_dir); sg_ptr = sg; for (i = 0; i <= buf_cnt / (HOST_SG_TBL_BUF_LEN / 8); i++) { u32 val = TRIG_DMA; int sg_cnt, j; if (i == buf_cnt / (HOST_SG_TBL_BUF_LEN / 8)) { sg_cnt = buf_cnt % (HOST_SG_TBL_BUF_LEN / 8); } else { sg_cnt = (HOST_SG_TBL_BUF_LEN / 8); } chip->sgi = 0; for (j = 0; j < sg_cnt; j++) { dma_addr_t addr = sg_dma_address(sg_ptr); unsigned int len = sg_dma_len(sg_ptr); u8 option; RTSX_DEBUGP("DMA addr: 0x%x, Len: 0x%x\n", (unsigned int)addr, len); if (j == (sg_cnt - 1)) { option = SG_VALID | SG_END | SG_TRANS_DATA; } else { option = SG_VALID | SG_TRANS_DATA; } rtsx_add_sg_tbl(chip, (u32)addr, (u32)len, option); sg_ptr = sg_next(sg_ptr); } RTSX_DEBUGP("SG table count = %d\n", chip->sgi); val |= (u32)(dir & 0x01) << 29; val |= ADMA_MODE; spin_lock_irq(&rtsx->reg_lock); init_completion(&trans_done); rtsx_writel(chip, RTSX_HDBAR, chip->host_sg_tbl_addr); rtsx_writel(chip, RTSX_HDBCTLR, val); spin_unlock_irq(&rtsx->reg_lock); timeleft = wait_for_completion_interruptible_timeout( &trans_done, timeout * HZ / 1000); if (timeleft <= 0) { RTSX_DEBUGP("Timeout (%s %d)\n", __func__, __LINE__); RTSX_DEBUGP("chip->int_reg = 0x%x\n", chip->int_reg); err = -ETIMEDOUT; goto out; } spin_lock_irq(&rtsx->reg_lock); if (rtsx->trans_result == TRANS_RESULT_FAIL) { err = -EIO; spin_unlock_irq(&rtsx->reg_lock); goto out; } spin_unlock_irq(&rtsx->reg_lock); sg_ptr += sg_cnt; } /* Wait for TRANS_OK_INT */ spin_lock_irq(&rtsx->reg_lock); if (rtsx->trans_result == TRANS_NOT_READY) { init_completion(&trans_done); spin_unlock_irq(&rtsx->reg_lock); timeleft = wait_for_completion_interruptible_timeout( &trans_done, timeout * HZ / 1000); if (timeleft <= 0) { RTSX_DEBUGP("Timeout (%s %d)\n", __func__, __LINE__); RTSX_DEBUGP("chip->int_reg = 0x%x\n", chip->int_reg); err = -ETIMEDOUT; goto out; } } else { spin_unlock_irq(&rtsx->reg_lock); } spin_lock_irq(&rtsx->reg_lock); if (rtsx->trans_result == TRANS_RESULT_FAIL) { err = -EIO; } else if (rtsx->trans_result == TRANS_RESULT_OK) { err = 0; } spin_unlock_irq(&rtsx->reg_lock); out: rtsx->done = NULL; rtsx->trans_state = STATE_TRANS_NONE; dma_unmap_sg(&(rtsx->pci->dev), sg, num_sg, dma_dir); if (err < 0) rtsx_stop_cmd(chip, card); return err; } static int rtsx_transfer_buf(struct rtsx_chip *chip, u8 card, void *buf, size_t len, enum dma_data_direction dma_dir, int timeout) { struct rtsx_dev *rtsx = chip->rtsx; struct completion trans_done; dma_addr_t addr; u8 dir; int err = 0; u32 val = (1 << 31); long timeleft; if ((buf == NULL) || (len <= 0)) return -EIO; if (dma_dir == DMA_TO_DEVICE) { dir = HOST_TO_DEVICE; } else if (dma_dir == DMA_FROM_DEVICE) { dir = DEVICE_TO_HOST; } else { return -ENXIO; } addr = dma_map_single(&(rtsx->pci->dev), buf, len, dma_dir); if (!addr) return -ENOMEM; if (card == SD_CARD) { rtsx->check_card_cd = SD_EXIST; } else if (card == MS_CARD) { rtsx->check_card_cd = MS_EXIST; } else if (card == XD_CARD) { rtsx->check_card_cd = XD_EXIST; } else { rtsx->check_card_cd = 0; } val |= (u32)(dir & 0x01) << 29; val |= (u32)(len & 0x00FFFFFF); spin_lock_irq(&rtsx->reg_lock); /* set up data structures for the wakeup system */ rtsx->done = &trans_done; init_completion(&trans_done); rtsx->trans_state = STATE_TRANS_BUF; rtsx->trans_result = TRANS_NOT_READY; rtsx_writel(chip, RTSX_HDBAR, addr); rtsx_writel(chip, RTSX_HDBCTLR, val); spin_unlock_irq(&rtsx->reg_lock); /* Wait for TRANS_OK_INT */ timeleft = wait_for_completion_interruptible_timeout( &trans_done, timeout * HZ / 1000); if (timeleft <= 0) { RTSX_DEBUGP("Timeout (%s %d)\n", __func__, __LINE__); RTSX_DEBUGP("chip->int_reg = 0x%x\n", chip->int_reg); err = -ETIMEDOUT; goto out; } spin_lock_irq(&rtsx->reg_lock); if (rtsx->trans_result == TRANS_RESULT_FAIL) { err = -EIO; } else if (rtsx->trans_result == TRANS_RESULT_OK) { err = 0; } spin_unlock_irq(&rtsx->reg_lock); out: rtsx->done = NULL; rtsx->trans_state = STATE_TRANS_NONE; dma_unmap_single(&(rtsx->pci->dev), addr, len, dma_dir); if (err < 0) rtsx_stop_cmd(chip, card); return err; } int rtsx_transfer_data_partial(struct rtsx_chip *chip, u8 card, void *buf, size_t len, int use_sg, unsigned int *index, unsigned int *offset, enum dma_data_direction dma_dir, int timeout) { int err = 0; /* don't transfer data during abort processing */ if (rtsx_chk_stat(chip, RTSX_STAT_ABORT)) return -EIO; if (use_sg) { err = rtsx_transfer_sglist_adma_partial(chip, card, (struct scatterlist *)buf, use_sg, index, offset, (int)len, dma_dir, timeout); } else { err = rtsx_transfer_buf(chip, card, buf, len, dma_dir, timeout); } if (err < 0) { if (RTSX_TST_DELINK(chip)) { RTSX_CLR_DELINK(chip); chip->need_reinit = SD_CARD | MS_CARD | XD_CARD; rtsx_reinit_cards(chip, 1); } } return err; } int rtsx_transfer_data(struct rtsx_chip *chip, u8 card, void *buf, size_t len, int use_sg, enum dma_data_direction dma_dir, int timeout) { int err = 0; RTSX_DEBUGP("use_sg = %d\n", use_sg); /* don't transfer data during abort processing */ if (rtsx_chk_stat(chip, RTSX_STAT_ABORT)) return -EIO; if (use_sg) { err = rtsx_transfer_sglist_adma(chip, card, (struct scatterlist *)buf, use_sg, dma_dir, timeout); } else { err = rtsx_transfer_buf(chip, card, buf, len, dma_dir, timeout); } if (err < 0) { if (RTSX_TST_DELINK(chip)) { RTSX_CLR_DELINK(chip); chip->need_reinit = SD_CARD | MS_CARD | XD_CARD; rtsx_reinit_cards(chip, 1); } } return err; }
gpl-3.0
papostolescu/DECAF
decaf/path.c
225
4782
/* Code to mangle pathnames into those matching a given prefix. eg. open("/lib/foo.so") => open("/usr/gnemul/i386-linux/lib/foo.so"); The assumption is that this area does not change. */ #include <sys/types.h> #include <sys/param.h> #include <dirent.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stdio.h> #include "qemu-common.h" struct pathelem { /* Name of this, eg. lib */ char *name; /* Full path name, eg. /usr/gnemul/x86-linux/lib. */ char *pathname; struct pathelem *parent; /* Children */ unsigned int num_entries; struct pathelem *entries[0]; }; static struct pathelem *base; /* First N chars of S1 match S2, and S2 is N chars long. */ static int strneq(const char *s1, unsigned int n, const char *s2) { unsigned int i; for (i = 0; i < n; i++) if (s1[i] != s2[i]) return 0; return s2[i] == 0; } static struct pathelem *add_entry(struct pathelem *root, const char *name, unsigned char type); static struct pathelem *new_entry(const char *root, struct pathelem *parent, const char *name) { struct pathelem *new = malloc(sizeof(*new)); new->name = strdup(name); if (asprintf(&new->pathname, "%s/%s", root, name) == -1) { printf("Cannot allocate memory\n"); exit(1); } new->num_entries = 0; return new; } #define streq(a,b) (strcmp((a), (b)) == 0) /* Not all systems provide this feature */ #if defined(DT_DIR) && defined(DT_UNKNOWN) # define dirent_type(dirent) ((dirent)->d_type) # define is_dir_maybe(type) ((type) == DT_DIR || (type) == DT_UNKNOWN) #else # define dirent_type(dirent) (1) # define is_dir_maybe(type) (type) #endif static struct pathelem *add_dir_maybe(struct pathelem *path) { DIR *dir; if ((dir = opendir(path->pathname)) != NULL) { struct dirent *dirent; while ((dirent = readdir(dir)) != NULL) { if (!streq(dirent->d_name,".") && !streq(dirent->d_name,"..")){ path = add_entry(path, dirent->d_name, dirent_type(dirent)); } } closedir(dir); } return path; } static struct pathelem *add_entry(struct pathelem *root, const char *name, unsigned char type) { struct pathelem **e; root->num_entries++; root = realloc(root, sizeof(*root) + sizeof(root->entries[0])*root->num_entries); e = &root->entries[root->num_entries-1]; *e = new_entry(root->pathname, root, name); if (is_dir_maybe(type)) { *e = add_dir_maybe(*e); } return root; } /* This needs to be done after tree is stabilized (ie. no more reallocs!). */ static void set_parents(struct pathelem *child, struct pathelem *parent) { unsigned int i; child->parent = parent; for (i = 0; i < child->num_entries; i++) set_parents(child->entries[i], child); } /* FIXME: Doesn't handle DIR/.. where DIR is not in emulated dir. */ static const char * follow_path(const struct pathelem *cursor, const char *name) { unsigned int i, namelen; name += strspn(name, "/"); namelen = strcspn(name, "/"); if (namelen == 0) return cursor->pathname; if (strneq(name, namelen, "..")) return follow_path(cursor->parent, name + namelen); if (strneq(name, namelen, ".")) return follow_path(cursor, name + namelen); for (i = 0; i < cursor->num_entries; i++) if (strneq(name, namelen, cursor->entries[i]->name)) return follow_path(cursor->entries[i], name + namelen); /* Not found */ return NULL; } void init_paths(const char *prefix) { char pref_buf[PATH_MAX]; if (prefix[0] == '\0' || !strcmp(prefix, "/")) return; if (prefix[0] != '/') { char *cwd = getcwd(NULL, 0); size_t pref_buf_len = sizeof(pref_buf); if (!cwd) abort(); pstrcpy(pref_buf, sizeof(pref_buf), cwd); pstrcat(pref_buf, pref_buf_len, "/"); pstrcat(pref_buf, pref_buf_len, prefix); free(cwd); } else pstrcpy(pref_buf, sizeof(pref_buf), prefix + 1); base = new_entry("", NULL, pref_buf); base = add_dir_maybe(base); if (base->num_entries == 0) { free (base); base = NULL; } else { set_parents(base, base); } } /* Look for path in emulation dir, otherwise return name. */ const char *path(const char *name) { /* Only do absolute paths: quick and dirty, but should mostly be OK. Could do relative by tracking cwd. */ if (!base || !name || name[0] != '/') return name; return follow_path(base, name) ?: name; }
gpl-3.0
kmangame0/stk
lib/bullet/src/BulletCollision/Gimpact/gim_memory.cpp
483
2908
/* ----------------------------------------------------------------------------- This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2006 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This library is free software; you can redistribute it and/or modify it under the terms of EITHER: (1) The GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The text of the GNU Lesser General Public License is included with this library in the file GIMPACT-LICENSE-LGPL.TXT. (2) The BSD-style license that is included with this library in the file GIMPACT-LICENSE-BSD.TXT. (3) The zlib/libpng license that is included with this library in the file GIMPACT-LICENSE-ZLIB.TXT. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files GIMPACT-LICENSE-LGPL.TXT, GIMPACT-LICENSE-ZLIB.TXT and GIMPACT-LICENSE-BSD.TXT for more details. ----------------------------------------------------------------------------- */ #include "gim_memory.h" #include "stdlib.h" #ifdef GIM_SIMD_MEMORY #include "LinearMath/btAlignedAllocator.h" #endif static gim_alloc_function *g_allocfn = 0; static gim_alloca_function *g_allocafn = 0; static gim_realloc_function *g_reallocfn = 0; static gim_free_function *g_freefn = 0; void gim_set_alloc_handler (gim_alloc_function *fn) { g_allocfn = fn; } void gim_set_alloca_handler (gim_alloca_function *fn) { g_allocafn = fn; } void gim_set_realloc_handler (gim_realloc_function *fn) { g_reallocfn = fn; } void gim_set_free_handler (gim_free_function *fn) { g_freefn = fn; } gim_alloc_function *gim_get_alloc_handler() { return g_allocfn; } gim_alloca_function *gim_get_alloca_handler() { return g_allocafn; } gim_realloc_function *gim_get_realloc_handler () { return g_reallocfn; } gim_free_function *gim_get_free_handler () { return g_freefn; } void * gim_alloc(size_t size) { void * ptr; if (g_allocfn) { ptr = g_allocfn(size); } else { #ifdef GIM_SIMD_MEMORY ptr = btAlignedAlloc(size,16); #else ptr = malloc(size); #endif } return ptr; } void * gim_alloca(size_t size) { if (g_allocafn) return g_allocafn(size); else return gim_alloc(size); } void * gim_realloc(void *ptr, size_t oldsize, size_t newsize) { void * newptr = gim_alloc(newsize); size_t copysize = oldsize<newsize?oldsize:newsize; gim_simd_memcpy(newptr,ptr,copysize); gim_free(ptr); return newptr; } void gim_free(void *ptr) { if (!ptr) return; if (g_freefn) { g_freefn(ptr); } else { #ifdef GIM_SIMD_MEMORY btAlignedFree(ptr); #else free(ptr); #endif } }
gpl-3.0
JiaolongTong/ONOMPS_RTU
OpenSourceLibrary/linux-3.2.0-psp04.06.00.08.sdk/drivers/rtc/rtc-pcf8563.c
248
7433
/* * An I2C driver for the Philips PCF8563 RTC * Copyright 2005-06 Tower Technologies * * Author: Alessandro Zummo <a.zummo@towertech.it> * Maintainers: http://www.nslu2-linux.org/ * * based on the other drivers in this same directory. * * http://www.semiconductors.philips.com/acrobat/datasheets/PCF8563-04.pdf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/i2c.h> #include <linux/bcd.h> #include <linux/rtc.h> #include <linux/slab.h> #include <linux/module.h> #define DRV_VERSION "0.4.3" #define PCF8563_REG_ST1 0x00 /* status */ #define PCF8563_REG_ST2 0x01 #define PCF8563_REG_SC 0x02 /* datetime */ #define PCF8563_REG_MN 0x03 #define PCF8563_REG_HR 0x04 #define PCF8563_REG_DM 0x05 #define PCF8563_REG_DW 0x06 #define PCF8563_REG_MO 0x07 #define PCF8563_REG_YR 0x08 #define PCF8563_REG_AMN 0x09 /* alarm */ #define PCF8563_REG_AHR 0x0A #define PCF8563_REG_ADM 0x0B #define PCF8563_REG_ADW 0x0C #define PCF8563_REG_CLKO 0x0D /* clock out */ #define PCF8563_REG_TMRC 0x0E /* timer control */ #define PCF8563_REG_TMR 0x0F /* timer */ #define PCF8563_SC_LV 0x80 /* low voltage */ #define PCF8563_MO_C 0x80 /* century */ static struct i2c_driver pcf8563_driver; struct pcf8563 { struct rtc_device *rtc; /* * The meaning of MO_C bit varies by the chip type. * From PCF8563 datasheet: this bit is toggled when the years * register overflows from 99 to 00 * 0 indicates the century is 20xx * 1 indicates the century is 19xx * From RTC8564 datasheet: this bit indicates change of * century. When the year digit data overflows from 99 to 00, * this bit is set. By presetting it to 0 while still in the * 20th century, it will be set in year 2000, ... * There seems no reliable way to know how the system use this * bit. So let's do it heuristically, assuming we are live in * 1970...2069. */ int c_polarity; /* 0: MO_C=1 means 19xx, otherwise MO_C=1 means 20xx */ }; /* * In the routines that deal directly with the pcf8563 hardware, we use * rtc_time -- month 0-11, hour 0-23, yr = calendar year-epoch. */ static int pcf8563_get_datetime(struct i2c_client *client, struct rtc_time *tm) { struct pcf8563 *pcf8563 = i2c_get_clientdata(client); unsigned char buf[13] = { PCF8563_REG_ST1 }; struct i2c_msg msgs[] = { { client->addr, 0, 1, buf }, /* setup read ptr */ { client->addr, I2C_M_RD, 13, buf }, /* read status + date */ }; /* read registers */ if ((i2c_transfer(client->adapter, msgs, 2)) != 2) { dev_err(&client->dev, "%s: read error\n", __func__); return -EIO; } if (buf[PCF8563_REG_SC] & PCF8563_SC_LV) dev_info(&client->dev, "low voltage detected, date/time is not reliable.\n"); dev_dbg(&client->dev, "%s: raw data is st1=%02x, st2=%02x, sec=%02x, min=%02x, hr=%02x, " "mday=%02x, wday=%02x, mon=%02x, year=%02x\n", __func__, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8]); tm->tm_sec = bcd2bin(buf[PCF8563_REG_SC] & 0x7F); tm->tm_min = bcd2bin(buf[PCF8563_REG_MN] & 0x7F); tm->tm_hour = bcd2bin(buf[PCF8563_REG_HR] & 0x3F); /* rtc hr 0-23 */ tm->tm_mday = bcd2bin(buf[PCF8563_REG_DM] & 0x3F); tm->tm_wday = buf[PCF8563_REG_DW] & 0x07; tm->tm_mon = bcd2bin(buf[PCF8563_REG_MO] & 0x1F) - 1; /* rtc mn 1-12 */ tm->tm_year = bcd2bin(buf[PCF8563_REG_YR]); if (tm->tm_year < 70) tm->tm_year += 100; /* assume we are in 1970...2069 */ /* detect the polarity heuristically. see note above. */ pcf8563->c_polarity = (buf[PCF8563_REG_MO] & PCF8563_MO_C) ? (tm->tm_year >= 100) : (tm->tm_year < 100); dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d, " "mday=%d, mon=%d, year=%d, wday=%d\n", __func__, tm->tm_sec, tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday); /* the clock can give out invalid datetime, but we cannot return * -EINVAL otherwise hwclock will refuse to set the time on bootup. */ if (rtc_valid_tm(tm) < 0) dev_err(&client->dev, "retrieved date/time is not valid.\n"); return 0; } static int pcf8563_set_datetime(struct i2c_client *client, struct rtc_time *tm) { struct pcf8563 *pcf8563 = i2c_get_clientdata(client); int i, err; unsigned char buf[9]; dev_dbg(&client->dev, "%s: secs=%d, mins=%d, hours=%d, " "mday=%d, mon=%d, year=%d, wday=%d\n", __func__, tm->tm_sec, tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday); /* hours, minutes and seconds */ buf[PCF8563_REG_SC] = bin2bcd(tm->tm_sec); buf[PCF8563_REG_MN] = bin2bcd(tm->tm_min); buf[PCF8563_REG_HR] = bin2bcd(tm->tm_hour); buf[PCF8563_REG_DM] = bin2bcd(tm->tm_mday); /* month, 1 - 12 */ buf[PCF8563_REG_MO] = bin2bcd(tm->tm_mon + 1); /* year and century */ buf[PCF8563_REG_YR] = bin2bcd(tm->tm_year % 100); if (pcf8563->c_polarity ? (tm->tm_year >= 100) : (tm->tm_year < 100)) buf[PCF8563_REG_MO] |= PCF8563_MO_C; buf[PCF8563_REG_DW] = tm->tm_wday & 0x07; /* write register's data */ for (i = 0; i < 7; i++) { unsigned char data[2] = { PCF8563_REG_SC + i, buf[PCF8563_REG_SC + i] }; err = i2c_master_send(client, data, sizeof(data)); if (err != sizeof(data)) { dev_err(&client->dev, "%s: err=%d addr=%02x, data=%02x\n", __func__, err, data[0], data[1]); return -EIO; } }; return 0; } static int pcf8563_rtc_read_time(struct device *dev, struct rtc_time *tm) { return pcf8563_get_datetime(to_i2c_client(dev), tm); } static int pcf8563_rtc_set_time(struct device *dev, struct rtc_time *tm) { return pcf8563_set_datetime(to_i2c_client(dev), tm); } static const struct rtc_class_ops pcf8563_rtc_ops = { .read_time = pcf8563_rtc_read_time, .set_time = pcf8563_rtc_set_time, }; static int pcf8563_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct pcf8563 *pcf8563; int err = 0; dev_dbg(&client->dev, "%s\n", __func__); if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) return -ENODEV; pcf8563 = kzalloc(sizeof(struct pcf8563), GFP_KERNEL); if (!pcf8563) return -ENOMEM; dev_info(&client->dev, "chip found, driver version " DRV_VERSION "\n"); i2c_set_clientdata(client, pcf8563); pcf8563->rtc = rtc_device_register(pcf8563_driver.driver.name, &client->dev, &pcf8563_rtc_ops, THIS_MODULE); if (IS_ERR(pcf8563->rtc)) { err = PTR_ERR(pcf8563->rtc); goto exit_kfree; } return 0; exit_kfree: kfree(pcf8563); return err; } static int pcf8563_remove(struct i2c_client *client) { struct pcf8563 *pcf8563 = i2c_get_clientdata(client); if (pcf8563->rtc) rtc_device_unregister(pcf8563->rtc); kfree(pcf8563); return 0; } static const struct i2c_device_id pcf8563_id[] = { { "pcf8563", 0 }, { "rtc8564", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, pcf8563_id); static struct i2c_driver pcf8563_driver = { .driver = { .name = "rtc-pcf8563", }, .probe = pcf8563_probe, .remove = pcf8563_remove, .id_table = pcf8563_id, }; static int __init pcf8563_init(void) { return i2c_add_driver(&pcf8563_driver); } static void __exit pcf8563_exit(void) { i2c_del_driver(&pcf8563_driver); } MODULE_AUTHOR("Alessandro Zummo <a.zummo@towertech.it>"); MODULE_DESCRIPTION("Philips PCF8563/Epson RTC8564 RTC driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); module_init(pcf8563_init); module_exit(pcf8563_exit);
gpl-3.0
CrazyLauren/sm_lib
src/tasks.cpp
1
1260
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* * tasks.cpp * * Copyright © 2016 https://github.com/CrazyLauren * * Created on: 12.04.2016 * Author: https://github.com/CrazyLauren * * Distributed under MPL 2.0 (See accompanying file LICENSE.txt or copy at * https://www.mozilla.org/en-US/MPL/2.0) */ #include <deftype> #include <tasks.h> #include <signal.h> namespace NSHARE { bool is_process_exist(int pID) { VLOG(2) << "Checking process " << pID << " exist."; #if defined(_WIN32) HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION, false, pID); if (!handle) { VLOG(2)<<"The process "<<pID<<" is not exist."; return false; } else { DWORD _status=0; bool _result=GetExitCodeProcess(handle,&_status)!=FALSE; CloseHandle(handle); VLOG_IF(2,_result)<<"The process "<<pID<<" is exist."; VLOG_IF(2,!_result)<<"The process "<<pID<<" is not exist."; return _status==STILL_ACTIVE; } #else if (kill(pID, 0) != 0 && errno != EPERM) { VLOG(2) << "The process " << pID << " is not exist."; return false; } else { VLOG(2) << "The process " << pID << " is exist."; return true; } #endif } }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
media/libvpx/libvpx/vpx_dsp/arm/highbd_vpx_convolve_neon.c
6
3355
/* * Copyright (c) 2016 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "./vpx_dsp_rtcd.h" #include "vpx_dsp/vpx_dsp_common.h" #include "vpx_dsp/vpx_filter.h" #include "vpx_ports/mem.h" void vpx_highbd_convolve8_neon(const uint8_t *src8, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int bd) { const uint16_t *src = CONVERT_TO_SHORTPTR(src8); const int y0_q4 = get_filter_offset(filter_y, get_filter_base(filter_y)); // + 1 to make it divisible by 4 DECLARE_ALIGNED(16, uint16_t, temp[64 * 136]); const int intermediate_height = (((h - 1) * y_step_q4 + y0_q4) >> SUBPEL_BITS) + SUBPEL_TAPS; /* Filter starting 3 lines back. The neon implementation will ignore the given * height and filter a multiple of 4 lines. Since this goes in to the temp * buffer which has lots of extra room and is subsequently discarded this is * safe if somewhat less than ideal. */ vpx_highbd_convolve8_horiz_neon(CONVERT_TO_BYTEPTR(src - src_stride * 3), src_stride, CONVERT_TO_BYTEPTR(temp), w, filter_x, x_step_q4, filter_y, y_step_q4, w, intermediate_height, bd); /* Step into the temp buffer 3 lines to get the actual frame data */ vpx_highbd_convolve8_vert_neon(CONVERT_TO_BYTEPTR(temp + w * 3), w, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, bd); } void vpx_highbd_convolve8_avg_neon(const uint8_t *src8, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int bd) { const uint16_t *src = CONVERT_TO_SHORTPTR(src8); const int y0_q4 = get_filter_offset(filter_y, get_filter_base(filter_y)); // + 1 to make it divisible by 4 DECLARE_ALIGNED(16, uint16_t, temp[64 * 136]); const int intermediate_height = (((h - 1) * y_step_q4 + y0_q4) >> SUBPEL_BITS) + SUBPEL_TAPS; /* This implementation has the same issues as above. In addition, we only want * to average the values after both passes. */ vpx_highbd_convolve8_horiz_neon(CONVERT_TO_BYTEPTR(src - src_stride * 3), src_stride, CONVERT_TO_BYTEPTR(temp), w, filter_x, x_step_q4, filter_y, y_step_q4, w, intermediate_height, bd); vpx_highbd_convolve8_avg_vert_neon(CONVERT_TO_BYTEPTR(temp + w * 3), w, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, bd); }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
security/nss/lib/freebl/ecl/ecp_jac.c
9
18801
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ecp.h" #include "mplogic.h" #include <stdlib.h> #ifdef ECL_DEBUG #include <assert.h> #endif /* Converts a point P(px, py) from affine coordinates to Jacobian * projective coordinates R(rx, ry, rz). Assumes input is already * field-encoded using field_enc, and returns output that is still * field-encoded. */ mp_err ec_GFp_pt_aff2jac(const mp_int *px, const mp_int *py, mp_int *rx, mp_int *ry, mp_int *rz, const ECGroup *group) { mp_err res = MP_OKAY; if (ec_GFp_pt_is_inf_aff(px, py) == MP_YES) { MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, rz)); } else { MP_CHECKOK(mp_copy(px, rx)); MP_CHECKOK(mp_copy(py, ry)); MP_CHECKOK(mp_set_int(rz, 1)); if (group->meth->field_enc) { MP_CHECKOK(group->meth->field_enc(rz, rz, group->meth)); } } CLEANUP: return res; } /* Converts a point P(px, py, pz) from Jacobian projective coordinates to * affine coordinates R(rx, ry). P and R can share x and y coordinates. * Assumes input is already field-encoded using field_enc, and returns * output that is still field-encoded. */ mp_err ec_GFp_pt_jac2aff(const mp_int *px, const mp_int *py, const mp_int *pz, mp_int *rx, mp_int *ry, const ECGroup *group) { mp_err res = MP_OKAY; mp_int z1, z2, z3; MP_DIGITS(&z1) = 0; MP_DIGITS(&z2) = 0; MP_DIGITS(&z3) = 0; MP_CHECKOK(mp_init(&z1)); MP_CHECKOK(mp_init(&z2)); MP_CHECKOK(mp_init(&z3)); /* if point at infinity, then set point at infinity and exit */ if (ec_GFp_pt_is_inf_jac(px, py, pz) == MP_YES) { MP_CHECKOK(ec_GFp_pt_set_inf_aff(rx, ry)); goto CLEANUP; } /* transform (px, py, pz) into (px / pz^2, py / pz^3) */ if (mp_cmp_d(pz, 1) == 0) { MP_CHECKOK(mp_copy(px, rx)); MP_CHECKOK(mp_copy(py, ry)); } else { MP_CHECKOK(group->meth->field_div(NULL, pz, &z1, group->meth)); MP_CHECKOK(group->meth->field_sqr(&z1, &z2, group->meth)); MP_CHECKOK(group->meth->field_mul(&z1, &z2, &z3, group->meth)); MP_CHECKOK(group->meth->field_mul(px, &z2, rx, group->meth)); MP_CHECKOK(group->meth->field_mul(py, &z3, ry, group->meth)); } CLEANUP: mp_clear(&z1); mp_clear(&z2); mp_clear(&z3); return res; } /* Checks if point P(px, py, pz) is at infinity. Uses Jacobian * coordinates. */ mp_err ec_GFp_pt_is_inf_jac(const mp_int *px, const mp_int *py, const mp_int *pz) { return mp_cmp_z(pz); } /* Sets P(px, py, pz) to be the point at infinity. Uses Jacobian * coordinates. */ mp_err ec_GFp_pt_set_inf_jac(mp_int *px, mp_int *py, mp_int *pz) { mp_zero(pz); return MP_OKAY; } /* Computes R = P + Q where R is (rx, ry, rz), P is (px, py, pz) and Q is * (qx, qy, 1). Elliptic curve points P, Q, and R can all be identical. * Uses mixed Jacobian-affine coordinates. Assumes input is already * field-encoded using field_enc, and returns output that is still * field-encoded. Uses equation (2) from Brown, Hankerson, Lopez, and * Menezes. Software Implementation of the NIST Elliptic Curves Over Prime * Fields. */ mp_err ec_GFp_pt_add_jac_aff(const mp_int *px, const mp_int *py, const mp_int *pz, const mp_int *qx, const mp_int *qy, mp_int *rx, mp_int *ry, mp_int *rz, const ECGroup *group) { mp_err res = MP_OKAY; mp_int A, B, C, D, C2, C3; MP_DIGITS(&A) = 0; MP_DIGITS(&B) = 0; MP_DIGITS(&C) = 0; MP_DIGITS(&D) = 0; MP_DIGITS(&C2) = 0; MP_DIGITS(&C3) = 0; MP_CHECKOK(mp_init(&A)); MP_CHECKOK(mp_init(&B)); MP_CHECKOK(mp_init(&C)); MP_CHECKOK(mp_init(&D)); MP_CHECKOK(mp_init(&C2)); MP_CHECKOK(mp_init(&C3)); /* If either P or Q is the point at infinity, then return the other * point */ if (ec_GFp_pt_is_inf_jac(px, py, pz) == MP_YES) { MP_CHECKOK(ec_GFp_pt_aff2jac(qx, qy, rx, ry, rz, group)); goto CLEANUP; } if (ec_GFp_pt_is_inf_aff(qx, qy) == MP_YES) { MP_CHECKOK(mp_copy(px, rx)); MP_CHECKOK(mp_copy(py, ry)); MP_CHECKOK(mp_copy(pz, rz)); goto CLEANUP; } /* A = qx * pz^2, B = qy * pz^3 */ MP_CHECKOK(group->meth->field_sqr(pz, &A, group->meth)); MP_CHECKOK(group->meth->field_mul(&A, pz, &B, group->meth)); MP_CHECKOK(group->meth->field_mul(&A, qx, &A, group->meth)); MP_CHECKOK(group->meth->field_mul(&B, qy, &B, group->meth)); /* C = A - px, D = B - py */ MP_CHECKOK(group->meth->field_sub(&A, px, &C, group->meth)); MP_CHECKOK(group->meth->field_sub(&B, py, &D, group->meth)); if (mp_cmp_z(&C) == 0) { /* P == Q or P == -Q */ if (mp_cmp_z(&D) == 0) { /* P == Q */ /* It is cheaper to double (qx, qy, 1) than (px, py, pz). */ MP_DIGIT(&D, 0) = 1; /* Set D to 1. */ MP_CHECKOK(ec_GFp_pt_dbl_jac(qx, qy, &D, rx, ry, rz, group)); } else { /* P == -Q */ MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, rz)); } goto CLEANUP; } /* C2 = C^2, C3 = C^3 */ MP_CHECKOK(group->meth->field_sqr(&C, &C2, group->meth)); MP_CHECKOK(group->meth->field_mul(&C, &C2, &C3, group->meth)); /* rz = pz * C */ MP_CHECKOK(group->meth->field_mul(pz, &C, rz, group->meth)); /* C = px * C^2 */ MP_CHECKOK(group->meth->field_mul(px, &C2, &C, group->meth)); /* A = D^2 */ MP_CHECKOK(group->meth->field_sqr(&D, &A, group->meth)); /* rx = D^2 - (C^3 + 2 * (px * C^2)) */ MP_CHECKOK(group->meth->field_add(&C, &C, rx, group->meth)); MP_CHECKOK(group->meth->field_add(&C3, rx, rx, group->meth)); MP_CHECKOK(group->meth->field_sub(&A, rx, rx, group->meth)); /* C3 = py * C^3 */ MP_CHECKOK(group->meth->field_mul(py, &C3, &C3, group->meth)); /* ry = D * (px * C^2 - rx) - py * C^3 */ MP_CHECKOK(group->meth->field_sub(&C, rx, ry, group->meth)); MP_CHECKOK(group->meth->field_mul(&D, ry, ry, group->meth)); MP_CHECKOK(group->meth->field_sub(ry, &C3, ry, group->meth)); CLEANUP: mp_clear(&A); mp_clear(&B); mp_clear(&C); mp_clear(&D); mp_clear(&C2); mp_clear(&C3); return res; } /* Computes R = 2P. Elliptic curve points P and R can be identical. Uses * Jacobian coordinates. * * Assumes input is already field-encoded using field_enc, and returns * output that is still field-encoded. * * This routine implements Point Doubling in the Jacobian Projective * space as described in the paper "Efficient elliptic curve exponentiation * using mixed coordinates", by H. Cohen, A Miyaji, T. Ono. */ mp_err ec_GFp_pt_dbl_jac(const mp_int *px, const mp_int *py, const mp_int *pz, mp_int *rx, mp_int *ry, mp_int *rz, const ECGroup *group) { mp_err res = MP_OKAY; mp_int t0, t1, M, S; MP_DIGITS(&t0) = 0; MP_DIGITS(&t1) = 0; MP_DIGITS(&M) = 0; MP_DIGITS(&S) = 0; MP_CHECKOK(mp_init(&t0)); MP_CHECKOK(mp_init(&t1)); MP_CHECKOK(mp_init(&M)); MP_CHECKOK(mp_init(&S)); /* P == inf or P == -P */ if (ec_GFp_pt_is_inf_jac(px, py, pz) == MP_YES || mp_cmp_z(py) == 0) { MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, rz)); goto CLEANUP; } if (mp_cmp_d(pz, 1) == 0) { /* M = 3 * px^2 + a */ MP_CHECKOK(group->meth->field_sqr(px, &t0, group->meth)); MP_CHECKOK(group->meth->field_add(&t0, &t0, &M, group->meth)); MP_CHECKOK(group->meth->field_add(&t0, &M, &t0, group->meth)); MP_CHECKOK(group->meth->field_add(&t0, &group->curvea, &M, group->meth)); } else if (MP_SIGN(&group->curvea) == MP_NEG && MP_USED(&group->curvea) == 1 && MP_DIGIT(&group->curvea, 0) == 3) { /* M = 3 * (px + pz^2) * (px - pz^2) */ MP_CHECKOK(group->meth->field_sqr(pz, &M, group->meth)); MP_CHECKOK(group->meth->field_add(px, &M, &t0, group->meth)); MP_CHECKOK(group->meth->field_sub(px, &M, &t1, group->meth)); MP_CHECKOK(group->meth->field_mul(&t0, &t1, &M, group->meth)); MP_CHECKOK(group->meth->field_add(&M, &M, &t0, group->meth)); MP_CHECKOK(group->meth->field_add(&t0, &M, &M, group->meth)); } else { /* M = 3 * (px^2) + a * (pz^4) */ MP_CHECKOK(group->meth->field_sqr(px, &t0, group->meth)); MP_CHECKOK(group->meth->field_add(&t0, &t0, &M, group->meth)); MP_CHECKOK(group->meth->field_add(&t0, &M, &t0, group->meth)); MP_CHECKOK(group->meth->field_sqr(pz, &M, group->meth)); MP_CHECKOK(group->meth->field_sqr(&M, &M, group->meth)); MP_CHECKOK(group->meth->field_mul(&M, &group->curvea, &M, group->meth)); MP_CHECKOK(group->meth->field_add(&M, &t0, &M, group->meth)); } /* rz = 2 * py * pz */ /* t0 = 4 * py^2 */ if (mp_cmp_d(pz, 1) == 0) { MP_CHECKOK(group->meth->field_add(py, py, rz, group->meth)); MP_CHECKOK(group->meth->field_sqr(rz, &t0, group->meth)); } else { MP_CHECKOK(group->meth->field_add(py, py, &t0, group->meth)); MP_CHECKOK(group->meth->field_mul(&t0, pz, rz, group->meth)); MP_CHECKOK(group->meth->field_sqr(&t0, &t0, group->meth)); } /* S = 4 * px * py^2 = px * (2 * py)^2 */ MP_CHECKOK(group->meth->field_mul(px, &t0, &S, group->meth)); /* rx = M^2 - 2 * S */ MP_CHECKOK(group->meth->field_add(&S, &S, &t1, group->meth)); MP_CHECKOK(group->meth->field_sqr(&M, rx, group->meth)); MP_CHECKOK(group->meth->field_sub(rx, &t1, rx, group->meth)); /* ry = M * (S - rx) - 8 * py^4 */ MP_CHECKOK(group->meth->field_sqr(&t0, &t1, group->meth)); if (mp_isodd(&t1)) { MP_CHECKOK(mp_add(&t1, &group->meth->irr, &t1)); } MP_CHECKOK(mp_div_2(&t1, &t1)); MP_CHECKOK(group->meth->field_sub(&S, rx, &S, group->meth)); MP_CHECKOK(group->meth->field_mul(&M, &S, &M, group->meth)); MP_CHECKOK(group->meth->field_sub(&M, &t1, ry, group->meth)); CLEANUP: mp_clear(&t0); mp_clear(&t1); mp_clear(&M); mp_clear(&S); return res; } /* by default, this routine is unused and thus doesn't need to be compiled */ #ifdef ECL_ENABLE_GFP_PT_MUL_JAC /* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters * a, b and p are the elliptic curve coefficients and the prime that * determines the field GFp. Elliptic curve points P and R can be * identical. Uses mixed Jacobian-affine coordinates. Assumes input is * already field-encoded using field_enc, and returns output that is still * field-encoded. Uses 4-bit window method. */ mp_err ec_GFp_pt_mul_jac(const mp_int *n, const mp_int *px, const mp_int *py, mp_int *rx, mp_int *ry, const ECGroup *group) { mp_err res = MP_OKAY; mp_int precomp[16][2], rz; int i, ni, d; MP_DIGITS(&rz) = 0; for (i = 0; i < 16; i++) { MP_DIGITS(&precomp[i][0]) = 0; MP_DIGITS(&precomp[i][1]) = 0; } ARGCHK(group != NULL, MP_BADARG); ARGCHK((n != NULL) && (px != NULL) && (py != NULL), MP_BADARG); /* initialize precomputation table */ for (i = 0; i < 16; i++) { MP_CHECKOK(mp_init(&precomp[i][0])); MP_CHECKOK(mp_init(&precomp[i][1])); } /* fill precomputation table */ mp_zero(&precomp[0][0]); mp_zero(&precomp[0][1]); MP_CHECKOK(mp_copy(px, &precomp[1][0])); MP_CHECKOK(mp_copy(py, &precomp[1][1])); for (i = 2; i < 16; i++) { MP_CHECKOK(group->point_add(&precomp[1][0], &precomp[1][1], &precomp[i - 1][0], &precomp[i - 1][1], &precomp[i][0], &precomp[i][1], group)); } d = (mpl_significant_bits(n) + 3) / 4; /* R = inf */ MP_CHECKOK(mp_init(&rz)); MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, &rz)); for (i = d - 1; i >= 0; i--) { /* compute window ni */ ni = MP_GET_BIT(n, 4 * i + 3); ni <<= 1; ni |= MP_GET_BIT(n, 4 * i + 2); ni <<= 1; ni |= MP_GET_BIT(n, 4 * i + 1); ni <<= 1; ni |= MP_GET_BIT(n, 4 * i); /* R = 2^4 * R */ MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); /* R = R + (ni * P) */ MP_CHECKOK(ec_GFp_pt_add_jac_aff(rx, ry, &rz, &precomp[ni][0], &precomp[ni][1], rx, ry, &rz, group)); } /* convert result S to affine coordinates */ MP_CHECKOK(ec_GFp_pt_jac2aff(rx, ry, &rz, rx, ry, group)); CLEANUP: mp_clear(&rz); for (i = 0; i < 16; i++) { mp_clear(&precomp[i][0]); mp_clear(&precomp[i][1]); } return res; } #endif /* Elliptic curve scalar-point multiplication. Computes R(x, y) = k1 * G + * k2 * P(x, y), where G is the generator (base point) of the group of * points on the elliptic curve. Allows k1 = NULL or { k2, P } = NULL. * Uses mixed Jacobian-affine coordinates. Input and output values are * assumed to be NOT field-encoded. Uses algorithm 15 (simultaneous * multiple point multiplication) from Brown, Hankerson, Lopez, Menezes. * Software Implementation of the NIST Elliptic Curves over Prime Fields. */ mp_err ec_GFp_pts_mul_jac(const mp_int *k1, const mp_int *k2, const mp_int *px, const mp_int *py, mp_int *rx, mp_int *ry, const ECGroup *group) { mp_err res = MP_OKAY; mp_int precomp[4][4][2]; mp_int rz; const mp_int *a, *b; unsigned int i, j; int ai, bi, d; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { MP_DIGITS(&precomp[i][j][0]) = 0; MP_DIGITS(&precomp[i][j][1]) = 0; } } MP_DIGITS(&rz) = 0; ARGCHK(group != NULL, MP_BADARG); ARGCHK(!((k1 == NULL) && ((k2 == NULL) || (px == NULL) || (py == NULL))), MP_BADARG); /* if some arguments are not defined used ECPoint_mul */ if (k1 == NULL) { return ECPoint_mul(group, k2, px, py, rx, ry); } else if ((k2 == NULL) || (px == NULL) || (py == NULL)) { return ECPoint_mul(group, k1, NULL, NULL, rx, ry); } /* initialize precomputation table */ for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { MP_CHECKOK(mp_init(&precomp[i][j][0])); MP_CHECKOK(mp_init(&precomp[i][j][1])); } } /* fill precomputation table */ /* assign {k1, k2} = {a, b} such that len(a) >= len(b) */ if (mpl_significant_bits(k1) < mpl_significant_bits(k2)) { a = k2; b = k1; if (group->meth->field_enc) { MP_CHECKOK(group->meth->field_enc(px, &precomp[1][0][0], group->meth)); MP_CHECKOK(group->meth->field_enc(py, &precomp[1][0][1], group->meth)); } else { MP_CHECKOK(mp_copy(px, &precomp[1][0][0])); MP_CHECKOK(mp_copy(py, &precomp[1][0][1])); } MP_CHECKOK(mp_copy(&group->genx, &precomp[0][1][0])); MP_CHECKOK(mp_copy(&group->geny, &precomp[0][1][1])); } else { a = k1; b = k2; MP_CHECKOK(mp_copy(&group->genx, &precomp[1][0][0])); MP_CHECKOK(mp_copy(&group->geny, &precomp[1][0][1])); if (group->meth->field_enc) { MP_CHECKOK(group->meth->field_enc(px, &precomp[0][1][0], group->meth)); MP_CHECKOK(group->meth->field_enc(py, &precomp[0][1][1], group->meth)); } else { MP_CHECKOK(mp_copy(px, &precomp[0][1][0])); MP_CHECKOK(mp_copy(py, &precomp[0][1][1])); } } /* precompute [*][0][*] */ mp_zero(&precomp[0][0][0]); mp_zero(&precomp[0][0][1]); MP_CHECKOK(group->point_dbl(&precomp[1][0][0], &precomp[1][0][1], &precomp[2][0][0], &precomp[2][0][1], group)); MP_CHECKOK(group->point_add(&precomp[1][0][0], &precomp[1][0][1], &precomp[2][0][0], &precomp[2][0][1], &precomp[3][0][0], &precomp[3][0][1], group)); /* precompute [*][1][*] */ for (i = 1; i < 4; i++) { MP_CHECKOK(group->point_add(&precomp[0][1][0], &precomp[0][1][1], &precomp[i][0][0], &precomp[i][0][1], &precomp[i][1][0], &precomp[i][1][1], group)); } /* precompute [*][2][*] */ MP_CHECKOK(group->point_dbl(&precomp[0][1][0], &precomp[0][1][1], &precomp[0][2][0], &precomp[0][2][1], group)); for (i = 1; i < 4; i++) { MP_CHECKOK(group->point_add(&precomp[0][2][0], &precomp[0][2][1], &precomp[i][0][0], &precomp[i][0][1], &precomp[i][2][0], &precomp[i][2][1], group)); } /* precompute [*][3][*] */ MP_CHECKOK(group->point_add(&precomp[0][1][0], &precomp[0][1][1], &precomp[0][2][0], &precomp[0][2][1], &precomp[0][3][0], &precomp[0][3][1], group)); for (i = 1; i < 4; i++) { MP_CHECKOK(group->point_add(&precomp[0][3][0], &precomp[0][3][1], &precomp[i][0][0], &precomp[i][0][1], &precomp[i][3][0], &precomp[i][3][1], group)); } d = (mpl_significant_bits(a) + 1) / 2; /* R = inf */ MP_CHECKOK(mp_init(&rz)); MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, &rz)); for (i = d; i-- > 0;) { ai = MP_GET_BIT(a, 2 * i + 1); ai <<= 1; ai |= MP_GET_BIT(a, 2 * i); bi = MP_GET_BIT(b, 2 * i + 1); bi <<= 1; bi |= MP_GET_BIT(b, 2 * i); /* R = 2^2 * R */ MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); /* R = R + (ai * A + bi * B) */ MP_CHECKOK(ec_GFp_pt_add_jac_aff(rx, ry, &rz, &precomp[ai][bi][0], &precomp[ai][bi][1], rx, ry, &rz, group)); } MP_CHECKOK(ec_GFp_pt_jac2aff(rx, ry, &rz, rx, ry, group)); if (group->meth->field_dec) { MP_CHECKOK(group->meth->field_dec(rx, rx, group->meth)); MP_CHECKOK(group->meth->field_dec(ry, ry, group->meth)); } CLEANUP: mp_clear(&rz); for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { mp_clear(&precomp[i][j][0]); mp_clear(&precomp[i][j][1]); } } return res; }
mpl-2.0
Johennes/firefox-ios
ThirdParty/SQLite.swift/Vendor/sqlcipher/src/crypto.c
16
27627
/* ** SQLCipher ** http://sqlcipher.net ** ** Copyright (c) 2008 - 2013, ZETETIC LLC ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** * Neither the name of the ZETETIC LLC nor the ** names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** */ /* BEGIN SQLCIPHER */ #ifdef SQLITE_HAS_CODEC #include <assert.h> #include "sqliteInt.h" #include "btreeInt.h" #include "crypto.h" static const char* codec_get_cipher_version() { return CIPHER_VERSION; } /* Generate code to return a string value */ static void codec_vdbe_return_static_string(Parse *pParse, const char *zLabel, const char *value){ Vdbe *v = sqlite3GetVdbe(pParse); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC); sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, value, 0); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } static int codec_set_btree_to_codec_pagesize(sqlite3 *db, Db *pDb, codec_ctx *ctx) { int rc, page_sz, reserve_sz; page_sz = sqlcipher_codec_ctx_get_pagesize(ctx); reserve_sz = sqlcipher_codec_ctx_get_reservesize(ctx); sqlite3_mutex_enter(db->mutex); db->nextPagesize = page_sz; /* before forcing the page size we need to unset the BTS_PAGESIZE_FIXED flag, else sqliteBtreeSetPageSize will block the change */ pDb->pBt->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; CODEC_TRACE(("codec_set_btree_to_codec_pagesize: sqlite3BtreeSetPageSize() size=%d reserve=%d\n", page_sz, reserve_sz)); rc = sqlite3BtreeSetPageSize(pDb->pBt, page_sz, reserve_sz, 0); sqlite3_mutex_leave(db->mutex); return rc; } static int codec_set_pass_key(sqlite3* db, int nDb, const void *zKey, int nKey, int for_ctx) { struct Db *pDb = &db->aDb[nDb]; CODEC_TRACE(("codec_set_pass_key: entered db=%p nDb=%d zKey=%s nKey=%d for_ctx=%d\n", db, nDb, (char *)zKey, nKey, for_ctx)); if(pDb->pBt) { codec_ctx *ctx; sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx); if(ctx) return sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, for_ctx); } return SQLITE_ERROR; } int sqlcipher_codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLeft, const char *zRight) { struct Db *pDb = &db->aDb[iDb]; codec_ctx *ctx = NULL; int rc; if(pDb->pBt) { sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx); } CODEC_TRACE(("sqlcipher_codec_pragma: entered db=%p iDb=%d pParse=%p zLeft=%s zRight=%s ctx=%p\n", db, iDb, pParse, zLeft, zRight, ctx)); if( sqlite3StrICmp(zLeft, "cipher_fips_status")== 0 && !zRight ){ if(ctx) { char *fips_mode_status = sqlite3_mprintf("%d", sqlcipher_codec_fips_status(ctx)); codec_vdbe_return_static_string(pParse, "cipher_fips_status", fips_mode_status); sqlite3_free(fips_mode_status); } } else if( sqlite3StrICmp(zLeft, "cipher_store_pass")==0 && zRight ) { if(ctx) { sqlcipher_codec_set_store_pass(ctx, sqlite3GetBoolean(zRight, 1)); } } else if( sqlite3StrICmp(zLeft, "cipher_store_pass")==0 && !zRight ) { if(ctx){ char *store_pass_value = sqlite3_mprintf("%d", sqlcipher_codec_get_store_pass(ctx)); codec_vdbe_return_static_string(pParse, "cipher_store_pass", store_pass_value); sqlite3_free(store_pass_value); } } if( sqlite3StrICmp(zLeft, "cipher_profile")== 0 && zRight ){ char *profile_status = sqlite3_mprintf("%d", sqlcipher_cipher_profile(db, zRight)); codec_vdbe_return_static_string(pParse, "cipher_profile", profile_status); sqlite3_free(profile_status); } else if( sqlite3StrICmp(zLeft, "cipher_add_random")==0 && zRight ){ if(ctx) { char *add_random_status = sqlite3_mprintf("%d", sqlcipher_codec_add_random(ctx, zRight, sqlite3Strlen30(zRight))); codec_vdbe_return_static_string(pParse, "cipher_add_random", add_random_status); sqlite3_free(add_random_status); } } else if( sqlite3StrICmp(zLeft, "cipher_migrate")==0 && !zRight ){ if(ctx){ char *migrate_status = sqlite3_mprintf("%d", sqlcipher_codec_ctx_migrate(ctx)); codec_vdbe_return_static_string(pParse, "cipher_migrate", migrate_status); sqlite3_free(migrate_status); } } else if( sqlite3StrICmp(zLeft, "cipher_provider")==0 && !zRight ){ if(ctx) { codec_vdbe_return_static_string(pParse, "cipher_provider", sqlcipher_codec_get_cipher_provider(ctx)); } } else if( sqlite3StrICmp(zLeft, "cipher_version")==0 && !zRight ){ codec_vdbe_return_static_string(pParse, "cipher_version", codec_get_cipher_version()); }else if( sqlite3StrICmp(zLeft, "cipher")==0 ){ if(ctx) { if( zRight ) { sqlcipher_codec_ctx_set_cipher(ctx, zRight, 2); // change cipher for both }else { codec_vdbe_return_static_string(pParse, "cipher", sqlcipher_codec_ctx_get_cipher(ctx, 2)); } } }else if( sqlite3StrICmp(zLeft, "rekey_cipher")==0 && zRight ){ if(ctx) sqlcipher_codec_ctx_set_cipher(ctx, zRight, 1); // change write cipher only }else if( sqlite3StrICmp(zLeft,"cipher_default_kdf_iter")==0 ){ if( zRight ) { sqlcipher_set_default_kdf_iter(atoi(zRight)); // change default KDF iterations } else { char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_get_default_kdf_iter()); codec_vdbe_return_static_string(pParse, "cipher_default_kdf_iter", kdf_iter); sqlite3_free(kdf_iter); } }else if( sqlite3StrICmp(zLeft, "kdf_iter")==0 ){ if(ctx) { if( zRight ) { sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight), 2); // change of RW PBKDF2 iteration } else { char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_kdf_iter(ctx, 2)); codec_vdbe_return_static_string(pParse, "kdf_iter", kdf_iter); sqlite3_free(kdf_iter); } } }else if( sqlite3StrICmp(zLeft, "fast_kdf_iter")==0){ if(ctx) { if( zRight ) { sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, atoi(zRight), 2); // change of RW PBKDF2 iteration } else { char *fast_kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_fast_kdf_iter(ctx, 2)); codec_vdbe_return_static_string(pParse, "fast_kdf_iter", fast_kdf_iter); sqlite3_free(fast_kdf_iter); } } }else if( sqlite3StrICmp(zLeft, "rekey_kdf_iter")==0 && zRight ){ if(ctx) sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight), 1); // write iterations only }else if( sqlite3StrICmp(zLeft,"cipher_page_size")==0 ){ if(ctx) { if( zRight ) { int size = atoi(zRight); rc = sqlcipher_codec_ctx_set_pagesize(ctx, size); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); } else { char * page_size = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_pagesize(ctx)); codec_vdbe_return_static_string(pParse, "cipher_page_size", page_size); sqlite3_free(page_size); } } }else if( sqlite3StrICmp(zLeft,"cipher_default_page_size")==0 ){ if( zRight ) { sqlcipher_set_default_pagesize(atoi(zRight)); } else { char *default_page_size = sqlite3_mprintf("%d", sqlcipher_get_default_pagesize()); codec_vdbe_return_static_string(pParse, "cipher_default_page_size", default_page_size); sqlite3_free(default_page_size); } }else if( sqlite3StrICmp(zLeft,"cipher_default_use_hmac")==0 ){ if( zRight ) { sqlcipher_set_default_use_hmac(sqlite3GetBoolean(zRight,1)); } else { char *default_use_hmac = sqlite3_mprintf("%d", sqlcipher_get_default_use_hmac()); codec_vdbe_return_static_string(pParse, "cipher_default_use_hmac", default_use_hmac); sqlite3_free(default_use_hmac); } }else if( sqlite3StrICmp(zLeft,"cipher_use_hmac")==0 ){ if(ctx) { if( zRight ) { rc = sqlcipher_codec_ctx_set_use_hmac(ctx, sqlite3GetBoolean(zRight,1)); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); /* since the use of hmac has changed, the page size may also change */ rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); } else { char *hmac_flag = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_use_hmac(ctx, 2)); codec_vdbe_return_static_string(pParse, "cipher_use_hmac", hmac_flag); sqlite3_free(hmac_flag); } } }else if( sqlite3StrICmp(zLeft,"cipher_hmac_pgno")==0 ){ if(ctx) { if(zRight) { // clear both pgno endian flags if(sqlite3StrICmp(zRight, "le") == 0) { sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO); sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_LE_PGNO); } else if(sqlite3StrICmp(zRight, "be") == 0) { sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO); sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_BE_PGNO); } else if(sqlite3StrICmp(zRight, "native") == 0) { sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO); sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO); } } else { if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_LE_PGNO, 2)) { codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "le"); } else if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_BE_PGNO, 2)) { codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "be"); } else { codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "native"); } } } }else if( sqlite3StrICmp(zLeft,"cipher_hmac_salt_mask")==0 ){ if(ctx) { if(zRight) { if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == 5) { unsigned char mask = 0; const unsigned char *hex = (const unsigned char *)zRight+2; cipher_hex2bin(hex,2,&mask); sqlcipher_set_hmac_salt_mask(mask); } } else { char *hmac_salt_mask = sqlite3_mprintf("%02x", sqlcipher_get_hmac_salt_mask()); codec_vdbe_return_static_string(pParse, "cipher_hmac_salt_mask", hmac_salt_mask); sqlite3_free(hmac_salt_mask); } } }else { return 0; } return 1; } /* * sqlite3Codec can be called in multiple modes. * encrypt mode - expected to return a pointer to the * encrypted data without altering pData. * decrypt mode - expected to return a pointer to pData, with * the data decrypted in the input buffer */ void* sqlite3Codec(void *iCtx, void *data, Pgno pgno, int mode) { codec_ctx *ctx = (codec_ctx *) iCtx; int offset = 0, rc = 0; int page_sz = sqlcipher_codec_ctx_get_pagesize(ctx); unsigned char *pData = (unsigned char *) data; void *buffer = sqlcipher_codec_ctx_get_data(ctx); void *kdf_salt = sqlcipher_codec_ctx_get_kdf_salt(ctx); CODEC_TRACE(("sqlite3Codec: entered pgno=%d, mode=%d, page_sz=%d\n", pgno, mode, page_sz)); /* call to derive keys if not present yet */ if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) { sqlcipher_codec_ctx_set_error(ctx, rc); return NULL; } if(pgno == 1) offset = FILE_HEADER_SZ; /* adjust starting pointers in data page for header offset on first page*/ CODEC_TRACE(("sqlite3Codec: switch mode=%d offset=%d\n", mode, offset)); switch(mode) { case 0: /* decrypt */ case 2: case 3: if(pgno == 1) memcpy(buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ); /* copy file header to the first 16 bytes of the page */ rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_DECRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); memcpy(pData, buffer, page_sz); /* copy buffer data back to pData and return */ return pData; break; case 6: /* encrypt */ if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */ rc = sqlcipher_page_cipher(ctx, CIPHER_WRITE_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); return buffer; /* return persistent buffer data, pData remains intact */ break; case 7: if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */ rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); return buffer; /* return persistent buffer data, pData remains intact */ break; default: return pData; break; } } void sqlite3FreeCodecArg(void *pCodecArg) { codec_ctx *ctx = (codec_ctx *) pCodecArg; if(pCodecArg == NULL) return; sqlcipher_codec_ctx_free(&ctx); // wipe and free allocated memory for the context sqlcipher_deactivate(); /* cleanup related structures, OpenSSL etc, when codec is detatched */ } int sqlite3CodecAttach(sqlite3* db, int nDb, const void *zKey, int nKey) { struct Db *pDb = &db->aDb[nDb]; CODEC_TRACE(("sqlite3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, (char *)zKey, nKey)); if(nKey && zKey && pDb->pBt) { int rc; Pager *pPager = pDb->pBt->pBt->pPager; sqlite3_file *fd = sqlite3Pager_get_fd(pPager); codec_ctx *ctx; sqlcipher_activate(); /* perform internal initialization for sqlcipher */ sqlite3_mutex_enter(db->mutex); /* point the internal codec argument against the contet to be prepared */ rc = sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, fd, zKey, nKey); if(rc != SQLITE_OK) return rc; /* initialization failed, do not attach potentially corrupted context */ sqlite3pager_sqlite3PagerSetCodec(sqlite3BtreePager(pDb->pBt), sqlite3Codec, NULL, sqlite3FreeCodecArg, (void *) ctx); codec_set_btree_to_codec_pagesize(db, pDb, ctx); /* force secure delete. This has the benefit of wiping internal data when deleted and also ensures that all pages are written to disk (i.e. not skipped by sqlite3PagerDontWrite optimizations) */ sqlite3BtreeSecureDelete(pDb->pBt, 1); /* if fd is null, then this is an in-memory database and we dont' want to overwrite the AutoVacuum settings if not null, then set to the default */ if(fd != NULL) { sqlite3BtreeSetAutoVacuum(pDb->pBt, SQLITE_DEFAULT_AUTOVACUUM); } sqlite3_mutex_leave(db->mutex); } return SQLITE_OK; } void sqlite3_activate_see(const char* in) { /* do nothing, security enhancements are always active */ } static int sqlcipher_find_db_index(sqlite3 *db, const char *zDb) { int db_index; if(zDb == NULL){ return 0; } for(db_index = 0; db_index < db->nDb; db_index++) { struct Db *pDb = &db->aDb[db_index]; if(strcmp(pDb->zName, zDb) == 0) { return db_index; } } return 0; } int sqlite3_key(sqlite3 *db, const void *pKey, int nKey) { CODEC_TRACE(("sqlite3_key entered: db=%p pKey=%s nKey=%d\n", db, (char *)pKey, nKey)); return sqlite3_key_v2(db, "main", pKey, nKey); } int sqlite3_key_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) { CODEC_TRACE(("sqlite3_key_v2: entered db=%p zDb=%s pKey=%s nKey=%d\n", db, zDb, (char *)pKey, nKey)); /* attach key if db and pKey are not null and nKey is > 0 */ if(db && pKey && nKey) { int db_index = sqlcipher_find_db_index(db, zDb); return sqlite3CodecAttach(db, db_index, pKey, nKey); } return SQLITE_ERROR; } int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) { CODEC_TRACE(("sqlite3_rekey entered: db=%p pKey=%s nKey=%d\n", db, (char *)pKey, nKey)); return sqlite3_rekey_v2(db, "main", pKey, nKey); } /* sqlite3_rekey_v2 ** Given a database, this will reencrypt the database using a new key. ** There is only one possible modes of operation - to encrypt a database ** that is already encrpyted. If the database is not already encrypted ** this should do nothing ** The proposed logic for this function follows: ** 1. Determine if the database is already encryptped ** 2. If there is NOT already a key present do nothing ** 3. If there is a key present, re-encrypt the database with the new key */ int sqlite3_rekey_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) { CODEC_TRACE(("sqlite3_rekey_v2: entered db=%p zDb=%s pKey=%s, nKey=%d\n", db, zDb, (char *)pKey, nKey)); if(db && pKey && nKey) { int db_index = sqlcipher_find_db_index(db, zDb); struct Db *pDb = &db->aDb[db_index]; CODEC_TRACE(("sqlite3_rekey_v2: database pDb=%p db_index:%d\n", pDb, db_index)); if(pDb->pBt) { codec_ctx *ctx; int rc, page_count; Pgno pgno; PgHdr *page; Pager *pPager = pDb->pBt->pBt->pPager; sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx); if(ctx == NULL) { /* there was no codec attached to this database, so this should do nothing! */ CODEC_TRACE(("sqlite3_rekey_v2: no codec attached to db, exiting\n")); return SQLITE_OK; } sqlite3_mutex_enter(db->mutex); codec_set_pass_key(db, db_index, pKey, nKey, CIPHER_WRITE_CTX); /* do stuff here to rewrite the database ** 1. Create a transaction on the database ** 2. Iterate through each page, reading it and then writing it. ** 3. If that goes ok then commit and put ctx->rekey into ctx->key ** note: don't deallocate rekey since it may be used in a subsequent iteration */ rc = sqlite3BtreeBeginTrans(pDb->pBt, 1); /* begin write transaction */ sqlite3PagerPagecount(pPager, &page_count); for(pgno = 1; rc == SQLITE_OK && pgno <= (unsigned int)page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */ if(!sqlite3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */ rc = sqlite3PagerGet(pPager, pgno, &page); if(rc == SQLITE_OK) { /* write page see pager_incr_changecounter for example */ rc = sqlite3PagerWrite(page); if(rc == SQLITE_OK) { sqlite3PagerUnref(page); } else { CODEC_TRACE(("sqlite3_rekey_v2: error %d occurred writing page %d\n", rc, pgno)); } } else { CODEC_TRACE(("sqlite3_rekey_v2: error %d occurred getting page %d\n", rc, pgno)); } } } /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */ if(rc == SQLITE_OK) { CODEC_TRACE(("sqlite3_rekey_v2: committing\n")); rc = sqlite3BtreeCommit(pDb->pBt); sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX); } else { CODEC_TRACE(("sqlite3_rekey_v2: rollback\n")); sqlite3BtreeRollback(pDb->pBt, SQLITE_ABORT_ROLLBACK, 0); } sqlite3_mutex_leave(db->mutex); } return SQLITE_OK; } return SQLITE_ERROR; } void sqlite3CodecGetKey(sqlite3* db, int nDb, void **zKey, int *nKey) { struct Db *pDb = &db->aDb[nDb]; CODEC_TRACE(("sqlite3CodecGetKey: entered db=%p, nDb=%d\n", db, nDb)); if( pDb->pBt ) { codec_ctx *ctx; sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx); if(ctx) { if(sqlcipher_codec_get_store_pass(ctx) == 1) { sqlcipher_codec_get_pass(ctx, zKey, nKey); } else { sqlcipher_codec_get_keyspec(ctx, zKey, nKey); } } else { *zKey = NULL; *nKey = 0; } } } #ifndef OMIT_EXPORT /* * Implementation of an "export" function that allows a caller * to duplicate the main database to an attached database. This is intended * as a conveneince for users who need to: * * 1. migrate from an non-encrypted database to an encrypted database * 2. move from an encrypted database to a non-encrypted database * 3. convert beween the various flavors of encrypted databases. * * This implementation is based heavily on the procedure and code used * in vacuum.c, but is exposed as a function that allows export to any * named attached database. */ /* ** Finalize a prepared statement. If there was an error, store the ** text of the error message in *pzErrMsg. Return the result code. ** ** Based on vacuumFinalize from vacuum.c */ static int sqlcipher_finalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){ int rc; rc = sqlite3VdbeFinalize((Vdbe*)pStmt); if( rc ){ sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); } return rc; } /* ** Execute zSql on database db. Return an error code. ** ** Based on execSql from vacuum.c */ static int sqlcipher_execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ sqlite3_stmt *pStmt; VVA_ONLY( int rc; ) if( !zSql ){ return SQLITE_NOMEM; } if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); return sqlite3_errcode(db); } VVA_ONLY( rc = ) sqlite3_step(pStmt); assert( rc!=SQLITE_ROW ); return sqlcipher_finalize(db, pStmt, pzErrMsg); } /* ** Execute zSql on database db. The statement returns exactly ** one column. Execute this as SQL on the same database. ** ** Based on execExecSql from vacuum.c */ static int sqlcipher_execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ sqlite3_stmt *pStmt; int rc; rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; while( SQLITE_ROW==sqlite3_step(pStmt) ){ rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0)); if( rc!=SQLITE_OK ){ sqlcipher_finalize(db, pStmt, pzErrMsg); return rc; } } return sqlcipher_finalize(db, pStmt, pzErrMsg); } /* * copy database and schema from the main database to an attached database * * Based on sqlite3RunVacuum from vacuum.c */ void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) { sqlite3 *db = sqlite3_context_db_handle(context); const char* attachedDb = (const char*) sqlite3_value_text(argv[0]); int saved_flags; /* Saved value of the db->flags */ int saved_nChange; /* Saved value of db->nChange */ int saved_nTotalChange; /* Saved value of db->nTotalChange */ void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */ int rc = SQLITE_OK; /* Return code from service routines */ char *zSql = NULL; /* SQL statements */ char *pzErrMsg = NULL; saved_flags = db->flags; saved_nChange = db->nChange; saved_nTotalChange = db->nTotalChange; saved_xTrace = db->xTrace; db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin; db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder); db->xTrace = 0; /* Query the schema of the main database. Create a mirror schema ** in the temporary database. */ zSql = sqlite3_mprintf( "SELECT 'CREATE TABLE %s.' || substr(sql,14) " " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" " AND rootpage>0" , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT 'CREATE INDEX %s.' || substr(sql,14)" " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %%' " , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT 'CREATE UNIQUE INDEX %s.' || substr(sql,21) " " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'" , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Loop through the tables in the main database. For each, do ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy ** the contents to the temporary database. */ zSql = sqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " "|| ' SELECT * FROM main.' || quote(name) || ';'" "FROM main.sqlite_master " "WHERE type = 'table' AND name!='sqlite_sequence' " " AND rootpage>0" , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Copy over the sequence table */ zSql = sqlite3_mprintf( "SELECT 'DELETE FROM %s.' || quote(name) || ';' " "FROM %s.sqlite_master WHERE name='sqlite_sequence' " , attachedDb, attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " "|| ' SELECT * FROM main.' || quote(name) || ';' " "FROM %s.sqlite_master WHERE name=='sqlite_sequence';" , attachedDb, attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Copy the triggers, views, and virtual tables from the main database ** over to the temporary database. None of these objects has any ** associated storage, so all we have to do is copy their entries ** from the SQLITE_MASTER table. */ zSql = sqlite3_mprintf( "INSERT INTO %s.sqlite_master " " SELECT type, name, tbl_name, rootpage, sql" " FROM main.sqlite_master" " WHERE type='view' OR type='trigger'" " OR (type='table' AND rootpage=0)" , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = NULL; end_of_export: db->flags = saved_flags; db->nChange = saved_nChange; db->nTotalChange = saved_nTotalChange; db->xTrace = saved_xTrace; sqlite3_free(zSql); if(rc) { if(pzErrMsg != NULL) { sqlite3_result_error(context, pzErrMsg, -1); sqlite3DbFree(db, pzErrMsg); } else { sqlite3_result_error(context, sqlite3ErrStr(rc), -1); } } } #endif /* END SQLCIPHER */ #endif
mpl-2.0
prusa3d/Slic3r
src/slic3r/Utils/Serial.cpp
1
15186
#include "Serial.hpp" #include "libslic3r/Exception.hpp" #include <algorithm> #include <string> #include <vector> #include <chrono> #include <thread> #include <fstream> #include <exception> #include <stdexcept> #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <boost/optional.hpp> #if _WIN32 #include <Windows.h> #include <Setupapi.h> #include <initguid.h> #include <devguid.h> #include <regex> // Undefine min/max macros incompatible with the standard library // For example, std::numeric_limits<std::streamsize>::max() // produces some weird errors #ifdef min #undef min #endif #ifdef max #undef max #endif #include "boost/nowide/convert.hpp" #pragma comment(lib, "user32.lib") #elif __APPLE__ #include <CoreFoundation/CoreFoundation.h> #include <CoreFoundation/CFString.h> #include <IOKit/IOKitLib.h> #include <IOKit/serial/IOSerialKeys.h> #include <IOKit/serial/ioss.h> #include <sys/syslimits.h> #endif #ifndef _WIN32 #include <sys/ioctl.h> #include <sys/time.h> #include <sys/unistd.h> #include <sys/select.h> #endif #if defined(__APPLE__) || defined(__OpenBSD__) #include <termios.h> #elif defined __linux__ #include <fcntl.h> #include <asm-generic/ioctls.h> #endif using boost::optional; namespace Slic3r { namespace Utils { static bool looks_like_printer(const std::string &friendly_name) { return friendly_name.find("Original Prusa") != std::string::npos; } #if _WIN32 void parse_hardware_id(const std::string &hardware_id, SerialPortInfo &spi) { unsigned vid, pid; std::regex pattern("USB\\\\.*VID_([[:xdigit:]]+)&PID_([[:xdigit:]]+).*"); std::smatch matches; if (std::regex_match(hardware_id, matches, pattern)) { vid = std::stoul(matches[1].str(), 0, 16); pid = std::stoul(matches[2].str(), 0, 16); spi.id_vendor = vid; spi.id_product = pid; } } #endif #ifdef __linux__ optional<std::string> sysfs_tty_prop(const std::string &tty_dev, const std::string &name) { const auto prop_path = (boost::format("/sys/class/tty/%1%/device/../%2%") % tty_dev % name).str(); std::ifstream file(prop_path); std::string res; std::getline(file, res); if (file.good()) { return res; } else { return boost::none; } } optional<unsigned long> sysfs_tty_prop_hex(const std::string &tty_dev, const std::string &name) { auto prop = sysfs_tty_prop(tty_dev, name); if (!prop) { return boost::none; } try { return std::stoul(*prop, 0, 16); } catch (const std::exception&) { return boost::none; } } #endif std::vector<SerialPortInfo> scan_serial_ports_extended() { std::vector<SerialPortInfo> output; #ifdef _WIN32 SP_DEVINFO_DATA devInfoData = { 0 }; devInfoData.cbSize = sizeof(devInfoData); // Get the tree containing the info for the ports. HDEVINFO hDeviceInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, 0, nullptr, DIGCF_PRESENT); if (hDeviceInfo != INVALID_HANDLE_VALUE) { // Iterate over all the devices in the tree. for (int nDevice = 0; SetupDiEnumDeviceInfo(hDeviceInfo, nDevice, &devInfoData); ++ nDevice) { SerialPortInfo port_info; // Get the registry key which stores the ports settings. HKEY hDeviceKey = SetupDiOpenDevRegKey(hDeviceInfo, &devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE); if (hDeviceKey) { // Read in the name of the port. wchar_t pszPortName[4096]; DWORD dwSize = sizeof(pszPortName); DWORD dwType = 0; if (RegQueryValueEx(hDeviceKey, L"PortName", NULL, &dwType, (LPBYTE)pszPortName, &dwSize) == ERROR_SUCCESS) port_info.port = boost::nowide::narrow(pszPortName); RegCloseKey(hDeviceKey); if (port_info.port.empty()) continue; } // Find the size required to hold the device info. DWORD regDataType; DWORD reqSize = 0; SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, nullptr, nullptr, 0, &reqSize); std::vector<wchar_t> hardware_id(reqSize > 1 ? reqSize : 1); // Now store it in a buffer. if (! SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, &regDataType, (BYTE*)hardware_id.data(), reqSize, nullptr)) continue; parse_hardware_id(boost::nowide::narrow(hardware_id.data()), port_info); // Find the size required to hold the friendly name. reqSize = 0; SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, nullptr, 0, &reqSize); std::vector<wchar_t> friendly_name; friendly_name.reserve(reqSize > 1 ? reqSize : 1); // Now store it in a buffer. if (! SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, (BYTE*)friendly_name.data(), reqSize, nullptr)) { port_info.friendly_name = port_info.port; } else { port_info.friendly_name = boost::nowide::narrow(friendly_name.data()); port_info.is_printer = looks_like_printer(port_info.friendly_name); } output.emplace_back(std::move(port_info)); } } #elif __APPLE__ // inspired by https://sigrok.org/wiki/Libserialport CFMutableDictionaryRef classes = IOServiceMatching(kIOSerialBSDServiceValue); if (classes != 0) { io_iterator_t iter; if (IOServiceGetMatchingServices(kIOMasterPortDefault, classes, &iter) == KERN_SUCCESS) { io_object_t port; while ((port = IOIteratorNext(iter)) != 0) { CFTypeRef cf_property = IORegistryEntryCreateCFProperty(port, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0); if (cf_property) { char path[PATH_MAX]; Boolean result = CFStringGetCString((CFStringRef)cf_property, path, sizeof(path), kCFStringEncodingUTF8); CFRelease(cf_property); if (result) { SerialPortInfo port_info; port_info.port = path; // Attempt to read out the device friendly name if ((cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane, CFSTR("USB Interface Name"), kCFAllocatorDefault, kIORegistryIterateRecursively | kIORegistryIterateParents)) || (cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane, CFSTR("USB Product Name"), kCFAllocatorDefault, kIORegistryIterateRecursively | kIORegistryIterateParents)) || (cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane, CFSTR("Product Name"), kCFAllocatorDefault, kIORegistryIterateRecursively | kIORegistryIterateParents)) || (cf_property = IORegistryEntryCreateCFProperty(port, CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0))) { // Description limited to 127 char, anything longer would not be user friendly anyway. char description[128]; if (CFStringGetCString((CFStringRef)cf_property, description, sizeof(description), kCFStringEncodingUTF8)) { port_info.friendly_name = std::string(description) + " (" + port_info.port + ")"; port_info.is_printer = looks_like_printer(port_info.friendly_name); } CFRelease(cf_property); } if (port_info.friendly_name.empty()) port_info.friendly_name = port_info.port; // Attempt to read out the VID & PID int vid, pid; auto cf_vendor = IORegistryEntrySearchCFProperty(port, kIOServicePlane, CFSTR("idVendor"), kCFAllocatorDefault, kIORegistryIterateRecursively | kIORegistryIterateParents); auto cf_product = IORegistryEntrySearchCFProperty(port, kIOServicePlane, CFSTR("idProduct"), kCFAllocatorDefault, kIORegistryIterateRecursively | kIORegistryIterateParents); if (cf_vendor && cf_product) { if (CFNumberGetValue((CFNumberRef)cf_vendor, kCFNumberIntType, &vid) && CFNumberGetValue((CFNumberRef)cf_product, kCFNumberIntType, &pid)) { port_info.id_vendor = vid; port_info.id_product = pid; } } if (cf_vendor) { CFRelease(cf_vendor); } if (cf_product) { CFRelease(cf_product); } output.emplace_back(std::move(port_info)); } } IOObjectRelease(port); } } } #else // UNIX / Linux std::initializer_list<const char*> prefixes { "ttyUSB" , "ttyACM", "tty.", "cu.", "rfcomm" }; for (auto &dir_entry : boost::filesystem::directory_iterator(boost::filesystem::path("/dev"))) { std::string name = dir_entry.path().filename().string(); for (const char *prefix : prefixes) { if (boost::starts_with(name, prefix)) { const auto path = dir_entry.path().string(); SerialPortInfo spi; spi.port = path; #ifdef __linux__ auto friendly_name = sysfs_tty_prop(name, "product"); if (friendly_name) { spi.is_printer = looks_like_printer(*friendly_name); spi.friendly_name = (boost::format("%1% (%2%)") % *friendly_name % path).str(); } else { spi.friendly_name = path; } auto vid = sysfs_tty_prop_hex(name, "idVendor"); auto pid = sysfs_tty_prop_hex(name, "idProduct"); if (vid && pid) { spi.id_vendor = *vid; spi.id_product = *pid; } #else spi.friendly_name = path; #endif output.emplace_back(std::move(spi)); break; } } } #endif output.erase(std::remove_if(output.begin(), output.end(), [](const SerialPortInfo &info) { return boost::starts_with(info.port, "Bluetooth") || boost::starts_with(info.port, "FireFly"); }), output.end()); return output; } std::vector<std::string> scan_serial_ports() { std::vector<SerialPortInfo> ports = scan_serial_ports_extended(); std::vector<std::string> output; output.reserve(ports.size()); for (const SerialPortInfo &spi : ports) output.emplace_back(std::move(spi.port)); return output; } // Class Serial namespace asio = boost::asio; using boost::system::error_code; Serial::Serial(asio::io_service& io_service) : asio::serial_port(io_service) {} Serial::Serial(asio::io_service& io_service, const std::string &name, unsigned baud_rate) : asio::serial_port(io_service, name) { set_baud_rate(baud_rate); } Serial::~Serial() {} void Serial::set_baud_rate(unsigned baud_rate) { try { // This does not support speeds > 115200 set_option(boost::asio::serial_port_base::baud_rate(baud_rate)); } catch (boost::system::system_error &) { auto handle = native_handle(); auto handle_errno = [](int retval) { if (retval != 0) { throw Slic3r::RuntimeError( (boost::format("Could not set baud rate: %1%") % strerror(errno)).str() ); } }; #if __APPLE__ termios ios; handle_errno(::tcgetattr(handle, &ios)); handle_errno(::cfsetspeed(&ios, baud_rate)); speed_t newSpeed = baud_rate; handle_errno(::ioctl(handle, IOSSIOSPEED, &newSpeed)); handle_errno(::tcsetattr(handle, TCSANOW, &ios)); #elif __linux__ /* The following definitions are kindly borrowed from: /usr/include/asm-generic/termbits.h Unfortunately we cannot just include that one because it would redefine the "struct termios" already defined the <termios.h> already included by Boost.ASIO. */ #define K_NCCS 19 struct termios2 { tcflag_t c_iflag; tcflag_t c_oflag; tcflag_t c_cflag; tcflag_t c_lflag; cc_t c_line; cc_t c_cc[K_NCCS]; speed_t c_ispeed; speed_t c_ospeed; }; #define BOTHER CBAUDEX termios2 ios; handle_errno(::ioctl(handle, TCGETS2, &ios)); ios.c_ispeed = ios.c_ospeed = baud_rate; ios.c_cflag &= ~CBAUD; ios.c_cflag |= BOTHER | CLOCAL | CREAD; ios.c_cc[VMIN] = 1; // Minimum of characters to read, prevents eof errors when 0 bytes are read ios.c_cc[VTIME] = 1; handle_errno(::ioctl(handle, TCSETS2, &ios)); #elif __OpenBSD__ struct termios ios; handle_errno(::tcgetattr(handle, &ios)); handle_errno(::cfsetspeed(&ios, baud_rate)); handle_errno(::tcsetattr(handle, TCSAFLUSH, &ios)); #else throw Slic3r::RuntimeError("Custom baud rates are not currently supported on this OS"); #endif } } /* void Serial::set_DTR(bool on) { auto handle = native_handle(); #if defined(_WIN32) && !defined(__SYMBIAN32__) if (! EscapeCommFunction(handle, on ? SETDTR : CLRDTR)) { throw Slic3r::RuntimeError("Could not set serial port DTR"); } #else int status; if (::ioctl(handle, TIOCMGET, &status) == 0) { on ? status |= TIOCM_DTR : status &= ~TIOCM_DTR; if (::ioctl(handle, TIOCMSET, &status) == 0) { return; } } throw Slic3r::RuntimeError( (boost::format("Could not set serial port DTR: %1%") % strerror(errno)).str() ); #endif } void Serial::reset_line_num() { // See https://github.com/MarlinFirmware/Marlin/wiki/M110 write_string("M110 N0\n"); m_line_num = 0; } bool Serial::read_line(unsigned timeout, std::string &line, error_code &ec) { auto& io_service = #if BOOST_VERSION >= 107000 //FIXME this is most certainly wrong! (boost::asio::io_context&)this->get_executor().context(); #else this->get_io_service(); #endif asio::deadline_timer timer(io_service); char c = 0; bool fail = false; while (true) { io_service.reset(); asio::async_read(*this, boost::asio::buffer(&c, 1), [&](const error_code &read_ec, size_t size) { if (ec || size == 0) { fail = true; ec = read_ec; // FIXME: only if operation not aborted } timer.cancel(); // FIXME: ditto }); if (timeout > 0) { timer.expires_from_now(boost::posix_time::milliseconds(timeout)); timer.async_wait([&](const error_code &ec) { // Ignore timer aborts if (!ec) { fail = true; this->cancel(); } }); } io_service.run(); if (fail) { return false; } else if (c != '\n') { line += c; } else { return true; } } } void Serial::printer_setup() { printer_reset(); write_string("\r\r\r\r\r\r\r\r\r\r"); // Gets rid of line noise, if any } size_t Serial::write_string(const std::string &str) { // TODO: might be wise to timeout here as well return asio::write(*this, asio::buffer(str)); } bool Serial::printer_ready_wait(unsigned retries, unsigned timeout) { std::string line; error_code ec; for (; retries > 0; retries--) { reset_line_num(); while (read_line(timeout, line, ec)) { if (line == "ok") { return true; } line.clear(); } line.clear(); } return false; } size_t Serial::printer_write_line(const std::string &line, unsigned line_num) { const auto formatted_line = Utils::Serial::printer_format_line(line, line_num); return write_string(formatted_line); } size_t Serial::printer_write_line(const std::string &line) { m_line_num++; return printer_write_line(line, m_line_num); } void Serial::printer_reset() { this->set_DTR(false); std::this_thread::sleep_for(std::chrono::milliseconds(200)); this->set_DTR(true); std::this_thread::sleep_for(std::chrono::milliseconds(200)); this->set_DTR(false); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } std::string Serial::printer_format_line(const std::string &line, unsigned line_num) { const auto line_num_str = std::to_string(line_num); unsigned checksum = 'N'; for (auto c : line_num_str) { checksum ^= c; } checksum ^= ' '; for (auto c : line) { checksum ^= c; } return (boost::format("N%1% %2%*%3%\n") % line_num_str % line % checksum).str(); } */ } // namespace Utils } // namespace Slic3r
agpl-3.0
oocran/vbbu
srslte/lib/fec/test/turbodecoder_test.c
2
7184
/** * * \section COPYRIGHT * * Copyright 2013-2015 Software Radio Systems Limited * * \section LICENSE * * This file is part of the srsLTE library. * * srsLTE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * srsLTE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * A copy of the GNU Affero General Public License can be found in * the LICENSE file in the top-level directory of this distribution * and at http://www.gnu.org/licenses/. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <time.h> #include "srslte/srslte.h" #include "turbodecoder_test.h" uint32_t frame_length = 1000, nof_frames = 100; float ebno_db = 100.0; uint32_t seed = 0; int K = -1; #define MAX_ITERATIONS 10 int nof_iterations = MAX_ITERATIONS; int test_known_data = 0; int test_errors = 0; int nof_repetitions = 1; #define SNR_POINTS 4 #define SNR_MIN 1.0 #define SNR_MAX 8.0 void usage(char *prog) { printf("Usage: %s [nlesv]\n", prog); printf( "\t-k Test with known data (ignores frame_length) [Default disabled]\n"); printf("\t-i nof_iterations [Default %d]\n", nof_iterations); printf("\t-n nof_frames [Default %d]\n", nof_frames); printf("\t-N nof_repetitions [Default %d]\n", nof_repetitions); printf("\t-l frame_length [Default %d]\n", frame_length); printf("\t-e ebno in dB [Default scan]\n"); printf("\t-t test: check errors on exit [Default disabled]\n"); printf("\t-s seed [Default 0=time]\n"); } void parse_args(int argc, char **argv) { int opt; while ((opt = getopt(argc, argv, "inNlstvekt")) != -1) { switch (opt) { case 'n': nof_frames = atoi(argv[optind]); break; case 'N': nof_repetitions = atoi(argv[optind]); break; case 'k': test_known_data = 1; break; case 't': test_errors = 1; break; case 'i': nof_iterations = atoi(argv[optind]); break; case 'l': frame_length = atoi(argv[optind]); break; case 'e': ebno_db = atof(argv[optind]); break; case 's': seed = (uint32_t) strtoul(argv[optind], NULL, 0); break; case 'v': srslte_verbose++; break; default: usage(argv[0]); exit(-1); } } } int main(int argc, char **argv) { uint32_t frame_cnt; float *llr; short *llr_s; uint8_t *llr_c; uint8_t *data_tx, *data_rx, *data_rx_bytes, *symbols; uint32_t i, j; float var[SNR_POINTS]; uint32_t snr_points; uint32_t errors; uint32_t coded_length; struct timeval tdata[3]; float mean_usec; srslte_tdec_t tdec; srslte_tcod_t tcod; parse_args(argc, argv); if (!seed) { seed = time(NULL); } srand(seed); if (test_known_data) { frame_length = KNOWN_DATA_LEN; } else { frame_length = srslte_cbsegm_cbsize(srslte_cbsegm_cbindex(frame_length)); } coded_length = 3 * (frame_length) + SRSLTE_TCOD_TOTALTAIL; printf(" Frame length: %d\n", frame_length); if (ebno_db < 100.0) { printf(" EbNo: %.2f\n", ebno_db); } data_tx = srslte_vec_malloc(frame_length * sizeof(uint8_t)); if (!data_tx) { perror("malloc"); exit(-1); } data_rx = srslte_vec_malloc(frame_length * sizeof(uint8_t)); if (!data_rx) { perror("malloc"); exit(-1); } data_rx_bytes = srslte_vec_malloc(frame_length * sizeof(uint8_t)); if (!data_rx_bytes) { perror("malloc"); exit(-1); } symbols = srslte_vec_malloc(coded_length * sizeof(uint8_t)); if (!symbols) { perror("malloc"); exit(-1); } llr = srslte_vec_malloc(coded_length * sizeof(float)); if (!llr) { perror("malloc"); exit(-1); } llr_s = srslte_vec_malloc(coded_length * sizeof(short)); if (!llr_s) { perror("malloc"); exit(-1); } llr_c = srslte_vec_malloc(coded_length * sizeof(uint8_t)); if (!llr_c) { perror("malloc"); exit(-1); } if (srslte_tcod_init(&tcod, frame_length)) { fprintf(stderr, "Error initiating Turbo coder\n"); exit(-1); } if (srslte_tdec_init(&tdec, frame_length)) { fprintf(stderr, "Error initiating Turbo decoder\n"); exit(-1); } float ebno_inc, esno_db; ebno_inc = (SNR_MAX - SNR_MIN) / SNR_POINTS; if (ebno_db == 100.0) { snr_points = SNR_POINTS; for (i = 0; i < snr_points; i++) { ebno_db = SNR_MIN + i * ebno_inc; esno_db = ebno_db + 10 * log10((double) 1 / 3); var[i] = sqrt(1 / (pow(10, esno_db / 10))); } } else { esno_db = ebno_db + 10 * log10((double) 1 / 3); var[0] = sqrt(1 / (pow(10, esno_db / 10))); snr_points = 1; } for (i = 0; i < snr_points; i++) { mean_usec = 0; errors = 0; frame_cnt = 0; while (frame_cnt < nof_frames) { /* generate data_tx */ for (j = 0; j < frame_length; j++) { if (test_known_data) { data_tx[j] = known_data[j]; } else { data_tx[j] = rand() % 2; } } /* coded BER */ if (test_known_data) { for (j = 0; j < coded_length; j++) { symbols[j] = known_data_encoded[j]; } } else { srslte_tcod_encode(&tcod, data_tx, symbols, frame_length); } for (j = 0; j < coded_length; j++) { llr[j] = symbols[j] ? 1 : -1; } srslte_ch_awgn_f(llr, llr, var[i], coded_length); for (j=0;j<coded_length;j++) { llr_s[j] = (int16_t) (100*llr[j]); } /* decoder */ srslte_tdec_reset(&tdec, frame_length); uint32_t t; if (nof_iterations == -1) { t = MAX_ITERATIONS; } else { t = nof_iterations; } gettimeofday(&tdata[1], NULL); for (int k=0;k<nof_repetitions;k++) { srslte_tdec_run_all(&tdec, llr_s, data_rx_bytes, t, frame_length); } gettimeofday(&tdata[2], NULL); get_time_interval(tdata); mean_usec = (float) mean_usec * 0.9 + (float) (tdata[0].tv_usec/nof_repetitions) * 0.1; srslte_bit_unpack_vector(data_rx_bytes, data_rx, frame_length); errors += srslte_bit_diff(data_tx, data_rx, frame_length); frame_cnt++; printf("Eb/No: %2.2f %10d/%d ", SNR_MIN + i * ebno_inc, frame_cnt, nof_frames); printf("BER: %.2e ", (float) errors / (frame_cnt * frame_length)); printf("%3.1f Mbps (%6.2f usec)", (float) frame_length / mean_usec, mean_usec); printf("\r"); } printf("\n"); } printf("\n"); if (snr_points == 1) { if (errors) { printf("%d Errors\n", errors); } } free(data_tx); free(symbols); free(llr); free(llr_c); free(data_rx); srslte_tdec_free(&tdec); srslte_tcod_free(&tcod); printf("\n"); printf("Done\n"); exit(0); }
agpl-3.0
josephlewis42/UDenverQGC
src/libs/utils/fancylineedit.cpp
28
8123
/** ****************************************************************************** * * @file fancylineedit.cpp * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. * @brief * @see The GNU Public License (GPL) Version 3 * @defgroup * @{ * *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "fancylineedit.h" #include <QtCore/QEvent> #include <QtCore/QDebug> #include <QtCore/QString> #include <QtGui/QApplication> #include <QtGui/QMenu> #include <QtGui/QMouseEvent> #include <QtGui/QLabel> enum { margin = 6 }; namespace Utils { static inline QString sideToStyleSheetString(FancyLineEdit::Side side) { return side == FancyLineEdit::Left ? QLatin1String("left") : QLatin1String("right"); } // Format style sheet for the label containing the pixmap. It has a margin on // the outer side of the whole FancyLineEdit. static QString labelStyleSheet(FancyLineEdit::Side side) { QString rc = QLatin1String("QLabel { margin-"); rc += sideToStyleSheetString(side); rc += QLatin1String(": "); rc += QString::number(margin); rc += QLatin1Char('}'); return rc; } // --------- FancyLineEditPrivate as QObject with label // event filter class FancyLineEditPrivate : public QObject { public: explicit FancyLineEditPrivate(QLineEdit *parent); virtual bool eventFilter(QObject *obj, QEvent *event); const QString m_leftLabelStyleSheet; const QString m_rightLabelStyleSheet; QLineEdit *m_lineEdit; QPixmap m_pixmap; QMenu *m_menu; QLabel *m_menuLabel; FancyLineEdit::Side m_side; bool m_useLayoutDirection; bool m_menuTabFocusTrigger; QString m_hintText; bool m_showingHintText; }; FancyLineEditPrivate::FancyLineEditPrivate(QLineEdit *parent) : QObject(parent), m_leftLabelStyleSheet(labelStyleSheet(FancyLineEdit::Left)), m_rightLabelStyleSheet(labelStyleSheet(FancyLineEdit::Right)), m_lineEdit(parent), m_menu(0), m_menuLabel(0), m_side(FancyLineEdit::Left), m_useLayoutDirection(false), m_menuTabFocusTrigger(false), m_showingHintText(false) { } bool FancyLineEditPrivate::eventFilter(QObject *obj, QEvent *event) { if (!m_menu || obj != m_menuLabel) return QObject::eventFilter(obj, event); switch (event->type()) { case QEvent::MouseButtonPress: { const QMouseEvent *me = static_cast<QMouseEvent *>(event); m_menu->exec(me->globalPos()); return true; } case QEvent::FocusIn: if (m_menuTabFocusTrigger) { m_lineEdit->setFocus(); m_menu->exec(m_menuLabel->mapToGlobal(m_menuLabel->rect().center())); return true; } default: break; } return QObject::eventFilter(obj, event); } // --------- FancyLineEdit FancyLineEdit::FancyLineEdit(QWidget *parent) : QLineEdit(parent), m_d(new FancyLineEditPrivate(this)) { m_d->m_menuLabel = new QLabel(this); m_d->m_menuLabel->installEventFilter(m_d); updateMenuLabel(); showHintText(); } FancyLineEdit::~FancyLineEdit() { } // Position the menu label left or right according to size. // Called when switching side and from resizeEvent. void FancyLineEdit::positionMenuLabel() { switch (side()) { case Left: m_d->m_menuLabel->setGeometry(0, 0, m_d->m_pixmap.width()+margin, height()); break; case Right: m_d->m_menuLabel->setGeometry(width() - m_d->m_pixmap.width() - margin, 0, m_d->m_pixmap.width()+margin, height()); break; } } void FancyLineEdit::updateStyleSheet(Side side) { // Udate the LineEdit style sheet. Make room for the label on the // respective side and set color according to whether we are showing the // hint text QString sheet = QLatin1String("QLineEdit{ padding-"); sheet += sideToStyleSheetString(side); sheet += QLatin1String(": "); sheet += QString::number(m_d->m_pixmap.width() + margin); sheet += QLatin1Char(';'); if (m_d->m_showingHintText) sheet += QLatin1String(" color: #BBBBBB;"); sheet += QLatin1Char('}'); setStyleSheet(sheet); } void FancyLineEdit::updateMenuLabel() { m_d->m_menuLabel->setPixmap(m_d->m_pixmap); const Side s = side(); switch (s) { case Left: m_d->m_menuLabel->setAlignment(Qt::AlignVCenter | Qt::AlignLeft); m_d->m_menuLabel->setStyleSheet(m_d->m_leftLabelStyleSheet); break; case Right: m_d->m_menuLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); m_d->m_menuLabel->setStyleSheet(m_d->m_rightLabelStyleSheet); break; } updateStyleSheet(s); positionMenuLabel(); } void FancyLineEdit::setSide(Side side) { m_d->m_side = side; updateMenuLabel(); } FancyLineEdit::Side FancyLineEdit::side() const { if (m_d->m_useLayoutDirection) return qApp->layoutDirection() == Qt::LeftToRight ? Left : Right; return m_d->m_side; } void FancyLineEdit::resizeEvent(QResizeEvent *) { positionMenuLabel(); } void FancyLineEdit::setPixmap(const QPixmap &pixmap) { m_d->m_pixmap = pixmap; updateMenuLabel(); } QPixmap FancyLineEdit::pixmap() const { return m_d->m_pixmap; } void FancyLineEdit::setMenu(QMenu *menu) { m_d->m_menu = menu; } QMenu *FancyLineEdit::menu() const { return m_d->m_menu; } bool FancyLineEdit::useLayoutDirection() const { return m_d->m_useLayoutDirection; } void FancyLineEdit::setUseLayoutDirection(bool v) { m_d->m_useLayoutDirection = v; } bool FancyLineEdit::isSideStored() const { return !m_d->m_useLayoutDirection; } bool FancyLineEdit::hasMenuTabFocusTrigger() const { return m_d->m_menuTabFocusTrigger; } void FancyLineEdit::setMenuTabFocusTrigger(bool v) { if (m_d->m_menuTabFocusTrigger == v) return; m_d->m_menuTabFocusTrigger = v; m_d->m_menuLabel->setFocusPolicy(v ? Qt::TabFocus : Qt::NoFocus); } QString FancyLineEdit::hintText() const { return m_d->m_hintText; } void FancyLineEdit::setHintText(const QString &ht) { // Updating magic to make the property work in Designer. if (ht == m_d->m_hintText) return; hideHintText(); m_d->m_hintText = ht; if (!hasFocus() && !ht.isEmpty()) showHintText(); } void FancyLineEdit::showHintText() { if (!m_d->m_showingHintText && text().isEmpty() && !m_d->m_hintText.isEmpty()) { m_d->m_showingHintText = true; setText(m_d->m_hintText); updateStyleSheet(side()); } } void FancyLineEdit::hideHintText() { if (m_d->m_showingHintText && !m_d->m_hintText.isEmpty()) { m_d->m_showingHintText = false; setText(QString()); updateStyleSheet(side()); } } void FancyLineEdit::focusInEvent(QFocusEvent *e) { hideHintText(); QLineEdit::focusInEvent(e); } void FancyLineEdit::focusOutEvent(QFocusEvent *e) { // Focus out: Switch to displaying the hint text unless // there is user input showHintText(); QLineEdit::focusOutEvent(e); } bool FancyLineEdit::isShowingHintText() const { return m_d->m_showingHintText; } QString FancyLineEdit::typedText() const { return m_d->m_showingHintText ? QString() : text(); } } // namespace Utils
agpl-3.0
pfchrono/rs-ascent
extras/collision/extractor/stormlib/zlib/adler32.c
144
1245
/* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-2002 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zlib.h" #define BASE 65521L /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {s1 += buf[i]; s2 += s1;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); /* ========================================================================= */ uLong ZEXPORT adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { unsigned long s1 = adler & 0xffff; unsigned long s2 = (adler >> 16) & 0xffff; int k; if (buf == Z_NULL) return 1L; while (len > 0) { k = len < NMAX ? len : NMAX; len -= k; while (k >= 16) { DO16(buf); buf += 16; k -= 16; } if (k != 0) do { s1 += *buf++; s2 += s1; } while (--k); s1 %= BASE; s2 %= BASE; } return (s2 << 16) | s1; }
agpl-3.0
jkriege2/JKQtPlotter
lib/jkqtplotter/jkqtpgraphsbasestylingmixins.cpp
1
21231
/* Copyright (c) 2008-2022 Jan W. Krieger (<jan@jkrieger.de>) This software is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License (LGPL) for more details. You should have received a copy of the GNU Lesser General Public License (LGPL) along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "jkqtplotter/jkqtpgraphsbasestylingmixins.h" #include "jkqtplotter/jkqtpbaseplotter.h" #include <QApplication> #include <QDebug> JKQTPGraphLineStyleMixin::JKQTPGraphLineStyleMixin() { m_linePen=QPen(QColor("red"), Qt::SolidLine); m_linePen.setJoinStyle(Qt::RoundJoin); m_linePen.setCapStyle(Qt::RoundCap); m_lineWidth=2; m_highlightingLineColor=QColor("yellow"); m_highlightingLineColor.setAlphaF(0.5); } void JKQTPGraphLineStyleMixin::initLineStyle(JKQTBasePlotter* parent, int &parentPlotStyle, JKQTPPlotStyleType styletype) { if (parent) { // get style settings from parent object if (parentPlotStyle<0) parentPlotStyle=parent->getNextStyle(); const JKQTBasePlotter::JKQTPPen pen=parent->getPlotStyle(parentPlotStyle, styletype); m_linePen.setColor(pen.color()); m_linePen.setStyle(pen.style()); m_lineWidth=pen.widthF(); m_highlightingLineColor=getLineColor(); m_highlightingLineColor.setAlphaF(0.5); } } JKQTPGraphLineStyleMixin::~JKQTPGraphLineStyleMixin() { } void JKQTPGraphLineStyleMixin::setLineColor(const QColor &__value) { m_linePen.setColor(__value); } void JKQTPGraphLineStyleMixin::setLineColor(const QColor &__value, double alpha) { QColor c=__value; c.setAlphaF(alpha); setLineColor(c); } QColor JKQTPGraphLineStyleMixin::getLineColor() const { return m_linePen.color(); } void JKQTPGraphLineStyleMixin::setLineStyle(Qt::PenStyle __value) { m_linePen.setStyle(__value); } Qt::PenStyle JKQTPGraphLineStyleMixin::getLineStyle() const { return m_linePen.style(); } void JKQTPGraphLineStyleMixin::setLineWidth(double __value) { this->m_lineWidth = __value; } double JKQTPGraphLineStyleMixin::getLineWidth() const { return this->m_lineWidth; } void JKQTPGraphLineStyleMixin::setLineDashOffset(qreal offset) { m_linePen.setDashOffset(offset); } qreal JKQTPGraphLineStyleMixin::getLineDashOffset() const { return m_linePen.dashOffset(); } void JKQTPGraphLineStyleMixin::setLineDashPattern(const QVector<qreal> &pattern) { m_linePen.setDashPattern(pattern); m_linePen.setStyle(Qt::CustomDashLine); } QVector<qreal> JKQTPGraphLineStyleMixin::getLineDashPattern() const { return m_linePen.dashPattern(); } void JKQTPGraphLineStyleMixin::setLineJoinStyle(Qt::PenJoinStyle style) { m_linePen.setJoinStyle(style); } Qt::PenJoinStyle JKQTPGraphLineStyleMixin::getLineJoinStyle() const { return m_linePen.joinStyle(); } void JKQTPGraphLineStyleMixin::setLineCapStyle(Qt::PenCapStyle style) { m_linePen.setCapStyle(style); } Qt::PenCapStyle JKQTPGraphLineStyleMixin::getLineCapStyle() const { return m_linePen.capStyle(); } void JKQTPGraphLineStyleMixin::setLineBrush(const QBrush &style) { m_linePen.setBrush(style); } QBrush JKQTPGraphLineStyleMixin::getLineBrush() const { return m_linePen.brush(); } QPen JKQTPGraphLineStyleMixin::getLinePen(JKQTPEnhancedPainter& painter, JKQTBasePlotter* parent) const { QPen p=m_linePen; p.setWidthF(qMax(JKQTPlotterDrawingTools::ABS_MIN_LINEWIDTH,parent->pt2px(painter, parent->getLineWidthMultiplier()*m_lineWidth))); return p; } QPen JKQTPGraphLineStyleMixin::getKeyLinePen(JKQTPEnhancedPainter& painter, const QRectF& rect, JKQTBasePlotter* parent) const { QPen p=m_linePen; p.setWidthF(getKeyLineWidthPx(painter, rect, parent)); return p; } QPen JKQTPGraphLineStyleMixin::getLinePenForRects(JKQTPEnhancedPainter &painter, JKQTBasePlotter *parent) const { QPen p=getLinePen(painter, parent); p.setJoinStyle(Qt::MiterJoin); return p; } JKQTPGraphLinesCompressionMixin::JKQTPGraphLinesCompressionMixin(): m_useNonvisibleLineCompression(false), m_nonvisibleLineCompressionAgressiveness(1) { } JKQTPGraphLinesCompressionMixin::~JKQTPGraphLinesCompressionMixin() { } void JKQTPGraphLinesCompressionMixin::setUseNonvisibleLineCompression(bool _useNonvisibleLineCompression) { m_useNonvisibleLineCompression=_useNonvisibleLineCompression; } bool JKQTPGraphLinesCompressionMixin::getUseNonvisibleLineCompression() const { return m_useNonvisibleLineCompression; } void JKQTPGraphLinesCompressionMixin::setNonvisibleLineCompressionAgressiveness(double Agressiveness) { m_nonvisibleLineCompressionAgressiveness=Agressiveness; } double JKQTPGraphLinesCompressionMixin::getNonvisibleLineCompressionAgressiveness() const { return m_nonvisibleLineCompressionAgressiveness; } JKQTPGraphSymbolStyleMixin::JKQTPGraphSymbolStyleMixin() { m_symbolColor=QColor("red"); m_symbolType=JKQTPGraphSymbols::JKQTPDefaultSymbol; m_symbolSize=12; m_symbolFillColor=m_symbolColor.lighter(); m_symbolLineWidth=1; m_symbolFontName=QGuiApplication::font().family(); } void JKQTPGraphSymbolStyleMixin::initSymbolStyle(JKQTBasePlotter *parent, int& parentPlotStyle, JKQTPPlotStyleType styletype) { if (parent) { // get style settings from parent object if (parentPlotStyle<0) parentPlotStyle=parent->getNextStyle(); const JKQTBasePlotter::JKQTPPen pen=parent->getPlotStyle(parentPlotStyle, styletype); m_symbolColor=pen.color(); m_symbolSize=pen.symbolSize(); m_symbolLineWidth=pen.symbolLineWidthF(); m_symbolType=pen.symbol(); m_symbolFillColor=pen.symbolFillColor(); m_symbolFontName=parent->getDefaultTextFontName(); } } JKQTPGraphSymbolStyleMixin::~JKQTPGraphSymbolStyleMixin() { } void JKQTPGraphSymbolStyleMixin::setSymbolType(JKQTPGraphSymbols __value) { m_symbolType=__value; } JKQTPGraphSymbols JKQTPGraphSymbolStyleMixin::getSymbolType() const { return m_symbolType; } void JKQTPGraphSymbolStyleMixin::setSymbolSize(double __value) { m_symbolSize=__value; } double JKQTPGraphSymbolStyleMixin::getSymbolSize() const { return m_symbolSize; } void JKQTPGraphSymbolStyleMixin::setSymbolColor(const QColor &__value) { m_symbolColor=__value; } void JKQTPGraphSymbolStyleMixin::setSymbolColor(const QColor &__value, double alpha) { m_symbolColor=__value; m_symbolColor.setAlphaF(alpha); } QColor JKQTPGraphSymbolStyleMixin::getSymbolColor() const { return m_symbolColor; } void JKQTPGraphSymbolStyleMixin::setSymbolFillColor(const QColor &__value) { m_symbolFillColor=__value; } void JKQTPGraphSymbolStyleMixin::setSymbolFillColor(const QColor &__value, double alpha) { m_symbolFillColor=__value; m_symbolFillColor.setAlphaF(alpha); } QColor JKQTPGraphSymbolStyleMixin::getSymbolFillColor() const { return m_symbolFillColor; } void JKQTPGraphSymbolStyleMixin::setSymbolAlpha(double alpha) { m_symbolColor.setAlphaF(alpha); m_symbolFillColor.setAlphaF(alpha); } void JKQTPGraphSymbolStyleMixin::setSymbolLineWidth(double __value) { m_symbolLineWidth=__value; } double JKQTPGraphSymbolStyleMixin::getSymbolLineWidth() const { return m_symbolLineWidth; } void JKQTPGraphSymbolStyleMixin::setSymbolFontName(const QString &__value) { m_symbolFontName=__value; } QString JKQTPGraphSymbolStyleMixin::getSymbolFontName() const { return m_symbolFontName; } double JKQTPGraphSymbolStyleMixin::getKeySymbolLineWidthPx(JKQTPEnhancedPainter& painter, const QRectF& keyRect, const JKQTBasePlotter *parent, double maxSymbolSizeFracton) const { const double minSize=qMin(keyRect.width(), keyRect.height()); double symbolWidth=parent->pt2px(painter, this->getSymbolLineWidth()*parent->getLineWidthMultiplier()); double symbolSize=getKeySymbolSizePx(painter, keyRect, parent, maxSymbolSizeFracton); if (symbolWidth>0.3*symbolSize) symbolWidth=0.3*symbolSize; return symbolWidth; } double JKQTPGraphSymbolStyleMixin::getKeySymbolSizePx(JKQTPEnhancedPainter& painter, const QRectF& keyRect, const JKQTBasePlotter *parent, double maxSymbolSizeFracton) const { const double minSize=qMin(keyRect.width(), keyRect.height()); double symbolSize=parent->pt2px(painter, this->getSymbolSize()); if (symbolSize>minSize*maxSymbolSizeFracton) symbolSize=minSize*maxSymbolSizeFracton; return symbolSize; } QPen JKQTPGraphSymbolStyleMixin::getSymbolPen(JKQTPEnhancedPainter& painter, JKQTBasePlotter* parent) const { QPen p; p.setColor(m_symbolColor); p.setWidthF(qMax(JKQTPlotterDrawingTools::ABS_MIN_LINEWIDTH,parent->pt2px(painter, parent->getLineWidthMultiplier()*m_symbolLineWidth))); p.setStyle(Qt::SolidLine); p.setJoinStyle(Qt::RoundJoin); p.setCapStyle(Qt::RoundCap); return p; } QBrush JKQTPGraphSymbolStyleMixin::getSymbolBrush(JKQTPEnhancedPainter& /*painter*/, JKQTBasePlotter* /*parent*/) const { QBrush b; b.setColor(m_symbolFillColor); return b; } QFont JKQTPGraphSymbolStyleMixin::getSymbolFont() const { QFont f(m_symbolFontName, m_symbolSize); f.setStyleStrategy(QFont::PreferDefault); return f; } JKQTPGraphFillStyleMixin::JKQTPGraphFillStyleMixin() { m_fillColor=QColor("red").lighter(); m_fillBrush.setColor(m_fillColor); m_fillBrush.setStyle(Qt::SolidPattern); } void JKQTPGraphFillStyleMixin::initFillStyleInvertedColor(JKQTPGraphFillStyleMixin *other) { if (other) { // get style settings from parent object m_fillColor=other->getFillColor(); #if QT_VERSION >= QT_VERSION_CHECK(6,0,0) float h=0,s=0,v=0,a=0; #else qreal h=0,s=0,v=0,a=0; #endif m_fillColor.getHsvF(&h, &s, &v, &a); h=std::fmod(h+120.0/360.0, 1.0); m_fillColor.setHsvF(h,s,v,a); m_fillBrush.setColor(m_fillColor); m_fillBrush.setStyle(other->getFillStyle()); } } void JKQTPGraphFillStyleMixin::initFillStyle(JKQTBasePlotter *parent, int &parentPlotStyle, JKQTPPlotStyleType styletype) { if (parent) { // get style settings from parent object if (parentPlotStyle<0) parentPlotStyle=parent->getNextStyle(); const JKQTBasePlotter::JKQTPPen pen=parent->getPlotStyle(parentPlotStyle, styletype); m_fillColor=pen.fillColor(); m_fillBrush.setColor(m_fillColor); m_fillBrush.setStyle(pen.fillStyle()); } } JKQTPGraphFillStyleMixin::~JKQTPGraphFillStyleMixin() { } void JKQTPGraphFillStyleMixin::setFillStyle(Qt::BrushStyle __value) { if (m_fillBrush.style()==Qt::LinearGradientPattern || m_fillBrush.style()==Qt::RadialGradientPattern || m_fillBrush.style()==Qt::ConicalGradientPattern || m_fillBrush.style()==Qt::TexturePattern) { m_fillBrush=QBrush(m_fillColor, __value); } else { m_fillBrush.setStyle(__value); } } Qt::BrushStyle JKQTPGraphFillStyleMixin::getFillStyle() const { return m_fillBrush.style(); } void JKQTPGraphFillStyleMixin::setFillColor(const QColor &__value) { m_fillColor=__value; m_fillBrush.setColor(m_fillColor); } void JKQTPGraphFillStyleMixin::setFillColor(const QColor &__value, double alpha) { m_fillColor=__value; m_fillColor.setAlphaF(alpha); m_fillBrush.setColor(m_fillColor); } QColor JKQTPGraphFillStyleMixin::getFillColor() const { return m_fillBrush.color(); } void JKQTPGraphFillStyleMixin::setFillTexture(const QPixmap &__value) { m_fillBrush.setStyle(Qt::TexturePattern); m_fillBrush.setTexture(__value); } void JKQTPGraphFillStyleMixin::setFillTexture(const QImage &__value) { m_fillBrush.setStyle(Qt::TexturePattern); m_fillBrush.setTextureImage(__value); } QPixmap JKQTPGraphFillStyleMixin::getFillTexture() const { return m_fillBrush.texture(); } QImage JKQTPGraphFillStyleMixin::getFillTextureImage() const { return m_fillBrush.textureImage(); } void JKQTPGraphFillStyleMixin::setFillGradient(const QGradient &__value) { m_fillBrush=QBrush(__value); } const QGradient *JKQTPGraphFillStyleMixin::getFillGradient() const { return m_fillBrush.gradient(); } void JKQTPGraphFillStyleMixin::setFillBrush(const QBrush &b) { m_fillBrush=b; m_fillColor=b.color(); } void JKQTPGraphFillStyleMixin::setFillTransform(const QTransform &b) { m_fillBrush.setTransform(b); } QBrush JKQTPGraphFillStyleMixin::getFillBrush(JKQTPEnhancedPainter &/*painter*/, JKQTBasePlotter * /*parent*/) const { return m_fillBrush; } void JKQTPGraphLineStyleMixin::setHighlightingLineColor(const QColor &__value) { m_highlightingLineColor=__value; } void JKQTPGraphLineStyleMixin::setHighlightingLineColor(const QColor &__value, double alpha) { m_highlightingLineColor=__value; m_highlightingLineColor.setAlphaF(alpha); } QColor JKQTPGraphLineStyleMixin::getHighlightingLineColor() const { return m_highlightingLineColor; } double JKQTPGraphLineStyleMixin::getKeyLineWidthPx(JKQTPEnhancedPainter &painter, const QRectF &keyRect, const JKQTBasePlotter *parent) const { const double minSize=qMin(keyRect.width(), keyRect.height()); double lineWidth=parent->pt2px(painter, this->getLineWidth()*parent->getLineWidthMultiplier()); if (lineWidth>0.4*minSize) lineWidth=0.4*minSize; return lineWidth; } QPen JKQTPGraphLineStyleMixin::getHighlightingLinePen(JKQTPEnhancedPainter &painter, JKQTBasePlotter *parent) const { QPen p=getLinePen(painter, parent); p.setColor(m_highlightingLineColor); p.setWidthF(p.widthF()*3.0); return p; } QPen JKQTPGraphLineStyleMixin::getHighlightingLinePenForRects(JKQTPEnhancedPainter &painter, JKQTBasePlotter *parent) const { QPen p=getHighlightingLinePen(painter, parent); p.setJoinStyle(Qt::MiterJoin); return p; } JKQTPGraphTextStyleMixin::JKQTPGraphTextStyleMixin(JKQTBasePlotter *parent) { m_textFontSize=parent->getCurrentPlotterStyle().graphsStyle.annotationStyle.defaultFontSize; m_textColor=parent->getCurrentPlotterStyle().graphsStyle.annotationStyle.defaultTextColor; m_textFontName=parent->getCurrentPlotterStyle().graphsStyle.annotationStyle.defaultFontName; } void JKQTPGraphTextStyleMixin::initTextStyle(JKQTBasePlotter *parent, int &/*parentPlotStyle*/, JKQTPPlotStyleType styletype) { if (parent && styletype==JKQTPPlotStyleType::Annotation) { // get style settings from parent object m_textFontSize=parent->getCurrentPlotterStyle().graphsStyle.annotationStyle.defaultFontSize; m_textColor=parent->getCurrentPlotterStyle().graphsStyle.annotationStyle.defaultTextColor; m_textFontName=parent->getCurrentPlotterStyle().graphsStyle.annotationStyle.defaultFontName; } } JKQTPGraphTextStyleMixin::~JKQTPGraphTextStyleMixin() { } void JKQTPGraphTextStyleMixin::setTextFontSize(double __value) { m_textFontSize=__value; } double JKQTPGraphTextStyleMixin::getTextFontSize() const { return m_textFontSize; } void JKQTPGraphTextStyleMixin::setTextFontName(const QString &__value) { m_textFontName=__value; } QString JKQTPGraphTextStyleMixin::getTextFontName() const { return m_textFontName; } void JKQTPGraphTextStyleMixin::setTextColor(const QColor &__value) { m_textColor=__value; } void JKQTPGraphTextStyleMixin::setTextColor(const QColor &__value, double alpha) { m_textColor=__value; m_textColor.setAlphaF(alpha); } QColor JKQTPGraphTextStyleMixin::getTextColor() const { return m_textColor; } JKQTPGraphDecoratedLineStyleMixin::JKQTPGraphDecoratedLineStyleMixin(): JKQTPGraphLineStyleMixin() { m_headDecoratorStyle=JKQTPLineDecoratorStyle::JKQTPDefaultLineDecorator; m_tailDecoratorStyle=JKQTPLineDecoratorStyle::JKQTPNoDecorator; m_tailDecoratorSizeFactor=m_headDecoratorSizeFactor=8.0; } void JKQTPGraphDecoratedLineStyleMixin::initDecoratedLineStyle(JKQTBasePlotter *parent, int &parentPlotStyle, JKQTPPlotStyleType styletype) { initLineStyle(parent, parentPlotStyle, styletype); if (parent) { // get style settings from parent object m_headDecoratorStyle=parent->getCurrentPlotterStyle().graphsStyle.getGraphStyleByType(styletype).defaultHeadDecoratorStyle; m_headDecoratorSizeFactor=m_tailDecoratorSizeFactor=parent->getCurrentPlotterStyle().graphsStyle.getGraphStyleByType(styletype).defaultHeadDecoratorSizeFactor; } } JKQTPGraphDecoratedLineStyleMixin::~JKQTPGraphDecoratedLineStyleMixin() { } void JKQTPGraphDecoratedLineStyleMixin::setHeadDecoratorStyle(const JKQTPLineDecoratorStyle &__value) { m_headDecoratorStyle=__value; } JKQTPLineDecoratorStyle JKQTPGraphDecoratedLineStyleMixin::getHeadDecoratorStyle() const { return m_headDecoratorStyle; } void JKQTPGraphDecoratedLineStyleMixin::setTailDecoratorStyle(const JKQTPLineDecoratorStyle &__value) { m_tailDecoratorStyle=__value; } JKQTPLineDecoratorStyle JKQTPGraphDecoratedLineStyleMixin::getTailDecoratorStyle() const { return m_tailDecoratorStyle; } void JKQTPGraphDecoratedLineStyleMixin::setHeadDecoratorSizeFactor(const double &__value) { m_headDecoratorSizeFactor=__value; } double JKQTPGraphDecoratedLineStyleMixin::getHeadDecoratorSizeFactor() const { return m_headDecoratorSizeFactor; } void JKQTPGraphDecoratedLineStyleMixin::setTailDecoratorSizeFactor(const double &__value) { m_tailDecoratorSizeFactor=__value; } double JKQTPGraphDecoratedLineStyleMixin::getTailDecoratorSizeFactor() const { return m_tailDecoratorSizeFactor; } double JKQTPGraphDecoratedLineStyleMixin::calcTailDecoratorSize(double line_width) const { return JKQTPLineDecoratorStyleCalcDecoratorSize(line_width, m_tailDecoratorSizeFactor); } double JKQTPGraphDecoratedLineStyleMixin::calcHeadDecoratorSize(double line_width) const { return JKQTPLineDecoratorStyleCalcDecoratorSize(line_width, m_headDecoratorSizeFactor); } JKQTPGraphDecoratedHeadLineStyleMixin::JKQTPGraphDecoratedHeadLineStyleMixin(): JKQTPGraphLineStyleMixin() { m_headDecoratorStyle=JKQTPLineDecoratorStyle::JKQTPDefaultLineDecorator; m_headDecoratorSizeFactor=8.0; } void JKQTPGraphDecoratedHeadLineStyleMixin::initDecoratedHeadLineStyle(JKQTBasePlotter *parent, int &parentPlotStyle, JKQTPPlotStyleType styletype) { initLineStyle(parent, parentPlotStyle, styletype); if (parent) { // get style settings from parent object m_headDecoratorStyle=parent->getCurrentPlotterStyle().graphsStyle.getGraphStyleByType(styletype).defaultHeadDecoratorStyle; m_headDecoratorSizeFactor=parent->getCurrentPlotterStyle().graphsStyle.getGraphStyleByType(styletype).defaultHeadDecoratorSizeFactor; } } JKQTPGraphDecoratedHeadLineStyleMixin::~JKQTPGraphDecoratedHeadLineStyleMixin() { } void JKQTPGraphDecoratedHeadLineStyleMixin::setHeadDecoratorStyle(const JKQTPLineDecoratorStyle &__value) { m_headDecoratorStyle=__value; } JKQTPLineDecoratorStyle JKQTPGraphDecoratedHeadLineStyleMixin::getHeadDecoratorStyle() const { return m_headDecoratorStyle; } void JKQTPGraphDecoratedHeadLineStyleMixin::setHeadDecoratorSizeFactor(const double &__value) { m_headDecoratorSizeFactor=__value; } double JKQTPGraphDecoratedHeadLineStyleMixin::getHeadDecoratorSizeFactor() const { return m_headDecoratorSizeFactor; } double JKQTPGraphDecoratedHeadLineStyleMixin::calcHeadDecoratorSize(double line_width) const { return JKQTPLineDecoratorStyleCalcDecoratorSize(line_width, m_headDecoratorSizeFactor); } JKQTPGraphLineAndFillStyleMixin::JKQTPGraphLineAndFillStyleMixin(): m_drawLine(true), m_fillCurve(true) { } void JKQTPGraphLineAndFillStyleMixin::setDrawLine(bool __value) { m_drawLine=__value; } bool JKQTPGraphLineAndFillStyleMixin::getDrawLine() const { return m_drawLine; } bool JKQTPGraphLineAndFillStyleMixin::doDrawLine() const { return m_drawLine; } void JKQTPGraphLineAndFillStyleMixin::setFillCurve(bool __value) { m_fillCurve=__value; } bool JKQTPGraphLineAndFillStyleMixin::getFillCurve() const { return m_fillCurve; } bool JKQTPGraphLineAndFillStyleMixin::doFillCurve() const { return m_fillCurve; }
lgpl-2.1
gabeharms/firestorm
indra/llui/lldockablefloater.cpp
1
5907
/** * @file lldockablefloater.cpp * @brief Creates a panel of a specific kind for a toast * * $LicenseInfo:firstyear=2000&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "lldockablefloater.h" #include "llfloaterreg.h" //static LLHandle<LLFloater> LLDockableFloater::sInstanceHandle; //static void LLDockableFloater::init(LLDockableFloater* thiz) { thiz->setDocked(thiz->mDockControl.get() != NULL && thiz->mDockControl.get()->isDockVisible()); thiz->resetInstance(); // all dockable floaters should have close, dock and minimize buttons thiz->setCanClose(TRUE); thiz->setCanDock(true); thiz->setCanMinimize(TRUE); thiz->setOverlapsScreenChannel(false); thiz->mForceDocking = false; } LLDockableFloater::LLDockableFloater(LLDockControl* dockControl, const LLSD& key, const Params& params) : LLFloater(key, params), mDockControl(dockControl), mUniqueDocking(true) { init(this); mUseTongue = true; } LLDockableFloater::LLDockableFloater(LLDockControl* dockControl, bool uniqueDocking, const LLSD& key, const Params& params) : LLFloater(key, params), mDockControl(dockControl), mUniqueDocking(uniqueDocking) { init(this); mUseTongue = true; } LLDockableFloater::LLDockableFloater(LLDockControl* dockControl, bool uniqueDocking, bool useTongue, const LLSD& key, const Params& params) : LLFloater(key, params), mDockControl(dockControl), mUseTongue(useTongue), mUniqueDocking(uniqueDocking) { init(this); } LLDockableFloater::~LLDockableFloater() { } BOOL LLDockableFloater::postBuild() { // Remember we should force docking when the floater is opened for the first time if (mIsDockedStateForcedCallback != NULL && mIsDockedStateForcedCallback()) { mForceDocking = true; } mDockTongue = LLUI::getUIImage("Flyout_Pointer"); LLFloater::setDocked(true); return LLView::postBuild(); } //static void LLDockableFloater::toggleInstance(const LLSD& sdname) { LLSD key; std::string name = sdname.asString(); LLDockableFloater* instance = dynamic_cast<LLDockableFloater*> (LLFloaterReg::findInstance(name)); // if floater closed or docked if (instance == NULL || (instance && instance->isDocked())) { LLFloaterReg::toggleInstance(name, key); // restore button toggle state if (instance != NULL) { instance->storeVisibilityControl(); } } // if floater undocked else if (instance != NULL) { instance->setMinimized(FALSE); if (instance->getVisible()) { instance->setVisible(FALSE); } else { instance->setVisible(TRUE); gFloaterView->bringToFront(instance); } } } void LLDockableFloater::resetInstance() { if (mUniqueDocking && sInstanceHandle.get() != this) { if (sInstanceHandle.get() != NULL && sInstanceHandle.get()->isDocked()) { sInstanceHandle.get()->setVisible(FALSE); } sInstanceHandle = getHandle(); } } void LLDockableFloater::setVisible(BOOL visible) { // Force docking if requested if (visible && mForceDocking) { setCanDock(true); setDocked(true); mForceDocking = false; } if(visible && isDocked()) { resetInstance(); } if (visible && mDockControl.get() != NULL) { mDockControl.get()->repositionDockable(); } if (visible) { LLFloater::setFrontmost(getAutoFocus()); } LLFloater::setVisible(visible); } void LLDockableFloater::setMinimized(BOOL minimize) { if(minimize && isDocked()) { // minimizing a docked floater just hides it setVisible(FALSE); } else { LLFloater::setMinimized(minimize); } } LLView * LLDockableFloater::getDockWidget() { LLView * res = NULL; if (getDockControl() != NULL) { res = getDockControl()->getDock(); } return res; } void LLDockableFloater::onDockHidden() { setCanDock(FALSE); } void LLDockableFloater::onDockShown() { if (!isMinimized()) { setCanDock(TRUE); } } void LLDockableFloater::setDocked(bool docked, bool pop_on_undock) { if (mDockControl.get() != NULL && mDockControl.get()->isDockVisible()) { if (docked) { resetInstance(); mDockControl.get()->on(); } else { mDockControl.get()->off(); } if (!docked && pop_on_undock) { // visually pop up a little bit to emphasize the undocking translate(0, UNDOCK_LEAP_HEIGHT); } } LLFloater::setDocked(docked, pop_on_undock); } void LLDockableFloater::draw() { if (mDockControl.get() != NULL) { mDockControl.get()->repositionDockable(); if (isDocked()) { mDockControl.get()->drawToungue(); } } LLFloater::draw(); } void LLDockableFloater::setDockControl(LLDockControl* dockControl) { mDockControl.reset(dockControl); setDocked(isDocked()); } const LLUIImagePtr& LLDockableFloater::getDockTongue(LLDockControl::DocAt dock_side) { switch(dock_side) { case LLDockControl::LEFT: mDockTongue = LLUI::getUIImage("Flyout_Left"); break; case LLDockControl::RIGHT: mDockTongue = LLUI::getUIImage("Flyout_Right"); break; default: mDockTongue = LLUI::getUIImage("Flyout_Pointer"); break; } return mDockTongue; } LLDockControl* LLDockableFloater::getDockControl() { return mDockControl.get(); }
lgpl-2.1
ShiftMediaProject/libbluray
src/libbluray/bdj/bdj.c
1
37265
/* * This file is part of libbluray * Copyright (C) 2010 William Hahne * Copyright (C) 2012-2019 Petri Hintukainen <phintuka@users.sourceforge.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details.s * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ #if HAVE_CONFIG_H #include "config.h" #endif #include "bdj.h" #include "native/register_native.h" #include "file/file.h" #include "file/dirs.h" #include "file/dl.h" #include "util/strutl.h" #include "util/macro.h" #include "util/logging.h" #include <jni.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __APPLE__ #include <sys/types.h> #include <sys/wait.h> #include <limits.h> #include <unistd.h> #endif #ifdef _WIN32 #include <windows.h> #include <winreg.h> #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP) #define getenv(x) NULL #endif #endif #ifdef HAVE_BDJ_J2ME #define BDJ_JARFILE "libbluray-j2me-" VERSION ".jar" #else #define BDJ_JARFILE "libbluray-j2se-" VERSION ".jar" #endif struct bdjava_s { #if defined(__APPLE__) && !defined(HAVE_BDJ_J2ME) void *h_libjli; #endif void *h_libjvm; JavaVM *jvm; }; typedef jint (JNICALL * fptr_JNI_CreateJavaVM) (JavaVM **pvm, void **penv,void *args); typedef jint (JNICALL * fptr_JNI_GetCreatedJavaVMs) (JavaVM **vmBuf, jsize bufLen, jsize *nVMs); #if defined(_WIN32) && !defined(HAVE_BDJ_J2ME) static void *_load_dll(const wchar_t *lib_path, const wchar_t *dll_search_path) { #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP) return NULL; #else void *result; typedef PVOID(WINAPI *AddDllDirectoryF) (PCWSTR); typedef BOOL(WINAPI *RemoveDllDirectoryF)(PVOID); AddDllDirectoryF pAddDllDirectory; RemoveDllDirectoryF pRemoveDllDirectory; pAddDllDirectory = (AddDllDirectoryF)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "AddDllDirectory"); pRemoveDllDirectory = (RemoveDllDirectoryF)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "RemoveDllDirectory"); if (pAddDllDirectory && pRemoveDllDirectory) { result = LoadLibraryExW(lib_path, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); if (!result) { PVOID cookie = pAddDllDirectory(dll_search_path); result = LoadLibraryExW(lib_path, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_USER_DIRS); pRemoveDllDirectory(cookie); } } else { result = LoadLibraryW(lib_path); if (!result) { SetDllDirectoryW(dll_search_path); result = LoadLibraryW(lib_path); SetDllDirectoryW(L""); } } return result; #endif } #endif #if defined(_WIN32) && !defined(HAVE_BDJ_J2ME) static void *_load_jvm_win32(const char **p_java_home) { #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP) return NULL; #else static char java_home[256] = ""; wchar_t buf_loc[4096] = L"SOFTWARE\\JavaSoft\\Java Runtime Environment\\"; wchar_t buf_vers[128]; wchar_t java_path[4096] = L""; char strbuf[256]; LONG r; DWORD lType; DWORD dSize = sizeof(buf_vers); HKEY hkey; r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buf_loc, 0, KEY_READ, &hkey); # ifndef NO_JAVA9_SUPPORT if (r != ERROR_SUCCESS) { /* Try Java 9 */ wcscpy(buf_loc, L"SOFTWARE\\JavaSoft\\JRE\\"); r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buf_loc, 0, KEY_READ, &hkey); } if (r != ERROR_SUCCESS) { wcscpy(buf_loc, L"SOFTWARE\\JavaSoft\\JDK\\"); r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buf_loc, 0, KEY_READ, &hkey); } # endif if (r != ERROR_SUCCESS) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Error opening registry key SOFTWARE\\JavaSoft\\Java Runtime Environment\\\n"); return NULL; } r = RegQueryValueExW(hkey, L"CurrentVersion", NULL, &lType, (LPBYTE)buf_vers, &dSize); RegCloseKey(hkey); if (r != ERROR_SUCCESS) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "CurrentVersion registry value not found\n"); return NULL; } if (debug_mask & DBG_BDJ) { if (!WideCharToMultiByte(CP_UTF8, 0, buf_vers, -1, strbuf, sizeof(strbuf), NULL, NULL)) { strbuf[0] = 0; } BD_DEBUG(DBG_BDJ, "JRE version: %s\n", strbuf); } wcscat(buf_loc, buf_vers); dSize = sizeof(buf_loc); r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buf_loc, 0, KEY_READ, &hkey); if (r != ERROR_SUCCESS) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Error opening JRE version-specific registry key\n"); return NULL; } r = RegQueryValueExW(hkey, L"JavaHome", NULL, &lType, (LPBYTE)buf_loc, &dSize); if (r == ERROR_SUCCESS) { /* do not fail even if not found */ if (WideCharToMultiByte(CP_UTF8, 0, buf_loc, -1, java_home, sizeof(java_home), NULL, NULL)) { *p_java_home = java_home; } BD_DEBUG(DBG_BDJ, "JavaHome: %s\n", java_home); wcscat(java_path, buf_loc); wcscat(java_path, L"\\bin"); } dSize = sizeof(buf_loc); r = RegQueryValueExW(hkey, L"RuntimeLib", NULL, &lType, (LPBYTE)buf_loc, &dSize); RegCloseKey(hkey); if (r != ERROR_SUCCESS) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "RuntimeLib registry value not found\n"); return NULL; } void *result = _load_dll(buf_loc, java_path); if (!WideCharToMultiByte(CP_UTF8, 0, buf_loc, -1, strbuf, sizeof(strbuf), NULL, NULL)) { strbuf[0] = 0; } if (!result) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "can't open library '%s'\n", strbuf); } else { BD_DEBUG(DBG_BDJ, "Using JRE library %s\n", strbuf); } return result; #endif } #endif #ifdef _WIN32 static inline char *_utf8_to_cp(const char *utf8) { int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0); if (wlen <= 0) { return NULL; } wchar_t *wide = (wchar_t *)malloc(wlen * sizeof(wchar_t)); if (!wide) { return NULL; } if (!MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wide, wlen)) { X_FREE(wide); return NULL; } size_t len = WideCharToMultiByte(CP_ACP, 0, wide, -1, NULL, 0, NULL, NULL); if (len <= 0) { X_FREE(wide); return NULL; } char *out = (char *)malloc(len); if (out != NULL) { if (!WideCharToMultiByte(CP_ACP, 0, wide, -1, out, len, NULL, NULL)) { X_FREE(out); } } X_FREE(wide); return out; } #endif #ifdef __APPLE__ // The current official JRE is installed by Oracle's Java Applet internet plugin: #define MACOS_JRE_HOME "/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home" static const char *jre_plugin_path = MACOS_JRE_HOME; #endif #if defined(__APPLE__) && !defined(HAVE_BDJ_J2ME) #define MACOS_JAVA_HOME "/usr/libexec/java_home" static char *_java_home_macos() { static char result[PATH_MAX] = ""; if (result[0]) return result; pid_t java_home_pid; int fd[2], exitcode; if (pipe(fd)) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "unable to set up pipes\n"); return NULL; } switch (java_home_pid = vfork()) { case -1: BD_DEBUG(DBG_BDJ | DBG_CRIT, "vfork failed\n"); return NULL; case 0: if (dup2(fd[1], STDOUT_FILENO) == -1) { _exit(-1); } close(fd[1]); close(fd[0]); execl(MACOS_JAVA_HOME, MACOS_JAVA_HOME); _exit(-1); default: close(fd[1]); for (int len = 0; ;) { int n = read(fd[0], result + len, sizeof result - len); if (n <= 0) break; len += n; result[len-1] = '\0'; } waitpid(java_home_pid, &exitcode, 0); } if (result[0] == '\0' || exitcode) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Unable to read path from " MACOS_JAVA_HOME "\n"); result[0] = '\0'; return NULL; } BD_DEBUG(DBG_BDJ, "macos java home: '%s'\n", result ); return result; } #undef MACOS_JAVA_HOME #endif static void *_jvm_dlopen(const char *java_home, const char *jvm_dir, const char *jvm_lib) { char *path = str_printf("%s" DIR_SEP "%s" DIR_SEP "%s", java_home, jvm_dir, jvm_lib); if (!path) { BD_DEBUG(DBG_CRIT, "out of memory\n"); return NULL; } BD_DEBUG(DBG_BDJ, "Opening %s ...\n", path); void *h = dl_dlopen(path, NULL); # ifdef NO_JAVA9_SUPPORT /* ignore Java 9+ */ if (h && dl_dlsym(h, "JVM_DefineModule")) { BD_DEBUG(DBG_CRIT | DBG_BDJ, "Ignoring JVM %s: looks like Java 9 or later\n", path); dl_dlclose(h); h = NULL; } # endif X_FREE(path); return h; } static void *_jvm_dlopen_a(const char *java_home, const char * const *jvm_dir, unsigned num_jvm_dir, const char *jvm_lib) { unsigned ii; void *dll = NULL; if (!java_home) { BD_DEBUG(DBG_BDJ, "Opening %s ...\n", jvm_lib); return dl_dlopen(jvm_lib, NULL); } for (ii = 0; !dll && ii < num_jvm_dir; ii++) { dll = _jvm_dlopen(java_home, jvm_dir[ii], jvm_lib); } return dll; } #if defined(__APPLE__) && !defined(HAVE_BDJ_J2ME) static void *_load_jli_macos() { const char *java_home = NULL; static const char * const jli_dir[] = { "jre/lib/jli", "lib/jli", }; const unsigned num_jli_dir = sizeof(jli_dir) / sizeof(jli_dir[0]); static const char jli_lib[] = "libjli"; void *handle; /* JAVA_HOME set, use it */ java_home = getenv("JAVA_HOME"); if (java_home) { return _jvm_dlopen_a(java_home, jli_dir, num_jli_dir, jli_lib); } java_home = _java_home_macos(); if (java_home) { handle = _jvm_dlopen_a(java_home, jli_dir, num_jli_dir, jli_lib); if (handle) { return handle; } } // check if the JRE is installed: return _jvm_dlopen(jre_plugin_path, "lib/jli", jli_lib); } #endif static void *_load_jvm(const char **p_java_home, const char *app_java_home) { #ifdef HAVE_BDJ_J2ME # ifdef _WIN32 static const char * const jvm_path[] = {NULL, JDK_HOME}; static const char * const jvm_dir[] = {"bin"}; static const char jvm_lib[] = "cvmi"; # else static const char * const jvm_path[] = {NULL, JDK_HOME, "/opt/PhoneME"}; static const char * const jvm_dir[] = {"bin"}; static const char jvm_lib[] = "libcvm"; # endif #else /* HAVE_BDJ_J2ME */ # ifdef _WIN32 static const char * const jvm_path[] = {NULL, JDK_HOME}; static const char * const jvm_dir[] = {"jre\\bin\\server", "bin\\server", "jre\\bin\\client", "bin\\client", }; static const char jvm_lib[] = "jvm"; # else # ifdef __APPLE__ static const char * const jvm_path[] = {NULL, JDK_HOME, MACOS_JRE_HOME}; static const char * const jvm_dir[] = {"jre/lib/server", "lib/server"}; # else static const char * const jvm_path[] = {NULL, JDK_HOME, # ifdef __FreeBSD__ "/usr/local/openjdk8", "/usr/local/openjdk11", "/usr/local/openjdk17", # elif defined(__OpenBSD__) "/usr/local/jdk-1.8.0", "/usr/local/jdk-11", "/usr/local/jdk-17", # else "/usr/lib/jvm/default-java", "/usr/lib/jvm/default", "/usr/lib/jvm/", "/etc/java-config-2/current-system-vm", "/usr/lib/jvm/java-8-openjdk", "/usr/lib/jvm/java-8-openjdk-" JAVA_ARCH, "/usr/lib/jvm/java-11-openjdk", "/usr/lib/jvm/java-11-openjdk-" JAVA_ARCH, "/usr/lib/jvm/java-17-openjdk", "/usr/lib/jvm/java-17-openjdk-" JAVA_ARCH, # endif }; static const char * const jvm_dir[] = {"jre/lib/" JAVA_ARCH "/server", "lib/" JAVA_ARCH "/server", "lib/server", "jre/lib/" JAVA_ARCH "/client", "lib/" JAVA_ARCH "/client", "lib/client", }; # endif static const char jvm_lib[] = "libjvm"; # endif #endif const unsigned num_jvm_dir = sizeof(jvm_dir) / sizeof(jvm_dir[0]); const unsigned num_jvm_path = sizeof(jvm_path) / sizeof(jvm_path[0]); const char *java_home = NULL; unsigned path_ind; void *handle = NULL; /* Application provided JAVA_HOME overrides everything else */ if (app_java_home) { BD_DEBUG(DBG_BDJ, "Using application-provided JAVA_HOME '%s'\n", app_java_home); *p_java_home = app_java_home; return _jvm_dlopen_a(app_java_home, jvm_dir, num_jvm_dir, jvm_lib); } /* JAVA_HOME set, use it */ java_home = getenv("JAVA_HOME"); if (java_home) { BD_DEBUG(DBG_BDJ, "Using JAVA_HOME '%s'\n", java_home); *p_java_home = java_home; return _jvm_dlopen_a(java_home, jvm_dir, num_jvm_dir, jvm_lib); } #if defined(_WIN32) && !defined(HAVE_BDJ_J2ME) /* Try Windows registry */ handle = _load_jvm_win32(p_java_home); if (handle) { return handle; } #endif #if defined(__APPLE__) && !defined(HAVE_BDJ_J2ME) java_home = _java_home_macos(); if (java_home) { handle = _jvm_dlopen_a(java_home, jvm_dir, num_jvm_dir, jvm_lib); if (handle) { *p_java_home = java_home; return handle; } } // check if the JRE is installed: handle = _jvm_dlopen(jre_plugin_path, "lib/server", jvm_lib); if (handle) { *p_java_home = jre_plugin_path; return handle; } #endif BD_DEBUG(DBG_BDJ, "JAVA_HOME not set, trying default locations\n"); /* try our pre-defined locations */ for (path_ind = 0; !handle && path_ind < num_jvm_path; path_ind++) { if (jvm_path[path_ind] && !jvm_path[path_ind][0]) { /* skip empty JVM_HOME */ } else if (jvm_path[path_ind] && file_path_exists(jvm_path[path_ind]) < 0) { BD_DEBUG(DBG_BDJ, "Skipping %s (not found)\n", jvm_path[path_ind]); } else { *p_java_home = jvm_path[path_ind]; handle = _jvm_dlopen_a(jvm_path[path_ind], jvm_dir, num_jvm_dir, jvm_lib); } } if (!*p_java_home) { *p_java_home = dl_get_path(); } return handle; } static int _can_read_file(const char *fn) { BD_FILE_H *fp; if (!fn) { return 0; } fp = file_open(fn, "rb"); if (fp) { uint8_t b; int result = (int)file_read(fp, &b, 1); file_close(fp); if (result == 1) { return 1; } BD_DEBUG(DBG_BDJ | DBG_CRIT, "Error reading %s\n", fn); } return 0; } void bdj_config_cleanup(BDJ_CONFIG *p) { X_FREE(p->cache_root); X_FREE(p->persistent_root); X_FREE(p->java_home); X_FREE(p->classpath[0]); X_FREE(p->classpath[1]); } static char *_find_libbluray_jar0() { // pre-defined search paths for libbluray.jar static const char * const jar_paths[] = { #ifndef _WIN32 # if defined(__FreeBSD__) || defined(__OpenBSD__) "/usr/local/share/java/" BDJ_JARFILE, # else "/usr/share/java/" BDJ_JARFILE, "/usr/share/libbluray/lib/" BDJ_JARFILE, # endif #endif BDJ_JARFILE, }; unsigned i; // check if overriding the classpath const char *classpath = getenv("LIBBLURAY_CP"); if (classpath) { size_t cp_len = strlen(classpath); char *jar; // directory or file ? if (cp_len > 0 && (classpath[cp_len - 1] == '/' || classpath[cp_len - 1] == '\\')) { jar = str_printf("%s%s", classpath, BDJ_JARFILE); } else { jar = str_dup(classpath); } if (!jar) { BD_DEBUG(DBG_CRIT, "out of memory\n"); return NULL; } if (_can_read_file(jar)) { return jar; } X_FREE(jar); BD_DEBUG(DBG_BDJ | DBG_CRIT, "invalid LIBBLURAY_CP %s\n", classpath); return NULL; } BD_DEBUG(DBG_BDJ, "LIBBLURAY_CP not set, searching for "BDJ_JARFILE" ...\n"); // check directory where libbluray.so was loaded from const char *lib_path = dl_get_path(); if (lib_path) { char *cp = str_printf("%s" BDJ_JARFILE, lib_path); if (!cp) { BD_DEBUG(DBG_CRIT, "out of memory\n"); return NULL; } BD_DEBUG(DBG_BDJ, "Checking %s ...\n", cp); if (_can_read_file(cp)) { BD_DEBUG(DBG_BDJ, "using %s\n", cp); return cp; } X_FREE(cp); } // check pre-defined directories for (i = 0; i < sizeof(jar_paths) / sizeof(jar_paths[0]); i++) { BD_DEBUG(DBG_BDJ, "Checking %s ...\n", jar_paths[i]); if (_can_read_file(jar_paths[i])) { BD_DEBUG(DBG_BDJ, "using %s\n", jar_paths[i]); return str_dup(jar_paths[i]); } } BD_DEBUG(DBG_BDJ | DBG_CRIT, BDJ_JARFILE" not found.\n"); return NULL; } static char *_find_libbluray_jar1(const char *jar0) { char *jar1; int cut; cut = (int)strlen(jar0) - (int)strlen(VERSION) - 9; if (cut <= 0) return NULL; jar1 = str_printf("%.*sawt-%s", cut, jar0, jar0 + cut); if (!jar1) return NULL; if (!_can_read_file(jar1)) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Cant access AWT jar file %s\n", jar1); X_FREE(jar1); } return jar1; } static int _find_libbluray_jar(BDJ_CONFIG *storage) { if (!storage->classpath[0]) { storage->classpath[0] = _find_libbluray_jar0(); X_FREE(storage->classpath[1]); if (!storage->classpath[0]) return 0; } if (!storage->classpath[1]) { storage->classpath[1] = _find_libbluray_jar1(storage->classpath[0]); if (!storage->classpath[1]) { X_FREE(storage->classpath[0]); X_FREE(storage->classpath[1]); } } return !!storage->classpath[0]; } static const char *_bdj_persistent_root(BDJ_CONFIG *storage) { const char *root; char *data_home; if (storage->no_persistent_storage) { return NULL; } if (!storage->persistent_root) { root = getenv("LIBBLURAY_PERSISTENT_ROOT"); if (root) { return root; } data_home = file_get_data_home(); if (data_home) { storage->persistent_root = str_printf("%s" DIR_SEP "bluray" DIR_SEP "dvb.persistent.root" DIR_SEP, data_home); X_FREE(data_home); BD_DEBUG(DBG_BDJ, "LIBBLURAY_PERSISTENT_ROOT not set, using %s\n", storage->persistent_root); } if (!storage->persistent_root) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "WARNING: BD-J persistent root not set\n"); } } return storage->persistent_root; } static const char *_bdj_buda_root(BDJ_CONFIG *storage) { const char *root; char *cache_home; if (storage->no_persistent_storage) { return NULL; } if (!storage->cache_root) { root = getenv("LIBBLURAY_CACHE_ROOT"); if (root) { return root; } cache_home = file_get_cache_home(); if (cache_home) { storage->cache_root = str_printf("%s" DIR_SEP "bluray" DIR_SEP "bluray.bindingunit.root" DIR_SEP, cache_home); X_FREE(cache_home); BD_DEBUG(DBG_BDJ, "LIBBLURAY_CACHE_ROOT not set, using %s\n", storage->cache_root); } if (!storage->cache_root) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "WARNING: BD-J cache root not set\n"); } } return storage->cache_root; } static int _get_method(JNIEnv *env, jclass *cls, jmethodID *method_id, const char *class_name, const char *method_name, const char *method_sig) { *method_id = NULL; *cls = (*env)->FindClass(env, class_name); if (!*cls) { (*env)->ExceptionDescribe(env); BD_DEBUG(DBG_BDJ | DBG_CRIT, "Failed to locate class %s\n", class_name); (*env)->ExceptionClear(env); return 0; } *method_id = (*env)->GetStaticMethodID(env, *cls, method_name, method_sig); if (!*method_id) { (*env)->ExceptionDescribe(env); BD_DEBUG(DBG_BDJ | DBG_CRIT, "Failed to locate class %s method %s %s\n", class_name, method_name, method_sig); (*env)->DeleteLocalRef(env, *cls); *cls = NULL; (*env)->ExceptionClear(env); return 0; } return 1; } static int _bdj_init(JNIEnv *env, struct bluray *bd, const char *disc_root, const char *bdj_disc_id, BDJ_CONFIG *storage) { if (!bdj_register_native_methods(env)) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Couldn't register native methods.\n"); } // initialize class org.videolan.Libbluray jclass init_class; jmethodID init_id; if (!_get_method(env, &init_class, &init_id, "org/videolan/Libbluray", "init", "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V")) { return 0; } const char *disc_id = (bdj_disc_id && bdj_disc_id[0]) ? bdj_disc_id : "00000000000000000000000000000000"; jlong param_bdjava_ptr = (jlong)(intptr_t) bd; jstring param_disc_id = (*env)->NewStringUTF(env, disc_id); jstring param_disc_root = (*env)->NewStringUTF(env, disc_root); jstring param_persistent_root = (*env)->NewStringUTF(env, _bdj_persistent_root(storage)); jstring param_buda_root = (*env)->NewStringUTF(env, _bdj_buda_root(storage)); (*env)->CallStaticVoidMethod(env, init_class, init_id, param_bdjava_ptr, param_disc_id, param_disc_root, param_persistent_root, param_buda_root); (*env)->DeleteLocalRef(env, init_class); (*env)->DeleteLocalRef(env, param_disc_id); (*env)->DeleteLocalRef(env, param_disc_root); (*env)->DeleteLocalRef(env, param_persistent_root); (*env)->DeleteLocalRef(env, param_buda_root); if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionDescribe(env); BD_DEBUG(DBG_BDJ | DBG_CRIT, "Failed to initialize BD-J (uncaught exception)\n"); (*env)->ExceptionClear(env); return 0; } return 1; } int bdj_jvm_available(BDJ_CONFIG *storage) { const char *java_home = NULL; void* jvm_lib = _load_jvm(&java_home, storage->java_home); if (!jvm_lib) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "BD-J check: Failed to load JVM library\n"); return BDJ_CHECK_NO_JVM; } dl_dlclose(jvm_lib); if (!_find_libbluray_jar(storage)) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "BD-J check: Failed to load libbluray.jar\n"); return BDJ_CHECK_NO_JAR; } BD_DEBUG(DBG_BDJ, "BD-J check: OK\n"); return BDJ_CHECK_OK; } static int _find_jvm(void *jvm_lib, JNIEnv **env, JavaVM **jvm) { fptr_JNI_GetCreatedJavaVMs JNI_GetCreatedJavaVMs_fp; *(void **)(&JNI_GetCreatedJavaVMs_fp) = dl_dlsym(jvm_lib, "JNI_GetCreatedJavaVMs"); if (JNI_GetCreatedJavaVMs_fp == NULL) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Couldn't find symbol JNI_GetCreatedJavaVMs.\n"); return 0; } jsize nVMs = 0; JavaVM* javavm = NULL; int result = JNI_GetCreatedJavaVMs_fp(&javavm, 1, &nVMs); if (result == JNI_OK && nVMs > 0) { *jvm = javavm; (**jvm)->AttachCurrentThread(*jvm, (void**)env, NULL); return 1; } return 0; } /* Export packages for Xlets */ static const char * const java_base_exports[] = { "javax.media" , "javax.media.protocol", "javax.tv.graphics", "javax.tv.service", "javax.tv.service.guide", "javax.tv.service.selection", "javax.tv.service.transport", "javax.tv.service.navigation", "javax.tv.net", "javax.tv.locator", "javax.tv.util", "javax.tv.media", "javax.tv.xlet", "javax.microedition.xlet", "org.davic.resources", "org.davic.net", "org.davic.media", "org.davic.mpeg", "org.dvb.user", "org.dvb.dsmcc", "org.dvb.application", "org.dvb.ui", "org.dvb.test", "org.dvb.lang", "org.dvb.event", "org.dvb.io.ixc", "org.dvb.io.persistent", "org.dvb.media", "org.havi.ui", "org.havi.ui.event", "org.bluray.application", "org.bluray.ui", "org.bluray.ui.event", "org.bluray.net", "org.bluray.storage", "org.bluray.vfs", "org.bluray.bdplus", "org.bluray.system", "org.bluray.media", "org.bluray.ti", "org.bluray.ti.selection", "org.blurayx.s3d.ui", "org.blurayx.s3d.system", "org.blurayx.s3d.media", "org.blurayx.s3d.ti", "org.blurayx.uhd.ui", "org.blurayx.uhd.system", "org.blurayx.uhd.ti", "com.aacsla.bluray.online", "com.aacsla.bluray.mc", "com.aacsla.bluray.mt", "org.videolan.backdoor", /* entry for injected Xlet / runtime fixes */ }; static const size_t num_java_base_exports = sizeof(java_base_exports) / sizeof(java_base_exports[0]); static int _create_jvm(void *jvm_lib, const char *java_home, BDJ_CONFIG *cfg, JNIEnv **env, JavaVM **jvm) { (void)java_home; /* used only with J2ME */ fptr_JNI_CreateJavaVM JNI_CreateJavaVM_fp; JavaVMOption option[96]; int n = 0, result, java_9; JavaVMInitArgs args; *(void **)(&JNI_CreateJavaVM_fp) = dl_dlsym(jvm_lib, "JNI_CreateJavaVM"); if (JNI_CreateJavaVM_fp == NULL) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Couldn't find symbol JNI_CreateJavaVM.\n"); return 0; } #ifdef HAVE_BDJ_J2ME java_9 = 0; #else java_9 = !!dl_dlsym(jvm_lib, "JVM_DefineModule"); if (java_9) { BD_DEBUG(DBG_BDJ, "Detected Java 9 or later JVM\n"); } #endif memset(option, 0, sizeof(option)); option[n++].optionString = str_dup ("-Dawt.toolkit=java.awt.BDToolkit"); option[n++].optionString = str_dup ("-Djava.awt.graphicsenv=java.awt.BDGraphicsEnvironment"); option[n++].optionString = str_dup ("-Djava.awt.headless=false"); option[n++].optionString = str_dup ("-Xms256M"); option[n++].optionString = str_dup ("-Xmx256M"); option[n++].optionString = str_dup ("-Xss2048k"); #ifdef HAVE_BDJ_J2ME option[n++].optionString = str_printf("-Djava.home=%s", java_home); option[n++].optionString = str_printf("-Xbootclasspath/a:%s/lib/xmlparser.jar", java_home); option[n++].optionString = str_dup ("-XfullShutdown"); #endif #ifdef _WIN32 # define CLASSPATH_FORMAT_P "%s;%s" #else # define CLASSPATH_FORMAT_P "%s:%s" #endif if (!java_9) { option[n++].optionString = str_dup ("-Djavax.accessibility.assistive_technologies= "); option[n++].optionString = str_printf("-Xbootclasspath/p:" CLASSPATH_FORMAT_P, cfg->classpath[0], cfg->classpath[1]); } else { option[n++].optionString = str_printf("--patch-module=java.base=%s", cfg->classpath[0]); option[n++].optionString = str_printf("--patch-module=java.desktop=%s", cfg->classpath[1]); /* Fix module graph */ option[n++].optionString = str_dup("--add-reads=java.base=java.desktop"); /* org.videolan.IxcRegistryImpl -> java.rmi.Remote */ option[n++].optionString = str_dup("--add-reads=java.base=java.rmi"); /* org.videolan.FontIndex -> java.xml. */ option[n++].optionString = str_dup("--add-reads=java.base=java.xml"); /* AWT needs to access logger and Xlet context */ option[n++].optionString = str_dup("--add-opens=java.base/org.videolan=java.desktop"); /* AWT needs to acess DVBGraphics */ option[n++].optionString = str_dup("--add-exports=java.base/org.dvb.ui=java.desktop"); /* org.havi.ui.HBackgroundImage needs to access sun.awt.image.FileImageSource */ option[n++].optionString = str_dup("--add-exports=java.desktop/sun.awt.image=java.base"); /* Export BluRay packages to Xlets */ for (size_t idx = 0; idx < num_java_base_exports; idx++) { option[n++].optionString = str_printf("--add-exports=java.base/%s=ALL-UNNAMED", java_base_exports[idx]); } } /* JVM debug options */ if (getenv("BDJ_JVM_DISABLE_JIT")) { BD_DEBUG(DBG_CRIT | DBG_BDJ, "Disabling BD-J JIT\n"); option[n++].optionString = str_dup("-Xint"); } if (getenv("BDJ_JVM_DEBUG")) { BD_DEBUG(DBG_CRIT | DBG_BDJ, "Enabling BD-J debug mode\n"); option[n++].optionString = str_dup("-ea"); //option[n++].optionString = str_dup("-verbose"); //option[n++].optionString = str_dup("-verbose:class,gc,jni"); option[n++].optionString = str_dup("-Xdebug"); option[n++].optionString = str_dup("-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"); } #ifdef HAVE_BDJ_J2ME /* see: http://docs.oracle.com/javame/config/cdc/cdc-opt-impl/ojmeec/1.0/runtime/html/cvm.htm#CACBHBJB trace method execution: BDJ_JVM_TRACE=0x0002 trace exceptions: BDJ_JVM_TRACE=0x4000 */ if (getenv("BDJ_JVM_TRACE")) { option[n++].optionString = str_printf("-Xtrace:%s", getenv("BDJ_JVM_TRACE")); } #endif args.version = JNI_VERSION_1_4; args.nOptions = n; args.options = option; args.ignoreUnrecognized = JNI_FALSE; // don't ignore unrecognized options #ifdef _WIN32 /* ... in windows, JVM options are not UTF8 but current system code page ... */ /* luckily, most BD-J options can be passed in as java strings later. But, not class path. */ int ii; for (ii = 0; ii < n; ii++) { char *tmp = _utf8_to_cp(option[ii].optionString); if (tmp) { X_FREE(option[ii].optionString); option[ii].optionString = tmp; } else { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Failed to convert %s\n", option[ii].optionString); } } #endif result = JNI_CreateJavaVM_fp(jvm, (void**) env, &args); while (--n >= 0) { X_FREE(option[n].optionString); } if (result != JNI_OK || !*env) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Failed to create new Java VM. JNI_CreateJavaVM result: %d\n", result); return 0; } BD_DEBUG(DBG_BDJ , "Created Java VM %p (env %p)\n", (void *)jvm, (void *)*env); return 1; } BDJAVA* bdj_open(const char *path, struct bluray *bd, const char *bdj_disc_id, BDJ_CONFIG *cfg) { BD_DEBUG(DBG_BDJ, "bdj_open()\n"); if (!_find_libbluray_jar(cfg)) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "BD-J start failed: " BDJ_JARFILE " not found.\n"); return NULL; } #if defined(__APPLE__) && !defined(HAVE_BDJ_J2ME) /* On macOS we need to load libjli to workaround a bug where the wrong * version would be used: https://bugs.openjdk.java.net/browse/JDK-7131356 */ void* jli_lib = _load_jli_macos(); if (!jli_lib) { BD_DEBUG(DBG_BDJ, "Wasn't able to load JLI\n"); } #endif // first load the jvm using dlopen const char *java_home = NULL; void* jvm_lib = _load_jvm(&java_home, cfg->java_home); if (!jvm_lib) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "Wasn't able to load JVM\n"); return 0; } BDJAVA* bdjava = calloc(1, sizeof(BDJAVA)); if (!bdjava) { dl_dlclose(jvm_lib); return NULL; } JNIEnv* env = NULL; JavaVM *jvm = NULL; if (!_find_jvm(jvm_lib, &env, &jvm) && !_create_jvm(jvm_lib, java_home, cfg, &env, &jvm)) { X_FREE(bdjava); dl_dlclose(jvm_lib); return NULL; } #if defined(__APPLE__) && !defined(HAVE_BDJ_J2ME) bdjava->h_libjli = jli_lib; #endif bdjava->h_libjvm = jvm_lib; bdjava->jvm = jvm; if (debug_mask & DBG_JNI) { int version = (int)(*env)->GetVersion(env); BD_DEBUG(DBG_BDJ, "Java JNI version: %d.%d\n", version >> 16, version & 0xffff); } if (!_bdj_init(env, bd, path, bdj_disc_id, cfg)) { bdj_close(bdjava); return NULL; } /* detach java main thread (CreateJavaVM attachs calling thread to JVM) */ (*bdjava->jvm)->DetachCurrentThread(bdjava->jvm); return bdjava; } void bdj_close(BDJAVA *bdjava) { JNIEnv *env; int attach = 0; jclass shutdown_class; jmethodID shutdown_id; if (!bdjava) { return; } BD_DEBUG(DBG_BDJ, "bdj_close()\n"); if (bdjava->jvm) { if ((*bdjava->jvm)->GetEnv(bdjava->jvm, (void**)&env, JNI_VERSION_1_4) != JNI_OK) { (*bdjava->jvm)->AttachCurrentThread(bdjava->jvm, (void**)&env, NULL); attach = 1; } if (_get_method(env, &shutdown_class, &shutdown_id, "org/videolan/Libbluray", "shutdown", "()V")) { (*env)->CallStaticVoidMethod(env, shutdown_class, shutdown_id); if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionDescribe(env); BD_DEBUG(DBG_BDJ | DBG_CRIT, "Failed to shutdown BD-J (uncaught exception)\n"); (*env)->ExceptionClear(env); } (*env)->DeleteLocalRef(env, shutdown_class); } bdj_unregister_native_methods(env); if (attach) { (*bdjava->jvm)->DetachCurrentThread(bdjava->jvm); } } if (bdjava->h_libjvm) { dl_dlclose(bdjava->h_libjvm); } #if defined(__APPLE__) && !defined(HAVE_BDJ_J2ME) if (bdjava->h_libjli) { dl_dlclose(bdjava->h_libjli); } #endif X_FREE(bdjava); } int bdj_process_event(BDJAVA *bdjava, unsigned ev, unsigned param) { static const char * const ev_name[] = { /* 0 */ "NONE", /* 1 */ "START", /* 2 */ "STOP", /* 3 */ "PSR102", /* 4 */ "PLAYLIST", /* 5 */ "PLAYITEM", /* 6 */ "CHAPTER", /* 7 */ "MARK", /* 8 */ "PTS", /* 9 */ "END_OF_PLAYLIST", /* 10 */ "SEEK", /* 11 */ "RATE", /* 12 */ "ANGLE", /* 13 */ "AUDIO_STREAM", /* 14 */ "SUBTITLE", /* 15 */ "SECONDARY_STREAM", /* 16 */ "VK_KEY", /* 17 */ "UO_MASKED", /* 18 */ "MOUSE", }; JNIEnv* env; int attach = 0; jclass event_class; jmethodID event_id; int result = -1; if (!bdjava) { return -1; } if (ev > BDJ_EVENT_LAST) { BD_DEBUG(DBG_BDJ | DBG_CRIT, "bdj_process_event(%d,%d): unknown event\n", ev, param); } // Disable too verbose logging (PTS) else if (ev != BDJ_EVENT_PTS) { BD_DEBUG(DBG_BDJ, "bdj_process_event(%s,%d)\n", ev_name[ev], param); } if ((*bdjava->jvm)->GetEnv(bdjava->jvm, (void**)&env, JNI_VERSION_1_4) != JNI_OK) { (*bdjava->jvm)->AttachCurrentThread(bdjava->jvm, (void**)&env, NULL); attach = 1; } if (_get_method(env, &event_class, &event_id, "org/videolan/Libbluray", "processEvent", "(II)Z")) { if ((*env)->CallStaticBooleanMethod(env, event_class, event_id, (jint)ev, (jint)param)) { result = 0; } if ((*env)->ExceptionOccurred(env)) { (*env)->ExceptionDescribe(env); BD_DEBUG(DBG_BDJ | DBG_CRIT, "bdj_process_event(%u,%u) failed (uncaught exception)\n", ev, param); (*env)->ExceptionClear(env); } (*env)->DeleteLocalRef(env, event_class); } if (attach) { (*bdjava->jvm)->DetachCurrentThread(bdjava->jvm); } return result; }
lgpl-2.1
rbouqueau/gpac_brew_travis
src/compositor/compositor_2d.c
1
55642
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / Scene Compositor sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include "visual_manager.h" #include "nodes_stacks.h" #include <gpac/options.h> #include <gpac/internal/terminal_dev.h> #include "texturing.h" #include "gl_inc.h" #ifdef OPENGL_RASTER static void c2d_gl_fill_no_alpha(void *cbk, u32 x, u32 y, u32 run_h_len, GF_Color color) { #if defined(GPAC_USE_GLES1X) GLfloat line[4]; line[0] = FIX2FLT(x); line[1] = FIX2FLT(y); line[2] = FIX2FLT(x+run_h_len); line[3] = line[1]; glColor4ub(GF_COL_R(color), GF_COL_G(color), GF_COL_B(color), 0xFF); glVertexPointer(2, GL_FLOAT, 0, line); glEnableClientState(GL_VERTEX_ARRAY); glDrawArrays(GL_LINES, 0, 2); glDisableClientState(GL_VERTEX_ARRAY); #else glBegin(GL_LINES); glColor3ub(GF_COL_R(color), GF_COL_G(color), GF_COL_B(color)); // glColor3f(GF_COL_R(color)/255, GF_COL_G(color)/255, GF_COL_B(color)/255); glVertex2i(x,y); glVertex2i(x+run_h_len,y); glEnd(); #endif } static void c2d_gl_fill_alpha(void *cbk, u32 x, u32 y, u32 run_h_len, GF_Color color, u8 alpha) { #if defined(GPAC_USE_GLES1X) GLfloat line[4]; line[0] = FIX2FLT(x); line[1] = FIX2FLT(y); line[2] = FIX2FLT(x+run_h_len); line[3] = line[1]; glEnable(GL_BLEND); glColor4ub(GF_COL_R(color), GF_COL_G(color), GF_COL_B(color), (u8) alpha); glVertexPointer(2, GL_FLOAT, 0, line); glEnableClientState(GL_VERTEX_ARRAY); glDrawArrays(GL_LINES, 0, 2); glDisableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); #else glEnable(GL_BLEND); glColor4ub(GF_COL_R(color), GF_COL_G(color), GF_COL_B(color), (u8) alpha); glBegin(GL_LINES); glVertex2i(x,y); glVertex2i(x+run_h_len,y); glEnd(); glDisable(GL_BLEND); #endif } static void c2d_gl_fill_rect(void *cbk, u32 x, u32 y, u32 width, u32 height, GF_Color color) { return; #if defined(GPAC_USE_GLES1X) GLfloat line[8]; line[0] = FIX2FLT(x); line[1] = FIX2FLT(y); line[2] = FIX2FLT(x+width); line[3] = FIX2FLT(y); line[4] = FIX2FLT(x+width); line[5] = FIX2FLT(y+height); line[6] = FIX2FLT(x); line[7] = FIX2FLT(y+height); glEnable(GL_BLEND); glColor4ub(GF_COL_R(color), GF_COL_G(color), GF_COL_B(color), GF_COL_A(color)); glVertexPointer(4, GL_FLOAT, 0, line); glEnableClientState(GL_VERTEX_ARRAY); glDrawArrays(GL_TRIANGLE_FAN, 0, 2); glDisableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); #else glEnable(GL_BLEND); glColor4ub(GF_COL_R(color), GF_COL_G(color), GF_COL_B(color), GF_COL_A(color)); glBegin(GL_TRIANGLES); glVertex2i(x,y); glVertex2i(x+width,y); glVertex2i(x+width,y+height); glEnd(); glBegin(GL_TRIANGLES); glVertex2i(x,y); glVertex2i(x+width,y+height); glVertex2i(x,y+height); glEnd(); glDisable(GL_BLEND); #endif } #endif #ifndef GPAC_DISABLE_3D void compositor_2d_hybgl_clear_surface(GF_VisualManager *visual, GF_IRect *rc, u32 BackColor, Bool is_offscreen_clear) { SFColor rgb; Fixed alpha = INT2FIX( GF_COL_A(BackColor) )/255; if (!visual->is_attached) return; if (!BackColor && !visual->offscreen && !is_offscreen_clear) { if (!visual->compositor->user || !(visual->compositor->user->init_flags & GF_TERM_WINDOW_TRANSPARENT)) { BackColor = visual->compositor->back_color & 0x00FFFFFF; } } if (is_offscreen_clear) { visual->compositor->rasterizer->surface_clear(visual->raster_surface, rc, BackColor); //if we clear the canvas with non-0 alpha, remember the area cleared in case we have to erase it later (overlapping bitmap) if (GF_COL_A(BackColor)) { ra_union_rect(&visual->hybgl_drawn, rc); } } else { rgb.red = INT2FIX( GF_COL_R(BackColor) ) / 255; rgb.green = INT2FIX( GF_COL_G(BackColor) )/255; rgb.blue = INT2FIX( GF_COL_B(BackColor) )/255; visual_3d_clear(visual, rgb , alpha); } } void compositor_2d_hybgl_flush_video(GF_Compositor *compositor, GF_IRect *area) { GF_TraverseState a_tr_state; //check if texture data has changed - if so, mark texture to be updated if (compositor->traverse_state->immediate_draw) { //nothing drawn, nothing to do if (!compositor->visual->hybgl_drawn.count) { return; } //nodes where drawn on canvas, push texture gf_sc_texture_set_data(compositor->hybgl_txh); } else { //nodes where drawn on canvas, push texture if (compositor->visual->hybgl_drawn.count) { //we could actually use texSubImage here, but we would need either to copy the data before pushing it or use current stride which will result in pushing too much data ... gf_sc_texture_set_data(compositor->hybgl_txh); } } //if no object drawn since the last flush, no need to draw the texture if (!compositor->visual->nb_objects_on_canvas_since_last_ogl_flush) goto exit; memset(&a_tr_state, 0, sizeof(GF_TraverseState)); a_tr_state.color_mat.identity = 1; a_tr_state.visual = compositor->visual; a_tr_state.camera = &compositor->visual->camera; gf_mx_init(a_tr_state.model_matrix); visual_3d_set_state(compositor->visual, V3D_STATE_LIGHT, GF_FALSE); visual_3d_enable_antialias(compositor->visual, GF_FALSE); gf_sc_texture_set_blend_mode(compositor->hybgl_txh, TX_MODULATE); //visual_3d_set_material_2d_argb(compositor->visual, 0xFFFFFFFF); compositor->visual->has_material_2d = 0; a_tr_state.mesh_num_textures = gf_sc_texture_enable(compositor->hybgl_txh, NULL); if (a_tr_state.mesh_num_textures ) { if (area) { u32 i; Fixed umin, umax, vmin, vmax; SFVec2f size, orig; size.x = INT2FIX(area->width); size.y = INT2FIX(area->height); orig.x = INT2FIX(area->x); orig.y = INT2FIX(area->y); mesh_new_rectangle(compositor->hybgl_mesh, size, &orig, GF_TRUE); orig.x = INT2FIX(area->x) + INT2FIX(compositor->vp_width)/2; orig.y = INT2FIX(compositor->vp_height)/2 - INT2FIX(area->y) + INT2FIX(area->height); //set our coor texture so that we update only the right part of the canvas umin = gf_divfix(orig.x, INT2FIX(compositor->vp_width)); umax = gf_divfix(orig.x+size.x, INT2FIX(compositor->vp_width)); vmin = gf_divfix(orig.y-size.y, INT2FIX(compositor->vp_height)); vmax = gf_divfix(orig.y, INT2FIX(compositor->vp_height)); for (i=0; i<compositor->hybgl_mesh->v_count; i++) { if (compositor->hybgl_mesh->vertices[i].texcoords.x == FIX_ONE) { compositor->hybgl_mesh->vertices[i].texcoords.x = umax; } else { compositor->hybgl_mesh->vertices[i].texcoords.x = umin; } if (compositor->hybgl_mesh->vertices[i].texcoords.y == FIX_ONE) { compositor->hybgl_mesh->vertices[i].texcoords.y = vmax; } else { compositor->hybgl_mesh->vertices[i].texcoords.y = vmin; } } } visual_3d_mesh_paint(&a_tr_state, compositor->hybgl_mesh); gf_sc_texture_disable(compositor->hybgl_txh); if (area) { SFVec2f size; size.x = INT2FIX(compositor->vp_width); size.y = INT2FIX(compositor->vp_height); mesh_new_rectangle(compositor->hybgl_mesh, size, NULL, GF_TRUE); } } exit: //in immediate mode always clear the canvas if (compositor->traverse_state->immediate_draw) { compositor->visual->hybgl_drawn.count = 0; //partial flush, reset if (area) memset(compositor->hybgl_txh->data, 0, compositor->hybgl_txh->stride*compositor->hybgl_txh->height); } //complete flush (end of frame) else if (!area) { compositor->visual->hybgl_drawn.count = 0; } compositor->visual->nb_objects_on_canvas_since_last_ogl_flush = 0; } Bool c2d_gl_draw_bitmap(GF_VisualManager *visual, GF_TraverseState *tr_state, DrawableContext *ctx) { u8 alpha = GF_COL_A(ctx->aspect.fill_color); if (ctx->transform.m[1] || ctx->transform.m[3]) return GF_FALSE; visual_3d_set_state(visual, V3D_STATE_LIGHT, GF_FALSE); visual_3d_enable_antialias(visual, GF_FALSE); if (alpha && (alpha != 0xFF)) { visual_3d_set_material_2d_argb(visual, ctx->aspect.fill_color); gf_sc_texture_set_blend_mode(ctx->aspect.fill_texture, TX_MODULATE); } else if (gf_sc_texture_is_transparent(ctx->aspect.fill_texture)) { gf_sc_texture_set_blend_mode(ctx->aspect.fill_texture, TX_REPLACE); } else { visual_3d_set_state(visual, V3D_STATE_BLEND, GF_FALSE); } #ifndef GPAC_DISABLE_VRML /*ignore texture transform for bitmap*/ tr_state->mesh_num_textures = gf_sc_texture_enable(ctx->aspect.fill_texture, tr_state->appear ? ((M_Appearance *)tr_state->appear)->textureTransform : NULL); if (tr_state->mesh_num_textures) { SFVec2f size, orig; GF_Mesh *mesh; size.x = ctx->bi->unclip.width; size.y = ctx->bi->unclip.height; # ifdef OPENGL_RASTER if (visual->compositor->opengl_raster) { orig.x = ctx->bi->unclip.x + INT2FIX(visual->compositor->vp_width)/2; orig.y = INT2FIX(visual->compositor->vp_height)/2 - ctx->bi->unclip.y + ctx->bi->unclip.height; } #endif mesh = new_mesh(); mesh_new_rectangle(mesh, size, &orig, GF_TRUE); visual_3d_mesh_paint(tr_state, mesh); mesh_free(mesh); gf_sc_texture_disable(ctx->aspect.fill_texture); tr_state->mesh_num_textures = 0; return GF_TRUE; } #endif return GF_FALSE; } Bool compositor_2d_hybgl_draw_bitmap(GF_VisualManager *visual, GF_TraverseState *tr_state, DrawableContext *ctx) { GF_Node *txtrans = NULL; //for anything but background use regular routines if (!(ctx->flags & CTX_IS_BACKGROUND)) return GF_FALSE; #ifndef GPAC_DISABLE_VRML if (tr_state->appear ) txtrans = ((M_Appearance *)tr_state->appear)->textureTransform; #endif /*ignore texture transform for bitmap*/ tr_state->mesh_num_textures = gf_sc_texture_enable(ctx->aspect.fill_texture, txtrans); if (tr_state->mesh_num_textures) { SFVec2f size, orig; size.x = ctx->bi->unclip.width; size.y = ctx->bi->unclip.height; orig.x = ctx->bi->unclip.x ; orig.y = ctx->bi->unclip.y; mesh_new_rectangle(visual->compositor->hybgl_mesh_background, size, &orig, GF_FALSE); visual_3d_mesh_paint(tr_state, visual->compositor->hybgl_mesh_background); gf_sc_texture_disable(ctx->aspect.fill_texture); tr_state->mesh_num_textures = 0; } return GF_TRUE; } #endif #ifndef GPAC_DISABLE_3D void compositor_2d_reset_gl_auto(GF_Compositor *compositor) { if (compositor->hybgl_txh) { if (compositor->hybgl_txh->data) { gf_free(compositor->hybgl_txh->data); compositor->hybgl_txh->data = NULL; } if (compositor->hybgl_txh->tx_io) gf_sc_texture_release(compositor->hybgl_txh); gf_free(compositor->hybgl_txh); compositor->hybgl_txh = NULL; } if (compositor->hybgl_mesh) { mesh_free(compositor->hybgl_mesh); compositor->hybgl_mesh = NULL; } if (compositor->hybgl_mesh_background) { mesh_free(compositor->hybgl_mesh_background); compositor->hybgl_mesh_background = NULL; } } static GF_Err compositor_2d_setup_opengl(GF_VisualManager *visual) { GF_Compositor *compositor = visual->compositor; visual->is_attached = GF_TRUE; visual_3d_setup(visual); visual->compositor->traverse_state->camera = &visual->camera; glViewport(0, 0, compositor->vp_width, compositor->vp_height); visual->camera.vp.x = visual->camera.vp.y = 0; visual->camera.vp.width = visual->camera.width = INT2FIX(compositor->vp_width); visual->camera.vp.height = visual->camera.height = INT2FIX(compositor->vp_height); visual->camera.up.y = FIX_ONE; visual->camera.end_zoom = FIX_ONE; visual->camera.position.z = INT2FIX(1000); visual->camera.flags = CAM_IS_DIRTY; camera_update(&visual->camera, NULL, visual->compositor->hybrid_opengl ? GF_TRUE : visual->center_coords); visual_3d_projection_matrix_modified(visual); #ifdef OPENGL_RASTER if (compositor->opengl_raster) { gf_mx_add_scale(&visual->camera.modelview, FIX_ONE, -FIX_ONE, FIX_ONE); gf_mx_add_translation(&visual->camera.modelview, -visual->camera.width/2, -visual->camera.height/2, 0); } #endif return GF_OK; } #endif #ifdef OPENGL_RASTER static GF_Err c2d_video_access_opengl_raster(GF_VisualManager *visual) { GF_Err e; GF_Compositor *compositor = visual->compositor; GF_RasterCallback callbacks; callbacks.cbk = visual; callbacks.fill_run_alpha = c2d_gl_fill_alpha; callbacks.fill_run_no_alpha = c2d_gl_fill_no_alpha; callbacks.fill_rect = c2d_gl_fill_rect; visual->DrawBitmap = c2d_gl_draw_bitmap; e = compositor->rasterizer->surface_attach_to_callbacks(visual->raster_surface, &callbacks, compositor->vp_width, compositor->vp_height); if (e) return e; return compositor_2d_setup_opengl(visual); } #endif #ifndef GPAC_DISABLE_3D static GF_Err c2d_video_access_hybrid_opengl(GF_VisualManager *visual) { GF_Err e; GF_Compositor *compositor = visual->compositor; if (!compositor->hybgl_txh) { GF_SAFEALLOC(compositor->hybgl_txh, GF_TextureHandler); if (!compositor->hybgl_txh) return GF_IO_ERR; compositor->hybgl_txh->compositor = compositor; } if ((compositor->hybgl_txh->width != compositor->vp_width) || (compositor->hybgl_txh->height != compositor->vp_height)) { SFVec2f size; compositor->hybgl_txh->data = (char*)gf_realloc(compositor->hybgl_txh->data, 4*compositor->vp_width*compositor->vp_height); if (compositor->hybgl_txh->tx_io) gf_sc_texture_release(compositor->hybgl_txh); compositor->hybgl_txh->width = compositor->vp_width; compositor->hybgl_txh->height = compositor->vp_height; compositor->hybgl_txh->stride = 4*compositor->vp_width; compositor->hybgl_txh->pixelformat = GF_PIXEL_RGBA; compositor->hybgl_txh->transparent = GF_TRUE; compositor->hybgl_txh->flags = GF_SR_TEXTURE_PRIVATE_MEDIA | GF_SR_TEXTURE_NO_GL_FLIP; memset(compositor->hybgl_txh->data, 0, 4*compositor->hybgl_txh->width*compositor->hybgl_txh->height); gf_sc_texture_allocate(compositor->hybgl_txh); gf_sc_texture_set_data(compositor->hybgl_txh); if (!compositor->hybgl_mesh) compositor->hybgl_mesh = new_mesh(); if (!compositor->hybgl_mesh_background) compositor->hybgl_mesh_background = new_mesh(); size.x = INT2FIX(compositor->vp_width); size.y = INT2FIX(compositor->vp_height); mesh_new_rectangle(compositor->hybgl_mesh, size, NULL, GF_TRUE); mesh_new_rectangle(compositor->hybgl_mesh_background, size, NULL, GF_FALSE); } if (!compositor->hybgl_txh->data) return GF_IO_ERR; if (visual->compositor->traverse_state->immediate_draw) memset(compositor->hybgl_txh->data, 0, 4*compositor->hybgl_txh->width*compositor->hybgl_txh->height); e = compositor->rasterizer->surface_attach_to_buffer(visual->raster_surface, compositor->hybgl_txh->data, compositor->hybgl_txh->width, compositor->hybgl_txh->height, 0, compositor->hybgl_txh->width * 4, (GF_PixelFormat) GF_PIXEL_RGBA); if (e) return e; e = compositor_2d_setup_opengl(visual); if (e) return e; visual->ClearSurface = compositor_2d_hybgl_clear_surface; visual->DrawBitmap = compositor_2d_hybgl_draw_bitmap; return GF_OK; } #endif static GF_Err c2d_get_video_access_normal(GF_VisualManager *visual) { GF_Err e; GF_Compositor *compositor = visual->compositor; compositor->hw_locked = GF_FALSE; e = GF_IO_ERR; /*try from video memory handle (WIN32) if supported*/ if ((compositor->video_out->hw_caps & GF_VIDEO_HW_HAS_HWND_HDC) && compositor->rasterizer->surface_attach_to_device && compositor->video_out->LockOSContext ) { compositor->hw_context = compositor->video_out->LockOSContext(compositor->video_out, GF_TRUE); if (compositor->hw_context) { e = compositor->rasterizer->surface_attach_to_device(visual->raster_surface, compositor->hw_context, compositor->vp_width, compositor->vp_height); if (!e) { visual->is_attached = GF_TRUE; GF_LOG(GF_LOG_DEBUG, GF_LOG_COMPOSE, ("[Compositor2D] Video surface handle attached to raster\n")); return GF_OK; } compositor->video_out->LockOSContext(compositor->video_out, GF_FALSE); GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Compositor2D] Cannot attach video surface handle to raster: %s\n", gf_error_to_string(e) )); } } if (compositor->video_out->hw_caps & GF_VIDEO_HW_HAS_LINE_BLIT) { e = compositor->rasterizer->surface_attach_to_callbacks(visual->raster_surface, &compositor->raster_callbacks, compositor->vp_width, compositor->vp_height); if (!e) { visual->is_attached = GF_TRUE; GF_LOG(GF_LOG_DEBUG, GF_LOG_COMPOSE, ("[Compositor2D] Video surface callbacks attached to raster\n")); return GF_OK; } GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Compositor2D] Failed to attach video surface callbacks to raster\n")); } e = GF_NOT_SUPPORTED; e = compositor->video_out->LockBackBuffer(compositor->video_out, &compositor->hw_surface, GF_TRUE); if (e==GF_OK) { compositor->hw_locked = GF_TRUE; e = compositor->rasterizer->surface_attach_to_buffer(visual->raster_surface, compositor->hw_surface.video_buffer, compositor->hw_surface.width, compositor->hw_surface.height, compositor->hw_surface.pitch_x, compositor->hw_surface.pitch_y, (GF_PixelFormat) compositor->hw_surface.pixel_format); if (!e) { visual->is_attached = GF_TRUE; GF_LOG(GF_LOG_DEBUG, GF_LOG_COMPOSE, ("[Compositor2D] Video surface memory attached to raster - w=%d h=%d pitch_x=%d pitch_y=%d\n", compositor->hw_surface.width, compositor->hw_surface.height, compositor->hw_surface.pitch_x, compositor->hw_surface.pitch_y)); return GF_OK; } GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Compositor2D] Cannot attach video surface memory to raster: %s\n", gf_error_to_string(e) )); compositor->video_out->LockBackBuffer(compositor->video_out, &compositor->hw_surface, GF_FALSE); } compositor->hw_locked = GF_FALSE; visual->is_attached = GF_FALSE; /*if using BlitTexture, return OK to still be able to blit images*/ if (compositor->video_out->BlitTexture) e = GF_OK; return e; } GF_Err compositor_2d_get_video_access(GF_VisualManager *visual) { if (!visual->raster_surface) return GF_BAD_PARAM; #ifdef OPENGL_RASTER if (visual->compositor->opengl_raster && visual->compositor->rasterizer->surface_attach_to_callbacks) { return c2d_video_access_opengl_raster(visual); } #endif #ifndef GPAC_DISABLE_3D if (visual->compositor->hybrid_opengl) { return c2d_video_access_hybrid_opengl(visual); } #endif //do nothing until asked to really attach return GF_OK; } Bool compositor_2d_check_attached(GF_VisualManager *visual) { if (!visual->is_attached) { c2d_get_video_access_normal(visual); } return visual->is_attached; } void compositor_2d_clear_surface(GF_VisualManager *visual, GF_IRect *rc, u32 BackColor, Bool offscreen_clear) { //visual not attached on main (direct video) visual, use texture bliting if (!visual->is_attached && visual->compositor->video_out->Blit && (visual->compositor->video_out->hw_caps & GF_VIDEO_HW_HAS_RGB)) { char data[12]; GF_Err e; GF_VideoSurface video_src; GF_Window src_wnd, dst_wnd; if (!BackColor && !visual->offscreen) { if (!visual->compositor->user || !(visual->compositor->user->init_flags & GF_TERM_WINDOW_TRANSPARENT)) { BackColor = visual->compositor->back_color; } } data[0] = data[3] = data[6] = data[9] = GF_COL_R(BackColor); data[1] = data[4] = data[7] = data[10] = GF_COL_G(BackColor); data[2] = data[5] = data[8] = data[11] = GF_COL_B(BackColor); memset(&video_src, 0, sizeof(GF_VideoSurface)); video_src.height = 2; video_src.width = 2; video_src.pitch_x = 0; video_src.pitch_y = 6; video_src.pixel_format = GF_PIXEL_RGB_24; video_src.video_buffer = data; src_wnd.x = src_wnd.y = 0; src_wnd.w = src_wnd.h = 1; if (rc) { if (visual->center_coords) { dst_wnd.x = rc->x + visual->width/2; dst_wnd.y = visual->height/2 - rc->y; } else { dst_wnd.x = rc->x; dst_wnd.y = rc->y - visual->height/2; } dst_wnd.w = rc->width; dst_wnd.h = rc->height; } else { dst_wnd.x = dst_wnd.y = 0; dst_wnd.w = visual->width; dst_wnd.h = visual->height; } e = visual->compositor->video_out->Blit(visual->compositor->video_out, &video_src, &src_wnd, &dst_wnd, 0); if (e==GF_OK) return; } visual_2d_clear_surface(visual, rc, BackColor, offscreen_clear); } void compositor_2d_release_video_access(GF_VisualManager *visual) { GF_Compositor *compositor = visual->compositor; if (visual->is_attached) { compositor->rasterizer->surface_detach(visual->raster_surface); visual->is_attached = GF_FALSE; } #ifndef GPAC_DISABLE_3D if (compositor->hybrid_opengl) { compositor_2d_hybgl_flush_video(compositor, NULL); return; } #endif //GPAC_DISABLE_3D if (compositor->hw_context) { compositor->video_out->LockOSContext(compositor->video_out, GF_FALSE); compositor->hw_context = NULL; } else if (compositor->hw_locked) { compositor->video_out->LockBackBuffer(compositor->video_out, &compositor->hw_surface, GF_FALSE); compositor->hw_locked = GF_FALSE; } } #ifndef GPAC_DISABLE_LOGS static void log_blit_times(GF_TextureHandler *txh, u32 push_time) { u32 ck; if (!txh->stream) return; push_time = gf_sys_clock() - push_time; gf_mo_get_object_time(txh->stream, &ck); if (ck>txh->last_frame_time) { GF_LOG(GF_LOG_DEBUG, GF_LOG_COMPOSE, ("[Compositor2D] Bliting frame (CTS %d) %d ms too late\n", txh->last_frame_time, ck - txh->last_frame_time )); } if (txh->nb_frames==100) { txh->nb_frames = 0; txh->upload_time = 0; } txh->nb_frames ++; txh->upload_time += push_time; GF_LOG(GF_LOG_DEBUG, GF_LOG_MEDIA, ("[2D Blitter] At %d Blit texture (CTS %d) %d ms after due date - blit in %d ms - average push time %d ms\n", ck, txh->last_frame_time, ck - txh->last_frame_time, push_time, txh->upload_time / txh->nb_frames)); } #endif Bool compositor_texture_rectangles(GF_VisualManager *visual, GF_TextureHandler *txh, GF_IRect *clip, GF_Rect *unclip, GF_Window *src, GF_Window *dst, Bool *disable_blit, Bool *has_scale) { Fixed w_scale, h_scale, tmp; u32 output_width, output_height; GF_IRect clipped_final = *clip; GF_Rect final = *unclip; Bool use_blit; src->w = src->h = 0; dst->w = dst->h = 0; if (disable_blit) *disable_blit = GF_FALSE; if (has_scale) *has_scale = GF_FALSE; if (final.width<=0 || final.height <=0) return GF_FALSE; if (txh->width==0 || txh->height==0) return GF_FALSE; w_scale = final.width / txh->width; h_scale = final.height / txh->height; if ((w_scale != FIX_ONE) || (h_scale!=FIX_ONE)) { if (has_scale) *has_scale = GF_TRUE; } if (visual->offscreen) { output_width = visual->width; output_height = visual->height; } else { /*use entire video surface for un-centering coord system*/ output_width = visual->compositor->vp_width; output_height = visual->compositor->vp_height; } /*take care of pixel rounding for odd width/height and make sure we strictly draw in the clipped bounds*/ if (visual->center_coords) { clipped_final.x += output_width / 2; final.x += INT2FIX( output_width / 2 ); clipped_final.y = output_height/ 2 - clipped_final.y; final.y = INT2FIX( output_height / 2) - final.y; } else { final.y -= final.height; clipped_final.y -= clipped_final.height; } /*make sure we lie in the final rect (this is needed for directdraw mode)*/ if (clipped_final.x<0) { clipped_final.width += clipped_final.x; clipped_final.x = 0; if (clipped_final.width <= 0) return GF_FALSE; } if (clipped_final.y<0) { clipped_final.height += clipped_final.y; clipped_final.y = 0; if (clipped_final.height <= 0) return GF_FALSE; } if (clipped_final.x + clipped_final.width > (s32) output_width) { clipped_final.width = output_width - clipped_final.x; clipped_final.x = output_width - clipped_final.width; } if (clipped_final.y + clipped_final.height > (s32) output_height) { clipped_final.height = output_height - clipped_final.y; clipped_final.y = output_height - clipped_final.height; } /*needed in direct drawing since clipping is not performed*/ if (clipped_final.width<=0 || clipped_final.height <=0) return GF_FALSE; if (clipped_final.width-1>= FIX2INT(final.width) ) clipped_final.width = FIX2INT(final.width); if (clipped_final.height-1>= FIX2INT(final.height) ) clipped_final.height = FIX2INT(final.height); /*set dest window*/ dst->x = (u32) clipped_final.x; dst->y = (u32) clipped_final.y; dst->w = (u32) clipped_final.width; dst->h = (u32) clipped_final.height; if (!dst->w || !dst->h) return GF_FALSE; #ifdef GPAC_FIXED_POINT #define ROUND_FIX(_v) \ _v = FIX2INT(tmp); #define CEILING(_v) \ _v = FIX2INT(tmp); \ if (INT2FIX(_v)!=tmp) _v++; #else #define ROUND_FIX(_v) \ _v = FIX2INT(tmp); \ tmp -= INT2FIX(_v); \ if (tmp>99*FIX_ONE/100) { _v++; tmp = 0; } \ if (ABS(tmp) > FIX_EPSILON) use_blit = 0; #define CEILING(_v) \ _v = FIX2INT(tmp); \ tmp -= INT2FIX(_v); \ if (tmp>0) { _v++; tmp = 0; } \ if (ABS(tmp) > FIX_EPSILON) use_blit = 0; #endif use_blit = GF_TRUE; if (txh->data && !txh->size && (txh->width==2) && (txh->height==2) ) { src->x = src->y = 0; src->w = 1; src->h = 1; } else { /*compute SRC window*/ tmp = gf_divfix(INT2FIX(clipped_final.x) - final.x, w_scale); if (tmp<0) tmp=0; CEILING(src->x); tmp = gf_divfix(INT2FIX(clipped_final.y) - final.y, h_scale); if (tmp<0) tmp=0; CEILING(src->y); tmp = gf_divfix(INT2FIX(clip->width), w_scale); ROUND_FIX(src->w); tmp = gf_divfix(INT2FIX(clip->height), h_scale); ROUND_FIX(src->h); if (src->w>txh->width) src->w=txh->width; if (src->h>txh->height) src->h=txh->height; if (!src->w || !src->h) return GF_FALSE; /*make sure we lie in src bounds*/ if (src->x + src->w>txh->width) src->w = txh->width - src->x; if (src->y + src->h>txh->height) src->h = txh->height - src->y; } #undef ROUND_FIX if (disable_blit) *disable_blit = use_blit ? GF_FALSE : GF_TRUE; return GF_TRUE; } static Bool compositor_2d_draw_bitmap_ex(GF_VisualManager *visual, GF_TextureHandler *txh, DrawableContext *ctx, GF_IRect *clip, GF_Rect *unclip, u8 alpha, GF_TraverseState *tr_state, Bool force_soft_blt) { GF_VideoSurface video_src; GF_Err e; Bool use_soft_stretch, use_blit, flush_video, is_attached, has_scale; u32 overlay_type; GF_Window src_wnd, dst_wnd; u32 output_width, output_height, hw_caps; if (!txh->data) return GF_TRUE; if (!visual->compositor->has_size_info && !(visual->compositor->msg_type & GF_SR_CFG_OVERRIDE_SIZE) && (visual->compositor->override_size_flags & 1) && !(visual->compositor->override_size_flags & 2) ) { if ( (visual->compositor->scene_width < txh->width) || (visual->compositor->scene_height < txh->height)) { visual->compositor->scene_width = txh->width; visual->compositor->scene_height = txh->height; visual->compositor->msg_type |= GF_SR_CFG_OVERRIDE_SIZE; return GF_TRUE; } } if (!compositor_texture_rectangles(visual, txh, clip, unclip, &src_wnd, &dst_wnd, &use_blit, &has_scale)) return GF_TRUE; /*can we use hardware blitter ?*/ hw_caps = visual->compositor->video_out->hw_caps; overlay_type = 0; flush_video = GF_FALSE; use_soft_stretch = GF_TRUE; output_width = visual->compositor->vp_width; output_height = visual->compositor->vp_height; if (visual->compositor->disable_hardware_blit) force_soft_blt = GF_TRUE; if (!force_soft_blt) { /*avoid partial redraw that don't come close to src pixels with the bliter, this leads to ugly artefacts - fall back to rasterizer*/ // if (!(ctx->flags & CTX_TEXTURE_DIRTY) && !use_blit && (src_wnd.x || src_wnd.y) ) // return 0; switch (txh->pixelformat) { case GF_PIXEL_RGB_24: case GF_PIXEL_BGR_24: case GF_PIXEL_RGBS: case GF_PIXEL_RGBD: // case GF_PIXEL_RGB_555: // case GF_PIXEL_RGB_565: if ((alpha==0xFF) && (hw_caps & GF_VIDEO_HW_HAS_RGB)) { use_soft_stretch = GF_FALSE; } else if ((alpha!=0xFF) && (hw_caps & GF_VIDEO_HW_HAS_RGBA)) { use_soft_stretch = GF_FALSE; } break; case GF_PIXEL_ARGB: case GF_PIXEL_RGBA: case GF_PIXEL_RGBAS: case GF_PIXEL_RGBDS: if (hw_caps & GF_VIDEO_HW_HAS_RGBA) use_soft_stretch = GF_FALSE; break; case GF_PIXEL_YV12: case GF_PIXEL_IYUV: case GF_PIXEL_I420: case GF_PIXEL_YVYU: case GF_PIXEL_YUY2: case GF_PIXEL_YUVD: case GF_PIXEL_YV12_10: if (hw_caps & GF_VIDEO_HW_HAS_YUV) use_soft_stretch = GF_FALSE; else if (hw_caps & GF_VIDEO_HW_HAS_YUV_OVERLAY) overlay_type = 1; break; default: break; } /*disable based on settings*/ if (!visual->compositor->enable_yuv_hw || (ctx->col_mat || !visual->compositor->video_out->Blit) ) { use_soft_stretch = GF_TRUE; overlay_type = 0; } if (visual->compositor->disable_partial_hw_blit && ((src_wnd.w!=txh->width) || (src_wnd.h!=txh->height) )) { use_soft_stretch = GF_TRUE; } /*disable HW color keying - not compatible with MPEG-4 MaterialKey*/ if (tr_state->col_key) { use_soft_stretch = GF_TRUE; overlay_type = 0; } if (overlay_type) { /*no more than one overlay is supported at the current time*/ if (visual->overlays) { ctx->drawable->flags &= ~DRAWABLE_IS_OVERLAY; overlay_type = 0; } /*direct draw or not last context: we must queue the overlay*/ else if (tr_state->immediate_draw || (ctx->next && ctx->next->drawable)) { overlay_type = 2; } /*OK we can overlay this video - if full display, don't flush*/ if (overlay_type==1) { if (dst_wnd.w==visual->compositor->display_width) flush_video = GF_FALSE; else if (dst_wnd.h==visual->compositor->display_height) flush_video = GF_FALSE; else flush_video = visual->has_modif; } /*if no color keying, we cannot queue the overlay*/ else if (!visual->compositor->video_out->overlay_color_key) { overlay_type = 0; } } } if (has_scale && !(hw_caps & GF_VIDEO_HW_HAS_STRETCH) && !overlay_type) { force_soft_blt = use_soft_stretch = GF_TRUE; } memset(&video_src, 0, sizeof(GF_VideoSurface)); video_src.height = txh->height; video_src.width = txh->width; video_src.pitch_x = 0; video_src.pitch_y = txh->stride; video_src.pixel_format = txh->pixelformat; #ifdef GF_SR_USE_DEPTH if (txh->pixelformat==GF_PIXEL_YUVD) video_src.pixel_format = GF_PIXEL_YV12; #endif video_src.video_buffer = txh->data; if (txh->raw_memory) { video_src.u_ptr = (char *) txh->pU; video_src.v_ptr = (char *) txh->pV; } video_src.global_alpha = alpha; //overlay queing if (overlay_type==2) { GF_IRect o_rc; GF_OverlayStack *ol, *first; /*queue overlay in order*/ GF_SAFEALLOC(ol, GF_OverlayStack); ol->ctx = ctx; ol->dst = dst_wnd; ol->src = src_wnd; first = visual->overlays; if (first) { while (first->next) first = first->next; first->next = ol; } else { visual->overlays = ol; } if (visual->center_coords) { o_rc.x = dst_wnd.x - output_width/2; o_rc.y = output_height/2- dst_wnd.y; } else { o_rc.x = dst_wnd.x; o_rc.y = dst_wnd.y + dst_wnd.h; } o_rc.width = dst_wnd.w; o_rc.height = dst_wnd.h; visual->ClearSurface(visual, &o_rc, visual->compositor->video_out->overlay_color_key, GF_FALSE); visual->has_overlays = GF_TRUE; /*mark drawable as overlay*/ ctx->drawable->flags |= DRAWABLE_IS_OVERLAY; /*prevents this context from being removed in direct draw mode by requesting a new one but not allocating it*/ if (tr_state->immediate_draw) visual_2d_get_drawable_context(visual); return GF_TRUE; } //will pause clock if first HW load gf_sc_texture_check_pause_on_first_load(txh); if (overlay_type) { u32 push_time; /*top level overlay*/ if (flush_video) { GF_Window rc; rc.x = rc.y = 0; rc.w = visual->compositor->display_width; rc.h = visual->compositor->display_height; visual_2d_release_raster(visual); visual->compositor->video_out->Flush(visual->compositor->video_out, &rc); visual_2d_init_raster(visual); } visual->compositor->skip_flush = 1; push_time = gf_sys_clock(); e = visual->compositor->video_out->Blit(visual->compositor->video_out, &video_src, &src_wnd, &dst_wnd, 1); if (!e) { #ifndef GPAC_DISABLE_LOG log_blit_times(txh, push_time); #endif /*mark drawable as overlay*/ ctx->drawable->flags |= DRAWABLE_IS_OVERLAY; visual->has_overlays = GF_TRUE; //will resume clock if first HW load gf_sc_texture_check_pause_on_first_load(txh); return GF_TRUE; } GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Compositor2D] Error during overlay blit - trying with soft one\n")); visual->compositor->skip_flush = GF_FALSE; } /*most graphic cards can't perform bliting on locked surface - force unlock by releasing the hardware*/ is_attached = visual->is_attached; if (is_attached) visual_2d_release_raster(visual); if (!use_soft_stretch) { u32 push_time = gf_sys_clock(); e = visual->compositor->video_out->Blit(visual->compositor->video_out, &video_src, &src_wnd, &dst_wnd, 0); /*HW pb, try soft*/ if (e) { use_soft_stretch = GF_TRUE; if (visual->compositor->video_memory==1) { GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Compositor2D] Error during hardware blit - will use soft one\n")); visual->compositor->video_memory = 2; } /*force a reconfigure of video output*/ else if (visual->compositor->video_memory!=2) { GF_LOG(GF_LOG_INFO, GF_LOG_COMPOSE, ("[Compositor2D] Reconfiguring video output to use video memory\n")); visual->compositor->request_video_memory = GF_TRUE; visual->compositor->root_visual_setup = GF_FALSE; gf_sc_next_frame_state(visual->compositor, GF_SC_DRAW_FRAME); } } #ifndef GPAC_DISABLE_LOG else { log_blit_times(txh, push_time); } #endif } //will resume clock if first HW load gf_sc_texture_check_pause_on_first_load(txh); if (use_soft_stretch) { GF_VideoSurface backbuffer; e = visual->compositor->video_out->LockBackBuffer(visual->compositor->video_out, &backbuffer, GF_TRUE); if (!e) { u32 push_time = gf_sys_clock(); gf_stretch_bits(&backbuffer, &video_src, &dst_wnd, &src_wnd, alpha, GF_FALSE, tr_state->col_key, ctx->col_mat); #ifndef GPAC_DISABLE_LOG log_blit_times(txh, push_time); #endif e = visual->compositor->video_out->LockBackBuffer(visual->compositor->video_out, &backbuffer, GF_FALSE); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Compositor2D] Cannot lock back buffer - Error %s\n", gf_error_to_string(e) )); if (is_attached) visual_2d_init_raster(visual); return GF_FALSE; } if (!visual->compositor->video_memory) { GF_LOG(GF_LOG_INFO, GF_LOG_COMPOSE, ("[Compositor2D] Reconfiguring video output to use video memory\n")); visual->compositor->video_memory = GF_TRUE; visual->compositor->root_visual_setup = GF_FALSE; gf_sc_next_frame_state(visual->compositor, GF_SC_DRAW_FRAME); } } visual->has_modif = GF_TRUE; if (is_attached) visual_2d_init_raster(visual); return GF_TRUE; } Bool compositor_2d_draw_bitmap(GF_VisualManager *visual, GF_TraverseState *tr_state, DrawableContext *ctx) { u8 alpha = 0xFF; if (!ctx->aspect.fill_texture) return GF_TRUE; /*check if texture is ready - if not pretend we drew it*/ if (!ctx->aspect.fill_texture->data) return GF_TRUE; if (ctx->transform.m[0]<0) return GF_FALSE; /*check if the <0 value is due to a flip in he scene description or due to bifs<->svg... context switching*/ if (ctx->transform.m[4]<0) { if (!(ctx->flags & CTX_FLIPED_COORDS)) return GF_FALSE; } else { if (ctx->flags & CTX_FLIPED_COORDS) return GF_FALSE; } if (ctx->transform.m[1] || ctx->transform.m[3]) return GF_FALSE; #ifndef GPAC_DISABLE_VRML if ((ctx->flags & CTX_HAS_APPEARANCE) && ctx->appear && ((M_Appearance*)ctx->appear)->textureTransform) return GF_FALSE; #endif alpha = GF_COL_A(ctx->aspect.fill_color); /*THIS IS A HACK, will not work when setting filled=0, transparency and XLineProps*/ if (!alpha) alpha = GF_COL_A(ctx->aspect.line_color); if (!alpha) return GF_TRUE; switch (ctx->aspect.fill_texture->pixelformat) { case GF_PIXEL_ALPHAGREY: case GF_PIXEL_GREYSCALE: case GF_PIXEL_RGB_24: case GF_PIXEL_BGR_24: case GF_PIXEL_RGB_555: case GF_PIXEL_RGB_565: case GF_PIXEL_ARGB: case GF_PIXEL_RGBA: case GF_PIXEL_YV12: case GF_PIXEL_IYUV: case GF_PIXEL_YVYU: case GF_PIXEL_YUY2: case GF_PIXEL_I420: case GF_PIXEL_NV21: case GF_PIXEL_YUVA: case GF_PIXEL_RGBS: case GF_PIXEL_RGBAS: case GF_PIXEL_YV12_10: break; case GF_PIXEL_YUVD: case GF_PIXEL_RGBD: case GF_PIXEL_RGBDS: #ifndef GPAC_DISABLE_3D /*using OpenGL to render depth images*/ if (visual->compositor->depth_gl_type) { gf_sc_set_option(visual->compositor, GF_OPT_USE_OPENGL, 2); return GF_TRUE; } #endif break; /*the rest has to be displayed through brush for now, we only use YUV and RGB pool*/ default: return GF_FALSE; } /*direct drawing, no clippers */ if (tr_state->immediate_draw) { if (visual->compositor->video_out->BlitTexture) { if (! visual->compositor->video_out->BlitTexture(visual->compositor->video_out, ctx->aspect.fill_texture, &ctx->transform, &ctx->bi->clip, alpha, tr_state->col_key #ifdef GF_SR_USE_DEPTH , ctx->depth_offset, ctx->depth_gain #else , 0, 0 #endif )) return GF_FALSE; } else { if (!compositor_2d_draw_bitmap_ex(visual, ctx->aspect.fill_texture, ctx, &ctx->bi->clip, &ctx->bi->unclip, alpha, tr_state, GF_FALSE)) return GF_FALSE; } } /*draw bitmap for all dirty rects*/ else { u32 i; GF_IRect clip; for (i=0; i<tr_state->visual->to_redraw.count; i++) { /*there's an opaque region above, don't draw*/ #ifdef TRACK_OPAQUE_REGIONS if (tr_state->visual->draw_node_index < tr_state->visual->to_redraw.list[i].opaque_node_index) continue; #endif clip = ctx->bi->clip; gf_irect_intersect(&clip, &tr_state->visual->to_redraw.list[i].rect); if (clip.width && clip.height) { if (visual->compositor->video_out->BlitTexture) { if (!visual->compositor->video_out->BlitTexture(visual->compositor->video_out, ctx->aspect.fill_texture, &ctx->transform, &ctx->bi->clip, alpha, tr_state->col_key #ifdef GF_SR_USE_DEPTH , ctx->depth_offset, ctx->depth_gain #else , 0, 0 #endif )) return GF_FALSE; } else if (!compositor_2d_draw_bitmap_ex(visual, ctx->aspect.fill_texture, ctx, &clip, &ctx->bi->unclip, alpha, tr_state, GF_FALSE)) { return GF_FALSE; } } } } ctx->aspect.fill_texture->flags |= GF_SR_TEXTURE_USED; return GF_TRUE; } GF_Err compositor_2d_set_aspect_ratio(GF_Compositor *compositor) { u32 old_vp_width, old_vp_height; Bool changed = GF_FALSE; Double ratio; GF_Event evt; GF_Err e; Fixed scaleX, scaleY; compositor->output_width = compositor->scene_width; compositor->output_height = compositor->scene_height; compositor->vp_x = compositor->vp_y = 0; scaleX = scaleY = FIX_ONE; old_vp_width = compositor->vp_width; old_vp_height = compositor->vp_height; /*force complete clean*/ compositor->traverse_state->invalidate_all = GF_TRUE; if (!compositor->has_size_info && !(compositor->override_size_flags & 2) ) { compositor->output_width = compositor->display_width; compositor->output_height = compositor->display_height; compositor->vp_width = compositor->visual->width = compositor->output_width; compositor->vp_height = compositor->visual->height = compositor->output_height; } else { if (compositor->rotate_mode % 2) { compositor->vp_height = compositor->display_width; compositor->vp_width = compositor->display_height; } else { compositor->vp_width = compositor->display_width; compositor->vp_height = compositor->display_height; } switch (compositor->aspect_ratio) { case GF_ASPECT_RATIO_FILL_SCREEN: break; case GF_ASPECT_RATIO_16_9: compositor->vp_width = compositor->display_width; compositor->vp_height = 9 * compositor->display_width / 16; if (compositor->vp_height>compositor->display_height) { compositor->vp_height = compositor->display_height; compositor->vp_width = 16 * compositor->display_height / 9; } break; case GF_ASPECT_RATIO_4_3: compositor->vp_width = compositor->display_width; compositor->vp_height = 3 * compositor->display_width / 4; if (compositor->vp_height>compositor->display_height) { compositor->vp_height = compositor->display_height; compositor->vp_width = 4 * compositor->display_height / 3; } break; default: ratio = compositor->scene_height; ratio /= compositor->scene_width; if (compositor->vp_width * ratio > compositor->vp_height) { compositor->vp_width = compositor->vp_height * compositor->scene_width; compositor->vp_width /= compositor->scene_height; } else { compositor->vp_height = compositor->vp_width * compositor->scene_height; compositor->vp_height /= compositor->scene_width; } break; } compositor->vp_x = (compositor->display_width - compositor->vp_width) / 2; compositor->vp_y = (compositor->display_height - compositor->vp_height) / 2; scaleX = gf_divfix(INT2FIX(compositor->vp_width), INT2FIX(compositor->scene_width)); if (!scaleX) scaleX = FIX_ONE; scaleY = gf_divfix(INT2FIX(compositor->vp_height), INT2FIX(compositor->scene_height)); if (!scaleY) scaleY = FIX_ONE; if (!compositor->scalable_zoom) { compositor->output_width = compositor->scene_width; compositor->output_height = compositor->scene_height; compositor->vp_width = FIX2INT(gf_divfix(INT2FIX(compositor->display_width), scaleX)); compositor->vp_height = FIX2INT(gf_divfix(INT2FIX(compositor->display_height), scaleY)); compositor->vp_x = (compositor->vp_width - compositor->output_width) / 2; compositor->vp_y = (compositor->vp_height - compositor->output_height) / 2; scaleX = scaleY = FIX_ONE; } else { compositor->output_width = compositor->display_width; compositor->output_height = compositor->display_height; compositor->vp_width = compositor->display_width; compositor->vp_height = compositor->display_height; } compositor->visual->width = compositor->output_width; compositor->visual->height = compositor->output_height; } /*resize hardware surface*/ memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_VIDEO_SETUP; evt.setup.width = compositor->vp_width; evt.setup.height = compositor->vp_height; evt.setup.opengl_mode = 0; /*copy over settings*/ evt.setup.system_memory = compositor->video_memory ? GF_FALSE : GF_TRUE; if (compositor->request_video_memory) evt.setup.system_memory = GF_FALSE; compositor->request_video_memory = GF_FALSE; #ifdef OPENGL_RASTER if (compositor->opengl_raster) { evt.setup.opengl_mode = 1; evt.setup.system_memory = GF_FALSE; evt.setup.back_buffer = GF_TRUE; } #endif #ifndef GPAC_DISABLE_3D if (compositor->hybrid_opengl) { evt.setup.opengl_mode = 1; evt.setup.system_memory = GF_FALSE; evt.setup.back_buffer = GF_TRUE; } #endif if (compositor->was_system_memory != evt.setup.system_memory) changed = GF_TRUE; else if (old_vp_width != compositor->vp_width) changed = GF_TRUE; else if (old_vp_height != compositor->vp_height) changed = GF_TRUE; else if (compositor->is_opengl != evt.setup.opengl_mode) changed = GF_TRUE; if (changed) { GF_LOG(GF_LOG_INFO, GF_LOG_COMPOSE, ("[Compositor2D] Reconfiguring display size %d x %d - opengl %s - use %s memory\n", evt.setup.width, evt.setup.height, (evt.setup.opengl_mode==2) ? "Offscreen" : (evt.setup.opengl_mode==1) ? "yes" : "no", evt.setup.system_memory ? "systems" : "video" )); e = compositor->video_out->ProcessEvent(compositor->video_out, &evt); if (e) { #ifndef GPAC_DISABLE_3D if (!compositor->hybrid_opengl) { compositor->hybrid_opengl = GF_TRUE; GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Compositor2D] Failed to configure 2D output (%s) - retrying in OpenGL mode\n", gf_error_to_string(e) )); return compositor_2d_set_aspect_ratio(compositor); } #endif compositor->video_setup_failed = GF_TRUE; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; evt.message.error = e; evt.message.message = "Cannot setup video output"; gf_term_send_event(compositor->term, &evt); return e; } compositor->is_opengl = evt.setup.opengl_mode; compositor->was_system_memory = evt.setup.system_memory; } if (compositor->has_size_info) { compositor->traverse_state->vp_size.x = INT2FIX(compositor->scene_width); compositor->traverse_state->vp_size.y = INT2FIX(compositor->scene_height); } else { compositor->traverse_state->vp_size.x = INT2FIX(compositor->output_width); compositor->traverse_state->vp_size.y = INT2FIX(compositor->output_height); } GF_LOG(GF_LOG_DEBUG, GF_LOG_COMPOSE, ("[Compositor2D] Reconfigured display size %d x %d done\n", evt.setup.width, evt.setup.height)); /*set scale factor*/ compositor_set_ar_scale(compositor, scaleX, scaleY); return GF_OK; } void compositor_send_resize_event(GF_Compositor *compositor, GF_SceneGraph *subscene, Fixed old_z, Fixed old_tx, Fixed old_ty, Bool is_resize) { #ifndef GPAC_DISABLE_SVG GF_DOM_Event evt; u32 i; GF_SceneGraph *scene = (subscene ? subscene : compositor->scene); GF_Node *root = gf_sg_get_root_node(scene); /*if root node is not DOM, sent a resize event (for VRML/BIFS). Otherwise this must be handled by the composition code of the node*/ if (!root || (gf_node_get_tag(root) > GF_NODE_RANGE_LAST_VRML) ) return; memset(&evt, 0, sizeof(GF_DOM_Event)); evt.prev_scale = compositor->scale_x*old_z; evt.new_scale = compositor->scale_x*compositor->zoom; evt.bubbles = 1; if (is_resize) { evt.type = GF_EVENT_RESIZE; if (subscene == NULL) { evt.screen_rect.width = INT2FIX(compositor->display_width); evt.screen_rect.height = INT2FIX(compositor->display_height); } else { u32 w, h; gf_sg_get_scene_size_info(scene, &w, &h); evt.screen_rect.width = INT2FIX(w); evt.screen_rect.height = INT2FIX(h); } } else if (evt.prev_scale == evt.new_scale) { /*cannot get params for scroll events*/ evt.type = GF_EVENT_SCROLL; } else { evt.screen_rect.x = INT2FIX(compositor->vp_x); evt.screen_rect.y = INT2FIX(compositor->vp_y); evt.screen_rect.width = INT2FIX(compositor->output_width); evt.screen_rect.height = INT2FIX(compositor->output_height); evt.prev_translate.x = old_tx; evt.prev_translate.y = old_ty; evt.new_translate.x = compositor->trans_x; evt.new_translate.y = compositor->trans_y; evt.type = GF_EVENT_ZOOM; evt.bubbles = 0; } gf_dom_event_fire(gf_sg_get_root_node(scene), &evt); i=0; while ((scene = (GF_SceneGraph*)gf_list_enum(compositor->extra_scenes, &i))) { gf_dom_event_fire(gf_sg_get_root_node(scene), &evt); } #endif } void compositor_2d_set_user_transform(GF_Compositor *compositor, Fixed zoom, Fixed tx, Fixed ty, Bool is_resize) { Fixed ratio; Fixed old_tx, old_ty, old_z; gf_sc_lock(compositor, GF_TRUE); old_tx = tx; old_ty = ty; old_z = compositor->zoom; if (zoom <= 0) zoom = FIX_ONE/1000; compositor->trans_x = tx; compositor->trans_y = ty; if (zoom != compositor->zoom) { ratio = gf_divfix(zoom, compositor->zoom); compositor->trans_x = gf_mulfix(compositor->trans_x, ratio); compositor->trans_y = gf_mulfix(compositor->trans_y, ratio); compositor->zoom = zoom; compositor->zoom_changed = GF_TRUE; /*recenter visual*/ if (!compositor->visual->center_coords) { Fixed c_x, c_y, nc_x, nc_y; c_x = INT2FIX(compositor->display_width/2); nc_y = c_y = INT2FIX(compositor->display_height/2); nc_x = gf_mulfix(c_x, ratio); nc_y = gf_mulfix(c_y, ratio); compositor->trans_x -= (nc_x-c_x); compositor->trans_y -= (nc_y-c_y); } } gf_mx2d_init(compositor->traverse_state->transform); switch (compositor->rotate_mode) { case 1: gf_mx2d_add_rotation(&compositor->traverse_state->transform, 0, 0, -GF_PI/2); break; case 2: gf_mx2d_add_scale(&compositor->traverse_state->transform, -1, -1); break; case 3: gf_mx2d_add_rotation(&compositor->traverse_state->transform, 0, 0, GF_PI/2); break; } gf_mx2d_add_scale(&compositor->traverse_state->transform, gf_mulfix(compositor->zoom,compositor->scale_x), gf_mulfix(compositor->zoom,compositor->scale_y)); gf_mx2d_add_translation(&compositor->traverse_state->transform, compositor->trans_x, compositor->trans_y); if (compositor->rotation) gf_mx2d_add_rotation(&compositor->traverse_state->transform, 0, 0, compositor->rotation); if (!compositor->visual->center_coords) { gf_mx2d_add_translation(&compositor->traverse_state->transform, INT2FIX(compositor->vp_x), INT2FIX(compositor->vp_y)); } GF_LOG(GF_LOG_DEBUG, GF_LOG_COMPOSE, ("[Compositor2D] Changing Zoom (%g) and Pan (%g %g)\n", FIX2FLT(compositor->zoom), FIX2FLT(compositor->trans_x) , FIX2FLT(compositor->trans_y))); gf_sc_next_frame_state(compositor, GF_SC_DRAW_FRAME); compositor->traverse_state->invalidate_all = GF_TRUE; /*for zoom&pan, send the event right away. For resize/scroll, wait for the frame to be drawn before sending it otherwise viewport info of SVG nodes won't be correct*/ if (!is_resize) compositor_send_resize_event(compositor, NULL, old_z, old_tx, old_ty, GF_FALSE); gf_sc_lock(compositor, GF_FALSE); } GF_Rect compositor_2d_update_clipper(GF_TraverseState *tr_state, GF_Rect this_clip, Bool *need_restore, GF_Rect *original, Bool for_layer) { GF_Rect clip, orig; if (for_layer) { orig = tr_state->layer_clipper; *need_restore = tr_state->has_layer_clip; } else { orig = tr_state->clipper; *need_restore = tr_state->has_clip; } *original = orig; clip = this_clip; if (*need_restore) { #ifndef GPAC_DISABLE_3D if (tr_state->visual->type_3d) { GF_Matrix mx; gf_mx_copy(mx, tr_state->model_matrix); gf_mx_inverse(&mx); gf_mx_apply_rect(&mx, &orig); gf_mx_apply_rect(&tr_state->layer_matrix, &orig); } else #endif { GF_Matrix2D mx2d; gf_mx2d_copy(mx2d, tr_state->transform); gf_mx2d_inverse(&mx2d); gf_mx2d_apply_rect(&mx2d, &orig); } if (clip.x < orig.x) { clip.width -= (orig.x - clip.x); clip.x = orig.x; } if (clip.x + clip.width > orig.x + orig.width) { clip.width = orig.x + orig.width - clip.x; } if (clip.y > orig.y) { clip.height -= (clip.y - orig.y); clip.y = orig.y; } if (clip.y - clip.height < orig.y - orig.height) { clip.height = clip.y - orig.y + orig.height; } } if (for_layer) { tr_state->layer_clipper = clip; tr_state->has_layer_clip = GF_TRUE; #ifndef GPAC_DISABLE_3D if (tr_state->visual->type_3d) { gf_mx_copy(tr_state->layer_matrix, tr_state->model_matrix); } #endif } else { tr_state->clipper = clip; #ifndef GPAC_DISABLE_3D if (tr_state->visual->type_3d) { /*retranslate to world coords*/ gf_mx_apply_rect(&tr_state->model_matrix, &tr_state->clipper); /*if 2D, also update with user zoom and translation*/ if (!tr_state->camera->is_3D) gf_mx_apply_rect(&tr_state->camera->modelview, &tr_state->clipper); } else #endif gf_mx2d_apply_rect(&tr_state->transform, &tr_state->clipper); tr_state->has_clip = GF_TRUE; } return clip; } /*overlay management*/ Bool visual_2d_overlaps_overlay(GF_VisualManager *visual, DrawableContext *ctx, GF_TraverseState *tr_state) { u32 res = 0; GF_OverlayStack *ol; GF_Compositor *compositor = visual->compositor; if (compositor->visual != visual) return GF_FALSE; ol = visual->overlays; while (ol) { u32 i; GF_IRect clip; if (ctx == ol->ctx) { ol = ol->next; continue; } clip = ctx->bi->clip; if (!ol->ra.count && !gf_irect_overlaps(&ol->ctx->bi->clip, &clip)) { ol = ol->next; continue; } /*check previsously drawn areas*/ for (i=0; i<ol->ra.count; i++) { /*we have drawn something here, don't draw*/ if (gf_irect_inside(&ol->ra.list[i].rect, &clip)) break; } res++; if (i<ol->ra.count) { ol = ol->next; continue; } /*note that we add the entire cliper, not the intersection with the overlay one. This is a simple way to handle the case where Drawble2 overlaps Drawable1 overlaps Overlay but Drawable2 doesn't overlaps Overlay by adding the entire drawable cliper, we will postpone drawing of all interconnected regions touching the overlay*/ ra_union_rect(&ol->ra, &clip); ol = ol->next; } return res ? GF_TRUE : GF_FALSE; } void visual_2d_flush_overlay_areas(GF_VisualManager *visual, GF_TraverseState *tr_state) { DrawableContext *ctx; GF_OverlayStack *ol; GF_Compositor *compositor = visual->compositor; if (compositor->visual != visual) return; /*draw all overlays*/ tr_state->traversing_mode = TRAVERSE_DRAW_2D; ol = visual->overlays; while (ol) { u32 i; Bool needs_draw = GF_TRUE; GF_IRect the_clip, vid_clip; ra_refresh(&ol->ra); for (i=0; i<ol->ra.count; i++) { the_clip = ol->ra.list[i].rect; /*draw all objects above this overlay*/ ctx = ol->ctx->next; while (ctx && ctx->drawable) { if (gf_irect_overlaps(&ctx->bi->clip, &the_clip)) { GF_IRect prev_clip = ctx->bi->clip; if (needs_draw) { /*if first object above is not transparent and completely covers the overlay skip video redraw*/ if ((ctx->flags & CTX_IS_TRANSPARENT) || !gf_irect_inside(&prev_clip, &the_clip)) { vid_clip = ol->ra.list[i].rect; gf_irect_intersect(&vid_clip, &ol->ctx->bi->clip); compositor_2d_draw_bitmap_ex(visual, ol->ctx->aspect.fill_texture, ol->ctx, &vid_clip, &ol->ctx->bi->unclip, 0xFF, tr_state, GF_TRUE); } needs_draw = GF_FALSE; } gf_irect_intersect(&ctx->bi->clip, &the_clip); tr_state->ctx = ctx; if (ctx->drawable->flags & DRAWABLE_USE_TRAVERSE_DRAW) { gf_node_traverse(ctx->drawable->node, tr_state); } else { drawable_draw(ctx->drawable, tr_state); } ctx->bi->clip = prev_clip; } ctx = ctx->next; } } ol = ol->next; } } void visual_2d_draw_overlays(GF_VisualManager *visual) { GF_Err e; GF_TextureHandler *txh; GF_VideoSurface video_src; while (1) { GF_OverlayStack *ol = visual->overlays; if (!ol) return; visual->overlays = ol->next; txh = ol->ctx->aspect.fill_texture; memset(&video_src, 0, sizeof(GF_VideoSurface)); video_src.height = txh->height; video_src.width = txh->width; video_src.pitch_x = 0; video_src.pitch_y = txh->stride; video_src.pixel_format = txh->pixelformat; video_src.video_buffer = txh->data; e = visual->compositor->video_out->Blit(visual->compositor->video_out, &video_src, &ol->src, &ol->dst, 2); if (e) GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Visual2D] Error %s during overlay update\n", gf_error_to_string(e) )); ra_del(&ol->ra); gf_free(ol); } } void compositor_2d_init_callbacks(GF_Compositor *compositor) { compositor->visual->DrawBitmap = compositor_2d_draw_bitmap; if (compositor->video_out->hw_caps & GF_VIDEO_HW_HAS_LINE_BLIT) { compositor->raster_callbacks.cbk = compositor->video_out; compositor->raster_callbacks.fill_run_alpha = (raster_cbk_fill_run_alpha) compositor->video_out->DrawHLineAlpha; compositor->raster_callbacks.fill_run_no_alpha = (raster_cbk_fill_run_no_alpha) compositor->video_out->DrawHLine; compositor->raster_callbacks.fill_rect = (raster_cbk_fill_rect) compositor->video_out->DrawRectangle; } }
lgpl-2.1
looooo/netgen
libsrc/interface/writeOpenFOAM15x.cpp
1
27648
/*! \file writeOpenFOAM15x.cpp * \brief Export Netgen Mesh in the OpenFOAM 1.5+ File format * \author Philippose Rajan * \date 25 October 2009 * * This function extends the export capabilities of * Netgen to include the OpenFOAM 1.5+ File Format. * * The OpenFOAM 1.5+ mesh format consists of a set of 5 files * which together define the mesh points, faces, cells and * boundary conditions. * * The files are: * 1. points -> A list of the point co-ordinates * 2. faces -> A list of the faces with format <n>(pnt_ind1 pnt_ind2 .... pnt_ind<n>) * 3. owner -> The owner cell of each face * 4. neighbour -> The neighbour cell of each face * 5. boundary -> The set of boundaries with name, start face, and num. of faces * * For a detailed description of the format, refer to the following link: * http://openfoamwiki.net/index.php/Write_OpenFOAM_meshes * */ #include <mystdlib.h> #include <myadt.hpp> #include <linalg.hpp> #include <csg.hpp> #include <meshing.hpp> #include <sys/stat.h> namespace netgen { #include "writeuser.hpp" extern MeshingParameters mparam; // Global arrays used to maintain the owner, neighbour and face lists // so that they are accessible across functions static Array<int> owner_facelist; static Array<int> owner_celllist; static Array<int> neighbour_celllist; static Array<int> surfelem_bclist; static Array<INDEX_2> surfelem_lists; static void WriteOpenFOAM15xBanner(ostream * outfile) { static char FOAMversion[4] = "1.5"; static char spaces[40]; memset(spaces, ' ', 40); spaces[38 - strlen(FOAMversion)] = '\0'; *outfile << "/*--------------------------------*- C++ -*----------------------------------*\\\n"; *outfile << "| ========= | |\n" "| \\\\ / F ield | OpenFOAM: The Open Source CFD Toolbox |\n" "| \\\\ / O peration | Version: " << FOAMversion << spaces << "|\n" "| \\\\ / A nd | Web: http://www.OpenFOAM.org |\n" "| \\\\/ M anipulation | |\n" "\\*---------------------------------------------------------------------------*/\n"; } static void WriteOpenFOAM15xDividerStart(ostream * outfile) { *outfile << "// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n"; } static void WriteOpenFOAM15xDividerEnd(ostream * outfile) { *outfile << "// ************************************************************************* //\n"; } static bool BuildOwnerNeighbourLists (const Mesh & mesh) { // Clear all the arrays owner_facelist.DeleteAll(); owner_celllist.DeleteAll(); neighbour_celllist.DeleteAll(); surfelem_bclist.DeleteAll(); surfelem_lists.DeleteAll(); const MeshTopology& meshtopo = mesh.GetTopology(); // Update the mesh topology structures const_cast<MeshTopology&> (meshtopo).SetBuildEdges(true); const_cast<MeshTopology&> (meshtopo).SetBuildFaces(true); const_cast<MeshTopology&> (meshtopo).Update(); // Extract important mesh metrics int ne = mesh.GetNE(); int nse = mesh.GetNSE(); int totfaces = meshtopo.GetNFaces(); // Preset the size of the arrays to speed up future operations // Number of internal faces = total faces - num. of surface faces owner_facelist.SetSize(totfaces - nse); owner_celllist.SetSize(totfaces - nse); neighbour_celllist.SetSize(totfaces - nse); surfelem_bclist.SetSize(nse); surfelem_lists.SetSize(nse); // Initialise arrays to zero if required neighbour_celllist = 0; // Array used to keep track of Faces which have already been // processed and added to the Owner list... In addition, also the // location where the face appears in the Owner list is also stored // to speed up creation of the Neighbour list Array<int> ownerfaces(totfaces); ownerfaces = 0; // Array to hold the set of local faces of each volume element // while running through the set of volume elements // NOTE: The size is set automatically by the Netgen topology function Array<int> locfaces; // Secondary indices used to independently advance the owner // and boundary condition arrays within the main loop int owner_ind = 1; int bc_ind = 1; // Loop through all the volume elements for(int elind = 1; elind <= ne; elind++) { // Extract the current volume element // const Element & el = mesh.VolumeElement(elind); // Get the face numbers of the faces of the current volume element // The values returned are given a sign depending on the orientation // of the faces. This is used while writing the faces file, to // determine whether or not to invert the face triangle before writing // it to file meshtopo.GetElementFaces(elind,locfaces,true); // Loop through the faces for(int i = 1; i <= locfaces.Size(); i++) { // The absolute value of a face number (because the faces // returned by the GetElementFaces function prepend it // with a sign depending on the face orientation) int absfacenr = abs(locfaces.Elem(i)); // If the face already exists in the owner list, add // the current cell into the neighbour list, in the // same location where the face appears in the owner list int owner_face = ownerfaces.Elem(absfacenr); if(owner_face) { neighbour_celllist.Elem(owner_face) = elind; // From this point on, the code within this "if" block // basically sorts the order of the Neighbour cells (along // with the faces list) in ascending order. // The approach used is..... to traverse the owner and neighbour cell lists // up and down, and sort the neighbour cells of a given owner cell // as the list evolves. // NOTE: A value of "zero" in the neighbour list implies that // the neighbour has not been found yet, so the "zero" locations need // to be skipped while sorting in ascending order int curr_owner = owner_celllist.Elem(owner_face); int peek_loc = owner_face - 1; int new_loc = owner_face; // Traversing upwards in the list while((owner_celllist.Elem(peek_loc) == curr_owner) && (peek_loc >= 1)) { if((neighbour_celllist.Elem(peek_loc) != 0) && (neighbour_celllist.Elem(new_loc) < neighbour_celllist.Elem(peek_loc))) { Swap(neighbour_celllist.Elem(new_loc),neighbour_celllist.Elem(peek_loc)); Swap(owner_facelist.Elem(new_loc),owner_facelist.Elem(peek_loc)); new_loc = peek_loc; } peek_loc--; } peek_loc = owner_face + 1; // Traversing downwards in the list while((owner_celllist.Elem(peek_loc) == curr_owner) && (peek_loc <= owner_ind)) { if((neighbour_celllist.Elem(peek_loc) != 0) && (neighbour_celllist.Elem(new_loc) > neighbour_celllist.Elem(peek_loc))) { Swap(neighbour_celllist.Elem(new_loc),neighbour_celllist.Elem(peek_loc)); Swap(owner_facelist.Elem(new_loc),owner_facelist.Elem(peek_loc)); new_loc = peek_loc; } peek_loc++; } continue; } // Check if the face is a surface element (boundary face) // if not, add the current volume element and the corresponding face into // the owner list int surfelem = meshtopo.GetFace2SurfaceElement(absfacenr); if(!surfelem) { // If it is a new face which has not been listed before, // add the current cell into the owner list, and save // the index location to be used later by the neighbour list owner_celllist.Elem(owner_ind) = elind; owner_facelist.Elem(owner_ind) = locfaces.Elem(i); // Update the array to indicate that the face is already processed ownerfaces.Elem(absfacenr) = owner_ind; owner_ind++; } // If the face is a boundary face, extract the boundary condition number of the // face, and append that along with the face number and the current cell // into the various surface elements lists else { Element2d sel = mesh.SurfaceElement(surfelem); surfelem_bclist.Elem(bc_ind) = mesh.GetFaceDescriptor(sel.GetIndex()).BCProperty(); surfelem_lists.Elem(bc_ind) = INDEX_2(locfaces.Elem(i),elind); bc_ind++; } } } // This correction is required in cases where the mesh has been "uniform refined".... for // some reason, the number of faces reported by Netgen is higher than the actual number // of faces in the mesh owner_facelist.SetSize(owner_ind-1); owner_celllist.SetSize(owner_ind-1); neighbour_celllist.SetSize(owner_ind-1); // Sort the list of surface elements in ascending order of boundary condition number // also sort the cell list in the same manner QuickSort(surfelem_bclist,surfelem_lists); /* // Debugging output to a file ofstream dbg("OpenFOAMDebug.log"); dbg << " ------- Boundary List -------- \n"; for(int i = 1; i <= surfelem_bclist.Size(); i++) { dbg << "bc = " << surfelem_bclist.Elem(i) << " : face = " << surfelem_lists.Elem(i).I1() << " : cell = " << surfelem_lists.Elem(i).I2() << "\n"; } dbg << "\n ------- Owner / Face / Neighbour List ------- \n"; for(int i = 1; i <= owner_celllist.Size(); i++) { dbg << "Ind:" << i << " :: (" << owner_celllist.Elem(i) << " " << owner_facelist.Elem(i) << " " << neighbour_celllist.Elem(i) << ")\n"; } dbg.close(); */ return(false); } static void WriteNeighbourFile (ostream * outfile) { // Write the OpenFOAM standard banner and dividers, etc... WriteOpenFOAM15xBanner(outfile); *outfile << "FoamFile \n" << "{ \n" << " version 2.0; \n" << " format ascii; \n" << " class labelList; \n" << " note \"Mesh generated and converted using NETGEN-" << PACKAGE_VERSION << "\"; \n" << " location \"constant\\polyMesh\"; \n" << " object neighbour; \n" << "} \n"; WriteOpenFOAM15xDividerStart(outfile); *outfile << "\n\n"; int nneighbours = neighbour_celllist.Size(); *outfile << nneighbours << "\n"; *outfile << "(\n"; // Write the neighbour cells to file for(int i = 1; i <= neighbour_celllist.Size(); i++) { *outfile << neighbour_celllist.Elem(i) - 1 << "\n"; } *outfile << ")\n\n"; WriteOpenFOAM15xDividerEnd(outfile); } static void WriteOwnerFile (ostream * outfile) { // Write the OpenFOAM standard banner and dividers, etc... WriteOpenFOAM15xBanner(outfile); *outfile << "FoamFile \n" << "{ \n" << " version 2.0; \n" << " format ascii; \n" << " class labelList; \n" << " note \"Mesh generated and converted using NETGEN-" << PACKAGE_VERSION << "\"; \n" << " location \"constant\\polyMesh\"; \n" << " object owner; \n" << "} \n"; WriteOpenFOAM15xDividerStart(outfile); *outfile << "\n\n"; int nowners = owner_celllist.Size() + surfelem_lists.Size(); *outfile << nowners << "\n"; *outfile << "(\n"; // Write the owners of the internal cells to file for(int i = 1; i <= owner_celllist.Size(); i++) { *outfile << owner_celllist.Elem(i) - 1 << "\n"; } // Write the owners of the boundary cells to file // (Written in order of ascending boundary condition numbers) for(int i = 1; i <= surfelem_lists.Size(); i++) { *outfile << surfelem_lists.Elem(i).I2() - 1 << "\n"; } *outfile << ")\n\n"; WriteOpenFOAM15xDividerEnd(outfile); } static void WriteFacesFile (ostream * outfile, const Mesh & mesh) { const MeshTopology& meshtopo = mesh.GetTopology(); // Write the OpenFOAM standard banner and dividers, etc... WriteOpenFOAM15xBanner(outfile); *outfile << "FoamFile \n" << "{ \n" << " version 2.0; \n" << " format ascii; \n" << " class faceList; \n" << " note \"Mesh generated and converted using NETGEN-" << PACKAGE_VERSION << "\"; \n" << " location \"constant\\polyMesh\"; \n" << " object faces; \n" << "} \n"; WriteOpenFOAM15xDividerStart(outfile); *outfile << "\n\n"; int nfaces = owner_facelist.Size() + surfelem_lists.Size(); *outfile << nfaces << "\n"; *outfile << "(\n"; // Array to hold the indices of the points of each face to // flip if required Array<int> facepnts; // Write the faces in the order specified in the owners lists of the // internal cells and the boundary cells for(int i = 1; i <= owner_facelist.Size(); i++) { int face_w_orientation = owner_facelist.Elem(i); int facenr = abs(face_w_orientation); meshtopo.GetFaceVertices(facenr,facepnts); // Get the orientation of the face, and invert it if required // Since the faces already have the orientation "embedded" into // them by means of the prepended sign, only this needs to be // checked for... if(face_w_orientation > 0) { int tmppnts = 0; if(facepnts.Size() == 4) { tmppnts = facepnts.Elem(1); facepnts.Elem(1) = facepnts.Elem(2); facepnts.Elem(2) = tmppnts; tmppnts = facepnts.Elem(3); facepnts.Elem(3) = facepnts.Elem(4); facepnts.Elem(4) = tmppnts; } else if(facepnts.Size() == 3) { tmppnts = facepnts.Elem(1); facepnts.Elem(1) = facepnts.Elem(3); facepnts.Elem(3) = tmppnts; } } *outfile << facepnts.Size(); *outfile << "("; for(int j = 1; j <= facepnts.Size(); j++) { *outfile << facepnts.Elem(j)-1; if(j != facepnts.Size()) *outfile << " "; } *outfile << ")\n"; } // Now append the faces of the surface elements (written in // ascending order of boundary condition number) also into // the faces file for(int i = 1; i <= surfelem_lists.Size(); i++) { int face_w_orientation = surfelem_lists.Elem(i).I1(); int facenr = abs(face_w_orientation); meshtopo.GetFaceVertices(facenr,facepnts); // Get the orientation of the face, and invert it if required if(face_w_orientation > 0) { int tmppnts = 0; if(facepnts.Size() == 4) { tmppnts = facepnts.Elem(1); facepnts.Elem(1) = facepnts.Elem(2); facepnts.Elem(2) = tmppnts; tmppnts = facepnts.Elem(3); facepnts.Elem(3) = facepnts.Elem(4); facepnts.Elem(4) = tmppnts; } else if(facepnts.Size() == 3) { tmppnts = facepnts.Elem(1); facepnts.Elem(1) = facepnts.Elem(3); facepnts.Elem(3) = tmppnts; } } *outfile << facepnts.Size(); *outfile << "("; for(int j = 1; j <= facepnts.Size(); j++) { *outfile << facepnts.Elem(j)-1; if(j != facepnts.Size()) *outfile << " "; } *outfile << ")\n"; } *outfile << ")\n\n"; WriteOpenFOAM15xDividerEnd(outfile); } static void WritePointsFile (ostream * outfile, const Mesh & mesh) { int np = mesh.GetNP(); // Write the OpenFOAM standard banner and dividers, etc... WriteOpenFOAM15xBanner(outfile); *outfile << "FoamFile \n" << "{ \n" << " version 2.0; \n" << " format ascii; \n" << " class vectorField; \n" << " note \"Mesh generated and converted using NETGEN-" << PACKAGE_VERSION << "\"; \n" << " location \"constant\\polyMesh\"; \n" << " object points; \n" << "} \n"; WriteOpenFOAM15xDividerStart(outfile); *outfile << "\n\n"; // Number of points in the following list *outfile << np << "\n"; outfile->precision(6); outfile->setf (ios::fixed, ios::floatfield); outfile->setf (ios::showpoint); // Coordinate list starts here *outfile << "(\n"; for(int i = 1; i <= np; i++) { const Point3d & p = mesh.Point(i); // Write coordinates to file *outfile << "("; *outfile << p.X() << " "; *outfile << p.Y() << " "; *outfile << p.Z(); *outfile << ")\n"; } *outfile << ")\n\n"; WriteOpenFOAM15xDividerEnd(outfile); } static void WriteBoundaryFile (ostream * outfile) { // Write the OpenFOAM standard banner and dividers, etc... WriteOpenFOAM15xBanner(outfile); *outfile << "FoamFile \n" << "{ \n" << " version 2.0; \n" << " format ascii; \n" << " class polyBoundaryMesh; \n" << " note \"Mesh generated and converted using NETGEN-" << PACKAGE_VERSION << "\"; \n" << " location \"constant\\polyMesh\"; \n" << " object boundary; \n" << "} \n"; WriteOpenFOAM15xDividerStart(outfile); *outfile << "\n"; Array<INDEX_3> bcarray; int ind = 1; // Since the boundary conditions are already sorted in ascending // order, the last element will give the maximum number of possible // boundary condition entries int bcmax = surfelem_bclist.Elem(surfelem_bclist.Size()); bcarray.SetSize(bcmax+1); bcarray.Elem(ind) = INDEX_3(surfelem_bclist.Elem(1),1,0); for(int i = 2; i <= surfelem_bclist.Size(); i++) { if(surfelem_bclist.Elem(i) == bcarray.Elem(ind).I1()) { bcarray.Elem(ind).I2() = bcarray.Elem(ind).I2()+1; } else { ind++; bcarray.Elem(ind) = INDEX_3(surfelem_bclist.Elem(i),1,i-1); } } bcarray.SetSize(ind); *outfile << bcarray.Size() << "\n"; *outfile << "(\n"; int startface = 0; for(int i = 1; i <= bcarray.Size(); i++) { startface = owner_celllist.Size() + bcarray.Elem(i).I3(); *outfile << " patch" << bcarray.Elem(i).I1() << "\n" << " {\n" << " type patch;\n" << " physicalType patch;\n" << " nFaces " << bcarray.Elem(i).I2() << ";\n" << " startFace " << startface << ";\n" << " }\n"; } *outfile << ")\n\n"; WriteOpenFOAM15xDividerEnd(outfile); } void WriteOpenFOAM15xFormat (const Mesh & mesh, const string & casename, const bool compressed) { bool error = false; char casefiles[256]; // Make sure that the mesh data has been updated const_cast<Mesh&> (mesh).Compress(); const_cast<Mesh&> (mesh).CalcSurfacesOfNode(); const_cast<Mesh&> (mesh).RebuildSurfaceElementLists(); const_cast<Mesh&> (mesh).BuildElementSearchTree(); int np = mesh.GetNP(); int nse = mesh.GetNSE(); int ne = mesh.GetNE(); cout << "Write OpenFOAM 1.5+ Mesh Files....\n"; // Abort if there are no points, surface elements or volume elements if((np <= 0) || (ne <= 0) || (nse <= 0)) { cout << "Export Error: Invalid mesh.... Aborting!\n"; return; } // OpenFOAM only supports linear meshes! if(mparam.secondorder || mesh.GetCurvedElements().IsHighOrder()) { cout << "Export Error: OpenFOAM 1.5+ does not support non-linear elements.... Aborting!\n"; return; } if(( (mesh.SurfaceElement(nse/2).GetType() != TRIG) && (mesh.SurfaceElement(nse/2).GetType() != QUAD) ) || (mesh.VolumeElement(ne/2).GetType() == TET10) || (mesh.VolumeElement(ne/2).GetType() == PRISM12)) { cout << "Export Error: OpenFOAM 1.5+ does not support non-linear elements.... Aborting!\n"; return; } cout << "Writing OpenFOAM 1.5+ Mesh files to case: " << casename << "\n"; // Create the case directory if it does not already exist // NOTE: This needs to be improved for the Linux variant....!!! #ifdef WIN32 char casedir[256]; sprintf(casedir, "mkdir %s\\constant\\polyMesh", casename.c_str()); system(casedir); #else char casedir[256]; mkdir(casename.c_str(), S_IRWXU|S_IRWXG); sprintf(casedir, "%s/constant", casename.c_str()); mkdir(casedir, S_IRWXU|S_IRWXG); sprintf(casedir, "%s/constant/polyMesh", casename.c_str()); mkdir(casedir, S_IRWXU|S_IRWXG); #endif // Open handles to the five required mesh files // points // faces // owner // neighbour // boundary ostream *outfile_pnts; ostream *outfile_faces; ostream *outfile_own; ostream *outfile_nei; ostream *outfile_bnd; if(compressed) { sprintf(casefiles, "%s/constant/polyMesh/points.gz", casename.c_str()); outfile_pnts = new ogzstream(casefiles); } else { sprintf(casefiles, "%s/constant/polyMesh/points", casename.c_str()); outfile_pnts = new ofstream(casefiles); } if(compressed) { sprintf(casefiles, "%s/constant/polyMesh/faces.gz", casename.c_str()); outfile_faces = new ogzstream(casefiles); } else { sprintf(casefiles, "%s/constant/polyMesh/faces", casename.c_str()); outfile_faces = new ofstream(casefiles); } if(compressed) { sprintf(casefiles, "%s/constant/polyMesh/owner.gz", casename.c_str()); outfile_own = new ogzstream(casefiles); } else { sprintf(casefiles, "%s/constant/polyMesh/owner", casename.c_str()); outfile_own = new ofstream(casefiles); } if(compressed) { sprintf(casefiles, "%s/constant/polyMesh/neighbour.gz", casename.c_str()); outfile_nei = new ogzstream(casefiles); } else { sprintf(casefiles, "%s/constant/polyMesh/neighbour", casename.c_str()); outfile_nei = new ofstream(casefiles); } // Note... the boundary file is not compressed sprintf(casefiles, "%s/constant/polyMesh/boundary", casename.c_str()); outfile_bnd = new ofstream(casefiles); ResetTime(); // Build the owner, neighbour, faces and boundary lists // from the Netgen mesh cout << "\nBuilding Owner, Neighbour and Face Lists: "; error = BuildOwnerNeighbourLists(mesh); cout << "Done! (Time Elapsed = " << GetTime() << " sec)\n"; // Write the "owner" file if(outfile_own->good() && !error) { cout << "Writing the owner file: "; WriteOwnerFile(outfile_own); delete outfile_own; cout << "Done! (Time Elapsed = " << GetTime() << " sec)\n"; } else { cout << "Export Error: Error creating file: owner.... Aborting\n"; error = true; } // Write the "neighbour" file if(outfile_nei->good() && !error) { cout << "Writing the neighbour file: "; WriteNeighbourFile(outfile_nei); delete outfile_nei; cout << "Done! (Time Elapsed = " << GetTime() << " sec)\n"; } else { cout << "Export Error: Error creating file: neighbour.... Aborting\n"; error = true; } // Write the "faces" file if(outfile_faces->good() && !error) { cout << "Writing the faces file: "; WriteFacesFile(outfile_faces, mesh); delete outfile_faces; cout << "Done! (Time Elapsed = " << GetTime() << " sec)\n"; } else { cout << "Export Error: Error creating file: faces.... Aborting\n"; error = true; } // Write the "points" file if(outfile_pnts->good() && !error) { cout << "Writing the points file: "; WritePointsFile(outfile_pnts,mesh); delete outfile_pnts; cout << "Done! (Time Elapsed = " << GetTime() << " sec)\n"; } else { cout << "Export Error: Error creating file: points.... Aborting\n"; error = true; } // Write the "boundary" file if(outfile_bnd->good() && !error) { cout << "Writing the boundary file: "; WriteBoundaryFile(outfile_bnd); delete outfile_bnd; cout << "Done! (Time Elapsed = " << GetTime() << " sec)\n"; } else { cout << "Export Error: Error creating file: boundary.... Aborting\n"; error = true; } if(!error) { cout << "OpenFOAM 1.5+ Export successfully completed (Time elapsed = " << GetTime() << " sec) !\n"; } else { cout << "Error in OpenFOAM 1.5+ Export.... Aborted!\n"; } } }
lgpl-2.1
stden/drmemory
drheapstat/drheapstat.c
1
78045
/* ********************************************************** * Copyright (c) 2010-2012 Google, Inc. All rights reserved. * Copyright (c) 2009-2010 VMware, Inc. All rights reserved. * **********************************************************/ /* Dr. Memory: the memory debugger * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License, and no later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /*************************************************************************** * Dr. Heapstat heap profiler */ #include "dr_api.h" #include "drwrap.h" #include "drheapstat.h" #include "alloc.h" #include "heap.h" #include "callstack.h" #include "crypto.h" #include "staleness.h" #include "../drmemory/leak.h" #include "../drmemory/stack.h" #include "../drmemory/shadow.h" #include "../drmemory/readwrite.h" #ifdef LINUX # include "sysnum_linux.h" # include <errno.h> # define _GNU_SOURCE /* for sched.h */ # include <linux/sched.h> /* for CLONE_VM */ # include <sys/time.h> # include <signal.h> /* for SIGSEGV */ #endif #include <stddef.h> /* for offsetof */ #ifdef USE_MD5 # define IF_MD5_ELSE(x, y) x #else # define IF_MD5_ELSE(x, y) y #endif /* for sharing data among instrumentation passes */ typedef struct _instru_info_t { bb_info_t bi; instr_t *where_dead; bool flags_dead; uint instrs_in_bb; } instru_info_t; char logsubdir[MAXIMUM_PATH]; file_t f_callstack = INVALID_FILE; file_t f_snapshot = INVALID_FILE; file_t f_staleness = INVALID_FILE; file_t f_nudge = INVALID_FILE; /* PR 502468 - nudge visualization */ static uint num_threads; /* Counters for time unit intervals */ static int instr_count; static int byte_count; static int allocfree_count; /* For -time_clock, the frequency is -dump_freq*10 milliseconds */ #define TIME_BASE_FREQ 10 /* These are all in milliseconds */ static uint timer_clock; static uint timer_stale; static uint timer_real; /* Needed to compute the current partial snapshot (PR 548013) */ uint64 timestamp_last_snapshot; static bool sideline_exit; /* FIXME i#297: DR synchs + terminates our sideline thread prior to * calling our exit event so we have no chance to clean up its memory. * DR then asserts about leaks. Using a targeted solution for now. */ static tls_util_t *sideline_pt; static int leak_count; static int reachable_leak_count; /* To avoid the code expansion from a clean call in every bb we use * a shared clean call sequence, entering it with a direct jump * and exiting with an indirect jump to a stored return point. */ static byte *shared_instrcnt_callout; static byte *shared_code_region; #define SHARED_CODE_SIZE \ (PAGE_SIZE + (options.staleness ? (SHARED_SLOWPATH_SIZE) : 0)) /* We serialize snapshots since rare so not costly perf-wise, and this avoids * needing potentially very large buffers to try and get atomic writes */ static void *snapshot_lock; /* We intercept libc/ntdll allocation routines instead of providing our * own, for maximum transparency. Both use 8-byte (for 32-bit) headers. * FIXME: for 64-bit Windows, 8-byte-or-smaller allocs have special headers * that are only 8 bytes instead of 16? */ #ifdef LINUX /* FIXME: mmap chunks have 2*size headers (xref PR 474912) */ # define HEADER_SIZE sizeof(size_t) #else # define HEADER_SIZE 2*sizeof(size_t) #endif static void reset_clock_timer(void); static void reset_real_timer(void); static void event_thread_exit(void *drcontext); #ifdef STATISTICS static void dump_statistics(void); # define STATS_DUMP_FREQ 10000 uint alloc_stack_count; static uint peaks_detected; static uint peaks_skipped; #endif /* PR 465174: share allocation site callstacks. * This table should only be accessed while holding the lock for * malloc_table (via malloc_lock()), which makes the coordinated * operations with malloc_table atomic. */ #define ASTACK_TABLE_HASH_BITS 8 static hashtable_t alloc_stack_table; #ifdef CHECK_WITH_MD5 /* Used to check collisions with crc32 */ static hashtable_t alloc_md5_table; #endif /*************************************************************************** * TLS and CLS */ typedef struct _tls_heapstat_t { char *errbuf; /* buffer for atomic writes */ size_t errbufsz; # ifdef LINUX int64 filepos; /* f_callstack file position */ # endif } tls_heapstat_t; /* XXX: share w/ syscall_os.h */ #ifdef WINDOWS # define SYSCALL_NUM_ARG_STORE 14 #else # define SYSCALL_NUM_ARG_STORE 6 /* 6 is max on Linux */ #endif typedef struct _cls_heapstat_t { /* for recording args so post-syscall can examine */ reg_t sysarg[SYSCALL_NUM_ARG_STORE]; } cls_heapstat_t; static int tls_idx_heapstat = -1; static int cls_idx_heapstat = -1; /*************************************************************************** * OPTIONS */ static void reset_intervals(void) { if (options.dump) { options.snapshots = 1; } else { options.dump_freq = 1; } /* Instr threshold is per 1k, so a max of 2 trillion instrs. * We could support more and still do 32-bit inlined arith by * having the callout do a mod. */ if (options.time_instrs) { if (options.dump_freq > UINT_MAX/1000) usage_error("-dump_freq: value too large", ""); options.dump_freq *= 1000; /* We count backward */ instr_count = options.dump_freq; } else if (options.time_bytes) { if (!options.dump) { /* only *8 if doing const # snapshots. this is invisible * to user so no need to talk about in docs: just makes * initial snapshots more reasonable than starting at 1. */ ASSERT(options.dump_freq == 1, "invalid assumption"); options.dump_freq = 8; } /* We count backward */ byte_count = options.dump_freq; } else if (options.time_allocs) { /* We count backward */ allocfree_count = options.dump_freq; } } static void drheap_options_init(const char *opstr) { options_init(opstr); reset_intervals(); /* set globals */ op_print_stderr = options.stderr; op_verbose_level = options.verbose; op_pause_at_assert = options.pause_at_assert; op_pause_via_loop = options.pause_via_loop; op_ignore_asserts = options.ignore_asserts; } /*************************************************************************** * EVENTS FOR COMMON/ALLOC.C */ /* Snapshot arrays: of size options.snapshots. For !options.dump, * when the arrays fill, we double the options.dump_freq frequency and * then replace snapshots that would not have existed if the * frequency had been the double one from the beginning. */ static uint snap_idx; static uint snap_fills; /* We keep a linked list of these structs per snapshot. * One struct per callstack that has non-zero usage in that snapshot. * This can save a lot of memory versus arrays when there are * many callstacks and few are present in all snapshots. * Xref PR 493134. */ typedef struct _heap_used_t { /* FIXME: 64-bit? */ uint instances; uint bytes_asked_for; ushort extra_usable; /* beyond bytes_asked_for */ ushort extra_occupied; /* beyond bytes_asked_for + extra_usable */ struct _heap_used_t *next; per_callstack_t *callstack; } heap_used_t; /* Arrays of snapshots. Not using a heap_used_t b/c we need larger counters. */ typedef struct _per_snapshot_t { uint64 stamp; uint64 tot_mallocs; uint64 tot_bytes_asked_for; uint64 tot_bytes_usable; uint64 tot_bytes_occupied; /* Linked list of non-zero usage per callstack */ heap_used_t *used; /* Staleness data: array with one entry per live malloc */ stale_snap_allocs_t *stale; } per_snapshot_t; static uint64 stamp; /* Used for starting time 0 in middle of run (post-nudge usually) */ static uint64 stamp_offs; static per_snapshot_t *snaps; /* peak snapshot (PR 476018) */ static per_snapshot_t snap_peak; /* track changes in # allocs+frees for PR 566116 */ static uint64 allocfree_cur, allocfree_last_peak; #define SNAPSHOT_LOG_BUF_SIZE (32*1024) static char snaps_log_buf[SNAPSHOT_LOG_BUF_SIZE]; /* PR 551841 */ struct _per_callstack_t { uint id; #if defined(USE_MD5) || defined(CHECK_WITH_MD5) /* PR 496304: we keep just the md5 to save memory. We either do so * instead of crc32, or in addition as a debug check on collisions. */ byte md5[MD5_RAW_BYTES]; #endif #ifndef USE_MD5 /* PR 496304: we keep just a checksum to save memory. Since crc32 could * collide we use crc32 of the whole callstack plus a separate crc32 * of the first half of the callstack. */ uint crc[2]; #endif /* for the current snapshot */ heap_used_t *used; /* for node removal w/o keeping a prev per heap_used_t per snapshot */ heap_used_t *prev_used; }; static uint num_callstacks; static uint snapshot_count; static uint nudge_count; uint get_cstack_id(per_callstack_t *per) { return per->id; } static inline per_callstack_t * get_cstack_from_alloc_data(void *client_data) { /* We store either per_callstack_t or stale_per_alloc_t in the * client_data slot in each malloc */ if (options.staleness) return ((stale_per_alloc_t *)client_data)->cstack; else return (per_callstack_t *) client_data; } void client_exit_iter_chunk(app_pc start, app_pc end, bool pre_us, uint client_flags, void *client_data) { if (options.check_leaks) leak_exit_iter_chunk(start, end, pre_us, client_flags, client_data); if (options.staleness) staleness_free_per_alloc((stale_per_alloc_t *)client_data); } void alloc_callstack_free(void *p) { per_callstack_t *per = (per_callstack_t *) p; global_free(per, sizeof(*per), HEAPSTAT_CALLSTACK); } void client_malloc_data_free(void *data) { /* nothing to do since we persist our callstacks in alloc_stack_table */ } void * client_malloc_data_to_free_list(void *cur_data, dr_mcontext_t *mc, app_pc post_call) { /* nothing to do since we persist our callstacks in alloc_stack_table */ return cur_data; } static void get_buffer(void *drcontext, char **buf/*OUT*/, size_t *bufsz/*OUT*/) { tls_heapstat_t *pt = (tls_heapstat_t *) drmgr_get_tls_field(drcontext, tls_idx_heapstat); ASSERT(buf != NULL && bufsz != NULL, "invalid args"); if (pt == NULL) { /* at init time no pt yet */ *bufsz = MAX_ERROR_INITIAL_LINES + max_callstack_size(); *buf = (char *) global_alloc(*bufsz, HEAPSTAT_CALLSTACK); } else { *buf = pt->errbuf; *bufsz = pt->errbufsz; } } static void release_buffer(void *drcontext, char *buf, size_t bufsz) { tls_heapstat_t *pt = (tls_heapstat_t *) drmgr_get_tls_field(drcontext, tls_idx_heapstat); if (pt == NULL) { global_free(buf, bufsz, HEAPSTAT_CALLSTACK); } } static const char * unit_name(void) { if (options.time_instrs) return "instrs"; if (options.time_allocs) return "mallocs"; if (options.time_bytes) return "bytes"; if (options.time_clock) return "ticks (10ms each)"; return "<error>"; } /* Up to caller to synchronize */ static void dump_snapshot(per_snapshot_t *snap, int idx/*-1 means peak*/) { heap_used_t *u; size_t sofar = 0; ssize_t len = 0; LOG(2, "dumping snapshot idx=%d count=%"INT64_FORMAT"u\n", idx, snap->stamp); dr_fprintf(f_snapshot, "SNAPSHOT #%4d @ %16"INT64_FORMAT"u %s\n", snapshot_count, snap->stamp + stamp_offs, unit_name()); dr_fprintf(f_snapshot, "idx=%d, stamp_offs=%16"INT64_FORMAT"u\n", idx, stamp_offs); dr_fprintf(f_snapshot, "total: %"INT64_FORMAT"u,%"INT64_FORMAT"u,%" INT64_FORMAT"u,%"INT64_FORMAT"u\n", snap->tot_mallocs, snap->tot_bytes_asked_for, snap->tot_bytes_usable, snap->tot_bytes_occupied); for (u = snap->used; u != NULL; u = u->next) { if (u->bytes_asked_for + u->extra_usable > 0) { /* PR 551841: buffer snapshot output else performance is bad. */ BUFFERED_WRITE(f_snapshot, snaps_log_buf, SNAPSHOT_LOG_BUF_SIZE, sofar, len, "%u,%u,%u,%u,%u\n", u->callstack->id, u->instances, u->bytes_asked_for, u->extra_usable, u->extra_occupied); } } FLUSH_BUFFER(f_snapshot, snaps_log_buf, sofar); if (options.staleness) { uint i; dr_fprintf(f_staleness, "SNAPSHOT #%4d @ %16"INT64_FORMAT"u %s\n", snapshot_count, snap->stamp + stamp_offs, unit_name()); /* FIXME: optimize by listing cstack id only once; or binary format. * If still too big then collapse similar timestamps and give up * some runtime flexibility in granularity */ sofar = 0; for (i = 0; snap->stale != NULL && i < snap->stale->num_entries; i++) { /* PR 551841: improve perf by printing to buffer to reduce # file writes */ BUFFERED_WRITE(f_staleness, snaps_log_buf, SNAPSHOT_LOG_BUF_SIZE, sofar, len, "%u,%u,%"INT64_FORMAT"u\n", staleness_get_snap_cstack_id(snap->stale, i), staleness_get_snap_bytes(snap->stale, i), staleness_get_snap_last_access(snap->stale, i)); } FLUSH_BUFFER(f_staleness, snaps_log_buf, sofar); } snapshot_count++; } /* Caller must hold snapshot_lock */ static void free_snapshot(per_snapshot_t *snap) { heap_used_t *u, *nxt_u; for (u = snap->used; u != NULL; u = nxt_u) { nxt_u = u->next; global_free(u, sizeof(*u), HEAPSTAT_SNAPSHOT); } snap->used = NULL; if (options.staleness && snap->stale != NULL) { staleness_free_snapshot(snap->stale); snap->stale = NULL; } } /* Caller must hold snapshot_lock. * Calls free_snapshot on dst first. * If new_live is true, dst is the new "live" in-progress snapshot * whose list is where callstack table entries point. */ static void copy_snapshot(per_snapshot_t *dst, per_snapshot_t *src, bool new_live) { heap_used_t *u, *nxt_u, *prev_u; int i; /* Replace the existing list at dst with a clone of * src, and update the callstack table pointers. First * we clear the callstack table pointers in case pointing to * entries not in the new list. */ ASSERT(src != dst, "cannot copy to self"); free_snapshot(dst); memcpy(dst, src, sizeof(*dst)); if (options.staleness) { /* We fill this in at snapshot time */ dst->stale = NULL; } hashtable_lock(&alloc_stack_table); if (new_live) { for (i = 0; i < HASHTABLE_SIZE(alloc_stack_table.table_bits); i++) { hash_entry_t *he; for (he = alloc_stack_table.table[i]; he != NULL; he = he->next) { per_callstack_t *per = (per_callstack_t *) he->payload; per->used = NULL; per->prev_used = NULL; } } } prev_u = NULL; for (u = src->used; u != NULL; u = u->next) { nxt_u = (heap_used_t *) global_alloc(sizeof(*nxt_u), HEAPSTAT_SNAPSHOT); memcpy(nxt_u, u, sizeof(*nxt_u)); if (prev_u == NULL) dst->used = nxt_u; else prev_u->next = nxt_u; if (new_live) { nxt_u->callstack->used = nxt_u; nxt_u->callstack->prev_used = prev_u; } nxt_u->next = NULL; prev_u = nxt_u; } hashtable_unlock(&alloc_stack_table); } static bool difference_exceeds_percent(uint64 new_val, uint64 old_val, uint percent) { /* Avoid floating-point via 100*. Assuming no overflow b/c uint64. */ uint64 diff = (new_val > old_val) ? (new_val - old_val) : (old_val - new_val); return (100 * diff > percent * old_val); } /* If the current snap_idx snapshot is larger than the current peak, * makes a new peak snapshot (PR 476018). * Assumes snapshot lock is held. */ static void check_for_peak(void) { if (snaps[snap_idx].tot_bytes_occupied > snap_peak.tot_bytes_occupied) { /* PR 566116: avoid too-frequent peak snapshots by ignoring if the new * peak is similar to the existing one, both in size and in malloc * makeup. May need to split -peak_threshold into 3 if we need * separate control of each variable. */ if (difference_exceeds_percent(snaps[snap_idx].tot_bytes_occupied, snap_peak.tot_bytes_occupied, options.peak_threshold) || difference_exceeds_percent(allocfree_cur, allocfree_last_peak, snap_peak.tot_bytes_occupied) || /* even if not much different, if it's been a long time, use it */ difference_exceeds_percent(snaps[snap_idx].stamp, snap_peak.stamp, options.peak_threshold)) { STATS_INC(peaks_detected); allocfree_last_peak = allocfree_cur; copy_snapshot(&snap_peak, &snaps[snap_idx], false/*isolated copy*/); if (options.staleness) { /* copy_snapshot called free_snapshot which freed this */ ASSERT(snap_peak.stale == NULL, "invalid staleness data"); snap_peak.stale = staleness_take_snapshot(stamp); } LOG(2, "new peak snapshot, tot occupied=%"INT64_FORMAT"u\n", snap_peak.tot_bytes_occupied); } else { STATS_INC(peaks_skipped); LOG(2, "NOT taking new peak snapshot, tot occupied=%"INT64_FORMAT"u\n", snap_peak.tot_bytes_occupied); } } } static void take_snapshot(void) { uint prev_idx; /* We serialize snapshots since rare so not costly perf-wise, and this avoids * needing potentially very large buffers to try and get atomic writes */ dr_mutex_lock(snapshot_lock); if (options.staleness) { /* Unlike the mem usage data which is maintained as the app * executes, we have to go collect this at snapshot time from * the malloc table. */ if (options.dump && snaps[snap_idx].stale != NULL) { staleness_free_snapshot(snaps[snap_idx].stale); snaps[snap_idx].stale = NULL; } ASSERT(snaps[snap_idx].stale == NULL, "invalid staleness data"); snaps[snap_idx].stale = staleness_take_snapshot(stamp); } if (options.dump) { snaps[snap_idx].stamp += options.dump_freq; dump_snapshot(&snaps[snap_idx], snap_idx); } else { stamp += options.dump_freq; snaps[snap_idx].stamp = stamp; prev_idx = snap_idx; LOG(2, "take_snapshot @idx=%u stamp=%"INT64_FORMAT"u\n", prev_idx, stamp); /* Check for peak on every snapshot (PR 476018) */ check_for_peak(); /* Find the next one we should overwrite. Keep those aligned * w/ current dump_freq. */ do { snap_idx++; if (snap_idx >= options.snapshots) { snap_fills++; snap_idx = 0; options.dump_freq *= 2; LOG(1, "adjusting snapshots: new freq=%u\n", options.dump_freq); if (options.time_clock) reset_clock_timer(); } } while (snaps[snap_idx].stamp > 0 && (snaps[snap_idx].stamp % options.dump_freq) == 0); /* Replace the existing list at snap_idx with a clone of prev_idx */ copy_snapshot(&snaps[snap_idx], &snaps[prev_idx], true/*live copy*/); } dr_mutex_unlock(snapshot_lock); } /* Called from pre-alloc-hashtable-change events. * Updates the current snapshot and callstack usage. */ static void account_for_bytes_pre(per_callstack_t *per, int asked_for, int extra_usable, int extra_occupied) { /* must be synched w/ take_snapshot(). the malloc lock is always acquired * before the snapshot lock. */ dr_mutex_lock(snapshot_lock); if (asked_for+extra_usable > 0) { if (per->used == NULL) { per->used = (heap_used_t *) global_alloc(sizeof(*per->used), HEAPSTAT_SNAPSHOT); memset(per->used, 0, sizeof(*per->used)); per->used->callstack = per; per->used->next = snaps[snap_idx].used; if (snaps[snap_idx].used != NULL) { ASSERT(snaps[snap_idx].used->callstack->prev_used == NULL, "prev_used should already be null"); snaps[snap_idx].used->callstack->prev_used = per->used; } ASSERT(per->prev_used == NULL, "prev_used should already be null"); snaps[snap_idx].used = per->used; } per->used->instances++; snaps[snap_idx].tot_mallocs++; } else { ASSERT(asked_for+extra_usable < 0, "cannot have 0-sized usable space"); ASSERT(per->used != NULL, "alloc must exist"); ASSERT(per->used->instances > 0, "alloc count must be >= 0"); ASSERT(snaps[snap_idx].tot_mallocs > 0, "alloc count must be >= 0"); per->used->instances--; snaps[snap_idx].tot_mallocs--; } per->used->bytes_asked_for += asked_for; per->used->extra_usable += extra_usable; per->used->extra_occupied += extra_occupied; LOG(2, "callstack id %u => %ux, %uB, +%uB, +%uB\n", per->id, per->used->instances, per->used->bytes_asked_for, per->used->extra_usable, per->used->extra_occupied); if (per->used->instances == 0) { /* remove the node to save memory since may not re-alloc */ ASSERT(per->used->bytes_asked_for == 0, "no malloc => no bytes!"); if (per->used->next != NULL) per->used->next->callstack->prev_used = per->prev_used; if (per->prev_used == NULL) { ASSERT(per->used == snaps[snap_idx].used, "prev node error"); snaps[snap_idx].used = per->used->next; } else { per->prev_used->next = per->used->next; } global_free(per->used, sizeof(*per->used), HEAPSTAT_SNAPSHOT); per->used = NULL; per->prev_used = NULL; } snaps[snap_idx].tot_bytes_asked_for += asked_for; snaps[snap_idx].tot_bytes_usable += asked_for + extra_usable; snaps[snap_idx].tot_bytes_occupied += asked_for + extra_usable + extra_occupied; dr_mutex_unlock(snapshot_lock); } /* Called from post-alloc-hashtable-change events which is important to * have a consistent view in the staleness hashtable walk (PR 567117). * Updates the -time_allocs and -time_bytes counters and potentially * takes snapshots. */ static void account_for_bytes_post(int asked_for, int extra_usable, int extra_occupied) { if (options.time_bytes) { /* PR 545288: consider dealloc as well as alloc */ int diff = asked_for + extra_usable + extra_occupied; if (diff < 0) diff = -diff; if (diff > byte_count) { /* allocs larger than cur freq occupy multiple snapshots */ while (diff > byte_count) { take_snapshot(); diff -= options.dump_freq; } byte_count = options.dump_freq; } else { byte_count -= diff; } } else if (options.time_allocs) { /* PR 545288: consider free as well as alloc */ /* We rely on malloc lock being held by caller */ allocfree_count--; if (allocfree_count <= 0) { take_snapshot(); allocfree_count = options.dump_freq; } } allocfree_cur++; } static void dump_callstack(packed_callstack_t *pcs, per_callstack_t *per, char *buf, size_t bufsz, size_t *sofar) { ssize_t len = 0; /* we use a buffer for atomic prints even though malloc lock does * currently synchronize */ BUFPRINT(buf, bufsz, *sofar, len, "CALLSTACK %u\n", per->id); packed_callstack_print(pcs, 0, buf, bufsz, sofar, NULL); BUFPRINT(buf, bufsz, *sofar, len, "%s", END_MARKER); print_buffer(f_callstack, buf); } /* A lock is held around the call to this routine */ void * client_add_malloc_pre(app_pc start, app_pc end, app_pc real_end, void *existing_data, dr_mcontext_t *mc, app_pc post_call) { void *drcontext = dr_get_current_drcontext(); per_callstack_t *per; char *buf; size_t bufsz; size_t sofar = 0; #ifdef STATISTICS static uint malloc_count; #endif get_buffer(drcontext, &buf, &bufsz); if (existing_data != NULL) { per = get_cstack_from_alloc_data(existing_data); IF_DEBUG({ hashtable_lock(&alloc_stack_table); ASSERT(hashtable_lookup(&alloc_stack_table, (void *)per->IF_MD5_ELSE(md5, crc)) == (void*)per, "malloc re-add should still be in table"); hashtable_unlock(&alloc_stack_table); }); } else { #if defined(USE_MD5) || defined(CHECK_WITH_MD5) byte md5[MD5_RAW_BYTES]; #endif #ifndef USE_MD5 uint crc[2]; #endif /* Printing to a buffer is slow (quite noticeable: 2x on cfrac) so it's * faster to create a packed callstack for computing the checksum to * decide uniqueness, limiting printing to new callstacks only. */ packed_callstack_t *pcs; app_loc_t loc; pc_to_loc(&loc, post_call); packed_callstack_record(&pcs, mc, &loc); #if defined(USE_MD5) || defined(CHECK_WITH_MD5) packed_callstack_md5(pcs, md5); #endif #ifndef USE_MD5 packed_callstack_crc32(pcs, crc); #endif hashtable_lock(&alloc_stack_table); per = (per_callstack_t *) hashtable_lookup(&alloc_stack_table, (void *)IF_MD5_ELSE(md5, crc)); #ifdef CHECK_WITH_MD5 /* Check for collisions with crc32 */ ASSERT(per == hashtable_lookup(&alloc_md5_table, (void *)md5), "crc and md5 do not agree"); #endif if (per == NULL) { per = (per_callstack_t *) global_alloc(sizeof(*per), HEAPSTAT_CALLSTACK); memset(per, 0, sizeof(*per)); /* we could do ++ since there's an outer lock */ per->id = atomic_add32_return_sum((volatile int *)&num_callstacks, 1); #if defined(USE_MD5) || defined(CHECK_WITH_MD5) memcpy(per->md5, md5, BUFFER_SIZE_BYTES(md5)); hashtable_add(IF_MD5_ELSE(&alloc_stack_table, &alloc_md5_table), (void *)per->md5, (void *)per); #endif #ifndef USE_MD5 per->crc[0] = crc[0]; per->crc[1] = crc[1]; hashtable_add(&alloc_stack_table, (void *)per->crc, (void *)per); #endif STATS_INC(alloc_stack_count); dump_callstack(pcs, per, buf, bufsz, &sofar); } hashtable_unlock(&alloc_stack_table); sofar = packed_callstack_free(pcs); ASSERT(sofar == 0, "pcs should have 0 ref count"); } #ifdef X64 /* FIXME: assert not truncating */ #endif account_for_bytes_pre(per, end - start, real_end - end, HEADER_SIZE); #ifdef STATISTICS if (((malloc_count++) % STATS_DUMP_FREQ) == 0) dump_statistics(); #endif release_buffer(drcontext, buf, bufsz); if (options.staleness) return (void *) staleness_create_per_alloc(per, stamp); else return (void *) per; } void client_add_malloc_post(app_pc start, app_pc end, app_pc real_end, void *data) { /* take potential snapshots here once table is consistent (PR 567117) */ account_for_bytes_post(end - start, real_end - end, HEADER_SIZE); } /* A lock is held around the call to this routine */ void client_remove_malloc_pre(app_pc start, app_pc end, app_pc real_end, void *data) { per_callstack_t *per = get_cstack_from_alloc_data(data); #ifdef X64 /* FIXME: assert not truncating */ #endif /* To avoid repeatedly redoing the peak snapshot we wait until a drop (PR 476018) */ check_for_peak(); account_for_bytes_pre(per, -(end - start), -(real_end - end), -(ssize_t)(HEADER_SIZE)); if (options.staleness) staleness_free_per_alloc((stale_per_alloc_t *)data); } void client_remove_malloc_post(app_pc start, app_pc end, app_pc real_end) { /* take potential snapshots here once table is consistent (PR 567117) */ account_for_bytes_post(end - start, real_end - end, HEADER_SIZE); } static void snapshot_init(void) { snapshot_lock = dr_mutex_create(); snaps = (per_snapshot_t *) global_alloc(options.snapshots*sizeof(*snaps), HEAPSTAT_SNAPSHOT); memset(snaps, 0, options.snapshots*sizeof(*snaps)); } /* Caller must hold malloc lock */ static void snapshot_dump_all(void) { uint i; dr_mutex_lock(snapshot_lock); /* These should be sorted by stamp, but simpler to have the vis tool * sort them. */ /* We do dump the partially-full current snapshot (PR 548013) */ if (options.time_clock) { uint64 diff = ((dr_get_milliseconds() - timestamp_last_snapshot) / TIME_BASE_FREQ) + 1 /* round up */; snaps[snap_idx].stamp = stamp + diff; } else if (options.time_allocs) snaps[snap_idx].stamp = stamp + (options.dump_freq - allocfree_count); else if (options.time_bytes) snaps[snap_idx].stamp = stamp + (options.dump_freq - byte_count); else if (options.time_instrs) snaps[snap_idx].stamp = stamp + (options.dump_freq - instr_count); /* Check for peak on every snapshot (PR 476018) */ check_for_peak(); dump_snapshot(&snap_peak, -1); if (snap_fills == 0) { for (i = 0; i <= snap_idx; i++) { dump_snapshot(&snaps[i], i); } } else { /* FIXME: sort by stamp */ for (i = 0; i < options.snapshots; i++) { dump_snapshot(&snaps[i], i); } } dr_mutex_unlock(snapshot_lock); } static void snapshot_exit(void) { int i; snapshot_dump_all(); for (i = 0; i < options.snapshots; i++) free_snapshot(&snaps[i]); global_free(snaps, options.snapshots*sizeof(*snaps), HEAPSTAT_SNAPSHOT); free_snapshot(&snap_peak); dr_mutex_destroy(snapshot_lock); } void client_handle_malloc(void *drcontext, app_pc base, size_t size, app_pc real_base, size_t real_size, bool zeroed, bool realloc, dr_mcontext_t *mc) { if (options.check_leaks) leak_handle_alloc(drcontext, base, size); } void client_handle_realloc(void *drcontext, app_pc old_base, size_t old_size, app_pc new_base, size_t new_size, app_pc new_real_base, dr_mcontext_t *mc) { if (options.check_leaks) leak_handle_alloc(drcontext, new_base, new_size); } void client_handle_alloc_failure(size_t sz, bool zeroed, bool realloc, app_pc pc, dr_mcontext_t *mc) { } void client_handle_realloc_null(app_pc pc, dr_mcontext_t *mc) { } /* Returns the value to pass to free(). Return "real_base" for no change. * The Windows heap param is INOUT so it can be changed as well. */ app_pc client_handle_free(app_pc base, size_t size, app_pc real_base, size_t real_size, dr_mcontext_t *mc, app_pc free_routine, void *client_data _IF_WINDOWS(ptr_int_t *auxarg INOUT)) { return real_base; } void client_invalid_heap_arg(app_pc pc, app_pc target, dr_mcontext_t *mc, const char *routine, bool is_free) { /* not reporting today */ LOG(1, "invalid heap arg\n"); } void client_mismatched_heap(app_pc pc, app_pc target, dr_mcontext_t *mc, const char *alloc_routine, const char *free_routine, void *client_data) { /* not reporting today */ LOG(1, "mismatched heap routines\n"); } void client_handle_mmap(void *drcontext, app_pc base, size_t size, bool anon) { } void client_handle_munmap(app_pc base, size_t size, bool anon) { } void client_handle_munmap_fail(app_pc base, size_t size, bool anon) { } #ifdef LINUX void client_handle_mremap(app_pc old_base, size_t old_size, app_pc new_base, size_t new_size, bool image) { } #endif void * client_add_malloc_routine(app_pc pc) { return NULL; } void client_remove_malloc_routine(void *client_data) { } #ifdef WINDOWS void client_handle_heap_destroy(void *drcontext, HANDLE heap, void *client_data) { } void client_remove_malloc_on_destroy(HANDLE heap, byte *start, byte *end) { if (options.check_leaks) leak_remove_malloc_on_destroy(heap, start, end); } void client_handle_cbret(void *drcontext) { } void client_handle_callback(void *drcontext) { } void client_handle_Ki(void *drcontext, app_pc pc, dr_mcontext_t *mc, bool is_cb) { } void client_handle_exception(void *drcontext, dr_mcontext_t *mc) { } void client_handle_continue(void *drcontext, dr_mcontext_t *mc) { } #endif /* WINDOWS */ void client_stack_alloc(byte *start, byte *end, bool defined) { } void client_stack_dealloc(byte *start, byte *end) { } void client_pre_syscall(void *drcontext, int sysnum, reg_t sysarg[]) { } void client_post_syscall(void *drcontext, int sysnum, reg_t sysarg[]) { } void client_found_leak(app_pc start, app_pc end, size_t indirect_bytes, bool pre_us, bool reachable, bool maybe_reachable, void *client_data, bool count_reachable, bool show_reachable) { per_callstack_t *per = get_cstack_from_alloc_data(client_data); ssize_t len = 0; size_t sofar = 0; char *buf; size_t bufsz; void *drcontext = dr_get_current_drcontext(); int num; ASSERT(options.check_leaks, "leak checking error"); if (pre_us && options.ignore_early_leaks) return; if (reachable) { if (count_reachable) ATOMIC_INC32(reachable_leak_count); if (!show_reachable) return; } if (maybe_reachable && !options.possible_leaks) return; num = atomic_add32_return_sum((volatile int *)&leak_count, 1); get_buffer(drcontext, &buf, &bufsz); BUFPRINT(buf, bufsz, sofar, len, "Error #%d: ", num); if (reachable) BUFPRINT(buf, bufsz, sofar, len, "REACHABLE "); else if (maybe_reachable) BUFPRINT(buf, bufsz, sofar, len, "POSSIBLE "); BUFPRINT(buf, bufsz, sofar, len, "LEAK %d direct bytes "PFX"-"PFX" + %d indirect bytes" "\n\tcallstack=%d\n\terror end\n", (end - start), start, end, indirect_bytes, per->id); print_buffer(f_global, buf); release_buffer(drcontext, buf, bufsz); } /*************************************************************************** * INSTRUMENTATION */ /* N.B.: mcontext is not in consistent app state, for efficiency. */ static void shared_instrcnt_callee(void) { bool do_snapshot = false; ASSERT(options.time_instrs, "option mismatch"); /* We racily subtract and check, so serialize now for a single snapshot */ dr_mutex_lock(snapshot_lock); /* We can still have a double-snapshot if threshold is low enough that * other threads bump the instr_count over it before 2nd guy to get lock * can do this check, but that's ok */ if (instr_count < 0) { do_snapshot = true; instr_count = options.dump_freq; } else { /* We assume can't take so long that it wraps around */ ASSERT(instr_count <= options.dump_freq, "callee incorrectly invoked"); } /* Release lock so take_snapshot can grab it */ dr_mutex_unlock(snapshot_lock); if (do_snapshot) take_snapshot(); } /* To avoid the code expansion from a clean call in every bb we use * a shared clean call sequence, entering it with a direct jump * and exiting with an indirect jump to a stored return point. */ static app_pc generate_shared_callout(void *drcontext, instrlist_t *ilist, app_pc pc) { /* On entry: * - SPILL_SLOT_2 holds the return address * The spill slots are persistent storage across clean calls. */ dr_insert_clean_call(drcontext, ilist, NULL, (void *) shared_instrcnt_callee, false, 0); PRE(ilist, NULL, INSTR_CREATE_jmp_ind(drcontext, dr_reg_spill_slot_opnd(drcontext, SPILL_SLOT_2))); shared_instrcnt_callout = pc; pc = instrlist_encode(drcontext, ilist, pc, false); instrlist_clear(drcontext, ilist); return pc; } static void create_shared_code(void) { void *drcontext = dr_get_current_drcontext(); byte *pc; IF_DEBUG(bool ok;) instrlist_t *ilist = instrlist_create(drcontext); shared_code_region = (byte *) nonheap_alloc(SHARED_CODE_SIZE, DR_MEMPROT_READ|DR_MEMPROT_WRITE|DR_MEMPROT_EXEC, HEAPSTAT_GENCODE); pc = shared_code_region; pc = generate_shared_callout(drcontext, ilist, pc); ASSERT(pc - shared_code_region <= SHARED_CODE_SIZE, "shared code region too small"); if (options.staleness) { pc = generate_shared_slowpath(drcontext, ilist, pc); ASSERT(pc - shared_code_region <= SHARED_CODE_SIZE, "shared code region too small"); } if (options.check_leaks) { pc = generate_shared_esp_slowpath(drcontext, ilist, pc); ASSERT(pc - shared_code_region <= SHARED_CODE_SIZE, "shared code region too small"); } instrlist_clear_and_destroy(drcontext, ilist); /* now mark as +rx (non-writable) */ IF_DEBUG(ok = ) dr_memory_protect(shared_code_region, SHARED_CODE_SIZE, DR_MEMPROT_READ|DR_MEMPROT_EXEC); ASSERT(ok, "-w failed on shared routines gencode"); DOLOG(2, { byte *end_pc = pc; pc = shared_code_region; LOG(2, "shared_code region:\n"); while (pc < end_pc) { pc = disassemble_with_info(drcontext, pc, f_global, true/*show pc*/, true/*show bytes*/); } }); } static void free_shared_code(void) { nonheap_free(shared_code_region, SHARED_CODE_SIZE, HEAPSTAT_GENCODE); } static void insert_instr_counter(void *drcontext, instrlist_t *bb, instr_t *first, bool flags_dead, instr_t *where_dead, uint instrs_in_bb) { instr_t *where = (where_dead == NULL) ? first : where_dead; instr_t *done = INSTR_CREATE_label(drcontext); if (!flags_dead) dr_save_arith_flags(drcontext, bb, first, SPILL_SLOT_1); /* Rather than an ongoing count that would need a 64-bit * counter, we do a racy subtract of a 32-bit counter and if * negative (so we don't need a cmp) then we go to a callout * that synchs for a counter reset and single snapshot. * We assume that racy mods during that synch won't overflow * the counter. We also ignore the detail of how many instrs * in this bb we've executed yet. */ instrlist_meta_preinsert (bb, where, INSTR_CREATE_sub(drcontext, OPND_CREATE_ABSMEM ((byte *)&instr_count, OPSZ_4), (instrs_in_bb <= CHAR_MAX) ? OPND_CREATE_INT8(instrs_in_bb) : OPND_CREATE_INT32(instrs_in_bb))); /* TODO: for better perf could not bother to check threshold * in every bb: but don't want to skip for single-bb-loop-body */ instrlist_meta_preinsert (bb, where, INSTR_CREATE_jcc(drcontext, OP_jns_short, opnd_create_instr(done))); /* To avoid the code expansion from a clean call in every bb we use * a shared clean call sequence, entering it with a direct jump * and exiting with an indirect jump to a stored return point. */ /* Get return point into SPILL_SLOT_2. Spill reg, mov imm to reg, and then * xchg reg and slot isn't any faster, right? */ instrlist_meta_preinsert (bb, where, INSTR_CREATE_mov_st (drcontext, dr_reg_spill_slot_opnd(drcontext, SPILL_SLOT_2), opnd_create_instr(done))); instrlist_meta_preinsert (bb, where, INSTR_CREATE_jmp(drcontext, opnd_create_pc(shared_instrcnt_callout))); /* Will return here */ instrlist_meta_preinsert(bb, where, done); if (!flags_dead) dr_restore_arith_flags(drcontext, bb, first, SPILL_SLOT_1); } static dr_emit_flags_t event_bb_app2app(void *drcontext, void *tag, instrlist_t *bb, bool for_trace, bool translating, void **user_data OUT) { /* we pass bi among all 4 phases */ instru_info_t *ii = thread_alloc(drcontext, sizeof(*ii), HEAPSTAT_PERBB); memset(ii, 0, sizeof(*ii)); *user_data = (void *) ii; return DR_EMIT_DEFAULT; } static dr_emit_flags_t event_bb_analysis(void *drcontext, void *tag, instrlist_t *bb, bool for_trace, bool translating, void *user_data) { instru_info_t *ii = (instru_info_t *) user_data; DOLOG(3, instrlist_disassemble(drcontext, tag, bb, LOGFILE_GET(drcontext));); #ifdef USE_DRSYMS DOLOG(3, { char buf[128]; size_t sofar = 0; ssize_t len; if (!translating) { BUFPRINT(buf, BUFFER_SIZE_ELEMENTS(buf), sofar, len, "new basic block @"PFX" ==", tag); print_symbol(tag, buf, BUFFER_SIZE_ELEMENTS(buf), &sofar, false, 0); LOG(1, "%s\n", buf); } }); #endif if (options.staleness) fastpath_top_of_bb(drcontext, tag, bb, &ii->bi); return DR_EMIT_DEFAULT; } static dr_emit_flags_t event_bb_insert(void *drcontext, void *tag, instrlist_t *bb, instr_t *inst, bool for_trace, bool translating, void *user_data) { instru_info_t *ii = (instru_info_t *) user_data; uint flags; fastpath_info_t mi; ii->instrs_in_bb++; if (options.time_instrs) { /* See if flags are dead anywhere. * FIXME: for fault handling we should either consider a faultable * instr as having live flags or recover somehow: ignoring for now * as pathological. */ flags = instr_get_arith_flags(inst); /* We insert after the prev instr to avoid messing up * -check_leaks instrumentation (PR 560871) */ if (TESTALL(EFLAGS_WRITE_6, flags) && !TESTANY(EFLAGS_READ_6, flags)) { ii->where_dead = instr_get_prev(inst); ii->flags_dead = true; } } if (options.staleness) { /* We want to spill AFTER any clean call in case it changes mcontext */ ii->bi.spill_after = instr_get_prev(inst); /* update liveness of whole-bb spilled regs */ fastpath_pre_instrument(drcontext, bb, inst, &ii->bi); if (instr_uses_memory_we_track(inst)) { if (instr_ok_for_instrument_fastpath(inst, &mi, &ii->bi)) { instrument_fastpath(drcontext, bb, inst, &mi, false); ii->bi.added_instru = true; } else { LOG(3, "fastpath unavailable "PFX": ", instr_get_app_pc(inst)); DOLOG(3, { instr_disassemble(drcontext, inst, LOGFILE_GET(drcontext)); }); LOG(3, "\n"); ii->bi.shared_memop = opnd_create_null(); /* Restore whole-bb spilled regs (PR 489221) * FIXME: optimize via liveness analysis */ mi.reg1 = ii->bi.reg1; mi.reg2 = ii->bi.reg2; memset(&mi.reg3, 0, sizeof(mi.reg3)); instrument_slowpath(drcontext, bb, inst, whole_bb_spills_enabled() ? &mi : NULL); /* for whole-bb slowpath does interact w/ global regs */ ii->bi.added_instru = whole_bb_spills_enabled(); } } } if (ZERO_STACK() && instr_writes_esp(inst)) { /* any new spill must be after the alloc instru */ ii->bi.spill_after = instr_get_prev(inst); /* we zero for leaks, and staleness does not care about xsp */ instrument_esp_adjust(drcontext, bb, inst, &ii->bi, SP_ADJUST_ACTION_ZERO); ii->bi.added_instru = true; } if (options.staleness) fastpath_pre_app_instr(drcontext, bb, inst, &ii->bi, &mi); return DR_EMIT_DEFAULT; } static dr_emit_flags_t event_bb_instru2instru(void *drcontext, void *tag, instrlist_t *bb, bool for_trace, bool translating, void *user_data) { instru_info_t *ii = (instru_info_t *) user_data; if (options.staleness) { fastpath_bottom_of_bb(drcontext, tag, bb, &ii->bi, ii->bi.added_instru, translating, false); } if (options.time_instrs) { insert_instr_counter(drcontext, bb, instrlist_first(bb), ii->flags_dead, /* insert after the prev instr to avoid messing up * -check_leaks instrumentation (PR 560871) */ (ii->where_dead == NULL) ? instrlist_first(bb) : instr_get_next(ii->where_dead), ii->instrs_in_bb); } LOG(3, "final instrumentation:\n"); DOLOG(3, instrlist_disassemble(drcontext, tag, bb, LOGFILE_GET(drcontext));); thread_free(drcontext, ii, sizeof(*ii), HEAPSTAT_PERBB); return DR_EMIT_DEFAULT; /* deterministic */ } /*************************************************************************** * DYNAMORIO EVENTS & TOP-LEVEL CODE */ #ifdef STATISTICS /* statistics * FIXME: make per-thread to avoid races (or use locked inc) * may want some of these to be 64-bit */ static void dump_statistics(void) { int i; dr_fprintf(f_global, "Statistics:\n"); dr_fprintf(f_global, "app mallocs: %8u, frees: %8u, large mallocs; %6u\n", num_mallocs, num_frees, num_large_mallocs); dr_fprintf(f_global, "unique malloc stacks: %8u\n", alloc_stack_count); dr_fprintf(f_global, "app heap regions: %8u\n", heap_regions); dr_fprintf(f_global, "peaks detected: %8u, skipped: %8u\n", peaks_detected, peaks_skipped); if (options.staleness) { dr_fprintf(f_global, "staleness: needs large: %7u, needs ext: %7u\n", stale_needs_large, stale_small_needs_ext); } /* FIXME: share w/ drmemory.c */ dr_fprintf(f_global, "\nPer-opcode slow path executions:\n"); for (i = 0; i <= OP_LAST; i++) { if (slowpath_count[i] > 0) { dr_fprintf(f_global, "\t%3u %10s: %12"UINT64_FORMAT_CODE"\n", i, decode_opcode_name(i), slowpath_count[i]); } } heap_dump_stats(f_global); } #endif /* STATISTICS */ static void client_heap_add(app_pc start, app_pc end, dr_mcontext_t *mc) { LOG(2, "%s "PFX"-"PFX"\n", __FUNCTION__, start, end); if (options.staleness) shadow_replace_specials_in_range(start, end); } static void client_heap_remove(app_pc start, app_pc end, dr_mcontext_t *mc) { /* save memory and improve performance by putting back the specials -- * except w/ our sideline thread doing sweeps we could have races * (unlikely since this is a heap region remove) so it's not safe. * we just live w/ the extra mem and writes. */ LOG(2, "%s "PFX"-"PFX"\n", __FUNCTION__, start, end); #if 0 /* disabled: see comment above */ if (options.staleness) shadow_reinstate_specials_in_range(start, end); #endif } static void heap_iter_region(app_pc start, app_pc end _IF_WINDOWS(HANDLE heap)) { client_heap_add(start, end, NULL); heap_region_add(start, end, HEAP_PRE_US | HEAP_ARENA, NULL); } static void heap_iter_chunk(app_pc start, app_pc end) { /* We don't have the asked-for size so we use real end for both */ malloc_add(start, end, end, true/*pre_us*/, 0, NULL, NULL); } /* Walk the heap blocks that are already allocated at client init time */ static void heap_walk(void) { heap_iterator(heap_iter_region, heap_iter_chunk); } /* if which_thread is >= 0, creates a file name with which_thread and * the cur thread's tid */ static file_t open_logfile(const char *name, bool pid_log, int which_thread) { file_t f; char logname[MAXIMUM_PATH]; IF_DEBUG(int len;) uint extra_flags = IF_LINUX_ELSE(DR_FILE_ALLOW_LARGE, 0); ASSERT(logsubdir[0] != '\0', "logsubdir not set up"); if (pid_log) { IF_DEBUG(len = ) dr_snprintf(logname, BUFFER_SIZE_ELEMENTS(logname), "%s%c%s.%d.log", logsubdir, DIRSEP, name, dr_get_process_id()); } else if (which_thread >= 0) { IF_DEBUG(len = ) dr_snprintf(logname, BUFFER_SIZE_ELEMENTS(logname), "%s%c%s.%d.%d.log", logsubdir, DIRSEP, name, which_thread, dr_get_thread_id(dr_get_current_drcontext())); /* have DR close on fork so we don't have to track and iterate */ extra_flags |= DR_FILE_CLOSE_ON_FORK; } else { IF_DEBUG(len = ) dr_snprintf(logname, BUFFER_SIZE_ELEMENTS(logname), "%s%c%s", logsubdir, DIRSEP, name); } ASSERT(len > 0, "logfile name buffer max reached"); NULL_TERMINATE_BUFFER(logname); f = dr_open_file(logname, DR_FILE_WRITE_OVERWRITE | extra_flags); ASSERT(f != INVALID_FILE, "unable to open log file"); if (which_thread > 0) { void *drcontext = dr_get_current_drcontext(); dr_log(drcontext, LOG_ALL, 1, "DrMemory: log for thread %d is %s\n", dr_get_thread_id(drcontext), logname); NOTIFY("thread logfile is %s"NL, logname); } return f; } /* also initializes logsubdir */ static void create_global_logfile(void) { uint count = 0; const char *appnm = dr_get_application_name(); const uint LOGDIR_TRY_MAX = 1000; /* PR 408644: pick a new subdir inside base logdir */ /* PR 453867: logdir must have pid in its name */ do { dr_snprintf(logsubdir, BUFFER_SIZE_ELEMENTS(logsubdir), "%s%cDrHeapstat-%s.%d.%03d", options.logdir, DIRSEP, appnm == NULL ? "null" : appnm, dr_get_process_id(), count); NULL_TERMINATE_BUFFER(logsubdir); /* FIXME PR 514092: if the base logdir is unwritable, we shouldn't loop * UINT_MAX times: it looks like we've hung. * Unfortuantely dr_directory_exists() is Windows-only and * dr_create_dir returns only a bool, so for now we just * fail if we hit 1000 dirs w/ same pid. */ } while (!dr_create_dir(logsubdir) && ++count < LOGDIR_TRY_MAX); if (count >= LOGDIR_TRY_MAX) { NOTIFY_ERROR("Unable to create subdir in log base dir %s"NL, options.logdir); ASSERT(false, "unable to create unique logsubdir"); dr_abort(); } f_global = open_logfile("global", true/*pid suffix*/, -1); #ifdef LINUX /* make it easier for wrapper script to find this logfile */ dr_fprintf(f_global, "process=%d, parent=%d\n", dr_get_process_id(), dr_get_parent_id()); #endif /* make sure "Dr. Heapstat" is 1st (or 2nd on linux) in file (for PR 453867) */ dr_fprintf(f_global, "Dr. Heapstat version %s\n", VERSION_STRING); NOTIFY("log dir is %s"NL, logsubdir); LOGF(1, f_global, "running %s\n", (dr_get_application_name() == NULL) ? "<null>" : dr_get_application_name()); LOGF(1, f_global, "global logfile fd=%d\n", f_global); f_callstack = open_logfile("callstack.log", false, -1); f_snapshot = open_logfile("snapshot.log", false, -1); if (options.staleness) f_staleness = open_logfile("staleness.log", false, -1); /* For long running multi-process apps like sfcbd, this can mean a lot of * index files. With each file being 1 MB minimum on esxi, space can be * used up fast. On ther other hand computing nudge index in postprocess * each time can be time consuming with large number of snapshots, thereby * affecting the vistool startup time. No simple solution. If the file * problem gets out of hand, we might use the global log, but then that * requires parsing the global log, which can get large. */ f_nudge = open_logfile("nudge.idx", false, -1); dr_fprintf(f_nudge, "%s snapshots\n", options.dump ? "variable" : "constant"); } static void close_file(file_t f) { /* with DRi#357, DR now isolates log files so little to do here */ dr_close_file(f); } #define dr_close_file DO_NOT_USE_dr_close_file static void reset_to_time_zero(bool keep_offs) { int i; dr_mutex_lock(snapshot_lock); /* take current data and make it the cur val of to-be-snapshot 0 */ if (snap_idx != 0) copy_snapshot(&snaps[0], &snaps[snap_idx], true/*live copy*/); for (i = 1; i < options.snapshots; i++) free_snapshot(&snaps[i]); memset(&snaps[1], 0, (options.snapshots-1)*sizeof(*snaps)); if (keep_offs) stamp_offs = stamp; else reset_intervals(); stamp = 0; snap_idx = 0; /* malloc_count we do not reset */ dr_mutex_unlock(snapshot_lock); } static void event_timer(void *drcontext, dr_mcontext_t *mcontext) { bool alarm_clock = false, alarm_stale = false; if (sideline_exit) { #ifdef LINUX dr_set_itimer(ITIMER_REAL, 0, event_timer); #endif return; } if (options.time_clock) { ASSERT(timer_real <= timer_clock, "timer internal error"); timer_clock -= timer_real; if (timer_clock == 0) { alarm_clock = true; timer_clock = options.dump_freq*TIME_BASE_FREQ; } } if (options.staleness) { ASSERT(timer_real <= timer_stale, "timer internal error"); timer_stale -= timer_real; if (timer_stale == 0) { alarm_stale = true; /* FIXME PR 553724: should -stale_granularity be increased as * -dump_freq increases? For a long-running app it seems fine to * make the staleness data coarser and coarser, which also improves * performance. */ timer_stale = options.stale_granularity; } } /* reset now before potentially taking a while in code below, to avoid * clock drift */ reset_real_timer(); if (alarm_clock) { timestamp_last_snapshot = dr_get_milliseconds(); /* must hold malloc lock first */ /* FIXME i#949: may need to use a special allocator option to have * a global malloc lock for -replace_malloc */ malloc_lock(); take_snapshot(); malloc_unlock(); } if (alarm_stale) { staleness_sweep(stamp); } } static void reset_real_timer(void) { /* set real timer to the smaller and when it fires we'll adjust both */ if (options.staleness) { if (options.time_clock) { timer_real = (timer_clock > 0 && timer_clock < timer_stale) ? timer_clock : timer_stale; } else timer_real = timer_stale; } else { ASSERT(options.time_clock, "timer should not be active"); timer_real = timer_clock; } ASSERT(timer_real >= 0, "timer internal error"); #ifdef LINUX if (!dr_set_itimer(ITIMER_REAL, timer_real, event_timer)) ASSERT(false, "unable to set up timer callback\n"); #endif } static void reset_clock_timer(void) { if (options.time_clock) timer_clock = options.dump_freq*TIME_BASE_FREQ; reset_real_timer(); } /* For -time_clock we need a timer (PR 476008): simplest to use a separate thread */ static void sideline_run(void *arg) { void *drcontext = dr_get_current_drcontext(); /* PR 609569: we spend a lot of time holding locks, so keep running * during synchall. Our locks keep us safe wrt leak scan, and we * do not mutate any app state or non-persistent DR state. */ dr_client_thread_set_suspendable(false); if (options.thread_logs) { /* easier to debug w/ all staleness and clock snaps in sep file */ /* FIXME i#297: have to use global heap for sideline thread */ sideline_pt = global_alloc(sizeof(*sideline_pt), HEAPSTAT_MISC); memset(sideline_pt, 0, sizeof(*sideline_pt)); /* store it in the slot provided in the drcontext */ drmgr_set_tls_field(drcontext, tls_idx_util, (void *)sideline_pt); utils_thread_set_file(drcontext, open_logfile("sideline.log", false, -1)); } if (options.staleness) timer_stale = options.stale_granularity; reset_clock_timer(); ASSERT(options.time_clock || options.staleness, "thread should not be running"); LOG(1, "sideline thread %d running\n", dr_get_thread_id(drcontext)); while (!sideline_exit) { #ifdef WINDOWS dr_sleep(timer_real); /* FIXME: check wall-clock time and normalize to get closer to real time */ event_timer(drcontext, NULL); #else dr_sleep(500); #endif } #ifdef LINUX dr_set_itimer(ITIMER_REAL, 0, event_timer); #endif /* i#297: we can't clean up sideline_pt so event_exit does it */ } #ifdef LINUX static void event_fork(void *drcontext) { /* we want a whole new log dir to avoid clobbering the parent's */ tls_heapstat_t *pt = (tls_heapstat_t *) drmgr_get_tls_field(drcontext, tls_idx_heapstat); /* fds are shared across fork so we must duplicate */ file_t f_parent_callstack = dr_dup_file_handle(f_callstack); /* we assume no lock is needed since only one thread post-fork */ static char buf[4096]; close_file(f_global); close_file(f_callstack); close_file(f_snapshot); if (options.staleness) close_file(f_staleness); close_file(f_nudge); /* now create new files for all 5 */ create_global_logfile(); utils_thread_set_file(drcontext, f_global); LOG(0, "new logfile after fork fd=%d\n", f_global); /* we don't expect the user to go find the parent's data, * so we need to duplicate the callstack file and start * the snapshots over. we no longer keep full callstacks * in memory (PR 496304) so we copy the file. * so we don't have to parse and find id# num_callstacks we * store the file position. */ if (dr_file_seek(f_parent_callstack, 0, DR_SEEK_SET)) { int64 curpos = 0; IF_DEBUG(ssize_t sz;) LOG(1, "copying parent callstacks "INT64_FORMAT_STRING" bytes\n", pt->filepos); while (curpos + sizeof(buf) <= pt->filepos) { IF_DEBUG(sz = ) dr_read_file(f_parent_callstack, buf, sizeof(buf)); ASSERT(sz == sizeof(buf), "error reading parent callstack data"); IF_DEBUG(sz = ) dr_write_file(f_callstack, buf, sizeof(buf)); ASSERT(sz == sizeof(buf), "error writing parent callstack data"); curpos += sizeof(buf); } ASSERT(pt->filepos - curpos < sizeof(buf), "buf calc error"); IF_DEBUG(sz = ) dr_read_file(f_parent_callstack, buf, pt->filepos - curpos); ASSERT(sz == pt->filepos - curpos, "error reading parent callstack data"); IF_DEBUG(sz = ) dr_write_file(f_callstack, buf, pt->filepos - curpos); ASSERT(sz == pt->filepos - curpos, "error writing parent callstack data"); } else LOG(0, "ERROR: unable to copy parent callstack file\n"); close_file(f_parent_callstack); reset_to_time_zero(false/*start time over*/); } #endif #ifdef LINUX dr_signal_action_t event_signal(void *drcontext, dr_siginfo_t *info) { if (info->sig == SIGSEGV && ZERO_STACK() && handle_zeroing_fault(drcontext, info->access_address, info->raw_mcontext, info->mcontext)) { return DR_SIGNAL_SUPPRESS; } return DR_SIGNAL_DELIVER; } #else bool event_exception(void *drcontext, dr_exception_t *excpt) { if (excpt->record->ExceptionCode == STATUS_ACCESS_VIOLATION) { app_pc target = (app_pc) excpt->record->ExceptionInformation[1]; if (ZERO_STACK() && excpt->record->ExceptionInformation[0] == 1 /* write */ && handle_zeroing_fault(drcontext, target, excpt->raw_mcontext, excpt->mcontext)) { return false; } } return true; } #endif bool event_restore_state_nop(void *drcontext, bool restore_memory, dr_restore_state_info_t *info) { /* nothing: just here to avoid DR warning on zeroing loop faulting instrs */ return true; } static bool event_filter_syscall(void *drcontext, int sysnum) { switch (sysnum) { #ifdef LINUX case SYS_close: case SYS_fork: case SYS_clone: IF_VMX86(case 1025:) return true; #endif default: return alloc_syscall_filter(drcontext, sysnum); } } static bool event_pre_syscall(void *drcontext, int sysnum) { tls_heapstat_t *pt = (tls_heapstat_t *) drmgr_get_tls_field(drcontext, tls_idx_heapstat); cls_heapstat_t *cpt = (cls_heapstat_t *) drmgr_get_cls_field(drcontext, cls_idx_heapstat); int i; dr_mcontext_t mc; /* do not init whole thing: memset is expensive */ mc.size = sizeof(mc); mc.flags = DR_MC_CONTROL|DR_MC_INTEGER; /* don't need xmm */ dr_get_mcontext(drcontext, &mc); /* FIXME: share this code w/ drmemory/syscall.c */ /* save params for post-syscall access * FIXME: it's possible for a pathological app to crash us here * by setting up stack so that our blind reading of SYSCALL_NUM_ARG_STORE * params will hit unreadable page. */ for (i = 0; i < SYSCALL_NUM_ARG_STORE; i++) cpt->sysarg[i] = dr_syscall_get_param(drcontext, i); handle_pre_alloc_syscall(drcontext, sysnum, &mc, cpt->sysarg, SYSCALL_NUM_ARG_STORE); #ifdef LINUX if (sysnum == SYS_fork || (sysnum == SYS_clone && !TEST(CLONE_VM, (uint) dr_syscall_get_param(drcontext, 0))) /* FIXME: if open-sourced we should split this. * Presumably we'll have the bora shlib split before then. */ IF_VMX86(|| sysnum == 1025)) { /* Store the file offset in the client_data field, shared across callbacks */ pt->filepos = dr_file_tell(f_callstack); LOG(1, "SYS_fork: callstack file @ "INT64_FORMAT_STRING"\n", pt->filepos); } #endif return true; /* execute syscall */ } static void event_post_syscall(void *drcontext, int sysnum) { cls_heapstat_t *cpt = (cls_heapstat_t *) drmgr_get_cls_field(drcontext, cls_idx_heapstat); dr_mcontext_t mc; /* do not init whole thing: memset is expensive */ mc.size = sizeof(mc); mc.flags = DR_MC_CONTROL|DR_MC_INTEGER; /* don't need xmm */ dr_get_mcontext(drcontext, &mc); handle_post_alloc_syscall(drcontext, sysnum, &mc, cpt->sysarg, SYSCALL_NUM_ARG_STORE); } static void check_for_leaks(bool at_exit) { if (options.check_leaks) { void *drcontext = dr_get_current_drcontext(); ssize_t len = 0; size_t sofar = 0; char *buf; size_t bufsz; leak_scan_for_leaks(at_exit); get_buffer(drcontext, &buf, &bufsz); BUFPRINT(buf, bufsz, sofar, len, "ERRORS IGNORED:\n %5d still-reachable allocation(s)\n", reachable_leak_count); if (!options.show_reachable) { BUFPRINT(buf, bufsz, sofar, len, " (re-run with \"-check_leaks -show_reachable\"" " for details)\n"); } print_buffer(f_global, buf); release_buffer(drcontext, buf, bufsz); } } static void print_nudge_header(file_t f) { dr_fprintf(f, "NUDGE @ %16"INT64_FORMAT"u %s\n\n", snaps[snap_idx].stamp, unit_name()); } static void event_nudge(void *drcontext, uint64 argument) { uint64 snapshot_fpos = 0; uint64 staleness_fpos = 0; /* PR 476043: use nudge to output snapshots for daemon app. For * now we have only one use, so we don't need the argument, but we * may want an option to reset the start point for whole-run * vs since-last-nudge snapshots: though that would require * changing all usage types to be signed (PR 553707) so we * keep everything absolute w/ no reset on nudge. */ /* We hold the malloc lock across the snapshot + reset to prevent * new allocs being added in between */ malloc_lock(); /* must be acquired before snapshot_lock */ nudge_count++; snapshot_dump_all(); print_nudge_header(f_snapshot); print_nudge_header(f_callstack); if (options.dump) { /* For const # snapshots, we want the peak to be the global peak for the * whole run, regardless of how many nudges were done. * For dump-as-you-go, we want a local peak since the last nudge. */ free_snapshot(&snap_peak); memset(&snap_peak, 0, sizeof(snap_peak)); } if (options.staleness) print_nudge_header(f_staleness); /* Print the nudge index information, i.e., for each nudge, print the file * position in snapshot.log that marks the begining of new data after nudge * data was dumped. This makes nudge handling efficient as opposed to * building the index during the post process stage which would require a * full pass of the snapshot.log file which can be large. The same applies * to staleness.log. Also specify whether snapshots are fixed in number or * variable (-dump). PR 502468. */ snapshot_fpos = dr_file_tell(f_snapshot); if (options.staleness) staleness_fpos = dr_file_tell(f_staleness); ASSERT(snapshot_fpos >= 0 && staleness_fpos >= 0, "bad log file location"); dr_fprintf(f_nudge, "%d,%"INT64_FORMAT"u,%"INT64_FORMAT"u\n", nudge_count, snapshot_fpos, staleness_fpos); malloc_unlock(); check_for_leaks(false/*!at_exit*/); print_nudge_header(f_global); NOTIFY("Received nudge"NL, logsubdir); } static void event_module_load(void *drcontext, const module_data_t *info, bool loaded) { callstack_module_load(drcontext, info, loaded); alloc_module_load(drcontext, info, loaded); } static void event_module_unload(void *drcontext, const module_data_t *info) { callstack_module_unload(drcontext, info); alloc_module_unload(drcontext, info); } static void event_fragment_delete(void *drcontext, void *tag) { instrument_fragment_delete(drcontext, tag); alloc_fragment_delete(drcontext, tag); } static void event_context_init(void *drcontext, bool new_depth) { cls_heapstat_t *data; if (new_depth) { data = (cls_heapstat_t *) thread_alloc(drcontext, sizeof(*data), HEAPSTAT_MISC); drmgr_set_cls_field(drcontext, cls_idx_heapstat, data); } else data = (cls_heapstat_t *) drmgr_get_cls_field(drcontext, cls_idx_heapstat); memset(data, 0, sizeof(*data)); } static void event_context_exit(void *drcontext, bool thread_exit) { if (thread_exit) { cls_heapstat_t *cpt = (cls_heapstat_t *) drmgr_get_cls_field(drcontext, cls_idx_heapstat); thread_free(drcontext, cpt, sizeof(*cpt), HEAPSTAT_MISC); } /* else, nothing to do: we leave the struct for re-use on next callback */ } static void event_thread_init(void *drcontext) { uint which_thread = atomic_add32_return_sum((volatile int *)&num_threads, 1) - 1; file_t f; tls_heapstat_t *pt = (tls_heapstat_t *) thread_alloc(drcontext, sizeof(*pt), HEAPSTAT_MISC); memset(pt, 0, sizeof(*pt)); drmgr_set_tls_field(drcontext, tls_idx_heapstat, (void *)pt); utils_thread_init(drcontext); LOGF(0, f_global, "new thread #%d id=%d\n", which_thread, dr_get_thread_id(drcontext)); if (!options.thread_logs) { f = f_global; } else { /* we're going to dump our data to a per-thread file */ f = open_logfile("thread", false, which_thread/*tid suffix*/); LOGPT(1, PT_GET(drcontext), "thread logfile fd=%d\n", f); } utils_thread_set_file(drcontext, f); pt->errbufsz = MAX_ERROR_INITIAL_LINES + max_callstack_size(); pt->errbuf = (char *) thread_alloc(drcontext, pt->errbufsz, HEAPSTAT_MISC); LOGPT(2, PT_GET(drcontext), "in event_thread_init()\n"); callstack_thread_init(drcontext); if (options.check_leaks || options.staleness) shadow_thread_init(drcontext); if (options.staleness) instrument_thread_init(drcontext); } static void event_thread_exit(void *drcontext) { tls_heapstat_t *pt = (tls_heapstat_t *) drmgr_get_tls_field(drcontext, tls_idx_heapstat); LOGPT(2, PT_GET(drcontext), "in event_thread_exit()\n"); if (options.staleness) instrument_thread_init(drcontext); callstack_thread_exit(drcontext); utils_thread_exit(drcontext); thread_free(drcontext, (void *) pt->errbuf, pt->errbufsz, HEAPSTAT_MISC); /* with PR 536058 we do have dcontext in exit event so indicate explicitly * that we've cleaned up the per-thread data */ drmgr_set_tls_field(drcontext, tls_idx_heapstat, NULL); thread_free(drcontext, pt, sizeof(*pt), HEAPSTAT_MISC); } static void event_exit(void) { LOGF(2, f_global, "in event_exit\n"); if (options.time_clock || options.staleness) { sideline_exit = true; if (options.thread_logs) { /* i#297: sideline_run never gets a chance to clean up so we do it */ ASSERT(sideline_pt != NULL, "sideline per-thread error"); global_free(sideline_pt, sizeof(*sideline_pt), HEAPSTAT_MISC); } } snapshot_exit(); if (options.check_leaks) { check_for_leaks(true/*at_exit*/); leak_exit(); } heap_region_exit(); alloc_exit(); /* must be before deleting alloc_stack_table */ LOG(1, "final alloc stack table size: %u bits, %u entries\n", alloc_stack_table.table_bits, alloc_stack_table.entries); hashtable_delete(&alloc_stack_table); #ifdef CHECK_WITH_MD5 hashtable_delete(&alloc_md5_table); #endif callstack_exit(); if (options.staleness) instrument_exit(); if (options.check_leaks || options.staleness) shadow_exit(); free_shared_code(); utils_exit(); #ifdef STATISTICS dump_statistics(); #endif drmgr_unregister_tls_field(tls_idx_heapstat); drmgr_unregister_cls_field(event_context_init, event_context_exit, cls_idx_heapstat); drwrap_exit(); drmgr_exit(); dr_fprintf(f_global, "LOG END\n"); close_file(f_global); dr_fprintf(f_callstack, "LOG END\n"); close_file(f_callstack); dr_fprintf(f_snapshot, "LOG END\n"); close_file(f_snapshot); if (options.staleness) { dr_fprintf(f_staleness, "LOG END\n"); close_file(f_staleness); } close_file(f_nudge); } DR_EXPORT void dr_init(client_id_t client_id) { const char *opstr = dr_get_options(client_id); alloc_options_t alloc_ops; drmgr_priority_t priority = {sizeof(priority), "drheapstat", NULL, NULL, 1000}; ASSERT(opstr != NULL, "error obtaining option string"); drheap_options_init(opstr); drmgr_init(); /* must be before utils_init and any other tls/cls uses */ tls_idx_heapstat = drmgr_register_tls_field(); ASSERT(tls_idx_heapstat > -1, "unable to reserve TLS slot"); cls_idx_heapstat = drmgr_register_cls_field (event_context_init, event_context_exit); ASSERT(cls_idx_heapstat > -1, "unable to reserve CLS field"); drwrap_init(); utils_init(); /* now that we know whether -quiet, print basic info */ NOTIFY("Dr. Heapstat version %s"NL, VERSION_STRING); NOTIFY("options are \"%s\""NL, opstr); create_global_logfile(); LOG(0, "options are \"%s\"\n", opstr); dr_register_exit_event(event_exit); drmgr_register_thread_init_event(event_thread_init); drmgr_register_thread_exit_event(event_thread_exit); if (!drmgr_register_bb_instrumentation_ex_event (event_bb_app2app, event_bb_analysis, event_bb_insert, event_bb_instru2instru, &priority)) ASSERT(false, "drmgr registration failed"); dr_register_module_load_event(event_module_load); dr_register_module_unload_event(event_module_unload); #ifdef LINUX dr_register_fork_init_event(event_fork); #endif if (ZERO_STACK()) { #ifdef LINUX dr_register_signal_event(event_signal); #else dr_register_exception_event(event_exception); #endif } dr_register_filter_syscall_event(event_filter_syscall); drmgr_register_pre_syscall_event(event_pre_syscall); dr_register_post_syscall_event(event_post_syscall); dr_register_nudge_event(event_nudge, client_id); if (options.staleness) dr_register_restore_state_ex_event(event_restore_state); /* DR complains if we have xl8 fields and faults w/o restore-state events */ else if (ZERO_STACK()) dr_register_restore_state_ex_event(event_restore_state_nop); if (options.staleness) dr_register_delete_event(event_fragment_delete); /* make it easy to tell, by looking at log file, which client executed */ dr_log(NULL, LOG_ALL, 1, "client = Dr. Heapstat version %s\n", VERSION_STRING); snapshot_init(); callstack_init(options.callstack_max_frames, 0x10000 /*stack_swap_threshold*/, /* default flags: but if we have apps w/ DGC we may * want to expose some flags as options */ 0, /* scan forward 1 page: good compromise bet perf (scanning * can be the bottleneck) and good callstacks */ PAGE_SIZE, /* XXX i#926: symbolize and suppress leaks online (and then * use options.callstack_style here) */ PRINT_FOR_POSTPROCESS, NULL, /* get_syscall_name */ /* XXX: may need better callstack heuristics w/o shadow info * if user turns off stack zeroing from -leaks_only */ NULL, IF_WINDOWS_ELSE(is_in_seh_unwind, NULL), NULL, NULL, NULL, NULL, NULL _IF_DEBUG(0)); heap_region_init(client_heap_add, client_heap_remove); /* We keep callstacks around forever and only free when we delete * the alloc_stack_table, so no refcounts */ memset(&alloc_ops, 0, sizeof(alloc_ops)); alloc_ops.track_allocs = true; alloc_ops.track_heap = true; alloc_ops.redzone_size = 0; /* no redzone */ alloc_ops.size_in_redzone = false; alloc_ops.record_allocs = true; alloc_ops.get_padded_size = true; alloc_ops.cache_postcall = false; alloc_ops.intercept_operators = false; alloc_ops.conservative = options.conservative; alloc_init(&alloc_ops, sizeof(alloc_ops)); hashtable_init_ex(&alloc_stack_table, ASTACK_TABLE_HASH_BITS, HASH_CUSTOM, false/*!str_dup*/, false/* !synch; + higher-level synch covered * by malloc_table's lock */, alloc_callstack_free, #ifdef USE_MD5 (uint (*)(void*)) md5_hash, (bool (*)(void*, void*)) md5_digests_equal #else (uint (*)(void*)) crc32_whole_and_half_hash, (bool (*)(void*, void*)) crc32_whole_and_half_equal #endif ); #ifdef CHECK_WITH_MD5 hashtable_init_ex(&alloc_md5_table, ASTACK_TABLE_HASH_BITS, HASH_CUSTOM, false/*!str_dup*/, false/* !synch; + higher-level synch covered * by malloc_table's lock */, NULL/*points at md5 data stored in alloc_stack_table*/, (uint (*)(void*)) md5_hash, (bool (*)(void*, void*)) md5_digests_equal); #endif /* must be before heap_walk() */ if (options.check_leaks || options.staleness) shadow_init(); /* must be after heap_region_init and snapshot_init */ heap_walk(); if (options.staleness) instrument_init(); create_shared_code(); if (options.time_clock) timestamp_last_snapshot = dr_get_milliseconds(); if (options.time_clock || options.staleness) { if (!dr_create_client_thread(sideline_run, NULL)) { ASSERT(false, "unable to create thread"); } } if (options.check_leaks) { leak_init(false/*no defined info*/, options.check_leaks_on_destroy, options.midchunk_new_ok, options.midchunk_inheritance_ok, options.midchunk_string_ok, options.midchunk_size_ok, options.show_reachable, IF_WINDOWS_(options.check_encoded_pointers) NULL, NULL, NULL); } }
lgpl-2.1
KDE/kdewebkit
src/kwebpluginfactory.cpp
1
5795
/* * This file is part of the KDE project. * * Copyright (C) 2008 Michael Howell <mhowell123@gmail.com> * Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org> * Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "kwebpluginfactory.h" #include "kwebpage.h" #include "kwebview.h" #include <kmimetypetrader.h> #include <kservicetypetrader.h> #include <QDebug> #include <kio/job.h> #include <kparts/readonlypart.h> #include <kparts/openurlarguments.h> #include <QListIterator> #include <QStringList> #include <QList> #include <qmimedatabase.h> #include <QWebPluginFactory> #include <QWebFrame> #include <QWebView> #define QL1S(x) QLatin1String(x) #define QL1C(x) QLatin1Char(x) KWebPluginFactory::KWebPluginFactory(QObject *parent) : QWebPluginFactory(parent), d(nullptr) { } KWebPluginFactory::~KWebPluginFactory() { } QObject *KWebPluginFactory::create(const QString &_mimeType, const QUrl &url, const QStringList &argumentNames, const QStringList &argumentValues) const { QString mimeType(_mimeType.trimmed()); // If no mimetype is provided, we do our best to correctly determine it here... if (mimeType.isEmpty()) { // qDebug() << "Looking up missing mimetype for plugin resource:" << url; extractGuessedMimeType(url, &mimeType); // qDebug() << "Updated mimetype to" << mimeType; } // Defer handling of flash content to QtWebKit's builtin viewer. // If you want to use/test KDE's nspluginviewer, comment out the // if statement below. KParts::ReadOnlyPart *part = (excludedMimeType(mimeType) ? nullptr : createPartInstanceFrom(mimeType, argumentNames, argumentValues, nullptr, parent())); // qDebug() << "Asked for" << mimeType << "plugin, got" << part; if (part) { QMap<QString, QString> metaData = part->arguments().metaData(); QString urlStr = url.toString(QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment); metaData.insert("PropagateHttpHeader", "true"); metaData.insert("referrer", urlStr); metaData.insert("cross-domain", urlStr); metaData.insert("main_frame_request", "TRUE"); metaData.insert("ssl_activate_warnings", "TRUE"); KWebPage *page = qobject_cast<KWebPage *>(parent()); if (page) { const QString scheme = page->currentFrame()->url().scheme(); if (page && (QString::compare(scheme, QL1S("https"), Qt::CaseInsensitive) == 0 || QString::compare(scheme, QL1S("webdavs"), Qt::CaseInsensitive) == 0)) { metaData.insert("ssl_was_in_use", "TRUE"); } else { metaData.insert("ssl_was_in_use", "FALSE"); } } KParts::OpenUrlArguments openUrlArgs = part->arguments(); openUrlArgs.metaData() = metaData; openUrlArgs.setMimeType(mimeType); part->setArguments(openUrlArgs); part->openUrl(url); return part->widget(); } return nullptr; } QList<KWebPluginFactory::Plugin> KWebPluginFactory::plugins() const { QList<Plugin> plugins; return plugins; } static bool isHttpProtocol(const QUrl &url) { const QString scheme(url.scheme()); return (scheme.startsWith(QL1S("http"), Qt::CaseInsensitive) || scheme.startsWith(QL1S("webdav"), Qt::CaseInsensitive)); } void KWebPluginFactory::extractGuessedMimeType(const QUrl &url, QString *mimeType) const { if (mimeType) { const QUrl reqUrl((isHttpProtocol(url) ? QUrl(url.path()) : url)); QMimeDatabase db; QMimeType mime = db.mimeTypeForFile(reqUrl.path(), QMimeDatabase::MatchExtension); if (!mime.isDefault() && !mime.name().startsWith(QL1S("inode/"))) { *mimeType = mime.name(); } } } KParts::ReadOnlyPart *KWebPluginFactory::createPartInstanceFrom(const QString &mimeType, const QStringList &argumentNames, const QStringList &argumentValues, QWidget *parentWidget, QObject *parentObj) const { KParts::ReadOnlyPart *part = nullptr; if (!mimeType.isEmpty()) { // Only attempt to find a KPart for the supported mime types... QVariantList arguments; const int count = argumentNames.count(); for (int i = 0; i < count; ++i) { arguments << QString(argumentNames.at(i) + QL1S("=\"") + argumentValues.at(i) + QL1C('\"')); } part = KMimeTypeTrader::createPartInstanceFromQuery<KParts::ReadOnlyPart>(mimeType, parentWidget, parentObj, QString(), arguments); } return part; } bool KWebPluginFactory::excludedMimeType(const QString &mimeType) const { if (mimeType.startsWith(QL1S("inode/"), Qt::CaseInsensitive)) { return true; } if (mimeType.startsWith(QL1S("application/x-java"), Qt::CaseInsensitive)) { return true; } if (mimeType == QL1S("application/x-shockwave-flash") || mimeType == QL1S("application/futuresplash")) { return true; } return false; }
lgpl-2.1
KDE/peruse
src/common/peruse_helpers.cpp
1
3574
#include "peruse_helpers.h" #include <QQmlEngine> #include <QString> #include <QQmlComponent> #include <QQmlContext> #include <QStandardPaths> #include <QApplication> #include <QOpenGLContext> #include <QOffscreenSurface> #include <QOpenGLFunctions> #include <QDebug> #include <QDir> #include <QtQuick/QQuickView> #include <KAboutData> #include <KCrash> #include <KLocalizedContext> #include <KQuickIconProvider> #include "peruse_helpers.h" namespace PeruseHelpers { int getMaxTextureSize() { int maxSize = 0; // Create a temp context - required if this is called from another thread QOpenGLContext ctx; if ( !ctx.create() ) { // TODO handle the error qDebug() << "No OpenGL context could be created, this is clearly bad..."; exit(-1); } // rather than using a QWindow - which actually doesn't seem to work in this case either! QOffscreenSurface surface; surface.setFormat( ctx.format() ); surface.create(); ctx.makeCurrent(&surface); // Now the call works QOpenGLFunctions glFuncs(QOpenGLContext::currentContext()); glFuncs.glEnable(GL_TEXTURE_2D); glFuncs.glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize); return maxSize; } int init(QString &path, QApplication& app, const QString &filename) { QQmlEngine engine; engine.addImageProvider(QStringLiteral("icon"), new KQuickIconProvider); engine.rootContext()->setContextObject(new KLocalizedContext(&app)); bool osIsWindows = false; #ifdef Q_OS_WIN // Because windows is a bit funny with paths and whatnot, just so the thing with the lib paths... QDir appdir(qApp->applicationDirPath()); appdir.cdUp(); qApp->addLibraryPath(appdir.canonicalPath() + "/lib"); engine.addImportPath(appdir.canonicalPath() + "/lib/qml"); engine.addImportPath(appdir.canonicalPath() + "/qml"); osIsWindows = true; #endif engine.rootContext()->setContextProperty("osIsWindows", osIsWindows); engine.rootContext()->setContextProperty("fileToOpen", filename); QQmlContext* objectContext = engine.rootContext(); QString platformEnv(qgetenv("PLASMA_PLATFORM")); engine.rootContext()->setContextProperty("PLASMA_PLATFORM", platformEnv); // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for // things like the archive book model to create imageproviders for the archives engine.rootContext()->setContextProperty("globalQmlEngine", &engine); engine.rootContext()->setContextProperty("maxTextureSize", getMaxTextureSize()); engine.rootContext()->setContextProperty(QStringLiteral("peruseAboutData"), QVariant::fromValue(KAboutData::applicationData())); QQmlComponent component(&engine, path); if (component.isError()) { qCritical() << "Failed to load the component from disk. Reported error was:" << component.errorString(); return -1; } if (component.status() != QQmlComponent::Ready) { qCritical() << "Failed to make the Qt Quick component ready. Status is:" << component.status(); return -3; } QObject* obj = component.create(objectContext); if (!obj) { qCritical() << "Failed to create an object from our component"; return -2; } QQuickWindow* window = qobject_cast<QQuickWindow*>(obj); QObject::connect(window, &QQuickView::sceneGraphError, &app, [] (QQuickWindow::SceneGraphError /*error*/, const QString &message) { KCrash::setErrorMessage(message); qFatal("%s", qPrintable(message)); }); return app.exec(); } }
lgpl-2.1
bblacey/FreeCAD-MacOS-CI
src/Mod/Sketcher/Gui/ViewProviderSketch.cpp
2
265972
/*************************************************************************** * Copyright (c) 2009 Juergen Riegel <juergen.riegel@web.de> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Standard_math.hxx> # include <Poly_Polygon3D.hxx> # include <Geom_BSplineCurve.hxx> # include <Geom_Circle.hxx> # include <Geom_Ellipse.hxx> # include <Geom_TrimmedCurve.hxx> # include <Inventor/actions/SoGetBoundingBoxAction.h> # include <Inventor/SoPath.h> # include <Inventor/SbBox3f.h> # include <Inventor/SbImage.h> # include <Inventor/SoPickedPoint.h> # include <Inventor/details/SoLineDetail.h> # include <Inventor/details/SoPointDetail.h> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoDrawStyle.h> # include <Inventor/nodes/SoImage.h> # include <Inventor/nodes/SoInfo.h> # include <Inventor/nodes/SoLineSet.h> # include <Inventor/nodes/SoPointSet.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoMaterial.h> # include <Inventor/nodes/SoAsciiText.h> # include <Inventor/nodes/SoTransform.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoAnnotation.h> # include <Inventor/nodes/SoVertexProperty.h> # include <Inventor/nodes/SoTranslation.h> # include <Inventor/nodes/SoText2.h> # include <Inventor/nodes/SoFont.h> # include <Inventor/nodes/SoPickStyle.h> # include <Inventor/nodes/SoCamera.h> /// Qt Include Files # include <QAction> # include <QApplication> # include <QColor> # include <QDialog> # include <QFont> # include <QImage> # include <QMenu> # include <QMessageBox> # include <QPainter> # include <QTextStream> #endif #ifndef _PreComp_ # include <boost/bind.hpp> #endif #include <Inventor/SbTime.h> #include <boost/scoped_ptr.hpp> /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Tools.h> #include <Base/Parameter.h> #include <Base/Console.h> #include <Base/Vector3D.h> #include <Base/Interpreter.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Document.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Selection.h> #include <Gui/Utilities.h> #include <Gui/MainWindow.h> #include <Gui/MenuManager.h> #include <Gui/View3DInventor.h> #include <Gui/View3DInventorViewer.h> #include <Gui/DlgEditFileIncludeProptertyExternal.h> #include <Gui/SoFCBoundingBox.h> #include <Gui/SoFCUnifiedSelection.h> #include <Gui/Inventor/MarkerBitmaps.h> #include <Mod/Part/App/Geometry.h> #include <Mod/Part/App/BodyBase.h> #include <Mod/Sketcher/App/SketchObject.h> #include <Mod/Sketcher/App/Sketch.h> #include "SoZoomTranslation.h" #include "SoDatumLabel.h" #include "EditDatumDialog.h" #include "ViewProviderSketch.h" #include "DrawSketchHandler.h" #include "TaskDlgEditSketch.h" #include "TaskSketcherValidation.h" // The first is used to point at a SoDatumLabel for some // constraints, and at a SoMaterial for others... #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 // Macros to define information layer node child positions within type #define GEOINFO_BSPLINE_DEGREE_POS 0 #define GEOINFO_BSPLINE_DEGREE_TEXT 3 #define GEOINFO_BSPLINE_POLYGON 1 using namespace SketcherGui; using namespace Sketcher; SbColor ViewProviderSketch::VertexColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::CurveColor (1.0f,1.0f,1.0f); // #FFFFFF -> (255,255,255) SbColor ViewProviderSketch::CurveDraftColor (0.0f,0.0f,0.86f); // #0000DC -> ( 0, 0,220) SbColor ViewProviderSketch::CurveExternalColor (0.8f,0.2f,0.6f); // #CC3399 -> (204, 51,153) SbColor ViewProviderSketch::CrossColorH (0.8f,0.4f,0.4f); // #CC6666 -> (204,102,102) SbColor ViewProviderSketch::CrossColorV (0.4f,0.8f,0.4f); // #66CC66 -> (102,204,102) SbColor ViewProviderSketch::FullyConstrainedColor (0.0f,1.0f,0.0f); // #00FF00 -> ( 0,255, 0) SbColor ViewProviderSketch::ConstrDimColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::ConstrIcoColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::NonDrivingConstrDimColor (0.0f,0.149f,1.0f); // #0026FF -> ( 0, 38,255) SbColor ViewProviderSketch::InformationColor (0.0f,1.0f,0.0f); // #00FF00 -> ( 0,255, 0) SbColor ViewProviderSketch::PreselectColor (0.88f,0.88f,0.0f); // #E1E100 -> (225,225, 0) SbColor ViewProviderSketch::SelectColor (0.11f,0.68f,0.11f); // #1CAD1C -> ( 28,173, 28) SbColor ViewProviderSketch::PreselectSelectedColor (0.36f,0.48f,0.11f); // #5D7B1C -> ( 93,123, 28) // Variables for holding previous click SbTime ViewProviderSketch::prvClickTime; SbVec3f ViewProviderSketch::prvClickPoint; SbVec2s ViewProviderSketch::prvCursorPos; SbVec2s ViewProviderSketch::newCursorPos; //************************************************************************** // Edit data structure /// Data structure while editing the sketch struct EditData { EditData(): sketchHandler(0), editDatumDialog(false), buttonPress(false), DragPoint(-1), DragCurve(-1), PreselectPoint(-1), PreselectCurve(-1), PreselectCross(-1), MarkerSize(7), blockedPreselection(false), FullyConstrained(false), //ActSketch(0), // if you are wondering, it went to SketchObject, accessible via getSketchObject()->getSolvedSketch() EditRoot(0), PointsMaterials(0), CurvesMaterials(0), RootCrossMaterials(0), EditCurvesMaterials(0), PointsCoordinate(0), CurvesCoordinate(0), RootCrossCoordinate(0), EditCurvesCoordinate(0), CurveSet(0), RootCrossSet(0), EditCurveSet(0), PointSet(0), textX(0), textPos(0), constrGroup(0), infoGroup(0), pickStyleAxes(0) {} // pointer to the active handler for new sketch objects DrawSketchHandler *sketchHandler; bool editDatumDialog; bool buttonPress; // dragged point int DragPoint; // dragged curve int DragCurve; // dragged constraints std::set<int> DragConstraintSet; SbColor PreselectOldColor; int PreselectPoint; int PreselectCurve; int PreselectCross; int MarkerSize; std::set<int> PreselectConstraintSet; bool blockedPreselection; bool FullyConstrained; // container to track our own selected parts std::set<int> SelPointSet; std::set<int> SelCurvSet; // also holds cross axes at -1 and -2 std::set<int> SelConstraintSet; std::vector<int> CurvIdToGeoId; // conversion of SoLineSet index to GeoId // helper data structures for the constraint rendering std::vector<ConstraintType> vConstrType; // For each of the combined constraint icons drawn, also create a vector // of bounding boxes and associated constraint IDs, to go from the icon's // pixel coordinates to the relevant constraint IDs. // // The outside map goes from a string representation of a set of constraint // icons (like the one used by the constraint IDs we insert into the Coin // rendering tree) to a vector of those bounding boxes paired with relevant // constraint IDs. std::map<QString, ViewProviderSketch::ConstrIconBBVec> combinedConstrBoxes; // nodes for the visuals SoSeparator *EditRoot; SoMaterial *PointsMaterials; SoMaterial *CurvesMaterials; SoMaterial *RootCrossMaterials; SoMaterial *EditCurvesMaterials; SoCoordinate3 *PointsCoordinate; SoCoordinate3 *CurvesCoordinate; SoCoordinate3 *RootCrossCoordinate; SoCoordinate3 *EditCurvesCoordinate; SoLineSet *CurveSet; SoLineSet *RootCrossSet; SoLineSet *EditCurveSet; SoMarkerSet *PointSet; SoText2 *textX; SoTranslation *textPos; SoGroup *constrGroup; SoGroup *infoGroup; SoPickStyle *pickStyleAxes; }; // this function is used to simulate cyclic periodic negative geometry indices (for external geometry) const Part::Geometry* GeoById(const std::vector<Part::Geometry*> GeoList, int Id) { if (Id >= 0) return GeoList[Id]; else return GeoList[GeoList.size()+Id]; } //************************************************************************** // Construction/Destruction /* TRANSLATOR SketcherGui::ViewProviderSketch */ PROPERTY_SOURCE(SketcherGui::ViewProviderSketch, PartGui::ViewProvider2DObject) ViewProviderSketch::ViewProviderSketch() : edit(0), Mode(STATUS_NONE), visibleInformationChanged(true) { ADD_PROPERTY_TYPE(Autoconstraints,(true),"Auto Constraints",(App::PropertyType)(App::Prop_None),"Create auto constraints"); ADD_PROPERTY_TYPE(TempoVis,(Py::None()),"Visibility automation",(App::PropertyType)(App::Prop_None),"Object that handles hiding and showing other objects when entering/leaving sketch."); ADD_PROPERTY_TYPE(HideDependent,(true),"Visibility automation",(App::PropertyType)(App::Prop_None),"If true, all objects that depend on the sketch are hidden when opening editing."); ADD_PROPERTY_TYPE(ShowLinks,(true),"Visibility automation",(App::PropertyType)(App::Prop_None),"If true, all objects used in links to external geometry are shown when opening sketch."); ADD_PROPERTY_TYPE(ShowSupport,(true),"Visibility automation",(App::PropertyType)(App::Prop_None),"If true, all objects this sketch is attached to are shown when opening sketch."); ADD_PROPERTY_TYPE(RestoreCamera,(true),"Visibility automation",(App::PropertyType)(App::Prop_None),"If true, camera position before entering sketch is remembered, and restored after closing it."); {//visibility automation: update defaults to follow preferences ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); this->HideDependent.setValue(hGrp->GetBool("HideDependent", true)); this->ShowLinks.setValue(hGrp->GetBool("ShowLinks", true)); this->ShowSupport.setValue(hGrp->GetBool("ShowSupport", true)); this->RestoreCamera.setValue(hGrp->GetBool("RestoreCamera", true)); } sPixmap = "Sketcher_Sketch"; LineColor.setValue(1,1,1); PointColor.setValue(1,1,1); PointSize.setValue(4); zCross=0.001f; zLines=0.005f; zConstr=0.007f; // constraint not construction zHighLine=0.006f; zPoints=0.008f; zHighlight=0.009f; zText=0.011f; zEdit=0.001f; zInfo=0.004f; xInit=0; yInit=0; relative=false; unsigned long color; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); // edge color App::Color edgeColor = LineColor.getValue(); color = (unsigned long)(edgeColor.getPackedValue()); color = hGrp->GetUnsigned("SketchEdgeColor", color); edgeColor.setPackedValue((uint32_t)color); LineColor.setValue(edgeColor); // vertex color App::Color vertexColor = PointColor.getValue(); color = (unsigned long)(vertexColor.getPackedValue()); color = hGrp->GetUnsigned("SketchVertexColor", color); vertexColor.setPackedValue((uint32_t)color); PointColor.setValue(vertexColor); //rubberband selection rubberband = new Gui::Rubberband(); } ViewProviderSketch::~ViewProviderSketch() { delete rubberband; } void ViewProviderSketch::slotUndoDocument(const Gui::Document& /*doc*/) { if(getSketchObject()->noRecomputes) getSketchObject()->solve(); // the sketch must be solved to update the DoF of the solver else getSketchObject()->getDocument()->recompute(); // or fully recomputed if applicable } void ViewProviderSketch::slotRedoDocument(const Gui::Document& /*doc*/) { if(getSketchObject()->noRecomputes) getSketchObject()->solve(); // the sketch must be solved to update the DoF of the solver else getSketchObject()->getDocument()->recompute(); // or fully recomputed if applicable } // handler management *************************************************************** void ViewProviderSketch::activateHandler(DrawSketchHandler *newHandler) { assert(edit); assert(edit->sketchHandler == 0); edit->sketchHandler = newHandler; Mode = STATUS_SKETCH_UseHandler; edit->sketchHandler->sketchgui = this; edit->sketchHandler->activated(this); } void ViewProviderSketch::deactivateHandler() { assert(edit); if(edit->sketchHandler != 0){ std::vector<Base::Vector2d> editCurve; editCurve.clear(); drawEdit(editCurve); // erase any line edit->sketchHandler->deactivated(this); edit->sketchHandler->unsetCursor(); delete(edit->sketchHandler); } edit->sketchHandler = 0; Mode = STATUS_NONE; } /// removes the active handler void ViewProviderSketch::purgeHandler(void) { deactivateHandler(); // ensure that we are in sketch only selection mode Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); Gui::View3DInventorViewer *viewer; viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(false); } void ViewProviderSketch::setAxisPickStyle(bool on) { assert(edit); if (on) edit->pickStyleAxes->style = SoPickStyle::SHAPE; else edit->pickStyleAxes->style = SoPickStyle::UNPICKABLE; } // ********************************************************************************** bool ViewProviderSketch::keyPressed(bool pressed, int key) { switch (key) { case SoKeyboardEvent::ESCAPE: { // make the handler quit but not the edit mode if (edit && edit->sketchHandler) { if (!pressed) edit->sketchHandler->quit(); return true; } if (edit && edit->editDatumDialog) { edit->editDatumDialog = false; return true; } if (edit && (edit->DragConstraintSet.empty() == false)) { if (!pressed) { edit->DragConstraintSet.clear(); } return true; } if (edit && edit->DragCurve >= 0) { if (!pressed) { getSketchObject()->movePoint(edit->DragCurve, Sketcher::none, Base::Vector3d(0,0,0), true); edit->DragCurve = -1; resetPositionText(); Mode = STATUS_NONE; } return true; } if (edit && edit->DragPoint >= 0) { if (!pressed) { int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); getSketchObject()->movePoint(GeoId, PosId, Base::Vector3d(0,0,0), true); edit->DragPoint = -1; resetPositionText(); Mode = STATUS_NONE; } return true; } if (edit) { // #0001479: 'Escape' key dismissing dialog cancels Sketch editing // If we receive a button release event but not a press event before // then ignore this one. if (!pressed && !edit->buttonPress) return true; edit->buttonPress = pressed; } return false; } default: { if (edit && edit->sketchHandler) edit->sketchHandler->registerPressedKey(pressed,key); } } return true; // handle all other key events } void ViewProviderSketch::snapToGrid(double &x, double &y) { if (GridSnap.getValue() != false) { // Snap Tolerance in pixels const double snapTol = GridSize.getValue() / 5; double tmpX = x, tmpY = y; // Find Nearest Snap points tmpX = tmpX / GridSize.getValue(); tmpX = tmpX < 0.0 ? ceil(tmpX - 0.5) : floor(tmpX + 0.5); tmpX *= GridSize.getValue(); tmpY = tmpY / GridSize.getValue(); tmpY = tmpY < 0.0 ? ceil(tmpY - 0.5) : floor(tmpY + 0.5); tmpY *= GridSize.getValue(); // Check if x within snap tolerance if (x < tmpX + snapTol && x > tmpX - snapTol) x = tmpX; // Snap X Mouse Position // Check if y within snap tolerance if (y < tmpY + snapTol && y > tmpY - snapTol) y = tmpY; // Snap Y Mouse Position } } void ViewProviderSketch::getProjectingLine(const SbVec2s& pnt, const Gui::View3DInventorViewer *viewer, SbLine& line) const { const SbViewportRegion& vp = viewer->getSoRenderManager()->getViewportRegion(); short x,y; pnt.getValue(x,y); SbVec2f siz = vp.getViewportSize(); float dX, dY; siz.getValue(dX, dY); float fRatio = vp.getViewportAspectRatio(); float pX = (float)x / float(vp.getViewportSizePixels()[0]); float pY = (float)y / float(vp.getViewportSizePixels()[1]); // now calculate the real points respecting aspect ratio information // if (fRatio > 1.0f) { pX = (pX - 0.5f*dX) * fRatio + 0.5f*dX; } else if (fRatio < 1.0f) { pY = (pY - 0.5f*dY) / fRatio + 0.5f*dY; } SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) return; SbViewVolume vol = pCam->getViewVolume(); vol.projectPointToLine(SbVec2f(pX,pY), line); } void ViewProviderSketch::getCoordsOnSketchPlane(double &u, double &v,const SbVec3f &point, const SbVec3f &normal) { // Plane form Base::Vector3d R0(0,0,0),RN(0,0,1),RX(1,0,0),RY(0,1,0); // move to position of Sketch Base::Placement Plz = getPlacement(); R0 = Plz.getPosition() ; Base::Rotation tmp(Plz.getRotation()); tmp.multVec(RN,RN); tmp.multVec(RX,RX); tmp.multVec(RY,RY); Plz.setRotation(tmp); // line Base::Vector3d R1(point[0],point[1],point[2]),RA(normal[0],normal[1],normal[2]); if (fabs(RN*RA) < FLT_EPSILON) throw Base::DivisionByZeroError("View direction is parallel to sketch plane"); // intersection point on plane Base::Vector3d S = R1 + ((RN * (R0-R1))/(RN*RA))*RA; // distance to x Axle of the sketch S.TransformToCoordinateSystem(R0,RX,RY); u = S.x; v = S.y; } bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVec2s &cursorPos, const Gui::View3DInventorViewer *viewer) { assert(edit); // Calculate 3d point to the mouse position SbLine line; getProjectingLine(cursorPos, viewer, line); SbVec3f point = line.getPosition(); SbVec3f normal = line.getDirection(); // use scoped_ptr to make sure that instance gets deleted in all cases boost::scoped_ptr<SoPickedPoint> pp(this->getPointOnRay(cursorPos, viewer)); // Radius maximum to allow double click event const int dblClickRadius = 5; double x,y; SbVec3f pos = point; if (pp) { const SoDetail *detail = pp->getDetail(); if (detail && detail->getTypeId() == SoPointDetail::getClassTypeId()) { pos = pp->getPoint(); } } try { getCoordsOnSketchPlane(x,y,pos,normal); snapToGrid(x, y); } catch (const Base::DivisionByZeroError&) { return false; } // Left Mouse button **************************************************** if (Button == 1) { if (pressed) { // Do things depending on the mode of the user interaction switch (Mode) { case STATUS_NONE:{ bool done=false; if (edit->PreselectPoint != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Point; done = true; } else if (edit->PreselectCurve != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Edge; done = true; } else if (edit->PreselectCross != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Cross; done = true; } else if (edit->PreselectConstraintSet.empty() != true) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Constraint; done = true; } // Double click events variables float dci = (float) QApplication::doubleClickInterval()/1000.0f; if (done && (point - prvClickPoint).length() < dblClickRadius && (SbTime::getTimeOfDay() - prvClickTime).getValue() < dci) { // Double Click Event Occurred editDoubleClicked(); // Reset Double Click Static Variables prvClickTime = SbTime(); prvClickPoint = SbVec3f(0.0f, 0.0f, 0.0f); Mode = STATUS_NONE; } else { prvClickTime = SbTime::getTimeOfDay(); prvClickPoint = point; prvCursorPos = cursorPos; newCursorPos = cursorPos; if (!done) Mode = STATUS_SKETCH_StartRubberBand; } return done; } case STATUS_SKETCH_UseHandler: return edit->sketchHandler->pressButton(Base::Vector2d(x,y)); default: return false; } } else { // Button 1 released // Do things depending on the mode of the user interaction switch (Mode) { case STATUS_SELECT_Point: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); // Do selection std::stringstream ss; ss << "Vertex" << edit->PreselectPoint + 1; if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Edge: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); std::stringstream ss; if (edit->PreselectCurve >= 0) ss << "Edge" << edit->PreselectCurve + 1; else // external geometry ss << "ExternalEdge" << -edit->PreselectCurve - 2; // If edge already selected move from selection if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { // Add edge to the selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Cross: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); std::stringstream ss; switch(edit->PreselectCross){ case 0: ss << "RootPoint" ; break; case 1: ss << "H_Axis" ; break; case 2: ss << "V_Axis" ; break; } // If cross already selected move from selection if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { // Add cross to the selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Constraint: if (pp) { for(std::set<int>::iterator it = edit->PreselectConstraintSet.begin(); it != edit->PreselectConstraintSet.end(); ++it) { std::string constraintName(Sketcher::PropertyConstraintList::getConstraintName(*it)); // If the constraint already selected remove if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),constraintName.c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), constraintName.c_str()); } else { // Add constraint to current selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,constraintName.c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } } Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragPoint: if (edit->DragPoint != -1) { int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { Gui::Command::openCommand("Drag Point"); try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.movePoint(%i,%i,App.Vector(%f,%f,0),%i)" ,getObject()->getNameInDocument() ,GeoId, PosId, x-xInit, y-yInit, relative ? 1 : 0 ); Gui::Command::commitCommand(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); bool autoRecompute = hGrp->GetBool("AutoRecompute",false); if(autoRecompute) Gui::Command::updateActive(); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); Base::Console().Error("Drag point: %s\n", e.what()); } } setPreselectPoint(edit->DragPoint); edit->DragPoint = -1; //updateColor(); } resetPositionText(); Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragCurve: if (edit->DragCurve != -1) { const Part::Geometry *geo = getSketchObject()->getGeometry(edit->DragCurve); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || geo->getTypeId() == Part::GeomCircle::getClassTypeId() || geo->getTypeId() == Part::GeomEllipse::getClassTypeId()|| geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()|| geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()|| geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()|| geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { Gui::Command::openCommand("Drag Curve"); try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.movePoint(%i,%i,App.Vector(%f,%f,0),%i)" ,getObject()->getNameInDocument() ,edit->DragCurve, Sketcher::none, x-xInit, y-yInit, relative ? 1 : 0 ); Gui::Command::commitCommand(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); bool autoRecompute = hGrp->GetBool("AutoRecompute",false); if(autoRecompute) Gui::Command::updateActive(); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); Base::Console().Error("Drag curve: %s\n", e.what()); } } edit->PreselectCurve = edit->DragCurve; edit->DragCurve = -1; //updateColor(); } resetPositionText(); Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragConstraint: if (edit->DragConstraintSet.empty() == false) { Gui::Command::openCommand("Drag Constraint"); for(std::set<int>::iterator it = edit->DragConstraintSet.begin(); it != edit->DragConstraintSet.end(); ++it) { moveConstraint(*it, Base::Vector2d(x, y)); //updateColor(); } edit->PreselectConstraintSet = edit->DragConstraintSet; edit->DragConstraintSet.clear(); } Mode = STATUS_NONE; return true; case STATUS_SKETCH_StartRubberBand: // a single click happened, so clear selection Mode = STATUS_NONE; Gui::Selection().clearSelection(); return true; case STATUS_SKETCH_UseRubberBand: doBoxSelection(prvCursorPos, cursorPos, viewer); rubberband->setWorking(false); //disable framebuffer drawing in viewer const_cast<Gui::View3DInventorViewer *>(viewer)->setRenderType(Gui::View3DInventorViewer::Native); // a redraw is required in order to clear the rubberband draw(true,false); Mode = STATUS_NONE; return true; case STATUS_SKETCH_UseHandler: return edit->sketchHandler->releaseButton(Base::Vector2d(x,y)); case STATUS_NONE: default: return false; } } } // Right mouse button **************************************************** else if (Button == 2) { if (!pressed) { switch (Mode) { case STATUS_SKETCH_UseHandler: // make the handler quit edit->sketchHandler->quit(); return true; case STATUS_NONE: { // A right click shouldn't change the Edit Mode if (edit->PreselectPoint != -1) { return true; } else if (edit->PreselectCurve != -1) { return true; } else if (edit->PreselectConstraintSet.empty() != true) { return true; } else { Gui::MenuItem *geom = new Gui::MenuItem(); geom->setCommand("Sketcher geoms"); *geom << "Sketcher_CreatePoint" << "Sketcher_CreateArc" << "Sketcher_Create3PointArc" << "Sketcher_CreateCircle" << "Sketcher_Create3PointCircle" << "Sketcher_CreateLine" << "Sketcher_CreatePolyline" << "Sketcher_CreateRectangle" << "Sketcher_CreateHexagon" << "Sketcher_CreateFillet" << "Sketcher_Trimming" << "Sketcher_External" << "Sketcher_ToggleConstruction" /*<< "Sketcher_CreateText"*/ /*<< "Sketcher_CreateDraftLine"*/ << "Separator"; Gui::Application::Instance->setupContextMenu("View", geom); //Create the Context Menu using the Main View Qt Widget QMenu contextMenu(viewer->getGLWidget()); Gui::MenuManager::getInstance()->setupContextMenu(geom, contextMenu); contextMenu.exec(QCursor::pos()); return true; } } case STATUS_SELECT_Point: break; case STATUS_SELECT_Edge: { Gui::MenuItem *geom = new Gui::MenuItem(); geom->setCommand("Sketcher constraints"); *geom << "Sketcher_ConstrainVertical" << "Sketcher_ConstrainHorizontal"; // Gets a selection vector std::vector<Gui::SelectionObject> selection = Gui::Selection().getSelectionEx(); bool rightClickOnSelectedLine = false; /* * Add Multiple Line Constraints to the menu */ // only one sketch with its subelements are allowed to be selected if (selection.size() == 1) { // get the needed lists and objects const std::vector<std::string> &SubNames = selection[0].getSubNames(); // Two Objects are selected if (SubNames.size() == 2) { // go through the selected subelements for (std::vector<std::string>::const_iterator it=SubNames.begin(); it!=SubNames.end();++it) { // If the object selected is of type edge if (it->size() > 4 && it->substr(0,4) == "Edge") { // Get the index of the object selected int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; if (edit->PreselectCurve == GeoId) rightClickOnSelectedLine = true; } else { // The selection is not exclusively edges rightClickOnSelectedLine = false; } } // End of Iteration } } if (rightClickOnSelectedLine) { *geom << "Sketcher_ConstrainParallel" << "Sketcher_ConstrainPerpendicular"; } Gui::Application::Instance->setupContextMenu("View", geom); //Create the Context Menu using the Main View Qt Widget QMenu contextMenu(viewer->getGLWidget()); Gui::MenuManager::getInstance()->setupContextMenu(geom, contextMenu); contextMenu.exec(QCursor::pos()); return true; } case STATUS_SELECT_Cross: case STATUS_SELECT_Constraint: case STATUS_SKETCH_DragPoint: case STATUS_SKETCH_DragCurve: case STATUS_SKETCH_DragConstraint: case STATUS_SKETCH_StartRubberBand: case STATUS_SKETCH_UseRubberBand: break; } } } return false; } void ViewProviderSketch::editDoubleClicked(void) { if (edit->PreselectPoint != -1) { Base::Console().Log("double click point:%d\n",edit->PreselectPoint); } else if (edit->PreselectCurve != -1) { Base::Console().Log("double click edge:%d\n",edit->PreselectCurve); } else if (edit->PreselectCross != -1) { Base::Console().Log("double click cross:%d\n",edit->PreselectCross); } else if (edit->PreselectConstraintSet.empty() != true) { // Find the constraint const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); for(std::set<int>::iterator it = edit->PreselectConstraintSet.begin(); it != edit->PreselectConstraintSet.end(); ++it) { Constraint *Constr = constrlist[*it]; // if its the right constraint if ((Constr->Type == Sketcher::Distance || Constr->Type == Sketcher::DistanceX || Constr->Type == Sketcher::DistanceY || Constr->Type == Sketcher::Radius || Constr->Type == Sketcher::Angle || Constr->Type == Sketcher::SnellsLaw) && Constr->isDriving ) { // Coin's SoIdleSensor causes problems on some platform while Qt seems to work properly (#0001517) EditDatumDialog *editDatumDialog = new EditDatumDialog(this, *it); QCoreApplication::postEvent(editDatumDialog, new QEvent(QEvent::User)); edit->editDatumDialog = true; // avoid to double handle "ESC" } } } } bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventorViewer *viewer) { // maximum radius for mouse moves when selecting a geometry before switching to drag mode const int dragIgnoredDistance = 3; if (!edit) return false; // ignore small moves after selection switch (Mode) { case STATUS_SELECT_Point: case STATUS_SELECT_Edge: case STATUS_SELECT_Constraint: case STATUS_SKETCH_StartRubberBand: short dx, dy; (cursorPos - prvCursorPos).getValue(dx, dy); if(std::abs(dx) < dragIgnoredDistance && std::abs(dy) < dragIgnoredDistance) return false; default: break; } // Calculate 3d point to the mouse position SbLine line; getProjectingLine(cursorPos, viewer, line); double x,y; try { getCoordsOnSketchPlane(x,y,line.getPosition(),line.getDirection()); snapToGrid(x, y); } catch (const Base::DivisionByZeroError&) { return false; } bool preselectChanged = false; if (Mode != STATUS_SELECT_Point && Mode != STATUS_SELECT_Edge && Mode != STATUS_SELECT_Constraint && Mode != STATUS_SKETCH_DragPoint && Mode != STATUS_SKETCH_DragCurve && Mode != STATUS_SKETCH_DragConstraint && Mode != STATUS_SKETCH_UseRubberBand) { boost::scoped_ptr<SoPickedPoint> pp(this->getPointOnRay(cursorPos, viewer)); preselectChanged = detectPreselection(pp.get(), viewer, cursorPos); } switch (Mode) { case STATUS_NONE: if (preselectChanged) { this->drawConstraintIcons(); this->updateColor(); return true; } return false; case STATUS_SELECT_Point: if (!getSketchObject()->getSolvedSketch().hasConflicts() && edit->PreselectPoint != -1 && edit->DragPoint != edit->PreselectPoint) { Mode = STATUS_SKETCH_DragPoint; edit->DragPoint = edit->PreselectPoint; int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { getSketchObject()->getSolvedSketch().initMove(GeoId, PosId, false); relative = false; xInit = 0; yInit = 0; } } else { Mode = STATUS_NONE; } resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SELECT_Edge: if (!getSketchObject()->getSolvedSketch().hasConflicts() && edit->PreselectCurve != -1 && edit->DragCurve != edit->PreselectCurve) { Mode = STATUS_SKETCH_DragCurve; edit->DragCurve = edit->PreselectCurve; getSketchObject()->getSolvedSketch().initMove(edit->DragCurve, Sketcher::none, false); const Part::Geometry *geo = getSketchObject()->getGeometry(edit->DragCurve); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() || geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() ) { relative = true; //xInit = x; //yInit = y; // Since the cursor moved from where it was clicked, and this is a relative move, // calculate the click position and use it as initial point. SbLine line2; getProjectingLine(prvCursorPos, viewer, line2); getCoordsOnSketchPlane(xInit,yInit,line2.getPosition(),line2.getDirection()); snapToGrid(xInit, yInit); } else { relative = false; xInit = 0; yInit = 0; } } else { Mode = STATUS_NONE; } resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SELECT_Constraint: Mode = STATUS_SKETCH_DragConstraint; edit->DragConstraintSet = edit->PreselectConstraintSet; resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SKETCH_DragPoint: if (edit->DragPoint != -1) { //Base::Console().Log("Drag Point:%d\n",edit->DragPoint); int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); Base::Vector3d vec(x-xInit,y-yInit,0); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { if (getSketchObject()->getSolvedSketch().movePoint(GeoId, PosId, vec, relative) == 0) { setPositionText(Base::Vector2d(x,y)); draw(true,false); signalSolved(QString::fromLatin1("Solved in %1 sec").arg(getSketchObject()->getSolvedSketch().SolveTime)); } else { signalSolved(QString::fromLatin1("Unsolved (%1 sec)").arg(getSketchObject()->getSolvedSketch().SolveTime)); //Base::Console().Log("Error solving:%d\n",ret); } } } return true; case STATUS_SKETCH_DragCurve: if (edit->DragCurve != -1) { Base::Vector3d vec(x-xInit,y-yInit,0); if (getSketchObject()->getSolvedSketch().movePoint(edit->DragCurve, Sketcher::none, vec, relative) == 0) { setPositionText(Base::Vector2d(x,y)); draw(true,false); signalSolved(QString::fromLatin1("Solved in %1 sec").arg(getSketchObject()->getSolvedSketch().SolveTime)); } else { signalSolved(QString::fromLatin1("Unsolved (%1 sec)").arg(getSketchObject()->getSolvedSketch().SolveTime)); } } return true; case STATUS_SKETCH_DragConstraint: if (edit->DragConstraintSet.empty() == false) { for(std::set<int>::iterator it = edit->DragConstraintSet.begin(); it != edit->DragConstraintSet.end(); ++it) moveConstraint(*it, Base::Vector2d(x,y)); } return true; case STATUS_SKETCH_UseHandler: edit->sketchHandler->mouseMove(Base::Vector2d(x,y)); if (preselectChanged) { this->drawConstraintIcons(); this->updateColor(); } return true; case STATUS_SKETCH_StartRubberBand: { Mode = STATUS_SKETCH_UseRubberBand; rubberband->setWorking(true); viewer->setRenderType(Gui::View3DInventorViewer::Image); return true; } case STATUS_SKETCH_UseRubberBand: { newCursorPos = cursorPos; rubberband->setCoords(prvCursorPos.getValue()[0], viewer->getGLWidget()->height() - prvCursorPos.getValue()[1], newCursorPos.getValue()[0], viewer->getGLWidget()->height() - newCursorPos.getValue()[1]); viewer->redraw(); return true; } default: return false; } return false; } void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d &toPos) { // are we in edit? if (!edit) return; const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); Constraint *Constr = constrlist[constNum]; #ifdef _DEBUG int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; int extGeoCount = getSketchObject()->getExternalGeometryCount(); #endif // with memory allocation const std::vector<Part::Geometry *> geomlist = getSketchObject()->getSolvedSketch().extractGeometry(true, true); #ifdef _DEBUG assert(int(geomlist.size()) == extGeoCount + intGeoCount); assert((Constr->First >= -extGeoCount && Constr->First < intGeoCount) || Constr->First != Constraint::GeoUndef); #endif if (Constr->Type == Distance || Constr->Type == DistanceX || Constr->Type == DistanceY || Constr->Type == Radius) { Base::Vector3d p1(0.,0.,0.), p2(0.,0.,0.); if (Constr->SecondPos != Sketcher::none) { // point to point distance p1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); p2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); } else if (Constr->Second != Constraint::GeoUndef) { // point to line distance p1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); const Part::Geometry *geo = GeoById(geomlist, Constr->Second); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(geo); Base::Vector3d l2p1 = lineSeg->getStartPoint(); Base::Vector3d l2p2 = lineSeg->getEndPoint(); // calculate the projection of p1 onto line2 p2.ProjectToLine(p1-l2p1, l2p2-l2p1); p2 += p1; } else return; } else if (Constr->FirstPos != Sketcher::none) { p2 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(geo); p1 = lineSeg->getStartPoint(); p2 = lineSeg->getEndPoint(); } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo); double radius = arc->getRadius(); p1 = arc->getCenter(); double angle = Constr->LabelPosition; if (angle == 10) { double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle = (startangle + endangle)/2; } else { Base::Vector3d tmpDir = Base::Vector3d(toPos.x, toPos.y, 0) - p1; angle = atan2(tmpDir.y, tmpDir.x); } p2 = p1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(geo); double radius = circle->getRadius(); p1 = circle->getCenter(); Base::Vector3d tmpDir = Base::Vector3d(toPos.x, toPos.y, 0) - p1; double angle = atan2(tmpDir.y, tmpDir.x); p2 = p1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else return; } else return; Base::Vector3d vec = Base::Vector3d(toPos.x, toPos.y, 0) - p2; Base::Vector3d dir; if (Constr->Type == Distance || Constr->Type == Radius) dir = (p2-p1).Normalize(); else if (Constr->Type == DistanceX) dir = Base::Vector3d( (p2.x - p1.x >= FLT_EPSILON) ? 1 : -1, 0, 0); else if (Constr->Type == DistanceY) dir = Base::Vector3d(0, (p2.y - p1.y >= FLT_EPSILON) ? 1 : -1, 0); if (Constr->Type == Radius) { Constr->LabelDistance = vec.x * dir.x + vec.y * dir.y; Constr->LabelPosition = atan2(dir.y, dir.x); } else { Base::Vector3d norm(-dir.y,dir.x,0); Constr->LabelDistance = vec.x * norm.x + vec.y * norm.y; if (Constr->Type == Distance || Constr->Type == DistanceX || Constr->Type == DistanceY) { vec = Base::Vector3d(toPos.x, toPos.y, 0) - (p2 + p1) / 2; Constr->LabelPosition = vec.x * dir.x + vec.y * dir.y; } } } else if (Constr->Type == Angle) { Base::Vector3d p0(0.,0.,0.); double factor = 0.5; if (Constr->Second != Constraint::GeoUndef) { // line to line angle Base::Vector3d dir1, dir2; if(Constr->Third == Constraint::GeoUndef) { //angle between two lines const Part::Geometry *geo1 = GeoById(geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(geomlist, Constr->Second); if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) return; const Part::GeomLineSegment *lineSeg1 = static_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = static_cast<const Part::GeomLineSegment *>(geo2); bool flip1 = (Constr->FirstPos == end); bool flip2 = (Constr->SecondPos == end); dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); Base::Vector3d pnt1 = flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); Base::Vector3d pnt2 = flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); // line-line intersection { double det = dir1.x*dir2.y - dir1.y*dir2.x; if ((det > 0 ? det : -det) < 1e-10) return;// lines are parallel - constraint unmoveable (DeepSOIC: why?..) double c1 = dir1.y*pnt1.x - dir1.x*pnt1.y; double c2 = dir2.y*pnt2.x - dir2.x*pnt2.y; double x = (dir1.x*c2 - dir2.x*c1)/det; double y = (dir1.y*c2 - dir2.y*c1)/det; // intersection point p0 = Base::Vector3d(x,y,0); Base::Vector3d vec = Base::Vector3d(toPos.x, toPos.y, 0) - p0; factor = factor * Base::sgn<double>((dir1+dir2) * vec); } } else {//angle-via-point Base::Vector3d p = getSketchObject()->getSolvedSketch().getPoint(Constr->Third, Constr->ThirdPos); p0 = Base::Vector3d(p.x, p.y, 0); dir1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, p.y); dir1.RotateZ(-M_PI/2);//convert to vector of tangency by rotating dir2 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, p.y); dir2.RotateZ(-M_PI/2); Base::Vector3d vec = Base::Vector3d(toPos.x, toPos.y, 0) - p0; factor = factor * Base::sgn<double>((dir1+dir2) * vec); } } else if (Constr->First != Constraint::GeoUndef) { // line/arc angle const Part::Geometry *geo = GeoById(geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(geo); p0 = (lineSeg->getEndPoint()+lineSeg->getStartPoint())/2; } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo); p0 = arc->getCenter(); } else { return; } } else return; Base::Vector3d vec = Base::Vector3d(toPos.x, toPos.y, 0) - p0; Constr->LabelDistance = factor * vec.Length(); } // delete the cloned objects for (std::vector<Part::Geometry *>::const_iterator it=geomlist.begin(); it != geomlist.end(); ++it) if (*it) delete *it; draw(true,false); } Base::Vector3d ViewProviderSketch::seekConstraintPosition(const Base::Vector3d &origPos, const Base::Vector3d &norm, const Base::Vector3d &dir, float step, const SoNode *constraint) { assert(edit); Gui::MDIView *mdi = this->getViewOfNode(edit->EditRoot); if (!(mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))) return Base::Vector3d(0, 0, 0); Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoRayPickAction rp(viewer->getSoRenderManager()->getViewportRegion()); float scaled_step = step * getScaleFactor(); int multiplier = 0; Base::Vector3d relPos, freePos; bool isConstraintAtPosition = true; while (isConstraintAtPosition && multiplier < 10) { // Calculate new position of constraint relPos = norm * 0.5f + dir * multiplier; freePos = origPos + relPos * scaled_step; rp.setRadius(0.1f); rp.setPickAll(true); rp.setRay(SbVec3f(freePos.x, freePos.y, -1.f), SbVec3f(0, 0, 1) ); //problem rp.apply(edit->constrGroup); // We could narrow it down to just the SoGroup containing the constraints // returns a copy of the point SoPickedPoint *pp = rp.getPickedPoint(); const SoPickedPointList ppl = rp.getPickedPointList(); if (ppl.getLength() <= 1 && pp) { SoPath *path = pp->getPath(); int length = path->getLength(); SoNode *tailFather1 = path->getNode(length-2); SoNode *tailFather2 = path->getNode(length-3); // checking if a constraint is the same as the one selected if (tailFather1 == constraint || tailFather2 == constraint) isConstraintAtPosition = false; } else { isConstraintAtPosition = false; } multiplier *= -1; // search in both sides if (multiplier >= 0) multiplier++; // Increment the multiplier } if (multiplier == 10) relPos = norm * 0.5f; // no free position found return relPos * step; } bool ViewProviderSketch::isSelectable(void) const { if (isEditing()) return false; else return PartGui::ViewProvider2DObject::isSelectable(); } void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) { // are we in edit? if (edit) { bool handled=false; if (Mode == STATUS_SKETCH_UseHandler) { handled = edit->sketchHandler->onSelectionChanged(msg); } if (handled) return; std::string temp; if (msg.Type == Gui::SelectionChanges::ClrSelection) { // if something selected in this object? if (edit->SelPointSet.size() > 0 || edit->SelCurvSet.size() > 0 || edit->SelConstraintSet.size() > 0) { // clear our selection and update the color of the viewed edges and points clearSelectPoints(); edit->SelCurvSet.clear(); edit->SelConstraintSet.clear(); this->drawConstraintIcons(); this->updateColor(); } } else if (msg.Type == Gui::SelectionChanges::AddSelection) { // is it this object?? if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; edit->SelCurvSet.insert(GeoId); this->updateColor(); } else if (shapetype.size() > 12 && shapetype.substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(&shapetype[12]) - 1; GeoId = -GeoId - 3; edit->SelCurvSet.insert(GeoId); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int VtId = std::atoi(&shapetype[6]) - 1; addSelectPoint(VtId); this->updateColor(); } else if (shapetype == "RootPoint") { addSelectPoint(Sketcher::GeoEnum::RtPnt); this->updateColor(); } else if (shapetype == "H_Axis") { edit->SelCurvSet.insert(Sketcher::GeoEnum::HAxis); this->updateColor(); } else if (shapetype == "V_Axis") { edit->SelCurvSet.insert(Sketcher::GeoEnum::VAxis); this->updateColor(); } else if (shapetype.size() > 10 && shapetype.substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); edit->SelConstraintSet.insert(ConstrId); this->drawConstraintIcons(); this->updateColor(); } } } } else if (msg.Type == Gui::SelectionChanges::RmvSelection) { // Are there any objects selected if (edit->SelPointSet.size() > 0 || edit->SelCurvSet.size() > 0 || edit->SelConstraintSet.size() > 0) { // is it this object?? if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; edit->SelCurvSet.erase(GeoId); this->updateColor(); } else if (shapetype.size() > 12 && shapetype.substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(&shapetype[12]) - 1; GeoId = -GeoId - 3; edit->SelCurvSet.erase(GeoId); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int VtId = std::atoi(&shapetype[6]) - 1; removeSelectPoint(VtId); this->updateColor(); } else if (shapetype == "RootPoint") { removeSelectPoint(Sketcher::GeoEnum::RtPnt); this->updateColor(); } else if (shapetype == "H_Axis") { edit->SelCurvSet.erase(Sketcher::GeoEnum::HAxis); this->updateColor(); } else if (shapetype == "V_Axis") { edit->SelCurvSet.erase(Sketcher::GeoEnum::VAxis); this->updateColor(); } else if (shapetype.size() > 10 && shapetype.substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); edit->SelConstraintSet.erase(ConstrId); this->drawConstraintIcons(); this->updateColor(); } } } } } else if (msg.Type == Gui::SelectionChanges::SetSelection) { // remove all items //selectionView->clear(); //std::vector<SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(Reason.pDocName); //for (std::vector<SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) { // // build name // temp = it->DocName; // temp += "."; // temp += it->FeatName; // if (it->SubName && it->SubName[0] != '\0') { // temp += "."; // temp += it->SubName; // } // new QListWidgetItem(QString::fromLatin1(temp.c_str()), selectionView); //} } else if (msg.Type == Gui::SelectionChanges::SetPreselect) { if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; resetPreselectPoint(); edit->PreselectCurve = GeoId; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int PtIndex = std::atoi(&shapetype[6]) - 1; setPreselectPoint(PtIndex); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } } } } else if (msg.Type == Gui::SelectionChanges::RmvPreselect) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } } } std::set<int> ViewProviderSketch::detectPreselectionConstr(const SoPickedPoint *Point, const Gui::View3DInventorViewer *viewer, const SbVec2s &cursorPos) { std::set<int> constrIndices; SoPath *path = Point->getPath(); SoNode *tail = path->getTail(); SoNode *tailFather = path->getNode(path->getLength()-2); for (int i=0; i < edit->constrGroup->getNumChildren(); ++i) if (edit->constrGroup->getChild(i) == tailFather) { SoSeparator *sep = static_cast<SoSeparator *>(tailFather); if(sep->getNumChildren() > CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID) { SoInfo *constrIds = NULL; if(tail == sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON)) { // First icon was hit constrIds = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID)); } else { // Assume second icon was hit if(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID<sep->getNumChildren()){ constrIds = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID)); } } if(constrIds) { QString constrIdsStr = QString::fromLatin1(constrIds->string.getValue().getString()); if(edit->combinedConstrBoxes.count(constrIdsStr) && dynamic_cast<SoImage *>(tail)) { // If it's a combined constraint icon // Screen dimensions of the icon SbVec3s iconSize = getDisplayedSize(static_cast<SoImage *>(tail)); // Center of the icon SbVec2f iconCoords = viewer->screenCoordsOfPath(path); // Coordinates of the mouse cursor on the icon, origin at top-left int iconX = cursorPos[0] - iconCoords[0] + iconSize[0]/2, iconY = iconCoords[1] - cursorPos[1] + iconSize[1]/2; for(ConstrIconBBVec::iterator b = edit->combinedConstrBoxes[constrIdsStr].begin(); b != edit->combinedConstrBoxes[constrIdsStr].end(); ++b) { if(b->first.contains(iconX, iconY)) // We've found a bounding box that contains the mouse pointer! for(std::set<int>::iterator k = b->second.begin(); k != b->second.end(); ++k) constrIndices.insert(*k); } } else { // It's a constraint icon, not a combined one QStringList constrIdStrings = constrIdsStr.split(QString::fromLatin1(",")); while(!constrIdStrings.empty()) constrIndices.insert(constrIdStrings.takeAt(0).toInt()); } } } else { // other constraint icons - eg radius... constrIndices.clear(); constrIndices.insert(i); } break; } return constrIndices; } bool ViewProviderSketch::detectPreselection(const SoPickedPoint *Point, const Gui::View3DInventorViewer *viewer, const SbVec2s &cursorPos) { assert(edit); int PtIndex = -1; int GeoIndex = -1; // valid values are 0,1,2,... for normal geometry and -3,-4,-5,... for external geometry int CrossIndex = -1; std::set<int> constrIndices; if (Point) { //Base::Console().Log("Point pick\n"); SoPath *path = Point->getPath(); SoNode *tail = path->getTail(); SoNode *tailFather2 = path->getNode(path->getLength()-3); // checking for a hit in the points if (tail == edit->PointSet) { const SoDetail *point_detail = Point->getDetail(edit->PointSet); if (point_detail && point_detail->getTypeId() == SoPointDetail::getClassTypeId()) { // get the index PtIndex = static_cast<const SoPointDetail *>(point_detail)->getCoordinateIndex(); PtIndex -= 1; // shift corresponding to RootPoint if (PtIndex == Sketcher::GeoEnum::RtPnt) CrossIndex = 0; // RootPoint was hit } } else { // checking for a hit in the curves if (tail == edit->CurveSet) { const SoDetail *curve_detail = Point->getDetail(edit->CurveSet); if (curve_detail && curve_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index int curveIndex = static_cast<const SoLineDetail *>(curve_detail)->getLineIndex(); GeoIndex = edit->CurvIdToGeoId[curveIndex]; } // checking for a hit in the cross } else if (tail == edit->RootCrossSet) { const SoDetail *cross_detail = Point->getDetail(edit->RootCrossSet); if (cross_detail && cross_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index (reserve index 0 for root point) CrossIndex = 1 + static_cast<const SoLineDetail *>(cross_detail)->getLineIndex(); } } else { // checking if a constraint is hit if (tailFather2 == edit->constrGroup) constrIndices = detectPreselectionConstr(Point, viewer, cursorPos); } } if (PtIndex != -1 && PtIndex != edit->PreselectPoint) { // if a new point is hit std::stringstream ss; ss << "Vertex" << PtIndex + 1; bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { setPreselectPoint(PtIndex); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (GeoIndex != -1 && GeoIndex != edit->PreselectCurve) { // if a new curve is hit std::stringstream ss; if (GeoIndex >= 0) ss << "Edge" << GeoIndex + 1; else // external geometry ss << "ExternalEdge" << -GeoIndex + Sketcher::GeoEnum::RefExt + 1; // convert index start from -3 to 1 bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { resetPreselectPoint(); edit->PreselectCurve = GeoIndex; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (CrossIndex != -1 && CrossIndex != edit->PreselectCross) { // if a cross line is hit std::stringstream ss; switch(CrossIndex){ case 0: ss << "RootPoint" ; break; case 1: ss << "H_Axis" ; break; case 2: ss << "V_Axis" ; break; } bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { if (CrossIndex == 0) setPreselectPoint(-1); else resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = CrossIndex; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (constrIndices.empty() == false && constrIndices != edit->PreselectConstraintSet) { // if a constraint is hit bool accepted = true; for(std::set<int>::iterator it = constrIndices.begin(); it != constrIndices.end(); ++it) { std::string constraintName(Sketcher::PropertyConstraintList::getConstraintName(*it)); accepted &= Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,constraintName.c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; //TODO: Should we clear preselections that went through, if one fails? } if (accepted) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet = constrIndices; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true;//Preselection changed } } else if ((PtIndex == -1 && GeoIndex == -1 && CrossIndex == -1 && constrIndices.empty()) && (edit->PreselectPoint != -1 || edit->PreselectCurve != -1 || edit->PreselectCross != -1 || edit->PreselectConstraintSet.empty() != true || edit->blockedPreselection)) { // we have just left a preselection resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); edit->blockedPreselection = false; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } Gui::Selection().setPreselectCoord(Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); // if(Point) } else if (edit->PreselectCurve != -1 || edit->PreselectPoint != -1 || edit->PreselectConstraintSet.empty() != true || edit->PreselectCross != -1 || edit->blockedPreselection) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); edit->blockedPreselection = false; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } return false; } SbVec3s ViewProviderSketch::getDisplayedSize(const SoImage *iconPtr) const { #if (COIN_MAJOR_VERSION >= 3) SbVec3s iconSize = iconPtr->image.getValue().getSize(); #else SbVec2s size; int nc; const unsigned char * bytes = iconPtr->image.getValue(size, nc); SbImage img (bytes, size, nc); SbVec3s iconSize = img.getSize(); #endif if (iconPtr->width.getValue() != -1) iconSize[0] = iconPtr->width.getValue(); if (iconPtr->height.getValue() != -1) iconSize[1] = iconPtr->height.getValue(); return iconSize; } void ViewProviderSketch::centerSelection() { Gui::MDIView *mdi = this->getActiveView(); Gui::View3DInventor *view = qobject_cast<Gui::View3DInventor*>(mdi); if (!view || !edit) return; SoGroup* group = new SoGroup(); group->ref(); for (int i=0; i < edit->constrGroup->getNumChildren(); i++) { if (edit->SelConstraintSet.find(i) != edit->SelConstraintSet.end()) { SoSeparator *sep = dynamic_cast<SoSeparator *>(edit->constrGroup->getChild(i)); if (sep) group->addChild(sep); } } Gui::View3DInventorViewer* viewer = view->getViewer(); SoGetBoundingBoxAction action(viewer->getSoRenderManager()->getViewportRegion()); action.apply(group); group->unref(); SbBox3f box = action.getBoundingBox(); if (!box.isEmpty()) { SoCamera* camera = viewer->getSoRenderManager()->getCamera(); SbVec3f direction; camera->orientation.getValue().multVec(SbVec3f(0, 0, 1), direction); SbVec3f box_cnt = box.getCenter(); SbVec3f cam_pos = box_cnt + camera->focalDistance.getValue() * direction; camera->position.setValue(cam_pos); } } void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s &endPos, const Gui::View3DInventorViewer *viewer) { std::vector<SbVec2s> corners0; corners0.push_back(startPos); corners0.push_back(endPos); std::vector<SbVec2f> corners = viewer->getGLPolygon(corners0); // all calculations with polygon and proj are in dimensionless [0 1] screen coordinates Base::Polygon2d polygon; polygon.Add(Base::Vector2d(corners[0].getValue()[0], corners[0].getValue()[1])); polygon.Add(Base::Vector2d(corners[0].getValue()[0], corners[1].getValue()[1])); polygon.Add(Base::Vector2d(corners[1].getValue()[0], corners[1].getValue()[1])); polygon.Add(Base::Vector2d(corners[1].getValue()[0], corners[0].getValue()[1])); Gui::ViewVolumeProjection proj(viewer->getSoRenderManager()->getCamera()->getViewVolume()); Sketcher::SketchObject *sketchObject = getSketchObject(); App::Document *doc = sketchObject->getDocument(); Base::Placement Plm = getPlacement(); int intGeoCount = sketchObject->getHighestCurveIndex() + 1; int extGeoCount = sketchObject->getExternalGeometryCount(); const std::vector<Part::Geometry *> geomlist = sketchObject->getCompleteGeometry(); // without memory allocation assert(int(geomlist.size()) == extGeoCount + intGeoCount); assert(int(geomlist.size()) >= 2); Base::Vector3d pnt0, pnt1, pnt2, pnt; int VertexId = -1; // the loop below should be in sync with the main loop in ViewProviderSketch::draw // so that the vertex indices are calculated correctly int GeoId = 0; for (std::vector<Part::Geometry *>::const_iterator it = geomlist.begin(); it != geomlist.end()-2; ++it, ++GeoId) { if (GeoId >= intGeoCount) GeoId = -extGeoCount; if ((*it)->getTypeId() == Part::GeomPoint::getClassTypeId()) { // ----- Check if single point lies inside box selection -----/ const Part::GeomPoint *point = static_cast<const Part::GeomPoint *>(*it); Plm.multVec(point->getPoint(), pnt0); pnt0 = proj(pnt0); VertexId += 1; if (polygon.Contains(Base::Vector2d(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // ----- Check if line segment lies inside box selection -----/ const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(*it); Plm.multVec(lineSeg->getStartPoint(), pnt1); Plm.multVec(lineSeg->getEndPoint(), pnt2); pnt1 = proj(pnt1); pnt2 = proj(pnt2); VertexId += 2; bool pnt1Inside = polygon.Contains(Base::Vector2d(pnt1.x, pnt1.y)); bool pnt2Inside = polygon.Contains(Base::Vector2d(pnt2.x, pnt2.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt2Inside) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt1Inside && pnt2Inside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { // ----- Check if circle lies inside box selection -----/ const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(*it); pnt0 = circle->getCenter(); VertexId += 1; Plm.multVec(pnt0, pnt0); pnt0 = proj(pnt0); if (polygon.Contains(Base::Vector2d(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); int countSegments = 12; float segment = float(2 * M_PI) / countSegments; // circumscribed polygon radius float radius = float(circle->getRadius()) / cos(segment/2); bool bpolyInside = true; pnt0 = circle->getCenter(); float angle = 0.f; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = Base::Vector3d(pnt0.x + radius * cos(angle), pnt0.y + radius * sin(angle), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { ss.clear(); ss.str(""); ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(),ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { // ----- Check if circle lies inside box selection -----/ const Part::GeomEllipse *ellipse = static_cast<const Part::GeomEllipse *>(*it); pnt0 = ellipse->getCenter(); VertexId += 1; Plm.multVec(pnt0, pnt0); pnt0 = proj(pnt0); if (polygon.Contains(Base::Vector2d(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); int countSegments = 12; double segment = (2 * M_PI) / countSegments; // circumscribed polygon radius double a = (ellipse->getMajorRadius()) / cos(segment/2); double b = (ellipse->getMinorRadius()) / cos(segment/2); Base::Vector3d majdir = ellipse->getMajorAxisDir(); Base::Vector3d mindir = Base::Vector3d(-majdir.y, majdir.x, 0.0); bool bpolyInside = true; pnt0 = ellipse->getCenter(); double angle = 0.; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = pnt0 + (cos(angle)*a)*majdir + sin(angle)*b*mindir; Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { ss.clear(); ss.str(""); ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(),ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // Check if arc lies inside box selection const Part::GeomArcOfCircle *aoc = static_cast<const Part::GeomArcOfCircle *>(*it); pnt0 = aoc->getStartPoint(/*emulateCCW=*/true); pnt1 = aoc->getEndPoint(/*emulateCCW=*/true); pnt2 = aoc->getCenter(); VertexId += 3; Plm.multVec(pnt0, pnt0); Plm.multVec(pnt1, pnt1); Plm.multVec(pnt2, pnt2); pnt0 = proj(pnt0); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt0Inside = polygon.Contains(Base::Vector2d(pnt0.x, pnt0.y)); if (pnt0Inside) { std::stringstream ss; ss << "Vertex" << VertexId - 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } bool pnt1Inside = polygon.Contains(Base::Vector2d(pnt1.x, pnt1.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (polygon.Contains(Base::Vector2d(pnt2.x, pnt2.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt0Inside && pnt1Inside) { double startangle, endangle; aoc->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); float segment = float(range) / countSegments; // circumscribed polygon radius float radius = float(aoc->getRadius()) / cos(segment/2); bool bpolyInside = true; pnt0 = aoc->getCenter(); float angle = float(startangle) + segment/2; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = Base::Vector3d(pnt0.x + radius * cos(angle), pnt0.y + radius * sin(angle), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { // Check if arc lies inside box selection const Part::GeomArcOfEllipse *aoe = static_cast<const Part::GeomArcOfEllipse *>(*it); pnt0 = aoe->getStartPoint(/*emulateCCW=*/true); pnt1 = aoe->getEndPoint(/*emulateCCW=*/true); pnt2 = aoe->getCenter(); VertexId += 3; Plm.multVec(pnt0, pnt0); Plm.multVec(pnt1, pnt1); Plm.multVec(pnt2, pnt2); pnt0 = proj(pnt0); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt0Inside = polygon.Contains(Base::Vector2d(pnt0.x, pnt0.y)); if (pnt0Inside) { std::stringstream ss; ss << "Vertex" << VertexId - 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } bool pnt1Inside = polygon.Contains(Base::Vector2d(pnt1.x, pnt1.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (polygon.Contains(Base::Vector2d(pnt2.x, pnt2.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt0Inside && pnt1Inside) { double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); double segment = (range) / countSegments; // circumscribed polygon radius double a = (aoe->getMajorRadius()) / cos(segment/2); double b = (aoe->getMinorRadius()) / cos(segment/2); Base::Vector3d majdir = aoe->getMajorAxisDir(); Base::Vector3d mindir = Base::Vector3d(-majdir.y, majdir.x, 0.0); bool bpolyInside = true; pnt0 = aoe->getCenter(); double angle = (startangle) + segment/2; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = pnt0 + cos(angle)*a*majdir + sin(angle)*b*mindir; Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { // Check if arc lies inside box selection const Part::GeomArcOfHyperbola *aoh = static_cast<const Part::GeomArcOfHyperbola *>(*it); pnt0 = aoh->getStartPoint(); pnt1 = aoh->getEndPoint(); pnt2 = aoh->getCenter(); VertexId += 3; Plm.multVec(pnt0, pnt0); Plm.multVec(pnt1, pnt1); Plm.multVec(pnt2, pnt2); pnt0 = proj(pnt0); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt0Inside = polygon.Contains(Base::Vector2d(pnt0.x, pnt0.y)); if (pnt0Inside) { std::stringstream ss; ss << "Vertex" << VertexId - 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } bool pnt1Inside = polygon.Contains(Base::Vector2d(pnt1.x, pnt1.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (polygon.Contains(Base::Vector2d(pnt2.x, pnt2.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt0Inside && pnt1Inside) { double startangle, endangle; aoh->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); float segment = float(range) / countSegments; // circumscribed polygon radius float a = float(aoh->getMajorRadius()) / cos(segment/2); float b = float(aoh->getMinorRadius()) / cos(segment/2); float phi = float(aoh->getAngleXU()); bool bpolyInside = true; pnt0 = aoh->getCenter(); float angle = float(startangle) + segment/2; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = Base::Vector3d(pnt0.x + a * cosh(angle) * cos(phi) - b * sinh(angle) * sin(phi), pnt0.y + a * cosh(angle) * sin(phi) + b * sinh(angle) * cos(phi), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { // Check if arc lies inside box selection const Part::GeomArcOfParabola *aop = dynamic_cast<const Part::GeomArcOfParabola *>(*it); pnt0 = aop->getStartPoint(); pnt1 = aop->getEndPoint(); pnt2 = aop->getCenter(); VertexId += 3; Plm.multVec(pnt0, pnt0); Plm.multVec(pnt1, pnt1); Plm.multVec(pnt2, pnt2); pnt0 = proj(pnt0); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt0Inside = polygon.Contains(Base::Vector2d(pnt0.x, pnt0.y)); if (pnt0Inside) { std::stringstream ss; ss << "Vertex" << VertexId - 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } bool pnt1Inside = polygon.Contains(Base::Vector2d(pnt1.x, pnt1.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (polygon.Contains(Base::Vector2d(pnt2.x, pnt2.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt0Inside && pnt1Inside) { double startangle, endangle; aop->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); float segment = float(range) / countSegments; //In local coordinate system, value() of parabola is: //P(U) = O + U*U/(4.*F)*XDir + U*YDir // circumscribed polygon radius float focal = float(aop->getFocal()) / cos(segment/2); float phi = float(aop->getAngleXU()); bool bpolyInside = true; pnt0 = aop->getCenter(); float angle = float(startangle) + segment/2; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = Base::Vector3d(pnt0.x + angle * angle / 4 / focal * cos(phi) - angle * sin(phi), pnt0.y + angle * angle / 4 / focal * sin(phi) + angle * cos(phi), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { const Part::GeomBSplineCurve *spline = static_cast<const Part::GeomBSplineCurve *>(*it); //std::vector<Base::Vector3d> poles = spline->getPoles(); VertexId += 2; Plm.multVec(spline->getStartPoint(), pnt1); Plm.multVec(spline->getEndPoint(), pnt2); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt1Inside = polygon.Contains(Base::Vector2d(pnt1.x, pnt1.y)); bool pnt2Inside = polygon.Contains(Base::Vector2d(pnt2.x, pnt2.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt2Inside) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } // This is a rather approximated approach. No it does not guarantie that the whole curve is boxed, specially // for periodic curves, but it works reasonably well. Including all poles, which could be done, generally // forces the user to select much more than the curve (all the poles) and it would not select the curve in cases // where it is indeed comprised in the box. if (pnt1Inside && pnt2Inside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } pnt0 = proj(Plm.getPosition()); if (polygon.Contains(Base::Vector2d(pnt0.x, pnt0.y))) Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), "RootPoint"); } void ViewProviderSketch::updateColor(void) { assert(edit); //Base::Console().Log("Draw preseletion\n"); int PtNum = edit->PointsMaterials->diffuseColor.getNum(); SbColor *pcolor = edit->PointsMaterials->diffuseColor.startEditing(); int CurvNum = edit->CurvesMaterials->diffuseColor.getNum(); SbColor *color = edit->CurvesMaterials->diffuseColor.startEditing(); SbColor *crosscolor = edit->RootCrossMaterials->diffuseColor.startEditing(); SbVec3f *verts = edit->CurvesCoordinate->point.startEditing(); //int32_t *index = edit->CurveSet->numVertices.startEditing(); // colors of the point set if (edit->FullyConstrained) { for (int i=0; i < PtNum; i++) pcolor[i] = FullyConstrainedColor; } else { for (int i=0; i < PtNum; i++) pcolor[i] = VertexColor; } if (edit->PreselectCross == 0) { pcolor[0] = PreselectColor; } else if (edit->PreselectPoint != -1) { if (edit->PreselectPoint + 1 < PtNum) pcolor[edit->PreselectPoint + 1] = PreselectColor; } for (std::set<int>::iterator it = edit->SelPointSet.begin(); it != edit->SelPointSet.end(); ++it) { if (*it < PtNum) { pcolor[*it] = (*it==(edit->PreselectPoint + 1) && (edit->PreselectPoint != -1)) ? PreselectSelectedColor : SelectColor; } } // colors of the curves //int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; //int extGeoCount = getSketchObject()->getExternalGeometryCount(); float x,y,z; int j=0; // vertexindex for (int i=0; i < CurvNum; i++) { int GeoId = edit->CurvIdToGeoId[i]; // CurvId has several vertex a ssociated to 1 material //edit->CurveSet->numVertices => [i] indicates number of vertex for line i. int indexes = (edit->CurveSet->numVertices[i]); bool selected = (edit->SelCurvSet.find(GeoId) != edit->SelCurvSet.end()); bool preselected = (edit->PreselectCurve == GeoId); if (selected && preselected) { color[i] = PreselectSelectedColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (selected){ color[i] = SelectColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (preselected){ color[i] = PreselectColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (GeoId <= Sketcher::GeoEnum::RefExt) { // external Geometry color[i] = CurveExternalColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zConstr); } } else if (getSketchObject()->getGeometry(GeoId)->Construction) { color[i] = CurveDraftColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } else if (edit->FullyConstrained) { color[i] = FullyConstrainedColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } else { color[i] = CurveColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } } // colors of the cross if (edit->SelCurvSet.find(-1) != edit->SelCurvSet.end()) crosscolor[0] = SelectColor; else if (edit->PreselectCross == 1) crosscolor[0] = PreselectColor; else crosscolor[0] = CrossColorH; if (edit->SelCurvSet.find(Sketcher::GeoEnum::VAxis) != edit->SelCurvSet.end()) crosscolor[1] = SelectColor; else if (edit->PreselectCross == 2) crosscolor[1] = PreselectColor; else crosscolor[1] = CrossColorV; // colors of the constraints for (int i=0; i < edit->constrGroup->getNumChildren(); i++) { SoSeparator *s = static_cast<SoSeparator *>(edit->constrGroup->getChild(i)); // Check Constraint Type Sketcher::Constraint* constraint = getSketchObject()->Constraints.getValues()[i]; ConstraintType type = constraint->Type; bool hasDatumLabel = (type == Sketcher::Angle || type == Sketcher::Radius || type == Sketcher::Symmetric || type == Sketcher::Distance || type == Sketcher::DistanceX || type == Sketcher::DistanceY); // Non DatumLabel Nodes will have a material excluding coincident bool hasMaterial = false; SoMaterial *m = 0; if (!hasDatumLabel && type != Sketcher::Coincident && type != Sketcher::InternalAlignment) { hasMaterial = true; m = static_cast<SoMaterial *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); } if (edit->SelConstraintSet.find(i) != edit->SelConstraintSet.end()) { if (hasDatumLabel) { SoDatumLabel *l = static_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = SelectColor; } else if (hasMaterial) { m->diffuseColor = SelectColor; } else if (type == Sketcher::Coincident) { int index; index = getSketchObject()->getSolvedSketch().getPointId(constraint->First, constraint->FirstPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; index = getSketchObject()->getSolvedSketch().getPointId(constraint->Second, constraint->SecondPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; } else if (type == Sketcher::InternalAlignment) { switch(constraint->AlignmentType) { case EllipseMajorDiameter: case EllipseMinorDiameter: { // color line int CurvNum = edit->CurvesMaterials->diffuseColor.getNum(); for (int i=0; i < CurvNum; i++) { int cGeoId = edit->CurvIdToGeoId[i]; if(cGeoId == constraint->First) { color[i] = SelectColor; break; } } } break; case EllipseFocus1: case EllipseFocus2: { int index = getSketchObject()->getSolvedSketch().getPointId(constraint->First, constraint->FirstPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; } break; default: break; } } } else if (edit->PreselectConstraintSet.count(i)) { if (hasDatumLabel) { SoDatumLabel *l = static_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = PreselectColor; } else if (hasMaterial) { m->diffuseColor = PreselectColor; } } else { if (hasDatumLabel) { SoDatumLabel *l = static_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = constraint->isDriving?ConstrDimColor:NonDrivingConstrDimColor; } else if (hasMaterial) { m->diffuseColor = constraint->isDriving?ConstrDimColor:NonDrivingConstrDimColor; } } } // end editing edit->CurvesMaterials->diffuseColor.finishEditing(); edit->PointsMaterials->diffuseColor.finishEditing(); edit->RootCrossMaterials->diffuseColor.finishEditing(); edit->CurvesCoordinate->point.finishEditing(); edit->CurveSet->numVertices.finishEditing(); } bool ViewProviderSketch::isPointOnSketch(const SoPickedPoint *pp) const { // checks if we picked a point on the sketch or any other nodes like the grid SoPath *path = pp->getPath(); return path->containsNode(edit->EditRoot); } bool ViewProviderSketch::doubleClicked(void) { Gui::Application::Instance->activeDocument()->setEdit(this); return true; } QString ViewProviderSketch::iconTypeFromConstraint(Constraint *constraint) { /*! TODO: Consider pushing this functionality up into Constraint */ switch(constraint->Type) { case Horizontal: return QString::fromLatin1("small/Constraint_Horizontal_sm"); case Vertical: return QString::fromLatin1("small/Constraint_Vertical_sm"); case PointOnObject: return QString::fromLatin1("small/Constraint_PointOnObject_sm"); case Tangent: return QString::fromLatin1("small/Constraint_Tangent_sm"); case Parallel: return QString::fromLatin1("small/Constraint_Parallel_sm"); case Perpendicular: return QString::fromLatin1("small/Constraint_Perpendicular_sm"); case Equal: return QString::fromLatin1("small/Constraint_EqualLength_sm"); case Symmetric: return QString::fromLatin1("small/Constraint_Symmetric_sm"); case SnellsLaw: return QString::fromLatin1("small/Constraint_SnellsLaw_sm"); default: return QString(); } } void ViewProviderSketch::sendConstraintIconToCoin(const QImage &icon, SoImage *soImagePtr) { SoSFImage icondata = SoSFImage(); Gui::BitmapFactory().convert(icon, icondata); SbVec2s iconSize(icon.width(), icon.height()); int four = 4; soImagePtr->image.setValue(iconSize, 4, icondata.getValue(iconSize, four)); //Set Image Alignment to Center soImagePtr->vertAlignment = SoImage::HALF; soImagePtr->horAlignment = SoImage::CENTER; } void ViewProviderSketch::clearCoinImage(SoImage *soImagePtr) { soImagePtr->setToDefaults(); } QColor ViewProviderSketch::constrColor(int constraintId) { static QColor constrIcoColor((int)(ConstrIcoColor [0] * 255.0f), (int)(ConstrIcoColor[1] * 255.0f), (int)(ConstrIcoColor[2] * 255.0f)); static QColor nonDrivingConstrIcoColor((int)(NonDrivingConstrDimColor[0] * 255.0f), (int)(NonDrivingConstrDimColor[1] * 255.0f), (int)(NonDrivingConstrDimColor[2] * 255.0f)); static QColor constrIconSelColor ((int)(SelectColor[0] * 255.0f), (int)(SelectColor[1] * 255.0f), (int)(SelectColor[2] * 255.0f)); static QColor constrIconPreselColor ((int)(PreselectColor[0] * 255.0f), (int)(PreselectColor[1] * 255.0f), (int)(PreselectColor[2] * 255.0f)); const std::vector<Sketcher::Constraint *> &constraints = getSketchObject()->Constraints.getValues(); if (edit->PreselectConstraintSet.count(constraintId)) return constrIconPreselColor; else if (edit->SelConstraintSet.find(constraintId) != edit->SelConstraintSet.end()) return constrIconSelColor; else if(!constraints[constraintId]->isDriving) return nonDrivingConstrIcoColor; else return constrIcoColor; } int ViewProviderSketch::constrColorPriority(int constraintId) { if (edit->PreselectConstraintSet.count(constraintId)) return 3; else if (edit->SelConstraintSet.find(constraintId) != edit->SelConstraintSet.end()) return 2; else return 1; } // public function that triggers drawing of most constraint icons void ViewProviderSketch::drawConstraintIcons() { const std::vector<Sketcher::Constraint *> &constraints = getSketchObject()->Constraints.getValues(); int constrId = 0; std::vector<constrIconQueueItem> iconQueue; for (std::vector<Sketcher::Constraint *>::const_iterator it=constraints.begin(); it != constraints.end(); ++it, ++constrId) { // Check if Icon Should be created bool multipleIcons = false; QString icoType = iconTypeFromConstraint(*it); if(icoType.isEmpty()) continue; switch((*it)->Type) { case Tangent: { // second icon is available only for colinear line segments const Part::Geometry *geo1 = getSketchObject()->getGeometry((*it)->First); const Part::Geometry *geo2 = getSketchObject()->getGeometry((*it)->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { multipleIcons = true; } } break; case Parallel: multipleIcons = true; break; case Perpendicular: // second icon is available only when there is no common point if ((*it)->FirstPos == Sketcher::none && (*it)->Third == Constraint::GeoUndef) multipleIcons = true; break; case Equal: multipleIcons = true; break; default: break; } // Find the Constraint Icon SoImage Node SoSeparator *sep = static_cast<SoSeparator *>(edit->constrGroup->getChild(constrId)); SbVec3f absPos; // Somewhat hacky - we use SoZoomTranslations for most types of icon, // but symmetry icons use SoTranslations... SoTranslation *translationPtr = static_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION)); if(dynamic_cast<SoZoomTranslation *>(translationPtr)) absPos = static_cast<SoZoomTranslation *>(translationPtr)->abPos.getValue(); else absPos = translationPtr->translation.getValue(); SoImage *coinIconPtr = dynamic_cast<SoImage *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON)); SoInfo *infoPtr = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID)); constrIconQueueItem thisIcon; thisIcon.type = icoType; thisIcon.constraintId = constrId; thisIcon.position = absPos; thisIcon.destination = coinIconPtr; thisIcon.infoPtr = infoPtr; if ((*it)->Type==Symmetric) { Base::Vector3d startingpoint = getSketchObject()->getPoint((*it)->First,(*it)->FirstPos); Base::Vector3d endpoint = getSketchObject()->getPoint((*it)->Second,(*it)->SecondPos); double x0,y0,x1,y1; SbVec3f pos0(startingpoint.x,startingpoint.y,startingpoint.z); SbVec3f pos1(endpoint.x,endpoint.y,endpoint.z); Gui::MDIView *mdi = this->getViewOfNode(edit->EditRoot); if (!(mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))) return; Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) return; try { SbViewVolume vol = pCam->getViewVolume(); getCoordsOnSketchPlane(x0,y0,pos0,vol.getProjectionDirection()); getCoordsOnSketchPlane(x1,y1,pos1,vol.getProjectionDirection()); thisIcon.iconRotation = -atan2((y1-y0),(x1-x0))*180/M_PI; } catch (const Base::DivisionByZeroError&) { thisIcon.iconRotation = 0; } } else { thisIcon.iconRotation = 0; } if (multipleIcons) { if((*it)->Name.empty()) thisIcon.label = QString::number(constrId + 1); else thisIcon.label = QString::fromUtf8((*it)->Name.c_str()); iconQueue.push_back(thisIcon); // Note that the second translation is meant to be applied after the first. // So, to get the position of the second icon, we add the two translations together // // See note ~30 lines up. translationPtr = static_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION)); if(dynamic_cast<SoZoomTranslation *>(translationPtr)) thisIcon.position += static_cast<SoZoomTranslation *>(translationPtr)->abPos.getValue(); else thisIcon.position += translationPtr->translation.getValue(); thisIcon.destination = dynamic_cast<SoImage *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON)); thisIcon.infoPtr = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID)); } else { if ((*it)->Name.empty()) thisIcon.label = QString(); else thisIcon.label = QString::fromUtf8((*it)->Name.c_str()); } iconQueue.push_back(thisIcon); } combineConstraintIcons(iconQueue); } void ViewProviderSketch::combineConstraintIcons(IconQueue iconQueue) { // getScaleFactor gives us a ratio of pixels per some kind of real units // (Translation: this number is somewhat made-up.) float maxDistSquared = pow(0.05 * getScaleFactor(), 2); // There's room for optimisation here; we could reuse the combined icons... edit->combinedConstrBoxes.clear(); while(!iconQueue.empty()) { // A group starts with an item popped off the back of our initial queue IconQueue thisGroup; thisGroup.push_back(iconQueue.back()); ViewProviderSketch::constrIconQueueItem init = iconQueue.back(); iconQueue.pop_back(); // we group only icons not being Symmetry icons, because we want those on the line if(init.type != QString::fromLatin1("small/Constraint_Symmetric_sm")){ IconQueue::iterator i = iconQueue.begin(); while(i != iconQueue.end()) { bool addedToGroup = false; for(IconQueue::iterator j = thisGroup.begin(); j != thisGroup.end(); ++j) if(i->position.equals(j->position, maxDistSquared) && (*i).type != QString::fromLatin1("small/Constraint_Symmetric_sm")) { // Found an icon in iconQueue that's close enough to // a member of thisGroup, so move it into thisGroup thisGroup.push_back(*i); i = iconQueue.erase(i); addedToGroup = true; break; } if(addedToGroup) { if(i == iconQueue.end()) // We just got the last icon out of iconQueue break; else // Start looking through the iconQueue again, in case // we have an icon that's now close enough to thisGroup i = iconQueue.begin(); } else ++i; } } if(thisGroup.size() == 1) { drawTypicalConstraintIcon(thisGroup[0]); } else { drawMergedConstraintIcons(thisGroup); } } } void ViewProviderSketch::drawMergedConstraintIcons(IconQueue iconQueue) { SbVec3f avPos(0, 0, 0); for(IconQueue::iterator i = iconQueue.begin(); i != iconQueue.end(); ++i) { clearCoinImage(i->destination); avPos = avPos + i->position; } avPos = avPos/iconQueue.size(); QImage compositeIcon; float closest = FLT_MAX; // Closest distance between avPos and any icon SoImage *thisDest = 0; SoInfo *thisInfo = 0; // Tracks all constraint IDs that are combined into this icon QString idString; int lastVPad = 0; QStringList labels; std::vector<int> ids; QString thisType; QColor iconColor; QList<QColor> labelColors; int maxColorPriority; double iconRotation; ConstrIconBBVec boundingBoxes; while(!iconQueue.empty()) { IconQueue::iterator i = iconQueue.begin(); labels.clear(); labels.append(i->label); ids.clear(); ids.push_back(i->constraintId); thisType = i->type; iconColor = constrColor(i->constraintId); labelColors.clear(); labelColors.append(iconColor); iconRotation= i->iconRotation; maxColorPriority = constrColorPriority(i->constraintId); if(idString.length()) idString.append(QString::fromLatin1(",")); idString.append(QString::number(i->constraintId)); if((avPos - i->position).length() < closest) { thisDest = i->destination; thisInfo = i->infoPtr; closest = (avPos - i->position).length(); } i = iconQueue.erase(i); while(i != iconQueue.end()) { if(i->type != thisType) { ++i; continue; } if((avPos - i->position).length() < closest) { thisDest = i->destination; thisInfo = i->infoPtr; closest = (avPos - i->position).length(); } labels.append(i->label); ids.push_back(i->constraintId); labelColors.append(constrColor(i->constraintId)); if(constrColorPriority(i->constraintId) > maxColorPriority) { maxColorPriority = constrColorPriority(i->constraintId); iconColor= constrColor(i->constraintId); } idString.append(QString::fromLatin1(",") + QString::number(i->constraintId)); i = iconQueue.erase(i); } // To be inserted into edit->combinedConstBoxes std::vector<QRect> boundingBoxesVec; int oldHeight = 0; // Render the icon here. if(compositeIcon.isNull()) { compositeIcon = renderConstrIcon(thisType, iconColor, labels, labelColors, iconRotation, &boundingBoxesVec, &lastVPad); } else { int thisVPad; QImage partialIcon = renderConstrIcon(thisType, iconColor, labels, labelColors, iconRotation, &boundingBoxesVec, &thisVPad); // Stack vertically for now. Down the road, it might make sense // to figure out the best orientation automatically. oldHeight = compositeIcon.height(); // This is overkill for the currently used (20 July 2014) font, // since it always seems to have the same vertical pad, but this // might not always be the case. The 3 pixel buffer might need // to vary depending on font size too... oldHeight -= std::max(lastVPad - 3, 0); compositeIcon = compositeIcon.copy(0, 0, std::max(partialIcon.width(), compositeIcon.width()), partialIcon.height() + compositeIcon.height()); QPainter qp(&compositeIcon); qp.drawImage(0, oldHeight, partialIcon); lastVPad = thisVPad; } // Add bounding boxes for the icon we just rendered to boundingBoxes std::vector<int>::iterator id = ids.begin(); std::set<int> nextIds; for(std::vector<QRect>::iterator bb = boundingBoxesVec.begin(); bb != boundingBoxesVec.end(); ++bb) { nextIds.clear(); if(bb == boundingBoxesVec.begin()) { // The first bounding box is for the icon at left, so assign // all IDs for that type of constraint to the icon. for(std::vector<int>::iterator j = ids.begin(); j != ids.end(); ++j) nextIds.insert(*j); } else nextIds.insert(*(id++)); ConstrIconBB newBB(bb->adjusted(0, oldHeight, 0, oldHeight), nextIds); boundingBoxes.push_back(newBB); } } edit->combinedConstrBoxes[idString] = boundingBoxes; thisInfo->string.setValue(idString.toLatin1().data()); sendConstraintIconToCoin(compositeIcon, thisDest); } /// Note: labels, labelColors, and boundignBoxes are all /// assumed to be the same length. QImage ViewProviderSketch::renderConstrIcon(const QString &type, const QColor &iconColor, const QStringList &labels, const QList<QColor> &labelColors, double iconRotation, std::vector<QRect> *boundingBoxes, int *vPad) { // Constants to help create constraint icons QString joinStr = QString::fromLatin1(", "); QImage icon = Gui::BitmapFactory().pixmap(type.toLatin1()).toImage(); QFont font = QApplication::font(); font.setPixelSize(11); font.setBold(true); QFontMetrics qfm = QFontMetrics(font); int labelWidth = qfm.boundingRect(labels.join(joinStr)).width(); // See Qt docs on qRect::bottom() for explanation of the +1 int pxBelowBase = qfm.boundingRect(labels.join(joinStr)).bottom() + 1; if(vPad) *vPad = pxBelowBase; QTransform rotation; rotation.rotate(iconRotation); QImage roticon = icon.transformed(rotation); QImage image = roticon.copy(0, 0, roticon.width() + labelWidth, roticon.height() + pxBelowBase); // Make a bounding box for the icon if(boundingBoxes) boundingBoxes->push_back(QRect(0, 0, roticon.width(), roticon.height())); // Render the Icons QPainter qp(&image); qp.setCompositionMode(QPainter::CompositionMode_SourceIn); qp.fillRect(roticon.rect(), iconColor); // Render constraint label if necessary if (!labels.join(QString()).isEmpty()) { qp.setCompositionMode(QPainter::CompositionMode_SourceOver); qp.setFont(font); int cursorOffset = 0; //In Python: "for label, color in zip(labels, labelColors):" QStringList::const_iterator labelItr; QString labelStr; QList<QColor>::const_iterator colorItr; QRect labelBB; for(labelItr = labels.begin(), colorItr = labelColors.begin(); labelItr != labels.end() && colorItr != labelColors.end(); ++labelItr, ++colorItr) { qp.setPen(*colorItr); if(labelItr + 1 == labels.end()) // if this is the last label labelStr = *labelItr; else labelStr = *labelItr + joinStr; // Note: text can sometimes draw to the left of the starting // position, eg italic fonts. Check QFontMetrics // documentation for more info, but be mindful if the // icon.width() is ever very small (or removed). qp.drawText(icon.width() + cursorOffset, icon.height(), labelStr); if(boundingBoxes) { labelBB = qfm.boundingRect(labelStr); labelBB.moveTo(icon.width() + cursorOffset, icon.height() - qfm.height() + pxBelowBase); boundingBoxes->push_back(labelBB); } cursorOffset += qfm.width(labelStr); } } return image; } void ViewProviderSketch::drawTypicalConstraintIcon(const constrIconQueueItem &i) { QColor color = constrColor(i.constraintId); QImage image = renderConstrIcon(i.type, color, QStringList(i.label), QList<QColor>() << color, i.iconRotation); i.infoPtr->string.setValue(QString::number(i.constraintId).toLatin1().data()); sendConstraintIconToCoin(image, i.destination); } float ViewProviderSketch::getScaleFactor() { assert(edit); Gui::MDIView *mdi = this->getViewOfNode(edit->EditRoot); if (mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoCamera* camera = viewer->getSoRenderManager()->getCamera(); float scale = camera->getViewVolume(camera->aspectRatio.getValue()).getWorldToScreenScale(SbVec3f(0.f, 0.f, 0.f), 0.1f) / 3; return scale; } else { return 1.f; } } void ViewProviderSketch::draw(bool temp /*=false*/, bool rebuildinformationlayer /*=true*/) { assert(edit); // Render Geometry =================================================== std::vector<Base::Vector3d> Coords; std::vector<Base::Vector3d> Points; std::vector<unsigned int> Index; int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; int extGeoCount = getSketchObject()->getExternalGeometryCount(); const std::vector<Part::Geometry *> *geomlist; std::vector<Part::Geometry *> tempGeo; if (temp) tempGeo = getSketchObject()->getSolvedSketch().extractGeometry(true, true); // with memory allocation else tempGeo = getSketchObject()->getCompleteGeometry(); // without memory allocation geomlist = &tempGeo; assert(int(geomlist->size()) == extGeoCount + intGeoCount); assert(int(geomlist->size()) >= 2); edit->CurvIdToGeoId.clear(); // information layer if(rebuildinformationlayer) { // every time we start with empty information layer edit->infoGroup->removeAllChildren(); } ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); int fontSize = hGrp->GetInt("EditSketcherFontSize", 17); int currentInfoNode = 0; ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); // end information layer int GeoId = 0; int stdcountsegments = hGrp->GetInt("SegmentsPerGeometry", 50); // RootPoint Points.push_back(Base::Vector3d(0.,0.,0.)); for (std::vector<Part::Geometry *>::const_iterator it = geomlist->begin(); it != geomlist->end()-2; ++it, GeoId++) { if (GeoId >= intGeoCount) GeoId = -extGeoCount; if ((*it)->getTypeId() == Part::GeomPoint::getClassTypeId()) { // add a point const Part::GeomPoint *point = static_cast<const Part::GeomPoint *>(*it); Points.push_back(point->getPoint()); } else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // add a line const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(*it); // create the definition struct for that geom Coords.push_back(lineSeg->getStartPoint()); Coords.push_back(lineSeg->getEndPoint()); Points.push_back(lineSeg->getStartPoint()); Points.push_back(lineSeg->getEndPoint()); Index.push_back(2); edit->CurvIdToGeoId.push_back(GeoId); } else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { // add a circle const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(*it); Handle_Geom_Circle curve = Handle_Geom_Circle::DownCast(circle->handle()); int countSegments = stdcountsegments; Base::Vector3d center = circle->getCenter(); double segment = (2 * M_PI) / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(i*segment); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } gp_Pnt pnt = curve->Value(0); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { // add an ellipse const Part::GeomEllipse *ellipse = static_cast<const Part::GeomEllipse *>(*it); Handle_Geom_Ellipse curve = Handle_Geom_Ellipse::DownCast(ellipse->handle()); int countSegments = stdcountsegments; Base::Vector3d center = ellipse->getCenter(); double segment = (2 * M_PI) / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(i*segment); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } gp_Pnt pnt = curve->Value(0); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // add an arc const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(*it); Handle_Geom_TrimmedCurve curve = Handle_Geom_TrimmedCurve::DownCast(arc->handle()); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/false); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(6, int(stdcountsegments * range / (2 * M_PI))); double segment = range / countSegments; Base::Vector3d center = arc->getCenter(); Base::Vector3d start = arc->getStartPoint(/*emulateCCW=*/true); Base::Vector3d end = arc->getEndPoint(/*emulateCCW=*/true); for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(startangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); startangle += segment; } // end point gp_Pnt pnt = curve->Value(endangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(start); Points.push_back(end); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { // add an arc const Part::GeomArcOfEllipse *arc = static_cast<const Part::GeomArcOfEllipse *>(*it); Handle_Geom_TrimmedCurve curve = Handle_Geom_TrimmedCurve::DownCast(arc->handle()); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/false); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(6, int(stdcountsegments * range / (2 * M_PI))); double segment = range / countSegments; Base::Vector3d center = arc->getCenter(); Base::Vector3d start = arc->getStartPoint(/*emulateCCW=*/true); Base::Vector3d end = arc->getEndPoint(/*emulateCCW=*/true); for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(startangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); startangle += segment; } // end point gp_Pnt pnt = curve->Value(endangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(start); Points.push_back(end); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { const Part::GeomArcOfHyperbola *aoh = dynamic_cast<const Part::GeomArcOfHyperbola *>(*it); Handle_Geom_TrimmedCurve curve = Handle_Geom_TrimmedCurve::DownCast(aoh->handle()); double startangle, endangle; aoh->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(6, int(stdcountsegments * range / (2 * M_PI))); double segment = range / countSegments; Base::Vector3d center = aoh->getCenter(); Base::Vector3d start = aoh->getStartPoint(); Base::Vector3d end = aoh->getEndPoint(); for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(startangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); startangle += segment; } // end point gp_Pnt pnt = curve->Value(endangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(start); Points.push_back(end); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { const Part::GeomArcOfParabola *aop = dynamic_cast<const Part::GeomArcOfParabola *>(*it); Handle_Geom_TrimmedCurve curve = Handle_Geom_TrimmedCurve::DownCast(aop->handle()); double startangle, endangle; aop->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(6, int(stdcountsegments * range / (2 * M_PI))); double segment = range / countSegments; Base::Vector3d center = aop->getCenter(); Base::Vector3d start = aop->getStartPoint(); Base::Vector3d end = aop->getEndPoint(); for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(startangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); startangle += segment; } // end point gp_Pnt pnt = curve->Value(endangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(start); Points.push_back(end); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // add a bspline const Part::GeomBSplineCurve *spline = static_cast<const Part::GeomBSplineCurve *>(*it); Handle_Geom_BSplineCurve curve = Handle_Geom_BSplineCurve::DownCast(spline->handle()); Base::Vector3d startp = spline->getStartPoint(); Base::Vector3d endp = spline->getEndPoint(); double first = curve->FirstParameter(); double last = curve->LastParameter(); if (first > last) // if arc is reversed std::swap(first, last); double range = last-first; int countSegments = stdcountsegments; double segment = range / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(first); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); first += segment; } // end point gp_Pnt end = curve->Value(last); Coords.push_back(Base::Vector3d(end.X(), end.Y(), end.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(startp); Points.push_back(endp); //---------------------------------------------------------- // geometry information layer // polynom degree -------------------------------------------------------- std::vector<Base::Vector3d> poles = spline->getPoles(); Base::Vector3d midp = Base::Vector3d(0,0,0); for (std::vector<Base::Vector3d>::iterator it = poles.begin(); it != poles.end(); ++it) { midp += (*it); } midp /= poles.size(); if(rebuildinformationlayer) { SoSwitch *sw = new SoSwitch(); sw->whichChild = hGrpsk->GetBool("BSplineDegreeVisible", true)?SO_SWITCH_ALL:SO_SWITCH_NONE; SoSeparator *sep = new SoSeparator(); sep->ref(); // no caching for fluctuand data structures sep->renderCaching = SoSeparator::OFF; // every information visual node gets its own material for to-be-implemented preselection and selection SoMaterial *mat = new SoMaterial; mat->ref(); mat->diffuseColor = InformationColor; SoTranslation *translate = new SoTranslation; translate->translation.setValue(midp.x,midp.y,zInfo); SoFont *font = new SoFont; font->name.setValue("Helvetica"); font->size.setValue(fontSize); SoText2 *degreetext = new SoText2; degreetext->string = SbString(spline->getDegree()); sep->addChild(translate); sep->addChild(mat); sep->addChild(font); sep->addChild(degreetext); sw->addChild(sep); edit->infoGroup->addChild(sw); sep->unref(); mat->unref(); } else { SoSwitch *sw = static_cast<SoSwitch *>(edit->infoGroup->getChild(currentInfoNode)); if(visibleInformationChanged) sw->whichChild = hGrpsk->GetBool("BSplineDegreeVisible", true)?SO_SWITCH_ALL:SO_SWITCH_NONE; SoSeparator *sep = static_cast<SoSeparator *>(sw->getChild(0)); static_cast<SoTranslation *>(sep->getChild(GEOINFO_BSPLINE_DEGREE_POS))->translation.setValue(midp.x,midp.y,zInfo); static_cast<SoText2 *>(sep->getChild(GEOINFO_BSPLINE_DEGREE_TEXT))->string = SbString(spline->getDegree()); } currentInfoNode++; // switch to next node // control polygon -------------------------------------------------------- if(rebuildinformationlayer) { SoSwitch *sw = new SoSwitch(); sw->whichChild = hGrpsk->GetBool("BSplineControlPolygonVisible", true)?SO_SWITCH_ALL:SO_SWITCH_NONE; SoSeparator *sep = new SoSeparator(); sep->ref(); // no caching for fluctuand data structures sep->renderCaching = SoSeparator::OFF; // every information visual node gets its own material for to-be-implemented preselection and selection SoMaterial *mat = new SoMaterial; mat->ref(); mat->diffuseColor = InformationColor; SoLineSet *lineset = new SoLineSet; SoCoordinate3 *coords = new SoCoordinate3; if(spline->isPeriodic()) { coords->point.setNum(poles.size()+1); } else { coords->point.setNum(poles.size()); } SbVec3f *vts = coords->point.startEditing(); int i=0; for (std::vector<Base::Vector3d>::iterator it = poles.begin(); it != poles.end(); ++it, i++) { vts[i].setValue((*it).x,(*it).y,zInfo); } if(spline->isPeriodic()) { vts[poles.size()].setValue(poles[0].x,poles[0].y,zInfo); } coords->point.finishEditing(); sep->addChild(mat); sep->addChild(coords); sep->addChild(lineset); sw->addChild(sep); edit->infoGroup->addChild(sw); sep->unref(); mat->unref(); } else { SoSwitch *sw = static_cast<SoSwitch *>(edit->infoGroup->getChild(currentInfoNode)); if(visibleInformationChanged) sw->whichChild = hGrpsk->GetBool("BSplineControlPolygonVisible", true)?SO_SWITCH_ALL:SO_SWITCH_NONE; SoSeparator *sep = static_cast<SoSeparator *>(sw->getChild(0)); SoCoordinate3 *coords = static_cast<SoCoordinate3 *>(sep->getChild(GEOINFO_BSPLINE_POLYGON)); if(spline->isPeriodic()) { coords->point.setNum(poles.size()+1); } else { coords->point.setNum(poles.size()); } SbVec3f *vts = coords->point.startEditing(); int i=0; for (std::vector<Base::Vector3d>::iterator it = poles.begin(); it != poles.end(); ++it, i++) { vts[i].setValue((*it).x,(*it).y,zInfo); } if(spline->isPeriodic()) { vts[poles.size()].setValue(poles[0].x,poles[0].y,zInfo); } coords->point.finishEditing(); } currentInfoNode++; // switch to next node // curvature graph -------------------------------------------------------- // reimplementation of python source: // https://github.com/tomate44/CurvesWB/blob/master/ParametricComb.py // by FreeCAD user Chris_G double firstparam = spline->getFirstParameter(); double lastparam = spline->getLastParameter(); const int ndiv = poles.size()>4?poles.size()*16:64; double step = (lastparam - firstparam ) / (ndiv -1); std::vector<double> paramlist(ndiv); std::vector<Base::Vector3d> pointatcurvelist(ndiv); std::vector<double> curvaturelist(ndiv); std::vector<Base::Vector3d> normallist(ndiv); double maxcurv = 0; double maxdisttocenterofmass = 0; //double length = spline->length(firstparam,lastparam); for(int i = 0; i < ndiv; i++) { paramlist[i] = firstparam + i * step; pointatcurvelist[i] = spline->pointAtParameter(paramlist[i]); curvaturelist[i] = spline->curvatureAt(paramlist[i]); if(curvaturelist[i] > maxcurv) maxcurv = curvaturelist[i]; try { spline->normalAt(paramlist[i],normallist[i]); } catch(Base::Exception) { normallist[i] = Base::Vector3d(0,0,0); } double temp = ( pointatcurvelist[i] - midp ).Length(); if( temp > maxdisttocenterofmass ) maxdisttocenterofmass = temp; } double repscale; repscale = ( 0.5 * maxdisttocenterofmass ) / maxcurv; // just a factor to make it reasonably visible //repscale = ( 0.5 * length ) / maxcurv; // this is Chris_G's original std::vector<Base::Vector3d> pointatcomblist(ndiv); for(int i = 0; i < ndiv; i++) { pointatcomblist[i] = pointatcurvelist[i] - repscale * curvaturelist[i] * normallist[i]; } if(rebuildinformationlayer) { SoSwitch *sw = new SoSwitch(); sw->whichChild = hGrpsk->GetBool("BSplineCombVisible", true)?SO_SWITCH_ALL:SO_SWITCH_NONE; SoSeparator *sep = new SoSeparator(); sep->ref(); // no caching for fluctuand data structures sep->renderCaching = SoSeparator::OFF; // every information visual node gets its own material for to-be-implemented preselection and selection SoMaterial *mat = new SoMaterial; mat->ref(); mat->diffuseColor = InformationColor; SoLineSet *lineset = new SoLineSet; SoCoordinate3 *coords = new SoCoordinate3; coords->point.setNum(3*ndiv); // 2*ndiv +1 points of ndiv separate segments + ndiv points for last segment lineset->numVertices.setNum(ndiv+1); // ndiv separate segments of radials + 1 segment connecting at comb end int32_t *index = lineset->numVertices.startEditing(); SbVec3f *vts = coords->point.startEditing(); for(int i = 0; i < ndiv; i++) { vts[2*i].setValue(pointatcurvelist[i].x, pointatcurvelist[i].y, zInfo); // radials vts[2*i+1].setValue(pointatcomblist[i].x, pointatcomblist[i].y, zInfo); index[i] = 2; vts[2*ndiv+i].setValue(pointatcomblist[i].x, pointatcomblist[i].y, zInfo); // comb endpoint closing segment } index[ndiv] = ndiv; // comb endpoint closing segment coords->point.finishEditing(); lineset->numVertices.finishEditing(); sep->addChild(mat); sep->addChild(coords); sep->addChild(lineset); sw->addChild(sep); edit->infoGroup->addChild(sw); sep->unref(); mat->unref(); } else { SoSwitch *sw = static_cast<SoSwitch *>(edit->infoGroup->getChild(currentInfoNode)); if(visibleInformationChanged) sw->whichChild = hGrpsk->GetBool("BSplineCombVisible", true)?SO_SWITCH_ALL:SO_SWITCH_NONE; SoSeparator *sep = static_cast<SoSeparator *>(sw->getChild(0)); SoCoordinate3 *coords = static_cast<SoCoordinate3 *>(sep->getChild(GEOINFO_BSPLINE_POLYGON)); SoLineSet *lineset = static_cast<SoLineSet *>(sep->getChild(GEOINFO_BSPLINE_POLYGON+1)); coords->point.setNum(3*ndiv); // 2*ndiv +1 points of ndiv separate segments + ndiv points for last segment lineset->numVertices.setNum(ndiv+1); // ndiv separate segments of radials + 1 segment connecting at comb end int32_t *index = lineset->numVertices.startEditing(); SbVec3f *vts = coords->point.startEditing(); for(int i = 0; i < ndiv; i++) { vts[2*i].setValue(pointatcurvelist[i].x, pointatcurvelist[i].y, zInfo); // radials vts[2*i+1].setValue(pointatcomblist[i].x, pointatcomblist[i].y, zInfo); index[i] = 2; vts[2*ndiv+i].setValue(pointatcomblist[i].x, pointatcomblist[i].y, zInfo); // comb endpoint closing segment } index[ndiv] = ndiv; // comb endpoint closing segment coords->point.finishEditing(); lineset->numVertices.finishEditing(); } currentInfoNode++; // switch to next node } else { } } visibleInformationChanged=false; // whatever that changed in Information layer is already updated edit->CurvesCoordinate->point.setNum(Coords.size()); edit->CurveSet->numVertices.setNum(Index.size()); edit->CurvesMaterials->diffuseColor.setNum(Index.size()); edit->PointsCoordinate->point.setNum(Points.size()); edit->PointsMaterials->diffuseColor.setNum(Points.size()); SbVec3f *verts = edit->CurvesCoordinate->point.startEditing(); int32_t *index = edit->CurveSet->numVertices.startEditing(); SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); int i=0; // setting up the line set for (std::vector<Base::Vector3d>::const_iterator it = Coords.begin(); it != Coords.end(); ++it,i++) verts[i].setValue(it->x,it->y,zLines); i=0; // setting up the indexes of the line set for (std::vector<unsigned int>::const_iterator it = Index.begin(); it != Index.end(); ++it,i++) index[i] = *it; i=0; // setting up the point set for (std::vector<Base::Vector3d>::const_iterator it = Points.begin(); it != Points.end(); ++it,i++) pverts[i].setValue(it->x,it->y,zPoints); edit->CurvesCoordinate->point.finishEditing(); edit->CurveSet->numVertices.finishEditing(); edit->PointsCoordinate->point.finishEditing(); // set cross coordinates edit->RootCrossSet->numVertices.set1Value(0,2); edit->RootCrossSet->numVertices.set1Value(1,2); float MiX = -exp(ceil(log(std::abs(MinX)))); MiX = std::min(MiX,(float)-exp(ceil(log(std::abs(0.1f*MaxX))))); float MaX = exp(ceil(log(std::abs(MaxX)))); MaX = std::max(MaX,(float)exp(ceil(log(std::abs(0.1f*MinX))))); float MiY = -exp(ceil(log(std::abs(MinY)))); MiY = std::min(MiY,(float)-exp(ceil(log(std::abs(0.1f*MaxY))))); float MaY = exp(ceil(log(std::abs(MaxY)))); MaY = std::max(MaY,(float)exp(ceil(log(std::abs(0.1f*MinY))))); edit->RootCrossCoordinate->point.set1Value(0,SbVec3f(MiX, 0.0f, zCross)); edit->RootCrossCoordinate->point.set1Value(1,SbVec3f(MaX, 0.0f, zCross)); edit->RootCrossCoordinate->point.set1Value(2,SbVec3f(0.0f, MiY, zCross)); edit->RootCrossCoordinate->point.set1Value(3,SbVec3f(0.0f, MaY, zCross)); // Render Constraints =================================================== const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); // After an undo/redo it can happen that we have an empty geometry list but a non-empty constraint list // In this case just ignore the constraints. (See bug #0000421) if (geomlist->size() <= 2 && !constrlist.empty()) { rebuildConstraintsVisual(); return; } // reset point if the constraint type has changed Restart: // check if a new constraint arrived if (constrlist.size() != edit->vConstrType.size()) rebuildConstraintsVisual(); assert(int(constrlist.size()) == edit->constrGroup->getNumChildren()); assert(int(edit->vConstrType.size()) == edit->constrGroup->getNumChildren()); // go through the constraints and update the position i = 0; for (std::vector<Sketcher::Constraint *>::const_iterator it=constrlist.begin(); it != constrlist.end(); ++it, i++) { // check if the type has changed if ((*it)->Type != edit->vConstrType[i]) { // clearing the type vector will force a rebuild of the visual nodes edit->vConstrType.clear(); //TODO: The 'goto' here is unsafe as it can happen that we cause an endless loop (see bug #0001956). goto Restart; } try{//because calculateNormalAtPoint, used in there, can throw // root separator for this constraint SoSeparator *sep = static_cast<SoSeparator *>(edit->constrGroup->getChild(i)); const Constraint *Constr = *it; // distinquish different constraint types to build up switch (Constr->Type) { case Horizontal: // write the new position of the Horizontal constraint Same as vertical position. case Vertical: // write the new position of the Vertical constraint { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); // get the geometry const Part::Geometry *geo = GeoById(*geomlist, Constr->First); // Vertical can only be a GeomLineSegment assert(geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()); const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(geo); // calculate the half distance between the start and endpoint Base::Vector3d midpos = ((lineSeg->getEndPoint()+lineSeg->getStartPoint())/2); //Get a set of vectors perpendicular and tangential to these Base::Vector3d dir = (lineSeg->getEndPoint()-lineSeg->getStartPoint()).Normalize(); Base::Vector3d norm(-dir.y,dir.x,0); Base::Vector3d relpos = seekConstraintPosition(midpos, norm, dir, 2.5, edit->constrGroup->getChild(i)); static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos.x, midpos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos.x, relpos.y, 0); } break; case Perpendicular: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); Base::Vector3d midpos1, dir1, norm1; Base::Vector3d midpos2, dir2, norm2; bool twoIcons = false;//a very local flag. It's set to true to indicate that the second dir+norm are valid and should be used if (Constr->Third != Constraint::GeoUndef || //perpty via point Constr->FirstPos != Sketcher::none) { //endpoint-to-curve or endpoint-to-endpoint perpty int ptGeoId; Sketcher::PointPos ptPosId; do {//dummy loop to use break =) Maybe goto? ptGeoId = Constr->First; ptPosId = Constr->FirstPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Second; ptPosId = Constr->SecondPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Third; ptPosId = Constr->ThirdPos; if (ptPosId != Sketcher::none) break; assert(0);//no point found! } while (false); if (temp) midpos1 = getSketchObject()->getSolvedSketch().getPoint(ptGeoId, ptPosId); else midpos1 = getSketchObject()->getPoint(ptGeoId, ptPosId); norm1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, midpos1.x, midpos1.y); norm1.Normalize(); dir1 = norm1; dir1.RotateZ(-M_PI/2.0); } else if (Constr->FirstPos == Sketcher::none) { if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg1 = static_cast<const Part::GeomLineSegment *>(geo1); midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); } else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo1); double startangle, endangle, midangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); midangle = (startangle + endangle)/2; norm1 = Base::Vector3d(cos(midangle),sin(midangle),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 = arc->getCenter() + arc->getRadius() * norm1; } else if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(geo1); norm1 = Base::Vector3d(cos(M_PI/4),sin(M_PI/4),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 = circle->getCenter() + circle->getRadius() * norm1; } else break; if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg2 = static_cast<const Part::GeomLineSegment *>(geo2); midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); norm2 = Base::Vector3d(-dir2.y,dir2.x,0.); } else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo2); double startangle, endangle, midangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); midangle = (startangle + endangle)/2; norm2 = Base::Vector3d(cos(midangle),sin(midangle),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 = arc->getCenter() + arc->getRadius() * norm2; } else if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(geo2); norm2 = Base::Vector3d(cos(M_PI/4),sin(M_PI/4),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 = circle->getCenter() + circle->getRadius() * norm2; } else break; twoIcons = true; } Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); if (twoIcons) { Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d secondPos = midpos2 - midpos1; static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); } } break; case Parallel: case Equal: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); Base::Vector3d midpos1, dir1, norm1; Base::Vector3d midpos2, dir2, norm2; if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { if (Constr->Type == Equal) { double r1a=0,r1b=0,r2a=0,r2b=0; double angle1,angle1plus=0., angle2, angle2plus=0.;//angle1 = rotation of object as a whole; angle1plus = arc angle (t parameter for ellipses). if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(geo1); r1a = circle->getRadius(); angle1 = M_PI/4; midpos1 = circle->getCenter(); } else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo1); r1a = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle1 = (startangle + endangle)/2; midpos1 = arc->getCenter(); } else if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId()) { const Part::GeomEllipse *ellipse = static_cast<const Part::GeomEllipse *>(geo1); r1a = ellipse->getMajorRadius(); r1b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); angle1 = atan2(majdir.y, majdir.x); angle1plus = M_PI/4; midpos1 = ellipse->getCenter(); } else if (geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { const Part::GeomArcOfEllipse *aoe = static_cast<const Part::GeomArcOfEllipse *>(geo1); r1a = aoe->getMajorRadius(); r1b = aoe->getMinorRadius(); double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = aoe->getMajorAxisDir(); angle1 = atan2(majdir.y, majdir.x); angle1plus = (startangle + endangle)/2; midpos1 = aoe->getCenter(); } else if (geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { const Part::GeomArcOfHyperbola *aoh = dynamic_cast<const Part::GeomArcOfHyperbola *>(geo1); r1a = aoh->getMajorRadius(); r1b = aoh->getMinorRadius(); double startangle, endangle; aoh->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = aoh->getMajorAxisDir(); angle1 = atan2(majdir.y, majdir.x); angle1plus = (startangle + endangle)/2; midpos1 = aoh->getCenter(); } else if (geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { const Part::GeomArcOfParabola *aop = dynamic_cast<const Part::GeomArcOfParabola *>(geo1); r1a = aop->getFocal(); double startangle, endangle; aop->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = - aop->getXAxisDir(); angle1 = atan2(majdir.y, majdir.x); angle1plus = (startangle + endangle)/2; midpos1 = aop->getFocus(); } else break; if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(geo2); r2a = circle->getRadius(); angle2 = M_PI/4; midpos2 = circle->getCenter(); } else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo2); r2a = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle2 = (startangle + endangle)/2; midpos2 = arc->getCenter(); } else if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId()) { const Part::GeomEllipse *ellipse = static_cast<const Part::GeomEllipse *>(geo2); r2a = ellipse->getMajorRadius(); r2b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); angle2 = atan2(majdir.y, majdir.x); angle2plus = M_PI/4; midpos2 = ellipse->getCenter(); } else if (geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { const Part::GeomArcOfEllipse *aoe = static_cast<const Part::GeomArcOfEllipse *>(geo2); r2a = aoe->getMajorRadius(); r2b = aoe->getMinorRadius(); double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = aoe->getMajorAxisDir(); angle2 = atan2(majdir.y, majdir.x); angle2plus = (startangle + endangle)/2; midpos2 = aoe->getCenter(); } else if (geo2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { const Part::GeomArcOfHyperbola *aoh = static_cast<const Part::GeomArcOfHyperbola *>(geo2); r2a = aoh->getMajorRadius(); r2b = aoh->getMinorRadius(); double startangle, endangle; aoh->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = aoh->getMajorAxisDir(); angle2 = atan2(majdir.y, majdir.x); angle2plus = (startangle + endangle)/2; midpos2 = aoh->getCenter(); } else if (geo2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { const Part::GeomArcOfParabola *aop = dynamic_cast<const Part::GeomArcOfParabola *>(geo2); r2a = aop->getFocal(); double startangle, endangle; aop->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = -aop->getXAxisDir(); angle2 = atan2(majdir.y, majdir.x); angle2plus = (startangle + endangle)/2; midpos2 = aop->getFocus(); } else break; if( geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() ){ Base::Vector3d majDir, minDir, rvec; majDir = Base::Vector3d(cos(angle1),sin(angle1),0);//direction of major axis of ellipse minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse rvec = (r1a*cos(angle1plus)) * majDir + (r1b*sin(angle1plus)) * minDir; midpos1 += rvec; rvec.Normalize(); norm1 = rvec; dir1 = Base::Vector3d(-rvec.y,rvec.x,0);//DeepSOIC: I'm not sure what dir is supposed to mean. } else { norm1 = Base::Vector3d(cos(angle1),sin(angle1),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 += r1a*norm1; } if( geo2->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || geo2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { Base::Vector3d majDir, minDir, rvec; majDir = Base::Vector3d(cos(angle2),sin(angle2),0);//direction of major axis of ellipse minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse rvec = (r2a*cos(angle2plus)) * majDir + (r2b*sin(angle2plus)) * minDir; midpos2 += rvec; rvec.Normalize(); norm2 = rvec; dir2 = Base::Vector3d(-rvec.y,rvec.x,0); } else { norm2 = Base::Vector3d(cos(angle2),sin(angle2),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 += r2a*norm2; } } else // Parallel can only apply to a GeomLineSegment break; } else { const Part::GeomLineSegment *lineSeg1 = static_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = static_cast<const Part::GeomLineSegment *>(geo2); // calculate the half distance between the start and endpoint midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); //Get a set of vectors perpendicular and tangential to these dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); norm2 = Base::Vector3d(-dir2.y,dir2.x,0.); } Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); Base::Vector3d secondPos = midpos2 - midpos1; static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x - relpos1.x, relpos2.y -relpos1.y, 0); } break; case Distance: case DistanceX: case DistanceY: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); if (Constr->SecondPos != Sketcher::none) { // point to point distance if (temp) { pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); } else { pnt1 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); pnt2 = getSketchObject()->getPoint(Constr->Second, Constr->SecondPos); } } else if (Constr->Second != Constraint::GeoUndef) { // point to line distance if (temp) { pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else { pnt1 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); } const Part::Geometry *geo = GeoById(*geomlist, Constr->Second); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(geo); Base::Vector3d l2p1 = lineSeg->getStartPoint(); Base::Vector3d l2p2 = lineSeg->getEndPoint(); // calculate the projection of p1 onto line2 pnt2.ProjectToLine(pnt1-l2p1, l2p2-l2p1); pnt2 += pnt1; } else break; } else if (Constr->FirstPos != Sketcher::none) { if (temp) { pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else { pnt2 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); } } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(geo); pnt1 = lineSeg->getStartPoint(); pnt2 = lineSeg->getEndPoint(); } else break; } else break; SoDatumLabel *asciiText = static_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Constr->getPresentationValue().getUserString().toUtf8().constData()); if (Constr->Type == Distance) asciiText->datumtype = SoDatumLabel::DISTANCE; else if (Constr->Type == DistanceX) asciiText->datumtype = SoDatumLabel::DISTANCEX; else if (Constr->Type == DistanceY) asciiText->datumtype = SoDatumLabel::DISTANCEY; // Assign the Datum Points asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = SbVec3f (pnt1.x,pnt1.y,zConstr); verts[1] = SbVec3f (pnt2.x,pnt2.y,zConstr); asciiText->pnts.finishEditing(); //Assign the Label Distance asciiText->param1 = Constr->LabelDistance; asciiText->param2 = Constr->LabelPosition; } break; case PointOnObject: case Tangent: case SnellsLaw: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); Base::Vector3d pos, relPos; if ( Constr->Type == PointOnObject || Constr->Type == SnellsLaw || (Constr->Type == Tangent && Constr->Third != Constraint::GeoUndef) || //Tangency via point (Constr->Type == Tangent && Constr->FirstPos != Sketcher::none) //endpoint-to-curve or endpoint-to-endpoint tangency ) { //find the point of tangency/point that is on object //just any point among first/second/third should be OK int ptGeoId; Sketcher::PointPos ptPosId; do {//dummy loop to use break =) Maybe goto? ptGeoId = Constr->First; ptPosId = Constr->FirstPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Second; ptPosId = Constr->SecondPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Third; ptPosId = Constr->ThirdPos; if (ptPosId != Sketcher::none) break; assert(0);//no point found! } while (false); pos = getSketchObject()->getSolvedSketch().getPoint(ptGeoId, ptPosId); Base::Vector3d norm = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, pos.x, pos.y); norm.Normalize(); Base::Vector3d dir = norm; dir.RotateZ(-M_PI/2.0); relPos = seekConstraintPosition(pos, norm, dir, 2.5, edit->constrGroup->getChild(i)); static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(pos.x, pos.y, zConstr); //Absolute Reference static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relPos.x, relPos.y, 0); } else if (Constr->Type == Tangent) { // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg1 = static_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = static_cast<const Part::GeomLineSegment *>(geo2); // tangency between two lines Base::Vector3d midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); Base::Vector3d midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); Base::Vector3d dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); Base::Vector3d dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); Base::Vector3d norm1 = Base::Vector3d(-dir1.y,dir1.x,0.f); Base::Vector3d norm2 = Base::Vector3d(-dir2.y,dir2.x,0.f); Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); Base::Vector3d secondPos = midpos2 - midpos1; static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); break; } else if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { std::swap(geo1,geo2); } if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(geo1); Base::Vector3d dir = (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Normalize(); Base::Vector3d norm(-dir.y, dir.x, 0); if (geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(geo2); // tangency between a line and a circle float length = (circle->getCenter() - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; //TODO Huh? } else if (geo2->getTypeId()== Part::GeomEllipse::getClassTypeId() || geo2->getTypeId()== Part::GeomArcOfEllipse::getClassTypeId()) { Base::Vector3d center; if(geo2->getTypeId()== Part::GeomEllipse::getClassTypeId()){ const Part::GeomEllipse *ellipse = static_cast<const Part::GeomEllipse *>(geo2); center=ellipse->getCenter(); } else { const Part::GeomArcOfEllipse *aoc = static_cast<const Part::GeomArcOfEllipse *>(geo2); center=aoc->getCenter(); } // tangency between a line and an ellipse float length = (center - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; } else if (geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between a line and an arc float length = (arc->getCenter() - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; //TODO Huh? } } if (geo1->getTypeId()== Part::GeomCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle1 = static_cast<const Part::GeomCircle *>(geo1); const Part::GeomCircle *circle2 = static_cast<const Part::GeomCircle *>(geo2); // tangency between two cicles Base::Vector3d dir = (circle2->getCenter() - circle1->getCenter()).Normalize(); pos = circle1->getCenter() + dir * circle1->getRadius(); relPos = dir * 1; } else if (geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { std::swap(geo1,geo2); } if (geo1->getTypeId()== Part::GeomCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(geo1); const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between a circle and an arc Base::Vector3d dir = (arc->getCenter() - circle->getCenter()).Normalize(); pos = circle->getCenter() + dir * circle->getRadius(); relPos = dir * 1; } else if (geo1->getTypeId()== Part::GeomArcOfCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc1 = static_cast<const Part::GeomArcOfCircle *>(geo1); const Part::GeomArcOfCircle *arc2 = static_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between two arcs Base::Vector3d dir = (arc2->getCenter() - arc1->getCenter()).Normalize(); pos = arc1->getCenter() + dir * arc1->getRadius(); relPos = dir * 1; } static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(pos.x, pos.y, zConstr); //Absolute Reference static_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relPos.x, relPos.y, 0); } } break; case Symmetric: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); Base::Vector3d pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); Base::Vector3d pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); SbVec3f p1(pnt1.x,pnt1.y,zConstr); SbVec3f p2(pnt2.x,pnt2.y,zConstr); SbVec3f dir = (p2-p1); dir.normalize(); SbVec3f norm (-dir[1],dir[0],0); SoDatumLabel *asciiText = static_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->datumtype = SoDatumLabel::SYMMETRIC; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p1; verts[1] = p2; asciiText->pnts.finishEditing(); static_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = (p1 + p2)/2; } break; case Angle: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert((Constr->Second >= -extGeoCount && Constr->Second < intGeoCount) || Constr->Second == Constraint::GeoUndef); SbVec3f p0; double startangle,range,endangle; if (Constr->Second != Constraint::GeoUndef) { Base::Vector3d dir1, dir2; if(Constr->Third == Constraint::GeoUndef) { //angle between two lines const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) break; const Part::GeomLineSegment *lineSeg1 = static_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = static_cast<const Part::GeomLineSegment *>(geo2); bool flip1 = (Constr->FirstPos == end); bool flip2 = (Constr->SecondPos == end); dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); Base::Vector3d pnt1 = flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); Base::Vector3d pnt2 = flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); // line-line intersection { double det = dir1.x*dir2.y - dir1.y*dir2.x; if ((det > 0 ? det : -det) < 1e-10) { // lines are coincident (or parallel) and in this case the center // of the point pairs with the shortest distance is used Base::Vector3d p1[2], p2[2]; p1[0] = lineSeg1->getStartPoint(); p1[1] = lineSeg1->getEndPoint(); p2[0] = lineSeg2->getStartPoint(); p2[1] = lineSeg2->getEndPoint(); double length = DBL_MAX; for (int i=0; i <= 1; i++) { for (int j=0; j <= 1; j++) { double tmp = (p2[j]-p1[i]).Length(); if (tmp < length) { length = tmp; p0.setValue((p2[j].x+p1[i].x)/2,(p2[j].y+p1[i].y)/2,0); } } } } else { double c1 = dir1.y*pnt1.x - dir1.x*pnt1.y; double c2 = dir2.y*pnt2.x - dir2.x*pnt2.y; double x = (dir1.x*c2 - dir2.x*c1)/det; double y = (dir1.y*c2 - dir2.y*c1)/det; p0 = SbVec3f(x,y,0); } } } else {//angle-via-point Base::Vector3d p = getSketchObject()->getSolvedSketch().getPoint(Constr->Third, Constr->ThirdPos); p0 = SbVec3f(p.x, p.y, 0); dir1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, p.y); dir1.RotateZ(-M_PI/2);//convert to vector of tangency by rotating dir2 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, p.y); dir2.RotateZ(-M_PI/2); } startangle = atan2(dir1.y,dir1.x); range = atan2(dir1.x*dir2.y-dir1.y*dir2.x, dir1.x*dir2.x+dir1.y*dir2.y); endangle = startangle + range; } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = static_cast<const Part::GeomLineSegment *>(geo); p0 = Base::convertTo<SbVec3f>((lineSeg->getEndPoint()+lineSeg->getStartPoint())/2); Base::Vector3d dir = lineSeg->getEndPoint()-lineSeg->getStartPoint(); startangle = 0.; range = atan2(dir.y,dir.x); endangle = startangle + range; } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo); p0 = Base::convertTo<SbVec3f>(arc->getCenter()); arc->getRange(startangle, endangle,/*emulateCCWXY=*/true); range = endangle - startangle; } else { break; } } else break; SoDatumLabel *asciiText = static_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Constr->getPresentationValue().getUserString().toUtf8().constData()); asciiText->datumtype = SoDatumLabel::ANGLE; asciiText->param1 = Constr->LabelDistance; asciiText->param2 = startangle; asciiText->param3 = range; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p0; asciiText->pnts.finishEditing(); } break; case Radius: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = static_cast<const Part::GeomArcOfCircle *>(geo); double radius = arc->getRadius(); double angle = (double) Constr->LabelPosition; if (angle == 10) { double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle = (startangle + endangle)/2; } pnt1 = arc->getCenter(); pnt2 = pnt1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = static_cast<const Part::GeomCircle *>(geo); double radius = circle->getRadius(); double angle = (double) Constr->LabelPosition; if (angle == 10) { angle = 0; } pnt1 = circle->getCenter(); pnt2 = pnt1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else break; } else break; SbVec3f p1(pnt1.x,pnt1.y,zConstr); SbVec3f p2(pnt2.x,pnt2.y,zConstr); SoDatumLabel *asciiText = static_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Constr->getPresentationValue().getUserString().toUtf8().constData()); asciiText->datumtype = SoDatumLabel::RADIUS; asciiText->param1 = Constr->LabelDistance; asciiText->param2 = Constr->LabelPosition; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p1; verts[1] = p2; asciiText->pnts.finishEditing(); } break; case Coincident: // nothing to do for coincident case None: case InternalAlignment: case NumConstraintTypes: break; } } catch (Base::Exception e) { Base::Console().Error("Exception during draw: %s\n", e.what()); } catch (...){ Base::Console().Error("Exception during draw: unknown\n"); } } this->drawConstraintIcons(); this->updateColor(); // delete the cloned objects if (temp) { for (std::vector<Part::Geometry *>::iterator it=tempGeo.begin(); it != tempGeo.end(); ++it) { if (*it) delete *it; } } Gui::MDIView *mdi = this->getActiveView(); if (mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { static_cast<Gui::View3DInventor *>(mdi)->getViewer()->redraw(); } } void ViewProviderSketch::rebuildConstraintsVisual(void) { const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); // clean up edit->constrGroup->removeAllChildren(); edit->vConstrType.clear(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); int fontSize = hGrp->GetInt("EditSketcherFontSize", 17); for (std::vector<Sketcher::Constraint *>::const_iterator it=constrlist.begin(); it != constrlist.end(); ++it) { // root separator for one constraint SoSeparator *sep = new SoSeparator(); sep->ref(); // no caching for fluctuand data structures sep->renderCaching = SoSeparator::OFF; // every constrained visual node gets its own material for preselection and selection SoMaterial *mat = new SoMaterial; mat->ref(); mat->diffuseColor = (*it)->isDriving?ConstrDimColor:NonDrivingConstrDimColor; // Get sketch normal Base::Vector3d RN(0,0,1); // move to position of Sketch Base::Placement Plz = getPlacement(); Base::Rotation tmp(Plz.getRotation()); tmp.multVec(RN,RN); Plz.setRotation(tmp); SbVec3f norm(RN.x, RN.y, RN.z); // distinguish different constraint types to build up switch ((*it)->Type) { case Distance: case DistanceX: case DistanceY: case Radius: case Angle: { SoDatumLabel *text = new SoDatumLabel(); text->norm.setValue(norm); text->string = ""; text->textColor = (*it)->isDriving?ConstrDimColor:NonDrivingConstrDimColor;; text->size.setValue(fontSize); text->useAntialiasing = false; SoAnnotation *anno = new SoAnnotation(); anno->renderCaching = SoSeparator::OFF; anno->addChild(text); // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(text); edit->constrGroup->addChild(anno); edit->vConstrType.push_back((*it)->Type); // nodes not needed sep->unref(); mat->unref(); continue; // jump to next constraint } break; case Horizontal: case Vertical: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); // remember the type of this constraint node edit->vConstrType.push_back((*it)->Type); } break; case Coincident: // no visual for coincident so far edit->vConstrType.push_back(Coincident); break; case Parallel: case Perpendicular: case Equal: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 sep->addChild(new SoInfo()); // remember the type of this constraint node edit->vConstrType.push_back((*it)->Type); } break; case PointOnObject: case Tangent: case SnellsLaw: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); if ((*it)->Type == Tangent) { const Part::Geometry *geo1 = getSketchObject()->getGeometry((*it)->First); const Part::Geometry *geo2 = getSketchObject()->getGeometry((*it)->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 sep->addChild(new SoInfo()); } } edit->vConstrType.push_back((*it)->Type); } break; case Symmetric: { SoDatumLabel *arrows = new SoDatumLabel(); arrows->norm.setValue(norm); arrows->string = ""; arrows->textColor = ConstrDimColor; // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(arrows); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); edit->vConstrType.push_back((*it)->Type); } break; case InternalAlignment: { edit->vConstrType.push_back((*it)->Type); } break; default: edit->vConstrType.push_back((*it)->Type); } edit->constrGroup->addChild(sep); // decrement ref counter again sep->unref(); mat->unref(); } } void ViewProviderSketch::drawEdit(const std::vector<Base::Vector2d> &EditCurve) { assert(edit); edit->EditCurveSet->numVertices.setNum(1); edit->EditCurvesCoordinate->point.setNum(EditCurve.size()); SbVec3f *verts = edit->EditCurvesCoordinate->point.startEditing(); int32_t *index = edit->EditCurveSet->numVertices.startEditing(); int i=0; // setting up the line set for (std::vector<Base::Vector2d>::const_iterator it = EditCurve.begin(); it != EditCurve.end(); ++it,i++) verts[i].setValue(it->x,it->y,zEdit); index[0] = EditCurve.size(); edit->EditCurvesCoordinate->point.finishEditing(); edit->EditCurveSet->numVertices.finishEditing(); } void ViewProviderSketch::updateData(const App::Property *prop) { ViewProvider2DObject::updateData(prop); if (edit && (prop == &(getSketchObject()->Geometry) || prop == &(getSketchObject()->Constraints))) { edit->FullyConstrained = false; // At this point, we do not need to solve the Sketch // If we are adding geometry an update can be triggered before the sketch is actually solved. // Because a solve is mandatory to any addition (at least to update the DoF of the solver), // only when the solver geometry is the same in number than the sketch geometry an update // should trigger a redraw. This reduces even more the number of redraws per insertion of geometry // solver information is also updated when no matching geometry, so that if a solving fails // this failed solving info is presented to the user UpdateSolverInformation(); // just update the solver window with the last SketchObject solving information if(getSketchObject()->getExternalGeometryCount()+getSketchObject()->getHighestCurveIndex() + 1 == getSketchObject()->getSolvedSketch().getGeometrySize()) { Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); if (mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) draw(false,true); signalConstraintsChanged(); signalElementsChanged(); } } } void ViewProviderSketch::onChanged(const App::Property *prop) { // call father PartGui::ViewProvider2DObject::onChanged(prop); } void ViewProviderSketch::attach(App::DocumentObject *pcFeat) { ViewProviderPart::attach(pcFeat); } void ViewProviderSketch::setupContextMenu(QMenu *menu, QObject *receiver, const char *member) { menu->addAction(tr("Edit sketch"), receiver, member); } bool ViewProviderSketch::setEdit(int ModNum) { Q_UNUSED(ModNum); //find the Part and body object the feature belongs to for placement calculations //TODO: this needs to be replaced with GRAPH methods to get the real stacked placement parentBody = Part::BodyBase::findBodyOf(getSketchObject()); if(parentBody) parentPart = App::Part::getPartOfObject(parentBody); else parentPart = App::Part::getPartOfObject(getSketchObject()); // always change to sketcher WB, remember where we come from oldWb = Gui::Command::assureWorkbench("SketcherWorkbench"); // When double-clicking on the item for this sketch the // object unsets and sets its edit mode without closing // the task panel Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); TaskDlgEditSketch *sketchDlg = qobject_cast<TaskDlgEditSketch *>(dlg); if (sketchDlg && sketchDlg->getSketchView() != this) sketchDlg = 0; // another sketch left open its task panel if (dlg && !sketchDlg) { QMessageBox msgBox; msgBox.setText(tr("A dialog is already open in the task panel")); msgBox.setInformativeText(tr("Do you want to close this dialog?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); if (ret == QMessageBox::Yes) Gui::Control().reject(); else return false; } Sketcher::SketchObject* sketch = getSketchObject(); if (!sketch->evaluateConstraints()) { QMessageBox box(Gui::getMainWindow()); box.setIcon(QMessageBox::Critical); box.setWindowTitle(tr("Invalid sketch")); box.setText(tr("Do you want to open the sketch validation tool?")); box.setInformativeText(tr("The sketch is invalid and cannot be edited.")); box.setStandardButtons(QMessageBox::Yes | QMessageBox::No); box.setDefaultButton(QMessageBox::Yes); switch (box.exec()) { case QMessageBox::Yes: Gui::Control().showDialog(new TaskSketcherValidation(getSketchObject())); break; default: break; } return false; } // clear the selection (convenience) Gui::Selection().clearSelection(); // create the container for the additional edit data assert(!edit); edit = new EditData(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); edit->MarkerSize = hGrp->GetInt("EditSketcherMarkerSize", 7); createEditInventorNodes(); //visibility automation try{ Gui::Command::addModule(Gui::Command::Gui,"Show.TempoVis"); try{ QString cmdstr = QString::fromLatin1( "ActiveSketch = App.ActiveDocument.getObject('{sketch_name}')\n" "tv = Show.TempoVis(App.ActiveDocument)\n" "if ActiveSketch.ViewObject.HideDependent:\n" " tv.hide_all_dependent(ActiveSketch)\n" "if ActiveSketch.ViewObject.ShowSupport:\n" " tv.show([ref[0] for ref in ActiveSketch.Support])\n" "if ActiveSketch.ViewObject.ShowLinks:\n" " tv.show([ref[0] for ref in ActiveSketch.ExternalGeometry])\n" "tv.hide(ActiveSketch)\n" "ActiveSketch.ViewObject.TempoVis = tv\n" "del(tv)\n" ); cmdstr.replace(QString::fromLatin1("{sketch_name}"),QString::fromLatin1(this->getSketchObject()->getNameInDocument())); QByteArray cmdstr_bytearray = cmdstr.toLatin1(); Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); } catch (Base::PyException &e){ Base::Console().Error("ViewProviderSketch::setEdit: visibility automation failed with an error: \n"); e.ReportException(); } } catch (Base::PyException &){ Base::Console().Warning("ViewProviderSketch::setEdit: could not import Show module. Visibility automation will not work.\n"); } ShowGrid.setValue(true); TightGrid.setValue(false); float transparency; // set the point color unsigned long color = (unsigned long)(VertexColor.getPackedValue()); color = hGrp->GetUnsigned("EditedVertexColor", color); VertexColor.setPackedValue((uint32_t)color, transparency); // set the curve color color = (unsigned long)(CurveColor.getPackedValue()); color = hGrp->GetUnsigned("EditedEdgeColor", color); CurveColor.setPackedValue((uint32_t)color, transparency); // set the construction curve color color = (unsigned long)(CurveDraftColor.getPackedValue()); color = hGrp->GetUnsigned("ConstructionColor", color); CurveDraftColor.setPackedValue((uint32_t)color, transparency); // set the cross lines color //CrossColorV.setPackedValue((uint32_t)color, transparency); //CrossColorH.setPackedValue((uint32_t)color, transparency); // set the fully constrained color color = (unsigned long)(FullyConstrainedColor.getPackedValue()); color = hGrp->GetUnsigned("FullyConstrainedColor", color); FullyConstrainedColor.setPackedValue((uint32_t)color, transparency); // set the constraint dimension color color = (unsigned long)(ConstrDimColor.getPackedValue()); color = hGrp->GetUnsigned("ConstrainedDimColor", color); ConstrDimColor.setPackedValue((uint32_t)color, transparency); // set the constraint color color = (unsigned long)(ConstrIcoColor.getPackedValue()); color = hGrp->GetUnsigned("ConstrainedIcoColor", color); ConstrIcoColor.setPackedValue((uint32_t)color, transparency); // set non-driving constraint color color = (unsigned long)(NonDrivingConstrDimColor.getPackedValue()); color = hGrp->GetUnsigned("NonDrivingConstrDimColor", color); NonDrivingConstrDimColor.setPackedValue((uint32_t)color, transparency); // set the external geometry color color = (unsigned long)(CurveExternalColor.getPackedValue()); color = hGrp->GetUnsigned("ExternalColor", color); CurveExternalColor.setPackedValue((uint32_t)color, transparency); // set the highlight color unsigned long highlight = (unsigned long)(PreselectColor.getPackedValue()); highlight = hGrp->GetUnsigned("HighlightColor", highlight); PreselectColor.setPackedValue((uint32_t)highlight, transparency); // set the selection color highlight = (unsigned long)(SelectColor.getPackedValue()); highlight = hGrp->GetUnsigned("SelectionColor", highlight); SelectColor.setPackedValue((uint32_t)highlight, transparency); // start the edit dialog if (sketchDlg) Gui::Control().showDialog(sketchDlg); else Gui::Control().showDialog(new TaskDlgEditSketch(this)); // This call to the solver is needed to initialize the DoF and solve time controls // The false parameter indicates that the geometry of the SketchObject shall not be updateData // so as not to trigger an onChanged that would set the document as modified and trigger a recompute // if we just close the sketch without touching anything. if (getSketchObject()->Support.getValue()) { if (!getSketchObject()->evaluateSupport()) getSketchObject()->validateExternalLinks(); } getSketchObject()->solve(false); UpdateSolverInformation(); draw(false,true); connectUndoDocument = Gui::Application::Instance->activeDocument() ->signalUndoDocument.connect(boost::bind(&ViewProviderSketch::slotUndoDocument, this, _1)); connectRedoDocument = Gui::Application::Instance->activeDocument() ->signalRedoDocument.connect(boost::bind(&ViewProviderSketch::slotRedoDocument, this, _1)); return true; } QString ViewProviderSketch::appendConflictMsg(const std::vector<int> &conflicting) { QString msg; QTextStream ss(&msg); if (conflicting.size() > 0) { if (conflicting.size() == 1) ss << tr("Please remove the following constraint:"); else ss << tr("Please remove at least one of the following constraints:"); ss << "\n"; ss << conflicting[0]; for (unsigned int i=1; i < conflicting.size(); i++) ss << ", " << conflicting[i]; ss << "\n"; } return msg; } QString ViewProviderSketch::appendRedundantMsg(const std::vector<int> &redundant) { QString msg; QTextStream ss(&msg); if (redundant.size() > 0) { if (redundant.size() == 1) ss << tr("Please remove the following redundant constraint:"); else ss << tr("Please remove the following redundant constraints:"); ss << "\n"; ss << redundant[0]; for (unsigned int i=1; i < redundant.size(); i++) ss << ", " << redundant[i]; ss << "\n"; } return msg; } void ViewProviderSketch::UpdateSolverInformation() { // Updates Solver Information with the Last solver execution at SketchObject level int dofs = getSketchObject()->getLastDoF(); bool hasConflicts = getSketchObject()->getLastHasConflicts(); bool hasRedundancies = getSketchObject()->getLastHasRedundancies(); if (getSketchObject()->Geometry.getSize() == 0) { signalSetUp(tr("Empty sketch")); signalSolved(QString()); } else if (dofs < 0) { // over-constrained sketch std::string msg; SketchObject::appendConflictMsg(getSketchObject()->getLastConflicting(), msg); signalSetUp(QString::fromLatin1("<font color='red'>%1<a href=\"#conflicting\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Over-constrained sketch ")) .arg(tr("(click to select)")) .arg(QString::fromStdString(msg))); signalSolved(QString()); } else if (hasConflicts) { // conflicting constraints signalSetUp(QString::fromLatin1("<font color='red'>%1<a href=\"#conflicting\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Sketch contains conflicting constraints ")) .arg(tr("(click to select)")) .arg(appendConflictMsg(getSketchObject()->getLastConflicting()))); signalSolved(QString()); } else { if (hasRedundancies) { // redundant constraints signalSetUp(QString::fromLatin1("<font color='orangered'>%1<a href=\"#redundant\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Sketch contains redundant constraints ")) .arg(tr("(click to select)")) .arg(appendRedundantMsg(getSketchObject()->getLastRedundant()))); } if (getSketchObject()->getLastSolverStatus() == 0) { if (dofs == 0) { // color the sketch as fully constrained if it has geometry (other than the axes) if(getSketchObject()->getSolvedSketch().getGeometrySize()>2) edit->FullyConstrained = true; if (!hasRedundancies) { signalSetUp(QString::fromLatin1("<font color='green'>%1</font>").arg(tr("Fully constrained sketch"))); } } else if (!hasRedundancies) { if (dofs == 1) signalSetUp(tr("Under-constrained sketch with 1 degree of freedom")); else signalSetUp(tr("Under-constrained sketch with %1 degrees of freedom").arg(dofs)); } signalSolved(QString::fromLatin1("<font color='green'>%1</font>").arg(tr("Solved in %1 sec").arg(getSketchObject()->getLastSolveTime()))); } else { signalSolved(QString::fromLatin1("<font color='red'>%1</font>").arg(tr("Unsolved (%1 sec)").arg(getSketchObject()->getLastSolveTime()))); } } } void ViewProviderSketch::createEditInventorNodes(void) { assert(edit); edit->EditRoot = new SoSeparator; edit->EditRoot->setName("Sketch_EditRoot"); pcRoot->addChild(edit->EditRoot); edit->EditRoot->renderCaching = SoSeparator::OFF ; // stuff for the points ++++++++++++++++++++++++++++++++++++++ SoSeparator* pointsRoot = new SoSeparator; edit->EditRoot->addChild(pointsRoot); edit->PointsMaterials = new SoMaterial; edit->PointsMaterials->setName("PointsMaterials"); pointsRoot->addChild(edit->PointsMaterials); SoMaterialBinding *MtlBind = new SoMaterialBinding; MtlBind->setName("PointsMaterialBinding"); MtlBind->value = SoMaterialBinding::PER_VERTEX; pointsRoot->addChild(MtlBind); edit->PointsCoordinate = new SoCoordinate3; edit->PointsCoordinate->setName("PointsCoordinate"); pointsRoot->addChild(edit->PointsCoordinate); SoDrawStyle *DrawStyle = new SoDrawStyle; DrawStyle->setName("PointsDrawStyle"); DrawStyle->pointSize = 8; pointsRoot->addChild(DrawStyle); edit->PointSet = new SoMarkerSet; edit->PointSet->setName("PointSet"); edit->PointSet->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", edit->MarkerSize); pointsRoot->addChild(edit->PointSet); // stuff for the Curves +++++++++++++++++++++++++++++++++++++++ SoSeparator* curvesRoot = new SoSeparator; edit->EditRoot->addChild(curvesRoot); edit->CurvesMaterials = new SoMaterial; edit->CurvesMaterials->setName("CurvesMaterials"); curvesRoot->addChild(edit->CurvesMaterials); MtlBind = new SoMaterialBinding; MtlBind->setName("CurvesMaterialsBinding"); MtlBind->value = SoMaterialBinding::PER_FACE; curvesRoot->addChild(MtlBind); edit->CurvesCoordinate = new SoCoordinate3; edit->CurvesCoordinate->setName("CurvesCoordinate"); curvesRoot->addChild(edit->CurvesCoordinate); DrawStyle = new SoDrawStyle; DrawStyle->setName("CurvesDrawStyle"); DrawStyle->lineWidth = 3; curvesRoot->addChild(DrawStyle); edit->CurveSet = new SoLineSet; edit->CurveSet->setName("CurvesLineSet"); curvesRoot->addChild(edit->CurveSet); // stuff for the RootCross lines +++++++++++++++++++++++++++++++++++++++ SoGroup* crossRoot = new Gui::SoSkipBoundingGroup; edit->pickStyleAxes = new SoPickStyle(); edit->pickStyleAxes->style = SoPickStyle::SHAPE; crossRoot->addChild(edit->pickStyleAxes); edit->EditRoot->addChild(crossRoot); MtlBind = new SoMaterialBinding; MtlBind->setName("RootCrossMaterialBinding"); MtlBind->value = SoMaterialBinding::PER_FACE; crossRoot->addChild(MtlBind); DrawStyle = new SoDrawStyle; DrawStyle->setName("RootCrossDrawStyle"); DrawStyle->lineWidth = 2; crossRoot->addChild(DrawStyle); edit->RootCrossMaterials = new SoMaterial; edit->RootCrossMaterials->setName("RootCrossMaterials"); edit->RootCrossMaterials->diffuseColor.set1Value(0,CrossColorH); edit->RootCrossMaterials->diffuseColor.set1Value(1,CrossColorV); crossRoot->addChild(edit->RootCrossMaterials); edit->RootCrossCoordinate = new SoCoordinate3; edit->RootCrossCoordinate->setName("RootCrossCoordinate"); crossRoot->addChild(edit->RootCrossCoordinate); edit->RootCrossSet = new SoLineSet; edit->RootCrossSet->setName("RootCrossLineSet"); crossRoot->addChild(edit->RootCrossSet); // stuff for the EditCurves +++++++++++++++++++++++++++++++++++++++ SoSeparator* editCurvesRoot = new SoSeparator; edit->EditRoot->addChild(editCurvesRoot); edit->EditCurvesMaterials = new SoMaterial; edit->EditCurvesMaterials->setName("EditCurvesMaterials"); editCurvesRoot->addChild(edit->EditCurvesMaterials); edit->EditCurvesCoordinate = new SoCoordinate3; edit->EditCurvesCoordinate->setName("EditCurvesCoordinate"); editCurvesRoot->addChild(edit->EditCurvesCoordinate); DrawStyle = new SoDrawStyle; DrawStyle->setName("EditCurvesDrawStyle"); DrawStyle->lineWidth = 3; editCurvesRoot->addChild(DrawStyle); edit->EditCurveSet = new SoLineSet; edit->EditCurveSet->setName("EditCurveLineSet"); editCurvesRoot->addChild(edit->EditCurveSet); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); float transparency; SbColor cursorTextColor(0,0,1); cursorTextColor.setPackedValue((uint32_t)hGrp->GetUnsigned("CursorTextColor", cursorTextColor.getPackedValue()), transparency); // stuff for the edit coordinates ++++++++++++++++++++++++++++++++++++++ SoSeparator *Coordsep = new SoSeparator(); Coordsep->setName("CoordSeparator"); // no caching for fluctuand data structures Coordsep->renderCaching = SoSeparator::OFF; SoMaterial *CoordTextMaterials = new SoMaterial; CoordTextMaterials->setName("CoordTextMaterials"); CoordTextMaterials->diffuseColor = cursorTextColor; Coordsep->addChild(CoordTextMaterials); int fontSize = hGrp->GetInt("EditSketcherFontSize", 17); SoFont *font = new SoFont(); font->size.setValue(fontSize); Coordsep->addChild(font); edit->textPos = new SoTranslation(); Coordsep->addChild(edit->textPos); edit->textX = new SoText2(); edit->textX->justification = SoText2::LEFT; edit->textX->string = ""; Coordsep->addChild(edit->textX); edit->EditRoot->addChild(Coordsep); // group node for the Constraint visual +++++++++++++++++++++++++++++++++++ MtlBind = new SoMaterialBinding; MtlBind->setName("ConstraintMaterialBinding"); MtlBind->value = SoMaterialBinding::OVERALL ; edit->EditRoot->addChild(MtlBind); // use small line width for the Constraints DrawStyle = new SoDrawStyle; DrawStyle->setName("ConstraintDrawStyle"); DrawStyle->lineWidth = 1; edit->EditRoot->addChild(DrawStyle); // add the group where all the constraints has its SoSeparator edit->constrGroup = new SoGroup(); edit->constrGroup->setName("ConstraintGroup"); edit->EditRoot->addChild(edit->constrGroup); // group node for the Geometry information visual +++++++++++++++++++++++++++++++++++ MtlBind = new SoMaterialBinding; MtlBind->setName("InformationMaterialBinding"); MtlBind->value = SoMaterialBinding::OVERALL ; edit->EditRoot->addChild(MtlBind); // use small line width for the information visual DrawStyle = new SoDrawStyle; DrawStyle->setName("InformationDrawStyle"); DrawStyle->lineWidth = 1; edit->EditRoot->addChild(DrawStyle); // add the group where all the information entity has its SoSeparator edit->infoGroup = new SoGroup(); edit->infoGroup->setName("InformationGroup"); edit->EditRoot->addChild(edit->infoGroup); } void ViewProviderSketch::unsetEdit(int ModNum) { Q_UNUSED(ModNum); ShowGrid.setValue(false); TightGrid.setValue(true); if (edit) { if (edit->sketchHandler) deactivateHandler(); edit->EditRoot->removeAllChildren(); pcRoot->removeChild(edit->EditRoot); //visibility autoation try{ QString cmdstr = QString::fromLatin1( "ActiveSketch = App.ActiveDocument.getObject('{sketch_name}')\n" "tv = ActiveSketch.ViewObject.TempoVis\n" "if tv:\n" " tv.restore()\n" "ActiveSketch.ViewObject.TempoVis = None\n" "del(tv)\n" ); cmdstr.replace(QString::fromLatin1("{sketch_name}"),QString::fromLatin1(this->getSketchObject()->getNameInDocument())); QByteArray cmdstr_bytearray = cmdstr.toLatin1(); Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); } catch (Base::PyException &e){ Base::Console().Error("ViewProviderSketch::unsetEdit: visibility automation failed with an error: \n"); e.ReportException(); } delete edit; edit = 0; try { // and update the sketch getSketchObject()->getDocument()->recompute(); } catch (...) { } } // clear the selection and set the new/edited sketch(convenience) Gui::Selection().clearSelection(); std::string ObjName = getSketchObject()->getNameInDocument(); std::string DocName = getSketchObject()->getDocument()->getName(); Gui::Selection().addSelection(DocName.c_str(),ObjName.c_str()); connectUndoDocument.disconnect(); connectRedoDocument.disconnect(); // when pressing ESC make sure to close the dialog Gui::Control().closeDialog(); //Gui::Application::Instance-> // return to the WB before edeting the sketch Gui::Command::assureWorkbench(oldWb.c_str()); } void ViewProviderSketch::setEditViewer(Gui::View3DInventorViewer* viewer, int ModNum) { Q_UNUSED(ModNum); //visibility automation: save camera if (! this->TempoVis.getValue().isNone()){ try{ QString cmdstr = QString::fromLatin1( "ActiveSketch = App.ActiveDocument.getObject('{sketch_name}')\n" "if ActiveSketch.ViewObject.RestoreCamera:\n" " ActiveSketch.ViewObject.TempoVis.saveCamera()\n" ); cmdstr.replace(QString::fromLatin1("{sketch_name}"),QString::fromLatin1(this->getSketchObject()->getNameInDocument())); QByteArray cmdstr_bytearray = cmdstr.toLatin1(); Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); } catch (Base::PyException &e){ Base::Console().Error("ViewProviderSketch::setEdit: visibility automation failed with an error: \n"); e.ReportException(); } } Base::Placement plm = getPlacement(); Base::Rotation tmp(plm.getRotation()); SbRotation rot((float)tmp[0],(float)tmp[1],(float)tmp[2],(float)tmp[3]); // Will the sketch be visible from the new position (#0000957)? // SoCamera* camera = viewer->getSoRenderManager()->getCamera(); SbVec3f curdir; // current view direction camera->orientation.getValue().multVec(SbVec3f(0, 0, -1), curdir); SbVec3f focal = camera->position.getValue() + camera->focalDistance.getValue() * curdir; SbVec3f newdir; // future view direction rot.multVec(SbVec3f(0, 0, -1), newdir); SbVec3f newpos = focal - camera->focalDistance.getValue() * newdir; SbVec3f plnpos = Base::convertTo<SbVec3f>(plm.getPosition()); double dist = (plnpos - newpos).dot(newdir); if (dist < 0) { float focalLength = camera->focalDistance.getValue() - dist + 5; camera->position = focal - focalLength * curdir; camera->focalDistance.setValue(focalLength); } viewer->setCameraOrientation(rot); viewer->setEditing(true); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(false); viewer->addGraphicsItem(rubberband); rubberband->setViewer(viewer); } void ViewProviderSketch::unsetEditViewer(Gui::View3DInventorViewer* viewer) { viewer->removeGraphicsItem(rubberband); viewer->setEditing(false); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(true); } void ViewProviderSketch::setPositionText(const Base::Vector2d &Pos, const SbString &text) { edit->textX->string = text; edit->textPos->translation = SbVec3f(Pos.x,Pos.y,zText); } void ViewProviderSketch::setPositionText(const Base::Vector2d &Pos) { SbString text; text.sprintf(" (%.1f,%.1f)", Pos.x, Pos.y); edit->textX->string = text; edit->textPos->translation = SbVec3f(Pos.x,Pos.y,zText); } void ViewProviderSketch::resetPositionText(void) { edit->textX->string = ""; } void ViewProviderSketch::setPreselectPoint(int PreselectPoint) { if (edit) { int oldPtId = -1; if (edit->PreselectPoint != -1) oldPtId = edit->PreselectPoint + 1; else if (edit->PreselectCross == 0) oldPtId = 0; int newPtId = PreselectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); float x,y,z; if (oldPtId != -1 && edit->SelPointSet.find(oldPtId) == edit->SelPointSet.end()) { // send to background pverts[oldPtId].getValue(x,y,z); pverts[oldPtId].setValue(x,y,zPoints); } // bring to foreground pverts[newPtId].getValue(x,y,z); pverts[newPtId].setValue(x,y,zHighlight); edit->PreselectPoint = PreselectPoint; edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::resetPreselectPoint(void) { if (edit) { int oldPtId = -1; if (edit->PreselectPoint != -1) oldPtId = edit->PreselectPoint + 1; else if (edit->PreselectCross == 0) oldPtId = 0; if (oldPtId != -1 && edit->SelPointSet.find(oldPtId) == edit->SelPointSet.end()) { // send to background SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); float x,y,z; pverts[oldPtId].getValue(x,y,z); pverts[oldPtId].setValue(x,y,zPoints); edit->PointsCoordinate->point.finishEditing(); } edit->PreselectPoint = -1; } } void ViewProviderSketch::addSelectPoint(int SelectPoint) { if (edit) { int PtId = SelectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // bring to foreground float x,y,z; pverts[PtId].getValue(x,y,z); pverts[PtId].setValue(x,y,zHighlight); edit->SelPointSet.insert(PtId); edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::removeSelectPoint(int SelectPoint) { if (edit) { int PtId = SelectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // send to background float x,y,z; pverts[PtId].getValue(x,y,z); pverts[PtId].setValue(x,y,zPoints); edit->SelPointSet.erase(PtId); edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::clearSelectPoints(void) { if (edit) { SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // send to background float x,y,z; for (std::set<int>::const_iterator it=edit->SelPointSet.begin(); it != edit->SelPointSet.end(); ++it) { pverts[*it].getValue(x,y,z); pverts[*it].setValue(x,y,zPoints); } edit->PointsCoordinate->point.finishEditing(); edit->SelPointSet.clear(); } } int ViewProviderSketch::getPreselectPoint(void) const { if (edit) return edit->PreselectPoint; return -1; } int ViewProviderSketch::getPreselectCurve(void) const { if (edit) return edit->PreselectCurve; return -1; } int ViewProviderSketch::getPreselectCross(void) const { if (edit) return edit->PreselectCross; return -1; } Sketcher::SketchObject *ViewProviderSketch::getSketchObject(void) const { return dynamic_cast<Sketcher::SketchObject *>(pcObject); } bool ViewProviderSketch::onDelete(const std::vector<std::string> &subList) { if (edit) { std::vector<std::string> SubNames = subList; Gui::Selection().clearSelection(); resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); std::set<int> delInternalGeometries, delExternalGeometries, delCoincidents, delConstraints; // go through the selected subelements for (std::vector<std::string>::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { if (it->size() > 4 && it->substr(0,4) == "Edge") { int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; if( GeoId >= 0 ) delInternalGeometries.insert(GeoId); else delExternalGeometries.insert(Sketcher::GeoEnum::RefExt - GeoId); } else if (it->size() > 12 && it->substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(it->substr(12,4000).c_str()) - 1; delExternalGeometries.insert(GeoId); } else if (it->size() > 6 && it->substr(0,6) == "Vertex") { int VtId = std::atoi(it->substr(6,4000).c_str()) - 1; int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(VtId, GeoId, PosId); if (getSketchObject()->getGeometry(GeoId)->getTypeId() == Part::GeomPoint::getClassTypeId()) { if(GeoId>=0) delInternalGeometries.insert(GeoId); else delExternalGeometries.insert(Sketcher::GeoEnum::RefExt - GeoId); } else delCoincidents.insert(VtId); } else if (*it == "RootPoint") { delCoincidents.insert(Sketcher::GeoEnum::RtPnt); } else if (it->size() > 10 && it->substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it); delConstraints.insert(ConstrId); } } std::set<int>::const_reverse_iterator rit; for (rit = delConstraints.rbegin(); rit != delConstraints.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delConstraint(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delCoincidents.rbegin(); rit != delCoincidents.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delConstraintOnPoint(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delInternalGeometries.rbegin(); rit != delInternalGeometries.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delGeometry(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delExternalGeometries.rbegin(); rit != delExternalGeometries.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delExternal(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } int ret=getSketchObject()->solve(); if(ret!=0){ // if the sketched could not be solved, we first redraw to update the UI geometry as // onChanged did not update it. UpdateSolverInformation(); draw(false,true); signalConstraintsChanged(); signalElementsChanged(); } /*this->drawConstraintIcons(); this->updateColor();*/ // if in edit not delete the object return false; } // if not in edit delete the whole object return PartGui::ViewProviderPart::onDelete(subList); } Base::Placement ViewProviderSketch::getPlacement() { //TODO: use GRAPH placement handling, as this function right now only works with one parent //part object Base::Placement Plz = getSketchObject()->Placement.getValue(); if(parentBody) Plz = parentBody->Placement.getValue()*Plz; if(parentPart) Plz = parentPart->Placement.getValue()*Plz; return Plz; } void ViewProviderSketch::showRestoreInformationLayer() { visibleInformationChanged = true ; draw(false,false); }
lgpl-2.1
Lyude/gtk-
gtk/gtkcssmatcher.c
2
19274
/* GTK - The GIMP Toolkit * Copyright (C) 2012 Benjamin Otte <otte@gnome.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "gtkcssmatcherprivate.h" #include "gtkcssnodedeclarationprivate.h" #include "gtkcssnodeprivate.h" #include "gtkwidgetpath.h" /* GTK_CSS_MATCHER_WIDGET_PATH */ static gboolean gtk_css_matcher_widget_path_get_parent (GtkCssMatcher *matcher, const GtkCssMatcher *child) { if (child->path.index == 0) return FALSE; matcher->path.klass = child->path.klass; matcher->path.decl = NULL; matcher->path.path = child->path.path; matcher->path.index = child->path.index - 1; matcher->path.sibling_index = gtk_widget_path_iter_get_sibling_index (matcher->path.path, matcher->path.index); return TRUE; } static gboolean gtk_css_matcher_widget_path_get_previous (GtkCssMatcher *matcher, const GtkCssMatcher *next) { if (next->path.sibling_index == 0) return FALSE; matcher->path.klass = next->path.klass; matcher->path.decl = NULL; matcher->path.path = next->path.path; matcher->path.index = next->path.index; matcher->path.sibling_index = next->path.sibling_index - 1; return TRUE; } static GtkStateFlags gtk_css_matcher_widget_path_get_state (const GtkCssMatcher *matcher) { const GtkWidgetPath *siblings; if (matcher->path.decl) return gtk_css_node_declaration_get_state (matcher->path.decl); siblings = gtk_widget_path_iter_get_siblings (matcher->path.path, matcher->path.index); if (siblings && matcher->path.sibling_index != gtk_widget_path_iter_get_sibling_index (matcher->path.path, matcher->path.index)) return gtk_widget_path_iter_get_state (siblings, matcher->path.sibling_index); else return gtk_widget_path_iter_get_state (matcher->path.path, matcher->path.index); } static gboolean gtk_css_matcher_widget_path_has_type (const GtkCssMatcher *matcher, GType type) { const GtkWidgetPath *siblings; siblings = gtk_widget_path_iter_get_siblings (matcher->path.path, matcher->path.index); if (siblings && matcher->path.sibling_index != gtk_widget_path_iter_get_sibling_index (matcher->path.path, matcher->path.index)) return g_type_is_a (gtk_widget_path_iter_get_object_type (siblings, matcher->path.sibling_index), type); else return g_type_is_a (gtk_widget_path_iter_get_object_type (matcher->path.path, matcher->path.index), type); } static gboolean gtk_css_matcher_widget_path_has_class (const GtkCssMatcher *matcher, GQuark class_name) { const GtkWidgetPath *siblings; if (matcher->path.decl && gtk_css_node_declaration_has_class (matcher->path.decl, class_name)) return TRUE; siblings = gtk_widget_path_iter_get_siblings (matcher->path.path, matcher->path.index); if (siblings && matcher->path.sibling_index != gtk_widget_path_iter_get_sibling_index (matcher->path.path, matcher->path.index)) return gtk_widget_path_iter_has_qclass (siblings, matcher->path.sibling_index, class_name); else return gtk_widget_path_iter_has_qclass (matcher->path.path, matcher->path.index, class_name); } static gboolean gtk_css_matcher_widget_path_has_id (const GtkCssMatcher *matcher, const char *id) { const GtkWidgetPath *siblings; siblings = gtk_widget_path_iter_get_siblings (matcher->path.path, matcher->path.index); if (siblings && matcher->path.sibling_index != gtk_widget_path_iter_get_sibling_index (matcher->path.path, matcher->path.index)) return gtk_widget_path_iter_has_name (siblings, matcher->path.sibling_index, id); else return gtk_widget_path_iter_has_name (matcher->path.path, matcher->path.index, id); } static gboolean gtk_css_matcher_widget_path_has_regions (const GtkCssMatcher *matcher) { const GtkWidgetPath *siblings; GSList *regions; gboolean result; if (matcher->path.decl) { GList *list = gtk_css_node_declaration_list_regions (matcher->path.decl); if (list) { g_list_free (list); return TRUE; } } G_GNUC_BEGIN_IGNORE_DEPRECATIONS siblings = gtk_widget_path_iter_get_siblings (matcher->path.path, matcher->path.index); if (siblings && matcher->path.sibling_index != gtk_widget_path_iter_get_sibling_index (matcher->path.path, matcher->path.index)) regions = gtk_widget_path_iter_list_regions (siblings, matcher->path.sibling_index); else regions = gtk_widget_path_iter_list_regions (matcher->path.path, matcher->path.index); result = regions != NULL; g_slist_free (regions); return result; G_GNUC_END_IGNORE_DEPRECATIONS } static gboolean gtk_css_matcher_widget_path_has_region (const GtkCssMatcher *matcher, const char *region, GtkRegionFlags flags) { const GtkWidgetPath *siblings; GtkRegionFlags region_flags; if (matcher->path.decl) { GQuark q = g_quark_try_string (region); if (q && gtk_css_node_declaration_has_region (matcher->path.decl, q, &region_flags)) goto found; } G_GNUC_BEGIN_IGNORE_DEPRECATIONS siblings = gtk_widget_path_iter_get_siblings (matcher->path.path, matcher->path.index); if (siblings && matcher->path.sibling_index != gtk_widget_path_iter_get_sibling_index (matcher->path.path, matcher->path.index)) { if (!gtk_widget_path_iter_has_region (siblings, matcher->path.sibling_index, region, &region_flags)) return FALSE; } else { if (!gtk_widget_path_iter_has_region (matcher->path.path, matcher->path.index, region, &region_flags)) return FALSE; } G_GNUC_END_IGNORE_DEPRECATIONS found: if ((flags & region_flags) != flags) return FALSE; return TRUE; } static gboolean gtk_css_matcher_widget_path_has_position (const GtkCssMatcher *matcher, gboolean forward, int a, int b) { const GtkWidgetPath *siblings; int x; siblings = gtk_widget_path_iter_get_siblings (matcher->path.path, matcher->path.index); if (!siblings) return FALSE; if (forward) x = matcher->path.sibling_index + 1; else x = gtk_widget_path_length (siblings) - matcher->path.sibling_index; x -= b; if (a == 0) return x == 0; if (x % a) return FALSE; return x / a > 0; } static const GtkCssMatcherClass GTK_CSS_MATCHER_WIDGET_PATH = { gtk_css_matcher_widget_path_get_parent, gtk_css_matcher_widget_path_get_previous, gtk_css_matcher_widget_path_get_state, gtk_css_matcher_widget_path_has_type, gtk_css_matcher_widget_path_has_class, gtk_css_matcher_widget_path_has_id, gtk_css_matcher_widget_path_has_regions, gtk_css_matcher_widget_path_has_region, gtk_css_matcher_widget_path_has_position, FALSE }; gboolean _gtk_css_matcher_init (GtkCssMatcher *matcher, const GtkWidgetPath *path, const GtkCssNodeDeclaration *decl) { if (gtk_widget_path_length (path) == 0) return FALSE; matcher->path.klass = &GTK_CSS_MATCHER_WIDGET_PATH; matcher->path.decl = decl; matcher->path.path = path; matcher->path.index = gtk_widget_path_length (path) - 1; matcher->path.sibling_index = gtk_widget_path_iter_get_sibling_index (path, matcher->path.index); return TRUE; } /* GTK_CSS_MATCHER_NODE */ static gboolean gtk_css_matcher_node_get_parent (GtkCssMatcher *matcher, const GtkCssMatcher *child) { GtkCssNode *node; node = gtk_css_node_get_parent (child->node.node); if (node == NULL) return FALSE; return gtk_css_node_init_matcher (node, matcher); } static GtkCssNode * get_previous_visible_sibling (GtkCssNode *node) { do { node = gtk_css_node_get_previous_sibling (node); } while (node && !gtk_css_node_get_visible (node)); return node; } static GtkCssNode * get_next_visible_sibling (GtkCssNode *node) { do { node = gtk_css_node_get_next_sibling (node); } while (node && !gtk_css_node_get_visible (node)); return node; } static gboolean gtk_css_matcher_node_get_previous (GtkCssMatcher *matcher, const GtkCssMatcher *next) { GtkCssNode *node; node = get_previous_visible_sibling (next->node.node); if (node == NULL) return FALSE; return gtk_css_node_init_matcher (node, matcher); } static GtkStateFlags gtk_css_matcher_node_get_state (const GtkCssMatcher *matcher) { return gtk_css_node_get_state (matcher->node.node); } static gboolean gtk_css_matcher_node_has_type (const GtkCssMatcher *matcher, GType type) { return g_type_is_a (gtk_css_node_get_widget_type (matcher->node.node), type); } static gboolean gtk_css_matcher_node_has_class (const GtkCssMatcher *matcher, GQuark class_name) { return gtk_css_node_has_class (matcher->node.node, class_name); } static gboolean gtk_css_matcher_node_has_id (const GtkCssMatcher *matcher, const char *id) { return gtk_css_node_get_id (matcher->node.node) == g_intern_string (id); } static gboolean gtk_css_matcher_node_has_regions (const GtkCssMatcher *matcher) { GList *regions; gboolean result; regions = gtk_css_node_list_regions (matcher->node.node); result = regions != NULL; g_list_free (regions); return result; } static gboolean gtk_css_matcher_node_has_region (const GtkCssMatcher *matcher, const char *region, GtkRegionFlags flags) { GtkRegionFlags region_flags; GQuark region_quark; region_quark = g_quark_try_string (region); if (!region_quark) return FALSE; if (!gtk_css_node_has_region (matcher->node.node, region_quark, &region_flags)) return FALSE; if ((flags & region_flags) != flags) return FALSE; return TRUE; } static gboolean gtk_css_matcher_node_nth_child (GtkCssNode *node, int a, int b) { while (b-- > 0) { if (node == NULL) return FALSE; node = get_previous_visible_sibling (node); } if (a == 0) return node == NULL; else if (a == 1) return TRUE; b = 0; while (node) { b++; node = get_previous_visible_sibling (node); } return b % a == 0; } static gboolean gtk_css_matcher_node_nth_last_child (GtkCssNode *node, int a, int b) { while (b-- > 0) { if (node == NULL) return FALSE; node = get_next_visible_sibling (node); } if (a == 0) return node == NULL; else if (a == 1) return TRUE; b = 0; while (node) { b++; node = get_next_visible_sibling (node); } return b % a == 0; } static gboolean gtk_css_matcher_node_has_position (const GtkCssMatcher *matcher, gboolean forward, int a, int b) { if (forward) return gtk_css_matcher_node_nth_child (matcher->node.node, a, b); else return gtk_css_matcher_node_nth_last_child (matcher->node.node, a, b); } static const GtkCssMatcherClass GTK_CSS_MATCHER_NODE = { gtk_css_matcher_node_get_parent, gtk_css_matcher_node_get_previous, gtk_css_matcher_node_get_state, gtk_css_matcher_node_has_type, gtk_css_matcher_node_has_class, gtk_css_matcher_node_has_id, gtk_css_matcher_node_has_regions, gtk_css_matcher_node_has_region, gtk_css_matcher_node_has_position, FALSE }; void _gtk_css_matcher_node_init (GtkCssMatcher *matcher, GtkCssNode *node) { matcher->node.klass = &GTK_CSS_MATCHER_NODE; matcher->node.node = node; } /* GTK_CSS_MATCHER_WIDGET_ANY */ static gboolean gtk_css_matcher_any_get_parent (GtkCssMatcher *matcher, const GtkCssMatcher *child) { _gtk_css_matcher_any_init (matcher); return TRUE; } static gboolean gtk_css_matcher_any_get_previous (GtkCssMatcher *matcher, const GtkCssMatcher *next) { _gtk_css_matcher_any_init (matcher); return TRUE; } static GtkStateFlags gtk_css_matcher_any_get_state (const GtkCssMatcher *matcher) { /* XXX: This gets tricky when we implement :not() */ return GTK_STATE_FLAG_ACTIVE | GTK_STATE_FLAG_PRELIGHT | GTK_STATE_FLAG_SELECTED | GTK_STATE_FLAG_INSENSITIVE | GTK_STATE_FLAG_INCONSISTENT | GTK_STATE_FLAG_FOCUSED | GTK_STATE_FLAG_BACKDROP | GTK_STATE_FLAG_LINK | GTK_STATE_FLAG_VISITED; } static gboolean gtk_css_matcher_any_has_type (const GtkCssMatcher *matcher, GType type) { return TRUE; } static gboolean gtk_css_matcher_any_has_class (const GtkCssMatcher *matcher, GQuark class_name) { return TRUE; } static gboolean gtk_css_matcher_any_has_id (const GtkCssMatcher *matcher, const char *id) { return TRUE; } static gboolean gtk_css_matcher_any_has_regions (const GtkCssMatcher *matcher) { return TRUE; } static gboolean gtk_css_matcher_any_has_region (const GtkCssMatcher *matcher, const char *region, GtkRegionFlags flags) { return TRUE; } static gboolean gtk_css_matcher_any_has_position (const GtkCssMatcher *matcher, gboolean forward, int a, int b) { return TRUE; } static const GtkCssMatcherClass GTK_CSS_MATCHER_ANY = { gtk_css_matcher_any_get_parent, gtk_css_matcher_any_get_previous, gtk_css_matcher_any_get_state, gtk_css_matcher_any_has_type, gtk_css_matcher_any_has_class, gtk_css_matcher_any_has_id, gtk_css_matcher_any_has_regions, gtk_css_matcher_any_has_region, gtk_css_matcher_any_has_position, TRUE }; void _gtk_css_matcher_any_init (GtkCssMatcher *matcher) { matcher->klass = &GTK_CSS_MATCHER_ANY; } /* GTK_CSS_MATCHER_WIDGET_SUPERSET */ static gboolean gtk_css_matcher_superset_get_parent (GtkCssMatcher *matcher, const GtkCssMatcher *child) { _gtk_css_matcher_any_init (matcher); return TRUE; } static gboolean gtk_css_matcher_superset_get_previous (GtkCssMatcher *matcher, const GtkCssMatcher *next) { _gtk_css_matcher_any_init (matcher); return TRUE; } static GtkStateFlags gtk_css_matcher_superset_get_state (const GtkCssMatcher *matcher) { /* XXX: This gets tricky when we implement :not() */ if (matcher->superset.relevant & GTK_CSS_CHANGE_STATE) return _gtk_css_matcher_get_state (matcher->superset.subset); else return GTK_STATE_FLAG_ACTIVE | GTK_STATE_FLAG_PRELIGHT | GTK_STATE_FLAG_SELECTED | GTK_STATE_FLAG_INSENSITIVE | GTK_STATE_FLAG_INCONSISTENT | GTK_STATE_FLAG_FOCUSED | GTK_STATE_FLAG_BACKDROP | GTK_STATE_FLAG_LINK | GTK_STATE_FLAG_VISITED; } static gboolean gtk_css_matcher_superset_has_type (const GtkCssMatcher *matcher, GType type) { if (matcher->superset.relevant & GTK_CSS_CHANGE_NAME) return _gtk_css_matcher_has_type (matcher->superset.subset, type); else return TRUE; } static gboolean gtk_css_matcher_superset_has_class (const GtkCssMatcher *matcher, GQuark class_name) { if (matcher->superset.relevant & GTK_CSS_CHANGE_CLASS) return _gtk_css_matcher_has_class (matcher->superset.subset, class_name); else return TRUE; } static gboolean gtk_css_matcher_superset_has_id (const GtkCssMatcher *matcher, const char *id) { if (matcher->superset.relevant & GTK_CSS_CHANGE_NAME) return _gtk_css_matcher_has_id (matcher->superset.subset, id); else return TRUE; } static gboolean gtk_css_matcher_superset_has_regions (const GtkCssMatcher *matcher) { if (matcher->superset.relevant & GTK_CSS_CHANGE_NAME) return _gtk_css_matcher_has_regions (matcher->superset.subset); else return TRUE; } static gboolean gtk_css_matcher_superset_has_region (const GtkCssMatcher *matcher, const char *region, GtkRegionFlags flags) { if (matcher->superset.relevant & GTK_CSS_CHANGE_NAME) { if (matcher->superset.relevant & GTK_CSS_CHANGE_POSITION) return _gtk_css_matcher_has_region (matcher->superset.subset, region, flags); else return _gtk_css_matcher_has_region (matcher->superset.subset, region, 0); } else return TRUE; } static gboolean gtk_css_matcher_superset_has_position (const GtkCssMatcher *matcher, gboolean forward, int a, int b) { if (matcher->superset.relevant & GTK_CSS_CHANGE_POSITION) return _gtk_css_matcher_has_position (matcher->superset.subset, forward, a, b); else return TRUE; } static const GtkCssMatcherClass GTK_CSS_MATCHER_SUPERSET = { gtk_css_matcher_superset_get_parent, gtk_css_matcher_superset_get_previous, gtk_css_matcher_superset_get_state, gtk_css_matcher_superset_has_type, gtk_css_matcher_superset_has_class, gtk_css_matcher_superset_has_id, gtk_css_matcher_superset_has_regions, gtk_css_matcher_superset_has_region, gtk_css_matcher_superset_has_position, FALSE }; void _gtk_css_matcher_superset_init (GtkCssMatcher *matcher, const GtkCssMatcher *subset, GtkCssChange relevant) { g_return_if_fail (subset != NULL); g_return_if_fail ((relevant & ~(GTK_CSS_CHANGE_CLASS | GTK_CSS_CHANGE_NAME | GTK_CSS_CHANGE_POSITION | GTK_CSS_CHANGE_STATE)) == 0); matcher->superset.klass = &GTK_CSS_MATCHER_SUPERSET; matcher->superset.subset = subset; matcher->superset.relevant = relevant; }
lgpl-2.1
kevleyski/DirectFB-1
lib/voodoo/connection_packet.cpp
2
14271
/* (c) Copyright 2012-2013 DirectFB integrated media GmbH (c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org) (c) Copyright 2000-2004 Convergence (integrated media) GmbH All rights reserved. Written by Denis Oliver Kropp <dok@directfb.org>, Andreas Shimokawa <andi@directfb.org>, Marek Pikarski <mass@directfb.org>, Sven Neumann <neo@directfb.org>, Ville Syrjälä <syrjala@sci.fi> and Claudio Ciccani <klan@users.sf.net>. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //#define DIRECT_ENABLE_DEBUG #include <config.h> extern "C" { #include <direct/debug.h> #include <direct/fastlz.h> #include <direct/list.h> #include <direct/mem.h> #include <direct/memcpy.h> #include <direct/messages.h> #include <direct/thread.h> #include <direct/util.h> #include <voodoo/conf.h> #include <voodoo/link.h> } #include <voodoo/connection_packet.h> #include <voodoo/manager.h> #include <voodoo/packet.h> #include <vector> //namespace Voodoo { D_DEBUG_DOMAIN( Voodoo_Connection, "Voodoo/Connection", "Voodoo Connection" ); D_DEBUG_DOMAIN( Voodoo_Input, "Voodoo/Input", "Voodoo Input" ); D_DEBUG_DOMAIN( Voodoo_Output, "Voodoo/Output", "Voodoo Output" ); /**********************************************************************************************************************/ VoodooConnectionPacket::VoodooConnectionPacket( VoodooLink *link ) : VoodooConnectionLink( link ), stop( false ), closed( false ) { D_DEBUG_AT( Voodoo_Connection, "VoodooConnectionPacket::%s( %p )\n", __func__, this ); } VoodooConnectionPacket::~VoodooConnectionPacket() { D_DEBUG_AT( Voodoo_Connection, "VoodooConnectionPacket::%s( %p )\n", __func__, this ); D_MAGIC_ASSERT( this, VoodooConnection ); } void VoodooConnectionPacket::Start( VoodooManager *manager ) { D_DEBUG_AT( Voodoo_Connection, "VoodooConnectionPacket::%s( %p )\n", __func__, this ); D_MAGIC_ASSERT( this, VoodooConnection ); D_ASSERT( manager != NULL ); D_ASSERT( this->manager == NULL ); this->manager = manager; io = direct_thread_create( DTT_DEFAULT, io_loop_main, this, "Voodoo IO" ); } void VoodooConnectionPacket::Stop() { D_DEBUG_AT( Voodoo_Connection, "VoodooConnectionPacket::%s( %p )\n", __func__, this ); D_MAGIC_ASSERT( this, VoodooConnection ); direct_mutex_lock( &output.lock ); while (!closed && output.packets) { D_DEBUG_AT( Voodoo_Connection, " -> waiting for output packets to be sent...\n" ); direct_waitqueue_wait( &output.wait, &output.lock ); } direct_mutex_unlock( &output.lock ); stop = true; link->WakeUp( link ); /* Wait for manager threads exiting. */ direct_thread_join( io ); direct_thread_destroy( io ); VoodooConnectionLink::Stop(); } /**********************************************************************************************************************/ void * VoodooConnectionPacket::io_loop() { D_DEBUG_AT( Voodoo_Connection, "VoodooConnectionPacket::%s( %p )\n", __func__, this ); while (!stop) { D_MAGIC_ASSERT( this, VoodooConnection ); if (input.start == input.max) { input.start = 0; input.end = 0; input.last = 0; input.max = VOODOO_CONNECTION_LINK_INPUT_BUF_MAX; } if (!stop) { DirectResult ret; VoodooChunk chunks[2]; VoodooChunk *chunk_read = NULL; VoodooChunk *chunk_write = NULL; size_t last = input.last; VoodooPacket *packet = NULL; std::vector<VoodooChunk> chunks_write; std::vector<VoodooChunk> chunks_read; if (!output.sending) { direct_mutex_lock( &output.lock ); if (output.packets) { VoodooPacket *packet = (VoodooPacket*) output.packets; D_ASSERT( packet->sending ); if (voodoo_config->compression_min && packet->size() >= voodoo_config->compression_min) { output.sending = VoodooPacket::Compressed( packet ); if (output.sending->flags() & VPHF_COMPRESSED) { D_DEBUG_AT( Voodoo_Output, " -> Compressed %u to %u bytes... (packet %p)\n", output.sending->uncompressed(), output.sending->size(), packet ); output.sending->sending = true; packet->sending = false; direct_list_remove( &output.packets, &packet->link ); direct_waitqueue_broadcast( &output.wait ); } } else output.sending = packet; output.sent = 0; } direct_mutex_unlock( &output.lock ); } if (output.sending) { packet = output.sending; D_ASSERT( packet->sending ); chunk_write = &chunks[1]; chunk_write->ptr = (char*) packet->data_header() + output.sent; chunk_write->length = VOODOO_MSG_ALIGN(packet->size() + sizeof(VoodooPacketHeader)) - output.sent; chunk_write->done = 0; chunks_write.push_back( chunks[1] ); chunk_write = chunks_write.data(); } if (input.end < input.max && manager->DispatchReady()) { chunk_read = &chunks[0]; chunk_read->ptr = input.buffer + input.end; chunk_read->length = input.max - input.end; chunk_read->done = 0; chunks_read.push_back( chunks[0] ); chunk_read = chunks_read.data(); } ret = link->SendReceive( link, chunks_write.data(), chunks_write.size(), chunks_read.data(), chunks_read.size() ); switch (ret) { case DR_OK: if (chunk_write && chunk_write->done) { D_DEBUG_AT( Voodoo_Output, " -> Sent "_ZD"/"_ZD" bytes... (packet %p)\n", chunk_write->done, chunk_write->length, packet ); output.sent += chunk_write->done; if (output.sent == VOODOO_MSG_ALIGN(packet->size() + sizeof(VoodooPacketHeader))) { output.sending = NULL; if (packet->flags() & VPHF_COMPRESSED) { packet->sending = false; D_FREE( packet ); } else { direct_mutex_lock( &output.lock ); packet->sending = false; direct_list_remove( &output.packets, &packet->link ); direct_mutex_unlock( &output.lock ); direct_waitqueue_broadcast( &output.wait ); } } } break; case DR_TIMEOUT: //D_DEBUG_AT( Voodoo_Connection, " -> timeout\n" ); break; case DR_INTERRUPTED: D_DEBUG_AT( Voodoo_Connection, " -> interrupted\n" ); break; default: if (ret == DR_IO) D_DEBUG_AT( Voodoo_Connection, " -> Connection closed!\n" ); else D_DERROR( ret, "Voodoo/ConnectionPacket: Could not receive data!\n" ); goto disconnect; } if (chunk_read && chunk_read->done) { D_DEBUG_AT( Voodoo_Input, " -> Received "_ZD" bytes...\n", chunk_read->done ); input.end += (size_t) chunk_read->done; do { VoodooPacketHeader *header; size_t aligned; D_DEBUG_AT( Voodoo_Input, " -> last = %zu\n", last ); /* Get the packet header. */ header = (VoodooPacketHeader *)(input.buffer + last); D_DEBUG_AT( Voodoo_Input, " -> header = %p\n", header ); D_DEBUG_AT( Voodoo_Input, " -> header->size = %u\n", header->size ); aligned = VOODOO_MSG_ALIGN( header->size ); D_DEBUG_AT( Voodoo_Input, " -> Next packet has %u ("_ZU") -> %u bytes (flags 0x%04x)...\n", header->size, aligned, header->uncompressed, header->flags ); if (input.end - last >= sizeof(VoodooPacketHeader)) { if (header->uncompressed < (int) sizeof(VoodooMessageHeader)) { D_DERROR( ret, "Voodoo/ConnectionPacket: Data error, uncompressed %d < min %zu!\n", header->uncompressed, sizeof(VoodooPacketHeader) ); goto disconnect; } if (header->uncompressed > VOODOO_PACKET_MAX) { D_DERROR( ret, "Voodoo/ConnectionPacket: Data error, uncompressed %d > max %d!\n", header->uncompressed, VOODOO_PACKET_MAX ); goto disconnect; } } if (sizeof(VoodooPacketHeader) + aligned > input.end - last) { D_DEBUG_AT( Voodoo_Input, " -> ...fetching tail of message.\n" ); /* Extend the buffer if the message doesn't fit into the default boundary. */ if (sizeof(VoodooPacketHeader) + aligned > input.max - last) input.max = last + sizeof(VoodooPacketHeader) + aligned; break; } last += sizeof(VoodooPacketHeader) + aligned; } while (last < input.end); if (last != input.last) { input.last = last; D_DEBUG_AT( Voodoo_Input, " { START "_ZD", LAST "_ZD", END "_ZD", MAX "_ZD" }\n", input.start, input.last, input.end, input.max ); while (input.start < input.last) { /* Get the packet header. */ VoodooPacketHeader *header = (VoodooPacketHeader *)(input.buffer + input.start); VoodooPacket *p; D_ASSERT( header->uncompressed <= VOODOO_PACKET_MAX ); if (header->flags & VPHF_COMPRESSED) { size_t uncompressed = direct_fastlz_decompress( header + 1, header->size, tmp, header->uncompressed ); D_DEBUG_AT( Voodoo_Input, " -> Uncompressed "_ZU" bytes (%u compressed)\n", uncompressed, header->size ); (void) uncompressed; D_ASSERT( uncompressed == header->uncompressed ); // FIXME: don't copy, but read into packet directly, maybe call manager->GetPacket() at the top of this loop p = VoodooPacket::Copy( header->uncompressed, VPHF_NONE, header->uncompressed, tmp ); } else { // FIXME: don't copy, but read into packet directly, maybe call manager->GetPacket() at the top of this loop p = VoodooPacket::Copy( header->uncompressed, VPHF_NONE, header->uncompressed, header + 1 ); } manager->DispatchPacket( p ); input.start += VOODOO_MSG_ALIGN(header->size) + sizeof(VoodooPacketHeader); } } } } } return NULL; disconnect: closed = true; manager->handle_disconnect(); return NULL; } /**********************************************************************************************************************/ void * VoodooConnectionPacket::io_loop_main( DirectThread *thread, void *arg ) { D_DEBUG_AT( Voodoo_Connection, "VoodooConnectionPacket::%s( %p, thread %p )\n", __func__, arg, thread ); VoodooConnectionPacket *connection = (VoodooConnectionPacket*) arg; return connection->io_loop(); }
lgpl-2.1
genesi/gstreamer
plugins/elements/gstmultiqueue.c
2
53111
/* GStreamer * Copyright (C) 2006 Edward Hervey <edward@fluendo.com> * Copyright (C) 2007 Jan Schmidt <jan@fluendo.com> * Copyright (C) 2007 Wim Taymans <wim@fluendo.com> * * gstmultiqueue.c: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * SECTION:element-multiqueue * @see_also: #GstQueue * * <refsect2> * <para> * Multiqueue is similar to a normal #GstQueue with the following additional * features: * <orderedlist> * <listitem> * <itemizedlist><title>Multiple streamhandling</title> * <listitem><para> * The element handles queueing data on more than one stream at once. To * achieve such a feature it has request sink pads (sink&percnt;d) and * 'sometimes' src pads (src&percnt;d). * </para><para> * When requesting a given sinkpad with gst_element_get_request_pad(), * the associated srcpad for that stream will be created. * Example: requesting sink1 will generate src1. * </para></listitem> * </itemizedlist> * </listitem> * <listitem> * <itemizedlist><title>Non-starvation on multiple streams</title> * <listitem><para> * If more than one stream is used with the element, the streams' queues * will be dynamically grown (up to a limit), in order to ensure that no * stream is risking data starvation. This guarantees that at any given * time there are at least N bytes queued and available for each individual * stream. * </para><para> * If an EOS event comes through a srcpad, the associated queue will be * considered as 'not-empty' in the queue-size-growing algorithm. * </para></listitem> * </itemizedlist> * </listitem> * <listitem> * <itemizedlist><title>Non-linked srcpads graceful handling</title> * <listitem><para> * In order to better support dynamic switching between streams, the multiqueue * (unlike the current GStreamer queue) continues to push buffers on non-linked * pads rather than shutting down. * </para><para> * In addition, to prevent a non-linked stream from very quickly consuming all * available buffers and thus 'racing ahead' of the other streams, the element * must ensure that buffers and inlined events for a non-linked stream are pushed * in the same order as they were received, relative to the other streams * controlled by the element. This means that a buffer cannot be pushed to a * non-linked pad any sooner than buffers in any other stream which were received * before it. * </para></listitem> * </itemizedlist> * </listitem> * </orderedlist> * </para> * <para> * Data is queued until one of the limits specified by the * #GstMultiQueue:max-size-buffers, #GstMultiQueue:max-size-bytes and/or * #GstMultiQueue:max-size-time properties has been reached. Any attempt to push * more buffers into the queue will block the pushing thread until more space * becomes available. #GstMultiQueue:extra-size-buffers, * </para> * <para> * #GstMultiQueue:extra-size-bytes and #GstMultiQueue:extra-size-time are * currently unused. * </para> * <para> * The default queue size limits are 5 buffers, 10MB of data, or * two second worth of data, whichever is reached first. Note that the number * of buffers will dynamically grow depending on the fill level of * other queues. * </para> * <para> * The #GstMultiQueue::underrun signal is emitted when all of the queues * are empty. The #GstMultiQueue::overrun signal is emitted when one of the * queues is filled. * Both signals are emitted from the context of the streaming thread. * </para> * </refsect2> * * Last reviewed on 2008-01-25 (0.10.17) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <gst/gst.h> #include "gstmultiqueue.h" /** * GstSingleQueue: * @sinkpad: associated sink #GstPad * @srcpad: associated source #GstPad * * Structure containing all information and properties about * a single queue. */ typedef struct _GstSingleQueue GstSingleQueue; struct _GstSingleQueue { /* unique identifier of the queue */ guint id; GstMultiQueue *mqueue; GstPad *sinkpad; GstPad *srcpad; /* flowreturn of previous srcpad push */ GstFlowReturn srcresult; /* segments */ GstSegment sink_segment; GstSegment src_segment; /* position of src/sink */ GstClockTime sinktime, srctime; /* TRUE if either position needs to be recalculated */ gboolean sink_tainted, src_tainted; /* queue of data */ GstDataQueue *queue; GstDataQueueSize max_size, extra_size; GstClockTime cur_time; gboolean is_eos; /* Protected by global lock */ guint32 nextid; /* ID of the next object waiting to be pushed */ guint32 oldid; /* ID of the last object pushed (last in a series) */ GCond *turn; /* SingleQueue turn waiting conditional */ }; /* Extension of GstDataQueueItem structure for our usage */ typedef struct _GstMultiQueueItem GstMultiQueueItem; struct _GstMultiQueueItem { GstMiniObject *object; guint size; guint64 duration; gboolean visible; GDestroyNotify destroy; guint32 posid; }; static GstSingleQueue *gst_single_queue_new (GstMultiQueue * mqueue); static void gst_single_queue_free (GstSingleQueue * squeue); static void wake_up_next_non_linked (GstMultiQueue * mq); static void compute_high_id (GstMultiQueue * mq); static void single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq); static void single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq); static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink%d", GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS_ANY); static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src%d", GST_PAD_SRC, GST_PAD_SOMETIMES, GST_STATIC_CAPS_ANY); GST_DEBUG_CATEGORY_STATIC (multi_queue_debug); #define GST_CAT_DEFAULT (multi_queue_debug) /* Signals and args */ enum { SIGNAL_UNDERRUN, SIGNAL_OVERRUN, LAST_SIGNAL }; /* default limits, we try to keep up to 2 seconds of data and if there is not * time, up to 10 MB. The number of buffers is dynamically scaled to make sure * there is data in the queues. Normally, the byte and time limits are not hit * in theses conditions. */ #define DEFAULT_MAX_SIZE_BYTES 10 * 1024 * 1024 /* 10 MB */ #define DEFAULT_MAX_SIZE_BUFFERS 5 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND /* second limits. When we hit one of the above limits we are probably dealing * with a badly muxed file and we scale the limits to these emergency values. * This is currently not yet implemented. * Since we dynamically scale the queue buffer size up to the limits but avoid * going above the max-size-buffers when we can, we don't really need this * aditional extra size. */ #define DEFAULT_EXTRA_SIZE_BYTES 10 * 1024 * 1024 /* 10 MB */ #define DEFAULT_EXTRA_SIZE_BUFFERS 5 #define DEFAULT_EXTRA_SIZE_TIME 3 * GST_SECOND #define DEFAULT_USE_BUFFERING FALSE #define DEFAULT_LOW_PERCENT 10 #define DEFAULT_HIGH_PERCENT 99 enum { PROP_0, PROP_EXTRA_SIZE_BYTES, PROP_EXTRA_SIZE_BUFFERS, PROP_EXTRA_SIZE_TIME, PROP_MAX_SIZE_BYTES, PROP_MAX_SIZE_BUFFERS, PROP_MAX_SIZE_TIME, PROP_USE_BUFFERING, PROP_LOW_PERCENT, PROP_HIGH_PERCENT, PROP_LAST }; #define GST_MULTI_QUEUE_MUTEX_LOCK(q) G_STMT_START { \ g_mutex_lock (q->qlock); \ } G_STMT_END #define GST_MULTI_QUEUE_MUTEX_UNLOCK(q) G_STMT_START { \ g_mutex_unlock (q->qlock); \ } G_STMT_END static void gst_multi_queue_finalize (GObject * object); static void gst_multi_queue_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_multi_queue_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static GstPad *gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp, const gchar * name); static void gst_multi_queue_release_pad (GstElement * element, GstPad * pad); static void gst_multi_queue_loop (GstPad * pad); #define _do_init(bla) \ GST_DEBUG_CATEGORY_INIT (multi_queue_debug, "multiqueue", 0, "multiqueue element"); GST_BOILERPLATE_FULL (GstMultiQueue, gst_multi_queue, GstElement, GST_TYPE_ELEMENT, _do_init); static guint gst_multi_queue_signals[LAST_SIGNAL] = { 0 }; static void gst_multi_queue_base_init (gpointer g_class) { GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class); gst_element_class_set_details_simple (gstelement_class, "MultiQueue", "Generic", "Multiple data queue", "Edward Hervey <edward@fluendo.com>"); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&sinktemplate)); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&srctemplate)); } static void gst_multi_queue_class_init (GstMultiQueueClass * klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); gobject_class->set_property = gst_multi_queue_set_property; gobject_class->get_property = gst_multi_queue_get_property; /* SIGNALS */ /** * GstMultiQueue::underrun: * @multiqueue: the multqueue instance * * This signal is emitted from the streaming thread when there is * no data in any of the queues inside the multiqueue instance (underrun). * * This indicates either starvation or EOS from the upstream data sources. */ gst_multi_queue_signals[SIGNAL_UNDERRUN] = g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GstMultiQueueClass, underrun), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); /** * GstMultiQueue::overrun: * @multiqueue: the multiqueue instance * * Reports that one of the queues in the multiqueue is full (overrun). * A queue is full if the total amount of data inside it (num-buffers, time, * size) is higher than the boundary values which can be set through the * GObject properties. * * This can be used as an indicator of pre-roll. */ gst_multi_queue_signals[SIGNAL_OVERRUN] = g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (GstMultiQueueClass, overrun), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); /* PROPERTIES */ g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES, g_param_spec_uint ("max-size-bytes", "Max. size (kB)", "Max. amount of data in the queue (bytes, 0=disable)", 0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS, g_param_spec_uint ("max-size-buffers", "Max. size (buffers)", "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT, DEFAULT_MAX_SIZE_BUFFERS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME, g_param_spec_uint64 ("max-size-time", "Max. size (ns)", "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64, DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BYTES, g_param_spec_uint ("extra-size-bytes", "Extra Size (kB)", "Amount of data the queues can grow if one of them is empty (bytes, 0=disable)" " (NOT IMPLEMENTED)", 0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BYTES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_BUFFERS, g_param_spec_uint ("extra-size-buffers", "Extra Size (buffers)", "Amount of buffers the queues can grow if one of them is empty (0=disable)" " (NOT IMPLEMENTED)", 0, G_MAXUINT, DEFAULT_EXTRA_SIZE_BUFFERS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_EXTRA_SIZE_TIME, g_param_spec_uint64 ("extra-size-time", "Extra Size (ns)", "Amount of time the queues can grow if one of them is empty (in ns, 0=disable)" " (NOT IMPLEMENTED)", 0, G_MAXUINT64, DEFAULT_EXTRA_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstMultiQueue:use-buffering * * Enable the buffering option in multiqueue so that BUFFERING messages are * emited based on low-/high-percent thresholds. * * Since: 0.10.26 */ g_object_class_install_property (gobject_class, PROP_USE_BUFFERING, g_param_spec_boolean ("use-buffering", "Use buffering", "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds", DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstMultiQueue:low-percent * * Low threshold percent for buffering to start. * * Since: 0.10.26 */ g_object_class_install_property (gobject_class, PROP_LOW_PERCENT, g_param_spec_int ("low-percent", "Low percent", "Low threshold for buffering to start", 0, 100, DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstMultiQueue:high-percent * * High threshold percent for buffering to finish. * * Since: 0.10.26 */ g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT, g_param_spec_int ("high-percent", "High percent", "High threshold for buffering to finish", 0, 100, DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); gobject_class->finalize = gst_multi_queue_finalize; gstelement_class->request_new_pad = GST_DEBUG_FUNCPTR (gst_multi_queue_request_new_pad); gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_multi_queue_release_pad); } static void gst_multi_queue_init (GstMultiQueue * mqueue, GstMultiQueueClass * klass) { mqueue->nbqueues = 0; mqueue->queues = NULL; mqueue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES; mqueue->max_size.visible = DEFAULT_MAX_SIZE_BUFFERS; mqueue->max_size.time = DEFAULT_MAX_SIZE_TIME; mqueue->extra_size.bytes = DEFAULT_EXTRA_SIZE_BYTES; mqueue->extra_size.visible = DEFAULT_EXTRA_SIZE_BUFFERS; mqueue->extra_size.time = DEFAULT_EXTRA_SIZE_TIME; mqueue->use_buffering = DEFAULT_USE_BUFFERING; mqueue->low_percent = DEFAULT_LOW_PERCENT; mqueue->high_percent = DEFAULT_HIGH_PERCENT; mqueue->counter = 1; mqueue->highid = -1; mqueue->nextnotlinked = -1; mqueue->qlock = g_mutex_new (); } static void gst_multi_queue_finalize (GObject * object) { GstMultiQueue *mqueue = GST_MULTI_QUEUE (object); g_list_foreach (mqueue->queues, (GFunc) gst_single_queue_free, NULL); g_list_free (mqueue->queues); mqueue->queues = NULL; mqueue->queues_cookie++; /* free/unref instance data */ g_mutex_free (mqueue->qlock); G_OBJECT_CLASS (parent_class)->finalize (object); } #define SET_CHILD_PROPERTY(mq,format) G_STMT_START { \ GList * tmp = mq->queues; \ while (tmp) { \ GstSingleQueue *q = (GstSingleQueue*)tmp->data; \ q->max_size.format = mq->max_size.format; \ tmp = g_list_next(tmp); \ }; \ } G_STMT_END static void gst_multi_queue_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstMultiQueue *mq = GST_MULTI_QUEUE (object); switch (prop_id) { case PROP_MAX_SIZE_BYTES: GST_MULTI_QUEUE_MUTEX_LOCK (mq); mq->max_size.bytes = g_value_get_uint (value); SET_CHILD_PROPERTY (mq, bytes); GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); break; case PROP_MAX_SIZE_BUFFERS: GST_MULTI_QUEUE_MUTEX_LOCK (mq); mq->max_size.visible = g_value_get_uint (value); SET_CHILD_PROPERTY (mq, visible); GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); break; case PROP_MAX_SIZE_TIME: GST_MULTI_QUEUE_MUTEX_LOCK (mq); mq->max_size.time = g_value_get_uint64 (value); SET_CHILD_PROPERTY (mq, time); GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); break; case PROP_EXTRA_SIZE_BYTES: mq->extra_size.bytes = g_value_get_uint (value); break; case PROP_EXTRA_SIZE_BUFFERS: mq->extra_size.visible = g_value_get_uint (value); break; case PROP_EXTRA_SIZE_TIME: mq->extra_size.time = g_value_get_uint64 (value); break; case PROP_USE_BUFFERING: mq->use_buffering = g_value_get_boolean (value); break; case PROP_LOW_PERCENT: mq->low_percent = g_value_get_int (value); break; case PROP_HIGH_PERCENT: mq->high_percent = g_value_get_int (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_multi_queue_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstMultiQueue *mq = GST_MULTI_QUEUE (object); GST_MULTI_QUEUE_MUTEX_LOCK (mq); switch (prop_id) { case PROP_EXTRA_SIZE_BYTES: g_value_set_uint (value, mq->extra_size.bytes); break; case PROP_EXTRA_SIZE_BUFFERS: g_value_set_uint (value, mq->extra_size.visible); break; case PROP_EXTRA_SIZE_TIME: g_value_set_uint64 (value, mq->extra_size.time); break; case PROP_MAX_SIZE_BYTES: g_value_set_uint (value, mq->max_size.bytes); break; case PROP_MAX_SIZE_BUFFERS: g_value_set_uint (value, mq->max_size.visible); break; case PROP_MAX_SIZE_TIME: g_value_set_uint64 (value, mq->max_size.time); break; case PROP_USE_BUFFERING: g_value_set_boolean (value, mq->use_buffering); break; case PROP_LOW_PERCENT: g_value_set_int (value, mq->low_percent); break; case PROP_HIGH_PERCENT: g_value_set_int (value, mq->high_percent); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); } static GstIterator * gst_multi_queue_iterate_internal_links (GstPad * pad) { GstIterator *it = NULL; GstPad *opad; GstSingleQueue *squeue; GstMultiQueue *mq = GST_MULTI_QUEUE (gst_pad_get_parent (pad)); GST_MULTI_QUEUE_MUTEX_LOCK (mq); squeue = gst_pad_get_element_private (pad); if (!squeue) goto out; if (squeue->sinkpad == pad) opad = gst_object_ref (squeue->srcpad); else if (squeue->srcpad == pad) opad = gst_object_ref (squeue->sinkpad); else goto out; it = gst_iterator_new_single (GST_TYPE_PAD, opad, (GstCopyFunction) gst_object_ref, (GFreeFunc) gst_object_unref); gst_object_unref (opad); out: GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); gst_object_unref (mq); return it; } /* * GstElement methods */ static GstPad * gst_multi_queue_request_new_pad (GstElement * element, GstPadTemplate * temp, const gchar * name) { GstMultiQueue *mqueue = GST_MULTI_QUEUE (element); GstSingleQueue *squeue; GST_LOG_OBJECT (element, "name : %s", GST_STR_NULL (name)); /* Create a new single queue, add the sink and source pad and return the sink pad */ squeue = gst_single_queue_new (mqueue); GST_MULTI_QUEUE_MUTEX_LOCK (mqueue); mqueue->queues = g_list_append (mqueue->queues, squeue); mqueue->queues_cookie++; GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue); GST_DEBUG_OBJECT (mqueue, "Returning pad %s:%s", GST_DEBUG_PAD_NAME (squeue->sinkpad)); return squeue->sinkpad; } static void gst_multi_queue_release_pad (GstElement * element, GstPad * pad) { GstMultiQueue *mqueue = GST_MULTI_QUEUE (element); GstSingleQueue *sq = NULL; GList *tmp; GST_LOG_OBJECT (element, "pad %s:%s", GST_DEBUG_PAD_NAME (pad)); GST_MULTI_QUEUE_MUTEX_LOCK (mqueue); /* Find which single queue it belongs to, knowing that it should be a sinkpad */ for (tmp = mqueue->queues; tmp; tmp = g_list_next (tmp)) { sq = (GstSingleQueue *) tmp->data; if (sq->sinkpad == pad) break; } if (!tmp) { GST_WARNING_OBJECT (mqueue, "That pad doesn't belong to this element ???"); GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue); return; } /* FIXME: The removal of the singlequeue should probably not happen until it * finishes draining */ /* remove it from the list */ mqueue->queues = g_list_delete_link (mqueue->queues, tmp); mqueue->queues_cookie++; /* FIXME : recompute next-non-linked */ GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue); /* delete SingleQueue */ gst_data_queue_set_flushing (sq->queue, TRUE); gst_pad_set_active (sq->srcpad, FALSE); gst_pad_set_active (sq->sinkpad, FALSE); gst_pad_set_element_private (sq->srcpad, NULL); gst_pad_set_element_private (sq->sinkpad, NULL); gst_element_remove_pad (element, sq->srcpad); gst_element_remove_pad (element, sq->sinkpad); gst_single_queue_free (sq); } static gboolean gst_single_queue_flush (GstMultiQueue * mq, GstSingleQueue * sq, gboolean flush) { gboolean result; GST_DEBUG_OBJECT (mq, "flush %s queue %d", (flush ? "start" : "stop"), sq->id); if (flush) { sq->srcresult = GST_FLOW_WRONG_STATE; gst_data_queue_set_flushing (sq->queue, TRUE); /* wake up non-linked task */ GST_LOG_OBJECT (mq, "SingleQueue %d : waking up eventually waiting task", sq->id); GST_MULTI_QUEUE_MUTEX_LOCK (mq); g_cond_signal (sq->turn); GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); GST_LOG_OBJECT (mq, "SingleQueue %d : pausing task", sq->id); result = gst_pad_pause_task (sq->srcpad); sq->sink_tainted = sq->src_tainted = TRUE; } else { gst_data_queue_flush (sq->queue); gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME); gst_segment_init (&sq->src_segment, GST_FORMAT_TIME); /* All pads start off not-linked for a smooth kick-off */ sq->srcresult = GST_FLOW_OK; sq->cur_time = 0; sq->max_size.visible = mq->max_size.visible; sq->is_eos = FALSE; sq->nextid = 0; sq->oldid = 0; gst_data_queue_set_flushing (sq->queue, FALSE); GST_LOG_OBJECT (mq, "SingleQueue %d : starting task", sq->id); result = gst_pad_start_task (sq->srcpad, (GstTaskFunction) gst_multi_queue_loop, sq->srcpad); } return result; } static void update_buffering (GstMultiQueue * mq, GstSingleQueue * sq) { GstDataQueueSize size; gint percent, tmp; gboolean post = FALSE; /* nothing to dowhen we are not in buffering mode */ if (!mq->use_buffering) return; gst_data_queue_get_level (sq->queue, &size); GST_DEBUG_OBJECT (mq, "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT, sq->id, size.visible, sq->max_size.visible, size.bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time); /* get bytes and time percentages and take the max */ if (sq->is_eos) { percent = 100; } else { percent = 0; if (sq->max_size.time > 0) { tmp = (sq->cur_time * 100) / sq->max_size.time; percent = MAX (percent, tmp); } if (sq->max_size.bytes > 0) { tmp = (size.bytes * 100) / sq->max_size.bytes; percent = MAX (percent, tmp); } } if (mq->buffering) { post = TRUE; if (percent >= mq->high_percent) { mq->buffering = FALSE; } /* make sure it increases */ percent = MAX (mq->percent, percent); if (percent == mq->percent) /* don't post if nothing changed */ post = FALSE; else /* else keep last value we posted */ mq->percent = percent; } else { if (percent < mq->low_percent) { mq->buffering = TRUE; mq->percent = percent; post = TRUE; } } if (post) { GstMessage *message; /* scale to high percent so that it becomes the 100% mark */ percent = percent * 100 / mq->high_percent; /* clip */ if (percent > 100) percent = 100; GST_DEBUG_OBJECT (mq, "buffering %d percent", percent); message = gst_message_new_buffering (GST_OBJECT_CAST (mq), percent); gst_element_post_message (GST_ELEMENT_CAST (mq), message); } else { GST_DEBUG_OBJECT (mq, "filled %d percent", percent); } } /* calculate the diff between running time on the sink and src of the queue. * This is the total amount of time in the queue. * WITH LOCK TAKEN */ static void update_time_level (GstMultiQueue * mq, GstSingleQueue * sq) { gint64 sink_time, src_time; if (sq->sink_tainted) { sink_time = sq->sinktime = gst_segment_to_running_time (&sq->sink_segment, GST_FORMAT_TIME, sq->sink_segment.last_stop); if (G_UNLIKELY (sink_time != GST_CLOCK_TIME_NONE)) /* if we have a time, we become untainted and use the time */ sq->sink_tainted = FALSE; } else sink_time = sq->sinktime; if (sq->src_tainted) { src_time = sq->srctime = gst_segment_to_running_time (&sq->src_segment, GST_FORMAT_TIME, sq->src_segment.last_stop); /* if we have a time, we become untainted and use the time */ if (G_UNLIKELY (src_time != GST_CLOCK_TIME_NONE)) sq->src_tainted = FALSE; } else src_time = sq->srctime; GST_DEBUG_OBJECT (mq, "queue %d, sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT, sq->id, GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time)); /* This allows for streams with out of order timestamping - sometimes the * emerging timestamp is later than the arriving one(s) */ if (G_LIKELY (sink_time != -1 && src_time != -1 && sink_time > src_time)) sq->cur_time = sink_time - src_time; else sq->cur_time = 0; /* updating the time level can change the buffering state */ update_buffering (mq, sq); return; } /* take a NEWSEGMENT event and apply the values to segment, updating the time * level of queue. */ static void apply_segment (GstMultiQueue * mq, GstSingleQueue * sq, GstEvent * event, GstSegment * segment) { gboolean update; GstFormat format; gdouble rate, arate; gint64 start, stop, time; gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format, &start, &stop, &time); /* now configure the values, we use these to track timestamps on the * sinkpad. */ if (format != GST_FORMAT_TIME) { /* non-time format, pretent the current time segment is closed with a * 0 start and unknown stop time. */ update = FALSE; format = GST_FORMAT_TIME; start = 0; stop = -1; time = 0; } GST_MULTI_QUEUE_MUTEX_LOCK (mq); gst_segment_set_newsegment_full (segment, update, rate, arate, format, start, stop, time); if (segment == &sq->sink_segment) sq->sink_tainted = TRUE; else sq->src_tainted = TRUE; GST_DEBUG_OBJECT (mq, "queue %d, configured NEWSEGMENT %" GST_SEGMENT_FORMAT, sq->id, segment); /* segment can update the time level of the queue */ update_time_level (mq, sq); GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); } /* take a buffer and update segment, updating the time level of the queue. */ static void apply_buffer (GstMultiQueue * mq, GstSingleQueue * sq, GstClockTime timestamp, GstClockTime duration, GstSegment * segment) { GST_MULTI_QUEUE_MUTEX_LOCK (mq); /* if no timestamp is set, assume it's continuous with the previous * time */ if (timestamp == GST_CLOCK_TIME_NONE) timestamp = segment->last_stop; /* add duration */ if (duration != GST_CLOCK_TIME_NONE) timestamp += duration; GST_DEBUG_OBJECT (mq, "queue %d, last_stop updated to %" GST_TIME_FORMAT, sq->id, GST_TIME_ARGS (timestamp)); gst_segment_set_last_stop (segment, GST_FORMAT_TIME, timestamp); if (segment == &sq->sink_segment) sq->sink_tainted = TRUE; else sq->src_tainted = TRUE; /* calc diff with other end */ update_time_level (mq, sq); GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); } static GstFlowReturn gst_single_queue_push_one (GstMultiQueue * mq, GstSingleQueue * sq, GstMiniObject * object) { GstFlowReturn result = GST_FLOW_OK; if (GST_IS_BUFFER (object)) { GstBuffer *buffer; GstClockTime timestamp, duration; GstCaps *caps; buffer = GST_BUFFER_CAST (object); timestamp = GST_BUFFER_TIMESTAMP (buffer); duration = GST_BUFFER_DURATION (buffer); caps = GST_BUFFER_CAPS (buffer); apply_buffer (mq, sq, timestamp, duration, &sq->src_segment); /* Applying the buffer may have made the queue non-full again, unblock it if needed */ gst_data_queue_limits_changed (sq->queue); GST_DEBUG_OBJECT (mq, "SingleQueue %d : Pushing buffer %p with ts %" GST_TIME_FORMAT, sq->id, buffer, GST_TIME_ARGS (timestamp)); /* Set caps on pad before pushing, this avoids core calling the acceptcaps * function on the srcpad, which will call acceptcaps upstream, which might * not accept these caps (anymore). */ if (caps && caps != GST_PAD_CAPS (sq->srcpad)) gst_pad_set_caps (sq->srcpad, caps); result = gst_pad_push (sq->srcpad, buffer); } else if (GST_IS_EVENT (object)) { GstEvent *event; event = GST_EVENT_CAST (object); switch (GST_EVENT_TYPE (event)) { case GST_EVENT_EOS: result = GST_FLOW_UNEXPECTED; break; case GST_EVENT_NEWSEGMENT: apply_segment (mq, sq, event, &sq->src_segment); /* Applying the segment may have made the queue non-full again, unblock it if needed */ gst_data_queue_limits_changed (sq->queue); break; default: break; } GST_DEBUG_OBJECT (mq, "SingleQueue %d : Pushing event %p of type %s", sq->id, event, GST_EVENT_TYPE_NAME (event)); gst_pad_push_event (sq->srcpad, event); } else { g_warning ("Unexpected object in singlequeue %d (refcounting problem?)", sq->id); } return result; /* ERRORS */ } static GstMiniObject * gst_multi_queue_item_steal_object (GstMultiQueueItem * item) { GstMiniObject *res; res = item->object; item->object = NULL; return res; } static void gst_multi_queue_item_destroy (GstMultiQueueItem * item) { if (item->object) gst_mini_object_unref (item->object); g_slice_free (GstMultiQueueItem, item); } /* takes ownership of passed mini object! */ static GstMultiQueueItem * gst_multi_queue_buffer_item_new (GstMiniObject * object, guint32 curid) { GstMultiQueueItem *item; item = g_slice_new (GstMultiQueueItem); item->object = object; item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy; item->posid = curid; item->size = GST_BUFFER_SIZE (object); item->duration = GST_BUFFER_DURATION (object); if (item->duration == GST_CLOCK_TIME_NONE) item->duration = 0; item->visible = TRUE; return item; } static GstMultiQueueItem * gst_multi_queue_event_item_new (GstMiniObject * object, guint32 curid) { GstMultiQueueItem *item; item = g_slice_new (GstMultiQueueItem); item->object = object; item->destroy = (GDestroyNotify) gst_multi_queue_item_destroy; item->posid = curid; item->size = 0; item->duration = 0; item->visible = FALSE; return item; } /* Each main loop attempts to push buffers until the return value * is not-linked. not-linked pads are not allowed to push data beyond * any linked pads, so they don't 'rush ahead of the pack'. */ static void gst_multi_queue_loop (GstPad * pad) { GstSingleQueue *sq; GstMultiQueueItem *item; GstDataQueueItem *sitem; GstMultiQueue *mq; GstMiniObject *object; guint32 newid; guint32 oldid = G_MAXUINT32; GstFlowReturn result; sq = (GstSingleQueue *) gst_pad_get_element_private (pad); mq = sq->mqueue; do { GST_DEBUG_OBJECT (mq, "SingleQueue %d : trying to pop an object", sq->id); /* Get something from the queue, blocking until that happens, or we get * flushed */ if (!(gst_data_queue_pop (sq->queue, &sitem))) goto out_flushing; item = (GstMultiQueueItem *) sitem; newid = item->posid; /* steal the object and destroy the item */ object = gst_multi_queue_item_steal_object (item); gst_multi_queue_item_destroy (item); GST_LOG_OBJECT (mq, "SingleQueue %d : newid:%d , oldid:%d", sq->id, newid, oldid); /* If we're not-linked, we do some extra work because we might need to * wait before pushing. If we're linked but there's a gap in the IDs, * or it's the first loop, or we just passed the previous highid, * we might need to wake some sleeping pad up, so there's extra work * there too */ if (sq->srcresult == GST_FLOW_NOT_LINKED || (oldid == G_MAXUINT32) || (newid != (oldid + 1)) || oldid > mq->highid) { GST_LOG_OBJECT (mq, "CHECKING sq->srcresult: %s", gst_flow_get_name (sq->srcresult)); GST_MULTI_QUEUE_MUTEX_LOCK (mq); /* Update the nextid so other threads know when to wake us up */ sq->nextid = newid; /* Update the oldid (the last ID we output) for highid tracking */ if (oldid != G_MAXUINT32) sq->oldid = oldid; if (sq->srcresult == GST_FLOW_NOT_LINKED) { /* Go to sleep until it's time to push this buffer */ /* Recompute the highid */ compute_high_id (mq); while (newid > mq->highid && sq->srcresult == GST_FLOW_NOT_LINKED) { GST_DEBUG_OBJECT (mq, "queue %d sleeping for not-linked wakeup with " "newid %u and highid %u", sq->id, newid, mq->highid); /* Wake up all non-linked pads before we sleep */ wake_up_next_non_linked (mq); mq->numwaiting++; g_cond_wait (sq->turn, mq->qlock); mq->numwaiting--; GST_DEBUG_OBJECT (mq, "queue %d woken from sleeping for not-linked " "wakeup with newid %u and highid %u", sq->id, newid, mq->highid); } /* Re-compute the high_id in case someone else pushed */ compute_high_id (mq); } else { compute_high_id (mq); /* Wake up all non-linked pads */ wake_up_next_non_linked (mq); } /* We're done waiting, we can clear the nextid */ sq->nextid = 0; GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); } GST_LOG_OBJECT (mq, "BEFORE PUSHING sq->srcresult: %s", gst_flow_get_name (sq->srcresult)); /* Try to push out the new object */ result = gst_single_queue_push_one (mq, sq, object); sq->srcresult = result; if (result != GST_FLOW_OK && result != GST_FLOW_NOT_LINKED && result != GST_FLOW_UNEXPECTED) goto out_flushing; GST_LOG_OBJECT (mq, "AFTER PUSHING sq->srcresult: %s", gst_flow_get_name (sq->srcresult)); oldid = newid; } while (TRUE); out_flushing: { /* Need to make sure wake up any sleeping pads when we exit */ GST_MULTI_QUEUE_MUTEX_LOCK (mq); compute_high_id (mq); wake_up_next_non_linked (mq); GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); /* upstream needs to see fatal result ASAP to shut things down, * but might be stuck in one of our other full queues; * so empty this one and trigger dynamic queue growth */ if (GST_FLOW_IS_FATAL (sq->srcresult)) { gst_data_queue_flush (sq->queue); single_queue_underrun_cb (sq->queue, sq); } gst_data_queue_set_flushing (sq->queue, TRUE); gst_pad_pause_task (sq->srcpad); GST_CAT_LOG_OBJECT (multi_queue_debug, mq, "SingleQueue[%d] task paused, reason:%s", sq->id, gst_flow_get_name (sq->srcresult)); return; } } /** * gst_multi_queue_chain: * * This is similar to GstQueue's chain function, except: * _ we don't have leak behavioures, * _ we push with a unique id (curid) */ static GstFlowReturn gst_multi_queue_chain (GstPad * pad, GstBuffer * buffer) { GstSingleQueue *sq; GstMultiQueue *mq; GstMultiQueueItem *item; guint32 curid; GstClockTime timestamp, duration; sq = gst_pad_get_element_private (pad); mq = sq->mqueue; /* Get a unique incrementing id */ curid = mq->counter++; GST_LOG_OBJECT (mq, "SingleQueue %d : about to enqueue buffer %p with id %d", sq->id, buffer, curid); item = gst_multi_queue_buffer_item_new (GST_MINI_OBJECT_CAST (buffer), curid); timestamp = GST_BUFFER_TIMESTAMP (buffer); duration = GST_BUFFER_DURATION (buffer); if (!(gst_data_queue_push (sq->queue, (GstDataQueueItem *) item))) goto flushing; /* update time level, we must do this after pushing the data in the queue so * that we never end up filling the queue first. */ apply_buffer (mq, sq, timestamp, duration, &sq->sink_segment); done: return sq->srcresult; /* ERRORS */ flushing: { GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s", sq->id, gst_flow_get_name (sq->srcresult)); gst_multi_queue_item_destroy (item); goto done; } } static gboolean gst_multi_queue_sink_activate_push (GstPad * pad, gboolean active) { GstSingleQueue *sq; sq = (GstSingleQueue *) gst_pad_get_element_private (pad); if (active) { /* All pads start off linked until they push one buffer */ sq->srcresult = GST_FLOW_OK; } else { sq->srcresult = GST_FLOW_WRONG_STATE; gst_data_queue_flush (sq->queue); } return TRUE; } static gboolean gst_multi_queue_sink_event (GstPad * pad, GstEvent * event) { GstSingleQueue *sq; GstMultiQueue *mq; guint32 curid; GstMultiQueueItem *item; gboolean res; GstEventType type; GstEvent *sref = NULL; sq = (GstSingleQueue *) gst_pad_get_element_private (pad); mq = (GstMultiQueue *) gst_pad_get_parent (pad); type = GST_EVENT_TYPE (event); switch (type) { case GST_EVENT_FLUSH_START: GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush start event", sq->id); res = gst_pad_push_event (sq->srcpad, event); gst_single_queue_flush (mq, sq, TRUE); goto done; case GST_EVENT_FLUSH_STOP: GST_DEBUG_OBJECT (mq, "SingleQueue %d : received flush stop event", sq->id); res = gst_pad_push_event (sq->srcpad, event); gst_single_queue_flush (mq, sq, FALSE); goto done; case GST_EVENT_NEWSEGMENT: /* take ref because the queue will take ownership and we need the event * afterwards to update the segment */ sref = gst_event_ref (event); break; default: if (!(GST_EVENT_IS_SERIALIZED (event))) { res = gst_pad_push_event (sq->srcpad, event); goto done; } break; } /* Get an unique incrementing id. protected with the STREAM_LOCK, unserialized * events already got pushed and don't end up in the queue. */ curid = mq->counter++; item = gst_multi_queue_event_item_new ((GstMiniObject *) event, curid); GST_DEBUG_OBJECT (mq, "SingleQueue %d : Enqueuing event %p of type %s with id %d", sq->id, event, GST_EVENT_TYPE_NAME (event), curid); if (!(res = gst_data_queue_push (sq->queue, (GstDataQueueItem *) item))) goto flushing; /* mark EOS when we received one, we must do that after putting the * buffer in the queue because EOS marks the buffer as filled. No need to take * a lock, the _check_full happens from this thread only, right before pushing * into dataqueue. */ switch (type) { case GST_EVENT_EOS: sq->is_eos = TRUE; /* EOS affects the buffering state */ update_buffering (mq, sq); single_queue_overrun_cb (sq->queue, sq); break; case GST_EVENT_NEWSEGMENT: apply_segment (mq, sq, sref, &sq->sink_segment); gst_event_unref (sref); break; default: break; } done: gst_object_unref (mq); return res; flushing: { GST_LOG_OBJECT (mq, "SingleQueue %d : exit because task paused, reason: %s", sq->id, gst_flow_get_name (sq->srcresult)); if (sref) gst_event_unref (sref); gst_multi_queue_item_destroy (item); goto done; } } static GstCaps * gst_multi_queue_getcaps (GstPad * pad) { GstSingleQueue *sq = gst_pad_get_element_private (pad); GstPad *otherpad; GstCaps *result; otherpad = (pad == sq->srcpad) ? sq->sinkpad : sq->srcpad; GST_LOG_OBJECT (otherpad, "Getting caps from the peer of this pad"); result = gst_pad_peer_get_caps (otherpad); if (result == NULL) result = gst_caps_new_any (); return result; } static gboolean gst_multi_queue_acceptcaps (GstPad * pad, GstCaps * caps) { GstSingleQueue *sq = gst_pad_get_element_private (pad); GstPad *otherpad; gboolean result; otherpad = (pad == sq->srcpad) ? sq->sinkpad : sq->srcpad; GST_LOG_OBJECT (otherpad, "Accept caps from the peer of this pad"); result = gst_pad_peer_accept_caps (otherpad, caps); return result; } static GstFlowReturn gst_multi_queue_bufferalloc (GstPad * pad, guint64 offset, guint size, GstCaps * caps, GstBuffer ** buf) { GstSingleQueue *sq = gst_pad_get_element_private (pad); return gst_pad_alloc_buffer (sq->srcpad, offset, size, caps, buf); } static gboolean gst_multi_queue_src_activate_push (GstPad * pad, gboolean active) { GstMultiQueue *mq; GstSingleQueue *sq; gboolean result = FALSE; sq = (GstSingleQueue *) gst_pad_get_element_private (pad); mq = sq->mqueue; GST_DEBUG_OBJECT (mq, "SingleQueue %d", sq->id); if (active) { result = gst_single_queue_flush (mq, sq, FALSE); } else { result = gst_single_queue_flush (mq, sq, TRUE); /* make sure streaming finishes */ result |= gst_pad_stop_task (pad); } return result; } static gboolean gst_multi_queue_src_event (GstPad * pad, GstEvent * event) { GstSingleQueue *sq = gst_pad_get_element_private (pad); return gst_pad_push_event (sq->sinkpad, event); } static gboolean gst_multi_queue_src_query (GstPad * pad, GstQuery * query) { GstSingleQueue *sq = gst_pad_get_element_private (pad); GstPad *peerpad; gboolean res; /* FIXME, Handle position offset depending on queue size */ /* default handling */ if (!(peerpad = gst_pad_get_peer (sq->sinkpad))) goto no_peer; res = gst_pad_query (peerpad, query); gst_object_unref (peerpad); return res; /* ERRORS */ no_peer: { GST_LOG_OBJECT (sq->sinkpad, "Couldn't send query because we have no peer"); return FALSE; } } /* * Next-non-linked functions */ /* WITH LOCK TAKEN */ static void wake_up_next_non_linked (GstMultiQueue * mq) { GList *tmp; /* maybe no-one is waiting */ if (mq->numwaiting < 1) return; /* Else figure out which singlequeue(s) need waking up */ for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) { GstSingleQueue *sq = (GstSingleQueue *) tmp->data; if (sq->srcresult == GST_FLOW_NOT_LINKED) { if (sq->nextid != 0 && sq->nextid <= mq->highid) { GST_LOG_OBJECT (mq, "Waking up singlequeue %d", sq->id); g_cond_signal (sq->turn); } } } } /* WITH LOCK TAKEN */ static void compute_high_id (GstMultiQueue * mq) { /* The high-id is either the highest id among the linked pads, or if all * pads are not-linked, it's the lowest not-linked pad */ GList *tmp; guint32 lowest = G_MAXUINT32; guint32 highid = G_MAXUINT32; for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) { GstSingleQueue *sq = (GstSingleQueue *) tmp->data; GST_LOG_OBJECT (mq, "inspecting sq:%d , nextid:%d, oldid:%d, srcresult:%s", sq->id, sq->nextid, sq->oldid, gst_flow_get_name (sq->srcresult)); if (sq->srcresult == GST_FLOW_NOT_LINKED) { /* No need to consider queues which are not waiting */ if (sq->nextid == 0) { GST_LOG_OBJECT (mq, "sq:%d is not waiting - ignoring", sq->id); continue; } if (sq->nextid < lowest) lowest = sq->nextid; } else if (sq->srcresult != GST_FLOW_UNEXPECTED) { /* If we don't have a global highid, or the global highid is lower than * this single queue's last outputted id, store the queue's one, * unless the singlequeue is at EOS (srcresult = UNEXPECTED) */ if ((highid == G_MAXUINT32) || (sq->oldid > highid)) highid = sq->oldid; } } if (highid == G_MAXUINT32 || lowest < highid) mq->highid = lowest; else mq->highid = highid; GST_LOG_OBJECT (mq, "Highid is now : %u, lowest non-linked %u", mq->highid, lowest); } #define IS_FILLED(q, format, value) (((q)->max_size.format) != 0 && \ ((q)->max_size.format) <= (value)) /* * GstSingleQueue functions */ static void single_queue_overrun_cb (GstDataQueue * dq, GstSingleQueue * sq) { GstMultiQueue *mq = sq->mqueue; GList *tmp; GstDataQueueSize size; gboolean filled = FALSE; gst_data_queue_get_level (sq->queue, &size); GST_LOG_OBJECT (mq, "Single Queue %d is full", sq->id); GST_MULTI_QUEUE_MUTEX_LOCK (mq); for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) { GstSingleQueue *oq = (GstSingleQueue *) tmp->data; GstDataQueueSize ssize; GST_LOG_OBJECT (mq, "Checking Queue %d", oq->id); if (gst_data_queue_is_empty (oq->queue)) { GST_LOG_OBJECT (mq, "Queue %d is empty", oq->id); if (IS_FILLED (sq, visible, size.visible)) { sq->max_size.visible = size.visible + 1; GST_DEBUG_OBJECT (mq, "Another queue is empty, bumping single queue %d max visible to %d", sq->id, sq->max_size.visible); } GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); goto beach; } /* check if we reached the hard time/bytes limits */ gst_data_queue_get_level (oq->queue, &ssize); GST_DEBUG_OBJECT (mq, "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT, oq->id, ssize.visible, oq->max_size.visible, ssize.bytes, oq->max_size.bytes, oq->cur_time, oq->max_size.time); /* if this queue is filled completely we must signal overrun. * FIXME, this seems wrong in many ways * - we're comparing the filled level of this queue against the * values of the other one * - we should only do this after we found no empty queues, ie, move * this check outside of the loop * - the debug statement talks about a different queue than the one * we are checking here. */ if (sq->is_eos || IS_FILLED (sq, bytes, ssize.bytes) || IS_FILLED (sq, time, sq->cur_time)) { GST_LOG_OBJECT (mq, "Queue %d is filled", oq->id); filled = TRUE; } } /* no queues were empty */ GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); /* Overrun is always forwarded, since this is blocking the upstream element */ if (filled) { GST_DEBUG_OBJECT (mq, "A queue is filled, signalling overrun"); g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_OVERRUN], 0); } beach: return; } static void single_queue_underrun_cb (GstDataQueue * dq, GstSingleQueue * sq) { gboolean empty = TRUE; GstMultiQueue *mq = sq->mqueue; GList *tmp; GST_LOG_OBJECT (mq, "Single Queue %d is empty, Checking other single queues", sq->id); GST_MULTI_QUEUE_MUTEX_LOCK (mq); for (tmp = mq->queues; tmp; tmp = g_list_next (tmp)) { GstSingleQueue *oq = (GstSingleQueue *) tmp->data; if (gst_data_queue_is_full (oq->queue)) { GstDataQueueSize size; gst_data_queue_get_level (oq->queue, &size); if (IS_FILLED (oq, visible, size.visible)) { oq->max_size.visible = size.visible + 1; GST_DEBUG_OBJECT (mq, "queue %d is filled, bumping its max visible to %d", oq->id, oq->max_size.visible); gst_data_queue_limits_changed (oq->queue); } } if (!gst_data_queue_is_empty (oq->queue)) empty = FALSE; } GST_MULTI_QUEUE_MUTEX_UNLOCK (mq); if (empty) { GST_DEBUG_OBJECT (mq, "All queues are empty, signalling it"); g_signal_emit (mq, gst_multi_queue_signals[SIGNAL_UNDERRUN], 0); } } static gboolean single_queue_check_full (GstDataQueue * dataq, guint visible, guint bytes, guint64 time, GstSingleQueue * sq) { gboolean res; GstMultiQueue *mq = sq->mqueue; GST_DEBUG_OBJECT (mq, "queue %d: visible %u/%u, bytes %u/%u, time %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT, sq->id, visible, sq->max_size.visible, bytes, sq->max_size.bytes, sq->cur_time, sq->max_size.time); /* we are always filled on EOS */ if (sq->is_eos) return TRUE; /* we never go past the max visible items unless we are in buffering mode */ if (!mq->use_buffering && IS_FILLED (sq, visible, visible)) return TRUE; /* check time or bytes */ res = IS_FILLED (sq, time, sq->cur_time) || IS_FILLED (sq, bytes, bytes); return res; } static void gst_single_queue_free (GstSingleQueue * sq) { /* DRAIN QUEUE */ gst_data_queue_flush (sq->queue); g_object_unref (sq->queue); g_cond_free (sq->turn); g_free (sq); } static GstSingleQueue * gst_single_queue_new (GstMultiQueue * mqueue) { GstSingleQueue *sq; gchar *tmp; sq = g_new0 (GstSingleQueue, 1); GST_MULTI_QUEUE_MUTEX_LOCK (mqueue); sq->id = mqueue->nbqueues++; /* copy over max_size and extra_size so we don't need to take the lock * any longer when checking if the queue is full. */ sq->max_size.visible = mqueue->max_size.visible; sq->max_size.bytes = mqueue->max_size.bytes; sq->max_size.time = mqueue->max_size.time; sq->extra_size.visible = mqueue->extra_size.visible; sq->extra_size.bytes = mqueue->extra_size.bytes; sq->extra_size.time = mqueue->extra_size.time; GST_MULTI_QUEUE_MUTEX_UNLOCK (mqueue); GST_DEBUG_OBJECT (mqueue, "Creating GstSingleQueue id:%d", sq->id); sq->mqueue = mqueue; sq->srcresult = GST_FLOW_WRONG_STATE; sq->queue = gst_data_queue_new_full ((GstDataQueueCheckFullFunction) single_queue_check_full, (GstDataQueueFullCallback) single_queue_overrun_cb, (GstDataQueueEmptyCallback) single_queue_underrun_cb, sq); sq->is_eos = FALSE; gst_segment_init (&sq->sink_segment, GST_FORMAT_TIME); gst_segment_init (&sq->src_segment, GST_FORMAT_TIME); sq->nextid = 0; sq->oldid = 0; sq->turn = g_cond_new (); sq->sinktime = GST_CLOCK_TIME_NONE; sq->srctime = GST_CLOCK_TIME_NONE; sq->sink_tainted = TRUE; sq->src_tainted = TRUE; tmp = g_strdup_printf ("sink%d", sq->id); sq->sinkpad = gst_pad_new_from_static_template (&sinktemplate, tmp); g_free (tmp); gst_pad_set_chain_function (sq->sinkpad, GST_DEBUG_FUNCPTR (gst_multi_queue_chain)); gst_pad_set_activatepush_function (sq->sinkpad, GST_DEBUG_FUNCPTR (gst_multi_queue_sink_activate_push)); gst_pad_set_event_function (sq->sinkpad, GST_DEBUG_FUNCPTR (gst_multi_queue_sink_event)); gst_pad_set_getcaps_function (sq->sinkpad, GST_DEBUG_FUNCPTR (gst_multi_queue_getcaps)); gst_pad_set_acceptcaps_function (sq->sinkpad, GST_DEBUG_FUNCPTR (gst_multi_queue_acceptcaps)); gst_pad_set_bufferalloc_function (sq->sinkpad, GST_DEBUG_FUNCPTR (gst_multi_queue_bufferalloc)); gst_pad_set_iterate_internal_links_function (sq->sinkpad, GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links)); tmp = g_strdup_printf ("src%d", sq->id); sq->srcpad = gst_pad_new_from_static_template (&srctemplate, tmp); g_free (tmp); gst_pad_set_activatepush_function (sq->srcpad, GST_DEBUG_FUNCPTR (gst_multi_queue_src_activate_push)); gst_pad_set_getcaps_function (sq->srcpad, GST_DEBUG_FUNCPTR (gst_multi_queue_getcaps)); gst_pad_set_acceptcaps_function (sq->srcpad, GST_DEBUG_FUNCPTR (gst_multi_queue_acceptcaps)); gst_pad_set_event_function (sq->srcpad, GST_DEBUG_FUNCPTR (gst_multi_queue_src_event)); gst_pad_set_query_function (sq->srcpad, GST_DEBUG_FUNCPTR (gst_multi_queue_src_query)); gst_pad_set_iterate_internal_links_function (sq->srcpad, GST_DEBUG_FUNCPTR (gst_multi_queue_iterate_internal_links)); gst_pad_set_element_private (sq->sinkpad, (gpointer) sq); gst_pad_set_element_private (sq->srcpad, (gpointer) sq); /* only activate the pads when we are not in the NULL state * and add the pad under the state_lock to prevend state changes * between activating and adding */ g_static_rec_mutex_lock (GST_STATE_GET_LOCK (mqueue)); if (GST_STATE_TARGET (mqueue) != GST_STATE_NULL) { gst_pad_set_active (sq->srcpad, TRUE); gst_pad_set_active (sq->sinkpad, TRUE); } gst_element_add_pad (GST_ELEMENT (mqueue), sq->srcpad); gst_element_add_pad (GST_ELEMENT (mqueue), sq->sinkpad); g_static_rec_mutex_unlock (GST_STATE_GET_LOCK (mqueue)); GST_DEBUG_OBJECT (mqueue, "GstSingleQueue [%d] created and pads added", sq->id); return sq; }
lgpl-2.1
marchelbling/osg
src/osg/Texture1D.cpp
3
16293
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/GLExtensions> #include <osg/Texture1D> #include <osg/State> #include <osg/GLU> typedef void (GL_APIENTRY * MyCompressedTexImage1DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); using namespace osg; Texture1D::Texture1D(): _textureWidth(0), _numMipmapLevels(0) { } Texture1D::Texture1D(osg::Image* image): _textureWidth(0), _numMipmapLevels(0) { setImage(image); } Texture1D::Texture1D(const Texture1D& text,const CopyOp& copyop): Texture(text,copyop), _textureWidth(text._textureWidth), _numMipmapLevels(text._numMipmapLevels), _subloadCallback(text._subloadCallback) { setImage(copyop(text._image.get())); } Texture1D::~Texture1D() { setImage(NULL); } int Texture1D::compare(const StateAttribute& sa) const { // check the types are equal and then create the rhs variable // used by the COMPARE_StateAttribute_Parameter macros below. COMPARE_StateAttribute_Types(Texture1D,sa) if (_image!=rhs._image) // smart pointer comparison. { if (_image.valid()) { if (rhs._image.valid()) { int result = _image->compare(*rhs._image); if (result!=0) return result; } else { return 1; // valid lhs._image is greater than null. } } else if (rhs._image.valid()) { return -1; // valid rhs._image is greater than null. } } if (!_image && !rhs._image) { // no image attached to either Texture2D // but could these textures already be downloaded? // check the _textureObjectBuffer to see if they have been // downloaded int result = compareTextureObjects(rhs); if (result!=0) return result; } int result = compareTexture(rhs); if (result!=0) return result; // compare each parameter in turn against the rhs. COMPARE_StateAttribute_Parameter(_textureWidth) COMPARE_StateAttribute_Parameter(_subloadCallback) return 0; // passed all the above comparison macros, must be equal. } void Texture1D::setImage(Image* image) { if (_image == image) return; if (_image.valid()) { _image->removeClient(this); if (_image->requiresUpdateCall()) { setUpdateCallback(0); setDataVariance(osg::Object::STATIC); } } // delete old texture objects. dirtyTextureObject(); _image = image; _modifiedCount.setAllElementsTo(0); if (_image.valid()) { _image->addClient(this); if (_image->requiresUpdateCall()) { setUpdateCallback(new Image::UpdateCallback()); setDataVariance(osg::Object::DYNAMIC); } } } void Texture1D::apply(State& state) const { #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) // get the contextID (user defined ID of 0 upwards) for the // current OpenGL context. const unsigned int contextID = state.getContextID(); // get the texture object for the current contextID. TextureObject* textureObject = getTextureObject(contextID); if (textureObject) { if (_image.valid() && getModifiedCount(contextID) != _image->getModifiedCount()) { // compute the internal texture format, this set the _internalFormat to an appropriate value. computeInternalFormat(); GLsizei new_width = _image->s(); GLsizei new_numMipmapLevels = _numMipmapLevels; if (!textureObject->match(GL_TEXTURE_1D, new_numMipmapLevels, _internalFormat, new_width, 1, 1, _borderWidth)) { _textureObjectBuffer[contextID]->release(); _textureObjectBuffer[contextID] = 0; textureObject = 0; } } } if (textureObject) { textureObject->bind(); if (getTextureParameterDirty(state.getContextID())) applyTexParameters(GL_TEXTURE_1D,state); if (_subloadCallback.valid()) { _subloadCallback->subload(*this,state); } else if (_image.valid() && getModifiedCount(contextID) != _image->getModifiedCount()) { applyTexImage1D(GL_TEXTURE_1D,_image.get(),state, _textureWidth, _numMipmapLevels); // update the modified count to show that it is up to date. getModifiedCount(contextID) = _image->getModifiedCount(); } } else if (_subloadCallback.valid()) { // we don't have a applyTexImage1D_subload yet so can't reuse.. so just generate a new texture object. textureObject = generateAndAssignTextureObject(contextID, GL_TEXTURE_1D); textureObject->bind(); applyTexParameters(GL_TEXTURE_1D,state); _subloadCallback->load(*this,state); textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,1,1,0); // in theory the following line is redundent, but in practice // have found that the first frame drawn doesn't apply the textures // unless a second bind is called?!! // perhaps it is the first glBind which is not required... //glBindTexture( GL_TEXTURE_1D, handle ); } else if (_image.valid() && _image->data()) { // we don't have a applyTexImage1D_subload yet so can't reuse.. so just generate a new texture object. textureObject = generateAndAssignTextureObject(contextID,GL_TEXTURE_1D); textureObject->bind(); applyTexParameters(GL_TEXTURE_1D,state); applyTexImage1D(GL_TEXTURE_1D,_image.get(),state, _textureWidth, _numMipmapLevels); textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,1,1,0); // update the modified count to show that it is up to date. getModifiedCount(contextID) = _image->getModifiedCount(); _textureObjectBuffer[contextID] = textureObject; // unref image data? if (isSafeToUnrefImageData(state) && _image->getDataVariance()==STATIC) { Texture1D* non_const_this = const_cast<Texture1D*>(this); non_const_this->_image = NULL; } } else if ( (_textureWidth!=0) && (_internalFormat!=0) ) { textureObject = generateAndAssignTextureObject(contextID, GL_TEXTURE_1D,_numMipmapLevels,_internalFormat,_textureWidth,1,1,0); textureObject->bind(); applyTexParameters(GL_TEXTURE_1D,state); // no image present, but dimensions are set so lets create the texture glTexImage1D( GL_TEXTURE_1D, 0, _internalFormat, _textureWidth, _borderWidth, _sourceFormat ? _sourceFormat : _internalFormat, _sourceType ? _sourceType : GL_UNSIGNED_BYTE, 0); if (_readPBuffer.valid()) { _readPBuffer->bindPBufferToTexture(GL_FRONT); } } else { glBindTexture( GL_TEXTURE_1D, 0 ); } // if texture object is now valid and we have to allocate mipmap levels, then if (textureObject != 0 && _texMipmapGenerationDirtyList[contextID]) { generateMipmap(state); } #else OSG_NOTICE<<"Warning: Texture1D::apply(State& state) not supported."<<std::endl; #endif } void Texture1D::computeInternalFormat() const { if (_image.valid()) computeInternalFormatWithImage(*_image); else computeInternalFormatType(); } void Texture1D::applyTexImage1D(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& numMipmapLevels) const { #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) // if we don't have a valid image we can't create a texture! if (!image || !image->data()) return; // get extension object const GLExtensions* extensions = state.get<GLExtensions>(); // compute the internal texture format, this set the _internalFormat to an appropriate value. computeInternalFormat(); // select the internalFormat required for the texture. bool compressed = isCompressedInternalFormat(_internalFormat); //Rescale if resize hint is set or NPOT not supported or dimension exceeds max size if( _resizeNonPowerOfTwoHint || !extensions->isNonPowerOfTwoTextureSupported(_min_filter) || inwidth > extensions->maxTextureSize ) { // this is not thread safe... should really create local image data and rescale to that as per Texture2D. image->ensureValidSizeForTexturing(extensions->maxTextureSize); } glPixelStorei(GL_UNPACK_ALIGNMENT,image->getPacking()); glPixelStorei(GL_UNPACK_ROW_LENGTH,image->getRowLength()); static MyCompressedTexImage1DArbProc glCompressedTexImage1D_ptr = convertPointerType<MyCompressedTexImage1DArbProc, void*>(getGLExtensionFuncPtr("glCompressedTexImage1DARB")); if( _min_filter == LINEAR || _min_filter == NEAREST ) { if ( !compressed ) { numMipmapLevels = 1; glTexImage1D( target, 0, _internalFormat, image->s(), _borderWidth, (GLenum)image->getPixelFormat(), (GLenum)image->getDataType(), image->data() ); } else if(glCompressedTexImage1D_ptr) { numMipmapLevels = 1; GLint blockSize = ( _internalFormat == GL_COMPRESSED_RGB_S3TC_DXT1_EXT ? 8 : 16 ); GLint size = ((image->s()+3)/4)*((image->t()+3)/4)*blockSize; glCompressedTexImage1D_ptr(target, 0, _internalFormat, image->s(), _borderWidth, size, image->data()); } } else { if(!image->isMipmap()) { numMipmapLevels = 1; gluBuild1DMipmaps( target, _internalFormat, image->s(), (GLenum)image->getPixelFormat(), (GLenum)image->getDataType(), image->data() ); } else { numMipmapLevels = image->getNumMipmapLevels(); int width = image->s(); if( !compressed ) { for( GLsizei k = 0 ; k < numMipmapLevels && width ;k++) { glTexImage1D( target, k, _internalFormat, width,_borderWidth, (GLenum)image->getPixelFormat(), (GLenum)image->getDataType(), image->getMipmapData(k)); width >>= 1; } } else if(glCompressedTexImage1D_ptr) { GLint blockSize = ( _internalFormat == GL_COMPRESSED_RGB_S3TC_DXT1_EXT ? 8 : 16 ); GLint size = 0; for( GLsizei k = 0 ; k < numMipmapLevels && width ;k++) { size = ((width+3)/4)*blockSize; glCompressedTexImage1D_ptr(target, k, _internalFormat, width, _borderWidth, size, image->getMipmapData(k)); width >>= 1; } } } } inwidth = image->s(); #else OSG_NOTICE<<"Warning: Texture1D::applyTexImage1D(State& state) not supported."<<std::endl; #endif } void Texture1D::copyTexImage1D(State& state, int x, int y, int width) { #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) const unsigned int contextID = state.getContextID(); // get the texture object for the current contextID. TextureObject* textureObject = getTextureObject(contextID); if (textureObject != 0) { if (width==(int)_textureWidth) { // we have a valid texture object which is the right size // so lets play clever and use copyTexSubImage1D instead. // this allows use to reuse the texture object and avoid // expensive memory allocations. copyTexSubImage1D(state,0 ,x, y, width); return; } // the relevant texture object is not of the right size so // needs to been deleted // remove previously bound textures. dirtyTextureObject(); // note, dirtyTextureObject() dirties all the texture objects for // this texture, is this right? Perhaps we should dirty just the // one for this context. Note sure yet will leave till later. // RO July 2001. } // remove any previously assigned images as these are nolonger valid. _image = NULL; // switch off mip-mapping. _min_filter = LINEAR; _mag_filter = LINEAR; textureObject = generateAndAssignTextureObject(contextID, GL_TEXTURE_1D); textureObject->bind(); applyTexParameters(GL_TEXTURE_1D,state); glCopyTexImage1D( GL_TEXTURE_1D, 0, GL_RGBA, x, y, width, 0 ); _textureWidth = width; _numMipmapLevels = 1; textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,1,1,0); // inform state that this texture is the current one bound. state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), this); #else OSG_NOTICE<<"Warning: Texture1D::copyTexImage1D(..) not supported."<<std::endl; #endif } void Texture1D::copyTexSubImage1D(State& state, int xoffset, int x, int y, int width) { #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) const unsigned int contextID = state.getContextID(); // get the texture object for the current contextID. TextureObject* textureObject = getTextureObject(contextID); if (textureObject != 0) { textureObject->bind(); // we have a valid image applyTexParameters(GL_TEXTURE_1D,state); glCopyTexSubImage1D( GL_TEXTURE_1D, 0, xoffset, x, y, width); // inform state that this texture is the current one bound. state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), this); } else { // no texture object already exsits for this context so need to // create it upfront - simply call copyTexImage1D. copyTexImage1D(state,x,y,width); } #else OSG_NOTICE<<"Warning: Texture1D::copyTexSubImage1D(..) not supported."<<std::endl; #endif } void Texture1D::allocateMipmap(State& state) const { #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) const unsigned int contextID = state.getContextID(); // get the texture object for the current contextID. TextureObject* textureObject = getTextureObject(contextID); if (textureObject && _textureWidth != 0) { // bind texture textureObject->bind(); // compute number of mipmap levels int width = _textureWidth; int numMipmapLevels = Image::computeNumberOfMipmapLevels(width); // we do not reallocate the level 0, since it was already allocated width >>= 1; for( GLsizei k = 1; k < numMipmapLevels && width; k++) { glTexImage1D( GL_TEXTURE_1D, k, _internalFormat, width, _borderWidth, _sourceFormat ? _sourceFormat : _internalFormat, _sourceType ? _sourceType : GL_UNSIGNED_BYTE, NULL); width >>= 1; } // inform state that this texture is the current one bound. state.haveAppliedTextureAttribute(state.getActiveTextureUnit(), this); } #else OSG_NOTICE<<"Warning: Texture1D::allocateMipmap(..) not supported."<<std::endl; #endif }
lgpl-2.1
neiljay/RIOT
sys/base64/base64.c
4
5497
/* * Copyright (C) 2014 Hochschule für Angewandte Wissenschaften Hamburg (HAW) * Copyright (C) 2014 Martin Landsmann <Martin.Landsmann@HAW-Hamburg.de> * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup sys_base64 * @{ * @file * @brief Functions to encode and decode base64 * * @author Martin Landsmann <Martin.Landsmann@HAW-Hamburg.de> * @} * */ #include "base64.h" #define BASE64_CAPITAL_UPPER_BOUND (25) /**< base64 'Z' */ #define BASE64_SMALL_UPPER_BOUND (51) /**< base64 'z' */ #define BASE64_NUMBER_UPPER_BOUND (61) /**< base64 '9' */ #define BASE64_PLUS (62) /**< base64 '+' */ #define BASE64_SLASH (63) /**< base64 '/' */ #define BASE64_EQUALS (0xFE) /**< no base64 symbol '=' */ #define BASE64_NOT_DEFINED (0xFF) /**< no base64 symbol */ /* * returns the corresponding ascii symbol value for the given base64 code */ static char getsymbol(unsigned char code) { if (code == BASE64_SLASH) { return '/'; } if (code == BASE64_PLUS) { return '+'; } if (code <= BASE64_CAPITAL_UPPER_BOUND) { return (code + 'A'); } if (code <= BASE64_SMALL_UPPER_BOUND) { return (code + ('z' - BASE64_SMALL_UPPER_BOUND)); } if (code <= BASE64_NUMBER_UPPER_BOUND) { return (code + ('9' - BASE64_NUMBER_UPPER_BOUND)); } return (char)BASE64_NOT_DEFINED; } int base64_encode(unsigned char *data_in, size_t data_in_size, \ unsigned char *base64_out, size_t *base64_out_size) { size_t required_size = 4 * ((data_in_size + 2) / 3); if (data_in == NULL) { return BASE64_ERROR_DATA_IN; } if (data_in_size < 1) { return BASE64_ERROR_DATA_IN_SIZE; } if (*base64_out_size < required_size) { *base64_out_size = required_size; return BASE64_ERROR_BUFFER_OUT_SIZE; } if (base64_out == NULL) { return BASE64_ERROR_BUFFER_OUT; } int iterate_base64_buffer = 0; unsigned char nNum = 0; int nLst = 0; int njump = 0; for (int i = 0; i < (int)(data_in_size); ++i) { unsigned char tmpval; njump++; tmpval = *(data_in + i); nNum = (tmpval >> (2 * njump)); if (njump == 4) { nNum = nLst << (8 - 2 * njump); njump = 0; nLst = 0; --i; } else { nNum += nLst << (8 - 2 * njump); nLst = tmpval & ((1 << njump * 2) - 1); } base64_out[iterate_base64_buffer++] = getsymbol(nNum); } /* The last character is not finished yet */ njump++; nNum = nLst << (8 - 2 * njump); base64_out[iterate_base64_buffer++] = getsymbol(nNum); /* if required we append '=' for the required dividability */ while (iterate_base64_buffer % 4) { base64_out[iterate_base64_buffer++] = '='; } *base64_out_size = iterate_base64_buffer; return BASE64_SUCCESS; } /* * returns the corresponding base64 code for the given ascii symbol */ static int getcode(char symbol) { if (symbol == '/') { return BASE64_SLASH; } if (symbol == '+') { return BASE64_PLUS; } if (symbol == '=') { /* indicates a padded base64 end */ return BASE64_EQUALS; } if (symbol < '0') { /* indicates that the given symbol is not base64 and should be ignored */ return BASE64_NOT_DEFINED; } if (symbol <= '9' && symbol >= '0') { return (symbol + (BASE64_NUMBER_UPPER_BOUND - '9')); } if (symbol <= 'Z' && symbol >= 'A') { return (symbol - 'A'); } if (symbol <= 'z' && symbol >= 'a') { return (symbol + (BASE64_SMALL_UPPER_BOUND - 'z')); } /* indicates that the given symbol is not base64 and should be ignored */ return BASE64_NOT_DEFINED; } int base64_decode(unsigned char *base64_in, size_t base64_in_size, \ unsigned char *data_out, size_t *data_out_size) { size_t required_size = ((base64_in_size / 4) * 3); if (base64_in == NULL) { return BASE64_ERROR_DATA_IN; } if (base64_in_size < 4) { return BASE64_ERROR_DATA_IN_SIZE; } if (*data_out_size < required_size) { *data_out_size = required_size; return BASE64_ERROR_BUFFER_OUT_SIZE; } if (data_out == NULL) { return BASE64_ERROR_BUFFER_OUT; } int iterate_data_buffer = 0; unsigned char nNum = 0; int nLst = getcode(base64_in[0]) << 2; int code = 0; int mask = 2; for (int i = 1; i < (int)(base64_in_size); i++) { code = getcode(base64_in[i]); if (code == BASE64_NOT_DEFINED || code == BASE64_EQUALS) { continue; } int nm = (0xFF << (2 * mask)); nNum = nLst + ((code & (0xFF & nm)) >> (2 * mask)); nLst = (code & (0xFF & ~nm)) << (8 - (2 * mask)); (mask != 3) ? data_out[iterate_data_buffer++] = nNum : nNum; (mask == 0) ? mask = 3 : mask--; } if (code == BASE64_EQUALS) { /* add the last character to the data_out buffer */ data_out[iterate_data_buffer] = nNum; } *data_out_size = iterate_data_buffer; return BASE64_SUCCESS; }
lgpl-2.1
davibe/gst-plugins-good
gst/audioparsers/gstac3parse.c
4
21053
/* GStreamer AC3 parser * Copyright (C) 2009 Tim-Philipp Müller <tim centricular net> * Copyright (C) 2009 Mark Nauwelaerts <mnauw users sf net> * Copyright (C) 2009 Nokia Corporation. All rights reserved. * Contact: Stefan Kost <stefan.kost@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * SECTION:element-ac3parse * @short_description: AC3 parser * @see_also: #GstAmrParse, #GstAACParse * * This is an AC3 parser. * * <refsect2> * <title>Example launch line</title> * |[ * gst-launch filesrc location=abc.ac3 ! ac3parse ! a52dec ! audioresample ! audioconvert ! autoaudiosink * ]| * </refsect2> */ /* TODO: * - add support for audio/x-private1-ac3 as well * - should accept framed and unframed input (needs decodebin fixes first) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include "gstac3parse.h" #include <gst/base/gstbytereader.h> #include <gst/base/gstbitreader.h> GST_DEBUG_CATEGORY_STATIC (ac3_parse_debug); #define GST_CAT_DEFAULT ac3_parse_debug static const struct { const guint bit_rate; /* nominal bit rate */ const guint frame_size[3]; /* frame size for 32kHz, 44kHz, and 48kHz */ } frmsizcod_table[38] = { { 32, { 64, 69, 96}}, { 32, { 64, 70, 96}}, { 40, { 80, 87, 120}}, { 40, { 80, 88, 120}}, { 48, { 96, 104, 144}}, { 48, { 96, 105, 144}}, { 56, { 112, 121, 168}}, { 56, { 112, 122, 168}}, { 64, { 128, 139, 192}}, { 64, { 128, 140, 192}}, { 80, { 160, 174, 240}}, { 80, { 160, 175, 240}}, { 96, { 192, 208, 288}}, { 96, { 192, 209, 288}}, { 112, { 224, 243, 336}}, { 112, { 224, 244, 336}}, { 128, { 256, 278, 384}}, { 128, { 256, 279, 384}}, { 160, { 320, 348, 480}}, { 160, { 320, 349, 480}}, { 192, { 384, 417, 576}}, { 192, { 384, 418, 576}}, { 224, { 448, 487, 672}}, { 224, { 448, 488, 672}}, { 256, { 512, 557, 768}}, { 256, { 512, 558, 768}}, { 320, { 640, 696, 960}}, { 320, { 640, 697, 960}}, { 384, { 768, 835, 1152}}, { 384, { 768, 836, 1152}}, { 448, { 896, 975, 1344}}, { 448, { 896, 976, 1344}}, { 512, { 1024, 1114, 1536}}, { 512, { 1024, 1115, 1536}}, { 576, { 1152, 1253, 1728}}, { 576, { 1152, 1254, 1728}}, { 640, { 1280, 1393, 1920}}, { 640, { 1280, 1394, 1920}} }; static const guint fscod_rates[4] = { 48000, 44100, 32000, 0 }; static const guint acmod_chans[8] = { 2, 1, 2, 3, 3, 4, 4, 5 }; static const guint numblks[4] = { 1, 2, 3, 6 }; static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ("audio/x-ac3, framed = (boolean) true, " " channels = (int) [ 1, 6 ], rate = (int) [ 8000, 48000 ], " " alignment = (string) { iec61937, frame}; " "audio/x-eac3, framed = (boolean) true, " " channels = (int) [ 1, 6 ], rate = (int) [ 8000, 48000 ], " " alignment = (string) { iec61937, frame}; ")); static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ("audio/x-ac3; " "audio/x-eac3; " "audio/ac3")); static void gst_ac3_parse_finalize (GObject * object); static gboolean gst_ac3_parse_start (GstBaseParse * parse); static gboolean gst_ac3_parse_stop (GstBaseParse * parse); static gboolean gst_ac3_parse_check_valid_frame (GstBaseParse * parse, GstBaseParseFrame * frame, guint * size, gint * skipsize); static GstFlowReturn gst_ac3_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame); static gboolean gst_ac3_parse_src_event (GstBaseParse * parse, GstEvent * event); static GstCaps *gst_ac3_parse_get_sink_caps (GstBaseParse * parse); GST_BOILERPLATE (GstAc3Parse, gst_ac3_parse, GstBaseParse, GST_TYPE_BASE_PARSE); static void gst_ac3_parse_base_init (gpointer klass) { GstElementClass *element_class = GST_ELEMENT_CLASS (klass); gst_element_class_add_static_pad_template (element_class, &sink_template); gst_element_class_add_static_pad_template (element_class, &src_template); gst_element_class_set_details_simple (element_class, "AC3 audio stream parser", "Codec/Parser/Converter/Audio", "AC3 parser", "Tim-Philipp Müller <tim centricular net>"); } static void gst_ac3_parse_class_init (GstAc3ParseClass * klass) { GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass); GObjectClass *object_class = G_OBJECT_CLASS (klass); GST_DEBUG_CATEGORY_INIT (ac3_parse_debug, "ac3parse", 0, "AC3 audio stream parser"); object_class->finalize = gst_ac3_parse_finalize; parse_class->start = GST_DEBUG_FUNCPTR (gst_ac3_parse_start); parse_class->stop = GST_DEBUG_FUNCPTR (gst_ac3_parse_stop); parse_class->check_valid_frame = GST_DEBUG_FUNCPTR (gst_ac3_parse_check_valid_frame); parse_class->parse_frame = GST_DEBUG_FUNCPTR (gst_ac3_parse_parse_frame); parse_class->src_event = GST_DEBUG_FUNCPTR (gst_ac3_parse_src_event); parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_ac3_parse_get_sink_caps); } static void gst_ac3_parse_reset (GstAc3Parse * ac3parse) { ac3parse->channels = -1; ac3parse->sample_rate = -1; ac3parse->blocks = -1; ac3parse->eac = FALSE; g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_NONE); } static void gst_ac3_parse_init (GstAc3Parse * ac3parse, GstAc3ParseClass * klass) { gst_base_parse_set_min_frame_size (GST_BASE_PARSE (ac3parse), 6); gst_ac3_parse_reset (ac3parse); } static void gst_ac3_parse_finalize (GObject * object) { G_OBJECT_CLASS (parent_class)->finalize (object); } static gboolean gst_ac3_parse_start (GstBaseParse * parse) { GstAc3Parse *ac3parse = GST_AC3_PARSE (parse); GST_DEBUG_OBJECT (parse, "starting"); gst_ac3_parse_reset (ac3parse); return TRUE; } static gboolean gst_ac3_parse_stop (GstBaseParse * parse) { GST_DEBUG_OBJECT (parse, "stopping"); return TRUE; } static void gst_ac3_parse_set_alignment (GstAc3Parse * ac3parse, gboolean eac) { GstCaps *caps; GstStructure *st; const gchar *str = NULL; int i; if (G_LIKELY (!eac)) goto done; caps = gst_pad_get_allowed_caps (GST_BASE_PARSE_SRC_PAD (ac3parse)); if (!caps) goto done; for (i = 0; i < gst_caps_get_size (caps); i++) { st = gst_caps_get_structure (caps, i); if (!g_str_equal (gst_structure_get_name (st), "audio/x-eac3")) continue; if ((str = gst_structure_get_string (st, "alignment"))) { if (g_str_equal (str, "iec61937")) { g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_IEC61937); GST_DEBUG_OBJECT (ac3parse, "picked iec61937 alignment"); } else if (g_str_equal (str, "frame") == 0) { g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME); GST_DEBUG_OBJECT (ac3parse, "picked frame alignment"); } else { g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME); GST_WARNING_OBJECT (ac3parse, "unknown alignment: %s", str); } break; } } if (caps) gst_caps_unref (caps); done: /* default */ if (ac3parse->align == GST_AC3_PARSE_ALIGN_NONE) { g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME); GST_DEBUG_OBJECT (ac3parse, "picked syncframe alignment"); } } static gboolean gst_ac3_parse_frame_header_ac3 (GstAc3Parse * ac3parse, GstBuffer * buf, gint skip, guint * frame_size, guint * rate, guint * chans, guint * blks, guint * sid) { GstBitReader bits = GST_BIT_READER_INIT_FROM_BUFFER (buf); guint8 fscod, frmsizcod, bsid, acmod, lfe_on, rate_scale; GST_LOG_OBJECT (ac3parse, "parsing ac3"); gst_bit_reader_skip_unchecked (&bits, skip * 8); gst_bit_reader_skip_unchecked (&bits, 16 + 16); fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2); frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6); if (G_UNLIKELY (fscod == 3 || frmsizcod >= G_N_ELEMENTS (frmsizcod_table))) { GST_DEBUG_OBJECT (ac3parse, "bad fscod=%d frmsizcod=%d", fscod, frmsizcod); return FALSE; } bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5); gst_bit_reader_skip_unchecked (&bits, 3); /* bsmod */ acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3); /* spec not quite clear here: decoder should decode if less than 8, * but seemingly only defines 6 and 8 cases */ /* Files with 9 and 10 happen, and seem to comply with the <= 8 format, so let them through. The spec says nothing about 9 and 10 */ if (bsid > 10) { GST_DEBUG_OBJECT (ac3parse, "unexpected bsid=%d", bsid); return FALSE; } else if (bsid != 8 && bsid != 6) { GST_DEBUG_OBJECT (ac3parse, "undefined bsid=%d", bsid); } if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */ gst_bit_reader_skip_unchecked (&bits, 2); if ((acmod & 0x4)) /* if a surround channel exists */ gst_bit_reader_skip_unchecked (&bits, 2); if (acmod == 0x2) /* if in 2/0 mode */ gst_bit_reader_skip_unchecked (&bits, 2); lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1); /* 6/8->0, 9->1, 10->2, see http://matroska.org/technical/specs/codecid/index.html */ rate_scale = (CLAMP (bsid, 8, 10) - 8); if (frame_size) *frame_size = frmsizcod_table[frmsizcod].frame_size[fscod] * 2; if (rate) *rate = fscod_rates[fscod] >> rate_scale; if (chans) *chans = acmod_chans[acmod] + lfe_on; if (blks) *blks = 6; if (sid) *sid = 0; return TRUE; } static gboolean gst_ac3_parse_frame_header_eac3 (GstAc3Parse * ac3parse, GstBuffer * buf, gint skip, guint * frame_size, guint * rate, guint * chans, guint * blks, guint * sid) { GstBitReader bits = GST_BIT_READER_INIT_FROM_BUFFER (buf); guint16 frmsiz, sample_rate, blocks; guint8 strmtyp, fscod, fscod2, acmod, lfe_on, strmid, numblkscod; GST_LOG_OBJECT (ac3parse, "parsing e-ac3"); gst_bit_reader_skip_unchecked (&bits, skip * 8); gst_bit_reader_skip_unchecked (&bits, 16); strmtyp = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2); /* strmtyp */ if (G_UNLIKELY (strmtyp == 3)) { GST_DEBUG_OBJECT (ac3parse, "bad strmtyp %d", strmtyp); return FALSE; } strmid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3); /* substreamid */ frmsiz = gst_bit_reader_get_bits_uint16_unchecked (&bits, 11); /* frmsiz */ fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2); /* fscod */ if (fscod == 3) { fscod2 = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2); /* fscod2 */ if (G_UNLIKELY (fscod2 == 3)) { GST_DEBUG_OBJECT (ac3parse, "invalid fscod2"); return FALSE; } sample_rate = fscod_rates[fscod2] / 2; blocks = 6; } else { numblkscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2); /* numblkscod */ sample_rate = fscod_rates[fscod]; blocks = numblks[numblkscod]; } acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3); /* acmod */ lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1); /* lfeon */ gst_bit_reader_skip_unchecked (&bits, 5); /* bsid */ if (frame_size) *frame_size = (frmsiz + 1) * 2; if (rate) *rate = sample_rate; if (chans) *chans = acmod_chans[acmod] + lfe_on; if (blks) *blks = blocks; if (sid) *sid = (strmtyp & 0x1) << 3 | strmid; return TRUE; } static gboolean gst_ac3_parse_frame_header (GstAc3Parse * parse, GstBuffer * buf, gint skip, guint * framesize, guint * rate, guint * chans, guint * blocks, guint * sid, gboolean * eac) { GstBitReader bits = GST_BIT_READER_INIT_FROM_BUFFER (buf); guint16 sync; guint8 bsid; GST_MEMDUMP_OBJECT (parse, "AC3 frame sync", GST_BUFFER_DATA (buf), 16); gst_bit_reader_skip_unchecked (&bits, skip * 8); sync = gst_bit_reader_get_bits_uint16_unchecked (&bits, 16); gst_bit_reader_skip_unchecked (&bits, 16 + 8); bsid = gst_bit_reader_peek_bits_uint8_unchecked (&bits, 5); if (G_UNLIKELY (sync != 0x0b77)) return FALSE; GST_LOG_OBJECT (parse, "bsid = %d", bsid); if (bsid <= 10) { if (eac) *eac = FALSE; return gst_ac3_parse_frame_header_ac3 (parse, buf, skip, framesize, rate, chans, blocks, sid); } else if (bsid <= 16) { if (eac) *eac = TRUE; return gst_ac3_parse_frame_header_eac3 (parse, buf, skip, framesize, rate, chans, blocks, sid); } else { GST_DEBUG_OBJECT (parse, "unexpected bsid %d", bsid); return FALSE; } } static gboolean gst_ac3_parse_check_valid_frame (GstBaseParse * parse, GstBaseParseFrame * frame, guint * framesize, gint * skipsize) { GstAc3Parse *ac3parse = GST_AC3_PARSE (parse); GstBuffer *buf = frame->buffer; GstByteReader reader = GST_BYTE_READER_INIT_FROM_BUFFER (buf); gint off; gboolean lost_sync, draining, eac, more = FALSE; guint frmsiz, blocks, sid; gint have_blocks = 0; if (G_UNLIKELY (GST_BUFFER_SIZE (buf) < 6)) return FALSE; off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000, 0, GST_BUFFER_SIZE (buf)); GST_LOG_OBJECT (parse, "possible sync at buffer offset %d", off); /* didn't find anything that looks like a sync word, skip */ if (off < 0) { *skipsize = GST_BUFFER_SIZE (buf) - 3; return FALSE; } /* possible frame header, but not at offset 0? skip bytes before sync */ if (off > 0) { *skipsize = off; return FALSE; } /* make sure the values in the frame header look sane */ if (!gst_ac3_parse_frame_header (ac3parse, buf, 0, &frmsiz, NULL, NULL, &blocks, &sid, &eac)) { *skipsize = off + 2; return FALSE; } *framesize = frmsiz; if (G_UNLIKELY (g_atomic_int_get (&ac3parse->align) == GST_AC3_PARSE_ALIGN_NONE)) gst_ac3_parse_set_alignment (ac3parse, eac); GST_LOG_OBJECT (parse, "got frame"); lost_sync = GST_BASE_PARSE_LOST_SYNC (parse); draining = GST_BASE_PARSE_DRAINING (parse); if (g_atomic_int_get (&ac3parse->align) == GST_AC3_PARSE_ALIGN_IEC61937) { /* We need 6 audio blocks from each substream, so we keep going forwards * till we have it */ g_assert (blocks > 0); GST_LOG_OBJECT (ac3parse, "Need %d frames before pushing", 6 / blocks); if (sid != 0) { /* We need the first substream to be the one with id 0 */ GST_LOG_OBJECT (ac3parse, "Skipping till we find sid 0"); *skipsize = off + 2; return FALSE; } *framesize = 0; /* Loop till we have 6 blocks per substream */ for (have_blocks = 0; !more && have_blocks < 6; have_blocks += blocks) { /* Loop till we get one frame from each substream */ do { *framesize += frmsiz; if (!gst_byte_reader_skip (&reader, frmsiz) || GST_BUFFER_SIZE (buf) < (*framesize + 6)) { more = TRUE; break; } if (!gst_ac3_parse_frame_header (ac3parse, buf, *framesize, &frmsiz, NULL, NULL, NULL, &sid, &eac)) { *skipsize = off + 2; return FALSE; } } while (sid); } /* We're now at the next frame, so no need to skip if resyncing */ frmsiz = 0; } if (lost_sync && !draining) { guint16 word = 0; GST_DEBUG_OBJECT (ac3parse, "resyncing; checking next frame syncword"); if (more || !gst_byte_reader_skip (&reader, frmsiz) || !gst_byte_reader_get_uint16_be (&reader, &word)) { GST_DEBUG_OBJECT (ac3parse, "... but not sufficient data"); gst_base_parse_set_min_frame_size (parse, *framesize + 6); *skipsize = 0; return FALSE; } else { if (word != 0x0b77) { GST_DEBUG_OBJECT (ac3parse, "0x%x not OK", word); *skipsize = off + 2; return FALSE; } else { /* ok, got sync now, let's assume constant frame size */ gst_base_parse_set_min_frame_size (parse, *framesize); } } } return TRUE; } static GstFlowReturn gst_ac3_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame) { GstAc3Parse *ac3parse = GST_AC3_PARSE (parse); GstBuffer *buf = frame->buffer; guint fsize, rate, chans, blocks, sid; gboolean eac, update_rate = FALSE; if (!gst_ac3_parse_frame_header (ac3parse, buf, 0, &fsize, &rate, &chans, &blocks, &sid, &eac)) goto broken_header; GST_LOG_OBJECT (parse, "size: %u, blocks: %u, rate: %u, chans: %u", fsize, blocks, rate, chans); if (G_UNLIKELY (sid)) { /* dependent frame, no need to (ac)count for or consider further */ GST_LOG_OBJECT (parse, "sid: %d", sid); frame->flags |= GST_BASE_PARSE_FRAME_FLAG_NO_FRAME; /* TODO maybe also mark as DELTA_UNIT, * if that does not surprise baseparse elsewhere */ /* occupies same time space as previous base frame */ if (G_LIKELY (GST_BUFFER_TIMESTAMP (buf) >= GST_BUFFER_DURATION (buf))) GST_BUFFER_TIMESTAMP (buf) -= GST_BUFFER_DURATION (buf); /* only return if we already arranged for caps */ if (G_LIKELY (ac3parse->sample_rate > 0)) return GST_FLOW_OK; } if (G_UNLIKELY (ac3parse->sample_rate != rate || ac3parse->channels != chans || ac3parse->eac != eac)) { GstCaps *caps = gst_caps_new_simple (eac ? "audio/x-eac3" : "audio/x-ac3", "framed", G_TYPE_BOOLEAN, TRUE, "rate", G_TYPE_INT, rate, "channels", G_TYPE_INT, chans, NULL); gst_caps_set_simple (caps, "alignment", G_TYPE_STRING, g_atomic_int_get (&ac3parse->align) == GST_AC3_PARSE_ALIGN_IEC61937 ? "iec61937" : "frame", NULL); gst_buffer_set_caps (buf, caps); gst_pad_set_caps (GST_BASE_PARSE_SRC_PAD (parse), caps); gst_caps_unref (caps); ac3parse->sample_rate = rate; ac3parse->channels = chans; ac3parse->eac = eac; update_rate = TRUE; } if (G_UNLIKELY (ac3parse->blocks != blocks)) { ac3parse->blocks = blocks; update_rate = TRUE; } if (G_UNLIKELY (update_rate)) gst_base_parse_set_frame_rate (parse, rate, 256 * blocks, 2, 2); return GST_FLOW_OK; /* ERRORS */ broken_header: { /* this really shouldn't ever happen */ GST_ELEMENT_ERROR (parse, STREAM, DECODE, (NULL), (NULL)); return GST_FLOW_ERROR; } } static gboolean gst_ac3_parse_src_event (GstBaseParse * parse, GstEvent * event) { GstAc3Parse *ac3parse = GST_AC3_PARSE (parse); if (G_UNLIKELY (GST_EVENT_TYPE (event) == GST_EVENT_CUSTOM_UPSTREAM) && gst_event_has_name (event, "ac3parse-set-alignment")) { const GstStructure *st = gst_event_get_structure (event); const gchar *align = gst_structure_get_string (st, "alignment"); if (g_str_equal (align, "iec61937")) { GST_DEBUG_OBJECT (ac3parse, "Switching to iec61937 alignment"); g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_IEC61937); } else if (g_str_equal (align, "frame")) { GST_DEBUG_OBJECT (ac3parse, "Switching to frame alignment"); g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME); } else { g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME); GST_WARNING_OBJECT (ac3parse, "Got unknown alignment request (%s) " "reverting to frame alignment.", gst_structure_get_string (st, "alignment")); } gst_event_unref (event); return TRUE; } return GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event); } static GstCaps * gst_ac3_parse_get_sink_caps (GstBaseParse * parse) { GstCaps *peercaps; GstCaps *res; peercaps = gst_pad_get_allowed_caps (GST_BASE_PARSE_SRC_PAD (parse)); if (peercaps) { guint i, n; /* Remove the framed and alignment field. We can convert * between different alignments. */ peercaps = gst_caps_make_writable (peercaps); n = gst_caps_get_size (peercaps); for (i = 0; i < n; i++) { GstStructure *s = gst_caps_get_structure (peercaps, i); gst_structure_remove_field (s, "framed"); gst_structure_remove_field (s, "alignment"); } res = gst_caps_intersect_full (peercaps, gst_pad_get_pad_template_caps (GST_BASE_PARSE_SRC_PAD (parse)), GST_CAPS_INTERSECT_FIRST); gst_caps_unref (peercaps); } else { res = gst_caps_copy (gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse))); } return res; }
lgpl-2.1
sumitn/pvfs
test/client/sysint/list-eattr.c
5
6926
/* * (C) 2004 Clemson University and The University of Chicago * * See COPYING in top-level directory. */ #include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <time.h> #include <stdlib.h> #include "pvfs2.h" #include "str-utils.h" #include "pint-sysint-utils.h" #ifndef PVFS2_VERSION #define PVFS2_VERSION "Unknown" #endif #define VALBUFSZ 1024 #ifndef NUM_KEYS_PER_REQUEST #define NUM_KEYS_PER_REQUEST 10 #endif /* optional parameters, filled in by parse_args() */ struct options { int nkey; PVFS_ds_keyval *key; int target_count; char** destfiles; }; static struct options* parse_args(int argc, char* argv[]); int pvfs2_listeattr (int nkey, PVFS_ds_keyval *key_p, char *destfile); static void usage(int argc, char** argv); int check_perm(char c); int main(int argc, char **argv) { int ret = 0; struct options* user_opts = NULL; int i, k; /* look at command line arguments */ user_opts = parse_args(argc, argv); if(!user_opts) { fprintf(stderr, "Error: failed to parse " "command line arguments.\n"); return(-1); } ret = PVFS_util_init_defaults(); if(ret < 0) { PVFS_perror("PVFS_util_init_defaults", ret); return(-1); } /* * for each file the user specified * for each file the user specified */ for (i = 0; i < user_opts->target_count; i++) { ret = pvfs2_listeattr(user_opts->nkey, user_opts->key, user_opts->destfiles[i]); if (ret < 0) { printf("listeattr returned error code - exiting\n"); break; } printf("listeattr returned %d keys\n", ret); for (k = 0; k < (user_opts->nkey ? ret : 0); k++) { printf("key[%d]:%s\n",k, (char *)user_opts->key[k].buffer); } /* TODO: need to free the request descriptions */ } PVFS_sys_finalize(); return(ret); } /* pvfs2_listeattr() * * Retrieves the list of keys for a particular object! * returns # of keys read successfully on success and negative one on failure */ int pvfs2_listeattr(int nkey, PVFS_ds_keyval *key_p, char *destfile) { int ret = -1; char str_buf[PVFS_NAME_MAX] = {0}; char pvfs_path[PVFS_NAME_MAX] = {0}; PVFS_fs_id cur_fs; PVFS_sysresp_lookup resp_lookup; PVFS_sysresp_listeattr resp_listeattr; PVFS_object_ref parent_ref; PVFS_credentials credentials; PVFS_ds_position token = PVFS_ITERATE_START; /* translate local path into pvfs2 relative path */ ret = PVFS_util_resolve(destfile,&cur_fs, pvfs_path, PVFS_NAME_MAX); if(ret < 0) { PVFS_perror("PVFS_util_resolve", ret); return -1; } PVFS_util_gen_credentials(&credentials); /* this if-else statement just pulls apart the pathname into its * parts....I think...this should be a function somewhere */ if (strcmp(pvfs_path,"/") == 0) { memset(&resp_lookup, 0, sizeof(PVFS_sysresp_lookup)); ret = PVFS_sys_lookup(cur_fs, pvfs_path, &credentials, &resp_lookup, PVFS2_LOOKUP_LINK_FOLLOW, NULL); if (ret < 0) { PVFS_perror("PVFS_sys_lookup", ret); return -1; } parent_ref.handle = resp_lookup.ref.handle; parent_ref.fs_id = resp_lookup.ref.fs_id; } else { /* get the absolute path on the pvfs2 file system */ if (PINT_remove_base_dir(pvfs_path,str_buf,PVFS_NAME_MAX)) { if (pvfs_path[0] != '/') { fprintf(stderr, "Error: poorly formatted path.\n"); } fprintf(stderr, "Error: cannot retrieve entry name for " "creation on %s\n",pvfs_path); return -1; } ret = PINT_lookup_parent(pvfs_path, cur_fs, &credentials, &parent_ref.handle); if(ret < 0) { PVFS_perror("PINT_lookup_parent", ret); return -1; } else { parent_ref.fs_id = cur_fs; } } memset(&resp_lookup, 0, sizeof(PVFS_sysresp_lookup)); ret = PVFS_sys_ref_lookup(parent_ref.fs_id, str_buf, parent_ref, &credentials, &resp_lookup, PVFS2_LOOKUP_LINK_NO_FOLLOW, NULL); if (ret != 0) { fprintf(stderr, "Target '%s' does not exist!\n", str_buf); return -1; } /* list extended attribute */ resp_listeattr.key_array = key_p; ret = PVFS_sys_listeattr(resp_lookup.ref, token, nkey, &credentials, &resp_listeattr, NULL); if (ret < 0) { PVFS_perror("PVFS_sys_listeattr failed with errcode", ret); return(-1); } return resp_listeattr.nkey; } /* parse_args() * * parses command line arguments * * returns pointer to options structure on success, NULL on failure */ static struct options* parse_args(int argc, char* argv[]) { /* getopt stuff */ extern char* optarg; extern int optind, opterr, optopt; char flags[] = "n:v"; int one_opt = 0; int i, k; struct options* tmp_opts = NULL; /* create storage for the command line options */ tmp_opts = (struct options*)malloc(sizeof(struct options)); if(!tmp_opts){ return(NULL); } memset(tmp_opts, 0, sizeof(struct options)); /* fill in defaults */ tmp_opts->key = NULL; tmp_opts->nkey = 0; tmp_opts->target_count = 0; tmp_opts->destfiles = NULL; if (argc < 3) { usage(argc,argv); exit(0); } /* look at command line arguments */ while((one_opt = getopt(argc, argv, flags)) != EOF) { switch(one_opt){ case('n'): tmp_opts->nkey = atoi(optarg); break; case('v'): printf("%s\n", PVFS2_VERSION); exit(0); case('?'): printf("?\n"); usage(argc, argv); exit(EXIT_FAILURE); } } /* now malloc space for the keys */ tmp_opts->key = (PVFS_ds_keyval *) malloc(sizeof(PVFS_ds_keyval) * tmp_opts->nkey); /* now re-run the list and copy them in */ for (k = 0; k < tmp_opts->nkey; k++) { tmp_opts->key[k].buffer_sz = 256; tmp_opts->key[k].buffer = (char *)malloc(sizeof(char)*tmp_opts->key[k].buffer_sz); } tmp_opts->target_count = argc-optind; tmp_opts->destfiles=(char **)malloc(sizeof(char *)*(tmp_opts->target_count)); for (i = 0; i < tmp_opts->target_count; i++) { char *cur_arg_str = argv[optind+i]; int length = strlen(cur_arg_str); tmp_opts->destfiles[i] = (char *)malloc(sizeof(char)*(length+1)); strncpy(tmp_opts->destfiles[i],cur_arg_str,length+1); } return(tmp_opts); } static void usage(int argc, char** argv) { fprintf(stderr,"Usage: %s [-v] -n <# of keys> filename(s)\n",argv[0]); fprintf(stderr," -v - print program version and terminate.\n"); return; } /* * Local variables: * c-indent-level: 4 * c-basic-offset: 4 * End: * * vim: ts=8 sts=4 sw=4 expandtab */
lgpl-2.1
cicku/libproxy
libproxy/modules/pacrunner_natus.cpp
5
3390
/******************************************************************************* * libproxy - A library for proxy configuration * Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include "../extension_pacrunner.hpp" #include <unistd.h> // gethostname using namespace libproxy; #define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE #include <natus/natus.h> #include "pacutils.h" using namespace natus; static Value dnsResolve(Value& ths, Value& fnc, vector<Value>& arg) { Value exc = checkArguments(ths, arg, "s"); if (exc.isException()) return exc; // Look it up struct addrinfo *info; if (getaddrinfo(arg[0].toString().c_str(), NULL, NULL, &info)) return NULL; // Try for IPv4 char* tmp = new char[INET6_ADDRSTRLEN+1]; if (getnameinfo(info->ai_addr, info->ai_addrlen, tmp, INET6_ADDRSTRLEN+1, NULL, 0, NI_NUMERICHOST)) { freeaddrinfo(info); delete tmp; return NULL; } freeaddrinfo(info); // Create the return value Value ret = ths.newString(tmp); delete tmp; return ret; } static Value myIpAddress(Value& ths, Value& fnc, vector<Value>& arg) { char hostname[1024]; if (!gethostname(hostname, 1023)) { vector<Value> dnsargs; dnsargs.push_back(ths.newString(hostname)); return dnsResolve(ths, fnc, dnsargs); } return ths.newString("Unable to find hostname!").toException(); } class natus_pacrunner : public pacrunner { public: natus_pacrunner(string pac, const url& pacurl) throw (bad_alloc) : pacrunner(pac, pacurl) { Value exc; // Create the basic context if (!eng.initialize()) goto error; glb = this->eng.newGlobal(); if (glb.isException()) goto error; // Add dnsResolve into the context if (!glb.set("dnsResolve", glb.newFunction(dnsResolve))) goto error; // Add myIpAddress into the context if (!glb.set("myIpAddress", glb.newFunction(myIpAddress))) goto error; // Add all other routines into the context exc = glb.evaluate(JAVASCRIPT_ROUTINES); if (exc.isException()) goto error; // Add the PAC into the context exc = glb.evaluate(pac.c_str(), pacurl.to_string()); if (exc.isException()) goto error; return; error: throw bad_alloc(); } string run(const url& url_) throw (bad_alloc) { vector<Value> args; args.push_back(glb.newString(url_.to_string())); args.push_back(glb.newString(url_.get_host())); Value res = glb.call("FindProxyForURL", args); if (res.isString() && !res.isException()) return res.toString(); return ""; } private: Engine eng; Value glb; }; PX_PACRUNNER_MODULE_EZ(natus, "nt_engine_init", "natus");
lgpl-2.1
vrjuggler/vrjuggler
modules/vapor/vpr/Util/BadCastException.cpp
6
1777
/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2011 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <vpr/Util/BadCastException.h> namespace vpr { BadCastException::BadCastException(const std::string& msg, const std::string& location) throw () : vpr::Exception(msg, location) { /* Do nothing. */ ; } BadCastException::~BadCastException() throw () { /* Do nothing. */ ; } }
lgpl-2.1