repo_name
string
path
string
copies
string
size
string
content
string
license
string
sherpa/sherpa
extern/fftw-3.3.9/rdft/scalar/r2cb/r2cb_6.c
3
4469
/* * Copyright (c) 2003, 2007-14 Matteo Frigo * Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Thu Dec 10 07:06:25 EST 2020 */ #include "rdft/codelet-rdft.h" #if defined(ARCH_PREFERS_FMA) || defined(ISA_EXTENSION_PREFERS_FMA) /* Generated by: ../../../genfft/gen_r2cb.native -fma -compact -variables 4 -pipeline-latency 4 -sign 1 -n 6 -name r2cb_6 -include rdft/scalar/r2cb.h */ /* * This function contains 14 FP additions, 6 FP multiplications, * (or, 8 additions, 0 multiplications, 6 fused multiply/add), * 17 stack variables, 2 constants, and 12 memory accesses */ #include "rdft/scalar/r2cb.h" static void r2cb_6(R *R0, R *R1, R *Cr, R *Ci, stride rs, stride csr, stride csi, INT v, INT ivs, INT ovs) { DK(KP1_732050807, +1.732050807568877293527446341505872366942805254); DK(KP2_000000000, +2.000000000000000000000000000000000000000000000); { INT i; for (i = v; i > 0; i = i - 1, R0 = R0 + ovs, R1 = R1 + ovs, Cr = Cr + ivs, Ci = Ci + ivs, MAKE_VOLATILE_STRIDE(24, rs), MAKE_VOLATILE_STRIDE(24, csr), MAKE_VOLATILE_STRIDE(24, csi)) { E T3, T7, Tc, Te, T6, T8, T1, T2, T9, Td; T1 = Cr[0]; T2 = Cr[WS(csr, 3)]; T3 = T1 + T2; T7 = T1 - T2; { E Ta, Tb, T4, T5; Ta = Ci[WS(csi, 2)]; Tb = Ci[WS(csi, 1)]; Tc = Ta - Tb; Te = Ta + Tb; T4 = Cr[WS(csr, 2)]; T5 = Cr[WS(csr, 1)]; T6 = T4 + T5; T8 = T5 - T4; } R0[0] = FMA(KP2_000000000, T6, T3); R1[WS(rs, 1)] = FNMS(KP2_000000000, T8, T7); T9 = T3 - T6; R0[WS(rs, 2)] = FNMS(KP1_732050807, Tc, T9); R0[WS(rs, 1)] = FMA(KP1_732050807, Tc, T9); Td = T7 + T8; R1[0] = FNMS(KP1_732050807, Te, Td); R1[WS(rs, 2)] = FMA(KP1_732050807, Te, Td); } } } static const kr2c_desc desc = { 6, "r2cb_6", { 8, 0, 6, 0 }, &GENUS }; void X(codelet_r2cb_6) (planner *p) { X(kr2c_register) (p, r2cb_6, &desc); } #else /* Generated by: ../../../genfft/gen_r2cb.native -compact -variables 4 -pipeline-latency 4 -sign 1 -n 6 -name r2cb_6 -include rdft/scalar/r2cb.h */ /* * This function contains 14 FP additions, 4 FP multiplications, * (or, 12 additions, 2 multiplications, 2 fused multiply/add), * 17 stack variables, 2 constants, and 12 memory accesses */ #include "rdft/scalar/r2cb.h" static void r2cb_6(R *R0, R *R1, R *Cr, R *Ci, stride rs, stride csr, stride csi, INT v, INT ivs, INT ovs) { DK(KP2_000000000, +2.000000000000000000000000000000000000000000000); DK(KP1_732050807, +1.732050807568877293527446341505872366942805254); { INT i; for (i = v; i > 0; i = i - 1, R0 = R0 + ovs, R1 = R1 + ovs, Cr = Cr + ivs, Ci = Ci + ivs, MAKE_VOLATILE_STRIDE(24, rs), MAKE_VOLATILE_STRIDE(24, csr), MAKE_VOLATILE_STRIDE(24, csi)) { E T3, T7, Tc, Te, T6, T8, T1, T2, T9, Td; T1 = Cr[0]; T2 = Cr[WS(csr, 3)]; T3 = T1 - T2; T7 = T1 + T2; { E Ta, Tb, T4, T5; Ta = Ci[WS(csi, 2)]; Tb = Ci[WS(csi, 1)]; Tc = KP1_732050807 * (Ta - Tb); Te = KP1_732050807 * (Ta + Tb); T4 = Cr[WS(csr, 2)]; T5 = Cr[WS(csr, 1)]; T6 = T4 - T5; T8 = T4 + T5; } R1[WS(rs, 1)] = FMA(KP2_000000000, T6, T3); R0[0] = FMA(KP2_000000000, T8, T7); T9 = T7 - T8; R0[WS(rs, 2)] = T9 - Tc; R0[WS(rs, 1)] = T9 + Tc; Td = T3 - T6; R1[0] = Td - Te; R1[WS(rs, 2)] = Td + Te; } } } static const kr2c_desc desc = { 6, "r2cb_6", { 12, 2, 2, 0 }, &GENUS }; void X(codelet_r2cb_6) (planner *p) { X(kr2c_register) (p, r2cb_6, &desc); } #endif
gpl-3.0
SkyFireArchives/SkyFireEMU_420
src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp
3
16034
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/> * Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "gamePCH.h" /* ScriptData SDName: Npc_EscortAI SD%Complete: 100 SDComment: SDCategory: Npc EndScriptData */ #include "ScriptPCH.h" #include "ScriptedEscortAI.h" #include "Group.h" enum ePoints { POINT_LAST_POINT = 0xFFFFFF, POINT_HOME = 0xFFFFFE }; npc_escortAI::npc_escortAI(Creature* pCreature) : ScriptedAI(pCreature), m_uiPlayerGUID(0), m_uiWPWaitTimer(2500), m_uiPlayerCheckTimer(1000), m_uiEscortState(STATE_ESCORT_NONE), MaxPlayerDistance(DEFAULT_MAX_PLAYER_DISTANCE), m_pQuestForEscort(NULL), m_bIsActiveAttacker(true), m_bIsRunning(false), m_bCanInstantRespawn(false), m_bCanReturnToStart(false), DespawnAtEnd(true), DespawnAtFar(true), ScriptWP(false) {} void npc_escortAI::AttackStart(Unit* pWho) { if (!pWho) return; if (me->Attack(pWho, true)) { if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); if (IsCombatMovement()) me->GetMotionMaster()->MoveChase(pWho); } } //see followerAI bool npc_escortAI::AssistPlayerInCombat(Unit* pWho) { if (!pWho || !pWho->getVictim()) return false; //experimental (unknown) flag not present if (!(me->GetCreatureInfo()->type_flags & CREATURE_TYPEFLAGS_AID_PLAYERS)) return false; //not a player if (!pWho->getVictim()->GetCharmerOrOwnerPlayerOrPlayerItself()) return false; //never attack friendly if (me->IsFriendlyTo(pWho)) return false; //too far away and no free sight? if (me->IsWithinDistInMap(pWho, GetMaxPlayerDistance()) && me->IsWithinLOSInMap(pWho)) { //already fighting someone? if (!me->getVictim()) { AttackStart(pWho); return true; } else { pWho->SetInCombatWith(me); me->AddThreat(pWho, 0.0f); return true; } } return false; } void npc_escortAI::MoveInLineOfSight(Unit* pWho) { if (!me->HasUnitState(UNIT_STAT_STUNNED) && pWho->isTargetableForAttack() && pWho->isInAccessiblePlaceFor(me)) { if (HasEscortState(STATE_ESCORT_ESCORTING) && AssistPlayerInCombat(pWho)) return; if (!me->canFly() && me->GetDistanceZ(pWho) > CREATURE_Z_ATTACK_RANGE) return; if (me->IsHostileTo(pWho)) { float fAttackRadius = me->GetAttackDistance(pWho); if (me->IsWithinDistInMap(pWho, fAttackRadius) && me->IsWithinLOSInMap(pWho)) { if (!me->getVictim()) { pWho->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); AttackStart(pWho); } else if (me->GetMap()->IsDungeon()) { pWho->SetInCombatWith(me); me->AddThreat(pWho, 0.0f); } } } } } void npc_escortAI::JustDied(Unit* /*pKiller*/) { if (!HasEscortState(STATE_ESCORT_ESCORTING) || !m_uiPlayerGUID || !m_pQuestForEscort) return; if (Player* pPlayer = GetPlayerForEscort()) { if (Group* pGroup = pPlayer->GetGroup()) { for (GroupReference* pRef = pGroup->GetFirstMember(); pRef != NULL; pRef = pRef->next()) { if (Player* pMember = pRef->getSource()) { if (pMember->GetQuestStatus(m_pQuestForEscort->GetQuestId()) == QUEST_STATUS_INCOMPLETE) pMember->FailQuest(m_pQuestForEscort->GetQuestId()); } } } else { if (pPlayer->GetQuestStatus(m_pQuestForEscort->GetQuestId()) == QUEST_STATUS_INCOMPLETE) pPlayer->FailQuest(m_pQuestForEscort->GetQuestId()); } } } void npc_escortAI::JustRespawned() { m_uiEscortState = STATE_ESCORT_NONE; if (!IsCombatMovement()) SetCombatMovement(true); //add a small delay before going to first waypoint, normal in near all cases m_uiWPWaitTimer = 2500; if (me->getFaction() != me->GetCreatureInfo()->faction_A) me->RestoreFaction(); Reset(); } void npc_escortAI::ReturnToLastPoint() { float x, y, z, o; me->GetHomePosition(x, y, z, o); me->GetMotionMaster()->MovePoint(POINT_LAST_POINT, x, y, z); } void npc_escortAI::EnterEvadeMode() { me->RemoveAllAuras(); me->DeleteThreatList(); me->CombatStop(true); me->SetLootRecipient(NULL); if (HasEscortState(STATE_ESCORT_ESCORTING)) { AddEscortState(STATE_ESCORT_RETURNING); ReturnToLastPoint(); sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI (script: %s, creature entry: %u) has left combat and is now returning to last point"); } else { me->GetMotionMaster()->MoveTargetedHome(); Reset(); } } bool npc_escortAI::IsPlayerOrGroupInRange() { if (Player* pPlayer = GetPlayerForEscort()) { if (Group* pGroup = pPlayer->GetGroup()) { for (GroupReference* pRef = pGroup->GetFirstMember(); pRef != NULL; pRef = pRef->next()) { Player* pMember = pRef->getSource(); if (pMember && me->IsWithinDistInMap(pMember, GetMaxPlayerDistance())) { return true; break; } } } else { if (me->IsWithinDistInMap(pPlayer, GetMaxPlayerDistance())) return true; } } return false; } void npc_escortAI::UpdateAI(const uint32 uiDiff) { //Waypoint Updating if (HasEscortState(STATE_ESCORT_ESCORTING) && !me->getVictim() && m_uiWPWaitTimer && !HasEscortState(STATE_ESCORT_RETURNING)) { if (m_uiWPWaitTimer <= uiDiff) { //End of the line if (CurrentWP == WaypointList.end()) { if (DespawnAtEnd) { sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI reached end of waypoints"); if (m_bCanReturnToStart) { float fRetX, fRetY, fRetZ; me->GetRespawnCoord(fRetX, fRetY, fRetZ); me->GetMotionMaster()->MovePoint(POINT_HOME, fRetX, fRetY, fRetZ); m_uiWPWaitTimer = 0; sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI are returning home to spawn location: %u, %f, %f, %f", POINT_HOME, fRetX, fRetY, fRetZ); return; } if (m_bCanInstantRespawn) { me->setDeathState(JUST_DIED); me->Respawn(); } else me->ForcedDespawn(); return; } else { sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI reached end of waypoints with Despawn off"); return; } } if (!HasEscortState(STATE_ESCORT_PAUSED)) { me->GetMotionMaster()->MovePoint(CurrentWP->id, CurrentWP->x, CurrentWP->y, CurrentWP->z); sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI start waypoint %u (%f, %f, %f).", CurrentWP->id, CurrentWP->x, CurrentWP->y, CurrentWP->z); WaypointStart(CurrentWP->id); m_uiWPWaitTimer = 0; } } else m_uiWPWaitTimer -= uiDiff; } //Check if player or any member of his group is within range if (HasEscortState(STATE_ESCORT_ESCORTING) && m_uiPlayerGUID && !me->getVictim() && !HasEscortState(STATE_ESCORT_RETURNING)) { if (m_uiPlayerCheckTimer <= uiDiff) { if (DespawnAtFar && !IsPlayerOrGroupInRange()) { sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI failed because player/group was to far away or not found"); if (m_bCanInstantRespawn) { me->setDeathState(JUST_DIED); me->Respawn(); } else me->ForcedDespawn(); return; } m_uiPlayerCheckTimer = 1000; } else m_uiPlayerCheckTimer -= uiDiff; } UpdateEscortAI(uiDiff); } void npc_escortAI::UpdateEscortAI(const uint32 /*uiDiff*/) { if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } void npc_escortAI::MovementInform(uint32 uiMoveType, uint32 uiPointId) { if (uiMoveType != POINT_MOTION_TYPE || !HasEscortState(STATE_ESCORT_ESCORTING)) return; //Combat start position reached, continue waypoint movement if (uiPointId == POINT_LAST_POINT) { sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI has returned to original position before combat"); if (m_bIsRunning && me->HasUnitMovementFlag(MOVEMENTFLAG_WALKING)) me->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); else if (!m_bIsRunning && !me->HasUnitMovementFlag(MOVEMENTFLAG_WALKING)) me->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); RemoveEscortState(STATE_ESCORT_RETURNING); if (!m_uiWPWaitTimer) m_uiWPWaitTimer = 1; } else if (uiPointId == POINT_HOME) { sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI has returned to original home location and will continue from beginning of waypoint list."); CurrentWP = WaypointList.begin(); m_uiWPWaitTimer = 1; } else { //Make sure that we are still on the right waypoint if (CurrentWP->id != uiPointId) { sLog->outError("TSCR ERROR: EscortAI reached waypoint out of order %u, expected %u, creature entry %u", uiPointId, CurrentWP->id, me->GetEntry()); return; } sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI Waypoint %u reached", CurrentWP->id); //Call WP function WaypointReached(CurrentWP->id); m_uiWPWaitTimer = CurrentWP->WaitTimeMs + 1; ++CurrentWP; } } /* void npc_escortAI::OnPossess(bool apply) { // We got possessed in the middle of being escorted, store the point // where we left off to come back to when possess is removed if (HasEscortState(STATE_ESCORT_ESCORTING)) { if (apply) me->GetPosition(LastPos.x, LastPos.y, LastPos.z); else { Returning = true; me->GetMotionMaster()->MovementExpired(); me->GetMotionMaster()->MovePoint(WP_LAST_POINT, LastPos.x, LastPos.y, LastPos.z); } } } */ void npc_escortAI::AddWaypoint(uint32 id, float x, float y, float z, uint32 WaitTimeMs) { Escort_Waypoint t(id, x, y, z, WaitTimeMs); WaypointList.push_back(t); // i think SD2 no longer uses this function ScriptWP = true; /*PointMovement wp; wp.m_uiCreatureEntry = me->GetEntry(); wp.m_uiPointId = id; wp.m_fX = x; wp.m_fY = y; wp.m_fZ = z; wp.m_uiWaitTime = WaitTimeMs; PointMovementMap[wp.m_uiCreatureEntry].push_back(wp);*/ } void npc_escortAI::FillPointMovementListForCreature() { std::vector<ScriptPointMove> const &pPointsEntries = sScriptSystemMgr->GetPointMoveList(me->GetEntry()); if (pPointsEntries.empty()) return; std::vector<ScriptPointMove>::const_iterator itr; for (itr = pPointsEntries.begin(); itr != pPointsEntries.end(); ++itr) { Escort_Waypoint pPoint(itr->uiPointId, itr->fX, itr->fY, itr->fZ, itr->uiWaitTime); WaypointList.push_back(pPoint); } } void npc_escortAI::SetRun(bool bRun) { if (bRun) { if (!m_bIsRunning) me->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); else sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI attempt to set run mode, but is already running."); } else { if (m_bIsRunning) me->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); else sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI attempt to set walk mode, but is already walking."); } m_bIsRunning = bRun; } //TODO: get rid of this many variables passed in function. void npc_escortAI::Start(bool bIsActiveAttacker, bool bRun, uint64 uiPlayerGUID, const Quest* pQuest, bool bInstantRespawn, bool bCanLoopPath) { if (me->getVictim()) { sLog->outError("TSCR ERROR: EscortAI (script: %s, creature entry: %u) attempts to Start while in combat", me->GetScriptName().c_str(), me->GetEntry()); return; } if (HasEscortState(STATE_ESCORT_ESCORTING)) { sLog->outError("TSCR: EscortAI (script: %s, creature entry: %u) attempts to Start while already escorting", me->GetScriptName().c_str(), me->GetEntry()); return; } if (!ScriptWP) // sd2 never adds wp in script, but tc does { if (!WaypointList.empty()) WaypointList.clear(); FillPointMovementListForCreature(); } if (WaypointList.empty()) { sLog->outErrorDb("TSCR: EscortAI (script: %s, creature entry: %u) starts with 0 waypoints (possible missing entry in script_waypoint. Quest: %u).", me->GetScriptName().c_str(), me->GetEntry(), pQuest ? pQuest->GetQuestId() : 0); return; } //set variables m_bIsActiveAttacker = bIsActiveAttacker; m_bIsRunning = bRun; m_uiPlayerGUID = uiPlayerGUID; m_pQuestForEscort = pQuest; m_bCanInstantRespawn = bInstantRespawn; m_bCanReturnToStart = bCanLoopPath; if (m_bCanReturnToStart && m_bCanInstantRespawn) sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI is set to return home after waypoint end and instant respawn at waypoint end. Creature will never despawn."); if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE) { me->GetMotionMaster()->MovementExpired(); me->GetMotionMaster()->MoveIdle(); sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI start with WAYPOINT_MOTION_TYPE, changed to MoveIdle."); } //disable npcflags me->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); sLog->outDebug(LOG_FILTER_TSCR, "TSCR: EscortAI started with " UI64FMTD " waypoints. ActiveAttacker = %d, Run = %d, PlayerGUID = " UI64FMTD "", uint64(WaypointList.size()), m_bIsActiveAttacker, m_bIsRunning, m_uiPlayerGUID); CurrentWP = WaypointList.begin(); //Set initial speed if (m_bIsRunning) me->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); else me->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); AddEscortState(STATE_ESCORT_ESCORTING); } void npc_escortAI::SetEscortPaused(bool bPaused) { if (!HasEscortState(STATE_ESCORT_ESCORTING)) return; if (bPaused) AddEscortState(STATE_ESCORT_PAUSED); else RemoveEscortState(STATE_ESCORT_PAUSED); }
gpl-3.0
Shmoopty/daphne-pi
src/sdl_mods/sdl-1.2.13/SDL_yuv.c
3
4586
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2006 Sam Lantinga 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 St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" /* This is the implementation of the YUV video surface support */ #include "SDL_video.h" #include "SDL_sysvideo.h" #include "SDL_yuvfuncs.h" #include "SDL_yuv_sw_c.h" unsigned int IsVistaOrNewer() { unsigned int uRes = 0; OSVERSIONINFOEX osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); // if function succeeds if (GetVersionEx((OSVERSIONINFO *) &osvi)) { if (osvi.dwMajorVersion >= 6) { uRes = 1; } } return uRes; } SDL_Overlay *SDL_CreateYUVOverlay(int w, int h, Uint32 format, SDL_Surface *display) { SDL_VideoDevice *video = current_video; SDL_VideoDevice *this = current_video; const char *yuv_hwaccel; SDL_Overlay *overlay; if ( (display->flags & SDL_OPENGL) == SDL_OPENGL ) { SDL_SetError("YUV overlays are not supported in OpenGL mode"); return NULL; } /* Display directly on video surface, if possible */ if ( SDL_getenv("SDL_VIDEO_YUV_DIRECT") ) { if ( (display == SDL_PublicSurface) && ((SDL_VideoSurface->format->BytesPerPixel == 2) || (SDL_VideoSurface->format->BytesPerPixel == 4)) ) { display = SDL_VideoSurface; } } overlay = NULL; // start MPO // YUV HW overlays are broken on Vista and newer, so only create them if this our OS is older than Vista. if (!IsVistaOrNewer()) { yuv_hwaccel = SDL_getenv("SDL_VIDEO_YUV_HWACCEL"); if ( ((display == SDL_VideoSurface) && video->CreateYUVOverlay) && (!yuv_hwaccel || (SDL_atoi(yuv_hwaccel) > 0)) ) { overlay = video->CreateYUVOverlay(this, w, h, format, display); } } // end MPO /* If hardware YUV overlay failed ... */ if ( overlay == NULL ) { overlay = SDL_CreateYUV_SW(this, w, h, format, display); } return overlay; } int SDL_LockYUVOverlay(SDL_Overlay *overlay) { if ( overlay == NULL ) { SDL_SetError("Passed NULL overlay"); return -1; } return overlay->hwfuncs->Lock(current_video, overlay); } void SDL_UnlockYUVOverlay(SDL_Overlay *overlay) { if ( overlay == NULL ) { return; } overlay->hwfuncs->Unlock(current_video, overlay); } int SDL_DisplayYUVOverlay(SDL_Overlay *overlay, SDL_Rect *dstrect) { SDL_Rect src, dst; int srcx, srcy, srcw, srch; int dstx, dsty, dstw, dsth; if ( overlay == NULL || dstrect == NULL ) { SDL_SetError("Passed NULL overlay or dstrect"); return -1; } /* Clip the rectangle to the screen area */ srcx = 0; srcy = 0; srcw = overlay->w; srch = overlay->h; dstx = dstrect->x; dsty = dstrect->y; dstw = dstrect->w; dsth = dstrect->h; if ( dstx < 0 ) { srcw += (dstx * overlay->w) / dstrect->w; dstw += dstx; srcx -= (dstx * overlay->w) / dstrect->w; dstx = 0; } if ( (dstx+dstw) > current_video->screen->w ) { int extra = (dstx+dstw - current_video->screen->w); srcw -= (extra * overlay->w) / dstrect->w; dstw -= extra; } if ( dsty < 0 ) { srch += (dsty * overlay->h) / dstrect->h; dsth += dsty; srcy -= (dsty * overlay->h) / dstrect->h; dsty = 0; } if ( (dsty+dsth) > current_video->screen->h ) { int extra = (dsty+dsth - current_video->screen->h); srch -= (extra * overlay->h) / dstrect->h; dsth -= extra; } if ( srcw <= 0 || srch <= 0 || srch <= 0 || dsth <= 0 ) { return 0; } /* Ugh, I can't wait for SDL_Rect to be int values */ src.x = srcx; src.y = srcy; src.w = srcw; src.h = srch; dst.x = dstx; dst.y = dsty; dst.w = dstw; dst.h = dsth; return overlay->hwfuncs->Display(current_video, overlay, &src, &dst); } void SDL_FreeYUVOverlay(SDL_Overlay *overlay) { if ( overlay == NULL ) { return; } if ( overlay->hwfuncs ) { overlay->hwfuncs->FreeHW(current_video, overlay); } SDL_free(overlay); }
gpl-3.0
luisvt/xuggle-xuggler
captive/ffmpeg/csrc/libavfilter/vf_setpts.c
4
5008
/* * Copyright (c) 2010 Stefano Sabatini * Copyright (c) 2008 Victor Paesa * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * video presentation timestamp (PTS) modification filter */ /* #define DEBUG */ #include "libavutil/eval.h" #include "libavutil/mathematics.h" #include "avfilter.h" static const char *const var_names[] = { "INTERLACED", ///< tell if the current frame is interlaced "N", ///< frame number (starting at zero) "POS", ///< original position in the file of the frame "PREV_INPTS", ///< previous input PTS "PREV_OUTPTS", ///< previous output PTS "PTS", ///< original pts in the file of the frame "STARTPTS", ///< PTS at start of movie "TB", ///< timebase NULL }; enum var_name { VAR_INTERLACED, VAR_N, VAR_POS, VAR_PREV_INPTS, VAR_PREV_OUTPTS, VAR_PTS, VAR_STARTPTS, VAR_TB, VAR_VARS_NB }; typedef struct { AVExpr *expr; double var_values[VAR_VARS_NB]; } SetPTSContext; static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque) { SetPTSContext *setpts = ctx->priv; int ret; if ((ret = av_expr_parse(&setpts->expr, args ? args : "PTS", var_names, NULL, NULL, NULL, NULL, 0, ctx)) < 0) { av_log(ctx, AV_LOG_ERROR, "Error while parsing expression '%s'\n", args); return ret; } setpts->var_values[VAR_N ] = 0.0; setpts->var_values[VAR_PREV_INPTS ] = NAN; setpts->var_values[VAR_PREV_OUTPTS] = NAN; setpts->var_values[VAR_STARTPTS ] = NAN; return 0; } static int config_input(AVFilterLink *inlink) { SetPTSContext *setpts = inlink->dst->priv; setpts->var_values[VAR_TB] = av_q2d(inlink->time_base); av_log(inlink->src, AV_LOG_INFO, "TB:%f\n", setpts->var_values[VAR_TB]); return 0; } #define D2TS(d) (isnan(d) ? AV_NOPTS_VALUE : (int64_t)(d)) #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts)) static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref) { SetPTSContext *setpts = inlink->dst->priv; double d; AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0); if (isnan(setpts->var_values[VAR_STARTPTS])) setpts->var_values[VAR_STARTPTS] = TS2D(inpicref->pts); setpts->var_values[VAR_INTERLACED] = inpicref->video->interlaced; setpts->var_values[VAR_PTS ] = TS2D(inpicref->pts); setpts->var_values[VAR_POS ] = inpicref->pos == -1 ? NAN : inpicref->pos; d = av_expr_eval(setpts->expr, setpts->var_values, NULL); outpicref->pts = D2TS(d); #ifdef DEBUG av_log(inlink->dst, AV_LOG_DEBUG, "n:%"PRId64" interlaced:%d pos:%"PRId64" pts:%"PRId64" t:%f -> pts:%"PRId64" t:%f\n", (int64_t)setpts->var_values[VAR_N], (int)setpts->var_values[VAR_INTERLACED], inpicref ->pos, inpicref ->pts, inpicref ->pts * av_q2d(inlink->time_base), outpicref->pts, outpicref->pts * av_q2d(inlink->time_base)); #endif setpts->var_values[VAR_N] += 1.0; setpts->var_values[VAR_PREV_INPTS ] = TS2D(inpicref ->pts); setpts->var_values[VAR_PREV_OUTPTS] = TS2D(outpicref->pts); avfilter_start_frame(inlink->dst->outputs[0], outpicref); } static av_cold void uninit(AVFilterContext *ctx) { SetPTSContext *setpts = ctx->priv; av_expr_free(setpts->expr); setpts->expr = NULL; } AVFilter avfilter_vf_setpts = { .name = "setpts", .description = NULL_IF_CONFIG_SMALL("Set PTS for the output video frame."), .init = init, .uninit = uninit, .priv_size = sizeof(SetPTSContext), .inputs = (const AVFilterPad[]) {{ .name = "default", .type = AVMEDIA_TYPE_VIDEO, .get_video_buffer = avfilter_null_get_video_buffer, .config_props = config_input, .start_frame = start_frame, }, { .name = NULL }}, .outputs = (const AVFilterPad[]) {{ .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { .name = NULL}}, };
gpl-3.0
fqez/JdeRobot
src/drivers/openniServer/OpenNiServerLib/PointCloudServer.cpp
4
6457
// // Created by frivas on 25/01/17. // #include "PointCloudServer.h" namespace openniServer { PointCloudServer::PointCloudServer(std::string &propertyPrefix, const Ice::PropertiesPtr propIn,ConcurrentDevicePtr device) : prefix(propertyPrefix), data(new jderobot::pointCloudData()), device(device) { Ice::PropertiesPtr prop = propIn; int fps = prop->getPropertyAsIntWithDefault("openniServer.pointCloud.Fps", 10); bool extra = (bool) prop->getPropertyAsIntWithDefault("openniServer.ExtraCalibration", 0); replyCloud = new ReplyCloud(this, device, prop->getProperty("openniServer.calibration"), fps, extra); this->control = replyCloud->start(); } PointCloudServer::~PointCloudServer() { LOG(INFO) << "Stopping and joining thread for pointCloud"; replyCloud->destroy(); this->control.join(); } jderobot::pointCloudDataPtr PointCloudServer::getCloudData(const Ice::Current &) { data = replyCloud->getCloud(); return data; } PointCloudServer::ReplyCloud::ReplyCloud(PointCloudServer *pcloud, ConcurrentDevicePtr device, std::string calibration_filepath, int fpsIn, bool extra_calibration): myCloud(pcloud), device(device), mypro(NULL), calibration_filepath(calibration_filepath), fps(fpsIn), temporalData(new jderobot::pointCloudData()), stableData(new jderobot::pointCloudData()), returnData(new jderobot::pointCloudData()), withExtraCalibration(extra_calibration), _done(false) { this->cameraSize=cv::Size(device->getVideoMode().witdh,device->getVideoMode().heigth); LOG(INFO) << "Working with: " << device->getVideoMode().witdh << " x " <<device->getVideoMode().heigth; } void PointCloudServer::ReplyCloud::run() { while (this->cameraSize == cv::Size(0,0)){ LOG(WARNING) << "Trying to get valid videoMode"; this->cameraSize=cv::Size(device->getVideoMode().witdh,device->getVideoMode().heigth); sleep(1); } mypro = new openniServer::myprogeo(1, this->cameraSize.width, this->cameraSize.height); mypro->load_cam((char *) this->calibration_filepath.c_str(), 0, this->cameraSize.width, this->cameraSize.height, withExtraCalibration); int cycle; // duración del ciclo cycle = (float) (1 / (float) fps) * 1000000; IceUtil::Time lastIT = IceUtil::Time::now(); while (!(_done)) { float distance; //creamos una copia local de la imagen de color y de las distancias. cv::Mat localRGB = this->device->getRGBImage(); std::vector<int> localDistance; this->device->getDistances(localDistance); int step; if (this->cameraSize.width<=320){ step=9; } else{ step=18; } temporalData->p.clear(); for (unsigned int i = 0; (i < (unsigned int) (this->cameraSize.width * this->cameraSize.height)) && (localDistance.size() > 0); i +=step) { distance = (float) localDistance[i]; if (distance != 0) { float xp, yp, zp, camx, camy, camz; float ux, uy, uz; float x, y; float k; float c1x, c1y, c1z; float fx, fy, fz; float fmod; float t; float Fx, Fy, Fz; mypro->mybackproject(i % this->cameraSize.width, i / this->cameraSize.width, &xp, &yp, &zp, &camx, &camy, &camz, 0); //vector unitario float modulo; modulo = sqrt(1 / (((camx - xp) * (camx - xp)) + ((camy - yp) * (camy - yp)) + ((camz - zp) * (camz - zp)))); mypro->mygetcamerafoa(&c1x, &c1y, &c1z, 0); fmod = sqrt(1 / (((camx - c1x) * (camx - c1x)) + ((camy - c1y) * (camy - c1y)) + ((camz - c1z) * (camz - c1z)))); fx = (c1x - camx) * fmod; fy = (c1y - camy) * fmod; fz = (c1z - camz) * fmod; ux = (xp - camx) * modulo; uy = (yp - camy) * modulo; uz = (zp - camz) * modulo; Fx = distance * fx + camx; Fy = distance * fy + camy; Fz = distance * fz + camz; // calculamos el punto real t = (-(fx * camx) + (fx * Fx) - (fy * camy) + (fy * Fy) - (fz * camz) + (fz * Fz)) / ((fx * ux) + (fy * uy) + (fz * uz)); auxP.x = t * ux + camx; auxP.y = t * uy + camy; auxP.z = t * uz + camz; if (withExtraCalibration) { mypro->applyExtraCalibration(&auxP.x, &auxP.y, &auxP.z); } if (localRGB.rows != 0) { auxP.r = (float) (int) (unsigned char) localRGB.data[3 * i]; auxP.g = (float) (int) (unsigned char) localRGB.data[3 * i + 1]; auxP.b = (float) (int) (unsigned char) localRGB.data[3 * i + 2]; } temporalData->p.push_back(auxP); } //} } this->mutex.lock(); this->stableData->p= this->temporalData->p; this->mutex.unlock(); int delay = IceUtil::Time::now().toMicroSeconds() - lastIT.toMicroSeconds(); if (delay > cycle) { DLOG(WARNING) << "-------- openniServer: POINTCLOUD openni timeout-"; } else { if (delay < 1 || delay > cycle) delay = 1; usleep(delay); } lastIT = IceUtil::Time::now(); } } jderobot::pointCloudDataPtr PointCloudServer::ReplyCloud::getCloud() { this->mutex.lock(); this->returnData->p = this->stableData->p; this->mutex.unlock(); return this->returnData; } void PointCloudServer::ReplyCloud::destroy() { this->_done = true; } }
gpl-3.0
cnoviello/mastering-stm32
nucleo-f070RB/system/src/stm32f0xx/stm32f0xx_ll_usart.c
5
21110
/** ****************************************************************************** * @file stm32f0xx_ll_usart.c * @author MCD Application Team * @version V1.4.0 * @date 27-May-2016 * @brief USART LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_ll_usart.h" #include "stm32f0xx_ll_rcc.h" #include "stm32f0xx_ll_bus.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F0xx_LL_Driver * @{ */ #if defined (USART1) || defined (USART2) || defined (USART3) || defined (USART4) || defined (USART5) || defined (USART6) || defined (USART7) || defined (USART8) /** @addtogroup USART_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @addtogroup USART_LL_Private_Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup USART_LL_Private_Macros * @{ */ /* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available * divided by the smallest oversampling used on the USART (i.e. 8) */ #define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 6000000U) #define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \ || ((__VALUE__) == LL_USART_DIRECTION_RX) \ || ((__VALUE__) == LL_USART_DIRECTION_TX) \ || ((__VALUE__) == LL_USART_DIRECTION_TX_RX)) #define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \ || ((__VALUE__) == LL_USART_PARITY_EVEN) \ || ((__VALUE__) == LL_USART_PARITY_ODD)) #if defined(USART_7BITS_SUPPORT) #define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_7B) \ || ((__VALUE__) == LL_USART_DATAWIDTH_8B) \ || ((__VALUE__) == LL_USART_DATAWIDTH_9B)) #else #define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_8B) \ || ((__VALUE__) == LL_USART_DATAWIDTH_9B)) #endif #define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \ || ((__VALUE__) == LL_USART_OVERSAMPLING_8)) #define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \ || ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT)) #define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \ || ((__VALUE__) == LL_USART_PHASE_2EDGE)) #define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \ || ((__VALUE__) == LL_USART_POLARITY_HIGH)) #define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \ || ((__VALUE__) == LL_USART_CLOCK_ENABLE)) #if defined(USART_SMARTCARD_SUPPORT) #define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \ || ((__VALUE__) == LL_USART_STOPBITS_1) \ || ((__VALUE__) == LL_USART_STOPBITS_1_5) \ || ((__VALUE__) == LL_USART_STOPBITS_2)) #else #define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_1) \ || ((__VALUE__) == LL_USART_STOPBITS_2)) #endif #define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \ || ((__VALUE__) == LL_USART_HWCONTROL_RTS) \ || ((__VALUE__) == LL_USART_HWCONTROL_CTS) \ || ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup USART_LL_Exported_Functions * @{ */ /** @addtogroup USART_LL_EF_Init * @{ */ /** * @brief De-initialize USART registers (Registers restored to their default values). * @param USARTx USART Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: USART registers are de-initialized * - ERROR: USART registers are not de-initialized */ ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_UART_INSTANCE(USARTx)); if (USARTx == USART1) { /* Force reset of USART clock */ LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_USART1); /* Release reset of USART clock */ LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_USART1); } #if defined(USART2) else if (USARTx == USART2) { /* Force reset of USART clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2); /* Release reset of USART clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2); } #endif /* USART2 */ #if defined(USART3) else if (USARTx == USART3) { /* Force reset of USART clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3); /* Release reset of USART clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3); } #endif /* USART3 */ #if defined(USART4) else if (USARTx == USART4) { /* Force reset of USART clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART4); /* Release reset of USART clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART4); } #endif /* USART4 */ #if defined(USART5) else if (USARTx == USART5) { /* Force reset of USART clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART5); /* Release reset of USART clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART5); } #endif /* USART5 */ #if defined(USART6) else if (USARTx == USART6) { /* Force reset of USART clock */ LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_USART6); /* Release reset of USART clock */ LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_USART6); } #endif /* USART6 */ #if defined(USART7) else if (USARTx == USART7) { /* Force reset of USART clock */ LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_USART7); /* Release reset of USART clock */ LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_USART7); } #endif /* USART7 */ #if defined(USART8) else if (USARTx == USART8) { /* Force reset of USART clock */ LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_USART8); /* Release reset of USART clock */ LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_USART8); } #endif /* USART8 */ else { status = ERROR; } return (status); } /** * @brief Initialize USART registers according to the specified * parameters in USART_InitStruct. * @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0), * USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. * @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0). * @param USARTx USART Instance * @param USART_InitStruct: pointer to a LL_USART_InitTypeDef structure * that contains the configuration information for the specified USART peripheral. * @retval An ErrorStatus enumeration value: * - SUCCESS: USART registers are initialized according to USART_InitStruct content * - ERROR: Problem occurred during USART Registers initialization */ ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct) { ErrorStatus status = ERROR; uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO; #if defined(STM32F030x8) || defined(STM32F030xC) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F051x8) || defined(STM32F058xx) || defined(STM32F070x6) || defined(STM32F070xB) || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) LL_RCC_ClocksTypeDef RCC_Clocks; #endif /* Check the parameters */ assert_param(IS_UART_INSTANCE(USARTx)); assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate)); assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth)); assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits)); assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity)); assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection)); assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl)); assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling)); /* USART needs to be in disabled state, in order to be able to configure some bits in CRx registers */ if (LL_USART_IsEnabled(USARTx) == 0U) { /*---------------------------- USART CR1 Configuration ----------------------- * Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters: * - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value * - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value * - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value * - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value. */ MODIFY_REG(USARTx->CR1, (USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8), (USART_InitStruct->DataWidth | USART_InitStruct->Parity | USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling)); /*---------------------------- USART CR2 Configuration ----------------------- * Configure USARTx CR2 (Stop bits) with parameters: * - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value. * - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit(). */ LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits); /*---------------------------- USART CR3 Configuration ----------------------- * Configure USARTx CR3 (Hardware Flow Control) with parameters: * - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to USART_InitStruct->HardwareFlowControl value. */ LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl); /*---------------------------- USART BRR Configuration ----------------------- * Retrieve Clock frequency used for USART Peripheral */ if (USARTx == USART1) { periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE); } #if defined(USART2) else if (USARTx == USART2) { #if defined (RCC_CFGR3_USART2SW) periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART2_CLKSOURCE); #else /* USART2 clock is PCLK */ LL_RCC_GetSystemClocksFreq(&RCC_Clocks); periphclk = RCC_Clocks.PCLK1_Frequency; #endif } #endif /* USART2 */ #if defined(USART3) else if (USARTx == USART3) { #if defined (RCC_CFGR3_USART3SW) periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART3_CLKSOURCE); #else /* USART3 clock is PCLK */ LL_RCC_GetSystemClocksFreq(&RCC_Clocks); periphclk = RCC_Clocks.PCLK1_Frequency; #endif } #endif /* USART3 */ #if defined(USART4) else if (USARTx == USART4) { /* USART4 clock is PCLK */ LL_RCC_GetSystemClocksFreq(&RCC_Clocks); periphclk = RCC_Clocks.PCLK1_Frequency; } #endif /* USART4 */ #if defined(USART5) else if (USARTx == USART5) { /* USART5 clock is PCLK */ LL_RCC_GetSystemClocksFreq(&RCC_Clocks); periphclk = RCC_Clocks.PCLK1_Frequency; } #endif /* USART5 */ #if defined(USART6) else if (USARTx == USART6) { /* USART6 clock is PCLK */ LL_RCC_GetSystemClocksFreq(&RCC_Clocks); periphclk = RCC_Clocks.PCLK1_Frequency; } #endif /* USART6 */ #if defined(USART7) else if (USARTx == USART7) { /* USART7 clock is PCLK */ LL_RCC_GetSystemClocksFreq(&RCC_Clocks); periphclk = RCC_Clocks.PCLK1_Frequency; } #endif /* USART7 */ #if defined(USART8) else if (USARTx == USART8) { /* USART8 clock is PCLK */ LL_RCC_GetSystemClocksFreq(&RCC_Clocks); periphclk = RCC_Clocks.PCLK1_Frequency; } #endif /* USART8 */ else { /* Nothing to do, as error code is already assigned to ERROR value */ } /* Configure the USART Baud Rate : - valid baud rate value (different from 0) is required - Peripheral clock as returned by RCC service, should be valid (different from 0). */ if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO) && (USART_InitStruct->BaudRate != 0U)) { status = SUCCESS; LL_USART_SetBaudRate(USARTx, periphclk, USART_InitStruct->OverSampling, USART_InitStruct->BaudRate); } } /* Endif (=> USART not in Disabled state => return ERROR) */ return (status); } /** * @brief Set each @ref LL_USART_InitTypeDef field to default value. * @param USART_InitStruct: pointer to a @ref LL_USART_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct) { /* Set USART_InitStruct fields to default values */ USART_InitStruct->BaudRate = 9600U; USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B; USART_InitStruct->StopBits = LL_USART_STOPBITS_1; USART_InitStruct->Parity = LL_USART_PARITY_NONE ; USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX; USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE; USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16; } /** * @brief Initialize USART Clock related settings according to the * specified parameters in the USART_ClockInitStruct. * @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0), * USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. * @param USARTx USART Instance * @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure * that contains the Clock configuration information for the specified USART peripheral. * @retval An ErrorStatus enumeration value: * - SUCCESS: USART registers related to Clock settings are initialized according to USART_ClockInitStruct content * - ERROR: Problem occurred during USART Registers initialization */ ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct) { ErrorStatus status = SUCCESS; /* Check USART Instance and Clock signal output parameters */ assert_param(IS_UART_INSTANCE(USARTx)); assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput)); /* USART needs to be in disabled state, in order to be able to configure some bits in CRx registers */ if (LL_USART_IsEnabled(USARTx) == 0U) { /*---------------------------- USART CR2 Configuration -----------------------*/ /* If Clock signal has to be output */ if (USART_ClockInitStruct->ClockOutput == LL_USART_CLOCK_DISABLE) { /* Deactivate Clock signal delivery : * - Disable Clock Output: USART_CR2_CLKEN cleared */ LL_USART_DisableSCLKOutput(USARTx); } else { /* Ensure USART instance is USART capable */ assert_param(IS_USART_INSTANCE(USARTx)); /* Check clock related parameters */ assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity)); assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase)); assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse)); /*---------------------------- USART CR2 Configuration ----------------------- * Configure USARTx CR2 (Clock signal related bits) with parameters: * - Enable Clock Output: USART_CR2_CLKEN set * - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value * - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value * - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value. */ MODIFY_REG(USARTx->CR2, USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL, USART_CR2_CLKEN | USART_ClockInitStruct->ClockPolarity | USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse); } } /* Else (USART not in Disabled state => return ERROR */ else { status = ERROR; } return (status); } /** * @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value. * @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct) { /* Set LL_USART_ClockInitStruct fields with default values */ USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE; USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */ USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */ USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */ } /** * @} */ /** * @} */ /** * @} */ #endif /* USART1 || USART2|| USART3 || USART4 || USART5 || USART6 || USART7 || USART8 */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
gpl-3.0
craftext/GNU-Coreutils--craftext-
src/nice.c
5
5948
/* nice -- run a program with modified niceness Copyright (C) 1990-2012 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/>. */ /* David MacKenzie <djm@gnu.ai.mit.edu> */ #include <config.h> #include <stdio.h> #include <getopt.h> #include <sys/types.h> #include "system.h" #if ! HAVE_NICE /* Include this after "system.h" so we're sure to have definitions (from time.h or sys/time.h) required for e.g. the ru_utime member. */ # include <sys/resource.h> #endif #include "error.h" #include "quote.h" #include "xstrtol.h" /* The official name of this program (e.g., no 'g' prefix). */ #define PROGRAM_NAME "nice" #define AUTHORS proper_name ("David MacKenzie") #if HAVE_NICE # define GET_NICENESS() nice (0) #else # define GET_NICENESS() getpriority (PRIO_PROCESS, 0) #endif #ifndef NZERO # define NZERO 20 #endif /* This is required for Darwin Kernel Version 7.7.0. */ #if NZERO == 0 # undef NZERO # define NZERO 20 #endif static struct option const longopts[] = { {"adjustment", required_argument, NULL, 'n'}, {GETOPT_HELP_OPTION_DECL}, {GETOPT_VERSION_OPTION_DECL}, {NULL, 0, NULL, 0} }; void usage (int status) { if (status != EXIT_SUCCESS) emit_try_help (); else { printf (_("Usage: %s [OPTION] [COMMAND [ARG]...]\n"), program_name); printf (_("\ Run COMMAND with an adjusted niceness, which affects process scheduling.\n\ With no COMMAND, print the current niceness. Nicenesses range from\n\ %d (most favorable scheduling) to %d (least favorable).\n\ \n\ -n, --adjustment=N add integer N to the niceness (default 10)\n\ "), - NZERO, NZERO - 1); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME); emit_ancillary_info (); } exit (status); } static bool perm_related_errno (int err) { return err == EACCES || err == EPERM; } int main (int argc, char **argv) { int current_niceness; int adjustment = 10; char const *adjustment_given = NULL; bool ok; int i; initialize_main (&argc, &argv); set_program_name (argv[0]); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); initialize_exit_failure (EXIT_CANCELED); atexit (close_stdout); for (i = 1; i < argc; /* empty */) { char const *s = argv[i]; if (s[0] == '-' && ISDIGIT (s[1 + (s[1] == '-' || s[1] == '+')])) { adjustment_given = s + 1; ++i; } else { int c; int fake_argc = argc - (i - 1); char **fake_argv = argv + (i - 1); /* Ensure that any getopt diagnostics use the right name. */ fake_argv[0] = argv[0]; /* Initialize getopt_long's internal state. */ optind = 0; c = getopt_long (fake_argc, fake_argv, "+n:", longopts, NULL); i += optind - 1; switch (c) { case 'n': adjustment_given = optarg; break; case -1: break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: usage (EXIT_CANCELED); break; } if (c == -1) break; } } if (adjustment_given) { /* If the requested adjustment is outside the valid range, silently bring it to just within range; this mimics what "setpriority" and "nice" do. */ enum { MIN_ADJUSTMENT = 1 - 2 * NZERO, MAX_ADJUSTMENT = 2 * NZERO - 1 }; long int tmp; if (LONGINT_OVERFLOW < xstrtol (adjustment_given, NULL, 10, &tmp, "")) error (EXIT_CANCELED, 0, _("invalid adjustment %s"), quote (adjustment_given)); adjustment = MAX (MIN_ADJUSTMENT, MIN (tmp, MAX_ADJUSTMENT)); } if (i == argc) { if (adjustment_given) { error (0, 0, _("a command must be given with an adjustment")); usage (EXIT_CANCELED); } /* No command given; print the niceness. */ errno = 0; current_niceness = GET_NICENESS (); if (current_niceness == -1 && errno != 0) error (EXIT_CANCELED, errno, _("cannot get niceness")); printf ("%d\n", current_niceness); exit (EXIT_SUCCESS); } errno = 0; #if HAVE_NICE ok = (nice (adjustment) != -1 || errno == 0); #else current_niceness = GET_NICENESS (); if (current_niceness == -1 && errno != 0) error (EXIT_CANCELED, errno, _("cannot get niceness")); ok = (setpriority (PRIO_PROCESS, 0, current_niceness + adjustment) == 0); #endif if (!ok) { error (perm_related_errno (errno) ? 0 : EXIT_CANCELED, errno, _("cannot set niceness")); /* error() flushes stderr, but does not check for write failure. Normally, we would catch this via our atexit() hook of close_stdout, but execvp() gets in the way. If stderr encountered a write failure, there is no need to try calling error() again. */ if (ferror (stderr)) exit (EXIT_CANCELED); } execvp (argv[i], &argv[i]); { int exit_status = (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE); error (0, errno, "%s", argv[i]); exit (exit_status); } }
gpl-3.0
dsstest/Mojo-Tec-Skyfire-4.0.6a-
src/server/game/Tools/CharacterDatabaseCleaner.cpp
6
4730
/* * Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010-2011 Project SkyFire <http://www.projectskyfire.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "gamePCH.h" #include "Common.h" #include "CharacterDatabaseCleaner.h" #include "World.h" #include "Database/DatabaseEnv.h" #include "DBCStores.h" void CharacterDatabaseCleaner::CleanDatabase() { // config to disable if (!sWorld->getBoolConfig(CONFIG_CLEAN_CHARACTER_DB)) return; sLog->outString("Cleaning character database..."); uint32 oldMSTime = getMSTime(); // check flags which clean ups are necessary QueryResult result = CharacterDatabase.Query("SELECT value FROM worldstates WHERE entry = 20004"); if (!result) return; uint32 flags = (*result)[0].GetUInt32(); // clean up if (flags & CLEANING_FLAG_ACHIEVEMENT_PROGRESS) CleanCharacterAchievementProgress(); if (flags & CLEANING_FLAG_SKILLS) CleanCharacterSkills(); if (flags & CLEANING_FLAG_SPELLS) CleanCharacterSpell(); if (flags & CLEANING_FLAG_TALENTS) CleanCharacterTalent(); if (flags & CLEANING_FLAG_QUESTSTATUS) CleanCharacterQuestStatus(); // NOTE: In order to have persistentFlags be set in worldstates for the next cleanup, // you need to define them at least once in worldstates. flags &= sWorld->getIntConfig(CONFIG_PERSISTENT_CHARACTER_CLEAN_FLAGS); CharacterDatabase.DirectPExecute("UPDATE worldstates SET value = %u WHERE entry = 20004", flags); sWorld->SetCleaningFlags(flags); sLog->outString(">> Cleaned character database in %u ms", GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); } void CharacterDatabaseCleaner::CheckUnique(const char* column, const char* table, bool (*check)(uint32)) { QueryResult result = CharacterDatabase.PQuery("SELECT DISTINCT %s FROM %s", column, table); if (!result) { sLog->outString("Table %s is empty.", table); return; } bool found = false; std::ostringstream ss; do { Field *fields = result->Fetch(); uint32 id = fields[0].GetUInt32(); if (!check(id)) { if (!found) { ss << "DELETE FROM " << table << " WHERE " << column << " IN ("; found = true; } else ss << ", "; ss << id; } } while(result->NextRow()); if (found) { ss << ")"; CharacterDatabase.Execute(ss.str().c_str()); } } bool CharacterDatabaseCleaner::AchievementProgressCheck(uint32 criteria) { return sAchievementCriteriaStore.LookupEntry(criteria); } void CharacterDatabaseCleaner::CleanCharacterAchievementProgress() { CheckUnique("criteria", "character_achievement_progress", &AchievementProgressCheck); } bool CharacterDatabaseCleaner::SkillCheck(uint32 skill) { return sSkillLineStore.LookupEntry(skill); } void CharacterDatabaseCleaner::CleanCharacterSkills() { CheckUnique("skill", "character_skills", &SkillCheck); } bool CharacterDatabaseCleaner::SpellCheck(uint32 spell_id) { return sSpellStore.LookupEntry(spell_id) && !GetTalentSpellPos(spell_id); } void CharacterDatabaseCleaner::CleanCharacterSpell() { CheckUnique("spell", "character_spell", &SpellCheck); } bool CharacterDatabaseCleaner::TalentCheck(uint32 talent_id) { TalentEntry const *talentInfo = sTalentStore.LookupEntry(talent_id); if (!talentInfo) return false; return sTalentTabStore.LookupEntry(talentInfo->TalentTab); } void CharacterDatabaseCleaner::CleanCharacterTalent() { CharacterDatabase.DirectPExecute("DELETE FROM character_talent WHERE spec > %u", MAX_TALENT_SPECS); CheckUnique("spell", "character_talent", &TalentCheck); } void CharacterDatabaseCleaner::CleanCharacterQuestStatus() { CharacterDatabase.DirectExecute("DELETE FROM character_queststatus WHERE status = 0"); }
gpl-3.0
John-Yu/Simple_PE_packer
lzo-2.10/src/lzo1c_9.c
6
1214
/* lzo1c_9.c -- main internal configuration file for the the LZO library This file is part of the LZO real-time data compression library. Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library 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. The LZO 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer <markus@oberhumer.com> http://www.oberhumer.com/opensource/lzo/ */ #define COMPRESS_ID 9 #define DDBITS 2 #define CLEVEL 9 #include "compr1c.h" /* vim:set ts=4 sw=4 et: */
gpl-3.0
Rdlgrmpf/nexmon
utilities/wireshark/epan/dissectors/packet-mip.c
6
54029
/* packet-mip.c * Routines for Mobile IP dissection * Copyright 2000, Stefan Raab <sraab@cisco.com> * Copyright 2007, Ville Nuorvala <Ville.Nuorvala@secgo.com> * Copyright 2009, Ohuchi Munenori <ohuchi_at_iij.ad.jp> * Copyright 2010, Yi Ren <yi_ren1@agilent.com> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include <epan/expert.h> #include <epan/to_str.h> #include <epan/sminmpec.h> void proto_register_mip(void); void proto_reg_handoff_mip(void); static dissector_table_t mip_nvse_ext_dissector_table; /* Initialize the protocol and registered fields */ static int proto_mip = -1; static int hf_mip_type = -1; static int hf_mip_flags = -1; static int hf_mip_s = -1; static int hf_mip_b = -1; static int hf_mip_d = -1; static int hf_mip_m = -1; static int hf_mip_g = -1; static int hf_mip_v = -1; static int hf_mip_t = -1; static int hf_mip_x = -1; static int hf_mip_code = -1; static int hf_mip_life = -1; static int hf_mip_homeaddr = -1; static int hf_mip_haaddr = -1; static int hf_mip_coa = -1; static int hf_mip_ident = -1; static int hf_mip_ext_type = -1; static int hf_mip_gaext_stype = -1; static int hf_mip_ext_len = -1; static int hf_mip_ext = -1; static int hf_mip_aext_spi = -1; static int hf_mip_aext_auth = -1; static int hf_mip_next_nai = -1; static int hf_mip_rext_flags = -1; static int hf_mip_rext_i = -1; static int hf_mip_rext_reserved = -1; static int hf_mip_rext_tstamp = -1; static int hf_mip_rev_reserved = -1; static int hf_mip_flags2 = -1; static int hf_mip_rev_a = -1; static int hf_mip_rev_i = -1; static int hf_mip_rev_reserved2 = -1; static int hf_mip_ack_reserved = -1; static int hf_mip_ack_i = -1; static int hf_mip_ack_reserved2 = -1; static int hf_mip_hda = -1; static int hf_mip_fda = -1; static int hf_mip_revid = -1; static int hf_mip_dhaext_stype = -1; static int hf_mip_dhaext_addr = -1; static int hf_mip_mstrext_stype = -1; static int hf_mip_mstrext_text = -1; static int hf_mip_nattt_nexthdr = -1; static int hf_mip_nattt_reserved = -1; static int hf_mip_utrqext_stype = -1; static int hf_mip_utrqext_reserved1 = -1; static int hf_mip_utrqext_flags = -1; static int hf_mip_utrqext_f = -1; static int hf_mip_utrqext_r = -1; static int hf_mip_utrqext_reserved2 = -1; static int hf_mip_utrqext_encap_type = -1; static int hf_mip_utrqext_reserved3 = -1; static int hf_mip_utrpext_stype = -1; static int hf_mip_utrpext_code = -1; static int hf_mip_utrpext_flags = -1; static int hf_mip_utrpext_f = -1; static int hf_mip_utrpext_reserved = -1; static int hf_mip_utrpext_keepalive = -1; static int hf_mip_pmipv4nonskipext_stype = -1; static int hf_mip_pmipv4nonskipext_pernodeauthmethod = -1; static int hf_mip_pmipv4skipext_stype = -1; static int hf_mip_pmipv4skipext_interfaceid = -1; static int hf_mip_pmipv4skipext_deviceid_type = -1; static int hf_mip_pmipv4skipext_deviceid_id = -1; static int hf_mip_pmipv4skipext_subscriberid_type = -1; static int hf_mip_pmipv4skipext_subscriberid_id = -1; static int hf_mip_pmipv4skipext_accesstechnology_type = -1; static int hf_mip_cvse_reserved = -1; static int hf_mip_cvse_vendor_org_id = -1; static int hf_mip_cvse_verizon_cvse_type = -1; static int hf_mip_cvse_3gpp2_cvse_type = -1; static int hf_mip_cvse_3gpp2_grekey = -1; static int hf_mip_cvse_vendor_cvse_type = -1; static int hf_mip_cvse_vendor_cvse_value = -1; static int hf_mip_nvse_reserved = -1; static int hf_mip_nvse_vendor_org_id = -1; static int hf_mip_nvse_vendor_nvse_type = -1; static int hf_mip_nvse_vendor_nvse_value = -1; static int hf_mip_nvse_3gpp2_type = -1; static int hf_mip_nvse_3gpp2_type17_entity = -1; static int hf_mip_nvse_3gpp2_type16_value = -1; static int hf_mip_nvse_3gpp2_type17_subtype1 = -1; static int hf_mip_nvse_3gpp2_type17_subtype2 = -1; static int hf_mip_nvse_3gpp2_type17_length = -1; static int hf_mip_nvse_3gpp2_type17_prim_dns = -1; static int hf_mip_nvse_3gpp2_type17_sec_dns = -1; /* Initialize the subtree pointers */ static gint ett_mip = -1; static gint ett_mip_flags = -1; static gint ett_mip_ext = -1; static gint ett_mip_exts = -1; static gint ett_mip_pmipv4_ext = -1; static expert_field ei_mip_data_not_dissected = EI_INIT; /* Port used for Mobile IP */ #define UDP_PORT_MIP 434 /* http://www.iana.org/assignments/mobileip-numbers */ typedef enum { MIP_REGISTRATION_REQUEST = 1, MIP_REGISTRATION_REPLY = 3, MIP_NATT_TUNNEL_DATA = 4, MIP_REGISTRATION_REVOCATION = 7, MIP_REGISTRATION_REVOCATION_ACK = 15, MIP_HANDOFF_REQUEST = 16, MIP_HANDOFF_REPLY = 17, MIP_REGIONAL_REG_REQ = 18, MIP_REGIONAL_REG_REP = 19, MIP_FAST_BINDING_UPD = 20, MIP_FAST_BINDING_ACK = 21, MIP_EXPERIMENTAL_MESSAGE = 255 } mipMessageTypes; static const value_string mip_types[] = { {MIP_REGISTRATION_REQUEST, "Registration Request"}, {MIP_REGISTRATION_REPLY, "Registration Reply"}, {MIP_NATT_TUNNEL_DATA, "NAT Traversal Tunnel Data"}, {MIP_REGISTRATION_REVOCATION, "Registration Revocation"}, {MIP_REGISTRATION_REVOCATION_ACK, "Registration Revocation Acknowledgement"}, {MIP_HANDOFF_REQUEST, "NAT Traversal Tunnel Data"}, {MIP_HANDOFF_REPLY, "NAT Traversal Tunnel Data"}, {MIP_REGIONAL_REG_REQ, "NAT Traversal Tunnel Data"}, {MIP_REGIONAL_REG_REP, "NAT Traversal Tunnel Data"}, {MIP_FAST_BINDING_UPD, "NAT Traversal Tunnel Data"}, {MIP_FAST_BINDING_ACK, "NAT Traversal Tunnel Data"}, {MIP_EXPERIMENTAL_MESSAGE, "Message for Experimental Use"}, {0, NULL} }; static const value_string mip_reply_codes[]= { {0, "Reg Accepted"}, {1, "Reg Accepted, but Simultaneous Bindings Unsupported"}, {64, "Reg Deny (FA)- Unspecified Reason"}, {65, "Reg Deny (FA)- Administratively Prohibited"}, {66, "Reg Deny (FA)- Insufficient Resources"}, {67, "Reg Deny (FA)- MN Failed Authentication"}, {68, "Reg Deny (FA)- HA Failed Authentication"}, {69, "Reg Deny (FA)- Requested Lifetime too Long"}, {70, "Reg Deny (FA)- Poorly Formed Request"}, {71, "Reg Deny (FA)- Poorly Formed Reply"}, {72, "Reg Deny (FA)- Requested Encapsulation Unavailable"}, {73, "Reg Deny (FA)- VJ Compression Unavailable"}, {74, "Reg Deny (FA)- Requested Reverse Tunnel Unavailable"}, {75, "Reg Deny (FA)- Reverse Tunnel Is Mandatory and 'T' Bit Not Set"}, {76, "Reg Deny (FA)- Mobile Node Too Distant"}, {77, "Reg Deny (FA)- Invalid Care-of Address"}, {78, "Reg Deny (FA)- Registration Timeout"}, {79, "Reg Deny (FA)- Delivery Style Not Supported"}, {80, "Reg Deny (FA)- Home Network Unreachable"}, {81, "Reg Deny (FA)- HA Host Unreachable"}, {82, "Reg Deny (FA)- HA Port Unreachable"}, {88, "Reg Deny (FA)- HA Unreachable"}, {89, "Reg Deny (FA)- Vendor-specific Reason"}, {90, "Reg Deny (FA)- Non-zero HA Address Required"}, {96, "Reg Deny (FA)(NAI) - Non-zero Home Address Required"}, {97, "Reg Deny (FA)(NAI) - Missing NAI"}, {98, "Reg Deny (FA)(NAI) - Missing Home Agent"}, {99, "Reg Deny (FA)(NAI) - Missing Home Address"}, {100, "Reg Deny (FA)- Unable to Interpret CVSE Sent by MN"}, {101, "Reg Deny (FA)- Unable to Interpret CVSE Sent by HA"}, {104, "Reg Deny (FA)- Unknown Challenge"}, {105, "Reg Deny (FA)- Missing Challenge"}, {106, "Reg Deny (FA)- Stale Challenge"}, {107, "Reg Deny (FA)- Missing MN-FA Key Generation Nonce Reply Extension"}, {108, "Reg Deny (FA)- MN Failed AAA Authentication"}, {109, "Reg Deny (FA)- HA Sent Wrong Challenge in Reply"}, {127, "Reg Deny (FA)- Error Code for Experimental Use"}, {128, "Reg Deny (HA)- Unspecified"}, {129, "Reg Deny (HA)- Administratively Prohibited"}, {130, "Reg Deny (HA)- Insufficient Resources"}, {131, "Reg Deny (HA)- MN Failed Authentication"}, {132, "Reg Deny (HA)- FA Failed Authentication"}, {133, "Reg Deny (HA)- Registration ID Mismatch"}, {134, "Reg Deny (HA)- Poorly Formed Request"}, {135, "Reg Deny (HA)- Too Many Simultaneous Bindings"}, {136, "Reg Deny (HA)- Unknown HA Address"}, {137, "Reg Deny (HA)- Requested Reverse Tunnel Unavailable"}, {138, "Reg Deny (HA)- Reverse Tunnel Is Mandatory and 'T' Bit Not Set"}, {139, "Reg Deny (HA)- Requested Encapsulation Unavailable"}, {140, "Reg Deny (HA)- Unable to Interpret CVSE Sent by MN"}, {141, "Reg Deny (HA)- Unable to Interpret CVSE Sent by FA"}, {142, "Reg Deny (HA)- UDP Encapsulation Unavailable"}, {143, "Reg Deny (HA)- Register with Redirected HA"}, {144, "Reg Deny (HA)- MN Failed AAA Authentication"}, {149, "Reg Deny (HA)- PMIP_UNSUPPORTED"}, /* draft-leung-mip4-proxy-mode */ {150, "Reg Deny (HA)- PMIP_DISALLOWED"}, /* draft-leung-mip4-proxy-mode */ {192, "Reg Deny (HA)- Error Code for Experimental Use"}, {0, NULL} }; static const value_string mip_nattt_nexthdr[]= { {4, "IP Header"}, {47, "GRE Header"}, {55, "Minimal IP Encapsulation Header"}, {0, NULL} }; typedef enum { MH_AUTH_EXT = 32, MF_AUTH_EXT = 33, FH_AUTH_EXT = 34, GEN_AUTH_EXT = 36, /* RFC 3012 */ OLD_CVSE_EXT = 37, /* RFC 3115 */ CVSE_EXT = 38, /* RFC 3115 */ UDP_TUN_REP_EXT = 44, /* RFC 3519 */ MIP_FA_ERROR_EXT = 45, /* [RFC4636] */ MIP_GFA_IP_ADDR_EXT = 46, /* [RFC4857] */ PMIPv4_NON_SKIP_EXT = 47, /* [RFC5563] */ MN_NAI_EXT = 131, /* RFC 2794 */ MF_CHALLENGE_EXT = 132, /* RFC 3012 */ OLD_NVSE_EXT = 133, /* RFC 3115 */ NVSE_EXT = 134, /* RFC 3115 */ REV_SUPP_EXT = 137, /* RFC 3543 */ DYN_HA_EXT = 139, /* RFC 4433 */ UDP_TUN_REQ_EXT = 144, /* RFC 3519 */ MSG_STR_EXT = 145, PMIPv4_SKIP_EXT = 147, /* draft-leung-mip4-proxy-mode */ SKIP_EXP_EXT = 255, /* RFC 4064 */ GRE_KEY_EXT = 0x0401 } MIP_EXTS; static const value_string mip_ext_types[]= { {MH_AUTH_EXT, "Mobile-Home Authentication Extension"}, {MF_AUTH_EXT, "Mobile-Foreign Authentication Extension"}, {FH_AUTH_EXT, "Foreign-Home Authentication Extension"}, {GEN_AUTH_EXT, "Generalized Mobile-IP Authentication Extension"}, {OLD_CVSE_EXT, "Critical Vendor/Organization Specific Extension"}, {CVSE_EXT, "Critical Vendor/Organization Specific Extension"}, {UDP_TUN_REP_EXT, "UDP Tunnel Reply Extension"}, {MIP_FA_ERROR_EXT, "FA Error Extension"}, {MIP_GFA_IP_ADDR_EXT, "GFA IP Address Extension"}, {PMIPv4_NON_SKIP_EXT, "Proxy Mobile IPv4 Non-skippable Extension"}, {128, "Deprecated (2001 Aug 31)"}, {129, "SKIP Firewall Traversal Extension"}, /*[RFC2356]*/ {130, "Encapsulating Delivery Style Extension"}, /*[RFC3024]*/ {MN_NAI_EXT, "Mobile Node NAI Extension"}, {MF_CHALLENGE_EXT, "MN-FA Challenge Extension"}, {OLD_NVSE_EXT, "Normal Vendor/Organization Specific Extension"}, {NVSE_EXT, "Normal Vendor/Organization Specific Extension"}, {136, "NAI Carrying Extension"}, /*[RFC3846]*/ {REV_SUPP_EXT, "Revocation Support Extension"}, {138, "Generalized Link Layer Address Registration Extension"}, /*[RFC4881]*/ {DYN_HA_EXT, "Dynamic HA Extension"}, {140, "Hierarchical Foreign Agent Extension"}, /*[RFC4857]*/ {141, "Replay Protection Style"}, /*[RFC4857]*/ {142, "Regional Registration Lifetime Extension"}, /*[RFC4857]*/ {UDP_TUN_REQ_EXT, "UDP Tunnel Request Extension"}, {MSG_STR_EXT, "Message String Extension"}, {PMIPv4_SKIP_EXT, "Proxy Mobile IPv4 Skippable Extension"}, {148, "Mobile Network Extension"}, /*[RFC5177]*/ {149, "Trusted Networks Configured (TNC) Extension"}, /*[RFC5265]*/ {150, "Reserved"}, {151, "Service Selection Extension"}, /*[RFC5446]*/ {152, "Dual Stack (DSMIPv4) Extension"}, /*[RFC5454]*/ {SKIP_EXP_EXT, "Skippable Extension for Experimental use"}, {0, NULL} }; static const value_string mip_gaext_stypes[]= { {1, "MN-AAA Authentication"}, {2, "FA-FA Authentication"}, {3, "MN-GFA Authentication"}, {4, "MN-PAR Auth Extension"}, {0, NULL} }; /* UDP Tunnel Reply Extension: */ static const value_string mip_utrpext_stypes[]= { {0, "Regular UDP Tunnel Reply Extension"}, {0, NULL} }; /* Dynamic HA Extension subtypes */ static const value_string mip_dhaext_stypes[]= { {1, "Requested HA Extension"}, {2, "Redirected HA Extension"}, {0, NULL} }; static const value_string mip_mstrext_stypes[]= { {1, "HA Extension"}, {2, "FA Extension"}, {0, NULL} }; static const value_string mip_utrqext_stypes[]= { {0, ""}, {0, NULL} }; static const value_string mip_utrqext_encap_types[]= { {4, "IP Header"}, {47, "GRE Header"}, {55, "Minimal IP Encapsulation Header"}, {0, NULL} }; static const value_string mip_utrpext_codes[]= { {0, "Will do Tunneling"}, {64, "Tunneling Declined, Reason Unspecified"}, {0, NULL} }; static const value_string mip_pmipv4nonskipext_stypes[]= { {0, "Unknown"}, {1, "Per-Node Authentication Method"}, {0, NULL} }; /* PMIPv4 Per-Node Authentication Method Types */ static const value_string mip_pmipv4nonskipext_pernodeauthmethod_types[]= { {0, "Reserved"}, {1, "FA-HA Authentication"}, {2, "IPSec Authentication"}, {0, NULL} }; #define PMIPv4_SKIPEXT_STYPE_INTERFACE_ID (1) #define PMIPv4_SKIPEXT_STYPE_DEVICE_ID (2) #define PMIPv4_SKIPEXT_STYPE_SUBSCRIBER_ID (3) #define PMIPv4_SKIPEXT_STYPE_ACCESS_TECHNOLOGY (4) static const value_string mip_pmipv4skipext_stypes[]= { {0, "Unknown"}, {PMIPv4_SKIPEXT_STYPE_INTERFACE_ID, "Interface ID"}, {PMIPv4_SKIPEXT_STYPE_DEVICE_ID, "Device ID"}, {PMIPv4_SKIPEXT_STYPE_SUBSCRIBER_ID, "Subscriber ID"}, {PMIPv4_SKIPEXT_STYPE_ACCESS_TECHNOLOGY, "Access Technology Type"}, {0, NULL} }; /* PMIPv4 Device ID Types */ static const value_string mip_pmipv4skipext_deviceid_types[]= { {0, "Reserved"}, {1, "Ethernet MAC address"}, {2, "Mobile Equipment Identifier (MEID)"}, {3, "International Mobile Equipment Identity (IMEI)"}, {4, "Electronic Serial Number (ESN)"}, {0, NULL} }; /* PMIPv4 Subscriber ID Types */ static const value_string mip_pmipv4skipext_subscriberid_types[]= { {0, "Reserved"}, {1, "International Mobile Subscriber Identity (IMSI)"}, {0, NULL} }; /* Access Technology Types */ static const value_string mip_pmipv4skipext_accesstechnology_types[]= { {0, "Reserved"}, {1, "802.3"}, {2, "802.11a/b/g"}, {3, "802.16e"}, {4, "802.16m"}, {5, "3GPP EUTRAN/LTE"}, {6, "3GPP UTRAN/GERAN"}, {7, "3GPP2 1xRTT/HRPD"}, {8, "3GPP2 UMB"}, {0, NULL} }; static const value_string mip_cvse_verizon_cvse_types[]= { {0, "Reserved"}, {1, "MIP Key Request"}, {2, "MIP Key Data"}, {3, "AAA Authenticator"}, {4, "Public Key Invalid"}, {0, NULL} }; /*http://www.3gpp2.org/public_html/X/VSA-VSE.cfm*/ #if 0 static const value_string mip_cvse_3gpp2_cvse_types[]= { {257, "Accounting/Radius"}, {258, "Accounting/Diameter"}, {513, "Accounting/Diameter"}, {769, "Data Available Indicator/Data Ready to Send"}, {1025,"GRE Key"}, {1281, "Binding Type Extension"}, {1537, "GRE Tunnel Endpoint Extension"}, {0, NULL} }; #endif static const value_string mip_nvse_3gpp2_type_vals[]= { {16, "PPP Link Indicator"}, /* X.S0011-003-C v1.0 */ {17, "DNS server IP address"}, {0, NULL} }; static const value_string mip_nvse_3gpp2_type17_entity_vals[]= { {0, "Unknown"}, {1, "HAAA"}, {2, "VAAA"}, {3, "HA"}, {0, NULL} }; static const value_string mip_nvse_3gpp2_type17_vals[]= { {0, "main service instance"}, {1, "negotiate PPP"}, {2, "do not negotiate PPP"}, {0, NULL} }; static dissector_handle_t ip_handle; /* Code to dissect 3GPP2 extensions */ static int dissect_mip_priv_ext_3gpp2(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, void *data _U_) { int offset = 0; guint16 type; int length = tvb_reported_length(tvb); type = tvb_get_ntohs(tvb,offset); proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type, tvb, offset, 2, ENC_BIG_ENDIAN); offset+=2; switch(type){ case 16: /* PPP Link Indicator X.S0011-003-C v1.0 */ proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type16_value, tvb, offset, 2, ENC_BIG_ENDIAN); break; case 17: /* DNS server IP address X.S0011-002-C v3.0*/ /* Entity-Type */ proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type17_entity, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Sub-Type1 */ proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type17_subtype1, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Length */ proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type17_length, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* DNS server IP address */ proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type17_prim_dns, tvb, offset, 4, ENC_BIG_ENDIAN); offset+=4; /* Sub-Type2 */ proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type17_subtype2, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Length */ proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type17_length, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* DNS server IP address.*/ proto_tree_add_item(tree, hf_mip_nvse_3gpp2_type17_sec_dns, tvb, offset, 4, ENC_BIG_ENDIAN); break; default: proto_tree_add_expert(tree, pinfo, &ei_mip_data_not_dissected, tvb, offset, -1); break; } return length; } /* Code to dissect extensions */ static void dissect_mip_extensions( tvbuff_t *tvb, int offset, proto_tree *tree, packet_info *pinfo) { proto_tree *exts_tree=NULL; proto_tree *ext_tree; proto_tree *pmipv4_tree; gint ext_len; guint8 ext_type; guint8 ext_subtype=0; guint8 pmipv4skipext_subscriberid_type; gint hdrLen; guint32 cvse_vendor_id; guint16 cvse_3gpp2_type; int cvse_local_offset= 0; int nvse_local_offset= 0; /* Add our tree, if we have extensions */ exts_tree = proto_tree_add_subtree(tree, tvb, offset, -1, ett_mip_exts, NULL, "Extensions"); /* And, handle each extension */ while (tvb_reported_length_remaining(tvb, offset) > 0) { /* Get our extension info */ ext_type = tvb_get_guint8(tvb, offset); if (ext_type == GEN_AUTH_EXT || ext_type == PMIPv4_NON_SKIP_EXT) { /* * Very nasty . . breaks normal extensions, since the length is * in the wrong place :( */ ext_subtype = tvb_get_guint8(tvb, offset + 1); ext_len = tvb_get_ntohs(tvb, offset + 2); hdrLen = 4; } else if(ext_type==CVSE_EXT){ /* * CVSE also breaks since it added reserved field before * the length field */ ext_len = tvb_get_ntohs(tvb, offset + 2); hdrLen = 4; } else { ext_len = tvb_get_guint8(tvb, offset + 1); hdrLen = 2; } ext_tree = proto_tree_add_subtree_format(exts_tree, tvb, offset, ext_len + hdrLen, ett_mip_ext, NULL, "Extension: %s", val_to_str(ext_type, mip_ext_types, "Unknown Extension %u")); proto_tree_add_uint(ext_tree, hf_mip_ext_type, tvb, offset, 1, ext_type); offset++; if (ext_type != GEN_AUTH_EXT && ext_type != PMIPv4_NON_SKIP_EXT && ext_type != CVSE_EXT) { /* Another nasty hack since GEN_AUTH_EXT and PMIPv4_NON_SKIP_EXT broke everything */ proto_tree_add_uint(ext_tree, hf_mip_ext_len, tvb, offset, 1, ext_len); offset++; } switch (ext_type) { case MH_AUTH_EXT: case MF_AUTH_EXT: case FH_AUTH_EXT: /* All these extensions look the same. 4 byte SPI followed by a key */ proto_tree_add_item(ext_tree, hf_mip_aext_spi, tvb, offset, 4, ENC_BIG_ENDIAN); proto_tree_add_item(ext_tree, hf_mip_aext_auth, tvb, offset+4, ext_len-4, ENC_NA); break; case MN_NAI_EXT: proto_tree_add_item(ext_tree, hf_mip_next_nai, tvb, offset, ext_len, ENC_ASCII|ENC_NA); break; case GEN_AUTH_EXT: /* RFC 3012 */ /* * Very nasty . . breaks normal extensions, since the length is * in the wrong place :( */ proto_tree_add_uint(ext_tree, hf_mip_gaext_stype, tvb, offset, 1, ext_subtype); offset++; proto_tree_add_uint(ext_tree, hf_mip_ext_len, tvb, offset, 2, ext_len); offset+=2; /* SPI */ proto_tree_add_item(ext_tree, hf_mip_aext_spi, tvb, offset, 4, ENC_BIG_ENDIAN); /* Key */ proto_tree_add_item(ext_tree, hf_mip_aext_auth, tvb, offset + 4, ext_len - 4, ENC_NA); break; case REV_SUPP_EXT: /* RFC 3543 */ { /* flags */ static const int * flags[] = { &hf_mip_rext_i, &hf_mip_rext_reserved, NULL }; proto_tree_add_bitmask(ext_tree, tvb, offset, hf_mip_rext_flags, ett_mip_flags, flags, ENC_BIG_ENDIAN); /* registration revocation timestamp */ proto_tree_add_item(ext_tree, hf_mip_rext_tstamp, tvb, offset + 2, 4, ENC_BIG_ENDIAN); } break; case DYN_HA_EXT: /* RFC 4433 */ /* subtype */ proto_tree_add_item(ext_tree, hf_mip_dhaext_stype, tvb, offset, 1, ENC_BIG_ENDIAN); /* Home Agent */ proto_tree_add_item(ext_tree, hf_mip_dhaext_addr, tvb, offset + 1, 4, ENC_BIG_ENDIAN); break; case MSG_STR_EXT: /* sub-type */ proto_tree_add_item(ext_tree, hf_mip_mstrext_stype, tvb, offset, 1, ENC_BIG_ENDIAN); /* text */ proto_tree_add_item(ext_tree, hf_mip_mstrext_text, tvb, offset + 1, ext_len-1, ENC_ASCII|ENC_NA); break; case UDP_TUN_REQ_EXT: /* RFC 3519 */ { static const int * flags[] = { &hf_mip_utrqext_f, &hf_mip_utrqext_r, &hf_mip_utrqext_reserved2, NULL }; /* sub-type */ proto_tree_add_item(ext_tree, hf_mip_utrqext_stype, tvb, offset, 1, ENC_BIG_ENDIAN); /* reserved 1 */ proto_tree_add_item(ext_tree, hf_mip_utrqext_reserved1, tvb, offset + 1, 1, ENC_BIG_ENDIAN); /* flags */ proto_tree_add_bitmask(ext_tree, tvb, offset + 2, hf_mip_utrqext_flags, ett_mip_flags, flags, ENC_BIG_ENDIAN); /* encapsulation */ proto_tree_add_item(ext_tree, hf_mip_utrqext_encap_type, tvb, offset + 3, 1, ENC_BIG_ENDIAN); /* reserved 3 */ proto_tree_add_item(ext_tree, hf_mip_utrqext_reserved3, tvb, offset + 4, 2, ENC_BIG_ENDIAN); } break; case UDP_TUN_REP_EXT: /* RFC 3519 */ { static const int * flags[] = { &hf_mip_utrpext_f, &hf_mip_utrpext_reserved, NULL }; /* sub-type */ proto_tree_add_item(ext_tree, hf_mip_utrpext_stype, tvb, offset, 1, ENC_BIG_ENDIAN); /* code */ proto_tree_add_item(ext_tree, hf_mip_utrpext_code, tvb, offset + 1, 1, ENC_BIG_ENDIAN); /* flags */ proto_tree_add_bitmask(ext_tree, tvb, offset + 2, hf_mip_utrpext_flags, ett_mip_flags, flags, ENC_BIG_ENDIAN); /* keepalive interval */ proto_tree_add_item(ext_tree, hf_mip_utrpext_keepalive, tvb, offset + 4, 2, ENC_BIG_ENDIAN); } break; case PMIPv4_NON_SKIP_EXT: /* draft-leung-mip4-proxy-mode */ /* sub-type */ proto_tree_add_uint(ext_tree, hf_mip_pmipv4nonskipext_stype, tvb, offset, 1, ext_subtype); offset++; /* len */ proto_tree_add_uint(ext_tree, hf_mip_ext_len, tvb, offset, 2, ext_len); offset+=2; if(ext_subtype == 1){ /* Sub-type == 1 : PMIPv4 Per-Node Authentication Method */ proto_tree_add_item(ext_tree, hf_mip_pmipv4nonskipext_pernodeauthmethod, tvb, offset, 1, ENC_BIG_ENDIAN); } break; case PMIPv4_SKIP_EXT: /* draft-leung-mip4-proxy-mode */ /* sub-type */ ext_subtype = tvb_get_guint8(tvb, offset); pmipv4_tree = proto_tree_add_subtree_format(ext_tree, tvb, offset, ext_len, ett_mip_pmipv4_ext, NULL, "PMIPv4 Sub-Type: %s", val_to_str(ext_subtype, mip_pmipv4skipext_stypes, "Unknown Sub-Type %u")); proto_tree_add_uint(pmipv4_tree, hf_mip_pmipv4skipext_stype, tvb, offset, 1, ext_subtype); if (ext_subtype == PMIPv4_SKIPEXT_STYPE_INTERFACE_ID) { proto_tree_add_item(pmipv4_tree, hf_mip_pmipv4skipext_interfaceid, tvb, offset + 1, ext_len-1, ENC_NA); } else if (ext_subtype == PMIPv4_SKIPEXT_STYPE_DEVICE_ID) { proto_tree_add_item(pmipv4_tree, hf_mip_pmipv4skipext_deviceid_type, tvb, offset + 1, 1, ENC_BIG_ENDIAN); proto_tree_add_item(pmipv4_tree, hf_mip_pmipv4skipext_deviceid_id, tvb, offset + 2, ext_len - 2, ENC_NA); } else if (ext_subtype == PMIPv4_SKIPEXT_STYPE_SUBSCRIBER_ID) { pmipv4skipext_subscriberid_type = tvb_get_guint8(tvb, offset + 1); proto_tree_add_uint(pmipv4_tree, hf_mip_pmipv4skipext_subscriberid_type, tvb, offset + 1, 1, pmipv4skipext_subscriberid_type); if (pmipv4skipext_subscriberid_type == 1) { proto_tree_add_item(pmipv4_tree, hf_mip_pmipv4skipext_subscriberid_id, tvb, offset + 2, ext_len - 2, ENC_NA); } } else if (ext_subtype == PMIPv4_SKIPEXT_STYPE_ACCESS_TECHNOLOGY) { proto_tree_add_item(pmipv4_tree, hf_mip_pmipv4skipext_accesstechnology_type, tvb, offset + 1, 1, ENC_BIG_ENDIAN); } break; case OLD_CVSE_EXT: /* RFC 3115 */ case CVSE_EXT: /* RFC 3115 */ /* * Very nasty . . breaks normal extensions, since the length is * in the wrong place :( */ proto_tree_add_item(ext_tree, hf_mip_cvse_reserved, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; proto_tree_add_uint(ext_tree, hf_mip_ext_len, tvb, offset, 2, ext_len); offset+=2; /* Vendor/Org ID */ /*Vendor ID & cvse type & cvse value are included in ext_len, so do not increment offset for them here.*/ cvse_local_offset = offset; proto_tree_add_item(ext_tree, hf_mip_cvse_vendor_org_id, tvb, cvse_local_offset, 4, ENC_BIG_ENDIAN); cvse_vendor_id = tvb_get_ntohl(tvb, cvse_local_offset); cvse_local_offset+=4; /*Vendor CVSE Type*/ if( cvse_vendor_id == VENDOR_VERIZON ){ /*Verizon CVSE type*/ proto_tree_add_item(ext_tree, hf_mip_cvse_verizon_cvse_type, tvb, cvse_local_offset, 2, ENC_BIG_ENDIAN); }else if( cvse_vendor_id == VENDOR_THE3GPP2 ){ /*THE3GPP2 CVSE type*/ proto_tree_add_item(ext_tree, hf_mip_cvse_3gpp2_cvse_type, tvb, cvse_local_offset, 2, ENC_BIG_ENDIAN); cvse_3gpp2_type = tvb_get_ntohs(tvb, cvse_local_offset); /* XXX: THE3GPP2 CVSE type is followed by a 2 byte length field ? - No ?*/ /* ... */ /* THE3GPP2 CVSE Value http://www.3gpp2.org/public_html/X/VSA-VSE.cfm X.S0011 * http://www.3gpp2.org/Public_html/specs/X.S0011-002-E_v1.0_091116.pdf Chapter 4.1.4 GRE CVSE */ if(cvse_3gpp2_type == GRE_KEY_EXT){ proto_tree_add_item(ext_tree, hf_mip_cvse_3gpp2_grekey, tvb, cvse_local_offset + 2, ext_len - 6, ENC_BIG_ENDIAN); } }else{ /*CVSE Type of Other vendor, just show raw numbers currently*/ proto_tree_add_item(ext_tree, hf_mip_cvse_vendor_cvse_type, tvb, cvse_local_offset, 2, ENC_BIG_ENDIAN); /* Vendor CVSE Type+Vendor/Org ID = 6 bytes*/ proto_tree_add_item(ext_tree, hf_mip_cvse_vendor_cvse_value, tvb, cvse_local_offset + 2, ext_len - 6, ENC_NA); } break; case OLD_NVSE_EXT: /* RFC 3115 */ case NVSE_EXT: /* RFC 3115 */ { guint32 nvse_vendor_org_id; tvbuff_t *next_tvb; proto_tree_add_item(ext_tree, hf_mip_nvse_reserved, tvb, offset, 2, ENC_BIG_ENDIAN); /* Vendor/Org ID */ /*Vendor ID & nvse type & nvse value are included in ext_len, so do not increment offset for them here.*/ nvse_local_offset = offset + hdrLen; nvse_vendor_org_id = tvb_get_ntohl(tvb, nvse_local_offset); proto_tree_add_item(ext_tree, hf_mip_nvse_vendor_org_id, tvb, nvse_local_offset, 4, ENC_BIG_ENDIAN); nvse_local_offset+=4; next_tvb = tvb_new_subset_length(tvb, nvse_local_offset, ext_len-6); if (!dissector_try_uint(mip_nvse_ext_dissector_table, nvse_vendor_org_id, next_tvb, pinfo, ext_tree)){ /*Vendor NVSE Type*/ proto_tree_add_item(ext_tree, hf_mip_nvse_vendor_nvse_type, tvb, nvse_local_offset, 2, ENC_BIG_ENDIAN); nvse_local_offset+=2; /* Vendor-NVSE-Value */ proto_tree_add_item(ext_tree, hf_mip_nvse_vendor_nvse_value, tvb, nvse_local_offset, ext_len - 8, ENC_NA); } } break; case MF_CHALLENGE_EXT: /* RFC 3012 */ /* The default dissector is good here. The challenge is all hex anyway. */ default: proto_tree_add_item(ext_tree, hf_mip_ext, tvb, offset, ext_len, ENC_NA); break; } /* ext type */ offset += ext_len; } /* while data remaining */ } /* dissect_mip_extensions */ /* Code to actually dissect the packets */ static int dissect_mip( tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_) { /* Set up structures we will need to add the protocol subtree and manage it */ proto_item *ti; proto_tree *mip_tree=NULL; guint8 type; gint offset=0; tvbuff_t *next_tvb; /* Make entries in Protocol column and Info column on summary display */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "MobileIP"); col_clear(pinfo->cinfo, COL_INFO); type = tvb_get_guint8(tvb, offset); switch (type) { case MIP_REGISTRATION_REQUEST: col_add_fstr(pinfo->cinfo, COL_INFO, "Reg Request: HoA=%s HA=%s CoA=%s", tvb_ip_to_str(tvb, 4), tvb_ip_to_str(tvb, 8), tvb_ip_to_str(tvb, 12)); if (tree) { static const int * flags[] = { &hf_mip_s, &hf_mip_b, &hf_mip_d, &hf_mip_m, &hf_mip_g, &hf_mip_v, &hf_mip_t, &hf_mip_x, NULL }; ti = proto_tree_add_item(tree, proto_mip, tvb, offset, -1, ENC_NA); mip_tree = proto_item_add_subtree(ti, ett_mip); /* type */ proto_tree_add_uint(mip_tree, hf_mip_type, tvb, offset, 1, type); offset++; /* flags */ proto_tree_add_bitmask(mip_tree, tvb, offset, hf_mip_flags, ett_mip_flags, flags, ENC_BIG_ENDIAN); offset++; /* lifetime */ proto_tree_add_item(mip_tree, hf_mip_life, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; /* home address */ proto_tree_add_item(mip_tree, hf_mip_homeaddr, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* home agent address */ proto_tree_add_item(mip_tree, hf_mip_haaddr, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* Care of Address */ proto_tree_add_item(mip_tree, hf_mip_coa, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* Identifier - assumed to be an NTP time here */ proto_tree_add_item(mip_tree, hf_mip_ident, tvb, offset, 8, ENC_TIME_NTP|ENC_BIG_ENDIAN); offset += 8; } /* if tree */ break; case MIP_REGISTRATION_REPLY: col_add_fstr(pinfo->cinfo, COL_INFO, "Reg Reply: HoA=%s HA=%s, Code=%u", tvb_ip_to_str(tvb, 4), tvb_ip_to_str(tvb, 8), tvb_get_guint8(tvb,1)); if (tree) { /* Add Subtree */ ti = proto_tree_add_item(tree, proto_mip, tvb, offset, -1, ENC_NA); mip_tree = proto_item_add_subtree(ti, ett_mip); /* Type */ proto_tree_add_uint(mip_tree, hf_mip_type, tvb, offset, 1, type); offset++; /* Reply Code */ proto_tree_add_item(mip_tree, hf_mip_code, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Registration Lifetime */ proto_tree_add_item(mip_tree, hf_mip_life, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; /* Home address */ proto_tree_add_item(mip_tree, hf_mip_homeaddr, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* Home Agent Address */ proto_tree_add_item(mip_tree, hf_mip_haaddr, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* Identifier - assumed to be an NTP time here */ proto_tree_add_item(mip_tree, hf_mip_ident, tvb, offset, 8, ENC_TIME_NTP|ENC_BIG_ENDIAN); offset += 8; } /* if tree */ break; case MIP_NATT_TUNNEL_DATA: col_add_fstr(pinfo->cinfo, COL_INFO, "Tunnel Data: Next Header=%u", tvb_get_guint8(tvb,1)); if (tree) { /* Add Subtree */ ti = proto_tree_add_item(tree, proto_mip, tvb, offset, -1, ENC_NA); mip_tree = proto_item_add_subtree(ti, ett_mip); /* Type */ proto_tree_add_uint(mip_tree, hf_mip_type, tvb, offset, 1, type); offset++; /* Next Header */ proto_tree_add_item(mip_tree, hf_mip_nattt_nexthdr, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* reserved */ proto_tree_add_item(mip_tree, hf_mip_nattt_reserved, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; } /* if tree */ else { offset += 4; } /* encapsulated payload */ next_tvb = tvb_new_subset_remaining(tvb, offset); call_dissector(ip_handle, next_tvb, pinfo, mip_tree); offset = tvb_reported_length(tvb); break; case MIP_REGISTRATION_REVOCATION: col_add_fstr(pinfo->cinfo, COL_INFO, "Reg Revocation: HoA=%s HDA=%s FDA=%s", tvb_ip_to_str(tvb, 4), tvb_ip_to_str(tvb, 8), tvb_ip_to_str(tvb, 12)); if (tree) { static const int * mip_flags[] = { &hf_mip_rev_a, &hf_mip_rev_i, &hf_mip_rev_reserved2, NULL }; ti = proto_tree_add_item(tree, proto_mip, tvb, offset, -1, ENC_NA); mip_tree = proto_item_add_subtree(ti, ett_mip); /* type */ proto_tree_add_uint(mip_tree, hf_mip_type, tvb, offset, 1, type); offset++; /* reserved */ proto_tree_add_item(mip_tree, hf_mip_rev_reserved, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* flags */ proto_tree_add_bitmask(mip_tree, tvb, offset, hf_mip_flags2, ett_mip_flags, mip_flags, ENC_BIG_ENDIAN); offset += 2; /* home address */ proto_tree_add_item(mip_tree, hf_mip_homeaddr, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* home domain address */ proto_tree_add_item(mip_tree, hf_mip_hda, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* foreign domain address */ proto_tree_add_item(mip_tree, hf_mip_fda, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* revocation identifier */ proto_tree_add_item(mip_tree, hf_mip_revid, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; } /* if tree */ break; case MIP_REGISTRATION_REVOCATION_ACK: col_add_fstr(pinfo->cinfo, COL_INFO, "Reg Revocation Ack: HoA=%s", tvb_ip_to_str(tvb, 4)); if (tree) { static const int * mip_flags[] = { &hf_mip_ack_i, &hf_mip_ack_reserved2, NULL }; ti = proto_tree_add_item(tree, proto_mip, tvb, offset, -1, ENC_NA); mip_tree = proto_item_add_subtree(ti, ett_mip); /* type */ proto_tree_add_uint(mip_tree, hf_mip_type, tvb, offset, 1, type); offset++; /* reserved */ proto_tree_add_item(mip_tree, hf_mip_ack_reserved, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* flags */ proto_tree_add_bitmask(mip_tree, tvb, offset, hf_mip_flags2, ett_mip_flags, mip_flags, ENC_BIG_ENDIAN); offset += 2; /* home address */ proto_tree_add_item(mip_tree, hf_mip_homeaddr, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; /* revocation identifier */ proto_tree_add_item(mip_tree, hf_mip_revid, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; } /* if tree */ break; } /* End switch */ if (tvb_reported_length_remaining(tvb, offset) > 0) dissect_mip_extensions(tvb, offset, mip_tree, pinfo); return tvb_captured_length(tvb); } /* dissect_mip */ /* Register the protocol with Wireshark */ void proto_register_mip(void) { /* Setup list of header fields */ static hf_register_info hf[] = { { &hf_mip_type, { "Message Type", "mip.type", FT_UINT8, BASE_DEC, VALS(mip_types), 0, "Mobile IP Message type.", HFILL } }, { &hf_mip_flags, {"Flags", "mip.flags", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL} }, { &hf_mip_s, {"Simultaneous Bindings", "mip.s", FT_BOOLEAN, 8, NULL, 128, "Simultaneous Bindings Allowed", HFILL } }, { &hf_mip_b, {"Broadcast Datagrams", "mip.b", FT_BOOLEAN, 8, NULL, 64, "Broadcast Datagrams requested", HFILL } }, { &hf_mip_d, { "Co-located Care-of Address", "mip.d", FT_BOOLEAN, 8, NULL, 32, "MN using Co-located Care-of address", HFILL } }, { &hf_mip_m, {"Minimal Encapsulation", "mip.m", FT_BOOLEAN, 8, NULL, 16, "MN wants Minimal encapsulation", HFILL } }, { &hf_mip_g, {"GRE", "mip.g", FT_BOOLEAN, 8, NULL, 8, "MN wants GRE encapsulation", HFILL } }, { &hf_mip_v, { "Van Jacobson", "mip.v", FT_BOOLEAN, 8, NULL, 4, NULL, HFILL } }, { &hf_mip_t, { "Reverse Tunneling", "mip.t", FT_BOOLEAN, 8, NULL, 2, "Reverse tunneling requested", HFILL } }, { &hf_mip_x, { "Reserved", "mip.x", FT_BOOLEAN, 8, NULL, 1, NULL, HFILL } }, { &hf_mip_code, { "Reply Code", "mip.code", FT_UINT8, BASE_DEC, VALS(mip_reply_codes), 0, "Mobile IP Reply code.", HFILL } }, { &hf_mip_life, { "Lifetime", "mip.life", FT_UINT16, BASE_DEC, NULL, 0, "Mobile IP Lifetime.", HFILL } }, { &hf_mip_homeaddr, { "Home Address", "mip.homeaddr", FT_IPv4, BASE_NONE, NULL, 0, "Mobile Node's home address.", HFILL } }, { &hf_mip_haaddr, { "Home Agent", "mip.haaddr", FT_IPv4, BASE_NONE, NULL, 0, "Home agent IP Address.", HFILL } }, { &hf_mip_coa, { "Care of Address", "mip.coa", FT_IPv4, BASE_NONE, NULL, 0, "Care of Address.", HFILL } }, { &hf_mip_ident, { "Identification", "mip.ident", FT_ABSOLUTE_TIME, ABSOLUTE_TIME_UTC, NULL, 0, "MN Identification.", HFILL } }, { &hf_mip_ext_type, { "Extension Type", "mip.ext.type", FT_UINT8, BASE_DEC, VALS(mip_ext_types), 0, "Mobile IP Extension Type.", HFILL } }, { &hf_mip_gaext_stype, { "Gen Auth Ext SubType", "mip.ext.auth.subtype", FT_UINT8, BASE_DEC, VALS(mip_gaext_stypes), 0, "Mobile IP Auth Extension Sub Type.", HFILL } }, { &hf_mip_ext_len, { "Extension Length", "mip.ext.len", FT_UINT16, BASE_DEC, NULL, 0, "Mobile IP Extension Length.", HFILL } }, { &hf_mip_ext, { "Extension", "mip.extension", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_mip_aext_spi, { "SPI", "mip.auth.spi", FT_UINT32, BASE_HEX, NULL, 0, "Authentication Header Security Parameter Index.", HFILL } }, { &hf_mip_aext_auth, { "Authenticator", "mip.auth.auth", FT_BYTES, BASE_NONE, NULL, 0, "Authenticator.", HFILL } }, { &hf_mip_next_nai, { "NAI", "mip.nai", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_mip_rext_flags, {"Rev Ext Flags", "mip.ext.rev.flags", FT_UINT16, BASE_HEX, NULL, 0x0, "Revocation Support Extension Flags", HFILL} }, { &hf_mip_rext_i, { "'I' bit Support", "mip.ext.rev.i", FT_BOOLEAN, 16, NULL, 32768, "Agent supports Inform bit in Revocation", HFILL } }, { &hf_mip_rext_reserved, { "Reserved", "mip.ext.rev.reserved", FT_UINT16, BASE_HEX, NULL, 0x7fff, NULL, HFILL } }, { &hf_mip_rext_tstamp, { "Timestamp", "mip.ext.rev.tstamp", FT_UINT32, BASE_DEC, NULL, 0, "Revocation Timestamp of Sending Agent", HFILL } }, { &hf_mip_rev_reserved, { "Reserved", "mip.rev.reserved", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL} }, { &hf_mip_flags2, {"Flags", "mip.flags2", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL} }, { &hf_mip_rev_a, { "Home Agent", "mip.rev.a", FT_BOOLEAN, 16, NULL, 32768, "Revocation sent by Home Agent", HFILL } }, { &hf_mip_rev_i, { "Inform", "mip.rev.i", FT_BOOLEAN, 16, NULL, 16384, "Inform Mobile Node", HFILL } }, { &hf_mip_rev_reserved2, { "Reserved", "mip.rev.reserved2", FT_UINT16, BASE_HEX, NULL, 0x3fff, NULL, HFILL}}, { &hf_mip_hda, { "Home Domain Address", "mip.rev.hda", FT_IPv4, BASE_NONE, NULL, 0, "Revocation Home Domain IP Address", HFILL } }, { &hf_mip_fda, { "Foreign Domain Address", "mip.rev.fda", FT_IPv4, BASE_NONE, NULL, 0, "Revocation Foreign Domain IP Address", HFILL } }, { &hf_mip_revid, { "Revocation Identifier", "mip.revid", FT_UINT32, BASE_DEC, NULL, 0, "Revocation Identifier of Initiating Agent", HFILL } }, { &hf_mip_ack_reserved, { "Reserved", "mip.ack.reserved", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL} }, { &hf_mip_ack_i, { "Inform", "mip.ack.i", FT_BOOLEAN, 16, NULL, 32768, "Inform Mobile Node", HFILL } }, { &hf_mip_ack_reserved2, { "Reserved", "mip.ack.reserved2", FT_UINT16, BASE_HEX, NULL, 0x7fff, NULL, HFILL}}, { &hf_mip_dhaext_stype, { "DynHA Ext SubType", "mip.ext.dynha.subtype", FT_UINT8, BASE_DEC, VALS(mip_dhaext_stypes), 0, "Dynamic HA Extension Sub-type", HFILL } }, { &hf_mip_dhaext_addr, { "DynHA Home Agent", "mip.ext.dynha.ha", FT_IPv4, BASE_NONE, NULL, 0, "Dynamic Home Agent IP Address", HFILL } }, { &hf_mip_mstrext_stype, { "MsgStr Ext SubType", "mip.ext.msgstr.subtype", FT_UINT8, BASE_DEC, VALS(mip_mstrext_stypes), 0, "Message String Extension Sub-type", HFILL } }, { &hf_mip_mstrext_text, { "MsgStr Text", "mip.ext.msgstr.text", FT_STRING, BASE_NONE, NULL, 0, "Message String Extension Text", HFILL } }, { &hf_mip_nattt_nexthdr, { "NATTT NextHeader", "mip.nattt.nexthdr", FT_UINT8, BASE_DEC, VALS(mip_nattt_nexthdr), 0, "NAT Traversal Tunnel Next Header.", HFILL } }, { &hf_mip_nattt_reserved, { "Reserved", "mip.nattt.reserved", FT_UINT16, BASE_HEX, NULL , 0x0, NULL, HFILL } }, { &hf_mip_utrqext_stype, { "UDP TunReq Ext SubType", "mip.ext.utrq.subtype", FT_UINT8, BASE_DEC, VALS(mip_utrqext_stypes), 0, "UDP Tunnel Request Extension Sub-type", HFILL } }, { &hf_mip_utrqext_reserved1, { "Reserved 1", "mip.ext.utrq.reserved1", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_mip_utrqext_flags, { "UDP TunReq Ext Flags", "mip.ext.utrq.flags", FT_UINT8, BASE_HEX, NULL, 0x0, "UDP Tunnel Request Extension Flags", HFILL } }, { &hf_mip_utrqext_f, { "Req Forced", "mip.ext.utrq.f", FT_BOOLEAN, 8, NULL, 128, "MN wants to Force UDP Tunneling", HFILL } }, { &hf_mip_utrqext_r, { "FA Registration Required", "mip.ext.utrq.r", FT_BOOLEAN, 8, NULL, 64, "Registration through FA Required", HFILL } }, { &hf_mip_utrqext_reserved2, { "Reserved 2", "mip.ext.utrq.reserved2", FT_UINT8, BASE_HEX, NULL, 0x3f, NULL, HFILL } }, { &hf_mip_utrqext_encap_type, { "UDP Encap Type", "mip.ext.utrq.encaptype", FT_UINT8, BASE_DEC, VALS(mip_utrqext_encap_types), 0, "UDP Encapsulation Type", HFILL } }, { &hf_mip_utrqext_reserved3, { "Reserved 3", "mip.ext.utrq.reserved3", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_mip_utrpext_stype, { "UDP TunRep Ext SubType", "mip.ext.utrp.subtype", FT_UINT8, BASE_DEC, VALS(mip_utrpext_stypes), 0, "UDP Tunnel Reply Extension Sub-type", HFILL } }, { &hf_mip_utrpext_code, { "UDP TunRep Code", "mip.ext.utrp.code", FT_UINT8, BASE_DEC, VALS(mip_utrpext_codes), 0, "UDP Tunnel Reply Code", HFILL } }, { &hf_mip_utrpext_flags, { "UDP TunRep Ext Flags", "mip.ext.utrp.flags", FT_UINT16, BASE_HEX, NULL, 0x0, "UDP Tunnel Request Extension Flags", HFILL } }, { &hf_mip_utrpext_f, { "Rep Forced", "mip.ext.utrp.f", FT_BOOLEAN, 16, NULL, 32768, "HA wants to Force UDP Tunneling", HFILL } }, { &hf_mip_utrpext_reserved, { "Reserved", "mip.ext.utrp.reserved", FT_UINT16, BASE_HEX, NULL, 0x7fff, NULL, HFILL } }, { &hf_mip_utrpext_keepalive, { "Keepalive Interval", "mip.ext.utrp.keepalive", FT_UINT16, BASE_DEC, NULL, 0, "NAT Keepalive Interval", HFILL } }, { &hf_mip_pmipv4nonskipext_stype, { "Sub-type", "mip.ext.pmipv4nonskipext.subtype", FT_UINT8, BASE_DEC, VALS(mip_pmipv4nonskipext_stypes), 0, "PMIPv4 Skippable Extension Sub-type", HFILL } }, { &hf_mip_pmipv4nonskipext_pernodeauthmethod, { "Per-Node Authentication Method", "mip.ext.pmipv4nonskipext.pernodeauthmethod", FT_UINT8, BASE_DEC, VALS(mip_pmipv4nonskipext_pernodeauthmethod_types), 0, NULL, HFILL } }, { &hf_mip_pmipv4skipext_stype, { "Sub-type", "mip.ext.pmipv4skipext.subtype", FT_UINT8, BASE_DEC, VALS(mip_pmipv4skipext_stypes), 0, "PMIPv4 Non-skippable Extension Sub-type", HFILL } }, { &hf_mip_pmipv4skipext_interfaceid, { "Interface ID", "mip.ext.pmipv4skipext.interfaceid", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_mip_pmipv4skipext_deviceid_type, { "ID-Type", "mip.ext.pmipv4skipext.deviceid_type", FT_UINT8, BASE_DEC, VALS(mip_pmipv4skipext_deviceid_types), 0, "Device ID-Type", HFILL } }, { &hf_mip_pmipv4skipext_deviceid_id, { "Identifier", "mip.ext.pmipv4skipext.deviceid_id", FT_BYTES, BASE_NONE, NULL, 0, "Device ID Identifier", HFILL } }, { &hf_mip_pmipv4skipext_subscriberid_type, { "ID-Type", "mip.ext.pmipv4skipext.subscriberid_type", FT_UINT8, BASE_DEC, VALS(mip_pmipv4skipext_subscriberid_types), 0, "Subscriber ID-Type", HFILL } }, { &hf_mip_pmipv4skipext_subscriberid_id, { "Identifier", "mip.ext.pmipv4skipext.subscriberid_id", FT_BYTES, BASE_NONE, NULL, 0, "Subscriber ID Identifier", HFILL } }, { &hf_mip_pmipv4skipext_accesstechnology_type, { "Access Technology Type", "mip.ext.pmipv4skipext.accesstechnology_type", FT_UINT8, BASE_DEC, VALS(mip_pmipv4skipext_accesstechnology_types), 0, NULL, HFILL } }, { &hf_mip_cvse_reserved, { "CVSE Reserved", "mip.ext.cvse.reserved", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_mip_cvse_vendor_org_id, { "CVSE Vendor/org ID", "mip.ext.cvse.vendor_id", FT_UINT32, BASE_DEC|BASE_EXT_STRING, &sminmpec_values_ext, 0, NULL, HFILL } }, { &hf_mip_cvse_verizon_cvse_type , { "Verizon CVSE Type", "mip.ext.cvse.verizon_type", FT_UINT16, BASE_DEC, VALS(mip_cvse_verizon_cvse_types), 0, NULL, HFILL } }, { &hf_mip_cvse_3gpp2_cvse_type , { "3GPP2 CVSE Type","mip.ext.cvse.3gpp2_type", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_mip_cvse_3gpp2_grekey, { "GRE Key","mip.ext.cvse.3gpp2_grekey", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_mip_cvse_vendor_cvse_type, { "Vendor CVSE Type", "mip.ext.cvse.vendor_type", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_mip_cvse_vendor_cvse_value, { "Vendor CVSE Value", "mip.ext.cvse.vendor_value", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_mip_nvse_reserved, { "Reserved", "mip.ext.nvse.reserved", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_mip_nvse_vendor_org_id, { "Vendor ID", "mip.ext.nvse.vendor_id", FT_UINT32, BASE_DEC|BASE_EXT_STRING, &sminmpec_values_ext, 0, NULL, HFILL } }, { &hf_mip_nvse_vendor_nvse_type , { "Vendor Type", "mip.ext.nvse.vendor_type", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_mip_nvse_vendor_nvse_value , { "Vendor Value", "mip.ext.nvse.vendor_value", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_mip_nvse_3gpp2_type , { "Type", "mip.ext.nvse.3gpp2.type", FT_UINT16, BASE_DEC, VALS(mip_nvse_3gpp2_type_vals), 0, NULL, HFILL } }, { &hf_mip_nvse_3gpp2_type16_value , { "value", "mip.ext.nvse.3gpp2.type16.value", FT_UINT16, BASE_DEC, VALS(mip_nvse_3gpp2_type17_vals), 0, NULL, HFILL } }, { &hf_mip_nvse_3gpp2_type17_entity, { "Entity-Type", "mip.ext.nvse.3gpp2.type17.entity", FT_UINT8, BASE_DEC, VALS(mip_nvse_3gpp2_type17_entity_vals), 0, NULL, HFILL } }, { &hf_mip_nvse_3gpp2_type17_subtype1, { "Sub-Type1", "mip.ext.nvse.3gpp2.type17.subtype1", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_mip_nvse_3gpp2_type17_length, { "Length", "mip.ext.nvse.3gpp2.type17.length", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_mip_nvse_3gpp2_type17_subtype2, { "Sub-Type2", "mip.ext.nvse.3gpp2.type17.subtype2", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_mip_nvse_3gpp2_type17_prim_dns, { "Primary DNS", "mip.ext.nvse.3gpp2.type17.prim_dns", FT_IPv4, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_mip_nvse_3gpp2_type17_sec_dns, { "Secondary DNS", "mip.ext.nvse.3gpp2.type17.sec_dns", FT_IPv4, BASE_NONE, NULL, 0, NULL, HFILL } }, }; /* Setup protocol subtree array */ static gint *ett[] = { &ett_mip, &ett_mip_flags, &ett_mip_ext, &ett_mip_exts, &ett_mip_pmipv4_ext, }; static ei_register_info ei[] = { { &ei_mip_data_not_dissected, { "mip.data_not_dissected", PI_UNDECODED, PI_WARN, "Data not dissected yet", EXPFILL }}, }; expert_module_t* expert_mip; /* Register the protocol name and description */ proto_mip = proto_register_protocol("Mobile IP", "Mobile IP", "mip"); /* Register the dissector by name */ register_dissector("mip", dissect_mip, proto_mip); /* Required function calls to register the header fields and subtrees used */ proto_register_field_array(proto_mip, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); expert_mip = expert_register_protocol(proto_mip); expert_register_field_array(expert_mip, ei, array_length(ei)); mip_nvse_ext_dissector_table = register_dissector_table("mip.nvse_ext", "MIP Normal Vendor/Organization Specific Extension", proto_mip, FT_UINT32, BASE_DEC); } void proto_reg_handoff_mip(void) { dissector_handle_t mip_handle; mip_handle = find_dissector("mip"); ip_handle = find_dissector_add_dependency("ip", proto_mip); dissector_add_uint("udp.port", UDP_PORT_MIP, mip_handle); /* Register as dissector for 3GPP2 NVSE */ dissector_add_uint("mip.nvse_ext", VENDOR_THE3GPP2, create_dissector_handle(dissect_mip_priv_ext_3gpp2, proto_mip)); } /* * Editor modelines * * Local Variables: * c-basic-offset: 2 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=2 tabstop=8 expandtab: * :indentSize=2:tabSize=8:noTabs=true: */
gpl-3.0
id-Software/Enemy-Territory
src/botai/ai_dmgoal_mp.c
7
101248
/* =========================================================================== Wolfenstein: Enemy Territory GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Wolfenstein: Enemy Territory GPL Source Code (“Wolf ET Source Code”). Wolf ET 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. Wolf ET 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 Wolf ET Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Wolf: ET 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 Wolf ET 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. =========================================================================== */ /***************************************************************************** * name: ai_dmgoal_mp.c * * desc: Wolf bot AI * * *****************************************************************************/ // // MULTIPLAYER GOAL AI // #include "../game/g_local.h" #include "../game/botlib.h" #include "../game/be_aas.h" #include "../game/be_ea.h" #include "../game/be_ai_char.h" #include "../game/be_ai_chat.h" #include "../game/be_ai_gen.h" #include "../game/be_ai_goal.h" #include "../game/be_ai_move.h" #include "../game/be_ai_weap.h" #include "../botai/botai.h" // #include "ai_main.h" #include "ai_team.h" #include "ai_dmq3.h" #include "ai_cmd.h" // #include "ai_dmnet_mp.h" #include "ai_dmgoal_mp.h" static bot_goal_t target; /* ================== BotMP_CheckClassActions() ================== */ qboolean BotMP_CheckClassActions( bot_state_t *bs ) { qboolean hasLeader; // // if carrying flag, screw others if ( BotCarryingFlag( bs->client ) && bs->enemy > -1 ) { return qfalse; } // if we are following a carrier, or a non-bot, then stay close hasLeader = qfalse; if ( bs->leader > -1 ) { if ( BotCarryingFlag( bs->leader ) || !( g_entities[bs->leader].r.svFlags & SVF_BOT ) ) { hasLeader = qtrue; } } /* if( bs->script.frameFlags & BSFFL_MOVETOTARGET ) { hasLeader = qtrue; // dont go so far if we're trying to get to a marker }*/ if ( bs->ainode == AINode_MP_MoveToAutonomyRange ) { hasLeader = qtrue; // dont go too far off course } if ( BotClass_MedicCheckRevives( bs, ( hasLeader ? 300 : 600 ), &target, qtrue ) ) { if ( target.entitynum != bs->target_goal.entitynum || bs->ainode != AINode_MP_MedicRevive ) { bs->target_goal = target; AIEnter_MP_MedicRevive( bs ); } return qtrue; } if ( BotCarryingFlag( bs->client ) ) { return qfalse; // only revive if we have flag (Gordon: or skip other checks if we have flag to make more sense...) } if ( BotClass_MedicCheckGiveHealth( bs, ( hasLeader ? 200 : 800 ), &target ) ) { if ( target.entitynum != bs->target_goal.entitynum || bs->ainode != AINode_MP_MedicGiveHealth ) { bs->target_goal = target; AIEnter_MP_MedicGiveHealth( bs ); } return qtrue; } if ( BotClass_LtCheckGiveAmmo( bs, ( hasLeader ? 200 : 800 ), &target ) ) { if ( target.entitynum != bs->target_goal.entitynum || bs->ainode != AINode_MP_GiveAmmo ) { bs->target_goal = target; AIEnter_MP_GiveAmmo( bs ); } return qtrue; } return qfalse; } /* =================== BotMP_CheckEmergencyGoals =================== */ qboolean BotMP_CheckEmergencyGoals( bot_state_t *bs ) { gentity_t *trav, *flag; int i, t; int list[32], numList; int oldest = 0, oldestTime, oldIgnoreTime, areanum, numTeammates; float dist, bestDist; vec3_t center, brushPos, vec; trace_t tr; // if ( bs->last_checkemergencytargets > level.time - 300 ) { return qfalse; } bs->last_checkemergencytargets = level.time + rand() % 200; // oldIgnoreTime = bs->ignore_specialgoal_time; bs->ignore_specialgoal_time = level.time + 2000; numTeammates = BotNumTeamMates( bs, NULL, 0 ); // check for voice chats BotCheckVoiceChats( bs ); // if a bot finds itself in a void, it should use DrirectMove() to get out of it if ( !bs->areanum ) { if ( bs->ainode == AINode_MP_NavigateFromVoid ) { return qfalse; } AIEnter_MP_NavigateFromVoid( bs ); return qtrue; } // DEBUG MODE: bot_debug = 11 trap_Cvar_Update( &bot_debug ); if ( g_cheats.integer && bot_debug.integer == BOT_DEBUG_FOLLOW_PLAYER ) { bs->leader = 0; if ( BotGoalForEntity( bs, bs->leader, &target, BGU_LOW ) ) { if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = target; AIEnter_MP_DefendTarget( bs ); return qtrue; } else { bs->leader = -1; } // DEBUG MODE: bot_debug = 12 (dont look for goals) } else if ( g_cheats.integer && bot_debug.integer == BOT_DEBUG_FOLLOW_PLAYER + 1 ) { return qfalse; } if ( !BotIsPOW( bs ) ) { // check for being outside autonomy range within reasonable cause if ( BotCheckMovementAutonomy( bs, &bs->target_goal ) ) { if ( bs->target_goal.entitynum == bs->leader && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } if ( bs->ainode == AINode_MP_MoveToAutonomyRange ) { return qfalse; } // get back to it AIEnter_MP_MoveToAutonomyRange( bs ); return qtrue; } // check for dropped flag if ( BotFindDroppedFlag( &trav ) ) { // if we are the owner and we just dropped it, then ignore it if ( !( trav->r.ownerNum == bs->client && trav->botIgnoreTime > level.time ) ) { // if we are already going for it if ( bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_TouchTarget ) { return qfalse; //keep going for it } // GO GET IT // do we have a route to the enemy flag? if ( BotGoalForEntity( NULL, trav->s.number, &target, BGU_HIGH ) ) { target.flags = GFL_NOSLOWAPPROACH; // if ( VectorDistanceSquared( target.origin, bs->origin ) < ( 1600 * 1600 ) || trap_InPVS( target.origin, bs->origin ) ) { if ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ) ) { bs->target_goal = target; AIEnter_MP_TouchTarget( bs ); return qtrue; } //if (g_cheats.integer) // G_Printf( "WARNING: dropped objective is unreachable\n" ); } } } } } else { return qtrue; } // if we have a visible & damagable script_mover target, then we should try to blow it up if ( ( trav = BotGetVisibleDamagableScriptMover( bs ) ) ) { if ( bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_AttackTarget ) { return qfalse; } if ( BotGoalForEntity( bs, trav->s.number, &target, BGU_MAXIMUM ) ) { bs->target_goal = target; AIEnter_MP_AttackTarget( bs ); return qtrue; } } // if a checkpoint is nearby, touch it trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_CHECKPOINT ) ) ) { // if the opposition team controls this checkpoint, or it hasnt been captured yet if ( trav->count == ( bs->sess.sessionTeam == TEAM_AXIS ? TEAM_ALLIES : TEAM_AXIS ) || ( trav->count < 0 ) ) { // if we can see it VectorAdd( trav->r.absmin, trav->r.absmax, center ); VectorScale( center, 0.5, center ); if ( VectorDistanceSquared( center, bs->origin ) > ( 1024 * 1024 ) ) { continue; } center[0] = trav->r.absmax[0]; center[1] = trav->r.absmax[1]; VectorSubtract( trav->r.absmax, trav->r.absmin, vec ); vec[2] = 0; VectorNormalize( vec ); VectorAdd( center, vec, brushPos ); if ( !trap_InPVS( brushPos, bs->origin ) ) { continue; } // GO GET IT // do we have a route to the enemy flag? if ( BotGoalForEntity( bs, trav->s.number, &target, BGU_MEDIUM ) ) { // if we are already going for it if ( bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_TouchTarget ) { return qfalse; //keep going for it } target.flags = GFL_NOSLOWAPPROACH; // if ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ) ) { bs->target_goal = target; AIEnter_MP_TouchTarget( bs ); return qtrue; } } } } // in GT_WOLF mode on defense, if the flag is not at base, then all units should help get it back if ( level.captureFlagMode ) { // if ( bs->sess.sessionTeam != level.attackingTeam ) { // if ( !BotFlagAtBase( bs->sess.sessionTeam, &flag ) ) { // // if we are pursuing the flag carrier, then continue if ( bs->enemy >= 0 && BotCarryingFlag( bs->enemy ) ) { return qfalse; } // // go to the transmission point? trav = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY ); if ( !trav ) { trav = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY_MULTIPLE ); } if ( trav ) { // if ( BotNumTeamMatesWithTarget( bs, trav->s.number, NULL, 0 ) < (int)ceil( 0.5 * numTeammates ) ) { // // if we are already heading for it, then continue if ( bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } // VectorAdd( trav->r.absmin, trav->r.absmax, brushPos ); VectorScale( brushPos, 0.5, brushPos ); // find the best goal area numList = trap_AAS_BBoxAreas( trav->r.absmin, trav->r.absmax, list, 32 ); if ( numList ) { oldestTime = -1; bestDist = -1; for ( i = 0; i < numList; i++ ) { if ( !trap_AAS_AreaReachability( list[i] ) ) { continue; } t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, list[i], bs->tfl ); if ( t > 0 ) { // choose the reachable area closest to the center of the info_objective brush trap_AAS_AreaCenter( list[i], center ); VectorSubtract( brushPos, center, vec ); vec[2] = 0; dist = VectorLength( vec ); if ( bestDist < 0 || dist < bestDist ) { oldestTime = t; oldest = list[i]; bestDist = dist; } } } if ( bestDist > 0 && oldestTime < 4000 && bestDist < 2000 ) { BotClearGoal( &target ); // use this as the goal origin VectorCopy( center, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); target.areanum = oldest; target.entitynum = trav->s.number; target.flags = GFL_NOSLOWAPPROACH; // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_HIGH ) ) { // if we are already heading there, continue if ( bs->target_goal.entitynum && bs->target_goal.entitynum == trav->s.number ) { return qfalse; } // bs->target_goal = target; BotFindSparseDefendArea( bs, &bs->target_goal, qtrue ); AIEnter_MP_DefendTarget( bs ); return qtrue; } } } }/* else { // go for the document room BotFlagAtBase(bs->sess.sessionTeam, &flag); // // do we have a route to the flag? BotClearGoal(&target); target.entitynum = flag->s.number; VectorCopy( flag->r.currentOrigin, center ); center[2] += 30; target.areanum = trap_AAS_PointAreaNum(center); target.flags = GFL_NOSLOWAPPROACH; VectorCopy( flag->r.mins, target.mins ); VectorCopy( flag->r.maxs, target.maxs ); VectorCopy( flag->r.currentOrigin, target.origin ); // t = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, target.areanum, bs->tfl); if (t) { // if we are already heading there, continue if (bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_TouchTarget) return qfalse; bs->target_goal = target; BotFindSparseDefendArea(bs, &bs->target_goal); AIEnter_MP_DefendTarget(bs); return qtrue; } }*/ } // keep sending some troops to the flag carrier, so we have the most direct route covered flag = BotGetEnemyFlagCarrier( bs ); if ( flag && ( VectorDistanceSquared( flag->r.currentOrigin, bs->eye ) < ( 1024 * 1024 ) || trap_InPVS( flag->r.currentOrigin, bs->eye ) || BotNumTeamMatesWithTarget( bs, flag->s.number, NULL, 0 ) < 1 ) ) { // HACK, err... lets just take a snapshot of where they are now, and go down there bs->enemyvisible_time = trap_AAS_Time(); //update the reachability area and origin if possible areanum = BotPointAreaNum( flag->s.number, flag->r.currentOrigin ); if ( areanum && trap_AAS_AreaReachability( areanum ) && trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, areanum, bs->tfl ) ) { VectorCopy( flag->r.currentOrigin, bs->lastenemyorigin ); bs->lastenemyareanum = areanum; // if ( BotGoalForEntity( bs, flag->s.number, &target, BGU_HIGH ) ) { bs->enemy = flag->s.number; AIEnter_MP_Battle_Chase( bs ); bs->chase_time += 20.0; return qtrue; } } } } } else // if we are close to the flag, get it! { // is the enemy flag at base? if ( ( ( bs->leader == -1 ) || !trap_InPVS( bs->origin, g_entities[bs->leader].r.currentOrigin ) || ( VectorDistanceSquared( bs->origin, g_entities[bs->leader].r.currentOrigin ) > ( MAX_BOTLEADER_DIST * MAX_BOTLEADER_DIST ) ) ) && ( !BotCarryingFlag( bs->client ) ) && ( BotFlagAtBase( level.attackingTeam == TEAM_AXIS ? TEAM_ALLIES : TEAM_AXIS, &flag ) == qtrue ) ) { qboolean getflag = qtrue; // // check special circumstances in which we should not go for the flag if ( bs->ainode == AINode_MP_MedicRevive || bs->ainode == AINode_MP_MedicGiveHealth ) { // if we are close to them, continue if ( trap_InPVS( bs->origin, g_entities[bs->target_goal.entitynum].r.currentOrigin ) && VectorDistanceSquared( bs->origin, g_entities[bs->target_goal.entitynum].r.currentOrigin ) < ( 512 * 512 ) ) { getflag = qfalse; } } // if ( getflag ) { // GO GET IT // do we have a route to the enemy flag? if ( BotGoalForEntity( bs, flag->s.number, &target, BGU_MEDIUM ) ) { target.flags = GFL_NOSLOWAPPROACH; // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( t ) { if ( trap_InPVS( bs->origin, target.origin ) ) { t = t / 2 - 300; } if ( t <= 0 ) { t = 1; } if ( t < 700 ) { if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_MEDIUM ) ) { if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_TouchTarget ) { return qfalse; } bs->target_goal = target; AIEnter_MP_TouchTarget( bs ); return qtrue; } } } } } } } } // check for medic trying to give us health // NOTE: check that we havent just spawned, since this can cause congestion at the start if ( ( g_entities[bs->client].client->respawnTime < level.time - 12000 ) && g_entities[bs->client].awaitingHelpTime > level.time + 200 ) { if ( bs->enemy < 0 && bs->stand_time < trap_AAS_Time() && !BotCarryingFlag( bs->client ) ) { AIEnter_MP_Stand( bs ); bs->stand_time = trap_AAS_Time() + 1.0; return qtrue; } } // if we are a medic, we should always revive nearby players if ( BotClass_MedicCheckRevives( bs, 300, &target, qtrue ) ) { if ( !BotCarryingFlag( bs->client ) || ( ( bs->enemy == -1 ) && ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, bs->target_goal.areanum, bs->tfl ) > 600 ) ) ) { if ( target.entitynum == bs->target_goal.entitynum && bs->ainode != AINode_MP_MedicRevive ) { return qfalse; } bs->target_goal = target; AIEnter_MP_MedicRevive( bs ); return qtrue; } } // PANZER TARGETS if ( ( COM_BitCheck( bs->cur_ps.weapons, WP_PANZERFAUST ) ) ) { if ( ( BotWeaponWantScale( bs, WP_PANZERFAUST ) > 0 ) ) { team_t team = bs->sess.sessionTeam == TEAM_AXIS ? TEAM_ALLIES : TEAM_AXIS; // shoot towards gun emplacements after spawning in i = 0; trav = NULL; numList = 0; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_MG42 ) ) ) { if ( ( trav->aiInactive && ( 1 << team ) ) ) { continue; } if ( trav->s.powerups != STATE_DEFAULT ) { continue; } if ( trav->health <= 0 ) { continue; } // make sure we can see it VectorCopy( trav->r.currentOrigin, center ); center[2] += 12; if ( !trap_InPVS( bs->eye, center ) ) { continue; } trap_Trace( &tr, bs->eye, NULL, NULL, center, bs->client, MASK_MISSILESHOT ); if ( tr.fraction < 1.0 && tr.entityNum != trav->s.number ) { continue; } // list[numList++] = trav->s.number; i++; } // if ( i ) { // pick a random mg42 t = rand() % i; trav = BotGetEntity( list[t] ); // trav is the mg42 trav->missionLevel = level.time + 10000; // target.entitynum = trav->s.number; VectorCopy( trav->r.currentOrigin, center ); center[2] += 12; VectorCopy( center, target.origin ); // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_HIGH ) ) { bs->target_goal = target; AIEnter_MP_PanzerTarget( bs ); return qtrue; } } } } // defense engineers should look for dynamite placed nearby objectives to defuse { int list[10], numList; // if ( ( numList = BotGetTargetDynamite( list, 10, NULL ) ) ) { for ( i = 0; i < numList; i++ ) { trav = BotGetEntity( list[i] ); if ( !trav ) { continue; } // Gordon: WTH is this for? if ( bs->sess.playerType != PC_ENGINEER ) { if ( BotCanSnipe( bs, qtrue ) ) { if ( level.explosiveTargets[bs->sess.sessionTeam == TEAM_AXIS ? 0 : 1] != BotGetTargetExplosives( bs->sess.sessionTeam, NULL, 0, qfalse ) || BotNumTeamMatesWithTarget( bs, list[i], NULL, 0 ) >= (int)( floor( 0.3 * numTeammates / numList ) ) ) { continue; } } } // if this dynamite has been laid by our team, and we are an engineer, no need to defend it if ( bs->sess.playerType == PC_ENGINEER && ( ( trav->s.teamNum % 4 ) == bs->sess.sessionTeam ) ) { continue; } //if (trav->missionLevel > level.time) continue; if ( BotNumTeamMatesWithTarget( bs, trav->s.number, NULL, 0 ) > (int)floor( (float)( numTeammates / numList ) ) ) { continue; } VectorAdd( trav->r.absmin, trav->r.absmax, center ); VectorScale( center, 0.5, center ); if ( ( areanum = BotPointAreaNum( trav->s.number, center ) ) ) { //if (areanum = BotReachableBBoxAreaNum( bs, trav->r.absmin, trav->r.absmax )) { if ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, areanum, bs->tfl ) ) { // make this our goal BotClearGoal( &target ); target.entitynum = trav->s.number; target.areanum = areanum; VectorCopy( trav->r.mins, target.mins ); VectorCopy( trav->r.maxs, target.maxs ); VectorCopy( center, target.origin ); // // if we are an engineer, and this is hostile dynamite, we should defuse it, otherwise defend it if ( bs->sess.playerType == PC_ENGINEER && ( ( trav->s.teamNum % 4 ) != bs->sess.sessionTeam ) ) { if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_HIGH ) ) { // if we are already heading there, continue if ( bs->target_goal.entitynum && bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_DisarmDynamite ) { return qfalse; } bs->target_goal = target; trav->missionLevel = level.time + 5000; AIEnter_MP_DisarmDynamite( bs ); return qtrue; } // only "defend" the dynamite if they are yet to break through any of the defenses } else if ( ( BotNumTeamMatesWithTargetAndCloser( bs, target.entitynum, target.areanum, NULL, 0, -1 ) < (int)( ceil( 0.3 * numTeammates / numList ) ) ) ) { // if we are already heading there, continue if ( bs->target_goal.entitynum && bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } // just "defend" it bs->target_goal = target; BotFindSparseDefendArea( bs, &bs->target_goal, qtrue ); AIEnter_MP_DefendTarget( bs ); return qtrue; } } } } } } // // look for healing/giving ammo to others if ( BotMP_CheckClassActions( bs ) ) { return qtrue; } // bs->ignore_specialgoal_time = oldIgnoreTime; return qfalse; } int botgoalPriorities_Standard[BFG_NUMBOTGOALTYPES] = { 0, // BFG_FOLLOW_LEADER -1, // BFG_CONSTRUCT 2, // BFG_TRIGGER -1, // BFG_DESTRUCTION_EXPLOSIVE -1, // BFG_DESTRUCTION_BUILDING -1, // BFG_MG42_REPAIR -1, // BFG_MINE 1, // BFG_ATTRACTOR -1, // BFG_SNIPERSPOT 2, // BFG_MG42 -1, // BFG_SCANFORMINES -1, // BFG_DESTRUCTION_SATCHEL }; int botgoalPriorities_Engineer[BFG_NUMBOTGOALTYPES] = { 1, // BFG_FOLLOW_LEADER 5, // BFG_CONSTRUCT 3, // BFG_TRIGGER 5, // BFG_DESTRUCTION_EXPLOSIVE 5, // BFG_DESTRUCTION_BUILDING 4, // BFG_MG42_REPAIR 4, // BFG_MINE 2, // BFG_ATTRACTOR -1, // BFG_SNIPERSPOT 0, // BFG_MG42 -1, // BFG_SCANFORMINES -1, // BFG_DESTRUCTION_SATCHEL }; int botgoalPriorities_CovertOps[BFG_NUMBOTGOALTYPES] = { 1, // BFG_FOLLOW_LEADER -1, // BFG_CONSTRUCT 3, // BFG_TRIGGER -1, // BFG_DESTRUCTION_EXPLOSIVE -1, // BFG_DESTRUCTION_BUILDING -1, // BFG_MG42_REPAIR -1, // BFG_MINE 2, // BFG_ATTRACTOR 4, // BFG_SNIPERSPOT 0, // BFG_MG42 4, // BFG_SCANFORMINES 4, // BFG_DESTRUCTION_SATCHEL }; int *botgoalPriorities_Class[NUM_PLAYER_CLASSES] = { botgoalPriorities_Standard, // PC_SOLDIER botgoalPriorities_Standard, // PC_MEDIC botgoalPriorities_Engineer, // PC_ENGINEER botgoalPriorities_Standard, // PC_FIELDOPS botgoalPriorities_CovertOps // PC_COVERTOPS }; int botgoalMaxCloser[BFG_NUMBOTGOALTYPES] = { 2, // BFG_FOLLOW_LEADER 1, // BFG_CONSTRUCT 2, // BFG_TRIGGER 1, // BFG_DESTRUCTION_EXPLOSIVE 1, // BFG_DESTRUCTION_BUILDING 0, // BFG_MG42_REPAIR 0, // BFG_MINE 2, // BFG_ATTRACTOR 0, // BFG_SNIPERSPOT 0, // BFG_MG42 0, // BFG_SCANFORMINES 0, // BFG_DESTRUCTION_SATCHEL }; typedef struct botgoalFind_s { gentity_t* ent; botgoalFindType_t type; qboolean ignore; int priority; int defaultPriority; int numPlayers; } botgoalFind_t; #define MAX_FIND_BOTGOALS 32 #define BFG_CHECKMAX if ( goalNum >= maxGoals ) { return maxGoals; } #define BFG_CHECKDISABLED( ent,bs ) ent->aiInactive & ( 1 << bs->sess.sessionTeam ) int BotMP_FindGoal_BuildGoalList( bot_state_t* bs, botgoalFind_t* pGoals, int maxGoals ) { int goalNum = 0; int leader, numTargets; int k, c; int tlist[10]; gentity_t *ent, *trav; BFG_CHECKMAX; leader = BotGetLeader( bs, ( bs->sess.playerType == PC_SOLDIER ) ); if ( leader != -1 && g_entities[leader].r.svFlags & SVF_BOT ) { pGoals[goalNum].type = BFG_FOLLOW_LEADER; pGoals[goalNum].ent = &g_entities[leader]; pGoals[goalNum].priority = g_entities[leader].goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } // trigger_multiples trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_TRIGGER_MULTIPLE ) ) ) { // is it disabled? if ( BFG_CHECKDISABLED( trav, bs ) ) { continue; } // is it active? if ( !trav->r.linked || ( trav->nextthink > level.time + 1000 ) ) { continue; // if it's thinking, then it's not active (doesnt respond to touch) } pGoals[goalNum].type = BFG_TRIGGER; pGoals[goalNum].ent = trav; pGoals[goalNum].priority = trav->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } if ( bs->sess.playerType == PC_ENGINEER ) { // Constructibles // find a constructible trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_OBJECTIVE_INFO ) ) ) { // is it disabled? if ( BFG_CHECKDISABLED( trav, bs ) ) { continue; } // find the constructible ent = G_ConstructionForTeam( trav, bs->sess.sessionTeam ); if ( !ent ) { continue; } if ( !BotIsConstructible( bs->sess.sessionTeam, trav->s.number ) ) { continue; } pGoals[goalNum].type = BFG_CONSTRUCT; pGoals[goalNum].ent = trav; pGoals[goalNum].priority = trav->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } // check for dynamite // look for things to blow up if ( BotWeaponCharged( bs, WP_DYNAMITE ) ) { numTargets = BotGetTargetExplosives( bs->sess.sessionTeam, tlist, 10, qfalse ); for ( k = 0; k < numTargets; k++ ) { // see if this is a worthy goal ent = &g_entities[tlist[k]]; if ( ent->s.eType == ET_OID_TRIGGER ) { pGoals[goalNum].type = BFG_DESTRUCTION_EXPLOSIVE; if ( ent->target_ent ) { pGoals[goalNum].priority = ent->target_ent->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; } else { // Gordon: this shouldn't happen really.... pGoals[goalNum].priority = ent->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; } } else { pGoals[goalNum].type = BFG_DESTRUCTION_BUILDING; pGoals[goalNum].priority = ent->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; } pGoals[goalNum].ent = ent; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } } // look for a broken MG42 that isnt already being fixed trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_MG42 ) ) ) { // is it disabled? if ( BFG_CHECKDISABLED( trav, bs ) ) { continue; } if ( trav->health <= 0 ) { if ( trav->melee ) { ent = trav->melee; if ( ( ent->botIgnoreTime < level.time ) ) { pGoals[goalNum].type = BFG_MG42_REPAIR; pGoals[goalNum].ent = ent; pGoals[goalNum].priority = trav->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } } } } // PLANT LAND MINES if ( G_CountTeamLandmines( bs->sess.sessionTeam ) < MAX_TEAM_LANDMINES ) { // look for a land mine area that isn't full trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_BOT_LANDMINE_AREA ) ) ) { // is it disabled? if ( BFG_CHECKDISABLED( trav, bs ) ) { continue; } // is it for us? if ( ( trav->spawnflags & 1 ) && ( bs->sess.sessionTeam != TEAM_AXIS ) ) { continue; } else if ( ( trav->spawnflags & 2 ) && ( bs->sess.sessionTeam != TEAM_ALLIES ) ) { continue; } // has it got enough landmines? if ( trav->count2 >= trav->count ) { continue; } pGoals[goalNum].type = BFG_MINE; pGoals[goalNum].ent = trav; pGoals[goalNum].priority = trav->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } } } trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_BOT_ATTRACTOR ) ) ) { if ( BFG_CHECKDISABLED( trav, bs ) ) { continue; } pGoals[goalNum].type = BFG_ATTRACTOR; pGoals[goalNum].ent = trav; pGoals[goalNum].priority = trav->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } // SNIPER SPOT if ( BotCanSnipe( bs, qtrue ) ) { c = BotBestSniperSpot( bs ); if ( c != -1 ) { pGoals[goalNum].type = BFG_SNIPERSPOT; pGoals[goalNum].ent = &g_entities[c]; pGoals[goalNum].priority = g_entities[c].goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } } if ( bs->sess.playerType == PC_COVERTOPS ) { c = BotBestLandmineSpotingSpot( bs ); if ( c != -1 ) { pGoals[goalNum].type = BFG_SCANFORMINES; pGoals[goalNum].ent = &g_entities[c]; pGoals[goalNum].priority = g_entities[c].goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } numTargets = BotGetTargetsForSatchelCharge( bs->sess.sessionTeam, tlist, 10, qfalse ); for ( k = 0; k < numTargets; k++ ) { // see if this is a worthy goal ent = &g_entities[tlist[k]]; pGoals[goalNum].type = BFG_DESTRUCTION_SATCHEL; pGoals[goalNum].priority = ent->goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].ent = ent; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } } // MG42 c = BotBestMG42Spot( bs, qfalse ); if ( c != -1 ) { pGoals[goalNum].type = BFG_MG42; pGoals[goalNum].ent = &g_entities[c]; pGoals[goalNum].priority = g_entities[c].goalPriority[bs->sess.sessionTeam - TEAM_AXIS]; pGoals[goalNum].defaultPriority = botgoalPriorities_Class[bs->sess.playerType][pGoals[goalNum].type]; goalNum++; BFG_CHECKMAX; } return goalNum; } int QDECL BotMP_FindGoals_Sort_Standard( const void *a, const void *b ) { botgoalFind_t* bg1 = (botgoalFind_t*)a; botgoalFind_t* bg2 = (botgoalFind_t*)b; if ( botgoalPriorities_Standard[bg1->type] > botgoalPriorities_Standard[bg2->type] ) { return -1; } else if ( botgoalPriorities_Standard[bg2->type] > botgoalPriorities_Standard[bg1->type] ) { return 1; } if ( bg1->priority > bg2->priority ) { return -1; } else if ( bg2->priority > bg1->priority ) { return 1; } return 0; } int QDECL BotMP_FindGoals_Sort_Engineer( const void *a, const void *b ) { botgoalFind_t* bg1 = (botgoalFind_t*)a; botgoalFind_t* bg2 = (botgoalFind_t*)b; if ( botgoalPriorities_Engineer[bg1->type] > botgoalPriorities_Engineer[bg2->type] ) { return -1; } else if ( botgoalPriorities_Engineer[bg2->type] > botgoalPriorities_Engineer[bg1->type] ) { return 1; } if ( bg1->priority > bg2->priority ) { return -1; } else if ( bg2->priority > bg1->priority ) { return 1; } return 0; } int QDECL BotMP_FindGoals_Sort_CovertOps( const void *a, const void *b ) { botgoalFind_t* bg1 = (botgoalFind_t*)a; botgoalFind_t* bg2 = (botgoalFind_t*)b; if ( botgoalPriorities_CovertOps[bg1->type] > botgoalPriorities_CovertOps[bg2->type] ) { return -1; } else if ( botgoalPriorities_CovertOps[bg2->type] > botgoalPriorities_CovertOps[bg1->type] ) { return 1; } if ( bg1->priority > bg2->priority ) { return -1; } else if ( bg2->priority > bg1->priority ) { return 1; } return 0; } typedef int QDECL sortFunc ( const void *a, const void *b ); sortFunc* botmp_sortFuncs[NUM_PLAYER_CLASSES] = { BotMP_FindGoals_Sort_Standard, // PC_SOLDIER BotMP_FindGoals_Sort_Standard, // PC_MEDIC BotMP_FindGoals_Sort_Engineer, // PC_ENGINEER BotMP_FindGoals_Sort_Standard, // PC_FIELDOPS BotMP_FindGoals_Sort_CovertOps // PC_COVERTOPS }; int BotMP_FindGoal_ClassForGoalType( botgoalFindType_t type ) { switch ( type ) { case BFG_CONSTRUCT: case BFG_DESTRUCTION_EXPLOSIVE: case BFG_DESTRUCTION_BUILDING: case BFG_MG42_REPAIR: case BFG_MINE: return PC_ENGINEER; case BFG_SNIPERSPOT: case BFG_SCANFORMINES: case BFG_DESTRUCTION_SATCHEL: return PC_COVERTOPS; default: break; } return -1; } #define BFG_RETURN_SUCCESS return BPG_NEWGOAL #define BFG_RETURN_FAILURE return BPG_FAILED #define BFG_RETURN_ALREADY return BPG_ALREADYDOING #define BFG_RETURN_FAILURE_AND_IGNORE bg->ignore = qtrue; BFG_RETURN_FAILURE #define BFG_GOAL_ENTITYNUM bg->ent - g_entities typedef enum botMPpg_e { BPG_FAILED, BPG_NEWGOAL, BPG_ALREADYDOING, } botMPpg_t; botMPpg_t BotMP_FindGoal_ProcessGoal( bot_state_t* bs, botgoalFind_t* bg, bot_goal_t* target_goal ) { int t, i; vec3_t mins, maxs; vec3_t center, brushPos, vec, end; vec_t dist; int list[32]; int numList; trace_t tr; weapon_t weap; switch ( bg->type ) { case BFG_FOLLOW_LEADER: // we have a leader, follow them if ( BotGoalForEntity( bs, BFG_GOAL_ENTITYNUM, target_goal, BGU_LOW ) ) { target_goal->flags = GFL_LEADER; t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target_goal->areanum, bs->tfl ); if ( t && t <= MAX_BOTLEADER_TRAVEL ) { BotFindSparseDefendArea( bs, target_goal, qtrue ); if ( bs->target_goal.entitynum == target_goal->entitynum && bs->ainode == AINode_MP_DefendTarget ) { BFG_RETURN_ALREADY; } BFG_RETURN_SUCCESS; } } bs->leader = -1; BFG_RETURN_FAILURE_AND_IGNORE; case BFG_CONSTRUCT: if ( !BotGetReachableEntityArea( bs, BFG_GOAL_ENTITYNUM, target_goal ) ) { BFG_RETURN_FAILURE_AND_IGNORE; // not reachable } if ( bs->target_goal.entitynum == BFG_GOAL_ENTITYNUM && bs->ainode == AINode_MP_ConstructibleTarget ) { BFG_RETURN_ALREADY; // already going for it } // Gordon: if this is a new goal, check pliers are half-full before heading off (optimist ;)) if ( bs->cur_ps.classWeaponTime > ( level.time - ( level.engineerChargeTime[bs->sess.sessionTeam - 1] * 0.5f ) ) ) { BFG_RETURN_FAILURE_AND_IGNORE; } t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target_goal->areanum, bs->tfl ); if ( !t ) { BFG_RETURN_FAILURE_AND_IGNORE; // failed for whatever reason } BFG_RETURN_SUCCESS; case BFG_TRIGGER: if ( !BotGetReachableEntityArea( bs, BFG_GOAL_ENTITYNUM, target_goal ) ) { BFG_RETURN_FAILURE_AND_IGNORE; // not reachable } if ( !BotGoalWithinMovementAutonomy( bs, target_goal, BGU_LOW ) ) { BFG_RETURN_FAILURE_AND_IGNORE; // outside autonomy range } // if the current destination is not touching the brush, abort VectorAdd( target_goal->origin, bs->cur_ps.mins, mins ); VectorAdd( target_goal->origin, bs->cur_ps.maxs, maxs ); if ( !trap_EntityContactCapsule( mins, maxs, bg->ent ) ) { BFG_RETURN_FAILURE_AND_IGNORE; } // get the travel time t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target_goal->areanum, bs->tfl ); if ( !t ) { BFG_RETURN_FAILURE_AND_IGNORE; } // is it for us only? if ( ( ( bg->ent->spawnflags & 1 ) && ( bs->sess.sessionTeam == TEAM_AXIS ) ) || ( ( bg->ent->spawnflags & 2 ) && ( bs->sess.sessionTeam == TEAM_ALLIES ) ) ) { if ( bs->target_goal.entitynum == target_goal->entitynum && bs->ainode == AINode_MP_TouchTarget ) { BFG_RETURN_ALREADY; } BFG_RETURN_SUCCESS; } else { // defend it if ( bs->target_goal.entitynum == target_goal->entitynum && bs->ainode == AINode_MP_DefendTarget ) { BFG_RETURN_ALREADY; } BFG_RETURN_SUCCESS; } case BFG_DESTRUCTION_EXPLOSIVE: // calc center VectorAdd( bg->ent->r.absmin, bg->ent->r.absmax, brushPos ); VectorScale( brushPos, 0.5, brushPos ); // find the best goal area numList = trap_AAS_BBoxAreas( bg->ent->r.absmin, bg->ent->r.absmax, list, 32 ); if ( numList ) { int oldestTime = -1; int bestDist = -1; int oldest = 0; for ( i = 0; i < numList; i++ ) { if ( !trap_AAS_AreaReachability( list[i] ) ) { continue; } t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, list[i], bs->tfl ); if ( t > 0 && t < 400 ) { // choose the reachable area closest to the center of the info_objective brush trap_AAS_AreaCenter( list[i], center ); VectorSubtract( brushPos, center, vec ); vec[2] = 0; dist = VectorLength( vec ); if ( bestDist < 0 || dist < bestDist ) { oldestTime = t; oldest = list[i]; bestDist = dist; } } } if ( oldestTime > 0 ) { // now trace from this area towards the func_explosive trap_AAS_AreaCenter( oldest, center ); VectorCopy( center, end ); end[2] -= 512; trap_Trace( &tr, center, bs->cur_ps.mins, bs->cur_ps.maxs, end, -1, MASK_PLAYERSOLID & ~CONTENTS_BODY ); VectorCopy( tr.endpos, center ); t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, oldest, bs->tfl ); if ( t ) { bg->ent->lastHintCheckTime = level.time + 5000; // use this as the goal origin VectorCopy( center, target_goal->origin ); VectorCopy( bs->cur_ps.mins, target_goal->mins ); VectorCopy( bs->cur_ps.maxs, target_goal->maxs ); target_goal->areanum = oldest; target_goal->entitynum = BFG_GOAL_ENTITYNUM; if ( bs->target_goal.entitynum == target_goal->entitynum && bs->ainode == AINode_MP_DynamiteTarget ) { BFG_RETURN_ALREADY; } BFG_RETURN_SUCCESS; } } } BFG_RETURN_FAILURE_AND_IGNORE; case BFG_DESTRUCTION_BUILDING: case BFG_DESTRUCTION_SATCHEL: if ( bg->type == BFG_DESTRUCTION_BUILDING ) { weap = WP_DYNAMITE; } else { weap = WP_SATCHEL; } VectorAdd( bg->ent->r.absmin, bg->ent->r.absmax, brushPos ); VectorScale( brushPos, 0.5, brushPos ); VectorCopy( bg->ent->r.absmin, mins ); VectorCopy( bg->ent->r.absmax, maxs ); for ( i = 0; i < 2; i++ ) { mins[i] -= G_GetWeaponDamage( weap ) * 0.2f; maxs[i] += G_GetWeaponDamage( weap ) * 0.2f; } // find the best goal area numList = trap_AAS_BBoxAreas( mins, maxs, list, 32 ); if ( numList ) { int oldestTime = -1; int bestDist = -1; int oldest = 0; for ( i = 0; i < numList; i++ ) { if ( !trap_AAS_AreaReachability( list[i] ) ) { continue; } // RF, make sure this is within range trap_AAS_AreaCenter( list[i], center ); VectorCopy( center, end ); end[2] -= 512; trap_Trace( &tr, center, bs->cur_ps.mins, bs->cur_ps.maxs, end, -1, MASK_PLAYERSOLID & ~CONTENTS_BODY ); VectorCopy( tr.endpos, center ); VectorSubtract( center, brushPos, vec ); G_AdjustedDamageVec( bg->ent, center, vec ); if ( ( VectorLengthSquared( vec ) <= SQR( G_GetWeaponDamage( weap ) ) ) && CanDamage( bg->ent, center ) ) { t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, list[i], bs->tfl ); if ( t ) { oldestTime = t; oldest = list[i]; bestDist = t; } } } if ( oldestTime != -1 ) { // now trace from this area towards the func_explosive trap_AAS_AreaCenter( oldest, center ); VectorCopy( center, end ); end[2] -= 512; trap_Trace( &tr, center, bs->cur_ps.mins, bs->cur_ps.maxs, end, -1, MASK_PLAYERSOLID & ~CONTENTS_BODY ); VectorCopy( tr.endpos, center ); t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, oldest, bs->tfl ); if ( t ) { bg->ent->lastHintCheckTime = level.time + 5000; // use this as the goal origin VectorCopy( center, target_goal->origin ); VectorCopy( bs->cur_ps.mins, target_goal->mins ); VectorCopy( bs->cur_ps.maxs, target_goal->maxs ); target_goal->areanum = oldest; target_goal->entitynum = BFG_GOAL_ENTITYNUM; if ( BotGoalWithinMovementAutonomy( bs, target_goal, BGU_LOW ) ) { if ( bs->target_goal.entitynum == target_goal->entitynum ) { if ( bs->ainode == AINode_MP_DynamiteTarget ) { BFG_RETURN_ALREADY; } // Gordon: FIXME: insert satchel node here /* if( bs->ainode == AINode_MP_DynamiteTarget ) { BFG_RETURN_ALREADY; }*/ } BFG_RETURN_SUCCESS; } BFG_RETURN_SUCCESS; } } } BFG_RETURN_FAILURE_AND_IGNORE; case BFG_MG42_REPAIR: if ( BotGoalForEntity( bs, BFG_GOAL_ENTITYNUM, target_goal, BGU_LOW ) ) { t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target_goal->areanum, bs->tfl ); if ( t < 500 ) { if ( bs->target_goal.entitynum == target_goal->entitynum && bs->ainode == AINode_MP_FixMG42 ) { BFG_RETURN_ALREADY; } // go fix it!! BFG_RETURN_SUCCESS; } } BFG_RETURN_FAILURE_AND_IGNORE; case BFG_MINE: if ( !BotGoalForEntity( bs, BFG_GOAL_ENTITYNUM, target_goal, BGU_LOW ) ) { BFG_RETURN_FAILURE_AND_IGNORE; } if ( bs->target_goal.entitynum == BFG_GOAL_ENTITYNUM && bs->ainode == AINode_MP_PlantMine ) { BFG_RETURN_ALREADY; } // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target_goal->areanum, bs->tfl ); if ( !t ) { BFG_RETURN_FAILURE_AND_IGNORE; } // find a spot inside the area to plant the mine i = 0; do { VectorAdd( BotGetOrigin( BFG_GOAL_ENTITYNUM ), bg->ent->pos3, vec ); vec[0] += crandom() * bg->ent->r.absmax[0] * 0.25; vec[1] += crandom() * bg->ent->r.absmax[1] * 0.25; target_goal->areanum = BotPointAreaNum( bs->client, vec ); VectorCopy( vec, target_goal->origin ); } while ( ( ++i < 5 ) && ( ( target_goal->areanum < 0 ) || !PointInBounds( vec, bg->ent->r.absmin, bg->ent->r.absmax ) ) ); if ( i < 5 ) { // we found a valid spot BFG_RETURN_SUCCESS; } BFG_RETURN_FAILURE_AND_IGNORE; case BFG_ATTRACTOR: if ( BotGoalForEntity( bs, BFG_GOAL_ENTITYNUM, target_goal, BGU_MAXIMUM ) ) { // get the distance, halve it if there is noone one going for this attractor t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target_goal->areanum, bs->tfl ); if ( t ) { BotFindSparseDefendArea( bs, target_goal, qtrue ); if ( bs->target_goal.entitynum == target_goal->entitynum && bs->ainode == AINode_MP_DefendTarget ) { BFG_RETURN_ALREADY; } BFG_RETURN_SUCCESS; } } BFG_RETURN_FAILURE_AND_IGNORE; case BFG_SNIPERSPOT: if ( bs->target_goal.entitynum == BFG_GOAL_ENTITYNUM && bs->ainode == AINode_MP_SniperSpot ) { BFG_RETURN_ALREADY; } target_goal->entitynum = BFG_GOAL_ENTITYNUM; VectorCopy( bg->ent->s.origin, target_goal->origin ); target_goal->areanum = BotPointAreaNum( -1, target_goal->origin ); VectorCopy( bs->cur_ps.mins, target_goal->mins ); VectorCopy( bs->cur_ps.maxs, target_goal->maxs ); BFG_RETURN_SUCCESS; case BFG_SCANFORMINES: if ( bs->target_goal.entitynum == BFG_GOAL_ENTITYNUM && bs->ainode == AINode_MP_ScanForLandmines ) { BFG_RETURN_ALREADY; } target_goal->entitynum = BFG_GOAL_ENTITYNUM; VectorCopy( bg->ent->s.origin, target_goal->origin ); target_goal->areanum = BotPointAreaNum( -1, target_goal->origin ); VectorCopy( bs->cur_ps.mins, target_goal->mins ); VectorCopy( bs->cur_ps.maxs, target_goal->maxs ); BFG_RETURN_SUCCESS; case BFG_MG42: if ( ( bs->target_goal.entitynum == BFG_GOAL_ENTITYNUM ) && ( bs->ainode == AINode_MP_MG42Mount || bs->ainode == AINode_MP_MG42Scan ) ) { BFG_RETURN_ALREADY; } target_goal->entitynum = BFG_GOAL_ENTITYNUM; VectorCopy( bg->ent->s.origin, target_goal->origin ); target_goal->areanum = BotPointAreaNum( -1, target_goal->origin ); VectorCopy( bs->cur_ps.mins, target_goal->mins ); VectorCopy( bs->cur_ps.maxs, target_goal->maxs ); BFG_RETURN_SUCCESS; default: break; } BFG_RETURN_FAILURE; } void BotMP_FindGoal_PostProcessGoal( bot_state_t* bs, botgoalFind_t* bg, bot_goal_t* goal ) { bs->target_goal = *goal; switch ( bg->type ) { case BFG_FOLLOW_LEADER: bs->leader = goal->entitynum; AIEnter_MP_DefendTarget( bs ); break; case BFG_CONSTRUCT: AIEnter_MP_ConstructibleTarget( bs ); break; case BFG_TRIGGER: if ( ( ( bg->ent->spawnflags & 1 ) && ( bs->sess.sessionTeam == TEAM_AXIS ) ) || ( ( bg->ent->spawnflags & 2 ) && ( bs->sess.sessionTeam == TEAM_ALLIES ) ) ) { AIEnter_MP_TouchTarget( bs ); } else { AIEnter_MP_DefendTarget( bs ); } break; case BFG_DESTRUCTION_EXPLOSIVE: case BFG_DESTRUCTION_BUILDING: AIEnter_MP_DynamiteTarget( bs ); break; case BFG_DESTRUCTION_SATCHEL: AIEnter_MP_SatchelChargeTarget( bs ); break; case BFG_MG42_REPAIR: AIEnter_MP_FixMG42( bs ); break; case BFG_MINE: AIEnter_MP_PlantMine( bs ); break; case BFG_ATTRACTOR: AIEnter_MP_DefendTarget( bs ); break; case BFG_SNIPERSPOT: AIEnter_MP_SniperSpot( bs ); break; case BFG_SCANFORMINES: AIEnter_MP_ScanForLandmines( bs ); break; case BFG_MG42: AIEnter_MP_MG42Mount( bs ); break; default: break; } } qboolean BotMP_AlreadyDoing_FastOut( bot_state_t *bs, botgoalFind_t *bg ) { // return qtrue if the given goal, which we are already doing, is ok to continue doing, without looking for other goals switch ( bg->type ) { case BFG_SNIPERSPOT: case BFG_MG42: case BFG_SCANFORMINES: return qtrue; case BFG_FOLLOW_LEADER: case BFG_CONSTRUCT: case BFG_TRIGGER: case BFG_DESTRUCTION_EXPLOSIVE: case BFG_DESTRUCTION_BUILDING: case BFG_DESTRUCTION_SATCHEL: case BFG_MG42_REPAIR: case BFG_MINE: case BFG_ATTRACTOR: default: return qfalse; } } qboolean BotMP_FindGoal_New( bot_state_t* bs ) { int numGoals, i, numCloser; botgoalFind_t findGoals[MAX_FIND_BOTGOALS]; botMPpg_t res, bestGoal_result = 0; bot_goal_t goal, bestGoal; int bestGoal_numCloser, bestGoal_InList; #ifdef _DEBUG // int t = trap_Milliseconds(); #endif // _DEBUG if ( bs->last_findspecialgoals > level.time - 1600 ) { return qfalse; } bs->last_findspecialgoals = level.time + rand() % 400; if ( bs->ignore_specialgoal_time > level.time ) { return qfalse; } numGoals = BotMP_FindGoal_BuildGoalList( bs, findGoals, MAX_FIND_BOTGOALS ); if ( !numGoals ) { // Gordon: didnt find any goals :( #ifdef _DEBUG /* if(bot_profile.integer == 1) { t = trap_Milliseconds() - t; G_Printf( "Findgoal: %s: %i\n", BG_ClassnameForNumber( bs->sess.playerType ), t ); }*/ #endif // _DEBUG return qfalse; } for ( i = 0; i < numGoals; i++ ) { if ( findGoals[i].defaultPriority == -1 ) { findGoals[i].ignore = qtrue; } else { findGoals[i].ignore = qfalse; } } qsort( findGoals, numGoals, sizeof( botgoalFind_t ), botmp_sortFuncs[bs->cur_ps.stats[STAT_PLAYER_CLASS]] ); bestGoal_numCloser = -1; bestGoal_InList = -1; for ( i = 0; i < numGoals; i++ ) { if ( findGoals[i].ignore ) { continue; } #ifdef _DEBUG /* if(bot_profile.integer == 1) { G_Printf( "Processing goaltype %i\n", findGoals[i].type ); }*/ #endif // _DEBUG res = BotMP_FindGoal_ProcessGoal( bs, &findGoals[i], &goal ); switch ( res ) { case BPG_FAILED: continue; case BPG_ALREADYDOING: // we should check for range also if we are already doing it, otherwise they may all get stuck at the same goal if ( BotMP_AlreadyDoing_FastOut( bs, &findGoals[i] ) ) { #ifdef _DEBUG /* if(bot_profile.integer == 1) { t = trap_Milliseconds() - t; G_Printf( "Findgoal: %s: %i\n", BG_ClassnameForNumber( bs->sess.playerType ), t ); }*/ #endif // _DEBUG return qfalse; } // else, drop down so we do a numCloser check case BPG_NEWGOAL: // Possible optimization here: record the travel time within each bot's AI node, so we can use that time inside BotNumTeamMatesWithTargetAndCloser() rather than calculating the time for all bots findGoals[i].numPlayers = numCloser = BotNumTeamMatesWithTargetAndCloser( bs, goal.entitynum, goal.areanum, NULL, 0, BotMP_FindGoal_ClassForGoalType( findGoals[i].type ) ); if ( bestGoal_numCloser >= 0 ) { // First, check against maxCloser lookup if ( numCloser > botgoalMaxCloser[findGoals[i].type] ) { continue; } // TODO: scale it down according to priority (?) if ( numCloser > bestGoal_numCloser ) { continue; } // if this has the same numCloser, but a lower priority, then skip it if ( numCloser == bestGoal_numCloser ) { // if the default priority is lower, ignore if ( findGoals[i].defaultPriority < findGoals[bestGoal_InList].defaultPriority ) { continue; } // if the default priority is the same, check script if ( ( findGoals[i].defaultPriority == findGoals[bestGoal_InList].defaultPriority ) && ( findGoals[i].priority <= findGoals[bestGoal_InList].priority ) ) { continue; } } } bestGoal = goal; bestGoal_result = res; bestGoal_numCloser = numCloser; bestGoal_InList = i; break; } } #ifdef _DEBUG /* if(bot_profile.integer == 1) { t = trap_Milliseconds() - t; G_Printf( "Findgoal: %s: %i\n", BG_ClassnameForNumber( bs->sess.playerType ), t ); }*/ #endif // _DEBUG if ( bestGoal_numCloser >= 0 ) { switch ( bestGoal_result ) { case BPG_NEWGOAL: BotMP_FindGoal_PostProcessGoal( bs, &findGoals[bestGoal_InList], &bestGoal ); return qtrue; case BPG_ALREADYDOING: return qfalse; default: break; } } return qfalse; } /* =================== BotMP_FindGoal =================== */ qboolean BotMP_FindGoal( bot_state_t *bs ) { int i, k, t = 0, c; int oldest = -1, oldestTime = -1, closestTime = -1; int tlist[10], numTargets; int teamlist[64], numTeammates; float dist, bestDist = -1, targetTime = 0, f = 0.0; gentity_t *ent, *trav; trace_t tr; vec3_t center, end, brushPos, vec; qboolean gotTarget, defendTarget = qfalse; bot_goal_t bestTarget, secondary; aas_altroutegoal_t altroutegoals[40]; vec3_t mins, maxs; int list[MAX_CLIENTS], numList; float ourDist, *distances; int targetPriority = 0, bestPriority = 0, bestGoalPriority = 0; if ( bs->last_findspecialgoals > level.time - 1600 ) { return qfalse; } bs->last_findspecialgoals = level.time + rand() % 400; if ( bs->ignore_specialgoal_time > level.time ) { return qfalse; } BotClearGoal( &target ); BotClearGoal( &secondary ); numTeammates = BotNumTeamMates( bs, teamlist, 64 ); gotTarget = qfalse; // LEADER // // look for a (better?) leader bs->leader = BotGetLeader( bs, ( bs->sess.playerType == PC_SOLDIER ) ); if ( bs->leader > -1 ) { // we have a leader, follow them if ( BotGoalForEntity( bs, bs->leader, &secondary, BGU_LOW ) || !( g_entities[bs->leader].r.svFlags & SVF_BOT ) ) { secondary.flags = GFL_LEADER; t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, secondary.areanum, bs->tfl ); if ( !t || t > MAX_BOTLEADER_TRAVEL ) { bs->leader = -1; } else { targetTime = t; gotTarget = qtrue; defendTarget = qtrue; bestTarget = secondary; } } else { bs->leader = -1; } } // IMPORTANT CONSTRUCTIBLES if ( bs->sess.playerType == PC_ENGINEER ) { int pass; // for ( pass = 0; pass < 2; pass++ ) { // find a constructible trav = NULL; ent = NULL; closestTime = 0; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_OBJECTIVE_INFO ) ) ) { // find the constructible // is it disabled? if ( trav->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { continue; } // is it not of highest priority? if ( trav->goalPriority[bs->sess.sessionTeam - 1] < 9 ) { continue; } ent = trav->target_ent; if ( !ent ) { continue; } if ( bs->sess.sessionTeam == TEAM_ALLIES ) { if ( ent->spawnflags & AXIS_CONSTRUCTIBLE ) { if ( ent->chain ) { ent = ent->chain; } else { continue; } } } else if ( bs->sess.sessionTeam == TEAM_AXIS ) { if ( ent->spawnflags & ALLIED_CONSTRUCTIBLE ) { if ( ent->chain ) { ent = ent->chain; } else { continue; } } } if ( ent->s.eType != ET_CONSTRUCTIBLE ) { continue; } // if ( !BotIsConstructible( bs->sess.sessionTeam, trav->s.number ) ) { continue; } if ( ( pass == 0 ) && BotNumTeamMatesWithTargetByClass( bs, trav->s.number, NULL, 0, PC_ENGINEER ) ) { continue; // someone else is going for it } if ( !BotGetReachableEntityArea( bs, trav->s.number, &target ) ) { continue; // not reachable } // // we can build it // // if we are already heading for this goal, stay with it, otherwise look only for closest targets // if ( bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_ConstructibleTarget ) { return qfalse; } // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( closestTime && t > closestTime ) { continue; } // // if our weapon wont be ready in time //if (bs->cur_ps.classWeaponTime + t*10 < (level.time - level.lieutenantChargeTime[bs->sess.sessionTeam-1])) continue; // bestTarget = target; closestTime = t; } // if ( closestTime ) { bs->target_goal = bestTarget; AIEnter_MP_ConstructibleTarget( bs ); return qtrue; } } } // IMPORTANT TRIGGER MULTIPLE { // find a trigger_multiple trav = NULL; ent = NULL; closestTime = 0; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_TRIGGER_MULTIPLE ) ) ) { // is it disabled? if ( trav->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { continue; } // is it active? if ( !trav->r.linked || ( trav->nextthink > level.time + 1000 ) ) { continue; // if it's thinking, then it's not active (doesnt respond to touch) } // is it not of highest priority? if ( trav->goalPriority[bs->sess.sessionTeam - 1] < 9 ) { continue; } // if ( !BotGetReachableEntityArea( bs, trav->s.number, &target ) ) { continue; // not reachable } if ( !BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { continue; // outside autonomy range } // if the current destination is not touching the brush, abort VectorAdd( target.origin, bs->cur_ps.mins, mins ); VectorAdd( target.origin, bs->cur_ps.maxs, maxs ); if ( !trap_EntityContactCapsule( mins, maxs, trav ) ) { continue; } // // get the travel time t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( !t ) { continue; } // targetPriority = 2; // // if there are too many going for this goal, then ignore it if we are the furthest away if ( ( numList = BotNumTeamMatesWithTargetAndCloser( bs, trav->s.number, target.areanum, list, MAX_CLIENTS, -1 ) ) > (int)floor( 0.3 * numTeammates ) ) { distances = BotSortPlayersByTraveltime( BotGetArea( trav->s.number ), list, numList ); if ( distances[numList - 1] < (float)t ) { // we are the furthest targetPriority = 1; } } // only go for it if our current best goal is of lesser priority if ( targetPriority < bestPriority ) { continue; } // // we should touch it // if ( ( targetPriority <= bestPriority ) && ( closestTime && t > closestTime ) ) { continue; } // bestTarget = target; closestTime = t; bestPriority = targetPriority; } // if ( closestTime ) { trav = &g_entities[bestTarget.entitynum]; // is it for us only? if ( ( ( trav->spawnflags & 1 ) && ( bs->sess.sessionTeam == TEAM_AXIS ) ) || ( ( trav->spawnflags & 2 ) && ( bs->sess.sessionTeam == TEAM_ALLIES ) ) ) { if ( bs->target_goal.entitynum == bestTarget.entitynum && bs->ainode == AINode_MP_TouchTarget ) { return qfalse; } bs->target_goal = bestTarget; AIEnter_MP_TouchTarget( bs ); return qtrue; } else { // defend it if ( targetPriority > 1 ) { if ( bs->target_goal.entitynum == bestTarget.entitynum && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = bestTarget; AIEnter_MP_DefendTarget( bs ); return qtrue; } else { targetTime = closestTime; gotTarget = -1; defendTarget = qtrue; } } } } // CONSTRUCTIBLES if ( bs->sess.playerType == PC_ENGINEER ) { int pass; // for ( pass = 0; pass < 2; pass++ ) { // find a constructible trav = NULL; ent = NULL; closestTime = 0; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_OBJECTIVE_INFO ) ) ) { // find the constructible // is it disabled? if ( trav->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { continue; } ent = trav->target_ent; if ( !ent ) { continue; } if ( bs->sess.sessionTeam == TEAM_ALLIES ) { if ( ent->spawnflags & AXIS_CONSTRUCTIBLE ) { if ( ent->chain ) { ent = ent->chain; } else { continue; } } } else if ( bs->sess.sessionTeam == TEAM_AXIS ) { if ( ent->spawnflags & ALLIED_CONSTRUCTIBLE ) { if ( ent->chain ) { ent = ent->chain; } else { continue; } } } if ( ent->s.eType != ET_CONSTRUCTIBLE ) { continue; } // if ( !BotIsConstructible( bs->sess.sessionTeam, trav->s.number ) ) { continue; } if ( BotNumTeamMatesWithTargetByClass( bs, trav->s.number, NULL, 0, PC_ENGINEER ) > pass ) { continue; // someone else is going for it } if ( !BotGetReachableEntityArea( bs, trav->s.number, &target ) ) { continue; // not reachable } if ( bestGoalPriority > trav->goalPriority[bs->sess.sessionTeam - 1] ) { continue; } // // we can build it // // if we are already heading for this goal, stay with it, otherwise look only for closest targets // if ( bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_ConstructibleTarget ) { return qfalse; } // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( bestGoalPriority == trav->goalPriority[bs->sess.sessionTeam - 1] ) { // only check the distance if the priorities are the same if ( closestTime && t > closestTime ) { continue; } } // // if our weapon wont be ready in time //if (bs->cur_ps.classWeaponTime + t*10 < (level.time - level.lieutenantChargeTime[bs->sess.sessionTeam-1])) continue; // bestTarget = target; closestTime = t; bestGoalPriority = trav->goalPriority[bs->sess.sessionTeam - 1]; } // if ( closestTime ) { bs->target_goal = bestTarget; AIEnter_MP_ConstructibleTarget( bs ); return qtrue; } } } // check for dynamite if ( bs->sess.playerType == PC_ENGINEER ) { // look for things to blow up numTargets = BotGetTargetExplosives( bs->sess.sessionTeam, tlist, 10, qfalse ); if ( numTargets ) { closestTime = -1; // pick the closest target for ( k = 0; k < numTargets; k++ ) { // oldest = tlist[k]; // // see if this is a worthy goal ent = BotGetEntity( oldest ); // is it disabled? // Gordon: forest script was setup to use the entity itself, NOT the toi (toi for building, entity itself for destruction) // if (ent->aiInactive & (1<<bs->sess.sessionTeam)) continue; // if (ent->parent && (ent->parent->aiInactive & (1<<bs->sess.sessionTeam))) continue; // is the target disabled? // if (ent->target_ent && (ent->target_ent->aiInactive & (1<<bs->sess.sessionTeam))) continue; // if ( ( numList = BotNumTeamMatesWithTarget( bs, oldest, list, 10 ) ) ) { continue; } // if ( ent->s.eType == ET_OID_TRIGGER ) { VectorAdd( ent->r.absmin, ent->r.absmax, brushPos ); VectorScale( brushPos, 0.5, brushPos ); // find the best goal area numList = trap_AAS_BBoxAreas( ent->r.absmin, ent->r.absmax, list, 32 ); if ( numList ) { oldestTime = -1; bestDist = -1; for ( i = 0; i < numList; i++ ) { if ( !trap_AAS_AreaReachability( list[i] ) ) { continue; } t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, list[i], bs->tfl ); if ( t > 0 && ( !gotTarget || t < 400 ) ) { // choose the reachable area closest to the center of the info_objective brush trap_AAS_AreaCenter( list[i], center ); VectorSubtract( brushPos, center, vec ); vec[2] = 0; dist = VectorLength( vec ); if ( bestDist < 0 || dist < bestDist ) { oldestTime = t; oldest = list[i]; bestDist = dist; } } } if ( oldestTime > 0 ) { // now trace from this area towards the func_explosive trap_AAS_AreaCenter( oldest, center ); //trap_Trace( &tr, center, bs->cur_ps.mins, bs->cur_ps.maxs, brushPos, -1, MASK_PLAYERSOLID & ~CONTENTS_BODY ); //VectorCopy( tr.endpos, center ); VectorCopy( center, end ); end[2] -= 512; trap_Trace( &tr, center, bs->cur_ps.mins, bs->cur_ps.maxs, end, -1, MASK_PLAYERSOLID & ~CONTENTS_BODY ); VectorCopy( tr.endpos, center ); //center[2] += 24; //oldest = trap_AAS_PointAreaNum(center); t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, oldest, bs->tfl ); if ( t && ( closestTime < 0 || closestTime > t ) ) { ent->lastHintCheckTime = level.time + 5000; // use this as the goal origin VectorCopy( center, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); target.areanum = oldest; target.entitynum = ent->s.number; // closestTime = t; } } } } else { VectorAdd( ent->r.absmin, ent->r.absmax, brushPos ); VectorScale( brushPos, 0.5, brushPos ); VectorCopy( ent->r.absmin, mins ); VectorCopy( ent->r.absmax, maxs ); for ( i = 0; i < 2; i++ ) { mins[i] -= G_GetWeaponDamage( WP_DYNAMITE ) * 0.25f; maxs[i] += G_GetWeaponDamage( WP_DYNAMITE ) * 0.25f; } // find the best goal area numList = trap_AAS_BBoxAreas( mins, maxs, list, 32 ); if ( numList ) { oldestTime = -1; bestDist = -1; for ( i = 0; i < numList; i++ ) { if ( !trap_AAS_AreaReachability( list[i] ) ) { continue; } // RF, make sure this is within range trap_AAS_AreaCenter( list[i], center ); VectorCopy( center, end ); end[2] -= 512; trap_Trace( &tr, center, bs->cur_ps.mins, bs->cur_ps.maxs, end, -1, MASK_PLAYERSOLID & ~CONTENTS_BODY ); VectorCopy( tr.endpos, center ); VectorSubtract( center, brushPos, vec ); G_AdjustedDamageVec( ent, center, vec ); if ( ( VectorLengthSquared( vec ) <= SQR( G_GetWeaponDamage( WP_DYNAMITE ) ) ) && CanDamage( ent, center ) ) { t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, list[i], bs->tfl ); if ( t > 0 && ( !gotTarget || t < 400 ) ) { if ( bestDist < 0 || t < bestDist ) { oldestTime = t; oldest = list[i]; bestDist = t; } } } } if ( oldestTime > 0 ) { // now trace from this area towards the func_explosive trap_AAS_AreaCenter( oldest, center ); //trap_Trace( &tr, center, bs->cur_ps.mins, bs->cur_ps.maxs, brushPos, -1, MASK_PLAYERSOLID & ~CONTENTS_BODY ); //VectorCopy( tr.endpos, center ); VectorCopy( center, end ); end[2] -= 512; trap_Trace( &tr, center, bs->cur_ps.mins, bs->cur_ps.maxs, end, -1, MASK_PLAYERSOLID & ~CONTENTS_BODY ); VectorCopy( tr.endpos, center ); //center[2] += 24; //oldest = trap_AAS_PointAreaNum(center); t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, oldest, bs->tfl ); if ( t && ( closestTime < 0 || closestTime > t ) ) { ent->lastHintCheckTime = level.time + 5000; // use this as the goal origin VectorCopy( center, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); target.areanum = oldest; target.entitynum = ent->s.number; // closestTime = t; } } } } } // if we have a closestTime, we have a target! if ( closestTime > 0 ) { if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_DynamiteTarget ) { return qfalse; } bs->target_goal = target; AIEnter_MP_DynamiteTarget( bs ); return qtrue; } } } } // BROKEN MG42 if ( bs->sess.playerType == PC_ENGINEER ) { // look for a broken MG42 that isnt already being fixed trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_MG42 ) ) ) { // is it disabled? if ( trav->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { continue; } if ( trav->health <= 0 ) { if ( trav->melee ) { ent = trav->melee; if ( ( ent->aiTeam == bs->sess.sessionTeam ) && ( ent->botIgnoreTime < level.time ) && ( BotNumTeamMatesWithTargetByClass( bs, trav->s.number, NULL, -1, PC_ENGINEER ) == 0 ) ) { // go fix it? if ( BotGoalForEntity( bs, ent->s.number, &target, BGU_LOW ) ) { // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); // if ( t < 500 && ( !gotTarget || t < 100 ) ) { if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_FixMG42 ) { return qfalse; } // go fix it!! bs->target_goal = target; AIEnter_MP_FixMG42( bs ); return qtrue; } } } } } } } // PLANT LAND MINES if ( bs->sess.playerType == PC_ENGINEER && ( G_CountTeamLandmines( bs->sess.sessionTeam ) < MAX_TEAM_LANDMINES ) ) { // look for a land mine area that isn't full closestTime = 0; trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_BOT_LANDMINE_AREA ) ) ) { // is it disabled? //if (trav->aiInactive & (1<<bs->sess.sessionTeam)) continue; // FIXME: djbob needs to add the etype of the landmine hint to the filter // is it for us? if ( ( trav->spawnflags & 1 ) && ( bs->sess.sessionTeam != TEAM_AXIS ) ) { continue; } if ( ( trav->spawnflags & 2 ) && ( bs->sess.sessionTeam != TEAM_ALLIES ) ) { continue; } // has it got enough landmines? if ( trav->count2 >= trav->count ) { continue; } // already someone else heading for it? if ( BotNumTeamMatesWithTargetByClass( bs, trav->s.number, NULL, 0, PC_ENGINEER ) ) { continue; // someone else is going for it } // valid goal towards it? if ( !BotGoalForEntity( bs, trav->s.number, &target, BGU_LOW ) ) { continue; } // // if we are already heading for this goal, stay with it, otherwise look only for closest targets // if ( bs->target_goal.entitynum == trav->s.number && bs->ainode == AINode_MP_PlantMine ) { return qfalse; } // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( !t ) { continue; } if ( closestTime && t > closestTime ) { continue; } // bestTarget = target; closestTime = t; } // if ( closestTime ) { // find a spot inside the area to plant the mine trav = &g_entities[bestTarget.entitynum]; i = 0; do { VectorAdd( BotGetOrigin( trav->s.number ), trav->pos3, vec ); vec[0] += crandom() * trav->r.absmax[0] * 0.25; vec[1] += crandom() * trav->r.absmax[1] * 0.25; // bestTarget.areanum = BotPointAreaNum( bs->client, vec ); VectorCopy( vec, bestTarget.origin ); } while ( ( ++i < 5 ) && ( ( bestTarget.areanum < 0 ) || !PointInBounds( vec, trav->r.absmin, trav->r.absmax ) ) ); // if ( i < 5 ) { // we found a valid spot bs->target_goal = bestTarget; AIEnter_MP_PlantMine( bs ); return qtrue; } } } // TRIGGER MULTIPLE { // find a trigger_multiple trav = NULL; ent = NULL; closestTime = 0; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_TRIGGER_MULTIPLE ) ) ) { // is it disabled? if ( trav->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { continue; } // is it active? if ( !trav->r.linked || ( trav->nextthink > level.time + 1000 ) ) { continue; // if it's thinking, then it's not active (doesnt respond to touch) } // if ( !BotGetReachableEntityArea( bs, trav->s.number, &target ) ) { continue; // not reachable } if ( !BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { continue; // outside autonomy range } // if the current destination is not touching the brush, abort VectorAdd( target.origin, bs->cur_ps.mins, mins ); VectorAdd( target.origin, bs->cur_ps.maxs, maxs ); if ( !trap_EntityContactCapsule( mins, maxs, trav ) ) { continue; } // // get the travel time t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( !t ) { continue; } // targetPriority = 2; // // if there are too many going for this goal, then ignore it if we are the furthest away if ( ( numList = BotNumTeamMatesWithTargetAndCloser( bs, trav->s.number, target.areanum, list, MAX_CLIENTS, -1 ) ) > (int)floor( 0.3 * numTeammates ) ) { distances = BotSortPlayersByTraveltime( BotGetArea( trav->s.number ), list, numList ); if ( distances[numList - 1] < (float)t ) { // we are the furthest targetPriority = 1; // also consider other goals t += 5000; } } // only go for it if our current best goal is of lesser priority if ( targetPriority < bestPriority ) { continue; } // // we should touch it // if ( ( targetPriority <= bestPriority ) && ( closestTime && t > closestTime ) ) { continue; } // bestTarget = target; closestTime = t; bestPriority = targetPriority; } // if ( closestTime ) { trav = &g_entities[bestTarget.entitynum]; // is it for us only? if ( ( ( trav->spawnflags & 1 ) && ( bs->sess.sessionTeam == TEAM_AXIS ) ) || ( ( trav->spawnflags & 2 ) && ( bs->sess.sessionTeam == TEAM_ALLIES ) ) ) { if ( targetPriority > 1 ) { if ( bs->target_goal.entitynum == bestTarget.entitynum && bs->ainode == AINode_MP_TouchTarget ) { return qfalse; } bs->target_goal = bestTarget; AIEnter_MP_TouchTarget( bs ); return qtrue; } else { // enough people going for it, so only go for it if there's nothing else to do targetTime = closestTime; gotTarget = -1; defendTarget = qfalse; } } else { // defend it if ( targetPriority > 1 ) { if ( bs->target_goal.entitynum == bestTarget.entitynum && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = bestTarget; AIEnter_MP_DefendTarget( bs ); return qtrue; } else { targetTime = closestTime; gotTarget = -1; defendTarget = qtrue; } } } } //================================================================================================ // SECONDARY TARGETS() // LEADER if ( !gotTarget ) { if ( bs->leader > -1 ) { if ( bs->lead_time > trap_AAS_Time() ) { // we must follow them goto secondaryTarget; } } } // CHECKPOINTS if ( !gotTarget ) { // Defend checkpoints if they are owned by us. Make sure we disperse troops amongst checkpoints, and actively // pursue checkpoints not owned by us more aggressively. t = 0; gotTarget = qfalse; // count the checkpoints i = 0; trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_CHECKPOINT ) ) ) { // is it disabled? if ( trav->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { continue; } i++; } if ( i ) { f = 1.0f / i; } //if (level.captureFlagMode) { // c = (int)ceil(0.35*f*numTeammates); //} else { c = (int)ceil( f * numTeammates ); //} // see if we should get/defend one trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_CHECKPOINT ) ) ) { // is it disabled? if ( trav->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { continue; } // if the opposition team controls this checkpoint, or it hasnt been captured yet if ( trav->count == ( bs->sess.sessionTeam == TEAM_AXIS ? TEAM_ALLIES : TEAM_AXIS ) || ( trav->count < 0 ) ) { if ( BotNumTeamMatesWithTarget( bs, trav->s.number, NULL, 0 ) < c ) { // GO GET IT // do we have a route to the enemy flag? secondary.entitynum = trav->s.number; VectorAdd( trav->r.absmin, trav->r.absmax, center ); VectorScale( center, 0.5, center ); secondary.areanum = BotReachableBBoxAreaNum( bs, trav->r.absmin, trav->r.absmax ); if ( !secondary.areanum ) { secondary.areanum = BotPointAreaNum( -1, center ); } //secondary.areanum = trap_AAS_PointAreaNum(center); secondary.flags = GFL_NOSLOWAPPROACH; VectorCopy( trav->r.mins, secondary.mins ); VectorCopy( trav->r.maxs, secondary.maxs ); VectorCopy( center, secondary.origin ); // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, secondary.areanum, bs->tfl ); if ( t && ( !gotTarget || t < targetTime ) ) { targetTime = t; gotTarget = -1; // use this if nothing else is around defendTarget = qfalse; bestTarget = secondary; if ( t < 500 && BotNumTeamMatesWithTarget( bs, trav->s.number, NULL, 0 ) < 1 ) { if ( BotGoalWithinMovementAutonomy( bs, &bestTarget, BGU_LOW ) ) { if ( bs->target_goal.entitynum == bestTarget.entitynum && bs->ainode == AINode_MP_TouchTarget ) { return qfalse; } bs->target_goal = bestTarget; AIEnter_MP_TouchTarget( bs ); return qtrue; } } } } } else { // defend the checkpoint? if ( !level.captureFlagMode && BotNumTeamMatesWithTarget( bs, trav->s.number, NULL, 0 ) < ( c > 1 ? c / 2 : c ) ) { // GO GET IT // do we have a route to the enemy flag? secondary.entitynum = trav->s.number; VectorAdd( trav->r.absmin, trav->r.absmax, center ); VectorScale( center, 0.5, center ); //VectorCopy( trav->r.currentOrigin, center ); //center[2] += 30; secondary.areanum = trap_AAS_PointAreaNum( center ); if ( !secondary.areanum ) { secondary.areanum = BotPointAreaNum( -1, center ); } secondary.flags = GFL_NOSLOWAPPROACH; VectorCopy( trav->r.mins, secondary.mins ); VectorCopy( trav->r.maxs, secondary.maxs ); VectorCopy( trav->r.currentOrigin, secondary.origin ); // // don't worry about our flag as much t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, secondary.areanum, bs->tfl ); if ( !t ) { t = BotFindSparseDefendArea( bs, &secondary, qfalse ); } if ( t ) { t = 200 + 2 * t; t += bs->client * 100; // random element to spread bots out if ( !gotTarget || t < targetTime ) { if ( BotGoalWithinMovementAutonomy( bs, &secondary, BGU_LOW ) ) { targetTime = t; gotTarget = -1; defendTarget = qtrue; bestTarget = secondary; } } } } } } } // ATTRACTORS if ( !gotTarget ) { trav = NULL; while ( ( trav = BotFindNextStaticEntity( trav, BOTSTATICENTITY_BOT_ATTRACTOR ) ) ) { if ( trav->aiInactive & ( 1 << bs->sess.sessionTeam ) ) { continue; } if ( BotGoalForEntity( bs, trav->s.number, &target, BGU_MAXIMUM ) ) { // get the distance, halve it if there is noone one going for this attractor t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( BotNumTeamMatesWithTarget( bs, trav->s.number, NULL, 0 ) == 0 ) { t /= 2; } if ( !gotTarget || ( t < targetTime ) ) { targetTime = t; gotTarget = -1; defendTarget = qtrue; bestTarget = target; } } } } // OBJECTIVE LOCATIONS // defend target objectives (both teams should try and "occupy" objectives) /* if (gotTarget != qtrue) { qboolean useObjective = qfalse; // count the objectives i = 0; c = 999; oldest = -1; trav = NULL; while ( trav = BotFindNextStaticEntity(trav, BOTSTATICENTITY_OBJECTIVE_INFO) ) { // is it disabled? if (trav->aiInactive & (1<<bs->sess.sessionTeam)) continue; // // only guard objectives that are attached to constructibles or destructibles // useObjective = qfalse; // if (trav->target_ent) { if (trav->target_ent->s.eType == ET_CONSTRUCTIBLE) { // has it been built? // all constructibles are considered important, whether built or not, unless they are disabled in scripting //if (BotIsConstructible( bs->sess.sessionTeam, trav->s.number )) { useObjective = qtrue; //} } else if (trav->target_ent->s.eType == ET_EXPLOSIVE) { // is it still valid? if (trav->target_ent->r.linked) { useObjective = qtrue; } } } // if (!useObjective) continue; // ignore this objective // i++; if ((k = BotNumTeamMatesWithTarget( bs, trav->s.number, NULL, 0 )) < c) { if (!BotGetReachableEntityArea( bs, trav->s.number, &secondary )) continue; // not reachable c = k; oldest = trav->s.number; } } if (i) { f = 1.0f / i; } trav = NULL; while (trav = BotFindNextStaticEntity(trav, BOTSTATICENTITY_OBJECTIVE_INFO)) { // is it disabled? if (trav->aiInactive & (1<<bs->sess.sessionTeam)) continue; // if (BotNumTeamMatesWithTarget( bs, trav->s.number, NULL, 0 ) >= (int)ceil(f*numTeammates)) { if (bestPriority >= 2) continue; // we already have an important goal targetPriority = 1; } else { targetPriority = 2; } // // only guard objectives that are attached to constructibles or destructibles // useObjective = qfalse; // if (trav->target_ent) { if (trav->target_ent->s.eType == ET_CONSTRUCTIBLE) { // has it been built? //if (BotIsConstructible( bs->sess.sessionTeam, trav->s.number )) { useObjective = qtrue; //} } else if (trav->target_ent->s.eType == ET_EXPLOSIVE) { // is it still valid? if (trav->target_ent->r.linked) { useObjective = qtrue; } } // if (!useObjective) continue; // ignore this objective // // GO GET IT // do we have a route to the objective? if (!BotGetReachableEntityArea( bs, trav->s.number, &secondary )) continue; // not reachable // t = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, secondary.areanum, bs->tfl); if (t) { if (!gotTarget || (targetPriority > bestPriority) || (oldest != -1 ? trav->s.number == oldest : t < targetTime)) { if (BotGoalWithinMovementAutonomy( bs, &secondary, BGU_LOW )) { targetTime = t; gotTarget = qtrue; defendTarget = qtrue; bestTarget = secondary; bestPriority = targetPriority; } } } } } }*/ //================================================================================================ // PRIMARY TARGETS() // FLAGS if ( level.captureFlagMode ) { if ( bs->sess.sessionTeam == level.attackingTeam ) { // ATTACKING // do we have the flag? if ( BotCarryingFlag( bs->client ) ) { // we have it!! ent = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY ); if ( !ent ) { ent = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY_MULTIPLE ); } if ( ent ) { vec3_t bestAreaCenter; // VectorAdd( ent->r.absmin, ent->r.absmax, brushPos ); VectorScale( brushPos, 0.5, brushPos ); // find the best goal area numList = trap_AAS_BBoxAreas( ent->r.absmin, ent->r.absmax, list, 32 ); if ( numList ) { oldestTime = -1; bestDist = -1; for ( i = 0; i < numList; i++ ) { if ( !trap_AAS_AreaReachability( list[i] ) ) { continue; } t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, list[i], bs->tfl ); if ( t > 0 ) { // choose the reachable area closest to the center of the info_objective brush trap_AAS_AreaCenter( list[i], center ); VectorSubtract( brushPos, center, vec ); vec[2] = 0; dist = VectorLength( vec ); if ( bestDist < 0 || dist < bestDist ) { oldestTime = t; oldest = list[i]; bestDist = dist; VectorCopy( center, bestAreaCenter ); } } } } if ( bestDist > 0 ) { if ( bs->target_goal.entitynum == ent->s.number && bs->ainode == AINode_MP_TouchTarget && bs->target_goal.areanum == oldest ) { return qfalse; } // BotClearGoal( &target ); // use this as the goal origin VectorCopy( bestAreaCenter, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); target.areanum = oldest; target.entitynum = ent->s.number; target.flags = GFL_NOSLOWAPPROACH; // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { // bs->target_goal = target; // // if we are close to the static flag, then look for an alternate route BotFlagAtBase( level.attackingTeam == TEAM_AXIS ? TEAM_ALLIES : TEAM_AXIS, &ent ); if ( ent && VectorDistanceSquared( bs->origin, ent->r.currentOrigin ) < ( 384 * 384 ) ) { // check for an alternate route if ( ( t > 1000 ) && ( numList = trap_AAS_AlternativeRouteGoals( bs->origin, bestAreaCenter, bs->tfl, altroutegoals, 40, 0 ) ) ) { //pick one at random i = rand() % numList; //make this the altrouetgoal bs->alt_goal = bs->target_goal; trap_AAS_AreaWaypoint( altroutegoals[i].areanum, bs->alt_goal.origin ); bs->alt_goal.areanum = trap_AAS_PointAreaNum( bs->alt_goal.origin ); bs->alt_goal.number = level.time; bs->target_goal.number = level.time; } } // AIEnter_MP_TouchTarget( bs ); return qtrue; } } else { // can't get to the destination point if ( bs->ainode == AINode_MP_Stand ) { return qfalse; } AIEnter_MP_Stand( bs ); return qfalse; } } } // SNIPER AI // note: snipers only operate if flag is at base if ( BotCanSnipe( bs, qtrue ) ) { // already sniping if ( bs->ainode == AINode_MP_SniperSpot ) { return qfalse; } // c = BotBestSniperSpot( bs ); if ( c > -1 ) { ent = BotGetEntity( c ); // do we have a route to the flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->s.origin, target.origin ); target.areanum = BotPointAreaNum( -1, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { bs->target_goal = target; AIEnter_MP_SniperSpot( bs ); return qtrue; } } } // MG42 AI // note: mg42 only operate if flag is at base if ( bs->sess.playerType == PC_SOLDIER ) { // c = BotBestMG42Spot( bs, !gotTarget ); if ( c > -1 ) { // are we already mounting it? if ( ( bs->target_goal.entitynum == c ) && ( bs->ainode == AINode_MP_MG42Mount || bs->ainode == AINode_MP_MG42Scan ) ) { return qfalse; } // ent = BotGetEntity( c ); // do we have a route to the flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->s.origin, target.origin ); target.areanum = BotPointAreaNum( -1, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { bs->target_goal = target; AIEnter_MP_MG42Mount( bs ); return qtrue; } } } // is the enemy flag at base? if ( BotFlagAtBase( level.attackingTeam == TEAM_AXIS ? TEAM_ALLIES : TEAM_AXIS, &ent ) == qtrue ) { // GO GET IT // do we have a route to the enemy flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->r.currentOrigin, center ); center[2] += 30; target.areanum = trap_AAS_PointAreaNum( center ); target.flags = GFL_NOSLOWAPPROACH; VectorCopy( ent->r.mins, target.mins ); VectorCopy( ent->r.maxs, target.maxs ); VectorCopy( center, target.origin ); // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( t && ( ( t < 500 ) || !gotTarget || defendTarget || ( ( t / 2 ) < targetTime ) ) ) { // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_MEDIUM ) ) { // if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_TouchTarget ) { return qfalse; } bs->target_goal = target; // // check for an alternate route if ( t > 600 && ( numList = trap_AAS_AlternativeRouteGoals( bs->origin, bs->target_goal.origin, bs->tfl, altroutegoals, 40, 0 ) ) ) { //pick one at random i = rand() % numList; //make this the altrouetgoal bs->alt_goal = bs->target_goal; trap_AAS_AreaWaypoint( altroutegoals[i].areanum, bs->alt_goal.origin ); bs->alt_goal.areanum = trap_AAS_PointAreaNum( bs->alt_goal.origin ); bs->alt_goal.number = level.time; bs->target_goal.number = level.time; } // AIEnter_MP_TouchTarget( bs ); return qtrue; } } } else { qboolean protect = qtrue; // who has it? BotClearGoal( &target ); target.entitynum = BotGetTeamFlagCarrier( bs ); // if ( ( target.entitynum > -1 && target.entitynum != bs->client ) && ( VectorDistanceSquared( g_entities[target.entitynum].r.currentOrigin, bs->origin ) < ( 1600 * 1600 ) ) /*&& (trap_InPVS(g_entities[target.entitynum].r.currentOrigin, bs->origin))*/) { // TODO: if there are too many defenders, and we are the furthest away, stop defending // !!! if ( ( numList = BotNumTeamMatesWithTarget( bs, target.entitynum, list, MAX_CLIENTS ) ) >= BOT_FLAG_CARRIER_DEFENDERS ) { ourDist = VectorDistanceSquared( bs->origin, g_entities[target.entitynum].r.currentOrigin ); //if (!trap_InPVS( bs->origin, g_entities[target.entitynum].r.currentOrigin )) ourDist += 2048; distances = BotSortPlayersByDistance( g_entities[target.entitynum].r.currentOrigin, list, numList ); if ( distances[numList - 1] < ourDist ) { // we are the furthest protect = qfalse; } } if ( protect ) { // protect the carrier ent = BotGetEntity( target.entitynum ); VectorCopy( ent->r.currentOrigin, center ); target.areanum = BotPointAreaNum( target.entitynum, center ); target.flags = GFL_NOSLOWAPPROACH; VectorCopy( ent->r.mins, target.mins ); VectorCopy( ent->r.maxs, target.maxs ); VectorCopy( ent->r.currentOrigin, target.origin ); // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( !t ) { t = BotFindSparseDefendArea( bs, &target, qfalse ); } if ( t && ( !gotTarget || defendTarget || t < targetTime ) ) { if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_HIGH ) ) { if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = target; BotFindSparseDefendArea( bs, &bs->target_goal, qtrue ); AIEnter_MP_DefendTarget( bs ); return qtrue; } } } } // head to the flag destination? ent = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY ); if ( !ent ) { ent = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY_MULTIPLE ); } if ( target.entitynum != bs->client && ent && ( BotNumTeamMatesWithTarget( bs, ent->s.number, NULL, 0 ) < (int)ceil( 0.3 * numTeammates ) ) ) { VectorAdd( ent->r.absmin, ent->r.absmax, brushPos ); VectorScale( brushPos, 0.5, brushPos ); // find the best goal area numList = trap_AAS_BBoxAreas( ent->r.absmin, ent->r.absmax, list, 32 ); if ( numList ) { oldestTime = -1; bestDist = -1; for ( i = 0; i < numList; i++ ) { if ( !trap_AAS_AreaReachability( list[i] ) ) { continue; } t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, list[i], bs->tfl ); if ( t > 0 ) { // choose the reachable area closest to the center of the info_objective brush trap_AAS_AreaCenter( list[i], center ); VectorSubtract( brushPos, center, vec ); vec[2] = 0; dist = VectorLength( vec ); if ( bestDist < 0 || dist < bestDist ) { oldestTime = t; oldest = list[i]; bestDist = dist; } } } } if ( bestDist > 0 ) { BotClearGoal( &target ); // use this as the goal origin VectorCopy( center, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); target.areanum = oldest; target.entitynum = ent->s.number; target.flags = GFL_NOSLOWAPPROACH; // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { if ( bs->target_goal.entitynum == ent->s.number && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = target; BotFindSparseDefendArea( bs, &bs->target_goal, qtrue ); AIEnter_MP_DefendTarget( bs ); return qtrue; } } } // HEAD FOR IT, THEN WAIT FOR IT BotFlagAtBase( level.attackingTeam == TEAM_AXIS ? TEAM_ALLIES : TEAM_AXIS, &ent ); // do we have a route to the enemy flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->r.currentOrigin, center ); center[2] += 30; target.areanum = trap_AAS_PointAreaNum( center ); target.flags = GFL_NOSLOWAPPROACH; VectorCopy( ent->r.mins, target.mins ); VectorCopy( ent->r.maxs, target.maxs ); VectorCopy( ent->r.currentOrigin, target.origin ); // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( !t ) { t = BotFindSparseDefendArea( bs, &target, qfalse ); } if ( t && ( !gotTarget || defendTarget || t < targetTime ) ) { if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = target; BotFindSparseDefendArea( bs, &bs->target_goal, qtrue ); AIEnter_MP_DefendTarget( bs ); return qtrue; } } } } else { // ================================================================ // DEFENDING() // SNIPER AI // note: snipers only operate if flag is at base if ( BotCanSnipe( bs, qtrue ) ) { // already sniping if ( bs->ainode == AINode_MP_SniperSpot ) { return qfalse; } c = BotBestSniperSpot( bs ); if ( c > -1 ) { ent = BotGetEntity( c ); // do we have a route to the flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->s.origin, target.origin ); target.areanum = BotPointAreaNum( -1, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { bs->target_goal = target; AIEnter_MP_SniperSpot( bs ); return qtrue; } } } // MG42 AI // note: mg42 only operate if flag is at base if ( ( bs->sess.playerType == PC_SOLDIER ) && ( BotFlagAtBase( bs->sess.sessionTeam, &ent ) == qtrue ) ) { // already sniping if ( bs->ainode == AINode_MP_MG42Mount || bs->ainode == AINode_MP_MG42Scan ) { return qfalse; } // c = BotBestMG42Spot( bs, !gotTarget ); if ( c > -1 ) { ent = BotGetEntity( c ); // do we have a route to the flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->s.origin, target.origin ); target.areanum = BotPointAreaNum( -1, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { bs->target_goal = target; AIEnter_MP_MG42Mount( bs ); return qtrue; } } } if ( !gotTarget || !level.explosiveTargets[bs->sess.sessionTeam == TEAM_AXIS ? 0 : 1] || ( level.explosiveTargets[bs->sess.sessionTeam == TEAM_AXIS ? 0 : 1] - BotGetTargetExplosives( bs->sess.sessionTeam, NULL, 0, qtrue ) > 0 ) ) { // at least one target has been breached, so start defending objective // defend the objective! if ( BotFlagAtBase( bs->sess.sessionTeam, &ent ) == qtrue ) { if ( !gotTarget || BotNumTeamMatesWithTarget( bs, ent->s.number, NULL, 0 ) < (int)ceil( 0.4 * numTeammates ) ) { // do we have a route to the flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->r.currentOrigin, center ); center[2] += 30; target.areanum = trap_AAS_PointAreaNum( center ); target.flags = GFL_NOSLOWAPPROACH; VectorCopy( ent->r.mins, target.mins ); VectorCopy( ent->r.maxs, target.maxs ); VectorCopy( ent->r.currentOrigin, target.origin ); // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( t && ( !gotTarget || defendTarget || t < targetTime ) ) { if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_MEDIUM ) ) { // BotFindSparseDefendArea( bs, &target, qtrue ); // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_MEDIUM ) ) { if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } // we are on defense BotVoiceChatAfterIdleTime( bs->client, "OnDefense", SAY_TEAM, 1000, qfalse, 10000 + rand() % 5000, qfalse ); bs->target_goal = target; AIEnter_MP_DefendTarget( bs ); return qtrue; } } } } } else { // defend the enemy destination ent = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY ); if ( !ent ) { ent = BotFindNextStaticEntity( NULL, BOTSTATICENTITY_FLAGONLY_MULTIPLE ); } if ( ent /*&& (BotNumTeamMatesWithTarget( bs, ent->s.number, NULL, 0 ) < (int)ceil(0.5*numTeammates))*/ ) { VectorAdd( ent->r.absmin, ent->r.absmax, brushPos ); VectorScale( brushPos, 0.5, brushPos ); bestDist = -1; // find the best goal area numList = trap_AAS_BBoxAreas( ent->r.absmin, ent->r.absmax, list, 32 ); if ( numList ) { oldestTime = -1; for ( i = 0; i < numList; i++ ) { if ( !trap_AAS_AreaReachability( list[i] ) ) { continue; } t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, list[i], bs->tfl ); if ( t > 0 ) { // choose the reachable area closest to the center of the info_objective brush trap_AAS_AreaCenter( list[i], center ); VectorSubtract( brushPos, center, vec ); vec[2] = 0; dist = VectorLength( vec ); if ( bestDist < 0 || dist < bestDist ) { oldestTime = t; oldest = list[i]; bestDist = dist; } } } } if ( bestDist > 0 ) { BotClearGoal( &target ); // use this as the goal origin VectorCopy( center, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); target.areanum = oldest; target.entitynum = ent->s.number; target.flags = GFL_NOSLOWAPPROACH; // BotFindSparseDefendArea( bs, &target, qtrue ); if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_MEDIUM ) ) { if ( bs->target_goal.entitynum == ent->s.number && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = target; AIEnter_MP_DefendTarget( bs ); return qtrue; } } } // // go to the flag room BotFlagAtBase( bs->sess.sessionTeam, &ent ); // do we have a route to the flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->r.currentOrigin, center ); center[2] += 30; target.areanum = trap_AAS_PointAreaNum( center ); target.flags = GFL_NOSLOWAPPROACH; VectorCopy( ent->r.mins, target.mins ); VectorCopy( ent->r.maxs, target.maxs ); VectorCopy( ent->r.currentOrigin, target.origin ); // t = trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin, target.areanum, bs->tfl ); if ( t && ( !gotTarget || defendTarget || t < targetTime ) ) { BotFindSparseDefendArea( bs, &target, qtrue ); if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_MEDIUM ) ) { if ( bs->target_goal.entitynum == target.entitynum && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = target; AIEnter_MP_DefendTarget( bs ); return qtrue; } } } } } } else { // NOT CTF MODE // SNIPER AI // note: snipers only operate if flag is at base if ( BotCanSnipe( bs, qtrue ) ) { // already sniping if ( bs->ainode == AINode_MP_SniperSpot ) { return qfalse; } // c = BotBestSniperSpot( bs ); if ( c > -1 ) { ent = BotGetEntity( c ); // do we have a route to the flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->s.origin, target.origin ); target.areanum = BotPointAreaNum( -1, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { bs->target_goal = target; AIEnter_MP_SniperSpot( bs ); return qtrue; } } } // MG42 AI // note: mg42 only operate if flag is at base if ( qtrue ) { //bs->sess.playerType == PC_SOLDIER) { // already sniping if ( bs->ainode == AINode_MP_MG42Mount || bs->ainode == AINode_MP_MG42Scan ) { return qfalse; } // c = BotBestMG42Spot( bs, !gotTarget ); if ( c > -1 ) { ent = BotGetEntity( c ); // do we have a route to the flag? BotClearGoal( &target ); target.entitynum = ent->s.number; VectorCopy( ent->s.origin, target.origin ); target.areanum = BotPointAreaNum( -1, target.origin ); VectorCopy( bs->cur_ps.mins, target.mins ); VectorCopy( bs->cur_ps.maxs, target.maxs ); // if ( BotGoalWithinMovementAutonomy( bs, &target, BGU_LOW ) ) { bs->target_goal = target; AIEnter_MP_MG42Mount( bs ); return qtrue; } } } } //================================================================================================ secondaryTarget: // if we found a secondary target (checkpoint), go for it if ( gotTarget ) { if ( defendTarget ) { BotFindSparseDefendArea( bs, &bestTarget, qtrue ); if ( BotGoalWithinMovementAutonomy( bs, &bestTarget, BGU_LOW ) ) { if ( bs->target_goal.entitynum == bestTarget.entitynum && bs->ainode == AINode_MP_DefendTarget ) { return qfalse; } bs->target_goal = bestTarget; AIEnter_MP_DefendTarget( bs ); return qtrue; } } else { if ( BotGoalWithinMovementAutonomy( bs, &bestTarget, BGU_LOW ) ) { if ( bs->target_goal.entitynum == bestTarget.entitynum && bs->ainode == AINode_MP_TouchTarget ) { return qfalse; } bs->target_goal = bestTarget; AIEnter_MP_TouchTarget( bs ); return qtrue; } } } return qfalse; }
gpl-3.0
bnwn/ardupilot
AntennaTracker/Log.cpp
7
3581
#include "Tracker.h" #if LOGGING_ENABLED == ENABLED // Code to Write and Read packets from DataFlash log memory // Write an attitude packet void Tracker::Log_Write_Attitude() { Vector3f targets; targets.y = nav_status.pitch * 100.0f; targets.z = wrap_360_cd(nav_status.bearing * 100.0f); DataFlash.Log_Write_Attitude(ahrs, targets); DataFlash.Log_Write_EKF(ahrs,false); DataFlash.Log_Write_AHRS2(ahrs); #if CONFIG_HAL_BOARD == HAL_BOARD_SITL sitl.Log_Write_SIMSTATE(&DataFlash); #endif DataFlash.Log_Write_POS(ahrs); } void Tracker::Log_Write_Baro(void) { DataFlash.Log_Write_Baro(barometer); } struct PACKED log_Vehicle_Baro { LOG_PACKET_HEADER; uint64_t time_us; float press; float alt_diff; }; // Write a vehicle baro packet void Tracker::Log_Write_Vehicle_Baro(float pressure, float altitude) { struct log_Vehicle_Baro pkt = { LOG_PACKET_HEADER_INIT(LOG_V_BAR_MSG), time_us : AP_HAL::micros64(), press : pressure, alt_diff : altitude }; DataFlash.WriteBlock(&pkt, sizeof(pkt)); } struct PACKED log_Vehicle_Pos { LOG_PACKET_HEADER; uint64_t time_us; int32_t vehicle_lat; int32_t vehicle_lng; int32_t vehicle_alt; float vehicle_vel_x; float vehicle_vel_y; float vehicle_vel_z; }; // Write a vehicle pos packet void Tracker::Log_Write_Vehicle_Pos(int32_t lat, int32_t lng, int32_t alt, const Vector3f& vel) { struct log_Vehicle_Pos pkt = { LOG_PACKET_HEADER_INIT(LOG_V_POS_MSG), time_us : AP_HAL::micros64(), vehicle_lat : lat, vehicle_lng : lng, vehicle_alt : alt, vehicle_vel_x : vel.x, vehicle_vel_y : vel.y, vehicle_vel_z : vel.z, }; DataFlash.WriteBlock(&pkt, sizeof(pkt)); } const struct LogStructure Tracker::log_structure[] = { LOG_COMMON_STRUCTURES, {LOG_V_BAR_MSG, sizeof(log_Vehicle_Baro), "VBAR", "Qff", "TimeUS,Press,AltDiff" }, {LOG_V_POS_MSG, sizeof(log_Vehicle_Pos), "VPOS", "QLLefff", "TimeUS,Lat,Lng,Alt,VelX,VelY,VelZ" } }; void Tracker::Log_Write_Vehicle_Startup_Messages() { DataFlash.Log_Write_Mode(control_mode); } // start a new log void Tracker::start_logging() { if (g.log_bitmask != 0) { if (!logging_started) { logging_started = true; DataFlash.setVehicle_Startup_Log_Writer(FUNCTOR_BIND(&tracker, &Tracker::Log_Write_Vehicle_Startup_Messages, void)); DataFlash.StartNewLog(); } // enable writes DataFlash.EnableWrites(true); } } void Tracker::log_init(void) { DataFlash.Init(log_structure, ARRAY_SIZE(log_structure)); if (!DataFlash.CardInserted()) { gcs_send_text(MAV_SEVERITY_WARNING, "No dataflash card inserted"); } else if (DataFlash.NeedPrep()) { gcs_send_text(MAV_SEVERITY_INFO, "Preparing log system"); DataFlash.Prep(); gcs_send_text(MAV_SEVERITY_INFO, "Prepared log system"); for (uint8_t i=0; i<num_gcs; i++) { gcs_chan[i].reset_cli_timeout(); } } if (g.log_bitmask != 0) { start_logging(); } } #else // LOGGING_ENABLED void Tracker::Log_Write_Attitude(void) {} void Tracker::Log_Write_Baro(void) {} void Tracker::start_logging() {} void Tracker::log_init(void) {} void Tracker::Log_Write_Vehicle_Pos(int32_t lat, int32_t lng, int32_t alt, const Vector3f& vel) {} void Tracker::Log_Write_Vehicle_Baro(float pressure, float altitude) {} #endif // LOGGING_ENABLED
gpl-3.0
syntheticpp/metashell
3rd/templight/llvm/tools/clang/test/SemaCXX/MicrosoftCompatibility.cpp
7
5795
// RUN: %clang_cc1 %s -triple i686-pc-win32 -fsyntax-only -std=c++11 -Wmicrosoft -verify -fms-compatibility -fexceptions -fcxx-exceptions -fms-compatibility-version=19.00 // RUN: %clang_cc1 %s -triple i686-pc-win32 -fsyntax-only -std=c++11 -Wmicrosoft -verify -fms-compatibility -fexceptions -fcxx-exceptions -fms-compatibility-version=18.00 #if defined(_HAS_CHAR16_T_LANGUAGE_SUPPORT) && _HAS_CHAR16_T_LANGUAGE_SUPPORT char16_t x; char32_t y; #else typedef unsigned short char16_t; typedef unsigned int char32_t; #endif _Atomic(int) z; template <typename T> struct _Atomic { _Atomic() {} ~_Atomic() {} }; template <typename T> struct atomic : _Atomic<T> { typedef _Atomic<T> TheBase; TheBase field; }; _Atomic(int) alpha; typename decltype(3) a; // expected-warning {{expected a qualified name after 'typename'}} namespace ms_conversion_rules { void f(float a); void f(int a); void test() { long a = 0; f((long)0); f(a); } } namespace ms_predefined_types { // ::type_info is a built-in forward class declaration. void f(const type_info &a); void f(size_t); } namespace ms_protected_scope { struct C { C(); }; int jump_over_variable_init(bool b) { if (b) goto foo; // expected-warning {{jump from this goto statement to its label is a Microsoft extension}} C c; // expected-note {{jump bypasses variable initialization}} foo: return 1; } struct Y { ~Y(); }; void jump_over_var_with_dtor() { goto end; // expected-warning{{jump from this goto statement to its label is a Microsoft extension}} Y y; // expected-note {{jump bypasses variable with a non-trivial destructor}} end: ; } void jump_over_variable_case(int c) { switch (c) { case 0: int x = 56; // expected-note {{jump bypasses variable initialization}} case 1: // expected-error {{cannot jump}} x = 10; } } void exception_jump() { goto l2; // expected-error {{cannot jump}} try { // expected-note {{jump bypasses initialization of try block}} l2: ; } catch(int) { } } int jump_over_indirect_goto() { static void *ps[] = { &&a0 }; goto *&&a0; // expected-warning {{jump from this goto statement to its label is a Microsoft extension}} int a = 3; // expected-note {{jump bypasses variable initialization}} a0: return 0; } } namespace PR11826 { struct pair { pair(int v) { } void operator=(pair&& rhs) { } }; void f() { pair p0(3); pair p = p0; } } namespace PR11826_for_symmetry { struct pair { pair(int v) { } pair(pair&& rhs) { } }; void f() { pair p0(3); pair p(4); p = p0; } } namespace ms_using_declaration_bug { class A { public: int f(); }; class B : public A { private: using A::f; void g() { f(); // no diagnostic } }; class C : public B { private: using B::f; // expected-warning {{using declaration referring to inaccessible member 'ms_using_declaration_bug::B::f' (which refers to accessible member 'ms_using_declaration_bug::A::f') is a Microsoft compatibility extension}} }; } namespace using_tag_redeclaration { struct S; namespace N { using ::using_tag_redeclaration::S; struct S {}; // expected-note {{previous definition is here}} } void f() { N::S s1; S s2; } void g() { struct S; // expected-note {{forward declaration of 'S'}} S s3; // expected-error {{variable has incomplete type 'S'}} } void h() { using ::using_tag_redeclaration::S; struct S {}; // expected-error {{redefinition of 'S'}} } } namespace MissingTypename { template<class T> class A { public: typedef int TYPE; }; template<class T> class B { public: typedef int TYPE; }; template<class T, class U> class C : private A<T>, public B<U> { public: typedef A<T> Base1; typedef B<U> Base2; typedef A<U> Base3; A<T>::TYPE a1; // expected-warning {{missing 'typename' prior to dependent type name}} Base1::TYPE a2; // expected-warning {{missing 'typename' prior to dependent type name}} B<U>::TYPE a3; // expected-warning {{missing 'typename' prior to dependent type name}} Base2::TYPE a4; // expected-warning {{missing 'typename' prior to dependent type name}} A<U>::TYPE a5; // expected-error {{missing 'typename' prior to dependent type name}} Base3::TYPE a6; // expected-error {{missing 'typename' prior to dependent type name}} }; class D { public: typedef int Type; }; template <class T> void function_missing_typename(const T::Type param)// expected-warning {{missing 'typename' prior to dependent type name}} { const T::Type var = 2; // expected-warning {{missing 'typename' prior to dependent type name}} } template void function_missing_typename<D>(const D::Type param); } enum ENUM2 { ENUM2_a = (enum ENUM2) 4, ENUM2_b = 0x9FFFFFFF, // expected-warning {{enumerator value is not representable in the underlying type 'int'}} ENUM2_c = 0x100000000 // expected-warning {{enumerator value is not representable in the underlying type 'int'}} }; namespace PR11791 { template<class _Ty> void del(_Ty *_Ptr) { _Ptr->~_Ty(); // expected-warning {{pseudo-destructors on type void are a Microsoft extension}} } void f() { int* a = 0; del((void*)a); // expected-note {{in instantiation of function template specialization}} } } namespace IntToNullPtrConv { struct Foo { static const int ZERO = 0; typedef void (Foo::*MemberFcnPtr)(); }; struct Bar { const Foo::MemberFcnPtr pB; }; Bar g_bar = { (Foo::MemberFcnPtr)Foo::ZERO }; template<int N> int *get_n() { return N; } // expected-warning {{expression which evaluates to zero treated as a null pointer constant}} int *g_nullptr = get_n<0>(); // expected-note {{in instantiation of function template specialization}} }
gpl-3.0
tbs1980/gsl
bspline/bspline.c
8
28862
/* bspline/bspline.c * * Copyright (C) 2006, 2007, 2008, 2009 Patrick Alken * Copyright (C) 2008 Rhys Ulerich * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_statistics.h> /* * This module contains routines related to calculating B-splines. * The algorithms used are described in * * [1] Carl de Boor, "A Practical Guide to Splines", Springer * Verlag, 1978. * * The bspline_pppack_* internal routines contain code adapted from * * [2] "PPPACK - Piecewise Polynomial Package", * http://www.netlib.org/pppack/ * */ #include "bspline.h" /* gsl_bspline_alloc() Allocate space for a bspline workspace. The size of the workspace is O(5k + nbreak) Inputs: k - spline order (cubic = 4) nbreak - number of breakpoints Return: pointer to workspace */ gsl_bspline_workspace * gsl_bspline_alloc (const size_t k, const size_t nbreak) { if (k == 0) { GSL_ERROR_NULL ("k must be at least 1", GSL_EINVAL); } else if (nbreak < 2) { GSL_ERROR_NULL ("nbreak must be at least 2", GSL_EINVAL); } else { gsl_bspline_workspace *w; w = (gsl_bspline_workspace *) malloc (sizeof (gsl_bspline_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->k = k; w->km1 = k - 1; w->nbreak = nbreak; w->l = nbreak - 1; w->n = w->l + k - 1; w->knots = gsl_vector_alloc (w->n + k); if (w->knots == 0) { free (w); GSL_ERROR_NULL ("failed to allocate space for knots vector", GSL_ENOMEM); } w->deltal = gsl_vector_alloc (k); if (w->deltal == 0) { gsl_vector_free (w->knots); free (w); GSL_ERROR_NULL ("failed to allocate space for deltal vector", GSL_ENOMEM); } w->deltar = gsl_vector_alloc (k); if (w->deltar == 0) { gsl_vector_free (w->deltal); gsl_vector_free (w->knots); free (w); GSL_ERROR_NULL ("failed to allocate space for deltar vector", GSL_ENOMEM); } w->B = gsl_vector_alloc (k); if (w->B == 0) { gsl_vector_free (w->deltar);; gsl_vector_free (w->deltal); gsl_vector_free (w->knots); free (w); GSL_ERROR_NULL ("failed to allocate space for temporary spline vector", GSL_ENOMEM); } return w; } } /* gsl_bspline_alloc() */ /* gsl_bspline_deriv_alloc() Allocate space for a bspline derivative workspace. The size of the workspace is O(2k^2) Inputs: k - spline order (cubic = 4) Return: pointer to workspace */ gsl_bspline_deriv_workspace * gsl_bspline_deriv_alloc (const size_t k) { if (k == 0) { GSL_ERROR_NULL ("k must be at least 1", GSL_EINVAL); } else { gsl_bspline_deriv_workspace *dw; dw = (gsl_bspline_deriv_workspace *) malloc (sizeof (gsl_bspline_deriv_workspace)); if (dw == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } dw->A = gsl_matrix_alloc (k, k); if (dw->A == 0) { free (dw); GSL_ERROR_NULL ("failed to allocate space for derivative work matrix", GSL_ENOMEM); } dw->dB = gsl_matrix_alloc (k, k + 1); if (dw->dB == 0) { gsl_matrix_free (dw->A); free (dw); GSL_ERROR_NULL ("failed to allocate space for temporary derivative matrix", GSL_ENOMEM); } dw->k = k; return dw; } } /* gsl_bspline_deriv_alloc() */ /* Return number of coefficients */ size_t gsl_bspline_ncoeffs (gsl_bspline_workspace * w) { return w->n; } /* Return order */ size_t gsl_bspline_order (gsl_bspline_workspace * w) { return w->k; } /* Return number of breakpoints */ size_t gsl_bspline_nbreak (gsl_bspline_workspace * w) { return w->nbreak; } /* Return the location of the i-th breakpoint*/ double gsl_bspline_breakpoint (size_t i, gsl_bspline_workspace * w) { size_t j = i + w->k - 1; return gsl_vector_get (w->knots, j); } /* Return the location of the i-th Greville abscissa */ double gsl_bspline_greville_abscissa(size_t i, gsl_bspline_workspace *w) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= gsl_bspline_ncoeffs(w))) { GSL_ERROR_VAL ("Greville abscissa index out of range", GSL_EINVAL, 0); } #endif const size_t stride = w->knots->stride; size_t km1 = w->km1; double * data = w->knots->data + (i+1)*stride; if (km1 == 0) { /* Return interval midpoints in degenerate k = 1 case*/ km1 = 2; data -= stride; } return gsl_stats_mean(data, stride, km1); } /* gsl_bspline_free() Free a gsl_bspline_workspace. Inputs: w - workspace to free Return: none */ void gsl_bspline_free (gsl_bspline_workspace * w) { RETURN_IF_NULL (w); gsl_vector_free (w->knots); gsl_vector_free (w->deltal); gsl_vector_free (w->deltar); gsl_vector_free (w->B); free (w); } /* gsl_bspline_free() */ /* gsl_bspline_deriv_free() Free a gsl_bspline_deriv_workspace. Inputs: dw - workspace to free Return: none */ void gsl_bspline_deriv_free (gsl_bspline_deriv_workspace * dw) { RETURN_IF_NULL (dw); gsl_matrix_free (dw->A); gsl_matrix_free (dw->dB); free (dw); } /* gsl_bspline_deriv_free() */ /* gsl_bspline_knots() Compute the knots from the given breakpoints: knots(1:k) = breakpts(1) knots(k+1:k+l-1) = breakpts(i), i = 2 .. l knots(n+1:n+k) = breakpts(l + 1) where l is the number of polynomial pieces (l = nbreak - 1) and n = k + l - 1 (using matlab syntax for the arrays) The repeated knots at the beginning and end of the interval correspond to the continuity condition there. See pg. 119 of [1]. Inputs: breakpts - breakpoints w - bspline workspace Return: success or error */ int gsl_bspline_knots (const gsl_vector * breakpts, gsl_bspline_workspace * w) { if (breakpts->size != w->nbreak) { GSL_ERROR ("breakpts vector has wrong size", GSL_EBADLEN); } else { size_t i; /* looping */ for (i = 0; i < w->k; i++) gsl_vector_set (w->knots, i, gsl_vector_get (breakpts, 0)); for (i = 1; i < w->l; i++) { gsl_vector_set (w->knots, w->k - 1 + i, gsl_vector_get (breakpts, i)); } for (i = w->n; i < w->n + w->k; i++) gsl_vector_set (w->knots, i, gsl_vector_get (breakpts, w->l)); return GSL_SUCCESS; } } /* gsl_bspline_knots() */ /* gsl_bspline_knots_uniform() Construct uniformly spaced knots on the interval [a,b] using the previously specified number of breakpoints. 'a' is the position of the first breakpoint and 'b' is the position of the last breakpoint. Inputs: a - left side of interval b - right side of interval w - bspline workspace Return: success or error Notes: 1) w->knots is modified to contain the uniformly spaced knots 2) The knots vector is set up as follows (using octave syntax): knots(1:k) = a knots(k+1:k+l-1) = a + i*delta, i = 1 .. l - 1 knots(n+1:n+k) = b */ int gsl_bspline_knots_uniform (const double a, const double b, gsl_bspline_workspace * w) { size_t i; /* looping */ double delta; /* interval spacing */ double x; delta = (b - a) / (double) w->l; for (i = 0; i < w->k; i++) gsl_vector_set (w->knots, i, a); x = a + delta; for (i = 0; i < w->l - 1; i++) { gsl_vector_set (w->knots, w->k + i, x); x += delta; } for (i = w->n; i < w->n + w->k; i++) gsl_vector_set (w->knots, i, b); return GSL_SUCCESS; } /* gsl_bspline_knots_uniform() */ /* gsl_bspline_eval() Evaluate the basis functions B_i(x) for all i. This is a wrapper function for gsl_bspline_eval_nonzero() which formats the output in a nice way. Inputs: x - point for evaluation B - (output) where to store B_i(x) values the length of this vector is n = nbreak + k - 2 = l + k - 1 = w->n w - bspline workspace Return: success or error Notes: The w->knots vector must be initialized prior to calling this function (see gsl_bspline_knots()) */ int gsl_bspline_eval (const double x, gsl_vector * B, gsl_bspline_workspace * w) { if (B->size != w->n) { GSL_ERROR ("vector B not of length n", GSL_EBADLEN); } else { size_t i; /* looping */ size_t istart; /* first non-zero spline for x */ size_t iend; /* last non-zero spline for x, knot for x */ int error; /* error handling */ /* find all non-zero B_i(x) values */ error = gsl_bspline_eval_nonzero (x, w->B, &istart, &iend, w); if (error) { return error; } /* store values in appropriate part of given vector */ for (i = 0; i < istart; i++) gsl_vector_set (B, i, 0.0); for (i = istart; i <= iend; i++) gsl_vector_set (B, i, gsl_vector_get (w->B, i - istart)); for (i = iend + 1; i < w->n; i++) gsl_vector_set (B, i, 0.0); return GSL_SUCCESS; } } /* gsl_bspline_eval() */ /* gsl_bspline_eval_nonzero() Evaluate all non-zero B-spline functions at point x. These are the B_i(x) for i in [istart, iend]. Always B_i(x) = 0 for i < istart and for i > iend. Inputs: x - point at which to evaluate splines Bk - (output) where to store B-spline values (length k) istart - (output) B-spline function index of first non-zero basis for given x iend - (output) B-spline function index of last non-zero basis for given x. This is also the knot index corresponding to x. w - bspline workspace Return: success or error Notes: 1) the w->knots vector must be initialized before calling this function 2) On output, B contains [B_{istart,k}, B_{istart+1,k}, ..., B_{iend-1,k}, B_{iend,k}] evaluated at the given x. */ int gsl_bspline_eval_nonzero (const double x, gsl_vector * Bk, size_t * istart, size_t * iend, gsl_bspline_workspace * w) { if (Bk->size != w->k) { GSL_ERROR ("Bk vector length does not match order k", GSL_EBADLEN); } else { size_t i; /* spline index */ size_t j; /* looping */ int flag = 0; /* interval search flag */ int error = 0; /* error flag */ i = bspline_find_interval (x, &flag, w); error = bspline_process_interval_for_eval (x, &i, flag, w); if (error) { return error; } *istart = i - w->k + 1; *iend = i; bspline_pppack_bsplvb (w->knots, w->k, 1, x, *iend, &j, w->deltal, w->deltar, Bk); return GSL_SUCCESS; } } /* gsl_bspline_eval_nonzero() */ /* gsl_bspline_deriv_eval() Evaluate d^j/dx^j B_i(x) for all i, 0 <= j <= nderiv. This is a wrapper function for gsl_bspline_deriv_eval_nonzero() which formats the output in a nice way. Inputs: x - point for evaluation nderiv - number of derivatives to compute, inclusive. dB - (output) where to store d^j/dx^j B_i(x) values. the size of this matrix is (n = nbreak + k - 2 = l + k - 1 = w->n) by (nderiv + 1) w - bspline derivative workspace Return: success or error Notes: 1) The w->knots vector must be initialized prior to calling this function (see gsl_bspline_knots()) 2) based on PPPACK's bsplvd */ int gsl_bspline_deriv_eval (const double x, const size_t nderiv, gsl_matrix * dB, gsl_bspline_workspace * w, gsl_bspline_deriv_workspace * dw) { if (dB->size1 != w->n) { GSL_ERROR ("dB matrix first dimension not of length n", GSL_EBADLEN); } else if (dB->size2 < nderiv + 1) { GSL_ERROR ("dB matrix second dimension must be at least length nderiv+1", GSL_EBADLEN); } else if (dw->k < w->k) { GSL_ERROR ("derivative workspace is too small", GSL_EBADLEN); } else { size_t i; /* looping */ size_t j; /* looping */ size_t istart; /* first non-zero spline for x */ size_t iend; /* last non-zero spline for x, knot for x */ int error; /* error handling */ /* find all non-zero d^j/dx^j B_i(x) values */ error = gsl_bspline_deriv_eval_nonzero (x, nderiv, dw->dB, &istart, &iend, w, dw); if (error) { return error; } /* store values in appropriate part of given matrix */ for (j = 0; j <= nderiv; j++) { for (i = 0; i < istart; i++) gsl_matrix_set (dB, i, j, 0.0); for (i = istart; i <= iend; i++) gsl_matrix_set (dB, i, j, gsl_matrix_get (dw->dB, i - istart, j)); for (i = iend + 1; i < w->n; i++) gsl_matrix_set (dB, i, j, 0.0); } return GSL_SUCCESS; } } /* gsl_bspline_deriv_eval() */ /* gsl_bspline_deriv_eval_nonzero() At point x evaluate all requested, non-zero B-spline function derivatives and store them in dB. These are the d^j/dx^j B_i(x) with i in [istart, iend] and j in [0, nderiv]. Always d^j/dx^j B_i(x) = 0 for i < istart and for i > iend. Inputs: x - point at which to evaluate splines nderiv - number of derivatives to request, inclusive dB - (output) where to store dB-spline derivatives (size k by nderiv + 1) istart - (output) B-spline function index of first non-zero basis for given x iend - (output) B-spline function index of last non-zero basis for given x. This is also the knot index corresponding to x. w - bspline derivative workspace Return: success or error Notes: 1) the w->knots vector must be initialized before calling this function 2) On output, dB contains [[B_{istart, k}, ..., d^nderiv/dx^nderiv B_{istart ,k}], [B_{istart+1,k}, ..., d^nderiv/dx^nderiv B_{istart+1,k}], ... [B_{iend-1, k}, ..., d^nderiv/dx^nderiv B_{iend-1, k}], [B_{iend, k}, ..., d^nderiv/dx^nderiv B_{iend, k}]] evaluated at x. B_{istart, k} is stored in dB(0,0). Each additional column contains an additional derivative. 3) Note that the zero-th column of the result contains the 0th derivative, which is simply a function evaluation. 4) based on PPPACK's bsplvd */ int gsl_bspline_deriv_eval_nonzero (const double x, const size_t nderiv, gsl_matrix * dB, size_t * istart, size_t * iend, gsl_bspline_workspace * w, gsl_bspline_deriv_workspace * dw) { if (dB->size1 != w->k) { GSL_ERROR ("dB matrix first dimension not of length k", GSL_EBADLEN); } else if (dB->size2 < nderiv + 1) { GSL_ERROR ("dB matrix second dimension must be at least length nderiv+1", GSL_EBADLEN); } else if (dw->k < w->k) { GSL_ERROR ("derivative workspace is too small", GSL_EBADLEN); } else { size_t i; /* spline index */ size_t j; /* looping */ int flag = 0; /* interval search flag */ int error = 0; /* error flag */ size_t min_nderivk; i = bspline_find_interval (x, &flag, w); error = bspline_process_interval_for_eval (x, &i, flag, w); if (error) { return error; } *istart = i - w->k + 1; *iend = i; bspline_pppack_bsplvd (w->knots, w->k, x, *iend, w->deltal, w->deltar, dw->A, dB, nderiv); /* An order k b-spline has at most k-1 nonzero derivatives so we need to zero all requested higher order derivatives */ min_nderivk = GSL_MIN_INT (nderiv, w->k - 1); for (j = min_nderivk + 1; j <= nderiv; j++) { for (i = 0; i < w->k; i++) { gsl_matrix_set (dB, i, j, 0.0); } } return GSL_SUCCESS; } } /* gsl_bspline_deriv_eval_nonzero() */ /**************************************** * INTERNAL ROUTINES * ****************************************/ /* bspline_find_interval() Find knot interval such that t_i <= x < t_{i + 1} where the t_i are knot values. Inputs: x - x value flag - (output) error flag w - bspline workspace Return: i (index in w->knots corresponding to left limit of interval) Notes: The error conditions are reported as follows: Condition Return value Flag --------- ------------ ---- x < t_0 0 -1 t_i <= x < t_{i+1} i 0 t_i < x = t_{i+1} = t_{n+k-1} i 0 t_{n+k-1} < x l+k-1 +1 */ static inline size_t bspline_find_interval (const double x, int *flag, gsl_bspline_workspace * w) { size_t i; if (x < gsl_vector_get (w->knots, 0)) { *flag = -1; return 0; } /* find i such that t_i <= x < t_{i+1} */ for (i = w->k - 1; i < w->k + w->l - 1; i++) { const double ti = gsl_vector_get (w->knots, i); const double tip1 = gsl_vector_get (w->knots, i + 1); if (tip1 < ti) { GSL_ERROR ("knots vector is not increasing", GSL_EINVAL); } if (ti <= x && x < tip1) break; if (ti < x && x == tip1 && tip1 == gsl_vector_get (w->knots, w->k + w->l - 1)) break; } if (i == w->k + w->l - 1) *flag = 1; else *flag = 0; return i; } /* bspline_find_interval() */ /* bspline_process_interval_for_eval() Consumes an x location, left knot from bspline_find_interval, flag from bspline_find_interval, and a workspace. Checks that x lies within the splines' knots, enforces some endpoint continuity requirements, and avoids divide by zero errors in the underlying bspline_pppack_* functions. */ static inline int bspline_process_interval_for_eval (const double x, size_t * i, const int flag, gsl_bspline_workspace * w) { if (flag == -1) { GSL_ERROR ("x outside of knot interval", GSL_EINVAL); } else if (flag == 1) { if (x <= gsl_vector_get (w->knots, *i) + GSL_DBL_EPSILON) { *i -= 1; } else { GSL_ERROR ("x outside of knot interval", GSL_EINVAL); } } if (gsl_vector_get (w->knots, *i) == gsl_vector_get (w->knots, *i + 1)) { GSL_ERROR ("knot(i) = knot(i+1) will result in division by zero", GSL_EINVAL); } return GSL_SUCCESS; } /* bspline_process_interval_for_eval */ /******************************************************************** * PPPACK ROUTINES * * The routines herein deliberately avoid using the bspline workspace, * choosing instead to pass all work areas explicitly. This allows * others to more easily adapt these routines to low memory or * parallel scenarios. ********************************************************************/ /* bspline_pppack_bsplvb() calculates the value of all possibly nonzero b-splines at x of order jout = max( jhigh , (j+1)*(index-1) ) with knot sequence t. Parameters: t - knot sequence, of length left + jout , assumed to be nondecreasing. assumption t(left).lt.t(left + 1). division by zero will result if t(left) = t(left+1) jhigh - index - integers which determine the order jout = max(jhigh, (j+1)*(index-1)) of the b-splines whose values at x are to be returned. index is used to avoid recalculations when several columns of the triangular array of b-spline values are needed (e.g., in bsplpp or in bsplvd ). precisely, if index = 1 , the calculation starts from scratch and the entire triangular array of b-spline values of orders 1,2,...,jhigh is generated order by order , i.e., column by column . if index = 2 , only the b-spline values of order j+1, j+2, ..., jout are generated, the assumption being that biatx, j, deltal, deltar are, on entry, as they were on exit at the previous call. in particular, if jhigh = 0, then jout = j+1, i.e., just the next column of b-spline values is generated. x - the point at which the b-splines are to be evaluated. left - an integer chosen (usually) so that t(left) .le. x .le. t(left+1). j - (output) a working scalar for indexing deltal - (output) a working area which must be of length at least jout deltar - (output) a working area which must be of length at least jout biatx - (output) array of length jout, with biatx(i) containing the value at x of the polynomial of order jout which agrees with the b-spline b(left-jout+i,jout,t) on the interval (t(left), t(left+1)) . Method: the recurrence relation x - t(i) t(i+j+1) - x b(i,j+1)(x) = -----------b(i,j)(x) + ---------------b(i+1,j)(x) t(i+j)-t(i) t(i+j+1)-t(i+1) is used (repeatedly) to generate the (j+1)-vector b(left-j,j+1)(x), ...,b(left,j+1)(x) from the j-vector b(left-j+1,j)(x),..., b(left,j)(x), storing the new values in biatx over the old. the facts that b(i,1) = 1 if t(i) .le. x .lt. t(i+1) and that b(i,j)(x) = 0 unless t(i) .le. x .lt. t(i+j) are used. the particular organization of the calculations follows algorithm (8) in chapter x of [1]. Notes: (1) This is a direct translation of PPPACK's bsplvb routine with j, deltal, deltar rewritten as input parameters and utilizing zero-based indexing. (2) This routine contains no error checking. Please use routines like gsl_bspline_eval(). */ static void bspline_pppack_bsplvb (const gsl_vector * t, const size_t jhigh, const size_t index, const double x, const size_t left, size_t * j, gsl_vector * deltal, gsl_vector * deltar, gsl_vector * biatx) { size_t i; /* looping */ double saved; double term; if (index == 1) { *j = 0; gsl_vector_set (biatx, 0, 1.0); } for ( /* NOP */ ; *j < jhigh - 1; *j += 1) { gsl_vector_set (deltar, *j, gsl_vector_get (t, left + *j + 1) - x); gsl_vector_set (deltal, *j, x - gsl_vector_get (t, left - *j)); saved = 0.0; for (i = 0; i <= *j; i++) { term = gsl_vector_get (biatx, i) / (gsl_vector_get (deltar, i) + gsl_vector_get (deltal, *j - i)); gsl_vector_set (biatx, i, saved + gsl_vector_get (deltar, i) * term); saved = gsl_vector_get (deltal, *j - i) * term; } gsl_vector_set (biatx, *j + 1, saved); } return; } /* gsl_bspline_pppack_bsplvb */ /* bspline_pppack_bsplvd() calculates value and derivs of all b-splines which do not vanish at x Parameters: t - the knot array, of length left+k (at least) k - the order of the b-splines to be evaluated x - the point at which these values are sought left - an integer indicating the left endpoint of the interval of interest. the k b-splines whose support contains the interval (t(left), t(left+1)) are to be considered. it is assumed that t(left) .lt. t(left+1) division by zero will result otherwise (in bsplvb). also, the output is as advertised only if t(left) .le. x .le. t(left+1) . deltal - a working area which must be of length at least k deltar - a working area which must be of length at least k a - an array of order (k,k), to contain b-coeffs of the derivatives of a certain order of the k b-splines of interest. dbiatx - an array of order (k,nderiv). its entry (i,m) contains value of (m)th derivative of (left-k+i)-th b-spline of order k for knot sequence t, i=1,...,k, m=0,...,nderiv. nderiv - an integer indicating that values of b-splines and their derivatives up to AND INCLUDING the nderiv-th are asked for. (nderiv is replaced internally by the integer mhigh in (1,k) closest to it.) Method: values at x of all the relevant b-splines of order k,k-1,..., k+1-nderiv are generated via bsplvb and stored temporarily in dbiatx. then, the b-coeffs of the required derivatives of the b-splines of interest are generated by differencing, each from the preceeding one of lower order, and combined with the values of b-splines of corresponding order in dbiatx to produce the desired values . Notes: (1) This is a direct translation of PPPACK's bsplvd routine with deltal, deltar rewritten as input parameters (to later feed them to bspline_pppack_bsplvb) and utilizing zero-based indexing. (2) This routine contains no error checking. */ static void bspline_pppack_bsplvd (const gsl_vector * t, const size_t k, const double x, const size_t left, gsl_vector * deltal, gsl_vector * deltar, gsl_matrix * a, gsl_matrix * dbiatx, const size_t nderiv) { int i, ideriv, il, j, jlow, jp1mid, kmm, ldummy, m, mhigh; double factor, fkmm, sum; size_t bsplvb_j; gsl_vector_view dbcol = gsl_matrix_column (dbiatx, 0); mhigh = GSL_MIN_INT (nderiv, k - 1); bspline_pppack_bsplvb (t, k - mhigh, 1, x, left, &bsplvb_j, deltal, deltar, &dbcol.vector); if (mhigh > 0) { /* the first column of dbiatx always contains the b-spline values for the current order. these are stored in column k-current order before bsplvb is called to put values for the next higher order on top of it. */ ideriv = mhigh; for (m = 1; m <= mhigh; m++) { for (j = ideriv, jp1mid = 0; j < (int) k; j++, jp1mid++) { gsl_matrix_set (dbiatx, j, ideriv, gsl_matrix_get (dbiatx, jp1mid, 0)); } ideriv--; bspline_pppack_bsplvb (t, k - ideriv, 2, x, left, &bsplvb_j, deltal, deltar, &dbcol.vector); } /* at this point, b(left-k+i, k+1-j)(x) is in dbiatx(i,j) for i=j,...,k-1 and j=0,...,mhigh. in particular, the first column of dbiatx is already in final form. to obtain corresponding derivatives of b-splines in subsequent columns, generate their b-repr. by differencing, then evaluate at x. */ jlow = 0; for (i = 0; i < (int) k; i++) { for (j = jlow; j < (int) k; j++) { gsl_matrix_set (a, j, i, 0.0); } jlow = i; gsl_matrix_set (a, i, i, 1.0); } /* at this point, a(.,j) contains the b-coeffs for the j-th of the k b-splines of interest here. */ for (m = 1; m <= mhigh; m++) { kmm = k - m; fkmm = (float) kmm; il = left; i = k - 1; /* for j=1,...,k, construct b-coeffs of (m)th derivative of b-splines from those for preceding derivative by differencing and store again in a(.,j) . the fact that a(i,j) = 0 for i .lt. j is used. */ for (ldummy = 0; ldummy < kmm; ldummy++) { factor = fkmm / (gsl_vector_get (t, il + kmm) - gsl_vector_get (t, il)); /* the assumption that t(left).lt.t(left+1) makes denominator in factor nonzero. */ for (j = 0; j <= i; j++) { gsl_matrix_set (a, i, j, factor * (gsl_matrix_get (a, i, j) - gsl_matrix_get (a, i - 1, j))); } il--; i--; } /* for i=1,...,k, combine b-coeffs a(.,i) with b-spline values stored in dbiatx(.,m) to get value of (m)th derivative of i-th b-spline (of interest here) at x, and store in dbiatx(i,m). storage of this value over the value of a b-spline of order m there is safe since the remaining b-spline derivatives of the same order do not use this value due to the fact that a(j,i) = 0 for j .lt. i . */ for (i = 0; i < (int) k; i++) { sum = 0; jlow = GSL_MAX_INT (i, m); for (j = jlow; j < (int) k; j++) { sum += gsl_matrix_get (a, j, i) * gsl_matrix_get (dbiatx, j, m); } gsl_matrix_set (dbiatx, i, m, sum); } } } return; } /* bspline_pppack_bsplvd */
gpl-3.0
encukou/samba
lib/socket_wrapper/socket_wrapper.c
8
117502
/* * Copyright (c) 2005-2008 Jelmer Vernooij <jelmer@samba.org> * Copyright (C) 2006-2014 Stefan Metzmacher <metze@samba.org> * Copyright (C) 2013-2014 Andreas Schneider <asn@samba.org> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* Socket wrapper library. Passes all socket communication over unix domain sockets if the environment variable SOCKET_WRAPPER_DIR is set. */ #include "config.h" #include <sys/types.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/ioctl.h> #ifdef HAVE_SYS_FILIO_H #include <sys/filio.h> #endif #ifdef HAVE_SYS_SIGNALFD_H #include <sys/signalfd.h> #endif #ifdef HAVE_SYS_EVENTFD_H #include <sys/eventfd.h> #endif #ifdef HAVE_SYS_TIMERFD_H #include <sys/timerfd.h> #endif #include <sys/uio.h> #include <errno.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include <stdarg.h> #include <stdbool.h> #include <unistd.h> #ifdef HAVE_GNU_LIB_NAMES_H #include <gnu/lib-names.h> #endif #ifdef HAVE_RPC_RPC_H #include <rpc/rpc.h> #endif enum swrap_dbglvl_e { SWRAP_LOG_ERROR = 0, SWRAP_LOG_WARN, SWRAP_LOG_DEBUG, SWRAP_LOG_TRACE }; /* GCC have printf type attribute check. */ #ifdef HAVE_FUNCTION_ATTRIBUTE_FORMAT #define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b))) #else #define PRINTF_ATTRIBUTE(a,b) #endif /* HAVE_FUNCTION_ATTRIBUTE_FORMAT */ #ifdef HAVE_DESTRUCTOR_ATTRIBUTE #define DESTRUCTOR_ATTRIBUTE __attribute__ ((destructor)) #else #define DESTRUCTOR_ATTRIBUTE #endif #ifdef HAVE_ADDRESS_SANITIZER_ATTRIBUTE #define DO_NOT_SANITIZE_ADDRESS_ATTRIBUTE __attribute__((no_sanitize_address)) #else #define DO_NOT_SANITIZE_ADDRESS_ATTRIBUTE #endif #ifdef HAVE_GCC_THREAD_LOCAL_STORAGE # define SWRAP_THREAD __thread #else # define SWRAP_THREAD #endif #ifndef MIN #define MIN(a,b) ((a)<(b)?(a):(b)) #endif #ifndef ZERO_STRUCT #define ZERO_STRUCT(x) memset((char *)&(x), 0, sizeof(x)) #endif #ifndef ZERO_STRUCTP #define ZERO_STRUCTP(x) do { \ if ((x) != NULL) \ memset((char *)(x), 0, sizeof(*(x))); \ } while(0) #endif #ifndef discard_const #define discard_const(ptr) ((void *)((uintptr_t)(ptr))) #endif #ifndef discard_const_p #define discard_const_p(type, ptr) ((type *)discard_const(ptr)) #endif #ifdef IPV6_PKTINFO # ifndef IPV6_RECVPKTINFO # define IPV6_RECVPKTINFO IPV6_PKTINFO # endif /* IPV6_RECVPKTINFO */ #endif /* IPV6_PKTINFO */ /* * On BSD IP_PKTINFO has a different name because during * the time when they implemented it, there was no RFC. * The name for IPv6 is the same as on Linux. */ #ifndef IP_PKTINFO # ifdef IP_RECVDSTADDR # define IP_PKTINFO IP_RECVDSTADDR # endif #endif #define SWRAP_DLIST_ADD(list,item) do { \ if (!(list)) { \ (item)->prev = NULL; \ (item)->next = NULL; \ (list) = (item); \ } else { \ (item)->prev = NULL; \ (item)->next = (list); \ (list)->prev = (item); \ (list) = (item); \ } \ } while (0) #define SWRAP_DLIST_REMOVE(list,item) do { \ if ((list) == (item)) { \ (list) = (item)->next; \ if (list) { \ (list)->prev = NULL; \ } \ } else { \ if ((item)->prev) { \ (item)->prev->next = (item)->next; \ } \ if ((item)->next) { \ (item)->next->prev = (item)->prev; \ } \ } \ (item)->prev = NULL; \ (item)->next = NULL; \ } while (0) #if defined(HAVE_GETTIMEOFDAY_TZ) || defined(HAVE_GETTIMEOFDAY_TZ_VOID) #define swrapGetTimeOfDay(tval) gettimeofday(tval,NULL) #else #define swrapGetTimeOfDay(tval) gettimeofday(tval) #endif /* we need to use a very terse format here as IRIX 6.4 silently truncates names to 16 chars, so if we use a longer name then we can't tell which port a packet came from with recvfrom() with this format we have 8 chars left for the directory name */ #define SOCKET_FORMAT "%c%02X%04X" #define SOCKET_TYPE_CHAR_TCP 'T' #define SOCKET_TYPE_CHAR_UDP 'U' #define SOCKET_TYPE_CHAR_TCP_V6 'X' #define SOCKET_TYPE_CHAR_UDP_V6 'Y' /* * Set the packet MTU to 1500 bytes for stream sockets to make it it easier to * format PCAP capture files (as the caller will simply continue from here). */ #define SOCKET_WRAPPER_MTU_DEFAULT 1500 #define SOCKET_WRAPPER_MTU_MIN 512 #define SOCKET_WRAPPER_MTU_MAX 32768 #define SOCKET_MAX_SOCKETS 1024 /* This limit is to avoid broadcast sendto() needing to stat too many * files. It may be raised (with a performance cost) to up to 254 * without changing the format above */ #define MAX_WRAPPED_INTERFACES 40 struct swrap_address { socklen_t sa_socklen; union { struct sockaddr s; struct sockaddr_in in; #ifdef HAVE_IPV6 struct sockaddr_in6 in6; #endif struct sockaddr_un un; struct sockaddr_storage ss; } sa; }; struct socket_info_fd { struct socket_info_fd *prev, *next; int fd; }; struct socket_info { struct socket_info_fd *fds; int family; int type; int protocol; int bound; int bcast; int is_server; int connected; int defer_connect; int pktinfo; int tcp_nodelay; /* The unix path so we can unlink it on close() */ struct sockaddr_un un_addr; struct swrap_address bindname; struct swrap_address myname; struct swrap_address peername; struct { unsigned long pck_snd; unsigned long pck_rcv; } io; struct socket_info *prev, *next; }; /* * File descriptors are shared between threads so we should share socket * information too. */ struct socket_info *sockets; /* Function prototypes */ bool socket_wrapper_enabled(void); void swrap_destructor(void) DESTRUCTOR_ATTRIBUTE; #ifdef NDEBUG # define SWRAP_LOG(...) #else static void swrap_log(enum swrap_dbglvl_e dbglvl, const char *func, const char *format, ...) PRINTF_ATTRIBUTE(3, 4); # define SWRAP_LOG(dbglvl, ...) swrap_log((dbglvl), __func__, __VA_ARGS__) static void swrap_log(enum swrap_dbglvl_e dbglvl, const char *func, const char *format, ...) { char buffer[1024]; va_list va; const char *d; unsigned int lvl = 0; d = getenv("SOCKET_WRAPPER_DEBUGLEVEL"); if (d != NULL) { lvl = atoi(d); } va_start(va, format); vsnprintf(buffer, sizeof(buffer), format, va); va_end(va); if (lvl >= dbglvl) { switch (dbglvl) { case SWRAP_LOG_ERROR: fprintf(stderr, "SWRAP_ERROR(%d) - %s: %s\n", (int)getpid(), func, buffer); break; case SWRAP_LOG_WARN: fprintf(stderr, "SWRAP_WARN(%d) - %s: %s\n", (int)getpid(), func, buffer); break; case SWRAP_LOG_DEBUG: fprintf(stderr, "SWRAP_DEBUG(%d) - %s: %s\n", (int)getpid(), func, buffer); break; case SWRAP_LOG_TRACE: fprintf(stderr, "SWRAP_TRACE(%d) - %s: %s\n", (int)getpid(), func, buffer); break; } } } #endif /********************************************************* * SWRAP LOADING LIBC FUNCTIONS *********************************************************/ #include <dlfcn.h> struct swrap_libc_fns { #ifdef HAVE_ACCEPT4 int (*libc_accept4)(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags); #else int (*libc_accept)(int sockfd, struct sockaddr *addr, socklen_t *addrlen); #endif int (*libc_bind)(int sockfd, const struct sockaddr *addr, socklen_t addrlen); int (*libc_close)(int fd); int (*libc_connect)(int sockfd, const struct sockaddr *addr, socklen_t addrlen); int (*libc_dup)(int fd); int (*libc_dup2)(int oldfd, int newfd); int (*libc_fcntl)(int fd, int cmd, ...); FILE *(*libc_fopen)(const char *name, const char *mode); #ifdef HAVE_EVENTFD int (*libc_eventfd)(int count, int flags); #endif int (*libc_getpeername)(int sockfd, struct sockaddr *addr, socklen_t *addrlen); int (*libc_getsockname)(int sockfd, struct sockaddr *addr, socklen_t *addrlen); int (*libc_getsockopt)(int sockfd, int level, int optname, void *optval, socklen_t *optlen); int (*libc_ioctl)(int d, unsigned long int request, ...); int (*libc_listen)(int sockfd, int backlog); int (*libc_open)(const char *pathname, int flags, mode_t mode); int (*libc_pipe)(int pipefd[2]); int (*libc_read)(int fd, void *buf, size_t count); ssize_t (*libc_readv)(int fd, const struct iovec *iov, int iovcnt); int (*libc_recv)(int sockfd, void *buf, size_t len, int flags); int (*libc_recvfrom)(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen); int (*libc_recvmsg)(int sockfd, const struct msghdr *msg, int flags); int (*libc_send)(int sockfd, const void *buf, size_t len, int flags); int (*libc_sendmsg)(int sockfd, const struct msghdr *msg, int flags); int (*libc_sendto)(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dst_addr, socklen_t addrlen); int (*libc_setsockopt)(int sockfd, int level, int optname, const void *optval, socklen_t optlen); #ifdef HAVE_SIGNALFD int (*libc_signalfd)(int fd, const sigset_t *mask, int flags); #endif int (*libc_socket)(int domain, int type, int protocol); int (*libc_socketpair)(int domain, int type, int protocol, int sv[2]); #ifdef HAVE_TIMERFD_CREATE int (*libc_timerfd_create)(int clockid, int flags); #endif ssize_t (*libc_write)(int fd, const void *buf, size_t count); ssize_t (*libc_writev)(int fd, const struct iovec *iov, int iovcnt); }; struct swrap { void *libc_handle; void *libsocket_handle; bool initialised; bool enabled; char *socket_dir; struct swrap_libc_fns fns; }; static struct swrap swrap; /* prototypes */ static const char *socket_wrapper_dir(void); #define LIBC_NAME "libc.so" enum swrap_lib { SWRAP_LIBC, SWRAP_LIBNSL, SWRAP_LIBSOCKET, }; #ifndef NDEBUG static const char *swrap_str_lib(enum swrap_lib lib) { switch (lib) { case SWRAP_LIBC: return "libc"; case SWRAP_LIBNSL: return "libnsl"; case SWRAP_LIBSOCKET: return "libsocket"; } /* Compiler would warn us about unhandled enum value if we get here */ return "unknown"; } #endif static void *swrap_load_lib_handle(enum swrap_lib lib) { int flags = RTLD_LAZY; void *handle = NULL; int i; #ifdef RTLD_DEEPBIND flags |= RTLD_DEEPBIND; #endif switch (lib) { case SWRAP_LIBNSL: /* FALL TROUGH */ case SWRAP_LIBSOCKET: #ifdef HAVE_LIBSOCKET handle = swrap.libsocket_handle; if (handle == NULL) { for (i = 10; i >= 0; i--) { char soname[256] = {0}; snprintf(soname, sizeof(soname), "libsocket.so.%d", i); handle = dlopen(soname, flags); if (handle != NULL) { break; } } swrap.libsocket_handle = handle; } break; #endif /* FALL TROUGH */ case SWRAP_LIBC: handle = swrap.libc_handle; #ifdef LIBC_SO if (handle == NULL) { handle = dlopen(LIBC_SO, flags); swrap.libc_handle = handle; } #endif if (handle == NULL) { for (i = 10; i >= 0; i--) { char soname[256] = {0}; snprintf(soname, sizeof(soname), "libc.so.%d", i); handle = dlopen(soname, flags); if (handle != NULL) { break; } } swrap.libc_handle = handle; } break; } if (handle == NULL) { #ifdef RTLD_NEXT handle = swrap.libc_handle = swrap.libsocket_handle = RTLD_NEXT; #else SWRAP_LOG(SWRAP_LOG_ERROR, "Failed to dlopen library: %s\n", dlerror()); exit(-1); #endif } return handle; } static void *_swrap_load_lib_function(enum swrap_lib lib, const char *fn_name) { void *handle; void *func; handle = swrap_load_lib_handle(lib); func = dlsym(handle, fn_name); if (func == NULL) { SWRAP_LOG(SWRAP_LOG_ERROR, "Failed to find %s: %s\n", fn_name, dlerror()); exit(-1); } SWRAP_LOG(SWRAP_LOG_TRACE, "Loaded %s from %s", fn_name, swrap_str_lib(lib)); return func; } #define swrap_load_lib_function(lib, fn_name) \ if (swrap.fns.libc_##fn_name == NULL) { \ void *swrap_cast_ptr = _swrap_load_lib_function(lib, #fn_name); \ *(void **) (&swrap.fns.libc_##fn_name) = \ swrap_cast_ptr; \ } /* * IMPORTANT * * Functions especially from libc need to be loaded individually, you can't load * all at once or gdb will segfault at startup. The same applies to valgrind and * has probably something todo with with the linker. * So we need load each function at the point it is called the first time. */ #ifdef HAVE_ACCEPT4 static int libc_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) { swrap_load_lib_function(SWRAP_LIBSOCKET, accept4); return swrap.fns.libc_accept4(sockfd, addr, addrlen, flags); } #else /* HAVE_ACCEPT4 */ static int libc_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, accept); return swrap.fns.libc_accept(sockfd, addr, addrlen); } #endif /* HAVE_ACCEPT4 */ static int libc_bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, bind); return swrap.fns.libc_bind(sockfd, addr, addrlen); } static int libc_close(int fd) { swrap_load_lib_function(SWRAP_LIBC, close); return swrap.fns.libc_close(fd); } static int libc_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, connect); return swrap.fns.libc_connect(sockfd, addr, addrlen); } static int libc_dup(int fd) { swrap_load_lib_function(SWRAP_LIBC, dup); return swrap.fns.libc_dup(fd); } static int libc_dup2(int oldfd, int newfd) { swrap_load_lib_function(SWRAP_LIBC, dup2); return swrap.fns.libc_dup2(oldfd, newfd); } #ifdef HAVE_EVENTFD static int libc_eventfd(int count, int flags) { swrap_load_lib_function(SWRAP_LIBC, eventfd); return swrap.fns.libc_eventfd(count, flags); } #endif DO_NOT_SANITIZE_ADDRESS_ATTRIBUTE static int libc_vfcntl(int fd, int cmd, va_list ap) { long int args[4]; int rc; int i; swrap_load_lib_function(SWRAP_LIBC, fcntl); for (i = 0; i < 4; i++) { args[i] = va_arg(ap, long int); } rc = swrap.fns.libc_fcntl(fd, cmd, args[0], args[1], args[2], args[3]); return rc; } static int libc_getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, getpeername); return swrap.fns.libc_getpeername(sockfd, addr, addrlen); } static int libc_getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, getsockname); return swrap.fns.libc_getsockname(sockfd, addr, addrlen); } static int libc_getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, getsockopt); return swrap.fns.libc_getsockopt(sockfd, level, optname, optval, optlen); } DO_NOT_SANITIZE_ADDRESS_ATTRIBUTE static int libc_vioctl(int d, unsigned long int request, va_list ap) { long int args[4]; int rc; int i; swrap_load_lib_function(SWRAP_LIBC, ioctl); for (i = 0; i < 4; i++) { args[i] = va_arg(ap, long int); } rc = swrap.fns.libc_ioctl(d, request, args[0], args[1], args[2], args[3]); return rc; } static int libc_listen(int sockfd, int backlog) { swrap_load_lib_function(SWRAP_LIBSOCKET, listen); return swrap.fns.libc_listen(sockfd, backlog); } static FILE *libc_fopen(const char *name, const char *mode) { swrap_load_lib_function(SWRAP_LIBC, fopen); return swrap.fns.libc_fopen(name, mode); } static int libc_vopen(const char *pathname, int flags, va_list ap) { long int mode = 0; int fd; swrap_load_lib_function(SWRAP_LIBC, open); mode = va_arg(ap, long int); fd = swrap.fns.libc_open(pathname, flags, (mode_t)mode); return fd; } static int libc_open(const char *pathname, int flags, ...) { va_list ap; int fd; va_start(ap, flags); fd = libc_vopen(pathname, flags, ap); va_end(ap); return fd; } static int libc_pipe(int pipefd[2]) { swrap_load_lib_function(SWRAP_LIBSOCKET, pipe); return swrap.fns.libc_pipe(pipefd); } static int libc_read(int fd, void *buf, size_t count) { swrap_load_lib_function(SWRAP_LIBC, read); return swrap.fns.libc_read(fd, buf, count); } static ssize_t libc_readv(int fd, const struct iovec *iov, int iovcnt) { swrap_load_lib_function(SWRAP_LIBSOCKET, readv); return swrap.fns.libc_readv(fd, iov, iovcnt); } static int libc_recv(int sockfd, void *buf, size_t len, int flags) { swrap_load_lib_function(SWRAP_LIBSOCKET, recv); return swrap.fns.libc_recv(sockfd, buf, len, flags); } static int libc_recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, recvfrom); return swrap.fns.libc_recvfrom(sockfd, buf, len, flags, src_addr, addrlen); } static int libc_recvmsg(int sockfd, struct msghdr *msg, int flags) { swrap_load_lib_function(SWRAP_LIBSOCKET, recvmsg); return swrap.fns.libc_recvmsg(sockfd, msg, flags); } static int libc_send(int sockfd, const void *buf, size_t len, int flags) { swrap_load_lib_function(SWRAP_LIBSOCKET, send); return swrap.fns.libc_send(sockfd, buf, len, flags); } static int libc_sendmsg(int sockfd, const struct msghdr *msg, int flags) { swrap_load_lib_function(SWRAP_LIBSOCKET, sendmsg); return swrap.fns.libc_sendmsg(sockfd, msg, flags); } static int libc_sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dst_addr, socklen_t addrlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, sendto); return swrap.fns.libc_sendto(sockfd, buf, len, flags, dst_addr, addrlen); } static int libc_setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen) { swrap_load_lib_function(SWRAP_LIBSOCKET, setsockopt); return swrap.fns.libc_setsockopt(sockfd, level, optname, optval, optlen); } #ifdef HAVE_SIGNALFD static int libc_signalfd(int fd, const sigset_t *mask, int flags) { swrap_load_lib_function(SWRAP_LIBSOCKET, signalfd); return swrap.fns.libc_signalfd(fd, mask, flags); } #endif static int libc_socket(int domain, int type, int protocol) { swrap_load_lib_function(SWRAP_LIBSOCKET, socket); return swrap.fns.libc_socket(domain, type, protocol); } static int libc_socketpair(int domain, int type, int protocol, int sv[2]) { swrap_load_lib_function(SWRAP_LIBSOCKET, socketpair); return swrap.fns.libc_socketpair(domain, type, protocol, sv); } #ifdef HAVE_TIMERFD_CREATE static int libc_timerfd_create(int clockid, int flags) { swrap_load_lib_function(SWRAP_LIBC, timerfd_create); return swrap.fns.libc_timerfd_create(clockid, flags); } #endif static ssize_t libc_write(int fd, const void *buf, size_t count) { swrap_load_lib_function(SWRAP_LIBC, write); return swrap.fns.libc_write(fd, buf, count); } static ssize_t libc_writev(int fd, const struct iovec *iov, int iovcnt) { swrap_load_lib_function(SWRAP_LIBSOCKET, writev); return swrap.fns.libc_writev(fd, iov, iovcnt); } /********************************************************* * SWRAP HELPER FUNCTIONS *********************************************************/ #ifdef HAVE_IPV6 /* * FD00::5357:5FXX */ static const struct in6_addr *swrap_ipv6(void) { static struct in6_addr v; static int initialized; int ret; if (initialized) { return &v; } initialized = 1; ret = inet_pton(AF_INET6, "FD00::5357:5F00", &v); if (ret <= 0) { abort(); } return &v; } #endif static void set_port(int family, int prt, struct swrap_address *addr) { switch (family) { case AF_INET: addr->sa.in.sin_port = htons(prt); break; #ifdef HAVE_IPV6 case AF_INET6: addr->sa.in6.sin6_port = htons(prt); break; #endif } } static size_t socket_length(int family) { switch (family) { case AF_INET: return sizeof(struct sockaddr_in); #ifdef HAVE_IPV6 case AF_INET6: return sizeof(struct sockaddr_in6); #endif } return 0; } static const char *socket_wrapper_dir(void) { const char *s = getenv("SOCKET_WRAPPER_DIR"); if (s == NULL) { return NULL; } /* TODO use realpath(3) here, when we add support for threads */ if (strncmp(s, "./", 2) == 0) { s += 2; } SWRAP_LOG(SWRAP_LOG_TRACE, "socket_wrapper_dir: %s", s); return s; } static unsigned int socket_wrapper_mtu(void) { static unsigned int max_mtu = 0; unsigned int tmp; const char *s; char *endp; if (max_mtu != 0) { return max_mtu; } max_mtu = SOCKET_WRAPPER_MTU_DEFAULT; s = getenv("SOCKET_WRAPPER_MTU"); if (s == NULL) { goto done; } tmp = strtol(s, &endp, 10); if (s == endp) { goto done; } if (tmp < SOCKET_WRAPPER_MTU_MIN || tmp > SOCKET_WRAPPER_MTU_MAX) { goto done; } max_mtu = tmp; done: return max_mtu; } bool socket_wrapper_enabled(void) { const char *s = socket_wrapper_dir(); return s != NULL ? true : false; } static unsigned int socket_wrapper_default_iface(void) { const char *s = getenv("SOCKET_WRAPPER_DEFAULT_IFACE"); if (s) { unsigned int iface; if (sscanf(s, "%u", &iface) == 1) { if (iface >= 1 && iface <= MAX_WRAPPED_INTERFACES) { return iface; } } } return 1;/* 127.0.0.1 */ } static int convert_un_in(const struct sockaddr_un *un, struct sockaddr *in, socklen_t *len) { unsigned int iface; unsigned int prt; const char *p; char type; p = strrchr(un->sun_path, '/'); if (p) p++; else p = un->sun_path; if (sscanf(p, SOCKET_FORMAT, &type, &iface, &prt) != 3) { errno = EINVAL; return -1; } SWRAP_LOG(SWRAP_LOG_TRACE, "type %c iface %u port %u", type, iface, prt); if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) { errno = EINVAL; return -1; } if (prt > 0xFFFF) { errno = EINVAL; return -1; } switch(type) { case SOCKET_TYPE_CHAR_TCP: case SOCKET_TYPE_CHAR_UDP: { struct sockaddr_in *in2 = (struct sockaddr_in *)(void *)in; if ((*len) < sizeof(*in2)) { errno = EINVAL; return -1; } memset(in2, 0, sizeof(*in2)); in2->sin_family = AF_INET; in2->sin_addr.s_addr = htonl((127<<24) | iface); in2->sin_port = htons(prt); *len = sizeof(*in2); break; } #ifdef HAVE_IPV6 case SOCKET_TYPE_CHAR_TCP_V6: case SOCKET_TYPE_CHAR_UDP_V6: { struct sockaddr_in6 *in2 = (struct sockaddr_in6 *)(void *)in; if ((*len) < sizeof(*in2)) { errno = EINVAL; return -1; } memset(in2, 0, sizeof(*in2)); in2->sin6_family = AF_INET6; in2->sin6_addr = *swrap_ipv6(); in2->sin6_addr.s6_addr[15] = iface; in2->sin6_port = htons(prt); *len = sizeof(*in2); break; } #endif default: errno = EINVAL; return -1; } return 0; } static int convert_in_un_remote(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un, int *bcast) { char type = '\0'; unsigned int prt; unsigned int iface; int is_bcast = 0; if (bcast) *bcast = 0; switch (inaddr->sa_family) { case AF_INET: { const struct sockaddr_in *in = (const struct sockaddr_in *)(const void *)inaddr; unsigned int addr = ntohl(in->sin_addr.s_addr); char u_type = '\0'; char b_type = '\0'; char a_type = '\0'; switch (si->type) { case SOCK_STREAM: u_type = SOCKET_TYPE_CHAR_TCP; break; case SOCK_DGRAM: u_type = SOCKET_TYPE_CHAR_UDP; a_type = SOCKET_TYPE_CHAR_UDP; b_type = SOCKET_TYPE_CHAR_UDP; break; default: SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n"); errno = ESOCKTNOSUPPORT; return -1; } prt = ntohs(in->sin_port); if (a_type && addr == 0xFFFFFFFF) { /* 255.255.255.255 only udp */ is_bcast = 2; type = a_type; iface = socket_wrapper_default_iface(); } else if (b_type && addr == 0x7FFFFFFF) { /* 127.255.255.255 only udp */ is_bcast = 1; type = b_type; iface = socket_wrapper_default_iface(); } else if ((addr & 0xFFFFFF00) == 0x7F000000) { /* 127.0.0.X */ is_bcast = 0; type = u_type; iface = (addr & 0x000000FF); } else { errno = ENETUNREACH; return -1; } if (bcast) *bcast = is_bcast; break; } #ifdef HAVE_IPV6 case AF_INET6: { const struct sockaddr_in6 *in = (const struct sockaddr_in6 *)(const void *)inaddr; struct in6_addr cmp1, cmp2; switch (si->type) { case SOCK_STREAM: type = SOCKET_TYPE_CHAR_TCP_V6; break; case SOCK_DGRAM: type = SOCKET_TYPE_CHAR_UDP_V6; break; default: SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n"); errno = ESOCKTNOSUPPORT; return -1; } /* XXX no multicast/broadcast */ prt = ntohs(in->sin6_port); cmp1 = *swrap_ipv6(); cmp2 = in->sin6_addr; cmp2.s6_addr[15] = 0; if (IN6_ARE_ADDR_EQUAL(&cmp1, &cmp2)) { iface = in->sin6_addr.s6_addr[15]; } else { errno = ENETUNREACH; return -1; } break; } #endif default: SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family!\n"); errno = ENETUNREACH; return -1; } if (prt == 0) { SWRAP_LOG(SWRAP_LOG_WARN, "Port not set\n"); errno = EINVAL; return -1; } if (is_bcast) { snprintf(un->sun_path, sizeof(un->sun_path), "%s/EINVAL", socket_wrapper_dir()); SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path); /* the caller need to do more processing */ return 0; } snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, socket_wrapper_dir(), type, iface, prt); SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path); return 0; } static int convert_in_un_alloc(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un, int *bcast) { char type = '\0'; unsigned int prt; unsigned int iface; struct stat st; int is_bcast = 0; if (bcast) *bcast = 0; switch (si->family) { case AF_INET: { const struct sockaddr_in *in = (const struct sockaddr_in *)(const void *)inaddr; unsigned int addr = ntohl(in->sin_addr.s_addr); char u_type = '\0'; char d_type = '\0'; char b_type = '\0'; char a_type = '\0'; prt = ntohs(in->sin_port); switch (si->type) { case SOCK_STREAM: u_type = SOCKET_TYPE_CHAR_TCP; d_type = SOCKET_TYPE_CHAR_TCP; break; case SOCK_DGRAM: u_type = SOCKET_TYPE_CHAR_UDP; d_type = SOCKET_TYPE_CHAR_UDP; a_type = SOCKET_TYPE_CHAR_UDP; b_type = SOCKET_TYPE_CHAR_UDP; break; default: SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n"); errno = ESOCKTNOSUPPORT; return -1; } if (addr == 0) { /* 0.0.0.0 */ is_bcast = 0; type = d_type; iface = socket_wrapper_default_iface(); } else if (a_type && addr == 0xFFFFFFFF) { /* 255.255.255.255 only udp */ is_bcast = 2; type = a_type; iface = socket_wrapper_default_iface(); } else if (b_type && addr == 0x7FFFFFFF) { /* 127.255.255.255 only udp */ is_bcast = 1; type = b_type; iface = socket_wrapper_default_iface(); } else if ((addr & 0xFFFFFF00) == 0x7F000000) { /* 127.0.0.X */ is_bcast = 0; type = u_type; iface = (addr & 0x000000FF); } else { errno = EADDRNOTAVAIL; return -1; } /* Store the bind address for connect() */ if (si->bindname.sa_socklen == 0) { struct sockaddr_in bind_in; socklen_t blen = sizeof(struct sockaddr_in); ZERO_STRUCT(bind_in); bind_in.sin_family = in->sin_family; bind_in.sin_port = in->sin_port; bind_in.sin_addr.s_addr = htonl(0x7F000000 | iface); si->bindname.sa_socklen = blen; memcpy(&si->bindname.sa.in, &bind_in, blen); } break; } #ifdef HAVE_IPV6 case AF_INET6: { const struct sockaddr_in6 *in = (const struct sockaddr_in6 *)(const void *)inaddr; struct in6_addr cmp1, cmp2; switch (si->type) { case SOCK_STREAM: type = SOCKET_TYPE_CHAR_TCP_V6; break; case SOCK_DGRAM: type = SOCKET_TYPE_CHAR_UDP_V6; break; default: SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n"); errno = ESOCKTNOSUPPORT; return -1; } /* XXX no multicast/broadcast */ prt = ntohs(in->sin6_port); cmp1 = *swrap_ipv6(); cmp2 = in->sin6_addr; cmp2.s6_addr[15] = 0; if (IN6_IS_ADDR_UNSPECIFIED(&in->sin6_addr)) { iface = socket_wrapper_default_iface(); } else if (IN6_ARE_ADDR_EQUAL(&cmp1, &cmp2)) { iface = in->sin6_addr.s6_addr[15]; } else { errno = EADDRNOTAVAIL; return -1; } /* Store the bind address for connect() */ if (si->bindname.sa_socklen == 0) { struct sockaddr_in6 bind_in; socklen_t blen = sizeof(struct sockaddr_in6); ZERO_STRUCT(bind_in); bind_in.sin6_family = in->sin6_family; bind_in.sin6_port = in->sin6_port; bind_in.sin6_addr = *swrap_ipv6(); bind_in.sin6_addr.s6_addr[15] = iface; memcpy(&si->bindname.sa.in6, &bind_in, blen); si->bindname.sa_socklen = blen; } break; } #endif default: SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family\n"); errno = EADDRNOTAVAIL; return -1; } if (bcast) *bcast = is_bcast; if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) { errno = EINVAL; return -1; } if (prt == 0) { /* handle auto-allocation of ephemeral ports */ for (prt = 5001; prt < 10000; prt++) { snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, socket_wrapper_dir(), type, iface, prt); if (stat(un->sun_path, &st) == 0) continue; set_port(si->family, prt, &si->myname); set_port(si->family, prt, &si->bindname); break; } if (prt == 10000) { errno = ENFILE; return -1; } } snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, socket_wrapper_dir(), type, iface, prt); SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path); return 0; } static struct socket_info *find_socket_info(int fd) { struct socket_info *i; for (i = sockets; i; i = i->next) { struct socket_info_fd *f; for (f = i->fds; f; f = f->next) { if (f->fd == fd) { return i; } } } return NULL; } #if 0 /* FIXME */ static bool check_addr_port_in_use(const struct sockaddr *sa, socklen_t len) { struct socket_info *s; /* first catch invalid input */ switch (sa->sa_family) { case AF_INET: if (len < sizeof(struct sockaddr_in)) { return false; } break; #if HAVE_IPV6 case AF_INET6: if (len < sizeof(struct sockaddr_in6)) { return false; } break; #endif default: return false; break; } for (s = sockets; s != NULL; s = s->next) { if (s->myname == NULL) { continue; } if (s->myname->sa_family != sa->sa_family) { continue; } switch (s->myname->sa_family) { case AF_INET: { struct sockaddr_in *sin1, *sin2; sin1 = (struct sockaddr_in *)s->myname; sin2 = (struct sockaddr_in *)sa; if (sin1->sin_addr.s_addr == htonl(INADDR_ANY)) { continue; } if (sin1->sin_port != sin2->sin_port) { continue; } if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) { continue; } /* found */ return true; break; } #if HAVE_IPV6 case AF_INET6: { struct sockaddr_in6 *sin1, *sin2; sin1 = (struct sockaddr_in6 *)s->myname; sin2 = (struct sockaddr_in6 *)sa; if (sin1->sin6_port != sin2->sin6_port) { continue; } if (!IN6_ARE_ADDR_EQUAL(&sin1->sin6_addr, &sin2->sin6_addr)) { continue; } /* found */ return true; break; } #endif default: continue; break; } } return false; } #endif static void swrap_remove_stale(int fd) { struct socket_info *si = find_socket_info(fd); struct socket_info_fd *fi; if (si != NULL) { for (fi = si->fds; fi; fi = fi->next) { if (fi->fd == fd) { SWRAP_LOG(SWRAP_LOG_TRACE, "remove stale wrapper for %d", fd); SWRAP_DLIST_REMOVE(si->fds, fi); free(fi); break; } } if (si->fds == NULL) { SWRAP_DLIST_REMOVE(sockets, si); if (si->un_addr.sun_path[0] != '\0') { unlink(si->un_addr.sun_path); } free(si); } } } static int sockaddr_convert_to_un(struct socket_info *si, const struct sockaddr *in_addr, socklen_t in_len, struct sockaddr_un *out_addr, int alloc_sock, int *bcast) { struct sockaddr *out = (struct sockaddr *)(void *)out_addr; (void) in_len; /* unused */ if (out_addr == NULL) { return 0; } out->sa_family = AF_UNIX; #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN out->sa_len = sizeof(*out_addr); #endif switch (in_addr->sa_family) { case AF_UNSPEC: { const struct sockaddr_in *sin; if (si->family != AF_INET) { break; } if (in_len < sizeof(struct sockaddr_in)) { break; } sin = (const struct sockaddr_in *)(const void *)in_addr; if(sin->sin_addr.s_addr != htonl(INADDR_ANY)) { break; } /* * Note: in the special case of AF_UNSPEC and INADDR_ANY, * AF_UNSPEC is mapped to AF_INET and must be treated here. */ /* FALL THROUGH */ } case AF_INET: #ifdef HAVE_IPV6 case AF_INET6: #endif switch (si->type) { case SOCK_STREAM: case SOCK_DGRAM: break; default: SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n"); errno = ESOCKTNOSUPPORT; return -1; } if (alloc_sock) { return convert_in_un_alloc(si, in_addr, out_addr, bcast); } else { return convert_in_un_remote(si, in_addr, out_addr, bcast); } default: break; } errno = EAFNOSUPPORT; SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family\n"); return -1; } static int sockaddr_convert_from_un(const struct socket_info *si, const struct sockaddr_un *in_addr, socklen_t un_addrlen, int family, struct sockaddr *out_addr, socklen_t *out_addrlen) { int ret; if (out_addr == NULL || out_addrlen == NULL) return 0; if (un_addrlen == 0) { *out_addrlen = 0; return 0; } switch (family) { case AF_INET: #ifdef HAVE_IPV6 case AF_INET6: #endif switch (si->type) { case SOCK_STREAM: case SOCK_DGRAM: break; default: SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n"); errno = ESOCKTNOSUPPORT; return -1; } ret = convert_un_in(in_addr, out_addr, out_addrlen); #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN out_addr->sa_len = *out_addrlen; #endif return ret; default: break; } SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family\n"); errno = EAFNOSUPPORT; return -1; } enum swrap_packet_type { SWRAP_CONNECT_SEND, SWRAP_CONNECT_UNREACH, SWRAP_CONNECT_RECV, SWRAP_CONNECT_ACK, SWRAP_ACCEPT_SEND, SWRAP_ACCEPT_RECV, SWRAP_ACCEPT_ACK, SWRAP_RECVFROM, SWRAP_SENDTO, SWRAP_SENDTO_UNREACH, SWRAP_PENDING_RST, SWRAP_RECV, SWRAP_RECV_RST, SWRAP_SEND, SWRAP_SEND_RST, SWRAP_CLOSE_SEND, SWRAP_CLOSE_RECV, SWRAP_CLOSE_ACK, }; struct swrap_file_hdr { uint32_t magic; uint16_t version_major; uint16_t version_minor; int32_t timezone; uint32_t sigfigs; uint32_t frame_max_len; #define SWRAP_FRAME_LENGTH_MAX 0xFFFF uint32_t link_type; }; #define SWRAP_FILE_HDR_SIZE 24 struct swrap_packet_frame { uint32_t seconds; uint32_t micro_seconds; uint32_t recorded_length; uint32_t full_length; }; #define SWRAP_PACKET_FRAME_SIZE 16 union swrap_packet_ip { struct { uint8_t ver_hdrlen; uint8_t tos; uint16_t packet_length; uint16_t identification; uint8_t flags; uint8_t fragment; uint8_t ttl; uint8_t protocol; uint16_t hdr_checksum; uint32_t src_addr; uint32_t dest_addr; } v4; #define SWRAP_PACKET_IP_V4_SIZE 20 struct { uint8_t ver_prio; uint8_t flow_label_high; uint16_t flow_label_low; uint16_t payload_length; uint8_t next_header; uint8_t hop_limit; uint8_t src_addr[16]; uint8_t dest_addr[16]; } v6; #define SWRAP_PACKET_IP_V6_SIZE 40 }; #define SWRAP_PACKET_IP_SIZE 40 union swrap_packet_payload { struct { uint16_t source_port; uint16_t dest_port; uint32_t seq_num; uint32_t ack_num; uint8_t hdr_length; uint8_t control; uint16_t window; uint16_t checksum; uint16_t urg; } tcp; #define SWRAP_PACKET_PAYLOAD_TCP_SIZE 20 struct { uint16_t source_port; uint16_t dest_port; uint16_t length; uint16_t checksum; } udp; #define SWRAP_PACKET_PAYLOAD_UDP_SIZE 8 struct { uint8_t type; uint8_t code; uint16_t checksum; uint32_t unused; } icmp4; #define SWRAP_PACKET_PAYLOAD_ICMP4_SIZE 8 struct { uint8_t type; uint8_t code; uint16_t checksum; uint32_t unused; } icmp6; #define SWRAP_PACKET_PAYLOAD_ICMP6_SIZE 8 }; #define SWRAP_PACKET_PAYLOAD_SIZE 20 #define SWRAP_PACKET_MIN_ALLOC \ (SWRAP_PACKET_FRAME_SIZE + \ SWRAP_PACKET_IP_SIZE + \ SWRAP_PACKET_PAYLOAD_SIZE) static const char *swrap_pcap_init_file(void) { static int initialized = 0; static const char *s = NULL; static const struct swrap_file_hdr h; static const struct swrap_packet_frame f; static const union swrap_packet_ip i; static const union swrap_packet_payload p; if (initialized == 1) { return s; } initialized = 1; /* * TODO: don't use the structs use plain buffer offsets * and PUSH_U8(), PUSH_U16() and PUSH_U32() * * for now make sure we disable PCAP support * if the struct has alignment! */ if (sizeof(h) != SWRAP_FILE_HDR_SIZE) { return NULL; } if (sizeof(f) != SWRAP_PACKET_FRAME_SIZE) { return NULL; } if (sizeof(i) != SWRAP_PACKET_IP_SIZE) { return NULL; } if (sizeof(i.v4) != SWRAP_PACKET_IP_V4_SIZE) { return NULL; } if (sizeof(i.v6) != SWRAP_PACKET_IP_V6_SIZE) { return NULL; } if (sizeof(p) != SWRAP_PACKET_PAYLOAD_SIZE) { return NULL; } if (sizeof(p.tcp) != SWRAP_PACKET_PAYLOAD_TCP_SIZE) { return NULL; } if (sizeof(p.udp) != SWRAP_PACKET_PAYLOAD_UDP_SIZE) { return NULL; } if (sizeof(p.icmp4) != SWRAP_PACKET_PAYLOAD_ICMP4_SIZE) { return NULL; } if (sizeof(p.icmp6) != SWRAP_PACKET_PAYLOAD_ICMP6_SIZE) { return NULL; } s = getenv("SOCKET_WRAPPER_PCAP_FILE"); if (s == NULL) { return NULL; } if (strncmp(s, "./", 2) == 0) { s += 2; } return s; } static uint8_t *swrap_pcap_packet_init(struct timeval *tval, const struct sockaddr *src, const struct sockaddr *dest, int socket_type, const uint8_t *payload, size_t payload_len, unsigned long tcp_seqno, unsigned long tcp_ack, unsigned char tcp_ctl, int unreachable, size_t *_packet_len) { uint8_t *base; uint8_t *buf; struct swrap_packet_frame *frame; union swrap_packet_ip *ip; union swrap_packet_payload *pay; size_t packet_len; size_t alloc_len; size_t nonwire_len = sizeof(*frame); size_t wire_hdr_len = 0; size_t wire_len = 0; size_t ip_hdr_len = 0; size_t icmp_hdr_len = 0; size_t icmp_truncate_len = 0; uint8_t protocol = 0, icmp_protocol = 0; const struct sockaddr_in *src_in = NULL; const struct sockaddr_in *dest_in = NULL; #ifdef HAVE_IPV6 const struct sockaddr_in6 *src_in6 = NULL; const struct sockaddr_in6 *dest_in6 = NULL; #endif uint16_t src_port; uint16_t dest_port; switch (src->sa_family) { case AF_INET: src_in = (const struct sockaddr_in *)(const void *)src; dest_in = (const struct sockaddr_in *)(const void *)dest; src_port = src_in->sin_port; dest_port = dest_in->sin_port; ip_hdr_len = sizeof(ip->v4); break; #ifdef HAVE_IPV6 case AF_INET6: src_in6 = (const struct sockaddr_in6 *)(const void *)src; dest_in6 = (const struct sockaddr_in6 *)(const void *)dest; src_port = src_in6->sin6_port; dest_port = dest_in6->sin6_port; ip_hdr_len = sizeof(ip->v6); break; #endif default: return NULL; } switch (socket_type) { case SOCK_STREAM: protocol = 0x06; /* TCP */ wire_hdr_len = ip_hdr_len + sizeof(pay->tcp); wire_len = wire_hdr_len + payload_len; break; case SOCK_DGRAM: protocol = 0x11; /* UDP */ wire_hdr_len = ip_hdr_len + sizeof(pay->udp); wire_len = wire_hdr_len + payload_len; break; default: return NULL; } if (unreachable) { icmp_protocol = protocol; switch (src->sa_family) { case AF_INET: protocol = 0x01; /* ICMPv4 */ icmp_hdr_len = ip_hdr_len + sizeof(pay->icmp4); break; #ifdef HAVE_IPV6 case AF_INET6: protocol = 0x3A; /* ICMPv6 */ icmp_hdr_len = ip_hdr_len + sizeof(pay->icmp6); break; #endif } if (wire_len > 64 ) { icmp_truncate_len = wire_len - 64; } wire_hdr_len += icmp_hdr_len; wire_len += icmp_hdr_len; } packet_len = nonwire_len + wire_len; alloc_len = packet_len; if (alloc_len < SWRAP_PACKET_MIN_ALLOC) { alloc_len = SWRAP_PACKET_MIN_ALLOC; } base = (uint8_t *)calloc(1, alloc_len); if (base == NULL) { return NULL; } buf = base; frame = (struct swrap_packet_frame *)(void *)buf; frame->seconds = tval->tv_sec; frame->micro_seconds = tval->tv_usec; frame->recorded_length = wire_len - icmp_truncate_len; frame->full_length = wire_len - icmp_truncate_len; buf += SWRAP_PACKET_FRAME_SIZE; ip = (union swrap_packet_ip *)(void *)buf; switch (src->sa_family) { case AF_INET: ip->v4.ver_hdrlen = 0x45; /* version 4 and 5 * 32 bit words */ ip->v4.tos = 0x00; ip->v4.packet_length = htons(wire_len - icmp_truncate_len); ip->v4.identification = htons(0xFFFF); ip->v4.flags = 0x40; /* BIT 1 set - means don't fragment */ ip->v4.fragment = htons(0x0000); ip->v4.ttl = 0xFF; ip->v4.protocol = protocol; ip->v4.hdr_checksum = htons(0x0000); ip->v4.src_addr = src_in->sin_addr.s_addr; ip->v4.dest_addr = dest_in->sin_addr.s_addr; buf += SWRAP_PACKET_IP_V4_SIZE; break; #ifdef HAVE_IPV6 case AF_INET6: ip->v6.ver_prio = 0x60; /* version 4 and 5 * 32 bit words */ ip->v6.flow_label_high = 0x00; ip->v6.flow_label_low = 0x0000; ip->v6.payload_length = htons(wire_len - icmp_truncate_len); /* TODO */ ip->v6.next_header = protocol; memcpy(ip->v6.src_addr, src_in6->sin6_addr.s6_addr, 16); memcpy(ip->v6.dest_addr, dest_in6->sin6_addr.s6_addr, 16); buf += SWRAP_PACKET_IP_V6_SIZE; break; #endif } if (unreachable) { pay = (union swrap_packet_payload *)(void *)buf; switch (src->sa_family) { case AF_INET: pay->icmp4.type = 0x03; /* destination unreachable */ pay->icmp4.code = 0x01; /* host unreachable */ pay->icmp4.checksum = htons(0x0000); pay->icmp4.unused = htonl(0x00000000); buf += SWRAP_PACKET_PAYLOAD_ICMP4_SIZE; /* set the ip header in the ICMP payload */ ip = (union swrap_packet_ip *)(void *)buf; ip->v4.ver_hdrlen = 0x45; /* version 4 and 5 * 32 bit words */ ip->v4.tos = 0x00; ip->v4.packet_length = htons(wire_len - icmp_hdr_len); ip->v4.identification = htons(0xFFFF); ip->v4.flags = 0x40; /* BIT 1 set - means don't fragment */ ip->v4.fragment = htons(0x0000); ip->v4.ttl = 0xFF; ip->v4.protocol = icmp_protocol; ip->v4.hdr_checksum = htons(0x0000); ip->v4.src_addr = dest_in->sin_addr.s_addr; ip->v4.dest_addr = src_in->sin_addr.s_addr; buf += SWRAP_PACKET_IP_V4_SIZE; src_port = dest_in->sin_port; dest_port = src_in->sin_port; break; #ifdef HAVE_IPV6 case AF_INET6: pay->icmp6.type = 0x01; /* destination unreachable */ pay->icmp6.code = 0x03; /* address unreachable */ pay->icmp6.checksum = htons(0x0000); pay->icmp6.unused = htonl(0x00000000); buf += SWRAP_PACKET_PAYLOAD_ICMP6_SIZE; /* set the ip header in the ICMP payload */ ip = (union swrap_packet_ip *)(void *)buf; ip->v6.ver_prio = 0x60; /* version 4 and 5 * 32 bit words */ ip->v6.flow_label_high = 0x00; ip->v6.flow_label_low = 0x0000; ip->v6.payload_length = htons(wire_len - icmp_truncate_len); /* TODO */ ip->v6.next_header = protocol; memcpy(ip->v6.src_addr, dest_in6->sin6_addr.s6_addr, 16); memcpy(ip->v6.dest_addr, src_in6->sin6_addr.s6_addr, 16); buf += SWRAP_PACKET_IP_V6_SIZE; src_port = dest_in6->sin6_port; dest_port = src_in6->sin6_port; break; #endif } } pay = (union swrap_packet_payload *)(void *)buf; switch (socket_type) { case SOCK_STREAM: pay->tcp.source_port = src_port; pay->tcp.dest_port = dest_port; pay->tcp.seq_num = htonl(tcp_seqno); pay->tcp.ack_num = htonl(tcp_ack); pay->tcp.hdr_length = 0x50; /* 5 * 32 bit words */ pay->tcp.control = tcp_ctl; pay->tcp.window = htons(0x7FFF); pay->tcp.checksum = htons(0x0000); pay->tcp.urg = htons(0x0000); buf += SWRAP_PACKET_PAYLOAD_TCP_SIZE; break; case SOCK_DGRAM: pay->udp.source_port = src_port; pay->udp.dest_port = dest_port; pay->udp.length = htons(8 + payload_len); pay->udp.checksum = htons(0x0000); buf += SWRAP_PACKET_PAYLOAD_UDP_SIZE; break; } if (payload && payload_len > 0) { memcpy(buf, payload, payload_len); } *_packet_len = packet_len - icmp_truncate_len; return base; } static int swrap_pcap_get_fd(const char *fname) { static int fd = -1; if (fd != -1) return fd; fd = libc_open(fname, O_WRONLY|O_CREAT|O_EXCL|O_APPEND, 0644); if (fd != -1) { struct swrap_file_hdr file_hdr; file_hdr.magic = 0xA1B2C3D4; file_hdr.version_major = 0x0002; file_hdr.version_minor = 0x0004; file_hdr.timezone = 0x00000000; file_hdr.sigfigs = 0x00000000; file_hdr.frame_max_len = SWRAP_FRAME_LENGTH_MAX; file_hdr.link_type = 0x0065; /* 101 RAW IP */ if (write(fd, &file_hdr, sizeof(file_hdr)) != sizeof(file_hdr)) { close(fd); fd = -1; } return fd; } fd = libc_open(fname, O_WRONLY|O_APPEND, 0644); return fd; } static uint8_t *swrap_pcap_marshall_packet(struct socket_info *si, const struct sockaddr *addr, enum swrap_packet_type type, const void *buf, size_t len, size_t *packet_len) { const struct sockaddr *src_addr; const struct sockaddr *dest_addr; unsigned long tcp_seqno = 0; unsigned long tcp_ack = 0; unsigned char tcp_ctl = 0; int unreachable = 0; struct timeval tv; switch (si->family) { case AF_INET: break; #ifdef HAVE_IPV6 case AF_INET6: break; #endif default: return NULL; } switch (type) { case SWRAP_CONNECT_SEND: if (si->type != SOCK_STREAM) return NULL; src_addr = &si->myname.sa.s; dest_addr = addr; tcp_seqno = si->io.pck_snd; tcp_ack = si->io.pck_rcv; tcp_ctl = 0x02; /* SYN */ si->io.pck_snd += 1; break; case SWRAP_CONNECT_RECV: if (si->type != SOCK_STREAM) return NULL; dest_addr = &si->myname.sa.s; src_addr = addr; tcp_seqno = si->io.pck_rcv; tcp_ack = si->io.pck_snd; tcp_ctl = 0x12; /** SYN,ACK */ si->io.pck_rcv += 1; break; case SWRAP_CONNECT_UNREACH: if (si->type != SOCK_STREAM) return NULL; dest_addr = &si->myname.sa.s; src_addr = addr; /* Unreachable: resend the data of SWRAP_CONNECT_SEND */ tcp_seqno = si->io.pck_snd - 1; tcp_ack = si->io.pck_rcv; tcp_ctl = 0x02; /* SYN */ unreachable = 1; break; case SWRAP_CONNECT_ACK: if (si->type != SOCK_STREAM) return NULL; src_addr = &si->myname.sa.s; dest_addr = addr; tcp_seqno = si->io.pck_snd; tcp_ack = si->io.pck_rcv; tcp_ctl = 0x10; /* ACK */ break; case SWRAP_ACCEPT_SEND: if (si->type != SOCK_STREAM) return NULL; dest_addr = &si->myname.sa.s; src_addr = addr; tcp_seqno = si->io.pck_rcv; tcp_ack = si->io.pck_snd; tcp_ctl = 0x02; /* SYN */ si->io.pck_rcv += 1; break; case SWRAP_ACCEPT_RECV: if (si->type != SOCK_STREAM) return NULL; src_addr = &si->myname.sa.s; dest_addr = addr; tcp_seqno = si->io.pck_snd; tcp_ack = si->io.pck_rcv; tcp_ctl = 0x12; /* SYN,ACK */ si->io.pck_snd += 1; break; case SWRAP_ACCEPT_ACK: if (si->type != SOCK_STREAM) return NULL; dest_addr = &si->myname.sa.s; src_addr = addr; tcp_seqno = si->io.pck_rcv; tcp_ack = si->io.pck_snd; tcp_ctl = 0x10; /* ACK */ break; case SWRAP_SEND: src_addr = &si->myname.sa.s; dest_addr = &si->peername.sa.s; tcp_seqno = si->io.pck_snd; tcp_ack = si->io.pck_rcv; tcp_ctl = 0x18; /* PSH,ACK */ si->io.pck_snd += len; break; case SWRAP_SEND_RST: dest_addr = &si->myname.sa.s; src_addr = &si->peername.sa.s; if (si->type == SOCK_DGRAM) { return swrap_pcap_marshall_packet(si, &si->peername.sa.s, SWRAP_SENDTO_UNREACH, buf, len, packet_len); } tcp_seqno = si->io.pck_rcv; tcp_ack = si->io.pck_snd; tcp_ctl = 0x14; /** RST,ACK */ break; case SWRAP_PENDING_RST: dest_addr = &si->myname.sa.s; src_addr = &si->peername.sa.s; if (si->type == SOCK_DGRAM) { return NULL; } tcp_seqno = si->io.pck_rcv; tcp_ack = si->io.pck_snd; tcp_ctl = 0x14; /* RST,ACK */ break; case SWRAP_RECV: dest_addr = &si->myname.sa.s; src_addr = &si->peername.sa.s; tcp_seqno = si->io.pck_rcv; tcp_ack = si->io.pck_snd; tcp_ctl = 0x18; /* PSH,ACK */ si->io.pck_rcv += len; break; case SWRAP_RECV_RST: dest_addr = &si->myname.sa.s; src_addr = &si->peername.sa.s; if (si->type == SOCK_DGRAM) { return NULL; } tcp_seqno = si->io.pck_rcv; tcp_ack = si->io.pck_snd; tcp_ctl = 0x14; /* RST,ACK */ break; case SWRAP_SENDTO: src_addr = &si->myname.sa.s; dest_addr = addr; si->io.pck_snd += len; break; case SWRAP_SENDTO_UNREACH: dest_addr = &si->myname.sa.s; src_addr = addr; unreachable = 1; break; case SWRAP_RECVFROM: dest_addr = &si->myname.sa.s; src_addr = addr; si->io.pck_rcv += len; break; case SWRAP_CLOSE_SEND: if (si->type != SOCK_STREAM) return NULL; src_addr = &si->myname.sa.s; dest_addr = &si->peername.sa.s; tcp_seqno = si->io.pck_snd; tcp_ack = si->io.pck_rcv; tcp_ctl = 0x11; /* FIN, ACK */ si->io.pck_snd += 1; break; case SWRAP_CLOSE_RECV: if (si->type != SOCK_STREAM) return NULL; dest_addr = &si->myname.sa.s; src_addr = &si->peername.sa.s; tcp_seqno = si->io.pck_rcv; tcp_ack = si->io.pck_snd; tcp_ctl = 0x11; /* FIN,ACK */ si->io.pck_rcv += 1; break; case SWRAP_CLOSE_ACK: if (si->type != SOCK_STREAM) return NULL; src_addr = &si->myname.sa.s; dest_addr = &si->peername.sa.s; tcp_seqno = si->io.pck_snd; tcp_ack = si->io.pck_rcv; tcp_ctl = 0x10; /* ACK */ break; default: return NULL; } swrapGetTimeOfDay(&tv); return swrap_pcap_packet_init(&tv, src_addr, dest_addr, si->type, (const uint8_t *)buf, len, tcp_seqno, tcp_ack, tcp_ctl, unreachable, packet_len); } static void swrap_pcap_dump_packet(struct socket_info *si, const struct sockaddr *addr, enum swrap_packet_type type, const void *buf, size_t len) { const char *file_name; uint8_t *packet; size_t packet_len = 0; int fd; file_name = swrap_pcap_init_file(); if (!file_name) { return; } packet = swrap_pcap_marshall_packet(si, addr, type, buf, len, &packet_len); if (packet == NULL) { return; } fd = swrap_pcap_get_fd(file_name); if (fd != -1) { if (write(fd, packet, packet_len) != (ssize_t)packet_len) { free(packet); return; } } free(packet); } /**************************************************************************** * SIGNALFD ***************************************************************************/ #ifdef HAVE_SIGNALFD static int swrap_signalfd(int fd, const sigset_t *mask, int flags) { int rc; rc = libc_signalfd(fd, mask, flags); if (rc != -1) { swrap_remove_stale(fd); } return rc; } int signalfd(int fd, const sigset_t *mask, int flags) { return swrap_signalfd(fd, mask, flags); } #endif /**************************************************************************** * SOCKET ***************************************************************************/ static int swrap_socket(int family, int type, int protocol) { struct socket_info *si; struct socket_info_fd *fi; int fd; int real_type = type; /* * Remove possible addition flags passed to socket() so * do not fail checking the type. * See https://lwn.net/Articles/281965/ */ #ifdef SOCK_CLOEXEC real_type &= ~SOCK_CLOEXEC; #endif #ifdef SOCK_NONBLOCK real_type &= ~SOCK_NONBLOCK; #endif if (!socket_wrapper_enabled()) { return libc_socket(family, type, protocol); } switch (family) { case AF_INET: #ifdef HAVE_IPV6 case AF_INET6: #endif break; #ifdef AF_NETLINK case AF_NETLINK: #endif /* AF_NETLINK */ #ifdef AF_PACKET case AF_PACKET: #endif /* AF_PACKET */ case AF_UNIX: return libc_socket(family, type, protocol); default: errno = EAFNOSUPPORT; return -1; } switch (real_type) { case SOCK_STREAM: break; case SOCK_DGRAM: break; default: errno = EPROTONOSUPPORT; return -1; } switch (protocol) { case 0: break; case 6: if (real_type == SOCK_STREAM) { break; } /*fall through*/ case 17: if (real_type == SOCK_DGRAM) { break; } /*fall through*/ default: errno = EPROTONOSUPPORT; return -1; } /* * We must call libc_socket with type, from the caller, not the version * we removed SOCK_CLOEXEC and SOCK_NONBLOCK from */ fd = libc_socket(AF_UNIX, type, 0); if (fd == -1) { return -1; } /* Check if we have a stale fd and remove it */ si = find_socket_info(fd); if (si != NULL) { swrap_remove_stale(fd); } si = (struct socket_info *)calloc(1, sizeof(struct socket_info)); if (si == NULL) { errno = ENOMEM; return -1; } si->family = family; /* however, the rest of the socket_wrapper code expects just * the type, not the flags */ si->type = real_type; si->protocol = protocol; /* * Setup myname so getsockname() can succeed to find out the socket * type. */ switch(si->family) { case AF_INET: { struct sockaddr_in sin = { .sin_family = AF_INET, }; si->myname.sa_socklen = sizeof(struct sockaddr_in); memcpy(&si->myname.sa.in, &sin, si->myname.sa_socklen); break; } case AF_INET6: { struct sockaddr_in6 sin6 = { .sin6_family = AF_INET6, }; si->myname.sa_socklen = sizeof(struct sockaddr_in6); memcpy(&si->myname.sa.in6, &sin6, si->myname.sa_socklen); break; } default: free(si); errno = EINVAL; return -1; } fi = (struct socket_info_fd *)calloc(1, sizeof(struct socket_info_fd)); if (fi == NULL) { free(si); errno = ENOMEM; return -1; } fi->fd = fd; SWRAP_DLIST_ADD(si->fds, fi); SWRAP_DLIST_ADD(sockets, si); SWRAP_LOG(SWRAP_LOG_TRACE, "Created %s socket for protocol %s", si->family == AF_INET ? "IPv4" : "IPv6", si->type == SOCK_DGRAM ? "UDP" : "TCP"); return fd; } int socket(int family, int type, int protocol) { return swrap_socket(family, type, protocol); } /**************************************************************************** * SOCKETPAIR ***************************************************************************/ static int swrap_socketpair(int family, int type, int protocol, int sv[2]) { int rc; rc = libc_socketpair(family, type, protocol, sv); if (rc != -1) { swrap_remove_stale(sv[0]); swrap_remove_stale(sv[1]); } return rc; } int socketpair(int family, int type, int protocol, int sv[2]) { return swrap_socketpair(family, type, protocol, sv); } /**************************************************************************** * SOCKETPAIR ***************************************************************************/ #ifdef HAVE_TIMERFD_CREATE static int swrap_timerfd_create(int clockid, int flags) { int fd; fd = libc_timerfd_create(clockid, flags); if (fd != -1) { swrap_remove_stale(fd); } return fd; } int timerfd_create(int clockid, int flags) { return swrap_timerfd_create(clockid, flags); } #endif /**************************************************************************** * PIPE ***************************************************************************/ static int swrap_pipe(int pipefd[2]) { int rc; rc = libc_pipe(pipefd); if (rc != -1) { swrap_remove_stale(pipefd[0]); swrap_remove_stale(pipefd[1]); } return rc; } int pipe(int pipefd[2]) { return swrap_pipe(pipefd); } /**************************************************************************** * ACCEPT ***************************************************************************/ static int swrap_accept(int s, struct sockaddr *addr, socklen_t *addrlen, int flags) { struct socket_info *parent_si, *child_si; struct socket_info_fd *child_fi; int fd; struct swrap_address un_addr = { .sa_socklen = sizeof(struct sockaddr_un), }; struct swrap_address un_my_addr = { .sa_socklen = sizeof(struct sockaddr_un), }; struct swrap_address in_addr = { .sa_socklen = sizeof(struct sockaddr_storage), }; struct swrap_address in_my_addr = { .sa_socklen = sizeof(struct sockaddr_storage), }; int ret; parent_si = find_socket_info(s); if (!parent_si) { #ifdef HAVE_ACCEPT4 return libc_accept4(s, addr, addrlen, flags); #else return libc_accept(s, addr, addrlen); #endif } /* * assume out sockaddr have the same size as the in parent * socket family */ in_addr.sa_socklen = socket_length(parent_si->family); if (in_addr.sa_socklen <= 0) { errno = EINVAL; return -1; } #ifdef HAVE_ACCEPT4 ret = libc_accept4(s, &un_addr.sa.s, &un_addr.sa_socklen, flags); #else ret = libc_accept(s, &un_addr.sa.s, &un_addr.sa_socklen); #endif if (ret == -1) { if (errno == ENOTSOCK) { /* Remove stale fds */ swrap_remove_stale(s); } return ret; } fd = ret; ret = sockaddr_convert_from_un(parent_si, &un_addr.sa.un, un_addr.sa_socklen, parent_si->family, &in_addr.sa.s, &in_addr.sa_socklen); if (ret == -1) { close(fd); return ret; } child_si = (struct socket_info *)calloc(1, sizeof(struct socket_info)); if (child_si == NULL) { close(fd); errno = ENOMEM; return -1; } child_fi = (struct socket_info_fd *)calloc(1, sizeof(struct socket_info_fd)); if (child_fi == NULL) { free(child_si); close(fd); errno = ENOMEM; return -1; } child_fi->fd = fd; SWRAP_DLIST_ADD(child_si->fds, child_fi); child_si->family = parent_si->family; child_si->type = parent_si->type; child_si->protocol = parent_si->protocol; child_si->bound = 1; child_si->is_server = 1; child_si->connected = 1; child_si->peername = (struct swrap_address) { .sa_socklen = in_addr.sa_socklen, }; memcpy(&child_si->peername.sa.ss, &in_addr.sa.ss, in_addr.sa_socklen); if (addr != NULL && addrlen != NULL) { size_t copy_len = MIN(*addrlen, in_addr.sa_socklen); if (copy_len > 0) { memcpy(addr, &in_addr.sa.ss, copy_len); } *addrlen = in_addr.sa_socklen; } ret = libc_getsockname(fd, &un_my_addr.sa.s, &un_my_addr.sa_socklen); if (ret == -1) { free(child_fi); free(child_si); close(fd); return ret; } ret = sockaddr_convert_from_un(child_si, &un_my_addr.sa.un, un_my_addr.sa_socklen, child_si->family, &in_my_addr.sa.s, &in_my_addr.sa_socklen); if (ret == -1) { free(child_fi); free(child_si); close(fd); return ret; } SWRAP_LOG(SWRAP_LOG_TRACE, "accept() path=%s, fd=%d", un_my_addr.sa.un.sun_path, s); child_si->myname = (struct swrap_address) { .sa_socklen = in_my_addr.sa_socklen, }; memcpy(&child_si->myname.sa.ss, &in_my_addr.sa.ss, in_my_addr.sa_socklen); SWRAP_DLIST_ADD(sockets, child_si); if (addr != NULL) { swrap_pcap_dump_packet(child_si, addr, SWRAP_ACCEPT_SEND, NULL, 0); swrap_pcap_dump_packet(child_si, addr, SWRAP_ACCEPT_RECV, NULL, 0); swrap_pcap_dump_packet(child_si, addr, SWRAP_ACCEPT_ACK, NULL, 0); } return fd; } #ifdef HAVE_ACCEPT4 int accept4(int s, struct sockaddr *addr, socklen_t *addrlen, int flags) { return swrap_accept(s, addr, (socklen_t *)addrlen, flags); } #endif #ifdef HAVE_ACCEPT_PSOCKLEN_T int accept(int s, struct sockaddr *addr, Psocklen_t addrlen) #else int accept(int s, struct sockaddr *addr, socklen_t *addrlen) #endif { return swrap_accept(s, addr, (socklen_t *)addrlen, 0); } static int autobind_start_init; static int autobind_start; /* using sendto() or connect() on an unbound socket would give the recipient no way to reply, as unlike UDP and TCP, a unix domain socket can't auto-assign ephemeral port numbers, so we need to assign it here. Note: this might change the family from ipv6 to ipv4 */ static int swrap_auto_bind(int fd, struct socket_info *si, int family) { struct swrap_address un_addr = { .sa_socklen = sizeof(struct sockaddr_un), }; int i; char type; int ret; int port; struct stat st; if (autobind_start_init != 1) { autobind_start_init = 1; autobind_start = getpid(); autobind_start %= 50000; autobind_start += 10000; } un_addr.sa.un.sun_family = AF_UNIX; switch (family) { case AF_INET: { struct sockaddr_in in; switch (si->type) { case SOCK_STREAM: type = SOCKET_TYPE_CHAR_TCP; break; case SOCK_DGRAM: type = SOCKET_TYPE_CHAR_UDP; break; default: errno = ESOCKTNOSUPPORT; return -1; } memset(&in, 0, sizeof(in)); in.sin_family = AF_INET; in.sin_addr.s_addr = htonl(127<<24 | socket_wrapper_default_iface()); si->myname = (struct swrap_address) { .sa_socklen = sizeof(in), }; memcpy(&si->myname.sa.in, &in, si->myname.sa_socklen); break; } #ifdef HAVE_IPV6 case AF_INET6: { struct sockaddr_in6 in6; if (si->family != family) { errno = ENETUNREACH; return -1; } switch (si->type) { case SOCK_STREAM: type = SOCKET_TYPE_CHAR_TCP_V6; break; case SOCK_DGRAM: type = SOCKET_TYPE_CHAR_UDP_V6; break; default: errno = ESOCKTNOSUPPORT; return -1; } memset(&in6, 0, sizeof(in6)); in6.sin6_family = AF_INET6; in6.sin6_addr = *swrap_ipv6(); in6.sin6_addr.s6_addr[15] = socket_wrapper_default_iface(); si->myname = (struct swrap_address) { .sa_socklen = sizeof(in6), }; memcpy(&si->myname.sa.in6, &in6, si->myname.sa_socklen); break; } #endif default: errno = ESOCKTNOSUPPORT; return -1; } if (autobind_start > 60000) { autobind_start = 10000; } for (i = 0; i < SOCKET_MAX_SOCKETS; i++) { port = autobind_start + i; snprintf(un_addr.sa.un.sun_path, sizeof(un_addr.sa.un.sun_path), "%s/"SOCKET_FORMAT, socket_wrapper_dir(), type, socket_wrapper_default_iface(), port); if (stat(un_addr.sa.un.sun_path, &st) == 0) continue; ret = libc_bind(fd, &un_addr.sa.s, un_addr.sa_socklen); if (ret == -1) return ret; si->un_addr = un_addr.sa.un; si->bound = 1; autobind_start = port + 1; break; } if (i == SOCKET_MAX_SOCKETS) { SWRAP_LOG(SWRAP_LOG_ERROR, "Too many open unix sockets (%u) for " "interface "SOCKET_FORMAT, SOCKET_MAX_SOCKETS, type, socket_wrapper_default_iface(), 0); errno = ENFILE; return -1; } si->family = family; set_port(si->family, port, &si->myname); return 0; } /**************************************************************************** * CONNECT ***************************************************************************/ static int swrap_connect(int s, const struct sockaddr *serv_addr, socklen_t addrlen) { int ret; struct swrap_address un_addr = { .sa_socklen = sizeof(struct sockaddr_un), }; struct socket_info *si = find_socket_info(s); int bcast = 0; if (!si) { return libc_connect(s, serv_addr, addrlen); } if (si->bound == 0) { ret = swrap_auto_bind(s, si, serv_addr->sa_family); if (ret == -1) return -1; } if (si->family != serv_addr->sa_family) { errno = EINVAL; return -1; } ret = sockaddr_convert_to_un(si, serv_addr, addrlen, &un_addr.sa.un, 0, &bcast); if (ret == -1) return -1; if (bcast) { errno = ENETUNREACH; return -1; } if (si->type == SOCK_DGRAM) { si->defer_connect = 1; ret = 0; } else { swrap_pcap_dump_packet(si, serv_addr, SWRAP_CONNECT_SEND, NULL, 0); ret = libc_connect(s, &un_addr.sa.s, un_addr.sa_socklen); } SWRAP_LOG(SWRAP_LOG_TRACE, "connect() path=%s, fd=%d", un_addr.sa.un.sun_path, s); /* to give better errors */ if (ret == -1 && errno == ENOENT) { errno = EHOSTUNREACH; } if (ret == 0) { si->peername = (struct swrap_address) { .sa_socklen = addrlen, }; memcpy(&si->peername.sa.ss, serv_addr, addrlen); si->connected = 1; /* * When we connect() on a socket than we have to bind the * outgoing connection on the interface we use for the * transport. We already bound it on the right interface * but here we have to update the name so getsockname() * returns correct information. */ if (si->bindname.sa_socklen > 0) { si->myname = (struct swrap_address) { .sa_socklen = si->bindname.sa_socklen, }; memcpy(&si->myname.sa.ss, &si->bindname.sa.ss, si->bindname.sa_socklen); /* Cleanup bindname */ si->bindname = (struct swrap_address) { .sa_socklen = 0, }; } swrap_pcap_dump_packet(si, serv_addr, SWRAP_CONNECT_RECV, NULL, 0); swrap_pcap_dump_packet(si, serv_addr, SWRAP_CONNECT_ACK, NULL, 0); } else { swrap_pcap_dump_packet(si, serv_addr, SWRAP_CONNECT_UNREACH, NULL, 0); } return ret; } int connect(int s, const struct sockaddr *serv_addr, socklen_t addrlen) { return swrap_connect(s, serv_addr, addrlen); } /**************************************************************************** * BIND ***************************************************************************/ static int swrap_bind(int s, const struct sockaddr *myaddr, socklen_t addrlen) { int ret; struct swrap_address un_addr = { .sa_socklen = sizeof(struct sockaddr_un), }; struct socket_info *si = find_socket_info(s); int bind_error = 0; #if 0 /* FIXME */ bool in_use; #endif if (!si) { return libc_bind(s, myaddr, addrlen); } switch (si->family) { case AF_INET: { const struct sockaddr_in *sin; if (addrlen < sizeof(struct sockaddr_in)) { bind_error = EINVAL; break; } sin = (const struct sockaddr_in *)(const void *)myaddr; if (sin->sin_family != AF_INET) { bind_error = EAFNOSUPPORT; } /* special case for AF_UNSPEC */ if (sin->sin_family == AF_UNSPEC && (sin->sin_addr.s_addr == htonl(INADDR_ANY))) { bind_error = 0; } break; } #ifdef HAVE_IPV6 case AF_INET6: { const struct sockaddr_in6 *sin6; if (addrlen < sizeof(struct sockaddr_in6)) { bind_error = EINVAL; break; } sin6 = (const struct sockaddr_in6 *)(const void *)myaddr; if (sin6->sin6_family != AF_INET6) { bind_error = EAFNOSUPPORT; } break; } #endif default: bind_error = EINVAL; break; } if (bind_error != 0) { errno = bind_error; return -1; } #if 0 /* FIXME */ in_use = check_addr_port_in_use(myaddr, addrlen); if (in_use) { errno = EADDRINUSE; return -1; } #endif si->myname.sa_socklen = addrlen; memcpy(&si->myname.sa.ss, myaddr, addrlen); ret = sockaddr_convert_to_un(si, myaddr, addrlen, &un_addr.sa.un, 1, &si->bcast); if (ret == -1) return -1; unlink(un_addr.sa.un.sun_path); ret = libc_bind(s, &un_addr.sa.s, un_addr.sa_socklen); SWRAP_LOG(SWRAP_LOG_TRACE, "bind() path=%s, fd=%d", un_addr.sa.un.sun_path, s); if (ret == 0) { si->bound = 1; } return ret; } int bind(int s, const struct sockaddr *myaddr, socklen_t addrlen) { return swrap_bind(s, myaddr, addrlen); } /**************************************************************************** * BINDRESVPORT ***************************************************************************/ #ifdef HAVE_BINDRESVPORT static int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen); static int swrap_bindresvport_sa(int sd, struct sockaddr *sa) { struct swrap_address myaddr = { .sa_socklen = sizeof(struct sockaddr_storage), }; socklen_t salen; static uint16_t port; uint16_t i; int rc = -1; int af; #define SWRAP_STARTPORT 600 #define SWRAP_ENDPORT (IPPORT_RESERVED - 1) #define SWRAP_NPORTS (SWRAP_ENDPORT - SWRAP_STARTPORT + 1) if (port == 0) { port = (getpid() % SWRAP_NPORTS) + SWRAP_STARTPORT; } if (sa == NULL) { salen = myaddr.sa_socklen; sa = &myaddr.sa.s; rc = swrap_getsockname(sd, &myaddr.sa.s, &salen); if (rc < 0) { return -1; } af = sa->sa_family; memset(&myaddr.sa.ss, 0, salen); } else { af = sa->sa_family; } for (i = 0; i < SWRAP_NPORTS; i++, port++) { switch(af) { case AF_INET: { struct sockaddr_in *sinp = (struct sockaddr_in *)(void *)sa; salen = sizeof(struct sockaddr_in); sinp->sin_port = htons(port); break; } case AF_INET6: { struct sockaddr_in6 *sin6p = (struct sockaddr_in6 *)(void *)sa; salen = sizeof(struct sockaddr_in6); sin6p->sin6_port = htons(port); break; } default: errno = EAFNOSUPPORT; return -1; } sa->sa_family = af; if (port > SWRAP_ENDPORT) { port = SWRAP_STARTPORT; } rc = swrap_bind(sd, (struct sockaddr *)sa, salen); if (rc == 0 || errno != EADDRINUSE) { break; } } return rc; } int bindresvport(int sockfd, struct sockaddr_in *sinp) { return swrap_bindresvport_sa(sockfd, (struct sockaddr *)sinp); } #endif /**************************************************************************** * LISTEN ***************************************************************************/ static int swrap_listen(int s, int backlog) { int ret; struct socket_info *si = find_socket_info(s); if (!si) { return libc_listen(s, backlog); } if (si->bound == 0) { ret = swrap_auto_bind(s, si, si->family); if (ret == -1) { errno = EADDRINUSE; return ret; } } ret = libc_listen(s, backlog); return ret; } int listen(int s, int backlog) { return swrap_listen(s, backlog); } /**************************************************************************** * FOPEN ***************************************************************************/ static FILE *swrap_fopen(const char *name, const char *mode) { FILE *fp; fp = libc_fopen(name, mode); if (fp != NULL) { int fd = fileno(fp); swrap_remove_stale(fd); } return fp; } FILE *fopen(const char *name, const char *mode) { return swrap_fopen(name, mode); } /**************************************************************************** * OPEN ***************************************************************************/ static int swrap_vopen(const char *pathname, int flags, va_list ap) { int ret; ret = libc_vopen(pathname, flags, ap); if (ret != -1) { /* * There are methods for closing descriptors (libc-internal code * paths, direct syscalls) which close descriptors in ways that * we can't intercept, so try to recover when we notice that * that's happened */ swrap_remove_stale(ret); } return ret; } int open(const char *pathname, int flags, ...) { va_list ap; int fd; va_start(ap, flags); fd = swrap_vopen(pathname, flags, ap); va_end(ap); return fd; } /**************************************************************************** * GETPEERNAME ***************************************************************************/ static int swrap_getpeername(int s, struct sockaddr *name, socklen_t *addrlen) { struct socket_info *si = find_socket_info(s); socklen_t len; if (!si) { return libc_getpeername(s, name, addrlen); } if (si->peername.sa_socklen == 0) { errno = ENOTCONN; return -1; } len = MIN(*addrlen, si->peername.sa_socklen); if (len == 0) { return 0; } memcpy(name, &si->peername.sa.ss, len); *addrlen = si->peername.sa_socklen; return 0; } #ifdef HAVE_ACCEPT_PSOCKLEN_T int getpeername(int s, struct sockaddr *name, Psocklen_t addrlen) #else int getpeername(int s, struct sockaddr *name, socklen_t *addrlen) #endif { return swrap_getpeername(s, name, (socklen_t *)addrlen); } /**************************************************************************** * GETSOCKNAME ***************************************************************************/ static int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen) { struct socket_info *si = find_socket_info(s); socklen_t len; if (!si) { return libc_getsockname(s, name, addrlen); } len = MIN(*addrlen, si->myname.sa_socklen); if (len == 0) { return 0; } memcpy(name, &si->myname.sa.ss, len); *addrlen = si->myname.sa_socklen; return 0; } #ifdef HAVE_ACCEPT_PSOCKLEN_T int getsockname(int s, struct sockaddr *name, Psocklen_t addrlen) #else int getsockname(int s, struct sockaddr *name, socklen_t *addrlen) #endif { return swrap_getsockname(s, name, (socklen_t *)addrlen); } /**************************************************************************** * GETSOCKOPT ***************************************************************************/ #ifndef SO_PROTOCOL # ifdef SO_PROTOTYPE /* The Solaris name */ # define SO_PROTOCOL SO_PROTOTYPE # endif /* SO_PROTOTYPE */ #endif /* SO_PROTOCOL */ static int swrap_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen) { struct socket_info *si = find_socket_info(s); if (!si) { return libc_getsockopt(s, level, optname, optval, optlen); } if (level == SOL_SOCKET) { switch (optname) { #ifdef SO_DOMAIN case SO_DOMAIN: if (optval == NULL || optlen == NULL || *optlen < (socklen_t)sizeof(int)) { errno = EINVAL; return -1; } *optlen = sizeof(int); *(int *)optval = si->family; return 0; #endif /* SO_DOMAIN */ #ifdef SO_PROTOCOL case SO_PROTOCOL: if (optval == NULL || optlen == NULL || *optlen < (socklen_t)sizeof(int)) { errno = EINVAL; return -1; } *optlen = sizeof(int); *(int *)optval = si->protocol; return 0; #endif /* SO_PROTOCOL */ case SO_TYPE: if (optval == NULL || optlen == NULL || *optlen < (socklen_t)sizeof(int)) { errno = EINVAL; return -1; } *optlen = sizeof(int); *(int *)optval = si->type; return 0; default: return libc_getsockopt(s, level, optname, optval, optlen); } } else if (level == IPPROTO_TCP) { switch (optname) { #ifdef TCP_NODELAY case TCP_NODELAY: /* * This enables sending packets directly out over TCP. * As a unix socket is doing that any way, report it as * enabled. */ if (optval == NULL || optlen == NULL || *optlen < (socklen_t)sizeof(int)) { errno = EINVAL; return -1; } *optlen = sizeof(int); *(int *)optval = si->tcp_nodelay; return 0; #endif /* TCP_NODELAY */ default: break; } } errno = ENOPROTOOPT; return -1; } #ifdef HAVE_ACCEPT_PSOCKLEN_T int getsockopt(int s, int level, int optname, void *optval, Psocklen_t optlen) #else int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen) #endif { return swrap_getsockopt(s, level, optname, optval, (socklen_t *)optlen); } /**************************************************************************** * SETSOCKOPT ***************************************************************************/ static int swrap_setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen) { struct socket_info *si = find_socket_info(s); if (!si) { return libc_setsockopt(s, level, optname, optval, optlen); } if (level == SOL_SOCKET) { return libc_setsockopt(s, level, optname, optval, optlen); } else if (level == IPPROTO_TCP) { switch (optname) { #ifdef TCP_NODELAY case TCP_NODELAY: { int i; /* * This enables sending packets directly out over TCP. * A unix socket is doing that any way. */ if (optval == NULL || optlen == 0 || optlen < (socklen_t)sizeof(int)) { errno = EINVAL; return -1; } i = *discard_const_p(int, optval); if (i != 0 && i != 1) { errno = EINVAL; return -1; } si->tcp_nodelay = i; return 0; } #endif /* TCP_NODELAY */ default: break; } } switch (si->family) { case AF_INET: if (level == IPPROTO_IP) { #ifdef IP_PKTINFO if (optname == IP_PKTINFO) { si->pktinfo = AF_INET; } #endif /* IP_PKTINFO */ } return 0; #ifdef HAVE_IPV6 case AF_INET6: if (level == IPPROTO_IPV6) { #ifdef IPV6_RECVPKTINFO if (optname == IPV6_RECVPKTINFO) { si->pktinfo = AF_INET6; } #endif /* IPV6_PKTINFO */ } return 0; #endif default: errno = ENOPROTOOPT; return -1; } } int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen) { return swrap_setsockopt(s, level, optname, optval, optlen); } /**************************************************************************** * IOCTL ***************************************************************************/ static int swrap_vioctl(int s, unsigned long int r, va_list va) { struct socket_info *si = find_socket_info(s); va_list ap; int value; int rc; if (!si) { return libc_vioctl(s, r, va); } va_copy(ap, va); rc = libc_vioctl(s, r, va); switch (r) { case FIONREAD: value = *((int *)va_arg(ap, int *)); if (rc == -1 && errno != EAGAIN && errno != ENOBUFS) { swrap_pcap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0); } else if (value == 0) { /* END OF FILE */ swrap_pcap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0); } break; } va_end(ap); return rc; } #ifdef HAVE_IOCTL_INT int ioctl(int s, int r, ...) #else int ioctl(int s, unsigned long int r, ...) #endif { va_list va; int rc; va_start(va, r); rc = swrap_vioctl(s, (unsigned long int) r, va); va_end(va); return rc; } /***************** * CMSG *****************/ #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL #ifndef CMSG_ALIGN # ifdef _ALIGN /* BSD */ #define CMSG_ALIGN _ALIGN # else #define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & ~(sizeof(size_t) - 1)) # endif /* _ALIGN */ #endif /* CMSG_ALIGN */ /** * @brief Add a cmsghdr to a msghdr. * * This is an function to add any type of cmsghdr. It will operate on the * msg->msg_control and msg->msg_controllen you pass in by adapting them to * the buffer position after the added cmsg element. Hence, this function is * intended to be used with an intermediate msghdr and not on the original * one handed in by the client. * * @param[in] msg The msghdr to which to add the cmsg. * * @param[in] level The cmsg level to set. * * @param[in] type The cmsg type to set. * * @param[in] data The cmsg data to set. * * @param[in] len the length of the data to set. */ static void swrap_msghdr_add_cmsghdr(struct msghdr *msg, int level, int type, const void *data, size_t len) { size_t cmlen = CMSG_LEN(len); size_t cmspace = CMSG_SPACE(len); uint8_t cmbuf[cmspace]; void *cast_ptr = (void *)cmbuf; struct cmsghdr *cm = (struct cmsghdr *)cast_ptr; uint8_t *p; memset(cmbuf, 0, cmspace); if (msg->msg_controllen < cmlen) { cmlen = msg->msg_controllen; msg->msg_flags |= MSG_CTRUNC; } if (msg->msg_controllen < cmspace) { cmspace = msg->msg_controllen; } /* * We copy the full input data into an intermediate cmsghdr first * in order to more easily cope with truncation. */ cm->cmsg_len = cmlen; cm->cmsg_level = level; cm->cmsg_type = type; memcpy(CMSG_DATA(cm), data, len); /* * We now copy the possibly truncated buffer. * We copy cmlen bytes, but consume cmspace bytes, * leaving the possible padding uninitialiazed. */ p = (uint8_t *)msg->msg_control; memcpy(p, cm, cmlen); p += cmspace; msg->msg_control = p; msg->msg_controllen -= cmspace; return; } static int swrap_msghdr_add_pktinfo(struct socket_info *si, struct msghdr *msg) { /* Add packet info */ switch (si->pktinfo) { #if defined(IP_PKTINFO) && (defined(HAVE_STRUCT_IN_PKTINFO) || defined(IP_RECVDSTADDR)) case AF_INET: { struct sockaddr_in *sin; #if defined(HAVE_STRUCT_IN_PKTINFO) struct in_pktinfo pkt; #elif defined(IP_RECVDSTADDR) struct in_addr pkt; #endif if (si->bindname.sa_socklen == sizeof(struct sockaddr_in)) { sin = &si->bindname.sa.in; } else { if (si->myname.sa_socklen != sizeof(struct sockaddr_in)) { return 0; } sin = &si->myname.sa.in; } ZERO_STRUCT(pkt); #if defined(HAVE_STRUCT_IN_PKTINFO) pkt.ipi_ifindex = socket_wrapper_default_iface(); pkt.ipi_addr.s_addr = sin->sin_addr.s_addr; #elif defined(IP_RECVDSTADDR) pkt = sin->sin_addr; #endif swrap_msghdr_add_cmsghdr(msg, IPPROTO_IP, IP_PKTINFO, &pkt, sizeof(pkt)); break; } #endif /* IP_PKTINFO */ #if defined(HAVE_IPV6) case AF_INET6: { #if defined(IPV6_PKTINFO) && defined(HAVE_STRUCT_IN6_PKTINFO) struct sockaddr_in6 *sin6; struct in6_pktinfo pkt6; if (si->bindname.sa_socklen == sizeof(struct sockaddr_in6)) { sin6 = &si->bindname.sa.in6; } else { if (si->myname.sa_socklen != sizeof(struct sockaddr_in6)) { return 0; } sin6 = &si->myname.sa.in6; } ZERO_STRUCT(pkt6); pkt6.ipi6_ifindex = socket_wrapper_default_iface(); pkt6.ipi6_addr = sin6->sin6_addr; swrap_msghdr_add_cmsghdr(msg, IPPROTO_IPV6, IPV6_PKTINFO, &pkt6, sizeof(pkt6)); #endif /* HAVE_STRUCT_IN6_PKTINFO */ break; } #endif /* IPV6_PKTINFO */ default: return -1; } return 0; } static int swrap_msghdr_add_socket_info(struct socket_info *si, struct msghdr *omsg) { int rc = 0; if (si->pktinfo > 0) { rc = swrap_msghdr_add_pktinfo(si, omsg); } return rc; } static int swrap_sendmsg_copy_cmsg(struct cmsghdr *cmsg, uint8_t **cm_data, size_t *cm_data_space); static int swrap_sendmsg_filter_cmsg_socket(struct cmsghdr *cmsg, uint8_t **cm_data, size_t *cm_data_space); static int swrap_sendmsg_filter_cmsghdr(struct msghdr *msg, uint8_t **cm_data, size_t *cm_data_space) { struct cmsghdr *cmsg; int rc = -1; /* Nothing to do */ if (msg->msg_controllen == 0 || msg->msg_control == NULL) { return 0; } for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg)) { switch (cmsg->cmsg_level) { case IPPROTO_IP: rc = swrap_sendmsg_filter_cmsg_socket(cmsg, cm_data, cm_data_space); break; default: rc = swrap_sendmsg_copy_cmsg(cmsg, cm_data, cm_data_space); break; } } return rc; } static int swrap_sendmsg_copy_cmsg(struct cmsghdr *cmsg, uint8_t **cm_data, size_t *cm_data_space) { size_t cmspace; uint8_t *p; cmspace = *cm_data_space + CMSG_ALIGN(cmsg->cmsg_len); p = realloc((*cm_data), cmspace); if (p == NULL) { return -1; } (*cm_data) = p; p = (*cm_data) + (*cm_data_space); *cm_data_space = cmspace; memcpy(p, cmsg, cmsg->cmsg_len); return 0; } static int swrap_sendmsg_filter_cmsg_pktinfo(struct cmsghdr *cmsg, uint8_t **cm_data, size_t *cm_data_space); static int swrap_sendmsg_filter_cmsg_socket(struct cmsghdr *cmsg, uint8_t **cm_data, size_t *cm_data_space) { int rc = -1; switch(cmsg->cmsg_type) { #ifdef IP_PKTINFO case IP_PKTINFO: rc = swrap_sendmsg_filter_cmsg_pktinfo(cmsg, cm_data, cm_data_space); break; #endif #ifdef IPV6_PKTINFO case IPV6_PKTINFO: rc = swrap_sendmsg_filter_cmsg_pktinfo(cmsg, cm_data, cm_data_space); break; #endif default: break; } return rc; } static int swrap_sendmsg_filter_cmsg_pktinfo(struct cmsghdr *cmsg, uint8_t **cm_data, size_t *cm_data_space) { (void)cmsg; /* unused */ (void)cm_data; /* unused */ (void)cm_data_space; /* unused */ /* * Passing a IP pktinfo to a unix socket might be rejected by the * Kernel, at least on FreeBSD. So skip this cmsg. */ return 0; } #endif /* HAVE_STRUCT_MSGHDR_MSG_CONTROL */ static ssize_t swrap_sendmsg_before(int fd, struct socket_info *si, struct msghdr *msg, struct iovec *tmp_iov, struct sockaddr_un *tmp_un, const struct sockaddr_un **to_un, const struct sockaddr **to, int *bcast) { size_t i, len = 0; ssize_t ret; if (to_un) { *to_un = NULL; } if (to) { *to = NULL; } if (bcast) { *bcast = 0; } switch (si->type) { case SOCK_STREAM: { unsigned long mtu; if (!si->connected) { errno = ENOTCONN; return -1; } if (msg->msg_iovlen == 0) { break; } mtu = socket_wrapper_mtu(); for (i = 0; i < (size_t)msg->msg_iovlen; i++) { size_t nlen; nlen = len + msg->msg_iov[i].iov_len; if (nlen > mtu) { break; } } msg->msg_iovlen = i; if (msg->msg_iovlen == 0) { *tmp_iov = msg->msg_iov[0]; tmp_iov->iov_len = MIN((size_t)tmp_iov->iov_len, (size_t)mtu); msg->msg_iov = tmp_iov; msg->msg_iovlen = 1; } break; } case SOCK_DGRAM: if (si->connected) { if (msg->msg_name != NULL) { /* * We are dealing with unix sockets and if we * are connected, we should only talk to the * connected unix path. Using the fd to send * to another server would be hard to achieve. */ msg->msg_name = NULL; msg->msg_namelen = 0; } } else { const struct sockaddr *msg_name; msg_name = (const struct sockaddr *)msg->msg_name; if (msg_name == NULL) { errno = ENOTCONN; return -1; } ret = sockaddr_convert_to_un(si, msg_name, msg->msg_namelen, tmp_un, 0, bcast); if (ret == -1) return -1; if (to_un) { *to_un = tmp_un; } if (to) { *to = msg_name; } msg->msg_name = tmp_un; msg->msg_namelen = sizeof(*tmp_un); } if (si->bound == 0) { ret = swrap_auto_bind(fd, si, si->family); if (ret == -1) { if (errno == ENOTSOCK) { swrap_remove_stale(fd); return -ENOTSOCK; } else { SWRAP_LOG(SWRAP_LOG_ERROR, "swrap_sendmsg_before failed"); return -1; } } } if (!si->defer_connect) { break; } ret = sockaddr_convert_to_un(si, &si->peername.sa.s, si->peername.sa_socklen, tmp_un, 0, NULL); if (ret == -1) return -1; ret = libc_connect(fd, (struct sockaddr *)(void *)tmp_un, sizeof(*tmp_un)); /* to give better errors */ if (ret == -1 && errno == ENOENT) { errno = EHOSTUNREACH; } if (ret == -1) { return ret; } si->defer_connect = 0; break; default: errno = EHOSTUNREACH; return -1; } #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL if (msg->msg_controllen > 0 && msg->msg_control != NULL) { uint8_t *cmbuf = NULL; size_t cmlen = 0; ret = swrap_sendmsg_filter_cmsghdr(msg, &cmbuf, &cmlen); if (ret < 0) { free(cmbuf); return -1; } if (cmlen == 0) { msg->msg_controllen = 0; msg->msg_control = NULL; } else if (cmlen < msg->msg_controllen && cmbuf != NULL) { memcpy(msg->msg_control, cmbuf, cmlen); msg->msg_controllen = cmlen; } free(cmbuf); } #endif return 0; } static void swrap_sendmsg_after(int fd, struct socket_info *si, struct msghdr *msg, const struct sockaddr *to, ssize_t ret) { int saved_errno = errno; size_t i, len = 0; uint8_t *buf; off_t ofs = 0; size_t avail = 0; size_t remain; /* to give better errors */ if (ret == -1) { if (saved_errno == ENOENT) { saved_errno = EHOSTUNREACH; } else if (saved_errno == ENOTSOCK) { /* If the fd is not a socket, remove it */ swrap_remove_stale(fd); } } for (i = 0; i < (size_t)msg->msg_iovlen; i++) { avail += msg->msg_iov[i].iov_len; } if (ret == -1) { remain = MIN(80, avail); } else { remain = ret; } /* we capture it as one single packet */ buf = (uint8_t *)malloc(remain); if (!buf) { /* we just not capture the packet */ errno = saved_errno; return; } for (i = 0; i < (size_t)msg->msg_iovlen; i++) { size_t this_time = MIN(remain, (size_t)msg->msg_iov[i].iov_len); memcpy(buf + ofs, msg->msg_iov[i].iov_base, this_time); ofs += this_time; remain -= this_time; } len = ofs; switch (si->type) { case SOCK_STREAM: if (ret == -1) { swrap_pcap_dump_packet(si, NULL, SWRAP_SEND, buf, len); swrap_pcap_dump_packet(si, NULL, SWRAP_SEND_RST, NULL, 0); } else { swrap_pcap_dump_packet(si, NULL, SWRAP_SEND, buf, len); } break; case SOCK_DGRAM: if (si->connected) { to = &si->peername.sa.s; } if (ret == -1) { swrap_pcap_dump_packet(si, to, SWRAP_SENDTO, buf, len); swrap_pcap_dump_packet(si, to, SWRAP_SENDTO_UNREACH, buf, len); } else { swrap_pcap_dump_packet(si, to, SWRAP_SENDTO, buf, len); } break; } free(buf); errno = saved_errno; } static int swrap_recvmsg_before(int fd, struct socket_info *si, struct msghdr *msg, struct iovec *tmp_iov) { size_t i, len = 0; ssize_t ret; (void)fd; /* unused */ switch (si->type) { case SOCK_STREAM: { unsigned int mtu; if (!si->connected) { errno = ENOTCONN; return -1; } if (msg->msg_iovlen == 0) { break; } mtu = socket_wrapper_mtu(); for (i = 0; i < (size_t)msg->msg_iovlen; i++) { size_t nlen; nlen = len + msg->msg_iov[i].iov_len; if (nlen > mtu) { break; } } msg->msg_iovlen = i; if (msg->msg_iovlen == 0) { *tmp_iov = msg->msg_iov[0]; tmp_iov->iov_len = MIN((size_t)tmp_iov->iov_len, (size_t)mtu); msg->msg_iov = tmp_iov; msg->msg_iovlen = 1; } break; } case SOCK_DGRAM: if (msg->msg_name == NULL) { errno = EINVAL; return -1; } if (msg->msg_iovlen == 0) { break; } if (si->bound == 0) { ret = swrap_auto_bind(fd, si, si->family); if (ret == -1) { /* * When attempting to read or write to a * descriptor, if an underlying autobind fails * because it's not a socket, stop intercepting * uses of that descriptor. */ if (errno == ENOTSOCK) { swrap_remove_stale(fd); return -ENOTSOCK; } else { SWRAP_LOG(SWRAP_LOG_ERROR, "swrap_recvmsg_before failed"); return -1; } } } break; default: errno = EHOSTUNREACH; return -1; } return 0; } static int swrap_recvmsg_after(int fd, struct socket_info *si, struct msghdr *msg, const struct sockaddr_un *un_addr, socklen_t un_addrlen, ssize_t ret) { int saved_errno = errno; size_t i; uint8_t *buf = NULL; off_t ofs = 0; size_t avail = 0; size_t remain; int rc; /* to give better errors */ if (ret == -1) { if (saved_errno == ENOENT) { saved_errno = EHOSTUNREACH; } else if (saved_errno == ENOTSOCK) { /* If the fd is not a socket, remove it */ swrap_remove_stale(fd); } } for (i = 0; i < (size_t)msg->msg_iovlen; i++) { avail += msg->msg_iov[i].iov_len; } /* Convert the socket address before we leave */ if (si->type == SOCK_DGRAM && un_addr != NULL) { rc = sockaddr_convert_from_un(si, un_addr, un_addrlen, si->family, msg->msg_name, &msg->msg_namelen); if (rc == -1) { goto done; } } if (avail == 0) { rc = 0; goto done; } if (ret == -1) { remain = MIN(80, avail); } else { remain = ret; } /* we capture it as one single packet */ buf = (uint8_t *)malloc(remain); if (buf == NULL) { /* we just not capture the packet */ errno = saved_errno; return -1; } for (i = 0; i < (size_t)msg->msg_iovlen; i++) { size_t this_time = MIN(remain, (size_t)msg->msg_iov[i].iov_len); memcpy(buf + ofs, msg->msg_iov[i].iov_base, this_time); ofs += this_time; remain -= this_time; } switch (si->type) { case SOCK_STREAM: if (ret == -1 && saved_errno != EAGAIN && saved_errno != ENOBUFS) { swrap_pcap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0); } else if (ret == 0) { /* END OF FILE */ swrap_pcap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0); } else if (ret > 0) { swrap_pcap_dump_packet(si, NULL, SWRAP_RECV, buf, ret); } break; case SOCK_DGRAM: if (ret == -1) { break; } if (un_addr != NULL) { swrap_pcap_dump_packet(si, msg->msg_name, SWRAP_RECVFROM, buf, ret); } else { swrap_pcap_dump_packet(si, msg->msg_name, SWRAP_RECV, buf, ret); } break; } rc = 0; done: free(buf); errno = saved_errno; #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL if (rc == 0 && msg->msg_controllen > 0 && msg->msg_control != NULL) { rc = swrap_msghdr_add_socket_info(si, msg); if (rc < 0) { return -1; } } #endif return rc; } /**************************************************************************** * RECVFROM ***************************************************************************/ static ssize_t swrap_recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen) { struct swrap_address from_addr = { .sa_socklen = sizeof(struct sockaddr_un), }; ssize_t ret; struct socket_info *si = find_socket_info(s); struct swrap_address saddr = { .sa_socklen = sizeof(struct sockaddr_storage), }; struct msghdr msg; struct iovec tmp; int tret; if (!si) { return libc_recvfrom(s, buf, len, flags, from, fromlen); } tmp.iov_base = buf; tmp.iov_len = len; ZERO_STRUCT(msg); if (from != NULL && fromlen != NULL) { msg.msg_name = from; /* optional address */ msg.msg_namelen = *fromlen; /* size of address */ } else { msg.msg_name = &saddr.sa.s; /* optional address */ msg.msg_namelen = saddr.sa_socklen; /* size of address */ } msg.msg_iov = &tmp; /* scatter/gather array */ msg.msg_iovlen = 1; /* # elements in msg_iov */ #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL msg.msg_control = NULL; /* ancillary data, see below */ msg.msg_controllen = 0; /* ancillary data buffer len */ msg.msg_flags = 0; /* flags on received message */ #endif tret = swrap_recvmsg_before(s, si, &msg, &tmp); if (tret < 0) { return -1; } buf = msg.msg_iov[0].iov_base; len = msg.msg_iov[0].iov_len; ret = libc_recvfrom(s, buf, len, flags, &from_addr.sa.s, &from_addr.sa_socklen); if (ret == -1) { return ret; } tret = swrap_recvmsg_after(s, si, &msg, &from_addr.sa.un, from_addr.sa_socklen, ret); if (tret != 0) { return tret; } if (from != NULL && fromlen != NULL) { *fromlen = msg.msg_namelen; } return ret; } #ifdef HAVE_ACCEPT_PSOCKLEN_T ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, Psocklen_t fromlen) #else ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen) #endif { return swrap_recvfrom(s, buf, len, flags, from, (socklen_t *)fromlen); } /**************************************************************************** * SENDTO ***************************************************************************/ static ssize_t swrap_sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen) { struct msghdr msg; struct iovec tmp; struct swrap_address un_addr = { .sa_socklen = sizeof(struct sockaddr_un), }; const struct sockaddr_un *to_un = NULL; ssize_t ret; int rc; struct socket_info *si = find_socket_info(s); int bcast = 0; if (!si) { return libc_sendto(s, buf, len, flags, to, tolen); } tmp.iov_base = discard_const_p(char, buf); tmp.iov_len = len; ZERO_STRUCT(msg); msg.msg_name = discard_const_p(struct sockaddr, to); /* optional address */ msg.msg_namelen = tolen; /* size of address */ msg.msg_iov = &tmp; /* scatter/gather array */ msg.msg_iovlen = 1; /* # elements in msg_iov */ #if HAVE_STRUCT_MSGHDR_MSG_CONTROL msg.msg_control = NULL; /* ancillary data, see below */ msg.msg_controllen = 0; /* ancillary data buffer len */ msg.msg_flags = 0; /* flags on received message */ #endif rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr.sa.un, &to_un, &to, &bcast); if (rc < 0) { return -1; } buf = msg.msg_iov[0].iov_base; len = msg.msg_iov[0].iov_len; if (bcast) { struct stat st; unsigned int iface; unsigned int prt = ntohs(((const struct sockaddr_in *)(const void *)to)->sin_port); char type; type = SOCKET_TYPE_CHAR_UDP; for(iface=0; iface <= MAX_WRAPPED_INTERFACES; iface++) { snprintf(un_addr.sa.un.sun_path, sizeof(un_addr.sa.un.sun_path), "%s/"SOCKET_FORMAT, socket_wrapper_dir(), type, iface, prt); if (stat(un_addr.sa.un.sun_path, &st) != 0) continue; /* ignore the any errors in broadcast sends */ libc_sendto(s, buf, len, flags, &un_addr.sa.s, un_addr.sa_socklen); } swrap_pcap_dump_packet(si, to, SWRAP_SENDTO, buf, len); return len; } /* * If it is a dgram socket and we are connected, don't include the * 'to' address. */ if (si->type == SOCK_DGRAM && si->connected) { ret = libc_sendto(s, buf, len, flags, NULL, 0); } else { ret = libc_sendto(s, buf, len, flags, (struct sockaddr *)msg.msg_name, msg.msg_namelen); } swrap_sendmsg_after(s, si, &msg, to, ret); return ret; } ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen) { return swrap_sendto(s, buf, len, flags, to, tolen); } /**************************************************************************** * READV ***************************************************************************/ static ssize_t swrap_recv(int s, void *buf, size_t len, int flags) { struct socket_info *si; struct msghdr msg; struct swrap_address saddr = { .sa_socklen = sizeof(struct sockaddr_storage), }; struct iovec tmp; ssize_t ret; int tret; si = find_socket_info(s); if (si == NULL) { return libc_recv(s, buf, len, flags); } tmp.iov_base = buf; tmp.iov_len = len; ZERO_STRUCT(msg); msg.msg_name = &saddr.sa.s; /* optional address */ msg.msg_namelen = saddr.sa_socklen; /* size of address */ msg.msg_iov = &tmp; /* scatter/gather array */ msg.msg_iovlen = 1; /* # elements in msg_iov */ #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL msg.msg_control = NULL; /* ancillary data, see below */ msg.msg_controllen = 0; /* ancillary data buffer len */ msg.msg_flags = 0; /* flags on received message */ #endif tret = swrap_recvmsg_before(s, si, &msg, &tmp); if (tret < 0) { return -1; } buf = msg.msg_iov[0].iov_base; len = msg.msg_iov[0].iov_len; ret = libc_recv(s, buf, len, flags); tret = swrap_recvmsg_after(s, si, &msg, NULL, 0, ret); if (tret != 0) { return tret; } return ret; } ssize_t recv(int s, void *buf, size_t len, int flags) { return swrap_recv(s, buf, len, flags); } /**************************************************************************** * READ ***************************************************************************/ static ssize_t swrap_read(int s, void *buf, size_t len) { struct socket_info *si; struct msghdr msg; struct iovec tmp; struct swrap_address saddr = { .sa_socklen = sizeof(struct sockaddr_storage), }; ssize_t ret; int tret; si = find_socket_info(s); if (si == NULL) { return libc_read(s, buf, len); } tmp.iov_base = buf; tmp.iov_len = len; ZERO_STRUCT(msg); msg.msg_name = &saddr.sa.ss; /* optional address */ msg.msg_namelen = saddr.sa_socklen; /* size of address */ msg.msg_iov = &tmp; /* scatter/gather array */ msg.msg_iovlen = 1; /* # elements in msg_iov */ #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL msg.msg_control = NULL; /* ancillary data, see below */ msg.msg_controllen = 0; /* ancillary data buffer len */ msg.msg_flags = 0; /* flags on received message */ #endif tret = swrap_recvmsg_before(s, si, &msg, &tmp); if (tret < 0) { if (tret == -ENOTSOCK) { return libc_read(s, buf, len); } return -1; } buf = msg.msg_iov[0].iov_base; len = msg.msg_iov[0].iov_len; ret = libc_read(s, buf, len); tret = swrap_recvmsg_after(s, si, &msg, NULL, 0, ret); if (tret != 0) { return tret; } return ret; } ssize_t read(int s, void *buf, size_t len) { return swrap_read(s, buf, len); } /**************************************************************************** * WRITE ***************************************************************************/ static ssize_t swrap_write(int s, const void *buf, size_t len) { struct msghdr msg; struct iovec tmp; struct sockaddr_un un_addr; ssize_t ret; int rc; struct socket_info *si; si = find_socket_info(s); if (si == NULL) { return libc_write(s, buf, len); } tmp.iov_base = discard_const_p(char, buf); tmp.iov_len = len; ZERO_STRUCT(msg); msg.msg_name = NULL; /* optional address */ msg.msg_namelen = 0; /* size of address */ msg.msg_iov = &tmp; /* scatter/gather array */ msg.msg_iovlen = 1; /* # elements in msg_iov */ #if HAVE_STRUCT_MSGHDR_MSG_CONTROL msg.msg_control = NULL; /* ancillary data, see below */ msg.msg_controllen = 0; /* ancillary data buffer len */ msg.msg_flags = 0; /* flags on received message */ #endif rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr, NULL, NULL, NULL); if (rc < 0) { return -1; } buf = msg.msg_iov[0].iov_base; len = msg.msg_iov[0].iov_len; ret = libc_write(s, buf, len); swrap_sendmsg_after(s, si, &msg, NULL, ret); return ret; } ssize_t write(int s, const void *buf, size_t len) { return swrap_write(s, buf, len); } /**************************************************************************** * SEND ***************************************************************************/ static ssize_t swrap_send(int s, const void *buf, size_t len, int flags) { struct msghdr msg; struct iovec tmp; struct sockaddr_un un_addr; ssize_t ret; int rc; struct socket_info *si = find_socket_info(s); if (!si) { return libc_send(s, buf, len, flags); } tmp.iov_base = discard_const_p(char, buf); tmp.iov_len = len; ZERO_STRUCT(msg); msg.msg_name = NULL; /* optional address */ msg.msg_namelen = 0; /* size of address */ msg.msg_iov = &tmp; /* scatter/gather array */ msg.msg_iovlen = 1; /* # elements in msg_iov */ #if HAVE_STRUCT_MSGHDR_MSG_CONTROL msg.msg_control = NULL; /* ancillary data, see below */ msg.msg_controllen = 0; /* ancillary data buffer len */ msg.msg_flags = 0; /* flags on received message */ #endif rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr, NULL, NULL, NULL); if (rc < 0) { return -1; } buf = msg.msg_iov[0].iov_base; len = msg.msg_iov[0].iov_len; ret = libc_send(s, buf, len, flags); swrap_sendmsg_after(s, si, &msg, NULL, ret); return ret; } ssize_t send(int s, const void *buf, size_t len, int flags) { return swrap_send(s, buf, len, flags); } /**************************************************************************** * RECVMSG ***************************************************************************/ static ssize_t swrap_recvmsg(int s, struct msghdr *omsg, int flags) { struct swrap_address from_addr = { .sa_socklen = sizeof(struct sockaddr_un), }; struct swrap_address convert_addr = { .sa_socklen = sizeof(struct sockaddr_storage), }; struct socket_info *si; struct msghdr msg; struct iovec tmp; #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL size_t msg_ctrllen_filled; size_t msg_ctrllen_left; #endif ssize_t ret; int rc; si = find_socket_info(s); if (si == NULL) { return libc_recvmsg(s, omsg, flags); } tmp.iov_base = NULL; tmp.iov_len = 0; ZERO_STRUCT(msg); msg.msg_name = &from_addr.sa; /* optional address */ msg.msg_namelen = from_addr.sa_socklen; /* size of address */ msg.msg_iov = omsg->msg_iov; /* scatter/gather array */ msg.msg_iovlen = omsg->msg_iovlen; /* # elements in msg_iov */ #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL msg_ctrllen_filled = 0; msg_ctrllen_left = omsg->msg_controllen; msg.msg_control = omsg->msg_control; /* ancillary data, see below */ msg.msg_controllen = omsg->msg_controllen; /* ancillary data buffer len */ msg.msg_flags = omsg->msg_flags; /* flags on received message */ #endif rc = swrap_recvmsg_before(s, si, &msg, &tmp); if (rc < 0) { return -1; } ret = libc_recvmsg(s, &msg, flags); #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL msg_ctrllen_filled += msg.msg_controllen; msg_ctrllen_left -= msg.msg_controllen; if (omsg->msg_control != NULL) { uint8_t *p; p = omsg->msg_control; p += msg_ctrllen_filled; msg.msg_control = p; msg.msg_controllen = msg_ctrllen_left; } else { msg.msg_control = NULL; msg.msg_controllen = 0; } #endif /* * We convert the unix address to a IP address so we need a buffer * which can store the address in case of SOCK_DGRAM, see below. */ msg.msg_name = &convert_addr.sa; msg.msg_namelen = convert_addr.sa_socklen; rc = swrap_recvmsg_after(s, si, &msg, &from_addr.sa.un, from_addr.sa_socklen, ret); if (rc != 0) { return rc; } #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL if (omsg->msg_control != NULL) { /* msg.msg_controllen = space left */ msg_ctrllen_left = msg.msg_controllen; msg_ctrllen_filled = omsg->msg_controllen - msg_ctrllen_left; } /* Update the original message length */ omsg->msg_controllen = msg_ctrllen_filled; omsg->msg_flags = msg.msg_flags; #endif omsg->msg_iovlen = msg.msg_iovlen; /* * From the manpage: * * The msg_name field points to a caller-allocated buffer that is * used to return the source address if the socket is unconnected. The * caller should set msg_namelen to the size of this buffer before this * call; upon return from a successful call, msg_name will contain the * length of the returned address. If the application does not need * to know the source address, msg_name can be specified as NULL. */ if (si->type == SOCK_STREAM) { omsg->msg_namelen = 0; } else if (omsg->msg_name != NULL && omsg->msg_namelen != 0 && omsg->msg_namelen >= msg.msg_namelen) { memcpy(omsg->msg_name, msg.msg_name, msg.msg_namelen); omsg->msg_namelen = msg.msg_namelen; } return ret; } ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) { return swrap_recvmsg(sockfd, msg, flags); } /**************************************************************************** * SENDMSG ***************************************************************************/ static ssize_t swrap_sendmsg(int s, const struct msghdr *omsg, int flags) { struct msghdr msg; struct iovec tmp; struct sockaddr_un un_addr; const struct sockaddr_un *to_un = NULL; const struct sockaddr *to = NULL; ssize_t ret; int rc; struct socket_info *si = find_socket_info(s); int bcast = 0; if (!si) { return libc_sendmsg(s, omsg, flags); } ZERO_STRUCT(un_addr); tmp.iov_base = NULL; tmp.iov_len = 0; ZERO_STRUCT(msg); if (si->connected == 0) { msg.msg_name = omsg->msg_name; /* optional address */ msg.msg_namelen = omsg->msg_namelen; /* size of address */ } msg.msg_iov = omsg->msg_iov; /* scatter/gather array */ msg.msg_iovlen = omsg->msg_iovlen; /* # elements in msg_iov */ #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL if (msg.msg_controllen > 0 && msg.msg_control != NULL) { /* omsg is a const so use a local buffer for modifications */ uint8_t cmbuf[omsg->msg_controllen]; memcpy(cmbuf, omsg->msg_control, omsg->msg_controllen); msg.msg_control = cmbuf; /* ancillary data, see below */ msg.msg_controllen = omsg->msg_controllen; /* ancillary data buffer len */ } msg.msg_flags = omsg->msg_flags; /* flags on received message */ #endif rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr, &to_un, &to, &bcast); if (rc < 0) { return -1; } if (bcast) { struct stat st; unsigned int iface; unsigned int prt = ntohs(((const struct sockaddr_in *)(const void *)to)->sin_port); char type; size_t i, len = 0; uint8_t *buf; off_t ofs = 0; size_t avail = 0; size_t remain; for (i = 0; i < (size_t)msg.msg_iovlen; i++) { avail += msg.msg_iov[i].iov_len; } len = avail; remain = avail; /* we capture it as one single packet */ buf = (uint8_t *)malloc(remain); if (!buf) { return -1; } for (i = 0; i < (size_t)msg.msg_iovlen; i++) { size_t this_time = MIN(remain, (size_t)msg.msg_iov[i].iov_len); memcpy(buf + ofs, msg.msg_iov[i].iov_base, this_time); ofs += this_time; remain -= this_time; } type = SOCKET_TYPE_CHAR_UDP; for(iface=0; iface <= MAX_WRAPPED_INTERFACES; iface++) { snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s/"SOCKET_FORMAT, socket_wrapper_dir(), type, iface, prt); if (stat(un_addr.sun_path, &st) != 0) continue; msg.msg_name = &un_addr; /* optional address */ msg.msg_namelen = sizeof(un_addr); /* size of address */ /* ignore the any errors in broadcast sends */ libc_sendmsg(s, &msg, flags); } swrap_pcap_dump_packet(si, to, SWRAP_SENDTO, buf, len); free(buf); return len; } ret = libc_sendmsg(s, &msg, flags); swrap_sendmsg_after(s, si, &msg, to, ret); return ret; } ssize_t sendmsg(int s, const struct msghdr *omsg, int flags) { return swrap_sendmsg(s, omsg, flags); } /**************************************************************************** * READV ***************************************************************************/ static ssize_t swrap_readv(int s, const struct iovec *vector, int count) { struct socket_info *si; struct msghdr msg; struct iovec tmp; struct swrap_address saddr = { .sa_socklen = sizeof(struct sockaddr_storage) }; ssize_t ret; int rc; si = find_socket_info(s); if (si == NULL) { return libc_readv(s, vector, count); } tmp.iov_base = NULL; tmp.iov_len = 0; ZERO_STRUCT(msg); msg.msg_name = &saddr.sa.s; /* optional address */ msg.msg_namelen = saddr.sa_socklen; /* size of address */ msg.msg_iov = discard_const_p(struct iovec, vector); /* scatter/gather array */ msg.msg_iovlen = count; /* # elements in msg_iov */ #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL msg.msg_control = NULL; /* ancillary data, see below */ msg.msg_controllen = 0; /* ancillary data buffer len */ msg.msg_flags = 0; /* flags on received message */ #endif rc = swrap_recvmsg_before(s, si, &msg, &tmp); if (rc < 0) { if (rc == -ENOTSOCK) { return libc_readv(s, vector, count); } return -1; } ret = libc_readv(s, msg.msg_iov, msg.msg_iovlen); rc = swrap_recvmsg_after(s, si, &msg, NULL, 0, ret); if (rc != 0) { return rc; } return ret; } ssize_t readv(int s, const struct iovec *vector, int count) { return swrap_readv(s, vector, count); } /**************************************************************************** * WRITEV ***************************************************************************/ static ssize_t swrap_writev(int s, const struct iovec *vector, int count) { struct msghdr msg; struct iovec tmp; struct sockaddr_un un_addr; ssize_t ret; int rc; struct socket_info *si = find_socket_info(s); if (!si) { return libc_writev(s, vector, count); } tmp.iov_base = NULL; tmp.iov_len = 0; ZERO_STRUCT(msg); msg.msg_name = NULL; /* optional address */ msg.msg_namelen = 0; /* size of address */ msg.msg_iov = discard_const_p(struct iovec, vector); /* scatter/gather array */ msg.msg_iovlen = count; /* # elements in msg_iov */ #if HAVE_STRUCT_MSGHDR_MSG_CONTROL msg.msg_control = NULL; /* ancillary data, see below */ msg.msg_controllen = 0; /* ancillary data buffer len */ msg.msg_flags = 0; /* flags on received message */ #endif rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr, NULL, NULL, NULL); if (rc < 0) { if (rc == -ENOTSOCK) { return libc_readv(s, vector, count); } return -1; } ret = libc_writev(s, msg.msg_iov, msg.msg_iovlen); swrap_sendmsg_after(s, si, &msg, NULL, ret); return ret; } ssize_t writev(int s, const struct iovec *vector, int count) { return swrap_writev(s, vector, count); } /**************************** * CLOSE ***************************/ static int swrap_close(int fd) { struct socket_info *si = find_socket_info(fd); struct socket_info_fd *fi; int ret; if (!si) { return libc_close(fd); } for (fi = si->fds; fi; fi = fi->next) { if (fi->fd == fd) { SWRAP_DLIST_REMOVE(si->fds, fi); free(fi); break; } } if (si->fds) { /* there are still references left */ return libc_close(fd); } SWRAP_DLIST_REMOVE(sockets, si); if (si->myname.sa_socklen > 0 && si->peername.sa_socklen > 0) { swrap_pcap_dump_packet(si, NULL, SWRAP_CLOSE_SEND, NULL, 0); } ret = libc_close(fd); if (si->myname.sa_socklen > 0 && si->peername.sa_socklen > 0) { swrap_pcap_dump_packet(si, NULL, SWRAP_CLOSE_RECV, NULL, 0); swrap_pcap_dump_packet(si, NULL, SWRAP_CLOSE_ACK, NULL, 0); } if (si->un_addr.sun_path[0] != '\0') { unlink(si->un_addr.sun_path); } free(si); return ret; } int close(int fd) { return swrap_close(fd); } /**************************** * DUP ***************************/ static int swrap_dup(int fd) { struct socket_info *si; struct socket_info_fd *fi; si = find_socket_info(fd); if (!si) { return libc_dup(fd); } fi = (struct socket_info_fd *)calloc(1, sizeof(struct socket_info_fd)); if (fi == NULL) { errno = ENOMEM; return -1; } fi->fd = libc_dup(fd); if (fi->fd == -1) { int saved_errno = errno; free(fi); errno = saved_errno; return -1; } /* Make sure we don't have an entry for the fd */ swrap_remove_stale(fi->fd); SWRAP_DLIST_ADD(si->fds, fi); return fi->fd; } int dup(int fd) { return swrap_dup(fd); } /**************************** * DUP2 ***************************/ static int swrap_dup2(int fd, int newfd) { struct socket_info *si; struct socket_info_fd *fi; si = find_socket_info(fd); if (!si) { return libc_dup2(fd, newfd); } if (find_socket_info(newfd)) { /* dup2() does an implicit close of newfd, which we * need to emulate */ swrap_close(newfd); } fi = (struct socket_info_fd *)calloc(1, sizeof(struct socket_info_fd)); if (fi == NULL) { errno = ENOMEM; return -1; } fi->fd = libc_dup2(fd, newfd); if (fi->fd == -1) { int saved_errno = errno; free(fi); errno = saved_errno; return -1; } /* Make sure we don't have an entry for the fd */ swrap_remove_stale(fi->fd); SWRAP_DLIST_ADD(si->fds, fi); return fi->fd; } int dup2(int fd, int newfd) { return swrap_dup2(fd, newfd); } /**************************** * FCNTL ***************************/ static int swrap_vfcntl(int fd, int cmd, va_list va) { struct socket_info_fd *fi; struct socket_info *si; int rc; si = find_socket_info(fd); if (si == NULL) { rc = libc_vfcntl(fd, cmd, va); return rc; } switch (cmd) { case F_DUPFD: fi = (struct socket_info_fd *)calloc(1, sizeof(struct socket_info_fd)); if (fi == NULL) { errno = ENOMEM; return -1; } fi->fd = libc_vfcntl(fd, cmd, va); if (fi->fd == -1) { int saved_errno = errno; free(fi); errno = saved_errno; return -1; } /* Make sure we don't have an entry for the fd */ swrap_remove_stale(fi->fd); SWRAP_DLIST_ADD(si->fds, fi); rc = fi->fd; break; default: rc = libc_vfcntl(fd, cmd, va); break; } return rc; } int fcntl(int fd, int cmd, ...) { va_list va; int rc; va_start(va, cmd); rc = swrap_vfcntl(fd, cmd, va); va_end(va); return rc; } /**************************** * EVENTFD ***************************/ #ifdef HAVE_EVENTFD static int swrap_eventfd(int count, int flags) { int fd; fd = libc_eventfd(count, flags); if (fd != -1) { swrap_remove_stale(fd); } return fd; } #ifdef HAVE_EVENTFD_UNSIGNED_INT int eventfd(unsigned int count, int flags) #else int eventfd(int count, int flags) #endif { return swrap_eventfd(count, flags); } #endif #ifdef HAVE_PLEDGE int pledge(const char *promises, const char *paths[]) { (void)promises; /* unused */ (void)paths; /* unused */ return 0; } #endif /* HAVE_PLEDGE */ /**************************** * DESTRUCTOR ***************************/ /* * This function is called when the library is unloaded and makes sure that * sockets get closed and the unix file for the socket are unlinked. */ void swrap_destructor(void) { struct socket_info *s = sockets; while (s != NULL) { struct socket_info_fd *f = s->fds; if (f != NULL) { swrap_close(f->fd); } s = sockets; } if (swrap.libc_handle != NULL) { dlclose(swrap.libc_handle); } if (swrap.libsocket_handle) { dlclose(swrap.libsocket_handle); } }
gpl-3.0
unknownworlds/decoda
libs/wxWidgets/src/univ/ctrlrend.cpp
8
16227
/////////////////////////////////////////////////////////////////////////////// // Name: src/univ/ctrlrend.cpp // Purpose: wxControlRenderer implementation // Author: Vadim Zeitlin // Modified by: // Created: 15.08.00 // RCS-ID: $Id: ctrlrend.cpp 42716 2006-10-30 12:33:25Z VS $ // Copyright: (c) 2000 SciTech Software, Inc. (www.scitechsoft.com) // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // =========================================================================== // declarations // =========================================================================== // --------------------------------------------------------------------------- // headers // --------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/app.h" #include "wx/control.h" #include "wx/checklst.h" #include "wx/listbox.h" #include "wx/scrolbar.h" #include "wx/dc.h" #include "wx/log.h" #include "wx/gauge.h" #include "wx/image.h" #endif // WX_PRECOMP #include "wx/univ/theme.h" #include "wx/univ/renderer.h" #include "wx/univ/colschem.h" // ============================================================================ // implementation // ============================================================================ wxRenderer::~wxRenderer() { } // ---------------------------------------------------------------------------- // wxControlRenderer // ---------------------------------------------------------------------------- wxControlRenderer::wxControlRenderer(wxWindow *window, wxDC& dc, wxRenderer *renderer) : m_dc(dc) { m_window = window; m_renderer = renderer; wxSize size = m_window->GetClientSize(); m_rect.x = m_rect.y = 0; m_rect.width = size.x; m_rect.height = size.y; } void wxControlRenderer::DrawLabel(const wxBitmap& bitmap, wxCoord marginX, wxCoord marginY) { m_dc.SetBackgroundMode(wxTRANSPARENT); m_dc.SetFont(m_window->GetFont()); m_dc.SetTextForeground(m_window->GetForegroundColour()); wxString label = m_window->GetLabel(); if ( !label.empty() || bitmap.Ok() ) { wxRect rectLabel = m_rect; if ( bitmap.Ok() ) { rectLabel.Inflate(-marginX, -marginY); } wxControl *ctrl = wxStaticCast(m_window, wxControl); m_renderer->DrawButtonLabel(m_dc, label, bitmap, rectLabel, m_window->GetStateFlags(), ctrl->GetAlignment(), ctrl->GetAccelIndex()); } } void wxControlRenderer::DrawFrame() { m_dc.SetFont(m_window->GetFont()); m_dc.SetTextForeground(m_window->GetForegroundColour()); m_dc.SetTextBackground(m_window->GetBackgroundColour()); wxControl *ctrl = wxStaticCast(m_window, wxControl); m_renderer->DrawFrame(m_dc, m_window->GetLabel(), m_rect, m_window->GetStateFlags(), ctrl->GetAlignment(), ctrl->GetAccelIndex()); } void wxControlRenderer::DrawButtonBorder() { int flags = m_window->GetStateFlags(); m_renderer->DrawButtonBorder(m_dc, m_rect, flags, &m_rect); // Why do this here? // m_renderer->DrawButtonSurface(m_dc, wxTHEME_BG_COLOUR(m_window), m_rect, flags ); } void wxControlRenderer::DrawBitmap(const wxBitmap& bitmap) { int style = m_window->GetWindowStyle(); DrawBitmap(m_dc, bitmap, m_rect, style & wxALIGN_MASK, style & wxBI_EXPAND ? wxEXPAND : wxSTRETCH_NOT); } /* static */ void wxControlRenderer::DrawBitmap(wxDC &dc, const wxBitmap& bitmap, const wxRect& rect, int alignment, wxStretch stretch) { // we may change the bitmap if we stretch it wxBitmap bmp = bitmap; if ( !bmp.Ok() ) return; int width = bmp.GetWidth(), height = bmp.GetHeight(); wxCoord x = 0, y = 0; if ( stretch & wxTILE ) { // tile the bitmap for ( ; x < rect.width; x += width ) { for ( y = 0; y < rect.height; y += height ) { // no need to use mask here as we cover the entire window area dc.DrawBitmap(bmp, x, y); } } } #if wxUSE_IMAGE else if ( stretch & wxEXPAND ) { // stretch bitmap to fill the entire control bmp = wxBitmap(wxImage(bmp.ConvertToImage()).Scale(rect.width, rect.height)); } #endif // wxUSE_IMAGE else // not stretched, not tiled { if ( alignment & wxALIGN_RIGHT ) { x = rect.GetRight() - width; } else if ( alignment & wxALIGN_CENTRE ) { x = (rect.GetLeft() + rect.GetRight() - width + 1) / 2; } else // alignment & wxALIGN_LEFT { x = rect.GetLeft(); } if ( alignment & wxALIGN_BOTTOM ) { y = rect.GetBottom() - height; } else if ( alignment & wxALIGN_CENTRE_VERTICAL ) { y = (rect.GetTop() + rect.GetBottom() - height + 1) / 2; } else // alignment & wxALIGN_TOP { y = rect.GetTop(); } } // do draw it dc.DrawBitmap(bmp, x, y, true /* use mask */); } #if wxUSE_SCROLLBAR void wxControlRenderer::DrawScrollbar(const wxScrollBar *scrollbar, int WXUNUSED(thumbPosOld)) { // we will only redraw the parts which must be redrawn and not everything wxRegion rgnUpdate = scrollbar->GetUpdateRegion(); { wxRect rectUpdate = rgnUpdate.GetBox(); wxLogTrace(_T("scrollbar"), _T("%s redraw: update box is (%d, %d)-(%d, %d)"), scrollbar->IsVertical() ? _T("vert") : _T("horz"), rectUpdate.GetLeft(), rectUpdate.GetTop(), rectUpdate.GetRight(), rectUpdate.GetBottom()); #if 0 //def WXDEBUG_SCROLLBAR static bool s_refreshDebug = false; if ( s_refreshDebug ) { wxClientDC dc(wxConstCast(scrollbar, wxScrollBar)); dc.SetBrush(*wxRED_BRUSH); dc.SetPen(*wxTRANSPARENT_PEN); dc.DrawRectangle(rectUpdate); // under Unix we use "--sync" X option for this #ifdef __WXMSW__ ::GdiFlush(); ::Sleep(200); #endif // __WXMSW__ } #endif // WXDEBUG_SCROLLBAR } wxOrientation orient = scrollbar->IsVertical() ? wxVERTICAL : wxHORIZONTAL; // the shaft for ( int nBar = 0; nBar < 2; nBar++ ) { wxScrollBar::Element elem = (wxScrollBar::Element)(wxScrollBar::Element_Bar_1 + nBar); wxRect rectBar = scrollbar->GetScrollbarRect(elem); if ( rgnUpdate.Contains(rectBar) ) { wxLogTrace(_T("scrollbar"), _T("drawing bar part %d at (%d, %d)-(%d, %d)"), nBar + 1, rectBar.GetLeft(), rectBar.GetTop(), rectBar.GetRight(), rectBar.GetBottom()); m_renderer->DrawScrollbarShaft(m_dc, orient, rectBar, scrollbar->GetState(elem)); } } // arrows for ( int nArrow = 0; nArrow < 2; nArrow++ ) { wxScrollBar::Element elem = (wxScrollBar::Element)(wxScrollBar::Element_Arrow_Line_1 + nArrow); wxRect rectArrow = scrollbar->GetScrollbarRect(elem); if ( rgnUpdate.Contains(rectArrow) ) { wxLogTrace(_T("scrollbar"), _T("drawing arrow %d at (%d, %d)-(%d, %d)"), nArrow + 1, rectArrow.GetLeft(), rectArrow.GetTop(), rectArrow.GetRight(), rectArrow.GetBottom()); scrollbar->GetArrows().DrawArrow ( (wxScrollArrows::Arrow)nArrow, m_dc, rectArrow, true // draw a scrollbar arrow, not just an arrow ); } } // TODO: support for page arrows // and the thumb wxScrollBar::Element elem = wxScrollBar::Element_Thumb; wxRect rectThumb = scrollbar->GetScrollbarRect(elem); if ( rectThumb.width && rectThumb.height && rgnUpdate.Contains(rectThumb) ) { wxLogTrace(_T("scrollbar"), _T("drawing thumb at (%d, %d)-(%d, %d)"), rectThumb.GetLeft(), rectThumb.GetTop(), rectThumb.GetRight(), rectThumb.GetBottom()); m_renderer->DrawScrollbarThumb(m_dc, orient, rectThumb, scrollbar->GetState(elem)); } } #endif // wxUSE_SCROLLBAR void wxControlRenderer::DrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2) { wxASSERT_MSG( x1 == x2 || y1 == y2, _T("line must be either horizontal or vertical") ); if ( x1 == x2 ) m_renderer->DrawVerticalLine(m_dc, x1, y1, y2); else // horizontal m_renderer->DrawHorizontalLine(m_dc, y1, x1, x2); } #if wxUSE_LISTBOX void wxControlRenderer::DrawItems(const wxListBox *lbox, size_t itemFirst, size_t itemLast) { DoDrawItems(lbox, itemFirst, itemLast); } void wxControlRenderer::DoDrawItems(const wxListBox *lbox, size_t itemFirst, size_t itemLast, #if wxUSE_CHECKLISTBOX bool isCheckLbox #else bool WXUNUSED(isCheckLbox) #endif ) { // prepare for the drawing: calc the initial position wxCoord lineHeight = lbox->GetLineHeight(); // note that SetClippingRegion() needs the physical (unscrolled) // coordinates while we use the logical (scrolled) ones for the drawing // itself wxRect rect; wxSize size = lbox->GetClientSize(); rect.width = size.x; rect.height = size.y; // keep the text inside the client rect or we will overwrite the vertical // scrollbar for the long strings m_dc.SetClippingRegion(rect.x, rect.y, rect.width + 1, rect.height + 1); // adjust the rect position now lbox->CalcScrolledPosition(rect.x, rect.y, &rect.x, &rect.y); rect.y += itemFirst*lineHeight; rect.height = lineHeight; // the rect should go to the right visible border so adjust the width if x // is shifted (rightmost point should stay the same) rect.width -= rect.x; // we'll keep the text colour unchanged m_dc.SetTextForeground(lbox->GetForegroundColour()); // an item should have the focused rect only when the lbox has focus, so // make sure that we never set wxCONTROL_FOCUSED flag if it doesn't int itemCurrent = wxWindow::FindFocus() == (wxWindow *)lbox // cast needed ? lbox->GetCurrentItem() : -1; for ( size_t n = itemFirst; n < itemLast; n++ ) { int flags = 0; if ( (int)n == itemCurrent ) flags |= wxCONTROL_FOCUSED; if ( lbox->IsSelected(n) ) flags |= wxCONTROL_SELECTED; #if wxUSE_CHECKLISTBOX if ( isCheckLbox ) { wxCheckListBox *checklstbox = wxStaticCast(lbox, wxCheckListBox); if ( checklstbox->IsChecked(n) ) flags |= wxCONTROL_CHECKED; m_renderer->DrawCheckItem(m_dc, lbox->GetString(n), wxNullBitmap, rect, flags); } else #endif // wxUSE_CHECKLISTBOX { m_renderer->DrawItem(m_dc, lbox->GetString(n), rect, flags); } rect.y += lineHeight; } } #endif // wxUSE_LISTBOX #if wxUSE_CHECKLISTBOX void wxControlRenderer::DrawCheckItems(const wxCheckListBox *lbox, size_t itemFirst, size_t itemLast) { DoDrawItems(lbox, itemFirst, itemLast, true); } #endif // wxUSE_CHECKLISTBOX #if wxUSE_GAUGE void wxControlRenderer::DrawProgressBar(const wxGauge *gauge) { // draw background m_dc.SetBrush(wxBrush(m_window->GetBackgroundColour(), wxSOLID)); m_dc.SetPen(*wxTRANSPARENT_PEN); m_dc.DrawRectangle(m_rect); int max = gauge->GetRange(); if ( !max ) { // nothing to draw return; } // calc the filled rect int pos = gauge->GetValue(); int left = max - pos; wxRect rect = m_rect; rect.Deflate(1); // FIXME this depends on the border width wxColour col = m_window->UseFgCol() ? m_window->GetForegroundColour() : wxTHEME_COLOUR(GAUGE); m_dc.SetBrush(wxBrush(col, wxSOLID)); if ( gauge->IsSmooth() ) { // just draw the rectangle in one go if ( gauge->IsVertical() ) { // vert bars grow from bottom to top wxCoord dy = ((rect.height - 1) * left) / max; rect.y += dy; rect.height -= dy; } else // horizontal { // grow from left to right rect.width -= ((rect.width - 1) * left) / max; } m_dc.DrawRectangle(rect); } else // discrete { wxSize sizeStep = m_renderer->GetProgressBarStep(); int step = gauge->IsVertical() ? sizeStep.y : sizeStep.x; // we divide by it below! wxCHECK_RET( step, _T("invalid wxGauge step") ); // round up to make the progress appear to start faster int lenTotal = gauge->IsVertical() ? rect.height : rect.width; int steps = ((lenTotal + step - 1) * pos) / (max * step); // calc the coords of one small rect wxCoord *px; wxCoord dx, dy; if ( gauge->IsVertical() ) { // draw from bottom to top: so first set y to the bottom rect.y += rect.height - 1; // then adjust the height rect.height = step; // and then adjust y again to be what it should for the first rect rect.y -= rect.height; // we are going up step = -step; // remember that this will be the coord which will change px = &rect.y; dy = 1; dx = 0; } else // horizontal { // don't leave 2 empty pixels in the beginning rect.x--; px = &rect.x; rect.width = step; dy = 0; dx = 1; } for ( int n = 0; n < steps; n++ ) { wxRect rectSegment = rect; rectSegment.Deflate(dx, dy); m_dc.DrawRectangle(rectSegment); *px += step; if ( *px < 1 ) { // this can only happen for the last step of vertical gauge rect.height = *px - step - 1; *px = 1; } else if ( *px > lenTotal - step ) { // this can only happen for the last step of horizontal gauge rect.width = lenTotal - *px - 1; } } } } #endif // wxUSE_GAUGE
gpl-3.0
cppisfun/GameEngine
foreign/boost/libs/locale/examples/wconversions.cpp
10
2934
// // Copyright (c) 2009-2011 Artyom Beilis (Tonkikh) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // // ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! // // BIG FAT WARNING FOR Microsoft Visual Studio Users // // YOU NEED TO CONVERT THIS SOURCE FILE ENCODING TO UTF-8 WITH BOM ENCODING. // // Unfortunately MSVC understands that the source code is encoded as // UTF-8 only if you add useless BOM in the beginning. // // So, before you compile "wide" examples with MSVC, please convert them to text // files with BOM. There are two very simple ways to do it: // // 1. Open file with Notepad and save it from there. It would convert // it to file with BOM. // 2. In Visual Studio go File->Advances Save Options... and select // Unicode (UTF-8 with signature) Codepage 65001 // // Note: once converted to UTF-8 with BOM, this source code would not // compile with other compilers, because no-one uses BOM with UTF-8 today // because it is absolutely meaningless in context of UTF-8. // // ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! // #include <boost/locale.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <iostream> #include <ctime> int main() { using namespace boost::locale; using namespace std; // Create system default locale generator gen; locale loc=gen(""); locale::global(loc); wcout.imbue(loc); // This is needed to prevent C library to // convert strings to narrow // instead of C++ on some platforms std::ios_base::sync_with_stdio(false); wcout<<L"Correct case conversion can't be done by simple, character by character conversion"<<endl; wcout<<L"because case conversion is context sensitive and not 1-to-1 conversion"<<endl; wcout<<L"For example:"<<endl; wcout<<L" German grüßen correctly converted to "<<to_upper(L"grüßen")<<L", instead of incorrect " <<boost::to_upper_copy(std::wstring(L"grüßen"))<<endl; wcout<<L" where ß is replaced with SS"<<endl; wcout<<L" Greek ὈΔΥΣΣΕΎΣ is correctly converted to "<<to_lower(L"ὈΔΥΣΣΕΎΣ")<<L", instead of incorrect " <<boost::to_lower_copy(std::wstring(L"ὈΔΥΣΣΕΎΣ"))<<endl; wcout<<L" where Σ is converted to σ or to ς, according to position in the word"<<endl; wcout<<L"Such type of conversion just can't be done using std::toupper that work on character base, also std::toupper is "<<endl; wcout<<L"not fully applicable when working with variable character length like in UTF-8 or UTF-16 limiting the correct "<<endl; wcout<<L"behavoir to BMP or ASCII only"<<endl; } // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 // boostinspect:noascii
gpl-3.0
Entropy-Soldier/ges-legacy-code
game/sdk/server/hl2/weapon_ar1.cpp
11
3494
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "basehlcombatweapon.h" #include "NPCevent.h" #include "basecombatcharacter.h" #include "AI_BaseNPC.h" #include "player.h" #include "in_buttons.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define DAMAGE_PER_SECOND 10 #define MAX_SETTINGS 5 float RateOfFire[ MAX_SETTINGS ] = { 0.1, 0.2, 0.5, 0.7, 1.0, }; float Damage[ MAX_SETTINGS ] = { 2, 4, 10, 14, 20, }; //========================================================= //========================================================= class CWeaponAR1 : public CHLMachineGun { DECLARE_DATADESC(); public: DECLARE_CLASS( CWeaponAR1, CHLMachineGun ); DECLARE_SERVERCLASS(); CWeaponAR1(); int m_ROF; void Precache( void ); bool Deploy( void ); float GetFireRate( void ) {return RateOfFire[ m_ROF ];} int CapabilitiesGet( void ) { return bits_CAP_WEAPON_RANGE_ATTACK1; } void SecondaryAttack( void ); virtual void FireBullets( const FireBulletsInfo_t &info ); virtual const Vector& GetBulletSpread( void ) { static const Vector cone = VECTOR_CONE_10DEGREES; return cone; } void Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator ) { switch( pEvent->event ) { case EVENT_WEAPON_AR1: { Vector vecShootOrigin, vecShootDir; vecShootOrigin = pOperator->Weapon_ShootPosition( ); CAI_BaseNPC *npc = pOperator->MyNPCPointer(); ASSERT( npc != NULL ); vecShootDir = npc->GetActualShootTrajectory( vecShootOrigin ); WeaponSound(SINGLE_NPC); pOperator->FireBullets( 1, vecShootOrigin, vecShootDir, VECTOR_CONE_PRECALCULATED, MAX_TRACE_LENGTH, m_iPrimaryAmmoType, 2 ); pOperator->DoMuzzleFlash(); } break; default: CBaseCombatWeapon::Operator_HandleAnimEvent( pEvent, pOperator ); break; } } DECLARE_ACTTABLE(); }; IMPLEMENT_SERVERCLASS_ST(CWeaponAR1, DT_WeaponAR1) END_SEND_TABLE() LINK_ENTITY_TO_CLASS( weapon_ar1, CWeaponAR1 ); PRECACHE_WEAPON_REGISTER(weapon_ar1); acttable_t CWeaponAR1::m_acttable[] = { { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_AR1, true }, }; IMPLEMENT_ACTTABLE(CWeaponAR1); //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CWeaponAR1 ) DEFINE_FIELD( m_ROF, FIELD_INTEGER ), END_DATADESC() CWeaponAR1::CWeaponAR1( ) { m_ROF = 0; } void CWeaponAR1::Precache( void ) { BaseClass::Precache(); } bool CWeaponAR1::Deploy( void ) { //CBaseCombatCharacter *pOwner = m_hOwner; return BaseClass::Deploy(); } //========================================================= //========================================================= void CWeaponAR1::FireBullets( const FireBulletsInfo_t &info ) { if(CBasePlayer *pPlayer = ToBasePlayer( GetOwner() )) { pPlayer->FireBullets( info ); } } void CWeaponAR1::SecondaryAttack( void ) { CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( pPlayer ) { pPlayer->m_nButtons &= ~IN_ATTACK2; } m_flNextSecondaryAttack = gpGlobals->curtime + 0.1; m_ROF += 1; if( m_ROF == MAX_SETTINGS ) { m_ROF = 0; } int i; Msg( "\n" ); for( i = 0 ; i < MAX_SETTINGS ; i++ ) { if( i == m_ROF ) { Msg( "|" ); } else { Msg( "-" ); } } Msg( "\n" ); }
gpl-3.0
k0nane/R915_kernel_GB
Kernel/drivers/gpu_atlas/pvr/sgx/sgxinit.c
11
76245
/********************************************************************** * * Copyright(c) 2008 Imagination Technologies Ltd. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful but, except * as otherwise stated in writing, 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 St - Fifth Floor, Boston, MA 02110-1301 USA. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". * * Contact Information: * Imagination Technologies Ltd. <gpl-support@imgtec.com> * Home Park Estate, Kings Langley, Herts, WD4 8LZ, UK * ******************************************************************************/ #include <stddef.h> #include "sgxdefs.h" #include "sgxmmu.h" #include "services_headers.h" #include "buffer_manager.h" #include "sgxapi_km.h" #include "sgxinfo.h" #include "sgx_mkif_km.h" #include "sgxconfig.h" #include "sysconfig.h" #include "pvr_bridge_km.h" #include "sgx_bridge_km.h" #include "pdump_km.h" #include "ra.h" #include "mmu.h" #include "handle.h" #include "perproc.h" #include "sgxutils.h" #include "pvrversion.h" #include "sgx_options.h" #include "lists.h" #include "srvkm.h" #define VAR(x) #x #define CHECK_SIZE(NAME) \ { \ if (psSGXStructSizes->ui32Sizeof_##NAME != psDevInfo->sSGXStructSizes.ui32Sizeof_##NAME) \ { \ PVR_DPF((PVR_DBG_ERROR, "SGXDevInitCompatCheck: Size check failed for SGXMKIF_%s (client) = %d bytes, (ukernel) = %d bytes\n", \ VAR(NAME), \ psDevInfo->sSGXStructSizes.ui32Sizeof_##NAME, \ psSGXStructSizes->ui32Sizeof_##NAME )); \ bStructSizesFailed = IMG_TRUE; \ } \ } #if defined (SYS_USING_INTERRUPTS) IMG_BOOL SGX_ISRHandler(IMG_VOID *pvData); #endif static PVRSRV_ERROR SGXGetMiscInfoUkernel(PVRSRV_SGXDEV_INFO *psDevInfo, PVRSRV_DEVICE_NODE *psDeviceNode); #if defined(PDUMP) static PVRSRV_ERROR SGXResetPDump(PVRSRV_DEVICE_NODE *psDeviceNode); #endif static IMG_VOID SGXCommandComplete(PVRSRV_DEVICE_NODE *psDeviceNode) { #if defined(OS_SUPPORTS_IN_LISR) if (OSInLISR(psDeviceNode->psSysData)) { psDeviceNode->bReProcessDeviceCommandComplete = IMG_TRUE; } else { SGXScheduleProcessQueuesKM(psDeviceNode); } #else SGXScheduleProcessQueuesKM(psDeviceNode); #endif } static IMG_UINT32 DeinitDevInfo(PVRSRV_SGXDEV_INFO *psDevInfo) { if (psDevInfo->psKernelCCBInfo != IMG_NULL) { OSFreeMem(PVRSRV_OS_PAGEABLE_HEAP, sizeof(PVRSRV_SGX_CCB_INFO), psDevInfo->psKernelCCBInfo, IMG_NULL); } return PVRSRV_OK; } static PVRSRV_ERROR InitDevInfo(PVRSRV_PER_PROCESS_DATA *psPerProc, PVRSRV_DEVICE_NODE *psDeviceNode, SGX_BRIDGE_INIT_INFO *psInitInfo) { PVRSRV_SGXDEV_INFO *psDevInfo = (PVRSRV_SGXDEV_INFO *)psDeviceNode->pvDevice; PVRSRV_ERROR eError; PVRSRV_SGX_CCB_INFO *psKernelCCBInfo = IMG_NULL; PVR_UNREFERENCED_PARAMETER(psPerProc); psDevInfo->sScripts = psInitInfo->sScripts; psDevInfo->psKernelCCBMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelCCBMemInfo; psDevInfo->psKernelCCB = (PVRSRV_SGX_KERNEL_CCB *) psDevInfo->psKernelCCBMemInfo->pvLinAddrKM; psDevInfo->psKernelCCBCtlMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelCCBCtlMemInfo; psDevInfo->psKernelCCBCtl = (PVRSRV_SGX_CCB_CTL *) psDevInfo->psKernelCCBCtlMemInfo->pvLinAddrKM; psDevInfo->psKernelCCBEventKickerMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelCCBEventKickerMemInfo; psDevInfo->pui32KernelCCBEventKicker = (IMG_UINT32 *)psDevInfo->psKernelCCBEventKickerMemInfo->pvLinAddrKM; psDevInfo->psKernelSGXHostCtlMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelSGXHostCtlMemInfo; psDevInfo->psSGXHostCtl = (SGXMKIF_HOST_CTL *)psDevInfo->psKernelSGXHostCtlMemInfo->pvLinAddrKM; psDevInfo->psKernelSGXTA3DCtlMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelSGXTA3DCtlMemInfo; psDevInfo->psKernelSGXMiscMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelSGXMiscMemInfo; #if defined(SGX_SUPPORT_HWPROFILING) psDevInfo->psKernelHWProfilingMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelHWProfilingMemInfo; #endif #if defined(SUPPORT_SGX_HWPERF) psDevInfo->psKernelHWPerfCBMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelHWPerfCBMemInfo; #endif psDevInfo->psKernelTASigBufferMemInfo = psInitInfo->hKernelTASigBufferMemInfo; psDevInfo->psKernel3DSigBufferMemInfo = psInitInfo->hKernel3DSigBufferMemInfo; #if defined(FIX_HW_BRN_29702) psDevInfo->psKernelCFIMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelCFIMemInfo; #endif #if defined(FIX_HW_BRN_29823) psDevInfo->psKernelDummyTermStreamMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelDummyTermStreamMemInfo; #endif #if defined(PVRSRV_USSE_EDM_STATUS_DEBUG) psDevInfo->psKernelEDMStatusBufferMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelEDMStatusBufferMemInfo; #endif #if defined(SGX_FEATURE_OVERLAPPED_SPM) psDevInfo->psKernelTmpRgnHeaderMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelTmpRgnHeaderMemInfo; #endif #if defined(SGX_FEATURE_SPM_MODE_0) psDevInfo->psKernelTmpDPMStateMemInfo = (PVRSRV_KERNEL_MEM_INFO *)psInitInfo->hKernelTmpDPMStateMemInfo; #endif psDevInfo->ui32ClientBuildOptions = psInitInfo->ui32ClientBuildOptions; psDevInfo->sSGXStructSizes = psInitInfo->sSGXStructSizes; eError = OSAllocMem(PVRSRV_OS_PAGEABLE_HEAP, sizeof(PVRSRV_SGX_CCB_INFO), (IMG_VOID **)&psKernelCCBInfo, 0, "SGX Circular Command Buffer Info"); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"InitDevInfo: Failed to alloc memory")); goto failed_allockernelccb; } OSMemSet(psKernelCCBInfo, 0, sizeof(PVRSRV_SGX_CCB_INFO)); psKernelCCBInfo->psCCBMemInfo = psDevInfo->psKernelCCBMemInfo; psKernelCCBInfo->psCCBCtlMemInfo = psDevInfo->psKernelCCBCtlMemInfo; psKernelCCBInfo->psCommands = psDevInfo->psKernelCCB->asCommands; psKernelCCBInfo->pui32WriteOffset = &psDevInfo->psKernelCCBCtl->ui32WriteOffset; psKernelCCBInfo->pui32ReadOffset = &psDevInfo->psKernelCCBCtl->ui32ReadOffset; psDevInfo->psKernelCCBInfo = psKernelCCBInfo; OSMemCopy(psDevInfo->aui32HostKickAddr, psInitInfo->aui32HostKickAddr, SGXMKIF_CMD_MAX * sizeof(psDevInfo->aui32HostKickAddr[0])); psDevInfo->bForcePTOff = IMG_FALSE; psDevInfo->ui32CacheControl = psInitInfo->ui32CacheControl; psDevInfo->ui32EDMTaskReg0 = psInitInfo->ui32EDMTaskReg0; psDevInfo->ui32EDMTaskReg1 = psInitInfo->ui32EDMTaskReg1; psDevInfo->ui32ClkGateStatusReg = psInitInfo->ui32ClkGateStatusReg; psDevInfo->ui32ClkGateStatusMask = psInitInfo->ui32ClkGateStatusMask; #if defined(SGX_FEATURE_MP) psDevInfo->ui32MasterClkGateStatusReg = psInitInfo->ui32MasterClkGateStatusReg; psDevInfo->ui32MasterClkGateStatusMask = psInitInfo->ui32MasterClkGateStatusMask; psDevInfo->ui32MasterClkGateStatus2Reg = psInitInfo->ui32MasterClkGateStatus2Reg; psDevInfo->ui32MasterClkGateStatus2Mask = psInitInfo->ui32MasterClkGateStatus2Mask; #endif OSMemCopy(&psDevInfo->asSGXDevData, &psInitInfo->asInitDevData, sizeof(psDevInfo->asSGXDevData)); return PVRSRV_OK; failed_allockernelccb: DeinitDevInfo(psDevInfo); return eError; } static PVRSRV_ERROR SGXRunScript(PVRSRV_SGXDEV_INFO *psDevInfo, SGX_INIT_COMMAND *psScript, IMG_UINT32 ui32NumInitCommands) { IMG_UINT32 ui32PC; SGX_INIT_COMMAND *psComm; for (ui32PC = 0, psComm = psScript; ui32PC < ui32NumInitCommands; ui32PC++, psComm++) { switch (psComm->eOp) { case SGX_INIT_OP_WRITE_HW_REG: { OSWriteHWReg(psDevInfo->pvRegsBaseKM, psComm->sWriteHWReg.ui32Offset, psComm->sWriteHWReg.ui32Value); PDUMPCOMMENT("SGXRunScript: Write HW reg operation"); PDUMPREG(SGX_PDUMPREG_NAME, psComm->sWriteHWReg.ui32Offset, psComm->sWriteHWReg.ui32Value); break; } #if defined(PDUMP) case SGX_INIT_OP_PDUMP_HW_REG: { PDUMPCOMMENT("SGXRunScript: Dump HW reg operation"); PDUMPREG(SGX_PDUMPREG_NAME, psComm->sPDumpHWReg.ui32Offset, psComm->sPDumpHWReg.ui32Value); break; } #endif case SGX_INIT_OP_HALT: { return PVRSRV_OK; } case SGX_INIT_OP_ILLEGAL: default: { PVR_DPF((PVR_DBG_ERROR,"SGXRunScript: PC %d: Illegal command: %d", ui32PC, psComm->eOp)); return PVRSRV_ERROR_UNKNOWN_SCRIPT_OPERATION; } } } return PVRSRV_ERROR_UNKNOWN_SCRIPT_OPERATION; } PVRSRV_ERROR SGXInitialise(PVRSRV_SGXDEV_INFO *psDevInfo, IMG_BOOL bHardwareRecovery) { PVRSRV_ERROR eError; PVRSRV_KERNEL_MEM_INFO *psSGXHostCtlMemInfo = psDevInfo->psKernelSGXHostCtlMemInfo; SGXMKIF_HOST_CTL *psSGXHostCtl = psSGXHostCtlMemInfo->pvLinAddrKM; static IMG_BOOL bFirstTime = IMG_TRUE; #if defined(PDUMP) IMG_BOOL bPDumpIsSuspended = PDumpIsSuspended(); #endif PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "SGX initialisation script part 1\n"); eError = SGXRunScript(psDevInfo, psDevInfo->sScripts.asInitCommandsPart1, SGX_MAX_INIT_COMMANDS); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"SGXInitialise: SGXRunScript (part 1) failed (%d)", eError)); return eError; } PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "End of SGX initialisation script part 1\n"); SGXReset(psDevInfo, bFirstTime || bHardwareRecovery, PDUMP_FLAGS_CONTINUOUS); #if defined(EUR_CR_POWER) #if defined(SGX531) OSWriteHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_POWER, 1); PDUMPREG(SGX_PDUMPREG_NAME, EUR_CR_POWER, 1); #else OSWriteHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_POWER, 0); PDUMPREG(SGX_PDUMPREG_NAME, EUR_CR_POWER, 0); #endif #endif *psDevInfo->pui32KernelCCBEventKicker = 0; #if defined(PDUMP) if (!bPDumpIsSuspended) { psDevInfo->ui32KernelCCBEventKickerDumpVal = 0; PDUMPMEM(&psDevInfo->ui32KernelCCBEventKickerDumpVal, psDevInfo->psKernelCCBEventKickerMemInfo, 0, sizeof(*psDevInfo->pui32KernelCCBEventKicker), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psDevInfo->psKernelCCBEventKickerMemInfo)); } #endif PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "SGX initialisation script part 2\n"); eError = SGXRunScript(psDevInfo, psDevInfo->sScripts.asInitCommandsPart2, SGX_MAX_INIT_COMMANDS); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"SGXInitialise: SGXRunScript (part 2) failed (%d)", eError)); return eError; } PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "End of SGX initialisation script part 2\n"); psSGXHostCtl->ui32HostClock = OSClockus(); psSGXHostCtl->ui32InitStatus = 0; #if defined(PDUMP) PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "Reset the SGX microkernel initialisation status\n"); PDUMPMEM(IMG_NULL, psSGXHostCtlMemInfo, offsetof(SGXMKIF_HOST_CTL, ui32InitStatus), sizeof(IMG_UINT32), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psSGXHostCtlMemInfo)); PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "Initialise the microkernel\n"); #endif #if defined(SGX_FEATURE_MULTI_EVENT_KICK) OSWriteMemoryBarrier(); OSWriteHWReg(psDevInfo->pvRegsBaseKM, SGX_MP_CORE_SELECT(EUR_CR_EVENT_KICK2, 0), EUR_CR_EVENT_KICK2_NOW_MASK); #else *psDevInfo->pui32KernelCCBEventKicker = (*psDevInfo->pui32KernelCCBEventKicker + 1) & 0xFF; OSWriteMemoryBarrier(); OSWriteHWReg(psDevInfo->pvRegsBaseKM, SGX_MP_CORE_SELECT(EUR_CR_EVENT_KICK, 0), EUR_CR_EVENT_KICK_NOW_MASK); #endif OSMemoryBarrier(); #if defined(PDUMP) if (!bPDumpIsSuspended) { #if defined(SGX_FEATURE_MULTI_EVENT_KICK) PDUMPREG(SGX_PDUMPREG_NAME, SGX_MP_CORE_SELECT(EUR_CR_EVENT_KICK2, 0), EUR_CR_EVENT_KICK2_NOW_MASK); #else psDevInfo->ui32KernelCCBEventKickerDumpVal = 1; PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "First increment of the SGX event kicker value\n"); PDUMPMEM(&psDevInfo->ui32KernelCCBEventKickerDumpVal, psDevInfo->psKernelCCBEventKickerMemInfo, 0, sizeof(IMG_UINT32), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psDevInfo->psKernelCCBEventKickerMemInfo)); PDUMPREG(SGX_PDUMPREG_NAME, SGX_MP_CORE_SELECT(EUR_CR_EVENT_KICK, 0), EUR_CR_EVENT_KICK_NOW_MASK); #endif } #endif #if !defined(NO_HARDWARE) if (PollForValueKM(&psSGXHostCtl->ui32InitStatus, PVRSRV_USSE_EDM_INIT_COMPLETE, PVRSRV_USSE_EDM_INIT_COMPLETE, MAX_HW_TIME_US, MAX_HW_TIME_US/WAIT_TRY_COUNT, IMG_FALSE) != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR, "SGXInitialise: Wait for uKernel initialisation failed")); #if !defined(FIX_HW_BRN_23281) PVR_DBG_BREAK; #endif return PVRSRV_ERROR_RETRY; } #endif #if defined(PDUMP) PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "Wait for the SGX microkernel initialisation to complete"); PDUMPMEMPOL(psSGXHostCtlMemInfo, offsetof(SGXMKIF_HOST_CTL, ui32InitStatus), PVRSRV_USSE_EDM_INIT_COMPLETE, PVRSRV_USSE_EDM_INIT_COMPLETE, PDUMP_POLL_OPERATOR_EQUAL, PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psSGXHostCtlMemInfo)); #endif #if defined(FIX_HW_BRN_22997) && defined(FIX_HW_BRN_23030) && defined(SGX_FEATURE_HOST_PORT) WorkaroundBRN22997ReadHostPort(psDevInfo); #endif PVR_ASSERT(psDevInfo->psKernelCCBCtl->ui32ReadOffset == psDevInfo->psKernelCCBCtl->ui32WriteOffset); bFirstTime = IMG_FALSE; return PVRSRV_OK; } PVRSRV_ERROR SGXDeinitialise(IMG_HANDLE hDevCookie) { PVRSRV_SGXDEV_INFO *psDevInfo = (PVRSRV_SGXDEV_INFO *) hDevCookie; PVRSRV_ERROR eError; if (psDevInfo->pvRegsBaseKM == IMG_NULL) { return PVRSRV_OK; } eError = SGXRunScript(psDevInfo, psDevInfo->sScripts.asDeinitCommands, SGX_MAX_DEINIT_COMMANDS); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"SGXDeinitialise: SGXRunScript failed (%d)", eError)); return eError; } return PVRSRV_OK; } static PVRSRV_ERROR DevInitSGXPart1 (IMG_VOID *pvDeviceNode) { IMG_HANDLE hDevMemHeap = IMG_NULL; PVRSRV_SGXDEV_INFO *psDevInfo; IMG_HANDLE hKernelDevMemContext; IMG_DEV_PHYADDR sPDDevPAddr; IMG_UINT32 i; PVRSRV_DEVICE_NODE *psDeviceNode = (PVRSRV_DEVICE_NODE *)pvDeviceNode; DEVICE_MEMORY_HEAP_INFO *psDeviceMemoryHeap = psDeviceNode->sDevMemoryInfo.psDeviceMemoryHeap; PVRSRV_ERROR eError; PDUMPCOMMENT("SGX Core Version Information: %s", SGX_CORE_FRIENDLY_NAME); #if defined(SGX_FEATURE_MP) PDUMPCOMMENT("SGX Multi-processor: %d cores", SGX_FEATURE_MP_CORE_COUNT); #endif #if (SGX_CORE_REV == 0) PDUMPCOMMENT("SGX Core Revision Information: head RTL"); #else PDUMPCOMMENT("SGX Core Revision Information: %d", SGX_CORE_REV); #endif #if defined(SGX_FEATURE_SYSTEM_CACHE) PDUMPCOMMENT("SGX System Level Cache is present\r\n"); #if defined(SGX_BYPASS_SYSTEM_CACHE) PDUMPCOMMENT("SGX System Level Cache is bypassed\r\n"); #endif #endif PDUMPCOMMENT("SGX Initialisation Part 1"); if(OSAllocMem( PVRSRV_OS_NON_PAGEABLE_HEAP, sizeof(PVRSRV_SGXDEV_INFO), (IMG_VOID **)&psDevInfo, IMG_NULL, "SGX Device Info") != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevInitSGXPart1 : Failed to alloc memory for DevInfo")); return (PVRSRV_ERROR_OUT_OF_MEMORY); } OSMemSet (psDevInfo, 0, sizeof(PVRSRV_SGXDEV_INFO)); psDevInfo->eDeviceType = DEV_DEVICE_TYPE; psDevInfo->eDeviceClass = DEV_DEVICE_CLASS; psDeviceNode->pvDevice = (IMG_PVOID)psDevInfo; psDevInfo->pvDeviceMemoryHeap = (IMG_VOID*)psDeviceMemoryHeap; hKernelDevMemContext = BM_CreateContext(psDeviceNode, &sPDDevPAddr, IMG_NULL, IMG_NULL); if (hKernelDevMemContext == IMG_NULL) { PVR_DPF((PVR_DBG_ERROR,"DevInitSGXPart1: Failed BM_CreateContext")); return PVRSRV_ERROR_OUT_OF_MEMORY; } psDevInfo->sKernelPDDevPAddr = sPDDevPAddr; for(i=0; i<psDeviceNode->sDevMemoryInfo.ui32HeapCount; i++) { switch(psDeviceMemoryHeap[i].DevMemHeapType) { case DEVICE_MEMORY_HEAP_KERNEL: case DEVICE_MEMORY_HEAP_SHARED: case DEVICE_MEMORY_HEAP_SHARED_EXPORTED: { hDevMemHeap = BM_CreateHeap (hKernelDevMemContext, &psDeviceMemoryHeap[i]); psDeviceMemoryHeap[i].hDevMemHeap = hDevMemHeap; break; } } } #if defined(PDUMP) if(hDevMemHeap) { psDevInfo->sMMUAttrib = *((BM_HEAP*)hDevMemHeap)->psMMUAttrib; } #endif eError = MMU_BIFResetPDAlloc(psDevInfo); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevInitSGX : Failed to alloc memory for BIF reset")); return eError; } return PVRSRV_OK; } IMG_EXPORT PVRSRV_ERROR SGXGetInfoForSrvinitKM(IMG_HANDLE hDevHandle, SGX_BRIDGE_INFO_FOR_SRVINIT *psInitInfo) { PVRSRV_DEVICE_NODE *psDeviceNode; PVRSRV_SGXDEV_INFO *psDevInfo; PVRSRV_ERROR eError; PDUMPCOMMENT("SGXGetInfoForSrvinit"); psDeviceNode = (PVRSRV_DEVICE_NODE *)hDevHandle; psDevInfo = (PVRSRV_SGXDEV_INFO *)psDeviceNode->pvDevice; psInitInfo->sPDDevPAddr = psDevInfo->sKernelPDDevPAddr; eError = PVRSRVGetDeviceMemHeapsKM(hDevHandle, &psInitInfo->asHeapInfo[0]); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"SGXGetInfoForSrvinit: PVRSRVGetDeviceMemHeapsKM failed (%d)", eError)); return eError; } return eError; } IMG_EXPORT PVRSRV_ERROR DevInitSGXPart2KM (PVRSRV_PER_PROCESS_DATA *psPerProc, IMG_HANDLE hDevHandle, SGX_BRIDGE_INIT_INFO *psInitInfo) { PVRSRV_DEVICE_NODE *psDeviceNode; PVRSRV_SGXDEV_INFO *psDevInfo; PVRSRV_ERROR eError; SGX_DEVICE_MAP *psSGXDeviceMap; PVRSRV_DEV_POWER_STATE eDefaultPowerState; PDUMPCOMMENT("SGX Initialisation Part 2"); psDeviceNode = (PVRSRV_DEVICE_NODE *)hDevHandle; psDevInfo = (PVRSRV_SGXDEV_INFO *)psDeviceNode->pvDevice; eError = InitDevInfo(psPerProc, psDeviceNode, psInitInfo); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevInitSGXPart2KM: Failed to load EDM program")); goto failed_init_dev_info; } eError = SysGetDeviceMemoryMap(PVRSRV_DEVICE_TYPE_SGX, (IMG_VOID**)&psSGXDeviceMap); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevInitSGXPart2KM: Failed to get device memory map!")); return PVRSRV_ERROR_INIT_FAILURE; } if (psSGXDeviceMap->pvRegsCpuVBase) { psDevInfo->pvRegsBaseKM = psSGXDeviceMap->pvRegsCpuVBase; } else { psDevInfo->pvRegsBaseKM = OSMapPhysToLin(psSGXDeviceMap->sRegsCpuPBase, psSGXDeviceMap->ui32RegsSize, PVRSRV_HAP_KERNEL_ONLY|PVRSRV_HAP_UNCACHED, IMG_NULL); if (!psDevInfo->pvRegsBaseKM) { PVR_DPF((PVR_DBG_ERROR,"DevInitSGXPart2KM: Failed to map in regs\n")); return PVRSRV_ERROR_BAD_MAPPING; } } psDevInfo->ui32RegSize = psSGXDeviceMap->ui32RegsSize; psDevInfo->sRegsPhysBase = psSGXDeviceMap->sRegsSysPBase; #if defined(SGX_FEATURE_HOST_PORT) if (psSGXDeviceMap->ui32Flags & SGX_HOSTPORT_PRESENT) { psDevInfo->pvHostPortBaseKM = OSMapPhysToLin(psSGXDeviceMap->sHPCpuPBase, psSGXDeviceMap->ui32HPSize, PVRSRV_HAP_KERNEL_ONLY|PVRSRV_HAP_UNCACHED, IMG_NULL); if (!psDevInfo->pvHostPortBaseKM) { PVR_DPF((PVR_DBG_ERROR,"DevInitSGXPart2KM: Failed to map in host port\n")); return PVRSRV_ERROR_BAD_MAPPING; } psDevInfo->ui32HPSize = psSGXDeviceMap->ui32HPSize; psDevInfo->sHPSysPAddr = psSGXDeviceMap->sHPSysPBase; } #endif #if defined (SYS_USING_INTERRUPTS) psDeviceNode->pvISRData = psDeviceNode; PVR_ASSERT(psDeviceNode->pfnDeviceISR == SGX_ISRHandler); #endif psDevInfo->psSGXHostCtl->ui32PowerStatus |= PVRSRV_USSE_EDM_POWMAN_NO_WORK; eDefaultPowerState = PVRSRV_DEV_POWER_STATE_OFF; eError = PVRSRVRegisterPowerDevice (psDeviceNode->sDevId.ui32DeviceIndex, &SGXPrePowerState, &SGXPostPowerState, &SGXPreClockSpeedChange, &SGXPostClockSpeedChange, (IMG_HANDLE)psDeviceNode, PVRSRV_DEV_POWER_STATE_OFF, eDefaultPowerState); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevInitSGXPart2KM: failed to register device with power manager")); return eError; } #if defined(FIX_HW_BRN_22997) && defined(FIX_HW_BRN_23030) && defined(SGX_FEATURE_HOST_PORT) eError = WorkaroundBRN22997Alloc(psDeviceNode); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"SGXInitialise : Failed to alloc memory for BRN22997 workaround")); return eError; } #endif #if defined(SUPPORT_EXTERNAL_SYSTEM_CACHE) psDevInfo->ui32ExtSysCacheRegsSize = psSGXDeviceMap->ui32ExtSysCacheRegsSize; psDevInfo->sExtSysCacheRegsDevPBase = psSGXDeviceMap->sExtSysCacheRegsDevPBase; eError = MMU_MapExtSystemCacheRegs(psDeviceNode); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"SGXInitialise : Failed to map external system cache registers")); return eError; } #endif OSMemSet(psDevInfo->psKernelCCB, 0, sizeof(PVRSRV_SGX_KERNEL_CCB)); OSMemSet(psDevInfo->psKernelCCBCtl, 0, sizeof(PVRSRV_SGX_CCB_CTL)); OSMemSet(psDevInfo->pui32KernelCCBEventKicker, 0, sizeof(*psDevInfo->pui32KernelCCBEventKicker)); PDUMPCOMMENT("Initialise Kernel CCB"); PDUMPMEM(IMG_NULL, psDevInfo->psKernelCCBMemInfo, 0, sizeof(PVRSRV_SGX_KERNEL_CCB), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psDevInfo->psKernelCCBMemInfo)); PDUMPCOMMENT("Initialise Kernel CCB Control"); PDUMPMEM(IMG_NULL, psDevInfo->psKernelCCBCtlMemInfo, 0, sizeof(PVRSRV_SGX_CCB_CTL), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psDevInfo->psKernelCCBCtlMemInfo)); PDUMPCOMMENT("Initialise Kernel CCB Event Kicker"); PDUMPMEM(IMG_NULL, psDevInfo->psKernelCCBEventKickerMemInfo, 0, sizeof(*psDevInfo->pui32KernelCCBEventKicker), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psDevInfo->psKernelCCBEventKickerMemInfo)); return PVRSRV_OK; failed_init_dev_info: return eError; } static PVRSRV_ERROR DevDeInitSGX (IMG_VOID *pvDeviceNode) { PVRSRV_DEVICE_NODE *psDeviceNode = (PVRSRV_DEVICE_NODE *)pvDeviceNode; PVRSRV_SGXDEV_INFO *psDevInfo = (PVRSRV_SGXDEV_INFO*)psDeviceNode->pvDevice; PVRSRV_ERROR eError; IMG_UINT32 ui32Heap; DEVICE_MEMORY_HEAP_INFO *psDeviceMemoryHeap; SGX_DEVICE_MAP *psSGXDeviceMap; if (!psDevInfo) { PVR_DPF((PVR_DBG_ERROR,"DevDeInitSGX: Null DevInfo")); return PVRSRV_OK; } #if defined(SUPPORT_HW_RECOVERY) if (psDevInfo->hTimer) { eError = OSRemoveTimer(psDevInfo->hTimer); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevDeInitSGX: Failed to remove timer")); return eError; } psDevInfo->hTimer = IMG_NULL; } #endif #if defined(SUPPORT_EXTERNAL_SYSTEM_CACHE) eError = MMU_UnmapExtSystemCacheRegs(psDeviceNode); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevDeInitSGX: Failed to unmap ext system cache registers")); return eError; } #endif #if defined(FIX_HW_BRN_22997) && defined(FIX_HW_BRN_23030) && defined(SGX_FEATURE_HOST_PORT) WorkaroundBRN22997Free(psDeviceNode); #endif MMU_BIFResetPDFree(psDevInfo); DeinitDevInfo(psDevInfo); psDeviceMemoryHeap = (DEVICE_MEMORY_HEAP_INFO *)psDevInfo->pvDeviceMemoryHeap; for(ui32Heap=0; ui32Heap<psDeviceNode->sDevMemoryInfo.ui32HeapCount; ui32Heap++) { switch(psDeviceMemoryHeap[ui32Heap].DevMemHeapType) { case DEVICE_MEMORY_HEAP_KERNEL: case DEVICE_MEMORY_HEAP_SHARED: case DEVICE_MEMORY_HEAP_SHARED_EXPORTED: { if (psDeviceMemoryHeap[ui32Heap].hDevMemHeap != IMG_NULL) { BM_DestroyHeap(psDeviceMemoryHeap[ui32Heap].hDevMemHeap); } break; } } } eError = BM_DestroyContext(psDeviceNode->sDevMemoryInfo.pBMKernelContext, IMG_NULL); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevDeInitSGX : Failed to destroy kernel context")); return eError; } eError = PVRSRVRemovePowerDevice (((PVRSRV_DEVICE_NODE*)pvDeviceNode)->sDevId.ui32DeviceIndex); if (eError != PVRSRV_OK) { return eError; } eError = SysGetDeviceMemoryMap(PVRSRV_DEVICE_TYPE_SGX, (IMG_VOID**)&psSGXDeviceMap); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"DevDeInitSGX: Failed to get device memory map!")); return eError; } if (!psSGXDeviceMap->pvRegsCpuVBase) { if (psDevInfo->pvRegsBaseKM != IMG_NULL) { OSUnMapPhysToLin(psDevInfo->pvRegsBaseKM, psDevInfo->ui32RegSize, PVRSRV_HAP_KERNEL_ONLY|PVRSRV_HAP_UNCACHED, IMG_NULL); } } #if defined(SGX_FEATURE_HOST_PORT) if (psSGXDeviceMap->ui32Flags & SGX_HOSTPORT_PRESENT) { if (psDevInfo->pvHostPortBaseKM != IMG_NULL) { OSUnMapPhysToLin(psDevInfo->pvHostPortBaseKM, psDevInfo->ui32HPSize, PVRSRV_HAP_KERNEL_ONLY|PVRSRV_HAP_UNCACHED, IMG_NULL); } } #endif OSFreeMem(PVRSRV_OS_NON_PAGEABLE_HEAP, sizeof(PVRSRV_SGXDEV_INFO), psDevInfo, 0); psDeviceNode->pvDevice = IMG_NULL; if (psDeviceMemoryHeap != IMG_NULL) { OSFreeMem(PVRSRV_OS_PAGEABLE_HEAP, sizeof(DEVICE_MEMORY_HEAP_INFO) * SGX_MAX_HEAP_ID, psDeviceMemoryHeap, 0); } return PVRSRV_OK; } static IMG_VOID SGXDumpDebugReg (PVRSRV_SGXDEV_INFO *psDevInfo, IMG_UINT32 ui32CoreNum, IMG_CHAR *pszName, IMG_UINT32 ui32RegAddr) { IMG_UINT32 ui32RegVal; ui32RegVal = OSReadHWReg(psDevInfo->pvRegsBaseKM, SGX_MP_CORE_SELECT(ui32RegAddr, ui32CoreNum)); PVR_LOG(("(P%u) %s%08X", ui32CoreNum, pszName, ui32RegVal)); } static IMG_VOID SGXDumpDebugInfo (PVRSRV_SGXDEV_INFO *psDevInfo, IMG_BOOL bDumpSGXRegs) { IMG_UINT32 ui32CoreNum; PVR_LOG(("SGX debug (%s)", PVRVERSION_STRING)); if (bDumpSGXRegs) { PVR_DPF((PVR_DBG_ERROR,"SGX Register Base Address (Linear): 0x%08X", (IMG_UINTPTR_T)psDevInfo->pvRegsBaseKM)); PVR_DPF((PVR_DBG_ERROR,"SGX Register Base Address (Physical): 0x%08X", psDevInfo->sRegsPhysBase.uiAddr)); for (ui32CoreNum = 0; ui32CoreNum < SGX_FEATURE_MP_CORE_COUNT; ui32CoreNum++) { SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_EVENT_STATUS: ", EUR_CR_EVENT_STATUS); SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_EVENT_STATUS2: ", EUR_CR_EVENT_STATUS2); SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_BIF_CTRL: ", EUR_CR_BIF_CTRL); #if defined(EUR_CR_BIF_BANK0) SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_BIF_BANK0: ", EUR_CR_BIF_BANK0); #endif SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_BIF_INT_STAT: ", EUR_CR_BIF_INT_STAT); SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_BIF_FAULT: ", EUR_CR_BIF_FAULT); SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_BIF_MEM_REQ_STAT: ", EUR_CR_BIF_MEM_REQ_STAT); SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_CLKGATECTL: ", EUR_CR_CLKGATECTL); #if defined(EUR_CR_PDS_PC_BASE) SGXDumpDebugReg(psDevInfo, ui32CoreNum, "EUR_CR_PDS_PC_BASE: ", EUR_CR_PDS_PC_BASE); #endif } } QueueDumpDebugInfo(); { IMG_UINT32 *pui32HostCtlBuffer = (IMG_UINT32 *)psDevInfo->psSGXHostCtl; IMG_UINT32 ui32LoopCounter; PVR_LOG(("SGX Host control:")); for (ui32LoopCounter = 0; ui32LoopCounter < sizeof(*psDevInfo->psSGXHostCtl) / sizeof(*pui32HostCtlBuffer); ui32LoopCounter += 4) { PVR_LOG(("\t(HC-%X) 0x%08X 0x%08X 0x%08X 0x%08X", ui32LoopCounter * sizeof(*pui32HostCtlBuffer), pui32HostCtlBuffer[ui32LoopCounter + 0], pui32HostCtlBuffer[ui32LoopCounter + 1], pui32HostCtlBuffer[ui32LoopCounter + 2], pui32HostCtlBuffer[ui32LoopCounter + 3])); } } { IMG_UINT32 *pui32TA3DCtlBuffer = psDevInfo->psKernelSGXTA3DCtlMemInfo->pvLinAddrKM; IMG_UINT32 ui32LoopCounter; PVR_LOG(("SGX TA/3D control:")); for (ui32LoopCounter = 0; ui32LoopCounter < psDevInfo->psKernelSGXTA3DCtlMemInfo->ui32AllocSize / sizeof(*pui32TA3DCtlBuffer); ui32LoopCounter += 4) { PVR_LOG(("\t(T3C-%X) 0x%08X 0x%08X 0x%08X 0x%08X", ui32LoopCounter * sizeof(*pui32TA3DCtlBuffer), pui32TA3DCtlBuffer[ui32LoopCounter + 0], pui32TA3DCtlBuffer[ui32LoopCounter + 1], pui32TA3DCtlBuffer[ui32LoopCounter + 2], pui32TA3DCtlBuffer[ui32LoopCounter + 3])); } } #if defined(PVRSRV_USSE_EDM_STATUS_DEBUG) { IMG_UINT32 *pui32MKTraceBuffer = psDevInfo->psKernelEDMStatusBufferMemInfo->pvLinAddrKM; IMG_UINT32 ui32LastStatusCode, ui32WriteOffset; ui32LastStatusCode = *pui32MKTraceBuffer; pui32MKTraceBuffer++; ui32WriteOffset = *pui32MKTraceBuffer; pui32MKTraceBuffer++; PVR_LOG(("Last SGX microkernel status code: %08X", ui32LastStatusCode)); #if defined(PVRSRV_DUMP_MK_TRACE) { IMG_UINT32 ui32LoopCounter; for (ui32LoopCounter = 0; ui32LoopCounter < SGXMK_TRACE_BUFFER_SIZE; ui32LoopCounter++) { IMG_UINT32 *pui32BufPtr; pui32BufPtr = pui32MKTraceBuffer + (((ui32WriteOffset + ui32LoopCounter) % SGXMK_TRACE_BUFFER_SIZE) * 4); PVR_LOG(("\t(MKT-%X) %08X %08X %08X %08X", ui32LoopCounter, pui32BufPtr[2], pui32BufPtr[3], pui32BufPtr[1], pui32BufPtr[0])); } } #endif } #endif { PVR_LOG(("SGX Kernel CCB WO:0x%X RO:0x%X", psDevInfo->psKernelCCBCtl->ui32WriteOffset, psDevInfo->psKernelCCBCtl->ui32ReadOffset)); #if defined(PVRSRV_DUMP_KERNEL_CCB) { IMG_UINT32 ui32LoopCounter; for (ui32LoopCounter = 0; ui32LoopCounter < sizeof(psDevInfo->psKernelCCB->asCommands) / sizeof(psDevInfo->psKernelCCB->asCommands[0]); ui32LoopCounter++) { SGXMKIF_COMMAND *psCommand = &psDevInfo->psKernelCCB->asCommands[ui32LoopCounter]; PVR_LOG(("\t(KCCB-%X) %08X %08X - %08X %08X %08X %08X", ui32LoopCounter, psCommand->ui32ServiceAddress, psCommand->ui32CacheControl, psCommand->ui32Data[0], psCommand->ui32Data[1], psCommand->ui32Data[2], psCommand->ui32Data[3])); } } #endif } } #if defined(SYS_USING_INTERRUPTS) || defined(SUPPORT_HW_RECOVERY) static IMG_VOID HWRecoveryResetSGX (PVRSRV_DEVICE_NODE *psDeviceNode, IMG_UINT32 ui32Component, IMG_UINT32 ui32CallerID) { PVRSRV_ERROR eError; PVRSRV_SGXDEV_INFO *psDevInfo = (PVRSRV_SGXDEV_INFO*)psDeviceNode->pvDevice; SGXMKIF_HOST_CTL *psSGXHostCtl = (SGXMKIF_HOST_CTL *)psDevInfo->psSGXHostCtl; PVR_UNREFERENCED_PARAMETER(ui32Component); eError = PVRSRVPowerLock(ui32CallerID, IMG_FALSE); if(eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_WARNING,"HWRecoveryResetSGX: Power transition in progress")); return; } psSGXHostCtl->ui32InterruptClearFlags |= PVRSRV_USSE_EDM_INTERRUPT_HWR; PVR_LOG(("HWRecoveryResetSGX: SGX Hardware Recovery triggered")); SGXDumpDebugInfo(psDeviceNode->pvDevice, IMG_TRUE); PDUMPSUSPEND(); #if defined(FIX_HW_BRN_23281) for (eError = PVRSRV_ERROR_RETRY; eError == PVRSRV_ERROR_RETRY;) #endif { eError = SGXInitialise(psDevInfo, IMG_TRUE); } if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"HWRecoveryResetSGX: SGXInitialise failed (%d)", eError)); } PDUMPRESUME(); PVRSRVPowerUnlock(ui32CallerID); SGXScheduleProcessQueuesKM(psDeviceNode); PVRSRVProcessQueues(ui32CallerID, IMG_TRUE); } #endif #if defined(SUPPORT_HW_RECOVERY) IMG_VOID SGXOSTimer(IMG_VOID *pvData) { PVRSRV_DEVICE_NODE *psDeviceNode = pvData; PVRSRV_SGXDEV_INFO *psDevInfo = psDeviceNode->pvDevice; static IMG_UINT32 ui32EDMTasks = 0; static IMG_UINT32 ui32LockupCounter = 0; static IMG_UINT32 ui32NumResets = 0; #if defined(FIX_HW_BRN_31093) static IMG_BOOL bBRN31093Inval = IMG_FALSE; #endif IMG_UINT32 ui32CurrentEDMTasks; IMG_BOOL bLockup = IMG_FALSE; IMG_BOOL bPoweredDown; psDevInfo->ui32TimeStamp++; #if defined(NO_HARDWARE) bPoweredDown = IMG_TRUE; #else bPoweredDown = (SGXIsDevicePowered(psDeviceNode)) ? IMG_FALSE : IMG_TRUE; #endif if (bPoweredDown) { ui32LockupCounter = 0; #if defined(FIX_HW_BRN_31093) bBRN31093Inval = IMG_FALSE; #endif } else { ui32CurrentEDMTasks = OSReadHWReg(psDevInfo->pvRegsBaseKM, psDevInfo->ui32EDMTaskReg0); if (psDevInfo->ui32EDMTaskReg1 != 0) { ui32CurrentEDMTasks ^= OSReadHWReg(psDevInfo->pvRegsBaseKM, psDevInfo->ui32EDMTaskReg1); } if ((ui32CurrentEDMTasks == ui32EDMTasks) && (psDevInfo->ui32NumResets == ui32NumResets)) { ui32LockupCounter++; if (ui32LockupCounter == 3) { ui32LockupCounter = 0; #if defined(FIX_HW_BRN_31093) if (bBRN31093Inval == IMG_FALSE) { #if defined(FIX_HW_BRN_29997) IMG_UINT32 ui32BIFCtrl; ui32BIFCtrl = OSReadHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_BIF_CTRL); OSWriteHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_BIF_CTRL, ui32BIFCtrl | EUR_CR_BIF_CTRL_PAUSE_MASK); OSWaitus(200 * 1000000 / psDevInfo->ui32CoreClockSpeed); #endif bBRN31093Inval = IMG_TRUE; OSWriteHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_BIF_CTRL_INVAL, EUR_CR_BIF_CTRL_INVAL_PTE_MASK); OSWaitus(200 * 1000000 / psDevInfo->ui32CoreClockSpeed); #if defined(FIX_HW_BRN_29997) OSWriteHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_BIF_CTRL, ui32BIFCtrl); #endif } else #endif { PVR_DPF((PVR_DBG_ERROR, "SGXOSTimer() detected SGX lockup (0x%x tasks)", ui32EDMTasks)); bLockup = IMG_TRUE; } } } else { #if defined(FIX_HW_BRN_31093) bBRN31093Inval = IMG_FALSE; #endif ui32LockupCounter = 0; ui32EDMTasks = ui32CurrentEDMTasks; ui32NumResets = psDevInfo->ui32NumResets; } } if (bLockup) { SGXMKIF_HOST_CTL *psSGXHostCtl = (SGXMKIF_HOST_CTL *)psDevInfo->psSGXHostCtl; psSGXHostCtl->ui32HostDetectedLockups ++; HWRecoveryResetSGX(psDeviceNode, 0, KERNEL_ID); } } #endif #if defined(SYS_USING_INTERRUPTS) IMG_BOOL SGX_ISRHandler (IMG_VOID *pvData) { IMG_BOOL bInterruptProcessed = IMG_FALSE; { IMG_UINT32 ui32EventStatus, ui32EventEnable; IMG_UINT32 ui32EventClear = 0; #if defined(SGX_FEATURE_DATA_BREAKPOINTS) IMG_UINT32 ui32EventStatus2, ui32EventEnable2; #endif IMG_UINT32 ui32EventClear2 = 0; PVRSRV_DEVICE_NODE *psDeviceNode; PVRSRV_SGXDEV_INFO *psDevInfo; if(pvData == IMG_NULL) { PVR_DPF((PVR_DBG_ERROR, "SGX_ISRHandler: Invalid params\n")); return bInterruptProcessed; } psDeviceNode = (PVRSRV_DEVICE_NODE *)pvData; psDevInfo = (PVRSRV_SGXDEV_INFO *)psDeviceNode->pvDevice; ui32EventStatus = OSReadHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_EVENT_STATUS); ui32EventEnable = OSReadHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_EVENT_HOST_ENABLE); ui32EventStatus &= ui32EventEnable; #if defined(SGX_FEATURE_DATA_BREAKPOINTS) ui32EventStatus2 = OSReadHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_EVENT_STATUS2); ui32EventEnable2 = OSReadHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_EVENT_HOST_ENABLE2); ui32EventStatus2 &= ui32EventEnable2; #endif if (ui32EventStatus & EUR_CR_EVENT_STATUS_SW_EVENT_MASK) { ui32EventClear |= EUR_CR_EVENT_HOST_CLEAR_SW_EVENT_MASK; } #if defined(SGX_FEATURE_DATA_BREAKPOINTS) if (ui32EventStatus2 & EUR_CR_EVENT_STATUS2_DATA_BREAKPOINT_UNTRAPPED_MASK) { ui32EventClear2 |= EUR_CR_EVENT_HOST_CLEAR2_DATA_BREAKPOINT_UNTRAPPED_MASK; } if (ui32EventStatus2 & EUR_CR_EVENT_STATUS2_DATA_BREAKPOINT_TRAPPED_MASK) { ui32EventClear2 |= EUR_CR_EVENT_HOST_CLEAR2_DATA_BREAKPOINT_TRAPPED_MASK; } #endif if (ui32EventClear || ui32EventClear2) { bInterruptProcessed = IMG_TRUE; ui32EventClear |= EUR_CR_EVENT_HOST_CLEAR_MASTER_INTERRUPT_MASK; OSWriteHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_EVENT_HOST_CLEAR, ui32EventClear); OSWriteHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_EVENT_HOST_CLEAR2, ui32EventClear2); } } return bInterruptProcessed; } static IMG_VOID SGX_MISRHandler (IMG_VOID *pvData) { PVRSRV_DEVICE_NODE *psDeviceNode = (PVRSRV_DEVICE_NODE *)pvData; PVRSRV_SGXDEV_INFO *psDevInfo = (PVRSRV_SGXDEV_INFO*)psDeviceNode->pvDevice; SGXMKIF_HOST_CTL *psSGXHostCtl = (SGXMKIF_HOST_CTL *)psDevInfo->psSGXHostCtl; if (((psSGXHostCtl->ui32InterruptFlags & PVRSRV_USSE_EDM_INTERRUPT_HWR) != 0UL) && ((psSGXHostCtl->ui32InterruptClearFlags & PVRSRV_USSE_EDM_INTERRUPT_HWR) == 0UL)) { HWRecoveryResetSGX(psDeviceNode, 0, ISR_ID); } #if defined(OS_SUPPORTS_IN_LISR) if (psDeviceNode->bReProcessDeviceCommandComplete) { SGXScheduleProcessQueuesKM(psDeviceNode); } #endif SGXTestActivePowerEvent(psDeviceNode, ISR_ID); } #endif #if defined(SUPPORT_MEMORY_TILING) PVRSRV_ERROR SGX_AllocMemTilingRange(PVRSRV_DEVICE_NODE *psDeviceNode, PVRSRV_KERNEL_MEM_INFO *psMemInfo, IMG_UINT32 ui32TilingStride, IMG_UINT32 *pui32RangeIndex) { #if defined(SGX_FEATURE_BIF_WIDE_TILING_AND_4K_ADDRESS) PVRSRV_SGXDEV_INFO *psDevInfo = psDeviceNode->pvDevice; IMG_UINT32 i; IMG_UINT32 ui32Start; IMG_UINT32 ui32End; IMG_UINT32 ui32Offset; IMG_UINT32 ui32Val; for(i=0; i<10; i++) { if((psDevInfo->ui32MemTilingUsage & (1U << i)) == 0) { psDevInfo->ui32MemTilingUsage |= 1U << i; *pui32RangeIndex = i; goto RangeAllocated; } } PVR_DPF((PVR_DBG_ERROR,"SGX_AllocMemTilingRange: all tiling ranges in use")); return PVRSRV_ERROR_EXCEEDED_HW_LIMITS; RangeAllocated: ui32Offset = EUR_CR_BIF_TILE0 + (i<<2); ui32Start = psMemInfo->sDevVAddr.uiAddr; ui32End = ui32Start + psMemInfo->ui32AllocSize + SGX_MMU_PAGE_SIZE - 1; ui32Val = ((ui32TilingStride << EUR_CR_BIF_TILE0_CFG_SHIFT) & EUR_CR_BIF_TILE0_CFG_MASK) | (((ui32End>>20) << EUR_CR_BIF_TILE0_MAX_ADDRESS_SHIFT) & EUR_CR_BIF_TILE0_MAX_ADDRESS_MASK) | (((ui32Start>>20) << EUR_CR_BIF_TILE0_MIN_ADDRESS_SHIFT) & EUR_CR_BIF_TILE0_MIN_ADDRESS_MASK) | (0x8 << EUR_CR_BIF_TILE0_CFG_SHIFT); OSWriteHWReg(psDevInfo->pvRegsBaseKM, ui32Offset, ui32Val); PDUMPREG(SGX_PDUMPREG_NAME, ui32Offset, ui32Val); ui32Offset = EUR_CR_BIF_TILE0_ADDR_EXT + (i<<2); ui32Val = (((ui32End>>12) << EUR_CR_BIF_TILE0_ADDR_EXT_MAX_SHIFT) & EUR_CR_BIF_TILE0_ADDR_EXT_MAX_MASK) | (((ui32Start>>12) << EUR_CR_BIF_TILE0_ADDR_EXT_MIN_SHIFT) & EUR_CR_BIF_TILE0_ADDR_EXT_MIN_MASK); OSWriteHWReg(psDevInfo->pvRegsBaseKM, ui32Offset, ui32Val); PDUMPREG(SGX_PDUMPREG_NAME, ui32Offset, ui32Val); return PVRSRV_OK; #else PVR_UNREFERENCED_PARAMETER(psDeviceNode); PVR_UNREFERENCED_PARAMETER(psMemInfo); PVR_UNREFERENCED_PARAMETER(ui32TilingStride); PVR_UNREFERENCED_PARAMETER(pui32RangeIndex); PVR_DPF((PVR_DBG_ERROR,"SGX_AllocMemTilingRange: device does not support memory tiling")); return PVRSRV_ERROR_NOT_SUPPORTED; #endif } PVRSRV_ERROR SGX_FreeMemTilingRange(PVRSRV_DEVICE_NODE *psDeviceNode, IMG_UINT32 ui32RangeIndex) { #if defined(SGX_FEATURE_BIF_WIDE_TILING_AND_4K_ADDRESS) PVRSRV_SGXDEV_INFO *psDevInfo = psDeviceNode->pvDevice; IMG_UINT32 ui32Offset; IMG_UINT32 ui32Val; if(ui32RangeIndex >= 10) { PVR_DPF((PVR_DBG_ERROR,"SGX_FreeMemTilingRange: invalid Range index ")); return PVRSRV_ERROR_INVALID_PARAMS; } psDevInfo->ui32MemTilingUsage &= ~(1<<ui32RangeIndex); ui32Offset = EUR_CR_BIF_TILE0 + (ui32RangeIndex<<2); ui32Val = 0; OSWriteHWReg(psDevInfo->pvRegsBaseKM, ui32Offset, ui32Val); PDUMPREG(SGX_PDUMPREG_NAME, ui32Offset, ui32Val); return PVRSRV_OK; #else PVR_UNREFERENCED_PARAMETER(psDeviceNode); PVR_UNREFERENCED_PARAMETER(ui32RangeIndex); PVR_DPF((PVR_DBG_ERROR,"SGX_FreeMemTilingRange: device does not support memory tiling")); return PVRSRV_ERROR_NOT_SUPPORTED; #endif } #endif PVRSRV_ERROR SGXRegisterDevice (PVRSRV_DEVICE_NODE *psDeviceNode) { DEVICE_MEMORY_INFO *psDevMemoryInfo; DEVICE_MEMORY_HEAP_INFO *psDeviceMemoryHeap; psDeviceNode->sDevId.eDeviceType = DEV_DEVICE_TYPE; psDeviceNode->sDevId.eDeviceClass = DEV_DEVICE_CLASS; #if defined(PDUMP) { SGX_DEVICE_MAP *psSGXDeviceMemMap; SysGetDeviceMemoryMap(PVRSRV_DEVICE_TYPE_SGX, (IMG_VOID**)&psSGXDeviceMemMap); psDeviceNode->sDevId.pszPDumpDevName = psSGXDeviceMemMap->pszPDumpDevName; PVR_ASSERT(psDeviceNode->sDevId.pszPDumpDevName != IMG_NULL); } psDeviceNode->sDevId.pszPDumpRegName = SGX_PDUMPREG_NAME; #endif psDeviceNode->pfnInitDevice = &DevInitSGXPart1; psDeviceNode->pfnDeInitDevice = &DevDeInitSGX; psDeviceNode->pfnInitDeviceCompatCheck = &SGXDevInitCompatCheck; #if defined(PDUMP) psDeviceNode->pfnPDumpInitDevice = &SGXResetPDump; psDeviceNode->pfnMMUGetContextID = &MMU_GetPDumpContextID; #endif psDeviceNode->pfnMMUInitialise = &MMU_Initialise; psDeviceNode->pfnMMUFinalise = &MMU_Finalise; psDeviceNode->pfnMMUInsertHeap = &MMU_InsertHeap; psDeviceNode->pfnMMUCreate = &MMU_Create; psDeviceNode->pfnMMUDelete = &MMU_Delete; psDeviceNode->pfnMMUAlloc = &MMU_Alloc; psDeviceNode->pfnMMUFree = &MMU_Free; psDeviceNode->pfnMMUMapPages = &MMU_MapPages; psDeviceNode->pfnMMUMapShadow = &MMU_MapShadow; psDeviceNode->pfnMMUUnmapPages = &MMU_UnmapPages; psDeviceNode->pfnMMUMapScatter = &MMU_MapScatter; psDeviceNode->pfnMMUGetPhysPageAddr = &MMU_GetPhysPageAddr; psDeviceNode->pfnMMUGetPDDevPAddr = &MMU_GetPDDevPAddr; #if defined(SUPPORT_PDUMP_MULTI_PROCESS) psDeviceNode->pfnMMUIsHeapShared = &MMU_IsHeapShared; #endif #if defined (SYS_USING_INTERRUPTS) psDeviceNode->pfnDeviceISR = SGX_ISRHandler; psDeviceNode->pfnDeviceMISR = SGX_MISRHandler; #endif #if defined(SUPPORT_MEMORY_TILING) psDeviceNode->pfnAllocMemTilingRange = SGX_AllocMemTilingRange; psDeviceNode->pfnFreeMemTilingRange = SGX_FreeMemTilingRange; #endif psDeviceNode->pfnDeviceCommandComplete = &SGXCommandComplete; psDevMemoryInfo = &psDeviceNode->sDevMemoryInfo; psDevMemoryInfo->ui32AddressSpaceSizeLog2 = SGX_FEATURE_ADDRESS_SPACE_SIZE; psDevMemoryInfo->ui32Flags = 0; if(OSAllocMem( PVRSRV_OS_PAGEABLE_HEAP, sizeof(DEVICE_MEMORY_HEAP_INFO) * SGX_MAX_HEAP_ID, (IMG_VOID **)&psDevMemoryInfo->psDeviceMemoryHeap, 0, "Array of Device Memory Heap Info") != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR,"SGXRegisterDevice : Failed to alloc memory for DEVICE_MEMORY_HEAP_INFO")); return (PVRSRV_ERROR_OUT_OF_MEMORY); } OSMemSet(psDevMemoryInfo->psDeviceMemoryHeap, 0, sizeof(DEVICE_MEMORY_HEAP_INFO) * SGX_MAX_HEAP_ID); psDeviceMemoryHeap = psDevMemoryInfo->psDeviceMemoryHeap; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_GENERAL_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_GENERAL_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_GENERAL_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_SINGLE_PROCESS; psDeviceMemoryHeap->pszName = "General"; psDeviceMemoryHeap->pszBSName = "General BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; #if !defined(SUPPORT_SGX_GENERAL_MAPPING_HEAP) psDevMemoryInfo->ui32MappingHeapID = (IMG_UINT32)(psDeviceMemoryHeap - psDevMemoryInfo->psDeviceMemoryHeap); #endif psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_TADATA_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_TADATA_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_TADATA_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_MULTI_PROCESS; psDeviceMemoryHeap->pszName = "TA Data"; psDeviceMemoryHeap->pszBSName = "TA Data BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_KERNEL_CODE_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_KERNEL_CODE_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_KERNEL_CODE_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_MULTI_PROCESS; psDeviceMemoryHeap->pszName = "Kernel Code"; psDeviceMemoryHeap->pszBSName = "Kernel Code BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_SHARED_EXPORTED; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_KERNEL_DATA_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_KERNEL_DATA_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_KERNEL_DATA_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_MULTI_PROCESS; psDeviceMemoryHeap->pszName = "KernelData"; psDeviceMemoryHeap->pszBSName = "KernelData BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_SHARED_EXPORTED; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_PIXELSHADER_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_PIXELSHADER_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = ((10 << SGX_USE_CODE_SEGMENT_RANGE_BITS) - 0x00001000); PVR_ASSERT(psDeviceMemoryHeap->ui32HeapSize <= SGX_PIXELSHADER_HEAP_SIZE); psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_SINGLE_PROCESS; psDeviceMemoryHeap->pszName = "PixelShaderUSSE"; psDeviceMemoryHeap->pszBSName = "PixelShaderUSSE BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_VERTEXSHADER_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_VERTEXSHADER_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = ((4 << SGX_USE_CODE_SEGMENT_RANGE_BITS) - 0x00001000); PVR_ASSERT(psDeviceMemoryHeap->ui32HeapSize <= SGX_VERTEXSHADER_HEAP_SIZE); psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_SINGLE_PROCESS; psDeviceMemoryHeap->pszName = "VertexShaderUSSE"; psDeviceMemoryHeap->pszBSName = "VertexShaderUSSE BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_PDSPIXEL_CODEDATA_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_PDSPIXEL_CODEDATA_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_PDSPIXEL_CODEDATA_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_SINGLE_PROCESS; psDeviceMemoryHeap->pszName = "PDSPixelCodeData"; psDeviceMemoryHeap->pszBSName = "PDSPixelCodeData BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_PDSVERTEX_CODEDATA_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_PDSVERTEX_CODEDATA_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_PDSVERTEX_CODEDATA_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_SINGLE_PROCESS; psDeviceMemoryHeap->pszName = "PDSVertexCodeData"; psDeviceMemoryHeap->pszBSName = "PDSVertexCodeData BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_SYNCINFO_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_SYNCINFO_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_SYNCINFO_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_MULTI_PROCESS; psDeviceMemoryHeap->pszName = "CacheCoherent"; psDeviceMemoryHeap->pszBSName = "CacheCoherent BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_SHARED_EXPORTED; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDevMemoryInfo->ui32SyncHeapID = (IMG_UINT32)(psDeviceMemoryHeap - psDevMemoryInfo->psDeviceMemoryHeap); psDeviceMemoryHeap++; psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_3DPARAMETERS_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_3DPARAMETERS_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_3DPARAMETERS_HEAP_SIZE; psDeviceMemoryHeap->pszName = "3DParameters"; psDeviceMemoryHeap->pszBSName = "3DParameters BS"; #if defined(SUPPORT_PERCONTEXT_PB) psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_SINGLE_PROCESS; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; #else psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_MULTI_PROCESS; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_SHARED_EXPORTED; #endif psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; #if defined(SUPPORT_SGX_GENERAL_MAPPING_HEAP) psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_GENERAL_MAPPING_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_GENERAL_MAPPING_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_GENERAL_MAPPING_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_HAP_MULTI_PROCESS; psDeviceMemoryHeap->pszName = "GeneralMapping"; psDeviceMemoryHeap->pszBSName = "GeneralMapping BS"; #if defined(SGX_FEATURE_MULTIPLE_MEM_CONTEXTS) && defined(FIX_HW_BRN_23410) psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_SHARED_EXPORTED; #else psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; #endif psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDevMemoryInfo->ui32MappingHeapID = (IMG_UINT32)(psDeviceMemoryHeap - psDevMemoryInfo->psDeviceMemoryHeap); psDeviceMemoryHeap++; #endif #if defined(SGX_FEATURE_2D_HARDWARE) psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_2D_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_2D_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_2D_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_SINGLE_PROCESS; psDeviceMemoryHeap->pszName = "2D"; psDeviceMemoryHeap->pszBSName = "2D BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_SHARED_EXPORTED; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; #endif #if defined(FIX_HW_BRN_26915) psDeviceMemoryHeap->ui32HeapID = HEAP_ID( PVRSRV_DEVICE_TYPE_SGX, SGX_CGBUFFER_HEAP_ID); psDeviceMemoryHeap->sDevVAddrBase.uiAddr = SGX_CGBUFFER_HEAP_BASE; psDeviceMemoryHeap->ui32HeapSize = SGX_CGBUFFER_HEAP_SIZE; psDeviceMemoryHeap->ui32Attribs = PVRSRV_HAP_WRITECOMBINE | PVRSRV_MEM_RAM_BACKED_ALLOCATION | PVRSRV_HAP_SINGLE_PROCESS; psDeviceMemoryHeap->pszName = "CGBuffer"; psDeviceMemoryHeap->pszBSName = "CGBuffer BS"; psDeviceMemoryHeap->DevMemHeapType = DEVICE_MEMORY_HEAP_PERCONTEXT; psDeviceMemoryHeap->ui32DataPageSize = SGX_MMU_PAGE_SIZE; psDeviceMemoryHeap++; #endif psDevMemoryInfo->ui32HeapCount = (IMG_UINT32)(psDeviceMemoryHeap - psDevMemoryInfo->psDeviceMemoryHeap); return PVRSRV_OK; } #if defined(PDUMP) static PVRSRV_ERROR SGXResetPDump(PVRSRV_DEVICE_NODE *psDeviceNode) { PVRSRV_SGXDEV_INFO *psDevInfo = (PVRSRV_SGXDEV_INFO *)(psDeviceNode->pvDevice); psDevInfo->psKernelCCBInfo->ui32CCBDumpWOff = 0; PVR_DPF((PVR_DBG_MESSAGE, "Reset pdump CCB write offset.")); return PVRSRV_OK; } #endif IMG_EXPORT PVRSRV_ERROR SGXGetClientInfoKM(IMG_HANDLE hDevCookie, SGX_CLIENT_INFO* psClientInfo) { PVRSRV_SGXDEV_INFO *psDevInfo = (PVRSRV_SGXDEV_INFO *)((PVRSRV_DEVICE_NODE *)hDevCookie)->pvDevice; psDevInfo->ui32ClientRefCount++; psClientInfo->ui32ProcessID = OSGetCurrentProcessIDKM(); OSMemCopy(&psClientInfo->asDevData, &psDevInfo->asSGXDevData, sizeof(psClientInfo->asDevData)); return PVRSRV_OK; } IMG_VOID SGXPanic(PVRSRV_SGXDEV_INFO *psDevInfo) { PVR_LOG(("SGX panic")); SGXDumpDebugInfo(psDevInfo, IMG_FALSE); #ifdef DSLSI_S5PC110 PVR_LOG(("Sleep 5sec before panic")); msleep(5000); #endif OSPanic(); } PVRSRV_ERROR SGXDevInitCompatCheck(PVRSRV_DEVICE_NODE *psDeviceNode) { PVRSRV_ERROR eError; PVRSRV_SGXDEV_INFO *psDevInfo; IMG_UINT32 ui32BuildOptions, ui32BuildOptionsMismatch; #if !defined(NO_HARDWARE) PPVRSRV_KERNEL_MEM_INFO psMemInfo; PVRSRV_SGX_MISCINFO_INFO *psSGXMiscInfoInt; PVRSRV_SGX_MISCINFO_FEATURES *psSGXFeatures; SGX_MISCINFO_STRUCT_SIZES *psSGXStructSizes; IMG_BOOL bStructSizesFailed; IMG_BOOL bCheckCoreRev; const IMG_UINT32 aui32CoreRevExceptions[] = { 0x10100, 0x10101 }; const IMG_UINT32 ui32NumCoreExceptions = sizeof(aui32CoreRevExceptions) / (2*sizeof(IMG_UINT32)); IMG_UINT i; #endif if(psDeviceNode->sDevId.eDeviceType != PVRSRV_DEVICE_TYPE_SGX) { PVR_LOG(("(FAIL) SGXInit: Device not of type SGX")); eError = PVRSRV_ERROR_INVALID_PARAMS; goto chk_exit; } psDevInfo = psDeviceNode->pvDevice; ui32BuildOptions = (SGX_BUILD_OPTIONS); if (ui32BuildOptions != psDevInfo->ui32ClientBuildOptions) { ui32BuildOptionsMismatch = ui32BuildOptions ^ psDevInfo->ui32ClientBuildOptions; if ( (psDevInfo->ui32ClientBuildOptions & ui32BuildOptionsMismatch) != 0) { PVR_LOG(("(FAIL) SGXInit: Mismatch in client-side and KM driver build options; " "extra options present in client-side driver: (0x%x). Please check sgx_options.h", psDevInfo->ui32ClientBuildOptions & ui32BuildOptionsMismatch )); } if ( (ui32BuildOptions & ui32BuildOptionsMismatch) != 0) { PVR_LOG(("(FAIL) SGXInit: Mismatch in client-side and KM driver build options; " "extra options present in KM: (0x%x). Please check sgx_options.h", ui32BuildOptions & ui32BuildOptionsMismatch )); } eError = PVRSRV_ERROR_BUILD_MISMATCH; goto chk_exit; } else { PVR_DPF((PVR_DBG_MESSAGE, "SGXInit: Client-side and KM driver build options match. [ OK ]")); } #if !defined (NO_HARDWARE) psMemInfo = psDevInfo->psKernelSGXMiscMemInfo; psSGXMiscInfoInt = psMemInfo->pvLinAddrKM; psSGXMiscInfoInt->ui32MiscInfoFlags = 0; psSGXMiscInfoInt->ui32MiscInfoFlags |= PVRSRV_USSE_MISCINFO_GET_STRUCT_SIZES; eError = SGXGetMiscInfoUkernel(psDevInfo, psDeviceNode); if(eError != PVRSRV_OK) { PVR_LOG(("(FAIL) SGXInit: Unable to validate device DDK version")); goto chk_exit; } psSGXFeatures = &((PVRSRV_SGX_MISCINFO_INFO*)(psMemInfo->pvLinAddrKM))->sSGXFeatures; if( (psSGXFeatures->ui32DDKVersion != ((PVRVERSION_MAJ << 16) | (PVRVERSION_MIN << 8) | PVRVERSION_BRANCH) ) || (psSGXFeatures->ui32DDKBuild != PVRVERSION_BUILD) ) { PVR_LOG(("(FAIL) SGXInit: Incompatible driver DDK revision (%d)/device DDK revision (%d).", PVRVERSION_BUILD, psSGXFeatures->ui32DDKBuild)); eError = PVRSRV_ERROR_DDK_VERSION_MISMATCH; PVR_DBG_BREAK; goto chk_exit; } else { PVR_DPF((PVR_DBG_MESSAGE, "SGXInit: driver DDK (%d) and device DDK (%d) match. [ OK ]", PVRVERSION_BUILD, psSGXFeatures->ui32DDKBuild)); } if (psSGXFeatures->ui32CoreRevSW == 0) { PVR_LOG(("SGXInit: HW core rev (%x) check skipped.", psSGXFeatures->ui32CoreRev)); } else { bCheckCoreRev = IMG_TRUE; for(i=0; i<ui32NumCoreExceptions; i+=2) { if( (psSGXFeatures->ui32CoreRev==aui32CoreRevExceptions[i]) && (psSGXFeatures->ui32CoreRevSW==aui32CoreRevExceptions[i+1]) ) { PVR_LOG(("SGXInit: HW core rev (%x), SW core rev (%x) check skipped.", psSGXFeatures->ui32CoreRev, psSGXFeatures->ui32CoreRevSW)); bCheckCoreRev = IMG_FALSE; } } if (bCheckCoreRev) { if (psSGXFeatures->ui32CoreRev != psSGXFeatures->ui32CoreRevSW) { PVR_LOG(("(FAIL) SGXInit: Incompatible HW core rev (%x) and SW core rev (%x).", psSGXFeatures->ui32CoreRev, psSGXFeatures->ui32CoreRevSW)); eError = PVRSRV_ERROR_BUILD_MISMATCH; goto chk_exit; } else { PVR_DPF((PVR_DBG_MESSAGE, "SGXInit: HW core rev (%x) and SW core rev (%x) match. [ OK ]", psSGXFeatures->ui32CoreRev, psSGXFeatures->ui32CoreRevSW)); } } } psSGXStructSizes = &((PVRSRV_SGX_MISCINFO_INFO*)(psMemInfo->pvLinAddrKM))->sSGXStructSizes; bStructSizesFailed = IMG_FALSE; CHECK_SIZE(HOST_CTL); CHECK_SIZE(COMMAND); #if defined(SGX_FEATURE_2D_HARDWARE) CHECK_SIZE(2DCMD); CHECK_SIZE(2DCMD_SHARED); #endif CHECK_SIZE(CMDTA); CHECK_SIZE(CMDTA_SHARED); CHECK_SIZE(TRANSFERCMD); CHECK_SIZE(TRANSFERCMD_SHARED); CHECK_SIZE(3DREGISTERS); CHECK_SIZE(HWPBDESC); CHECK_SIZE(HWRENDERCONTEXT); CHECK_SIZE(HWRENDERDETAILS); CHECK_SIZE(HWRTDATA); CHECK_SIZE(HWRTDATASET); CHECK_SIZE(HWTRANSFERCONTEXT); if (bStructSizesFailed == IMG_TRUE) { PVR_LOG(("(FAIL) SGXInit: Mismatch in SGXMKIF structure sizes.")); eError = PVRSRV_ERROR_BUILD_MISMATCH; goto chk_exit; } else { PVR_DPF((PVR_DBG_MESSAGE, "SGXInit: SGXMKIF structure sizes match. [ OK ]")); } ui32BuildOptions = psSGXFeatures->ui32BuildOptions; if (ui32BuildOptions != (SGX_BUILD_OPTIONS)) { ui32BuildOptionsMismatch = ui32BuildOptions ^ (SGX_BUILD_OPTIONS); if ( ((SGX_BUILD_OPTIONS) & ui32BuildOptionsMismatch) != 0) { PVR_LOG(("(FAIL) SGXInit: Mismatch in driver and microkernel build options; " "extra options present in driver: (0x%x). Please check sgx_options.h", (SGX_BUILD_OPTIONS) & ui32BuildOptionsMismatch )); } if ( (ui32BuildOptions & ui32BuildOptionsMismatch) != 0) { PVR_LOG(("(FAIL) SGXInit: Mismatch in driver and microkernel build options; " "extra options present in microkernel: (0x%x). Please check sgx_options.h", ui32BuildOptions & ui32BuildOptionsMismatch )); } eError = PVRSRV_ERROR_BUILD_MISMATCH; goto chk_exit; } else { PVR_DPF((PVR_DBG_MESSAGE, "SGXInit: Driver and microkernel build options match. [ OK ]")); } #endif eError = PVRSRV_OK; chk_exit: #if defined(IGNORE_SGX_INIT_COMPATIBILITY_CHECK) return PVRSRV_OK; #else return eError; #endif } static PVRSRV_ERROR SGXGetMiscInfoUkernel(PVRSRV_SGXDEV_INFO *psDevInfo, PVRSRV_DEVICE_NODE *psDeviceNode) { PVRSRV_ERROR eError; SGXMKIF_COMMAND sCommandData; PVRSRV_SGX_MISCINFO_INFO *psSGXMiscInfoInt; PVRSRV_SGX_MISCINFO_FEATURES *psSGXFeatures; SGX_MISCINFO_STRUCT_SIZES *psSGXStructSizes; PPVRSRV_KERNEL_MEM_INFO psMemInfo = psDevInfo->psKernelSGXMiscMemInfo; if (! psMemInfo->pvLinAddrKM) { PVR_DPF((PVR_DBG_ERROR, "SGXGetMiscInfoUkernel: Invalid address.")); return PVRSRV_ERROR_INVALID_PARAMS; } psSGXMiscInfoInt = psMemInfo->pvLinAddrKM; psSGXFeatures = &psSGXMiscInfoInt->sSGXFeatures; psSGXStructSizes = &psSGXMiscInfoInt->sSGXStructSizes; psSGXMiscInfoInt->ui32MiscInfoFlags &= ~PVRSRV_USSE_MISCINFO_READY; OSMemSet(psSGXFeatures, 0, sizeof(*psSGXFeatures)); OSMemSet(psSGXStructSizes, 0, sizeof(*psSGXStructSizes)); sCommandData.ui32Data[1] = psMemInfo->sDevVAddr.uiAddr; PDUMPCOMMENT("Microkernel kick for SGXGetMiscInfo"); eError = SGXScheduleCCBCommandKM(psDeviceNode, SGXMKIF_CMD_GETMISCINFO, &sCommandData, KERNEL_ID, 0, IMG_FALSE); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR, "SGXGetMiscInfoUkernel: SGXScheduleCCBCommandKM failed.")); return eError; } #if !defined(NO_HARDWARE) { IMG_BOOL bExit; bExit = IMG_FALSE; LOOP_UNTIL_TIMEOUT(MAX_HW_TIME_US) { if ((psSGXMiscInfoInt->ui32MiscInfoFlags & PVRSRV_USSE_MISCINFO_READY) != 0) { bExit = IMG_TRUE; break; } } END_LOOP_UNTIL_TIMEOUT(); if (!bExit) { PVR_DPF((PVR_DBG_ERROR, "SGXGetMiscInfoUkernel: Timeout occurred waiting for misc info.")); return PVRSRV_ERROR_TIMEOUT; } } #endif return PVRSRV_OK; } IMG_EXPORT PVRSRV_ERROR SGXGetMiscInfoKM(PVRSRV_SGXDEV_INFO *psDevInfo, SGX_MISC_INFO *psMiscInfo, PVRSRV_DEVICE_NODE *psDeviceNode, IMG_HANDLE hDevMemContext) { PVRSRV_ERROR eError; PPVRSRV_KERNEL_MEM_INFO psMemInfo = psDevInfo->psKernelSGXMiscMemInfo; IMG_UINT32 *pui32MiscInfoFlags = &((PVRSRV_SGX_MISCINFO_INFO*)(psMemInfo->pvLinAddrKM))->ui32MiscInfoFlags; *pui32MiscInfoFlags = 0; #if !defined(SUPPORT_SGX_EDM_MEMORY_DEBUG) PVR_UNREFERENCED_PARAMETER(hDevMemContext); #endif switch(psMiscInfo->eRequest) { #if defined(SGX_FEATURE_DATA_BREAKPOINTS) case SGX_MISC_INFO_REQUEST_SET_BREAKPOINT: { IMG_UINT32 ui32MaskDM; IMG_UINT32 ui32CtrlWEnable; IMG_UINT32 ui32CtrlREnable; IMG_UINT32 ui32CtrlTrapEnable; IMG_UINT32 ui32RegVal; IMG_UINT32 ui32StartRegVal; IMG_UINT32 ui32EndRegVal; SGXMKIF_COMMAND sCommandData; if(psMiscInfo->uData.sSGXBreakpointInfo.bBPEnable) { IMG_DEV_VIRTADDR sBPDevVAddr = psMiscInfo->uData.sSGXBreakpointInfo.sBPDevVAddr; IMG_DEV_VIRTADDR sBPDevVAddrEnd = psMiscInfo->uData.sSGXBreakpointInfo.sBPDevVAddrEnd; ui32StartRegVal = sBPDevVAddr.uiAddr & EUR_CR_BREAKPOINT0_START_ADDRESS_MASK; ui32EndRegVal = sBPDevVAddrEnd.uiAddr & EUR_CR_BREAKPOINT0_END_ADDRESS_MASK; ui32MaskDM = psMiscInfo->uData.sSGXBreakpointInfo.ui32DataMasterMask; ui32CtrlWEnable = psMiscInfo->uData.sSGXBreakpointInfo.bWrite; ui32CtrlREnable = psMiscInfo->uData.sSGXBreakpointInfo.bRead; ui32CtrlTrapEnable = psMiscInfo->uData.sSGXBreakpointInfo.bTrapped; ui32RegVal = ((ui32MaskDM<<EUR_CR_BREAKPOINT0_MASK_DM_SHIFT) & EUR_CR_BREAKPOINT0_MASK_DM_MASK) | ((ui32CtrlWEnable<<EUR_CR_BREAKPOINT0_CTRL_WENABLE_SHIFT) & EUR_CR_BREAKPOINT0_CTRL_WENABLE_MASK) | ((ui32CtrlREnable<<EUR_CR_BREAKPOINT0_CTRL_RENABLE_SHIFT) & EUR_CR_BREAKPOINT0_CTRL_RENABLE_MASK) | ((ui32CtrlTrapEnable<<EUR_CR_BREAKPOINT0_CTRL_TRAPENABLE_SHIFT) & EUR_CR_BREAKPOINT0_CTRL_TRAPENABLE_MASK); } else { ui32RegVal = ui32StartRegVal = ui32EndRegVal = 0; } sCommandData.ui32Data[0] = psMiscInfo->uData.sSGXBreakpointInfo.ui32BPIndex; sCommandData.ui32Data[1] = ui32StartRegVal; sCommandData.ui32Data[2] = ui32EndRegVal; sCommandData.ui32Data[3] = ui32RegVal; psDevInfo->psSGXHostCtl->ui32BPSetClearSignal = 0; PDUMPCOMMENT("Microkernel kick for setting a data breakpoint"); eError = SGXScheduleCCBCommandKM(psDeviceNode, SGXMKIF_CMD_DATABREAKPOINT, &sCommandData, KERNEL_ID, 0, IMG_FALSE); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR, "SGXGetMiscInfoKM: SGXScheduleCCBCommandKM failed.")); return eError; } #if defined(NO_HARDWARE) psDevInfo->psSGXHostCtl->ui32BPSetClearSignal = 0; #else { IMG_BOOL bExit; bExit = IMG_FALSE; LOOP_UNTIL_TIMEOUT(MAX_HW_TIME_US) { if (psDevInfo->psSGXHostCtl->ui32BPSetClearSignal != 0) { bExit = IMG_TRUE; psDevInfo->psSGXHostCtl->ui32BPSetClearSignal = 0; break; } } END_LOOP_UNTIL_TIMEOUT(); if (!bExit) { PVR_DPF((PVR_DBG_ERROR, "SGXGetMiscInfoKM: Timeout occurred waiting BP set/clear")); return PVRSRV_ERROR_TIMEOUT; } } #endif return PVRSRV_OK; } case SGX_MISC_INFO_REQUEST_WAIT_FOR_BREAKPOINT: { PDUMPCOMMENT("Wait for data breakpoint hit"); #if defined(NO_HARDWARE) && defined(PDUMP) { PDUMPREGPOL(SGX_PDUMPREG_NAME, EUR_CR_EVENT_STATUS2, EUR_CR_EVENT_STATUS2_DATA_BREAKPOINT_TRAPPED_MASK, EUR_CR_EVENT_STATUS2_DATA_BREAKPOINT_TRAPPED_MASK); PDUMPREG(SGX_PDUMPREG_NAME, EUR_CR_EVENT_HOST_CLEAR2, EUR_CR_EVENT_HOST_CLEAR2_DATA_BREAKPOINT_TRAPPED_MASK); PDUMPCOMMENT("Breakpoint detected. Wait a bit to show that pipeline stops in simulation"); PDUMPIDL(2000); PDUMPCOMMENT("Now we can resume"); PDUMPREG(SGX_PDUMPREG_NAME, EUR_CR_BREAKPOINT_TRAP, EUR_CR_BREAKPOINT_TRAP_WRNOTIFY_MASK | EUR_CR_BREAKPOINT_TRAP_CONTINUE_MASK); } #else { } #endif return PVRSRV_OK; } case SGX_MISC_INFO_REQUEST_POLL_BREAKPOINT: { #if !defined(NO_HARDWARE) IMG_BOOL bTrappedBPMaster; IMG_BOOL abTrappedBPPerCore[SGX_FEATURE_MP_CORE_COUNT]; IMG_UINT32 ui32CoreNum, ui32TrappedBPCoreNum; IMG_BOOL bTrappedBPAny; ui32TrappedBPCoreNum = 0; bTrappedBPMaster = !!(EUR_CR_MASTER_BREAKPOINT_TRAPPED_MASK & OSReadHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_MASTER_BREAKPOINT)); bTrappedBPAny = bTrappedBPMaster; for (ui32CoreNum = 0; ui32CoreNum < SGX_FEATURE_MP_CORE_COUNT; ui32CoreNum++) { abTrappedBPPerCore[ui32CoreNum] = !!(EUR_CR_BREAKPOINT_TRAPPED_MASK & OSReadHWReg(psDevInfo->pvRegsBaseKM, SGX_MP_CORE_SELECT(EUR_CR_BREAKPOINT, ui32CoreNum))); if (abTrappedBPPerCore[ui32CoreNum]) { bTrappedBPAny = IMG_TRUE; ui32TrappedBPCoreNum = ui32CoreNum; } } psMiscInfo->uData.sSGXBreakpointInfo.bTrappedBP = bTrappedBPAny; if (psMiscInfo->uData.sSGXBreakpointInfo.bTrappedBP) { IMG_UINT32 ui32Info0, ui32Info1; ui32Info0 = OSReadHWReg(psDevInfo->pvRegsBaseKM, bTrappedBPMaster?EUR_CR_MASTER_BREAKPOINT_TRAP_INFO0:SGX_MP_CORE_SELECT(EUR_CR_BREAKPOINT_TRAP_INFO0, ui32TrappedBPCoreNum)); ui32Info1 = OSReadHWReg(psDevInfo->pvRegsBaseKM, bTrappedBPMaster?EUR_CR_MASTER_BREAKPOINT_TRAP_INFO1:SGX_MP_CORE_SELECT(EUR_CR_BREAKPOINT_TRAP_INFO1, ui32TrappedBPCoreNum)); psMiscInfo->uData.sSGXBreakpointInfo.ui32BPIndex = (ui32Info1 & EUR_CR_BREAKPOINT_TRAP_INFO1_NUMBER_MASK) >> EUR_CR_BREAKPOINT_TRAP_INFO1_NUMBER_SHIFT; psMiscInfo->uData.sSGXBreakpointInfo.sTrappedBPDevVAddr.uiAddr = ui32Info0 & EUR_CR_BREAKPOINT_TRAP_INFO0_ADDRESS_MASK; psMiscInfo->uData.sSGXBreakpointInfo.ui32TrappedBPBurstLength = (ui32Info1 & EUR_CR_BREAKPOINT_TRAP_INFO1_SIZE_MASK) >> EUR_CR_BREAKPOINT_TRAP_INFO1_SIZE_SHIFT; psMiscInfo->uData.sSGXBreakpointInfo.bTrappedBPRead = !!(ui32Info1 & EUR_CR_BREAKPOINT_TRAP_INFO1_RNW_MASK); psMiscInfo->uData.sSGXBreakpointInfo.ui32TrappedBPDataMaster = (ui32Info1 & EUR_CR_BREAKPOINT_TRAP_INFO1_DATA_MASTER_MASK) >> EUR_CR_BREAKPOINT_TRAP_INFO1_DATA_MASTER_SHIFT; psMiscInfo->uData.sSGXBreakpointInfo.ui32TrappedBPTag = (ui32Info1 & EUR_CR_BREAKPOINT_TRAP_INFO1_TAG_MASK) >> EUR_CR_BREAKPOINT_TRAP_INFO1_TAG_SHIFT; psMiscInfo->uData.sSGXBreakpointInfo.ui32CoreNum = bTrappedBPMaster?65535:ui32TrappedBPCoreNum; } #endif return PVRSRV_OK; } case SGX_MISC_INFO_REQUEST_RESUME_BREAKPOINT: { #if !defined(NO_HARDWARE) IMG_UINT32 ui32CoreNum; IMG_BOOL bMaster; IMG_UINT32 ui32OldSeqNum, ui32NewSeqNum; ui32CoreNum = psMiscInfo->uData.sSGXBreakpointInfo.ui32CoreNum; bMaster = ui32CoreNum > SGX_FEATURE_MP_CORE_COUNT; if (bMaster) { ui32OldSeqNum = 0x1c & OSReadHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_MASTER_BREAKPOINT); OSWriteHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_MASTER_BREAKPOINT_TRAP, EUR_CR_MASTER_BREAKPOINT_TRAP_WRNOTIFY_MASK | EUR_CR_MASTER_BREAKPOINT_TRAP_CONTINUE_MASK); do { ui32NewSeqNum = 0x1c & OSReadHWReg(psDevInfo->pvRegsBaseKM, EUR_CR_MASTER_BREAKPOINT); } while (ui32OldSeqNum == ui32NewSeqNum); } else { ui32OldSeqNum = 0x1c & OSReadHWReg(psDevInfo->pvRegsBaseKM, SGX_MP_CORE_SELECT(EUR_CR_BREAKPOINT, ui32CoreNum)); OSWriteHWReg(psDevInfo->pvRegsBaseKM, SGX_MP_CORE_SELECT(EUR_CR_BREAKPOINT_TRAP, ui32CoreNum), EUR_CR_BREAKPOINT_TRAP_WRNOTIFY_MASK | EUR_CR_BREAKPOINT_TRAP_CONTINUE_MASK); do { ui32NewSeqNum = 0x1c & OSReadHWReg(psDevInfo->pvRegsBaseKM, SGX_MP_CORE_SELECT(EUR_CR_BREAKPOINT, ui32CoreNum)); } while (ui32OldSeqNum == ui32NewSeqNum); } #endif return PVRSRV_OK; } #endif case SGX_MISC_INFO_REQUEST_CLOCKSPEED: { psMiscInfo->uData.ui32SGXClockSpeed = psDevInfo->ui32CoreClockSpeed; return PVRSRV_OK; } case SGX_MISC_INFO_REQUEST_ACTIVEPOWER: { psMiscInfo->uData.sActivePower.ui32NumActivePowerEvents = psDevInfo->psSGXHostCtl->ui32NumActivePowerEvents; return PVRSRV_OK; } case SGX_MISC_INFO_REQUEST_LOCKUPS: { #if defined(SUPPORT_HW_RECOVERY) psMiscInfo->uData.sLockups.ui32uKernelDetectedLockups = psDevInfo->psSGXHostCtl->ui32uKernelDetectedLockups; psMiscInfo->uData.sLockups.ui32HostDetectedLockups = psDevInfo->psSGXHostCtl->ui32HostDetectedLockups; #else psMiscInfo->uData.sLockups.ui32uKernelDetectedLockups = 0; psMiscInfo->uData.sLockups.ui32HostDetectedLockups = 0; #endif return PVRSRV_OK; } case SGX_MISC_INFO_REQUEST_SPM: { return PVRSRV_OK; } case SGX_MISC_INFO_REQUEST_SGXREV: { PVRSRV_SGX_MISCINFO_FEATURES *psSGXFeatures; eError = SGXGetMiscInfoUkernel(psDevInfo, psDeviceNode); if(eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR, "An error occurred in SGXGetMiscInfoUkernel: %d\n", eError)); return eError; } psSGXFeatures = &((PVRSRV_SGX_MISCINFO_INFO*)(psMemInfo->pvLinAddrKM))->sSGXFeatures; psMiscInfo->uData.sSGXFeatures = *psSGXFeatures; PVR_DPF((PVR_DBG_MESSAGE, "SGXGetMiscInfoKM: Core 0x%x, sw ID 0x%x, sw Rev 0x%x\n", psSGXFeatures->ui32CoreRev, psSGXFeatures->ui32CoreIdSW, psSGXFeatures->ui32CoreRevSW)); PVR_DPF((PVR_DBG_MESSAGE, "SGXGetMiscInfoKM: DDK version 0x%x, DDK build 0x%x\n", psSGXFeatures->ui32DDKVersion, psSGXFeatures->ui32DDKBuild)); return PVRSRV_OK; } case SGX_MISC_INFO_REQUEST_DRIVER_SGXREV: { PVRSRV_SGX_MISCINFO_FEATURES *psSGXFeatures; psSGXFeatures = &((PVRSRV_SGX_MISCINFO_INFO*)(psMemInfo->pvLinAddrKM))->sSGXFeatures; OSMemSet(psMemInfo->pvLinAddrKM, 0, sizeof(PVRSRV_SGX_MISCINFO_INFO)); psSGXFeatures->ui32DDKVersion = (PVRVERSION_MAJ << 16) | (PVRVERSION_MIN << 8) | PVRVERSION_BRANCH; psSGXFeatures->ui32DDKBuild = PVRVERSION_BUILD; psSGXFeatures->ui32BuildOptions = (SGX_BUILD_OPTIONS); #if defined(PVRSRV_USSE_EDM_STATUS_DEBUG) psSGXFeatures->sDevVAEDMStatusBuffer = psDevInfo->psKernelEDMStatusBufferMemInfo->sDevVAddr; psSGXFeatures->pvEDMStatusBuffer = psDevInfo->psKernelEDMStatusBufferMemInfo->pvLinAddrKM; #endif psMiscInfo->uData.sSGXFeatures = *psSGXFeatures; return PVRSRV_OK; } #if defined(SUPPORT_SGX_EDM_MEMORY_DEBUG) case SGX_MISC_INFO_REQUEST_MEMREAD: case SGX_MISC_INFO_REQUEST_MEMCOPY: { PVRSRV_ERROR eError; PVRSRV_SGX_MISCINFO_FEATURES *psSGXFeatures; PVRSRV_SGX_MISCINFO_MEMACCESS *psSGXMemSrc; PVRSRV_SGX_MISCINFO_MEMACCESS *psSGXMemDest; { *pui32MiscInfoFlags |= PVRSRV_USSE_MISCINFO_MEMREAD; psSGXMemSrc = &((PVRSRV_SGX_MISCINFO_INFO*)(psMemInfo->pvLinAddrKM))->sSGXMemAccessSrc; if(psMiscInfo->sDevVAddrSrc.uiAddr != 0) { psSGXMemSrc->sDevVAddr = psMiscInfo->sDevVAddrSrc; } else { return PVRSRV_ERROR_INVALID_PARAMS; } } if( psMiscInfo->eRequest == SGX_MISC_INFO_REQUEST_MEMCOPY) { *pui32MiscInfoFlags |= PVRSRV_USSE_MISCINFO_MEMWRITE; psSGXMemDest = &((PVRSRV_SGX_MISCINFO_INFO*)(psMemInfo->pvLinAddrKM))->sSGXMemAccessDest; if(psMiscInfo->sDevVAddrDest.uiAddr != 0) { psSGXMemDest->sDevVAddr = psMiscInfo->sDevVAddrDest; } else { return PVRSRV_ERROR_INVALID_PARAMS; } } if(psMiscInfo->hDevMemContext != IMG_NULL) { SGXGetMMUPDAddrKM( (IMG_HANDLE)psDeviceNode, hDevMemContext, &psSGXMemSrc->sPDDevPAddr); psSGXMemDest->sPDDevPAddr = psSGXMemSrc->sPDDevPAddr; } else { return PVRSRV_ERROR_INVALID_PARAMS; } eError = SGXGetMiscInfoUkernel(psDevInfo, psDeviceNode); if(eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR, "An error occurred in SGXGetMiscInfoUkernel: %d\n", eError)); return eError; } psSGXFeatures = &((PVRSRV_SGX_MISCINFO_INFO*)(psMemInfo->pvLinAddrKM))->sSGXFeatures; #if !defined(SGX_FEATURE_MULTIPLE_MEM_CONTEXTS) if(*pui32MiscInfoFlags & PVRSRV_USSE_MISCINFO_MEMREAD_FAIL) { return PVRSRV_ERROR_INVALID_MISCINFO; } #endif psMiscInfo->uData.sSGXFeatures = *psSGXFeatures; return PVRSRV_OK; } #endif #if defined(SUPPORT_SGX_HWPERF) case SGX_MISC_INFO_REQUEST_SET_HWPERF_STATUS: { PVRSRV_SGX_MISCINFO_SET_HWPERF_STATUS *psSetHWPerfStatus = &psMiscInfo->uData.sSetHWPerfStatus; const IMG_UINT32 ui32ValidFlags = PVRSRV_SGX_HWPERF_STATUS_RESET_COUNTERS | PVRSRV_SGX_HWPERF_STATUS_GRAPHICS_ON | PVRSRV_SGX_HWPERF_STATUS_PERIODIC_ON | PVRSRV_SGX_HWPERF_STATUS_MK_EXECUTION_ON; SGXMKIF_COMMAND sCommandData = {0}; if ((psSetHWPerfStatus->ui32NewHWPerfStatus & ~ui32ValidFlags) != 0) { return PVRSRV_ERROR_INVALID_PARAMS; } #if defined(PDUMP) PDUMPCOMMENTWITHFLAGS(PDUMP_FLAGS_CONTINUOUS, "SGX ukernel HWPerf status %u\n", psSetHWPerfStatus->ui32NewHWPerfStatus); #endif #if defined(SGX_FEATURE_EXTENDED_PERF_COUNTERS) OSMemCopy(&psDevInfo->psSGXHostCtl->aui32PerfGroup[0], &psSetHWPerfStatus->aui32PerfGroup[0], sizeof(psDevInfo->psSGXHostCtl->aui32PerfGroup)); OSMemCopy(&psDevInfo->psSGXHostCtl->aui32PerfBit[0], &psSetHWPerfStatus->aui32PerfBit[0], sizeof(psDevInfo->psSGXHostCtl->aui32PerfBit)); #if defined(PDUMP) PDUMPMEM(IMG_NULL, psDevInfo->psKernelSGXHostCtlMemInfo, offsetof(SGXMKIF_HOST_CTL, aui32PerfGroup), sizeof(psDevInfo->psSGXHostCtl->aui32PerfGroup), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psDevInfo->psKernelSGXHostCtlMemInfo)); PDUMPMEM(IMG_NULL, psDevInfo->psKernelSGXHostCtlMemInfo, offsetof(SGXMKIF_HOST_CTL, aui32PerfBit), sizeof(psDevInfo->psSGXHostCtl->aui32PerfBit), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psDevInfo->psKernelSGXHostCtlMemInfo)); #endif #else psDevInfo->psSGXHostCtl->ui32PerfGroup = psSetHWPerfStatus->ui32PerfGroup; #if defined(PDUMP) PDUMPMEM(IMG_NULL, psDevInfo->psKernelSGXHostCtlMemInfo, offsetof(SGXMKIF_HOST_CTL, ui32PerfGroup), sizeof(psDevInfo->psSGXHostCtl->ui32PerfGroup), PDUMP_FLAGS_CONTINUOUS, MAKEUNIQUETAG(psDevInfo->psKernelSGXHostCtlMemInfo)); #endif #endif sCommandData.ui32Data[0] = psSetHWPerfStatus->ui32NewHWPerfStatus; eError = SGXScheduleCCBCommandKM(psDeviceNode, SGXMKIF_CMD_SETHWPERFSTATUS, &sCommandData, KERNEL_ID, 0, IMG_FALSE); return eError; } #endif case SGX_MISC_INFO_DUMP_DEBUG_INFO: { PVR_LOG(("User requested SGX debug info")); SGXDumpDebugInfo(psDeviceNode->pvDevice, IMG_FALSE); return PVRSRV_OK; } case SGX_MISC_INFO_PANIC: { if (psDeviceNode->bReProcessDeviceCommandComplete) { PVR_LOG(("User requested SGX panic but attempting SGXScheduleProcessQueuesKM")); SGXScheduleProcessQueuesKM(psDeviceNode); } else { PVR_LOG(("User requested SGX panic")); SGXPanic(psDeviceNode->pvDevice); } return PVRSRV_OK; } default: { return PVRSRV_ERROR_INVALID_PARAMS; } } } IMG_EXPORT PVRSRV_ERROR SGXReadHWPerfCBKM(IMG_HANDLE hDevHandle, IMG_UINT32 ui32ArraySize, PVRSRV_SGX_HWPERF_CB_ENTRY *psClientHWPerfEntry, IMG_UINT32 *pui32DataCount, IMG_UINT32 *pui32ClockSpeed, IMG_UINT32 *pui32HostTimeStamp) { PVRSRV_ERROR eError = PVRSRV_OK; PVRSRV_DEVICE_NODE *psDeviceNode = hDevHandle; PVRSRV_SGXDEV_INFO *psDevInfo = psDeviceNode->pvDevice; SGXMKIF_HWPERF_CB *psHWPerfCB = psDevInfo->psKernelHWPerfCBMemInfo->pvLinAddrKM; IMG_UINT i; for (i = 0; psHWPerfCB->ui32Woff != psHWPerfCB->ui32Roff && i < ui32ArraySize; i++) { SGXMKIF_HWPERF_CB_ENTRY *psMKPerfEntry = &psHWPerfCB->psHWPerfCBData[psHWPerfCB->ui32Roff]; psClientHWPerfEntry[i].ui32FrameNo = psMKPerfEntry->ui32FrameNo; psClientHWPerfEntry[i].ui32Type = psMKPerfEntry->ui32Type; psClientHWPerfEntry[i].ui32Ordinal = psMKPerfEntry->ui32Ordinal; psClientHWPerfEntry[i].ui32Info = psMKPerfEntry->ui32Info; psClientHWPerfEntry[i].ui32Clocksx16 = SGXConvertTimeStamp(psDevInfo, psMKPerfEntry->ui32TimeWraps, psMKPerfEntry->ui32Time); OSMemCopy(&psClientHWPerfEntry[i].ui32Counters[0][0], &psMKPerfEntry->ui32Counters[0][0], sizeof(psMKPerfEntry->ui32Counters)); psHWPerfCB->ui32Roff = (psHWPerfCB->ui32Roff + 1) & (SGXMKIF_HWPERF_CB_SIZE - 1); } *pui32DataCount = i; *pui32ClockSpeed = psDevInfo->ui32CoreClockSpeed; *pui32HostTimeStamp = OSClockus(); return eError; }
gpl-3.0
peter-b/livecode
engine/src/text-pane.cpp
11
5364
/* Copyright (C) 2015 LiveCode Ltd. This file is part of LiveCode. LiveCode is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License v3 as published by the Free Software Foundation. LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */ #include "prefix.h" #include <foundation-math.h> #include "text-pane.h" #include "text-paragraph.h" #include "graphics.h" #include "stack.h" #include "context.h" MCTextPane::MCTextPane() : MCTextCell(), m_paragraphs(NULL), m_stack(NULL), m_text_wrap(true) { // TESTING m_stack = MCdefaultstackptr; } MCTextPane::~MCTextPane() { deleteContents(); } MCTextCellType MCTextPane::getType() const { return kMCTextCellTypePane; } MCTextCell* MCTextPane::getParent() const { return NULL; } MCTextCell* MCTextPane::getChildren() const { return m_paragraphs; } void MCTextPane::performLayout() { if (!needsLayout()) return; // Tell each of the paragraphs to do their layout. This is necessary so that // the total size of the paragraphs can be calculated. MCTextParagraph* t_paragraph; coord_t t_total_height; coord_t t_max_width; t_paragraph = m_paragraphs; t_total_height = t_max_width = 0.0f; do { if (getTextWrap()) t_paragraph->setMaxSize(getMaxWidth(), INFINITY); else t_paragraph->setMaxSize(INFINITY, INFINITY); t_paragraph->performLayout(); t_total_height += t_paragraph->getHeight(); t_max_width = MCMax(t_max_width, t_paragraph->getWidth()); t_paragraph = t_paragraph->next(); } while (t_paragraph != m_paragraphs); if (getTextWrap()) recordSize(getMaxWidth(), t_total_height); else recordSize(t_max_width, t_total_height); // Position the paragraphs correctly finishLayout(); repositionChildren(); } void MCTextPane::clearLayout() { // Clear the layout of every paragraph MCTextParagraph* t_paragraph; t_paragraph = m_paragraphs; do { t_paragraph->clearLayout(); t_paragraph = t_paragraph->next(); } while (t_paragraph != m_paragraphs); } void MCTextPane::draw(MCDC* dc) { // Ensure that layout has been completed performLayout(); // Draw each of the paragraphs in turn MCTextParagraph* t_paragraph; t_paragraph = m_paragraphs; do { dc->save(); dc->setorigin(t_paragraph->getX(), t_paragraph->getY()); t_paragraph->draw(dc); dc->restore(); t_paragraph = t_paragraph->next(); } while (t_paragraph != m_paragraphs); } void MCTextPane::repositionChildren() { // Based on vertical alignment, calculate the offset for positioning coord_t t_offset; t_offset = 0.0f; if (getHeight() < getMaxHeight()) { switch (getVerticalAlignment()) { case kMCTextCellAlignCenter: t_offset = (getMaxHeight() - getHeight())/2; break; case kMCTextCellAlignStart: case kMCTextCellAlignJustify: break; case kMCTextCellAlignEnd: t_offset = getMaxHeight() - getHeight(); break; default: MCUnreachable(); } } // Position each of the paragraphs in turn coord_t t_y = 0; MCTextParagraph* t_paragraph; t_paragraph = m_paragraphs; do { // Position the paragraph at the top or bottom of the pane, as required if (isReversedLineOrder()) { // Position from the bottom, remembering to account for the height // of this paragraph as well t_y += t_paragraph->getHeight(); t_paragraph->setPosition(0, getHeight() - t_y + t_offset); } else { // Position from the top of the pane t_paragraph->setPosition(0, t_y + t_offset); t_y += t_paragraph->getHeight(); } t_paragraph->repositionChildren(); t_paragraph = t_paragraph->next(); } while (t_paragraph != m_paragraphs); } void MCTextPane::setContentsPlain(MCStringRef p_string) { // Clear the existing contents deleteContents(); // Create a new paragraph to hold the contents of the pane m_paragraphs = new MCTextParagraph(this); m_paragraphs->setContentsPlain(p_string); // TODO: examine the list of blocks in the paragraph for paragraph breaks // Pane needs to be laid-out setNeedsLayout(); } MCGAffineTransform MCTextPane::getTransform() const { return m_stack->getdevicetransform(); } void MCTextPane::deleteContents() { if (m_paragraphs == NULL) return; // The layout needs to be reset clearLayout(); // Delete each of the paragraphs while (m_paragraphs != NULL) delete m_paragraphs->remove(m_paragraphs); }
gpl-3.0
Monroe88/RetroArch
deps/libvita2d/source/vita2d_draw.c
13
5142
#include <math.h> #include "vita2d.h" #include "shared.h" void vita2d_draw_pixel(float x, float y, unsigned int color) { vita2d_color_vertex *vertex = (vita2d_color_vertex *)vita2d_pool_memalign( 1 * sizeof(vita2d_color_vertex), // 1 vertex sizeof(vita2d_color_vertex)); uint16_t *index = (uint16_t *)vita2d_pool_memalign( 1 * sizeof(uint16_t), // 1 index sizeof(uint16_t)); vertex->x = x; vertex->y = y; vertex->z = +0.5f; vertex->color = color; *index = 0; sceGxmSetVertexProgram(_vita2d_context, _vita2d_colorVertexProgram); sceGxmSetFragmentProgram(_vita2d_context, _vita2d_colorFragmentProgram); void *vertexDefaultBuffer; sceGxmReserveVertexDefaultUniformBuffer(_vita2d_context, &vertexDefaultBuffer); sceGxmSetUniformDataF(vertexDefaultBuffer, _vita2d_colorWvpParam, 0, 16, _vita2d_ortho_matrix); sceGxmSetVertexStream(_vita2d_context, 0, vertex); sceGxmSetFrontPolygonMode(_vita2d_context, SCE_GXM_POLYGON_MODE_POINT); sceGxmDraw(_vita2d_context, SCE_GXM_PRIMITIVE_POINTS, SCE_GXM_INDEX_FORMAT_U16, index, 1); sceGxmSetFrontPolygonMode(_vita2d_context, SCE_GXM_POLYGON_MODE_TRIANGLE_FILL); } void vita2d_draw_line(float x0, float y0, float x1, float y1, unsigned int color) { vita2d_color_vertex *vertices = (vita2d_color_vertex *)vita2d_pool_memalign( 2 * sizeof(vita2d_color_vertex), // 2 vertices sizeof(vita2d_color_vertex)); uint16_t *indices = (uint16_t *)vita2d_pool_memalign( 2 * sizeof(uint16_t), // 2 indices sizeof(uint16_t)); vertices[0].x = x0; vertices[0].y = y0; vertices[0].z = +0.5f; vertices[0].color = color; vertices[1].x = x1; vertices[1].y = y1; vertices[1].z = +0.5f; vertices[1].color = color; indices[0] = 0; indices[1] = 1; sceGxmSetVertexProgram(_vita2d_context, _vita2d_colorVertexProgram); sceGxmSetFragmentProgram(_vita2d_context, _vita2d_colorFragmentProgram); void *vertexDefaultBuffer; sceGxmReserveVertexDefaultUniformBuffer(_vita2d_context, &vertexDefaultBuffer); sceGxmSetUniformDataF(vertexDefaultBuffer, _vita2d_colorWvpParam, 0, 16, _vita2d_ortho_matrix); sceGxmSetVertexStream(_vita2d_context, 0, vertices); sceGxmSetFrontPolygonMode(_vita2d_context, SCE_GXM_POLYGON_MODE_LINE); sceGxmDraw(_vita2d_context, SCE_GXM_PRIMITIVE_LINES, SCE_GXM_INDEX_FORMAT_U16, indices, 2); sceGxmSetFrontPolygonMode(_vita2d_context, SCE_GXM_POLYGON_MODE_TRIANGLE_FILL); } void vita2d_draw_rectangle(float x, float y, float w, float h, unsigned int color) { vita2d_color_vertex *vertices = (vita2d_color_vertex *)vita2d_pool_memalign( 4 * sizeof(vita2d_color_vertex), // 4 vertices sizeof(vita2d_color_vertex)); uint16_t *indices = (uint16_t *)vita2d_pool_memalign( 4 * sizeof(uint16_t), // 4 indices sizeof(uint16_t)); vertices[0].x = x; vertices[0].y = y; vertices[0].z = +0.5f; vertices[0].color = color; vertices[1].x = x + w; vertices[1].y = y; vertices[1].z = +0.5f; vertices[1].color = color; vertices[2].x = x; vertices[2].y = y + h; vertices[2].z = +0.5f; vertices[2].color = color; vertices[3].x = x + w; vertices[3].y = y + h; vertices[3].z = +0.5f; vertices[3].color = color; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 3; sceGxmSetVertexProgram(_vita2d_context, _vita2d_colorVertexProgram); sceGxmSetFragmentProgram(_vita2d_context, _vita2d_colorFragmentProgram); void *vertexDefaultBuffer; sceGxmReserveVertexDefaultUniformBuffer(_vita2d_context, &vertexDefaultBuffer); sceGxmSetUniformDataF(vertexDefaultBuffer, _vita2d_colorWvpParam, 0, 16, _vita2d_ortho_matrix); sceGxmSetVertexStream(_vita2d_context, 0, vertices); sceGxmDraw(_vita2d_context, SCE_GXM_PRIMITIVE_TRIANGLE_STRIP, SCE_GXM_INDEX_FORMAT_U16, indices, 4); } void vita2d_draw_fill_circle(float x, float y, float radius, unsigned int color) { static const int num_segments = 100; vita2d_color_vertex *vertices = (vita2d_color_vertex *)vita2d_pool_memalign( (num_segments + 1) * sizeof(vita2d_color_vertex), sizeof(vita2d_color_vertex)); uint16_t *indices = (uint16_t *)vita2d_pool_memalign( (num_segments + 2) * sizeof(uint16_t), sizeof(uint16_t)); vertices[0].x = x; vertices[0].y = y; vertices[0].z = +0.5f; vertices[0].color = color; indices[0] = 0; float theta = 2 * M_PI / (float)num_segments; float c = cosf(theta); float s = sinf(theta); float t; float xx = radius; float yy = 0; int i; for (i = 1; i <= num_segments; i++) { vertices[i].x = x + xx; vertices[i].y = y + yy; vertices[i].z = +0.5f; vertices[i].color = color; indices[i] = i; t = xx; xx = c * xx - s * yy; yy = s * t + c * yy; } indices[num_segments + 1] = 1; sceGxmSetVertexProgram(_vita2d_context, _vita2d_colorVertexProgram); sceGxmSetFragmentProgram(_vita2d_context, _vita2d_colorFragmentProgram); void *vertexDefaultBuffer; sceGxmReserveVertexDefaultUniformBuffer(_vita2d_context, &vertexDefaultBuffer); sceGxmSetUniformDataF(vertexDefaultBuffer, _vita2d_colorWvpParam, 0, 16, _vita2d_ortho_matrix); sceGxmSetVertexStream(_vita2d_context, 0, vertices); sceGxmDraw(_vita2d_context, SCE_GXM_PRIMITIVE_TRIANGLE_FAN, SCE_GXM_INDEX_FORMAT_U16, indices, num_segments + 2); }
gpl-3.0
huangweiqing80/u-boot-2014.04.tq210
drivers/mtd/nand/atmel_nand.c
13
37185
/* * (C) Copyright 2007-2008 * Stelian Pop <stelian@popies.net> * Lead Tech Design <www.leadtechdesign.com> * * (C) Copyright 2006 ATMEL Rousset, Lacressonniere Nicolas * * Add Programmable Multibit ECC support for various AT91 SoC * (C) Copyright 2012 ATMEL, Hong Xu * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/gpio.h> #include <asm/arch/gpio.h> #include <malloc.h> #include <nand.h> #include <watchdog.h> #ifdef CONFIG_ATMEL_NAND_HWECC /* Register access macros */ #define ecc_readl(add, reg) \ readl(AT91_BASE_SYS + add + ATMEL_ECC_##reg) #define ecc_writel(add, reg, value) \ writel((value), AT91_BASE_SYS + add + ATMEL_ECC_##reg) #include "atmel_nand_ecc.h" /* Hardware ECC registers */ #ifdef CONFIG_ATMEL_NAND_HW_PMECC #ifdef CONFIG_SPL_BUILD #undef CONFIG_SYS_NAND_ONFI_DETECTION #endif struct atmel_nand_host { struct pmecc_regs __iomem *pmecc; struct pmecc_errloc_regs __iomem *pmerrloc; void __iomem *pmecc_rom_base; u8 pmecc_corr_cap; u16 pmecc_sector_size; u32 pmecc_index_table_offset; int pmecc_bytes_per_sector; int pmecc_sector_number; int pmecc_degree; /* Degree of remainders */ int pmecc_cw_len; /* Length of codeword */ /* lookup table for alpha_to and index_of */ void __iomem *pmecc_alpha_to; void __iomem *pmecc_index_of; /* data for pmecc computation */ int16_t *pmecc_smu; int16_t *pmecc_partial_syn; int16_t *pmecc_si; int16_t *pmecc_lmu; /* polynomal order */ int *pmecc_mu; int *pmecc_dmu; int *pmecc_delta; }; static struct atmel_nand_host pmecc_host; static struct nand_ecclayout atmel_pmecc_oobinfo; /* * Return number of ecc bytes per sector according to sector size and * correction capability * * Following table shows what at91 PMECC supported: * Correction Capability Sector_512_bytes Sector_1024_bytes * ===================== ================ ================= * 2-bits 4-bytes 4-bytes * 4-bits 7-bytes 7-bytes * 8-bits 13-bytes 14-bytes * 12-bits 20-bytes 21-bytes * 24-bits 39-bytes 42-bytes */ static int pmecc_get_ecc_bytes(int cap, int sector_size) { int m = 12 + sector_size / 512; return (m * cap + 7) / 8; } static void pmecc_config_ecc_layout(struct nand_ecclayout *layout, int oobsize, int ecc_len) { int i; layout->eccbytes = ecc_len; /* ECC will occupy the last ecc_len bytes continuously */ for (i = 0; i < ecc_len; i++) layout->eccpos[i] = oobsize - ecc_len + i; layout->oobfree[0].offset = 2; layout->oobfree[0].length = oobsize - ecc_len - layout->oobfree[0].offset; } static void __iomem *pmecc_get_alpha_to(struct atmel_nand_host *host) { int table_size; table_size = host->pmecc_sector_size == 512 ? PMECC_INDEX_TABLE_SIZE_512 : PMECC_INDEX_TABLE_SIZE_1024; /* the ALPHA lookup table is right behind the INDEX lookup table. */ return host->pmecc_rom_base + host->pmecc_index_table_offset + table_size * sizeof(int16_t); } static void pmecc_data_free(struct atmel_nand_host *host) { free(host->pmecc_partial_syn); free(host->pmecc_si); free(host->pmecc_lmu); free(host->pmecc_smu); free(host->pmecc_mu); free(host->pmecc_dmu); free(host->pmecc_delta); } static int pmecc_data_alloc(struct atmel_nand_host *host) { const int cap = host->pmecc_corr_cap; int size; size = (2 * cap + 1) * sizeof(int16_t); host->pmecc_partial_syn = malloc(size); host->pmecc_si = malloc(size); host->pmecc_lmu = malloc((cap + 1) * sizeof(int16_t)); host->pmecc_smu = malloc((cap + 2) * size); size = (cap + 1) * sizeof(int); host->pmecc_mu = malloc(size); host->pmecc_dmu = malloc(size); host->pmecc_delta = malloc(size); if (host->pmecc_partial_syn && host->pmecc_si && host->pmecc_lmu && host->pmecc_smu && host->pmecc_mu && host->pmecc_dmu && host->pmecc_delta) return 0; /* error happened */ pmecc_data_free(host); return -ENOMEM; } static void pmecc_gen_syndrome(struct mtd_info *mtd, int sector) { struct nand_chip *nand_chip = mtd->priv; struct atmel_nand_host *host = nand_chip->priv; int i; uint32_t value; /* Fill odd syndromes */ for (i = 0; i < host->pmecc_corr_cap; i++) { value = readl(&host->pmecc->rem_port[sector].rem[i / 2]); if (i & 1) value >>= 16; value &= 0xffff; host->pmecc_partial_syn[(2 * i) + 1] = (int16_t)value; } } static void pmecc_substitute(struct mtd_info *mtd) { struct nand_chip *nand_chip = mtd->priv; struct atmel_nand_host *host = nand_chip->priv; int16_t __iomem *alpha_to = host->pmecc_alpha_to; int16_t __iomem *index_of = host->pmecc_index_of; int16_t *partial_syn = host->pmecc_partial_syn; const int cap = host->pmecc_corr_cap; int16_t *si; int i, j; /* si[] is a table that holds the current syndrome value, * an element of that table belongs to the field */ si = host->pmecc_si; memset(&si[1], 0, sizeof(int16_t) * (2 * cap - 1)); /* Computation 2t syndromes based on S(x) */ /* Odd syndromes */ for (i = 1; i < 2 * cap; i += 2) { for (j = 0; j < host->pmecc_degree; j++) { if (partial_syn[i] & (0x1 << j)) si[i] = readw(alpha_to + i * j) ^ si[i]; } } /* Even syndrome = (Odd syndrome) ** 2 */ for (i = 2, j = 1; j <= cap; i = ++j << 1) { if (si[j] == 0) { si[i] = 0; } else { int16_t tmp; tmp = readw(index_of + si[j]); tmp = (tmp * 2) % host->pmecc_cw_len; si[i] = readw(alpha_to + tmp); } } } /* * This function defines a Berlekamp iterative procedure for * finding the value of the error location polynomial. * The input is si[], initialize by pmecc_substitute(). * The output is smu[][]. * * This function is written according to chip datasheet Chapter: * Find the Error Location Polynomial Sigma(x) of Section: * Programmable Multibit ECC Control (PMECC). */ static void pmecc_get_sigma(struct mtd_info *mtd) { struct nand_chip *nand_chip = mtd->priv; struct atmel_nand_host *host = nand_chip->priv; int16_t *lmu = host->pmecc_lmu; int16_t *si = host->pmecc_si; int *mu = host->pmecc_mu; int *dmu = host->pmecc_dmu; /* Discrepancy */ int *delta = host->pmecc_delta; /* Delta order */ int cw_len = host->pmecc_cw_len; const int16_t cap = host->pmecc_corr_cap; const int num = 2 * cap + 1; int16_t __iomem *index_of = host->pmecc_index_of; int16_t __iomem *alpha_to = host->pmecc_alpha_to; int i, j, k; uint32_t dmu_0_count, tmp; int16_t *smu = host->pmecc_smu; /* index of largest delta */ int ro; int largest; int diff; /* Init the Sigma(x) */ memset(smu, 0, sizeof(int16_t) * ARRAY_SIZE(smu)); dmu_0_count = 0; /* First Row */ /* Mu */ mu[0] = -1; smu[0] = 1; /* discrepancy set to 1 */ dmu[0] = 1; /* polynom order set to 0 */ lmu[0] = 0; /* delta[0] = (mu[0] * 2 - lmu[0]) >> 1; */ delta[0] = -1; /* Second Row */ /* Mu */ mu[1] = 0; /* Sigma(x) set to 1 */ smu[num] = 1; /* discrepancy set to S1 */ dmu[1] = si[1]; /* polynom order set to 0 */ lmu[1] = 0; /* delta[1] = (mu[1] * 2 - lmu[1]) >> 1; */ delta[1] = 0; for (i = 1; i <= cap; i++) { mu[i + 1] = i << 1; /* Begin Computing Sigma (Mu+1) and L(mu) */ /* check if discrepancy is set to 0 */ if (dmu[i] == 0) { dmu_0_count++; tmp = ((cap - (lmu[i] >> 1) - 1) / 2); if ((cap - (lmu[i] >> 1) - 1) & 0x1) tmp += 2; else tmp += 1; if (dmu_0_count == tmp) { for (j = 0; j <= (lmu[i] >> 1) + 1; j++) smu[(cap + 1) * num + j] = smu[i * num + j]; lmu[cap + 1] = lmu[i]; return; } /* copy polynom */ for (j = 0; j <= lmu[i] >> 1; j++) smu[(i + 1) * num + j] = smu[i * num + j]; /* copy previous polynom order to the next */ lmu[i + 1] = lmu[i]; } else { ro = 0; largest = -1; /* find largest delta with dmu != 0 */ for (j = 0; j < i; j++) { if ((dmu[j]) && (delta[j] > largest)) { largest = delta[j]; ro = j; } } /* compute difference */ diff = (mu[i] - mu[ro]); /* Compute degree of the new smu polynomial */ if ((lmu[i] >> 1) > ((lmu[ro] >> 1) + diff)) lmu[i + 1] = lmu[i]; else lmu[i + 1] = ((lmu[ro] >> 1) + diff) * 2; /* Init smu[i+1] with 0 */ for (k = 0; k < num; k++) smu[(i + 1) * num + k] = 0; /* Compute smu[i+1] */ for (k = 0; k <= lmu[ro] >> 1; k++) { int16_t a, b, c; if (!(smu[ro * num + k] && dmu[i])) continue; a = readw(index_of + dmu[i]); b = readw(index_of + dmu[ro]); c = readw(index_of + smu[ro * num + k]); tmp = a + (cw_len - b) + c; a = readw(alpha_to + tmp % cw_len); smu[(i + 1) * num + (k + diff)] = a; } for (k = 0; k <= lmu[i] >> 1; k++) smu[(i + 1) * num + k] ^= smu[i * num + k]; } /* End Computing Sigma (Mu+1) and L(mu) */ /* In either case compute delta */ delta[i + 1] = (mu[i + 1] * 2 - lmu[i + 1]) >> 1; /* Do not compute discrepancy for the last iteration */ if (i >= cap) continue; for (k = 0; k <= (lmu[i + 1] >> 1); k++) { tmp = 2 * (i - 1); if (k == 0) { dmu[i + 1] = si[tmp + 3]; } else if (smu[(i + 1) * num + k] && si[tmp + 3 - k]) { int16_t a, b, c; a = readw(index_of + smu[(i + 1) * num + k]); b = si[2 * (i - 1) + 3 - k]; c = readw(index_of + b); tmp = a + c; tmp %= cw_len; dmu[i + 1] = readw(alpha_to + tmp) ^ dmu[i + 1]; } } } } static int pmecc_err_location(struct mtd_info *mtd) { struct nand_chip *nand_chip = mtd->priv; struct atmel_nand_host *host = nand_chip->priv; const int cap = host->pmecc_corr_cap; const int num = 2 * cap + 1; int sector_size = host->pmecc_sector_size; int err_nbr = 0; /* number of error */ int roots_nbr; /* number of roots */ int i; uint32_t val; int16_t *smu = host->pmecc_smu; int timeout = PMECC_MAX_TIMEOUT_US; writel(PMERRLOC_DISABLE, &host->pmerrloc->eldis); for (i = 0; i <= host->pmecc_lmu[cap + 1] >> 1; i++) { writel(smu[(cap + 1) * num + i], &host->pmerrloc->sigma[i]); err_nbr++; } val = PMERRLOC_ELCFG_NUM_ERRORS(err_nbr - 1); if (sector_size == 1024) val |= PMERRLOC_ELCFG_SECTOR_1024; writel(val, &host->pmerrloc->elcfg); writel(sector_size * 8 + host->pmecc_degree * cap, &host->pmerrloc->elen); while (--timeout) { if (readl(&host->pmerrloc->elisr) & PMERRLOC_CALC_DONE) break; WATCHDOG_RESET(); udelay(1); } if (!timeout) { dev_err(host->dev, "atmel_nand : Timeout to calculate PMECC error location\n"); return -1; } roots_nbr = (readl(&host->pmerrloc->elisr) & PMERRLOC_ERR_NUM_MASK) >> 8; /* Number of roots == degree of smu hence <= cap */ if (roots_nbr == host->pmecc_lmu[cap + 1] >> 1) return err_nbr - 1; /* Number of roots does not match the degree of smu * unable to correct error */ return -1; } static void pmecc_correct_data(struct mtd_info *mtd, uint8_t *buf, uint8_t *ecc, int sector_num, int extra_bytes, int err_nbr) { struct nand_chip *nand_chip = mtd->priv; struct atmel_nand_host *host = nand_chip->priv; int i = 0; int byte_pos, bit_pos, sector_size, pos; uint32_t tmp; uint8_t err_byte; sector_size = host->pmecc_sector_size; while (err_nbr) { tmp = readl(&host->pmerrloc->el[i]) - 1; byte_pos = tmp / 8; bit_pos = tmp % 8; if (byte_pos >= (sector_size + extra_bytes)) BUG(); /* should never happen */ if (byte_pos < sector_size) { err_byte = *(buf + byte_pos); *(buf + byte_pos) ^= (1 << bit_pos); pos = sector_num * host->pmecc_sector_size + byte_pos; dev_dbg(host->dev, "Bit flip in data area, byte_pos: %d, bit_pos: %d, 0x%02x -> 0x%02x\n", pos, bit_pos, err_byte, *(buf + byte_pos)); } else { /* Bit flip in OOB area */ tmp = sector_num * host->pmecc_bytes_per_sector + (byte_pos - sector_size); err_byte = ecc[tmp]; ecc[tmp] ^= (1 << bit_pos); pos = tmp + nand_chip->ecc.layout->eccpos[0]; dev_dbg(host->dev, "Bit flip in OOB, oob_byte_pos: %d, bit_pos: %d, 0x%02x -> 0x%02x\n", pos, bit_pos, err_byte, ecc[tmp]); } i++; err_nbr--; } return; } static int pmecc_correction(struct mtd_info *mtd, u32 pmecc_stat, uint8_t *buf, u8 *ecc) { struct nand_chip *nand_chip = mtd->priv; struct atmel_nand_host *host = nand_chip->priv; int i, err_nbr, eccbytes; uint8_t *buf_pos; eccbytes = nand_chip->ecc.bytes; for (i = 0; i < eccbytes; i++) if (ecc[i] != 0xff) goto normal_check; /* Erased page, return OK */ return 0; normal_check: for (i = 0; i < host->pmecc_sector_number; i++) { err_nbr = 0; if (pmecc_stat & 0x1) { buf_pos = buf + i * host->pmecc_sector_size; pmecc_gen_syndrome(mtd, i); pmecc_substitute(mtd); pmecc_get_sigma(mtd); err_nbr = pmecc_err_location(mtd); if (err_nbr == -1) { dev_err(host->dev, "PMECC: Too many errors\n"); mtd->ecc_stats.failed++; return -EIO; } else { pmecc_correct_data(mtd, buf_pos, ecc, i, host->pmecc_bytes_per_sector, err_nbr); mtd->ecc_stats.corrected += err_nbr; } } pmecc_stat >>= 1; } return 0; } static int atmel_nand_pmecc_read_page(struct mtd_info *mtd, struct nand_chip *chip, uint8_t *buf, int oob_required, int page) { struct atmel_nand_host *host = chip->priv; int eccsize = chip->ecc.size; uint8_t *oob = chip->oob_poi; uint32_t *eccpos = chip->ecc.layout->eccpos; uint32_t stat; int timeout = PMECC_MAX_TIMEOUT_US; pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_RST); pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_DISABLE); pmecc_writel(host->pmecc, cfg, ((pmecc_readl(host->pmecc, cfg)) & ~PMECC_CFG_WRITE_OP) | PMECC_CFG_AUTO_ENABLE); pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_ENABLE); pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_DATA); chip->read_buf(mtd, buf, eccsize); chip->read_buf(mtd, oob, mtd->oobsize); while (--timeout) { if (!(pmecc_readl(host->pmecc, sr) & PMECC_SR_BUSY)) break; WATCHDOG_RESET(); udelay(1); } if (!timeout) { dev_err(host->dev, "atmel_nand : Timeout to read PMECC page\n"); return -1; } stat = pmecc_readl(host->pmecc, isr); if (stat != 0) if (pmecc_correction(mtd, stat, buf, &oob[eccpos[0]]) != 0) return -EIO; return 0; } static int atmel_nand_pmecc_write_page(struct mtd_info *mtd, struct nand_chip *chip, const uint8_t *buf, int oob_required) { struct atmel_nand_host *host = chip->priv; uint32_t *eccpos = chip->ecc.layout->eccpos; int i, j; int timeout = PMECC_MAX_TIMEOUT_US; pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_RST); pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_DISABLE); pmecc_writel(host->pmecc, cfg, (pmecc_readl(host->pmecc, cfg) | PMECC_CFG_WRITE_OP) & ~PMECC_CFG_AUTO_ENABLE); pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_ENABLE); pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_DATA); chip->write_buf(mtd, (u8 *)buf, mtd->writesize); while (--timeout) { if (!(pmecc_readl(host->pmecc, sr) & PMECC_SR_BUSY)) break; WATCHDOG_RESET(); udelay(1); } if (!timeout) { dev_err(host->dev, "atmel_nand : Timeout to read PMECC status, fail to write PMECC in oob\n"); goto out; } for (i = 0; i < host->pmecc_sector_number; i++) { for (j = 0; j < host->pmecc_bytes_per_sector; j++) { int pos; pos = i * host->pmecc_bytes_per_sector + j; chip->oob_poi[eccpos[pos]] = readb(&host->pmecc->ecc_port[i].ecc[j]); } } chip->write_buf(mtd, chip->oob_poi, mtd->oobsize); out: return 0; } static void atmel_pmecc_core_init(struct mtd_info *mtd) { struct nand_chip *nand_chip = mtd->priv; struct atmel_nand_host *host = nand_chip->priv; uint32_t val = 0; struct nand_ecclayout *ecc_layout; pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_RST); pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_DISABLE); switch (host->pmecc_corr_cap) { case 2: val = PMECC_CFG_BCH_ERR2; break; case 4: val = PMECC_CFG_BCH_ERR4; break; case 8: val = PMECC_CFG_BCH_ERR8; break; case 12: val = PMECC_CFG_BCH_ERR12; break; case 24: val = PMECC_CFG_BCH_ERR24; break; } if (host->pmecc_sector_size == 512) val |= PMECC_CFG_SECTOR512; else if (host->pmecc_sector_size == 1024) val |= PMECC_CFG_SECTOR1024; switch (host->pmecc_sector_number) { case 1: val |= PMECC_CFG_PAGE_1SECTOR; break; case 2: val |= PMECC_CFG_PAGE_2SECTORS; break; case 4: val |= PMECC_CFG_PAGE_4SECTORS; break; case 8: val |= PMECC_CFG_PAGE_8SECTORS; break; } val |= (PMECC_CFG_READ_OP | PMECC_CFG_SPARE_DISABLE | PMECC_CFG_AUTO_DISABLE); pmecc_writel(host->pmecc, cfg, val); ecc_layout = nand_chip->ecc.layout; pmecc_writel(host->pmecc, sarea, mtd->oobsize - 1); pmecc_writel(host->pmecc, saddr, ecc_layout->eccpos[0]); pmecc_writel(host->pmecc, eaddr, ecc_layout->eccpos[ecc_layout->eccbytes - 1]); /* See datasheet about PMECC Clock Control Register */ pmecc_writel(host->pmecc, clk, PMECC_CLK_133MHZ); pmecc_writel(host->pmecc, idr, 0xff); pmecc_writel(host->pmecc, ctrl, PMECC_CTRL_ENABLE); } #ifdef CONFIG_SYS_NAND_ONFI_DETECTION /* * get_onfi_ecc_param - Get ECC requirement from ONFI parameters * @ecc_bits: store the ONFI ECC correct bits capbility * @sector_size: in how many bytes that ONFI require to correct @ecc_bits * * Returns -1 if ONFI parameters is not supported. In this case @ecc_bits, * @sector_size are initialize to 0. * Return 0 if success to get the ECC requirement. */ static int get_onfi_ecc_param(struct nand_chip *chip, int *ecc_bits, int *sector_size) { *ecc_bits = *sector_size = 0; if (chip->onfi_params.ecc_bits == 0xff) /* TODO: the sector_size and ecc_bits need to be find in * extended ecc parameter, currently we don't support it. */ return -1; *ecc_bits = chip->onfi_params.ecc_bits; /* The default sector size (ecc codeword size) is 512 */ *sector_size = 512; return 0; } /* * pmecc_choose_ecc - Get ecc requirement from ONFI parameters. If * pmecc_corr_cap or pmecc_sector_size is 0, then set it as * ONFI ECC parameters. * @host: point to an atmel_nand_host structure. * if host->pmecc_corr_cap is 0 then set it as the ONFI ecc_bits. * if host->pmecc_sector_size is 0 then set it as the ONFI sector_size. * @chip: point to an nand_chip structure. * @cap: store the ONFI ECC correct bits capbility * @sector_size: in how many bytes that ONFI require to correct @ecc_bits * * Return 0 if success. otherwise return the error code. */ static int pmecc_choose_ecc(struct atmel_nand_host *host, struct nand_chip *chip, int *cap, int *sector_size) { /* Get ECC requirement from ONFI parameters */ *cap = *sector_size = 0; if (chip->onfi_version) { if (!get_onfi_ecc_param(chip, cap, sector_size)) { MTDDEBUG(MTD_DEBUG_LEVEL1, "ONFI params, minimum required ECC: %d bits in %d bytes\n", *cap, *sector_size); } else { dev_info(host->dev, "NAND chip ECC reqirement is in Extended ONFI parameter, we don't support yet.\n"); } } else { dev_info(host->dev, "NAND chip is not ONFI compliant, assume ecc_bits is 2 in 512 bytes"); } if (*cap == 0 && *sector_size == 0) { /* Non-ONFI compliant or use extended ONFI parameters */ *cap = 2; *sector_size = 512; } /* If head file doesn't specify then use the one in ONFI parameters */ if (host->pmecc_corr_cap == 0) { /* use the most fitable ecc bits (the near bigger one ) */ if (*cap <= 2) host->pmecc_corr_cap = 2; else if (*cap <= 4) host->pmecc_corr_cap = 4; else if (*cap <= 8) host->pmecc_corr_cap = 8; else if (*cap <= 12) host->pmecc_corr_cap = 12; else if (*cap <= 24) host->pmecc_corr_cap = 24; else return -EINVAL; } if (host->pmecc_sector_size == 0) { /* use the most fitable sector size (the near smaller one ) */ if (*sector_size >= 1024) host->pmecc_sector_size = 1024; else if (*sector_size >= 512) host->pmecc_sector_size = 512; else return -EINVAL; } return 0; } #endif static int atmel_pmecc_nand_init_params(struct nand_chip *nand, struct mtd_info *mtd) { struct atmel_nand_host *host; int cap, sector_size; host = nand->priv = &pmecc_host; nand->ecc.mode = NAND_ECC_HW; nand->ecc.calculate = NULL; nand->ecc.correct = NULL; nand->ecc.hwctl = NULL; #ifdef CONFIG_SYS_NAND_ONFI_DETECTION host->pmecc_corr_cap = host->pmecc_sector_size = 0; #ifdef CONFIG_PMECC_CAP host->pmecc_corr_cap = CONFIG_PMECC_CAP; #endif #ifdef CONFIG_PMECC_SECTOR_SIZE host->pmecc_sector_size = CONFIG_PMECC_SECTOR_SIZE; #endif /* Get ECC requirement of ONFI parameters. And if CONFIG_PMECC_CAP or * CONFIG_PMECC_SECTOR_SIZE not defined, then use ecc_bits, sector_size * from ONFI. */ if (pmecc_choose_ecc(host, nand, &cap, &sector_size)) { dev_err(host->dev, "The NAND flash's ECC requirement(ecc_bits: %d, sector_size: %d) are not support!", cap, sector_size); return -EINVAL; } if (cap > host->pmecc_corr_cap) dev_info(host->dev, "WARNING: Using different ecc correct bits(%d bit) from Nand ONFI ECC reqirement (%d bit).\n", host->pmecc_corr_cap, cap); if (sector_size < host->pmecc_sector_size) dev_info(host->dev, "WARNING: Using different ecc correct sector size (%d bytes) from Nand ONFI ECC reqirement (%d bytes).\n", host->pmecc_sector_size, sector_size); #else /* CONFIG_SYS_NAND_ONFI_DETECTION */ host->pmecc_corr_cap = CONFIG_PMECC_CAP; host->pmecc_sector_size = CONFIG_PMECC_SECTOR_SIZE; #endif cap = host->pmecc_corr_cap; sector_size = host->pmecc_sector_size; /* TODO: need check whether cap & sector_size is validate */ if (host->pmecc_sector_size == 512) host->pmecc_index_table_offset = ATMEL_PMECC_INDEX_OFFSET_512; else host->pmecc_index_table_offset = ATMEL_PMECC_INDEX_OFFSET_1024; MTDDEBUG(MTD_DEBUG_LEVEL1, "Initialize PMECC params, cap: %d, sector: %d\n", cap, sector_size); host->pmecc = (struct pmecc_regs __iomem *) ATMEL_BASE_PMECC; host->pmerrloc = (struct pmecc_errloc_regs __iomem *) ATMEL_BASE_PMERRLOC; host->pmecc_rom_base = (void __iomem *) ATMEL_BASE_ROM; /* ECC is calculated for the whole page (1 step) */ nand->ecc.size = mtd->writesize; /* set ECC page size and oob layout */ switch (mtd->writesize) { case 2048: case 4096: case 8192: host->pmecc_degree = (sector_size == 512) ? PMECC_GF_DIMENSION_13 : PMECC_GF_DIMENSION_14; host->pmecc_cw_len = (1 << host->pmecc_degree) - 1; host->pmecc_sector_number = mtd->writesize / sector_size; host->pmecc_bytes_per_sector = pmecc_get_ecc_bytes( cap, sector_size); host->pmecc_alpha_to = pmecc_get_alpha_to(host); host->pmecc_index_of = host->pmecc_rom_base + host->pmecc_index_table_offset; nand->ecc.steps = 1; nand->ecc.bytes = host->pmecc_bytes_per_sector * host->pmecc_sector_number; if (nand->ecc.bytes > MTD_MAX_ECCPOS_ENTRIES_LARGE) { dev_err(host->dev, "too large eccpos entries. max support ecc.bytes is %d\n", MTD_MAX_ECCPOS_ENTRIES_LARGE); return -EINVAL; } if (nand->ecc.bytes > mtd->oobsize - 2) { dev_err(host->dev, "No room for ECC bytes\n"); return -EINVAL; } pmecc_config_ecc_layout(&atmel_pmecc_oobinfo, mtd->oobsize, nand->ecc.bytes); nand->ecc.layout = &atmel_pmecc_oobinfo; break; case 512: case 1024: /* TODO */ dev_err(host->dev, "Unsupported page size for PMECC, use Software ECC\n"); default: /* page size not handled by HW ECC */ /* switching back to soft ECC */ nand->ecc.mode = NAND_ECC_SOFT; nand->ecc.read_page = NULL; nand->ecc.postpad = 0; nand->ecc.prepad = 0; nand->ecc.bytes = 0; return 0; } /* Allocate data for PMECC computation */ if (pmecc_data_alloc(host)) { dev_err(host->dev, "Cannot allocate memory for PMECC computation!\n"); return -ENOMEM; } nand->ecc.read_page = atmel_nand_pmecc_read_page; nand->ecc.write_page = atmel_nand_pmecc_write_page; nand->ecc.strength = cap; atmel_pmecc_core_init(mtd); return 0; } #else /* oob layout for large page size * bad block info is on bytes 0 and 1 * the bytes have to be consecutives to avoid * several NAND_CMD_RNDOUT during read */ static struct nand_ecclayout atmel_oobinfo_large = { .eccbytes = 4, .eccpos = {60, 61, 62, 63}, .oobfree = { {2, 58} }, }; /* oob layout for small page size * bad block info is on bytes 4 and 5 * the bytes have to be consecutives to avoid * several NAND_CMD_RNDOUT during read */ static struct nand_ecclayout atmel_oobinfo_small = { .eccbytes = 4, .eccpos = {0, 1, 2, 3}, .oobfree = { {6, 10} }, }; /* * Calculate HW ECC * * function called after a write * * mtd: MTD block structure * dat: raw data (unused) * ecc_code: buffer for ECC */ static int atmel_nand_calculate(struct mtd_info *mtd, const u_char *dat, unsigned char *ecc_code) { unsigned int ecc_value; /* get the first 2 ECC bytes */ ecc_value = ecc_readl(CONFIG_SYS_NAND_ECC_BASE, PR); ecc_code[0] = ecc_value & 0xFF; ecc_code[1] = (ecc_value >> 8) & 0xFF; /* get the last 2 ECC bytes */ ecc_value = ecc_readl(CONFIG_SYS_NAND_ECC_BASE, NPR) & ATMEL_ECC_NPARITY; ecc_code[2] = ecc_value & 0xFF; ecc_code[3] = (ecc_value >> 8) & 0xFF; return 0; } /* * HW ECC read page function * * mtd: mtd info structure * chip: nand chip info structure * buf: buffer to store read data * oob_required: caller expects OOB data read to chip->oob_poi */ static int atmel_nand_read_page(struct mtd_info *mtd, struct nand_chip *chip, uint8_t *buf, int oob_required, int page) { int eccsize = chip->ecc.size; int eccbytes = chip->ecc.bytes; uint32_t *eccpos = chip->ecc.layout->eccpos; uint8_t *p = buf; uint8_t *oob = chip->oob_poi; uint8_t *ecc_pos; int stat; /* read the page */ chip->read_buf(mtd, p, eccsize); /* move to ECC position if needed */ if (eccpos[0] != 0) { /* This only works on large pages * because the ECC controller waits for * NAND_CMD_RNDOUTSTART after the * NAND_CMD_RNDOUT. * anyway, for small pages, the eccpos[0] == 0 */ chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize + eccpos[0], -1); } /* the ECC controller needs to read the ECC just after the data */ ecc_pos = oob + eccpos[0]; chip->read_buf(mtd, ecc_pos, eccbytes); /* check if there's an error */ stat = chip->ecc.correct(mtd, p, oob, NULL); if (stat < 0) mtd->ecc_stats.failed++; else mtd->ecc_stats.corrected += stat; /* get back to oob start (end of page) */ chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1); /* read the oob */ chip->read_buf(mtd, oob, mtd->oobsize); return 0; } /* * HW ECC Correction * * function called after a read * * mtd: MTD block structure * dat: raw data read from the chip * read_ecc: ECC from the chip (unused) * isnull: unused * * Detect and correct a 1 bit error for a page */ static int atmel_nand_correct(struct mtd_info *mtd, u_char *dat, u_char *read_ecc, u_char *isnull) { struct nand_chip *nand_chip = mtd->priv; unsigned int ecc_status; unsigned int ecc_word, ecc_bit; /* get the status from the Status Register */ ecc_status = ecc_readl(CONFIG_SYS_NAND_ECC_BASE, SR); /* if there's no error */ if (likely(!(ecc_status & ATMEL_ECC_RECERR))) return 0; /* get error bit offset (4 bits) */ ecc_bit = ecc_readl(CONFIG_SYS_NAND_ECC_BASE, PR) & ATMEL_ECC_BITADDR; /* get word address (12 bits) */ ecc_word = ecc_readl(CONFIG_SYS_NAND_ECC_BASE, PR) & ATMEL_ECC_WORDADDR; ecc_word >>= 4; /* if there are multiple errors */ if (ecc_status & ATMEL_ECC_MULERR) { /* check if it is a freshly erased block * (filled with 0xff) */ if ((ecc_bit == ATMEL_ECC_BITADDR) && (ecc_word == (ATMEL_ECC_WORDADDR >> 4))) { /* the block has just been erased, return OK */ return 0; } /* it doesn't seems to be a freshly * erased block. * We can't correct so many errors */ dev_warn(host->dev, "atmel_nand : multiple errors detected." " Unable to correct.\n"); return -EIO; } /* if there's a single bit error : we can correct it */ if (ecc_status & ATMEL_ECC_ECCERR) { /* there's nothing much to do here. * the bit error is on the ECC itself. */ dev_warn(host->dev, "atmel_nand : one bit error on ECC code." " Nothing to correct\n"); return 0; } dev_warn(host->dev, "atmel_nand : one bit error on data." " (word offset in the page :" " 0x%x bit offset : 0x%x)\n", ecc_word, ecc_bit); /* correct the error */ if (nand_chip->options & NAND_BUSWIDTH_16) { /* 16 bits words */ ((unsigned short *) dat)[ecc_word] ^= (1 << ecc_bit); } else { /* 8 bits words */ dat[ecc_word] ^= (1 << ecc_bit); } dev_warn(host->dev, "atmel_nand : error corrected\n"); return 1; } /* * Enable HW ECC : unused on most chips */ static void atmel_nand_hwctl(struct mtd_info *mtd, int mode) { } int atmel_hwecc_nand_init_param(struct nand_chip *nand, struct mtd_info *mtd) { nand->ecc.mode = NAND_ECC_HW; nand->ecc.calculate = atmel_nand_calculate; nand->ecc.correct = atmel_nand_correct; nand->ecc.hwctl = atmel_nand_hwctl; nand->ecc.read_page = atmel_nand_read_page; nand->ecc.bytes = 4; if (nand->ecc.mode == NAND_ECC_HW) { /* ECC is calculated for the whole page (1 step) */ nand->ecc.size = mtd->writesize; /* set ECC page size and oob layout */ switch (mtd->writesize) { case 512: nand->ecc.layout = &atmel_oobinfo_small; ecc_writel(CONFIG_SYS_NAND_ECC_BASE, MR, ATMEL_ECC_PAGESIZE_528); break; case 1024: nand->ecc.layout = &atmel_oobinfo_large; ecc_writel(CONFIG_SYS_NAND_ECC_BASE, MR, ATMEL_ECC_PAGESIZE_1056); break; case 2048: nand->ecc.layout = &atmel_oobinfo_large; ecc_writel(CONFIG_SYS_NAND_ECC_BASE, MR, ATMEL_ECC_PAGESIZE_2112); break; case 4096: nand->ecc.layout = &atmel_oobinfo_large; ecc_writel(CONFIG_SYS_NAND_ECC_BASE, MR, ATMEL_ECC_PAGESIZE_4224); break; default: /* page size not handled by HW ECC */ /* switching back to soft ECC */ nand->ecc.mode = NAND_ECC_SOFT; nand->ecc.calculate = NULL; nand->ecc.correct = NULL; nand->ecc.hwctl = NULL; nand->ecc.read_page = NULL; nand->ecc.postpad = 0; nand->ecc.prepad = 0; nand->ecc.bytes = 0; break; } } return 0; } #endif /* CONFIG_ATMEL_NAND_HW_PMECC */ #endif /* CONFIG_ATMEL_NAND_HWECC */ static void at91_nand_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int ctrl) { struct nand_chip *this = mtd->priv; if (ctrl & NAND_CTRL_CHANGE) { ulong IO_ADDR_W = (ulong) this->IO_ADDR_W; IO_ADDR_W &= ~(CONFIG_SYS_NAND_MASK_ALE | CONFIG_SYS_NAND_MASK_CLE); if (ctrl & NAND_CLE) IO_ADDR_W |= CONFIG_SYS_NAND_MASK_CLE; if (ctrl & NAND_ALE) IO_ADDR_W |= CONFIG_SYS_NAND_MASK_ALE; #ifdef CONFIG_SYS_NAND_ENABLE_PIN gpio_set_value(CONFIG_SYS_NAND_ENABLE_PIN, !(ctrl & NAND_NCE)); #endif this->IO_ADDR_W = (void *) IO_ADDR_W; } if (cmd != NAND_CMD_NONE) writeb(cmd, this->IO_ADDR_W); } #ifdef CONFIG_SYS_NAND_READY_PIN static int at91_nand_ready(struct mtd_info *mtd) { return gpio_get_value(CONFIG_SYS_NAND_READY_PIN); } #endif #ifdef CONFIG_SPL_BUILD /* The following code is for SPL */ static nand_info_t mtd; static struct nand_chip nand_chip; static int nand_command(int block, int page, uint32_t offs, u8 cmd) { struct nand_chip *this = mtd.priv; int page_addr = page + block * CONFIG_SYS_NAND_PAGE_COUNT; void (*hwctrl)(struct mtd_info *mtd, int cmd, unsigned int ctrl) = this->cmd_ctrl; while (this->dev_ready(&mtd)) ; if (cmd == NAND_CMD_READOOB) { offs += CONFIG_SYS_NAND_PAGE_SIZE; cmd = NAND_CMD_READ0; } hwctrl(&mtd, cmd, NAND_CTRL_CLE | NAND_CTRL_CHANGE); if (this->options & NAND_BUSWIDTH_16) offs >>= 1; hwctrl(&mtd, offs & 0xff, NAND_CTRL_ALE | NAND_CTRL_CHANGE); hwctrl(&mtd, (offs >> 8) & 0xff, NAND_CTRL_ALE); hwctrl(&mtd, (page_addr & 0xff), NAND_CTRL_ALE); hwctrl(&mtd, ((page_addr >> 8) & 0xff), NAND_CTRL_ALE); #ifdef CONFIG_SYS_NAND_5_ADDR_CYCLE hwctrl(&mtd, (page_addr >> 16) & 0x0f, NAND_CTRL_ALE); #endif hwctrl(&mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE); hwctrl(&mtd, NAND_CMD_READSTART, NAND_CTRL_CLE | NAND_CTRL_CHANGE); hwctrl(&mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE); while (this->dev_ready(&mtd)) ; return 0; } static int nand_is_bad_block(int block) { struct nand_chip *this = mtd.priv; nand_command(block, 0, CONFIG_SYS_NAND_BAD_BLOCK_POS, NAND_CMD_READOOB); if (this->options & NAND_BUSWIDTH_16) { if (readw(this->IO_ADDR_R) != 0xffff) return 1; } else { if (readb(this->IO_ADDR_R) != 0xff) return 1; } return 0; } #ifdef CONFIG_SPL_NAND_ECC static int nand_ecc_pos[] = CONFIG_SYS_NAND_ECCPOS; #define ECCSTEPS (CONFIG_SYS_NAND_PAGE_SIZE / \ CONFIG_SYS_NAND_ECCSIZE) #define ECCTOTAL (ECCSTEPS * CONFIG_SYS_NAND_ECCBYTES) static int nand_read_page(int block, int page, void *dst) { struct nand_chip *this = mtd.priv; u_char ecc_calc[ECCTOTAL]; u_char ecc_code[ECCTOTAL]; u_char oob_data[CONFIG_SYS_NAND_OOBSIZE]; int eccsize = CONFIG_SYS_NAND_ECCSIZE; int eccbytes = CONFIG_SYS_NAND_ECCBYTES; int eccsteps = ECCSTEPS; int i; uint8_t *p = dst; nand_command(block, page, 0, NAND_CMD_READ0); for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) { if (this->ecc.mode != NAND_ECC_SOFT) this->ecc.hwctl(&mtd, NAND_ECC_READ); this->read_buf(&mtd, p, eccsize); this->ecc.calculate(&mtd, p, &ecc_calc[i]); } this->read_buf(&mtd, oob_data, CONFIG_SYS_NAND_OOBSIZE); for (i = 0; i < ECCTOTAL; i++) ecc_code[i] = oob_data[nand_ecc_pos[i]]; eccsteps = ECCSTEPS; p = dst; for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) this->ecc.correct(&mtd, p, &ecc_code[i], &ecc_calc[i]); return 0; } #else static int nand_read_page(int block, int page, void *dst) { struct nand_chip *this = mtd.priv; nand_command(block, page, 0, NAND_CMD_READ0); atmel_nand_pmecc_read_page(&mtd, this, dst, 0, page); return 0; } #endif /* CONFIG_SPL_NAND_ECC */ int nand_spl_load_image(uint32_t offs, unsigned int size, void *dst) { unsigned int block, lastblock; unsigned int page; block = offs / CONFIG_SYS_NAND_BLOCK_SIZE; lastblock = (offs + size - 1) / CONFIG_SYS_NAND_BLOCK_SIZE; page = (offs % CONFIG_SYS_NAND_BLOCK_SIZE) / CONFIG_SYS_NAND_PAGE_SIZE; while (block <= lastblock) { if (!nand_is_bad_block(block)) { while (page < CONFIG_SYS_NAND_PAGE_COUNT) { nand_read_page(block, page, dst); dst += CONFIG_SYS_NAND_PAGE_SIZE; page++; } page = 0; } else { lastblock++; } block++; } return 0; } int at91_nand_wait_ready(struct mtd_info *mtd) { struct nand_chip *this = mtd->priv; udelay(this->chip_delay); return 0; } int board_nand_init(struct nand_chip *nand) { int ret = 0; nand->ecc.mode = NAND_ECC_SOFT; #ifdef CONFIG_SYS_NAND_DBW_16 nand->options = NAND_BUSWIDTH_16; nand->read_buf = nand_read_buf16; #else nand->read_buf = nand_read_buf; #endif nand->cmd_ctrl = at91_nand_hwcontrol; #ifdef CONFIG_SYS_NAND_READY_PIN nand->dev_ready = at91_nand_ready; #else nand->dev_ready = at91_nand_wait_ready; #endif nand->chip_delay = 20; #ifdef CONFIG_ATMEL_NAND_HWECC #ifdef CONFIG_ATMEL_NAND_HW_PMECC ret = atmel_pmecc_nand_init_params(nand, &mtd); #endif #endif return ret; } void nand_init(void) { mtd.writesize = CONFIG_SYS_NAND_PAGE_SIZE; mtd.oobsize = CONFIG_SYS_NAND_OOBSIZE; mtd.priv = &nand_chip; nand_chip.IO_ADDR_R = (void __iomem *)CONFIG_SYS_NAND_BASE; nand_chip.IO_ADDR_W = (void __iomem *)CONFIG_SYS_NAND_BASE; board_nand_init(&nand_chip); #ifdef CONFIG_SPL_NAND_ECC if (nand_chip.ecc.mode == NAND_ECC_SOFT) { nand_chip.ecc.calculate = nand_calculate_ecc; nand_chip.ecc.correct = nand_correct_data; } #endif if (nand_chip.select_chip) nand_chip.select_chip(&mtd, 0); } void nand_deselect(void) { if (nand_chip.select_chip) nand_chip.select_chip(&mtd, -1); } #else #ifndef CONFIG_SYS_NAND_BASE_LIST #define CONFIG_SYS_NAND_BASE_LIST { CONFIG_SYS_NAND_BASE } #endif static struct nand_chip nand_chip[CONFIG_SYS_MAX_NAND_DEVICE]; static ulong base_addr[CONFIG_SYS_MAX_NAND_DEVICE] = CONFIG_SYS_NAND_BASE_LIST; int atmel_nand_chip_init(int devnum, ulong base_addr) { int ret; struct mtd_info *mtd = &nand_info[devnum]; struct nand_chip *nand = &nand_chip[devnum]; mtd->priv = nand; nand->IO_ADDR_R = nand->IO_ADDR_W = (void __iomem *)base_addr; #ifdef CONFIG_NAND_ECC_BCH nand->ecc.mode = NAND_ECC_SOFT_BCH; #else nand->ecc.mode = NAND_ECC_SOFT; #endif #ifdef CONFIG_SYS_NAND_DBW_16 nand->options = NAND_BUSWIDTH_16; #endif nand->cmd_ctrl = at91_nand_hwcontrol; #ifdef CONFIG_SYS_NAND_READY_PIN nand->dev_ready = at91_nand_ready; #endif nand->chip_delay = 75; ret = nand_scan_ident(mtd, CONFIG_SYS_NAND_MAX_CHIPS, NULL); if (ret) return ret; #ifdef CONFIG_ATMEL_NAND_HWECC #ifdef CONFIG_ATMEL_NAND_HW_PMECC ret = atmel_pmecc_nand_init_params(nand, mtd); #else ret = atmel_hwecc_nand_init_param(nand, mtd); #endif if (ret) return ret; #endif ret = nand_scan_tail(mtd); if (!ret) nand_register(devnum); return ret; } void board_nand_init(void) { int i; for (i = 0; i < CONFIG_SYS_MAX_NAND_DEVICE; i++) if (atmel_nand_chip_init(i, base_addr[i])) dev_err(host->dev, "atmel_nand: Fail to initialize #%d chip", i); } #endif /* CONFIG_SPL_BUILD */
gpl-3.0
sabel83/metashell
3rd/templight/llvm/unittests/ExecutionEngine/Orc/IndirectionUtilsTest.cpp
13
1994
//===- LazyEmittingLayerTest.cpp - Unit tests for the lazy emitting layer -===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h" #include "OrcTestCommon.h" #include "llvm/ADT/SmallVector.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(IndirectionUtilsTest, MakeStub) { LLVMContext Context; ModuleBuilder MB(Context, "x86_64-apple-macosx10.10", ""); FunctionType *FTy = FunctionType::get( Type::getVoidTy(Context), {getDummyStructTy(Context), getDummyStructTy(Context)}, false); Function *F = MB.createFunctionDecl(FTy, ""); AttributeSet FnAttrs = AttributeSet::get( Context, AttrBuilder().addAttribute(Attribute::NoUnwind)); AttributeSet RetAttrs; // None AttributeSet ArgAttrs[2] = { AttributeSet::get(Context, AttrBuilder().addAttribute(Attribute::StructRet)), AttributeSet::get(Context, AttrBuilder().addAttribute(Attribute::ByVal)), }; F->setAttributes(AttributeList::get(Context, FnAttrs, RetAttrs, ArgAttrs)); auto ImplPtr = orc::createImplPointer(*F->getType(), *MB.getModule(), "", nullptr); orc::makeStub(*F, *ImplPtr); auto II = F->getEntryBlock().begin(); EXPECT_TRUE(isa<LoadInst>(*II)) << "First instruction of stub should be a load."; auto *Call = dyn_cast<CallInst>(std::next(II)); EXPECT_TRUE(Call != nullptr) << "Second instruction of stub should be a call."; EXPECT_TRUE(Call->isTailCall()) << "Indirect call from stub should be tail call."; EXPECT_TRUE(Call->hasStructRetAttr()) << "makeStub should propagate sret attr on 1st argument."; EXPECT_TRUE(Call->paramHasAttr(1U, Attribute::ByVal)) << "makeStub should propagate byval attr on 2nd argument."; } }
gpl-3.0
pagaille/libsigrok
src/output/ols.c
15
4035
/* * This file is part of the libsigrok project. * * Copyright (C) 2011 Uwe Hermann <uwe@hermann-uwe.de> * Copyright (C) 2013 Bert Vermeulen <bert@biot.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. * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ /* * This implements version 1.3 of the output format for the OpenBench Logic * Sniffer "Alternative" Java client. Details: * https://github.com/jawi/ols/wiki/OLS-data-file-format */ #include <config.h> #include <stdlib.h> #include <string.h> #include <glib.h> #include <libsigrok/libsigrok.h> #include "libsigrok-internal.h" #define LOG_PREFIX "output/ols" struct context { uint64_t samplerate; uint64_t num_samples; }; static int init(struct sr_output *o, GHashTable *options) { struct context *ctx; (void)options; ctx = g_malloc0(sizeof(struct context)); o->priv = ctx; ctx->samplerate = 0; ctx->num_samples = 0; return SR_OK; } static GString *gen_header(const struct sr_dev_inst *sdi, struct context *ctx) { struct sr_channel *ch; GSList *l; GString *s; GVariant *gvar; int num_enabled_channels; if (!ctx->samplerate && sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar) == SR_OK) { ctx->samplerate = g_variant_get_uint64(gvar); g_variant_unref(gvar); } num_enabled_channels = 0; for (l = sdi->channels; l; l = l->next) { ch = l->data; if (ch->type != SR_CHANNEL_LOGIC) continue; if (!ch->enabled) continue; num_enabled_channels++; } s = g_string_sized_new(512); g_string_append_printf(s, ";Rate: %"PRIu64"\n", ctx->samplerate); g_string_append_printf(s, ";Channels: %d\n", num_enabled_channels); g_string_append_printf(s, ";EnabledChannels: -1\n"); g_string_append_printf(s, ";Compressed: true\n"); g_string_append_printf(s, ";CursorEnabled: false\n"); return s; } static int receive(const struct sr_output *o, const struct sr_datafeed_packet *packet, GString **out) { struct context *ctx; const struct sr_datafeed_meta *meta; const struct sr_datafeed_logic *logic; const struct sr_config *src; GSList *l; unsigned int i, j; uint8_t c; *out = NULL; if (!o || !o->sdi) return SR_ERR_ARG; ctx = o->priv; switch (packet->type) { case SR_DF_META: meta = packet->payload; for (l = meta->config; l; l = l->next) { src = l->data; if (src->key == SR_CONF_SAMPLERATE) ctx->samplerate = g_variant_get_uint64(src->data); } break; case SR_DF_LOGIC: logic = packet->payload; if (ctx->num_samples == 0) { /* First logic packet in the feed. */ *out = gen_header(o->sdi, ctx); } else *out = g_string_sized_new(512); for (i = 0; i <= logic->length - logic->unitsize; i += logic->unitsize) { for (j = 0; j < logic->unitsize; j++) { /* The OLS format wants the samples presented MSB first. */ c = *((uint8_t *)logic->data + i + logic->unitsize - 1 - j); g_string_append_printf(*out, "%02x", c); } g_string_append_printf(*out, "@%"PRIu64"\n", ctx->num_samples++); } break; } return SR_OK; } static int cleanup(struct sr_output *o) { struct context *ctx; if (!o || !o->sdi) return SR_ERR_ARG; ctx = o->priv; g_free(ctx); o->priv = NULL; return SR_OK; } SR_PRIV struct sr_output_module output_ols = { .id = "ols", .name = "OLS", .desc = "OpenBench Logic Sniffer", .exts = (const char*[]){"ols", NULL}, .flags = 0, .options = NULL, .init = init, .receive = receive, .cleanup = cleanup };
gpl-3.0
tecip-nes/pyot
contiki-tres/examples/sky-ip/sky-webserver.c
15
2022
/* * Copyright (c) 2006, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. * * This file is part of the Contiki operating system. * */ /** * \file * Multi-hop webserver for the Tmote Sky * \author * Adam Dunkels <adam@sics.se> */ #include "webserver-nogui.h" #include "contiki.h" /*---------------------------------------------------------------------------*/ AUTOSTART_PROCESSES(&webserver_nogui_process); /*---------------------------------------------------------------------------*/
gpl-3.0
piksels-and-lines-orchestra/gimp
plug-ins/imagemap/imap_cmd_select.c
16
2044
/* * This is a plug-in for GIMP. * * Generates clickable image maps. * * Copyright (C) 1998-2003 Maurits Rijk lpeek.mrijk@consunet.nl * * 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" #include <gtk/gtk.h> #include "imap_commands.h" #include "libgimp/stdplugins-intl.h" static void select_command_destruct(Command_t *parent); static CmdExecuteValue_t select_command_execute(Command_t *parent); static void select_command_undo(Command_t *parent); static CommandClass_t select_command_class = { select_command_destruct, select_command_execute, select_command_undo, NULL /* select_command_redo */ }; typedef struct { Command_t parent; Object_t *obj; } SelectCommand_t; Command_t* select_command_new(Object_t *obj) { SelectCommand_t *command = g_new(SelectCommand_t, 1); command->obj = object_ref(obj); return command_init(&command->parent, _("Select"), &select_command_class); } static void select_command_destruct(Command_t *parent) { SelectCommand_t *command = (SelectCommand_t*) parent; object_unref(command->obj); } static CmdExecuteValue_t select_command_execute(Command_t *parent) { SelectCommand_t *command = (SelectCommand_t*) parent; object_select(command->obj); return CMD_APPEND; } static void select_command_undo(Command_t *parent) { SelectCommand_t *command = (SelectCommand_t*) parent; object_unselect(command->obj); }
gpl-3.0
chuank/firmware
tests/unit/character.cpp
17
2080
#include "catch.hpp" #include "spark_wiring_character.h" // smoke tests for character APIs TEST_CASE("isAlpha") { CHECK(isAlpha('a')); CHECK(isAlpha('Z')); CHECK(!isAlpha('@')); } TEST_CASE("isAlphaNumeric") { CHECK(isAlphaNumeric('a')); CHECK(isAlphaNumeric('Z')); CHECK(!isAlphaNumeric('@')); CHECK(isAlphaNumeric('5')); } TEST_CASE("isAscii") { CHECK(isAscii('a')); CHECK(isAscii('Z')); CHECK(isAscii('~')); CHECK(!isAscii(0x80)); } TEST_CASE("isControl") { for (int i=0; i<0x1f; i++) { CHECK(isControl(i)); } CHECK(!isControl('r')); CHECK(!isControl('F')); } TEST_CASE("isDigit") { for (int i=0; i<256; i++) { CHECK(isDigit(i)== (i>='0' && i<='9')); } } TEST_CASE("isGraph") { CHECK(!isGraph(' ')); CHECK(isGraph('G')); } TEST_CASE("isHexadecimalDigit") { CHECK(isHexadecimalDigit('A')); CHECK(isHexadecimalDigit('f')); CHECK(!isHexadecimalDigit('G')); CHECK(isHexadecimalDigit('9')); } TEST_CASE("isLowerCase") { CHECK(isLowerCase('l')); CHECK(!isLowerCase('L')); CHECK(!isLowerCase('5')); } TEST_CASE("isPrintable") { CHECK(!isPrintable(0x1f)); CHECK(isPrintable(' ')); CHECK(isPrintable('q')); } TEST_CASE("isPunct") { CHECK(isPunct('.')); CHECK(!isPunct(' ')); CHECK(isPunct('#')); CHECK(isPunct('$')); } TEST_CASE("isSpace") { CHECK(isSpace(' ')); CHECK(isSpace('\t')); CHECK(isSpace('\n')); CHECK(!isSpace('_')); } TEST_CASE("isUpperCase") { CHECK(isUpperCase('A')); CHECK(!isUpperCase('5')); CHECK(!isUpperCase('f')); } TEST_CASE("isWhitespace") { CHECK(isWhitespace(' ')); CHECK(isWhitespace('\t')); CHECK(!isWhitespace('\n')); CHECK(!isWhitespace('_')); CHECK(!isWhitespace('0')); } TEST_CASE("toLowerCase") { CHECK(toLowerCase('A')=='a'); CHECK(toLowerCase('Z')=='z'); CHECK(toLowerCase('6')=='6'); } TEST_CASE("toUpperCase") { CHECK(toUpperCase('a')=='A'); CHECK(toUpperCase('z')=='Z'); CHECK(toUpperCase('6')=='6'); }
gpl-3.0
pwojnowski/emacs
src/intervals.c
17
69952
/* Code for doing intervals. Copyright (C) 1993-1995, 1997-1998, 2001-2015 Free Software Foundation, Inc. This file is part of GNU Emacs. GNU Emacs 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. GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */ /* NOTES: Have to ensure that we can't put symbol nil on a plist, or some functions may work incorrectly. An idea: Have the owner of the tree keep count of splits and/or insertion lengths (in intervals), and balance after every N. Need to call *_left_hook when buffer is killed. Scan for zero-length, or 0-length to see notes about handling zero length interval-markers. There are comments around about freeing intervals. It might be faster to explicitly free them (put them on the free list) than to GC them. */ #include <config.h> #include <intprops.h> #include "lisp.h" #include "intervals.h" #include "character.h" #include "buffer.h" #include "puresize.h" #include "keyboard.h" #include "keymap.h" /* Test for membership, allowing for t (actually any non-cons) to mean the universal set. */ #define TMEM(sym, set) (CONSP (set) ? ! NILP (Fmemq (sym, set)) : ! NILP (set)) static Lisp_Object merge_properties_sticky (Lisp_Object, Lisp_Object); static INTERVAL merge_interval_right (INTERVAL); static INTERVAL reproduce_tree (INTERVAL, INTERVAL); /* Utility functions for intervals. */ /* Use these functions to set pointer slots of struct interval. */ static void set_interval_left (INTERVAL i, INTERVAL left) { i->left = left; } static void set_interval_right (INTERVAL i, INTERVAL right) { i->right = right; } /* Make the parent of D be whatever the parent of S is, regardless of the type. This is used when balancing an interval tree. */ static void copy_interval_parent (INTERVAL d, INTERVAL s) { d->up = s->up; d->up_obj = s->up_obj; } /* Create the root interval of some object, a buffer or string. */ INTERVAL create_root_interval (Lisp_Object parent) { INTERVAL new; CHECK_IMPURE (parent); new = make_interval (); if (BUFFERP (parent)) { new->total_length = (BUF_Z (XBUFFER (parent)) - BUF_BEG (XBUFFER (parent))); eassert (TOTAL_LENGTH (new) >= 0); set_buffer_intervals (XBUFFER (parent), new); new->position = BEG; } else if (STRINGP (parent)) { new->total_length = SCHARS (parent); eassert (TOTAL_LENGTH (new) >= 0); set_string_intervals (parent, new); new->position = 0; } eassert (LENGTH (new) > 0); set_interval_object (new, parent); return new; } /* Make the interval TARGET have exactly the properties of SOURCE. */ void copy_properties (register INTERVAL source, register INTERVAL target) { if (DEFAULT_INTERVAL_P (source) && DEFAULT_INTERVAL_P (target)) return; COPY_INTERVAL_CACHE (source, target); set_interval_plist (target, Fcopy_sequence (source->plist)); } /* Merge the properties of interval SOURCE into the properties of interval TARGET. That is to say, each property in SOURCE is added to TARGET if TARGET has no such property as yet. */ static void merge_properties (register INTERVAL source, register INTERVAL target) { register Lisp_Object o, sym, val; if (DEFAULT_INTERVAL_P (source) && DEFAULT_INTERVAL_P (target)) return; MERGE_INTERVAL_CACHE (source, target); o = source->plist; while (CONSP (o)) { sym = XCAR (o); o = XCDR (o); CHECK_CONS (o); val = target->plist; while (CONSP (val) && !EQ (XCAR (val), sym)) { val = XCDR (val); if (!CONSP (val)) break; val = XCDR (val); } if (NILP (val)) { val = XCAR (o); set_interval_plist (target, Fcons (sym, Fcons (val, target->plist))); } o = XCDR (o); } } /* Return true if the two intervals have the same properties. */ bool intervals_equal (INTERVAL i0, INTERVAL i1) { Lisp_Object i0_cdr, i0_sym; Lisp_Object i1_cdr, i1_val; if (DEFAULT_INTERVAL_P (i0) && DEFAULT_INTERVAL_P (i1)) return true; if (DEFAULT_INTERVAL_P (i0) || DEFAULT_INTERVAL_P (i1)) return false; i0_cdr = i0->plist; i1_cdr = i1->plist; while (CONSP (i0_cdr) && CONSP (i1_cdr)) { i0_sym = XCAR (i0_cdr); i0_cdr = XCDR (i0_cdr); if (!CONSP (i0_cdr)) return false; i1_val = i1->plist; while (CONSP (i1_val) && !EQ (XCAR (i1_val), i0_sym)) { i1_val = XCDR (i1_val); if (!CONSP (i1_val)) return false; i1_val = XCDR (i1_val); } /* i0 has something i1 doesn't. */ if (EQ (i1_val, Qnil)) return false; /* i0 and i1 both have sym, but it has different values in each. */ if (!CONSP (i1_val) || (i1_val = XCDR (i1_val), !CONSP (i1_val)) || !EQ (XCAR (i1_val), XCAR (i0_cdr))) return false; i0_cdr = XCDR (i0_cdr); i1_cdr = XCDR (i1_cdr); if (!CONSP (i1_cdr)) return false; i1_cdr = XCDR (i1_cdr); } /* Lengths of the two plists were equal. */ return (NILP (i0_cdr) && NILP (i1_cdr)); } /* Traverse an interval tree TREE, performing FUNCTION on each node. No guarantee is made about the order of traversal. Pass FUNCTION two args: an interval, and ARG. */ void traverse_intervals_noorder (INTERVAL tree, void (*function) (INTERVAL, Lisp_Object), Lisp_Object arg) { /* Minimize stack usage. */ while (tree) { (*function) (tree, arg); if (!tree->right) tree = tree->left; else { traverse_intervals_noorder (tree->left, function, arg); tree = tree->right; } } } /* Traverse an interval tree TREE, performing FUNCTION on each node. Pass FUNCTION two args: an interval, and ARG. */ void traverse_intervals (INTERVAL tree, ptrdiff_t position, void (*function) (INTERVAL, Lisp_Object), Lisp_Object arg) { while (tree) { traverse_intervals (tree->left, position, function, arg); position += LEFT_TOTAL_LENGTH (tree); tree->position = position; (*function) (tree, arg); position += LENGTH (tree); tree = tree->right; } } #if 0 static int icount; static int idepth; static int zero_length; /* These functions are temporary, for debugging purposes only. */ INTERVAL search_interval, found_interval; void check_for_interval (INTERVAL i) { if (i == search_interval) { found_interval = i; icount++; } } INTERVAL search_for_interval (INTERVAL i, INTERVAL tree) { icount = 0; search_interval = i; found_interval = NULL; traverse_intervals_noorder (tree, &check_for_interval, Qnil); return found_interval; } static void inc_interval_count (INTERVAL i) { icount++; if (LENGTH (i) == 0) zero_length++; if (depth > idepth) idepth = depth; } int count_intervals (INTERVAL i) { icount = 0; idepth = 0; zero_length = 0; traverse_intervals_noorder (i, &inc_interval_count, Qnil); return icount; } static INTERVAL root_interval (INTERVAL interval) { register INTERVAL i = interval; while (! ROOT_INTERVAL_P (i)) i = INTERVAL_PARENT (i); return i; } #endif /* Assuming that a left child exists, perform the following operation: A B / \ / \ B => A / \ / \ c c */ static INTERVAL rotate_right (INTERVAL A) { INTERVAL B = A->left; INTERVAL c = B->right; ptrdiff_t old_total = A->total_length; eassert (old_total > 0); eassert (LENGTH (A) > 0); eassert (LENGTH (B) > 0); /* Deal with any Parent of A; make it point to B. */ if (! ROOT_INTERVAL_P (A)) { if (AM_LEFT_CHILD (A)) set_interval_left (INTERVAL_PARENT (A), B); else set_interval_right (INTERVAL_PARENT (A), B); } copy_interval_parent (B, A); /* Make B the parent of A. */ set_interval_right (B, A); set_interval_parent (A, B); /* Make A point to c. */ set_interval_left (A, c); if (c) set_interval_parent (c, A); /* A's total length is decreased by the length of B and its left child. */ A->total_length -= B->total_length - TOTAL_LENGTH (c); eassert (TOTAL_LENGTH (A) > 0); eassert (LENGTH (A) > 0); /* B must have the same total length of A. */ B->total_length = old_total; eassert (LENGTH (B) > 0); return B; } /* Assuming that a right child exists, perform the following operation: A B / \ / \ B => A / \ / \ c c */ static INTERVAL rotate_left (INTERVAL A) { INTERVAL B = A->right; INTERVAL c = B->left; ptrdiff_t old_total = A->total_length; eassert (old_total > 0); eassert (LENGTH (A) > 0); eassert (LENGTH (B) > 0); /* Deal with any parent of A; make it point to B. */ if (! ROOT_INTERVAL_P (A)) { if (AM_LEFT_CHILD (A)) set_interval_left (INTERVAL_PARENT (A), B); else set_interval_right (INTERVAL_PARENT (A), B); } copy_interval_parent (B, A); /* Make B the parent of A. */ set_interval_left (B, A); set_interval_parent (A, B); /* Make A point to c. */ set_interval_right (A, c); if (c) set_interval_parent (c, A); /* A's total length is decreased by the length of B and its right child. */ A->total_length -= B->total_length - TOTAL_LENGTH (c); eassert (TOTAL_LENGTH (A) > 0); eassert (LENGTH (A) > 0); /* B must have the same total length of A. */ B->total_length = old_total; eassert (LENGTH (B) > 0); return B; } /* Balance an interval tree with the assumption that the subtrees themselves are already balanced. */ static INTERVAL balance_an_interval (INTERVAL i) { register ptrdiff_t old_diff, new_diff; eassert (LENGTH (i) > 0); eassert (TOTAL_LENGTH (i) >= LENGTH (i)); while (1) { old_diff = LEFT_TOTAL_LENGTH (i) - RIGHT_TOTAL_LENGTH (i); if (old_diff > 0) { /* Since the left child is longer, there must be one. */ new_diff = i->total_length - i->left->total_length + RIGHT_TOTAL_LENGTH (i->left) - LEFT_TOTAL_LENGTH (i->left); if (eabs (new_diff) >= old_diff) break; i = rotate_right (i); balance_an_interval (i->right); } else if (old_diff < 0) { /* Since the right child is longer, there must be one. */ new_diff = i->total_length - i->right->total_length + LEFT_TOTAL_LENGTH (i->right) - RIGHT_TOTAL_LENGTH (i->right); if (eabs (new_diff) >= -old_diff) break; i = rotate_left (i); balance_an_interval (i->left); } else break; } return i; } /* Balance INTERVAL, potentially stuffing it back into its parent Lisp Object. */ static INTERVAL balance_possible_root_interval (INTERVAL interval) { Lisp_Object parent; bool have_parent = false; if (INTERVAL_HAS_OBJECT (interval)) { have_parent = true; GET_INTERVAL_OBJECT (parent, interval); } else if (!INTERVAL_HAS_PARENT (interval)) return interval; interval = balance_an_interval (interval); if (have_parent) { if (BUFFERP (parent)) set_buffer_intervals (XBUFFER (parent), interval); else if (STRINGP (parent)) set_string_intervals (parent, interval); } return interval; } /* Balance the interval tree TREE. Balancing is by weight (the amount of text). */ static INTERVAL balance_intervals_internal (register INTERVAL tree) { /* Balance within each side. */ if (tree->left) balance_intervals_internal (tree->left); if (tree->right) balance_intervals_internal (tree->right); return balance_an_interval (tree); } /* Advertised interface to balance intervals. */ INTERVAL balance_intervals (INTERVAL tree) { return tree ? balance_intervals_internal (tree) : NULL; } /* Rebalance text properties of B. */ static void buffer_balance_intervals (struct buffer *b) { INTERVAL i; eassert (b != NULL); i = buffer_intervals (b); if (i) set_buffer_intervals (b, balance_an_interval (i)); } /* Split INTERVAL into two pieces, starting the second piece at character position OFFSET (counting from 0), relative to INTERVAL. INTERVAL becomes the left-hand piece, and the right-hand piece (second, lexicographically) is returned. The size and position fields of the two intervals are set based upon those of the original interval. The property list of the new interval is reset, thus it is up to the caller to do the right thing with the result. Note that this does not change the position of INTERVAL; if it is a root, it is still a root after this operation. */ INTERVAL split_interval_right (INTERVAL interval, ptrdiff_t offset) { INTERVAL new = make_interval (); ptrdiff_t position = interval->position; ptrdiff_t new_length = LENGTH (interval) - offset; new->position = position + offset; set_interval_parent (new, interval); if (NULL_RIGHT_CHILD (interval)) { set_interval_right (interval, new); new->total_length = new_length; eassert (LENGTH (new) > 0); } else { /* Insert the new node between INTERVAL and its right child. */ set_interval_right (new, interval->right); set_interval_parent (interval->right, new); set_interval_right (interval, new); new->total_length = new_length + new->right->total_length; balance_an_interval (new); } balance_possible_root_interval (interval); return new; } /* Split INTERVAL into two pieces, starting the second piece at character position OFFSET (counting from 0), relative to INTERVAL. INTERVAL becomes the right-hand piece, and the left-hand piece (first, lexicographically) is returned. The size and position fields of the two intervals are set based upon those of the original interval. The property list of the new interval is reset, thus it is up to the caller to do the right thing with the result. Note that this does not change the position of INTERVAL; if it is a root, it is still a root after this operation. */ INTERVAL split_interval_left (INTERVAL interval, ptrdiff_t offset) { INTERVAL new = make_interval (); ptrdiff_t new_length = offset; new->position = interval->position; interval->position = interval->position + offset; set_interval_parent (new, interval); if (NULL_LEFT_CHILD (interval)) { set_interval_left (interval, new); new->total_length = new_length; eassert (LENGTH (new) > 0); } else { /* Insert the new node between INTERVAL and its left child. */ set_interval_left (new, interval->left); set_interval_parent (new->left, new); set_interval_left (interval, new); new->total_length = new_length + new->left->total_length; balance_an_interval (new); } balance_possible_root_interval (interval); return new; } /* Return the proper position for the first character described by the interval tree SOURCE. This is 1 if the parent is a buffer, 0 if the parent is a string or if there is no parent. Don't use this function on an interval which is the child of another interval! */ static int interval_start_pos (INTERVAL source) { Lisp_Object parent; if (!source) return 0; if (! INTERVAL_HAS_OBJECT (source)) return 0; GET_INTERVAL_OBJECT (parent, source); if (BUFFERP (parent)) return BUF_BEG (XBUFFER (parent)); return 0; } /* Find the interval containing text position POSITION in the text represented by the interval tree TREE. POSITION is a buffer position (starting from 1) or a string index (starting from 0). If POSITION is at the end of the buffer or string, return the interval containing the last character. The `position' field, which is a cache of an interval's position, is updated in the interval found. Other functions (e.g., next_interval) will update this cache based on the result of find_interval. */ INTERVAL find_interval (register INTERVAL tree, register ptrdiff_t position) { /* The distance from the left edge of the subtree at TREE to POSITION. */ register ptrdiff_t relative_position; if (!tree) return NULL; relative_position = position; if (INTERVAL_HAS_OBJECT (tree)) { Lisp_Object parent; GET_INTERVAL_OBJECT (parent, tree); if (BUFFERP (parent)) relative_position -= BUF_BEG (XBUFFER (parent)); } eassert (relative_position <= TOTAL_LENGTH (tree)); tree = balance_possible_root_interval (tree); while (1) { eassert (tree); if (relative_position < LEFT_TOTAL_LENGTH (tree)) { tree = tree->left; } else if (! NULL_RIGHT_CHILD (tree) && relative_position >= (TOTAL_LENGTH (tree) - RIGHT_TOTAL_LENGTH (tree))) { relative_position -= (TOTAL_LENGTH (tree) - RIGHT_TOTAL_LENGTH (tree)); tree = tree->right; } else { tree->position = (position - relative_position /* left edge of *tree. */ + LEFT_TOTAL_LENGTH (tree)); /* left edge of this interval. */ return tree; } } } /* Find the succeeding interval (lexicographically) to INTERVAL. Sets the `position' field based on that of INTERVAL (see find_interval). */ INTERVAL next_interval (register INTERVAL interval) { register INTERVAL i = interval; register ptrdiff_t next_position; if (!i) return NULL; next_position = interval->position + LENGTH (interval); if (! NULL_RIGHT_CHILD (i)) { i = i->right; while (! NULL_LEFT_CHILD (i)) i = i->left; i->position = next_position; return i; } while (! NULL_PARENT (i)) { if (AM_LEFT_CHILD (i)) { i = INTERVAL_PARENT (i); i->position = next_position; return i; } i = INTERVAL_PARENT (i); } return NULL; } /* Find the preceding interval (lexicographically) to INTERVAL. Sets the `position' field based on that of INTERVAL (see find_interval). */ INTERVAL previous_interval (register INTERVAL interval) { register INTERVAL i; if (!interval) return NULL; if (! NULL_LEFT_CHILD (interval)) { i = interval->left; while (! NULL_RIGHT_CHILD (i)) i = i->right; i->position = interval->position - LENGTH (i); return i; } i = interval; while (! NULL_PARENT (i)) { if (AM_RIGHT_CHILD (i)) { i = INTERVAL_PARENT (i); i->position = interval->position - LENGTH (i); return i; } i = INTERVAL_PARENT (i); } return NULL; } /* Find the interval containing POS given some non-NULL INTERVAL in the same tree. Note that we need to update interval->position if we go down the tree. To speed up the process, we assume that the ->position of I and all its parents is already uptodate. */ INTERVAL update_interval (register INTERVAL i, ptrdiff_t pos) { if (!i) return NULL; while (1) { if (pos < i->position) { /* Move left. */ if (pos >= i->position - TOTAL_LENGTH (i->left)) { i->left->position = i->position - TOTAL_LENGTH (i->left) + LEFT_TOTAL_LENGTH (i->left); i = i->left; /* Move to the left child. */ } else if (NULL_PARENT (i)) error ("Point before start of properties"); else i = INTERVAL_PARENT (i); continue; } else if (pos >= INTERVAL_LAST_POS (i)) { /* Move right. */ if (pos < INTERVAL_LAST_POS (i) + TOTAL_LENGTH (i->right)) { i->right->position = INTERVAL_LAST_POS (i) + LEFT_TOTAL_LENGTH (i->right); i = i->right; /* Move to the right child. */ } else if (NULL_PARENT (i)) error ("Point %"pD"d after end of properties", pos); else i = INTERVAL_PARENT (i); continue; } else return i; } } /* Effect an adjustment corresponding to the addition of LENGTH characters of text. Do this by finding the interval containing POSITION in the interval tree TREE, and then adjusting all of its ancestors by adding LENGTH to them. If POSITION is the first character of an interval, meaning that point is actually between the two intervals, make the new text belong to the interval which is "sticky". If both intervals are "sticky", then make them belong to the left-most interval. Another possibility would be to create a new interval for this text, and make it have the merged properties of both ends. */ static INTERVAL adjust_intervals_for_insertion (INTERVAL tree, ptrdiff_t position, ptrdiff_t length) { INTERVAL i; INTERVAL temp; bool eobp = 0; Lisp_Object parent; ptrdiff_t offset; eassert (TOTAL_LENGTH (tree) > 0); GET_INTERVAL_OBJECT (parent, tree); offset = (BUFFERP (parent) ? BUF_BEG (XBUFFER (parent)) : 0); /* If inserting at point-max of a buffer, that position will be out of range. Remember that buffer positions are 1-based. */ if (position >= TOTAL_LENGTH (tree) + offset) { position = TOTAL_LENGTH (tree) + offset; eobp = 1; } i = find_interval (tree, position); /* If in middle of an interval which is not sticky either way, we must not just give its properties to the insertion. So split this interval at the insertion point. Originally, the if condition here was this: (! (position == i->position || eobp) && END_NONSTICKY_P (i) && FRONT_NONSTICKY_P (i)) But, these macros are now unreliable because of introduction of Vtext_property_default_nonsticky. So, we always check properties one by one if POSITION is in middle of an interval. */ if (! (position == i->position || eobp)) { Lisp_Object tail; Lisp_Object front, rear; tail = i->plist; /* Properties font-sticky and rear-nonsticky override Vtext_property_default_nonsticky. So, if they are t, we can skip one by one checking of properties. */ rear = textget (i->plist, Qrear_nonsticky); if (! CONSP (rear) && ! NILP (rear)) { /* All properties are nonsticky. We split the interval. */ goto check_done; } front = textget (i->plist, Qfront_sticky); if (! CONSP (front) && ! NILP (front)) { /* All properties are sticky. We don't split the interval. */ tail = Qnil; goto check_done; } /* Does any actual property pose an actual problem? We break the loop if we find a nonsticky property. */ for (; CONSP (tail); tail = Fcdr (XCDR (tail))) { Lisp_Object prop, tmp; prop = XCAR (tail); /* Is this particular property front-sticky? */ if (CONSP (front) && ! NILP (Fmemq (prop, front))) continue; /* Is this particular property rear-nonsticky? */ if (CONSP (rear) && ! NILP (Fmemq (prop, rear))) break; /* Is this particular property recorded as sticky or nonsticky in Vtext_property_default_nonsticky? */ tmp = Fassq (prop, Vtext_property_default_nonsticky); if (CONSP (tmp)) { if (NILP (tmp)) continue; break; } /* By default, a text property is rear-sticky, thus we continue the loop. */ } check_done: /* If any property is a real problem, split the interval. */ if (! NILP (tail)) { temp = split_interval_right (i, position - i->position); copy_properties (i, temp); i = temp; } } /* If we are positioned between intervals, check the stickiness of both of them. We have to do this too, if we are at BEG or Z. */ if (position == i->position || eobp) { register INTERVAL prev; if (position == BEG) prev = 0; else if (eobp) { prev = i; i = 0; } else prev = previous_interval (i); /* Even if we are positioned between intervals, we default to the left one if it exists. We extend it now and split off a part later, if stickiness demands it. */ for (temp = prev ? prev : i; temp; temp = INTERVAL_PARENT_OR_NULL (temp)) { temp->total_length += length; temp = balance_possible_root_interval (temp); } /* If at least one interval has sticky properties, we check the stickiness property by property. Originally, the if condition here was this: (END_NONSTICKY_P (prev) || FRONT_STICKY_P (i)) But, these macros are now unreliable because of introduction of Vtext_property_default_nonsticky. So, we always have to check stickiness of properties one by one. If cache of stickiness is implemented in the future, we may be able to use those macros again. */ if (1) { Lisp_Object pleft, pright; struct interval newi; RESET_INTERVAL (&newi); pleft = prev ? prev->plist : Qnil; pright = i ? i->plist : Qnil; set_interval_plist (&newi, merge_properties_sticky (pleft, pright)); if (! prev) /* i.e. position == BEG */ { if (! intervals_equal (i, &newi)) { i = split_interval_left (i, length); set_interval_plist (i, newi.plist); } } else if (! intervals_equal (prev, &newi)) { prev = split_interval_right (prev, position - prev->position); set_interval_plist (prev, newi.plist); if (i && intervals_equal (prev, i)) merge_interval_right (prev); } /* We will need to update the cache here later. */ } else if (! prev && ! NILP (i->plist)) { /* Just split off a new interval at the left. Since I wasn't front-sticky, the empty plist is ok. */ i = split_interval_left (i, length); } } /* Otherwise just extend the interval. */ else { for (temp = i; temp; temp = INTERVAL_PARENT_OR_NULL (temp)) { temp->total_length += length; temp = balance_possible_root_interval (temp); } } return tree; } /* Any property might be front-sticky on the left, rear-sticky on the left, front-sticky on the right, or rear-sticky on the right; the 16 combinations can be arranged in a matrix with rows denoting the left conditions and columns denoting the right conditions: _ __ _ _ FR FR FR FR FR__ 0 1 2 3 _FR 4 5 6 7 FR 8 9 A B FR C D E F left-props = '(front-sticky (p8 p9 pa pb pc pd pe pf) rear-nonsticky (p4 p5 p6 p7 p8 p9 pa pb) p0 L p1 L p2 L p3 L p4 L p5 L p6 L p7 L p8 L p9 L pa L pb L pc L pd L pe L pf L) right-props = '(front-sticky (p2 p3 p6 p7 pa pb pe pf) rear-nonsticky (p1 p2 p5 p6 p9 pa pd pe) p0 R p1 R p2 R p3 R p4 R p5 R p6 R p7 R p8 R p9 R pa R pb R pc R pd R pe R pf R) We inherit from whoever has a sticky side facing us. If both sides do (cases 2, 3, E, and F), then we inherit from whichever side has a non-nil value for the current property. If both sides do, then we take from the left. When we inherit a property, we get its stickiness as well as its value. So, when we merge the above two lists, we expect to get this: result = '(front-sticky (p6 p7 pa pb pc pd pe pf) rear-nonsticky (p6 pa) p0 L p1 L p2 L p3 L p6 R p7 R pa R pb R pc L pd L pe L pf L) The optimizable special cases are: left rear-nonsticky = nil, right front-sticky = nil (inherit left) left rear-nonsticky = t, right front-sticky = t (inherit right) left rear-nonsticky = t, right front-sticky = nil (inherit none) */ static Lisp_Object merge_properties_sticky (Lisp_Object pleft, Lisp_Object pright) { Lisp_Object props, front, rear; Lisp_Object lfront, lrear, rfront, rrear; Lisp_Object tail1, tail2, sym, lval, rval, cat; bool use_left, use_right, lpresent; props = Qnil; front = Qnil; rear = Qnil; lfront = textget (pleft, Qfront_sticky); lrear = textget (pleft, Qrear_nonsticky); rfront = textget (pright, Qfront_sticky); rrear = textget (pright, Qrear_nonsticky); /* Go through each element of PRIGHT. */ for (tail1 = pright; CONSP (tail1); tail1 = Fcdr (XCDR (tail1))) { Lisp_Object tmp; sym = XCAR (tail1); /* Sticky properties get special treatment. */ if (EQ (sym, Qrear_nonsticky) || EQ (sym, Qfront_sticky)) continue; rval = Fcar (XCDR (tail1)); for (tail2 = pleft; CONSP (tail2); tail2 = Fcdr (XCDR (tail2))) if (EQ (sym, XCAR (tail2))) break; /* Indicate whether the property is explicitly defined on the left. (We know it is defined explicitly on the right because otherwise we don't get here.) */ lpresent = ! NILP (tail2); lval = (NILP (tail2) ? Qnil : Fcar (Fcdr (tail2))); /* Even if lrear or rfront say nothing about the stickiness of SYM, Vtext_property_default_nonsticky may give default stickiness to SYM. */ tmp = Fassq (sym, Vtext_property_default_nonsticky); use_left = (lpresent && ! (TMEM (sym, lrear) || (CONSP (tmp) && ! NILP (XCDR (tmp))))); use_right = (TMEM (sym, rfront) || (CONSP (tmp) && NILP (XCDR (tmp)))); if (use_left && use_right) { if (NILP (lval)) use_left = 0; else if (NILP (rval)) use_right = 0; } if (use_left) { /* We build props as (value sym ...) rather than (sym value ...) because we plan to nreverse it when we're done. */ props = Fcons (lval, Fcons (sym, props)); if (TMEM (sym, lfront)) front = Fcons (sym, front); if (TMEM (sym, lrear)) rear = Fcons (sym, rear); } else if (use_right) { props = Fcons (rval, Fcons (sym, props)); if (TMEM (sym, rfront)) front = Fcons (sym, front); if (TMEM (sym, rrear)) rear = Fcons (sym, rear); } } /* Now go through each element of PLEFT. */ for (tail2 = pleft; CONSP (tail2); tail2 = Fcdr (XCDR (tail2))) { Lisp_Object tmp; sym = XCAR (tail2); /* Sticky properties get special treatment. */ if (EQ (sym, Qrear_nonsticky) || EQ (sym, Qfront_sticky)) continue; /* If sym is in PRIGHT, we've already considered it. */ for (tail1 = pright; CONSP (tail1); tail1 = Fcdr (XCDR (tail1))) if (EQ (sym, XCAR (tail1))) break; if (! NILP (tail1)) continue; lval = Fcar (XCDR (tail2)); /* Even if lrear or rfront say nothing about the stickiness of SYM, Vtext_property_default_nonsticky may give default stickiness to SYM. */ tmp = Fassq (sym, Vtext_property_default_nonsticky); /* Since rval is known to be nil in this loop, the test simplifies. */ if (! (TMEM (sym, lrear) || (CONSP (tmp) && ! NILP (XCDR (tmp))))) { props = Fcons (lval, Fcons (sym, props)); if (TMEM (sym, lfront)) front = Fcons (sym, front); } else if (TMEM (sym, rfront) || (CONSP (tmp) && NILP (XCDR (tmp)))) { /* The value is nil, but we still inherit the stickiness from the right. */ front = Fcons (sym, front); if (TMEM (sym, rrear)) rear = Fcons (sym, rear); } } props = Fnreverse (props); if (! NILP (rear)) props = Fcons (Qrear_nonsticky, Fcons (Fnreverse (rear), props)); cat = textget (props, Qcategory); if (! NILP (front) && /* If we have inherited a front-stick category property that is t, we don't need to set up a detailed one. */ ! (! NILP (cat) && SYMBOLP (cat) && EQ (Fget (cat, Qfront_sticky), Qt))) props = Fcons (Qfront_sticky, Fcons (Fnreverse (front), props)); return props; } /* Delete a node I from its interval tree by merging its subtrees into one subtree which is then returned. Caller is responsible for storing the resulting subtree into its parent. */ static INTERVAL delete_node (register INTERVAL i) { register INTERVAL migrate, this; register ptrdiff_t migrate_amt; if (!i->left) return i->right; if (!i->right) return i->left; migrate = i->left; migrate_amt = i->left->total_length; this = i->right; this->total_length += migrate_amt; while (this->left) { this = this->left; this->total_length += migrate_amt; } set_interval_left (this, migrate); set_interval_parent (migrate, this); eassert (LENGTH (this) > 0); eassert (LENGTH (i->right) > 0); return i->right; } /* Delete interval I from its tree by calling `delete_node' and properly connecting the resultant subtree. I is presumed to be empty; that is, no adjustments are made for the length of I. */ static void delete_interval (register INTERVAL i) { register INTERVAL parent; ptrdiff_t amt = LENGTH (i); eassert (amt == 0); /* Only used on zero-length intervals now. */ if (ROOT_INTERVAL_P (i)) { Lisp_Object owner; GET_INTERVAL_OBJECT (owner, i); parent = delete_node (i); if (parent) set_interval_object (parent, owner); if (BUFFERP (owner)) set_buffer_intervals (XBUFFER (owner), parent); else if (STRINGP (owner)) set_string_intervals (owner, parent); else emacs_abort (); return; } parent = INTERVAL_PARENT (i); if (AM_LEFT_CHILD (i)) { set_interval_left (parent, delete_node (i)); if (parent->left) set_interval_parent (parent->left, parent); } else { set_interval_right (parent, delete_node (i)); if (parent->right) set_interval_parent (parent->right, parent); } } /* Find the interval in TREE corresponding to the relative position FROM and delete as much as possible of AMOUNT from that interval. Return the amount actually deleted, and if the interval was zeroed-out, delete that interval node from the tree. Note that FROM is actually origin zero, aka relative to the leftmost edge of tree. This is appropriate since we call ourselves recursively on subtrees. Do this by recursing down TREE to the interval in question, and deleting the appropriate amount of text. */ static ptrdiff_t interval_deletion_adjustment (register INTERVAL tree, register ptrdiff_t from, register ptrdiff_t amount) { register ptrdiff_t relative_position = from; if (!tree) return 0; /* Left branch. */ if (relative_position < LEFT_TOTAL_LENGTH (tree)) { ptrdiff_t subtract = interval_deletion_adjustment (tree->left, relative_position, amount); tree->total_length -= subtract; eassert (LENGTH (tree) > 0); return subtract; } /* Right branch. */ else if (relative_position >= (TOTAL_LENGTH (tree) - RIGHT_TOTAL_LENGTH (tree))) { ptrdiff_t subtract; relative_position -= (tree->total_length - RIGHT_TOTAL_LENGTH (tree)); subtract = interval_deletion_adjustment (tree->right, relative_position, amount); tree->total_length -= subtract; eassert (LENGTH (tree) > 0); return subtract; } /* Here -- this node. */ else { /* How much can we delete from this interval? */ ptrdiff_t my_amount = ((tree->total_length - RIGHT_TOTAL_LENGTH (tree)) - relative_position); if (amount > my_amount) amount = my_amount; tree->total_length -= amount; eassert (LENGTH (tree) >= 0); if (LENGTH (tree) == 0) delete_interval (tree); return amount; } /* Never reach here. */ } /* Effect the adjustments necessary to the interval tree of BUFFER to correspond to the deletion of LENGTH characters from that buffer text. The deletion is effected at position START (which is a buffer position, i.e. origin 1). */ static void adjust_intervals_for_deletion (struct buffer *buffer, ptrdiff_t start, ptrdiff_t length) { ptrdiff_t left_to_delete = length; INTERVAL tree = buffer_intervals (buffer); Lisp_Object parent; ptrdiff_t offset; GET_INTERVAL_OBJECT (parent, tree); offset = (BUFFERP (parent) ? BUF_BEG (XBUFFER (parent)) : 0); if (!tree) return; eassert (start <= offset + TOTAL_LENGTH (tree) && start + length <= offset + TOTAL_LENGTH (tree)); if (length == TOTAL_LENGTH (tree)) { set_buffer_intervals (buffer, NULL); return; } if (ONLY_INTERVAL_P (tree)) { tree->total_length -= length; eassert (LENGTH (tree) > 0); return; } if (start > offset + TOTAL_LENGTH (tree)) start = offset + TOTAL_LENGTH (tree); while (left_to_delete > 0) { left_to_delete -= interval_deletion_adjustment (tree, start - offset, left_to_delete); tree = buffer_intervals (buffer); if (left_to_delete == tree->total_length) { set_buffer_intervals (buffer, NULL); return; } } } /* Make the adjustments necessary to the interval tree of BUFFER to represent an addition or deletion of LENGTH characters starting at position START. Addition or deletion is indicated by the sign of LENGTH. */ void offset_intervals (struct buffer *buffer, ptrdiff_t start, ptrdiff_t length) { if (!buffer_intervals (buffer) || length == 0) return; if (length > 0) adjust_intervals_for_insertion (buffer_intervals (buffer), start, length); else adjust_intervals_for_deletion (buffer, start, -length); } /* Merge interval I with its lexicographic successor. The resulting interval is returned, and has the properties of the original successor. The properties of I are lost. I is removed from the interval tree. IMPORTANT: The caller must verify that this is not the last (rightmost) interval. */ static INTERVAL merge_interval_right (register INTERVAL i) { register ptrdiff_t absorb = LENGTH (i); register INTERVAL successor; /* Find the succeeding interval. */ if (! NULL_RIGHT_CHILD (i)) /* It's below us. Add absorb as we descend. */ { successor = i->right; while (! NULL_LEFT_CHILD (successor)) { successor->total_length += absorb; eassert (LENGTH (successor) > 0); successor = successor->left; } successor->total_length += absorb; eassert (LENGTH (successor) > 0); delete_interval (i); return successor; } /* Zero out this interval. */ i->total_length -= absorb; eassert (TOTAL_LENGTH (i) >= 0); successor = i; while (! NULL_PARENT (successor)) /* It's above us. Subtract as we ascend. */ { if (AM_LEFT_CHILD (successor)) { successor = INTERVAL_PARENT (successor); delete_interval (i); return successor; } successor = INTERVAL_PARENT (successor); successor->total_length -= absorb; eassert (LENGTH (successor) > 0); } /* This must be the rightmost or last interval and cannot be merged right. The caller should have known. */ emacs_abort (); } /* Merge interval I with its lexicographic predecessor. The resulting interval is returned, and has the properties of the original predecessor. The properties of I are lost. Interval node I is removed from the tree. IMPORTANT: The caller must verify that this is not the first (leftmost) interval. */ INTERVAL merge_interval_left (register INTERVAL i) { register ptrdiff_t absorb = LENGTH (i); register INTERVAL predecessor; /* Find the preceding interval. */ if (! NULL_LEFT_CHILD (i)) /* It's below us. Go down, adding ABSORB as we go. */ { predecessor = i->left; while (! NULL_RIGHT_CHILD (predecessor)) { predecessor->total_length += absorb; eassert (LENGTH (predecessor) > 0); predecessor = predecessor->right; } predecessor->total_length += absorb; eassert (LENGTH (predecessor) > 0); delete_interval (i); return predecessor; } /* Zero out this interval. */ i->total_length -= absorb; eassert (TOTAL_LENGTH (i) >= 0); predecessor = i; while (! NULL_PARENT (predecessor)) /* It's above us. Go up, subtracting ABSORB. */ { if (AM_RIGHT_CHILD (predecessor)) { predecessor = INTERVAL_PARENT (predecessor); delete_interval (i); return predecessor; } predecessor = INTERVAL_PARENT (predecessor); predecessor->total_length -= absorb; eassert (LENGTH (predecessor) > 0); } /* This must be the leftmost or first interval and cannot be merged left. The caller should have known. */ emacs_abort (); } /* Create a copy of SOURCE but with the default value of UP. */ static INTERVAL reproduce_interval (INTERVAL source) { register INTERVAL target = make_interval (); eassert (LENGTH (source) > 0); target->total_length = source->total_length; target->position = source->position; copy_properties (source, target); if (! NULL_LEFT_CHILD (source)) set_interval_left (target, reproduce_tree (source->left, target)); if (! NULL_RIGHT_CHILD (source)) set_interval_right (target, reproduce_tree (source->right, target)); eassert (LENGTH (target) > 0); return target; } /* Make an exact copy of interval tree SOURCE which descends from PARENT. This is done by recursing through SOURCE, copying the current interval and its properties, and then adjusting the pointers of the copy. */ static INTERVAL reproduce_tree (INTERVAL source, INTERVAL parent) { INTERVAL target = reproduce_interval (source); set_interval_parent (target, parent); return target; } static INTERVAL reproduce_tree_obj (INTERVAL source, Lisp_Object parent) { INTERVAL target = reproduce_interval (source); set_interval_object (target, parent); return target; } /* Insert the intervals of SOURCE into BUFFER at POSITION. LENGTH is the length of the text in SOURCE. The `position' field of the SOURCE intervals is assumed to be consistent with its parent; therefore, SOURCE must be an interval tree made with copy_interval or must be the whole tree of a buffer or a string. This is used in insdel.c when inserting Lisp_Strings into the buffer. The text corresponding to SOURCE is already in the buffer when this is called. The intervals of new tree are a copy of those belonging to the string being inserted; intervals are never shared. If the inserted text had no intervals associated, and we don't want to inherit the surrounding text's properties, this function simply returns -- offset_intervals should handle placing the text in the correct interval, depending on the sticky bits. If the inserted text had properties (intervals), then there are two cases -- either insertion happened in the middle of some interval, or between two intervals. If the text goes into the middle of an interval, then new intervals are created in the middle, and new text has the union of its properties and those of the text into which it was inserted. If the text goes between two intervals, then if neither interval had its appropriate sticky property set (front_sticky, rear_sticky), the new text has only its properties. If one of the sticky properties is set, then the new text "sticks" to that region and its properties depend on merging as above. If both the preceding and succeeding intervals to the new text are "sticky", then the new text retains only its properties, as if neither sticky property were set. Perhaps we should consider merging all three sets of properties onto the new text... */ void graft_intervals_into_buffer (INTERVAL source, ptrdiff_t position, ptrdiff_t length, struct buffer *buffer, bool inherit) { INTERVAL tree = buffer_intervals (buffer); INTERVAL under, over, this; ptrdiff_t over_used; /* If the new text has no properties, then with inheritance it becomes part of whatever interval it was inserted into. To prevent inheritance, we must clear out the properties of the newly inserted text. */ if (!source) { Lisp_Object buf; if (!inherit && tree && length > 0) { XSETBUFFER (buf, buffer); set_text_properties_1 (make_number (position), make_number (position + length), Qnil, buf, find_interval (tree, position)); } /* Shouldn't be necessary. --Stef */ buffer_balance_intervals (buffer); return; } eassert (length == TOTAL_LENGTH (source)); if ((BUF_Z (buffer) - BUF_BEG (buffer)) == length) { /* The inserted text constitutes the whole buffer, so simply copy over the interval structure. */ Lisp_Object buf; XSETBUFFER (buf, buffer); set_buffer_intervals (buffer, reproduce_tree_obj (source, buf)); buffer_intervals (buffer)->position = BUF_BEG (buffer); eassert (buffer_intervals (buffer)->up_obj == 1); return; } else if (!tree) { /* Create an interval tree in which to place a copy of the intervals of the inserted string. */ Lisp_Object buf; XSETBUFFER (buf, buffer); tree = create_root_interval (buf); } /* Paranoia -- the text has already been added, so this buffer should be of non-zero length. */ eassert (TOTAL_LENGTH (tree) > 0); this = under = find_interval (tree, position); eassert (under); over = find_interval (source, interval_start_pos (source)); /* Here for insertion in the middle of an interval. Split off an equivalent interval to the right, then don't bother with it any more. */ if (position > under->position) { INTERVAL end_unchanged = split_interval_left (this, position - under->position); copy_properties (under, end_unchanged); under->position = position; } else { /* This call may have some effect because previous_interval may update `position' fields of intervals. Thus, don't ignore it for the moment. Someone please tell me the truth (K.Handa). */ INTERVAL prev = previous_interval (under); (void) prev; #if 0 /* But, this code surely has no effect. And, anyway, END_NONSTICKY_P is unreliable now. */ if (prev && !END_NONSTICKY_P (prev)) prev = 0; #endif /* 0 */ } /* Insertion is now at beginning of UNDER. */ /* The inserted text "sticks" to the interval `under', which means it gets those properties. The properties of under are the result of adjust_intervals_for_insertion, so stickiness has already been taken care of. */ /* OVER is the interval we are copying from next. OVER_USED says how many characters' worth of OVER have already been copied into target intervals. UNDER is the next interval in the target. */ over_used = 0; while (over) { /* If UNDER is longer than OVER, split it. */ if (LENGTH (over) - over_used < LENGTH (under)) { this = split_interval_left (under, LENGTH (over) - over_used); copy_properties (under, this); } else this = under; /* THIS is now the interval to copy or merge into. OVER covers all of it. */ if (inherit) merge_properties (over, this); else copy_properties (over, this); /* If THIS and OVER end at the same place, advance OVER to a new source interval. */ if (LENGTH (this) == LENGTH (over) - over_used) { over = next_interval (over); over_used = 0; } else /* Otherwise just record that more of OVER has been used. */ over_used += LENGTH (this); /* Always advance to a new target interval. */ under = next_interval (this); } buffer_balance_intervals (buffer); } /* Get the value of property PROP from PLIST, which is the plist of an interval. We check for direct properties, for categories with property PROP, and for PROP appearing on the default-text-properties list. */ Lisp_Object textget (Lisp_Object plist, register Lisp_Object prop) { return lookup_char_property (plist, prop, 1); } Lisp_Object lookup_char_property (Lisp_Object plist, Lisp_Object prop, bool textprop) { Lisp_Object tail, fallback = Qnil; for (tail = plist; CONSP (tail); tail = Fcdr (XCDR (tail))) { register Lisp_Object tem; tem = XCAR (tail); if (EQ (prop, tem)) return Fcar (XCDR (tail)); if (EQ (tem, Qcategory)) { tem = Fcar (XCDR (tail)); if (SYMBOLP (tem)) fallback = Fget (tem, prop); } } if (! NILP (fallback)) return fallback; /* Check for alternative properties. */ tail = Fassq (prop, Vchar_property_alias_alist); if (! NILP (tail)) { tail = XCDR (tail); for (; NILP (fallback) && CONSP (tail); tail = XCDR (tail)) fallback = Fplist_get (plist, XCAR (tail)); } if (textprop && NILP (fallback) && CONSP (Vdefault_text_properties)) fallback = Fplist_get (Vdefault_text_properties, prop); return fallback; } /* Set point in BUFFER "temporarily" to CHARPOS, which corresponds to byte position BYTEPOS. */ void temp_set_point_both (struct buffer *buffer, ptrdiff_t charpos, ptrdiff_t bytepos) { /* In a single-byte buffer, the two positions must be equal. */ eassert (BUF_ZV (buffer) != BUF_ZV_BYTE (buffer) || charpos == bytepos); eassert (charpos <= bytepos); eassert (charpos <= BUF_ZV (buffer) || BUF_BEGV (buffer) <= charpos); SET_BUF_PT_BOTH (buffer, charpos, bytepos); } /* Set point "temporarily", without checking any text properties. */ void temp_set_point (struct buffer *buffer, ptrdiff_t charpos) { temp_set_point_both (buffer, charpos, buf_charpos_to_bytepos (buffer, charpos)); } /* Set point in BUFFER to CHARPOS. If the target position is before an intangible character, move to an ok place. */ void set_point (ptrdiff_t charpos) { set_point_both (charpos, buf_charpos_to_bytepos (current_buffer, charpos)); } /* Set PT from MARKER's clipped position. */ void set_point_from_marker (Lisp_Object marker) { if (XMARKER (marker)->buffer != current_buffer) signal_error ("Marker points into wrong buffer", marker); set_point_both (clip_to_bounds (BEGV, marker_position (marker), ZV), clip_to_bounds (BEGV_BYTE, marker_byte_position (marker), ZV_BYTE)); } /* If there's an invisible character at position POS + TEST_OFFS in the current buffer, and the invisible property has a `stickiness' such that inserting a character at position POS would inherit the property it, return POS + ADJ, otherwise return POS. If TEST_INTANG, intangibility is required as well as invisibility. TEST_OFFS should be either 0 or -1, and ADJ should be either 1 or -1. Note that `stickiness' is determined by overlay marker insertion types, if the invisible property comes from an overlay. */ static ptrdiff_t adjust_for_invis_intang (ptrdiff_t pos, ptrdiff_t test_offs, ptrdiff_t adj, bool test_intang) { Lisp_Object invis_propval, invis_overlay; Lisp_Object test_pos; if ((adj < 0 && pos + adj < BEGV) || (adj > 0 && pos + adj > ZV)) /* POS + ADJ would be beyond the buffer bounds, so do no adjustment. */ return pos; test_pos = make_number (pos + test_offs); invis_propval = get_char_property_and_overlay (test_pos, Qinvisible, Qnil, &invis_overlay); if ((!test_intang || ! NILP (Fget_char_property (test_pos, Qintangible, Qnil))) && TEXT_PROP_MEANS_INVISIBLE (invis_propval) /* This next test is true if the invisible property has a stickiness such that an insertion at POS would inherit it. */ && (NILP (invis_overlay) /* Invisible property is from a text-property. */ ? (text_property_stickiness (Qinvisible, make_number (pos), Qnil) == (test_offs == 0 ? 1 : -1)) /* Invisible property is from an overlay. */ : (test_offs == 0 ? XMARKER (OVERLAY_START (invis_overlay))->insertion_type == 0 : XMARKER (OVERLAY_END (invis_overlay))->insertion_type == 1))) pos += adj; return pos; } /* Set point in BUFFER to CHARPOS, which corresponds to byte position BYTEPOS. If the target position is before an intangible character, move to an ok place. */ void set_point_both (ptrdiff_t charpos, ptrdiff_t bytepos) { register INTERVAL to, from, toprev, fromprev; ptrdiff_t buffer_point; ptrdiff_t old_position = PT; /* This ensures that we move forward past intangible text when the initial position is the same as the destination, in the rare instances where this is important, e.g. in line-move-finish (simple.el). */ bool backwards = charpos < old_position; bool have_overlays; ptrdiff_t original_position; bset_point_before_scroll (current_buffer, Qnil); if (charpos == PT) return; /* In a single-byte buffer, the two positions must be equal. */ eassert (ZV != ZV_BYTE || charpos == bytepos); /* Check this now, before checking if the buffer has any intervals. That way, we can catch conditions which break this sanity check whether or not there are intervals in the buffer. */ eassert (charpos <= ZV && charpos >= BEGV); have_overlays = buffer_has_overlays (); /* If we have no text properties and overlays, then we can do it quickly. */ if (!buffer_intervals (current_buffer) && ! have_overlays) { temp_set_point_both (current_buffer, charpos, bytepos); return; } /* Set TO to the interval containing the char after CHARPOS, and TOPREV to the interval containing the char before CHARPOS. Either one may be null. They may be equal. */ to = find_interval (buffer_intervals (current_buffer), charpos); if (charpos == BEGV) toprev = 0; else if (to && to->position == charpos) toprev = previous_interval (to); else toprev = to; buffer_point = (PT == ZV ? ZV - 1 : PT); /* Set FROM to the interval containing the char after PT, and FROMPREV to the interval containing the char before PT. Either one may be null. They may be equal. */ /* We could cache this and save time. */ from = find_interval (buffer_intervals (current_buffer), buffer_point); if (buffer_point == BEGV) fromprev = 0; else if (from && from->position == PT) fromprev = previous_interval (from); else if (buffer_point != PT) fromprev = from, from = 0; else fromprev = from; /* Moving within an interval. */ if (to == from && toprev == fromprev && INTERVAL_VISIBLE_P (to) && ! have_overlays) { temp_set_point_both (current_buffer, charpos, bytepos); return; } original_position = charpos; /* If the new position is between two intangible characters with the same intangible property value, move forward or backward until a change in that property. */ if (NILP (Vinhibit_point_motion_hooks) && ((to && toprev) || have_overlays) /* Intangibility never stops us from positioning at the beginning or end of the buffer, so don't bother checking in that case. */ && charpos != BEGV && charpos != ZV) { Lisp_Object pos; Lisp_Object intangible_propval; if (backwards) { /* If the preceding character is both intangible and invisible, and the invisible property is `rear-sticky', perturb it so that the search starts one character earlier -- this ensures that point can never move to the end of an invisible/ intangible/rear-sticky region. */ charpos = adjust_for_invis_intang (charpos, -1, -1, 1); XSETINT (pos, charpos); /* If following char is intangible, skip back over all chars with matching intangible property. */ intangible_propval = Fget_char_property (pos, Qintangible, Qnil); if (! NILP (intangible_propval)) { while (XINT (pos) > BEGV && EQ (Fget_char_property (make_number (XINT (pos) - 1), Qintangible, Qnil), intangible_propval)) pos = Fprevious_char_property_change (pos, Qnil); /* Set CHARPOS from POS, and if the final intangible character that we skipped over is also invisible, and the invisible property is `front-sticky', perturb it to be one character earlier -- this ensures that point can never move to the beginning of an invisible/intangible/front-sticky region. */ charpos = adjust_for_invis_intang (XINT (pos), 0, -1, 0); } } else { /* If the following character is both intangible and invisible, and the invisible property is `front-sticky', perturb it so that the search starts one character later -- this ensures that point can never move to the beginning of an invisible/intangible/front-sticky region. */ charpos = adjust_for_invis_intang (charpos, 0, 1, 1); XSETINT (pos, charpos); /* If preceding char is intangible, skip forward over all chars with matching intangible property. */ intangible_propval = Fget_char_property (make_number (charpos - 1), Qintangible, Qnil); if (! NILP (intangible_propval)) { while (XINT (pos) < ZV && EQ (Fget_char_property (pos, Qintangible, Qnil), intangible_propval)) pos = Fnext_char_property_change (pos, Qnil); /* Set CHARPOS from POS, and if the final intangible character that we skipped over is also invisible, and the invisible property is `rear-sticky', perturb it to be one character later -- this ensures that point can never move to the end of an invisible/intangible/rear-sticky region. */ charpos = adjust_for_invis_intang (XINT (pos), -1, 1, 0); } } bytepos = buf_charpos_to_bytepos (current_buffer, charpos); } if (charpos != original_position) { /* Set TO to the interval containing the char after CHARPOS, and TOPREV to the interval containing the char before CHARPOS. Either one may be null. They may be equal. */ to = find_interval (buffer_intervals (current_buffer), charpos); if (charpos == BEGV) toprev = 0; else if (to && to->position == charpos) toprev = previous_interval (to); else toprev = to; } /* Here TO is the interval after the stopping point and TOPREV is the interval before the stopping point. One or the other may be null. */ temp_set_point_both (current_buffer, charpos, bytepos); /* We run point-left and point-entered hooks here, if the two intervals are not equivalent. These hooks take (old_point, new_point) as arguments. */ if (NILP (Vinhibit_point_motion_hooks) && (! intervals_equal (from, to) || ! intervals_equal (fromprev, toprev))) { Lisp_Object leave_after, leave_before, enter_after, enter_before; if (fromprev) leave_before = textget (fromprev->plist, Qpoint_left); else leave_before = Qnil; if (from) leave_after = textget (from->plist, Qpoint_left); else leave_after = Qnil; if (toprev) enter_before = textget (toprev->plist, Qpoint_entered); else enter_before = Qnil; if (to) enter_after = textget (to->plist, Qpoint_entered); else enter_after = Qnil; if (! EQ (leave_before, enter_before) && !NILP (leave_before)) call2 (leave_before, make_number (old_position), make_number (charpos)); if (! EQ (leave_after, enter_after) && !NILP (leave_after)) call2 (leave_after, make_number (old_position), make_number (charpos)); if (! EQ (enter_before, leave_before) && !NILP (enter_before)) call2 (enter_before, make_number (old_position), make_number (charpos)); if (! EQ (enter_after, leave_after) && !NILP (enter_after)) call2 (enter_after, make_number (old_position), make_number (charpos)); } } /* Move point to POSITION, unless POSITION is inside an intangible segment that reaches all the way to point. */ void move_if_not_intangible (ptrdiff_t position) { Lisp_Object pos; Lisp_Object intangible_propval; XSETINT (pos, position); if (! NILP (Vinhibit_point_motion_hooks)) /* If intangible is inhibited, always move point to POSITION. */ ; else if (PT < position && XINT (pos) < ZV) { /* We want to move forward, so check the text before POSITION. */ intangible_propval = Fget_char_property (pos, Qintangible, Qnil); /* If following char is intangible, skip back over all chars with matching intangible property. */ if (! NILP (intangible_propval)) while (XINT (pos) > BEGV && EQ (Fget_char_property (make_number (XINT (pos) - 1), Qintangible, Qnil), intangible_propval)) pos = Fprevious_char_property_change (pos, Qnil); } else if (XINT (pos) > BEGV) { /* We want to move backward, so check the text after POSITION. */ intangible_propval = Fget_char_property (make_number (XINT (pos) - 1), Qintangible, Qnil); /* If following char is intangible, skip forward over all chars with matching intangible property. */ if (! NILP (intangible_propval)) while (XINT (pos) < ZV && EQ (Fget_char_property (pos, Qintangible, Qnil), intangible_propval)) pos = Fnext_char_property_change (pos, Qnil); } else if (position < BEGV) position = BEGV; else if (position > ZV) position = ZV; /* If the whole stretch between PT and POSITION isn't intangible, try moving to POSITION (which means we actually move farther if POSITION is inside of intangible text). */ if (XINT (pos) != PT) SET_PT (position); } /* If text at position POS has property PROP, set *VAL to the property value, *START and *END to the beginning and end of a region that has the same property, and return true. Otherwise return false. OBJECT is the string or buffer to look for the property in; nil means the current buffer. */ bool get_property_and_range (ptrdiff_t pos, Lisp_Object prop, Lisp_Object *val, ptrdiff_t *start, ptrdiff_t *end, Lisp_Object object) { INTERVAL i, prev, next; if (NILP (object)) i = find_interval (buffer_intervals (current_buffer), pos); else if (BUFFERP (object)) i = find_interval (buffer_intervals (XBUFFER (object)), pos); else if (STRINGP (object)) i = find_interval (string_intervals (object), pos); else emacs_abort (); if (!i || (i->position + LENGTH (i) <= pos)) return 0; *val = textget (i->plist, prop); if (NILP (*val)) return 0; next = i; /* remember it in advance */ prev = previous_interval (i); while (prev && EQ (*val, textget (prev->plist, prop))) i = prev, prev = previous_interval (prev); *start = i->position; next = next_interval (i); while (next && EQ (*val, textget (next->plist, prop))) i = next, next = next_interval (next); *end = i->position + LENGTH (i); return 1; } /* Return the proper local keymap TYPE for position POSITION in BUFFER; TYPE should be one of `keymap' or `local-map'. Use the map specified by the PROP property, if any. Otherwise, if TYPE is `local-map' use BUFFER's local map. */ Lisp_Object get_local_map (ptrdiff_t position, struct buffer *buffer, Lisp_Object type) { Lisp_Object prop, lispy_position, lispy_buffer; ptrdiff_t old_begv, old_zv, old_begv_byte, old_zv_byte; position = clip_to_bounds (BUF_BEGV (buffer), position, BUF_ZV (buffer)); /* Ignore narrowing, so that a local map continues to be valid even if the visible region contains no characters and hence no properties. */ old_begv = BUF_BEGV (buffer); old_zv = BUF_ZV (buffer); old_begv_byte = BUF_BEGV_BYTE (buffer); old_zv_byte = BUF_ZV_BYTE (buffer); SET_BUF_BEGV_BOTH (buffer, BUF_BEG (buffer), BUF_BEG_BYTE (buffer)); SET_BUF_ZV_BOTH (buffer, BUF_Z (buffer), BUF_Z_BYTE (buffer)); XSETFASTINT (lispy_position, position); XSETBUFFER (lispy_buffer, buffer); /* First check if the CHAR has any property. This is because when we click with the mouse, the mouse pointer is really pointing to the CHAR after POS. */ prop = Fget_char_property (lispy_position, type, lispy_buffer); /* If not, look at the POS's properties. This is necessary because when editing a field with a `local-map' property, we want insertion at the end to obey the `local-map' property. */ if (NILP (prop)) prop = Fget_pos_property (lispy_position, type, lispy_buffer); SET_BUF_BEGV_BOTH (buffer, old_begv, old_begv_byte); SET_BUF_ZV_BOTH (buffer, old_zv, old_zv_byte); /* Use the local map only if it is valid. */ prop = get_keymap (prop, 0, 0); if (CONSP (prop)) return prop; if (EQ (type, Qkeymap)) return Qnil; else return BVAR (buffer, keymap); } /* Produce an interval tree reflecting the intervals in TREE from START to START + LENGTH. The new interval tree has no parent and has a starting-position of 0. */ INTERVAL copy_intervals (INTERVAL tree, ptrdiff_t start, ptrdiff_t length) { register INTERVAL i, new, t; register ptrdiff_t got, prevlen; if (!tree || length <= 0) return NULL; i = find_interval (tree, start); eassert (i && LENGTH (i) > 0); /* If there is only one interval and it's the default, return nil. */ if ((start - i->position + 1 + length) < LENGTH (i) && DEFAULT_INTERVAL_P (i)) return NULL; new = make_interval (); new->position = 0; got = (LENGTH (i) - (start - i->position)); new->total_length = length; eassert (TOTAL_LENGTH (new) >= 0); copy_properties (i, new); t = new; prevlen = got; while (got < length) { i = next_interval (i); t = split_interval_right (t, prevlen); copy_properties (i, t); prevlen = LENGTH (i); got += prevlen; } return balance_an_interval (new); } /* Give STRING the properties of BUFFER from POSITION to LENGTH. */ void copy_intervals_to_string (Lisp_Object string, struct buffer *buffer, ptrdiff_t position, ptrdiff_t length) { INTERVAL interval_copy = copy_intervals (buffer_intervals (buffer), position, length); if (!interval_copy) return; set_interval_object (interval_copy, string); set_string_intervals (string, interval_copy); } /* Return true if strings S1 and S2 have identical properties. Assume they have identical characters. */ bool compare_string_intervals (Lisp_Object s1, Lisp_Object s2) { INTERVAL i1, i2; ptrdiff_t pos = 0; ptrdiff_t end = SCHARS (s1); i1 = find_interval (string_intervals (s1), 0); i2 = find_interval (string_intervals (s2), 0); while (pos < end) { /* Determine how far we can go before we reach the end of I1 or I2. */ ptrdiff_t len1 = (i1 != 0 ? INTERVAL_LAST_POS (i1) : end) - pos; ptrdiff_t len2 = (i2 != 0 ? INTERVAL_LAST_POS (i2) : end) - pos; ptrdiff_t distance = min (len1, len2); /* If we ever find a mismatch between the strings, they differ. */ if (! intervals_equal (i1, i2)) return 0; /* Advance POS till the end of the shorter interval, and advance one or both interval pointers for the new position. */ pos += distance; if (len1 == distance) i1 = next_interval (i1); if (len2 == distance) i2 = next_interval (i2); } return 1; } /* Recursively adjust interval I in the current buffer for setting enable_multibyte_characters to MULTI_FLAG. The range of interval I is START ... END in characters, START_BYTE ... END_BYTE in bytes. */ static void set_intervals_multibyte_1 (INTERVAL i, bool multi_flag, ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end, ptrdiff_t end_byte) { /* Fix the length of this interval. */ if (multi_flag) i->total_length = end - start; else i->total_length = end_byte - start_byte; eassert (TOTAL_LENGTH (i) >= 0); if (TOTAL_LENGTH (i) == 0) { delete_interval (i); return; } /* Recursively fix the length of the subintervals. */ if (i->left) { ptrdiff_t left_end, left_end_byte; if (multi_flag) { ptrdiff_t temp; left_end_byte = start_byte + LEFT_TOTAL_LENGTH (i); left_end = BYTE_TO_CHAR (left_end_byte); temp = CHAR_TO_BYTE (left_end); /* If LEFT_END_BYTE is in the middle of a character, adjust it and LEFT_END to a char boundary. */ if (left_end_byte > temp) { left_end_byte = temp; } if (left_end_byte < temp) { left_end--; left_end_byte = CHAR_TO_BYTE (left_end); } } else { left_end = start + LEFT_TOTAL_LENGTH (i); left_end_byte = CHAR_TO_BYTE (left_end); } set_intervals_multibyte_1 (i->left, multi_flag, start, start_byte, left_end, left_end_byte); } if (i->right) { ptrdiff_t right_start_byte, right_start; if (multi_flag) { ptrdiff_t temp; right_start_byte = end_byte - RIGHT_TOTAL_LENGTH (i); right_start = BYTE_TO_CHAR (right_start_byte); /* If RIGHT_START_BYTE is in the middle of a character, adjust it and RIGHT_START to a char boundary. */ temp = CHAR_TO_BYTE (right_start); if (right_start_byte < temp) { right_start_byte = temp; } if (right_start_byte > temp) { right_start++; right_start_byte = CHAR_TO_BYTE (right_start); } } else { right_start = end - RIGHT_TOTAL_LENGTH (i); right_start_byte = CHAR_TO_BYTE (right_start); } set_intervals_multibyte_1 (i->right, multi_flag, right_start, right_start_byte, end, end_byte); } /* Rounding to char boundaries can theoretically make this interval spurious. If so, delete one child, and copy its property list to this interval. */ if (LEFT_TOTAL_LENGTH (i) + RIGHT_TOTAL_LENGTH (i) >= TOTAL_LENGTH (i)) { if ((i)->left) { set_interval_plist (i, i->left->plist); (i)->left->total_length = 0; delete_interval ((i)->left); } else { set_interval_plist (i, i->right->plist); (i)->right->total_length = 0; delete_interval ((i)->right); } } } /* Update the intervals of the current buffer to fit the contents as multibyte (if MULTI_FLAG) or to fit them as non-multibyte (if not MULTI_FLAG). */ void set_intervals_multibyte (bool multi_flag) { INTERVAL i = buffer_intervals (current_buffer); if (i) set_intervals_multibyte_1 (i, multi_flag, BEG, BEG_BYTE, Z, Z_BYTE); }
gpl-3.0
AntonioModer/decoda
libs/wxWidgets/src/msw/wince/textctrlce.cpp
17
35155
/////////////////////////////////////////////////////////////////////////////// // Name: src/msw/wince/textctrlce.cpp // Purpose: wxTextCtrl implementation for smart phones driven by WinCE // Author: Wlodzimierz ABX Skiba // Modified by: // Created: 30.08.2004 // RCS-ID: $Id: textctrlce.cpp 42816 2006-10-31 08:50:17Z RD $ // Copyright: (c) Wlodzimierz Skiba // License: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_TEXTCTRL && defined(__SMARTPHONE__) && defined(__WXWINCE__) #include "wx/textctrl.h" #ifndef WX_PRECOMP #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly" #endif #include "wx/spinbutt.h" #include "wx/textfile.h" #define GetBuddyHwnd() (HWND)(m_hwndBuddy) #define IsVertical(wxStyle) (true) // ---------------------------------------------------------------------------- // event tables and other macros // ---------------------------------------------------------------------------- #if wxUSE_EXTENDED_RTTI // TODO #else IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxControl) #endif BEGIN_EVENT_TABLE(wxTextCtrl, wxControl) EVT_CHAR(wxTextCtrl::OnChar) EVT_MENU(wxID_CUT, wxTextCtrl::OnCut) EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy) EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste) EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo) EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo) EVT_MENU(wxID_CLEAR, wxTextCtrl::OnDelete) EVT_MENU(wxID_SELECTALL, wxTextCtrl::OnSelectAll) EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut) EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy) EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste) EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo) EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo) EVT_UPDATE_UI(wxID_CLEAR, wxTextCtrl::OnUpdateDelete) EVT_UPDATE_UI(wxID_SELECTALL, wxTextCtrl::OnUpdateSelectAll) EVT_SET_FOCUS(wxTextCtrl::OnSetFocus) END_EVENT_TABLE() // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // the margin between the up-down control and its buddy (can be arbitrary, // choose what you like - or may be decide during run-time depending on the // font size?) static const int MARGIN_BETWEEN = 0; // ============================================================================ // implementation // ============================================================================ wxArrayTextSpins wxTextCtrl::ms_allTextSpins; // ---------------------------------------------------------------------------- // wnd proc for the buddy text ctrl // ---------------------------------------------------------------------------- LRESULT APIENTRY _EXPORT wxBuddyTextCtrlWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { wxTextCtrl *spin = (wxTextCtrl *)wxGetWindowUserData(hwnd); // forward some messages (the key and focus ones only so far) to // the spin ctrl switch ( message ) { case WM_SETFOCUS: // if the focus comes from the spin control itself, don't set it // back to it -- we don't want to go into an infinite loop if ( (WXHWND)wParam == spin->GetHWND() ) break; //else: fall through case WM_KILLFOCUS: case WM_CHAR: case WM_DEADCHAR: case WM_KEYUP: case WM_KEYDOWN: spin->MSWWindowProc(message, wParam, lParam); // The control may have been deleted at this point, so check. if ( !::IsWindow(hwnd) || wxGetWindowUserData(hwnd) != spin ) return 0; break; case WM_GETDLGCODE: // we want to get WXK_RETURN in order to generate the event for it return DLGC_WANTCHARS; } return ::CallWindowProc(CASTWNDPROC spin->GetBuddyWndProc(), hwnd, message, wParam, lParam); } // ---------------------------------------------------------------------------- // creation // ---------------------------------------------------------------------------- void wxTextCtrl::Init() { m_suppressNextUpdate = false; m_isNativeCaretShown = true; } wxTextCtrl::~wxTextCtrl() { } bool wxTextCtrl::Create(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) { if ( (style & wxBORDER_MASK) == wxBORDER_DEFAULT ) style |= wxBORDER_SIMPLE; SetWindowStyle(style); WXDWORD exStyle = 0; WXDWORD msStyle = MSWGetStyle(GetWindowStyle(), & exStyle) ; wxSize sizeText(size), sizeBtn(size); sizeBtn.x = GetBestSpinnerSize(IsVertical(style)).x / 2; if ( sizeText.x == wxDefaultCoord ) { // DEFAULT_ITEM_WIDTH is the default width for the text control sizeText.x = DEFAULT_ITEM_WIDTH + MARGIN_BETWEEN + sizeBtn.x; } sizeText.x -= sizeBtn.x + MARGIN_BETWEEN; if ( sizeText.x <= 0 ) { wxLogDebug(_T("not enough space for wxSpinCtrl!")); } wxPoint posBtn(pos); posBtn.x += sizeText.x + MARGIN_BETWEEN; // we need to turn '\n's into "\r\n"s for the multiline controls wxString valueWin; if ( m_windowStyle & wxTE_MULTILINE ) { valueWin = wxTextFile::Translate(value, wxTextFileType_Dos); } else // single line { valueWin = value; } // we must create the list control before the spin button for the purpose // of the dialog navigation: if there is a static text just before the spin // control, activating it by Alt-letter should give focus to the text // control, not the spin and the dialog navigation code will give focus to // the next control (at Windows level), not the one after it // create the text window m_hwndBuddy = (WXHWND)::CreateWindowEx ( exStyle, // sunken border _T("EDIT"), // window class valueWin, // no window title msStyle, // style (will be shown later) pos.x, pos.y, // position 0, 0, // size (will be set later) GetHwndOf(parent), // parent (HMENU)-1, // control id wxGetInstance(), // app instance NULL // unused client data ); if ( !m_hwndBuddy ) { wxLogLastError(wxT("CreateWindow(buddy text window)")); return false; } // initialize wxControl if ( !CreateControl(parent, id, posBtn, sizeBtn, style, validator, name) ) return false; // now create the real HWND WXDWORD spiner_style = WS_VISIBLE | UDS_ALIGNRIGHT | UDS_EXPANDABLE | UDS_NOSCROLL; if ( !IsVertical(style) ) spiner_style |= UDS_HORZ; if ( style & wxSP_WRAP ) spiner_style |= UDS_WRAP; if ( !MSWCreateControl(UPDOWN_CLASS, spiner_style, posBtn, sizeBtn, _T(""), 0) ) return false; // subclass the text ctrl to be able to intercept some events wxSetWindowUserData(GetBuddyHwnd(), this); m_wndProcBuddy = (WXFARPROC)wxSetWindowProc(GetBuddyHwnd(), wxBuddyTextCtrlWndProc); // set up fonts and colours (This is nomally done in MSWCreateControl) InheritAttributes(); if (!m_hasFont) SetFont(GetDefaultAttributes().font); // set the size of the text window - can do it only now, because we // couldn't call DoGetBestSize() before as font wasn't set if ( sizeText.y <= 0 ) { int cx, cy; wxGetCharSize(GetHWND(), &cx, &cy, GetFont()); sizeText.y = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy); } SetInitialSize(size); (void)::ShowWindow(GetBuddyHwnd(), SW_SHOW); // associate the list window with the spin button (void)::SendMessage(GetHwnd(), UDM_SETBUDDY, (WPARAM)GetBuddyHwnd(), 0); // do it after finishing with m_hwndBuddy creation to avoid generating // initial wxEVT_COMMAND_TEXT_UPDATED message ms_allTextSpins.Add(this); return true; } // Make sure the window style (etc.) reflects the HWND style (roughly) void wxTextCtrl::AdoptAttributesFromHWND() { wxWindow::AdoptAttributesFromHWND(); long style = ::GetWindowLong(GetBuddyHwnd(), GWL_STYLE); if (style & ES_MULTILINE) m_windowStyle |= wxTE_MULTILINE; if (style & ES_PASSWORD) m_windowStyle |= wxTE_PASSWORD; if (style & ES_READONLY) m_windowStyle |= wxTE_READONLY; if (style & ES_WANTRETURN) m_windowStyle |= wxTE_PROCESS_ENTER; if (style & ES_CENTER) m_windowStyle |= wxTE_CENTRE; if (style & ES_RIGHT) m_windowStyle |= wxTE_RIGHT; } WXDWORD wxTextCtrl::MSWGetStyle(long style, WXDWORD *exstyle) const { // we never have an external border WXDWORD msStyle = wxControl::MSWGetStyle ( (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle ); msStyle |= WS_VISIBLE; // styles which we alaways add by default if ( style & wxTE_MULTILINE ) { wxASSERT_MSG( !(style & wxTE_PROCESS_ENTER), wxT("wxTE_PROCESS_ENTER style is ignored for multiline text controls (they always process it)") ); msStyle |= ES_MULTILINE | ES_WANTRETURN; if ( !(style & wxTE_NO_VSCROLL) ) { // always adjust the vertical scrollbar automatically if we have it msStyle |= WS_VSCROLL | ES_AUTOVSCROLL; } style |= wxTE_PROCESS_ENTER; } else // !multiline { // there is really no reason to not have this style for single line // text controls msStyle |= ES_AUTOHSCROLL; } // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz // scrollbar, there is no wrapping -- which makes sense if ( style & wxTE_DONTWRAP ) { // automatically scroll the control horizontally as necessary // // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't // show horz scrollbar at all, even in spite of WS_HSCROLL, and as // it doesn't seem to do any harm for plain edit controls, add it // always msStyle |= WS_HSCROLL | ES_AUTOHSCROLL; } if ( style & wxTE_READONLY ) msStyle |= ES_READONLY; if ( style & wxTE_PASSWORD ) msStyle |= ES_PASSWORD; if ( style & wxTE_NOHIDESEL ) msStyle |= ES_NOHIDESEL; // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0 if ( style & wxTE_CENTRE ) msStyle |= ES_CENTER; else if ( style & wxTE_RIGHT ) msStyle |= ES_RIGHT; else msStyle |= ES_LEFT; // ES_LEFT is 0 as well but for consistency... return msStyle; } // ---------------------------------------------------------------------------- // set/get the controls text // ---------------------------------------------------------------------------- wxString wxTextCtrl::GetValue() const { // range 0..-1 is special for GetRange() and means to retrieve all text return GetRange(0, -1); } wxString wxTextCtrl::GetRange(long from, long to) const { wxString str; if ( from >= to && to != -1 ) { // nothing to retrieve return str; } // retrieve all text str = wxGetWindowText(GetBuddyHwnd()); // need only a range? if ( from < to ) { str = str.Mid(from, to - from); } // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the // canonical one (same one as above) for consistency with the other kinds // of controls and, more importantly, with the other ports str = wxTextFile::Translate(str, wxTextFileType_Unix); return str; } void wxTextCtrl::DoSetValue(const wxString& value, int flags) { // if the text is long enough, it's faster to just set it instead of first // comparing it with the old one (chances are that it will be different // anyhow, this comparison is there to avoid flicker for small single-line // edit controls mostly) if ( (value.length() > 0x400) || (value != GetValue()) ) { DoWriteText(value, flags); // for compatibility, don't move the cursor when doing SetValue() SetInsertionPoint(0); } else // same text { // still send an event for consistency if ( flags & SetValue_SendEvent ) SendUpdateEvent(); } // we should reset the modified flag even if the value didn't really change // mark the control as being not dirty - we changed its text, not the // user DiscardEdits(); } void wxTextCtrl::WriteText(const wxString& value) { DoWriteText(value); } void wxTextCtrl::DoWriteText(const wxString& value, int flags) { bool selectionOnly = (flags & SetValue_SelectionOnly) != 0; wxString valueDos; if ( m_windowStyle & wxTE_MULTILINE ) valueDos = wxTextFile::Translate(value, wxTextFileType_Dos); else valueDos = value; // in some cases we get 2 EN_CHANGE notifications after the SendMessage // call below which is confusing for the client code and so should be // avoided // if ( selectionOnly && HasSelection() ) { m_suppressNextUpdate = true; } ::SendMessage(GetBuddyHwnd(), selectionOnly ? EM_REPLACESEL : WM_SETTEXT, 0, (LPARAM)valueDos.c_str()); if ( !selectionOnly && !( flags & SetValue_SendEvent ) ) { // Windows already sends an update event for single-line // controls. if ( m_windowStyle & wxTE_MULTILINE ) SendUpdateEvent(); } AdjustSpaceLimit(); } void wxTextCtrl::AppendText(const wxString& text) { SetInsertionPointEnd(); WriteText(text); } void wxTextCtrl::Clear() { ::SetWindowText(GetBuddyHwnd(), wxEmptyString); // Windows already sends an update event for single-line // controls. if ( m_windowStyle & wxTE_MULTILINE ) SendUpdateEvent(); } // ---------------------------------------------------------------------------- // Clipboard operations // ---------------------------------------------------------------------------- void wxTextCtrl::Copy() { if (CanCopy()) { ::SendMessage(GetBuddyHwnd(), WM_COPY, 0, 0L); } } void wxTextCtrl::Cut() { if (CanCut()) { ::SendMessage(GetBuddyHwnd(), WM_CUT, 0, 0L); } } void wxTextCtrl::Paste() { if (CanPaste()) { ::SendMessage(GetBuddyHwnd(), WM_PASTE, 0, 0L); } } bool wxTextCtrl::HasSelection() const { long from, to; GetSelection(&from, &to); return from != to; } bool wxTextCtrl::CanCopy() const { // Can copy if there's a selection return HasSelection(); } bool wxTextCtrl::CanCut() const { return CanCopy() && IsEditable(); } bool wxTextCtrl::CanPaste() const { if ( !IsEditable() ) return false; // Standard edit control: check for straight text on clipboard if ( !::OpenClipboard(GetHwndOf(wxTheApp->GetTopWindow())) ) return false; bool isTextAvailable = ::IsClipboardFormatAvailable(CF_TEXT) != 0; ::CloseClipboard(); return isTextAvailable; } // ---------------------------------------------------------------------------- // Accessors // ---------------------------------------------------------------------------- void wxTextCtrl::SetEditable(bool editable) { ::SendMessage(GetBuddyHwnd(), EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L); } void wxTextCtrl::SetInsertionPoint(long pos) { DoSetSelection(pos, pos); } void wxTextCtrl::SetInsertionPointEnd() { if ( GetInsertionPoint() != GetLastPosition() ) SetInsertionPoint(GetLastPosition()); } long wxTextCtrl::GetInsertionPoint() const { DWORD Pos = (DWORD)::SendMessage(GetBuddyHwnd(), EM_GETSEL, 0, 0L); return Pos & 0xFFFF; } wxTextPos wxTextCtrl::GetLastPosition() const { int numLines = GetNumberOfLines(); long posStartLastLine = XYToPosition(0, numLines - 1); long lenLastLine = GetLengthOfLineContainingPos(posStartLastLine); return posStartLastLine + lenLastLine; } void wxTextCtrl::GetSelection(long* from, long* to) const { DWORD dwStart, dwEnd; ::SendMessage(GetBuddyHwnd(), EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd); *from = dwStart; *to = dwEnd; } bool wxTextCtrl::IsEditable() const { if ( !GetBuddyHwnd() ) return true; long style = ::GetWindowLong(GetBuddyHwnd(), GWL_STYLE); return (style & ES_READONLY) == 0; } // ---------------------------------------------------------------------------- // selection // ---------------------------------------------------------------------------- void wxTextCtrl::SetSelection(long from, long to) { // if from and to are both -1, it means (in wxWidgets) that all text should // be selected - translate into Windows convention if ( (from == -1) && (to == -1) ) { from = 0; to = -1; } DoSetSelection(from, to); } void wxTextCtrl::DoSetSelection(long from, long to, bool scrollCaret) { ::SendMessage(GetBuddyHwnd(), EM_SETSEL, (WPARAM)from, (LPARAM)to); if ( scrollCaret ) { ::SendMessage(GetBuddyHwnd(), EM_SCROLLCARET, (WPARAM)0, (LPARAM)0); } } // ---------------------------------------------------------------------------- // Working with files // ---------------------------------------------------------------------------- bool wxTextCtrl::LoadFile(const wxString& file) { if ( wxTextCtrlBase::LoadFile(file) ) { // update the size limit if needed AdjustSpaceLimit(); return true; } return false; } // ---------------------------------------------------------------------------- // Editing // ---------------------------------------------------------------------------- void wxTextCtrl::Replace(long from, long to, const wxString& value) { // Set selection and remove it DoSetSelection(from, to, false); DoWriteText(value, SetValue_SelectionOnly); } void wxTextCtrl::Remove(long from, long to) { Replace(from, to, wxEmptyString); } bool wxTextCtrl::IsModified() const { return ::SendMessage(GetBuddyHwnd(), EM_GETMODIFY, 0, 0) != 0; } void wxTextCtrl::MarkDirty() { ::SendMessage(GetBuddyHwnd(), EM_SETMODIFY, TRUE, 0L); } void wxTextCtrl::DiscardEdits() { ::SendMessage(GetBuddyHwnd(), EM_SETMODIFY, FALSE, 0L); } int wxTextCtrl::GetNumberOfLines() const { return (int)::SendMessage(GetBuddyHwnd(), EM_GETLINECOUNT, 0, 0L); } // ---------------------------------------------------------------------------- // Positions <-> coords // ---------------------------------------------------------------------------- long wxTextCtrl::XYToPosition(long x, long y) const { // This gets the char index for the _beginning_ of this line long charIndex = ::SendMessage(GetBuddyHwnd(), EM_LINEINDEX, (WPARAM)y, (LPARAM)0); return charIndex + x; } bool wxTextCtrl::PositionToXY(long pos, long *x, long *y) const { // This gets the line number containing the character long lineNo = ::SendMessage(GetBuddyHwnd(), EM_LINEFROMCHAR, (WPARAM)pos, 0); if ( lineNo == -1 ) { // no such line return false; } // This gets the char index for the _beginning_ of this line long charIndex = ::SendMessage(GetBuddyHwnd(), EM_LINEINDEX, (WPARAM)lineNo, (LPARAM)0); if ( charIndex == -1 ) { return false; } // The X position must therefore be the different between pos and charIndex if ( x ) *x = pos - charIndex; if ( y ) *y = lineNo; return true; } wxTextCtrlHitTestResult wxTextCtrl::HitTest(const wxPoint& pt, long *posOut) const { // first get the position from Windows // for the plain ones, we are limited to 16 bit positions which are // combined in a single 32 bit value LPARAM lParam = MAKELPARAM(pt.x, pt.y); LRESULT pos = ::SendMessage(GetBuddyHwnd(), EM_CHARFROMPOS, 0, lParam); if ( pos == -1 ) { // this seems to indicate an error... return wxTE_HT_UNKNOWN; } // for plain EDIT controls the higher word contains something else pos = LOWORD(pos); // next determine where it is relatively to our point: EM_CHARFROMPOS // always returns the closest character but we need to be more precise, so // double check that we really are where it pretends POINTL ptReal; LRESULT lRc = ::SendMessage(GetBuddyHwnd(), EM_POSFROMCHAR, pos, 0); if ( lRc == -1 ) { // this is apparently returned when pos corresponds to the last // position ptReal.x = ptReal.y = 0; } else { ptReal.x = LOWORD(lRc); ptReal.y = HIWORD(lRc); } wxTextCtrlHitTestResult rc; if ( pt.y > ptReal.y + GetCharHeight() ) rc = wxTE_HT_BELOW; else if ( pt.x > ptReal.x + GetCharWidth() ) rc = wxTE_HT_BEYOND; else rc = wxTE_HT_ON_TEXT; if ( posOut ) *posOut = pos; return rc; } void wxTextCtrl::ShowPosition(long pos) { int currentLineLineNo = (int)::SendMessage(GetBuddyHwnd(), EM_GETFIRSTVISIBLELINE, 0, 0L); int specifiedLineLineNo = (int)::SendMessage(GetBuddyHwnd(), EM_LINEFROMCHAR, (WPARAM)pos, 0L); int linesToScroll = specifiedLineLineNo - currentLineLineNo; if (linesToScroll != 0) (void)::SendMessage(GetBuddyHwnd(), EM_LINESCROLL, 0, (LPARAM)linesToScroll); } long wxTextCtrl::GetLengthOfLineContainingPos(long pos) const { return ::SendMessage(GetBuddyHwnd(), EM_LINELENGTH, (WPARAM)pos, 0L); } int wxTextCtrl::GetLineLength(long lineNo) const { long pos = XYToPosition(0, lineNo); return GetLengthOfLineContainingPos(pos); } wxString wxTextCtrl::GetLineText(long lineNo) const { size_t len = (size_t)GetLineLength(lineNo) + 1; // there must be at least enough place for the length WORD in the // buffer len += sizeof(WORD); wxString str; { wxStringBufferLength tmp(str, len); wxChar *buf = tmp; *(WORD *)buf = (WORD)len; len = (size_t)::SendMessage(GetBuddyHwnd(), EM_GETLINE, lineNo, (LPARAM)buf); // remove the '\n' at the end, if any (this is how this function is // supposed to work according to the docs) if ( buf[len - 1] == _T('\n') ) { len--; } buf[len] = 0; tmp.SetLength(len); } return str; } void wxTextCtrl::SetMaxLength(unsigned long len) { ::SendMessage(GetBuddyHwnd(), EM_LIMITTEXT, len, 0); } // ---------------------------------------------------------------------------- // Undo/redo // ---------------------------------------------------------------------------- void wxTextCtrl::Undo() { if (CanUndo()) { ::SendMessage(GetBuddyHwnd(), EM_UNDO, 0, 0); } } void wxTextCtrl::Redo() { if (CanRedo()) { ::SendMessage(GetBuddyHwnd(), EM_UNDO, 0, 0); } } bool wxTextCtrl::CanUndo() const { return ::SendMessage(GetBuddyHwnd(), EM_CANUNDO, 0, 0) != 0; } bool wxTextCtrl::CanRedo() const { return ::SendMessage(GetBuddyHwnd(), EM_CANUNDO, 0, 0) != 0; } // ---------------------------------------------------------------------------- // caret handling // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // implemenation details // ---------------------------------------------------------------------------- void wxTextCtrl::Command(wxCommandEvent & event) { SetValue(event.GetString()); ProcessCommand (event); } // ---------------------------------------------------------------------------- // kbd input processing // ---------------------------------------------------------------------------- void wxTextCtrl::OnChar(wxKeyEvent& event) { switch ( event.GetKeyCode() ) { case WXK_RETURN: if ( !HasFlag(wxTE_MULTILINE) ) { wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId); InitCommandEvent(event); event.SetString(GetValue()); if ( GetEventHandler()->ProcessEvent(event) ) return; } //else: multiline controls need Enter for themselves break; case WXK_TAB: // ok, so this is getting absolutely ridiculous but I don't see // any other way to fix this bug: when a multiline text control is // inside a wxFrame, we need to generate the navigation event as // otherwise nothing happens at all, but when the same control is // created inside a dialog, IsDialogMessage() *does* switch focus // all by itself and so if we do it here as well, it is advanced // twice and goes to the next control... to prevent this from // happening we're doing this ugly check, the logic being that if // we don't have focus then it had been already changed to the next // control // // the right thing to do would, of course, be to understand what // the hell is IsDialogMessage() doing but this is beyond my feeble // forces at the moment unfortunately if ( !(m_windowStyle & wxTE_PROCESS_TAB)) { if ( FindFocus() == this ) { int flags = 0; if (!event.ShiftDown()) flags |= wxNavigationKeyEvent::IsForward ; if (event.ControlDown()) flags |= wxNavigationKeyEvent::WinChange ; if (Navigate(flags)) return; } } else { // Insert tab since calling the default Windows handler // doesn't seem to do it WriteText(wxT("\t")); } break; } // no, we didn't process it event.Skip(); } WXLRESULT wxTextCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) { WXLRESULT lRc = wxTextCtrlBase::MSWWindowProc(nMsg, wParam, lParam); if ( nMsg == WM_GETDLGCODE ) { // we always want the chars and the arrows: the arrows for navigation // and the chars because we want Ctrl-C to work even in a read only // control long lDlgCode = DLGC_WANTCHARS | DLGC_WANTARROWS; if ( IsEditable() ) { // we may have several different cases: // 1. normal case: both TAB and ENTER are used for dlg navigation // 2. ctrl which wants TAB for itself: ENTER is used to pass to the // next control in the dialog // 3. ctrl which wants ENTER for itself: TAB is used for dialog // navigation // 4. ctrl which wants both TAB and ENTER: Ctrl-ENTER is used to go // to the next control // the multiline edit control should always get <Return> for itself if ( HasFlag(wxTE_PROCESS_ENTER) || HasFlag(wxTE_MULTILINE) ) lDlgCode |= DLGC_WANTMESSAGE; if ( HasFlag(wxTE_PROCESS_TAB) ) lDlgCode |= DLGC_WANTTAB; lRc |= lDlgCode; } else // !editable { // NB: use "=", not "|=" as the base class version returns the // same flags is this state as usual (i.e. including // DLGC_WANTMESSAGE). This is strange (how does it work in the // native Win32 apps?) but for now live with it. lRc = lDlgCode; } } return lRc; } // ---------------------------------------------------------------------------- // text control event processing // ---------------------------------------------------------------------------- bool wxTextCtrl::SendUpdateEvent() { // is event reporting suspended? if ( m_suppressNextUpdate ) { // do process the next one m_suppressNextUpdate = false; return false; } wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId()); InitCommandEvent(event); event.SetString(GetValue()); return ProcessCommand(event); } bool wxTextCtrl::MSWCommand(WXUINT param, WXWORD WXUNUSED(id)) { switch ( param ) { case EN_SETFOCUS: case EN_KILLFOCUS: { wxFocusEvent event(param == EN_KILLFOCUS ? wxEVT_KILL_FOCUS : wxEVT_SET_FOCUS, m_windowId); event.SetEventObject(this); GetEventHandler()->ProcessEvent(event); } break; case EN_CHANGE: SendUpdateEvent(); break; case EN_MAXTEXT: // the text size limit has been hit -- try to increase it if ( !AdjustSpaceLimit() ) { wxCommandEvent event(wxEVT_COMMAND_TEXT_MAXLEN, m_windowId); InitCommandEvent(event); event.SetString(GetValue()); ProcessCommand(event); } break; // the other edit notification messages are not processed default: return false; } // processed return true; } bool wxTextCtrl::AdjustSpaceLimit() { unsigned int limit = ::SendMessage(GetBuddyHwnd(), EM_GETLIMITTEXT, 0, 0); // HACK: we try to automatically extend the limit for the amount of text // to allow (interactively) entering more than 64Kb of text under // Win9x but we shouldn't reset the text limit which was previously // set explicitly with SetMaxLength() // // we could solve this by storing the limit we set in wxTextCtrl but // to save space we prefer to simply test here the actual limit // value: we consider that SetMaxLength() can only be called for // values < 32Kb if ( limit < 0x8000 ) { // we've got more text than limit set by SetMaxLength() return false; } unsigned int len = ::GetWindowTextLength(GetBuddyHwnd()); if ( len >= limit ) { limit = len + 0x8000; // 32Kb if ( limit > 0xffff ) { // this will set it to a platform-dependent maximum (much more // than 64Kb under NT) limit = 0; } ::SendMessage(GetBuddyHwnd(), EM_LIMITTEXT, limit, 0L); } // we changed the limit return true; } bool wxTextCtrl::AcceptsFocus() const { // we don't want focus if we can't be edited unless we're a multiline // control because then it might be still nice to get focus from keyboard // to be able to scroll it without mouse return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus(); } void wxTextCtrl::DoMoveWindow(int x, int y, int width, int height) { int widthBtn = GetBestSpinnerSize(IsVertical(GetWindowStyle())).x / 2; int widthText = width - widthBtn - MARGIN_BETWEEN; if ( widthText <= 0 ) { wxLogDebug(_T("not enough space for wxSpinCtrl!")); } if ( !::MoveWindow(GetBuddyHwnd(), x, y, widthText, height, TRUE) ) { wxLogLastError(wxT("MoveWindow(buddy)")); } x += widthText + MARGIN_BETWEEN; if ( !::MoveWindow(GetHwnd(), x, y, widthBtn, height, TRUE) ) { wxLogLastError(wxT("MoveWindow")); } } wxSize wxTextCtrl::DoGetBestSize() const { int cx, cy; wxGetCharSize(GetBuddyHwnd(), &cx, &cy, GetFont()); int wText = DEFAULT_ITEM_WIDTH; int hText = cy; if ( m_windowStyle & wxTE_MULTILINE ) { hText *= wxMax(GetNumberOfLines(), 5); } //else: for single line control everything is ok // we have to add the adjustments for the control height only once, not // once per line, so do it after multiplication above hText += EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy) - cy; return wxSize(wText, hText); } // ---------------------------------------------------------------------------- // standard handlers for standard edit menu events // ---------------------------------------------------------------------------- void wxTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event)) { Cut(); } void wxTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event)) { Copy(); } void wxTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event)) { Paste(); } void wxTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event)) { Undo(); } void wxTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event)) { Redo(); } void wxTextCtrl::OnDelete(wxCommandEvent& WXUNUSED(event)) { long from, to; GetSelection(& from, & to); if (from != -1 && to != -1) Remove(from, to); } void wxTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event)) { SetSelection(-1, -1); } void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event) { event.Enable( CanCut() ); } void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event) { event.Enable( CanCopy() ); } void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event) { event.Enable( CanPaste() ); } void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event) { event.Enable( CanUndo() ); } void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event) { event.Enable( CanRedo() ); } void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent& event) { long from, to; GetSelection(& from, & to); event.Enable(from != -1 && to != -1 && from != to && IsEditable()) ; } void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event) { event.Enable(GetLastPosition() > 0); } void wxTextCtrl::OnSetFocus(wxFocusEvent& WXUNUSED(event)) { // be sure the caret remains invisible if the user had hidden it if ( !m_isNativeCaretShown ) { ::HideCaret(GetBuddyHwnd()); } } #endif // wxUSE_TEXTCTRL && __SMARTPHONE__ && __WXWINCE__
gpl-3.0
davidbuzz/ardupilot
libraries/SITL/SIM_Gripper_EPM.cpp
19
3694
/* 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/>. */ /* simple Gripper (OpenGrab EPM) simulation class */ #include "SIM_Gripper_EPM.h" #include "AP_HAL/AP_HAL.h" #include <stdio.h> #include <AP_Math/AP_Math.h> extern const AP_HAL::HAL& hal; using namespace SITL; // table of user settable parameters const AP_Param::GroupInfo Gripper_EPM::var_info[] = { // @Param: ENABLE // @DisplayName: Gripper servo Sim enable/disable // @Description: Allows you to enable (1) or disable (0) the gripper servo simulation // @Values: 0:Disabled,1:Enabled // @User: Advanced AP_GROUPINFO("ENABLE", 0, Gripper_EPM, gripper_emp_enable, 0), // @Param: PIN // @DisplayName: Gripper emp pin // @Description: The pin number that the gripper emp is connected to. (start at 1) // @Range: 0 15 // @User: Advanced AP_GROUPINFO("PIN", 1, Gripper_EPM, gripper_emp_servo_pin, -1), AP_GROUPEND }; /* update gripper state */ void Gripper_EPM::update_servobased(int16_t gripper_pwm) { if (!servo_based) { return; } if (gripper_pwm >= 0) { demand = (gripper_pwm - 1000) * 0.001f; // 0.0 - 1.0 if (is_negative(demand)) { // never updated demand = 0.0f; } } } void Gripper_EPM::update_from_demand() { const uint64_t now = AP_HAL::micros64(); const float dt = (now - last_update_us) * 1.0e-6f; // decay the field field_strength = field_strength * (100.0f - field_decay_rate * dt) / 100.0f; // note that "demand" here is just an on/off switch; we only care // about which range it falls into if (demand > 0.6f) { // we are instructed to grip harder field_strength = field_strength + (100.0f - field_strength) * field_strength_slew_rate / 100.0f * dt; } else if (demand < 0.4f) { // we are instructed to loosen grip field_strength = field_strength * (100.0f - field_degauss_rate * dt) / 100.0f; } else { // neutral; no demanded change } if (should_report()) { hal.console->printf("demand=%f\n", demand); hal.console->printf("Field strength: %f%%\n", field_strength); hal.console->printf("Field strength: %f Tesla\n", tesla()); last_report_us = now; reported_field_strength = field_strength; } last_update_us = now; } void Gripper_EPM::update(const struct sitl_input &input) { const int16_t gripper_pwm = gripper_emp_servo_pin >= 1 ? input.servos[gripper_emp_servo_pin-1] : -1; update_servobased(gripper_pwm); update_from_demand(); } bool Gripper_EPM::should_report() const { if (AP_HAL::micros64() - last_report_us < report_interval) { return false; } if (fabsf(reported_field_strength - field_strength) > 10.0) { return true; } return false; } float Gripper_EPM::tesla() const { // https://en.wikipedia.org/wiki/Orders_of_magnitude_(magnetic_field) // 200N lifting capacity ~= 2.5T const float percentage_to_tesla = 0.25f; return static_cast<float>(percentage_to_tesla * field_strength / 100.0f); }
gpl-3.0
OS2World/DEV-MISC-gettext
gettext-tools/gnulib-tests/test-ftello4.c
19
1793
/* Test of ftello() function. Copyright (C) 2011-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> #include <stdio.h> #include <errno.h> #include <unistd.h> #include "macros.h" int main (int argc, char **argv) { const char *filename = argv[1]; /* Test that ftello() sets errno if someone else closes the stream fd behind the back of stdio. */ { FILE *fp = fopen (filename, "r"); ASSERT (fp != NULL); setvbuf (fp, NULL, _IONBF, 0); ASSERT (close (fileno (fp)) == 0); errno = 0; ASSERT (ftello (fp) == (off_t)-1); ASSERT (errno == EBADF); fclose (fp); } /* Test that ftello() sets errno if the stream was constructed with an invalid file descriptor. */ { FILE *fp = fdopen (-1, "w"); if (fp != NULL) { errno = 0; ASSERT (ftello (fp) == (off_t)-1); ASSERT (errno == EBADF); fclose (fp); } } { FILE *fp; close (99); fp = fdopen (99, "w"); if (fp != NULL) { errno = 0; ASSERT (ftello (fp) == (off_t)-1); ASSERT (errno == EBADF); fclose (fp); } } return 0; }
gpl-3.0
slfl/HUAWEI89_WE_KK_610
kernel/arch/sh/kernel/cpu/sh2a/clock-sh7201.c
9237
2017
/* * arch/sh/kernel/cpu/sh2a/clock-sh7201.c * * SH7201 support for the clock framework * * Copyright (C) 2008 Peter Griffin <pgriffin@mpc-data.co.uk> * * Based on clock-sh4.c * Copyright (C) 2005 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/init.h> #include <linux/kernel.h> #include <asm/clock.h> #include <asm/freq.h> #include <asm/io.h> static const int pll1rate[]={1,2,3,4,6,8}; static const int pfc_divisors[]={1,2,3,4,6,8,12}; #define ifc_divisors pfc_divisors static unsigned int pll2_mult; static void master_clk_init(struct clk *clk) { clk->rate = 10000000 * pll2_mult * pll1rate[(__raw_readw(FREQCR) >> 8) & 0x0007]; } static struct sh_clk_ops sh7201_master_clk_ops = { .init = master_clk_init, }; static unsigned long module_clk_recalc(struct clk *clk) { int idx = (__raw_readw(FREQCR) & 0x0007); return clk->parent->rate / pfc_divisors[idx]; } static struct sh_clk_ops sh7201_module_clk_ops = { .recalc = module_clk_recalc, }; static unsigned long bus_clk_recalc(struct clk *clk) { int idx = (__raw_readw(FREQCR) & 0x0007); return clk->parent->rate / pfc_divisors[idx]; } static struct sh_clk_ops sh7201_bus_clk_ops = { .recalc = bus_clk_recalc, }; static unsigned long cpu_clk_recalc(struct clk *clk) { int idx = ((__raw_readw(FREQCR) >> 4) & 0x0007); return clk->parent->rate / ifc_divisors[idx]; } static struct sh_clk_ops sh7201_cpu_clk_ops = { .recalc = cpu_clk_recalc, }; static struct sh_clk_ops *sh7201_clk_ops[] = { &sh7201_master_clk_ops, &sh7201_module_clk_ops, &sh7201_bus_clk_ops, &sh7201_cpu_clk_ops, }; void __init arch_init_clk_ops(struct sh_clk_ops **ops, int idx) { if (test_mode_pin(MODE_PIN1 | MODE_PIN0)) pll2_mult = 1; else if (test_mode_pin(MODE_PIN1)) pll2_mult = 2; else pll2_mult = 4; if (idx < ARRAY_SIZE(sh7201_clk_ops)) *ops = sh7201_clk_ops[idx]; }
gpl-3.0
ndhanushkodi/SoftwareSystems
lecture18/pthread_example.c
23
2492
/* Example code for Software Systems at Olin College. Based on an example from http://www.learn-c.org/en/Linked_lists Copyright 2014 Allen Downey License: Creative Commons Attribution-ShareAlike 3.0 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pthread.h> #include <errno.h> /* This typedef is the C equivalent of creating a new class named Card, with the following instance variables, and no methods */ typedef struct { int rank, suit; } Card; /* The entry procedure is where the child thread will start executing. When the child thread starts, its stack will contain only the activation record for entry. When we return from entry, the thread terminates, just as when the parent thread returns from main, it terminates. */ void *entry (void *arg) { /* The entry procedure takes a single pointer as an argument, but it can be a pointer to anything, including structures that are in the heap (as in this case) */ Card *card = (Card *) arg; int ret; /* I put this sleep statement here to force the parent to run first */ sleep(1); /* alternatively, I could use... */ ret = sched_yield (); if (ret == -1) { perror ("yield failed"); exit (-1); } printf ("Child: rank = %d, suit = %d\n", card->rank, card->suit); pthread_exit (NULL); } /* the parent thread starts executing in main */ int main () { /* the parent thread creates a new object in the heap using malloc */ Card *card = (Card *) malloc (sizeof (Card)); int i, ret; pthread_t child; card->rank = 6; card->suit = 3; /* the parent thread creates the new thread, passing a pointer to card as an argument */ ret = pthread_create (&child, NULL, entry, (void *) card); if (ret == -1) { perror ("pthread_create failed"); exit (-1); } /* when the parent thread modifies the card, the child sees the change! */ card->rank = 7; printf ("Parent: rank = %d, suit = %d\n", card->rank, card->suit); /* if the parent is done with the child, it detaches it, which means that when the child completes, its resources will be reclaimed */ ret = pthread_detach (child); if (ret == -1) { perror ("pthread_detach failed"); exit (-1); } /* if the parent dies before the child, it usually takes the child with it! Unless, that is, the parent calls pthread_exit, which forces it to wait for all threads to terminate. */ pthread_exit (NULL); }
gpl-3.0
curiousguy13/shogun
src/shogun/io/IOBuffer.cpp
23
4430
/* Copyright (c) 2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed under the BSD (revised) open source license. Copyright (c) 2011 Berlin Institute of Technology and Max-Planck-Society. 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. Shogun adjustments (w) 2011 Shashwat Lal Das */ #include <string.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <shogun/io/IOBuffer.h> #include <shogun/io/SGIO.h> #include <shogun/lib/v_array.h> using namespace shogun; CIOBuffer::CIOBuffer() { init(); } CIOBuffer::CIOBuffer(int fd) { init(); working_file = fd; } CIOBuffer::~CIOBuffer() { } void CIOBuffer::init() { size_t s = 1 << 16; space.reserve(s); endloaded = space.begin; working_file=-1; } void CIOBuffer::use_file(int fd) { working_file = fd; } int CIOBuffer::open_file(const char* name, char flag) { int ret=1; switch(flag) { case 'r': working_file = open(name, O_RDONLY|O_LARGEFILE); break; case 'w': working_file = open(name, O_CREAT|O_TRUNC|O_WRONLY, 0666); break; default: SG_ERROR("Unknown file operation. Something other than 'r'/'w' specified.\n") ret = 0; } return ret; } void CIOBuffer::reset_file() { lseek(working_file, 0, SEEK_SET); endloaded = space.begin; space.end = space.begin; } void CIOBuffer::set(char *p) { space.end = p; } ssize_t CIOBuffer::read_file(void* buf, size_t nbytes) { return read(working_file, buf, nbytes); } size_t CIOBuffer::fill() { if (space.end_array - endloaded == 0) { size_t offset = endloaded - space.begin; space.reserve(2 * (space.end_array - space.begin)); endloaded = space.begin+offset; } ssize_t num_read = read_file(endloaded, space.end_array - endloaded); if (num_read >= 0) { endloaded = endloaded+num_read; return num_read; } else return 0; } ssize_t CIOBuffer::write_file(const void* buf, size_t nbytes) { return write(working_file, buf, nbytes); } void CIOBuffer::flush() { if (working_file>=0) { if (write_file(space.begin, space.index()) != (int) space.index()) SG_ERROR("Error, failed to write example!\n") } space.end = space.begin; fsync(working_file); } bool CIOBuffer::close_file() { if (working_file < 0) return false; else { int r = close(working_file); if (r < 0) SG_ERROR("Error closing the file!\n") return true; } } ssize_t CIOBuffer::readto(char* &pointer, char terminal) { //Return a pointer to the bytes before the terminal. Must be less //than the buffer size. pointer = space.end; while (pointer != endloaded && *pointer != terminal) pointer++; if (pointer != endloaded) { size_t n = pointer - space.end; space.end = pointer+1; pointer -= n; return n; } else { if (endloaded == space.end_array) { size_t left = endloaded - space.end; memmove(space.begin, space.end, left); space.end = space.begin; endloaded = space.begin+left; pointer = endloaded; } if (fill() > 0)// more bytes are read. return readto(pointer,terminal); else //no more bytes to read, return nothing. return 0; } } void CIOBuffer::buf_write(char* &pointer, int n) { if (space.end + n <= space.end_array) { pointer = space.end; space.end += n; } else // Time to dump the file { if (space.end != space.begin) flush(); else // Array is short, so increase size. { space.reserve(2 * (space.end_array - space.begin)); endloaded = space.begin; } buf_write(pointer,n); } } unsigned int CIOBuffer::buf_read(char* &pointer, int n) { // Return a pointer to the next n bytes. // n must be smaller than the maximum size. if (space.end + n <= endloaded) { pointer = space.end; space.end += n; return n; } else // out of bytes, so refill. { if (space.end != space.begin) //There exists room to shift. { // Out of buffer so swap to beginning. int left = endloaded - space.end; memmove(space.begin, space.end, left); space.end = space.begin; endloaded = space.begin+left; } if (fill() > 0) return buf_read(pointer,n);// more bytes are read. else { // No more bytes to read, return all that we have left. pointer = space.end; space.end = endloaded; return endloaded - pointer; } } }
gpl-3.0
PJayB/DOOM-3-BFG-DX11
neo/idlib/math/Ode.cpp
26
9216
/* =========================================================================== Doom 3 BFG Edition GPL Source Code Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code"). Doom 3 BFG Edition 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 BFG Edition 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 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 BFG Edition 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 BFG Edition 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. =========================================================================== */ #pragma hdrstop #include "../precompiled.h" //=============================================================== // // idODE_Euler // //=============================================================== /* ============= idODE_Euler::idODE_Euler ============= */ idODE_Euler::idODE_Euler( const int dim, deriveFunction_t dr, const void *ud ) { dimension = dim; derivatives = new (TAG_MATH) float[dim]; derive = dr; userData = ud; } /* ============= idODE_Euler::~idODE_Euler ============= */ idODE_Euler::~idODE_Euler() { delete[] derivatives; } /* ============= idODE_Euler::Evaluate ============= */ float idODE_Euler::Evaluate( const float *state, float *newState, float t0, float t1 ) { float delta; int i; derive( t0, userData, state, derivatives ); delta = t1 - t0; for ( i = 0; i < dimension; i++ ) { newState[i] = state[i] + delta * derivatives[i]; } return delta; } //=============================================================== // // idODE_Midpoint // //=============================================================== /* ============= idODE_Midpoint::idODE_Midpoint ============= */ idODE_Midpoint::idODE_Midpoint( const int dim, deriveFunction_t dr, const void *ud ) { dimension = dim; tmpState = new (TAG_MATH) float[dim]; derivatives = new (TAG_MATH) float[dim]; derive = dr; userData = ud; } /* ============= idODE_Midpoint::~idODE_Midpoint ============= */ idODE_Midpoint::~idODE_Midpoint() { delete tmpState; delete derivatives; } /* ============= idODE_Midpoint::~Evaluate ============= */ float idODE_Midpoint::Evaluate( const float *state, float *newState, float t0, float t1 ) { double delta, halfDelta; int i; delta = t1 - t0; halfDelta = delta * 0.5; // first step derive( t0, userData, state, derivatives ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + halfDelta * derivatives[i]; } // second step derive( t0 + halfDelta, userData, tmpState, derivatives ); for ( i = 0; i < dimension; i++ ) { newState[i] = state[i] + delta * derivatives[i]; } return delta; } //=============================================================== // // idODE_RK4 // //=============================================================== /* ============= idODE_RK4::idODE_RK4 ============= */ idODE_RK4::idODE_RK4( const int dim, deriveFunction_t dr, const void *ud ) { dimension = dim; derive = dr; userData = ud; tmpState = new (TAG_MATH) float[dim]; d1 = new (TAG_MATH) float[dim]; d2 = new (TAG_MATH) float[dim]; d3 = new (TAG_MATH) float[dim]; d4 = new (TAG_MATH) float[dim]; } /* ============= idODE_RK4::~idODE_RK4 ============= */ idODE_RK4::~idODE_RK4() { delete tmpState; delete d1; delete d2; delete d3; delete d4; } /* ============= idODE_RK4::Evaluate ============= */ float idODE_RK4::Evaluate( const float *state, float *newState, float t0, float t1 ) { double delta, halfDelta, sixthDelta; int i; delta = t1 - t0; halfDelta = delta * 0.5; // first step derive( t0, userData, state, d1 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + halfDelta * d1[i]; } // second step derive( t0 + halfDelta, userData, tmpState, d2 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + halfDelta * d2[i]; } // third step derive( t0 + halfDelta, userData, tmpState, d3 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + delta * d3[i]; } // fourth step derive( t0 + delta, userData, tmpState, d4 ); sixthDelta = delta * (1.0/6.0); for ( i = 0; i < dimension; i++ ) { newState[i] = state[i] + sixthDelta * (d1[i] + 2.0 * (d2[i] + d3[i]) + d4[i]); } return delta; } //=============================================================== // // idODE_RK4Adaptive // //=============================================================== /* ============= idODE_RK4Adaptive::idODE_RK4Adaptive ============= */ idODE_RK4Adaptive::idODE_RK4Adaptive( const int dim, deriveFunction_t dr, const void *ud ) { dimension = dim; derive = dr; userData = ud; maxError = 0.01f; tmpState = new (TAG_MATH) float[dim]; d1 = new (TAG_MATH) float[dim]; d1half = new (TAG_MATH) float [dim]; d2 = new (TAG_MATH) float[dim]; d3 = new (TAG_MATH) float[dim]; d4 = new (TAG_MATH) float[dim]; } /* ============= idODE_RK4Adaptive::~idODE_RK4Adaptive ============= */ idODE_RK4Adaptive::~idODE_RK4Adaptive() { delete tmpState; delete d1; delete d1half; delete d2; delete d3; delete d4; } /* ============= idODE_RK4Adaptive::SetMaxError ============= */ void idODE_RK4Adaptive::SetMaxError( const float err ) { if ( err > 0.0f ) { maxError = err; } } /* ============= idODE_RK4Adaptive::Evaluate ============= */ float idODE_RK4Adaptive::Evaluate( const float *state, float *newState, float t0, float t1 ) { double delta, halfDelta, fourthDelta, sixthDelta; double error, max; int i, n; delta = t1 - t0; for ( n = 0; n < 4; n++ ) { halfDelta = delta * 0.5; fourthDelta = delta * 0.25; // first step of first half delta derive( t0, userData, state, d1 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + fourthDelta * d1[i]; } // second step of first half delta derive( t0 + fourthDelta, userData, tmpState, d2 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + fourthDelta * d2[i]; } // third step of first half delta derive( t0 + fourthDelta, userData, tmpState, d3 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + halfDelta * d3[i]; } // fourth step of first half delta derive( t0 + halfDelta, userData, tmpState, d4 ); sixthDelta = halfDelta * (1.0/6.0); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + sixthDelta * (d1[i] + 2.0 * (d2[i] + d3[i]) + d4[i]); } // first step of second half delta derive( t0 + halfDelta, userData, tmpState, d1half ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + fourthDelta * d1half[i]; } // second step of second half delta derive( t0 + halfDelta + fourthDelta, userData, tmpState, d2 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + fourthDelta * d2[i]; } // third step of second half delta derive( t0 + halfDelta + fourthDelta, userData, tmpState, d3 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + halfDelta * d3[i]; } // fourth step of second half delta derive( t0 + delta, userData, tmpState, d4 ); sixthDelta = halfDelta * (1.0/6.0); for ( i = 0; i < dimension; i++ ) { newState[i] = state[i] + sixthDelta * (d1[i] + 2.0 * (d2[i] + d3[i]) + d4[i]); } // first step of full delta for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + halfDelta * d1[i]; } // second step of full delta derive( t0 + halfDelta, userData, tmpState, d2 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + halfDelta * d2[i]; } // third step of full delta derive( t0 + halfDelta, userData, tmpState, d3 ); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + delta * d3[i]; } // fourth step of full delta derive( t0 + delta, userData, tmpState, d4 ); sixthDelta = delta * (1.0/6.0); for ( i = 0; i < dimension; i++ ) { tmpState[i] = state[i] + sixthDelta * (d1[i] + 2.0 * (d2[i] + d3[i]) + d4[i]); } // get max estimated error max = 0.0; for ( i = 0; i < dimension; i++ ) { error = idMath::Fabs( (newState[i] - tmpState[i]) / (delta * d1[i] + 1e-10) ); if ( error > max ) { max = error; } } error = max / maxError; if ( error <= 1.0f ) { return delta * 4.0; } if ( delta <= 1e-7 ) { return delta; } delta *= 0.25; } return delta; }
gpl-3.0
s20121035/rk3288_android5.1_repo
external/libnl/lib/netfilter/log_msg.c
27
4950
/* * lib/netfilter/log_msg.c Netfilter Log Message * * 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. * * Copyright (c) 2003-2008 Thomas Graf <tgraf@suug.ch> * Copyright (c) 2007 Philip Craig <philipc@snapgear.com> * Copyright (c) 2007 Secure Computing Corporation * Copyright (c) 2008 Patrick McHardy <kaber@trash.net> */ /** * @ingroup nfnl * @defgroup log Log * @brief * @{ */ #include <sys/types.h> #include <linux/netfilter/nfnetlink_log.h> #include <netlink-local.h> #include <netlink/attr.h> #include <netlink/netfilter/nfnl.h> #include <netlink/netfilter/log_msg.h> #if __BYTE_ORDER == __BIG_ENDIAN static uint64_t ntohll(uint64_t x) { return x; } #elif __BYTE_ORDER == __LITTLE_ENDIAN static uint64_t ntohll(uint64_t x) { return __bswap_64(x); } #endif static struct nla_policy log_msg_policy[NFULA_MAX+1] = { [NFULA_PACKET_HDR] = { .minlen = sizeof(struct nfulnl_msg_packet_hdr) }, [NFULA_MARK] = { .type = NLA_U32 }, [NFULA_TIMESTAMP] = { .minlen = sizeof(struct nfulnl_msg_packet_timestamp) }, [NFULA_IFINDEX_INDEV] = { .type = NLA_U32 }, [NFULA_IFINDEX_OUTDEV] = { .type = NLA_U32 }, [NFULA_IFINDEX_PHYSINDEV] = { .type = NLA_U32 }, [NFULA_IFINDEX_PHYSOUTDEV] = { .type = NLA_U32 }, [NFULA_HWADDR] = { .minlen = sizeof(struct nfulnl_msg_packet_hw) }, //[NFULA_PAYLOAD] [NFULA_PREFIX] = { .type = NLA_STRING, }, [NFULA_UID] = { .type = NLA_U32 }, [NFULA_GID] = { .type = NLA_U32 }, [NFULA_SEQ] = { .type = NLA_U32 }, [NFULA_SEQ_GLOBAL] = { .type = NLA_U32 }, }; int nfnlmsg_log_msg_parse(struct nlmsghdr *nlh, struct nfnl_log_msg **result) { struct nfnl_log_msg *msg; struct nlattr *tb[NFULA_MAX+1]; struct nlattr *attr; int err; msg = nfnl_log_msg_alloc(); if (!msg) return -NLE_NOMEM; msg->ce_msgtype = nlh->nlmsg_type; err = nlmsg_parse(nlh, sizeof(struct nfgenmsg), tb, NFULA_MAX, log_msg_policy); if (err < 0) goto errout; nfnl_log_msg_set_family(msg, nfnlmsg_family(nlh)); attr = tb[NFULA_PACKET_HDR]; if (attr) { struct nfulnl_msg_packet_hdr *hdr = nla_data(attr); if (hdr->hw_protocol) nfnl_log_msg_set_hwproto(msg, hdr->hw_protocol); nfnl_log_msg_set_hook(msg, hdr->hook); } attr = tb[NFULA_MARK]; if (attr) nfnl_log_msg_set_mark(msg, ntohl(nla_get_u32(attr))); attr = tb[NFULA_TIMESTAMP]; if (attr) { struct nfulnl_msg_packet_timestamp *timestamp = nla_data(attr); struct timeval tv; tv.tv_sec = ntohll(timestamp->sec); tv.tv_usec = ntohll(timestamp->usec); nfnl_log_msg_set_timestamp(msg, &tv); } attr = tb[NFULA_IFINDEX_INDEV]; if (attr) nfnl_log_msg_set_indev(msg, ntohl(nla_get_u32(attr))); attr = tb[NFULA_IFINDEX_OUTDEV]; if (attr) nfnl_log_msg_set_outdev(msg, ntohl(nla_get_u32(attr))); attr = tb[NFULA_IFINDEX_PHYSINDEV]; if (attr) nfnl_log_msg_set_physindev(msg, ntohl(nla_get_u32(attr))); attr = tb[NFULA_IFINDEX_PHYSOUTDEV]; if (attr) nfnl_log_msg_set_physoutdev(msg, ntohl(nla_get_u32(attr))); attr = tb[NFULA_HWADDR]; if (attr) { struct nfulnl_msg_packet_hw *hw = nla_data(attr); nfnl_log_msg_set_hwaddr(msg, hw->hw_addr, ntohs(hw->hw_addrlen)); } attr = tb[NFULA_PAYLOAD]; if (attr) { err = nfnl_log_msg_set_payload(msg, nla_data(attr), nla_len(attr)); if (err < 0) goto errout; } attr = tb[NFULA_PREFIX]; if (attr) { err = nfnl_log_msg_set_prefix(msg, nla_data(attr)); if (err < 0) goto errout; } attr = tb[NFULA_UID]; if (attr) nfnl_log_msg_set_uid(msg, ntohl(nla_get_u32(attr))); attr = tb[NFULA_GID]; if (attr) nfnl_log_msg_set_gid(msg, ntohl(nla_get_u32(attr))); attr = tb[NFULA_SEQ]; if (attr) nfnl_log_msg_set_seq(msg, ntohl(nla_get_u32(attr))); attr = tb[NFULA_SEQ_GLOBAL]; if (attr) nfnl_log_msg_set_seq_global(msg, ntohl(nla_get_u32(attr))); *result = msg; return 0; errout: nfnl_log_msg_put(msg); return err; } static int log_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who, struct nlmsghdr *nlh, struct nl_parser_param *pp) { struct nfnl_log_msg *msg; int err; if ((err = nfnlmsg_log_msg_parse(nlh, &msg)) < 0) goto errout; err = pp->pp_cb((struct nl_object *) msg, pp); errout: nfnl_log_msg_put(msg); return err; } /** @} */ #define NFNLMSG_LOG_TYPE(type) NFNLMSG_TYPE(NFNL_SUBSYS_ULOG, (type)) static struct nl_cache_ops nfnl_log_msg_ops = { .co_name = "netfilter/log_msg", .co_hdrsize = NFNL_HDRLEN, .co_msgtypes = { { NFNLMSG_LOG_TYPE(NFULNL_MSG_PACKET), NL_ACT_NEW, "new" }, END_OF_MSGTYPES_LIST, }, .co_protocol = NETLINK_NETFILTER, .co_msg_parser = log_msg_parser, .co_obj_ops = &log_msg_obj_ops, }; static void __init log_msg_init(void) { nl_cache_mngt_register(&nfnl_log_msg_ops); } static void __exit log_msg_exit(void) { nl_cache_mngt_unregister(&nfnl_log_msg_ops); } /** @} */
gpl-3.0
sbx320/mtasa-blue-old
vendor/bass_tags/src/tags/id3_genres.cpp
30
2219
////////////////////////////////////////////////////////////////////////// // // id3_genres.cpp - id3 genre table // // Author: Wraith, 2k5-2k6 // Public domain. No warranty. // // (internal) // #include "id3_genres.h" namespace { const char* g[] = { "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", "Psychedelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion", "Bebop", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock", "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo", "Acapella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass", "Club House", "Hardcore", "Terror", "Indie", "BritPop", "Black Punk", "Polsk Punk", "Beat", "Christian Gangsta", "Heavy Metal", "Black Metal", "Crossover", "Contemporary C", "Christian Rock", "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "SynthPop" }; } const size_t g_id3_genre_count = sizeof(g)/sizeof(g[0]); const char* const * const g_id3_genres = g;
gpl-3.0
jhonatajh/mtasa-blue
MTA10/mods/deathmatch/logic/rpc/CMarkerRPCs.cpp
31
5158
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: mods/deathmatch/logic/rpc/CMarkerRPCs.cpp * PURPOSE: Marker remote procedure calls * DEVELOPERS: Jax <> * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #include <StdInc.h> #include "CMarkerRPCs.h" void CMarkerRPCs::LoadFunctions ( void ) { AddHandler ( SET_MARKER_TYPE, SetMarkerType, "SetMarkerType" ); AddHandler ( SET_MARKER_COLOR, SetMarkerColor, "SetMarkerColor" ); AddHandler ( SET_MARKER_SIZE, SetMarkerSize, "SetMarkerSize" ); AddHandler ( SET_MARKER_TARGET, SetMarkerTarget, "SetMarkerTarget" ); AddHandler ( SET_MARKER_ICON, SetMarkerIcon, "SetMarkerIcon" ); } void CMarkerRPCs::SetMarkerType ( CClientEntity* pSource, NetBitStreamInterface& bitStream ) { // Read out the ID and the type unsigned char ucType; if ( bitStream.Read ( ucType ) ) { // Grab the marker CClientMarker* pMarker = m_pMarkerManager->Get ( pSource->GetID () ); if ( pMarker ) { // Set the new type pMarker->SetMarkerType ( static_cast < CClientMarker::eMarkerType > ( ucType ) ); } } } void CMarkerRPCs::SetMarkerColor ( CClientEntity* pSource, NetBitStreamInterface& bitStream ) { // Read out the ID and the color SColor color; if ( bitStream.Read ( color.B ) && bitStream.Read ( color.G ) && bitStream.Read ( color.R ) && bitStream.Read ( color.A ) ) { // Grab the marker CClientMarker* pMarker = m_pMarkerManager->Get ( pSource->GetID () ); if ( pMarker ) { // Set the new position pMarker->SetColor ( color ); } } } void CMarkerRPCs::SetMarkerSize ( CClientEntity* pSource, NetBitStreamInterface& bitStream ) { // Read out the ID and the color float fSize; if ( bitStream.Read ( fSize ) ) { // Grab the marker CClientMarker* pMarker = m_pMarkerManager->Get ( pSource->GetID () ); if ( pMarker ) { // Set the new position pMarker->SetSize ( fSize ); } } } void CMarkerRPCs::SetMarkerTarget ( CClientEntity* pSource, NetBitStreamInterface& bitStream ) { // Read out the marker id and if there's a new target unsigned char ucTemp; if ( bitStream.Read ( ucTemp ) ) { // Grab the marker CClientMarker* pMarker = m_pMarkerManager->Get ( pSource->GetID () ); if ( pMarker ) { // Grab the checkpoint marker from it CClientCheckpoint* pCheckpoint = pMarker->GetCheckpoint (); if ( pCheckpoint ) { // Handle this according to the temp char switch ( ucTemp ) { // No target? case 0: { pCheckpoint->SetIcon ( CClientCheckpoint::ICON_NONE ); pCheckpoint->SetDirection ( CVector ( 1.0f, 0.0f, 0.0f ) ); pCheckpoint->SetHasTarget ( false ); pCheckpoint->ReCreateWithSameIdentifier(); break; } // Position target? case 1: { // Read out the position CVector vecPosition; if ( bitStream.Read ( vecPosition.fX ) && bitStream.Read ( vecPosition.fY ) && bitStream.Read ( vecPosition.fZ ) ) { // Set the icon to arrow and the target position pCheckpoint->SetNextPosition ( vecPosition ); pCheckpoint->SetIcon ( CClientCheckpoint::ICON_ARROW ); pCheckpoint->SetHasTarget ( true ); pCheckpoint->SetTarget ( vecPosition ); pCheckpoint->ReCreateWithSameIdentifier(); } break; } } } } } } void CMarkerRPCs::SetMarkerIcon ( CClientEntity* pSource, NetBitStreamInterface& bitStream ) { // Read out the marker id and icon unsigned char ucIcon; if ( bitStream.Read ( ucIcon ) ) { // Grab the marker CClientMarker* pMarker = m_pMarkerManager->Get ( pSource->GetID () ); if ( pMarker ) { // Convert it to a checkpoint CClientCheckpoint* pCheckpoint = pMarker->GetCheckpoint (); if ( pCheckpoint ) { pCheckpoint->SetIcon ( static_cast < unsigned int > ( ucIcon ) ); } } } }
gpl-3.0
sathieu/samba
source3/torture/msgtest.c
33
4164
/* Unix SMB/CIFS implementation. Copyright (C) Andrew Tridgell 2000 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/>. */ /* test code for internal messaging */ #include "includes.h" #include "messages.h" static int pong_count; /**************************************************************************** a useful function for testing the message system ****************************************************************************/ static void pong_message(struct messaging_context *msg_ctx, void *private_data, uint32_t msg_type, struct server_id pid, DATA_BLOB *data) { pong_count++; } int main(int argc, char *argv[]) { struct tevent_context *evt_ctx; struct messaging_context *msg_ctx; pid_t pid; int i, n; char buf[12]; int ret; TALLOC_CTX *frame = talloc_stackframe(); smb_init_locale(); setup_logging(argv[0], DEBUG_STDOUT); lp_load_global(get_dyn_CONFIGFILE()); if (!(evt_ctx = samba_tevent_context_init(NULL)) || !(msg_ctx = messaging_init(NULL, evt_ctx))) { fprintf(stderr, "could not init messaging context\n"); TALLOC_FREE(frame); exit(1); } if (argc != 3) { fprintf(stderr, "%s: Usage - %s pid count\n", argv[0], argv[0]); TALLOC_FREE(frame); exit(1); } pid = atoi(argv[1]); n = atoi(argv[2]); messaging_register(msg_ctx, NULL, MSG_PONG, pong_message); for (i=0;i<n;i++) { messaging_send(msg_ctx, pid_to_procid(pid), MSG_PING, &data_blob_null); } while (pong_count < i) { ret = tevent_loop_once(evt_ctx); if (ret != 0) { break; } } /* Ensure all messages get through to ourselves. */ pong_count = 0; strlcpy(buf, "1234567890", sizeof(buf)); for (i=0;i<n;i++) { messaging_send(msg_ctx, messaging_server_id(msg_ctx), MSG_PING, &data_blob_null); messaging_send_buf(msg_ctx, messaging_server_id(msg_ctx), MSG_PING,(uint8_t *)buf, 11); } /* * We have to loop at least 2 times for * each message as local ping messages are * handled by an immediate callback, that * has to be dispatched, which sends a pong * message, which also has to be dispatched. * Above we sent 2*n messages, which means * we have to dispatch 4*n times. */ while (pong_count < n*2) { ret = tevent_loop_once(evt_ctx); if (ret != 0) { break; } } if (pong_count != 2*n) { fprintf(stderr, "Message count failed (%d).\n", pong_count); } /* Speed testing */ pong_count = 0; { struct timeval tv = timeval_current(); size_t timelimit = n; size_t ping_count = 0; printf("Sending pings for %d seconds\n", (int)timelimit); while (timeval_elapsed(&tv) < timelimit) { if(NT_STATUS_IS_OK(messaging_send_buf( msg_ctx, pid_to_procid(pid), MSG_PING, (uint8_t *)buf, 11))) ping_count++; if(NT_STATUS_IS_OK(messaging_send( msg_ctx, pid_to_procid(pid), MSG_PING, &data_blob_null))) ping_count++; while (ping_count > pong_count + 20) { ret = tevent_loop_once(evt_ctx); if (ret != 0) { break; } } } printf("waiting for %d remaining replies (done %d)\n", (int)(ping_count - pong_count), pong_count); while (timeval_elapsed(&tv) < 30 && pong_count < ping_count) { ret = tevent_loop_once(evt_ctx); if (ret != 0) { break; } } if (ping_count != pong_count) { fprintf(stderr, "ping test failed! received %d, sent " "%d\n", pong_count, (int)ping_count); } printf("ping rate of %.0f messages/sec\n", (ping_count+pong_count)/timeval_elapsed(&tv)); } TALLOC_FREE(frame); return (0); }
gpl-3.0
Open-Bionics/Open-Bionics.github.io
boards/openbionics-board-index/openbionics-samd-1.2.6/cores/arduino/Stream.cpp
34
8804
/* Stream.cpp - adds parsing methods to Stream class Copyright (c) 2008 David A. Mellis. All right reserved. 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 St, Fifth Floor, Boston, MA 02110-1301 USA Created July 2011 parsing functions based on TextFinder library by Michael Margolis findMulti/findUntil routines written by Jim Leonard/Xuth */ #include "Arduino.h" #include "Stream.h" #define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait // protected method to read stream with timeout int Stream::timedRead() { int c; _startMillis = millis(); do { c = read(); if (c >= 0) return c; } while(millis() - _startMillis < _timeout); return -1; // -1 indicates timeout } // protected method to peek stream with timeout int Stream::timedPeek() { int c; _startMillis = millis(); do { c = peek(); if (c >= 0) return c; } while(millis() - _startMillis < _timeout); return -1; // -1 indicates timeout } // returns peek of the next digit in the stream or -1 if timeout // discards non-numeric characters int Stream::peekNextDigit(LookaheadMode lookahead, bool detectDecimal) { int c; while (1) { c = timedPeek(); if( c < 0 || c == '-' || (c >= '0' && c <= '9') || (detectDecimal && c == '.')) return c; switch( lookahead ){ case SKIP_NONE: return -1; // Fail code. case SKIP_WHITESPACE: switch( c ){ case ' ': case '\t': case '\r': case '\n': break; default: return -1; // Fail code. } case SKIP_ALL: break; } read(); // discard non-numeric } } // Public Methods ////////////////////////////////////////////////////////////// void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait { _timeout = timeout; } // find returns true if the target string is found bool Stream::find(char *target) { return findUntil(target, strlen(target), NULL, 0); } // reads data from the stream until the target string of given length is found // returns true if target string is found, false if timed out bool Stream::find(char *target, size_t length) { return findUntil(target, length, NULL, 0); } // as find but search ends if the terminator string is found bool Stream::findUntil(char *target, char *terminator) { return findUntil(target, strlen(target), terminator, strlen(terminator)); } // reads data from the stream until the target string of the given length is found // search terminated if the terminator string is found // returns true if target string is found, false if terminated or timed out bool Stream::findUntil(char *target, size_t targetLen, char *terminator, size_t termLen) { if (terminator == NULL) { MultiTarget t[1] = {{target, targetLen, 0}}; return findMulti(t, 1) == 0 ? true : false; } else { MultiTarget t[2] = {{target, targetLen, 0}, {terminator, termLen, 0}}; return findMulti(t, 2) == 0 ? true : false; } } // returns the first valid (long) integer value from the current position. // lookahead determines how parseInt looks ahead in the stream. // See LookaheadMode enumeration at the top of the file. // Lookahead is terminated by the first character that is not a valid part of an integer. // Once parsing commences, 'ignore' will be skipped in the stream. long Stream::parseInt(LookaheadMode lookahead, char ignore) { bool isNegative = false; long value = 0; int c; c = peekNextDigit(lookahead, false); // ignore non numeric leading characters if(c < 0) return 0; // zero returned if timeout do{ if(c == ignore) ; // ignore this character else if(c == '-') isNegative = true; else if(c >= '0' && c <= '9') // is c a digit? value = value * 10 + c - '0'; read(); // consume the character we got with peek c = timedPeek(); } while( (c >= '0' && c <= '9') || c == ignore ); if(isNegative) value = -value; return value; } // as parseInt but returns a floating point value float Stream::parseFloat(LookaheadMode lookahead, char ignore) { bool isNegative = false; bool isFraction = false; long value = 0; int c; float fraction = 1.0; c = peekNextDigit(lookahead, true); // ignore non numeric leading characters if(c < 0) return 0; // zero returned if timeout do{ if(c == ignore) ; // ignore else if(c == '-') isNegative = true; else if (c == '.') isFraction = true; else if(c >= '0' && c <= '9') { // is c a digit? value = value * 10 + c - '0'; if(isFraction) fraction *= 0.1; } read(); // consume the character we got with peek c = timedPeek(); } while( (c >= '0' && c <= '9') || (c == '.' && !isFraction) || c == ignore ); if(isNegative) value = -value; if(isFraction) return value * fraction; else return value; } // read characters from stream into buffer // terminates if length characters have been read, or timeout (see setTimeout) // returns the number of characters placed in the buffer // the buffer is NOT null terminated. // size_t Stream::readBytes(char *buffer, size_t length) { size_t count = 0; while (count < length) { int c = timedRead(); if (c < 0) break; *buffer++ = (char)c; count++; } return count; } // as readBytes with terminator character // terminates if length characters have been read, timeout, or if the terminator character detected // returns the number of characters placed in the buffer (0 means no valid data found) size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length) { if (length < 1) return 0; size_t index = 0; while (index < length) { int c = timedRead(); if (c < 0 || c == terminator) break; *buffer++ = (char)c; index++; } return index; // return number of characters, not including null terminator } String Stream::readString() { String ret; int c = timedRead(); while (c >= 0) { ret += (char)c; c = timedRead(); } return ret; } String Stream::readStringUntil(char terminator) { String ret; int c = timedRead(); while (c >= 0 && c != terminator) { ret += (char)c; c = timedRead(); } return ret; } int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) { // any zero length target string automatically matches and would make // a mess of the rest of the algorithm. for (struct MultiTarget *t = targets; t < targets+tCount; ++t) { if (t->len <= 0) return t - targets; } while (1) { int c = timedRead(); if (c < 0) return -1; for (struct MultiTarget *t = targets; t < targets+tCount; ++t) { // the simple case is if we match, deal with that first. if (c == t->str[t->index]) { if (++t->index == t->len) return t - targets; else continue; } // if not we need to walk back and see if we could have matched further // down the stream (ie '1112' doesn't match the first position in '11112' // but it will match the second position so we can't just reset the current // index to 0 when we find a mismatch. if (t->index == 0) continue; int origIndex = t->index; do { --t->index; // first check if current char works against the new current index if (c != t->str[t->index]) continue; // if it's the only char then we're good, nothing more to check if (t->index == 0) { t->index++; break; } // otherwise we need to check the rest of the found string int diff = origIndex - t->index; size_t i; for (i = 0; i < t->index; ++i) { if (t->str[i] != t->str[i + diff]) break; } // if we successfully got through the previous loop then our current // index is good. if (i == t->index) { t->index++; break; } // otherwise we just try the next index } while (t->index); } } // unreachable return -1; }
gpl-3.0
uwafsl/ardupilot
libraries/GCS_MAVLink/examples/routing/routing.cpp
37
3019
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- // // Simple test for the GCS_MAVLink routing // #include <AP_HAL/AP_HAL.h> #include <GCS_MAVLink/GCS.h> #include <GCS_MAVLink/GCS_MAVLink.h> const AP_HAL::HAL& hal = AP_HAL::get_HAL(); static const uint8_t num_gcs = MAVLINK_COMM_NUM_BUFFERS; static GCS_MAVLINK gcs[MAVLINK_COMM_NUM_BUFFERS]; extern mavlink_system_t mavlink_system; const AP_Param::GroupInfo GCS_MAVLINK::var_info[] = { AP_GROUPEND }; static MAVLink_routing routing; void setup(void) { hal.console->println("routing test startup..."); gcs[0].init(hal.uartA, MAVLINK_COMM_0); } void loop(void) { uint16_t err_count = 0; // incoming heartbeat mavlink_message_t msg; mavlink_heartbeat_t heartbeat = {0}; mavlink_msg_heartbeat_encode(3, 1, &msg, &heartbeat); if (!routing.check_and_forward(MAVLINK_COMM_0, &msg)) { hal.console->printf("heartbeat should be processed locally\n"); err_count++; } // incoming non-targetted message mavlink_attitude_t attitude = {0}; mavlink_msg_attitude_encode(3, 1, &msg, &attitude); if (!routing.check_and_forward(MAVLINK_COMM_0, &msg)) { hal.console->printf("attitude should be processed locally\n"); err_count++; } // incoming targetted message for someone else mavlink_param_set_t param_set = {0}; param_set.target_system = mavlink_system.sysid+1; param_set.target_component = mavlink_system.compid; mavlink_msg_param_set_encode(3, 1, &msg, &param_set); if (routing.check_and_forward(MAVLINK_COMM_0, &msg)) { hal.console->printf("param set 1 should not be processed locally\n"); err_count++; } // incoming targetted message for us param_set.target_system = mavlink_system.sysid; param_set.target_component = mavlink_system.compid; mavlink_msg_param_set_encode(3, 1, &msg, &param_set); if (!routing.check_and_forward(MAVLINK_COMM_0, &msg)) { hal.console->printf("param set 2 should be processed locally\n"); err_count++; } // incoming targetted message for our system, but other compid // should be processed locally param_set.target_system = mavlink_system.sysid; param_set.target_component = mavlink_system.compid+1; mavlink_msg_param_set_encode(3, 1, &msg, &param_set); if (!routing.check_and_forward(MAVLINK_COMM_0, &msg)) { hal.console->printf("param set 3 should be processed locally\n"); err_count++; } // incoming broadcast message should be processed locally param_set.target_system = 0; param_set.target_component = mavlink_system.compid+1; mavlink_msg_param_set_encode(3, 1, &msg, &param_set); if (!routing.check_and_forward(MAVLINK_COMM_0, &msg)) { hal.console->printf("param set 4 should be processed locally\n"); err_count++; } if (err_count == 0) { hal.console->printf("All OK\n"); } hal.scheduler->delay(1000); } AP_HAL_MAIN();
gpl-3.0
gwq5210/litlib
thirdparty/sources/boost_1_60_0/libs/geometry/doc/src/examples/algorithms/union.cpp
37
1614
// Boost.Geometry (aka GGL, Generic Geometry Library) // QuickBook Example // Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //[union //` Shows how to get a united geometry of two polygons #include <iostream> #include <vector> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/foreach.hpp> /*<-*/ #include "create_svg_overlay.hpp" /*->*/ int main() { typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon; polygon green, blue; boost::geometry::read_wkt( "POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)" "(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))", green); boost::geometry::read_wkt( "POLYGON((4.0 -0.5 , 3.5 1.0 , 2.0 1.5 , 3.5 2.0 , 4.0 3.5 , 4.5 2.0 , 6.0 1.5 , 4.5 1.0 , 4.0 -0.5))", blue); std::vector<polygon> output; boost::geometry::union_(green, blue, output); int i = 0; std::cout << "green || blue:" << std::endl; BOOST_FOREACH(polygon const& p, output) { std::cout << i++ << ": " << boost::geometry::area(p) << std::endl; } /*<-*/ create_svg("union.svg", green, blue, output); /*->*/ return 0; } //] //[union_output /*` Output: [pre green || blue: 0: 5.64795 [$img/algorithms/union.png] ] */ //]
gpl-3.0
ezibyte/EziSocial-3x-Silver-Bullet
examples/Cocos2dx/3.x/HelloWorld-Cocos2dx/cocos2d/extensions/GUI/CCEditBox/CCEditBoxImplWin.cpp
38
8480
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013 Jozef Pridavok http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCEditBoxImplWin.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #ifndef GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WIN32 #endif #ifndef GLFW_EXPOSE_NATIVE_WGL #define GLFW_EXPOSE_NATIVE_WGL #endif #include "CCEditBox.h" #include "proj.win32/Win32InputBox.h" #include "glfw3native.h" NS_CC_EXT_BEGIN EditBoxImpl* __createSystemEditBox(EditBox* pEditBox) { return new EditBoxImplWin(pEditBox); } EditBoxImplWin::EditBoxImplWin(EditBox* pEditText) : EditBoxImpl(pEditText) , _label(nullptr) , _labelPlaceHolder(nullptr) , _editBoxInputMode(EditBox::InputMode::SINGLE_LINE) , _editBoxInputFlag(EditBox::InputFlag::INTIAL_CAPS_ALL_CHARACTERS) , _keyboardReturnType(EditBox::KeyboardReturnType::DEFAULT) , _colText(Color3B::WHITE) , _colPlaceHolder(Color3B::GRAY) , _maxLength(-1) { } EditBoxImplWin::~EditBoxImplWin() { } void EditBoxImplWin::doAnimationWhenKeyboardMove(float duration, float distance) { } bool EditBoxImplWin::initWithSize(const Size& size) { //! int fontSize = getFontSizeAccordingHeightJni(size.height-12); _label = Label::create(); _label->setSystemFontSize(size.height-12); // align the text vertically center _label->setAnchorPoint(Vec2(0, 0.5f)); _label->setPosition(Vec2(5, size.height / 2.0f)); _label->setColor(_colText); _editBox->addChild(_label); _labelPlaceHolder = Label::create(); _labelPlaceHolder->setSystemFontSize(size.height-12); // align the text vertically center _labelPlaceHolder->setAnchorPoint(Vec2(0, 0.5f)); _labelPlaceHolder->setPosition(Vec2(5, size.height / 2.0f)); _labelPlaceHolder->setVisible(false); _labelPlaceHolder->setColor(_colPlaceHolder); _editBox->addChild(_labelPlaceHolder); _editSize = size; return true; } void EditBoxImplWin::setFont(const char* pFontName, int fontSize) { if(_label != nullptr) { _label->setSystemFontName(pFontName); _label->setSystemFontSize(fontSize); } if(_labelPlaceHolder != nullptr) { _labelPlaceHolder->setSystemFontName(pFontName); _labelPlaceHolder->setSystemFontSize(fontSize); } } void EditBoxImplWin::setFontColor(const Color3B& color) { _colText = color; _label->setColor(color); } void EditBoxImplWin::setPlaceholderFont(const char* pFontName, int fontSize) { if(_labelPlaceHolder != nullptr) { _labelPlaceHolder->setSystemFontName(pFontName); _labelPlaceHolder->setSystemFontSize(fontSize); } } void EditBoxImplWin::setPlaceholderFontColor(const Color3B& color) { _colPlaceHolder = color; _labelPlaceHolder->setColor(color); } void EditBoxImplWin::setInputMode(EditBox::InputMode inputMode) { _editBoxInputMode = inputMode; } void EditBoxImplWin::setMaxLength(int maxLength) { _maxLength = maxLength; } int EditBoxImplWin::getMaxLength() { return _maxLength; } void EditBoxImplWin::setInputFlag(EditBox::InputFlag inputFlag) { _editBoxInputFlag = inputFlag; } void EditBoxImplWin::setReturnType(EditBox::KeyboardReturnType returnType) { _keyboardReturnType = returnType; } bool EditBoxImplWin::isEditing() { return false; } void EditBoxImplWin::setText(const char* pText) { if (pText != nullptr) { _text = pText; if (_text.length() > 0) { _labelPlaceHolder->setVisible(false); std::string strToShow; if (EditBox::InputFlag::PASSWORD == _editBoxInputFlag) { long length = cc_utf8_strlen(_text.c_str(), -1); for (long i = 0; i < length; i++) { strToShow.append("*"); } } else { strToShow = _text; } //! std::string strWithEllipsis = getStringWithEllipsisJni(strToShow.c_str(), _editSize.width, _editSize.height-12); //! _label->setString(strWithEllipsis.c_str()); _label->setString(strToShow.c_str()); } else { _labelPlaceHolder->setVisible(true); _label->setString(""); } } } const char* EditBoxImplWin::getText(void) { return _text.c_str(); } void EditBoxImplWin::setPlaceHolder(const char* pText) { if (pText != nullptr) { _placeHolder = pText; if (_placeHolder.length() > 0 && _text.length() == 0) { _labelPlaceHolder->setVisible(true); } _labelPlaceHolder->setString(_placeHolder.c_str()); } } void EditBoxImplWin::setPosition(const Vec2& pos) { //_label->setPosition(pos); //_labelPlaceHolder->setPosition(pos); } void EditBoxImplWin::setVisible(bool visible) { // don't need to be implemented on win32 platform. } void EditBoxImplWin::setContentSize(const Size& size) { } void EditBoxImplWin::setAnchorPoint(const Vec2& anchorPoint) { // don't need to be implemented on win32 platform. } void EditBoxImplWin::visit(void) { } void EditBoxImplWin::openKeyboard() { if (_delegate != nullptr) { _delegate->editBoxEditingDidBegin(_editBox); } EditBox* pEditBox = this->getEditBox(); if (nullptr != pEditBox && 0 != pEditBox->getScriptEditBoxHandler()) { CommonScriptData data(pEditBox->getScriptEditBoxHandler(), "began",pEditBox); ScriptEvent event(kCommonEvent,(void*)&data); ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); } std::string placeHolder = _labelPlaceHolder->getString(); if (placeHolder.length() == 0) placeHolder = "Enter value"; char pText[100]= {0}; std::string text = getText(); if (text.length()) strncpy(pText, text.c_str(), 100); GLView *glView = Director::getInstance()->getOpenGLView(); GLFWwindow *glfwWindow = glView->getWindow(); HWND hwnd = glfwGetWin32Window(glfwWindow); bool didChange = CWin32InputBox::InputBox("Input", placeHolder.c_str(), pText, 100, false, hwnd) == IDOK; if (didChange) setText(pText); if (_delegate != nullptr) { if (didChange) _delegate->editBoxTextChanged(_editBox, getText()); _delegate->editBoxEditingDidEnd(_editBox); _delegate->editBoxReturn(_editBox); } #if CC_ENABLE_SCRIPT_BINDING if (nullptr != _editBox && 0 != _editBox->getScriptEditBoxHandler()) { CommonScriptData data(_editBox->getScriptEditBoxHandler(), "changed",_editBox); ScriptEvent event(kCommonEvent,(void*)&data); if (didChange) { ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); } memset(data.eventName,0,sizeof(data.eventName)); strncpy(data.eventName,"ended",sizeof(data.eventName)); event.data = (void*)&data; ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); memset(data.eventName,0,sizeof(data.eventName)); strncpy(data.eventName,"return",sizeof(data.eventName)); event.data = (void*)&data; ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); } #endif // #if CC_ENABLE_SCRIPT_BINDING } void EditBoxImplWin::closeKeyboard() { } void EditBoxImplWin::onEnter(void) { } NS_CC_EXT_END #endif /* (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) */
gpl-3.0
SpectraLogic/samba
lib/compression/testsuite.c
40
2515
/* Unix SMB/CIFS implementation. test suite for the compression functions Copyright (C) Jelmer Vernooij 2007 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 "includes.h" #include "torture/torture.h" #include "torture/local/proto.h" #include "talloc.h" #include "lzxpress.h" /* test lzxpress */ static bool test_lzxpress(struct torture_context *test) { TALLOC_CTX *tmp_ctx = talloc_new(test); const char *fixed_data = "this is a test. and this is a test too"; const uint8_t fixed_out[] = { 0x00, 0x20, 0x00, 0x04, 0x74, 0x68, 0x69, 0x73, 0x20, 0x10, 0x00, 0x61, 0x20, 0x74, 0x65, 0x73, 0x74, 0x2E, 0x20, 0x61, 0x6E, 0x64, 0x20, 0x9F, 0x00, 0x04, 0x20, 0x74, 0x6F, 0x6F, 0x00, 0x00, 0x00, 0x00 }; ssize_t c_size; uint8_t *out, *out2; out = talloc_size(tmp_ctx, 2048); memset(out, 0x42, talloc_get_size(out)); torture_comment(test, "lzxpress fixed compression\n"); c_size = lzxpress_compress((const uint8_t *)fixed_data, strlen(fixed_data), out, talloc_get_size(out)); torture_assert_int_equal(test, c_size, sizeof(fixed_out), "fixed lzxpress_compress size"); torture_assert_mem_equal(test, out, fixed_out, c_size, "fixed lzxpress_compress data"); torture_comment(test, "lzxpress fixed decompression\n"); out2 = talloc_size(tmp_ctx, strlen(fixed_data)); c_size = lzxpress_decompress(out, sizeof(fixed_out), out2, talloc_get_size(out2)); torture_assert_int_equal(test, c_size, strlen(fixed_data), "fixed lzxpress_decompress size"); torture_assert_mem_equal(test, out2, fixed_data, c_size, "fixed lzxpress_decompress data"); return true; } struct torture_suite *torture_local_compression(TALLOC_CTX *mem_ctx) { struct torture_suite *suite = torture_suite_create(mem_ctx, "compression"); torture_suite_add_simple_test(suite, "lzxpress", test_lzxpress); return suite; }
gpl-3.0
multitheftauto/multitheftauto-archived
vendor/cegui-0.4.0-custom/src/elements/CEGUICheckbox.cpp
41
4618
/************************************************************************ filename: CEGUICheckbox.cpp created: 13/4/2004 author: Paul D Turner purpose: Implementation of Checkbox base class *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "StdInc.h" #include "elements/CEGUICheckbox.h" // Start of CEGUI namespace section namespace CEGUI { const String Checkbox::EventNamespace("Checkbox"); /************************************************************************* Definitions for Properties *************************************************************************/ CheckboxProperties::Selected Checkbox::d_selectedProperty; /************************************************************************* Event name constants *************************************************************************/ // generated internally by Window const String Checkbox::EventCheckStateChanged( (utf8*)"CheckStateChanged" ); /************************************************************************* Constructor *************************************************************************/ Checkbox::Checkbox(const String& type, const String& name) : ButtonBase(type, name), d_selected(false) { // add events for this widget addCheckboxEvents(); addCheckboxProperties(); } /************************************************************************* Destructor *************************************************************************/ Checkbox::~Checkbox(void) { } /************************************************************************* set whether the check-box is selected or not *************************************************************************/ void Checkbox::setSelected(bool select) { if (select != d_selected) { d_selected = select; requestRedraw(); WindowEventArgs args(this); onSelectStateChange(args); } } /************************************************************************* event triggered internally when state of check-box changes *************************************************************************/ void Checkbox::onSelectStateChange(WindowEventArgs& e) { fireEvent(EventCheckStateChanged, e, EventNamespace); } /************************************************************************* Handler for mouse button up events *************************************************************************/ void Checkbox::onMouseButtonUp(MouseEventArgs& e) { if ((e.button == LeftButton) && isPushed()) { Window* sheet = System::getSingleton().getGUISheet(); if (sheet != NULL) { // if mouse was released over this widget if (this == sheet->getChildAtPosition(e.position)) { // toggle selected state setSelected(d_selected ^ true); } } e.handled = true; } // default handling ButtonBase::onMouseButtonUp(e); } /************************************************************************* Add check-box specific events *************************************************************************/ void Checkbox::addCheckboxEvents(bool bCommon) { if ( bCommon == true ) addEvent(EventCheckStateChanged); } /************************************************************************* Add properties *************************************************************************/ void Checkbox::addCheckboxProperties( bool bCommon ) { if ( bCommon == false ) addProperty(&d_selectedProperty); } } // End of CEGUI namespace section
gpl-3.0
tectronics/multitheftauto
vendor/ehs/staticssllocking.cpp
41
2477
/* 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 #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef COMPILE_WITH_SSL #include "staticssllocking.h" // deal with static variables MUTEX_TYPE * StaticSslLocking::poMutexes; void StaticSslLocking::SslStaticLockCallback ( int inMode, int inMutex, const char * ipsFile, int inLine ) { if ( inMode & CRYPTO_LOCK ) { MUTEX_LOCK ( StaticSslLocking::poMutexes [ inMutex ] ); } else { MUTEX_UNLOCK ( StaticSslLocking::poMutexes [ inMutex ] ); } } unsigned long StaticSslLocking::SslThreadIdCallback ( ) { return ( (unsigned long) THREAD_ID ); } StaticSslLocking::StaticSslLocking ( ) { // allocate the needed number of locks StaticSslLocking::poMutexes = new MUTEX_TYPE [ CRYPTO_num_locks ( ) ]; assert ( StaticSslLocking::poMutexes != NULL ); // initialize the mutexes for ( int i = 0; i < CRYPTO_num_locks ( ); i++ ) { MUTEX_SETUP ( StaticSslLocking::poMutexes [ i ] ); } // set callbacks CRYPTO_set_id_callback ( StaticSslLocking::SslThreadIdCallback ); CRYPTO_set_locking_callback ( StaticSslLocking::SslStaticLockCallback ); } StaticSslLocking::~StaticSslLocking ( ) { assert ( StaticSslLocking::poMutexes != NULL ); CRYPTO_set_id_callback ( NULL ); CRYPTO_set_locking_callback ( NULL ); for ( int i = 0; i < CRYPTO_num_locks ( ); i++ ) { MUTEX_CLEANUP ( StaticSslLocking::poMutexes [ i ] ); } delete [] StaticSslLocking::poMutexes; StaticSslLocking::poMutexes = NULL; } #endif // COMPILE_WITH_SSL
gpl-3.0
Fusl/cjdns
node_build/dependencies/libuv/test/test-tcp-try-write.c
42
3801
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 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 "uv.h" #include "task.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_BYTES 1024 * 1024 #ifdef _WIN32 TEST_IMPL(tcp_try_write) { MAKE_VALGRIND_HAPPY(); return 0; } #else /* !_WIN32 */ static uv_tcp_t server; static uv_tcp_t client; static uv_tcp_t incoming; static int connect_cb_called; static int close_cb_called; static int connection_cb_called; static int bytes_read; static int bytes_written; static void close_cb(uv_handle_t* handle) { close_cb_called++; } static void connect_cb(uv_connect_t* req, int status) { static char zeroes[1024]; int r; uv_buf_t buf; ASSERT(status == 0); connect_cb_called++; do { buf = uv_buf_init(zeroes, sizeof(zeroes)); r = uv_try_write((uv_stream_t*) &client, &buf, 1); ASSERT(r >= 0); bytes_written += r; /* Partial write */ if (r != (int) sizeof(zeroes)) break; } while (1); uv_close((uv_handle_t*) &client, close_cb); } static void alloc_cb(uv_handle_t* handle, size_t size, uv_buf_t* buf) { static char base[1024]; buf->base = base; buf->len = sizeof(base); } static void read_cb(uv_stream_t* tcp, ssize_t nread, const uv_buf_t* buf) { if (nread < 0) { uv_close((uv_handle_t*) tcp, close_cb); uv_close((uv_handle_t*) &server, close_cb); return; } bytes_read += nread; } static void connection_cb(uv_stream_t* tcp, int status) { ASSERT(status == 0); ASSERT(0 == uv_tcp_init(tcp->loop, &incoming)); ASSERT(0 == uv_accept(tcp, (uv_stream_t*) &incoming)); connection_cb_called++; ASSERT(0 == uv_read_start((uv_stream_t*) &incoming, alloc_cb, read_cb)); } static void start_server(void) { struct sockaddr_in addr; ASSERT(0 == uv_ip4_addr("0.0.0.0", TEST_PORT, &addr)); ASSERT(0 == uv_tcp_init(uv_default_loop(), &server)); ASSERT(0 == uv_tcp_bind(&server, (struct sockaddr*) &addr, 0)); ASSERT(0 == uv_listen((uv_stream_t*) &server, 128, connection_cb)); } TEST_IMPL(tcp_try_write) { uv_connect_t connect_req; struct sockaddr_in addr; start_server(); ASSERT(0 == uv_ip4_addr("127.0.0.1", TEST_PORT, &addr)); ASSERT(0 == uv_tcp_init(uv_default_loop(), &client)); ASSERT(0 == uv_tcp_connect(&connect_req, &client, (struct sockaddr*) &addr, connect_cb)); ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT)); ASSERT(connect_cb_called == 1); ASSERT(close_cb_called == 3); ASSERT(connection_cb_called == 1); ASSERT(bytes_read == bytes_written); ASSERT(bytes_written > 0); MAKE_VALGRIND_HAPPY(); return 0; } #endif /* !_WIN32 */
gpl-3.0
sathieu/samba
source4/ntvfs/posix/xattr_system.c
46
3385
/* Unix SMB/CIFS implementation. POSIX NTVFS backend - xattr support using filesystem xattrs Copyright (C) Andrew Tridgell 2004 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 "includes.h" #include "vfs_posix.h" /* pull a xattr as a blob, from either a file or a file descriptor */ NTSTATUS pull_xattr_blob_system(struct pvfs_state *pvfs, TALLOC_CTX *mem_ctx, const char *attr_name, const char *fname, int fd, size_t estimated_size, DATA_BLOB *blob) { int ret; *blob = data_blob_talloc(mem_ctx, NULL, estimated_size+16); if (blob->data == NULL) { return NT_STATUS_NO_MEMORY; } again: if (fd != -1) { ret = fgetxattr(fd, attr_name, blob->data, estimated_size); } else { ret = getxattr(fname, attr_name, blob->data, estimated_size); } if (ret == -1 && errno == ERANGE) { estimated_size *= 2; blob->data = talloc_realloc(mem_ctx, blob->data, uint8_t, estimated_size); if (blob->data == NULL) { return NT_STATUS_NO_MEMORY; } blob->length = estimated_size; goto again; } if (ret == -1 && errno == EPERM) { struct stat statbuf; if (fd != -1) { ret = fstat(fd, &statbuf); } else { ret = stat(fname, &statbuf); } if (ret == 0) { /* check if this is a directory and the sticky bit is set */ if (S_ISDIR(statbuf.st_mode) && (statbuf.st_mode & S_ISVTX)) { /* pretend we could not find the xattr */ data_blob_free(blob); return NT_STATUS_NOT_FOUND; } else { /* if not this was probably a legitimate error * reset ret and errno to the correct values */ errno = EPERM; ret = -1; } } } if (ret == -1) { data_blob_free(blob); return pvfs_map_errno(pvfs, errno); } blob->length = ret; return NT_STATUS_OK; } /* push a xattr as a blob, from either a file or a file descriptor */ NTSTATUS push_xattr_blob_system(struct pvfs_state *pvfs, const char *attr_name, const char *fname, int fd, const DATA_BLOB *blob) { int ret; if (fd != -1) { ret = fsetxattr(fd, attr_name, blob->data, blob->length, 0); } else { ret = setxattr(fname, attr_name, blob->data, blob->length, 0); } if (ret == -1) { return pvfs_map_errno(pvfs, errno); } return NT_STATUS_OK; } /* delete a xattr */ NTSTATUS delete_xattr_system(struct pvfs_state *pvfs, const char *attr_name, const char *fname, int fd) { int ret; if (fd != -1) { ret = fremovexattr(fd, attr_name); } else { ret = removexattr(fname, attr_name); } if (ret == -1) { return pvfs_map_errno(pvfs, errno); } return NT_STATUS_OK; } /* unlink a file - cleanup any xattrs */ NTSTATUS unlink_xattr_system(struct pvfs_state *pvfs, const char *fname) { /* nothing needs to be done for filesystem based xattrs */ return NT_STATUS_OK; }
gpl-3.0
wcs1only/libzmq
tests/test_spec_rep.cpp
46
5179
/* Copyright (c) 2007-2015 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq 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 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "testutil.hpp" const char *bind_address = 0; const char *connect_address = 0; void test_fair_queue_in (void *ctx) { void *rep = zmq_socket (ctx, ZMQ_REP); assert (rep); int timeout = 250; int rc = zmq_setsockopt (rep, ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); rc = zmq_bind (rep, bind_address); assert (rc == 0); const size_t services = 5; void *reqs [services]; for (size_t peer = 0; peer < services; ++peer) { reqs [peer] = zmq_socket (ctx, ZMQ_REQ); assert (reqs [peer]); rc = zmq_setsockopt (reqs [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); rc = zmq_connect (reqs [peer], connect_address); assert (rc == 0); } s_send_seq (reqs [0], "A", SEQ_END); s_recv_seq (rep, "A", SEQ_END); s_send_seq (rep, "A", SEQ_END); s_recv_seq (reqs [0], "A", SEQ_END); s_send_seq (reqs [0], "A", SEQ_END); s_recv_seq (rep, "A", SEQ_END); s_send_seq (rep, "A", SEQ_END); s_recv_seq (reqs [0], "A", SEQ_END); // TODO: following test fails randomly on some boxes #ifdef SOMEONE_FIXES_THIS // send N requests for (size_t peer = 0; peer < services; ++peer) { char * str = strdup("A"); str [0] += peer; s_send_seq (reqs [peer], str, SEQ_END); free (str); } // handle N requests for (size_t peer = 0; peer < services; ++peer) { char * str = strdup("A"); str [0] += peer; // Test fails here s_recv_seq (rep, str, SEQ_END); s_send_seq (rep, str, SEQ_END); s_recv_seq (reqs [peer], str, SEQ_END); free (str); } #endif close_zero_linger (rep); for (size_t peer = 0; peer < services; ++peer) close_zero_linger (reqs [peer]); // Wait for disconnects. rc = zmq_poll (0, 0, 100); assert (rc == 0); } void test_envelope (void *ctx) { void *rep = zmq_socket (ctx, ZMQ_REP); assert (rep); int rc = zmq_bind (rep, bind_address); assert (rc == 0); void *dealer = zmq_socket (ctx, ZMQ_DEALER); assert (dealer); rc = zmq_connect (dealer, connect_address); assert (rc == 0); // minimal envelope s_send_seq (dealer, 0, "A", SEQ_END); s_recv_seq (rep, "A", SEQ_END); s_send_seq (rep, "A", SEQ_END); s_recv_seq (dealer, 0, "A", SEQ_END); // big envelope s_send_seq (dealer, "X", "Y", 0, "A", SEQ_END); s_recv_seq (rep, "A", SEQ_END); s_send_seq (rep, "A", SEQ_END); s_recv_seq (dealer, "X", "Y", 0, "A", SEQ_END); close_zero_linger (rep); close_zero_linger (dealer); // Wait for disconnects. rc = zmq_poll (0, 0, 100); assert (rc == 0); } int main (void) { setup_test_environment(); void *ctx = zmq_ctx_new (); assert (ctx); const char *binds [] = { "inproc://a", "tcp://127.0.0.1:5555" }; const char *connects [] = { "inproc://a", "tcp://localhost:5555" }; for (int transport = 0; transport < 2; ++transport) { bind_address = binds [transport]; connect_address = connects [transport]; // SHALL receive incoming messages from its peers using a fair-queuing // strategy. test_fair_queue_in (ctx); // For an incoming message: // SHALL remove and store the address envelope, including the delimiter. // SHALL pass the remaining data frames to its calling application. // SHALL wait for a single reply message from its calling application. // SHALL prepend the address envelope and delimiter. // SHALL deliver this message back to the originating peer. test_envelope (ctx); } int rc = zmq_ctx_term (ctx); assert (rc == 0); return 0 ; }
gpl-3.0
daodewang/DECAF
DroidScope/qemu/qjson.c
307
7454
/* * QObject JSON integration * * Copyright IBM, Corp. 2009 * * Authors: * Anthony Liguori <aliguori@us.ibm.com> * * This work is licensed under the terms of the GNU LGPL, version 2.1 or later. * See the COPYING.LIB file in the top-level directory. * */ #include "json-lexer.h" #include "json-parser.h" #include "json-streamer.h" #include "qjson.h" #include "qint.h" #include "qlist.h" #include "qbool.h" #include "qfloat.h" #include "qdict.h" typedef struct JSONParsingState { JSONMessageParser parser; va_list *ap; QObject *result; } JSONParsingState; static void parse_json(JSONMessageParser *parser, QList *tokens) { JSONParsingState *s = container_of(parser, JSONParsingState, parser); s->result = json_parser_parse(tokens, s->ap); } QObject *qobject_from_jsonv(const char *string, va_list *ap) { JSONParsingState state = {}; state.ap = ap; json_message_parser_init(&state.parser, parse_json); json_message_parser_feed(&state.parser, string, strlen(string)); json_message_parser_flush(&state.parser); json_message_parser_destroy(&state.parser); return state.result; } QObject *qobject_from_json(const char *string) { return qobject_from_jsonv(string, NULL); } /* * IMPORTANT: This function aborts on error, thus it must not * be used with untrusted arguments. */ QObject *qobject_from_jsonf(const char *string, ...) { QObject *obj; va_list ap; va_start(ap, string); obj = qobject_from_jsonv(string, &ap); va_end(ap); assert(obj != NULL); return obj; } typedef struct ToJsonIterState { int indent; int pretty; int count; QString *str; } ToJsonIterState; static void to_json(const QObject *obj, QString *str, int pretty, int indent); static void to_json_dict_iter(const char *key, QObject *obj, void *opaque) { ToJsonIterState *s = opaque; QString *qkey; int j; if (s->count) qstring_append(s->str, ", "); if (s->pretty) { qstring_append(s->str, "\n"); for (j = 0 ; j < s->indent ; j++) qstring_append(s->str, " "); } qkey = qstring_from_str(key); to_json(QOBJECT(qkey), s->str, s->pretty, s->indent); QDECREF(qkey); qstring_append(s->str, ": "); to_json(obj, s->str, s->pretty, s->indent); s->count++; } static void to_json_list_iter(QObject *obj, void *opaque) { ToJsonIterState *s = opaque; int j; if (s->count) qstring_append(s->str, ", "); if (s->pretty) { qstring_append(s->str, "\n"); for (j = 0 ; j < s->indent ; j++) qstring_append(s->str, " "); } to_json(obj, s->str, s->pretty, s->indent); s->count++; } static void to_json(const QObject *obj, QString *str, int pretty, int indent) { switch (qobject_type(obj)) { case QTYPE_QINT: { QInt *val = qobject_to_qint(obj); char buffer[1024]; snprintf(buffer, sizeof(buffer), "%" PRId64, qint_get_int(val)); qstring_append(str, buffer); break; } case QTYPE_QSTRING: { QString *val = qobject_to_qstring(obj); const char *ptr; ptr = qstring_get_str(val); qstring_append(str, "\""); while (*ptr) { if ((ptr[0] & 0xE0) == 0xE0 && (ptr[1] & 0x80) && (ptr[2] & 0x80)) { uint16_t wchar; char escape[7]; wchar = (ptr[0] & 0x0F) << 12; wchar |= (ptr[1] & 0x3F) << 6; wchar |= (ptr[2] & 0x3F); ptr += 2; snprintf(escape, sizeof(escape), "\\u%04X", wchar); qstring_append(str, escape); } else if ((ptr[0] & 0xE0) == 0xC0 && (ptr[1] & 0x80)) { uint16_t wchar; char escape[7]; wchar = (ptr[0] & 0x1F) << 6; wchar |= (ptr[1] & 0x3F); ptr++; snprintf(escape, sizeof(escape), "\\u%04X", wchar); qstring_append(str, escape); } else switch (ptr[0]) { case '\"': qstring_append(str, "\\\""); break; case '\\': qstring_append(str, "\\\\"); break; case '\b': qstring_append(str, "\\b"); break; case '\f': qstring_append(str, "\\f"); break; case '\n': qstring_append(str, "\\n"); break; case '\r': qstring_append(str, "\\r"); break; case '\t': qstring_append(str, "\\t"); break; default: { if (ptr[0] <= 0x1F) { char escape[7]; snprintf(escape, sizeof(escape), "\\u%04X", ptr[0]); qstring_append(str, escape); } else { char buf[2] = { ptr[0], 0 }; qstring_append(str, buf); } break; } } ptr++; } qstring_append(str, "\""); break; } case QTYPE_QDICT: { ToJsonIterState s; QDict *val = qobject_to_qdict(obj); s.count = 0; s.str = str; s.indent = indent + 1; s.pretty = pretty; qstring_append(str, "{"); qdict_iter(val, to_json_dict_iter, &s); if (pretty) { int j; qstring_append(str, "\n"); for (j = 0 ; j < indent ; j++) qstring_append(str, " "); } qstring_append(str, "}"); break; } case QTYPE_QLIST: { ToJsonIterState s; QList *val = qobject_to_qlist(obj); s.count = 0; s.str = str; s.indent = indent + 1; s.pretty = pretty; qstring_append(str, "["); qlist_iter(val, (void *)to_json_list_iter, &s); if (pretty) { int j; qstring_append(str, "\n"); for (j = 0 ; j < indent ; j++) qstring_append(str, " "); } qstring_append(str, "]"); break; } case QTYPE_QFLOAT: { QFloat *val = qobject_to_qfloat(obj); char buffer[1024]; int len; len = snprintf(buffer, sizeof(buffer), "%f", qfloat_get_double(val)); while (len > 0 && buffer[len - 1] == '0') { len--; } if (len && buffer[len - 1] == '.') { buffer[len - 1] = 0; } else { buffer[len] = 0; } qstring_append(str, buffer); break; } case QTYPE_QBOOL: { QBool *val = qobject_to_qbool(obj); if (qbool_get_int(val)) { qstring_append(str, "true"); } else { qstring_append(str, "false"); } break; } case QTYPE_QERROR: /* XXX: should QError be emitted? */ case QTYPE_NONE: break; } } QString *qobject_to_json(const QObject *obj) { QString *str = qstring_new(); to_json(obj, str, 0, 0); return str; } QString *qobject_to_json_pretty(const QObject *obj) { QString *str = qstring_new(); to_json(obj, str, 1, 0); return str; }
gpl-3.0
crawford/grub
grub-core/video/fb/fbutil.c
56
3915
/* * GRUB -- GRand Unified Bootloader * Copyright (C) 2006,2007,2009 Free Software Foundation, Inc. * * GRUB 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. * * GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>. */ /* SPECIAL NOTES! Please note following when reading the code below: - In this driver we assume that every memory can be accessed by same memory bus. If there are different address spaces do not use this code as a base code for other archs. - Every function in this code assumes that bounds checking has been done in previous phase and they are opted out in here. */ #include <grub/fbutil.h> #include <grub/types.h> #include <grub/video.h> grub_video_color_t get_pixel (struct grub_video_fbblit_info *source, unsigned int x, unsigned int y) { grub_video_color_t color = 0; switch (source->mode_info->bpp) { case 32: color = *(grub_uint32_t *)grub_video_fb_get_video_ptr (source, x, y); break; case 24: { grub_uint8_t *ptr; ptr = grub_video_fb_get_video_ptr (source, x, y); #ifdef GRUB_CPU_WORDS_BIGENDIAN color = ptr[2] | (ptr[1] << 8) | (ptr[0] << 16); #else color = ptr[0] | (ptr[1] << 8) | (ptr[2] << 16); #endif } break; case 16: case 15: color = *(grub_uint16_t *)grub_video_fb_get_video_ptr (source, x, y); break; case 8: color = *(grub_uint8_t *)grub_video_fb_get_video_ptr (source, x, y); break; case 1: if (source->mode_info->blit_format == GRUB_VIDEO_BLIT_FORMAT_1BIT_PACKED) { int bit_index = y * source->mode_info->width + x; grub_uint8_t *ptr = source->data + bit_index / 8; int bit_pos = 7 - bit_index % 8; color = (*ptr >> bit_pos) & 0x01; } break; default: break; } return color; } void set_pixel (struct grub_video_fbblit_info *source, unsigned int x, unsigned int y, grub_video_color_t color) { switch (source->mode_info->bpp) { case 32: { grub_uint32_t *ptr; ptr = (grub_uint32_t *)grub_video_fb_get_video_ptr (source, x, y); *ptr = color; } break; case 24: { grub_uint8_t *ptr; #ifdef GRUB_CPU_WORDS_BIGENDIAN grub_uint8_t *colorptr = ((grub_uint8_t *)&color) + 1; #else grub_uint8_t *colorptr = (grub_uint8_t *)&color; #endif ptr = grub_video_fb_get_video_ptr (source, x, y); ptr[0] = colorptr[0]; ptr[1] = colorptr[1]; ptr[2] = colorptr[2]; } break; case 16: case 15: { grub_uint16_t *ptr; ptr = (grub_uint16_t *)grub_video_fb_get_video_ptr (source, x, y); *ptr = (grub_uint16_t) (color & 0xFFFF); } break; case 8: { grub_uint8_t *ptr; ptr = (grub_uint8_t *)grub_video_fb_get_video_ptr (source, x, y); *ptr = (grub_uint8_t) (color & 0xFF); } break; case 1: if (source->mode_info->blit_format == GRUB_VIDEO_BLIT_FORMAT_1BIT_PACKED) { int bit_index = y * source->mode_info->width + x; grub_uint8_t *ptr = source->data + bit_index / 8; int bit_pos = 7 - bit_index % 8; *ptr = (*ptr & ~(1 << bit_pos)) | ((color & 0x01) << bit_pos); } break; default: break; } }
gpl-3.0
xtmacbook/DOOM-3
neo/framework/DeclAF.cpp
58
46452
/* =========================================================================== 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 "../idlib/precompiled.h" #pragma hdrstop /* =============================================================================== idDeclAF =============================================================================== */ /* ================ idAFVector::idAFVector ================ */ idAFVector::idAFVector( void ) { type = VEC_COORDS; vec.Zero(); negate = false; } /* ================ idAFVector::Parse ================ */ bool idAFVector::Parse( idLexer &src ) { idToken token; if ( !src.ReadToken( &token ) ) { return false; } if ( token == "-" ) { negate = true; if ( !src.ReadToken( &token ) ) { return false; } } else { negate = false; } if ( token == "(" ) { type = idAFVector::VEC_COORDS; vec.x = src.ParseFloat(); src.ExpectTokenString( "," ); vec.y = src.ParseFloat(); src.ExpectTokenString( "," ); vec.z = src.ParseFloat(); src.ExpectTokenString( ")" ); } else if ( token == "joint" ) { type = idAFVector::VEC_JOINT; src.ExpectTokenString( "(" ); src.ReadToken( &token ); joint1 = token; src.ExpectTokenString( ")" ); } else if ( token == "bonecenter" ) { type = idAFVector::VEC_BONECENTER; src.ExpectTokenString( "(" ); src.ReadToken( &token ); joint1 = token; src.ExpectTokenString( "," ); src.ReadToken( &token ); joint2 = token; src.ExpectTokenString( ")" ); } else if ( token == "bonedir" ) { type = idAFVector::VEC_BONEDIR; src.ExpectTokenString( "(" ); src.ReadToken( &token ); joint1 = token; src.ExpectTokenString( "," ); src.ReadToken( &token ); joint2 = token; src.ExpectTokenString( ")" ); } else { src.Error( "unknown token %s in vector", token.c_str() ); return false; } return true; } /* ================ idAFVector::Finish ================ */ bool idAFVector::Finish( const char *fileName, const getJointTransform_t GetJointTransform, const idJointMat *frame, void *model ) const { idMat3 axis; idVec3 start, end; switch( type ) { case idAFVector::VEC_COORDS: { break; } case idAFVector::VEC_JOINT: { if ( !GetJointTransform( model, frame, joint1, vec, axis ) ) { common->Warning( "invalid joint %s in joint() in '%s'", joint1.c_str(), fileName ); vec.Zero(); } break; } case idAFVector::VEC_BONECENTER: { if ( !GetJointTransform( model, frame, joint1, start, axis ) ) { common->Warning( "invalid joint %s in bonecenter() in '%s'", joint1.c_str(), fileName ); start.Zero(); } if ( !GetJointTransform( model, frame, joint2, end, axis ) ) { common->Warning( "invalid joint %s in bonecenter() in '%s'", joint2.c_str(), fileName ); end.Zero(); } vec = ( start + end ) * 0.5f; break; } case idAFVector::VEC_BONEDIR: { if ( !GetJointTransform( model, frame, joint1, start, axis ) ) { common->Warning( "invalid joint %s in bonedir() in '%s'", joint1.c_str(), fileName ); start.Zero(); } if ( !GetJointTransform( model, frame, joint2, end, axis ) ) { common->Warning( "invalid joint %s in bonedir() in '%s'", joint2.c_str(), fileName ); end.Zero(); } vec = ( end - start ); break; } default: { vec.Zero(); break; } } if ( negate ) { vec = -vec; } return true; } /* ================ idAFVector::Write ================ */ bool idAFVector::Write( idFile *f ) const { if ( negate ) { f->WriteFloatString( "-" ); } switch( type ) { case idAFVector::VEC_COORDS: { f->WriteFloatString( "( %f, %f, %f )", vec.x, vec.y, vec.z ); break; } case idAFVector::VEC_JOINT: { f->WriteFloatString( "joint( \"%s\" )", joint1.c_str() ); break; } case idAFVector::VEC_BONECENTER: { f->WriteFloatString( "bonecenter( \"%s\", \"%s\" )", joint1.c_str(), joint2.c_str() ); break; } case idAFVector::VEC_BONEDIR: { f->WriteFloatString( "bonedir( \"%s\", \"%s\" )", joint1.c_str(), joint2.c_str() ); break; } default: { break; } } return true; } /* ================ idAFVector::ToString ================ */ const char *idAFVector::ToString( idStr &str, const int precision ) { switch( type ) { case idAFVector::VEC_COORDS: { char format[128]; sprintf( format, "( %%.%df, %%.%df, %%.%df )", precision, precision, precision ); sprintf( str, format, vec.x, vec.y, vec.z ); break; } case idAFVector::VEC_JOINT: { sprintf( str, "joint( \"%s\" )", joint1.c_str() ); break; } case idAFVector::VEC_BONECENTER: { sprintf( str, "bonecenter( \"%s\", \"%s\" )", joint1.c_str(), joint2.c_str() ); break; } case idAFVector::VEC_BONEDIR: { sprintf( str, "bonedir( \"%s\", \"%s\" )", joint1.c_str(), joint2.c_str() ); break; } default: { break; } } if ( negate ) { str = "-" + str; } return str.c_str(); } /* ================ idDeclAF_Body::SetDefault ================ */ void idDeclAF_Body::SetDefault( const idDeclAF *file ) { name = "noname"; modelType = TRM_BOX; v1.type = idAFVector::VEC_COORDS; v1.ToVec3().x = v1.ToVec3().y = v1.ToVec3().z = -10.0f; v2.type = idAFVector::VEC_COORDS; v2.ToVec3().x = v2.ToVec3().y = v2.ToVec3().z = 10.0f; numSides = 3; origin.ToVec3().Zero(); angles.Zero(); density = 0.2f; inertiaScale.Identity(); linearFriction = file->defaultLinearFriction; angularFriction = file->defaultAngularFriction; contactFriction = file->defaultContactFriction; contents = file->contents; clipMask = file->clipMask; selfCollision = file->selfCollision; frictionDirection.ToVec3().Zero(); contactMotorDirection.ToVec3().Zero(); jointName = "origin"; jointMod = DECLAF_JOINTMOD_AXIS; containedJoints = "*origin"; } /* ================ idDeclAF_Constraint::SetDefault ================ */ void idDeclAF_Constraint::SetDefault( const idDeclAF *file ) { name = "noname"; type = DECLAF_CONSTRAINT_UNIVERSALJOINT; if ( file->bodies.Num() ) { body1 = file->bodies[0]->name; } else { body1 = "world"; } body2 = "world"; friction = file->defaultConstraintFriction; anchor.ToVec3().Zero(); anchor2.ToVec3().Zero(); axis.ToVec3().Set( 1.0f, 0.0f, 0.0f ); shaft[0].ToVec3().Set( 0.0f, 0.0f, -1.0f ); shaft[1].ToVec3().Set( 0.0f, 0.0f, 1.0f ); limit = idDeclAF_Constraint::LIMIT_NONE; limitAngles[0] = limitAngles[1] = limitAngles[2] = 0.0f; limitAxis.ToVec3().Set( 0.0f, 0.0f, -1.0f ); } /* ================ idDeclAF::WriteBody ================ */ bool idDeclAF::WriteBody( idFile *f, const idDeclAF_Body &body ) const { idStr str; f->WriteFloatString( "\nbody \"%s\" {\n", body.name.c_str() ); f->WriteFloatString( "\tjoint \"%s\"\n", body.jointName.c_str() ); f->WriteFloatString( "\tmod %s\n", JointModToString( body.jointMod ) ); switch( body.modelType ) { case TRM_BOX: { f->WriteFloatString( "\tmodel box( " ); body.v1.Write( f ); f->WriteFloatString( ", " ); body.v2.Write( f ); f->WriteFloatString( " )\n" ); break; } case TRM_OCTAHEDRON: { f->WriteFloatString( "\tmodel octahedron( " ); body.v1.Write( f ); f->WriteFloatString( ", " ); body.v2.Write( f ); f->WriteFloatString( " )\n" ); break; } case TRM_DODECAHEDRON: { f->WriteFloatString( "\tmodel dodecahedron( " ); body.v1.Write( f ); f->WriteFloatString( ", " ); body.v2.Write( f ); f->WriteFloatString( " )\n" ); break; } case TRM_CYLINDER: { f->WriteFloatString( "\tmodel cylinder( " ); body.v1.Write( f ); f->WriteFloatString( ", " ); body.v2.Write( f ); f->WriteFloatString( ", %d )\n", body.numSides ); break; } case TRM_CONE: { f->WriteFloatString( "\tmodel cone( " ); body.v1.Write( f ); f->WriteFloatString( ", " ); body.v2.Write( f ); f->WriteFloatString( ", %d )\n", body.numSides ); break; } case TRM_BONE: { f->WriteFloatString( "\tmodel bone( " ); body.v1.Write( f ); f->WriteFloatString( ", " ); body.v2.Write( f ); f->WriteFloatString( ", %f )\n", body.width ); break; } default: assert( 0 ); break; } f->WriteFloatString( "\torigin " ); body.origin.Write( f ); f->WriteFloatString( "\n" ); if ( body.angles != ang_zero ) { f->WriteFloatString( "\tangles ( %f, %f, %f )\n", body.angles.pitch, body.angles.yaw, body.angles.roll ); } f->WriteFloatString( "\tdensity %f\n", body.density ); if ( body.inertiaScale != mat3_identity ) { const idMat3 &ic = body.inertiaScale; f->WriteFloatString( "\tinertiaScale (%f %f %f %f %f %f %f %f %f)\n", ic[0][0], ic[0][1], ic[0][2], ic[1][0], ic[1][1], ic[1][2], ic[2][0], ic[2][1], ic[2][2] ); } if ( body.linearFriction != -1 ) { f->WriteFloatString( "\tfriction %f, %f, %f\n", body.linearFriction, body.angularFriction, body.contactFriction ); } f->WriteFloatString( "\tcontents %s\n", ContentsToString( body.contents, str ) ); f->WriteFloatString( "\tclipMask %s\n", ContentsToString( body.clipMask, str ) ); f->WriteFloatString( "\tselfCollision %d\n", body.selfCollision ); if ( body.frictionDirection.ToVec3() != vec3_origin ) { f->WriteFloatString( "\tfrictionDirection " ); body.frictionDirection.Write( f ); f->WriteFloatString( "\n" ); } if ( body.contactMotorDirection.ToVec3() != vec3_origin ) { f->WriteFloatString( "\tcontactMotorDirection " ); body.contactMotorDirection.Write( f ); f->WriteFloatString( "\n" ); } f->WriteFloatString( "\tcontainedJoints \"%s\"\n", body.containedJoints.c_str() ); f->WriteFloatString( "}\n" ); return true; } /* ================ idDeclAF::WriteFixed ================ */ bool idDeclAF::WriteFixed( idFile *f, const idDeclAF_Constraint &c ) const { f->WriteFloatString( "\nfixed \"%s\" {\n", c.name.c_str() ); f->WriteFloatString( "\tbody1 \"%s\"\n", c.body1.c_str() ); f->WriteFloatString( "\tbody2 \"%s\"\n", c.body2.c_str() ); f->WriteFloatString( "}\n" ); return true; } /* ================ idDeclAF::WriteBallAndSocketJoint ================ */ bool idDeclAF::WriteBallAndSocketJoint( idFile *f, const idDeclAF_Constraint &c ) const { f->WriteFloatString( "\nballAndSocketJoint \"%s\" {\n", c.name.c_str() ); f->WriteFloatString( "\tbody1 \"%s\"\n", c.body1.c_str() ); f->WriteFloatString( "\tbody2 \"%s\"\n", c.body2.c_str() ); f->WriteFloatString( "\tanchor " ); c.anchor.Write( f ); f->WriteFloatString( "\n" ); f->WriteFloatString( "\tfriction %f\n", c.friction ); if ( c.limit == idDeclAF_Constraint::LIMIT_CONE ) { f->WriteFloatString( "\tconeLimit " ); c.limitAxis.Write( f ); f->WriteFloatString( ", %f, ", c.limitAngles[0] ); c.shaft[0].Write( f ); f->WriteFloatString( "\n" ); } else if ( c.limit == idDeclAF_Constraint::LIMIT_PYRAMID ) { f->WriteFloatString( "\tpyramidLimit " ); c.limitAxis.Write( f ); f->WriteFloatString( ", %f, %f, %f, ", c.limitAngles[0], c.limitAngles[1], c.limitAngles[2] ); c.shaft[0].Write( f ); f->WriteFloatString( "\n" ); } f->WriteFloatString( "}\n" ); return true; } /* ================ idDeclAF::WriteUniversalJoint ================ */ bool idDeclAF::WriteUniversalJoint( idFile *f, const idDeclAF_Constraint &c ) const { f->WriteFloatString( "\nuniversalJoint \"%s\" {\n", c.name.c_str() ); f->WriteFloatString( "\tbody1 \"%s\"\n", c.body1.c_str() ); f->WriteFloatString( "\tbody2 \"%s\"\n", c.body2.c_str() ); f->WriteFloatString( "\tanchor " ); c.anchor.Write( f ); f->WriteFloatString( "\n" ); f->WriteFloatString( "\tshafts " ); c.shaft[0].Write( f ); f->WriteFloatString( ", " ); c.shaft[1].Write( f ); f->WriteFloatString( "\n" ); f->WriteFloatString( "\tfriction %f\n", c.friction ); if ( c.limit == idDeclAF_Constraint::LIMIT_CONE ) { f->WriteFloatString( "\tconeLimit " ); c.limitAxis.Write( f ); f->WriteFloatString( ", %f\n", c.limitAngles[0] ); } else if ( c.limit == idDeclAF_Constraint::LIMIT_PYRAMID ) { f->WriteFloatString( "\tpyramidLimit " ); c.limitAxis.Write( f ); f->WriteFloatString( ", %f, %f, %f\n", c.limitAngles[0], c.limitAngles[1], c.limitAngles[2] ); } f->WriteFloatString( "}\n" ); return true; } /* ================ idDeclAF::WriteHinge ================ */ bool idDeclAF::WriteHinge( idFile *f, const idDeclAF_Constraint &c ) const { f->WriteFloatString( "\nhinge \"%s\" {\n", c.name.c_str() ); f->WriteFloatString( "\tbody1 \"%s\"\n", c.body1.c_str() ); f->WriteFloatString( "\tbody2 \"%s\"\n", c.body2.c_str() ); f->WriteFloatString( "\tanchor " ); c.anchor.Write( f ); f->WriteFloatString( "\n" ); f->WriteFloatString( "\taxis " ); c.axis.Write( f ); f->WriteFloatString( "\n" ); f->WriteFloatString( "\tfriction %f\n", c.friction ); if ( c.limit == idDeclAF_Constraint::LIMIT_CONE ) { f->WriteFloatString( "\tlimit " ); f->WriteFloatString( "%f, %f, %f", c.limitAngles[0], c.limitAngles[1], c.limitAngles[2] ); f->WriteFloatString( "\n" ); } f->WriteFloatString( "}\n" ); return true; } /* ================ idDeclAF::WriteSlider ================ */ bool idDeclAF::WriteSlider( idFile *f, const idDeclAF_Constraint &c ) const { f->WriteFloatString( "\nslider \"%s\" {\n", c.name.c_str() ); f->WriteFloatString( "\tbody1 \"%s\"\n", c.body1.c_str() ); f->WriteFloatString( "\tbody2 \"%s\"\n", c.body2.c_str() ); f->WriteFloatString( "\taxis " ); c.axis.Write( f ); f->WriteFloatString( "\n" ); f->WriteFloatString( "\tfriction %f\n", c.friction ); f->WriteFloatString( "}\n" ); return true; } /* ================ idDeclAF::WriteSpring ================ */ bool idDeclAF::WriteSpring( idFile *f, const idDeclAF_Constraint &c ) const { f->WriteFloatString( "\nspring \"%s\" {\n", c.name.c_str() ); f->WriteFloatString( "\tbody1 \"%s\"\n", c.body1.c_str() ); f->WriteFloatString( "\tbody2 \"%s\"\n", c.body2.c_str() ); f->WriteFloatString( "\tanchor1 " ); c.anchor.Write( f ); f->WriteFloatString( "\n" ); f->WriteFloatString( "\tanchor2 " ); c.anchor2.Write( f ); f->WriteFloatString( "\n" ); f->WriteFloatString( "\tfriction %f\n", c.friction ); f->WriteFloatString( "\tstretch %f\n", c.stretch ); f->WriteFloatString( "\tcompress %f\n", c.compress ); f->WriteFloatString( "\tdamping %f\n", c.damping ); f->WriteFloatString( "\trestLength %f\n", c.restLength ); f->WriteFloatString( "\tminLength %f\n", c.minLength ); f->WriteFloatString( "\tmaxLength %f\n", c.maxLength ); f->WriteFloatString( "}\n" ); return true; } /* ================ idDeclAF::WriteConstraint ================ */ bool idDeclAF::WriteConstraint( idFile *f, const idDeclAF_Constraint &c ) const { switch( c.type ) { case DECLAF_CONSTRAINT_FIXED: return WriteFixed( f, c ); case DECLAF_CONSTRAINT_BALLANDSOCKETJOINT: return WriteBallAndSocketJoint( f, c ); case DECLAF_CONSTRAINT_UNIVERSALJOINT: return WriteUniversalJoint( f, c ); case DECLAF_CONSTRAINT_HINGE: return WriteHinge( f, c ); case DECLAF_CONSTRAINT_SLIDER: return WriteSlider( f, c ); case DECLAF_CONSTRAINT_SPRING: return WriteSpring( f, c ); default: break; } return false; } /* ================ idDeclAF::WriteSettings ================ */ bool idDeclAF::WriteSettings( idFile *f ) const { idStr str; f->WriteFloatString( "\nsettings {\n" ); f->WriteFloatString( "\tmodel \"%s\"\n", model.c_str() ); f->WriteFloatString( "\tskin \"%s\"\n", skin.c_str() ); f->WriteFloatString( "\tfriction %f, %f, %f, %f\n", defaultLinearFriction, defaultAngularFriction, defaultContactFriction, defaultConstraintFriction ); f->WriteFloatString( "\tsuspendSpeed %f, %f, %f, %f\n", suspendVelocity[0], suspendVelocity[1], suspendAcceleration[0], suspendAcceleration[1] ); f->WriteFloatString( "\tnoMoveTime %f\n", noMoveTime ); f->WriteFloatString( "\tnoMoveTranslation %f\n", noMoveTranslation ); f->WriteFloatString( "\tnoMoveRotation %f\n", noMoveRotation ); f->WriteFloatString( "\tminMoveTime %f\n", minMoveTime ); f->WriteFloatString( "\tmaxMoveTime %f\n", maxMoveTime ); f->WriteFloatString( "\ttotalMass %f\n", totalMass ); f->WriteFloatString( "\tcontents %s\n", ContentsToString( contents, str ) ); f->WriteFloatString( "\tclipMask %s\n", ContentsToString( clipMask, str ) ); f->WriteFloatString( "\tselfCollision %d\n", selfCollision ); f->WriteFloatString( "}\n" ); return true; } /* ================ idDeclAF::RebuildTextSource ================ */ bool idDeclAF::RebuildTextSource( void ) { int i; idFile_Memory f; f.WriteFloatString("\n\n/*\n" "\tGenerated by the Articulated Figure Editor.\n" "\tDo not edit directly but launch the game and type 'editAFs' on the console.\n" "*/\n" ); f.WriteFloatString( "\narticulatedFigure %s {\n", GetName() ); if ( !WriteSettings( &f ) ) { return false; } for ( i = 0; i < bodies.Num(); i++ ) { if ( !WriteBody( &f, *bodies[i] ) ) { return false; } } for ( i = 0; i < constraints.Num(); i++ ) { if ( !WriteConstraint( &f, *constraints[i] ) ) { return false; } } f.WriteFloatString( "\n}" ); SetText( f.GetDataPtr() ); return true; } /* ================ idDeclAF::Save ================ */ bool idDeclAF::Save( void ) { RebuildTextSource(); ReplaceSourceFileText(); modified = false; return true; } /* ================ idDeclAF::ContentsFromString ================ */ int idDeclAF::ContentsFromString( const char *str ) { int c; idToken token; idLexer src( str, idStr::Length( str ), "idDeclAF::ContentsFromString" ); c = 0; while( src.ReadToken( &token ) ) { if ( token.Icmp( "none" ) == 0 ) { c = 0; } else if ( token.Icmp( "solid" ) == 0 ) { c |= CONTENTS_SOLID; } else if ( token.Icmp( "body" ) == 0 ) { c |= CONTENTS_BODY; } else if ( token.Icmp( "corpse" ) == 0 ) { c |= CONTENTS_CORPSE; } else if ( token.Icmp( "playerclip" ) == 0 ) { c |= CONTENTS_PLAYERCLIP; } else if ( token.Icmp( "monsterclip" ) == 0 ) { c |= CONTENTS_MONSTERCLIP; } else if ( token == "," ) { continue; } else { return c; } } return c; } /* ================ idDeclAF::ContentsToString ================ */ const char *idDeclAF::ContentsToString( const int contents, idStr &str ) { str = ""; if ( contents & CONTENTS_SOLID ) { if ( str.Length() ) str += ", "; str += "solid"; } if ( contents & CONTENTS_BODY ) { if ( str.Length() ) str += ", "; str += "body"; } if ( contents & CONTENTS_CORPSE ) { if ( str.Length() ) str += ", "; str += "corpse"; } if ( contents & CONTENTS_PLAYERCLIP ) { if ( str.Length() ) str += ", "; str += "playerclip"; } if ( contents & CONTENTS_MONSTERCLIP ) { if ( str.Length() ) str += ", "; str += "monsterclip"; } if ( str[0] == '\0' ) { str = "none"; } return str.c_str(); } /* ================ idDeclAF::JointModFromString ================ */ declAFJointMod_t idDeclAF::JointModFromString( const char *str ) { if ( idStr::Icmp( str, "orientation" ) == 0 ) { return DECLAF_JOINTMOD_AXIS; } if ( idStr::Icmp( str, "position" ) == 0 ) { return DECLAF_JOINTMOD_ORIGIN; } if ( idStr::Icmp( str, "both" ) == 0 ) { return DECLAF_JOINTMOD_BOTH; } return DECLAF_JOINTMOD_AXIS; } /* ================ idDeclAF::JointModToString ================ */ const char * idDeclAF::JointModToString( declAFJointMod_t jointMod ) { switch( jointMod ) { case DECLAF_JOINTMOD_AXIS: { return "orientation"; } case DECLAF_JOINTMOD_ORIGIN: { return "position"; } case DECLAF_JOINTMOD_BOTH: { return "both"; } } return "orientation"; } /* ================= idDeclAF::Size ================= */ size_t idDeclAF::Size( void ) const { return sizeof( idDeclAF ); } /* ================ idDeclAF::ParseContents ================ */ bool idDeclAF::ParseContents( idLexer &src, int &c ) const { idToken token; idStr str; while( src.ReadToken( &token ) ) { str += token; if ( !src.CheckTokenString( "," ) ) { break; } str += ","; } c = ContentsFromString( str ); return true; } /* ================ idDeclAF::ParseBody ================ */ bool idDeclAF::ParseBody( idLexer &src ) { bool hasJoint = false; idToken token; idAFVector angles; idDeclAF_Body *body = new idDeclAF_Body; bodies.Alloc() = body; body->SetDefault( this ); if ( !src.ExpectTokenType( TT_STRING, 0, &token ) || !src.ExpectTokenString( "{" ) ) { return false; } body->name = token; if ( !body->name.Icmp( "origin" ) || !body->name.Icmp( "world" ) ) { src.Error( "a body may not be named \"origin\" or \"world\"" ); return false; } while( src.ReadToken( &token ) ) { if ( !token.Icmp( "model" ) ) { if ( !src.ExpectTokenType( TT_NAME, 0, &token ) ) { return false; } if ( !token.Icmp( "box" ) ) { body->modelType = TRM_BOX; if ( !src.ExpectTokenString( "(" ) || !body->v1.Parse( src ) || !src.ExpectTokenString( "," ) || !body->v2.Parse( src ) || !src.ExpectTokenString( ")" ) ) { return false; } } else if ( !token.Icmp( "octahedron" ) ) { body->modelType = TRM_OCTAHEDRON; if ( !src.ExpectTokenString( "(" ) || !body->v1.Parse( src ) || !src.ExpectTokenString( "," ) || !body->v2.Parse( src ) || !src.ExpectTokenString( ")" ) ) { return false; } } else if ( !token.Icmp( "dodecahedron" ) ) { body->modelType = TRM_DODECAHEDRON; if ( !src.ExpectTokenString( "(" ) || !body->v1.Parse( src ) || !src.ExpectTokenString( "," ) || !body->v2.Parse( src ) || !src.ExpectTokenString( ")" ) ) { return false; } } else if ( !token.Icmp( "cylinder" ) ) { body->modelType = TRM_CYLINDER; if ( !src.ExpectTokenString( "(" ) || !body->v1.Parse( src ) || !src.ExpectTokenString( "," ) || !body->v2.Parse( src ) || !src.ExpectTokenString( "," ) ) { return false; } body->numSides = src.ParseInt(); if ( !src.ExpectTokenString( ")" ) ) { return false; } } else if ( !token.Icmp( "cone" ) ) { body->modelType = TRM_CONE; if ( !src.ExpectTokenString( "(" ) || !body->v1.Parse( src ) || !src.ExpectTokenString( "," ) || !body->v2.Parse( src ) || !src.ExpectTokenString( "," ) ) { return false; } body->numSides = src.ParseInt(); if ( !src.ExpectTokenString( ")" ) ) { return false; } } else if ( !token.Icmp( "bone" ) ) { body->modelType = TRM_BONE; if ( !src.ExpectTokenString( "(" ) || !body->v1.Parse( src ) || !src.ExpectTokenString( "," ) || !body->v2.Parse( src ) || !src.ExpectTokenString( "," ) ) { return false; } body->width = src.ParseFloat(); if ( !src.ExpectTokenString( ")" ) ) { return false; } } else if ( !token.Icmp( "custom" ) ) { src.Error( "custom models not yet implemented" ); return false; } else { src.Error( "unkown model type %s", token.c_str() ); return false; } } else if ( !token.Icmp( "origin" ) ) { if ( !body->origin.Parse( src ) ) { return false; } } else if ( !token.Icmp( "angles" ) ) { if ( !angles.Parse( src ) ) { return false; } body->angles = idAngles( angles.ToVec3().x, angles.ToVec3().y, angles.ToVec3().z ); } else if ( !token.Icmp( "joint" ) ) { if ( !src.ExpectTokenType( TT_STRING, 0, &token ) ) { return false; } body->jointName = token; hasJoint = true; } else if ( !token.Icmp( "mod" ) ) { if ( !src.ExpectAnyToken( &token ) ) { return false; } body->jointMod = JointModFromString( token.c_str() ); } else if ( !token.Icmp( "density" ) ) { body->density = src.ParseFloat(); } else if ( !token.Icmp( "inertiaScale" ) ) { src.Parse1DMatrix( 9, body->inertiaScale[0].ToFloatPtr() ); } else if ( !token.Icmp( "friction" ) ) { body->linearFriction = src.ParseFloat(); src.ExpectTokenString( "," ); body->angularFriction = src.ParseFloat(); src.ExpectTokenString( "," ); body->contactFriction = src.ParseFloat(); } else if ( !token.Icmp( "contents" ) ) { ParseContents( src, body->contents ); } else if ( !token.Icmp( "clipMask" ) ) { ParseContents( src, body->clipMask ); } else if ( !token.Icmp( "selfCollision" ) ) { body->selfCollision = src.ParseBool(); } else if ( !token.Icmp( "containedjoints" ) ) { if ( !src.ExpectTokenType( TT_STRING, 0, &token ) ) { return false; } body->containedJoints = token; } else if ( !token.Icmp( "frictionDirection" ) ) { if ( !body->frictionDirection.Parse( src ) ) { return false; } } else if ( !token.Icmp( "contactMotorDirection" ) ) { if ( !body->contactMotorDirection.Parse( src ) ) { return false; } } else if ( token == "}" ) { break; } else { src.Error( "unknown token %s in body", token.c_str() ); return false; } } if ( body->modelType == TRM_INVALID ) { src.Error( "no model set for body" ); return false; } if ( !hasJoint ) { src.Error( "no joint set for body" ); return false; } body->clipMask |= CONTENTS_MOVEABLECLIP; return true; } /* ================ idDeclAF::ParseFixed ================ */ bool idDeclAF::ParseFixed( idLexer &src ) { idToken token; idDeclAF_Constraint *constraint = new idDeclAF_Constraint; constraint->SetDefault( this ); constraints.Alloc() = constraint; if ( !src.ExpectTokenType( TT_STRING, 0, &token ) || !src.ExpectTokenString( "{" ) ) { return false; } constraint->type = DECLAF_CONSTRAINT_FIXED; constraint->name = token; while( src.ReadToken( &token ) ) { if ( !token.Icmp( "body1" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body1 = token; } else if ( !token.Icmp( "body2" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body2 = token; } else if ( token == "}" ) { break; } else { src.Error( "unknown token %s in ball and socket joint", token.c_str() ); return false; } } return true; } /* ================ idDeclAF::ParseBallAndSocketJoint ================ */ bool idDeclAF::ParseBallAndSocketJoint( idLexer &src ) { idToken token; idDeclAF_Constraint *constraint = new idDeclAF_Constraint; constraint->SetDefault( this ); constraints.Alloc() = constraint; if ( !src.ExpectTokenType( TT_STRING, 0, &token ) || !src.ExpectTokenString( "{" ) ) { return false; } constraint->type = DECLAF_CONSTRAINT_BALLANDSOCKETJOINT; constraint->limit = idDeclAF_Constraint::LIMIT_NONE; constraint->name = token; constraint->friction = 0.5f; constraint->anchor.ToVec3().Zero(); constraint->shaft[0].ToVec3().Zero(); while( src.ReadToken( &token ) ) { if ( !token.Icmp( "body1" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body1 = token; } else if ( !token.Icmp( "body2" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body2 = token; } else if ( !token.Icmp( "anchor" ) ) { if ( !constraint->anchor.Parse( src ) ) { return false; } } else if ( !token.Icmp( "conelimit" ) ) { if ( !constraint->limitAxis.Parse( src ) || !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[0] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) || !constraint->shaft[0].Parse( src ) ) { return false; } constraint->limit = idDeclAF_Constraint::LIMIT_CONE; } else if ( !token.Icmp( "pyramidlimit" ) ) { if ( !constraint->limitAxis.Parse( src ) || !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[0] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[1] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[2] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) || !constraint->shaft[0].Parse( src ) ) { return false; } constraint->limit = idDeclAF_Constraint::LIMIT_PYRAMID; } else if ( !token.Icmp( "friction" ) ) { constraint->friction = src.ParseFloat(); } else if ( token == "}" ) { break; } else { src.Error( "unknown token %s in ball and socket joint", token.c_str() ); return false; } } return true; } /* ================ idDeclAF::ParseUniversalJoint ================ */ bool idDeclAF::ParseUniversalJoint( idLexer &src ) { idToken token; idDeclAF_Constraint *constraint = new idDeclAF_Constraint; constraint->SetDefault( this ); constraints.Alloc() = constraint; if ( !src.ExpectTokenType( TT_STRING, 0, &token ) || !src.ExpectTokenString( "{" ) ) { return false; } constraint->type = DECLAF_CONSTRAINT_UNIVERSALJOINT; constraint->limit = idDeclAF_Constraint::LIMIT_NONE; constraint->name = token; constraint->friction = 0.5f; constraint->anchor.ToVec3().Zero(); constraint->shaft[0].ToVec3().Zero(); constraint->shaft[1].ToVec3().Zero(); while( src.ReadToken( &token ) ) { if ( !token.Icmp( "body1" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body1 = token; } else if ( !token.Icmp( "body2" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body2 = token; } else if ( !token.Icmp( "anchor" ) ) { if ( !constraint->anchor.Parse( src ) ) { return false; } } else if ( !token.Icmp( "shafts" ) ) { if ( !constraint->shaft[0].Parse( src ) || !src.ExpectTokenString( "," ) || !constraint->shaft[1].Parse( src ) ) { return false; } } else if ( !token.Icmp( "conelimit" ) ) { if ( !constraint->limitAxis.Parse( src ) || !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[0] = src.ParseFloat(); constraint->limit = idDeclAF_Constraint::LIMIT_CONE; } else if ( !token.Icmp( "pyramidlimit" ) ) { if ( !constraint->limitAxis.Parse( src ) || !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[0] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[1] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[2] = src.ParseFloat(); constraint->limit = idDeclAF_Constraint::LIMIT_PYRAMID; } else if ( !token.Icmp( "friction" ) ) { constraint->friction = src.ParseFloat(); } else if ( token == "}" ) { break; } else { src.Error( "unknown token %s in universal joint", token.c_str() ); return false; } } return true; } /* ================ idDeclAF::ParseHinge ================ */ bool idDeclAF::ParseHinge( idLexer &src ) { idToken token; idDeclAF_Constraint *constraint = new idDeclAF_Constraint; constraint->SetDefault( this ); constraints.Alloc() = constraint; if ( !src.ExpectTokenType( TT_STRING, 0, &token ) || !src.ExpectTokenString( "{" ) ) { return false; } constraint->type = DECLAF_CONSTRAINT_HINGE; constraint->limit = idDeclAF_Constraint::LIMIT_NONE; constraint->name = token; constraint->friction = 0.5f; constraint->anchor.ToVec3().Zero(); constraint->axis.ToVec3().Zero(); while( src.ReadToken( &token ) ) { if ( !token.Icmp( "body1" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body1 = token; } else if ( !token.Icmp( "body2" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body2 = token; } else if ( !token.Icmp( "anchor" ) ) { if ( !constraint->anchor.Parse( src ) ) { return false; } } else if ( !token.Icmp( "axis" ) ) { if ( !constraint->axis.Parse( src ) ) { return false; } } else if ( !token.Icmp( "limit" ) ) { constraint->limitAngles[0] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[1] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } constraint->limitAngles[2] = src.ParseFloat(); constraint->limit = idDeclAF_Constraint::LIMIT_CONE; } else if ( !token.Icmp( "friction" ) ) { constraint->friction = src.ParseFloat(); } else if ( token == "}" ) { break; } else { src.Error( "unknown token %s in hinge", token.c_str() ); return false; } } return true; } /* ================ idDeclAF::ParseSlider ================ */ bool idDeclAF::ParseSlider( idLexer &src ) { idToken token; idDeclAF_Constraint *constraint = new idDeclAF_Constraint; constraint->SetDefault( this ); constraints.Alloc() = constraint; if ( !src.ExpectTokenType( TT_STRING, 0, &token ) || !src.ExpectTokenString( "{" ) ) { return false; } constraint->type = DECLAF_CONSTRAINT_SLIDER; constraint->limit = idDeclAF_Constraint::LIMIT_NONE; constraint->name = token; constraint->friction = 0.5f; while( src.ReadToken( &token ) ) { if ( !token.Icmp( "body1" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body1 = token; } else if ( !token.Icmp( "body2" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body2 = token; } else if ( !token.Icmp( "axis" ) ) { if ( !constraint->axis.Parse( src ) ) { return false; } } else if ( !token.Icmp( "friction" ) ) { constraint->friction = src.ParseFloat(); } else if ( token == "}" ) { break; } else { src.Error( "unknown token %s in slider", token.c_str() ); return false; } } return true; } /* ================ idDeclAF::ParseSpring ================ */ bool idDeclAF::ParseSpring( idLexer &src ) { idToken token; idDeclAF_Constraint *constraint = new idDeclAF_Constraint; constraint->SetDefault( this ); constraints.Alloc() = constraint; if ( !src.ExpectTokenType( TT_STRING, 0, &token ) || !src.ExpectTokenString( "{" ) ) { return false; } constraint->type = DECLAF_CONSTRAINT_SPRING; constraint->limit = idDeclAF_Constraint::LIMIT_NONE; constraint->name = token; constraint->friction = 0.5f; while( src.ReadToken( &token ) ) { if ( !token.Icmp( "body1" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body1 = token; } else if ( !token.Icmp( "body2" ) ) { src.ExpectTokenType( TT_STRING, 0, &token ); constraint->body2 = token; } else if ( !token.Icmp( "anchor1" ) ) { if ( !constraint->anchor.Parse( src ) ) { return false; } } else if ( !token.Icmp( "anchor2" ) ) { if ( !constraint->anchor2.Parse( src ) ) { return false; } } else if ( !token.Icmp( "friction" ) ) { constraint->friction = src.ParseFloat(); } else if ( !token.Icmp( "stretch" ) ) { constraint->stretch = src.ParseFloat(); } else if ( !token.Icmp( "compress" ) ) { constraint->compress = src.ParseFloat(); } else if ( !token.Icmp( "damping" ) ) { constraint->damping = src.ParseFloat(); } else if ( !token.Icmp( "restLength" ) ) { constraint->restLength = src.ParseFloat(); } else if ( !token.Icmp( "minLength" ) ) { constraint->minLength = src.ParseFloat(); } else if ( !token.Icmp( "maxLength" ) ) { constraint->maxLength = src.ParseFloat(); } else if ( token == "}" ) { break; } else { src.Error( "unknown token %s in spring", token.c_str() ); return false; } } return true; } /* ================ idDeclAF::ParseSettings ================ */ bool idDeclAF::ParseSettings( idLexer &src ) { idToken token; if ( !src.ExpectTokenString( "{" ) ) { return false; } while( src.ReadToken( &token ) ) { if ( !token.Icmp( "mesh" ) ) { if ( !src.ExpectTokenType( TT_STRING, 0, &token ) ) { return false; } } else if ( !token.Icmp( "anim" ) ) { if ( !src.ExpectTokenType( TT_STRING, 0, &token ) ) { return false; } } else if ( !token.Icmp( "model" ) ) { if ( !src.ExpectTokenType( TT_STRING, 0, &token ) ) { return false; } model = token; } else if ( !token.Icmp( "skin" ) ) { if ( !src.ExpectTokenType( TT_STRING, 0, &token ) ) { return false; } skin = token; } else if ( !token.Icmp( "friction" ) ) { defaultLinearFriction = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } defaultAngularFriction = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } defaultContactFriction = src.ParseFloat(); if ( src.CheckTokenString( "," ) ) { defaultConstraintFriction = src.ParseFloat(); } } else if ( !token.Icmp( "totalMass" ) ) { totalMass = src.ParseFloat(); } else if ( !token.Icmp( "suspendSpeed" ) ) { suspendVelocity[0] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } suspendVelocity[1] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } suspendAcceleration[0] = src.ParseFloat(); if ( !src.ExpectTokenString( "," ) ) { return false; } suspendAcceleration[1] = src.ParseFloat(); } else if ( !token.Icmp( "noMoveTime" ) ) { noMoveTime = src.ParseFloat(); } else if ( !token.Icmp( "noMoveTranslation" ) ) { noMoveTranslation = src.ParseFloat(); } else if ( !token.Icmp( "noMoveRotation" ) ) { noMoveRotation = src.ParseFloat(); } else if ( !token.Icmp( "minMoveTime" ) ) { minMoveTime = src.ParseFloat(); } else if ( !token.Icmp( "maxMoveTime" ) ) { maxMoveTime = src.ParseFloat(); } else if ( !token.Icmp( "contents" ) ) { ParseContents( src, contents ); } else if ( !token.Icmp( "clipMask" ) ) { ParseContents( src, clipMask ); } else if ( !token.Icmp( "selfCollision" ) ) { selfCollision = src.ParseBool(); } else if ( token == "}" ) { break; } else { src.Error( "unknown token %s in settings", token.c_str() ); return false; } } return true; } /* ================ idDeclAF::Parse ================ */ bool idDeclAF::Parse( const char *text, const int textLength ) { int i, j; idLexer src; idToken token; src.LoadMemory( text, textLength, GetFileName(), GetLineNum() ); src.SetFlags( DECL_LEXER_FLAGS ); src.SkipUntilString( "{" ); while( src.ReadToken( &token ) ) { if ( !token.Icmp( "settings" ) ) { if ( !ParseSettings( src ) ) { return false; } } else if ( !token.Icmp( "body" ) ) { if ( !ParseBody( src ) ) { return false; } } else if ( !token.Icmp( "fixed" ) ) { if ( !ParseFixed( src ) ) { return false; } } else if ( !token.Icmp( "ballAndSocketJoint" ) ) { if ( !ParseBallAndSocketJoint( src ) ) { return false; } } else if ( !token.Icmp( "universalJoint" ) ) { if ( !ParseUniversalJoint( src ) ) { return false; } } else if ( !token.Icmp( "hinge" ) ) { if ( !ParseHinge( src ) ) { return false; } } else if ( !token.Icmp( "slider" ) ) { if ( !ParseSlider( src ) ) { return false; } } else if ( !token.Icmp( "spring" ) ) { if ( !ParseSpring( src ) ) { return false; } } else if ( token == "}" ) { break; } else { src.Error( "unknown keyword %s", token.c_str() ); return false; } } for ( i = 0; i < bodies.Num(); i++ ) { // check for multiple bodies with the same name for ( j = i+1; j < bodies.Num(); j++ ) { if ( bodies[i]->name == bodies[j]->name ) { src.Error( "two bodies with the same name \"%s\"", bodies[i]->name.c_str() ); } } } for ( i = 0; i < constraints.Num(); i++ ) { // check for multiple constraints with the same name for ( j = i+1; j < constraints.Num(); j++ ) { if ( constraints[i]->name == constraints[j]->name ) { src.Error( "two constraints with the same name \"%s\"", constraints[i]->name.c_str() ); } } // check if there are two valid bodies set if ( constraints[i]->body1 == "" ) { src.Error( "no valid body1 specified for constraint '%s'", constraints[i]->name.c_str() ); } if ( constraints[i]->body2 == "" ) { src.Error( "no valid body2 specified for constraint '%s'", constraints[i]->name.c_str() ); } } // make sure the body which modifies the origin comes first for ( i = 0; i < bodies.Num(); i++ ) { if ( bodies[i]->jointName == "origin" ) { if ( i != 0 ) { idDeclAF_Body *b = bodies[0]; bodies[0] = bodies[i]; bodies[i] = b; } break; } } return true; } /* ================ idDeclAF::DefaultDefinition ================ */ const char *idDeclAF::DefaultDefinition( void ) const { return "{\n" "\t" "settings {\n" "\t\t" "model \"\"\n" "\t\t" "skin \"\"\n" "\t\t" "friction 0.01, 0.01, 0.8, 0.5\n" "\t\t" "suspendSpeed 20, 30, 40, 60\n" "\t\t" "noMoveTime 1\n" "\t\t" "noMoveTranslation 10\n" "\t\t" "noMoveRotation 10\n" "\t\t" "minMoveTime -1\n" "\t\t" "maxMoveTime -1\n" "\t\t" "totalMass -1\n" "\t\t" "contents corpse\n" "\t\t" "clipMask solid, corpse\n" "\t\t" "selfCollision 1\n" "\t" "}\n" "\t" "body \"body\" {\n" "\t\t" "joint \"origin\"\n" "\t\t" "mod orientation\n" "\t\t" "model box( ( -10, -10, -10 ), ( 10, 10, 10 ) )\n" "\t\t" "origin ( 0, 0, 0 )\n" "\t\t" "density 0.2\n" "\t\t" "friction 0.01, 0.01, 0.8\n" "\t\t" "contents corpse\n" "\t\t" "clipMask solid, corpse\n" "\t\t" "selfCollision 1\n" "\t\t" "containedJoints \"*origin\"\n" "\t" "}\n" "}\n"; } /* ================ idDeclAF::FreeData ================ */ void idDeclAF::FreeData( void ) { modified = false; defaultLinearFriction = 0.01f; defaultAngularFriction = 0.01f; defaultContactFriction = 0.8f; defaultConstraintFriction = 0.5f; totalMass = -1; suspendVelocity.Set( 20.0f, 30.0f ); suspendAcceleration.Set( 40.0f, 60.0f ); noMoveTime = 1.0f; noMoveTranslation = 10.0f; noMoveRotation = 10.0f; minMoveTime = -1.0f; maxMoveTime = -1.0f; selfCollision = true; contents = CONTENTS_CORPSE; clipMask = CONTENTS_SOLID | CONTENTS_CORPSE; bodies.DeleteContents( true ); constraints.DeleteContents( true ); } /* ================ idDeclAF::Finish ================ */ void idDeclAF::Finish( const getJointTransform_t GetJointTransform, const idJointMat *frame, void *model ) const { int i; const char *name = GetName(); for ( i = 0; i < bodies.Num(); i++ ) { idDeclAF_Body *body = bodies[i]; body->v1.Finish( name, GetJointTransform, frame, model ); body->v2.Finish( name, GetJointTransform, frame, model ); body->origin.Finish( name, GetJointTransform, frame, model ); body->frictionDirection.Finish( name, GetJointTransform, frame, model ); body->contactMotorDirection.Finish( name, GetJointTransform, frame, model ); } for ( i = 0; i < constraints.Num(); i++ ) { idDeclAF_Constraint *constraint = constraints[i]; constraint->anchor.Finish( name, GetJointTransform, frame, model ); constraint->anchor2.Finish( name, GetJointTransform, frame, model ); constraint->shaft[0].Finish( name, GetJointTransform, frame, model ); constraint->shaft[1].Finish( name, GetJointTransform, frame, model ); constraint->axis.Finish( name, GetJointTransform, frame, model ); constraint->limitAxis.Finish( name, GetJointTransform, frame, model ); } } /* ================ idDeclAF::NewBody ================ */ void idDeclAF::NewBody( const char *name ) { idDeclAF_Body *body; body = new idDeclAF_Body(); body->SetDefault( this ); body->name = name; bodies.Append( body ); } /* ================ idDeclAF::RenameBody rename the body with the given name and rename all constraint body references ================ */ void idDeclAF::RenameBody( const char *oldName, const char *newName ) { int i; for ( i = 0; i < bodies.Num(); i++ ) { if ( bodies[i]->name.Icmp( oldName ) == 0 ) { bodies[i]->name = newName; break; } } for ( i = 0; i < constraints.Num(); i++ ) { if ( constraints[i]->body1.Icmp( oldName ) == 0 ) { constraints[i]->body1 = newName; } else if ( constraints[i]->body2.Icmp( oldName ) == 0 ) { constraints[i]->body2 = newName; } } } /* ================ idDeclAF::DeleteBody delete the body with the given name and delete all constraints that reference the body ================ */ void idDeclAF::DeleteBody( const char *name ) { int i; for ( i = 0; i < bodies.Num(); i++ ) { if ( bodies[i]->name.Icmp( name ) == 0 ) { delete bodies[i]; bodies.RemoveIndex( i ); break; } } for ( i = 0; i < constraints.Num(); i++ ) { if ( constraints[i]->body1.Icmp( name ) == 0 || constraints[i]->body2.Icmp( name ) == 0 ) { delete constraints[i]; constraints.RemoveIndex( i ); i--; } } } /* ================ idDeclAF::NewConstraint ================ */ void idDeclAF::NewConstraint( const char *name ) { idDeclAF_Constraint *constraint; constraint = new idDeclAF_Constraint; constraint->SetDefault( this ); constraint->name = name; constraints.Append( constraint ); } /* ================ idDeclAF::RenameConstraint ================ */ void idDeclAF::RenameConstraint( const char *oldName, const char *newName ) { int i; for ( i = 0; i < constraints.Num(); i++ ) { if ( constraints[i]->name.Icmp( oldName ) == 0 ) { constraints[i]->name = newName; return; } } } /* ================ idDeclAF::DeleteConstraint ================ */ void idDeclAF::DeleteConstraint( const char *name ) { int i; for ( i = 0; i < constraints.Num(); i++ ) { if ( constraints[i]->name.Icmp( name ) == 0 ) { delete constraints[i]; constraints.RemoveIndex( i ); return; } } } /* ================ idDeclAF::idDeclAF ================ */ idDeclAF::idDeclAF( void ) { FreeData(); } /* ================ idDeclAF::~idDeclAF ================ */ idDeclAF::~idDeclAF( void ) { bodies.DeleteContents( true ); constraints.DeleteContents( true ); }
gpl-3.0
marbalon/betaflight
lib/main/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dfsdm.c
58
131666
/** ****************************************************************************** * @file stm32f4xx_hal_dfsdm.c * @author MCD Application Team * @version V1.6.0 * @date 04-November-2016 * @brief This file provides firmware functions to manage the following * functionalities of the Digital Filter for Sigma-Delta Modulators * (DFSDM) peripherals: * + Initialization and configuration of channels and filters * + Regular channels configuration * + Injected channels configuration * + Regular/Injected Channels DMA Configuration * + Interrupts and flags management * + Analog watchdog feature * + Short-circuit detector feature * + Extremes detector feature * + Clock absence detector feature * + Break generation on analog watchdog or short-circuit event * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] *** Channel initialization *** ============================== [..] (#) User has first to initialize channels (before filters initialization). (#) As prerequisite, fill in the HAL_DFSDM_ChannelMspInit() : (++) Enable DFSDMz clock interface with __HAL_RCC_DFSDMz_CLK_ENABLE(). (++) Enable the clocks for the DFSDMz GPIOS with __HAL_RCC_GPIOx_CLK_ENABLE(). (++) Configure these DFSDMz pins in alternate mode using HAL_GPIO_Init(). (++) If interrupt mode is used, enable and configure DFSDMz_FLT0 global interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). (#) Configure the output clock, input, serial interface, analog watchdog, offset and data right bit shift parameters for this channel using the HAL_DFSDM_ChannelInit() function. *** Channel clock absence detector *** ====================================== [..] (#) Start clock absence detector using HAL_DFSDM_ChannelCkabStart() or HAL_DFSDM_ChannelCkabStart_IT(). (#) In polling mode, use HAL_DFSDM_ChannelPollForCkab() to detect the clock absence. (#) In interrupt mode, HAL_DFSDM_ChannelCkabCallback() will be called if clock absence is detected. (#) Stop clock absence detector using HAL_DFSDM_ChannelCkabStop() or HAL_DFSDM_ChannelCkabStop_IT(). (#) Please note that the same mode (polling or interrupt) has to be used for all channels because the channels are sharing the same interrupt. (#) Please note also that in interrupt mode, if clock absence detector is stopped for one channel, interrupt will be disabled for all channels. *** Channel short circuit detector *** ====================================== [..] (#) Start short circuit detector using HAL_DFSDM_ChannelScdStart() or or HAL_DFSDM_ChannelScdStart_IT(). (#) In polling mode, use HAL_DFSDM_ChannelPollForScd() to detect short circuit. (#) In interrupt mode, HAL_DFSDM_ChannelScdCallback() will be called if short circuit is detected. (#) Stop short circuit detector using HAL_DFSDM_ChannelScdStop() or or HAL_DFSDM_ChannelScdStop_IT(). (#) Please note that the same mode (polling or interrupt) has to be used for all channels because the channels are sharing the same interrupt. (#) Please note also that in interrupt mode, if short circuit detector is stopped for one channel, interrupt will be disabled for all channels. *** Channel analog watchdog value *** ===================================== [..] (#) Get analog watchdog filter value of a channel using HAL_DFSDM_ChannelGetAwdValue(). *** Channel offset value *** ===================================== [..] (#) Modify offset value of a channel using HAL_DFSDM_ChannelModifyOffset(). *** Filter initialization *** ============================= [..] (#) After channel initialization, user has to init filters. (#) As prerequisite, fill in the HAL_DFSDM_FilterMspInit() : (++) If interrupt mode is used , enable and configure DFSDMz_FLTx global interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). Please note that DFSDMz_FLT0 global interrupt could be already enabled if interrupt is used for channel. (++) If DMA mode is used, configure DMA with HAL_DMA_Init() and link it with DFSDMz filter handle using __HAL_LINKDMA(). (#) Configure the regular conversion, injected conversion and filter parameters for this filter using the HAL_DFSDM_FilterInit() function. *** Filter regular channel conversion *** ========================================= [..] (#) Select regular channel and enable/disable continuous mode using HAL_DFSDM_FilterConfigRegChannel(). (#) Start regular conversion using HAL_DFSDM_FilterRegularStart(), HAL_DFSDM_FilterRegularStart_IT(), HAL_DFSDM_FilterRegularStart_DMA() or HAL_DFSDM_FilterRegularMsbStart_DMA(). (#) In polling mode, use HAL_DFSDM_FilterPollForRegConversion() to detect the end of regular conversion. (#) In interrupt mode, HAL_DFSDM_FilterRegConvCpltCallback() will be called at the end of regular conversion. (#) Get value of regular conversion and corresponding channel using HAL_DFSDM_FilterGetRegularValue(). (#) In DMA mode, HAL_DFSDM_FilterRegConvHalfCpltCallback() and HAL_DFSDM_FilterRegConvCpltCallback() will be called respectively at the half transfer and at the transfer complete. Please note that HAL_DFSDM_FilterRegConvHalfCpltCallback() will be called only in DMA circular mode. (#) Stop regular conversion using HAL_DFSDM_FilterRegularStop(), HAL_DFSDM_FilterRegularStop_IT() or HAL_DFSDM_FilterRegularStop_DMA(). *** Filter injected channels conversion *** =========================================== [..] (#) Select injected channels using HAL_DFSDM_FilterConfigInjChannel(). (#) Start injected conversion using HAL_DFSDM_FilterInjectedStart(), HAL_DFSDM_FilterInjectedStart_IT(), HAL_DFSDM_FilterInjectedStart_DMA() or HAL_DFSDM_FilterInjectedMsbStart_DMA(). (#) In polling mode, use HAL_DFSDM_FilterPollForInjConversion() to detect the end of injected conversion. (#) In interrupt mode, HAL_DFSDM_FilterInjConvCpltCallback() will be called at the end of injected conversion. (#) Get value of injected conversion and corresponding channel using HAL_DFSDM_FilterGetInjectedValue(). (#) In DMA mode, HAL_DFSDM_FilterInjConvHalfCpltCallback() and HAL_DFSDM_FilterInjConvCpltCallback() will be called respectively at the half transfer and at the transfer complete. Please note that HAL_DFSDM_FilterInjConvCpltCallback() will be called only in DMA circular mode. (#) Stop injected conversion using HAL_DFSDM_FilterInjectedStop(), HAL_DFSDM_FilterInjectedStop_IT() or HAL_DFSDM_FilterInjectedStop_DMA(). *** Filter analog watchdog *** ============================== [..] (#) Start filter analog watchdog using HAL_DFSDM_FilterAwdStart_IT(). (#) HAL_DFSDM_FilterAwdCallback() will be called if analog watchdog occurs. (#) Stop filter analog watchdog using HAL_DFSDM_FilterAwdStop_IT(). *** Filter extreme detector *** =============================== [..] (#) Start filter extreme detector using HAL_DFSDM_FilterExdStart(). (#) Get extreme detector maximum value using HAL_DFSDM_FilterGetExdMaxValue(). (#) Get extreme detector minimum value using HAL_DFSDM_FilterGetExdMinValue(). (#) Start filter extreme detector using HAL_DFSDM_FilterExdStop(). *** Filter conversion time *** ============================== [..] (#) Get conversion time value using HAL_DFSDM_FilterGetConvTimeValue(). @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ #ifdef HAL_DFSDM_MODULE_ENABLED #if defined(STM32F412Zx) || defined(STM32F412Vx) || defined(STM32F412Rx) || defined(STM32F412Cx) || defined(STM32F413xx) || defined(STM32F423xx) /** @defgroup DFSDM DFSDM * @brief DFSDM HAL driver module * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup DFSDM_Private_Define DFSDM Private Define * @{ */ #define DFSDM_CHCFGR1_CLK_DIV_OFFSET POSITION_VAL(DFSDM_CHCFGR1_CKOUTDIV) #define DFSDM_CHAWSCDR_BKSCD_OFFSET POSITION_VAL(DFSDM_CHAWSCDR_BKSCD) #define DFSDM_CHAWSCDR_FOSR_OFFSET POSITION_VAL(DFSDM_CHAWSCDR_AWFOSR) #define DFSDM_CHCFGR2_OFFSET_OFFSET POSITION_VAL(DFSDM_CHCFGR2_OFFSET) #define DFSDM_CHCFGR2_DTRBS_OFFSET POSITION_VAL(DFSDM_CHCFGR2_DTRBS) #define DFSDM_FLTFCR_FOSR_OFFSET POSITION_VAL(DFSDM_FLTFCR_FOSR) #define DFSDM_FLTCR1_MSB_RCH_OFFSET 8U #define DFSDM_FLTCR2_EXCH_OFFSET POSITION_VAL(DFSDM_FLTCR2_EXCH) #define DFSDM_FLTCR2_AWDCH_OFFSET POSITION_VAL(DFSDM_FLTCR2_AWDCH) #define DFSDM_FLTISR_CKABF_OFFSET POSITION_VAL(DFSDM_FLTISR_CKABF) #define DFSDM_FLTISR_SCDF_OFFSET POSITION_VAL(DFSDM_FLTISR_SCDF) #define DFSDM_FLTICR_CLRCKABF_OFFSET POSITION_VAL(DFSDM_FLTICR_CLRCKABF) #define DFSDM_FLTICR_CLRSCDF_OFFSET POSITION_VAL(DFSDM_FLTICR_CLRSCSDF) #define DFSDM_FLTRDATAR_DATA_OFFSET POSITION_VAL(DFSDM_FLTRDATAR_RDATA) #define DFSDM_FLTJDATAR_DATA_OFFSET POSITION_VAL(DFSDM_FLTJDATAR_JDATA) #define DFSDM_FLTAWHTR_THRESHOLD_OFFSET POSITION_VAL(DFSDM_FLTAWHTR_AWHT) #define DFSDM_FLTAWLTR_THRESHOLD_OFFSET POSITION_VAL(DFSDM_FLTAWLTR_AWLT) #define DFSDM_FLTEXMAX_DATA_OFFSET POSITION_VAL(DFSDM_FLTEXMAX_EXMAX) #define DFSDM_FLTEXMIN_DATA_OFFSET POSITION_VAL(DFSDM_FLTEXMIN_EXMIN) #define DFSDM_FLTCNVTIMR_DATA_OFFSET POSITION_VAL(DFSDM_FLTCNVTIMR_CNVCNT) #define DFSDM_FLTAWSR_HIGH_OFFSET POSITION_VAL(DFSDM_FLTAWSR_AWHTF) #define DFSDM_MSB_MASK 0xFFFF0000U #define DFSDM_LSB_MASK 0x0000FFFFU #define DFSDM_CKAB_TIMEOUT 5000U #define DFSDM1_CHANNEL_NUMBER 4U #if defined (DFSDM2_Channel0) #define DFSDM2_CHANNEL_NUMBER 8U #endif /* DFSDM2_Channel0 */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup DFSDM_Private_Variables DFSDM Private Variables * @{ */ __IO uint32_t v_dfsdm1ChannelCounter = 0U; DFSDM_Channel_HandleTypeDef* a_dfsdm1ChannelHandle[DFSDM1_CHANNEL_NUMBER] = {NULL}; #if defined (DFSDM2_Channel0) __IO uint32_t v_dfsdm2ChannelCounter = 0U; DFSDM_Channel_HandleTypeDef* a_dfsdm2ChannelHandle[DFSDM2_CHANNEL_NUMBER] = {NULL}; #endif /* DFSDM2_Channel0 */ /** * @} */ /* Private function prototypes -----------------------------------------------*/ /** @defgroup DFSDM_Private_Functions DFSDM Private Functions * @{ */ static uint32_t DFSDM_GetInjChannelsNbr(uint32_t Channels); static uint32_t DFSDM_GetChannelFromInstance(DFSDM_Channel_TypeDef* Instance); static void DFSDM_RegConvStart(DFSDM_Filter_HandleTypeDef *hdfsdm_filter); static void DFSDM_RegConvStop(DFSDM_Filter_HandleTypeDef* hdfsdm_filter); static void DFSDM_InjConvStart(DFSDM_Filter_HandleTypeDef* hdfsdm_filter); static void DFSDM_InjConvStop(DFSDM_Filter_HandleTypeDef* hdfsdm_filter); static void DFSDM_DMARegularHalfConvCplt(DMA_HandleTypeDef *hdma); static void DFSDM_DMARegularConvCplt(DMA_HandleTypeDef *hdma); static void DFSDM_DMAInjectedHalfConvCplt(DMA_HandleTypeDef *hdma); static void DFSDM_DMAInjectedConvCplt(DMA_HandleTypeDef *hdma); static void DFSDM_DMAError(DMA_HandleTypeDef *hdma); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup DFSDM_Exported_Functions DFSDM Exported Functions * @{ */ /** @defgroup DFSDM_Exported_Functions_Group1_Channel Channel initialization and de-initialization functions * @brief Channel initialization and de-initialization functions * @verbatim ============================================================================== ##### Channel initialization and de-initialization functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize the DFSDM channel. (+) De-initialize the DFSDM channel. @endverbatim * @{ */ /** * @brief Initialize the DFSDM channel according to the specified parameters * in the DFSDM_ChannelInitTypeDef structure and initialize the associated handle. * @param hdfsdm_channel : DFSDM channel handle. * @retval HAL status. */ HAL_StatusTypeDef HAL_DFSDM_ChannelInit(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { #if defined(DFSDM2_Channel0) __IO uint32_t* channelCounterPtr; DFSDM_Channel_HandleTypeDef **channelHandleTable; DFSDM_Channel_TypeDef* channel0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check DFSDM Channel handle */ if(hdfsdm_channel == NULL) { return HAL_ERROR; } /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); assert_param(IS_FUNCTIONAL_STATE(hdfsdm_channel->Init.OutputClock.Activation)); assert_param(IS_DFSDM_CHANNEL_INPUT(hdfsdm_channel->Init.Input.Multiplexer)); assert_param(IS_DFSDM_CHANNEL_DATA_PACKING(hdfsdm_channel->Init.Input.DataPacking)); assert_param(IS_DFSDM_CHANNEL_INPUT_PINS(hdfsdm_channel->Init.Input.Pins)); assert_param(IS_DFSDM_CHANNEL_SERIAL_INTERFACE_TYPE(hdfsdm_channel->Init.SerialInterface.Type)); assert_param(IS_DFSDM_CHANNEL_SPI_CLOCK(hdfsdm_channel->Init.SerialInterface.SpiClock)); assert_param(IS_DFSDM_CHANNEL_FILTER_ORDER(hdfsdm_channel->Init.Awd.FilterOrder)); assert_param(IS_DFSDM_CHANNEL_FILTER_OVS_RATIO(hdfsdm_channel->Init.Awd.Oversampling)); assert_param(IS_DFSDM_CHANNEL_OFFSET(hdfsdm_channel->Init.Offset)); assert_param(IS_DFSDM_CHANNEL_RIGHT_BIT_SHIFT(hdfsdm_channel->Init.RightBitShift)); #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { channelCounterPtr = &v_dfsdm1ChannelCounter; channelHandleTable = a_dfsdm1ChannelHandle; channel0Instance = DFSDM1_Channel0; } else { channelCounterPtr = &v_dfsdm2ChannelCounter; channelHandleTable = a_dfsdm2ChannelHandle; channel0Instance = DFSDM2_Channel0; } /* Check that channel has not been already initialized */ if(channelHandleTable[DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance)] != NULL) { return HAL_ERROR; } /* Call MSP init function */ HAL_DFSDM_ChannelMspInit(hdfsdm_channel); /* Update the channel counter */ (*channelCounterPtr)++; /* Configure output serial clock and enable global DFSDM interface only for first channel */ if(*channelCounterPtr == 1U) { assert_param(IS_DFSDM_CHANNEL_OUTPUT_CLOCK(hdfsdm_channel->Init.OutputClock.Selection)); /* Set the output serial clock source */ channel0Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_CKOUTSRC); channel0Instance->CHCFGR1 |= hdfsdm_channel->Init.OutputClock.Selection; /* Reset clock divider */ channel0Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_CKOUTDIV); if(hdfsdm_channel->Init.OutputClock.Activation == ENABLE) { assert_param(IS_DFSDM_CHANNEL_OUTPUT_CLOCK_DIVIDER(hdfsdm_channel->Init.OutputClock.Divider)); /* Set the output clock divider */ channel0Instance->CHCFGR1 |= (uint32_t) ((hdfsdm_channel->Init.OutputClock.Divider - 1U) << DFSDM_CHCFGR1_CLK_DIV_OFFSET); } /* enable the DFSDM global interface */ channel0Instance->CHCFGR1 |= DFSDM_CHCFGR1_DFSDMEN; } /* Set channel input parameters */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_DATPACK | DFSDM_CHCFGR1_DATMPX | DFSDM_CHCFGR1_CHINSEL); hdfsdm_channel->Instance->CHCFGR1 |= (hdfsdm_channel->Init.Input.Multiplexer | hdfsdm_channel->Init.Input.DataPacking | hdfsdm_channel->Init.Input.Pins); /* Set serial interface parameters */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_SITP | DFSDM_CHCFGR1_SPICKSEL); hdfsdm_channel->Instance->CHCFGR1 |= (hdfsdm_channel->Init.SerialInterface.Type | hdfsdm_channel->Init.SerialInterface.SpiClock); /* Set analog watchdog parameters */ hdfsdm_channel->Instance->CHAWSCDR &= ~(DFSDM_CHAWSCDR_AWFORD | DFSDM_CHAWSCDR_AWFOSR); hdfsdm_channel->Instance->CHAWSCDR |= (hdfsdm_channel->Init.Awd.FilterOrder | ((hdfsdm_channel->Init.Awd.Oversampling - 1U) << DFSDM_CHAWSCDR_FOSR_OFFSET)); /* Set channel offset and right bit shift */ hdfsdm_channel->Instance->CHCFGR2 &= ~(DFSDM_CHCFGR2_OFFSET | DFSDM_CHCFGR2_DTRBS); hdfsdm_channel->Instance->CHCFGR2 |= (((uint32_t) hdfsdm_channel->Init.Offset << DFSDM_CHCFGR2_OFFSET_OFFSET) | (hdfsdm_channel->Init.RightBitShift << DFSDM_CHCFGR2_DTRBS_OFFSET)); /* Enable DFSDM channel */ hdfsdm_channel->Instance->CHCFGR1 |= DFSDM_CHCFGR1_CHEN; /* Set DFSDM Channel to ready state */ hdfsdm_channel->State = HAL_DFSDM_CHANNEL_STATE_READY; /* Store channel handle in DFSDM channel handle table */ channelHandleTable[DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance)] = hdfsdm_channel; #else /* Check that channel has not been already initialized */ if(a_dfsdm1ChannelHandle[DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance)] != NULL) { return HAL_ERROR; } /* Call MSP init function */ HAL_DFSDM_ChannelMspInit(hdfsdm_channel); /* Update the channel counter */ v_dfsdm1ChannelCounter++; /* Configure output serial clock and enable global DFSDM interface only for first channel */ if(v_dfsdm1ChannelCounter == 1U) { assert_param(IS_DFSDM_CHANNEL_OUTPUT_CLOCK(hdfsdm_channel->Init.OutputClock.Selection)); /* Set the output serial clock source */ DFSDM1_Channel0->CHCFGR1 &= ~(DFSDM_CHCFGR1_CKOUTSRC); DFSDM1_Channel0->CHCFGR1 |= hdfsdm_channel->Init.OutputClock.Selection; /* Reset clock divider */ DFSDM1_Channel0->CHCFGR1 &= ~(DFSDM_CHCFGR1_CKOUTDIV); if(hdfsdm_channel->Init.OutputClock.Activation == ENABLE) { assert_param(IS_DFSDM_CHANNEL_OUTPUT_CLOCK_DIVIDER(hdfsdm_channel->Init.OutputClock.Divider)); /* Set the output clock divider */ DFSDM1_Channel0->CHCFGR1 |= (uint32_t) ((hdfsdm_channel->Init.OutputClock.Divider - 1U) << DFSDM_CHCFGR1_CLK_DIV_OFFSET); } /* enable the DFSDM global interface */ DFSDM1_Channel0->CHCFGR1 |= DFSDM_CHCFGR1_DFSDMEN; } /* Set channel input parameters */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_DATPACK | DFSDM_CHCFGR1_DATMPX | DFSDM_CHCFGR1_CHINSEL); hdfsdm_channel->Instance->CHCFGR1 |= (hdfsdm_channel->Init.Input.Multiplexer | hdfsdm_channel->Init.Input.DataPacking | hdfsdm_channel->Init.Input.Pins); /* Set serial interface parameters */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_SITP | DFSDM_CHCFGR1_SPICKSEL); hdfsdm_channel->Instance->CHCFGR1 |= (hdfsdm_channel->Init.SerialInterface.Type | hdfsdm_channel->Init.SerialInterface.SpiClock); /* Set analog watchdog parameters */ hdfsdm_channel->Instance->CHAWSCDR &= ~(DFSDM_CHAWSCDR_AWFORD | DFSDM_CHAWSCDR_AWFOSR); hdfsdm_channel->Instance->CHAWSCDR |= (hdfsdm_channel->Init.Awd.FilterOrder | ((hdfsdm_channel->Init.Awd.Oversampling - 1U) << DFSDM_CHAWSCDR_FOSR_OFFSET)); /* Set channel offset and right bit shift */ hdfsdm_channel->Instance->CHCFGR2 &= ~(DFSDM_CHCFGR2_OFFSET | DFSDM_CHCFGR2_DTRBS); hdfsdm_channel->Instance->CHCFGR2 |= (((uint32_t) hdfsdm_channel->Init.Offset << DFSDM_CHCFGR2_OFFSET_OFFSET) | (hdfsdm_channel->Init.RightBitShift << DFSDM_CHCFGR2_DTRBS_OFFSET)); /* Enable DFSDM channel */ hdfsdm_channel->Instance->CHCFGR1 |= DFSDM_CHCFGR1_CHEN; /* Set DFSDM Channel to ready state */ hdfsdm_channel->State = HAL_DFSDM_CHANNEL_STATE_READY; /* Store channel handle in DFSDM channel handle table */ a_dfsdm1ChannelHandle[DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance)] = hdfsdm_channel; #endif /* DFSDM2_Channel0 */ return HAL_OK; } /** * @brief De-initialize the DFSDM channel. * @param hdfsdm_channel : DFSDM channel handle. * @retval HAL status. */ HAL_StatusTypeDef HAL_DFSDM_ChannelDeInit(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { #if defined(DFSDM2_Channel0) __IO uint32_t* channelCounterPtr; DFSDM_Channel_HandleTypeDef **channelHandleTable; DFSDM_Channel_TypeDef* channel0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check DFSDM Channel handle */ if(hdfsdm_channel == NULL) { return HAL_ERROR; } /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { channelCounterPtr = &v_dfsdm1ChannelCounter; channelHandleTable = a_dfsdm1ChannelHandle; channel0Instance = DFSDM1_Channel0; } else { channelCounterPtr = &v_dfsdm2ChannelCounter; channelHandleTable = a_dfsdm2ChannelHandle; channel0Instance = DFSDM2_Channel0; } /* Check that channel has not been already deinitialized */ if(channelHandleTable[DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance)] == NULL) { return HAL_ERROR; } /* Disable the DFSDM channel */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_CHEN); /* Update the channel counter */ (*channelCounterPtr)--; /* Disable global DFSDM at deinit of last channel */ if(*channelCounterPtr == 0U) { channel0Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_DFSDMEN); } /* Call MSP deinit function */ HAL_DFSDM_ChannelMspDeInit(hdfsdm_channel); /* Set DFSDM Channel in reset state */ hdfsdm_channel->State = HAL_DFSDM_CHANNEL_STATE_RESET; /* Reset channel handle in DFSDM channel handle table */ channelHandleTable[DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance)] = NULL; #else /* Check that channel has not been already deinitialized */ if(a_dfsdm1ChannelHandle[DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance)] == NULL) { return HAL_ERROR; } /* Disable the DFSDM channel */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_CHEN); /* Update the channel counter */ v_dfsdm1ChannelCounter--; /* Disable global DFSDM at deinit of last channel */ if(v_dfsdm1ChannelCounter == 0U) { DFSDM1_Channel0->CHCFGR1 &= ~(DFSDM_CHCFGR1_DFSDMEN); } /* Call MSP deinit function */ HAL_DFSDM_ChannelMspDeInit(hdfsdm_channel); /* Set DFSDM Channel in reset state */ hdfsdm_channel->State = HAL_DFSDM_CHANNEL_STATE_RESET; /* Reset channel handle in DFSDM channel handle table */ a_dfsdm1ChannelHandle[DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance)] = (DFSDM_Channel_HandleTypeDef *) NULL; #endif /* defined(DFSDM2_Channel0) */ return HAL_OK; } /** * @brief Initialize the DFSDM channel MSP. * @param hdfsdm_channel : DFSDM channel handle. * @retval None */ __weak void HAL_DFSDM_ChannelMspInit(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_channel); /* NOTE : This function should not be modified, when the function is needed, the HAL_DFSDM_ChannelMspInit could be implemented in the user file. */ } /** * @brief De-initialize the DFSDM channel MSP. * @param hdfsdm_channel : DFSDM channel handle. * @retval None */ __weak void HAL_DFSDM_ChannelMspDeInit(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_channel); /* NOTE : This function should not be modified, when the function is needed, the HAL_DFSDM_ChannelMspDeInit could be implemented in the user file. */ } /** * @} */ /** @defgroup DFSDM_Exported_Functions_Group2_Channel Channel operation functions * @brief Channel operation functions * @verbatim ============================================================================== ##### Channel operation functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Manage clock absence detector feature. (+) Manage short circuit detector feature. (+) Get analog watchdog value. (+) Modify offset value. @endverbatim * @{ */ /** * @brief This function allows to start clock absence detection in polling mode. * @note Same mode has to be used for all channels. * @note If clock is not available on this channel during 5 seconds, * clock absence detection will not be activated and function * will return HAL_TIMEOUT error. * @param hdfsdm_channel : DFSDM channel handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelCkabStart(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t tickstart; uint32_t channel; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { #if defined (DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } /* Get channel number from channel instance */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); /* Get timeout */ tickstart = HAL_GetTick(); /* Clear clock absence flag */ while((((filter0Instance->FLTISR & DFSDM_FLTISR_CKABF) >> (DFSDM_FLTISR_CKABF_OFFSET + channel)) & 1U) != 0U) { filter0Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); /* Check the Timeout */ if((HAL_GetTick()-tickstart) > DFSDM_CKAB_TIMEOUT) { /* Set timeout status */ status = HAL_TIMEOUT; break; } } #else /* Get channel number from channel instance */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); /* Get timeout */ tickstart = HAL_GetTick(); /* Clear clock absence flag */ while((((DFSDM1_Filter0->FLTISR & DFSDM_FLTISR_CKABF) >> (DFSDM_FLTISR_CKABF_OFFSET + channel)) & 1U) != 0U) { DFSDM1_Filter0->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); /* Check the Timeout */ if((HAL_GetTick()-tickstart) > DFSDM_CKAB_TIMEOUT) { /* Set timeout status */ status = HAL_TIMEOUT; break; } } #endif /* DFSDM2_Channel0 */ if(status == HAL_OK) { /* Start clock absence detection */ hdfsdm_channel->Instance->CHCFGR1 |= DFSDM_CHCFGR1_CKABEN; } } /* Return function status */ return status; } /** * @brief This function allows to poll for the clock absence detection. * @param hdfsdm_channel : DFSDM channel handle. * @param Timeout : Timeout value in milliseconds. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelPollForCkab(DFSDM_Channel_HandleTypeDef *hdfsdm_channel, uint32_t Timeout) { uint32_t tickstart; uint32_t channel; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ return HAL_ERROR; } else { #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } /* Get channel number from channel instance */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); /* Get timeout */ tickstart = HAL_GetTick(); /* Wait clock absence detection */ while((((filter0Instance->FLTISR & DFSDM_FLTISR_CKABF) >> (DFSDM_FLTISR_CKABF_OFFSET + channel)) & 1U) == 0U) { /* Check the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) { /* Return timeout status */ return HAL_TIMEOUT; } } } /* Clear clock absence detection flag */ filter0Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); #else /* Get channel number from channel instance */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); /* Get timeout */ tickstart = HAL_GetTick(); /* Wait clock absence detection */ while((((DFSDM1_Filter0->FLTISR & DFSDM_FLTISR_CKABF) >> (DFSDM_FLTISR_CKABF_OFFSET + channel)) & 1U) == 0U) { /* Check the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) { /* Return timeout status */ return HAL_TIMEOUT; } } } /* Clear clock absence detection flag */ DFSDM1_Filter0->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); #endif /* defined(DFSDM2_Channel0) */ /* Return function status */ return HAL_OK; } } /** * @brief This function allows to stop clock absence detection in polling mode. * @param hdfsdm_channel : DFSDM channel handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelCkabStop(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t channel; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } /* Stop clock absence detection */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_CKABEN); /* Clear clock absence flag */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); filter0Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); #else /* Stop clock absence detection */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_CKABEN); /* Clear clock absence flag */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); DFSDM1_Filter0->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); #endif /* DFSDM2_Channel0 */ } /* Return function status */ return status; } /** * @brief This function allows to start clock absence detection in interrupt mode. * @note Same mode has to be used for all channels. * @note If clock is not available on this channel during 5 seconds, * clock absence detection will not be activated and function * will return HAL_TIMEOUT error. * @param hdfsdm_channel : DFSDM channel handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelCkabStart_IT(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t channel; uint32_t tickstart; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } /* Get channel number from channel instance */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); /* Get timeout */ tickstart = HAL_GetTick(); /* Clear clock absence flag */ while((((filter0Instance->FLTISR & DFSDM_FLTISR_CKABF) >> (DFSDM_FLTISR_CKABF_OFFSET + channel)) & 1U) != 0U) { filter0Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); /* Check the Timeout */ if((HAL_GetTick()-tickstart) > DFSDM_CKAB_TIMEOUT) { /* Set timeout status */ status = HAL_TIMEOUT; break; } } if(status == HAL_OK) { /* Activate clock absence detection interrupt */ filter0Instance->FLTCR2 |= DFSDM_FLTCR2_CKABIE; /* Start clock absence detection */ hdfsdm_channel->Instance->CHCFGR1 |= DFSDM_CHCFGR1_CKABEN; } #else /* Get channel number from channel instance */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); /* Get timeout */ tickstart = HAL_GetTick(); /* Clear clock absence flag */ while((((DFSDM1_Filter0->FLTISR & DFSDM_FLTISR_CKABF) >> (DFSDM_FLTISR_CKABF_OFFSET + channel)) & 1U) != 0U) { DFSDM1_Filter0->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); /* Check the Timeout */ if((HAL_GetTick()-tickstart) > DFSDM_CKAB_TIMEOUT) { /* Set timeout status */ status = HAL_TIMEOUT; break; } } if(status == HAL_OK) { /* Activate clock absence detection interrupt */ DFSDM1_Filter0->FLTCR2 |= DFSDM_FLTCR2_CKABIE; /* Start clock absence detection */ hdfsdm_channel->Instance->CHCFGR1 |= DFSDM_CHCFGR1_CKABEN; } #endif /* defined(DFSDM2_Channel0) */ } /* Return function status */ return status; } /** * @brief Clock absence detection callback. * @param hdfsdm_channel : DFSDM channel handle. * @retval None */ __weak void HAL_DFSDM_ChannelCkabCallback(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_channel); /* NOTE : This function should not be modified, when the callback is needed, the HAL_DFSDM_ChannelCkabCallback could be implemented in the user file */ } /** * @brief This function allows to stop clock absence detection in interrupt mode. * @note Interrupt will be disabled for all channels * @param hdfsdm_channel : DFSDM channel handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelCkabStop_IT(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t channel; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } /* Stop clock absence detection */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_CKABEN); /* Clear clock absence flag */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); filter0Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); /* Disable clock absence detection interrupt */ filter0Instance->FLTCR2 &= ~(DFSDM_FLTCR2_CKABIE); #else /* Stop clock absence detection */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_CKABEN); /* Clear clock absence flag */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); DFSDM1_Filter0->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); /* Disable clock absence detection interrupt */ DFSDM1_Filter0->FLTCR2 &= ~(DFSDM_FLTCR2_CKABIE); #endif /* DFSDM2_Channel0 */ } /* Return function status */ return status; } /** * @brief This function allows to start short circuit detection in polling mode. * @note Same mode has to be used for all channels * @param hdfsdm_channel : DFSDM channel handle. * @param Threshold : Short circuit detector threshold. * This parameter must be a number between Min_Data = 0 and Max_Data = 255. * @param BreakSignal : Break signals assigned to short circuit event. * This parameter can be a values combination of @ref DFSDM_BreakSignals. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelScdStart(DFSDM_Channel_HandleTypeDef *hdfsdm_channel, uint32_t Threshold, uint32_t BreakSignal) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); assert_param(IS_DFSDM_CHANNEL_SCD_THRESHOLD(Threshold)); assert_param(IS_DFSDM_BREAK_SIGNALS(BreakSignal)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { /* Configure threshold and break signals */ hdfsdm_channel->Instance->CHAWSCDR &= ~(DFSDM_CHAWSCDR_BKSCD | DFSDM_CHAWSCDR_SCDT); hdfsdm_channel->Instance->CHAWSCDR |= ((BreakSignal << DFSDM_CHAWSCDR_BKSCD_OFFSET) | \ Threshold); /* Start short circuit detection */ hdfsdm_channel->Instance->CHCFGR1 |= DFSDM_CHCFGR1_SCDEN; } /* Return function status */ return status; } /** * @brief This function allows to poll for the short circuit detection. * @param hdfsdm_channel : DFSDM channel handle. * @param Timeout : Timeout value in milliseconds. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelPollForScd(DFSDM_Channel_HandleTypeDef *hdfsdm_channel, uint32_t Timeout) { uint32_t tickstart; uint32_t channel; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ return HAL_ERROR; } else { /* Get channel number from channel instance */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } /* Get timeout */ tickstart = HAL_GetTick(); /* Wait short circuit detection */ while(((filter0Instance->FLTISR & DFSDM_FLTISR_SCDF) >> (DFSDM_FLTISR_SCDF_OFFSET + channel)) == 0U) { /* Check the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) { /* Return timeout status */ return HAL_TIMEOUT; } } } /* Clear short circuit detection flag */ filter0Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRSCDF_OFFSET + channel)); #else /* Get timeout */ tickstart = HAL_GetTick(); /* Wait short circuit detection */ while(((DFSDM1_Filter0->FLTISR & DFSDM_FLTISR_SCDF) >> (DFSDM_FLTISR_SCDF_OFFSET + channel)) == 0U) { /* Check the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) { /* Return timeout status */ return HAL_TIMEOUT; } } } /* Clear short circuit detection flag */ DFSDM1_Filter0->FLTICR = (1U << (DFSDM_FLTICR_CLRSCDF_OFFSET + channel)); #endif /* DFSDM2_Channel0 */ /* Return function status */ return HAL_OK; } } /** * @brief This function allows to stop short circuit detection in polling mode. * @param hdfsdm_channel : DFSDM channel handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelScdStop(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t channel; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { /* Stop short circuit detection */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_SCDEN); /* Clear short circuit detection flag */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } filter0Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRSCDF_OFFSET + channel)); #else DFSDM1_Filter0->FLTICR = (1U << (DFSDM_FLTICR_CLRSCDF_OFFSET + channel)); #endif /* DFSDM2_Channel0*/ } /* Return function status */ return status; } /** * @brief This function allows to start short circuit detection in interrupt mode. * @note Same mode has to be used for all channels * @param hdfsdm_channel : DFSDM channel handle. * @param Threshold : Short circuit detector threshold. * This parameter must be a number between Min_Data = 0 and Max_Data = 255. * @param BreakSignal : Break signals assigned to short circuit event. * This parameter can be a values combination of @ref DFSDM_BreakSignals. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelScdStart_IT(DFSDM_Channel_HandleTypeDef *hdfsdm_channel, uint32_t Threshold, uint32_t BreakSignal) { HAL_StatusTypeDef status = HAL_OK; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); assert_param(IS_DFSDM_CHANNEL_SCD_THRESHOLD(Threshold)); assert_param(IS_DFSDM_BREAK_SIGNALS(BreakSignal)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } /* Activate short circuit detection interrupt */ filter0Instance->FLTCR2 |= DFSDM_FLTCR2_SCDIE; #else /* Activate short circuit detection interrupt */ DFSDM1_Filter0->FLTCR2 |= DFSDM_FLTCR2_SCDIE; #endif /* DFSDM2_Channel0 */ /* Configure threshold and break signals */ hdfsdm_channel->Instance->CHAWSCDR &= ~(DFSDM_CHAWSCDR_BKSCD | DFSDM_CHAWSCDR_SCDT); hdfsdm_channel->Instance->CHAWSCDR |= ((BreakSignal << DFSDM_CHAWSCDR_BKSCD_OFFSET) | \ Threshold); /* Start short circuit detection */ hdfsdm_channel->Instance->CHCFGR1 |= DFSDM_CHCFGR1_SCDEN; } /* Return function status */ return status; } /** * @brief Short circuit detection callback. * @param hdfsdm_channel : DFSDM channel handle. * @retval None */ __weak void HAL_DFSDM_ChannelScdCallback(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_channel); /* NOTE : This function should not be modified, when the callback is needed, the HAL_DFSDM_ChannelScdCallback could be implemented in the user file */ } /** * @brief This function allows to stop short circuit detection in interrupt mode. * @note Interrupt will be disabled for all channels * @param hdfsdm_channel : DFSDM channel handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_ChannelScdStop_IT(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { HAL_StatusTypeDef status = HAL_OK; uint32_t channel; #if defined(DFSDM2_Channel0) DFSDM_Filter_TypeDef* filter0Instance; #endif /* defined(DFSDM2_Channel0) */ /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { /* Stop short circuit detection */ hdfsdm_channel->Instance->CHCFGR1 &= ~(DFSDM_CHCFGR1_SCDEN); /* Clear short circuit detection flag */ channel = DFSDM_GetChannelFromInstance(hdfsdm_channel->Instance); #if defined(DFSDM2_Channel0) /* Get channel counter, channel handle table and channel 0 instance */ if(IS_DFSDM1_CHANNEL_INSTANCE(hdfsdm_channel->Instance)) { filter0Instance = DFSDM1_Filter0; } else { filter0Instance = DFSDM2_Filter0; } filter0Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRSCDF_OFFSET + channel)); /* Disable short circuit detection interrupt */ filter0Instance->FLTCR2 &= ~(DFSDM_FLTCR2_SCDIE); #else DFSDM1_Filter0->FLTICR = (1U << (DFSDM_FLTICR_CLRSCDF_OFFSET + channel)); /* Disable short circuit detection interrupt */ DFSDM1_Filter0->FLTCR2 &= ~(DFSDM_FLTCR2_SCDIE); #endif /* DFSDM2_Channel0 */ } /* Return function status */ return status; } /** * @brief This function allows to get channel analog watchdog value. * @param hdfsdm_channel : DFSDM channel handle. * @retval Channel analog watchdog value. */ int16_t HAL_DFSDM_ChannelGetAwdValue(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { return (int16_t) hdfsdm_channel->Instance->CHWDATAR; } /** * @brief This function allows to modify channel offset value. * @param hdfsdm_channel : DFSDM channel handle. * @param Offset : DFSDM channel offset. * This parameter must be a number between Min_Data = -8388608 and Max_Data = 8388607. * @retval HAL status. */ HAL_StatusTypeDef HAL_DFSDM_ChannelModifyOffset(DFSDM_Channel_HandleTypeDef *hdfsdm_channel, int32_t Offset) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_CHANNEL_ALL_INSTANCE(hdfsdm_channel->Instance)); assert_param(IS_DFSDM_CHANNEL_OFFSET(Offset)); /* Check DFSDM channel state */ if(hdfsdm_channel->State != HAL_DFSDM_CHANNEL_STATE_READY) { /* Return error status */ status = HAL_ERROR; } else { /* Modify channel offset */ hdfsdm_channel->Instance->CHCFGR2 &= ~(DFSDM_CHCFGR2_OFFSET); hdfsdm_channel->Instance->CHCFGR2 |= ((uint32_t) Offset << DFSDM_CHCFGR2_OFFSET_OFFSET); } /* Return function status */ return status; } /** * @} */ /** @defgroup DFSDM_Exported_Functions_Group3_Channel Channel state function * @brief Channel state function * @verbatim ============================================================================== ##### Channel state function ##### ============================================================================== [..] This section provides function allowing to: (+) Get channel handle state. @endverbatim * @{ */ /** * @brief This function allows to get the current DFSDM channel handle state. * @param hdfsdm_channel : DFSDM channel handle. * @retval DFSDM channel state. */ HAL_DFSDM_Channel_StateTypeDef HAL_DFSDM_ChannelGetState(DFSDM_Channel_HandleTypeDef *hdfsdm_channel) { /* Return DFSDM channel handle state */ return hdfsdm_channel->State; } /** * @} */ /** @defgroup DFSDM_Exported_Functions_Group1_Filter Filter initialization and de-initialization functions * @brief Filter initialization and de-initialization functions * @verbatim ============================================================================== ##### Filter initialization and de-initialization functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Initialize the DFSDM filter. (+) De-initialize the DFSDM filter. @endverbatim * @{ */ /** * @brief Initialize the DFSDM filter according to the specified parameters * in the DFSDM_FilterInitTypeDef structure and initialize the associated handle. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status. */ HAL_StatusTypeDef HAL_DFSDM_FilterInit(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Check DFSDM Channel handle */ if(hdfsdm_filter == NULL) { return HAL_ERROR; } /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(IS_DFSDM_FILTER_REG_TRIGGER(hdfsdm_filter->Init.RegularParam.Trigger)); assert_param(IS_FUNCTIONAL_STATE(hdfsdm_filter->Init.RegularParam.FastMode)); assert_param(IS_FUNCTIONAL_STATE(hdfsdm_filter->Init.RegularParam.DmaMode)); assert_param(IS_DFSDM_FILTER_INJ_TRIGGER(hdfsdm_filter->Init.InjectedParam.Trigger)); assert_param(IS_FUNCTIONAL_STATE(hdfsdm_filter->Init.InjectedParam.ScanMode)); assert_param(IS_FUNCTIONAL_STATE(hdfsdm_filter->Init.InjectedParam.DmaMode)); assert_param(IS_DFSDM_FILTER_SINC_ORDER(hdfsdm_filter->Init.FilterParam.SincOrder)); assert_param(IS_DFSDM_FILTER_OVS_RATIO(hdfsdm_filter->Init.FilterParam.Oversampling)); assert_param(IS_DFSDM_FILTER_INTEGRATOR_OVS_RATIO(hdfsdm_filter->Init.FilterParam.IntOversampling)); /* Check parameters compatibility */ if((hdfsdm_filter->Instance == DFSDM1_Filter0) && ((hdfsdm_filter->Init.RegularParam.Trigger == DFSDM_FILTER_SYNC_TRIGGER) || (hdfsdm_filter->Init.InjectedParam.Trigger == DFSDM_FILTER_SYNC_TRIGGER))) { return HAL_ERROR; } #if defined (DFSDM2_Channel0) if((hdfsdm_filter->Instance == DFSDM2_Filter0) && ((hdfsdm_filter->Init.RegularParam.Trigger == DFSDM_FILTER_SYNC_TRIGGER) || (hdfsdm_filter->Init.InjectedParam.Trigger == DFSDM_FILTER_SYNC_TRIGGER))) { return HAL_ERROR; } #endif /* DFSDM2_Channel0 */ /* Initialize DFSDM filter variables with default values */ hdfsdm_filter->RegularContMode = DFSDM_CONTINUOUS_CONV_OFF; hdfsdm_filter->InjectedChannelsNbr = 1U; hdfsdm_filter->InjConvRemaining = 1U; hdfsdm_filter->ErrorCode = DFSDM_FILTER_ERROR_NONE; /* Call MSP init function */ HAL_DFSDM_FilterMspInit(hdfsdm_filter); /* Set regular parameters */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_RSYNC); if(hdfsdm_filter->Init.RegularParam.FastMode == ENABLE) { hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_FAST; } else { hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_FAST); } if(hdfsdm_filter->Init.RegularParam.DmaMode == ENABLE) { hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_RDMAEN; } else { hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_RDMAEN); } /* Set injected parameters */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_JSYNC | DFSDM_FLTCR1_JEXTEN | DFSDM_FLTCR1_JEXTSEL); if(hdfsdm_filter->Init.InjectedParam.Trigger == DFSDM_FILTER_EXT_TRIGGER) { assert_param(IS_DFSDM_FILTER_EXT_TRIG(hdfsdm_filter->Init.InjectedParam.ExtTrigger)); assert_param(IS_DFSDM_FILTER_EXT_TRIG_EDGE(hdfsdm_filter->Init.InjectedParam.ExtTriggerEdge)); hdfsdm_filter->Instance->FLTCR1 |= (hdfsdm_filter->Init.InjectedParam.ExtTrigger); } if(hdfsdm_filter->Init.InjectedParam.ScanMode == ENABLE) { hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_JSCAN; } else { hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_JSCAN); } if(hdfsdm_filter->Init.InjectedParam.DmaMode == ENABLE) { hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_JDMAEN; } else { hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_JDMAEN); } /* Set filter parameters */ hdfsdm_filter->Instance->FLTFCR &= ~(DFSDM_FLTFCR_FORD | DFSDM_FLTFCR_FOSR | DFSDM_FLTFCR_IOSR); hdfsdm_filter->Instance->FLTFCR |= (hdfsdm_filter->Init.FilterParam.SincOrder | ((hdfsdm_filter->Init.FilterParam.Oversampling - 1U) << DFSDM_FLTFCR_FOSR_OFFSET) | (hdfsdm_filter->Init.FilterParam.IntOversampling - 1U)); /* Store regular and injected triggers and injected scan mode*/ hdfsdm_filter->RegularTrigger = hdfsdm_filter->Init.RegularParam.Trigger; hdfsdm_filter->InjectedTrigger = hdfsdm_filter->Init.InjectedParam.Trigger; hdfsdm_filter->ExtTriggerEdge = hdfsdm_filter->Init.InjectedParam.ExtTriggerEdge; hdfsdm_filter->InjectedScanMode = hdfsdm_filter->Init.InjectedParam.ScanMode; /* Enable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_DFEN; /* Set DFSDM filter to ready state */ hdfsdm_filter->State = HAL_DFSDM_FILTER_STATE_READY; return HAL_OK; } /** * @brief De-initializes the DFSDM filter. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status. */ HAL_StatusTypeDef HAL_DFSDM_FilterDeInit(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Check DFSDM filter handle */ if(hdfsdm_filter == NULL) { return HAL_ERROR; } /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Disable the DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_DFEN); /* Call MSP deinit function */ HAL_DFSDM_FilterMspDeInit(hdfsdm_filter); /* Set DFSDM filter in reset state */ hdfsdm_filter->State = HAL_DFSDM_FILTER_STATE_RESET; return HAL_OK; } /** * @brief Initializes the DFSDM filter MSP. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ __weak void HAL_DFSDM_FilterMspInit(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_filter); /* NOTE : This function should not be modified, when the function is needed, the HAL_DFSDM_FilterMspInit could be implemented in the user file. */ } /** * @brief De-initializes the DFSDM filter MSP. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ __weak void HAL_DFSDM_FilterMspDeInit(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_filter); /* NOTE : This function should not be modified, when the function is needed, the HAL_DFSDM_FilterMspDeInit could be implemented in the user file. */ } /** * @} */ /** @defgroup DFSDM_Exported_Functions_Group2_Filter Filter control functions * @brief Filter control functions * @verbatim ============================================================================== ##### Filter control functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Select channel and enable/disable continuous mode for regular conversion. (+) Select channels for injected conversion. @endverbatim * @{ */ /** * @brief This function allows to select channel and to enable/disable * continuous mode for regular conversion. * @param hdfsdm_filter : DFSDM filter handle. * @param Channel : Channel for regular conversion. * This parameter can be a value of @ref DFSDM_Channel_Selection. * @param ContinuousMode : Enable/disable continuous mode for regular conversion. * This parameter can be a value of @ref DFSDM_ContinuousMode. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterConfigRegChannel(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t Channel, uint32_t ContinuousMode) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(IS_DFSDM_REGULAR_CHANNEL(Channel)); assert_param(IS_DFSDM_CONTINUOUS_MODE(ContinuousMode)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_RESET) && (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_ERROR)) { /* Configure channel and continuous mode for regular conversion */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_RCH | DFSDM_FLTCR1_RCONT); if(ContinuousMode == DFSDM_CONTINUOUS_CONV_ON) { hdfsdm_filter->Instance->FLTCR1 |= (uint32_t) (((Channel & DFSDM_MSB_MASK) << DFSDM_FLTCR1_MSB_RCH_OFFSET) | DFSDM_FLTCR1_RCONT); } else { hdfsdm_filter->Instance->FLTCR1 |= (uint32_t) ((Channel & DFSDM_MSB_MASK) << DFSDM_FLTCR1_MSB_RCH_OFFSET); } /* Store continuous mode information */ hdfsdm_filter->RegularContMode = ContinuousMode; } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to select channels for injected conversion. * @param hdfsdm_filter : DFSDM filter handle. * @param Channel : Channels for injected conversion. * This parameter can be a values combination of @ref DFSDM_Channel_Selection. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterConfigInjChannel(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(IS_DFSDM_INJECTED_CHANNEL(Channel)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_RESET) && (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_ERROR)) { /* Configure channel for injected conversion */ hdfsdm_filter->Instance->FLTJCHGR = (uint32_t) (Channel & DFSDM_LSB_MASK); /* Store number of injected channels */ hdfsdm_filter->InjectedChannelsNbr = DFSDM_GetInjChannelsNbr(Channel); /* Update number of injected channels remaining */ hdfsdm_filter->InjConvRemaining = (hdfsdm_filter->InjectedScanMode == ENABLE) ? \ hdfsdm_filter->InjectedChannelsNbr : 1U; } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @} */ /** @defgroup DFSDM_Exported_Functions_Group3_Filter Filter operation functions * @brief Filter operation functions * @verbatim ============================================================================== ##### Filter operation functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Start conversion of regular/injected channel. (+) Poll for the end of regular/injected conversion. (+) Stop conversion of regular/injected channel. (+) Start conversion of regular/injected channel and enable interrupt. (+) Call the callback functions at the end of regular/injected conversions. (+) Stop conversion of regular/injected channel and disable interrupt. (+) Start conversion of regular/injected channel and enable DMA transfer. (+) Stop conversion of regular/injected channel and disable DMA transfer. (+) Start analog watchdog and enable interrupt. (+) Call the callback function when analog watchdog occurs. (+) Stop analog watchdog and disable interrupt. (+) Start extreme detector. (+) Stop extreme detector. (+) Get result of regular channel conversion. (+) Get result of injected channel conversion. (+) Get extreme detector maximum and minimum values. (+) Get conversion time. (+) Handle DFSDM interrupt request. @endverbatim * @{ */ /** * @brief This function allows to start regular conversion in polling mode. * @note This function should be called only when DFSDM filter instance is * in idle state or if injected conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterRegularStart(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_INJ)) { /* Start regular conversion */ DFSDM_RegConvStart(hdfsdm_filter); } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to poll for the end of regular conversion. * @note This function should be called only if regular conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @param Timeout : Timeout value in milliseconds. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterPollForRegConversion(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t Timeout) { uint32_t tickstart; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG) && \ (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG_INJ)) { /* Return error status */ return HAL_ERROR; } else { /* Get timeout */ tickstart = HAL_GetTick(); /* Wait end of regular conversion */ while((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_REOCF) != DFSDM_FLTISR_REOCF) { /* Check the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) { /* Return timeout status */ return HAL_TIMEOUT; } } } /* Check if overrun occurs */ if((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_ROVRF) == DFSDM_FLTISR_ROVRF) { /* Update error code and call error callback */ hdfsdm_filter->ErrorCode = DFSDM_FILTER_ERROR_REGULAR_OVERRUN; HAL_DFSDM_FilterErrorCallback(hdfsdm_filter); /* Clear regular overrun flag */ hdfsdm_filter->Instance->FLTICR = DFSDM_FLTICR_CLRROVRF; } /* Update DFSDM filter state only if not continuous conversion and SW trigger */ if((hdfsdm_filter->RegularContMode == DFSDM_CONTINUOUS_CONV_OFF) && \ (hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER)) { hdfsdm_filter->State = (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG) ? \ HAL_DFSDM_FILTER_STATE_READY : HAL_DFSDM_FILTER_STATE_INJ; } /* Return function status */ return HAL_OK; } } /** * @brief This function allows to stop regular conversion in polling mode. * @note This function should be called only if regular conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterRegularStop(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG) && \ (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG_INJ)) { /* Return error status */ status = HAL_ERROR; } else { /* Stop regular conversion */ DFSDM_RegConvStop(hdfsdm_filter); } /* Return function status */ return status; } /** * @brief This function allows to start regular conversion in interrupt mode. * @note This function should be called only when DFSDM filter instance is * in idle state or if injected conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterRegularStart_IT(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_INJ)) { /* Enable interrupts for regular conversions */ hdfsdm_filter->Instance->FLTCR2 |= (DFSDM_FLTCR2_REOCIE | DFSDM_FLTCR2_ROVRIE); /* Start regular conversion */ DFSDM_RegConvStart(hdfsdm_filter); } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to stop regular conversion in interrupt mode. * @note This function should be called only if regular conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterRegularStop_IT(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG) && \ (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG_INJ)) { /* Return error status */ status = HAL_ERROR; } else { /* Disable interrupts for regular conversions */ hdfsdm_filter->Instance->FLTCR2 &= ~(DFSDM_FLTCR2_REOCIE | DFSDM_FLTCR2_ROVRIE); /* Stop regular conversion */ DFSDM_RegConvStop(hdfsdm_filter); } /* Return function status */ return status; } /** * @brief This function allows to start regular conversion in DMA mode. * @note This function should be called only when DFSDM filter instance is * in idle state or if injected conversion is ongoing. * Please note that data on buffer will contain signed regular conversion * value on 24 most significant bits and corresponding channel on 3 least * significant bits. * @param hdfsdm_filter : DFSDM filter handle. * @param pData : The destination buffer address. * @param Length : The length of data to be transferred from DFSDM filter to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterRegularStart_DMA(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, int32_t *pData, uint32_t Length) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check destination address and length */ if((pData == NULL) || (Length == 0U)) { status = HAL_ERROR; } /* Check that DMA is enabled for regular conversion */ else if((hdfsdm_filter->Instance->FLTCR1 & DFSDM_FLTCR1_RDMAEN) != DFSDM_FLTCR1_RDMAEN) { status = HAL_ERROR; } /* Check parameters compatibility */ else if((hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER) && \ (hdfsdm_filter->RegularContMode == DFSDM_CONTINUOUS_CONV_OFF) && \ (hdfsdm_filter->hdmaReg->Init.Mode == DMA_NORMAL) && \ (Length != 1U)) { status = HAL_ERROR; } else if((hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER) && \ (hdfsdm_filter->RegularContMode == DFSDM_CONTINUOUS_CONV_OFF) && \ (hdfsdm_filter->hdmaReg->Init.Mode == DMA_CIRCULAR)) { status = HAL_ERROR; } /* Check DFSDM filter state */ else if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_INJ)) { /* Set callbacks on DMA handler */ hdfsdm_filter->hdmaReg->XferCpltCallback = DFSDM_DMARegularConvCplt; hdfsdm_filter->hdmaReg->XferErrorCallback = DFSDM_DMAError; hdfsdm_filter->hdmaReg->XferHalfCpltCallback = (hdfsdm_filter->hdmaReg->Init.Mode == DMA_CIRCULAR) ?\ DFSDM_DMARegularHalfConvCplt : NULL; /* Start DMA in interrupt mode */ if(HAL_DMA_Start_IT(hdfsdm_filter->hdmaReg, (uint32_t)&hdfsdm_filter->Instance->FLTRDATAR, \ (uint32_t) pData, Length) != HAL_OK) { /* Set DFSDM filter in error state */ hdfsdm_filter->State = HAL_DFSDM_FILTER_STATE_ERROR; status = HAL_ERROR; } else { /* Start regular conversion */ DFSDM_RegConvStart(hdfsdm_filter); } } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to start regular conversion in DMA mode and to get * only the 16 most significant bits of conversion. * @note This function should be called only when DFSDM filter instance is * in idle state or if injected conversion is ongoing. * Please note that data on buffer will contain signed 16 most significant * bits of regular conversion. * @param hdfsdm_filter : DFSDM filter handle. * @param pData : The destination buffer address. * @param Length : The length of data to be transferred from DFSDM filter to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterRegularMsbStart_DMA(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, int16_t *pData, uint32_t Length) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check destination address and length */ if((pData == NULL) || (Length == 0U)) { status = HAL_ERROR; } /* Check that DMA is enabled for regular conversion */ else if((hdfsdm_filter->Instance->FLTCR1 & DFSDM_FLTCR1_RDMAEN) != DFSDM_FLTCR1_RDMAEN) { status = HAL_ERROR; } /* Check parameters compatibility */ else if((hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER) && \ (hdfsdm_filter->RegularContMode == DFSDM_CONTINUOUS_CONV_OFF) && \ (hdfsdm_filter->hdmaReg->Init.Mode == DMA_NORMAL) && \ (Length != 1U)) { status = HAL_ERROR; } else if((hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER) && \ (hdfsdm_filter->RegularContMode == DFSDM_CONTINUOUS_CONV_OFF) && \ (hdfsdm_filter->hdmaReg->Init.Mode == DMA_CIRCULAR)) { status = HAL_ERROR; } /* Check DFSDM filter state */ else if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_INJ)) { /* Set callbacks on DMA handler */ hdfsdm_filter->hdmaReg->XferCpltCallback = DFSDM_DMARegularConvCplt; hdfsdm_filter->hdmaReg->XferErrorCallback = DFSDM_DMAError; hdfsdm_filter->hdmaReg->XferHalfCpltCallback = (hdfsdm_filter->hdmaReg->Init.Mode == DMA_CIRCULAR) ?\ DFSDM_DMARegularHalfConvCplt : NULL; /* Start DMA in interrupt mode */ if(HAL_DMA_Start_IT(hdfsdm_filter->hdmaReg, (uint32_t)(&hdfsdm_filter->Instance->FLTRDATAR) + 2U, \ (uint32_t) pData, Length) != HAL_OK) { /* Set DFSDM filter in error state */ hdfsdm_filter->State = HAL_DFSDM_FILTER_STATE_ERROR; status = HAL_ERROR; } else { /* Start regular conversion */ DFSDM_RegConvStart(hdfsdm_filter); } } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to stop regular conversion in DMA mode. * @note This function should be called only if regular conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterRegularStop_DMA(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG) && \ (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG_INJ)) { /* Return error status */ status = HAL_ERROR; } else { /* Stop current DMA transfer */ if(HAL_DMA_Abort(hdfsdm_filter->hdmaReg) != HAL_OK) { /* Set DFSDM filter in error state */ hdfsdm_filter->State = HAL_DFSDM_FILTER_STATE_ERROR; status = HAL_ERROR; } else { /* Stop regular conversion */ DFSDM_RegConvStop(hdfsdm_filter); } } /* Return function status */ return status; } /** * @brief This function allows to get regular conversion value. * @param hdfsdm_filter : DFSDM filter handle. * @param Channel : Corresponding channel of regular conversion. * @retval Regular conversion value */ int32_t HAL_DFSDM_FilterGetRegularValue(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t *Channel) { uint32_t reg = 0U; int32_t value = 0U; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(Channel != NULL); /* Get value of data register for regular channel */ reg = hdfsdm_filter->Instance->FLTRDATAR; /* Extract channel and regular conversion value */ *Channel = (reg & DFSDM_FLTRDATAR_RDATACH); value = ((reg & DFSDM_FLTRDATAR_RDATA) >> DFSDM_FLTRDATAR_DATA_OFFSET); /* return regular conversion value */ return value; } /** * @brief This function allows to start injected conversion in polling mode. * @note This function should be called only when DFSDM filter instance is * in idle state or if regular conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterInjectedStart(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG)) { /* Start injected conversion */ DFSDM_InjConvStart(hdfsdm_filter); } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to poll for the end of injected conversion. * @note This function should be called only if injected conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @param Timeout : Timeout value in milliseconds. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterPollForInjConversion(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t Timeout) { uint32_t tickstart; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_INJ) && \ (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG_INJ)) { /* Return error status */ return HAL_ERROR; } else { /* Get timeout */ tickstart = HAL_GetTick(); /* Wait end of injected conversions */ while((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_JEOCF) != DFSDM_FLTISR_JEOCF) { /* Check the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) { /* Return timeout status */ return HAL_TIMEOUT; } } } /* Check if overrun occurs */ if((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_JOVRF) == DFSDM_FLTISR_JOVRF) { /* Update error code and call error callback */ hdfsdm_filter->ErrorCode = DFSDM_FILTER_ERROR_INJECTED_OVERRUN; HAL_DFSDM_FilterErrorCallback(hdfsdm_filter); /* Clear injected overrun flag */ hdfsdm_filter->Instance->FLTICR = DFSDM_FLTICR_CLRJOVRF; } /* Update remaining injected conversions */ hdfsdm_filter->InjConvRemaining--; if(hdfsdm_filter->InjConvRemaining == 0U) { /* Update DFSDM filter state only if trigger is software */ if(hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) { hdfsdm_filter->State = (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_INJ) ? \ HAL_DFSDM_FILTER_STATE_READY : HAL_DFSDM_FILTER_STATE_REG; } /* end of injected sequence, reset the value */ hdfsdm_filter->InjConvRemaining = (hdfsdm_filter->InjectedScanMode == ENABLE) ? \ hdfsdm_filter->InjectedChannelsNbr : 1U; } /* Return function status */ return HAL_OK; } } /** * @brief This function allows to stop injected conversion in polling mode. * @note This function should be called only if injected conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterInjectedStop(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_INJ) && \ (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG_INJ)) { /* Return error status */ status = HAL_ERROR; } else { /* Stop injected conversion */ DFSDM_InjConvStop(hdfsdm_filter); } /* Return function status */ return status; } /** * @brief This function allows to start injected conversion in interrupt mode. * @note This function should be called only when DFSDM filter instance is * in idle state or if regular conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterInjectedStart_IT(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG)) { /* Enable interrupts for injected conversions */ hdfsdm_filter->Instance->FLTCR2 |= (DFSDM_FLTCR2_JEOCIE | DFSDM_FLTCR2_JOVRIE); /* Start injected conversion */ DFSDM_InjConvStart(hdfsdm_filter); } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to stop injected conversion in interrupt mode. * @note This function should be called only if injected conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterInjectedStop_IT(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_INJ) && \ (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG_INJ)) { /* Return error status */ status = HAL_ERROR; } else { /* Disable interrupts for injected conversions */ hdfsdm_filter->Instance->FLTCR2 &= ~(DFSDM_FLTCR2_JEOCIE | DFSDM_FLTCR2_JOVRIE); /* Stop injected conversion */ DFSDM_InjConvStop(hdfsdm_filter); } /* Return function status */ return status; } /** * @brief This function allows to start injected conversion in DMA mode. * @note This function should be called only when DFSDM filter instance is * in idle state or if regular conversion is ongoing. * Please note that data on buffer will contain signed injected conversion * value on 24 most significant bits and corresponding channel on 3 least * significant bits. * @param hdfsdm_filter : DFSDM filter handle. * @param pData : The destination buffer address. * @param Length : The length of data to be transferred from DFSDM filter to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterInjectedStart_DMA(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, int32_t *pData, uint32_t Length) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check destination address and length */ if((pData == NULL) || (Length == 0U)) { status = HAL_ERROR; } /* Check that DMA is enabled for injected conversion */ else if((hdfsdm_filter->Instance->FLTCR1 & DFSDM_FLTCR1_JDMAEN) != DFSDM_FLTCR1_JDMAEN) { status = HAL_ERROR; } /* Check parameters compatibility */ else if((hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) && \ (hdfsdm_filter->hdmaInj->Init.Mode == DMA_NORMAL) && \ (Length > hdfsdm_filter->InjConvRemaining)) { status = HAL_ERROR; } else if((hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) && \ (hdfsdm_filter->hdmaInj->Init.Mode == DMA_CIRCULAR)) { status = HAL_ERROR; } /* Check DFSDM filter state */ else if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG)) { /* Set callbacks on DMA handler */ hdfsdm_filter->hdmaInj->XferCpltCallback = DFSDM_DMAInjectedConvCplt; hdfsdm_filter->hdmaInj->XferErrorCallback = DFSDM_DMAError; hdfsdm_filter->hdmaInj->XferHalfCpltCallback = (hdfsdm_filter->hdmaInj->Init.Mode == DMA_CIRCULAR) ?\ DFSDM_DMAInjectedHalfConvCplt : NULL; /* Start DMA in interrupt mode */ if(HAL_DMA_Start_IT(hdfsdm_filter->hdmaInj, (uint32_t)&hdfsdm_filter->Instance->FLTJDATAR, \ (uint32_t) pData, Length) != HAL_OK) { /* Set DFSDM filter in error state */ hdfsdm_filter->State = HAL_DFSDM_FILTER_STATE_ERROR; status = HAL_ERROR; } else { /* Start injected conversion */ DFSDM_InjConvStart(hdfsdm_filter); } } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to start injected conversion in DMA mode and to get * only the 16 most significant bits of conversion. * @note This function should be called only when DFSDM filter instance is * in idle state or if regular conversion is ongoing. * Please note that data on buffer will contain signed 16 most significant * bits of injected conversion. * @param hdfsdm_filter : DFSDM filter handle. * @param pData : The destination buffer address. * @param Length : The length of data to be transferred from DFSDM filter to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterInjectedMsbStart_DMA(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, int16_t *pData, uint32_t Length) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check destination address and length */ if((pData == NULL) || (Length == 0U)) { status = HAL_ERROR; } /* Check that DMA is enabled for injected conversion */ else if((hdfsdm_filter->Instance->FLTCR1 & DFSDM_FLTCR1_JDMAEN) != DFSDM_FLTCR1_JDMAEN) { status = HAL_ERROR; } /* Check parameters compatibility */ else if((hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) && \ (hdfsdm_filter->hdmaInj->Init.Mode == DMA_NORMAL) && \ (Length > hdfsdm_filter->InjConvRemaining)) { status = HAL_ERROR; } else if((hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) && \ (hdfsdm_filter->hdmaInj->Init.Mode == DMA_CIRCULAR)) { status = HAL_ERROR; } /* Check DFSDM filter state */ else if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG)) { /* Set callbacks on DMA handler */ hdfsdm_filter->hdmaInj->XferCpltCallback = DFSDM_DMAInjectedConvCplt; hdfsdm_filter->hdmaInj->XferErrorCallback = DFSDM_DMAError; hdfsdm_filter->hdmaInj->XferHalfCpltCallback = (hdfsdm_filter->hdmaInj->Init.Mode == DMA_CIRCULAR) ?\ DFSDM_DMAInjectedHalfConvCplt : NULL; /* Start DMA in interrupt mode */ if(HAL_DMA_Start_IT(hdfsdm_filter->hdmaInj, (uint32_t)(&hdfsdm_filter->Instance->FLTJDATAR) + 2U, \ (uint32_t) pData, Length) != HAL_OK) { /* Set DFSDM filter in error state */ hdfsdm_filter->State = HAL_DFSDM_FILTER_STATE_ERROR; status = HAL_ERROR; } else { /* Start injected conversion */ DFSDM_InjConvStart(hdfsdm_filter); } } else { status = HAL_ERROR; } /* Return function status */ return status; } /** * @brief This function allows to stop injected conversion in DMA mode. * @note This function should be called only if injected conversion is ongoing. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterInjectedStop_DMA(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_INJ) && \ (hdfsdm_filter->State != HAL_DFSDM_FILTER_STATE_REG_INJ)) { /* Return error status */ status = HAL_ERROR; } else { /* Stop current DMA transfer */ if(HAL_DMA_Abort(hdfsdm_filter->hdmaInj) != HAL_OK) { /* Set DFSDM filter in error state */ hdfsdm_filter->State = HAL_DFSDM_FILTER_STATE_ERROR; status = HAL_ERROR; } else { /* Stop regular conversion */ DFSDM_InjConvStop(hdfsdm_filter); } } /* Return function status */ return status; } /** * @brief This function allows to get injected conversion value. * @param hdfsdm_filter : DFSDM filter handle. * @param Channel : Corresponding channel of injected conversion. * @retval Injected conversion value */ int32_t HAL_DFSDM_FilterGetInjectedValue(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t *Channel) { uint32_t reg = 0U; int32_t value = 0U; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(Channel != NULL); /* Get value of data register for injected channel */ reg = hdfsdm_filter->Instance->FLTJDATAR; /* Extract channel and injected conversion value */ *Channel = (reg & DFSDM_FLTJDATAR_JDATACH); value = ((reg & DFSDM_FLTJDATAR_JDATA) >> DFSDM_FLTJDATAR_DATA_OFFSET); /* return regular conversion value */ return value; } /** * @brief This function allows to start filter analog watchdog in interrupt mode. * @param hdfsdm_filter : DFSDM filter handle. * @param awdParam : DFSDM filter analog watchdog parameters. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterAwdStart_IT(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, DFSDM_Filter_AwdParamTypeDef *awdParam) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(IS_DFSDM_FILTER_AWD_DATA_SOURCE(awdParam->DataSource)); assert_param(IS_DFSDM_INJECTED_CHANNEL(awdParam->Channel)); assert_param(IS_DFSDM_FILTER_AWD_THRESHOLD(awdParam->HighThreshold)); assert_param(IS_DFSDM_FILTER_AWD_THRESHOLD(awdParam->LowThreshold)); assert_param(IS_DFSDM_BREAK_SIGNALS(awdParam->HighBreakSignal)); assert_param(IS_DFSDM_BREAK_SIGNALS(awdParam->LowBreakSignal)); /* Check DFSDM filter state */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_RESET) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_ERROR)) { /* Return error status */ status = HAL_ERROR; } else { /* Set analog watchdog data source */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_AWFSEL); hdfsdm_filter->Instance->FLTCR1 |= awdParam->DataSource; /* Set thresholds and break signals */ hdfsdm_filter->Instance->FLTAWHTR &= ~(DFSDM_FLTAWHTR_AWHT | DFSDM_FLTAWHTR_BKAWH); hdfsdm_filter->Instance->FLTAWHTR |= (((uint32_t) awdParam->HighThreshold << DFSDM_FLTAWHTR_THRESHOLD_OFFSET) | \ awdParam->HighBreakSignal); hdfsdm_filter->Instance->FLTAWLTR &= ~(DFSDM_FLTAWLTR_AWLT | DFSDM_FLTAWLTR_BKAWL); hdfsdm_filter->Instance->FLTAWLTR |= (((uint32_t) awdParam->LowThreshold << DFSDM_FLTAWLTR_THRESHOLD_OFFSET) | \ awdParam->LowBreakSignal); /* Set channels and interrupt for analog watchdog */ hdfsdm_filter->Instance->FLTCR2 &= ~(DFSDM_FLTCR2_AWDCH); hdfsdm_filter->Instance->FLTCR2 |= (((awdParam->Channel & DFSDM_LSB_MASK) << DFSDM_FLTCR2_AWDCH_OFFSET) | \ DFSDM_FLTCR2_AWDIE); } /* Return function status */ return status; } /** * @brief This function allows to stop filter analog watchdog in interrupt mode. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterAwdStop_IT(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_RESET) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_ERROR)) { /* Return error status */ status = HAL_ERROR; } else { /* Reset channels for analog watchdog and deactivate interrupt */ hdfsdm_filter->Instance->FLTCR2 &= ~(DFSDM_FLTCR2_AWDCH | DFSDM_FLTCR2_AWDIE); /* Clear all analog watchdog flags */ hdfsdm_filter->Instance->FLTAWCFR = (DFSDM_FLTAWCFR_CLRAWHTF | DFSDM_FLTAWCFR_CLRAWLTF); /* Reset thresholds and break signals */ hdfsdm_filter->Instance->FLTAWHTR &= ~(DFSDM_FLTAWHTR_AWHT | DFSDM_FLTAWHTR_BKAWH); hdfsdm_filter->Instance->FLTAWLTR &= ~(DFSDM_FLTAWLTR_AWLT | DFSDM_FLTAWLTR_BKAWL); /* Reset analog watchdog data source */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_AWFSEL); } /* Return function status */ return status; } /** * @brief This function allows to start extreme detector feature. * @param hdfsdm_filter : DFSDM filter handle. * @param Channel : Channels where extreme detector is enabled. * This parameter can be a values combination of @ref DFSDM_Channel_Selection. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterExdStart(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t Channel) { HAL_StatusTypeDef status = HAL_OK; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(IS_DFSDM_INJECTED_CHANNEL(Channel)); /* Check DFSDM filter state */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_RESET) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_ERROR)) { /* Return error status */ status = HAL_ERROR; } else { /* Set channels for extreme detector */ hdfsdm_filter->Instance->FLTCR2 &= ~(DFSDM_FLTCR2_EXCH); hdfsdm_filter->Instance->FLTCR2 |= ((Channel & DFSDM_LSB_MASK) << DFSDM_FLTCR2_EXCH_OFFSET); } /* Return function status */ return status; } /** * @brief This function allows to stop extreme detector feature. * @param hdfsdm_filter : DFSDM filter handle. * @retval HAL status */ HAL_StatusTypeDef HAL_DFSDM_FilterExdStop(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { HAL_StatusTypeDef status = HAL_OK; __IO uint32_t reg1; __IO uint32_t reg2; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Check DFSDM filter state */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_RESET) || \ (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_ERROR)) { /* Return error status */ status = HAL_ERROR; } else { /* Reset channels for extreme detector */ hdfsdm_filter->Instance->FLTCR2 &= ~(DFSDM_FLTCR2_EXCH); /* Clear extreme detector values */ reg1 = hdfsdm_filter->Instance->FLTEXMAX; reg2 = hdfsdm_filter->Instance->FLTEXMIN; UNUSED(reg1); /* To avoid GCC warning */ UNUSED(reg2); /* To avoid GCC warning */ } /* Return function status */ return status; } /** * @brief This function allows to get extreme detector maximum value. * @param hdfsdm_filter : DFSDM filter handle. * @param Channel : Corresponding channel. * @retval Extreme detector maximum value * This value is between Min_Data = -8388608 and Max_Data = 8388607. */ int32_t HAL_DFSDM_FilterGetExdMaxValue(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t *Channel) { uint32_t reg = 0U; int32_t value = 0U; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(Channel != NULL); /* Get value of extreme detector maximum register */ reg = hdfsdm_filter->Instance->FLTEXMAX; /* Extract channel and extreme detector maximum value */ *Channel = (reg & DFSDM_FLTEXMAX_EXMAXCH); value = ((reg & DFSDM_FLTEXMAX_EXMAX) >> DFSDM_FLTEXMAX_DATA_OFFSET); /* return extreme detector maximum value */ return value; } /** * @brief This function allows to get extreme detector minimum value. * @param hdfsdm_filter : DFSDM filter handle. * @param Channel : Corresponding channel. * @retval Extreme detector minimum value * This value is between Min_Data = -8388608 and Max_Data = 8388607. */ int32_t HAL_DFSDM_FilterGetExdMinValue(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t *Channel) { uint32_t reg = 0U; int32_t value = 0U; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); assert_param(Channel != NULL); /* Get value of extreme detector minimum register */ reg = hdfsdm_filter->Instance->FLTEXMIN; /* Extract channel and extreme detector minimum value */ *Channel = (reg & DFSDM_FLTEXMIN_EXMINCH); value = ((reg & DFSDM_FLTEXMIN_EXMIN) >> DFSDM_FLTEXMIN_DATA_OFFSET); /* return extreme detector minimum value */ return value; } /** * @brief This function allows to get conversion time value. * @param hdfsdm_filter : DFSDM filter handle. * @retval Conversion time value * @note To get time in second, this value has to be divided by DFSDM clock frequency. */ uint32_t HAL_DFSDM_FilterGetConvTimeValue(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { uint32_t reg = 0U; uint32_t value = 0U; /* Check parameters */ assert_param(IS_DFSDM_FILTER_ALL_INSTANCE(hdfsdm_filter->Instance)); /* Get value of conversion timer register */ reg = hdfsdm_filter->Instance->FLTCNVTIMR; /* Extract conversion time value */ value = ((reg & DFSDM_FLTCNVTIMR_CNVCNT) >> DFSDM_FLTCNVTIMR_DATA_OFFSET); /* return extreme detector minimum value */ return value; } /** * @brief This function handles the DFSDM interrupts. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ void HAL_DFSDM_IRQHandler(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Check if overrun occurs during regular conversion */ if(((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_ROVRF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_ROVRIE) != 0U)) { /* Clear regular overrun flag */ hdfsdm_filter->Instance->FLTICR = DFSDM_FLTICR_CLRROVRF; /* Update error code */ hdfsdm_filter->ErrorCode = DFSDM_FILTER_ERROR_REGULAR_OVERRUN; /* Call error callback */ HAL_DFSDM_FilterErrorCallback(hdfsdm_filter); } /* Check if overrun occurs during injected conversion */ else if(((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_JOVRF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_JOVRIE) != 0U)) { /* Clear injected overrun flag */ hdfsdm_filter->Instance->FLTICR = DFSDM_FLTICR_CLRJOVRF; /* Update error code */ hdfsdm_filter->ErrorCode = DFSDM_FILTER_ERROR_INJECTED_OVERRUN; /* Call error callback */ HAL_DFSDM_FilterErrorCallback(hdfsdm_filter); } /* Check if end of regular conversion */ else if(((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_REOCF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_REOCIE) != 0U)) { /* Call regular conversion complete callback */ HAL_DFSDM_FilterRegConvCpltCallback(hdfsdm_filter); /* End of conversion if mode is not continuous and software trigger */ if((hdfsdm_filter->RegularContMode == DFSDM_CONTINUOUS_CONV_OFF) && \ (hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER)) { /* Disable interrupts for regular conversions */ hdfsdm_filter->Instance->FLTCR2 &= ~(DFSDM_FLTCR2_REOCIE); /* Update DFSDM filter state */ hdfsdm_filter->State = (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG) ? \ HAL_DFSDM_FILTER_STATE_READY : HAL_DFSDM_FILTER_STATE_INJ; } } /* Check if end of injected conversion */ else if(((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_JEOCF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_JEOCIE) != 0U)) { /* Call injected conversion complete callback */ HAL_DFSDM_FilterInjConvCpltCallback(hdfsdm_filter); /* Update remaining injected conversions */ hdfsdm_filter->InjConvRemaining--; if(hdfsdm_filter->InjConvRemaining == 0U) { /* End of conversion if trigger is software */ if(hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) { /* Disable interrupts for injected conversions */ hdfsdm_filter->Instance->FLTCR2 &= ~(DFSDM_FLTCR2_JEOCIE); /* Update DFSDM filter state */ hdfsdm_filter->State = (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_INJ) ? \ HAL_DFSDM_FILTER_STATE_READY : HAL_DFSDM_FILTER_STATE_REG; } /* end of injected sequence, reset the value */ hdfsdm_filter->InjConvRemaining = (hdfsdm_filter->InjectedScanMode == ENABLE) ? \ hdfsdm_filter->InjectedChannelsNbr : 1U; } } /* Check if analog watchdog occurs */ else if(((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_AWDF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_AWDIE) != 0U)) { uint32_t reg = 0U; uint32_t threshold = 0U; uint32_t channel = 0U; /* Get channel and threshold */ reg = hdfsdm_filter->Instance->FLTAWSR; threshold = ((reg & DFSDM_FLTAWSR_AWLTF) != 0U) ? DFSDM_AWD_LOW_THRESHOLD : DFSDM_AWD_HIGH_THRESHOLD; if(threshold == DFSDM_AWD_HIGH_THRESHOLD) { reg = reg >> DFSDM_FLTAWSR_HIGH_OFFSET; } while((reg & 1U) == 0U) { channel++; reg = reg >> 1U; } /* Clear analog watchdog flag */ hdfsdm_filter->Instance->FLTAWCFR = (threshold == DFSDM_AWD_HIGH_THRESHOLD) ? \ (1U << (DFSDM_FLTAWSR_HIGH_OFFSET + channel)) : \ (1U << channel); /* Call analog watchdog callback */ HAL_DFSDM_FilterAwdCallback(hdfsdm_filter, channel, threshold); } /* Check if clock absence occurs */ else if((hdfsdm_filter->Instance == DFSDM1_Filter0) && \ ((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_CKABF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_CKABIE) != 0U)) { uint32_t reg = 0U; uint32_t channel = 0U; reg = ((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_CKABF) >> DFSDM_FLTISR_CKABF_OFFSET); while(channel < DFSDM1_CHANNEL_NUMBER) { /* Check if flag is set and corresponding channel is enabled */ if(((reg & 1U) != 0U) && (a_dfsdm1ChannelHandle[channel] != NULL)) { /* Check clock absence has been enabled for this channel */ if((a_dfsdm1ChannelHandle[channel]->Instance->CHCFGR1 & DFSDM_CHCFGR1_CKABEN) != 0U) { /* Clear clock absence flag */ hdfsdm_filter->Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); /* Call clock absence callback */ HAL_DFSDM_ChannelCkabCallback(a_dfsdm1ChannelHandle[channel]); } } channel++; reg = reg >> 1U; } } #if defined (DFSDM2_Channel0) /* Check if clock absence occurs */ else if((hdfsdm_filter->Instance == DFSDM2_Filter0) && \ ((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_CKABF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_CKABIE) != 0U)) { uint32_t reg = 0U; uint32_t channel = 0U; reg = ((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_CKABF) >> DFSDM_FLTISR_CKABF_OFFSET); while(channel < DFSDM2_CHANNEL_NUMBER) { /* Check if flag is set and corresponding channel is enabled */ if(((reg & 1U) != 0U) && (a_dfsdm2ChannelHandle[channel] != NULL)) { /* Check clock absence has been enabled for this channel */ if((a_dfsdm2ChannelHandle[channel]->Instance->CHCFGR1 & DFSDM_CHCFGR1_CKABEN) != 0U) { /* Clear clock absence flag */ hdfsdm_filter->Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRCKABF_OFFSET + channel)); /* Call clock absence callback */ HAL_DFSDM_ChannelCkabCallback(a_dfsdm2ChannelHandle[channel]); } } channel++; reg = reg >> 1U; } } #endif /* DFSDM2_Channel0 */ /* Check if short circuit detection occurs */ else if((hdfsdm_filter->Instance == DFSDM1_Filter0) && \ ((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_SCDF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_SCDIE) != 0U)) { uint32_t reg = 0U; uint32_t channel = 0U; /* Get channel */ reg = ((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_SCDF) >> DFSDM_FLTISR_SCDF_OFFSET); while((reg & 1U) == 0U) { channel++; reg = reg >> 1U; } /* Clear short circuit detection flag */ hdfsdm_filter->Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRSCDF_OFFSET + channel)); /* Call short circuit detection callback */ HAL_DFSDM_ChannelScdCallback(a_dfsdm1ChannelHandle[channel]); } #if defined (DFSDM2_Channel0) /* Check if short circuit detection occurs */ else if((hdfsdm_filter->Instance == DFSDM2_Filter0) && \ ((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_SCDF) != 0U) && \ ((hdfsdm_filter->Instance->FLTCR2 & DFSDM_FLTCR2_SCDIE) != 0U)) { uint32_t reg = 0U; uint32_t channel = 0U; /* Get channel */ reg = ((hdfsdm_filter->Instance->FLTISR & DFSDM_FLTISR_SCDF) >> DFSDM_FLTISR_SCDF_OFFSET); while((reg & 1U) == 0U) { channel++; reg = reg >> 1U; } /* Clear short circuit detection flag */ hdfsdm_filter->Instance->FLTICR = (1U << (DFSDM_FLTICR_CLRSCDF_OFFSET + channel)); /* Call short circuit detection callback */ HAL_DFSDM_ChannelScdCallback(a_dfsdm2ChannelHandle[channel]); } #endif /* DFSDM2_Channel0 */ } /** * @brief Regular conversion complete callback. * @note In interrupt mode, user has to read conversion value in this function * using HAL_DFSDM_FilterGetRegularValue. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ __weak void HAL_DFSDM_FilterRegConvCpltCallback(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_filter); /* NOTE : This function should not be modified, when the callback is needed, the HAL_DFSDM_FilterRegConvCpltCallback could be implemented in the user file. */ } /** * @brief Half regular conversion complete callback. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ __weak void HAL_DFSDM_FilterRegConvHalfCpltCallback(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_filter); /* NOTE : This function should not be modified, when the callback is needed, the HAL_DFSDM_FilterRegConvHalfCpltCallback could be implemented in the user file. */ } /** * @brief Injected conversion complete callback. * @note In interrupt mode, user has to read conversion value in this function * using HAL_DFSDM_FilterGetInjectedValue. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ __weak void HAL_DFSDM_FilterInjConvCpltCallback(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_filter); /* NOTE : This function should not be modified, when the callback is needed, the HAL_DFSDM_FilterInjConvCpltCallback could be implemented in the user file. */ } /** * @brief Half injected conversion complete callback. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ __weak void HAL_DFSDM_FilterInjConvHalfCpltCallback(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_filter); /* NOTE : This function should not be modified, when the callback is needed, the HAL_DFSDM_FilterInjConvHalfCpltCallback could be implemented in the user file. */ } /** * @brief Filter analog watchdog callback. * @param hdfsdm_filter : DFSDM filter handle. * @param Channel : Corresponding channel. * @param Threshold : Low or high threshold has been reached. * @retval None */ __weak void HAL_DFSDM_FilterAwdCallback(DFSDM_Filter_HandleTypeDef *hdfsdm_filter, uint32_t Channel, uint32_t Threshold) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_filter); UNUSED(Channel); UNUSED(Threshold); /* NOTE : This function should not be modified, when the callback is needed, the HAL_DFSDM_FilterAwdCallback could be implemented in the user file. */ } /** * @brief Error callback. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ __weak void HAL_DFSDM_FilterErrorCallback(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Prevent unused argument(s) compilation warning */ UNUSED(hdfsdm_filter); /* NOTE : This function should not be modified, when the callback is needed, the HAL_DFSDM_FilterErrorCallback could be implemented in the user file. */ } /** * @} */ /** @defgroup DFSDM_Exported_Functions_Group4_Filter Filter state functions * @brief Filter state functions * @verbatim ============================================================================== ##### Filter state functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Get the DFSDM filter state. (+) Get the DFSDM filter error. @endverbatim * @{ */ /** * @brief This function allows to get the current DFSDM filter handle state. * @param hdfsdm_filter : DFSDM filter handle. * @retval DFSDM filter state. */ HAL_DFSDM_Filter_StateTypeDef HAL_DFSDM_FilterGetState(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { /* Return DFSDM filter handle state */ return hdfsdm_filter->State; } /** * @brief This function allows to get the current DFSDM filter error. * @param hdfsdm_filter : DFSDM filter handle. * @retval DFSDM filter error code. */ uint32_t HAL_DFSDM_FilterGetError(DFSDM_Filter_HandleTypeDef *hdfsdm_filter) { return hdfsdm_filter->ErrorCode; } /** * @} */ /** @defgroup DFSDM_Exported_Functions_Group5_Filter MultiChannel operation functions * @brief Filter state functions * @verbatim ============================================================================== ##### Filter state functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Control the DFSDM Multi channel delay block @endverbatim * @{ */ #if defined(SYSCFG_MCHDLYCR_BSCKSEL) /** * @brief Select the DFSDM2 as clock source for the bitstream clock. * @retval None */ void HAL_DFSDM_BitstreamClock_Start(void) { uint32_t tmp = 0; tmp = SYSCFG->MCHDLYCR; tmp = (tmp &(~SYSCFG_MCHDLYCR_BSCKSEL)); SYSCFG->MCHDLYCR = (tmp|SYSCFG_MCHDLYCR_BSCKSEL); } /** * @brief Stop the DFSDM2 as clock source for the bitstream clock. * @retval None */ void HAL_DFSDM_BitstreamClock_Stop(void) { uint32_t tmp = 0; tmp = SYSCFG->MCHDLYCR; tmp = (tmp &(~SYSCFG_MCHDLYCR_BSCKSEL)); SYSCFG->MCHDLYCR = tmp; } /** * @brief Disable Delay Clock for DFSDM1/2. * @param MCHDLY: HAL_MCHDLY_CLOCK_DFSDM2. * HAL_MCHDLY_CLOCK_DFSDM1. * @retval None */ void HAL_DFSDM_DisableDelayClock(uint32_t MCHDLY) { uint32_t tmp = 0; assert_param(IS_DFSDM_DELAY_CLOCK(MCHDLY)); tmp = SYSCFG->MCHDLYCR; if(MCHDLY == HAL_MCHDLY_CLOCK_DFSDM2) { tmp = tmp &(~SYSCFG_MCHDLYCR_MCHDLY2EN); } else { tmp = tmp &(~SYSCFG_MCHDLYCR_MCHDLY1EN); } SYSCFG->MCHDLYCR = tmp; } /** * @brief Enable Delay Clock for DFSDM1/2. * @param MCHDLY: HAL_MCHDLY_CLOCK_DFSDM2. * HAL_MCHDLY_CLOCK_DFSDM1. * @retval None */ void HAL_DFSDM_EnableDelayClock(uint32_t MCHDLY) { uint32_t tmp = 0; assert_param(IS_DFSDM_DELAY_CLOCK(MCHDLY)); tmp = SYSCFG->MCHDLYCR; tmp = tmp & ~MCHDLY; SYSCFG->MCHDLYCR = (tmp|MCHDLY); } /** * @brief Select the source for CKin signals for DFSDM1/2. * @param source: HAL_DFSDM2_CKIN_PAD. * HAL_DFSDM2_CKIN_DM. * HAL_DFSDM1_CKIN_PAD. * HAL_DFSDM1_CKIN_DM. * @retval None */ void HAL_DFSDM_ClockIn_SourceSelection(uint32_t source) { uint32_t tmp = 0; assert_param(IS_DFSDM_CLOCKIN_SELECTION(source)); tmp = SYSCFG->MCHDLYCR; if((source == HAL_DFSDM2_CKIN_PAD) || (source == HAL_DFSDM2_CKIN_DM)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2CFG); if(source == HAL_DFSDM2_CKIN_PAD) { source = 0x000000; } } else { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM1CFG); } SYSCFG->MCHDLYCR = (source|tmp); } /** * @brief Select the source for CKOut signals for DFSDM1/2. * @param source: HAL_DFSDM2_CKOUT_DFSDM2. * HAL_DFSDM2_CKOUT_M27. * HAL_DFSDM1_CKOUT_DFSDM1. * HAL_DFSDM1_CKOUT_M27. * @retval None */ void HAL_DFSDM_ClockOut_SourceSelection(uint32_t source) { uint32_t tmp = 0; assert_param(IS_DFSDM_CLOCKOUT_SELECTION(source)); tmp = SYSCFG->MCHDLYCR; if((source == HAL_DFSDM2_CKOUT_DFSDM2) || (source == HAL_DFSDM2_CKOUT_M27)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2CKOSEL); if(source == HAL_DFSDM2_CKOUT_DFSDM2) { source = 0x000; } } else { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM1CKOSEL); } SYSCFG->MCHDLYCR = (source|tmp); } /** * @brief Select the source for DataIn0 signals for DFSDM1/2. * @param source: HAL_DATAIN0_DFSDM2_PAD. * HAL_DATAIN0_DFSDM2_DATAIN1. * HAL_DATAIN0_DFSDM1_PAD. * HAL_DATAIN0_DFSDM1_DATAIN1. * @retval None */ void HAL_DFSDM_DataIn0_SourceSelection(uint32_t source) { uint32_t tmp = 0; assert_param(IS_DFSDM_DATAIN0_SRC_SELECTION(source)); tmp = SYSCFG->MCHDLYCR; if((source == HAL_DATAIN0_DFSDM2_PAD)|| (source == HAL_DATAIN0_DFSDM2_DATAIN1)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2D0SEL); if(source == HAL_DATAIN0_DFSDM2_PAD) { source = 0x00000; } } else { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM1D0SEL); } SYSCFG->MCHDLYCR = (source|tmp); } /** * @brief Select the source for DataIn2 signals for DFSDM1/2. * @param source: HAL_DATAIN2_DFSDM2_PAD. * HAL_DATAIN2_DFSDM2_DATAIN3. * HAL_DATAIN2_DFSDM1_PAD. * HAL_DATAIN2_DFSDM1_DATAIN3. * @retval None */ void HAL_DFSDM_DataIn2_SourceSelection(uint32_t source) { uint32_t tmp = 0; assert_param(IS_DFSDM_DATAIN2_SRC_SELECTION(source)); tmp = SYSCFG->MCHDLYCR; if((source == HAL_DATAIN2_DFSDM2_PAD)|| (source == HAL_DATAIN2_DFSDM2_DATAIN3)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2D2SEL); if (source == HAL_DATAIN2_DFSDM2_PAD) { source = 0x0000; } } else { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM1D2SEL); } SYSCFG->MCHDLYCR = (source|tmp); } /** * @brief Select the source for DataIn4 signals for DFSDM2. * @param source: HAL_DATAIN4_DFSDM2_PAD. * HAL_DATAIN4_DFSDM2_DATAIN5 * @retval None */ void HAL_DFSDM_DataIn4_SourceSelection(uint32_t source) { uint32_t tmp = 0; assert_param(IS_DFSDM_DATAIN4_SRC_SELECTION(source)); tmp = SYSCFG->MCHDLYCR; tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2D4SEL); SYSCFG->MCHDLYCR = (source|tmp); } /** * @brief Select the source for DataIn6 signals for DFSDM2. * @param source: HAL_DATAIN6_DFSDM2_PAD. * HAL_DATAIN6_DFSDM2_DATAIN7. * @retval None */ void HAL_DFSDM_DataIn6_SourceSelection(uint32_t source) { uint32_t tmp = 0; assert_param(IS_DFSDM_DATAIN6_SRC_SELECTION(source)); tmp = SYSCFG->MCHDLYCR; tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2D6SEL); SYSCFG->MCHDLYCR = (source|tmp); } /** * @brief Configure the distribution of the bitstream clock gated from TIM4_OC * for DFSDM1 or TIM3_OC for DFSDM2 * @param source: HAL_DFSDM1_CLKIN0_TIM4OC2 * HAL_DFSDM1_CLKIN2_TIM4OC2 * HAL_DFSDM1_CLKIN1_TIM4OC1 * HAL_DFSDM1_CLKIN3_TIM4OC1 * HAL_DFSDM2_CLKIN0_TIM3OC4 * HAL_DFSDM2_CLKIN4_TIM3OC4 * HAL_DFSDM2_CLKIN1_TIM3OC3 * HAL_DFSDM2_CLKIN5_TIM3OC3 * HAL_DFSDM2_CLKIN2_TIM3OC2 * HAL_DFSDM2_CLKIN6_TIM3OC2 * HAL_DFSDM2_CLKIN3_TIM3OC1 * HAL_DFSDM2_CLKIN7_TIM3OC1 * @retval None */ void HAL_DFSDM_BitStreamClkDistribution_Config(uint32_t source) { uint32_t tmp = 0; assert_param(IS_DFSDM_BITSTREM_CLK_DISTRIBUTION(source)); if((source == HAL_DFSDM1_CLKIN0_TIM4OC2) ||(source == HAL_DFSDM1_CLKIN1_TIM4OC1)|| (source == HAL_DFSDM2_CLKIN0_TIM3OC4) ||(source == HAL_DFSDM2_CLKIN1_TIM3OC3)|| (source == HAL_DFSDM2_CLKIN2_TIM3OC2) ||(source == HAL_DFSDM2_CLKIN3_TIM3OC1)) { source = 0x0000; } tmp = SYSCFG->MCHDLYCR; if ((source == HAL_DFSDM1_CLKIN0_TIM4OC2) || (source == HAL_DFSDM1_CLKIN2_TIM4OC2)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM1CK02SEL); } else if ((source == HAL_DFSDM1_CLKIN1_TIM4OC1) || (source == HAL_DFSDM1_CLKIN3_TIM4OC1)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM1CK13SEL); } else if ((source == HAL_DFSDM2_CLKIN0_TIM3OC4) || (source == HAL_DFSDM2_CLKIN4_TIM3OC4)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2CK04SEL); } else if ((source == HAL_DFSDM2_CLKIN1_TIM3OC3) || (source == HAL_DFSDM2_CLKIN5_TIM3OC3)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2CK15SEL); }else if ((source == HAL_DFSDM2_CLKIN2_TIM3OC2) || (source == HAL_DFSDM2_CLKIN6_TIM3OC2)) { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2CK26SEL); } else { tmp = (tmp & ~SYSCFG_MCHDLYCR_DFSDM2CK37SEL); } SYSCFG->MCHDLYCR = (source|tmp); } #endif /* SYSCFG_MCHDLYCR_BSCKSEL */ /** * @} */ /** * @} */ /* End of exported functions -------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @addtogroup DFSDM_Private_Functions DFSDM Private Functions * @{ */ /** * @brief DMA half transfer complete callback for regular conversion. * @param hdma : DMA handle. * @retval None */ static void DFSDM_DMARegularHalfConvCplt(DMA_HandleTypeDef *hdma) { /* Get DFSDM filter handle */ DFSDM_Filter_HandleTypeDef* hdfsdm_filter = (DFSDM_Filter_HandleTypeDef*) ((DMA_HandleTypeDef*)hdma)->Parent; /* Call regular half conversion complete callback */ HAL_DFSDM_FilterRegConvHalfCpltCallback(hdfsdm_filter); } /** * @brief DMA transfer complete callback for regular conversion. * @param hdma : DMA handle. * @retval None */ static void DFSDM_DMARegularConvCplt(DMA_HandleTypeDef *hdma) { /* Get DFSDM filter handle */ DFSDM_Filter_HandleTypeDef* hdfsdm_filter = (DFSDM_Filter_HandleTypeDef*) ((DMA_HandleTypeDef*)hdma)->Parent; /* Call regular conversion complete callback */ HAL_DFSDM_FilterRegConvCpltCallback(hdfsdm_filter); } /** * @brief DMA half transfer complete callback for injected conversion. * @param hdma : DMA handle. * @retval None */ static void DFSDM_DMAInjectedHalfConvCplt(DMA_HandleTypeDef *hdma) { /* Get DFSDM filter handle */ DFSDM_Filter_HandleTypeDef* hdfsdm_filter = (DFSDM_Filter_HandleTypeDef*) ((DMA_HandleTypeDef*)hdma)->Parent; /* Call injected half conversion complete callback */ HAL_DFSDM_FilterInjConvHalfCpltCallback(hdfsdm_filter); } /** * @brief DMA transfer complete callback for injected conversion. * @param hdma : DMA handle. * @retval None */ static void DFSDM_DMAInjectedConvCplt(DMA_HandleTypeDef *hdma) { /* Get DFSDM filter handle */ DFSDM_Filter_HandleTypeDef* hdfsdm_filter = (DFSDM_Filter_HandleTypeDef*) ((DMA_HandleTypeDef*)hdma)->Parent; /* Call injected conversion complete callback */ HAL_DFSDM_FilterInjConvCpltCallback(hdfsdm_filter); } /** * @brief DMA error callback. * @param hdma : DMA handle. * @retval None */ static void DFSDM_DMAError(DMA_HandleTypeDef *hdma) { /* Get DFSDM filter handle */ DFSDM_Filter_HandleTypeDef* hdfsdm_filter = (DFSDM_Filter_HandleTypeDef*) ((DMA_HandleTypeDef*)hdma)->Parent; /* Update error code */ hdfsdm_filter->ErrorCode = DFSDM_FILTER_ERROR_DMA; /* Call error callback */ HAL_DFSDM_FilterErrorCallback(hdfsdm_filter); } /** * @brief This function allows to get the number of injected channels. * @param Channels : bitfield of injected channels. * @retval Number of injected channels. */ static uint32_t DFSDM_GetInjChannelsNbr(uint32_t Channels) { uint32_t nbChannels = 0U; uint32_t tmp; /* Get the number of channels from bitfield */ tmp = (uint32_t) (Channels & DFSDM_LSB_MASK); while(tmp != 0U) { if((tmp & 1U) != 0U) { nbChannels++; } tmp = (uint32_t) (tmp >> 1U); } return nbChannels; } /** * @brief This function allows to get the channel number from channel instance. * @param Instance : DFSDM channel instance. * @retval Channel number. */ static uint32_t DFSDM_GetChannelFromInstance(DFSDM_Channel_TypeDef* Instance) { uint32_t channel = 0xFFU; /* Get channel from instance */ #if defined(DFSDM2_Channel0) if((Instance == DFSDM1_Channel0) || (Instance == DFSDM2_Channel0)) { channel = 0U; } else if((Instance == DFSDM1_Channel1) || (Instance == DFSDM2_Channel1)) { channel = 1U; } else if((Instance == DFSDM1_Channel2) || (Instance == DFSDM2_Channel2)) { channel = 2U; } else if((Instance == DFSDM1_Channel3) || (Instance == DFSDM2_Channel3)) { channel = 3U; } else if(Instance == DFSDM2_Channel4) { channel = 4U; } else if(Instance == DFSDM2_Channel5) { channel = 5U; } else if(Instance == DFSDM2_Channel6) { channel = 6U; } else if(Instance == DFSDM2_Channel7) { channel = 7U; } #else if(Instance == DFSDM1_Channel0) { channel = 0U; } else if(Instance == DFSDM1_Channel1) { channel = 1U; } else if(Instance == DFSDM1_Channel2) { channel = 2U; } else if(Instance == DFSDM1_Channel3) { channel = 3U; } #endif /* defined(DFSDM2_Channel0) */ return channel; } /** * @brief This function allows to really start regular conversion. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ static void DFSDM_RegConvStart(DFSDM_Filter_HandleTypeDef* hdfsdm_filter) { /* Check regular trigger */ if(hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER) { /* Software start of regular conversion */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_RSWSTART; } else /* synchronous trigger */ { /* Disable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_DFEN); /* Set RSYNC bit in DFSDM_FLTCR1 register */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_RSYNC; /* Enable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_DFEN; /* If injected conversion was in progress, restart it */ if(hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_INJ) { if(hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) { hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_JSWSTART; } /* Update remaining injected conversions */ hdfsdm_filter->InjConvRemaining = (hdfsdm_filter->InjectedScanMode == ENABLE) ? \ hdfsdm_filter->InjectedChannelsNbr : 1U; } } /* Update DFSDM filter state */ hdfsdm_filter->State = (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) ? \ HAL_DFSDM_FILTER_STATE_REG : HAL_DFSDM_FILTER_STATE_REG_INJ; } /** * @brief This function allows to really stop regular conversion. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ static void DFSDM_RegConvStop(DFSDM_Filter_HandleTypeDef* hdfsdm_filter) { /* Disable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_DFEN); /* If regular trigger was synchronous, reset RSYNC bit in DFSDM_FLTCR1 register */ if(hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SYNC_TRIGGER) { hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_RSYNC); } /* Enable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_DFEN; /* If injected conversion was in progress, restart it */ if(hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG_INJ) { if(hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) { hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_JSWSTART; } /* Update remaining injected conversions */ hdfsdm_filter->InjConvRemaining = (hdfsdm_filter->InjectedScanMode == ENABLE) ? \ hdfsdm_filter->InjectedChannelsNbr : 1U; } /* Update DFSDM filter state */ hdfsdm_filter->State = (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG) ? \ HAL_DFSDM_FILTER_STATE_READY : HAL_DFSDM_FILTER_STATE_INJ; } /** * @brief This function allows to really start injected conversion. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ static void DFSDM_InjConvStart(DFSDM_Filter_HandleTypeDef* hdfsdm_filter) { /* Check injected trigger */ if(hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SW_TRIGGER) { /* Software start of injected conversion */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_JSWSTART; } else /* external or synchronous trigger */ { /* Disable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_DFEN); if(hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SYNC_TRIGGER) { /* Set JSYNC bit in DFSDM_FLTCR1 register */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_JSYNC; } else /* external trigger */ { /* Set JEXTEN[1:0] bits in DFSDM_FLTCR1 register */ hdfsdm_filter->Instance->FLTCR1 |= hdfsdm_filter->ExtTriggerEdge; } /* Enable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_DFEN; /* If regular conversion was in progress, restart it */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG) && \ (hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER)) { hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_RSWSTART; } } /* Update DFSDM filter state */ hdfsdm_filter->State = (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_READY) ? \ HAL_DFSDM_FILTER_STATE_INJ : HAL_DFSDM_FILTER_STATE_REG_INJ; } /** * @brief This function allows to really stop injected conversion. * @param hdfsdm_filter : DFSDM filter handle. * @retval None */ static void DFSDM_InjConvStop(DFSDM_Filter_HandleTypeDef* hdfsdm_filter) { /* Disable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_DFEN); /* If injected trigger was synchronous, reset JSYNC bit in DFSDM_FLTCR1 register */ if(hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_SYNC_TRIGGER) { hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_JSYNC); } else if(hdfsdm_filter->InjectedTrigger == DFSDM_FILTER_EXT_TRIGGER) { /* Reset JEXTEN[1:0] bits in DFSDM_FLTCR1 register */ hdfsdm_filter->Instance->FLTCR1 &= ~(DFSDM_FLTCR1_JEXTEN); } /* Enable DFSDM filter */ hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_DFEN; /* If regular conversion was in progress, restart it */ if((hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_REG_INJ) && \ (hdfsdm_filter->RegularTrigger == DFSDM_FILTER_SW_TRIGGER)) { hdfsdm_filter->Instance->FLTCR1 |= DFSDM_FLTCR1_RSWSTART; } /* Update remaining injected conversions */ hdfsdm_filter->InjConvRemaining = (hdfsdm_filter->InjectedScanMode == ENABLE) ? \ hdfsdm_filter->InjectedChannelsNbr : 1U; /* Update DFSDM filter state */ hdfsdm_filter->State = (hdfsdm_filter->State == HAL_DFSDM_FILTER_STATE_INJ) ? \ HAL_DFSDM_FILTER_STATE_READY : HAL_DFSDM_FILTER_STATE_REG; } /** * @} */ /* End of private functions --------------------------------------------------*/ /** * @} */ #endif /* STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx || STM32F413xx || STM32F423xx */ #endif /* HAL_DFSDM_MODULE_ENABLED */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
gpl-3.0
GilCol/TextSecure
jni/webrtc/modules/audio_coding/codecs/isac/fix/test/test_iSACfixfloat.c
62
18762
/* * Copyright (c) 2011 The WebRTC 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. */ /* * test_iSACfixfloat.c * * Test compatibility and quality between floating- and fixed-point code * */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* include API */ #include "isac.h" #include "isacfix.h" /* max number of samples per frame (= 60 ms frame) */ #define MAX_FRAMESAMPLES 960 /* number of samples per 10ms frame */ #define FRAMESAMPLES_10ms 160 /* sampling frequency (Hz) */ #define FS 16000 /* Runtime statistics */ #include <time.h> #define CLOCKS_PER_SEC 1000 // FILE *histfile, *ratefile; /* function for reading audio data from PCM file */ int readframe(int16_t *data, FILE *inp, int length) { short k, rlen, status = 0; rlen = fread(data, sizeof(int16_t), length, inp); if (rlen < length) { for (k = rlen; k < length; k++) data[k] = 0; status = 1; } return status; } typedef struct { uint32_t send_time; /* samples */ uint32_t arrival_time; /* samples */ uint32_t sample_count; /* samples */ uint16_t rtp_number; } BottleNeckModel; void get_arrival_time(int current_framesamples, /* samples */ int packet_size, /* bytes */ int bottleneck, /* excluding headers; bits/s */ BottleNeckModel *BN_data) { const int HeaderSize = 35; int HeaderRate; HeaderRate = HeaderSize * 8 * FS / current_framesamples; /* bits/s */ /* everything in samples */ BN_data->sample_count = BN_data->sample_count + current_framesamples; BN_data->arrival_time += ((packet_size + HeaderSize) * 8 * FS) / (bottleneck + HeaderRate); BN_data->send_time += current_framesamples; if (BN_data->arrival_time < BN_data->sample_count) BN_data->arrival_time = BN_data->sample_count; BN_data->rtp_number++; } int main(int argc, char* argv[]) { char inname[50], outname[50], bottleneck_file[50], bitfilename[60], bitending[10]="_bits.pcm"; FILE *inp, *outp, *f_bn, *bitsp; int framecnt, endfile; int i,j,errtype, plc=0; int16_t CodingMode; int16_t bottleneck; int16_t framesize = 30; /* ms */ //int16_t framesize = 60; /* To invoke cisco complexity case at frame 2252 */ int cur_framesmpls, err; /* Runtime statistics */ double starttime; double runtime; double length_file; int16_t stream_len = 0; int16_t declen; int16_t shortdata[FRAMESAMPLES_10ms]; int16_t decoded[MAX_FRAMESAMPLES]; uint16_t streamdata[600]; int16_t speechType[1]; // int16_t *iSACstruct; char version_number[20]; int mode=-1, tmp, nbTest=0; /*,sss;*/ #ifdef _DEBUG FILE *fy; double kbps; int totalbits =0; int totalsmpls =0; #endif /* _DEBUG */ /* only one structure used for ISAC encoder */ ISAC_MainStruct *ISAC_main_inst; ISACFIX_MainStruct *ISACFIX_main_inst; BottleNeckModel BN_data; f_bn = NULL; #ifdef _DEBUG fy = fopen("bit_rate.dat", "w"); fclose(fy); fy = fopen("bytes_frames.dat", "w"); fclose(fy); #endif /* _DEBUG */ //histfile = fopen("histo.dat", "ab"); //ratefile = fopen("rates.dat", "ab"); /* handling wrong input arguments in the command line */ if ((argc<6) || (argc>10)) { printf("\n\nWrong number of arguments or flag values.\n\n"); printf("\n"); WebRtcIsacfix_version(version_number); printf("iSAC version %s \n\n", version_number); printf("Usage:\n\n"); printf("./kenny.exe [-I] bottleneck_value infile outfile \n\n"); printf("with:\n"); printf("[-I] : if -I option is specified, the coder will use\n"); printf(" an instantaneous Bottleneck value. If not, it\n"); printf(" will be an adaptive Bottleneck value.\n\n"); printf("bottleneck_value : the value of the bottleneck provided either\n"); printf(" as a fixed value (e.g. 25000) or\n"); printf(" read from a file (e.g. bottleneck.txt)\n\n"); printf("[-m] mode : Mode (encoder - decoder):\n"); printf(" : 0 - float - float \n"); printf(" : 1 - float - fix \n"); printf(" : 2 - fix - float \n"); printf(" : 3 - fix - fix \n"); printf("[-PLC] : Test PLC packetlosses\n"); printf("[-NB] num : Test NB interfaces, num=1 encNB, num=2 decNB\n"); printf("infile : Normal speech input file\n\n"); printf("outfile : Speech output file\n\n"); printf("Example usage:\n\n"); printf("./kenny.exe -I bottleneck.txt -m 1 speechIn.pcm speechOut.pcm\n\n"); exit(0); } printf("--------------------START---------------------\n\n"); WebRtcIsac_version(version_number); printf("iSAC FLOAT version %s \n", version_number); WebRtcIsacfix_version(version_number); printf("iSAC FIX version %s \n\n", version_number); CodingMode = 0; tmp=1; for (i = 1; i < argc;i++) { if (!strcmp ("-I", argv[i])) { printf("\nInstantaneous BottleNeck\n"); CodingMode = 1; i++; tmp=0; } if (!strcmp ("-m", argv[i])) { mode=atoi(argv[i+1]); i++; } if (!strcmp ("-PLC", argv[i])) { plc=1; } if (!strcmp ("-NB", argv[i])) { nbTest = atoi(argv[i + 1]); i++; } } if(mode<0) { printf("\nError! Mode must be set: -m 0 \n"); exit(0); } if (CodingMode == 0) { printf("\nAdaptive BottleNeck\n"); } /* Get Bottleneck value */ bottleneck = atoi(argv[2-tmp]); if (bottleneck == 0) { sscanf(argv[2-tmp], "%s", bottleneck_file); f_bn = fopen(bottleneck_file, "rb"); if (f_bn == NULL) { printf("No value provided for BottleNeck and cannot read file %s.\n", bottleneck_file); exit(0); } else { printf("reading bottleneck rates from file %s\n\n",bottleneck_file); if (fscanf(f_bn, "%d", &bottleneck) == EOF) { /* Set pointer to beginning of file */ fseek(f_bn, 0L, SEEK_SET); fscanf(f_bn, "%d", &bottleneck); } /* Bottleneck is a cosine function * Matlab code for writing the bottleneck file: * BottleNeck_10ms = 20e3 + 10e3 * cos((0:5999)/5999*2*pi); * fid = fopen('bottleneck.txt', 'wb'); * fprintf(fid, '%d\n', BottleNeck_10ms); fclose(fid); */ } } else { printf("\nfixed bottleneck rate of %d bits/s\n\n", bottleneck); } /* Get Input and Output files */ sscanf(argv[argc-2], "%s", inname); sscanf(argv[argc-1], "%s", outname); if ((inp = fopen(inname,"rb")) == NULL) { printf(" iSAC: Cannot read file %s.\n", inname); exit(1); } if ((outp = fopen(outname,"wb")) == NULL) { printf(" iSAC: Cannot write file %s.\n", outname); exit(1); } printf("\nInput:%s\nOutput:%s\n", inname, outname); i=0; while (outname[i]!='\0') { bitfilename[i]=outname[i]; i++; } i-=4; for (j=0;j<9;j++, i++) bitfilename[i]=bitending[j]; bitfilename[i]='\0'; if ((bitsp = fopen(bitfilename,"wb")) == NULL) { printf(" iSAC: Cannot read file %s.\n", bitfilename); exit(1); } printf("Bitstream:%s\n\n", bitfilename); starttime = clock()/(double)CLOCKS_PER_SEC; /* Runtime statistics */ /* Initialize the ISAC and BN structs */ WebRtcIsac_create(&ISAC_main_inst); /* WebRtcIsacfix_AssignSize(&sss); iSACstruct=malloc(sss); WebRtcIsacfix_Assign(&ISACFIX_main_inst,iSACstruct);*/ WebRtcIsacfix_Create(&ISACFIX_main_inst); BN_data.send_time = 0; BN_data.arrival_time = 0; BN_data.sample_count = 0; BN_data.rtp_number = 0; /* Initialize encoder and decoder */ framecnt= 0; endfile = 0; if (mode==0) { /* Encode using FLOAT, decode using FLOAT */ printf("Coding mode: Encode using FLOAT, decode using FLOAT \n\n"); /* Init iSAC FLOAT */ WebRtcIsac_EncoderInit(ISAC_main_inst, CodingMode); WebRtcIsac_DecoderInit(ISAC_main_inst); if (CodingMode == 1) { err = WebRtcIsac_Control(ISAC_main_inst, bottleneck, framesize); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsac_GetErrorCode(ISAC_main_inst); printf("\n\n Error in initialization: %d.\n\n", errtype); // exit(EXIT_FAILURE); } } } else if (mode==1) { /* Encode using FLOAT, decode using FIX */ printf("Coding mode: Encode using FLOAT, decode using FIX \n\n"); /* Init iSAC FLOAT */ WebRtcIsac_EncoderInit(ISAC_main_inst, CodingMode); WebRtcIsac_DecoderInit(ISAC_main_inst); if (CodingMode == 1) { err = WebRtcIsac_Control(ISAC_main_inst, bottleneck, framesize); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsac_GetErrorCode(ISAC_main_inst); printf("\n\n Error in initialization: %d.\n\n", errtype); // exit(EXIT_FAILURE); } } /* Init iSAC FIX */ WebRtcIsacfix_EncoderInit(ISACFIX_main_inst, CodingMode); WebRtcIsacfix_DecoderInit(ISACFIX_main_inst); if (CodingMode == 1) { err = WebRtcIsacfix_Control(ISACFIX_main_inst, bottleneck, framesize); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\n Error in initialization: %d.\n\n", errtype); //exit(EXIT_FAILURE); } } } else if (mode==2) { /* Encode using FIX, decode using FLOAT */ printf("Coding mode: Encode using FIX, decode using FLOAT \n\n"); /* Init iSAC FLOAT */ WebRtcIsac_EncoderInit(ISAC_main_inst, CodingMode); WebRtcIsac_DecoderInit(ISAC_main_inst); if (CodingMode == 1) { err = WebRtcIsac_Control(ISAC_main_inst, bottleneck, framesize); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsac_GetErrorCode(ISAC_main_inst); printf("\n\n Error in initialization: %d.\n\n", errtype); //exit(EXIT_FAILURE); } } /* Init iSAC FIX */ WebRtcIsacfix_EncoderInit(ISACFIX_main_inst, CodingMode); WebRtcIsacfix_DecoderInit(ISACFIX_main_inst); if (CodingMode == 1) { err = WebRtcIsacfix_Control(ISACFIX_main_inst, bottleneck, framesize); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\n Error in initialization: %d.\n\n", errtype); //exit(EXIT_FAILURE); } } } else if (mode==3) { printf("Coding mode: Encode using FIX, decode using FIX \n\n"); WebRtcIsacfix_EncoderInit(ISACFIX_main_inst, CodingMode); WebRtcIsacfix_DecoderInit(ISACFIX_main_inst); if (CodingMode == 1) { err = WebRtcIsacfix_Control(ISACFIX_main_inst, bottleneck, framesize); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\n Error in initialization: %d.\n\n", errtype); //exit(EXIT_FAILURE); } } } else printf("Mode must be value between 0 and 3\n"); *speechType = 1; //#define BI_TEST 1 #ifdef BI_TEST err = WebRtcIsacfix_SetMaxPayloadSize(ISACFIX_main_inst, 300); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\n Error in setMaxPayloadSize: %d.\n\n", errtype); fclose(inp); fclose(outp); fclose(bitsp); return(EXIT_FAILURE); } #endif while (endfile == 0) { cur_framesmpls = 0; while (1) { /* Read 10 ms speech block */ if (nbTest != 1) endfile = readframe(shortdata, inp, FRAMESAMPLES_10ms); else endfile = readframe(shortdata, inp, (FRAMESAMPLES_10ms/2)); /* iSAC encoding */ if (mode==0 || mode ==1) { stream_len = WebRtcIsac_Encode(ISAC_main_inst, shortdata, streamdata); if (stream_len < 0) { /* exit if returned with error */ errtype=WebRtcIsac_GetErrorCode(ISAC_main_inst); printf("\n\nError in encoder: %d.\n\n", errtype); // exit(EXIT_FAILURE); } } else if (mode==2 || mode==3) { /* iSAC encoding */ if (nbTest != 1) stream_len = WebRtcIsacfix_Encode(ISACFIX_main_inst, shortdata, streamdata); else stream_len = WebRtcIsacfix_EncodeNb(ISACFIX_main_inst, shortdata, streamdata); if (stream_len < 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\nError in encoder: %d.\n\n", errtype); // exit(EXIT_FAILURE); } } cur_framesmpls += FRAMESAMPLES_10ms; /* read next bottleneck rate */ if (f_bn != NULL) { if (fscanf(f_bn, "%d", &bottleneck) == EOF) { /* Set pointer to beginning of file */ fseek(f_bn, 0L, SEEK_SET); fscanf(f_bn, "%d", &bottleneck); } if (CodingMode == 1) { if (mode==0 || mode==1) WebRtcIsac_Control(ISAC_main_inst, bottleneck, framesize); else if (mode==2 || mode==3) WebRtcIsacfix_Control(ISACFIX_main_inst, bottleneck, framesize); } } /* exit encoder loop if the encoder returned a bitstream */ if (stream_len != 0) break; } fwrite(streamdata, 1, stream_len, bitsp); /* NOTE! Writes bytes to file */ /* simulate packet handling through NetEq and the modem */ get_arrival_time(cur_framesmpls, stream_len, bottleneck, &BN_data); //***************************** if (1){ if (mode==0) { err = WebRtcIsac_UpdateBwEstimate(ISAC_main_inst, streamdata, stream_len, BN_data.rtp_number, BN_data.arrival_time); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsac_GetErrorCode(ISAC_main_inst); printf("\n\nError in decoder: %d.\n\n", errtype); //exit(EXIT_FAILURE); } /* iSAC decoding */ declen = WebRtcIsac_Decode(ISAC_main_inst, streamdata, stream_len, decoded, speechType); if (declen <= 0) { /* exit if returned with error */ errtype=WebRtcIsac_GetErrorCode(ISAC_main_inst); printf("\n\nError in decoder: %d.\n\n", errtype); //exit(EXIT_FAILURE); } } else if (mode==1) { err = WebRtcIsac_UpdateBwEstimate(ISAC_main_inst, streamdata, stream_len, BN_data.rtp_number, BN_data.arrival_time); err = WebRtcIsacfix_UpdateBwEstimate1(ISACFIX_main_inst, streamdata, stream_len, BN_data.rtp_number, BN_data.arrival_time); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\nError in decoder: %d.\n\n", errtype); //exit(EXIT_FAILURE); } declen = WebRtcIsac_Decode(ISAC_main_inst, streamdata, stream_len, decoded, speechType); /* iSAC decoding */ if (plc && (framecnt+1)%10 == 0) { if (nbTest !=2 ) declen = WebRtcIsacfix_DecodePlc( ISACFIX_main_inst, decoded, 1 ); else declen = WebRtcIsacfix_DecodePlcNb( ISACFIX_main_inst, decoded, 1 ); } else { if (nbTest !=2 ) declen = WebRtcIsacfix_Decode(ISACFIX_main_inst, streamdata, stream_len, decoded, speechType); else declen = WebRtcIsacfix_DecodeNb(ISACFIX_main_inst, streamdata, stream_len, decoded, speechType); } if (declen <= 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\nError in decoder: %d.\n\n", errtype); //exit(EXIT_FAILURE); } } else if (mode==2) { err = WebRtcIsacfix_UpdateBwEstimate1(ISACFIX_main_inst, streamdata, stream_len, BN_data.rtp_number, BN_data.arrival_time); err = WebRtcIsac_UpdateBwEstimate(ISAC_main_inst, streamdata, stream_len, BN_data.rtp_number, BN_data.arrival_time); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsac_GetErrorCode(ISAC_main_inst); printf("\n\nError in decoder: %d.\n\n", errtype); //exit(EXIT_FAILURE); } /* iSAC decoding */ declen = WebRtcIsac_Decode(ISAC_main_inst, streamdata, stream_len, decoded, speechType); if (declen <= 0) { /* exit if returned with error */ errtype=WebRtcIsac_GetErrorCode(ISAC_main_inst); printf("\n\nError in decoder: %d.\n\n", errtype); //exit(EXIT_FAILURE); } } else if (mode==3) { err = WebRtcIsacfix_UpdateBwEstimate(ISACFIX_main_inst, streamdata, stream_len, BN_data.rtp_number, BN_data.send_time, BN_data.arrival_time); if (err < 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\nError in decoder: %d.\n\n", errtype); //exit(EXIT_FAILURE); } /* iSAC decoding */ if (plc && (framecnt+1)%10 == 0) { if (nbTest !=2 ) declen = WebRtcIsacfix_DecodePlc( ISACFIX_main_inst, decoded, 1 ); else declen = WebRtcIsacfix_DecodePlcNb( ISACFIX_main_inst, decoded, 1 ); } else { if (nbTest !=2 ) declen = WebRtcIsacfix_Decode(ISACFIX_main_inst, streamdata, stream_len, decoded, speechType); else declen = WebRtcIsacfix_DecodeNb(ISACFIX_main_inst, streamdata, stream_len, decoded, speechType); } if (declen <= 0) { /* exit if returned with error */ errtype=WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst); printf("\n\nError in decoder: %d.\n\n", errtype); //exit(EXIT_FAILURE); } } /* Write decoded speech frame to file */ fwrite(decoded, sizeof(int16_t), declen, outp); } fprintf(stderr," \rframe = %d", framecnt); framecnt++; #ifdef _DEBUG totalsmpls += declen; totalbits += 8 * stream_len; kbps = ((double) FS) / ((double) cur_framesmpls) * 8.0 * stream_len / 1000.0;// kbits/s fy = fopen("bit_rate.dat", "a"); fprintf(fy, "Frame %i = %0.14f\n", framecnt, kbps); fclose(fy); #endif /* _DEBUG */ } #ifdef _DEBUG printf("\n\ntotal bits = %d bits", totalbits); printf("\nmeasured average bitrate = %0.3f kbits/s", (double)totalbits *(FS/1000) / totalsmpls); printf("\n"); #endif /* _DEBUG */ /* Runtime statistics */ runtime = (double)(clock()/(double)CLOCKS_PER_SEC-starttime); length_file = ((double)framecnt*(double)declen/FS); printf("\n\nLength of speech file: %.1f s\n", length_file); printf("Time to run iSAC: %.2f s (%.2f %% of realtime)\n\n", runtime, (100*runtime/length_file)); printf("---------------------END----------------------\n"); fclose(inp); fclose(outp); WebRtcIsac_Free(ISAC_main_inst); WebRtcIsacfix_Free(ISACFIX_main_inst); // fclose(histfile); // fclose(ratefile); return 0; }
gpl-3.0
Zentyal/samba
testprogs/win32/prepare_dcpromo/prepare_dcpromo.c
69
27369
/* Copyright (C) Stefan Metzmacher <metze@samba.org> 2010 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/>. Published to the public domain */ /* * This tool can set the DOMAIN-SID and nextRid counter in * the local SAM on windows servers (tested with w2k8r2) * * dcpromo will use this values for the ad domain it creates. * * This might be useful for upgrades from a Samba3 domain. */ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> /* Convert a binary SID to a character string */ static DWORD SidToString(const SID *sid, char **string) { DWORD id_auth; int i, ofs, maxlen; char *result; if (!sid) { return ERROR_INVALID_SID; } maxlen = sid->SubAuthorityCount * 11 + 25; result = (char *)malloc(maxlen); if (result == NULL) { return ERROR_NOT_ENOUGH_MEMORY; } /* * BIG NOTE: this function only does SIDS where the identauth is not * >= ^32 in a range of 2^48. */ id_auth = sid->IdentifierAuthority.Value[5] + (sid->IdentifierAuthority.Value[4] << 8) + (sid->IdentifierAuthority.Value[3] << 16) + (sid->IdentifierAuthority.Value[2] << 24); ofs = snprintf(result, maxlen, "S-%u-%lu", (unsigned int)sid->Revision, (unsigned long)id_auth); for (i = 0; i < sid->SubAuthorityCount; i++) { ofs += snprintf(result + ofs, maxlen - ofs, "-%lu", (unsigned long)sid->SubAuthority[i]); } *string = result; return ERROR_SUCCESS; } static DWORD StringToSid(const char *str, SID *sid) { const char *p; char *q; DWORD x; if (!sid) { return ERROR_INVALID_PARAMETER; } /* Sanity check for either "S-" or "s-" */ if (!str || (str[0]!='S' && str[0]!='s') || (str[1]!='-')) { return ERROR_INVALID_PARAMETER; } /* Get the SID revision number */ p = str+2; x = (DWORD)strtol(p, &q, 10); if (x==0 || !q || *q!='-') { return ERROR_INVALID_SID; } sid->Revision = (BYTE)x; /* Next the Identifier Authority. This is stored in big-endian in a 6 byte array. */ p = q+1; x = (DWORD)strtol(p, &q, 10); if (!q || *q!='-') { return ERROR_INVALID_SID; } sid->IdentifierAuthority.Value[5] = (x & 0x000000ff); sid->IdentifierAuthority.Value[4] = (x & 0x0000ff00) >> 8; sid->IdentifierAuthority.Value[3] = (x & 0x00ff0000) >> 16; sid->IdentifierAuthority.Value[2] = (x & 0xff000000) >> 24; sid->IdentifierAuthority.Value[1] = 0; sid->IdentifierAuthority.Value[0] = 0; /* now read the the subauthorities */ p = q +1; sid->SubAuthorityCount = 0; while (sid->SubAuthorityCount < 6) { x=(DWORD)strtoul(p, &q, 10); if (p == q) break; if (q == NULL) { return ERROR_INVALID_SID; } sid->SubAuthority[sid->SubAuthorityCount++] = x; if ((*q!='-') || (*q=='\0')) break; p = q + 1; } /* IF we ended early, then the SID could not be converted */ if (q && *q!='\0') { return ERROR_INVALID_SID; } return ERROR_SUCCESS; } #define MIN(a,b) ((a)<(b)?(a):(b)) static void print_asc(const unsigned char *buf,int len) { int i; for (i=0;i<len;i++) printf("%c", isprint(buf[i])?buf[i]:'.'); } static void dump_data(const unsigned char *buf1,int len) { const unsigned char *buf = (const unsigned char *)buf1; int i=0; if (len<=0) return; printf("[%03X] ",i); for (i=0;i<len;) { printf("%02X ",(int)buf[i]); i++; if (i%8 == 0) printf(" "); if (i%16 == 0) { print_asc(&buf[i-16],8); printf(" "); print_asc(&buf[i-8],8); printf("\n"); if (i<len) printf("[%03X] ",i); } } if (i%16) { int n; n = 16 - (i%16); printf(" "); if (n>8) printf(" "); while (n--) printf(" "); n = MIN(8,i%16); print_asc(&buf[i-(i%16)],n); printf( " " ); n = (i%16) - n; if (n>0) print_asc(&buf[i-n],n); printf("\n"); } } static DWORD calc_tmp_HKLM_SECURITY_SD(SECURITY_DESCRIPTOR *old_sd, SID *current_user_sid, SECURITY_DESCRIPTOR **_old_parent_sd, SECURITY_DESCRIPTOR **_old_child_sd, SECURITY_DESCRIPTOR **_new_parent_sd, SECURITY_DESCRIPTOR **_new_child_sd) { LONG status; DWORD cbSecurityDescriptor = 0; SECURITY_DESCRIPTOR *old_parent_sd = NULL; SECURITY_DESCRIPTOR *old_child_sd = NULL; SECURITY_DESCRIPTOR *new_parent_sd = NULL; SECURITY_DESCRIPTOR *new_child_sd = NULL; BOOL ok; ACL *old_Dacl = NULL; ACL *new_Dacl = NULL; ACL_SIZE_INFORMATION dacl_info; DWORD i = 0; SECURITY_DESCRIPTOR *AbsoluteSD = NULL; DWORD dwAbsoluteSDSize = 0; DWORD dwRelativeSDSize = 0; DWORD dwDaclSize = 0; ACL *Sacl = NULL; DWORD dwSaclSize = 0; SID *Owner = NULL; DWORD dwOwnerSize = 0; SID *PrimaryGroup = NULL; DWORD dwPrimaryGroupSize = 0; ACCESS_ALLOWED_ACE *ace = NULL; ok = MakeAbsoluteSD(old_sd, NULL, &dwAbsoluteSDSize, NULL, &dwDaclSize, NULL, &dwSaclSize, NULL, &dwOwnerSize, NULL, &dwPrimaryGroupSize); if (!ok) { status = GetLastError(); } if (status != ERROR_INSUFFICIENT_BUFFER) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } AbsoluteSD = (SECURITY_DESCRIPTOR *)malloc(dwAbsoluteSDSize+1024); if (AbsoluteSD == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } old_Dacl = (ACL *)malloc(dwDaclSize + 1024); if (old_Dacl == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } Sacl = (ACL *)malloc(dwSaclSize); if (Sacl == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } Owner = (SID *)malloc(dwOwnerSize); if (Owner == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } PrimaryGroup = (SID *)malloc(dwPrimaryGroupSize); if (PrimaryGroup == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } ok = MakeAbsoluteSD(old_sd, AbsoluteSD, &dwAbsoluteSDSize, old_Dacl, &dwDaclSize, Sacl, &dwSaclSize, Owner, &dwOwnerSize, PrimaryGroup, &dwPrimaryGroupSize); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } AbsoluteSD->Control |= SE_DACL_AUTO_INHERITED | SE_DACL_AUTO_INHERIT_REQ | SE_DACL_PROTECTED; dwRelativeSDSize = 0; ok = MakeSelfRelativeSD(AbsoluteSD, NULL, &dwRelativeSDSize); if (!ok) { status = GetLastError(); } if (status != ERROR_INSUFFICIENT_BUFFER) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return ERROR_NOT_ENOUGH_MEMORY; } old_parent_sd = (SECURITY_DESCRIPTOR *)malloc(dwRelativeSDSize); if (old_parent_sd == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } ok = MakeSelfRelativeSD(AbsoluteSD, old_parent_sd, &dwRelativeSDSize); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } ok = GetAclInformation(old_Dacl, &dacl_info, sizeof(dacl_info), AclSizeInformation); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } new_Dacl = (ACL *)calloc(dacl_info.AclBytesInUse + 1024, 1); if (new_Dacl == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } InitializeAcl(new_Dacl, dacl_info.AclBytesInUse + 1024, ACL_REVISION); ok = AddAccessAllowedAce(new_Dacl, ACL_REVISION, KEY_ALL_ACCESS, current_user_sid); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } ok = GetAce(new_Dacl, 0, (LPVOID *)&ace); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } ace->Header.AceFlags |= CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE; for (i=0; i < dacl_info.AceCount; i++) { ok = GetAce(old_Dacl, i, (LPVOID *)&ace); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } ok = AddAce(new_Dacl, ACL_REVISION, MAXDWORD, ace, ace->Header.AceSize); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } } AbsoluteSD->Dacl = new_Dacl; dwRelativeSDSize = 0; ok = MakeSelfRelativeSD(AbsoluteSD, NULL, &dwRelativeSDSize); if (!ok) { status = GetLastError(); } if (status != ERROR_INSUFFICIENT_BUFFER) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return ERROR_NOT_ENOUGH_MEMORY; } new_parent_sd = (SECURITY_DESCRIPTOR *)malloc(dwRelativeSDSize); if (new_parent_sd == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } ok = MakeSelfRelativeSD(AbsoluteSD, new_parent_sd, &dwRelativeSDSize); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } for (i=0; i < dacl_info.AceCount; i++) { ok = GetAce(old_Dacl, i, (LPVOID *)&ace); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } ace->Header.AceFlags |= INHERITED_ACE; } AbsoluteSD->Control &= ~SE_DACL_PROTECTED; AbsoluteSD->Dacl = old_Dacl; dwRelativeSDSize = 0; ok = MakeSelfRelativeSD(AbsoluteSD, NULL, &dwRelativeSDSize); if (!ok) { status = GetLastError(); } if (status != ERROR_INSUFFICIENT_BUFFER) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return ERROR_NOT_ENOUGH_MEMORY; } old_child_sd = (SECURITY_DESCRIPTOR *)malloc(dwRelativeSDSize); if (old_child_sd == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } ok = MakeSelfRelativeSD(AbsoluteSD, old_child_sd, &dwRelativeSDSize); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } for (i=0; i < dacl_info.AceCount + 1; i++) { ok = GetAce(new_Dacl, i, (LPVOID *)&ace); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } ace->Header.AceFlags |= INHERITED_ACE; } AbsoluteSD->Dacl = new_Dacl; dwRelativeSDSize = 0; ok = MakeSelfRelativeSD(AbsoluteSD, NULL, &dwRelativeSDSize); if (!ok) { status = GetLastError(); } if (status != ERROR_INSUFFICIENT_BUFFER) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return ERROR_NOT_ENOUGH_MEMORY; } new_child_sd = (SECURITY_DESCRIPTOR *)malloc(dwRelativeSDSize); if (new_child_sd == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } ok = MakeSelfRelativeSD(AbsoluteSD, new_child_sd, &dwRelativeSDSize); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } *_old_parent_sd = old_parent_sd; *_old_child_sd = old_child_sd; *_new_parent_sd = new_parent_sd; *_new_child_sd = new_child_sd; return ERROR_SUCCESS; } static DWORD inherit_SD(HKEY parent_hk, char *current_key, BOOL reset, SECURITY_DESCRIPTOR *current_sd, SECURITY_DESCRIPTOR *child_sd) { DWORD status; DWORD i = 0; HKEY current_hk; if (!reset) { status = RegOpenKeyEx(parent_hk, current_key, 0, /* options */ WRITE_DAC, /* samDesired */ &current_hk); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } status = RegSetKeySecurity(current_hk, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION | UNPROTECTED_SACL_SECURITY_INFORMATION, current_sd /* pSecurityDescriptor */ ); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } RegCloseKey(current_hk); } status = RegOpenKeyEx(parent_hk, current_key, 0, /* options */ KEY_ENUMERATE_SUB_KEYS, /* samDesired */ &current_hk); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } for (i=0; ; i++) { char subkey[10240]; HKEY hk_child; memset(subkey, 0, sizeof(subkey)); status = RegEnumKey(current_hk, i, subkey, sizeof(subkey)); if (status == ERROR_NO_MORE_ITEMS) { break; } if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } #if 0 printf("subkey: %s\n", subkey); #endif status = inherit_SD(current_hk, subkey, reset, child_sd, child_sd); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } } RegCloseKey(current_hk); if (reset) { status = RegOpenKeyEx(parent_hk, current_key, 0, /* options */ WRITE_DAC, /* samDesired */ &current_hk); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } status = RegSetKeySecurity(current_hk, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION | UNPROTECTED_SACL_SECURITY_INFORMATION, current_sd /* pSecurityDescriptor */ ); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } RegCloseKey(current_hk); } return ERROR_SUCCESS; } static DWORD replaceSIDBuffer(BYTE *buf, DWORD len, SID *oldDomainSid, SID *newDomainSid) { DWORD ret = 0; BYTE *oldb = ((BYTE *)oldDomainSid)+2; BYTE *newb = ((BYTE *)newDomainSid)+2; int cmp; #if 0 printf("replaceSIDBuffer: %u\n", len); dump_data(buf, len); #endif if (len < 24) { return 0; } if (buf[0] != SID_REVISION) { return 0; } switch (buf[1]) { case 4: ret = 24; break; case 5: if (len < 28) { return 0; } ret = 28; break; default: return 0; } #if 0 printf("oldb:\n"); dump_data(oldb, 22); #endif cmp = memcmp(&buf[2], oldb, 22); if (cmp != 0) { return 0; } memcpy(&buf[2], newb, 22); return ret; } static DWORD replaceSID(HKEY parent_hk, const char *parent_path, const char *current_key, SID *oldDomainSid, SID *newDomainSid) { DWORD status; DWORD i = 0; HKEY current_hk; char current_path[10240]; snprintf(current_path, sizeof(current_path), "%s\\%s", parent_path, current_key); status = RegOpenKeyEx(parent_hk, current_key, 0, /* options */ KEY_ALL_ACCESS, /* samDesired */ &current_hk); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } for (i=0; ; i++) { char subkey[10240]; HKEY hk_child; memset(subkey, 0, sizeof(subkey)); status = RegEnumKey(current_hk, i, subkey, sizeof(subkey)); if (status == ERROR_NO_MORE_ITEMS) { break; } if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } #if 0 printf("subkey: %s\n", subkey); #endif status = replaceSID(current_hk, current_path, subkey, oldDomainSid, newDomainSid); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } } for (i=0; ; i++) { char valueName[10240]; DWORD cbValueName; DWORD valueType = 0; BYTE *valueData = NULL; DWORD cbValueData = 0; DWORD ofs = 0; BOOL modified = FALSE; memset(valueName, 0, sizeof(valueName)); cbValueName = sizeof(valueName)-1; status = RegEnumValue(current_hk, i, valueName, &cbValueName, NULL, NULL, NULL, &cbValueData); if (status == ERROR_NO_MORE_ITEMS) { break; } if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } valueData = (BYTE *)malloc(cbValueData); if (valueData == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return ERROR_NOT_ENOUGH_MEMORY; } cbValueName = sizeof(valueName)-1; status = RegEnumValue(current_hk, i, valueName, &cbValueName, NULL, &valueType, valueData, &cbValueData); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } if (valueType != REG_BINARY) { free(valueData); continue; } for (ofs=0; ofs < cbValueData;) { DWORD len; len = replaceSIDBuffer(valueData + ofs, cbValueData - ofs, oldDomainSid, newDomainSid); if (len == 0) { ofs += 4; continue; } #if 0 printf("%s value[%u]:%s modified ofs:%u (0x%X) len:%u\n", current_path, i, valueName, ofs, ofs, len); #endif ofs += len; modified = TRUE; } if (!modified) { free(valueData); continue; } printf("%s value[%u]:%s replacing data\n", current_path, i, valueName); status = RegSetValueEx(current_hk, valueName, 0, valueType, valueData, cbValueData); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } free(valueData); } RegCloseKey(current_hk); return ERROR_SUCCESS; } int main(int argc, char *argv[]) { LONG status; HANDLE tokenHandle = NULL; TOKEN_USER *tokenUser = NULL; DWORD cbTokenUser = 0; HKEY hklm; HKEY hk_security; HKEY hk_account_domain; DWORD cbSecurityDescriptor = 0; SECURITY_DESCRIPTOR *security_old_sd = NULL; SECURITY_DESCRIPTOR *security_parent_old_sd = NULL; SECURITY_DESCRIPTOR *security_child_old_sd = NULL; SECURITY_DESCRIPTOR *security_parent_new_sd = NULL; SECURITY_DESCRIPTOR *security_child_new_sd = NULL; SID *currentUserSid = NULL; char *currentUserSidString = NULL; BOOL ok; DWORD cbTmp = 0; BYTE *AccountDomainF = NULL; DWORD cbAccountDomainF = 0; DWORD AccountDomainFType = 0; DWORD *nextRid = NULL; DWORD oldNextRid = 0; DWORD newNextRid = 0; BYTE *AccountDomainV = NULL; DWORD cbAccountDomainV = 0; SID *oldDomainSid = NULL; char *oldDomainSidString = NULL; SID *newDomainSid = NULL; const char *newDomainSidString = NULL; if (argc < 2 || argc > 3) { printf("Usage: %s <DOMAINSID> [<NEXTRID>]\n", argv[0]); return -1; } newDomainSidString = argv[1]; newDomainSid = (SID *)malloc(24); if (newDomainSid == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return -1; } status = StringToSid(newDomainSidString, newDomainSid); if (status != ERROR_SUCCESS) { printf("Failed to parse DOMAINSID[%s]: Error: %d (0x%X)\n", newDomainSidString, status, status); return -1; } if (newDomainSid->SubAuthorityCount != 4) { printf("DOMAINSID[%s]: Invalid SubAuthorityCount[%u] should be 4\n", newDomainSidString, newDomainSid->SubAuthorityCount); return -1; } if (argc == 3) { char *q = NULL; newNextRid = (DWORD)strtoul(argv[2], &q, 10); if (newNextRid == 0 || newNextRid == 0xFFFFFFFF || !q || *q!='\0') { printf("Invalid newNextRid[%s]\n", argv[2]); return -1; } if (newNextRid < 1000) { printf("newNextRid[%u] < 1000\n", newNextRid); return -1; } } ok = OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &tokenHandle); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } ok = GetTokenInformation(tokenHandle, TokenUser, NULL, 0, &cbTokenUser); if (!ok) { status = GetLastError(); } if (status != ERROR_INSUFFICIENT_BUFFER) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } tokenUser = (TOKEN_USER *)malloc(cbTokenUser); if (tokenUser == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return -1; } ok = GetTokenInformation(tokenHandle, TokenUser, tokenUser, cbTokenUser, &cbTokenUser); if (!ok) { status = GetLastError(); printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } currentUserSid = tokenUser->User.Sid; status = SidToString(currentUserSid, &currentUserSidString); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } status = RegConnectRegistry(NULL, HKEY_LOCAL_MACHINE, &hklm); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } status = RegOpenKeyEx(hklm, "SECURITY", 0, /* options */ READ_CONTROL, /* samDesired */ &hk_security); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } status = RegGetKeySecurity(hk_security, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION | UNPROTECTED_SACL_SECURITY_INFORMATION, NULL, /* pSecurityDescriptor */ &cbSecurityDescriptor /* lpcbSecurityDescriptor */ ); if (status != ERROR_INSUFFICIENT_BUFFER) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } security_old_sd = (SECURITY_DESCRIPTOR *)malloc(cbSecurityDescriptor); if (security_old_sd == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return -1; } status = RegGetKeySecurity(hk_security, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION | UNPROTECTED_SACL_SECURITY_INFORMATION, security_old_sd, /* pSecurityDescriptor */ &cbSecurityDescriptor /* lpcbSecurityDescriptor */ ); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } RegCloseKey(hk_security); printf("currentUserSid: %s\n", currentUserSidString); status = calc_tmp_HKLM_SECURITY_SD(security_old_sd, currentUserSid, &security_parent_old_sd, &security_child_old_sd, &security_parent_new_sd, &security_child_new_sd); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } printf("Grant full access to HKLM\\SECURITY\n"); status = inherit_SD(hklm, "SECURITY", FALSE, security_parent_new_sd, security_child_new_sd); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } status = RegOpenKeyEx(hklm, "SECURITY\\SAM\\Domains\\Account", 0, /* options */ KEY_ALL_ACCESS, /* samDesired */ &hk_account_domain); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } status = RegQueryValueEx(hk_account_domain, "F", NULL, NULL, NULL, &cbAccountDomainF); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } AccountDomainF = (BYTE *)malloc(cbAccountDomainF); if (AccountDomainF == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return -1; } status = RegQueryValueEx(hk_account_domain, "F", NULL, NULL, AccountDomainF, &cbAccountDomainF); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } nextRid = (DWORD *)((BYTE *)AccountDomainF + 0x48); oldNextRid = *nextRid; if (newNextRid == 0) { newNextRid = oldNextRid; } printf("AccountDomainF: %u bytes\n", cbAccountDomainF); status = RegQueryValueEx(hk_account_domain, "V", NULL, NULL, NULL, &cbAccountDomainV); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } AccountDomainV = (BYTE *)malloc(cbAccountDomainV); if (AccountDomainV == NULL) { printf("LINE:%u: Error: no memory\n", __LINE__); return -1; } status = RegQueryValueEx(hk_account_domain, "V", NULL, NULL, AccountDomainV, &cbAccountDomainV); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } printf("AccountDomainV: %u bytes\n", cbAccountDomainV); oldDomainSid = (SID *)((BYTE *)AccountDomainV + (cbAccountDomainV - 24)); status = SidToString(oldDomainSid, &oldDomainSidString); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } printf("Old Domain:%s, NextRid: %u (0x%08X)\n", oldDomainSidString, oldNextRid, oldNextRid); printf("New Domain:%s, NextRid: %u (0x%08X)\n", newDomainSidString, newNextRid, newNextRid); status = replaceSID(hklm, "HKLM", "SECURITY\\SAM\\Domains", oldDomainSid, newDomainSid); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); goto failed; } status = RegQueryValueEx(hk_account_domain, "F", NULL, &AccountDomainFType, AccountDomainF, &cbAccountDomainF); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } nextRid = (DWORD *)((BYTE *)AccountDomainF + 0x48); *nextRid = newNextRid; printf("AccountDomainF replacing data (nextRid)\n"); status = RegSetValueEx(hk_account_domain, "F", 0, AccountDomainFType, AccountDomainF, cbAccountDomainF); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return status; } printf("Withdraw full access to HKLM\\SECURITY\n"); status = inherit_SD(hklm, "SECURITY", TRUE, security_parent_old_sd, security_child_old_sd); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } printf("DONE!\n"); return 0; failed: printf("Withdraw full access to HKLM\\SECURITY\n"); status = inherit_SD(hklm, "SECURITY", TRUE, security_parent_old_sd, security_child_old_sd); if (status != ERROR_SUCCESS) { printf("LINE:%u: Error: %d (0x%X)\n", __LINE__, status, status); return -1; } printf("FAILED!\n"); return 0; }
gpl-3.0
tianhang/QrCodeScan
ZBarLib/jni/decoder/codabar.c
77
12304
/*------------------------------------------------------------------------ * Copyright 2011 (c) Jeff Brown <spadix@users.sourceforge.net> * * This file is part of the ZBar Bar Code Reader. * * The ZBar Bar Code Reader is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * The ZBar Bar Code Reader 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with the ZBar Bar Code Reader; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA * * http://sourceforge.net/projects/zbar *------------------------------------------------------------------------*/ #include <config.h> #include <string.h> /* memmove */ #include <zbar.h> #ifdef DEBUG_CODABAR # define DEBUG_LEVEL (DEBUG_CODABAR) #endif #include "debug.h" #include "decoder.h" #define NIBUF 6 /* initial scan buffer size */ static const signed char codabar_lo[12] = { 0x0, 0x1, 0x4, 0x5, 0x2, 0xa, 0xb, 0x9, 0x6, 0x7, 0x8, 0x3 }; static const unsigned char codabar_hi[8] = { 0x1, 0x4, 0x7, 0x6, 0x2, 0x3, 0x0, 0x5 }; static const unsigned char codabar_characters[20] = "0123456789-$:/.+ABCD"; static inline int check_width (unsigned ref, unsigned w) { unsigned dref = ref; ref *= 4; w *= 4; return(ref - dref <= w && w <= ref + dref); } static inline signed char codabar_decode7 (zbar_decoder_t *dcode) { codabar_decoder_t *codabar = &dcode->codabar; unsigned s = codabar->s7; dbprintf(2, " s=%d", s); if(s < 7) return(-1); /* check width */ if(!check_width(codabar->width, s)) { dbprintf(2, " [width]"); return(-1); } /* extract min/max bar */ unsigned ibar = decode_sortn(dcode, 4, 1); dbprintf(2, " bar=%04x", ibar); unsigned wbmax = get_width(dcode, ibar & 0xf); unsigned wbmin = get_width(dcode, ibar >> 12); if(8 * wbmin < wbmax || 3 * wbmin > 2 * wbmax) { dbprintf(2, " [bar outer ratio]"); return(-1); } unsigned wb1 = get_width(dcode, (ibar >> 8) & 0xf); unsigned wb2 = get_width(dcode, (ibar >> 4) & 0xf); unsigned long b0b3 = wbmin * wbmax; unsigned long b1b2 = wb1 * wb2; if(b1b2 + b1b2 / 8 < b0b3) { /* single wide bar combinations */ if(8 * wbmin < 5 * wb1 || 8 * wb1 < 5 * wb2 || 4 * wb2 > 3 * wbmax || wb2 * wb2 >= wb1 * wbmax) { dbprintf(2, " [1bar inner ratios]"); return(-1); } ibar = (ibar >> 1) & 0x3; } else if(b1b2 > b0b3 + b0b3 / 8) { /* three wide bars, no wide spaces */ if(4 * wbmin > 3 * wb1 || 8 * wb1 < 5 * wb2 || 8 * wb2 < 5 * wbmax || wbmin * wb2 >= wb1 * wb1) { dbprintf(2, " [3bar inner ratios]"); return(-1); } ibar = (ibar >> 13) + 4; } else { dbprintf(2, " [bar inner ratios]"); return(-1); } unsigned ispc = decode_sort3(dcode, 2); dbprintf(2, "(%x) spc=%03x", ibar, ispc); unsigned wsmax = get_width(dcode, ispc & 0xf); unsigned wsmid = get_width(dcode, (ispc >> 4) & 0xf); unsigned wsmin = get_width(dcode, (ispc >> 8) & 0xf); if(ibar >> 2) { /* verify no wide spaces */ if(8 * wsmin < wsmax || 8 * wsmin < 5 * wsmid || 8 * wsmid < 5 * wsmax) { dbprintf(2, " [0space inner ratios]"); return(-1); } ibar &= 0x3; if(codabar->direction) ibar = 3 - ibar; int c = (0xfcde >> (ibar << 2)) & 0xf; dbprintf(2, " ex[%d]=%x", ibar, c); return(c); } else if(8 * wsmin < wsmax || 3 * wsmin > 2 * wsmax) { dbprintf(2, " [space outer ratio]"); return(-1); } unsigned long s0s2 = wsmin * wsmax; unsigned long s1s1 = wsmid * wsmid; if(s1s1 + s1s1 / 8 < s0s2) { /* single wide space */ if(8 * wsmin < 5 * wsmid || 4 * wsmid > 3 * wsmax) { dbprintf(2, " [1space inner ratios]"); return(-1); } ispc = ((ispc & 0xf) >> 1) - 1; unsigned ic = (ispc << 2) | ibar; if(codabar->direction) ic = 11 - ic; int c = codabar_lo[ic]; dbprintf(2, "(%d) lo[%d]=%x", ispc, ic, c); return(c); } else if(s1s1 > s0s2 + s0s2 / 8) { /* two wide spaces, check start/stop */ if(4 * wsmin > 3 * wsmid || 8 * wsmid < 5 * wsmax) { dbprintf(2, " [2space inner ratios]"); return(-1); } if((ispc >> 8) == 4) { dbprintf(2, " [space comb]"); return(-1); } ispc >>= 10; dbprintf(2, "(%d)", ispc); unsigned ic = ispc * 4 + ibar; zassert(ic < 8, -1, "ic=%d ispc=%d ibar=%d", ic, ispc, ibar); unsigned char c = codabar_hi[ic]; if(c >> 2 != codabar->direction) { dbprintf(2, " [invalid stop]"); return(-1); } c = (c & 0x3) | 0x10; dbprintf(2, " hi[%d]=%x", ic, c); return(c); } else { dbprintf(2, " [space inner ratios]"); return(-1); } } static inline signed char codabar_decode_start (zbar_decoder_t *dcode) { codabar_decoder_t *codabar = &dcode->codabar; unsigned s = codabar->s7; if(s < 8) return(ZBAR_NONE); dbprintf(2, " codabar: s=%d", s); /* check leading quiet zone - spec is 10x */ unsigned qz = get_width(dcode, 8); if((qz && qz * 2 < s) || 4 * get_width(dcode, 0) > 3 * s) { dbprintf(2, " [invalid qz/ics]\n"); return(ZBAR_NONE); } /* check space ratios first */ unsigned ispc = decode_sort3(dcode, 2); dbprintf(2, " spc=%03x", ispc); if((ispc >> 8) == 4) { dbprintf(2, " [space comb]\n"); return(ZBAR_NONE); } /* require 2 wide and 1 narrow spaces */ unsigned wsmax = get_width(dcode, ispc & 0xf); unsigned wsmin = get_width(dcode, ispc >> 8); unsigned wsmid = get_width(dcode, (ispc >> 4) & 0xf); if(8 * wsmin < wsmax || 3 * wsmin > 2 * wsmax || 4 * wsmin > 3 * wsmid || 8 * wsmid < 5 * wsmax || wsmid * wsmid <= wsmax * wsmin) { dbprintf(2, " [space ratio]\n"); return(ZBAR_NONE); } ispc >>= 10; dbprintf(2, "(%d)", ispc); /* check bar ratios */ unsigned ibar = decode_sortn(dcode, 4, 1); dbprintf(2, " bar=%04x", ibar); unsigned wbmax = get_width(dcode, ibar & 0xf); unsigned wbmin = get_width(dcode, ibar >> 12); if(8 * wbmin < wbmax || 3 * wbmin > 2 * wbmax) { dbprintf(2, " [bar outer ratio]\n"); return(ZBAR_NONE); } /* require 1 wide & 3 narrow bars */ unsigned wb1 = get_width(dcode, (ibar >> 8) & 0xf); unsigned wb2 = get_width(dcode, (ibar >> 4) & 0xf); if(8 * wbmin < 5 * wb1 || 8 * wb1 < 5 * wb2 || 4 * wb2 > 3 * wbmax || wb1 * wb2 >= wbmin * wbmax || wb2 * wb2 >= wb1 * wbmax) { dbprintf(2, " [bar inner ratios]\n"); return(ZBAR_NONE); } ibar = ((ibar & 0xf) - 1) >> 1; dbprintf(2, "(%d)", ibar); /* decode combination */ int ic = ispc * 4 + ibar; zassert(ic < 8, ZBAR_NONE, "ic=%d ispc=%d ibar=%d", ic, ispc, ibar); int c = codabar_hi[ic]; codabar->buf[0] = (c & 0x3) | 0x10; /* set character direction */ codabar->direction = c >> 2; codabar->element = 4; codabar->character = 1; codabar->width = codabar->s7; dbprintf(1, " start=%c dir=%x [valid start]\n", codabar->buf[0] + 0x31, codabar->direction); return(ZBAR_PARTIAL); } static inline int codabar_checksum (zbar_decoder_t *dcode, unsigned n) { unsigned chk = 0; unsigned char *buf = dcode->buf; while(n--) chk += *(buf++); return(!!(chk & 0xf)); } static inline zbar_symbol_type_t codabar_postprocess (zbar_decoder_t *dcode) { codabar_decoder_t *codabar = &dcode->codabar; int dir = codabar->direction; dcode->direction = 1 - 2 * dir; int i, n = codabar->character; for(i = 0; i < NIBUF; i++) dcode->buf[i] = codabar->buf[i]; if(dir) /* reverse buffer */ for(i = 0; i < n / 2; i++) { unsigned j = n - 1 - i; char code = dcode->buf[i]; dcode->buf[i] = dcode->buf[j]; dcode->buf[j] = code; } if(TEST_CFG(codabar->config, ZBAR_CFG_ADD_CHECK)) { /* validate checksum */ if(codabar_checksum(dcode, n)) return(ZBAR_NONE); if(!TEST_CFG(codabar->config, ZBAR_CFG_EMIT_CHECK)) { dcode->buf[n - 2] = dcode->buf[n - 1]; n--; } } for(i = 0; i < n; i++) { unsigned c = dcode->buf[i]; dcode->buf[i] = ((c < 0x14) ? codabar_characters[c] : '?'); } dcode->buflen = i; dcode->buf[i] = '\0'; dcode->modifiers = 0; codabar->character = -1; return(ZBAR_CODABAR); } zbar_symbol_type_t _zbar_decode_codabar (zbar_decoder_t *dcode) { codabar_decoder_t *codabar = &dcode->codabar; /* update latest character width */ codabar->s7 -= get_width(dcode, 8); codabar->s7 += get_width(dcode, 1); if(get_color(dcode) != ZBAR_SPACE) return(ZBAR_NONE); if(codabar->character < 0) return(codabar_decode_start(dcode)); if(codabar->character < 2 && codabar_decode_start(dcode)) return(ZBAR_PARTIAL); if(--codabar->element) return(ZBAR_NONE); codabar->element = 4; dbprintf(1, " codabar[%c%02d+%x]", (codabar->direction) ? '<' : '>', codabar->character, codabar->element); signed char c = codabar_decode7(dcode); dbprintf(1, " %d", c); if(c < 0) { dbprintf(1, " [aborted]\n"); goto reset; } unsigned char *buf; if(codabar->character < NIBUF) buf = codabar->buf; else { if(codabar->character >= BUFFER_MIN && size_buf(dcode, codabar->character + 1)) { dbprintf(1, " [overflow]\n"); goto reset; } buf = dcode->buf; } buf[codabar->character++] = c; /* lock shared resources */ if(codabar->character == NIBUF && acquire_lock(dcode, ZBAR_CODABAR)) { codabar->character = -1; return(ZBAR_PARTIAL); } unsigned s = codabar->s7; if(c & 0x10) { unsigned qz = get_width(dcode, 0); if(qz && qz * 2 < s) { dbprintf(2, " [invalid qz]\n"); goto reset; } unsigned n = codabar->character; if(n < CFG(*codabar, ZBAR_CFG_MIN_LEN) || (CFG(*codabar, ZBAR_CFG_MAX_LEN) > 0 && n > CFG(*codabar, ZBAR_CFG_MAX_LEN))) { dbprintf(2, " [invalid len]\n"); goto reset; } if(codabar->character < NIBUF && acquire_lock(dcode, ZBAR_CODABAR)) { codabar->character = -1; return(ZBAR_PARTIAL); } dbprintf(2, " stop=%c", c + 0x31); zbar_symbol_type_t sym = codabar_postprocess(dcode); if(sym > ZBAR_PARTIAL) dbprintf(2, " [valid stop]"); else { release_lock(dcode, ZBAR_CODABAR); codabar->character = -1; } dbprintf(2, "\n"); return(sym); } else if(4 * get_width(dcode, 0) > 3 * s) { dbprintf(2, " [ics]\n"); goto reset; } dbprintf(2, "\n"); return(ZBAR_NONE); reset: if(codabar->character >= NIBUF) release_lock(dcode, ZBAR_CODABAR); codabar->character = -1; return(ZBAR_NONE); }
gpl-3.0
tierney/cryptagram-cc
src/cryptopp/camellia.cpp
80
20929
// camellia.cpp - by Kevin Springle, 2003 // This code is hereby placed in the public domain. /* Optimisations and defense against timing attacks added in Jan 2007 by Wei Dai. The first 2 rounds and the last round seem especially vulnerable to timing attacks. The protection is similar to what was implemented for Rijndael. See comments at top of rijndael.cpp for more details. */ #include "pch.h" #include "camellia.h" #include "misc.h" #include "cpu.h" NAMESPACE_BEGIN(CryptoPP) // round implementation that uses a small table for protection against timing attacks #define SLOW_ROUND(lh, ll, rh, rl, kh, kl) { \ word32 zr = ll ^ kl; \ word32 zl = lh ^ kh; \ zr= rotlFixed(s1[GETBYTE(zr, 3)], 1) | \ (rotrFixed(s1[GETBYTE(zr, 2)], 1) << 24) | \ (s1[rotlFixed(CRYPTOPP_GET_BYTE_AS_BYTE(zr, 1),1)] << 16) | \ (s1[GETBYTE(zr, 0)] << 8); \ zl= (s1[GETBYTE(zl, 3)] << 24) | \ (rotlFixed(s1[GETBYTE(zl, 2)], 1) << 16) | \ (rotrFixed(s1[GETBYTE(zl, 1)], 1) << 8) | \ s1[rotlFixed(CRYPTOPP_GET_BYTE_AS_BYTE(zl, 0), 1)]; \ zl ^= zr; \ zr = zl ^ rotlFixed(zr, 8); \ zl = zr ^ rotrFixed(zl, 8); \ rh ^= rotlFixed(zr, 16); \ rh ^= zl; \ rl ^= rotlFixed(zl, 8); \ } // normal round - same output as above but using larger tables for faster speed #define ROUND(lh, ll, rh, rl, kh, kl) { \ word32 th = lh ^ kh; \ word32 tl = ll ^ kl; \ word32 d = SP[0][GETBYTE(tl,0)] ^ SP[1][GETBYTE(tl,3)] ^ SP[2][GETBYTE(tl,2)] ^ SP[3][GETBYTE(tl,1)]; \ word32 u = SP[0][GETBYTE(th,3)] ^ SP[1][GETBYTE(th,2)] ^ SP[2][GETBYTE(th,1)] ^ SP[3][GETBYTE(th,0)]; \ d ^= u; \ rh ^= d; \ rl ^= d; \ rl ^= rotrFixed(u, 8);} #define DOUBLE_ROUND(lh, ll, rh, rl, k0, k1, k2, k3) \ ROUND(lh, ll, rh, rl, k0, k1) \ ROUND(rh, rl, lh, ll, k2, k3) #ifdef IS_LITTLE_ENDIAN #define EFI(i) (1-(i)) #else #define EFI(i) (i) #endif void Camellia::Base::UncheckedSetKey(const byte *key, unsigned int keylen, const NameValuePairs &) { m_rounds = (keylen >= 24) ? 4 : 3; unsigned int kslen = (8 * m_rounds + 2); m_key.New(kslen*2); word32 *ks32 = m_key.data(); int m=0, a=0; if (!IsForwardTransformation()) m = -1, a = kslen-1; word32 kl0, kl1, kl2, kl3; GetBlock<word32, BigEndian> getBlock(key); getBlock(kl0)(kl1)(kl2)(kl3); word32 k0=kl0, k1=kl1, k2=kl2, k3=kl3; #define CALC_ADDR2(base, i, j) ((byte *)(base)+8*(i)+4*(j)+((-16*(i))&m)) #define CALC_ADDR(base, i) CALC_ADDR2(base, i, 0) #if 1 word64 kwl, kwr; ks32 += 2*a; #define PREPARE_KS_ROUNDS \ kwl = (word64(k0) << 32) | k1; \ kwr = (word64(k2) << 32) | k3 #define KS_ROUND_0(i) \ *(word64*)CALC_ADDR(ks32, i+EFI(0)) = kwl; \ *(word64*)CALC_ADDR(ks32, i+EFI(1)) = kwr #define KS_ROUND(i, r, which) \ if (which & (1<<int(r<64))) *(word64*)CALC_ADDR(ks32, i+EFI(r<64)) = (kwr << (r%64)) | (kwl >> (64 - (r%64))); \ if (which & (1<<int(r>64))) *(word64*)CALC_ADDR(ks32, i+EFI(r>64)) = (kwl << (r%64)) | (kwr >> (64 - (r%64))) #else // SSE2 version is 30% faster on Intel Core 2. Doesn't seem worth the hassle of maintenance, but left here // #if'd out in case someone needs it. __m128i kw, kw2; __m128i *ks128 = (__m128i *)ks32+a/2; ks32 += 2*a; #define PREPARE_KS_ROUNDS \ kw = _mm_set_epi32(k0, k1, k2, k3); \ if (m) kw2 = kw, kw = _mm_shuffle_epi32(kw, _MM_SHUFFLE(1, 0, 3, 2)); \ else kw2 = _mm_shuffle_epi32(kw, _MM_SHUFFLE(1, 0, 3, 2)) #define KS_ROUND_0(i) \ _mm_store_si128((__m128i *)CALC_ADDR(ks128, i), kw) #define KS_ROUND(i, r, which) { \ __m128i temp; \ if (r<64 && (which!=1 || m)) temp = _mm_or_si128(_mm_slli_epi64(kw, r%64), _mm_srli_epi64(kw2, 64-r%64)); \ else temp = _mm_or_si128(_mm_slli_epi64(kw2, r%64), _mm_srli_epi64(kw, 64-r%64)); \ if (which & 2) _mm_store_si128((__m128i *)CALC_ADDR(ks128, i), temp); \ else _mm_storel_epi64((__m128i*)CALC_ADDR(ks32, i+EFI(0)), temp); \ } #endif if (keylen == 16) { // KL PREPARE_KS_ROUNDS; KS_ROUND_0(0); KS_ROUND(4, 15, 3); KS_ROUND(10, 45, 3); KS_ROUND(12, 60, 2); KS_ROUND(16, 77, 3); KS_ROUND(18, 94, 3); KS_ROUND(22, 111, 3); // KA k0=kl0, k1=kl1, k2=kl2, k3=kl3; DOUBLE_ROUND(k0, k1, k2, k3, 0xA09E667Ful, 0x3BCC908Bul, 0xB67AE858ul, 0x4CAA73B2ul); k0^=kl0, k1^=kl1, k2^=kl2, k3^=kl3; DOUBLE_ROUND(k0, k1, k2, k3, 0xC6EF372Ful, 0xE94F82BEul, 0x54FF53A5ul, 0xF1D36F1Cul); PREPARE_KS_ROUNDS; KS_ROUND_0(2); KS_ROUND(6, 15, 3); KS_ROUND(8, 30, 3); KS_ROUND(12, 45, 1); KS_ROUND(14, 60, 3); KS_ROUND(20, 94, 3); KS_ROUND(24, 47, 3); } else { // KL PREPARE_KS_ROUNDS; KS_ROUND_0(0); KS_ROUND(12, 45, 3); KS_ROUND(16, 60, 3); KS_ROUND(22, 77, 3); KS_ROUND(30, 111, 3); // KR word32 kr0, kr1, kr2, kr3; GetBlock<word32, BigEndian>(key+16)(kr0)(kr1); if (keylen == 24) kr2 = ~kr0, kr3 = ~kr1; else GetBlock<word32, BigEndian>(key+24)(kr2)(kr3); k0=kr0, k1=kr1, k2=kr2, k3=kr3; PREPARE_KS_ROUNDS; KS_ROUND(4, 15, 3); KS_ROUND(8, 30, 3); KS_ROUND(18, 60, 3); KS_ROUND(26, 94, 3); // KA k0^=kl0, k1^=kl1, k2^=kl2, k3^=kl3; DOUBLE_ROUND(k0, k1, k2, k3, 0xA09E667Ful, 0x3BCC908Bul, 0xB67AE858ul, 0x4CAA73B2ul); k0^=kl0, k1^=kl1, k2^=kl2, k3^=kl3; DOUBLE_ROUND(k0, k1, k2, k3, 0xC6EF372Ful, 0xE94F82BEul, 0x54FF53A5ul, 0xF1D36F1Cul); PREPARE_KS_ROUNDS; KS_ROUND(6, 15, 3); KS_ROUND(14, 45, 3); KS_ROUND(24, 77, 3); KS_ROUND(28, 94, 3); // KB k0^=kr0, k1^=kr1, k2^=kr2, k3^=kr3; DOUBLE_ROUND(k0, k1, k2, k3, 0x10E527FAul, 0xDE682D1Dul, 0xB05688C2ul, 0xB3E6C1FDul); PREPARE_KS_ROUNDS; KS_ROUND_0(2); KS_ROUND(10, 30, 3); KS_ROUND(20, 60, 3); KS_ROUND(32, 47, 3); } } void Camellia::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { #define KS(i, j) ks[i*4 + EFI(j/2)*2 + EFI(j%2)] #define FL(klh, kll, krh, krl) \ ll ^= rotlFixed(lh & klh, 1); \ lh ^= (ll | kll); \ rh ^= (rl | krl); \ rl ^= rotlFixed(rh & krh, 1); word32 lh, ll, rh, rl; typedef BlockGetAndPut<word32, BigEndian> Block; Block::Get(inBlock)(lh)(ll)(rh)(rl); const word32 *ks = m_key.data(); lh ^= KS(0,0); ll ^= KS(0,1); rh ^= KS(0,2); rl ^= KS(0,3); // timing attack countermeasure. see comments at top for more details const int cacheLineSize = GetCacheLineSize(); unsigned int i; word32 u = 0; for (i=0; i<256; i+=cacheLineSize) u &= *(const word32 *)(s1+i); u &= *(const word32 *)(s1+252); lh |= u; ll |= u; SLOW_ROUND(lh, ll, rh, rl, KS(1,0), KS(1,1)) SLOW_ROUND(rh, rl, lh, ll, KS(1,2), KS(1,3)) for (i = m_rounds-1; i > 0; --i) { DOUBLE_ROUND(lh, ll, rh, rl, KS(2,0), KS(2,1), KS(2,2), KS(2,3)) DOUBLE_ROUND(lh, ll, rh, rl, KS(3,0), KS(3,1), KS(3,2), KS(3,3)) FL(KS(4,0), KS(4,1), KS(4,2), KS(4,3)); DOUBLE_ROUND(lh, ll, rh, rl, KS(5,0), KS(5,1), KS(5,2), KS(5,3)) ks += 16; } DOUBLE_ROUND(lh, ll, rh, rl, KS(2,0), KS(2,1), KS(2,2), KS(2,3)) ROUND(lh, ll, rh, rl, KS(3,0), KS(3,1)) SLOW_ROUND(rh, rl, lh, ll, KS(3,2), KS(3,3)) lh ^= KS(4,0); ll ^= KS(4,1); rh ^= KS(4,2); rl ^= KS(4,3); Block::Put(xorBlock, outBlock)(rh)(rl)(lh)(ll); } // The Camellia s-boxes const byte Camellia::Base::s1[256] = { 112,130,44,236,179,39,192,229,228,133,87,53,234,12,174,65, 35,239,107,147,69,25,165,33,237,14,79,78,29,101,146,189, 134,184,175,143,124,235,31,206,62,48,220,95,94,197,11,26, 166,225,57,202,213,71,93,61,217,1,90,214,81,86,108,77, 139,13,154,102,251,204,176,45,116,18,43,32,240,177,132,153, 223,76,203,194,52,126,118,5,109,183,169,49,209,23,4,215, 20,88,58,97,222,27,17,28,50,15,156,22,83,24,242,34, 254,68,207,178,195,181,122,145,36,8,232,168,96,252,105,80, 170,208,160,125,161,137,98,151,84,91,30,149,224,255,100,210, 16,196,0,72,163,247,117,219,138,3,230,218,9,63,221,148, 135,92,131,2,205,74,144,51,115,103,246,243,157,127,191,226, 82,155,216,38,200,55,198,59,129,150,111,75,19,190,99,46, 233,121,167,140,159,110,188,142,41,245,249,182,47,253,180,89, 120,152,6,106,231,70,113,186,212,37,171,66,136,162,141,250, 114,7,185,85,248,238,172,10,54,73,42,104,60,56,241,164, 64,40,211,123,187,201,67,193,21,227,173,244,119,199,128,158 }; const word32 Camellia::Base::SP[4][256] = { { 0x70707000, 0x82828200, 0x2c2c2c00, 0xececec00, 0xb3b3b300, 0x27272700, 0xc0c0c000, 0xe5e5e500, 0xe4e4e400, 0x85858500, 0x57575700, 0x35353500, 0xeaeaea00, 0x0c0c0c00, 0xaeaeae00, 0x41414100, 0x23232300, 0xefefef00, 0x6b6b6b00, 0x93939300, 0x45454500, 0x19191900, 0xa5a5a500, 0x21212100, 0xededed00, 0x0e0e0e00, 0x4f4f4f00, 0x4e4e4e00, 0x1d1d1d00, 0x65656500, 0x92929200, 0xbdbdbd00, 0x86868600, 0xb8b8b800, 0xafafaf00, 0x8f8f8f00, 0x7c7c7c00, 0xebebeb00, 0x1f1f1f00, 0xcecece00, 0x3e3e3e00, 0x30303000, 0xdcdcdc00, 0x5f5f5f00, 0x5e5e5e00, 0xc5c5c500, 0x0b0b0b00, 0x1a1a1a00, 0xa6a6a600, 0xe1e1e100, 0x39393900, 0xcacaca00, 0xd5d5d500, 0x47474700, 0x5d5d5d00, 0x3d3d3d00, 0xd9d9d900, 0x01010100, 0x5a5a5a00, 0xd6d6d600, 0x51515100, 0x56565600, 0x6c6c6c00, 0x4d4d4d00, 0x8b8b8b00, 0x0d0d0d00, 0x9a9a9a00, 0x66666600, 0xfbfbfb00, 0xcccccc00, 0xb0b0b000, 0x2d2d2d00, 0x74747400, 0x12121200, 0x2b2b2b00, 0x20202000, 0xf0f0f000, 0xb1b1b100, 0x84848400, 0x99999900, 0xdfdfdf00, 0x4c4c4c00, 0xcbcbcb00, 0xc2c2c200, 0x34343400, 0x7e7e7e00, 0x76767600, 0x05050500, 0x6d6d6d00, 0xb7b7b700, 0xa9a9a900, 0x31313100, 0xd1d1d100, 0x17171700, 0x04040400, 0xd7d7d700, 0x14141400, 0x58585800, 0x3a3a3a00, 0x61616100, 0xdedede00, 0x1b1b1b00, 0x11111100, 0x1c1c1c00, 0x32323200, 0x0f0f0f00, 0x9c9c9c00, 0x16161600, 0x53535300, 0x18181800, 0xf2f2f200, 0x22222200, 0xfefefe00, 0x44444400, 0xcfcfcf00, 0xb2b2b200, 0xc3c3c300, 0xb5b5b500, 0x7a7a7a00, 0x91919100, 0x24242400, 0x08080800, 0xe8e8e800, 0xa8a8a800, 0x60606000, 0xfcfcfc00, 0x69696900, 0x50505000, 0xaaaaaa00, 0xd0d0d000, 0xa0a0a000, 0x7d7d7d00, 0xa1a1a100, 0x89898900, 0x62626200, 0x97979700, 0x54545400, 0x5b5b5b00, 0x1e1e1e00, 0x95959500, 0xe0e0e000, 0xffffff00, 0x64646400, 0xd2d2d200, 0x10101000, 0xc4c4c400, 0x00000000, 0x48484800, 0xa3a3a300, 0xf7f7f700, 0x75757500, 0xdbdbdb00, 0x8a8a8a00, 0x03030300, 0xe6e6e600, 0xdadada00, 0x09090900, 0x3f3f3f00, 0xdddddd00, 0x94949400, 0x87878700, 0x5c5c5c00, 0x83838300, 0x02020200, 0xcdcdcd00, 0x4a4a4a00, 0x90909000, 0x33333300, 0x73737300, 0x67676700, 0xf6f6f600, 0xf3f3f300, 0x9d9d9d00, 0x7f7f7f00, 0xbfbfbf00, 0xe2e2e200, 0x52525200, 0x9b9b9b00, 0xd8d8d800, 0x26262600, 0xc8c8c800, 0x37373700, 0xc6c6c600, 0x3b3b3b00, 0x81818100, 0x96969600, 0x6f6f6f00, 0x4b4b4b00, 0x13131300, 0xbebebe00, 0x63636300, 0x2e2e2e00, 0xe9e9e900, 0x79797900, 0xa7a7a700, 0x8c8c8c00, 0x9f9f9f00, 0x6e6e6e00, 0xbcbcbc00, 0x8e8e8e00, 0x29292900, 0xf5f5f500, 0xf9f9f900, 0xb6b6b600, 0x2f2f2f00, 0xfdfdfd00, 0xb4b4b400, 0x59595900, 0x78787800, 0x98989800, 0x06060600, 0x6a6a6a00, 0xe7e7e700, 0x46464600, 0x71717100, 0xbababa00, 0xd4d4d400, 0x25252500, 0xababab00, 0x42424200, 0x88888800, 0xa2a2a200, 0x8d8d8d00, 0xfafafa00, 0x72727200, 0x07070700, 0xb9b9b900, 0x55555500, 0xf8f8f800, 0xeeeeee00, 0xacacac00, 0x0a0a0a00, 0x36363600, 0x49494900, 0x2a2a2a00, 0x68686800, 0x3c3c3c00, 0x38383800, 0xf1f1f100, 0xa4a4a400, 0x40404000, 0x28282800, 0xd3d3d300, 0x7b7b7b00, 0xbbbbbb00, 0xc9c9c900, 0x43434300, 0xc1c1c100, 0x15151500, 0xe3e3e300, 0xadadad00, 0xf4f4f400, 0x77777700, 0xc7c7c700, 0x80808000, 0x9e9e9e00 }, { 0x00e0e0e0, 0x00050505, 0x00585858, 0x00d9d9d9, 0x00676767, 0x004e4e4e, 0x00818181, 0x00cbcbcb, 0x00c9c9c9, 0x000b0b0b, 0x00aeaeae, 0x006a6a6a, 0x00d5d5d5, 0x00181818, 0x005d5d5d, 0x00828282, 0x00464646, 0x00dfdfdf, 0x00d6d6d6, 0x00272727, 0x008a8a8a, 0x00323232, 0x004b4b4b, 0x00424242, 0x00dbdbdb, 0x001c1c1c, 0x009e9e9e, 0x009c9c9c, 0x003a3a3a, 0x00cacaca, 0x00252525, 0x007b7b7b, 0x000d0d0d, 0x00717171, 0x005f5f5f, 0x001f1f1f, 0x00f8f8f8, 0x00d7d7d7, 0x003e3e3e, 0x009d9d9d, 0x007c7c7c, 0x00606060, 0x00b9b9b9, 0x00bebebe, 0x00bcbcbc, 0x008b8b8b, 0x00161616, 0x00343434, 0x004d4d4d, 0x00c3c3c3, 0x00727272, 0x00959595, 0x00ababab, 0x008e8e8e, 0x00bababa, 0x007a7a7a, 0x00b3b3b3, 0x00020202, 0x00b4b4b4, 0x00adadad, 0x00a2a2a2, 0x00acacac, 0x00d8d8d8, 0x009a9a9a, 0x00171717, 0x001a1a1a, 0x00353535, 0x00cccccc, 0x00f7f7f7, 0x00999999, 0x00616161, 0x005a5a5a, 0x00e8e8e8, 0x00242424, 0x00565656, 0x00404040, 0x00e1e1e1, 0x00636363, 0x00090909, 0x00333333, 0x00bfbfbf, 0x00989898, 0x00979797, 0x00858585, 0x00686868, 0x00fcfcfc, 0x00ececec, 0x000a0a0a, 0x00dadada, 0x006f6f6f, 0x00535353, 0x00626262, 0x00a3a3a3, 0x002e2e2e, 0x00080808, 0x00afafaf, 0x00282828, 0x00b0b0b0, 0x00747474, 0x00c2c2c2, 0x00bdbdbd, 0x00363636, 0x00222222, 0x00383838, 0x00646464, 0x001e1e1e, 0x00393939, 0x002c2c2c, 0x00a6a6a6, 0x00303030, 0x00e5e5e5, 0x00444444, 0x00fdfdfd, 0x00888888, 0x009f9f9f, 0x00656565, 0x00878787, 0x006b6b6b, 0x00f4f4f4, 0x00232323, 0x00484848, 0x00101010, 0x00d1d1d1, 0x00515151, 0x00c0c0c0, 0x00f9f9f9, 0x00d2d2d2, 0x00a0a0a0, 0x00555555, 0x00a1a1a1, 0x00414141, 0x00fafafa, 0x00434343, 0x00131313, 0x00c4c4c4, 0x002f2f2f, 0x00a8a8a8, 0x00b6b6b6, 0x003c3c3c, 0x002b2b2b, 0x00c1c1c1, 0x00ffffff, 0x00c8c8c8, 0x00a5a5a5, 0x00202020, 0x00898989, 0x00000000, 0x00909090, 0x00474747, 0x00efefef, 0x00eaeaea, 0x00b7b7b7, 0x00151515, 0x00060606, 0x00cdcdcd, 0x00b5b5b5, 0x00121212, 0x007e7e7e, 0x00bbbbbb, 0x00292929, 0x000f0f0f, 0x00b8b8b8, 0x00070707, 0x00040404, 0x009b9b9b, 0x00949494, 0x00212121, 0x00666666, 0x00e6e6e6, 0x00cecece, 0x00ededed, 0x00e7e7e7, 0x003b3b3b, 0x00fefefe, 0x007f7f7f, 0x00c5c5c5, 0x00a4a4a4, 0x00373737, 0x00b1b1b1, 0x004c4c4c, 0x00919191, 0x006e6e6e, 0x008d8d8d, 0x00767676, 0x00030303, 0x002d2d2d, 0x00dedede, 0x00969696, 0x00262626, 0x007d7d7d, 0x00c6c6c6, 0x005c5c5c, 0x00d3d3d3, 0x00f2f2f2, 0x004f4f4f, 0x00191919, 0x003f3f3f, 0x00dcdcdc, 0x00797979, 0x001d1d1d, 0x00525252, 0x00ebebeb, 0x00f3f3f3, 0x006d6d6d, 0x005e5e5e, 0x00fbfbfb, 0x00696969, 0x00b2b2b2, 0x00f0f0f0, 0x00313131, 0x000c0c0c, 0x00d4d4d4, 0x00cfcfcf, 0x008c8c8c, 0x00e2e2e2, 0x00757575, 0x00a9a9a9, 0x004a4a4a, 0x00575757, 0x00848484, 0x00111111, 0x00454545, 0x001b1b1b, 0x00f5f5f5, 0x00e4e4e4, 0x000e0e0e, 0x00737373, 0x00aaaaaa, 0x00f1f1f1, 0x00dddddd, 0x00595959, 0x00141414, 0x006c6c6c, 0x00929292, 0x00545454, 0x00d0d0d0, 0x00787878, 0x00707070, 0x00e3e3e3, 0x00494949, 0x00808080, 0x00505050, 0x00a7a7a7, 0x00f6f6f6, 0x00777777, 0x00939393, 0x00868686, 0x00838383, 0x002a2a2a, 0x00c7c7c7, 0x005b5b5b, 0x00e9e9e9, 0x00eeeeee, 0x008f8f8f, 0x00010101, 0x003d3d3d }, { 0x38003838, 0x41004141, 0x16001616, 0x76007676, 0xd900d9d9, 0x93009393, 0x60006060, 0xf200f2f2, 0x72007272, 0xc200c2c2, 0xab00abab, 0x9a009a9a, 0x75007575, 0x06000606, 0x57005757, 0xa000a0a0, 0x91009191, 0xf700f7f7, 0xb500b5b5, 0xc900c9c9, 0xa200a2a2, 0x8c008c8c, 0xd200d2d2, 0x90009090, 0xf600f6f6, 0x07000707, 0xa700a7a7, 0x27002727, 0x8e008e8e, 0xb200b2b2, 0x49004949, 0xde00dede, 0x43004343, 0x5c005c5c, 0xd700d7d7, 0xc700c7c7, 0x3e003e3e, 0xf500f5f5, 0x8f008f8f, 0x67006767, 0x1f001f1f, 0x18001818, 0x6e006e6e, 0xaf00afaf, 0x2f002f2f, 0xe200e2e2, 0x85008585, 0x0d000d0d, 0x53005353, 0xf000f0f0, 0x9c009c9c, 0x65006565, 0xea00eaea, 0xa300a3a3, 0xae00aeae, 0x9e009e9e, 0xec00ecec, 0x80008080, 0x2d002d2d, 0x6b006b6b, 0xa800a8a8, 0x2b002b2b, 0x36003636, 0xa600a6a6, 0xc500c5c5, 0x86008686, 0x4d004d4d, 0x33003333, 0xfd00fdfd, 0x66006666, 0x58005858, 0x96009696, 0x3a003a3a, 0x09000909, 0x95009595, 0x10001010, 0x78007878, 0xd800d8d8, 0x42004242, 0xcc00cccc, 0xef00efef, 0x26002626, 0xe500e5e5, 0x61006161, 0x1a001a1a, 0x3f003f3f, 0x3b003b3b, 0x82008282, 0xb600b6b6, 0xdb00dbdb, 0xd400d4d4, 0x98009898, 0xe800e8e8, 0x8b008b8b, 0x02000202, 0xeb00ebeb, 0x0a000a0a, 0x2c002c2c, 0x1d001d1d, 0xb000b0b0, 0x6f006f6f, 0x8d008d8d, 0x88008888, 0x0e000e0e, 0x19001919, 0x87008787, 0x4e004e4e, 0x0b000b0b, 0xa900a9a9, 0x0c000c0c, 0x79007979, 0x11001111, 0x7f007f7f, 0x22002222, 0xe700e7e7, 0x59005959, 0xe100e1e1, 0xda00dada, 0x3d003d3d, 0xc800c8c8, 0x12001212, 0x04000404, 0x74007474, 0x54005454, 0x30003030, 0x7e007e7e, 0xb400b4b4, 0x28002828, 0x55005555, 0x68006868, 0x50005050, 0xbe00bebe, 0xd000d0d0, 0xc400c4c4, 0x31003131, 0xcb00cbcb, 0x2a002a2a, 0xad00adad, 0x0f000f0f, 0xca00caca, 0x70007070, 0xff00ffff, 0x32003232, 0x69006969, 0x08000808, 0x62006262, 0x00000000, 0x24002424, 0xd100d1d1, 0xfb00fbfb, 0xba00baba, 0xed00eded, 0x45004545, 0x81008181, 0x73007373, 0x6d006d6d, 0x84008484, 0x9f009f9f, 0xee00eeee, 0x4a004a4a, 0xc300c3c3, 0x2e002e2e, 0xc100c1c1, 0x01000101, 0xe600e6e6, 0x25002525, 0x48004848, 0x99009999, 0xb900b9b9, 0xb300b3b3, 0x7b007b7b, 0xf900f9f9, 0xce00cece, 0xbf00bfbf, 0xdf00dfdf, 0x71007171, 0x29002929, 0xcd00cdcd, 0x6c006c6c, 0x13001313, 0x64006464, 0x9b009b9b, 0x63006363, 0x9d009d9d, 0xc000c0c0, 0x4b004b4b, 0xb700b7b7, 0xa500a5a5, 0x89008989, 0x5f005f5f, 0xb100b1b1, 0x17001717, 0xf400f4f4, 0xbc00bcbc, 0xd300d3d3, 0x46004646, 0xcf00cfcf, 0x37003737, 0x5e005e5e, 0x47004747, 0x94009494, 0xfa00fafa, 0xfc00fcfc, 0x5b005b5b, 0x97009797, 0xfe00fefe, 0x5a005a5a, 0xac00acac, 0x3c003c3c, 0x4c004c4c, 0x03000303, 0x35003535, 0xf300f3f3, 0x23002323, 0xb800b8b8, 0x5d005d5d, 0x6a006a6a, 0x92009292, 0xd500d5d5, 0x21002121, 0x44004444, 0x51005151, 0xc600c6c6, 0x7d007d7d, 0x39003939, 0x83008383, 0xdc00dcdc, 0xaa00aaaa, 0x7c007c7c, 0x77007777, 0x56005656, 0x05000505, 0x1b001b1b, 0xa400a4a4, 0x15001515, 0x34003434, 0x1e001e1e, 0x1c001c1c, 0xf800f8f8, 0x52005252, 0x20002020, 0x14001414, 0xe900e9e9, 0xbd00bdbd, 0xdd00dddd, 0xe400e4e4, 0xa100a1a1, 0xe000e0e0, 0x8a008a8a, 0xf100f1f1, 0xd600d6d6, 0x7a007a7a, 0xbb00bbbb, 0xe300e3e3, 0x40004040, 0x4f004f4f }, { 0x70700070, 0x2c2c002c, 0xb3b300b3, 0xc0c000c0, 0xe4e400e4, 0x57570057, 0xeaea00ea, 0xaeae00ae, 0x23230023, 0x6b6b006b, 0x45450045, 0xa5a500a5, 0xeded00ed, 0x4f4f004f, 0x1d1d001d, 0x92920092, 0x86860086, 0xafaf00af, 0x7c7c007c, 0x1f1f001f, 0x3e3e003e, 0xdcdc00dc, 0x5e5e005e, 0x0b0b000b, 0xa6a600a6, 0x39390039, 0xd5d500d5, 0x5d5d005d, 0xd9d900d9, 0x5a5a005a, 0x51510051, 0x6c6c006c, 0x8b8b008b, 0x9a9a009a, 0xfbfb00fb, 0xb0b000b0, 0x74740074, 0x2b2b002b, 0xf0f000f0, 0x84840084, 0xdfdf00df, 0xcbcb00cb, 0x34340034, 0x76760076, 0x6d6d006d, 0xa9a900a9, 0xd1d100d1, 0x04040004, 0x14140014, 0x3a3a003a, 0xdede00de, 0x11110011, 0x32320032, 0x9c9c009c, 0x53530053, 0xf2f200f2, 0xfefe00fe, 0xcfcf00cf, 0xc3c300c3, 0x7a7a007a, 0x24240024, 0xe8e800e8, 0x60600060, 0x69690069, 0xaaaa00aa, 0xa0a000a0, 0xa1a100a1, 0x62620062, 0x54540054, 0x1e1e001e, 0xe0e000e0, 0x64640064, 0x10100010, 0x00000000, 0xa3a300a3, 0x75750075, 0x8a8a008a, 0xe6e600e6, 0x09090009, 0xdddd00dd, 0x87870087, 0x83830083, 0xcdcd00cd, 0x90900090, 0x73730073, 0xf6f600f6, 0x9d9d009d, 0xbfbf00bf, 0x52520052, 0xd8d800d8, 0xc8c800c8, 0xc6c600c6, 0x81810081, 0x6f6f006f, 0x13130013, 0x63630063, 0xe9e900e9, 0xa7a700a7, 0x9f9f009f, 0xbcbc00bc, 0x29290029, 0xf9f900f9, 0x2f2f002f, 0xb4b400b4, 0x78780078, 0x06060006, 0xe7e700e7, 0x71710071, 0xd4d400d4, 0xabab00ab, 0x88880088, 0x8d8d008d, 0x72720072, 0xb9b900b9, 0xf8f800f8, 0xacac00ac, 0x36360036, 0x2a2a002a, 0x3c3c003c, 0xf1f100f1, 0x40400040, 0xd3d300d3, 0xbbbb00bb, 0x43430043, 0x15150015, 0xadad00ad, 0x77770077, 0x80800080, 0x82820082, 0xecec00ec, 0x27270027, 0xe5e500e5, 0x85850085, 0x35350035, 0x0c0c000c, 0x41410041, 0xefef00ef, 0x93930093, 0x19190019, 0x21210021, 0x0e0e000e, 0x4e4e004e, 0x65650065, 0xbdbd00bd, 0xb8b800b8, 0x8f8f008f, 0xebeb00eb, 0xcece00ce, 0x30300030, 0x5f5f005f, 0xc5c500c5, 0x1a1a001a, 0xe1e100e1, 0xcaca00ca, 0x47470047, 0x3d3d003d, 0x01010001, 0xd6d600d6, 0x56560056, 0x4d4d004d, 0x0d0d000d, 0x66660066, 0xcccc00cc, 0x2d2d002d, 0x12120012, 0x20200020, 0xb1b100b1, 0x99990099, 0x4c4c004c, 0xc2c200c2, 0x7e7e007e, 0x05050005, 0xb7b700b7, 0x31310031, 0x17170017, 0xd7d700d7, 0x58580058, 0x61610061, 0x1b1b001b, 0x1c1c001c, 0x0f0f000f, 0x16160016, 0x18180018, 0x22220022, 0x44440044, 0xb2b200b2, 0xb5b500b5, 0x91910091, 0x08080008, 0xa8a800a8, 0xfcfc00fc, 0x50500050, 0xd0d000d0, 0x7d7d007d, 0x89890089, 0x97970097, 0x5b5b005b, 0x95950095, 0xffff00ff, 0xd2d200d2, 0xc4c400c4, 0x48480048, 0xf7f700f7, 0xdbdb00db, 0x03030003, 0xdada00da, 0x3f3f003f, 0x94940094, 0x5c5c005c, 0x02020002, 0x4a4a004a, 0x33330033, 0x67670067, 0xf3f300f3, 0x7f7f007f, 0xe2e200e2, 0x9b9b009b, 0x26260026, 0x37370037, 0x3b3b003b, 0x96960096, 0x4b4b004b, 0xbebe00be, 0x2e2e002e, 0x79790079, 0x8c8c008c, 0x6e6e006e, 0x8e8e008e, 0xf5f500f5, 0xb6b600b6, 0xfdfd00fd, 0x59590059, 0x98980098, 0x6a6a006a, 0x46460046, 0xbaba00ba, 0x25250025, 0x42420042, 0xa2a200a2, 0xfafa00fa, 0x07070007, 0x55550055, 0xeeee00ee, 0x0a0a000a, 0x49490049, 0x68680068, 0x38380038, 0xa4a400a4, 0x28280028, 0x7b7b007b, 0xc9c900c9, 0xc1c100c1, 0xe3e300e3, 0xf4f400f4, 0xc7c700c7, 0x9e9e009e }}; NAMESPACE_END
gpl-3.0
CG-F15-9-Rutgers/SteerLite
external/glfw/lib/carbon/carbon_thread.c
87
11629
//======================================================================== // GLFW - An OpenGL framework // Platform: Carbon/AGL/CGL // API Version: 2.7 // WWW: http://www.glfw.org/ //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard // Copyright (c) 2003 Keith Bauer // Copyright (c) 2003-2010 Camilla Berglund <elmindreda@elmindreda.org> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // //======================================================================== #include "internal.h" //************************************************************************ //**** GLFW internal functions **** //************************************************************************ //======================================================================== // This is simply a "wrapper" for calling the user thread function. //======================================================================== void * _glfwNewThread( void * arg ) { GLFWthreadfun threadfun; _GLFWthread *t; // Get pointer to thread information for current thread t = _glfwGetThreadPointer( glfwGetThreadID() ); if( t == NULL ) { return 0; } // Get user thread function pointer threadfun = t->Function; // Call the user thread function threadfun( arg ); // Remove thread from thread list ENTER_THREAD_CRITICAL_SECTION _glfwRemoveThread( t ); LEAVE_THREAD_CRITICAL_SECTION // When the thread function returns, the thread will die... return NULL; } //************************************************************************ //**** Platform implementation functions **** //************************************************************************ //======================================================================== // Create a new thread //======================================================================== GLFWthread _glfwPlatformCreateThread( GLFWthreadfun fun, void *arg ) { GLFWthread ID; _GLFWthread *t; int result; // Enter critical section ENTER_THREAD_CRITICAL_SECTION // Create a new thread information memory area t = (_GLFWthread *) malloc( sizeof(_GLFWthread) ); if( t == NULL ) { // Leave critical section LEAVE_THREAD_CRITICAL_SECTION return -1; } // Get a new unique thread id ID = _glfwThrd.NextID ++; // Store thread information in the thread list t->Function = fun; t->ID = ID; // Create thread result = pthread_create( &t->PosixID, // Thread handle NULL, // Default thread attributes _glfwNewThread, // Thread function (a wrapper function) (void *)arg // Argument to thread is user argument ); // Did the thread creation fail? if( result != 0 ) { free( (void *) t ); LEAVE_THREAD_CRITICAL_SECTION return -1; } // Append thread to thread list _glfwAppendThread( t ); // Leave critical section LEAVE_THREAD_CRITICAL_SECTION // Return the GLFW thread ID return ID; } //======================================================================== // Kill a thread. NOTE: THIS IS A VERY DANGEROUS OPERATION, AND SHOULD NOT // BE USED EXCEPT IN EXTREME SITUATIONS! //======================================================================== void _glfwPlatformDestroyThread( GLFWthread ID ) { _GLFWthread *t; // Enter critical section ENTER_THREAD_CRITICAL_SECTION // Get thread information pointer t = _glfwGetThreadPointer( ID ); if( t == NULL ) { LEAVE_THREAD_CRITICAL_SECTION return; } // Simply murder the process, no mercy! pthread_kill( t->PosixID, SIGKILL ); // Remove thread from thread list _glfwRemoveThread( t ); // Leave critical section LEAVE_THREAD_CRITICAL_SECTION } //======================================================================== // Wait for a thread to die //======================================================================== int _glfwPlatformWaitThread( GLFWthread ID, int waitmode ) { pthread_t thread; _GLFWthread *t; // Enter critical section ENTER_THREAD_CRITICAL_SECTION // Get thread information pointer t = _glfwGetThreadPointer( ID ); // Is the thread already dead? if( t == NULL ) { LEAVE_THREAD_CRITICAL_SECTION return GL_TRUE; } // If got this far, the thread is alive => polling returns FALSE if( waitmode == GLFW_NOWAIT ) { LEAVE_THREAD_CRITICAL_SECTION return GL_FALSE; } // Get thread handle thread = t->PosixID; // Leave critical section LEAVE_THREAD_CRITICAL_SECTION // Wait for thread to die (void) pthread_join( thread, NULL ); return GL_TRUE; } //======================================================================== // Return the thread ID for the current thread //======================================================================== GLFWthread _glfwPlatformGetThreadID( void ) { _GLFWthread *t; GLFWthread ID = -1; pthread_t posixID; // Get current thread ID posixID = pthread_self(); // Enter critical section ENTER_THREAD_CRITICAL_SECTION // Loop through entire list of threads to find the matching POSIX // thread ID for( t = &_glfwThrd.First; t != NULL; t = t->Next ) { if( t->PosixID == posixID ) { ID = t->ID; break; } } // Leave critical section LEAVE_THREAD_CRITICAL_SECTION // Return the found GLFW thread identifier return ID; } //======================================================================== // Create a mutual exclusion object //======================================================================== GLFWmutex _glfwPlatformCreateMutex( void ) { pthread_mutex_t *mutex; // Allocate memory for mutex mutex = (pthread_mutex_t *) malloc( sizeof( pthread_mutex_t ) ); if( !mutex ) { return NULL; } // Initialise a mutex object (void) pthread_mutex_init( mutex, NULL ); // Cast to GLFWmutex and return return (GLFWmutex) mutex; } //======================================================================== // Destroy a mutual exclusion object //======================================================================== void _glfwPlatformDestroyMutex( GLFWmutex mutex ) { // Destroy the mutex object pthread_mutex_destroy( (pthread_mutex_t *) mutex ); // Free memory for mutex object free( (void *) mutex ); } //======================================================================== // Request access to a mutex //======================================================================== void _glfwPlatformLockMutex( GLFWmutex mutex ) { // Wait for mutex to be released (void) pthread_mutex_lock( (pthread_mutex_t *) mutex ); } //======================================================================== // Release a mutex //======================================================================== void _glfwPlatformUnlockMutex( GLFWmutex mutex ) { // Release mutex pthread_mutex_unlock( (pthread_mutex_t *) mutex ); } //======================================================================== // Create a new condition variable object //======================================================================== GLFWcond _glfwPlatformCreateCond( void ) { pthread_cond_t *cond; // Allocate memory for condition variable cond = (pthread_cond_t *) malloc( sizeof(pthread_cond_t) ); if( !cond ) { return NULL; } // Initialise condition variable (void) pthread_cond_init( cond, NULL ); // Cast to GLFWcond and return return (GLFWcond) cond; } //======================================================================== // Destroy a condition variable object //======================================================================== void _glfwPlatformDestroyCond( GLFWcond cond ) { // Destroy the condition variable object (void) pthread_cond_destroy( (pthread_cond_t *) cond ); // Free memory for condition variable object free( (void *) cond ); } //======================================================================== // Wait for a condition to be raised //======================================================================== void _glfwPlatformWaitCond( GLFWcond cond, GLFWmutex mutex, double timeout ) { struct timeval currenttime; struct timespec wait; long dt_sec, dt_usec; // Select infinite or timed wait if( timeout >= GLFW_INFINITY ) { // Wait for condition (infinite wait) (void) pthread_cond_wait( (pthread_cond_t *) cond, (pthread_mutex_t *) mutex ); } else { // Set timeout time, relatvie to current time gettimeofday( &currenttime, NULL ); dt_sec = (long) timeout; dt_usec = (long) ((timeout - (double)dt_sec) * 1000000.0); wait.tv_nsec = (currenttime.tv_usec + dt_usec) * 1000L; if( wait.tv_nsec > 1000000000L ) { wait.tv_nsec -= 1000000000L; dt_sec ++; } wait.tv_sec = currenttime.tv_sec + dt_sec; // Wait for condition (timed wait) (void) pthread_cond_timedwait( (pthread_cond_t *) cond, (pthread_mutex_t *) mutex, &wait ); } } //======================================================================== // Signal a condition to one waiting thread //======================================================================== void _glfwPlatformSignalCond( GLFWcond cond ) { // Signal condition (void) pthread_cond_signal( (pthread_cond_t *) cond ); } //======================================================================== // Broadcast a condition to all waiting threads //======================================================================== void _glfwPlatformBroadcastCond( GLFWcond cond ) { // Broadcast condition (void) pthread_cond_broadcast( (pthread_cond_t *) cond ); } //======================================================================== // Return the number of processors in the system. //======================================================================== int _glfwPlatformGetNumberOfProcessors( void ) { int n; // Get number of processors online _glfw_numprocessors( n ); return n; }
gpl-3.0
MoguCloud/shadowsocks-android
src/main/jni/openssl/crypto/o_init.c
602
3147
/* o_init.c */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project. */ /* ==================================================================== * Copyright (c) 2011 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * */ #include <e_os.h> #include <openssl/err.h> #ifdef OPENSSL_FIPS #include <openssl/fips.h> #include <openssl/rand.h> #endif /* Perform any essential OpenSSL initialization operations. * Currently only sets FIPS callbacks */ void OPENSSL_init(void) { static int done = 0; if (done) return; done = 1; #ifdef OPENSSL_FIPS FIPS_set_locking_callbacks(CRYPTO_lock, CRYPTO_add_lock); FIPS_set_error_callbacks(ERR_put_error, ERR_add_error_vdata); FIPS_set_malloc_callbacks(CRYPTO_malloc, CRYPTO_free); RAND_init_fips(); #endif #if 0 fprintf(stderr, "Called OPENSSL_init\n"); #endif }
gpl-3.0
murdercdh/shadowsocks-android
src/main/jni/pdnsd/src/servers.c
351
23399
/* servers.c - manage a set of dns servers Copyright (C) 2000, 2001 Thomas Moestl Copyright (C) 2002, 2003, 2005, 2007, 2009, 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 <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> #include <unistd.h> #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/wait.h> #include <string.h> #include <errno.h> #include <signal.h> #include <sys/stat.h> #include <fcntl.h> #include <fnmatch.h> #include <string.h> #include "thread.h" #include "error.h" #include "servers.h" #include "conff.h" #include "consts.h" #include "icmp.h" #include "netdev.h" #include "helpers.h" #include "dns_query.h" /* * We may be a little over-strict with locks here. Never mind... * Also, there may be some code-redundancy regarding uptests. It saves some locks, though. */ static pthread_mutex_t servers_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t server_data_cond = PTHREAD_COND_INITIALIZER; static pthread_cond_t server_test_cond = PTHREAD_COND_INITIALIZER; static int server_data_users = 0, server_status_ping = 0; /* Used to notify the server status thread that it should discontinue uptests. */ volatile int signal_interrupt=0; #define statusintsig SIGHUP static short retest_flag=0; static char schm[32]; static void sigint_handler(int signum); /* * Execute an individual uptest. Call with locks applied */ static int uptest (servparm_t *serv, int j) { int ret=0, count_running_ping=0; pdnsd_a *s_addr= PDNSD_A2_TO_A(&DA_INDEX(serv->atup_a,j).a); DEBUG_PDNSDA_MSG("performing uptest (type=%s) for %s\n",const_name(serv->uptest),PDNSDA2STR(s_addr)); /* Unlock the mutex because some of the tests may take a while. */ ++server_data_users; if((serv->uptest==C_PING || serv->uptest==C_QUERY) && pthread_equal(pthread_self(),servstat_thrid)) { /* Inform other threads that a ping is in progress. */ count_running_ping=1; ++server_status_ping; } pthread_mutex_unlock(&servers_lock); switch (serv->uptest) { case C_NONE: /* Don't change */ ret=DA_INDEX(serv->atup_a,j).is_up; break; case C_PING: ret=ping(is_inaddr_any(&serv->ping_a) ? s_addr : &serv->ping_a, serv->ping_timeout,PINGREPEAT)!=-1; break; case C_IF: case C_DEV: case C_DIALD: ret=if_up(serv->interface); #if (TARGET==TARGET_LINUX) if (ret!=0) { if(serv->uptest==C_DEV) ret=dev_up(serv->interface,serv->device); else if (serv->uptest==C_DIALD) ret=dev_up("diald",serv->device); } #endif break; case C_EXEC: { pid_t pid; if ((pid=fork())==-1) { DEBUG_MSG("Could not fork to perform exec uptest: %s\n",strerror(errno)); break; } else if (pid==0) { /* child */ /* * If we ran as setuid or setgid, do not inherit this to the * command. This is just a last guard. Running pdnsd as setuid() * or setgid() is a no-no. */ if (setgid(getgid()) == -1 || setuid(getuid()) == -1) { log_error("Could not reset uid or gid: %s",strerror(errno)); _exit(1); } /* Try to setuid() to a different user as specified. Good when you don't want the test command to run as root */ if (!run_as(serv->uptest_usr)) { _exit(1); } { struct rlimit rl; int i; /* * Mark all open fd's FD_CLOEXEC for paranoia reasons. */ if (getrlimit(RLIMIT_NOFILE, &rl) == -1) { log_error("getrlimit() failed: %s",strerror(errno)); _exit(1); } for (i = 0; i < rl.rlim_max; i++) { if (fcntl(i, F_SETFD, FD_CLOEXEC) == -1 && errno != EBADF) { log_error("fcntl(F_SETFD) failed: %s",strerror(errno)); _exit(1); } } } execl("/bin/sh", "uptest_sh","-c",serv->uptest_cmd,(char *)NULL); _exit(1); /* failed execl */ } else { /* parent */ int status; pid_t wpid = waitpid(pid,&status,0); if (wpid==pid) { if(WIFEXITED(status)) { int exitstatus=WEXITSTATUS(status); DEBUG_MSG("uptest command \"%s\" exited with status %d\n", serv->uptest_cmd, exitstatus); ret=(exitstatus==0); } #if DEBUG>0 else if(WIFSIGNALED(status)) { DEBUG_MSG("uptest command \"%s\" was terminated by signal %d\n", serv->uptest_cmd, WTERMSIG(status)); } else { DEBUG_MSG("status of uptest command \"%s\" is of unkown type (0x%x)\n", serv->uptest_cmd, status); } #endif } #if DEBUG>0 else if (wpid==-1) { DEBUG_MSG("Error while waiting for uptest command \"%s\" to terminate: " "waitpid for pid %d failed: %s\n", serv->uptest_cmd, pid, strerror(errno)); } else { DEBUG_MSG("Error while waiting for uptest command \"%s\" to terminate: " "waitpid returned %d, expected pid %d\n", serv->uptest_cmd, wpid, pid); } #endif } } break; case C_QUERY: ret=query_uptest(s_addr, serv->port, serv->query_test_name, serv->timeout>=global.timeout?serv->timeout:global.timeout, PINGREPEAT); } /* end of switch */ pthread_mutex_lock(&servers_lock); if(count_running_ping) --server_status_ping; PDNSD_ASSERT(server_data_users>0, "server_data_users non-positive before attempt to decrement it"); if (--server_data_users==0) pthread_cond_broadcast(&server_data_cond); DEBUG_PDNSDA_MSG("result of uptest for %s: %s\n", PDNSDA2STR(s_addr), ret?"OK":"failed"); return ret; } static int scheme_ok(servparm_t *serv) { if (serv->scheme[0]) { if (!schm[0]) { ssize_t nschm; int sc = open(global.scheme_file, O_RDONLY); char *s; if (sc<0) return 0; nschm = read(sc, schm, sizeof(schm)-1); close(sc); if (nschm < 0) return 0; schm[nschm] = '\0'; s = strchr(schm, '\n'); if (s) *s='\0'; } if (fnmatch(serv->scheme, schm, 0)) return 0; } return 1; } /* Internal server test. Call with locks applied. May test a single server ip or several collectively. */ static void retest(int i, int j) { time_t s_ts; servparm_t *srv=&DA_INDEX(servers,i); int nsrvs=DA_NEL(srv->atup_a); if(!nsrvs) return; if(j>=0) { if(j<nsrvs) nsrvs=j+1; /* test just one */ } else { j=0; /* test a range of servers */ } if(!scheme_ok(srv)) { s_ts=time(NULL); for(;j<nsrvs;++j) { atup_t *at=&DA_INDEX(srv->atup_a,j); at->is_up=0; at->i_ts=s_ts; } } else if(srv->uptest==C_NONE) { s_ts=time(NULL); for(;j<nsrvs;++j) { DA_INDEX(srv->atup_a,j).i_ts=s_ts; } } else if(srv->uptest==C_QUERY || (srv->uptest==C_PING && is_inaddr_any(&srv->ping_a))) { /* test each ip address separately */ for(;j<nsrvs;++j) { atup_t *at=&DA_INDEX(srv->atup_a,j); s_ts=time(NULL); at->is_up=uptest(srv,j); if(signal_interrupt) break; at->i_ts=s_ts; } } else { /* test ip addresses collectively */ int res; s_ts=time(NULL); res=uptest(srv,j); for(;j<nsrvs;++j) { atup_t *at=&DA_INDEX(srv->atup_a,j); at->is_up=res; if(signal_interrupt && srv->uptest==C_PING) continue; at->i_ts=s_ts; } } } /* This is called by the server status thread to discover the addresses of root servers. Call with server_lock applied. */ static addr2_array resolv_rootserver_addrs(atup_array a, int port, char edns_query, time_t timeout) { addr2_array retval=NULL; /* Unlock the mutex because this may take a while. */ ++server_data_users; pthread_mutex_unlock(&servers_lock); retval= dns_rootserver_resolv(a,port,edns_query,timeout); pthread_mutex_lock(&servers_lock); PDNSD_ASSERT(server_data_users>0, "server_data_users non-positive before attempt to decrement it"); if (--server_data_users==0) pthread_cond_broadcast(&server_data_cond); return retval; } /* * Refresh the server status by pinging or testing the interface in the given interval. * Note that you may get inaccuracies in the dimension of the ping timeout or the runtime * of your uptest command if you have uptest=ping or uptest=exec for at least one server. * This happens when all the uptests for the first n servers take more time than the inteval * of n+1 (or 0 when n+1>servnum). I do not think that these delays are critical, so I did * not to anything about that (because that may also be costly). */ void *servstat_thread(void *p) { struct sigaction action; int keep_testing; /* (void)p; */ /* To inhibit "unused variable" warning */ THREAD_SIGINIT; pthread_mutex_lock(&servers_lock); /* servstat_thrid=pthread_self(); */ signal_interrupt=0; action.sa_handler = sigint_handler; sigemptyset(&action.sa_mask); action.sa_flags = 0; if(sigaction(statusintsig, &action, NULL) == 0) { sigset_t smask; sigemptyset(&smask); sigaddset(&smask, statusintsig); pthread_sigmask(SIG_UNBLOCK,&smask,NULL); } else { log_warn("Cannot install signal handler for server status thread: %s\n",strerror(errno)); } for(;;) { do { int i,n; keep_testing=0; retest_flag=0; schm[0] = '\0'; n=DA_NEL(servers); for (i=0;i<n;++i) { servparm_t *sp=&DA_INDEX(servers,i); int j,m; if(sp->rootserver==2) { /* First get addresses of root servers. */ addr2_array adrs; int l, one_up=0; if(!scheme_ok(sp)) { time_t now=time(NULL); m=DA_NEL(sp->atup_a); for(j=0;j<m;++j) DA_INDEX(sp->atup_a,j).i_ts=now; } else if(sp->uptest==C_PING || sp->uptest==C_QUERY) { /* Skip ping or query tests until after discovery. */ if(sp->interval>0) one_up= DA_NEL(sp->atup_a); else { time_t now=time(NULL); m=DA_NEL(sp->atup_a); for(j=0;j<m;++j) { atup_t *at=&DA_INDEX(sp->atup_a,j); if(at->is_up || at->i_ts==0) one_up=1; at->i_ts=now; } } } else { retest(i,-1); m=DA_NEL(sp->atup_a); for(j=0;j<m;++j) { if(DA_INDEX(sp->atup_a,j).is_up) { one_up=1; break; } } } if(!one_up) { if (needs_intermittent_testing(sp)) keep_testing=1; continue; } DEBUG_MSG("Attempting to discover root servers for server section #%d.\n",i); adrs=resolv_rootserver_addrs(sp->atup_a,sp->port,sp->edns_query,sp->timeout); l= DA_NEL(adrs); if(l>0) { struct timeval now; struct timespec timeout; atup_array ata; DEBUG_MSG("Filling server section #%d with %d root server addresses.\n",i,l); gettimeofday(&now,NULL); timeout.tv_sec = now.tv_sec + 60; /* time out after 60 seconds */ timeout.tv_nsec = now.tv_usec * 1000; while (server_data_users>0) { if(pthread_cond_timedwait(&server_data_cond, &servers_lock, &timeout) == ETIMEDOUT) { DEBUG_MSG("Timed out while waiting for exclusive access to server data" " to set root server addresses of server section #%d\n",i); da_free(adrs); keep_testing=1; continue; } } ata = DA_CREATE(atup_array, l); if(!ata) { log_warn("Out of memory in servstat_thread() while discovering root servers."); da_free(adrs); keep_testing=1; continue; } for(j=0; j<l; ++j) { atup_t *at = &DA_INDEX(ata,j); at->a = DA_INDEX(adrs,j); at->is_up=sp->preset; at->i_ts= sp->interval<0 ? time(NULL): 0; } da_free(sp->atup_a); sp->atup_a=ata; da_free(adrs); /* Successfully set IP addresses for this server section. */ sp->rootserver=1; } else { DEBUG_MSG("Failed to discover root servers in servstat_thread() (server section #%d).\n",i); if(adrs) da_free(adrs); if(DA_NEL(sp->atup_a)) keep_testing=1; continue; } } if (needs_testing(sp)) keep_testing=1; m=DA_NEL(sp->atup_a); for(j=0;j<m;++j) if(DA_INDEX(sp->atup_a,j).i_ts) goto individual_tests; /* Test collectively */ if(!signal_interrupt) retest(i,-1); continue; individual_tests: for(j=0; !signal_interrupt && j<m; ++j) { time_t ts=DA_INDEX(sp->atup_a,j).i_ts, now; if (ts==0 /* Always test servers with timestamp 0 */ || (needs_intermittent_testing(sp) && ((now=time(NULL))-ts>sp->interval || ts>now /* kluge for clock skew */))) { retest(i,j); } } } } while(!signal_interrupt && retest_flag); signal_interrupt=0; /* Break the loop and exit the thread if it is no longer needed. */ if(!keep_testing) break; { struct timeval now; struct timespec timeout; time_t minwait; int i,n,retval; gettimeofday(&now,NULL); minwait=3600; /* Check at least once every hour. */ n=DA_NEL(servers); for (i=0;i<n;++i) { servparm_t *sp=&DA_INDEX(servers,i); int j,m=DA_NEL(sp->atup_a); for(j=0;j<m;++j) { time_t ts= DA_INDEX(sp->atup_a,j).i_ts; if(ts==0) { /* Test servers with timestamp 0 without delay */ if(minwait > 0) minwait=0; } else if(needs_intermittent_testing(sp)) { time_t wait= ts + sp->interval - now.tv_sec; if(wait < minwait) minwait=wait; } } } timeout.tv_sec = now.tv_sec; if(minwait>0) timeout.tv_sec += minwait; timeout.tv_nsec = now.tv_usec * 1000 + 500000000; /* wait at least half a second. */ if(timeout.tv_nsec>=1000000000) { timeout.tv_nsec -= 1000000000; ++timeout.tv_sec; } /* While we wait for a server_test_cond condition or a timeout the servers_lock mutex is unlocked, so other threads can access server data */ retval=pthread_cond_timedwait(&server_test_cond, &servers_lock, &timeout); DEBUG_MSG("Server status thread woke up (%s signal).\n", retval==0?"test condition":retval==ETIMEDOUT?"timer":retval==EINTR?"interrupt":"error"); } } /* server status thread no longer needed. */ servstat_thrid=main_thrid; pthread_mutex_unlock(&servers_lock); DEBUG_MSG("Server status thread exiting.\n"); return NULL; } /* * Start the server status thread. */ int start_servstat_thread() { pthread_t stt; int rv=pthread_create(&stt,&attr_detached,servstat_thread,NULL); if (rv) log_warn("Failed to start server status thread: %s",strerror(rv)); else { servstat_thrid=stt; log_info(2,"Server status thread started."); } return rv; } /* * This can be used to mark a server (or a list of nadr servers) up (up=1) or down (up=0), * or to schedule an immediate retest (up=-1). * We can't always use indices to identify a server, because we allow run-time * configuration of server addresses, so the servers are identified by their IP addresses. */ void sched_server_test(pdnsd_a *sa, int nadr, int up) { int k,signal_test; pthread_mutex_lock(&servers_lock); signal_test=0; /* This obviously isn't very efficient, but nadr should be small and anything else would introduce considerable overhead */ for(k=0;k<nadr;++k) { pdnsd_a *sak= &sa[k]; int i,n=DA_NEL(servers); for(i=0;i<n;++i) { servparm_t *sp=&DA_INDEX(servers,i); int j,m=DA_NEL(sp->atup_a); for(j=0;j<m;++j) { atup_t *at=&DA_INDEX(sp->atup_a,j); if(equiv_inaddr2(sak,&at->a)) { if(up>=0) { at->is_up=up; at->i_ts=time(NULL); DEBUG_PDNSDA_MSG("Marked server %s %s.\n",PDNSDA2STR(sak),up?"up":"down"); } else if(at->i_ts) { /* A test may take a while, and we don't want to hold up the calling thread. Instead we set the timestamp to zero and signal a condition which should wake up the server test thread. */ at->i_ts=0; signal_test=1; } } } } } if(signal_test) pthread_cond_signal(&server_test_cond); pthread_mutex_unlock(&servers_lock); } /* Mark a set of servers up or down or schedule uptests. * If i>=0 only the server section with index i is scanned, * if i<0 all sections are scanned. * Only sections matching label are actually set. A NULL label matches * any section. * up=1 or up=0 means mark server up or down, up=-1 means retest. * * A non-zero return value indicates an error. */ int mark_servers(int i, char *label, int up) { int retval=0,n,signal_test; pthread_mutex_lock(&servers_lock); signal_test=0; n=DA_NEL(servers); if(i>=0) { /* just one section */ if(i<n) n=i+1; } else { i=0; /* scan all sections */ } for(;i<n;++i) { servparm_t *sp=&DA_INDEX(servers,i); if(!label || (sp->label && !strcmp(sp->label,label))) { int j,m=DA_NEL(sp->atup_a); /* If a section with undiscovered root servers is marked up, signal a test. */ if(m && sp->rootserver>1 && up>0) signal_test=1; for(j=0;j<m;++j) { atup_t *at=&DA_INDEX(sp->atup_a,j); if(up>=0) { at->is_up=up; at->i_ts=time(NULL); } else if(at->i_ts) { /* A test may take a while, and we don't want to hold up the calling thread. Instead we set the timestamp to zero and signal a condition which should wake up the server test thread. */ at->i_ts=0; signal_test=1; } } } } if(signal_test) { if(pthread_equal(servstat_thrid,main_thrid)) retval=start_servstat_thread(); else { retest_flag=1; retval=pthread_cond_signal(&server_test_cond); } } pthread_mutex_unlock(&servers_lock); return retval; } /* * Test called by the dns query handlers to handle interval=onquery cases. */ void test_onquery() { int i,n,signal_test; pthread_mutex_lock(&servers_lock); schm[0] = '\0'; signal_test=0; n=DA_NEL(servers); for (i=0;i<n;++i) { servparm_t *sp=&DA_INDEX(servers,i); if (sp->interval==-1) { if(sp->rootserver<=1) retest(i,-1); else { /* We leave root-server discovery to the server status thread */ int j,m=DA_NEL(sp->atup_a); for(j=0;j<m;++j) DA_INDEX(sp->atup_a,j).i_ts=0; signal_test=1; } } } if(signal_test) { int rv; if(pthread_equal(servstat_thrid,main_thrid)) start_servstat_thread(); else { retest_flag=1; if((rv=pthread_cond_signal(&server_test_cond))) { DEBUG_MSG("test_onquery(): couldn't signal server status thread: %s\n",strerror(rv)); } } } pthread_mutex_unlock(&servers_lock); } /* non-exclusive lock, for read only access to server data. */ void lock_server_data() { pthread_mutex_lock(&servers_lock); ++server_data_users; pthread_mutex_unlock(&servers_lock); } void unlock_server_data() { pthread_mutex_lock(&servers_lock); PDNSD_ASSERT(server_data_users>0, "server_data_users non-positive before attempt to decrement it"); if (--server_data_users==0) pthread_cond_broadcast(&server_data_cond); pthread_mutex_unlock(&servers_lock); } /* Try to obtain an exclusive lock, needed for modifying server data. Return 1 on success, 0 on failure (time out after tm seconds). */ int exclusive_lock_server_data(int tm) { struct timeval now; struct timespec timeout; pthread_mutex_lock(&servers_lock); if(server_status_ping>0 && !pthread_equal(servstat_thrid,main_thrid)) { int err; /* Try to interrupt server status thread to prevent delays. */ DEBUG_MSG("Sending server status thread an interrupt signal.\n"); if((err=pthread_kill(servstat_thrid,statusintsig))) { DEBUG_MSG("pthread_kill failed: %s\n",strerror(err)); } } gettimeofday(&now,NULL); timeout.tv_sec = now.tv_sec + tm; /* time out after tm seconds */ timeout.tv_nsec = now.tv_usec * 1000; while (server_data_users>0) { if(pthread_cond_timedwait(&server_data_cond, &servers_lock, &timeout) == ETIMEDOUT) { pthread_mutex_unlock(&servers_lock); return 0; } } return 1; } /* Call this to free the lock obtained with exclusive_lock_server_data(). If retest is nonzero, the server-status thread is reactivated to check which servers are up. This is useful in case the configuration has changed. */ void exclusive_unlock_server_data(int retest) { if(retest) { if(pthread_equal(servstat_thrid,main_thrid)) start_servstat_thread(); else pthread_cond_signal(&server_test_cond); } pthread_mutex_unlock(&servers_lock); } /* Change addresses of servers during runtime. i is the number of the server section to change. ar should point to an array of IP addresses (may be NULL). up=1 or up=0 means mark server up or down afterwards, up=-1 means retest. A non-zero return value indicates an error. */ int change_servers(int i, addr_array ar, int up) { int retval=0,j,change,signal_test; int n; servparm_t *sp; pthread_mutex_lock(&servers_lock); signal_test=0; change=0; n=DA_NEL(ar); sp=&DA_INDEX(servers,i); if(n != DA_NEL(sp->atup_a) || sp->rootserver>1) change=1; else { int j; for(j=0;j<n;++j) if(!same_inaddr2(&DA_INDEX(ar,j),&DA_INDEX(sp->atup_a,j).a)) { change=1; break; } } if(change) { /* we need exclusive access to the server data to make the changes */ struct timeval now; struct timespec timeout; atup_array ata; if(server_status_ping>0 && !pthread_equal(servstat_thrid,main_thrid)) { int err; /* Try to interrupt server status thread to prevent delays. */ DEBUG_MSG("Sending server status thread an interrupt signal.\n"); if((err=pthread_kill(servstat_thrid,statusintsig))) { DEBUG_MSG("pthread_kill failed: %s\n",strerror(err)); } } DEBUG_MSG("Changing IPs of server section #%d\n",i); gettimeofday(&now,NULL); timeout.tv_sec = now.tv_sec + 60; /* time out after 60 seconds */ timeout.tv_nsec = now.tv_usec * 1000; while (server_data_users>0) { if(pthread_cond_timedwait(&server_data_cond, &servers_lock, &timeout) == ETIMEDOUT) { retval=ETIMEDOUT; goto unlock_mutex; } } ata= DA_CREATE(atup_array, n); if(!ata) { log_warn("Out of memory in change_servers()."); retval=ENOMEM; goto unlock_mutex; } da_free(sp->atup_a); sp->atup_a=ata; /* Stop trying to discover rootservers if we set the addresses using this routine. */ if(sp->rootserver>1) sp->rootserver=1; } for(j=0; j<n; ++j) { atup_t *at = &DA_INDEX(sp->atup_a,j); if(change) { SET_PDNSD_A2(&at->a, &DA_INDEX(ar,j)); at->is_up=sp->preset; } if(up>=0) { at->is_up=up; at->i_ts=time(NULL); } else if(change || at->i_ts) { /* A test may take a while, and we don't want to hold up the calling thread. Instead we set the timestamp to zero and signal a condition which should wake up the server test thread. */ at->i_ts=0; signal_test=1; } } if(signal_test) { if(pthread_equal(servstat_thrid,main_thrid)) retval=start_servstat_thread(); else { retest_flag=1; retval=pthread_cond_signal(&server_test_cond); } } unlock_mutex: pthread_mutex_unlock(&servers_lock); return retval; } /* The signal handler for the signal to tell the server status thread to discontinue testing. */ static void sigint_handler(int signum) { signal_interrupt=1; }
gpl-3.0
mammuth/Signal-Android
jni/webrtc/modules/audio_coding/codecs/isac/main/source/filter_functions.c
98
7619
/* * Copyright (c) 2011 The WebRTC 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 <memory.h> #ifdef WEBRTC_ANDROID #include <stdlib.h> #endif #include "pitch_estimator.h" #include "lpc_analysis.h" #include "codec.h" void WebRtcIsac_AllPoleFilter(double *InOut, double *Coef, int lengthInOut, int orderCoef){ /* the state of filter is assumed to be in InOut[-1] to InOut[-orderCoef] */ double scal; double sum; int n,k; //if (fabs(Coef[0]-1.0)<0.001) { if ( (Coef[0] > 0.9999) && (Coef[0] < 1.0001) ) { for(n = 0; n < lengthInOut; n++) { sum = Coef[1] * InOut[-1]; for(k = 2; k <= orderCoef; k++){ sum += Coef[k] * InOut[-k]; } *InOut++ -= sum; } } else { scal = 1.0 / Coef[0]; for(n=0;n<lengthInOut;n++) { *InOut *= scal; for(k=1;k<=orderCoef;k++){ *InOut -= scal*Coef[k]*InOut[-k]; } InOut++; } } } void WebRtcIsac_AllZeroFilter(double *In, double *Coef, int lengthInOut, int orderCoef, double *Out){ /* the state of filter is assumed to be in In[-1] to In[-orderCoef] */ int n, k; double tmp; for(n = 0; n < lengthInOut; n++) { tmp = In[0] * Coef[0]; for(k = 1; k <= orderCoef; k++){ tmp += Coef[k] * In[-k]; } *Out++ = tmp; In++; } } void WebRtcIsac_ZeroPoleFilter(double *In, double *ZeroCoef, double *PoleCoef, int lengthInOut, int orderCoef, double *Out){ /* the state of the zero section is assumed to be in In[-1] to In[-orderCoef] */ /* the state of the pole section is assumed to be in Out[-1] to Out[-orderCoef] */ WebRtcIsac_AllZeroFilter(In,ZeroCoef,lengthInOut,orderCoef,Out); WebRtcIsac_AllPoleFilter(Out,PoleCoef,lengthInOut,orderCoef); } void WebRtcIsac_AutoCorr( double *r, const double *x, int N, int order ) { int lag, n; double sum, prod; const double *x_lag; for (lag = 0; lag <= order; lag++) { sum = 0.0f; x_lag = &x[lag]; prod = x[0] * x_lag[0]; for (n = 1; n < N - lag; n++) { sum += prod; prod = x[n] * x_lag[n]; } sum += prod; r[lag] = sum; } } void WebRtcIsac_BwExpand(double *out, double *in, double coef, short length) { int i; double chirp; chirp = coef; out[0] = in[0]; for (i = 1; i < length; i++) { out[i] = chirp * in[i]; chirp *= coef; } } void WebRtcIsac_WeightingFilter(const double *in, double *weiout, double *whiout, WeightFiltstr *wfdata) { double tmpbuffer[PITCH_FRAME_LEN + PITCH_WLPCBUFLEN]; double corr[PITCH_WLPCORDER+1], rc[PITCH_WLPCORDER+1]; double apol[PITCH_WLPCORDER+1], apolr[PITCH_WLPCORDER+1]; double rho=0.9, *inp, *dp, *dp2; double whoutbuf[PITCH_WLPCBUFLEN + PITCH_WLPCORDER]; double weoutbuf[PITCH_WLPCBUFLEN + PITCH_WLPCORDER]; double *weo, *who, opol[PITCH_WLPCORDER+1], ext[PITCH_WLPCWINLEN]; int k, n, endpos, start; /* Set up buffer and states */ memcpy(tmpbuffer, wfdata->buffer, sizeof(double) * PITCH_WLPCBUFLEN); memcpy(tmpbuffer+PITCH_WLPCBUFLEN, in, sizeof(double) * PITCH_FRAME_LEN); memcpy(wfdata->buffer, tmpbuffer+PITCH_FRAME_LEN, sizeof(double) * PITCH_WLPCBUFLEN); dp=weoutbuf; dp2=whoutbuf; for (k=0;k<PITCH_WLPCORDER;k++) { *dp++ = wfdata->weostate[k]; *dp2++ = wfdata->whostate[k]; opol[k]=0.0; } opol[0]=1.0; opol[PITCH_WLPCORDER]=0.0; weo=dp; who=dp2; endpos=PITCH_WLPCBUFLEN + PITCH_SUBFRAME_LEN; inp=tmpbuffer + PITCH_WLPCBUFLEN; for (n=0; n<PITCH_SUBFRAMES; n++) { /* Windowing */ start=endpos-PITCH_WLPCWINLEN; for (k=0; k<PITCH_WLPCWINLEN; k++) { ext[k]=wfdata->window[k]*tmpbuffer[start+k]; } /* Get LPC polynomial */ WebRtcIsac_AutoCorr(corr, ext, PITCH_WLPCWINLEN, PITCH_WLPCORDER); corr[0]=1.01*corr[0]+1.0; /* White noise correction */ WebRtcIsac_LevDurb(apol, rc, corr, PITCH_WLPCORDER); WebRtcIsac_BwExpand(apolr, apol, rho, PITCH_WLPCORDER+1); /* Filtering */ WebRtcIsac_ZeroPoleFilter(inp, apol, apolr, PITCH_SUBFRAME_LEN, PITCH_WLPCORDER, weo); WebRtcIsac_ZeroPoleFilter(inp, apolr, opol, PITCH_SUBFRAME_LEN, PITCH_WLPCORDER, who); inp+=PITCH_SUBFRAME_LEN; endpos+=PITCH_SUBFRAME_LEN; weo+=PITCH_SUBFRAME_LEN; who+=PITCH_SUBFRAME_LEN; } /* Export filter states */ for (k=0;k<PITCH_WLPCORDER;k++) { wfdata->weostate[k]=weoutbuf[PITCH_FRAME_LEN+k]; wfdata->whostate[k]=whoutbuf[PITCH_FRAME_LEN+k]; } /* Export output data */ memcpy(weiout, weoutbuf+PITCH_WLPCORDER, sizeof(double) * PITCH_FRAME_LEN); memcpy(whiout, whoutbuf+PITCH_WLPCORDER, sizeof(double) * PITCH_FRAME_LEN); } static const double APupper[ALLPASSSECTIONS] = {0.0347, 0.3826}; static const double APlower[ALLPASSSECTIONS] = {0.1544, 0.744}; void WebRtcIsac_AllpassFilterForDec(double *InOut, const double *APSectionFactors, int lengthInOut, double *FilterState) { //This performs all-pass filtering--a series of first order all-pass sections are used //to filter the input in a cascade manner. int n,j; double temp; for (j=0; j<ALLPASSSECTIONS; j++){ for (n=0;n<lengthInOut;n+=2){ temp = InOut[n]; //store input InOut[n] = FilterState[j] + APSectionFactors[j]*temp; FilterState[j] = -APSectionFactors[j]*InOut[n] + temp; } } } void WebRtcIsac_DecimateAllpass(const double *in, double *state_in, /* array of size: 2*ALLPASSSECTIONS+1 */ int N, /* number of input samples */ double *out) /* array of size N/2 */ { int n; double data_vec[PITCH_FRAME_LEN]; /* copy input */ memcpy(data_vec+1, in, sizeof(double) * (N-1)); data_vec[0] = state_in[2*ALLPASSSECTIONS]; //the z^(-1) state state_in[2*ALLPASSSECTIONS] = in[N-1]; WebRtcIsac_AllpassFilterForDec(data_vec+1, APupper, N, state_in); WebRtcIsac_AllpassFilterForDec(data_vec, APlower, N, state_in+ALLPASSSECTIONS); for (n=0;n<N/2;n++) out[n] = data_vec[2*n] + data_vec[2*n+1]; } /* create high-pass filter ocefficients * z = 0.998 * exp(j*2*pi*35/8000); * p = 0.94 * exp(j*2*pi*140/8000); * HP_b = [1, -2*real(z), abs(z)^2]; * HP_a = [1, -2*real(p), abs(p)^2]; */ static const double a_coef[2] = { 1.86864659625574, -0.88360000000000}; static const double b_coef[2] = {-1.99524591718270, 0.99600400000000}; static const float a_coef_float[2] = { 1.86864659625574f, -0.88360000000000f}; static const float b_coef_float[2] = {-1.99524591718270f, 0.99600400000000f}; /* second order high-pass filter */ void WebRtcIsac_Highpass(const double *in, double *out, double *state, int N) { int k; for (k=0; k<N; k++) { *out = *in + state[1]; state[1] = state[0] + b_coef[0] * *in + a_coef[0] * *out; state[0] = b_coef[1] * *in++ + a_coef[1] * *out++; } } void WebRtcIsac_Highpass_float(const float *in, double *out, double *state, int N) { int k; for (k=0; k<N; k++) { *out = (double)*in + state[1]; state[1] = state[0] + b_coef_float[0] * *in + a_coef_float[0] * *out; state[0] = b_coef_float[1] * (double)*in++ + a_coef_float[1] * *out++; } }
gpl-3.0
Smapo/customized-sipdroid-for-spotlight-reception
jni/silk/src/SKP_Silk_decode_parameters_v4.c
99
7943
/*********************************************************************** Copyright (c) 2006-2010, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, (subject to the limitations in the disclaimer below) 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 Skype Limited, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #include "SKP_Silk_main.h" /* Decode parameters from payload */ void SKP_Silk_decode_parameters_v4( SKP_Silk_decoder_state *psDec, /* I/O State */ SKP_Silk_decoder_control *psDecCtrl, /* I/O Decoder control */ SKP_int q[ MAX_FRAME_LENGTH ], /* O Excitation signal */ const SKP_int fullDecoding /* I Flag to tell if only arithmetic decoding */ ) { SKP_int i, k, Ix, nBytesUsed; SKP_int pNLSF_Q15[ MAX_LPC_ORDER ], pNLSF0_Q15[ MAX_LPC_ORDER ]; const SKP_int16 *cbk_ptr_Q14; const SKP_Silk_NLSF_CB_struct *psNLSF_CB = NULL; SKP_Silk_range_coder_state *psRC = &psDec->sRC; psDec->FrameTermination = SKP_SILK_MORE_FRAMES; psDecCtrl->sigtype = psDec->sigtype[ psDec->nFramesDecoded ]; psDecCtrl->QuantOffsetType = psDec->QuantOffsetType[ psDec->nFramesDecoded ]; psDec->vadFlag = psDec->vadFlagBuf[ psDec->nFramesDecoded ]; psDecCtrl->NLSFInterpCoef_Q2 = psDec->NLSFInterpCoef_Q2[ psDec->nFramesDecoded ]; psDecCtrl->Seed = psDec->Seed[ psDec->nFramesDecoded ]; /* Dequant Gains */ SKP_Silk_gains_dequant( psDecCtrl->Gains_Q16, psDec->GainsIndices[ psDec->nFramesDecoded ], &psDec->LastGainIndex, psDec->nFramesDecoded ); /****************/ /* Decode NLSFs */ /****************/ /* Set pointer to NLSF VQ CB for the current signal type */ psNLSF_CB = psDec->psNLSF_CB[ psDecCtrl->sigtype ]; /* From the NLSF path, decode an NLSF vector */ SKP_Silk_NLSF_MSVQ_decode( pNLSF_Q15, psNLSF_CB, psDec->NLSFIndices[ psDec->nFramesDecoded ], psDec->LPC_order ); /* Convert NLSF parameters to AR prediction filter coefficients */ SKP_Silk_NLSF2A_stable( psDecCtrl->PredCoef_Q12[ 1 ], pNLSF_Q15, psDec->LPC_order ); /* If just reset, e.g., because internal Fs changed, do not allow interpolation */ /* improves the case of packet loss in the first frame after a switch */ if( psDec->first_frame_after_reset == 1 ) { psDecCtrl->NLSFInterpCoef_Q2 = 4; } if( psDecCtrl->NLSFInterpCoef_Q2 < 4 ) { /* Calculation of the interpolated NLSF0 vector from the interpolation factor, */ /* the previous NLSF1, and the current NLSF1 */ for( i = 0; i < psDec->LPC_order; i++ ) { pNLSF0_Q15[ i ] = psDec->prevNLSF_Q15[ i ] + SKP_RSHIFT( SKP_MUL( psDecCtrl->NLSFInterpCoef_Q2, ( pNLSF_Q15[ i ] - psDec->prevNLSF_Q15[ i ] ) ), 2 ); } /* Convert NLSF parameters to AR prediction filter coefficients */ SKP_Silk_NLSF2A_stable( psDecCtrl->PredCoef_Q12[ 0 ], pNLSF0_Q15, psDec->LPC_order ); } else { /* Copy LPC coefficients for first half from second half */ SKP_memcpy( psDecCtrl->PredCoef_Q12[ 0 ], psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order * sizeof( SKP_int16 ) ); } SKP_memcpy( psDec->prevNLSF_Q15, pNLSF_Q15, psDec->LPC_order * sizeof( SKP_int ) ); /* After a packet loss do BWE of LPC coefs */ if( psDec->lossCnt ) { SKP_Silk_bwexpander( psDecCtrl->PredCoef_Q12[ 0 ], psDec->LPC_order, BWE_AFTER_LOSS_Q16 ); SKP_Silk_bwexpander( psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order, BWE_AFTER_LOSS_Q16 ); } if( psDecCtrl->sigtype == SIG_TYPE_VOICED ) { /*********************/ /* Decode pitch lags */ /*********************/ /* Decode pitch values */ SKP_Silk_decode_pitch( psDec->lagIndex[ psDec->nFramesDecoded ], psDec->contourIndex[ psDec->nFramesDecoded ], psDecCtrl->pitchL, psDec->fs_kHz ); /********************/ /* Decode LTP gains */ /********************/ psDecCtrl->PERIndex = psDec->PERIndex[ psDec->nFramesDecoded ]; /* Decode Codebook Index */ cbk_ptr_Q14 = SKP_Silk_LTP_vq_ptrs_Q14[ psDecCtrl->PERIndex ]; /* set pointer to start of codebook */ for( k = 0; k < NB_SUBFR; k++ ) { Ix = psDec->LTPIndex[ psDec->nFramesDecoded ][ k ]; for( i = 0; i < LTP_ORDER; i++ ) { psDecCtrl->LTPCoef_Q14[ SKP_SMULBB( k, LTP_ORDER ) + i ] = cbk_ptr_Q14[ SKP_SMULBB( Ix, LTP_ORDER ) + i ]; } } /**********************/ /* Decode LTP scaling */ /**********************/ Ix = psDec->LTP_scaleIndex[ psDec->nFramesDecoded ]; psDecCtrl->LTP_scale_Q14 = SKP_Silk_LTPScales_table_Q14[ Ix ]; } else { SKP_memset( psDecCtrl->pitchL, 0, NB_SUBFR * sizeof( SKP_int ) ); SKP_memset( psDecCtrl->LTPCoef_Q14, 0, NB_SUBFR * LTP_ORDER * sizeof( SKP_int16 ) ); psDecCtrl->PERIndex = 0; psDecCtrl->LTP_scale_Q14 = 0; } /*********************************************/ /* Decode quantization indices of excitation */ /*********************************************/ SKP_Silk_decode_pulses( psRC, psDecCtrl, q, psDec->frame_length ); /****************************************/ /* get number of bytes used so far */ /****************************************/ SKP_Silk_range_coder_get_length( psRC, &nBytesUsed ); psDec->nBytesLeft = psRC->bufferLength - nBytesUsed; if( psDec->nBytesLeft < 0 ) { psRC->error = RANGE_CODER_READ_BEYOND_BUFFER; } /****************************************/ /* check remaining bits in last byte */ /****************************************/ if( psDec->nBytesLeft == 0 ) { SKP_Silk_range_coder_check_after_decoding( psRC ); } if( psDec->nFramesInPacket == (psDec->nFramesDecoded + 1)) { /* To indicate the packet has been fully decoded */ psDec->FrameTermination = SKP_SILK_LAST_FRAME; } }
gpl-3.0
yuexy/shadowsocks-android
src/main/jni/badvpn/ncd/modules/sys_request_server.c
360
25319
/** * @file sys_request_server.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 * * A simple a IPC interface for NCD to talk to other processes over a Unix socket. * * Synopsis: * sys.request_server(listen_address, string request_handler_template, list args) * * Description: * Initializes a request server on the given socket path. Requests are served by * starting a template process for every request. Multiple such processes may * exist simultaneously. Termination of these processess may be initiated at * any time if the request server no longer needs the request in question served. * The payload of a request is a value, and can be accessed as _request.data * from within the handler process. Replies to the request can be sent using * _request->reply(data); replies are values too. Finally, _request->finish() * should be called to indicate that no further replies will be sent. Calling * finish() will immediately initiate termination of the handler process. * Requests can be sent to NCD using the badvpn-ncd-request program. * * The listen address should be in the same format as for the socket module. * In particular, it must be in one of the following forms: * - {"tcp", {"ipv4", ipv4_address, port_number}}, * - {"tcp", {"ipv6", ipv6_address, port_number}}, * - {"unix", socket_path}. * * Predefined objects and variables in request_handler_template: * _caller - provides access to objects as seen from the sys.request_server() * command * _request.data - the request payload as sent by the client * string _request.client_addr - the address of the client. The form is * like the second part of the sys.request_server() address format, e.g. * {"ipv4", "1.2.3.4", "4000"}. * * Synopsis: * sys.request_server.request::reply(reply_data) * * Synopsis: * sys.request_server.request::finish() */ #include <stdlib.h> #include <string.h> #include <limits.h> #include <inttypes.h> #include <errno.h> #include <misc/offset.h> #include <misc/debug.h> #include <misc/byteorder.h> #include <protocol/packetproto.h> #include <protocol/requestproto.h> #include <structure/LinkedList0.h> #include <system/BConnection.h> #include <system/BConnectionGeneric.h> #include <system/BAddr.h> #include <flow/PacketProtoDecoder.h> #include <flow/PacketStreamSender.h> #include <flow/PacketPassFifoQueue.h> #include <ncd/NCDValParser.h> #include <ncd/NCDValGenerator.h> #include <ncd/NCDModule.h> #include <ncd/static_strings.h> #include <ncd/extra/value_utils.h> #include <ncd/extra/address_utils.h> #include <generated/blog_channel_ncd_sys_request_server.h> #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__) #define ModuleString(i, id) ((i)->m->group->strings[(id)]) #define SEND_PAYLOAD_MTU 32768 #define RECV_PAYLOAD_MTU 32768 #define SEND_MTU (SEND_PAYLOAD_MTU + sizeof(struct requestproto_header)) #define RECV_MTU (RECV_PAYLOAD_MTU + sizeof(struct requestproto_header)) struct instance { NCDModuleInst *i; NCDValRef request_handler_template; NCDValRef args; BListener listener; LinkedList0 connections_list; int dying; }; #define CONNECTION_STATE_RUNNING 1 #define CONNECTION_STATE_TERMINATING 2 struct reply; struct connection { struct instance *inst; LinkedList0Node connections_list_node; BConnection con; BAddr addr; PacketProtoDecoder recv_decoder; PacketPassInterface recv_if; PacketPassFifoQueue send_queue; PacketStreamSender send_pss; LinkedList0 requests_list; LinkedList0 replies_list; int state; }; struct request { struct connection *con; uint32_t request_id; LinkedList0Node requests_list_node; NCDValMem request_data_mem; NCDValRef request_data; struct reply *end_reply; NCDModuleProcess process; int terminating; int got_finished; }; struct reply { struct connection *con; LinkedList0Node replies_list_node; PacketPassFifoQueueFlow send_qflow; PacketPassInterface *send_qflow_if; uint8_t *send_buf; }; static void listener_handler (struct instance *o); static void connection_free (struct connection *c); static void connection_free_link (struct connection *c); static void connection_terminate (struct connection *c); static void connection_con_handler (struct connection *c, int event); static void connection_recv_decoder_handler_error (struct connection *c); static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len); static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len); static void request_free (struct request *r); static struct request * find_request (struct connection *c, uint32_t request_id); static void request_process_handler_event (NCDModuleProcess *process, int event); static int request_process_func_getspecialobj (NCDModuleProcess *process, NCD_string_id_t name, NCDObject *out_object); static int request_process_caller_obj_func_getobj (const NCDObject *obj, NCD_string_id_t name, NCDObject *out_object); static int request_process_request_obj_func_getvar (const NCDObject *obj, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out_value); static void request_terminate (struct request *r); static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data); static void reply_start (struct reply *r, uint32_t type); static void reply_free (struct reply *r); static void reply_send_qflow_if_handler_done (struct reply *r); static void instance_free (struct instance *o); enum {STRING_REQUEST, STRING_DATA, STRING_CLIENT_ADDR, STRING_SYS_REQUEST_SERVER_REQUEST}; static const char *strings[] = { "_request", "data", "client_addr", "sys.request_server.request", NULL }; static void listener_handler (struct instance *o) { ASSERT(!o->dying) BReactor *reactor = o->i->params->iparams->reactor; BPendingGroup *pg = BReactor_PendingGroup(reactor); struct connection *c = malloc(sizeof(*c)); if (!c) { ModuleLog(o->i, BLOG_ERROR, "malloc failed"); goto fail0; } c->inst = o; LinkedList0_Prepend(&o->connections_list, &c->connections_list_node); if (!BConnection_Init(&c->con, BConnection_source_listener(&o->listener, &c->addr), reactor, c, (BConnection_handler)connection_con_handler)) { ModuleLog(o->i, BLOG_ERROR, "BConnection_Init failed"); goto fail1; } BConnection_SendAsync_Init(&c->con); BConnection_RecvAsync_Init(&c->con); StreamPassInterface *con_send_if = BConnection_SendAsync_GetIf(&c->con); StreamRecvInterface *con_recv_if = BConnection_RecvAsync_GetIf(&c->con); PacketPassInterface_Init(&c->recv_if, RECV_MTU, (PacketPassInterface_handler_send)connection_recv_if_handler_send, c, pg); if (!PacketProtoDecoder_Init(&c->recv_decoder, con_recv_if, &c->recv_if, pg, c, (PacketProtoDecoder_handler_error)connection_recv_decoder_handler_error)) { ModuleLog(o->i, BLOG_ERROR, "PacketProtoDecoder_Init failed"); goto fail2; } PacketStreamSender_Init(&c->send_pss, con_send_if, PACKETPROTO_ENCLEN(SEND_MTU), pg); PacketPassFifoQueue_Init(&c->send_queue, PacketStreamSender_GetInput(&c->send_pss), pg); LinkedList0_Init(&c->requests_list); LinkedList0_Init(&c->replies_list); c->state = CONNECTION_STATE_RUNNING; ModuleLog(o->i, BLOG_INFO, "connection initialized"); return; fail2: PacketPassInterface_Free(&c->recv_if); BConnection_RecvAsync_Free(&c->con); BConnection_SendAsync_Free(&c->con); BConnection_Free(&c->con); fail1: LinkedList0_Remove(&o->connections_list, &c->connections_list_node); free(c); fail0: return; } static void connection_free (struct connection *c) { struct instance *o = c->inst; ASSERT(c->state == CONNECTION_STATE_TERMINATING) ASSERT(LinkedList0_IsEmpty(&c->requests_list)) ASSERT(LinkedList0_IsEmpty(&c->replies_list)) LinkedList0_Remove(&o->connections_list, &c->connections_list_node); free(c); } static void connection_free_link (struct connection *c) { PacketPassFifoQueue_PrepareFree(&c->send_queue); LinkedList0Node *ln; while (ln = LinkedList0_GetFirst(&c->replies_list)) { struct reply *r = UPPER_OBJECT(ln, struct reply, replies_list_node); ASSERT(r->con == c) reply_free(r); } PacketPassFifoQueue_Free(&c->send_queue); PacketStreamSender_Free(&c->send_pss); PacketProtoDecoder_Free(&c->recv_decoder); PacketPassInterface_Free(&c->recv_if); BConnection_RecvAsync_Free(&c->con); BConnection_SendAsync_Free(&c->con); BConnection_Free(&c->con); } static void connection_terminate (struct connection *c) { ASSERT(c->state == CONNECTION_STATE_RUNNING) for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) { struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node); if (!r->terminating) { request_terminate(r); } } connection_free_link(c); c->state = CONNECTION_STATE_TERMINATING; if (LinkedList0_IsEmpty(&c->requests_list)) { connection_free(c); return; } } static void connection_con_handler (struct connection *c, int event) { struct instance *o = c->inst; ASSERT(c->state == CONNECTION_STATE_RUNNING) ModuleLog(o->i, BLOG_INFO, "connection closed"); connection_terminate(c); } static void connection_recv_decoder_handler_error (struct connection *c) { struct instance *o = c->inst; ASSERT(c->state == CONNECTION_STATE_RUNNING) ModuleLog(o->i, BLOG_ERROR, "decoder error"); connection_terminate(c); } static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len) { struct instance *o = c->inst; ASSERT(c->state == CONNECTION_STATE_RUNNING) ASSERT(data_len >= 0) ASSERT(data_len <= RECV_MTU) PacketPassInterface_Done(&c->recv_if); if (data_len < sizeof(struct requestproto_header)) { ModuleLog(o->i, BLOG_ERROR, "missing requestproto header"); goto fail; } struct requestproto_header header; memcpy(&header, data, sizeof(header)); uint32_t request_id = ltoh32(header.request_id); uint32_t type = ltoh32(header.type); switch (type) { case REQUESTPROTO_TYPE_CLIENT_REQUEST: { if (find_request(c, request_id)) { ModuleLog(o->i, BLOG_ERROR, "request with the same ID already exists"); goto fail; } if (!request_init(c, request_id, data + sizeof(header), data_len - sizeof(header))) { goto fail; } } break; case REQUESTPROTO_TYPE_CLIENT_ABORT: { struct request *r = find_request(c, request_id); if (!r) { // this is expected if we finish before we get the abort return; } if (!r->terminating) { request_terminate(r); } } break; default: ModuleLog(o->i, BLOG_ERROR, "invalid requestproto type"); goto fail; } return; fail: connection_terminate(c); } static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len) { struct instance *o = c->inst; ASSERT(c->state == CONNECTION_STATE_RUNNING) ASSERT(!find_request(c, request_id)) ASSERT(data_len >= 0) ASSERT(data_len <= RECV_PAYLOAD_MTU) struct request *r = malloc(sizeof(*r)); if (!r) { ModuleLog(o->i, BLOG_ERROR, "malloc failed"); goto fail0; } r->con = c; r->request_id = request_id; LinkedList0_Prepend(&c->requests_list, &r->requests_list_node); NCDValMem_Init(&r->request_data_mem); if (!NCDValParser_Parse((const char *)data, data_len, &r->request_data_mem, &r->request_data)) { ModuleLog(o->i, BLOG_ERROR, "NCDValParser_Parse failed"); goto fail1; } if (!(r->end_reply = reply_init(c, request_id, NCDVal_NewInvalid()))) { goto fail1; } if (!NCDModuleProcess_InitValue(&r->process, o->i, o->request_handler_template, o->args, request_process_handler_event)) { ModuleLog(o->i, BLOG_ERROR, "NCDModuleProcess_Init failed"); goto fail3; } NCDModuleProcess_SetSpecialFuncs(&r->process, request_process_func_getspecialobj); r->terminating = 0; r->got_finished = 0; ModuleLog(o->i, BLOG_INFO, "request initialized"); return 1; fail3: reply_free(r->end_reply); fail1: NCDValMem_Free(&r->request_data_mem); LinkedList0_Remove(&c->requests_list, &r->requests_list_node); free(r); fail0: return 0; } static void request_free (struct request *r) { struct connection *c = r->con; NCDModuleProcess_AssertFree(&r->process); if (c->state != CONNECTION_STATE_TERMINATING) { uint32_t type = r->got_finished ? REQUESTPROTO_TYPE_SERVER_FINISHED : REQUESTPROTO_TYPE_SERVER_ERROR; reply_start(r->end_reply, type); } NCDModuleProcess_Free(&r->process); NCDValMem_Free(&r->request_data_mem); LinkedList0_Remove(&c->requests_list, &r->requests_list_node); free(r); } static struct request * find_request (struct connection *c, uint32_t request_id) { for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) { struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node); if (!r->terminating && r->request_id == request_id) { return r; } } return NULL; } static void request_process_handler_event (NCDModuleProcess *process, int event) { struct request *r = UPPER_OBJECT(process, struct request, process); struct connection *c = r->con; struct instance *o = c->inst; switch (event) { case NCDMODULEPROCESS_EVENT_UP: { ASSERT(!r->terminating) } break; case NCDMODULEPROCESS_EVENT_DOWN: { ASSERT(!r->terminating) NCDModuleProcess_Continue(&r->process); } break; case NCDMODULEPROCESS_EVENT_TERMINATED: { ASSERT(r->terminating) request_free(r); if (c->state == CONNECTION_STATE_TERMINATING && LinkedList0_IsEmpty(&c->requests_list)) { connection_free(c); if (o->dying && LinkedList0_IsEmpty(&o->connections_list)) { instance_free(o); return; } } } break; default: ASSERT(0); } } static int request_process_func_getspecialobj (NCDModuleProcess *process, NCD_string_id_t name, NCDObject *out_object) { struct request *r = UPPER_OBJECT(process, struct request, process); if (name == NCD_STRING_CALLER) { *out_object = NCDObject_Build(-1, r, NCDObject_no_getvar, request_process_caller_obj_func_getobj); return 1; } if (name == ModuleString(r->con->inst->i, STRING_REQUEST)) { *out_object = NCDObject_Build(ModuleString(r->con->inst->i, STRING_SYS_REQUEST_SERVER_REQUEST), r, request_process_request_obj_func_getvar, NCDObject_no_getobj); return 1; } return 0; } static int request_process_caller_obj_func_getobj (const NCDObject *obj, NCD_string_id_t name, NCDObject *out_object) { struct request *r = NCDObject_DataPtr(obj); return NCDModuleInst_Backend_GetObj(r->con->inst->i, name, out_object); } static int request_process_request_obj_func_getvar (const NCDObject *obj, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out) { struct request *r = NCDObject_DataPtr(obj); if (name == ModuleString(r->con->inst->i, STRING_DATA)) { *out = NCDVal_NewCopy(mem, r->request_data); return 1; } if (name == ModuleString(r->con->inst->i, STRING_CLIENT_ADDR)) { *out = ncd_make_baddr(r->con->addr, mem); return 1; } return 0; } static void request_terminate (struct request *r) { ASSERT(!r->terminating) NCDModuleProcess_Terminate(&r->process); r->terminating = 1; } static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data) { struct instance *o = c->inst; ASSERT(c->state == CONNECTION_STATE_RUNNING) NCDVal_Assert(reply_data); struct reply *r = malloc(sizeof(*r)); if (!r) { ModuleLog(o->i, BLOG_ERROR, "malloc failed"); goto fail0; } r->con = c; LinkedList0_Prepend(&c->replies_list, &r->replies_list_node); PacketPassFifoQueueFlow_Init(&r->send_qflow, &c->send_queue); r->send_qflow_if = PacketPassFifoQueueFlow_GetInput(&r->send_qflow); PacketPassInterface_Sender_Init(r->send_qflow_if, (PacketPassInterface_handler_done)reply_send_qflow_if_handler_done, r); ExpString str; if (!ExpString_Init(&str)) { ModuleLog(o->i, BLOG_ERROR, "ExpString_Init failed"); goto fail1; } if (!ExpString_AppendZeros(&str, sizeof(struct packetproto_header) + sizeof(struct requestproto_header))) { ModuleLog(o->i, BLOG_ERROR, "ExpString_AppendZeros failed"); goto fail2; } if (!NCDVal_IsInvalid(reply_data) && !NCDValGenerator_AppendGenerate(reply_data, &str)) { ModuleLog(o->i, BLOG_ERROR, "NCDValGenerator_AppendGenerate failed"); goto fail2; } size_t len = ExpString_Length(&str); if (len > INT_MAX || len > PACKETPROTO_ENCLEN(SEND_MTU) || len - sizeof(struct packetproto_header) > UINT16_MAX) { ModuleLog(o->i, BLOG_ERROR, "reply is too long"); goto fail2; } r->send_buf = (uint8_t *)ExpString_Get(&str); struct packetproto_header pp; pp.len = htol16(len - sizeof(pp)); struct requestproto_header rp; rp.request_id = htol32(request_id); memcpy(r->send_buf, &pp, sizeof(pp)); memcpy(r->send_buf + sizeof(pp), &rp, sizeof(rp)); return r; fail2: ExpString_Free(&str); fail1: PacketPassFifoQueueFlow_Free(&r->send_qflow); LinkedList0_Remove(&c->replies_list, &r->replies_list_node); free(r); fail0: return NULL; } static void reply_start (struct reply *r, uint32_t type) { struct requestproto_header rp; memcpy(&rp, r->send_buf + sizeof(struct packetproto_header), sizeof(rp)); rp.type = htol32(type); memcpy(r->send_buf + sizeof(struct packetproto_header), &rp, sizeof(rp)); struct packetproto_header pp; memcpy(&pp, r->send_buf, sizeof(pp)); int len = ltoh16(pp.len) + sizeof(struct packetproto_header); PacketPassInterface_Sender_Send(r->send_qflow_if, r->send_buf, len); } static void reply_free (struct reply *r) { struct connection *c = r->con; PacketPassFifoQueueFlow_AssertFree(&r->send_qflow); free(r->send_buf); PacketPassFifoQueueFlow_Free(&r->send_qflow); LinkedList0_Remove(&c->replies_list, &r->replies_list_node); free(r); } static void reply_send_qflow_if_handler_done (struct reply *r) { reply_free(r); } static void func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct instance *o = vo; o->i = i; // check arguments NCDValRef listen_addr_arg; NCDValRef request_handler_template_arg; NCDValRef args_arg; if (!NCDVal_ListRead(params->args, 3, &listen_addr_arg, &request_handler_template_arg, &args_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(request_handler_template_arg) || !NCDVal_IsList(args_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong type"); goto fail0; } o->request_handler_template = request_handler_template_arg; o->args = args_arg; // read listen address struct BConnection_addr addr; if (!ncd_read_bconnection_addr(listen_addr_arg, &addr)) { ModuleLog(o->i, BLOG_ERROR, "wrong listen address"); goto fail0; } // init listener if (!BListener_InitGeneric(&o->listener, addr, i->params->iparams->reactor, o, (BListener_handler)listener_handler)) { ModuleLog(o->i, BLOG_ERROR, "BListener_InitGeneric failed"); goto fail0; } // init connections list LinkedList0_Init(&o->connections_list); // set not dying o->dying = 0; // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void instance_free (struct instance *o) { ASSERT(o->dying) ASSERT(LinkedList0_IsEmpty(&o->connections_list)) NCDModuleInst_Backend_Dead(o->i); } static void func_die (void *vo) { struct instance *o = vo; ASSERT(!o->dying) // free listener BListener_Free(&o->listener); // terminate connections LinkedList0Node *next_ln; for (LinkedList0Node *ln = LinkedList0_GetFirst(&o->connections_list); ln && (next_ln = LinkedList0Node_Next(ln)), ln; ln = next_ln) { struct connection *c = UPPER_OBJECT(ln, struct connection, connections_list_node); ASSERT(c->inst == o) if (c->state != CONNECTION_STATE_TERMINATING) { connection_terminate(c); } } // set dying o->dying = 1; // if no connections, die right away if (LinkedList0_IsEmpty(&o->connections_list)) { instance_free(o); return; } } static void reply_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { NCDValRef reply_data; if (!NCDVal_ListRead(params->args, 1, &reply_data)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail; } NCDModuleInst_Backend_Up(i); struct request *r = params->method_user; struct connection *c = r->con; if (r->terminating) { ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit reply"); goto fail; } struct reply *rpl = reply_init(c, r->request_id, reply_data); if (!rpl) { ModuleLog(i, BLOG_ERROR, "failed to submit reply"); goto fail; } reply_start(rpl, REQUESTPROTO_TYPE_SERVER_REPLY); return; fail: NCDModuleInst_Backend_DeadError(i); } static void finish_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { if (!NCDVal_ListRead(params->args, 0)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail; } NCDModuleInst_Backend_Up(i); struct request *r = params->method_user; if (r->terminating) { ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit finished"); goto fail; } r->got_finished = 1; request_terminate(r); return; fail: NCDModuleInst_Backend_DeadError(i); } static struct NCDModule modules[] = { { .type = "sys.request_server", .func_new2 = func_new, .func_die = func_die, .alloc_size = sizeof(struct instance) }, { .type = "sys.request_server.request::reply", .func_new2 = reply_func_new }, { .type = "sys.request_server.request::finish", .func_new2 = finish_func_new }, { .type = NULL } }; const struct NCDModuleGroup ncdmodule_sys_request_server = { .modules = modules, .strings = strings };
gpl-3.0
sjzhao/shadowsocks-android
src/main/jni/openssl/crypto/rand/rand_unix.c
618
13510
/* crypto/rand/rand_unix.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.] */ /* ==================================================================== * Copyright (c) 1998-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 * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #define USE_SOCKETS #include "e_os.h" #include "cryptlib.h" #include <openssl/rand.h> #include "rand_lcl.h" #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_NETWARE)) #include <sys/types.h> #include <sys/time.h> #include <sys/times.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <time.h> #if defined(OPENSSL_SYS_LINUX) /* should actually be available virtually everywhere */ # include <poll.h> #endif #include <limits.h> #ifndef FD_SETSIZE # define FD_SETSIZE (8*sizeof(fd_set)) #endif #if defined(OPENSSL_SYS_VOS) /* The following algorithm repeatedly samples the real-time clock (RTC) to generate a sequence of unpredictable data. The algorithm relies upon the uneven execution speed of the code (due to factors such as cache misses, interrupts, bus activity, and scheduling) and upon the rather large relative difference between the speed of the clock and the rate at which it can be read. If this code is ported to an environment where execution speed is more constant or where the RTC ticks at a much slower rate, or the clock can be read with fewer instructions, it is likely that the results would be far more predictable. As a precaution, we generate 4 times the minimum required amount of seed data. */ int RAND_poll(void) { short int code; gid_t curr_gid; pid_t curr_pid; uid_t curr_uid; int i, k; struct timespec ts; unsigned char v; #ifdef OPENSSL_SYS_VOS_HPPA long duration; extern void s$sleep (long *_duration, short int *_code); #else #ifdef OPENSSL_SYS_VOS_IA32 long long duration; extern void s$sleep2 (long long *_duration, short int *_code); #else #error "Unsupported Platform." #endif /* OPENSSL_SYS_VOS_IA32 */ #endif /* OPENSSL_SYS_VOS_HPPA */ /* Seed with the gid, pid, and uid, to ensure *some* variation between different processes. */ curr_gid = getgid(); RAND_add (&curr_gid, sizeof curr_gid, 1); curr_gid = 0; curr_pid = getpid(); RAND_add (&curr_pid, sizeof curr_pid, 1); curr_pid = 0; curr_uid = getuid(); RAND_add (&curr_uid, sizeof curr_uid, 1); curr_uid = 0; for (i=0; i<(ENTROPY_NEEDED*4); i++) { /* burn some cpu; hope for interrupts, cache collisions, bus interference, etc. */ for (k=0; k<99; k++) ts.tv_nsec = random (); #ifdef OPENSSL_SYS_VOS_HPPA /* sleep for 1/1024 of a second (976 us). */ duration = 1; s$sleep (&duration, &code); #else #ifdef OPENSSL_SYS_VOS_IA32 /* sleep for 1/65536 of a second (15 us). */ duration = 1; s$sleep2 (&duration, &code); #endif /* OPENSSL_SYS_VOS_IA32 */ #endif /* OPENSSL_SYS_VOS_HPPA */ /* get wall clock time. */ clock_gettime (CLOCK_REALTIME, &ts); /* take 8 bits */ v = (unsigned char) (ts.tv_nsec % 256); RAND_add (&v, sizeof v, 1); v = 0; } return 1; } #elif defined __OpenBSD__ int RAND_poll(void) { u_int32_t rnd = 0, i; unsigned char buf[ENTROPY_NEEDED]; for (i = 0; i < sizeof(buf); i++) { if (i % 4 == 0) rnd = arc4random(); buf[i] = rnd; rnd >>= 8; } RAND_add(buf, sizeof(buf), ENTROPY_NEEDED); memset(buf, 0, sizeof(buf)); return 1; } #else /* !defined(__OpenBSD__) */ int RAND_poll(void) { unsigned long l; pid_t curr_pid = getpid(); #if defined(DEVRANDOM) || defined(DEVRANDOM_EGD) unsigned char tmpbuf[ENTROPY_NEEDED]; int n = 0; #endif #ifdef DEVRANDOM static const char *randomfiles[] = { DEVRANDOM }; struct stat randomstats[sizeof(randomfiles)/sizeof(randomfiles[0])]; int fd; unsigned int i; #endif #ifdef DEVRANDOM_EGD static const char *egdsockets[] = { DEVRANDOM_EGD, NULL }; const char **egdsocket = NULL; #endif #ifdef DEVRANDOM memset(randomstats,0,sizeof(randomstats)); /* Use a random entropy pool device. Linux, FreeBSD and OpenBSD * have this. Use /dev/urandom if you can as /dev/random may block * if it runs out of random entries. */ for (i = 0; (i < sizeof(randomfiles)/sizeof(randomfiles[0])) && (n < ENTROPY_NEEDED); i++) { if ((fd = open(randomfiles[i], O_RDONLY #ifdef O_NONBLOCK |O_NONBLOCK #endif #ifdef O_BINARY |O_BINARY #endif #ifdef O_NOCTTY /* If it happens to be a TTY (god forbid), do not make it our controlling tty */ |O_NOCTTY #endif )) >= 0) { int usec = 10*1000; /* spend 10ms on each file */ int r; unsigned int j; struct stat *st=&randomstats[i]; /* Avoid using same input... Used to be O_NOFOLLOW * above, but it's not universally appropriate... */ if (fstat(fd,st) != 0) { close(fd); continue; } for (j=0;j<i;j++) { if (randomstats[j].st_ino==st->st_ino && randomstats[j].st_dev==st->st_dev) break; } if (j<i) { close(fd); continue; } do { int try_read = 0; #if defined(OPENSSL_SYS_BEOS_R5) /* select() is broken in BeOS R5, so we simply * try to read something and snooze if we couldn't */ try_read = 1; #elif defined(OPENSSL_SYS_LINUX) /* use poll() */ struct pollfd pset; pset.fd = fd; pset.events = POLLIN; pset.revents = 0; if (poll(&pset, 1, usec / 1000) < 0) usec = 0; else try_read = (pset.revents & POLLIN) != 0; #else /* use select() */ fd_set fset; struct timeval t; t.tv_sec = 0; t.tv_usec = usec; if (FD_SETSIZE > 0 && (unsigned)fd >= FD_SETSIZE) { /* can't use select, so just try to read once anyway */ try_read = 1; } else { FD_ZERO(&fset); FD_SET(fd, &fset); if (select(fd+1,&fset,NULL,NULL,&t) >= 0) { usec = t.tv_usec; if (FD_ISSET(fd, &fset)) try_read = 1; } else usec = 0; } #endif if (try_read) { r = read(fd,(unsigned char *)tmpbuf+n, ENTROPY_NEEDED-n); if (r > 0) n += r; #if defined(OPENSSL_SYS_BEOS_R5) if (r == 0) snooze(t.tv_usec); #endif } else r = -1; /* Some Unixen will update t in select(), some won't. For those who won't, or if we didn't use select() in the first place, give up here, otherwise, we will do this once again for the remaining time. */ if (usec == 10*1000) usec = 0; } while ((r > 0 || (errno == EINTR || errno == EAGAIN)) && usec != 0 && n < ENTROPY_NEEDED); close(fd); } } #endif /* defined(DEVRANDOM) */ #ifdef DEVRANDOM_EGD /* Use an EGD socket to read entropy from an EGD or PRNGD entropy * collecting daemon. */ for (egdsocket = egdsockets; *egdsocket && n < ENTROPY_NEEDED; egdsocket++) { int r; r = RAND_query_egd_bytes(*egdsocket, (unsigned char *)tmpbuf+n, ENTROPY_NEEDED-n); if (r > 0) n += r; } #endif /* defined(DEVRANDOM_EGD) */ #if defined(DEVRANDOM) || defined(DEVRANDOM_EGD) if (n > 0) { RAND_add(tmpbuf,sizeof tmpbuf,(double)n); OPENSSL_cleanse(tmpbuf,n); } #endif /* put in some default random data, we need more than just this */ l=curr_pid; RAND_add(&l,sizeof(l),0.0); l=getuid(); RAND_add(&l,sizeof(l),0.0); l=time(NULL); RAND_add(&l,sizeof(l),0.0); #if defined(OPENSSL_SYS_BEOS) { system_info sysInfo; get_system_info(&sysInfo); RAND_add(&sysInfo,sizeof(sysInfo),0); } #endif #if defined(DEVRANDOM) || defined(DEVRANDOM_EGD) return 1; #else return 0; #endif } #endif /* defined(__OpenBSD__) */ #endif /* !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_NETWARE)) */ #if defined(OPENSSL_SYS_VXWORKS) int RAND_poll(void) { return 0; } #endif
gpl-3.0
imWildCat/shadowsocks-android
src/main/jni/badvpn/client/FrameDecider.c
368
28716
/** * @file FrameDecider.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 <string.h> #include <stddef.h> #include <misc/debug.h> #include <misc/offset.h> #include <misc/balloc.h> #include <misc/ethernet_proto.h> #include <misc/ipv4_proto.h> #include <misc/igmp_proto.h> #include <misc/byteorder.h> #include <misc/compare.h> #include <misc/print_macros.h> #include <client/FrameDecider.h> #include <generated/blog_channel_FrameDecider.h> #define DECIDE_STATE_NONE 1 #define DECIDE_STATE_UNICAST 2 #define DECIDE_STATE_FLOOD 3 #define DECIDE_STATE_MULTICAST 4 #define PeerLog(_o, ...) BLog_LogViaFunc((_o)->logfunc, (_o)->user, BLOG_CURRENT_CHANNEL, __VA_ARGS__) static int compare_macs (const uint8_t *mac1, const uint8_t *mac2) { int c = memcmp(mac1, mac2, 6); return B_COMPARE(c, 0); } #include "FrameDecider_macs_tree.h" #include <structure/SAvl_impl.h> #include "FrameDecider_groups_tree.h" #include <structure/SAvl_impl.h> #include "FrameDecider_multicast_tree.h" #include <structure/SAvl_impl.h> static void add_mac_to_peer (FrameDeciderPeer *o, uint8_t *mac) { FrameDecider *d = o->d; // locate entry in tree struct _FrameDecider_mac_entry *e_entry = FDMacsTree_LookupExact(&d->macs_tree, 0, mac); if (e_entry) { if (e_entry->peer == o) { // this is our MAC; only move it to the end of the used list LinkedList1_Remove(&o->mac_entries_used, &e_entry->list_node); LinkedList1_Append(&o->mac_entries_used, &e_entry->list_node); return; } // some other peer has that MAC; disassociate it FDMacsTree_Remove(&d->macs_tree, 0, e_entry); LinkedList1_Remove(&e_entry->peer->mac_entries_used, &e_entry->list_node); LinkedList1_Append(&e_entry->peer->mac_entries_free, &e_entry->list_node); } // aquire MAC address entry, if there are no free ones reuse the oldest used one LinkedList1Node *list_node; struct _FrameDecider_mac_entry *entry; if (list_node = LinkedList1_GetFirst(&o->mac_entries_free)) { entry = UPPER_OBJECT(list_node, struct _FrameDecider_mac_entry, list_node); ASSERT(entry->peer == o) // remove from free LinkedList1_Remove(&o->mac_entries_free, &entry->list_node); } else { list_node = LinkedList1_GetFirst(&o->mac_entries_used); ASSERT(list_node) entry = UPPER_OBJECT(list_node, struct _FrameDecider_mac_entry, list_node); ASSERT(entry->peer == o) // remove from used FDMacsTree_Remove(&d->macs_tree, 0, entry); LinkedList1_Remove(&o->mac_entries_used, &entry->list_node); } PeerLog(o, BLOG_INFO, "adding MAC %02"PRIx8":%02"PRIx8":%02"PRIx8":%02"PRIx8":%02"PRIx8":%02"PRIx8"", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); // set MAC in entry memcpy(entry->mac, mac, sizeof(entry->mac)); // add to used LinkedList1_Append(&o->mac_entries_used, &entry->list_node); int res = FDMacsTree_Insert(&d->macs_tree, 0, entry, NULL); ASSERT_EXECUTE(res) } static uint32_t compute_sig_for_group (uint32_t group) { return hton32(ntoh32(group)&0x7FFFFF); } static uint32_t compute_sig_for_mac (uint8_t *mac) { uint32_t sig; memcpy(&sig, mac + 2, 4); sig = hton32(ntoh32(sig)&0x7FFFFF); return sig; } static void add_to_multicast (FrameDecider *d, struct _FrameDecider_group_entry *group_entry) { // compute sig uint32_t sig = compute_sig_for_group(group_entry->group); struct _FrameDecider_group_entry *master = FDMulticastTree_LookupExact(&d->multicast_tree, 0, sig); if (master) { // use existing master ASSERT(master->is_master) // set not master group_entry->is_master = 0; // insert to list LinkedList3Node_InitAfter(&group_entry->sig_list_node, &master->sig_list_node); } else { // make this entry master // set master group_entry->is_master = 1; // set sig group_entry->master.sig = sig; // insert to multicast tree int res = FDMulticastTree_Insert(&d->multicast_tree, 0, group_entry, NULL); ASSERT_EXECUTE(res) // init list node LinkedList3Node_InitLonely(&group_entry->sig_list_node); } } static void remove_from_multicast (FrameDecider *d, struct _FrameDecider_group_entry *group_entry) { // compute sig uint32_t sig = compute_sig_for_group(group_entry->group); if (group_entry->is_master) { // remove master from multicast tree FDMulticastTree_Remove(&d->multicast_tree, 0, group_entry); if (!LinkedList3Node_IsLonely(&group_entry->sig_list_node)) { // at least one more group entry for this sig; make another entry the master // get an entry LinkedList3Node *list_node = LinkedList3Node_NextOrPrev(&group_entry->sig_list_node); struct _FrameDecider_group_entry *newmaster = UPPER_OBJECT(list_node, struct _FrameDecider_group_entry, sig_list_node); ASSERT(!newmaster->is_master) // set master newmaster->is_master = 1; // set sig newmaster->master.sig = sig; // insert to multicast tree int res = FDMulticastTree_Insert(&d->multicast_tree, 0, newmaster, NULL); ASSERT_EXECUTE(res) } } // free linked list node LinkedList3Node_Free(&group_entry->sig_list_node); } static void add_group_to_peer (FrameDeciderPeer *o, uint32_t group) { FrameDecider *d = o->d; struct _FrameDecider_group_entry *group_entry = FDGroupsTree_LookupExact(&o->groups_tree, 0, group); if (group_entry) { // move to end of used list LinkedList1_Remove(&o->group_entries_used, &group_entry->list_node); LinkedList1_Append(&o->group_entries_used, &group_entry->list_node); } else { PeerLog(o, BLOG_INFO, "joined group %"PRIu8".%"PRIu8".%"PRIu8".%"PRIu8"", ((uint8_t *)&group)[0], ((uint8_t *)&group)[1], ((uint8_t *)&group)[2], ((uint8_t *)&group)[3] ); // aquire group entry, if there are no free ones reuse the earliest used one LinkedList1Node *node; if (node = LinkedList1_GetFirst(&o->group_entries_free)) { group_entry = UPPER_OBJECT(node, struct _FrameDecider_group_entry, list_node); // remove from free list LinkedList1_Remove(&o->group_entries_free, &group_entry->list_node); } else { node = LinkedList1_GetFirst(&o->group_entries_used); ASSERT(node) group_entry = UPPER_OBJECT(node, struct _FrameDecider_group_entry, list_node); // remove from multicast remove_from_multicast(d, group_entry); // remove from peer's groups tree FDGroupsTree_Remove(&o->groups_tree, 0, group_entry); // remove from used list LinkedList1_Remove(&o->group_entries_used, &group_entry->list_node); } // add entry to used list LinkedList1_Append(&o->group_entries_used, &group_entry->list_node); // set group address group_entry->group = group; // insert to peer's groups tree int res = FDGroupsTree_Insert(&o->groups_tree, 0, group_entry, NULL); ASSERT_EXECUTE(res) // add to multicast add_to_multicast(d, group_entry); } // set timer group_entry->timer_endtime = btime_gettime() + d->igmp_group_membership_interval; BReactor_SetTimerAbsolute(d->reactor, &group_entry->timer, group_entry->timer_endtime); } static void remove_group_entry (struct _FrameDecider_group_entry *group_entry) { FrameDeciderPeer *peer = group_entry->peer; FrameDecider *d = peer->d; uint32_t group = group_entry->group; PeerLog(peer, BLOG_INFO, "left group %"PRIu8".%"PRIu8".%"PRIu8".%"PRIu8"", ((uint8_t *)&group)[0], ((uint8_t *)&group)[1], ((uint8_t *)&group)[2], ((uint8_t *)&group)[3] ); // remove from multicast remove_from_multicast(d, group_entry); // remove from peer's groups tree FDGroupsTree_Remove(&peer->groups_tree, 0, group_entry); // remove from used list LinkedList1_Remove(&peer->group_entries_used, &group_entry->list_node); // add to free list LinkedList1_Append(&peer->group_entries_free, &group_entry->list_node); // stop timer BReactor_RemoveTimer(d->reactor, &group_entry->timer); } static void lower_group_timers_to_lmqt (FrameDecider *d, uint32_t group) { // have to lower all the group timers of this group down to LMQT // compute sig uint32_t sig = compute_sig_for_group(group); // look up the sig in multicast tree struct _FrameDecider_group_entry *master = FDMulticastTree_LookupExact(&d->multicast_tree, 0, sig); if (!master) { return; } ASSERT(master->is_master) // iterate all group entries with this sig LinkedList3Iterator it; LinkedList3Iterator_Init(&it, LinkedList3Node_First(&master->sig_list_node), 1); LinkedList3Node *sig_list_node; while (sig_list_node = LinkedList3Iterator_Next(&it)) { struct _FrameDecider_group_entry *group_entry = UPPER_OBJECT(sig_list_node, struct _FrameDecider_group_entry, sig_list_node); // skip wrong groups if (group_entry->group != group) { continue; } // lower timer down to LMQT btime_t now = btime_gettime(); if (group_entry->timer_endtime > now + d->igmp_last_member_query_time) { group_entry->timer_endtime = now + d->igmp_last_member_query_time; BReactor_SetTimerAbsolute(d->reactor, &group_entry->timer, group_entry->timer_endtime); } } } static void group_entry_timer_handler (struct _FrameDecider_group_entry *group_entry) { DebugObject_Access(&group_entry->peer->d_obj); remove_group_entry(group_entry); } void FrameDecider_Init (FrameDecider *o, int max_peer_macs, int max_peer_groups, btime_t igmp_group_membership_interval, btime_t igmp_last_member_query_time, BReactor *reactor) { ASSERT(max_peer_macs > 0) ASSERT(max_peer_groups > 0) // init arguments o->max_peer_macs = max_peer_macs; o->max_peer_groups = max_peer_groups; o->igmp_group_membership_interval = igmp_group_membership_interval; o->igmp_last_member_query_time = igmp_last_member_query_time; o->reactor = reactor; // init peers list LinkedList1_Init(&o->peers_list); // init MAC tree FDMacsTree_Init(&o->macs_tree); // init multicast tree FDMulticastTree_Init(&o->multicast_tree); // init decide state o->decide_state = DECIDE_STATE_NONE; // set no current flood peer o->decide_flood_current = NULL; DebugObject_Init(&o->d_obj); } void FrameDecider_Free (FrameDecider *o) { ASSERT(FDMulticastTree_IsEmpty(&o->multicast_tree)) ASSERT(FDMacsTree_IsEmpty(&o->macs_tree)) ASSERT(LinkedList1_IsEmpty(&o->peers_list)) DebugObject_Free(&o->d_obj); } void FrameDecider_AnalyzeAndDecide (FrameDecider *o, const uint8_t *frame, int frame_len) { ASSERT(frame_len >= 0) DebugObject_Access(&o->d_obj); // reset decide state switch (o->decide_state) { case DECIDE_STATE_NONE: break; case DECIDE_STATE_UNICAST: break; case DECIDE_STATE_FLOOD: break; case DECIDE_STATE_MULTICAST: LinkedList3Iterator_Free(&o->decide_multicast_it); return; default: ASSERT(0); } o->decide_state = DECIDE_STATE_NONE; o->decide_flood_current = NULL; // analyze frame const uint8_t *pos = frame; int len = frame_len; if (len < sizeof(struct ethernet_header)) { return; } struct ethernet_header eh; memcpy(&eh, pos, sizeof(eh)); pos += sizeof(struct ethernet_header); len -= sizeof(struct ethernet_header); int is_igmp = 0; switch (ntoh16(eh.type)) { case ETHERTYPE_IPV4: { // check IPv4 header struct ipv4_header ipv4_header; if (!ipv4_check((uint8_t *)pos, len, &ipv4_header, (uint8_t **)&pos, &len)) { BLog(BLOG_INFO, "decide: wrong IP packet"); goto out; } // check if it's IGMP if (ntoh8(ipv4_header.protocol) != IPV4_PROTOCOL_IGMP) { goto out; } // remember that it's IGMP; we have to flood IGMP frames is_igmp = 1; // check IGMP header if (len < sizeof(struct igmp_base)) { BLog(BLOG_INFO, "decide: IGMP: short packet"); goto out; } struct igmp_base igmp_base; memcpy(&igmp_base, pos, sizeof(igmp_base)); pos += sizeof(struct igmp_base); len -= sizeof(struct igmp_base); switch (ntoh8(igmp_base.type)) { case IGMP_TYPE_MEMBERSHIP_QUERY: { if (len == sizeof(struct igmp_v2_extra) && ntoh8(igmp_base.max_resp_code) != 0) { // V2 query struct igmp_v2_extra query; memcpy(&query, pos, sizeof(query)); pos += sizeof(struct igmp_v2_extra); len -= sizeof(struct igmp_v2_extra); if (ntoh32(query.group) != 0) { // got a Group-Specific Query, lower group timers to LMQT lower_group_timers_to_lmqt(o, query.group); } } else if (len >= sizeof(struct igmp_v3_query_extra)) { // V3 query struct igmp_v3_query_extra query; memcpy(&query, pos, sizeof(query)); pos += sizeof(struct igmp_v3_query_extra); len -= sizeof(struct igmp_v3_query_extra); // iterate sources uint16_t num_sources = ntoh16(query.number_of_sources); int i; for (i = 0; i < num_sources; i++) { // check source if (len < sizeof(struct igmp_source)) { BLog(BLOG_NOTICE, "decide: IGMP: short source"); goto out; } pos += sizeof(struct igmp_source); len -= sizeof(struct igmp_source); } if (ntoh32(query.group) != 0 && num_sources == 0) { // got a Group-Specific Query, lower group timers to LMQT lower_group_timers_to_lmqt(o, query.group); } } } break; } } break; } out:; const uint8_t broadcast_mac[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; const uint8_t multicast_mac_header[] = {0x01, 0x00, 0x5e}; // if it's broadcast or IGMP, flood it if (is_igmp || !memcmp(eh.dest, broadcast_mac, sizeof(broadcast_mac))) { o->decide_state = DECIDE_STATE_FLOOD; o->decide_flood_current = LinkedList1_GetFirst(&o->peers_list); return; } // if it's multicast, forward to all peers with the given sig if (!memcmp(eh.dest, multicast_mac_header, sizeof(multicast_mac_header))) { // extract group's sig from destination MAC uint32_t sig = compute_sig_for_mac(eh.dest); // look up the sig in multicast tree struct _FrameDecider_group_entry *master = FDMulticastTree_LookupExact(&o->multicast_tree, 0, sig); if (master) { ASSERT(master->is_master) o->decide_state = DECIDE_STATE_MULTICAST; LinkedList3Iterator_Init(&o->decide_multicast_it, LinkedList3Node_First(&master->sig_list_node), 1); } return; } // look for MAC entry struct _FrameDecider_mac_entry *entry = FDMacsTree_LookupExact(&o->macs_tree, 0, eh.dest); if (entry) { o->decide_state = DECIDE_STATE_UNICAST; o->decide_unicast_peer = entry->peer; return; } // unknown destination MAC, flood o->decide_state = DECIDE_STATE_FLOOD; o->decide_flood_current = LinkedList1_GetFirst(&o->peers_list); return; } FrameDeciderPeer * FrameDecider_NextDestination (FrameDecider *o) { DebugObject_Access(&o->d_obj); switch (o->decide_state) { case DECIDE_STATE_NONE: { return NULL; } break; case DECIDE_STATE_UNICAST: { o->decide_state = DECIDE_STATE_NONE; return o->decide_unicast_peer; } break; case DECIDE_STATE_FLOOD: { if (!o->decide_flood_current) { o->decide_state = DECIDE_STATE_NONE; return NULL; } LinkedList1Node *list_node = o->decide_flood_current; o->decide_flood_current = LinkedList1Node_Next(o->decide_flood_current); FrameDeciderPeer *peer = UPPER_OBJECT(list_node, FrameDeciderPeer, list_node); return peer; } break; case DECIDE_STATE_MULTICAST: { LinkedList3Node *list_node = LinkedList3Iterator_Next(&o->decide_multicast_it); if (!list_node) { o->decide_state = DECIDE_STATE_NONE; return NULL; } struct _FrameDecider_group_entry *group_entry = UPPER_OBJECT(list_node, struct _FrameDecider_group_entry, sig_list_node); return group_entry->peer; } break; default: ASSERT(0); return NULL; } } int FrameDeciderPeer_Init (FrameDeciderPeer *o, FrameDecider *d, void *user, BLog_logfunc logfunc) { // init arguments o->d = d; o->user = user; o->logfunc = logfunc; // allocate MAC entries if (!(o->mac_entries = (struct _FrameDecider_mac_entry *)BAllocArray(d->max_peer_macs, sizeof(struct _FrameDecider_mac_entry)))) { PeerLog(o, BLOG_ERROR, "failed to allocate MAC entries"); goto fail0; } // allocate group entries if (!(o->group_entries = (struct _FrameDecider_group_entry *)BAllocArray(d->max_peer_groups, sizeof(struct _FrameDecider_group_entry)))) { PeerLog(o, BLOG_ERROR, "failed to allocate group entries"); goto fail1; } // insert to peers list LinkedList1_Append(&d->peers_list, &o->list_node); // init MAC entry lists LinkedList1_Init(&o->mac_entries_free); LinkedList1_Init(&o->mac_entries_used); // initialize MAC entries for (int i = 0; i < d->max_peer_macs; i++) { struct _FrameDecider_mac_entry *entry = &o->mac_entries[i]; // set peer entry->peer = o; // insert to free list LinkedList1_Append(&o->mac_entries_free, &entry->list_node); } // init group entry lists LinkedList1_Init(&o->group_entries_free); LinkedList1_Init(&o->group_entries_used); // initialize group entries for (int i = 0; i < d->max_peer_groups; i++) { struct _FrameDecider_group_entry *entry = &o->group_entries[i]; // set peer entry->peer = o; // insert to free list LinkedList1_Append(&o->group_entries_free, &entry->list_node); // init timer BTimer_Init(&entry->timer, 0, (BTimer_handler)group_entry_timer_handler, entry); } // initialize groups tree FDGroupsTree_Init(&o->groups_tree); DebugObject_Init(&o->d_obj); return 1; fail1: BFree(o->mac_entries); fail0: return 0; } void FrameDeciderPeer_Free (FrameDeciderPeer *o) { DebugObject_Free(&o->d_obj); FrameDecider *d = o->d; // remove decide unicast reference if (d->decide_state == DECIDE_STATE_UNICAST && d->decide_unicast_peer == o) { d->decide_state = DECIDE_STATE_NONE; } LinkedList1Node *node; // free group entries for (node = LinkedList1_GetFirst(&o->group_entries_used); node; node = LinkedList1Node_Next(node)) { struct _FrameDecider_group_entry *entry = UPPER_OBJECT(node, struct _FrameDecider_group_entry, list_node); // remove from multicast remove_from_multicast(d, entry); // stop timer BReactor_RemoveTimer(d->reactor, &entry->timer); } // remove used MAC entries from tree for (node = LinkedList1_GetFirst(&o->mac_entries_used); node; node = LinkedList1Node_Next(node)) { struct _FrameDecider_mac_entry *entry = UPPER_OBJECT(node, struct _FrameDecider_mac_entry, list_node); // remove from tree FDMacsTree_Remove(&d->macs_tree, 0, entry); } // remove from peers list if (d->decide_flood_current == &o->list_node) { d->decide_flood_current = LinkedList1Node_Next(d->decide_flood_current); } LinkedList1_Remove(&d->peers_list, &o->list_node); // free group entries BFree(o->group_entries); // free MAC entries BFree(o->mac_entries); } void FrameDeciderPeer_Analyze (FrameDeciderPeer *o, const uint8_t *frame, int frame_len) { ASSERT(frame_len >= 0) DebugObject_Access(&o->d_obj); const uint8_t *pos = frame; int len = frame_len; if (len < sizeof(struct ethernet_header)) { goto out; } struct ethernet_header eh; memcpy(&eh, pos, sizeof(eh)); pos += sizeof(struct ethernet_header); len -= sizeof(struct ethernet_header); // register source MAC address with this peer add_mac_to_peer(o, eh.source); switch (ntoh16(eh.type)) { case ETHERTYPE_IPV4: { // check IPv4 header struct ipv4_header ipv4_header; if (!ipv4_check((uint8_t *)pos, len, &ipv4_header, (uint8_t **)&pos, &len)) { PeerLog(o, BLOG_INFO, "analyze: wrong IP packet"); goto out; } // check if it's IGMP if (ntoh8(ipv4_header.protocol) != IPV4_PROTOCOL_IGMP) { goto out; } // check IGMP header if (len < sizeof(struct igmp_base)) { PeerLog(o, BLOG_INFO, "analyze: IGMP: short packet"); goto out; } struct igmp_base igmp_base; memcpy(&igmp_base, pos, sizeof(igmp_base)); pos += sizeof(struct igmp_base); len -= sizeof(struct igmp_base); switch (ntoh8(igmp_base.type)) { case IGMP_TYPE_V2_MEMBERSHIP_REPORT: { // check extra if (len < sizeof(struct igmp_v2_extra)) { PeerLog(o, BLOG_INFO, "analyze: IGMP: short v2 report"); goto out; } struct igmp_v2_extra report; memcpy(&report, pos, sizeof(report)); pos += sizeof(struct igmp_v2_extra); len -= sizeof(struct igmp_v2_extra); // add to group add_group_to_peer(o, report.group); } break; case IGMP_TYPE_V3_MEMBERSHIP_REPORT: { // check extra if (len < sizeof(struct igmp_v3_report_extra)) { PeerLog(o, BLOG_INFO, "analyze: IGMP: short v3 report"); goto out; } struct igmp_v3_report_extra report; memcpy(&report, pos, sizeof(report)); pos += sizeof(struct igmp_v3_report_extra); len -= sizeof(struct igmp_v3_report_extra); // iterate records uint16_t num_records = ntoh16(report.number_of_group_records); for (int i = 0; i < num_records; i++) { // check record if (len < sizeof(struct igmp_v3_report_record)) { PeerLog(o, BLOG_INFO, "analyze: IGMP: short record header"); goto out; } struct igmp_v3_report_record record; memcpy(&record, pos, sizeof(record)); pos += sizeof(struct igmp_v3_report_record); len -= sizeof(struct igmp_v3_report_record); // iterate sources uint16_t num_sources = ntoh16(record.number_of_sources); int j; for (j = 0; j < num_sources; j++) { // check source if (len < sizeof(struct igmp_source)) { PeerLog(o, BLOG_INFO, "analyze: IGMP: short source"); goto out; } pos += sizeof(struct igmp_source); len -= sizeof(struct igmp_source); } // check aux data uint16_t aux_len = ntoh16(record.aux_data_len); if (len < aux_len) { PeerLog(o, BLOG_INFO, "analyze: IGMP: short record aux data"); goto out; } pos += aux_len; len -= aux_len; switch (record.type) { case IGMP_RECORD_TYPE_MODE_IS_INCLUDE: case IGMP_RECORD_TYPE_CHANGE_TO_INCLUDE_MODE: if (num_sources != 0) { add_group_to_peer(o, record.group); } break; case IGMP_RECORD_TYPE_MODE_IS_EXCLUDE: case IGMP_RECORD_TYPE_CHANGE_TO_EXCLUDE_MODE: add_group_to_peer(o, record.group); break; } } } break; } } break; } out:; }
gpl-3.0
opapa/shadowsocks-android
src/main/jni/badvpn/examples/indexedlist_test.c
369
2926
/** * @file indexedlist_test.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/debug.h> #include <misc/offset.h> #include <structure/IndexedList.h> IndexedList il; struct elem { int value; IndexedListNode node; }; static void elem_insert (struct elem *e, int value, uint64_t index) { e->value = value; IndexedList_InsertAt(&il, &e->node, index); } static void remove_at (uint64_t index) { IndexedListNode *n = IndexedList_GetAt(&il, index); struct elem *e = UPPER_OBJECT(n, struct elem, node); IndexedList_Remove(&il, &e->node); } static void print_list (void) { for (uint64_t i = 0; i < IndexedList_Count(&il); i++) { IndexedListNode *n = IndexedList_GetAt(&il, i); struct elem *e = UPPER_OBJECT(n, struct elem, node); printf("%d ", e->value); } printf("\n"); } int main (int argc, char *argv[]) { IndexedList_Init(&il); struct elem arr[100]; print_list(); elem_insert(&arr[0], 1, 0); print_list(); elem_insert(&arr[1], 2, 0); print_list(); elem_insert(&arr[2], 3, 0); print_list(); elem_insert(&arr[3], 4, 0); print_list(); elem_insert(&arr[4], 5, 0); print_list(); elem_insert(&arr[5], 6, 0); print_list(); elem_insert(&arr[6], 7, 1); print_list(); remove_at(0); print_list(); remove_at(5); print_list(); return 0; }
gpl-3.0
geminy/aidear
oss/linux/linux-4.7/drivers/media/usb/uvc/uvc_entity.c
375
3238
/* * uvc_entity.c -- USB Video Class driver * * Copyright (C) 2005-2011 * Laurent Pinchart (laurent.pinchart@ideasonboard.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 <linux/kernel.h> #include <linux/list.h> #include <linux/videodev2.h> #include <media/v4l2-common.h> #include "uvcvideo.h" static int uvc_mc_create_links(struct uvc_video_chain *chain, struct uvc_entity *entity) { const u32 flags = MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE; struct media_entity *sink; unsigned int i; int ret; sink = (UVC_ENTITY_TYPE(entity) == UVC_TT_STREAMING) ? (entity->vdev ? &entity->vdev->entity : NULL) : &entity->subdev.entity; if (sink == NULL) return 0; for (i = 0; i < entity->num_pads; ++i) { struct media_entity *source; struct uvc_entity *remote; u8 remote_pad; if (!(entity->pads[i].flags & MEDIA_PAD_FL_SINK)) continue; remote = uvc_entity_by_id(chain->dev, entity->baSourceID[i]); if (remote == NULL) return -EINVAL; source = (UVC_ENTITY_TYPE(remote) == UVC_TT_STREAMING) ? (remote->vdev ? &remote->vdev->entity : NULL) : &remote->subdev.entity; if (source == NULL) continue; remote_pad = remote->num_pads - 1; ret = media_create_pad_link(source, remote_pad, sink, i, flags); if (ret < 0) return ret; } return 0; } static struct v4l2_subdev_ops uvc_subdev_ops = { }; void uvc_mc_cleanup_entity(struct uvc_entity *entity) { if (UVC_ENTITY_TYPE(entity) != UVC_TT_STREAMING) media_entity_cleanup(&entity->subdev.entity); else if (entity->vdev != NULL) media_entity_cleanup(&entity->vdev->entity); } static int uvc_mc_init_entity(struct uvc_video_chain *chain, struct uvc_entity *entity) { int ret; if (UVC_ENTITY_TYPE(entity) != UVC_TT_STREAMING) { v4l2_subdev_init(&entity->subdev, &uvc_subdev_ops); strlcpy(entity->subdev.name, entity->name, sizeof(entity->subdev.name)); ret = media_entity_pads_init(&entity->subdev.entity, entity->num_pads, entity->pads); if (ret < 0) return ret; ret = v4l2_device_register_subdev(&chain->dev->vdev, &entity->subdev); } else if (entity->vdev != NULL) { ret = media_entity_pads_init(&entity->vdev->entity, entity->num_pads, entity->pads); if (entity->flags & UVC_ENTITY_FLAG_DEFAULT) entity->vdev->entity.flags |= MEDIA_ENT_FL_DEFAULT; } else ret = 0; return ret; } int uvc_mc_register_entities(struct uvc_video_chain *chain) { struct uvc_entity *entity; int ret; list_for_each_entry(entity, &chain->entities, chain) { ret = uvc_mc_init_entity(chain, entity); if (ret < 0) { uvc_printk(KERN_INFO, "Failed to initialize entity for " "entity %u\n", entity->id); return ret; } } list_for_each_entry(entity, &chain->entities, chain) { ret = uvc_mc_create_links(chain, entity); if (ret < 0) { uvc_printk(KERN_INFO, "Failed to create links for " "entity %u\n", entity->id); return ret; } } return 0; }
gpl-3.0
shlyakpavel/s720-KK-kernel
kernel/drivers/net/fddi/skfp/skfddi.c
5244
64922
/* * File Name: * skfddi.c * * Copyright Information: * Copyright SysKonnect 1998,1999. * * 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. * * The information in this file is provided "AS IS" without warranty. * * Abstract: * A Linux device driver supporting the SysKonnect FDDI PCI controller * familie. * * Maintainers: * CG Christoph Goos (cgoos@syskonnect.de) * * Contributors: * DM David S. Miller * * Address all question to: * linux@syskonnect.de * * The technical manual for the adapters is available from SysKonnect's * web pages: www.syskonnect.com * Goto "Support" and search Knowledge Base for "manual". * * Driver Architecture: * The driver architecture is based on the DEC FDDI driver by * Lawrence V. Stefani and several ethernet drivers. * I also used an existing Windows NT miniport driver. * All hardware dependent functions are handled by the SysKonnect * Hardware Module. * The only headerfiles that are directly related to this source * are skfddi.c, h/types.h, h/osdef1st.h, h/targetos.h. * The others belong to the SysKonnect FDDI Hardware Module and * should better not be changed. * * Modification History: * Date Name Description * 02-Mar-98 CG Created. * * 10-Mar-99 CG Support for 2.2.x added. * 25-Mar-99 CG Corrected IRQ routing for SMP (APIC) * 26-Oct-99 CG Fixed compilation error on 2.2.13 * 12-Nov-99 CG Source code release * 22-Nov-99 CG Included in kernel source. * 07-May-00 DM 64 bit fixes, new dma interface * 31-Jul-03 DB Audit copy_*_user in skfp_ioctl * Daniele Bellucci <bellucda@tiscali.it> * 03-Dec-03 SH Convert to PCI device model * * Compilation options (-Dxxx): * DRIVERDEBUG print lots of messages to log file * DUMPPACKETS print received/transmitted packets to logfile * * Tested cpu architectures: * - i386 * - sparc64 */ /* Version information string - should be updated prior to */ /* each new release!!! */ #define VERSION "2.07" static const char * const boot_msg = "SysKonnect FDDI PCI Adapter driver v" VERSION " for\n" " SK-55xx/SK-58xx adapters (SK-NET FDDI-FP/UP/LP)"; /* Include files */ #include <linux/capability.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/fddidevice.h> #include <linux/skbuff.h> #include <linux/bitops.h> #include <linux/gfp.h> #include <asm/byteorder.h> #include <asm/io.h> #include <asm/uaccess.h> #include "h/types.h" #undef ADDR // undo Linux definition #include "h/skfbi.h" #include "h/fddi.h" #include "h/smc.h" #include "h/smtstate.h" // Define module-wide (static) routines static int skfp_driver_init(struct net_device *dev); static int skfp_open(struct net_device *dev); static int skfp_close(struct net_device *dev); static irqreturn_t skfp_interrupt(int irq, void *dev_id); static struct net_device_stats *skfp_ctl_get_stats(struct net_device *dev); static void skfp_ctl_set_multicast_list(struct net_device *dev); static void skfp_ctl_set_multicast_list_wo_lock(struct net_device *dev); static int skfp_ctl_set_mac_address(struct net_device *dev, void *addr); static int skfp_ioctl(struct net_device *dev, struct ifreq *rq, int cmd); static netdev_tx_t skfp_send_pkt(struct sk_buff *skb, struct net_device *dev); static void send_queued_packets(struct s_smc *smc); static void CheckSourceAddress(unsigned char *frame, unsigned char *hw_addr); static void ResetAdapter(struct s_smc *smc); // Functions needed by the hardware module void *mac_drv_get_space(struct s_smc *smc, u_int size); void *mac_drv_get_desc_mem(struct s_smc *smc, u_int size); unsigned long mac_drv_virt2phys(struct s_smc *smc, void *virt); unsigned long dma_master(struct s_smc *smc, void *virt, int len, int flag); void dma_complete(struct s_smc *smc, volatile union s_fp_descr *descr, int flag); void mac_drv_tx_complete(struct s_smc *smc, volatile struct s_smt_fp_txd *txd); void llc_restart_tx(struct s_smc *smc); void mac_drv_rx_complete(struct s_smc *smc, volatile struct s_smt_fp_rxd *rxd, int frag_count, int len); void mac_drv_requeue_rxd(struct s_smc *smc, volatile struct s_smt_fp_rxd *rxd, int frag_count); void mac_drv_fill_rxd(struct s_smc *smc); void mac_drv_clear_rxd(struct s_smc *smc, volatile struct s_smt_fp_rxd *rxd, int frag_count); int mac_drv_rx_init(struct s_smc *smc, int len, int fc, char *look_ahead, int la_len); void dump_data(unsigned char *Data, int length); // External functions from the hardware module extern u_int mac_drv_check_space(void); extern int mac_drv_init(struct s_smc *smc); extern void hwm_tx_frag(struct s_smc *smc, char far * virt, u_long phys, int len, int frame_status); extern int hwm_tx_init(struct s_smc *smc, u_char fc, int frag_count, int frame_len, int frame_status); extern void fddi_isr(struct s_smc *smc); extern void hwm_rx_frag(struct s_smc *smc, char far * virt, u_long phys, int len, int frame_status); extern void mac_drv_rx_mode(struct s_smc *smc, int mode); extern void mac_drv_clear_rx_queue(struct s_smc *smc); extern void enable_tx_irq(struct s_smc *smc, u_short queue); static DEFINE_PCI_DEVICE_TABLE(skfddi_pci_tbl) = { { PCI_VENDOR_ID_SK, PCI_DEVICE_ID_SK_FP, PCI_ANY_ID, PCI_ANY_ID, }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(pci, skfddi_pci_tbl); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Mirko Lindner <mlindner@syskonnect.de>"); // Define module-wide (static) variables static int num_boards; /* total number of adapters configured */ static const struct net_device_ops skfp_netdev_ops = { .ndo_open = skfp_open, .ndo_stop = skfp_close, .ndo_start_xmit = skfp_send_pkt, .ndo_get_stats = skfp_ctl_get_stats, .ndo_change_mtu = fddi_change_mtu, .ndo_set_rx_mode = skfp_ctl_set_multicast_list, .ndo_set_mac_address = skfp_ctl_set_mac_address, .ndo_do_ioctl = skfp_ioctl, }; /* * ================= * = skfp_init_one = * ================= * * Overview: * Probes for supported FDDI PCI controllers * * Returns: * Condition code * * Arguments: * pdev - pointer to PCI device information * * Functional Description: * This is now called by PCI driver registration process * for each board found. * * Return Codes: * 0 - This device (fddi0, fddi1, etc) configured successfully * -ENODEV - No devices present, or no SysKonnect FDDI PCI device * present for this device name * * * Side Effects: * Device structures for FDDI adapters (fddi0, fddi1, etc) are * initialized and the board resources are read and stored in * the device structure. */ static int skfp_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *dev; struct s_smc *smc; /* board pointer */ void __iomem *mem; int err; pr_debug("entering skfp_init_one\n"); if (num_boards == 0) printk("%s\n", boot_msg); err = pci_enable_device(pdev); if (err) return err; err = pci_request_regions(pdev, "skfddi"); if (err) goto err_out1; pci_set_master(pdev); #ifdef MEM_MAPPED_IO if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) { printk(KERN_ERR "skfp: region is not an MMIO resource\n"); err = -EIO; goto err_out2; } mem = ioremap(pci_resource_start(pdev, 0), 0x4000); #else if (!(pci_resource_flags(pdev, 1) & IO_RESOURCE_IO)) { printk(KERN_ERR "skfp: region is not PIO resource\n"); err = -EIO; goto err_out2; } mem = ioport_map(pci_resource_start(pdev, 1), FP_IO_LEN); #endif if (!mem) { printk(KERN_ERR "skfp: Unable to map register, " "FDDI adapter will be disabled.\n"); err = -EIO; goto err_out2; } dev = alloc_fddidev(sizeof(struct s_smc)); if (!dev) { printk(KERN_ERR "skfp: Unable to allocate fddi device, " "FDDI adapter will be disabled.\n"); err = -ENOMEM; goto err_out3; } dev->irq = pdev->irq; dev->netdev_ops = &skfp_netdev_ops; SET_NETDEV_DEV(dev, &pdev->dev); /* Initialize board structure with bus-specific info */ smc = netdev_priv(dev); smc->os.dev = dev; smc->os.bus_type = SK_BUS_TYPE_PCI; smc->os.pdev = *pdev; smc->os.QueueSkb = MAX_TX_QUEUE_LEN; smc->os.MaxFrameSize = MAX_FRAME_SIZE; smc->os.dev = dev; smc->hw.slot = -1; smc->hw.iop = mem; smc->os.ResetRequested = FALSE; skb_queue_head_init(&smc->os.SendSkbQueue); dev->base_addr = (unsigned long)mem; err = skfp_driver_init(dev); if (err) goto err_out4; err = register_netdev(dev); if (err) goto err_out5; ++num_boards; pci_set_drvdata(pdev, dev); if ((pdev->subsystem_device & 0xff00) == 0x5500 || (pdev->subsystem_device & 0xff00) == 0x5800) printk("%s: SysKonnect FDDI PCI adapter" " found (SK-%04X)\n", dev->name, pdev->subsystem_device); else printk("%s: FDDI PCI adapter found\n", dev->name); return 0; err_out5: if (smc->os.SharedMemAddr) pci_free_consistent(pdev, smc->os.SharedMemSize, smc->os.SharedMemAddr, smc->os.SharedMemDMA); pci_free_consistent(pdev, MAX_FRAME_SIZE, smc->os.LocalRxBuffer, smc->os.LocalRxBufferDMA); err_out4: free_netdev(dev); err_out3: #ifdef MEM_MAPPED_IO iounmap(mem); #else ioport_unmap(mem); #endif err_out2: pci_release_regions(pdev); err_out1: pci_disable_device(pdev); return err; } /* * Called for each adapter board from pci_unregister_driver */ static void __devexit skfp_remove_one(struct pci_dev *pdev) { struct net_device *p = pci_get_drvdata(pdev); struct s_smc *lp = netdev_priv(p); unregister_netdev(p); if (lp->os.SharedMemAddr) { pci_free_consistent(&lp->os.pdev, lp->os.SharedMemSize, lp->os.SharedMemAddr, lp->os.SharedMemDMA); lp->os.SharedMemAddr = NULL; } if (lp->os.LocalRxBuffer) { pci_free_consistent(&lp->os.pdev, MAX_FRAME_SIZE, lp->os.LocalRxBuffer, lp->os.LocalRxBufferDMA); lp->os.LocalRxBuffer = NULL; } #ifdef MEM_MAPPED_IO iounmap(lp->hw.iop); #else ioport_unmap(lp->hw.iop); #endif pci_release_regions(pdev); free_netdev(p); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); } /* * ==================== * = skfp_driver_init = * ==================== * * Overview: * Initializes remaining adapter board structure information * and makes sure adapter is in a safe state prior to skfp_open(). * * Returns: * Condition code * * Arguments: * dev - pointer to device information * * Functional Description: * This function allocates additional resources such as the host memory * blocks needed by the adapter. * The adapter is also reset. The OS must call skfp_open() to open * the adapter and bring it on-line. * * Return Codes: * 0 - initialization succeeded * -1 - initialization failed */ static int skfp_driver_init(struct net_device *dev) { struct s_smc *smc = netdev_priv(dev); skfddi_priv *bp = &smc->os; int err = -EIO; pr_debug("entering skfp_driver_init\n"); // set the io address in private structures bp->base_addr = dev->base_addr; // Get the interrupt level from the PCI Configuration Table smc->hw.irq = dev->irq; spin_lock_init(&bp->DriverLock); // Allocate invalid frame bp->LocalRxBuffer = pci_alloc_consistent(&bp->pdev, MAX_FRAME_SIZE, &bp->LocalRxBufferDMA); if (!bp->LocalRxBuffer) { printk("could not allocate mem for "); printk("LocalRxBuffer: %d byte\n", MAX_FRAME_SIZE); goto fail; } // Determine the required size of the 'shared' memory area. bp->SharedMemSize = mac_drv_check_space(); pr_debug("Memory for HWM: %ld\n", bp->SharedMemSize); if (bp->SharedMemSize > 0) { bp->SharedMemSize += 16; // for descriptor alignment bp->SharedMemAddr = pci_alloc_consistent(&bp->pdev, bp->SharedMemSize, &bp->SharedMemDMA); if (!bp->SharedMemAddr) { printk("could not allocate mem for "); printk("hardware module: %ld byte\n", bp->SharedMemSize); goto fail; } bp->SharedMemHeap = 0; // Nothing used yet. } else { bp->SharedMemAddr = NULL; bp->SharedMemHeap = 0; } // SharedMemSize > 0 memset(bp->SharedMemAddr, 0, bp->SharedMemSize); card_stop(smc); // Reset adapter. pr_debug("mac_drv_init()..\n"); if (mac_drv_init(smc) != 0) { pr_debug("mac_drv_init() failed\n"); goto fail; } read_address(smc, NULL); pr_debug("HW-Addr: %pMF\n", smc->hw.fddi_canon_addr.a); memcpy(dev->dev_addr, smc->hw.fddi_canon_addr.a, 6); smt_reset_defaults(smc, 0); return 0; fail: if (bp->SharedMemAddr) { pci_free_consistent(&bp->pdev, bp->SharedMemSize, bp->SharedMemAddr, bp->SharedMemDMA); bp->SharedMemAddr = NULL; } if (bp->LocalRxBuffer) { pci_free_consistent(&bp->pdev, MAX_FRAME_SIZE, bp->LocalRxBuffer, bp->LocalRxBufferDMA); bp->LocalRxBuffer = NULL; } return err; } // skfp_driver_init /* * ============= * = skfp_open = * ============= * * Overview: * Opens the adapter * * Returns: * Condition code * * Arguments: * dev - pointer to device information * * Functional Description: * This function brings the adapter to an operational state. * * Return Codes: * 0 - Adapter was successfully opened * -EAGAIN - Could not register IRQ */ static int skfp_open(struct net_device *dev) { struct s_smc *smc = netdev_priv(dev); int err; pr_debug("entering skfp_open\n"); /* Register IRQ - support shared interrupts by passing device ptr */ err = request_irq(dev->irq, skfp_interrupt, IRQF_SHARED, dev->name, dev); if (err) return err; /* * Set current address to factory MAC address * * Note: We've already done this step in skfp_driver_init. * However, it's possible that a user has set a node * address override, then closed and reopened the * adapter. Unless we reset the device address field * now, we'll continue to use the existing modified * address. */ read_address(smc, NULL); memcpy(dev->dev_addr, smc->hw.fddi_canon_addr.a, 6); init_smt(smc, NULL); smt_online(smc, 1); STI_FBI(); /* Clear local multicast address tables */ mac_clear_multicast(smc); /* Disable promiscuous filter settings */ mac_drv_rx_mode(smc, RX_DISABLE_PROMISC); netif_start_queue(dev); return 0; } // skfp_open /* * ============== * = skfp_close = * ============== * * Overview: * Closes the device/module. * * Returns: * Condition code * * Arguments: * dev - pointer to device information * * Functional Description: * This routine closes the adapter and brings it to a safe state. * The interrupt service routine is deregistered with the OS. * The adapter can be opened again with another call to skfp_open(). * * Return Codes: * Always return 0. * * Assumptions: * No further requests for this adapter are made after this routine is * called. skfp_open() can be called to reset and reinitialize the * adapter. */ static int skfp_close(struct net_device *dev) { struct s_smc *smc = netdev_priv(dev); skfddi_priv *bp = &smc->os; CLI_FBI(); smt_reset_defaults(smc, 1); card_stop(smc); mac_drv_clear_tx_queue(smc); mac_drv_clear_rx_queue(smc); netif_stop_queue(dev); /* Deregister (free) IRQ */ free_irq(dev->irq, dev); skb_queue_purge(&bp->SendSkbQueue); bp->QueueSkb = MAX_TX_QUEUE_LEN; return 0; } // skfp_close /* * ================== * = skfp_interrupt = * ================== * * Overview: * Interrupt processing routine * * Returns: * None * * Arguments: * irq - interrupt vector * dev_id - pointer to device information * * Functional Description: * This routine calls the interrupt processing routine for this adapter. It * disables and reenables adapter interrupts, as appropriate. We can support * shared interrupts since the incoming dev_id pointer provides our device * structure context. All the real work is done in the hardware module. * * Return Codes: * None * * Assumptions: * The interrupt acknowledgement at the hardware level (eg. ACKing the PIC * on Intel-based systems) is done by the operating system outside this * routine. * * System interrupts are enabled through this call. * * Side Effects: * Interrupts are disabled, then reenabled at the adapter. */ static irqreturn_t skfp_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct s_smc *smc; /* private board structure pointer */ skfddi_priv *bp; smc = netdev_priv(dev); bp = &smc->os; // IRQs enabled or disabled ? if (inpd(ADDR(B0_IMSK)) == 0) { // IRQs are disabled: must be shared interrupt return IRQ_NONE; } // Note: At this point, IRQs are enabled. if ((inpd(ISR_A) & smc->hw.is_imask) == 0) { // IRQ? // Adapter did not issue an IRQ: must be shared interrupt return IRQ_NONE; } CLI_FBI(); // Disable IRQs from our adapter. spin_lock(&bp->DriverLock); // Call interrupt handler in hardware module (HWM). fddi_isr(smc); if (smc->os.ResetRequested) { ResetAdapter(smc); smc->os.ResetRequested = FALSE; } spin_unlock(&bp->DriverLock); STI_FBI(); // Enable IRQs from our adapter. return IRQ_HANDLED; } // skfp_interrupt /* * ====================== * = skfp_ctl_get_stats = * ====================== * * Overview: * Get statistics for FDDI adapter * * Returns: * Pointer to FDDI statistics structure * * Arguments: * dev - pointer to device information * * Functional Description: * Gets current MIB objects from adapter, then * returns FDDI statistics structure as defined * in if_fddi.h. * * Note: Since the FDDI statistics structure is * still new and the device structure doesn't * have an FDDI-specific get statistics handler, * we'll return the FDDI statistics structure as * a pointer to an Ethernet statistics structure. * That way, at least the first part of the statistics * structure can be decoded properly. * We'll have to pay attention to this routine as the * device structure becomes more mature and LAN media * independent. * */ static struct net_device_stats *skfp_ctl_get_stats(struct net_device *dev) { struct s_smc *bp = netdev_priv(dev); /* Fill the bp->stats structure with driver-maintained counters */ bp->os.MacStat.port_bs_flag[0] = 0x1234; bp->os.MacStat.port_bs_flag[1] = 0x5678; // goos: need to fill out fddi statistic #if 0 /* Get FDDI SMT MIB objects */ /* Fill the bp->stats structure with the SMT MIB object values */ memcpy(bp->stats.smt_station_id, &bp->cmd_rsp_virt->smt_mib_get.smt_station_id, sizeof(bp->cmd_rsp_virt->smt_mib_get.smt_station_id)); bp->stats.smt_op_version_id = bp->cmd_rsp_virt->smt_mib_get.smt_op_version_id; bp->stats.smt_hi_version_id = bp->cmd_rsp_virt->smt_mib_get.smt_hi_version_id; bp->stats.smt_lo_version_id = bp->cmd_rsp_virt->smt_mib_get.smt_lo_version_id; memcpy(bp->stats.smt_user_data, &bp->cmd_rsp_virt->smt_mib_get.smt_user_data, sizeof(bp->cmd_rsp_virt->smt_mib_get.smt_user_data)); bp->stats.smt_mib_version_id = bp->cmd_rsp_virt->smt_mib_get.smt_mib_version_id; bp->stats.smt_mac_cts = bp->cmd_rsp_virt->smt_mib_get.smt_mac_ct; bp->stats.smt_non_master_cts = bp->cmd_rsp_virt->smt_mib_get.smt_non_master_ct; bp->stats.smt_master_cts = bp->cmd_rsp_virt->smt_mib_get.smt_master_ct; bp->stats.smt_available_paths = bp->cmd_rsp_virt->smt_mib_get.smt_available_paths; bp->stats.smt_config_capabilities = bp->cmd_rsp_virt->smt_mib_get.smt_config_capabilities; bp->stats.smt_config_policy = bp->cmd_rsp_virt->smt_mib_get.smt_config_policy; bp->stats.smt_connection_policy = bp->cmd_rsp_virt->smt_mib_get.smt_connection_policy; bp->stats.smt_t_notify = bp->cmd_rsp_virt->smt_mib_get.smt_t_notify; bp->stats.smt_stat_rpt_policy = bp->cmd_rsp_virt->smt_mib_get.smt_stat_rpt_policy; bp->stats.smt_trace_max_expiration = bp->cmd_rsp_virt->smt_mib_get.smt_trace_max_expiration; bp->stats.smt_bypass_present = bp->cmd_rsp_virt->smt_mib_get.smt_bypass_present; bp->stats.smt_ecm_state = bp->cmd_rsp_virt->smt_mib_get.smt_ecm_state; bp->stats.smt_cf_state = bp->cmd_rsp_virt->smt_mib_get.smt_cf_state; bp->stats.smt_remote_disconnect_flag = bp->cmd_rsp_virt->smt_mib_get.smt_remote_disconnect_flag; bp->stats.smt_station_status = bp->cmd_rsp_virt->smt_mib_get.smt_station_status; bp->stats.smt_peer_wrap_flag = bp->cmd_rsp_virt->smt_mib_get.smt_peer_wrap_flag; bp->stats.smt_time_stamp = bp->cmd_rsp_virt->smt_mib_get.smt_msg_time_stamp.ls; bp->stats.smt_transition_time_stamp = bp->cmd_rsp_virt->smt_mib_get.smt_transition_time_stamp.ls; bp->stats.mac_frame_status_functions = bp->cmd_rsp_virt->smt_mib_get.mac_frame_status_functions; bp->stats.mac_t_max_capability = bp->cmd_rsp_virt->smt_mib_get.mac_t_max_capability; bp->stats.mac_tvx_capability = bp->cmd_rsp_virt->smt_mib_get.mac_tvx_capability; bp->stats.mac_available_paths = bp->cmd_rsp_virt->smt_mib_get.mac_available_paths; bp->stats.mac_current_path = bp->cmd_rsp_virt->smt_mib_get.mac_current_path; memcpy(bp->stats.mac_upstream_nbr, &bp->cmd_rsp_virt->smt_mib_get.mac_upstream_nbr, FDDI_K_ALEN); memcpy(bp->stats.mac_downstream_nbr, &bp->cmd_rsp_virt->smt_mib_get.mac_downstream_nbr, FDDI_K_ALEN); memcpy(bp->stats.mac_old_upstream_nbr, &bp->cmd_rsp_virt->smt_mib_get.mac_old_upstream_nbr, FDDI_K_ALEN); memcpy(bp->stats.mac_old_downstream_nbr, &bp->cmd_rsp_virt->smt_mib_get.mac_old_downstream_nbr, FDDI_K_ALEN); bp->stats.mac_dup_address_test = bp->cmd_rsp_virt->smt_mib_get.mac_dup_address_test; bp->stats.mac_requested_paths = bp->cmd_rsp_virt->smt_mib_get.mac_requested_paths; bp->stats.mac_downstream_port_type = bp->cmd_rsp_virt->smt_mib_get.mac_downstream_port_type; memcpy(bp->stats.mac_smt_address, &bp->cmd_rsp_virt->smt_mib_get.mac_smt_address, FDDI_K_ALEN); bp->stats.mac_t_req = bp->cmd_rsp_virt->smt_mib_get.mac_t_req; bp->stats.mac_t_neg = bp->cmd_rsp_virt->smt_mib_get.mac_t_neg; bp->stats.mac_t_max = bp->cmd_rsp_virt->smt_mib_get.mac_t_max; bp->stats.mac_tvx_value = bp->cmd_rsp_virt->smt_mib_get.mac_tvx_value; bp->stats.mac_frame_error_threshold = bp->cmd_rsp_virt->smt_mib_get.mac_frame_error_threshold; bp->stats.mac_frame_error_ratio = bp->cmd_rsp_virt->smt_mib_get.mac_frame_error_ratio; bp->stats.mac_rmt_state = bp->cmd_rsp_virt->smt_mib_get.mac_rmt_state; bp->stats.mac_da_flag = bp->cmd_rsp_virt->smt_mib_get.mac_da_flag; bp->stats.mac_una_da_flag = bp->cmd_rsp_virt->smt_mib_get.mac_unda_flag; bp->stats.mac_frame_error_flag = bp->cmd_rsp_virt->smt_mib_get.mac_frame_error_flag; bp->stats.mac_ma_unitdata_available = bp->cmd_rsp_virt->smt_mib_get.mac_ma_unitdata_available; bp->stats.mac_hardware_present = bp->cmd_rsp_virt->smt_mib_get.mac_hardware_present; bp->stats.mac_ma_unitdata_enable = bp->cmd_rsp_virt->smt_mib_get.mac_ma_unitdata_enable; bp->stats.path_tvx_lower_bound = bp->cmd_rsp_virt->smt_mib_get.path_tvx_lower_bound; bp->stats.path_t_max_lower_bound = bp->cmd_rsp_virt->smt_mib_get.path_t_max_lower_bound; bp->stats.path_max_t_req = bp->cmd_rsp_virt->smt_mib_get.path_max_t_req; memcpy(bp->stats.path_configuration, &bp->cmd_rsp_virt->smt_mib_get.path_configuration, sizeof(bp->cmd_rsp_virt->smt_mib_get.path_configuration)); bp->stats.port_my_type[0] = bp->cmd_rsp_virt->smt_mib_get.port_my_type[0]; bp->stats.port_my_type[1] = bp->cmd_rsp_virt->smt_mib_get.port_my_type[1]; bp->stats.port_neighbor_type[0] = bp->cmd_rsp_virt->smt_mib_get.port_neighbor_type[0]; bp->stats.port_neighbor_type[1] = bp->cmd_rsp_virt->smt_mib_get.port_neighbor_type[1]; bp->stats.port_connection_policies[0] = bp->cmd_rsp_virt->smt_mib_get.port_connection_policies[0]; bp->stats.port_connection_policies[1] = bp->cmd_rsp_virt->smt_mib_get.port_connection_policies[1]; bp->stats.port_mac_indicated[0] = bp->cmd_rsp_virt->smt_mib_get.port_mac_indicated[0]; bp->stats.port_mac_indicated[1] = bp->cmd_rsp_virt->smt_mib_get.port_mac_indicated[1]; bp->stats.port_current_path[0] = bp->cmd_rsp_virt->smt_mib_get.port_current_path[0]; bp->stats.port_current_path[1] = bp->cmd_rsp_virt->smt_mib_get.port_current_path[1]; memcpy(&bp->stats.port_requested_paths[0 * 3], &bp->cmd_rsp_virt->smt_mib_get.port_requested_paths[0], 3); memcpy(&bp->stats.port_requested_paths[1 * 3], &bp->cmd_rsp_virt->smt_mib_get.port_requested_paths[1], 3); bp->stats.port_mac_placement[0] = bp->cmd_rsp_virt->smt_mib_get.port_mac_placement[0]; bp->stats.port_mac_placement[1] = bp->cmd_rsp_virt->smt_mib_get.port_mac_placement[1]; bp->stats.port_available_paths[0] = bp->cmd_rsp_virt->smt_mib_get.port_available_paths[0]; bp->stats.port_available_paths[1] = bp->cmd_rsp_virt->smt_mib_get.port_available_paths[1]; bp->stats.port_pmd_class[0] = bp->cmd_rsp_virt->smt_mib_get.port_pmd_class[0]; bp->stats.port_pmd_class[1] = bp->cmd_rsp_virt->smt_mib_get.port_pmd_class[1]; bp->stats.port_connection_capabilities[0] = bp->cmd_rsp_virt->smt_mib_get.port_connection_capabilities[0]; bp->stats.port_connection_capabilities[1] = bp->cmd_rsp_virt->smt_mib_get.port_connection_capabilities[1]; bp->stats.port_bs_flag[0] = bp->cmd_rsp_virt->smt_mib_get.port_bs_flag[0]; bp->stats.port_bs_flag[1] = bp->cmd_rsp_virt->smt_mib_get.port_bs_flag[1]; bp->stats.port_ler_estimate[0] = bp->cmd_rsp_virt->smt_mib_get.port_ler_estimate[0]; bp->stats.port_ler_estimate[1] = bp->cmd_rsp_virt->smt_mib_get.port_ler_estimate[1]; bp->stats.port_ler_cutoff[0] = bp->cmd_rsp_virt->smt_mib_get.port_ler_cutoff[0]; bp->stats.port_ler_cutoff[1] = bp->cmd_rsp_virt->smt_mib_get.port_ler_cutoff[1]; bp->stats.port_ler_alarm[0] = bp->cmd_rsp_virt->smt_mib_get.port_ler_alarm[0]; bp->stats.port_ler_alarm[1] = bp->cmd_rsp_virt->smt_mib_get.port_ler_alarm[1]; bp->stats.port_connect_state[0] = bp->cmd_rsp_virt->smt_mib_get.port_connect_state[0]; bp->stats.port_connect_state[1] = bp->cmd_rsp_virt->smt_mib_get.port_connect_state[1]; bp->stats.port_pcm_state[0] = bp->cmd_rsp_virt->smt_mib_get.port_pcm_state[0]; bp->stats.port_pcm_state[1] = bp->cmd_rsp_virt->smt_mib_get.port_pcm_state[1]; bp->stats.port_pc_withhold[0] = bp->cmd_rsp_virt->smt_mib_get.port_pc_withhold[0]; bp->stats.port_pc_withhold[1] = bp->cmd_rsp_virt->smt_mib_get.port_pc_withhold[1]; bp->stats.port_ler_flag[0] = bp->cmd_rsp_virt->smt_mib_get.port_ler_flag[0]; bp->stats.port_ler_flag[1] = bp->cmd_rsp_virt->smt_mib_get.port_ler_flag[1]; bp->stats.port_hardware_present[0] = bp->cmd_rsp_virt->smt_mib_get.port_hardware_present[0]; bp->stats.port_hardware_present[1] = bp->cmd_rsp_virt->smt_mib_get.port_hardware_present[1]; /* Fill the bp->stats structure with the FDDI counter values */ bp->stats.mac_frame_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.frame_cnt.ls; bp->stats.mac_copied_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.copied_cnt.ls; bp->stats.mac_transmit_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.transmit_cnt.ls; bp->stats.mac_error_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.error_cnt.ls; bp->stats.mac_lost_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.lost_cnt.ls; bp->stats.port_lct_fail_cts[0] = bp->cmd_rsp_virt->cntrs_get.cntrs.lct_rejects[0].ls; bp->stats.port_lct_fail_cts[1] = bp->cmd_rsp_virt->cntrs_get.cntrs.lct_rejects[1].ls; bp->stats.port_lem_reject_cts[0] = bp->cmd_rsp_virt->cntrs_get.cntrs.lem_rejects[0].ls; bp->stats.port_lem_reject_cts[1] = bp->cmd_rsp_virt->cntrs_get.cntrs.lem_rejects[1].ls; bp->stats.port_lem_cts[0] = bp->cmd_rsp_virt->cntrs_get.cntrs.link_errors[0].ls; bp->stats.port_lem_cts[1] = bp->cmd_rsp_virt->cntrs_get.cntrs.link_errors[1].ls; #endif return (struct net_device_stats *)&bp->os.MacStat; } // ctl_get_stat /* * ============================== * = skfp_ctl_set_multicast_list = * ============================== * * Overview: * Enable/Disable LLC frame promiscuous mode reception * on the adapter and/or update multicast address table. * * Returns: * None * * Arguments: * dev - pointer to device information * * Functional Description: * This function acquires the driver lock and only calls * skfp_ctl_set_multicast_list_wo_lock then. * This routine follows a fairly simple algorithm for setting the * adapter filters and CAM: * * if IFF_PROMISC flag is set * enable promiscuous mode * else * disable promiscuous mode * if number of multicast addresses <= max. multicast number * add mc addresses to adapter table * else * enable promiscuous mode * update adapter filters * * Assumptions: * Multicast addresses are presented in canonical (LSB) format. * * Side Effects: * On-board adapter filters are updated. */ static void skfp_ctl_set_multicast_list(struct net_device *dev) { struct s_smc *smc = netdev_priv(dev); skfddi_priv *bp = &smc->os; unsigned long Flags; spin_lock_irqsave(&bp->DriverLock, Flags); skfp_ctl_set_multicast_list_wo_lock(dev); spin_unlock_irqrestore(&bp->DriverLock, Flags); } // skfp_ctl_set_multicast_list static void skfp_ctl_set_multicast_list_wo_lock(struct net_device *dev) { struct s_smc *smc = netdev_priv(dev); struct netdev_hw_addr *ha; /* Enable promiscuous mode, if necessary */ if (dev->flags & IFF_PROMISC) { mac_drv_rx_mode(smc, RX_ENABLE_PROMISC); pr_debug("PROMISCUOUS MODE ENABLED\n"); } /* Else, update multicast address table */ else { mac_drv_rx_mode(smc, RX_DISABLE_PROMISC); pr_debug("PROMISCUOUS MODE DISABLED\n"); // Reset all MC addresses mac_clear_multicast(smc); mac_drv_rx_mode(smc, RX_DISABLE_ALLMULTI); if (dev->flags & IFF_ALLMULTI) { mac_drv_rx_mode(smc, RX_ENABLE_ALLMULTI); pr_debug("ENABLE ALL MC ADDRESSES\n"); } else if (!netdev_mc_empty(dev)) { if (netdev_mc_count(dev) <= FPMAX_MULTICAST) { /* use exact filtering */ // point to first multicast addr netdev_for_each_mc_addr(ha, dev) { mac_add_multicast(smc, (struct fddi_addr *)ha->addr, 1); pr_debug("ENABLE MC ADDRESS: %pMF\n", ha->addr); } } else { // more MC addresses than HW supports mac_drv_rx_mode(smc, RX_ENABLE_ALLMULTI); pr_debug("ENABLE ALL MC ADDRESSES\n"); } } else { // no MC addresses pr_debug("DISABLE ALL MC ADDRESSES\n"); } /* Update adapter filters */ mac_update_multicast(smc); } } // skfp_ctl_set_multicast_list_wo_lock /* * =========================== * = skfp_ctl_set_mac_address = * =========================== * * Overview: * set new mac address on adapter and update dev_addr field in device table. * * Returns: * None * * Arguments: * dev - pointer to device information * addr - pointer to sockaddr structure containing unicast address to set * * Assumptions: * The address pointed to by addr->sa_data is a valid unicast * address and is presented in canonical (LSB) format. */ static int skfp_ctl_set_mac_address(struct net_device *dev, void *addr) { struct s_smc *smc = netdev_priv(dev); struct sockaddr *p_sockaddr = (struct sockaddr *) addr; skfddi_priv *bp = &smc->os; unsigned long Flags; memcpy(dev->dev_addr, p_sockaddr->sa_data, FDDI_K_ALEN); spin_lock_irqsave(&bp->DriverLock, Flags); ResetAdapter(smc); spin_unlock_irqrestore(&bp->DriverLock, Flags); return 0; /* always return zero */ } // skfp_ctl_set_mac_address /* * ============== * = skfp_ioctl = * ============== * * Overview: * * Perform IOCTL call functions here. Some are privileged operations and the * effective uid is checked in those cases. * * Returns: * status value * 0 - success * other - failure * * Arguments: * dev - pointer to device information * rq - pointer to ioctl request structure * cmd - ? * */ static int skfp_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct s_smc *smc = netdev_priv(dev); skfddi_priv *lp = &smc->os; struct s_skfp_ioctl ioc; int status = 0; if (copy_from_user(&ioc, rq->ifr_data, sizeof(struct s_skfp_ioctl))) return -EFAULT; switch (ioc.cmd) { case SKFP_GET_STATS: /* Get the driver statistics */ ioc.len = sizeof(lp->MacStat); status = copy_to_user(ioc.data, skfp_ctl_get_stats(dev), ioc.len) ? -EFAULT : 0; break; case SKFP_CLR_STATS: /* Zero out the driver statistics */ if (!capable(CAP_NET_ADMIN)) { status = -EPERM; } else { memset(&lp->MacStat, 0, sizeof(lp->MacStat)); } break; default: printk("ioctl for %s: unknown cmd: %04x\n", dev->name, ioc.cmd); status = -EOPNOTSUPP; } // switch return status; } // skfp_ioctl /* * ===================== * = skfp_send_pkt = * ===================== * * Overview: * Queues a packet for transmission and try to transmit it. * * Returns: * Condition code * * Arguments: * skb - pointer to sk_buff to queue for transmission * dev - pointer to device information * * Functional Description: * Here we assume that an incoming skb transmit request * is contained in a single physically contiguous buffer * in which the virtual address of the start of packet * (skb->data) can be converted to a physical address * by using pci_map_single(). * * We have an internal queue for packets we can not send * immediately. Packets in this queue can be given to the * adapter if transmit buffers are freed. * * We can't free the skb until after it's been DMA'd * out by the adapter, so we'll keep it in the driver and * return it in mac_drv_tx_complete. * * Return Codes: * 0 - driver has queued and/or sent packet * 1 - caller should requeue the sk_buff for later transmission * * Assumptions: * The entire packet is stored in one physically * contiguous buffer which is not cached and whose * 32-bit physical address can be determined. * * It's vital that this routine is NOT reentered for the * same board and that the OS is not in another section of * code (eg. skfp_interrupt) for the same board on a * different thread. * * Side Effects: * None */ static netdev_tx_t skfp_send_pkt(struct sk_buff *skb, struct net_device *dev) { struct s_smc *smc = netdev_priv(dev); skfddi_priv *bp = &smc->os; pr_debug("skfp_send_pkt\n"); /* * Verify that incoming transmit request is OK * * Note: The packet size check is consistent with other * Linux device drivers, although the correct packet * size should be verified before calling the * transmit routine. */ if (!(skb->len >= FDDI_K_LLC_ZLEN && skb->len <= FDDI_K_LLC_LEN)) { bp->MacStat.gen.tx_errors++; /* bump error counter */ // dequeue packets from xmt queue and send them netif_start_queue(dev); dev_kfree_skb(skb); return NETDEV_TX_OK; /* return "success" */ } if (bp->QueueSkb == 0) { // return with tbusy set: queue full netif_stop_queue(dev); return NETDEV_TX_BUSY; } bp->QueueSkb--; skb_queue_tail(&bp->SendSkbQueue, skb); send_queued_packets(netdev_priv(dev)); if (bp->QueueSkb == 0) { netif_stop_queue(dev); } return NETDEV_TX_OK; } // skfp_send_pkt /* * ======================= * = send_queued_packets = * ======================= * * Overview: * Send packets from the driver queue as long as there are some and * transmit resources are available. * * Returns: * None * * Arguments: * smc - pointer to smc (adapter) structure * * Functional Description: * Take a packet from queue if there is any. If not, then we are done. * Check if there are resources to send the packet. If not, requeue it * and exit. * Set packet descriptor flags and give packet to adapter. * Check if any send resources can be freed (we do not use the * transmit complete interrupt). */ static void send_queued_packets(struct s_smc *smc) { skfddi_priv *bp = &smc->os; struct sk_buff *skb; unsigned char fc; int queue; struct s_smt_fp_txd *txd; // Current TxD. dma_addr_t dma_address; unsigned long Flags; int frame_status; // HWM tx frame status. pr_debug("send queued packets\n"); for (;;) { // send first buffer from queue skb = skb_dequeue(&bp->SendSkbQueue); if (!skb) { pr_debug("queue empty\n"); return; } // queue empty ! spin_lock_irqsave(&bp->DriverLock, Flags); fc = skb->data[0]; queue = (fc & FC_SYNC_BIT) ? QUEUE_S : QUEUE_A0; #ifdef ESS // Check if the frame may/must be sent as a synchronous frame. if ((fc & ~(FC_SYNC_BIT | FC_LLC_PRIOR)) == FC_ASYNC_LLC) { // It's an LLC frame. if (!smc->ess.sync_bw_available) fc &= ~FC_SYNC_BIT; // No bandwidth available. else { // Bandwidth is available. if (smc->mib.fddiESSSynchTxMode) { // Send as sync. frame. fc |= FC_SYNC_BIT; } } } #endif // ESS frame_status = hwm_tx_init(smc, fc, 1, skb->len, queue); if ((frame_status & (LOC_TX | LAN_TX)) == 0) { // Unable to send the frame. if ((frame_status & RING_DOWN) != 0) { // Ring is down. pr_debug("Tx attempt while ring down.\n"); } else if ((frame_status & OUT_OF_TXD) != 0) { pr_debug("%s: out of TXDs.\n", bp->dev->name); } else { pr_debug("%s: out of transmit resources", bp->dev->name); } // Note: We will retry the operation as soon as // transmit resources become available. skb_queue_head(&bp->SendSkbQueue, skb); spin_unlock_irqrestore(&bp->DriverLock, Flags); return; // Packet has been queued. } // if (unable to send frame) bp->QueueSkb++; // one packet less in local queue // source address in packet ? CheckSourceAddress(skb->data, smc->hw.fddi_canon_addr.a); txd = (struct s_smt_fp_txd *) HWM_GET_CURR_TXD(smc, queue); dma_address = pci_map_single(&bp->pdev, skb->data, skb->len, PCI_DMA_TODEVICE); if (frame_status & LAN_TX) { txd->txd_os.skb = skb; // save skb txd->txd_os.dma_addr = dma_address; // save dma mapping } hwm_tx_frag(smc, skb->data, dma_address, skb->len, frame_status | FIRST_FRAG | LAST_FRAG | EN_IRQ_EOF); if (!(frame_status & LAN_TX)) { // local only frame pci_unmap_single(&bp->pdev, dma_address, skb->len, PCI_DMA_TODEVICE); dev_kfree_skb_irq(skb); } spin_unlock_irqrestore(&bp->DriverLock, Flags); } // for return; // never reached } // send_queued_packets /************************ * * CheckSourceAddress * * Verify if the source address is set. Insert it if necessary. * ************************/ static void CheckSourceAddress(unsigned char *frame, unsigned char *hw_addr) { unsigned char SRBit; if ((((unsigned long) frame[1 + 6]) & ~0x01) != 0) // source routing bit return; if ((unsigned short) frame[1 + 10] != 0) return; SRBit = frame[1 + 6] & 0x01; memcpy(&frame[1 + 6], hw_addr, 6); frame[8] |= SRBit; } // CheckSourceAddress /************************ * * ResetAdapter * * Reset the adapter and bring it back to operational mode. * Args * smc - A pointer to the SMT context struct. * Out * Nothing. * ************************/ static void ResetAdapter(struct s_smc *smc) { pr_debug("[fddi: ResetAdapter]\n"); // Stop the adapter. card_stop(smc); // Stop all activity. // Clear the transmit and receive descriptor queues. mac_drv_clear_tx_queue(smc); mac_drv_clear_rx_queue(smc); // Restart the adapter. smt_reset_defaults(smc, 1); // Initialize the SMT module. init_smt(smc, (smc->os.dev)->dev_addr); // Initialize the hardware. smt_online(smc, 1); // Insert into the ring again. STI_FBI(); // Restore original receive mode (multicasts, promiscuous, etc.). skfp_ctl_set_multicast_list_wo_lock(smc->os.dev); } // ResetAdapter //--------------- functions called by hardware module ---------------- /************************ * * llc_restart_tx * * The hardware driver calls this routine when the transmit complete * interrupt bits (end of frame) for the synchronous or asynchronous * queue is set. * * NOTE The hardware driver calls this function also if no packets are queued. * The routine must be able to handle this case. * Args * smc - A pointer to the SMT context struct. * Out * Nothing. * ************************/ void llc_restart_tx(struct s_smc *smc) { skfddi_priv *bp = &smc->os; pr_debug("[llc_restart_tx]\n"); // Try to send queued packets spin_unlock(&bp->DriverLock); send_queued_packets(smc); spin_lock(&bp->DriverLock); netif_start_queue(bp->dev);// system may send again if it was blocked } // llc_restart_tx /************************ * * mac_drv_get_space * * The hardware module calls this function to allocate the memory * for the SMT MBufs if the define MB_OUTSIDE_SMC is specified. * Args * smc - A pointer to the SMT context struct. * * size - Size of memory in bytes to allocate. * Out * != 0 A pointer to the virtual address of the allocated memory. * == 0 Allocation error. * ************************/ void *mac_drv_get_space(struct s_smc *smc, unsigned int size) { void *virt; pr_debug("mac_drv_get_space (%d bytes), ", size); virt = (void *) (smc->os.SharedMemAddr + smc->os.SharedMemHeap); if ((smc->os.SharedMemHeap + size) > smc->os.SharedMemSize) { printk("Unexpected SMT memory size requested: %d\n", size); return NULL; } smc->os.SharedMemHeap += size; // Move heap pointer. pr_debug("mac_drv_get_space end\n"); pr_debug("virt addr: %lx\n", (ulong) virt); pr_debug("bus addr: %lx\n", (ulong) (smc->os.SharedMemDMA + ((char *) virt - (char *)smc->os.SharedMemAddr))); return virt; } // mac_drv_get_space /************************ * * mac_drv_get_desc_mem * * This function is called by the hardware dependent module. * It allocates the memory for the RxD and TxD descriptors. * * This memory must be non-cached, non-movable and non-swappable. * This memory should start at a physical page boundary. * Args * smc - A pointer to the SMT context struct. * * size - Size of memory in bytes to allocate. * Out * != 0 A pointer to the virtual address of the allocated memory. * == 0 Allocation error. * ************************/ void *mac_drv_get_desc_mem(struct s_smc *smc, unsigned int size) { char *virt; pr_debug("mac_drv_get_desc_mem\n"); // Descriptor memory must be aligned on 16-byte boundary. virt = mac_drv_get_space(smc, size); size = (u_int) (16 - (((unsigned long) virt) & 15UL)); size = size % 16; pr_debug("Allocate %u bytes alignment gap ", size); pr_debug("for descriptor memory.\n"); if (!mac_drv_get_space(smc, size)) { printk("fddi: Unable to align descriptor memory.\n"); return NULL; } return virt + size; } // mac_drv_get_desc_mem /************************ * * mac_drv_virt2phys * * Get the physical address of a given virtual address. * Args * smc - A pointer to the SMT context struct. * * virt - A (virtual) pointer into our 'shared' memory area. * Out * Physical address of the given virtual address. * ************************/ unsigned long mac_drv_virt2phys(struct s_smc *smc, void *virt) { return smc->os.SharedMemDMA + ((char *) virt - (char *)smc->os.SharedMemAddr); } // mac_drv_virt2phys /************************ * * dma_master * * The HWM calls this function, when the driver leads through a DMA * transfer. If the OS-specific module must prepare the system hardware * for the DMA transfer, it should do it in this function. * * The hardware module calls this dma_master if it wants to send an SMT * frame. This means that the virt address passed in here is part of * the 'shared' memory area. * Args * smc - A pointer to the SMT context struct. * * virt - The virtual address of the data. * * len - The length in bytes of the data. * * flag - Indicates the transmit direction and the buffer type: * DMA_RD (0x01) system RAM ==> adapter buffer memory * DMA_WR (0x02) adapter buffer memory ==> system RAM * SMT_BUF (0x80) SMT buffer * * >> NOTE: SMT_BUF and DMA_RD are always set for PCI. << * Out * Returns the pyhsical address for the DMA transfer. * ************************/ u_long dma_master(struct s_smc * smc, void *virt, int len, int flag) { return smc->os.SharedMemDMA + ((char *) virt - (char *)smc->os.SharedMemAddr); } // dma_master /************************ * * dma_complete * * The hardware module calls this routine when it has completed a DMA * transfer. If the operating system dependent module has set up the DMA * channel via dma_master() (e.g. Windows NT or AIX) it should clean up * the DMA channel. * Args * smc - A pointer to the SMT context struct. * * descr - A pointer to a TxD or RxD, respectively. * * flag - Indicates the DMA transfer direction / SMT buffer: * DMA_RD (0x01) system RAM ==> adapter buffer memory * DMA_WR (0x02) adapter buffer memory ==> system RAM * SMT_BUF (0x80) SMT buffer (managed by HWM) * Out * Nothing. * ************************/ void dma_complete(struct s_smc *smc, volatile union s_fp_descr *descr, int flag) { /* For TX buffers, there are two cases. If it is an SMT transmit * buffer, there is nothing to do since we use consistent memory * for the 'shared' memory area. The other case is for normal * transmit packets given to us by the networking stack, and in * that case we cleanup the PCI DMA mapping in mac_drv_tx_complete * below. * * For RX buffers, we have to unmap dynamic PCI DMA mappings here * because the hardware module is about to potentially look at * the contents of the buffer. If we did not call the PCI DMA * unmap first, the hardware module could read inconsistent data. */ if (flag & DMA_WR) { skfddi_priv *bp = &smc->os; volatile struct s_smt_fp_rxd *r = &descr->r; /* If SKB is NULL, we used the local buffer. */ if (r->rxd_os.skb && r->rxd_os.dma_addr) { int MaxFrameSize = bp->MaxFrameSize; pci_unmap_single(&bp->pdev, r->rxd_os.dma_addr, MaxFrameSize, PCI_DMA_FROMDEVICE); r->rxd_os.dma_addr = 0; } } } // dma_complete /************************ * * mac_drv_tx_complete * * Transmit of a packet is complete. Release the tx staging buffer. * * Args * smc - A pointer to the SMT context struct. * * txd - A pointer to the last TxD which is used by the frame. * Out * Returns nothing. * ************************/ void mac_drv_tx_complete(struct s_smc *smc, volatile struct s_smt_fp_txd *txd) { struct sk_buff *skb; pr_debug("entering mac_drv_tx_complete\n"); // Check if this TxD points to a skb if (!(skb = txd->txd_os.skb)) { pr_debug("TXD with no skb assigned.\n"); return; } txd->txd_os.skb = NULL; // release the DMA mapping pci_unmap_single(&smc->os.pdev, txd->txd_os.dma_addr, skb->len, PCI_DMA_TODEVICE); txd->txd_os.dma_addr = 0; smc->os.MacStat.gen.tx_packets++; // Count transmitted packets. smc->os.MacStat.gen.tx_bytes+=skb->len; // Count bytes // free the skb dev_kfree_skb_irq(skb); pr_debug("leaving mac_drv_tx_complete\n"); } // mac_drv_tx_complete /************************ * * dump packets to logfile * ************************/ #ifdef DUMPPACKETS void dump_data(unsigned char *Data, int length) { int i, j; unsigned char s[255], sh[10]; if (length > 64) { length = 64; } printk(KERN_INFO "---Packet start---\n"); for (i = 0, j = 0; i < length / 8; i++, j += 8) printk(KERN_INFO "%02x %02x %02x %02x %02x %02x %02x %02x\n", Data[j + 0], Data[j + 1], Data[j + 2], Data[j + 3], Data[j + 4], Data[j + 5], Data[j + 6], Data[j + 7]); strcpy(s, ""); for (i = 0; i < length % 8; i++) { sprintf(sh, "%02x ", Data[j + i]); strcat(s, sh); } printk(KERN_INFO "%s\n", s); printk(KERN_INFO "------------------\n"); } // dump_data #else #define dump_data(data,len) #endif // DUMPPACKETS /************************ * * mac_drv_rx_complete * * The hardware module calls this function if an LLC frame is received * in a receive buffer. Also the SMT, NSA, and directed beacon frames * from the network will be passed to the LLC layer by this function * if passing is enabled. * * mac_drv_rx_complete forwards the frame to the LLC layer if it should * be received. It also fills the RxD ring with new receive buffers if * some can be queued. * Args * smc - A pointer to the SMT context struct. * * rxd - A pointer to the first RxD which is used by the receive frame. * * frag_count - Count of RxDs used by the received frame. * * len - Frame length. * Out * Nothing. * ************************/ void mac_drv_rx_complete(struct s_smc *smc, volatile struct s_smt_fp_rxd *rxd, int frag_count, int len) { skfddi_priv *bp = &smc->os; struct sk_buff *skb; unsigned char *virt, *cp; unsigned short ri; u_int RifLength; pr_debug("entering mac_drv_rx_complete (len=%d)\n", len); if (frag_count != 1) { // This is not allowed to happen. printk("fddi: Multi-fragment receive!\n"); goto RequeueRxd; // Re-use the given RXD(s). } skb = rxd->rxd_os.skb; if (!skb) { pr_debug("No skb in rxd\n"); smc->os.MacStat.gen.rx_errors++; goto RequeueRxd; } virt = skb->data; // The DMA mapping was released in dma_complete above. dump_data(skb->data, len); /* * FDDI Frame format: * +-------+-------+-------+------------+--------+------------+ * | FC[1] | DA[6] | SA[6] | RIF[0..18] | LLC[3] | Data[0..n] | * +-------+-------+-------+------------+--------+------------+ * * FC = Frame Control * DA = Destination Address * SA = Source Address * RIF = Routing Information Field * LLC = Logical Link Control */ // Remove Routing Information Field (RIF), if present. if ((virt[1 + 6] & FDDI_RII) == 0) RifLength = 0; else { int n; // goos: RIF removal has still to be tested pr_debug("RIF found\n"); // Get RIF length from Routing Control (RC) field. cp = virt + FDDI_MAC_HDR_LEN; // Point behind MAC header. ri = ntohs(*((__be16 *) cp)); RifLength = ri & FDDI_RCF_LEN_MASK; if (len < (int) (FDDI_MAC_HDR_LEN + RifLength)) { printk("fddi: Invalid RIF.\n"); goto RequeueRxd; // Discard the frame. } virt[1 + 6] &= ~FDDI_RII; // Clear RII bit. // regions overlap virt = cp + RifLength; for (n = FDDI_MAC_HDR_LEN; n; n--) *--virt = *--cp; // adjust sbd->data pointer skb_pull(skb, RifLength); len -= RifLength; RifLength = 0; } // Count statistics. smc->os.MacStat.gen.rx_packets++; // Count indicated receive // packets. smc->os.MacStat.gen.rx_bytes+=len; // Count bytes. // virt points to header again if (virt[1] & 0x01) { // Check group (multicast) bit. smc->os.MacStat.gen.multicast++; } // deliver frame to system rxd->rxd_os.skb = NULL; skb_trim(skb, len); skb->protocol = fddi_type_trans(skb, bp->dev); netif_rx(skb); HWM_RX_CHECK(smc, RX_LOW_WATERMARK); return; RequeueRxd: pr_debug("Rx: re-queue RXD.\n"); mac_drv_requeue_rxd(smc, rxd, frag_count); smc->os.MacStat.gen.rx_errors++; // Count receive packets // not indicated. } // mac_drv_rx_complete /************************ * * mac_drv_requeue_rxd * * The hardware module calls this function to request the OS-specific * module to queue the receive buffer(s) represented by the pointer * to the RxD and the frag_count into the receive queue again. This * buffer was filled with an invalid frame or an SMT frame. * Args * smc - A pointer to the SMT context struct. * * rxd - A pointer to the first RxD which is used by the receive frame. * * frag_count - Count of RxDs used by the received frame. * Out * Nothing. * ************************/ void mac_drv_requeue_rxd(struct s_smc *smc, volatile struct s_smt_fp_rxd *rxd, int frag_count) { volatile struct s_smt_fp_rxd *next_rxd; volatile struct s_smt_fp_rxd *src_rxd; struct sk_buff *skb; int MaxFrameSize; unsigned char *v_addr; dma_addr_t b_addr; if (frag_count != 1) // This is not allowed to happen. printk("fddi: Multi-fragment requeue!\n"); MaxFrameSize = smc->os.MaxFrameSize; src_rxd = rxd; for (; frag_count > 0; frag_count--) { next_rxd = src_rxd->rxd_next; rxd = HWM_GET_CURR_RXD(smc); skb = src_rxd->rxd_os.skb; if (skb == NULL) { // this should not happen pr_debug("Requeue with no skb in rxd!\n"); skb = alloc_skb(MaxFrameSize + 3, GFP_ATOMIC); if (skb) { // we got a skb rxd->rxd_os.skb = skb; skb_reserve(skb, 3); skb_put(skb, MaxFrameSize); v_addr = skb->data; b_addr = pci_map_single(&smc->os.pdev, v_addr, MaxFrameSize, PCI_DMA_FROMDEVICE); rxd->rxd_os.dma_addr = b_addr; } else { // no skb available, use local buffer pr_debug("Queueing invalid buffer!\n"); rxd->rxd_os.skb = NULL; v_addr = smc->os.LocalRxBuffer; b_addr = smc->os.LocalRxBufferDMA; } } else { // we use skb from old rxd rxd->rxd_os.skb = skb; v_addr = skb->data; b_addr = pci_map_single(&smc->os.pdev, v_addr, MaxFrameSize, PCI_DMA_FROMDEVICE); rxd->rxd_os.dma_addr = b_addr; } hwm_rx_frag(smc, v_addr, b_addr, MaxFrameSize, FIRST_FRAG | LAST_FRAG); src_rxd = next_rxd; } } // mac_drv_requeue_rxd /************************ * * mac_drv_fill_rxd * * The hardware module calls this function at initialization time * to fill the RxD ring with receive buffers. It is also called by * mac_drv_rx_complete if rx_free is large enough to queue some new * receive buffers into the RxD ring. mac_drv_fill_rxd queues new * receive buffers as long as enough RxDs and receive buffers are * available. * Args * smc - A pointer to the SMT context struct. * Out * Nothing. * ************************/ void mac_drv_fill_rxd(struct s_smc *smc) { int MaxFrameSize; unsigned char *v_addr; unsigned long b_addr; struct sk_buff *skb; volatile struct s_smt_fp_rxd *rxd; pr_debug("entering mac_drv_fill_rxd\n"); // Walk through the list of free receive buffers, passing receive // buffers to the HWM as long as RXDs are available. MaxFrameSize = smc->os.MaxFrameSize; // Check if there is any RXD left. while (HWM_GET_RX_FREE(smc) > 0) { pr_debug(".\n"); rxd = HWM_GET_CURR_RXD(smc); skb = alloc_skb(MaxFrameSize + 3, GFP_ATOMIC); if (skb) { // we got a skb skb_reserve(skb, 3); skb_put(skb, MaxFrameSize); v_addr = skb->data; b_addr = pci_map_single(&smc->os.pdev, v_addr, MaxFrameSize, PCI_DMA_FROMDEVICE); rxd->rxd_os.dma_addr = b_addr; } else { // no skb available, use local buffer // System has run out of buffer memory, but we want to // keep the receiver running in hope of better times. // Multiple descriptors may point to this local buffer, // so data in it must be considered invalid. pr_debug("Queueing invalid buffer!\n"); v_addr = smc->os.LocalRxBuffer; b_addr = smc->os.LocalRxBufferDMA; } rxd->rxd_os.skb = skb; // Pass receive buffer to HWM. hwm_rx_frag(smc, v_addr, b_addr, MaxFrameSize, FIRST_FRAG | LAST_FRAG); } pr_debug("leaving mac_drv_fill_rxd\n"); } // mac_drv_fill_rxd /************************ * * mac_drv_clear_rxd * * The hardware module calls this function to release unused * receive buffers. * Args * smc - A pointer to the SMT context struct. * * rxd - A pointer to the first RxD which is used by the receive buffer. * * frag_count - Count of RxDs used by the receive buffer. * Out * Nothing. * ************************/ void mac_drv_clear_rxd(struct s_smc *smc, volatile struct s_smt_fp_rxd *rxd, int frag_count) { struct sk_buff *skb; pr_debug("entering mac_drv_clear_rxd\n"); if (frag_count != 1) // This is not allowed to happen. printk("fddi: Multi-fragment clear!\n"); for (; frag_count > 0; frag_count--) { skb = rxd->rxd_os.skb; if (skb != NULL) { skfddi_priv *bp = &smc->os; int MaxFrameSize = bp->MaxFrameSize; pci_unmap_single(&bp->pdev, rxd->rxd_os.dma_addr, MaxFrameSize, PCI_DMA_FROMDEVICE); dev_kfree_skb(skb); rxd->rxd_os.skb = NULL; } rxd = rxd->rxd_next; // Next RXD. } } // mac_drv_clear_rxd /************************ * * mac_drv_rx_init * * The hardware module calls this routine when an SMT or NSA frame of the * local SMT should be delivered to the LLC layer. * * It is necessary to have this function, because there is no other way to * copy the contents of SMT MBufs into receive buffers. * * mac_drv_rx_init allocates the required target memory for this frame, * and receives the frame fragment by fragment by calling mac_drv_rx_frag. * Args * smc - A pointer to the SMT context struct. * * len - The length (in bytes) of the received frame (FC, DA, SA, Data). * * fc - The Frame Control field of the received frame. * * look_ahead - A pointer to the lookahead data buffer (may be NULL). * * la_len - The length of the lookahead data stored in the lookahead * buffer (may be zero). * Out * Always returns zero (0). * ************************/ int mac_drv_rx_init(struct s_smc *smc, int len, int fc, char *look_ahead, int la_len) { struct sk_buff *skb; pr_debug("entering mac_drv_rx_init(len=%d)\n", len); // "Received" a SMT or NSA frame of the local SMT. if (len != la_len || len < FDDI_MAC_HDR_LEN || !look_ahead) { pr_debug("fddi: Discard invalid local SMT frame\n"); pr_debug(" len=%d, la_len=%d, (ULONG) look_ahead=%08lXh.\n", len, la_len, (unsigned long) look_ahead); return 0; } skb = alloc_skb(len + 3, GFP_ATOMIC); if (!skb) { pr_debug("fddi: Local SMT: skb memory exhausted.\n"); return 0; } skb_reserve(skb, 3); skb_put(skb, len); skb_copy_to_linear_data(skb, look_ahead, len); // deliver frame to system skb->protocol = fddi_type_trans(skb, smc->os.dev); netif_rx(skb); return 0; } // mac_drv_rx_init /************************ * * smt_timer_poll * * This routine is called periodically by the SMT module to clean up the * driver. * * Return any queued frames back to the upper protocol layers if the ring * is down. * Args * smc - A pointer to the SMT context struct. * Out * Nothing. * ************************/ void smt_timer_poll(struct s_smc *smc) { } // smt_timer_poll /************************ * * ring_status_indication * * This function indicates a change of the ring state. * Args * smc - A pointer to the SMT context struct. * * status - The current ring status. * Out * Nothing. * ************************/ void ring_status_indication(struct s_smc *smc, u_long status) { pr_debug("ring_status_indication( "); if (status & RS_RES15) pr_debug("RS_RES15 "); if (status & RS_HARDERROR) pr_debug("RS_HARDERROR "); if (status & RS_SOFTERROR) pr_debug("RS_SOFTERROR "); if (status & RS_BEACON) pr_debug("RS_BEACON "); if (status & RS_PATHTEST) pr_debug("RS_PATHTEST "); if (status & RS_SELFTEST) pr_debug("RS_SELFTEST "); if (status & RS_RES9) pr_debug("RS_RES9 "); if (status & RS_DISCONNECT) pr_debug("RS_DISCONNECT "); if (status & RS_RES7) pr_debug("RS_RES7 "); if (status & RS_DUPADDR) pr_debug("RS_DUPADDR "); if (status & RS_NORINGOP) pr_debug("RS_NORINGOP "); if (status & RS_VERSION) pr_debug("RS_VERSION "); if (status & RS_STUCKBYPASSS) pr_debug("RS_STUCKBYPASSS "); if (status & RS_EVENT) pr_debug("RS_EVENT "); if (status & RS_RINGOPCHANGE) pr_debug("RS_RINGOPCHANGE "); if (status & RS_RES0) pr_debug("RS_RES0 "); pr_debug("]\n"); } // ring_status_indication /************************ * * smt_get_time * * Gets the current time from the system. * Args * None. * Out * The current time in TICKS_PER_SECOND. * * TICKS_PER_SECOND has the unit 'count of timer ticks per second'. It is * defined in "targetos.h". The definition of TICKS_PER_SECOND must comply * to the time returned by smt_get_time(). * ************************/ unsigned long smt_get_time(void) { return jiffies; } // smt_get_time /************************ * * smt_stat_counter * * Status counter update (ring_op, fifo full). * Args * smc - A pointer to the SMT context struct. * * stat - = 0: A ring operational change occurred. * = 1: The FORMAC FIFO buffer is full / FIFO overflow. * Out * Nothing. * ************************/ void smt_stat_counter(struct s_smc *smc, int stat) { // BOOLEAN RingIsUp ; pr_debug("smt_stat_counter\n"); switch (stat) { case 0: pr_debug("Ring operational change.\n"); break; case 1: pr_debug("Receive fifo overflow.\n"); smc->os.MacStat.gen.rx_errors++; break; default: pr_debug("Unknown status (%d).\n", stat); break; } } // smt_stat_counter /************************ * * cfm_state_change * * Sets CFM state in custom statistics. * Args * smc - A pointer to the SMT context struct. * * c_state - Possible values are: * * EC0_OUT, EC1_IN, EC2_TRACE, EC3_LEAVE, EC4_PATH_TEST, * EC5_INSERT, EC6_CHECK, EC7_DEINSERT * Out * Nothing. * ************************/ void cfm_state_change(struct s_smc *smc, int c_state) { #ifdef DRIVERDEBUG char *s; switch (c_state) { case SC0_ISOLATED: s = "SC0_ISOLATED"; break; case SC1_WRAP_A: s = "SC1_WRAP_A"; break; case SC2_WRAP_B: s = "SC2_WRAP_B"; break; case SC4_THRU_A: s = "SC4_THRU_A"; break; case SC5_THRU_B: s = "SC5_THRU_B"; break; case SC7_WRAP_S: s = "SC7_WRAP_S"; break; case SC9_C_WRAP_A: s = "SC9_C_WRAP_A"; break; case SC10_C_WRAP_B: s = "SC10_C_WRAP_B"; break; case SC11_C_WRAP_S: s = "SC11_C_WRAP_S"; break; default: pr_debug("cfm_state_change: unknown %d\n", c_state); return; } pr_debug("cfm_state_change: %s\n", s); #endif // DRIVERDEBUG } // cfm_state_change /************************ * * ecm_state_change * * Sets ECM state in custom statistics. * Args * smc - A pointer to the SMT context struct. * * e_state - Possible values are: * * SC0_ISOLATED, SC1_WRAP_A (5), SC2_WRAP_B (6), SC4_THRU_A (12), * SC5_THRU_B (7), SC7_WRAP_S (8) * Out * Nothing. * ************************/ void ecm_state_change(struct s_smc *smc, int e_state) { #ifdef DRIVERDEBUG char *s; switch (e_state) { case EC0_OUT: s = "EC0_OUT"; break; case EC1_IN: s = "EC1_IN"; break; case EC2_TRACE: s = "EC2_TRACE"; break; case EC3_LEAVE: s = "EC3_LEAVE"; break; case EC4_PATH_TEST: s = "EC4_PATH_TEST"; break; case EC5_INSERT: s = "EC5_INSERT"; break; case EC6_CHECK: s = "EC6_CHECK"; break; case EC7_DEINSERT: s = "EC7_DEINSERT"; break; default: s = "unknown"; break; } pr_debug("ecm_state_change: %s\n", s); #endif //DRIVERDEBUG } // ecm_state_change /************************ * * rmt_state_change * * Sets RMT state in custom statistics. * Args * smc - A pointer to the SMT context struct. * * r_state - Possible values are: * * RM0_ISOLATED, RM1_NON_OP, RM2_RING_OP, RM3_DETECT, * RM4_NON_OP_DUP, RM5_RING_OP_DUP, RM6_DIRECTED, RM7_TRACE * Out * Nothing. * ************************/ void rmt_state_change(struct s_smc *smc, int r_state) { #ifdef DRIVERDEBUG char *s; switch (r_state) { case RM0_ISOLATED: s = "RM0_ISOLATED"; break; case RM1_NON_OP: s = "RM1_NON_OP - not operational"; break; case RM2_RING_OP: s = "RM2_RING_OP - ring operational"; break; case RM3_DETECT: s = "RM3_DETECT - detect dupl addresses"; break; case RM4_NON_OP_DUP: s = "RM4_NON_OP_DUP - dupl. addr detected"; break; case RM5_RING_OP_DUP: s = "RM5_RING_OP_DUP - ring oper. with dupl. addr"; break; case RM6_DIRECTED: s = "RM6_DIRECTED - sending directed beacons"; break; case RM7_TRACE: s = "RM7_TRACE - trace initiated"; break; default: s = "unknown"; break; } pr_debug("[rmt_state_change: %s]\n", s); #endif // DRIVERDEBUG } // rmt_state_change /************************ * * drv_reset_indication * * This function is called by the SMT when it has detected a severe * hardware problem. The driver should perform a reset on the adapter * as soon as possible, but not from within this function. * Args * smc - A pointer to the SMT context struct. * Out * Nothing. * ************************/ void drv_reset_indication(struct s_smc *smc) { pr_debug("entering drv_reset_indication\n"); smc->os.ResetRequested = TRUE; // Set flag. } // drv_reset_indication static struct pci_driver skfddi_pci_driver = { .name = "skfddi", .id_table = skfddi_pci_tbl, .probe = skfp_init_one, .remove = __devexit_p(skfp_remove_one), }; static int __init skfd_init(void) { return pci_register_driver(&skfddi_pci_driver); } static void __exit skfd_exit(void) { pci_unregister_driver(&skfddi_pci_driver); } module_init(skfd_init); module_exit(skfd_exit);
gpl-3.0
TRothfelder/Multicopter
libs/STM32Cube_FW_F4_V1.16.0/Projects/STM32469I_EVAL/Examples/TIM/TIM_PWMInput/Src/system_stm32f4xx.c
125
22970
/** ****************************************************************************** * @file system_stm32f4xx.c * @author MCD Application Team * @version V1.1.0 * @date 17-February-2017 * @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File. * * This file provides two functions and one global variable to be called from * user application: * - SystemInit(): This function is called at startup just after reset and * before branch to main program. This call is made inside * the "startup_stm32f4xx.s" file. * * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used * by the user application to setup the SysTick * timer or configure other parameters. * * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must * be called whenever the core clock is changed * during program execution. * * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f4xx_system * @{ */ /** @addtogroup STM32F4xx_System_Private_Includes * @{ */ #include "stm32f4xx.h" #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)25000000) /*!< Default value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @} */ /** @addtogroup STM32F4xx_System_Private_TypesDefinitions * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Private_Defines * @{ */ /************************* Miscellaneous Configuration ************************/ /*!< Uncomment the following line if you need to use external SRAM or SDRAM mounted on STMicroelectronics EVAL/Discovery boards as data memory */ /* #define DATA_IN_ExtSRAM */ /* #define DATA_IN_ExtSDRAM */ /*!< Uncomment the following line if you need to relocate your vector Table in Internal SRAM. */ /* #define VECT_TAB_SRAM */ #define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field. This value must be a multiple of 0x200. */ /******************************************************************************/ /** * @} */ /** @addtogroup STM32F4xx_System_Private_Macros * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Private_Variables * @{ */ /* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetHCLKFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency Note: If you use this function to configure the system clock; then there is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ uint32_t SystemCoreClock = 16000000; const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; /** * @} */ /** @addtogroup STM32F4xx_System_Private_FunctionPrototypes * @{ */ #if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) static void SystemInit_ExtMemCtl(void); #endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ /** * @} */ /** @addtogroup STM32F4xx_System_Private_Functions * @{ */ /** * @brief Setup the microcontroller system * Initialize the FPU setting, vector table location and External memory * configuration. * @param None * @retval None */ void SystemInit(void) { /* FPU settings ------------------------------------------------------------*/ #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ #endif /* Reset the RCC clock configuration to the default reset state ------------*/ /* Set HSION bit */ RCC->CR |= (uint32_t)0x00000001; /* Reset CFGR register */ RCC->CFGR = 0x00000000; /* Reset HSEON, CSSON and PLLON bits */ RCC->CR &= (uint32_t)0xFEF6FFFF; /* Reset PLLCFGR register */ RCC->PLLCFGR = 0x24003010; /* Reset HSEBYP bit */ RCC->CR &= (uint32_t)0xFFFBFFFF; /* Disable all interrupts */ RCC->CIR = 0x00000000; #if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) SystemInit_ExtMemCtl(); #endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ /* Configure the Vector Table location add offset address ------------------*/ #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ #else SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ #endif } /** * @brief Update SystemCoreClock variable according to Clock Register Values. * The SystemCoreClock variable contains the core clock (HCLK), it can * be used by the user application to setup the SysTick timer or configure * other parameters. * * @note Each time the core clock (HCLK) changes, this function must be called * to update SystemCoreClock variable value. Otherwise, any configuration * based on this variable will be incorrect. * * @note - The system frequency computed by this function is not the real * frequency in the chip. It is calculated based on the predefined * constant and the selected clock source: * * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) * * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) * * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) * or HSI_VALUE(*) multiplied/divided by the PLL factors. * * (*) HSI_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value * 16 MHz) but the real value may vary depending on the variations * in voltage and temperature. * * (**) HSE_VALUE is a constant defined in stm32f4xx_hal_conf.h file (its value * depends on the application requirements), user has to ensure that HSE_VALUE * is same as the real frequency of the crystal used. Otherwise, this function * may have wrong result. * * - The result of this function could be not correct when using fractional * value for HSE crystal. * * @param None * @retval None */ void SystemCoreClockUpdate(void) { uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; /* Get SYSCLK source -------------------------------------------------------*/ tmp = RCC->CFGR & RCC_CFGR_SWS; switch (tmp) { case 0x00: /* HSI used as system clock source */ SystemCoreClock = HSI_VALUE; break; case 0x04: /* HSE used as system clock source */ SystemCoreClock = HSE_VALUE; break; case 0x08: /* PLL used as system clock source */ /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N SYSCLK = PLL_VCO / PLL_P */ pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22; pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; if (pllsource != 0) { /* HSE used as PLL clock source */ pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); } else { /* HSI used as PLL clock source */ pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); } pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2; SystemCoreClock = pllvco/pllp; break; default: SystemCoreClock = HSI_VALUE; break; } /* Compute HCLK frequency --------------------------------------------------*/ /* Get HCLK prescaler */ tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; /* HCLK frequency */ SystemCoreClock >>= tmp; } #if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) /** * @brief Setup the external memory controller. * Called in startup_stm32f7xx.s before jump to main. * This function configures the external memories (SRAM/SDRAM) * This SRAM/SDRAM will be used as program data memory (including heap and stack). * @param None * @retval None */ void SystemInit_ExtMemCtl(void) { __IO uint32_t tmp = 0; #if defined (DATA_IN_ExtSDRAM) && defined (DATA_IN_ExtSRAM) register uint32_t tmpreg = 0, timeout = 0xFFFF; register uint32_t index; /* Enable GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */ RCC->AHB1ENR |= 0x000001F8; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN); /* Connect PDx pins to FMC Alternate function */ GPIOD->AFR[0] = 0x00CC00CC; GPIOD->AFR[1] = 0xCCCCCCCC; /* Configure PDx pins in Alternate function mode */ GPIOD->MODER = 0xAAAA0A0A; /* Configure PDx pins speed to 100 MHz */ GPIOD->OSPEEDR = 0xFFFF0F0F; /* Configure PDx pins Output type to push-pull */ GPIOD->OTYPER = 0x00000000; /* No pull-up, pull-down for PDx pins */ GPIOD->PUPDR = 0x00000000; /* Connect PEx pins to FMC Alternate function */ GPIOE->AFR[0] = 0xC00CC0CC; GPIOE->AFR[1] = 0xCCCCCCCC; /* Configure PEx pins in Alternate function mode */ GPIOE->MODER = 0xAAAA828A; /* Configure PEx pins speed to 100 MHz */ GPIOE->OSPEEDR = 0xFFFFC3CF; /* Configure PEx pins Output type to push-pull */ GPIOE->OTYPER = 0x00000000; /* No pull-up, pull-down for PEx pins */ GPIOE->PUPDR = 0x00000000; /* Connect PFx pins to FMC Alternate function */ GPIOF->AFR[0] = 0x00CCCCCC; GPIOF->AFR[1] = 0xCCCCC000; /* Configure PFx pins in Alternate function mode */ GPIOF->MODER = 0xAA800AAA; /* Configure PFx pins speed to 100 MHz */ GPIOF->OSPEEDR = 0xFFC00FFF; /* Configure PFx pins Output type to push-pull */ GPIOF->OTYPER = 0x00000000; /* No pull-up, pull-down for PFx pins */ GPIOF->PUPDR = 0x00000000; /* Connect PGx pins to FMC Alternate function */ GPIOG->AFR[0] = 0x0CCCCCCC; GPIOG->AFR[1] = 0xC00000CC; /* Configure PGx pins in Alternate function mode */ GPIOG->MODER = 0x800A0AAA; /* Configure PGx pins speed to 100 MHz */ GPIOG->OSPEEDR = 0xC00F0FFF; /* Configure PGx pins Output type to push-pull */ GPIOG->OTYPER = 0x00000000; /* No pull-up, pull-down for PGx pins */ GPIOG->PUPDR = 0x00000000; /* Connect PHx pins to FMC Alternate function */ GPIOH->AFR[0] = 0x00C0CC00; GPIOH->AFR[1] = 0xCCCCCCCC; /* Configure PHx pins in Alternate function mode */ GPIOH->MODER = 0xAAAA08A0; /* Configure PHx pins speed to 100 MHz */ GPIOH->OSPEEDR = 0xFFFF0CF0; /* Configure PHx pins Output type to push-pull */ GPIOH->OTYPER = 0x00000000; /* No pull-up, pull-down for PHx pins */ GPIOH->PUPDR = 0x00000000; /* Connect PIx pins to FMC Alternate function */ GPIOI->AFR[0] = 0xCCCCCCCC; GPIOI->AFR[1] = 0x00000CC0; /* Configure PIx pins in Alternate function mode */ GPIOI->MODER = 0x0028AAAA; /* Configure PIx pins speed to 100 MHz */ GPIOI->OSPEEDR = 0x003CFFFF; /* Configure PIx pins Output type to push-pull */ GPIOI->OTYPER = 0x00000000; /* No pull-up, pull-down for PIx pins */ GPIOI->PUPDR = 0x00000000; /*-- FMC Configuration ------------------------------------------------------*/ /* Enable the FMC interface clock */ RCC->AHB3ENR |= 0x00000001; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); /* Configure and enable Bank1_SRAM2 */ FMC_Bank1->BTCR[2] = 0x00001091; FMC_Bank1->BTCR[3] = 0x00110212; FMC_Bank1E->BWTR[2] = 0x0FFFFFFF; /* Configure and enable SDRAM bank1 */ FMC_Bank5_6->SDCR[0] = 0x000019E5; FMC_Bank5_6->SDTR[0] = 0x01115351; /* SDRAM initialization sequence */ /* Clock enable command */ FMC_Bank5_6->SDCMR = 0x00000011; tmpreg = FMC_Bank5_6->SDSR & 0x00000020; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Delay */ for (index = 0; index<1000; index++); /* PALL command */ FMC_Bank5_6->SDCMR = 0x00000012; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Auto refresh command */ FMC_Bank5_6->SDCMR = 0x000000F3; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* MRD register program */ FMC_Bank5_6->SDCMR = 0x00046014; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Set refresh count */ tmpreg = FMC_Bank5_6->SDRTR; FMC_Bank5_6->SDRTR = (tmpreg | (0x0000056A<<1)); /* Disable write protection */ tmpreg = FMC_Bank5_6->SDCR[0]; FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); #elif defined (DATA_IN_ExtSDRAM) register uint32_t tmpreg = 0, timeout = 0xFFFF; register uint32_t index; /* Enable GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */ RCC->AHB1ENR |= 0x000001F8; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN); /* Connect PDx pins to FMC Alternate function */ GPIOD->AFR[0] = 0x000000CC; GPIOD->AFR[1] = 0xCC000CCC; /* Configure PDx pins in Alternate function mode */ GPIOD->MODER = 0xA02A000A; /* Configure PDx pins speed to 100 MHz */ GPIOD->OSPEEDR = 0xF03F000F; /* Configure PDx pins Output type to push-pull */ GPIOD->OTYPER = 0x00000000; /* No pull-up, pull-down for PDx pins */ GPIOD->PUPDR = 0x00000000; /* Connect PEx pins to FMC Alternate function */ GPIOE->AFR[0] = 0xC00000CC; GPIOE->AFR[1] = 0xCCCCCCCC; /* Configure PEx pins in Alternate function mode */ GPIOE->MODER = 0xAAAA800A; /* Configure PEx pins speed to 100 MHz */ GPIOE->OSPEEDR = 0xFFFFC00F; /* Configure PEx pins Output type to push-pull */ GPIOE->OTYPER = 0x00000000; /* No pull-up, pull-down for PEx pins */ GPIOE->PUPDR = 0x00000000; /* Connect PFx pins to FMC Alternate function */ GPIOF->AFR[0] = 0x00CCCCCC; GPIOF->AFR[1] = 0xCCCCC000; /* Configure PFx pins in Alternate function mode */ GPIOF->MODER = 0xAA800AAA; /* Configure PFx pins speed to 100 MHz */ GPIOF->OSPEEDR = 0xFFC00FFF; /* Configure PFx pins Output type to push-pull */ GPIOF->OTYPER = 0x00000000; /* No pull-up, pull-down for PFx pins */ GPIOF->PUPDR = 0x00000000; /* Connect PGx pins to FMC Alternate function */ GPIOG->AFR[0] = 0x00CC00CC; GPIOG->AFR[1] = 0xC000000C; /* Configure PGx pins in Alternate function mode */ GPIOG->MODER = 0x80020A0A; /* Configure PGx pins speed to 100 MHz */ GPIOG->OSPEEDR = 0xC0030F0F; /* Configure PGx pins Output type to push-pull */ GPIOG->OTYPER = 0x00000000; /* No pull-up, pull-down for PGx pins */ GPIOG->PUPDR = 0x00000000; /* Connect PHx pins to FMC Alternate function */ GPIOH->AFR[0] = 0x00C0CC00; GPIOH->AFR[1] = 0xCCCCCCCC; /* Configure PHx pins in Alternate function mode */ GPIOH->MODER = 0xAAAA08A0; /* Configure PHx pins speed to 100 MHz */ GPIOH->OSPEEDR = 0xFFFF0CF0; /* Configure PHx pins Output type to push-pull */ GPIOH->OTYPER = 0x00000000; /* No pull-up, pull-down for PHx pins */ GPIOH->PUPDR = 0x00000000; /* Connect PIx pins to FMC Alternate function */ GPIOI->AFR[0] = 0xCCCCCCCC; GPIOI->AFR[1] = 0x00000CC0; /* Configure PIx pins in Alternate function mode */ GPIOI->MODER = 0x0028AAAA; /* Configure PIx pins speed to 100 MHz */ GPIOI->OSPEEDR = 0x003CFFFF; /* Configure PIx pins Output type to push-pull */ GPIOI->OTYPER = 0x00000000; /* No pull-up, pull-down for PIx pins */ GPIOI->PUPDR = 0x00000000; /*-- FMC Configuration ------------------------------------------------------*/ /* Enable the FMC interface clock */ RCC->AHB3ENR |= 0x00000001; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); /* Configure and enable SDRAM bank1 */ FMC_Bank5_6->SDCR[0] = 0x000019E5; FMC_Bank5_6->SDTR[0] = 0x01115351; /* SDRAM initialization sequence */ /* Clock enable command */ FMC_Bank5_6->SDCMR = 0x00000011; tmpreg = FMC_Bank5_6->SDSR & 0x00000020; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Delay */ for (index = 0; index<1000; index++); /* PALL command */ FMC_Bank5_6->SDCMR = 0x00000012; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Auto refresh command */ FMC_Bank5_6->SDCMR = 0x000000F3; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* MRD register program */ FMC_Bank5_6->SDCMR = 0x00046014; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Set refresh count */ tmpreg = FMC_Bank5_6->SDRTR; FMC_Bank5_6->SDRTR = (tmpreg | (0x0000056A<<1)); /* Disable write protection */ tmpreg = FMC_Bank5_6->SDCR[0]; FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); #elif defined(DATA_IN_ExtSRAM) /*-- GPIOs Configuration -----------------------------------------------------*/ /* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */ RCC->AHB1ENR |= 0x00000078; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN); /* Connect PDx pins to FMC Alternate function */ GPIOD->AFR[0] = 0x00CC00CC; GPIOD->AFR[1] = 0xCCCCCCCC; /* Configure PDx pins in Alternate function mode */ GPIOD->MODER = 0xAAAA0A0A; /* Configure PDx pins speed to 100 MHz */ GPIOD->OSPEEDR = 0xFFFF0F0F; /* Configure PDx pins Output type to push-pull */ GPIOD->OTYPER = 0x00000000; /* No pull-up, pull-down for PDx pins */ GPIOD->PUPDR = 0x00000000; /* Connect PEx pins to FMC Alternate function */ GPIOE->AFR[0] = 0xC00CC0CC; GPIOE->AFR[1] = 0xCCCCCCCC; /* Configure PEx pins in Alternate function mode */ GPIOE->MODER = 0xAAAA828A; /* Configure PEx pins speed to 100 MHz */ GPIOE->OSPEEDR = 0xFFFFC3CF; /* Configure PEx pins Output type to push-pull */ GPIOE->OTYPER = 0x00000000; /* No pull-up, pull-down for PEx pins */ GPIOE->PUPDR = 0x00000000; /* Connect PFx pins to FMC Alternate function */ GPIOF->AFR[0] = 0x00CCCCCC; GPIOF->AFR[1] = 0xCCCC0000; /* Configure PFx pins in Alternate function mode */ GPIOF->MODER = 0xAA000AAA; /* Configure PFx pins speed to 100 MHz */ GPIOF->OSPEEDR = 0xFF000FFF; /* Configure PFx pins Output type to push-pull */ GPIOF->OTYPER = 0x00000000; /* No pull-up, pull-down for PFx pins */ GPIOF->PUPDR = 0x00000000; /* Connect PGx pins to FMC Alternate function */ GPIOG->AFR[0] = 0x00CCCCCC; GPIOG->AFR[1] = 0x000000C0; /* Configure PGx pins in Alternate function mode */ GPIOG->MODER = 0x00080AAA; /* Configure PGx pins speed to 100 MHz */ GPIOG->OSPEEDR = 0x000C0FFF; /* Configure PGx pins Output type to push-pull */ GPIOG->OTYPER = 0x00000000; /* No pull-up, pull-down for PGx pins */ GPIOG->PUPDR = 0x00000000; /*-- FMC/FSMC Configuration --------------------------------------------------*/ /* Enable the FMC/FSMC interface clock */ RCC->AHB3ENR |= 0x00000001; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); /* Configure and enable Bank2_SRAM */ FMC_Bank1->BTCR[2] = 0x00001091; FMC_Bank1->BTCR[3] = 0x00110212; FMC_Bank1E->BWTR[2] = 0x0FFFFFFF; #endif /* DATA_IN_ExtSRAM */ (void)(tmp); } #endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
gpl-3.0
luke147/tvclipper
ffmpeg-2.7.2/libavcodec/jfdctfst.c
125
11243
/* * This file is part of the Independent JPEG Group's software. * * The authors make NO WARRANTY or representation, either express or implied, * with respect to this software, its quality, accuracy, merchantability, or * fitness for a particular purpose. This software is provided "AS IS", and * you, its user, assume the entire risk as to its quality and accuracy. * * This software is copyright (C) 1994-1996, Thomas G. Lane. * All Rights Reserved except as specified below. * * Permission is hereby granted to use, copy, modify, and distribute this * software (or portions thereof) for any purpose, without fee, subject to * these conditions: * (1) If any part of the source code for this software is distributed, then * this README file must be included, with this copyright and no-warranty * notice unaltered; and any additions, deletions, or changes to the original * files must be clearly indicated in accompanying documentation. * (2) If only executable code is distributed, then the accompanying * documentation must state that "this software is based in part on the work * of the Independent JPEG Group". * (3) Permission for use of this software is granted only if the user accepts * full responsibility for any undesirable consequences; the authors accept * NO LIABILITY for damages of any kind. * * These conditions apply to any software derived from or based on the IJG * code, not just to the unmodified library. If you use our work, you ought * to acknowledge us. * * Permission is NOT granted for the use of any IJG author's name or company * name in advertising or publicity relating to this software or products * derived from it. This software may be referred to only as "the Independent * JPEG Group's software". * * We specifically permit and encourage the use of this software as the basis * of commercial products, provided that all warranty or liability claims are * assumed by the product vendor. * * This file contains a fast, not so accurate integer implementation of the * forward DCT (Discrete Cosine Transform). * * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT * on each column. Direct algorithms are also available, but they are * much more complex and seem not to be any faster when reduced to code. * * This implementation is based on Arai, Agui, and Nakajima's algorithm for * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in * Japanese, but the algorithm is described in the Pennebaker & Mitchell * JPEG textbook (see REFERENCES section in file README). The following code * is based directly on figure 4-8 in P&M. * While an 8-point DCT cannot be done in less than 11 multiplies, it is * possible to arrange the computation so that many of the multiplies are * simple scalings of the final outputs. These multiplies can then be * folded into the multiplications or divisions by the JPEG quantization * table entries. The AA&N method leaves only 5 multiplies and 29 adds * to be done in the DCT itself. * The primary disadvantage of this method is that with fixed-point math, * accuracy is lost due to imprecise representation of the scaled * quantization values. The smaller the quantization table entry, the less * precise the scaled value, so this implementation does worse with high- * quality-setting files than with low-quality ones. */ /** * @file * Independent JPEG Group's fast AAN dct. */ #include <stdlib.h> #include <stdio.h> #include "libavutil/common.h" #include "dct.h" #define DCTSIZE 8 #define GLOBAL(x) x #define RIGHT_SHIFT(x, n) ((x) >> (n)) /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ #endif /* Scaling decisions are generally the same as in the LL&M algorithm; * see jfdctint.c for more details. However, we choose to descale * (right shift) multiplication products as soon as they are formed, * rather than carrying additional fractional bits into subsequent additions. * This compromises accuracy slightly, but it lets us save a few shifts. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples) * everywhere except in the multiplications proper; this saves a good deal * of work on 16-bit-int machines. * * Again to save a few shifts, the intermediate results between pass 1 and * pass 2 are not upscaled, but are represented only to integral precision. * * A final compromise is to represent the multiplicative constants to only * 8 fractional bits, rather than 13. This saves some shifting work on some * machines, and may also reduce the cost of multiplication (since there * are fewer one-bits in the constants). */ #define CONST_BITS 8 /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus * causing a lot of useless floating-point operations at run time. * To get around this we use the following pre-calculated constants. * If you change CONST_BITS you may want to add appropriate values. * (With a reasonable C compiler, you can just rely on the FIX() macro...) */ #if CONST_BITS == 8 #define FIX_0_382683433 ((int32_t) 98) /* FIX(0.382683433) */ #define FIX_0_541196100 ((int32_t) 139) /* FIX(0.541196100) */ #define FIX_0_707106781 ((int32_t) 181) /* FIX(0.707106781) */ #define FIX_1_306562965 ((int32_t) 334) /* FIX(1.306562965) */ #else #define FIX_0_382683433 FIX(0.382683433) #define FIX_0_541196100 FIX(0.541196100) #define FIX_0_707106781 FIX(0.707106781) #define FIX_1_306562965 FIX(1.306562965) #endif /* We can gain a little more speed, with a further compromise in accuracy, * by omitting the addition in a descaling shift. This yields an incorrectly * rounded result half the time... */ #ifndef USE_ACCURATE_ROUNDING #undef DESCALE #define DESCALE(x,n) RIGHT_SHIFT(x, n) #endif /* Multiply a int16_t variable by an int32_t constant, and immediately * descale to yield a int16_t result. */ #define MULTIPLY(var,const) ((int16_t) DESCALE((var) * (const), CONST_BITS)) static av_always_inline void row_fdct(int16_t * data){ int tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; int tmp10, tmp11, tmp12, tmp13; int z1, z2, z3, z4, z5, z11, z13; int16_t *dataptr; int ctr; /* Pass 1: process rows. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { tmp0 = dataptr[0] + dataptr[7]; tmp7 = dataptr[0] - dataptr[7]; tmp1 = dataptr[1] + dataptr[6]; tmp6 = dataptr[1] - dataptr[6]; tmp2 = dataptr[2] + dataptr[5]; tmp5 = dataptr[2] - dataptr[5]; tmp3 = dataptr[3] + dataptr[4]; tmp4 = dataptr[3] - dataptr[4]; /* Even part */ tmp10 = tmp0 + tmp3; /* phase 2 */ tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; dataptr[0] = tmp10 + tmp11; /* phase 3 */ dataptr[4] = tmp10 - tmp11; z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */ dataptr[2] = tmp13 + z1; /* phase 5 */ dataptr[6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */ z11 = tmp7 + z3; /* phase 5 */ z13 = tmp7 - z3; dataptr[5] = z13 + z2; /* phase 6 */ dataptr[3] = z13 - z2; dataptr[1] = z11 + z4; dataptr[7] = z11 - z4; dataptr += DCTSIZE; /* advance pointer to next row */ } } /* * Perform the forward DCT on one block of samples. */ GLOBAL(void) ff_fdct_ifast (int16_t * data) { int tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; int tmp10, tmp11, tmp12, tmp13; int z1, z2, z3, z4, z5, z11, z13; int16_t *dataptr; int ctr; row_fdct(data); /* Pass 2: process columns. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; /* Even part */ tmp10 = tmp0 + tmp3; /* phase 2 */ tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */ dataptr[DCTSIZE*4] = tmp10 - tmp11; z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */ dataptr[DCTSIZE*6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */ z11 = tmp7 + z3; /* phase 5 */ z13 = tmp7 - z3; dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */ dataptr[DCTSIZE*3] = z13 - z2; dataptr[DCTSIZE*1] = z11 + z4; dataptr[DCTSIZE*7] = z11 - z4; dataptr++; /* advance pointer to next column */ } } /* * Perform the forward 2-4-8 DCT on one block of samples. */ GLOBAL(void) ff_fdct_ifast248 (int16_t * data) { int tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; int tmp10, tmp11, tmp12, tmp13; int z1; int16_t *dataptr; int ctr; row_fdct(data); /* Pass 2: process columns. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*1]; tmp1 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*3]; tmp2 = dataptr[DCTSIZE*4] + dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*6] + dataptr[DCTSIZE*7]; tmp4 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*1]; tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*3]; tmp6 = dataptr[DCTSIZE*4] - dataptr[DCTSIZE*5]; tmp7 = dataptr[DCTSIZE*6] - dataptr[DCTSIZE*7]; /* Even part */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; tmp13 = tmp0 - tmp3; dataptr[DCTSIZE*0] = tmp10 + tmp11; dataptr[DCTSIZE*4] = tmp10 - tmp11; z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); dataptr[DCTSIZE*2] = tmp13 + z1; dataptr[DCTSIZE*6] = tmp13 - z1; tmp10 = tmp4 + tmp7; tmp11 = tmp5 + tmp6; tmp12 = tmp5 - tmp6; tmp13 = tmp4 - tmp7; dataptr[DCTSIZE*1] = tmp10 + tmp11; dataptr[DCTSIZE*5] = tmp10 - tmp11; z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); dataptr[DCTSIZE*3] = tmp13 + z1; dataptr[DCTSIZE*7] = tmp13 - z1; dataptr++; /* advance pointer to next column */ } } #undef GLOBAL #undef CONST_BITS #undef DESCALE #undef FIX_0_541196100 #undef FIX_1_306562965
gpl-3.0
DRLFeBo/Alice
ALICE_PLATFORM/src/Eigen/test/dense_storage.cpp
126
2579
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2013 Hauke Heibel <hauke.heibel@gmail.com> // // 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 "main.h" #include <Eigen/Core> template <typename T, int Rows, int Cols> void dense_storage_copy() { static const int Size = ((Rows==Dynamic || Cols==Dynamic) ? Dynamic : Rows*Cols); typedef DenseStorage<T,Size, Rows,Cols, 0> DenseStorageType; const int rows = (Rows==Dynamic) ? 4 : Rows; const int cols = (Cols==Dynamic) ? 3 : Cols; const int size = rows*cols; DenseStorageType reference(size, rows, cols); T* raw_reference = reference.data(); for (int i=0; i<size; ++i) raw_reference[i] = static_cast<T>(i); DenseStorageType copied_reference(reference); const T* raw_copied_reference = copied_reference.data(); for (int i=0; i<size; ++i) VERIFY_IS_EQUAL(raw_reference[i], raw_copied_reference[i]); } template <typename T, int Rows, int Cols> void dense_storage_assignment() { static const int Size = ((Rows==Dynamic || Cols==Dynamic) ? Dynamic : Rows*Cols); typedef DenseStorage<T,Size, Rows,Cols, 0> DenseStorageType; const int rows = (Rows==Dynamic) ? 4 : Rows; const int cols = (Cols==Dynamic) ? 3 : Cols; const int size = rows*cols; DenseStorageType reference(size, rows, cols); T* raw_reference = reference.data(); for (int i=0; i<size; ++i) raw_reference[i] = static_cast<T>(i); DenseStorageType copied_reference; copied_reference = reference; const T* raw_copied_reference = copied_reference.data(); for (int i=0; i<size; ++i) VERIFY_IS_EQUAL(raw_reference[i], raw_copied_reference[i]); } void test_dense_storage() { dense_storage_copy<int,Dynamic,Dynamic>(); dense_storage_copy<int,Dynamic,3>(); dense_storage_copy<int,4,Dynamic>(); dense_storage_copy<int,4,3>(); dense_storage_copy<float,Dynamic,Dynamic>(); dense_storage_copy<float,Dynamic,3>(); dense_storage_copy<float,4,Dynamic>(); dense_storage_copy<float,4,3>(); dense_storage_assignment<int,Dynamic,Dynamic>(); dense_storage_assignment<int,Dynamic,3>(); dense_storage_assignment<int,4,Dynamic>(); dense_storage_assignment<int,4,3>(); dense_storage_assignment<float,Dynamic,Dynamic>(); dense_storage_assignment<float,Dynamic,3>(); dense_storage_assignment<float,4,Dynamic>(); dense_storage_assignment<float,4,3>(); }
gpl-3.0
shlyakpavel/s720-KK-kernel
kernel/drivers/video/via/via-gpio.c
5248
7531
/* * Support for viafb GPIO ports. * * Copyright 2009 Jonathan Corbet <corbet@lwn.net> * Distributable under version 2 of the GNU General Public License. */ #include <linux/spinlock.h> #include <linux/gpio.h> #include <linux/platform_device.h> #include <linux/via-core.h> #include <linux/via-gpio.h> #include <linux/export.h> /* * The ports we know about. Note that the port-25 gpios are not * mentioned in the datasheet. */ struct viafb_gpio { char *vg_name; /* Data sheet name */ u16 vg_io_port; u8 vg_port_index; int vg_mask_shift; }; static struct viafb_gpio viafb_all_gpios[] = { { .vg_name = "VGPIO0", /* Guess - not in datasheet */ .vg_io_port = VIASR, .vg_port_index = 0x25, .vg_mask_shift = 1 }, { .vg_name = "VGPIO1", .vg_io_port = VIASR, .vg_port_index = 0x25, .vg_mask_shift = 0 }, { .vg_name = "VGPIO2", /* aka DISPCLKI0 */ .vg_io_port = VIASR, .vg_port_index = 0x2c, .vg_mask_shift = 1 }, { .vg_name = "VGPIO3", /* aka DISPCLKO0 */ .vg_io_port = VIASR, .vg_port_index = 0x2c, .vg_mask_shift = 0 }, { .vg_name = "VGPIO4", /* DISPCLKI1 */ .vg_io_port = VIASR, .vg_port_index = 0x3d, .vg_mask_shift = 1 }, { .vg_name = "VGPIO5", /* DISPCLKO1 */ .vg_io_port = VIASR, .vg_port_index = 0x3d, .vg_mask_shift = 0 }, }; #define VIAFB_NUM_GPIOS ARRAY_SIZE(viafb_all_gpios) /* * This structure controls the active GPIOs, which may be a subset * of those which are known. */ struct viafb_gpio_cfg { struct gpio_chip gpio_chip; struct viafb_dev *vdev; struct viafb_gpio *active_gpios[VIAFB_NUM_GPIOS]; const char *gpio_names[VIAFB_NUM_GPIOS]; }; /* * GPIO access functions */ static void via_gpio_set(struct gpio_chip *chip, unsigned int nr, int value) { struct viafb_gpio_cfg *cfg = container_of(chip, struct viafb_gpio_cfg, gpio_chip); u8 reg; struct viafb_gpio *gpio; unsigned long flags; spin_lock_irqsave(&cfg->vdev->reg_lock, flags); gpio = cfg->active_gpios[nr]; reg = via_read_reg(VIASR, gpio->vg_port_index); reg |= 0x40 << gpio->vg_mask_shift; /* output enable */ if (value) reg |= 0x10 << gpio->vg_mask_shift; else reg &= ~(0x10 << gpio->vg_mask_shift); via_write_reg(VIASR, gpio->vg_port_index, reg); spin_unlock_irqrestore(&cfg->vdev->reg_lock, flags); } static int via_gpio_dir_out(struct gpio_chip *chip, unsigned int nr, int value) { via_gpio_set(chip, nr, value); return 0; } /* * Set the input direction. I'm not sure this is right; we should * be able to do input without disabling output. */ static int via_gpio_dir_input(struct gpio_chip *chip, unsigned int nr) { struct viafb_gpio_cfg *cfg = container_of(chip, struct viafb_gpio_cfg, gpio_chip); struct viafb_gpio *gpio; unsigned long flags; spin_lock_irqsave(&cfg->vdev->reg_lock, flags); gpio = cfg->active_gpios[nr]; via_write_reg_mask(VIASR, gpio->vg_port_index, 0, 0x40 << gpio->vg_mask_shift); spin_unlock_irqrestore(&cfg->vdev->reg_lock, flags); return 0; } static int via_gpio_get(struct gpio_chip *chip, unsigned int nr) { struct viafb_gpio_cfg *cfg = container_of(chip, struct viafb_gpio_cfg, gpio_chip); u8 reg; struct viafb_gpio *gpio; unsigned long flags; spin_lock_irqsave(&cfg->vdev->reg_lock, flags); gpio = cfg->active_gpios[nr]; reg = via_read_reg(VIASR, gpio->vg_port_index); spin_unlock_irqrestore(&cfg->vdev->reg_lock, flags); return reg & (0x04 << gpio->vg_mask_shift); } static struct viafb_gpio_cfg viafb_gpio_config = { .gpio_chip = { .label = "VIAFB onboard GPIO", .owner = THIS_MODULE, .direction_output = via_gpio_dir_out, .set = via_gpio_set, .direction_input = via_gpio_dir_input, .get = via_gpio_get, .base = -1, .ngpio = 0, .can_sleep = 0 } }; /* * Manage the software enable bit. */ static void viafb_gpio_enable(struct viafb_gpio *gpio) { via_write_reg_mask(VIASR, gpio->vg_port_index, 0x02, 0x02); } static void viafb_gpio_disable(struct viafb_gpio *gpio) { via_write_reg_mask(VIASR, gpio->vg_port_index, 0, 0x02); } #ifdef CONFIG_PM static int viafb_gpio_suspend(void *private) { return 0; } static int viafb_gpio_resume(void *private) { int i; for (i = 0; i < viafb_gpio_config.gpio_chip.ngpio; i += 2) viafb_gpio_enable(viafb_gpio_config.active_gpios[i]); return 0; } static struct viafb_pm_hooks viafb_gpio_pm_hooks = { .suspend = viafb_gpio_suspend, .resume = viafb_gpio_resume }; #endif /* CONFIG_PM */ /* * Look up a specific gpio and return the number it was assigned. */ int viafb_gpio_lookup(const char *name) { int i; for (i = 0; i < viafb_gpio_config.gpio_chip.ngpio; i++) if (!strcmp(name, viafb_gpio_config.active_gpios[i]->vg_name)) return viafb_gpio_config.gpio_chip.base + i; return -1; } EXPORT_SYMBOL_GPL(viafb_gpio_lookup); /* * Platform device stuff. */ static __devinit int viafb_gpio_probe(struct platform_device *platdev) { struct viafb_dev *vdev = platdev->dev.platform_data; struct via_port_cfg *port_cfg = vdev->port_cfg; int i, ngpio = 0, ret; struct viafb_gpio *gpio; unsigned long flags; /* * Set up entries for all GPIOs which have been configured to * operate as such (as opposed to as i2c ports). */ for (i = 0; i < VIAFB_NUM_PORTS; i++) { if (port_cfg[i].mode != VIA_MODE_GPIO) continue; for (gpio = viafb_all_gpios; gpio < viafb_all_gpios + VIAFB_NUM_GPIOS; gpio++) if (gpio->vg_port_index == port_cfg[i].ioport_index) { viafb_gpio_config.active_gpios[ngpio] = gpio; viafb_gpio_config.gpio_names[ngpio] = gpio->vg_name; ngpio++; } } viafb_gpio_config.gpio_chip.ngpio = ngpio; viafb_gpio_config.gpio_chip.names = viafb_gpio_config.gpio_names; viafb_gpio_config.vdev = vdev; if (ngpio == 0) { printk(KERN_INFO "viafb: no GPIOs configured\n"); return 0; } /* * Enable the ports. They come in pairs, with a single * enable bit for both. */ spin_lock_irqsave(&viafb_gpio_config.vdev->reg_lock, flags); for (i = 0; i < ngpio; i += 2) viafb_gpio_enable(viafb_gpio_config.active_gpios[i]); spin_unlock_irqrestore(&viafb_gpio_config.vdev->reg_lock, flags); /* * Get registered. */ viafb_gpio_config.gpio_chip.base = -1; /* Dynamic */ ret = gpiochip_add(&viafb_gpio_config.gpio_chip); if (ret) { printk(KERN_ERR "viafb: failed to add gpios (%d)\n", ret); viafb_gpio_config.gpio_chip.ngpio = 0; } #ifdef CONFIG_PM viafb_pm_register(&viafb_gpio_pm_hooks); #endif return ret; } static int viafb_gpio_remove(struct platform_device *platdev) { unsigned long flags; int ret = 0, i; #ifdef CONFIG_PM viafb_pm_unregister(&viafb_gpio_pm_hooks); #endif /* * Get unregistered. */ if (viafb_gpio_config.gpio_chip.ngpio > 0) { ret = gpiochip_remove(&viafb_gpio_config.gpio_chip); if (ret) { /* Somebody still using it? */ printk(KERN_ERR "Viafb: GPIO remove failed\n"); return ret; } } /* * Disable the ports. */ spin_lock_irqsave(&viafb_gpio_config.vdev->reg_lock, flags); for (i = 0; i < viafb_gpio_config.gpio_chip.ngpio; i += 2) viafb_gpio_disable(viafb_gpio_config.active_gpios[i]); viafb_gpio_config.gpio_chip.ngpio = 0; spin_unlock_irqrestore(&viafb_gpio_config.vdev->reg_lock, flags); return ret; } static struct platform_driver via_gpio_driver = { .driver = { .name = "viafb-gpio", }, .probe = viafb_gpio_probe, .remove = viafb_gpio_remove, }; int viafb_gpio_init(void) { return platform_driver_register(&via_gpio_driver); } void viafb_gpio_exit(void) { platform_driver_unregister(&via_gpio_driver); }
gpl-3.0
CertifiedBlyndGuy/ewok-onyx
drivers/isdn/gigaset/ser-gigaset.c
133
18503
/* This is the serial hardware link layer (HLL) for the Gigaset 307x isdn * DECT base (aka Sinus 45 isdn) using the RS232 DECT data module M101, * written as a line discipline. * * ===================================================================== * 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 "gigaset.h" #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/platform_device.h> #include <linux/completion.h> /* Version Information */ #define DRIVER_AUTHOR "Tilman Schmidt" #define DRIVER_DESC "Serial Driver for Gigaset 307x using Siemens M101" #define GIGASET_MINORS 1 #define GIGASET_MINOR 0 #define GIGASET_MODULENAME "ser_gigaset" #define GIGASET_DEVNAME "ttyGS" /* length limit according to Siemens 3070usb-protokoll.doc ch. 2.1 */ #define IF_WRITEBUF 264 MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); MODULE_ALIAS_LDISC(N_GIGASET_M101); static int startmode = SM_ISDN; module_param(startmode, int, S_IRUGO); MODULE_PARM_DESC(startmode, "initial operation mode"); static int cidmode = 1; module_param(cidmode, int, S_IRUGO); MODULE_PARM_DESC(cidmode, "stay in CID mode when idle"); static struct gigaset_driver *driver; struct ser_cardstate { struct platform_device dev; struct tty_struct *tty; atomic_t refcnt; struct completion dead_cmp; }; static struct platform_driver device_driver = { .driver = { .name = GIGASET_MODULENAME, }, }; static void flush_send_queue(struct cardstate *); /* transmit data from current open skb * result: number of bytes sent or error code < 0 */ static int write_modem(struct cardstate *cs) { struct tty_struct *tty = cs->hw.ser->tty; struct bc_state *bcs = &cs->bcs[0]; /* only one channel */ struct sk_buff *skb = bcs->tx_skb; int sent = -EOPNOTSUPP; if (!tty || !tty->driver || !skb) return -EINVAL; if (!skb->len) { dev_kfree_skb_any(skb); bcs->tx_skb = NULL; return -EINVAL; } set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); if (tty->ops->write) sent = tty->ops->write(tty, skb->data, skb->len); gig_dbg(DEBUG_OUTPUT, "write_modem: sent %d", sent); if (sent < 0) { /* error */ flush_send_queue(cs); return sent; } skb_pull(skb, sent); if (!skb->len) { /* skb sent completely */ gigaset_skb_sent(bcs, skb); gig_dbg(DEBUG_INTR, "kfree skb (Adr: %lx)!", (unsigned long) skb); dev_kfree_skb_any(skb); bcs->tx_skb = NULL; } return sent; } /* * transmit first queued command buffer * result: number of bytes sent or error code < 0 */ static int send_cb(struct cardstate *cs) { struct tty_struct *tty = cs->hw.ser->tty; struct cmdbuf_t *cb, *tcb; unsigned long flags; int sent = 0; if (!tty || !tty->driver) return -EFAULT; cb = cs->cmdbuf; if (!cb) return 0; /* nothing to do */ if (cb->len) { set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); sent = tty->ops->write(tty, cb->buf + cb->offset, cb->len); if (sent < 0) { /* error */ gig_dbg(DEBUG_OUTPUT, "send_cb: write error %d", sent); flush_send_queue(cs); return sent; } cb->offset += sent; cb->len -= sent; gig_dbg(DEBUG_OUTPUT, "send_cb: sent %d, left %u, queued %u", sent, cb->len, cs->cmdbytes); } while (cb && !cb->len) { spin_lock_irqsave(&cs->cmdlock, flags); cs->cmdbytes -= cs->curlen; tcb = cb; cs->cmdbuf = cb = cb->next; if (cb) { cb->prev = NULL; cs->curlen = cb->len; } else { cs->lastcmdbuf = NULL; cs->curlen = 0; } spin_unlock_irqrestore(&cs->cmdlock, flags); if (tcb->wake_tasklet) tasklet_schedule(tcb->wake_tasklet); kfree(tcb); } return sent; } /* * send queue tasklet * If there is already a skb opened, put data to the transfer buffer * by calling "write_modem". * Otherwise take a new skb out of the queue. */ static void gigaset_modem_fill(unsigned long data) { struct cardstate *cs = (struct cardstate *) data; struct bc_state *bcs; struct sk_buff *nextskb; int sent = 0; if (!cs) { gig_dbg(DEBUG_OUTPUT, "%s: no cardstate", __func__); return; } bcs = cs->bcs; if (!bcs) { gig_dbg(DEBUG_OUTPUT, "%s: no cardstate", __func__); return; } if (!bcs->tx_skb) { /* no skb is being sent; send command if any */ sent = send_cb(cs); gig_dbg(DEBUG_OUTPUT, "%s: send_cb -> %d", __func__, sent); if (sent) /* something sent or error */ return; /* no command to send; get skb */ nextskb = skb_dequeue(&bcs->squeue); if (!nextskb) /* no skb either, nothing to do */ return; bcs->tx_skb = nextskb; gig_dbg(DEBUG_INTR, "Dequeued skb (Adr: %lx)", (unsigned long) bcs->tx_skb); } /* send skb */ gig_dbg(DEBUG_OUTPUT, "%s: tx_skb", __func__); if (write_modem(cs) < 0) gig_dbg(DEBUG_OUTPUT, "%s: write_modem failed", __func__); } /* * throw away all data queued for sending */ static void flush_send_queue(struct cardstate *cs) { struct sk_buff *skb; struct cmdbuf_t *cb; unsigned long flags; /* command queue */ spin_lock_irqsave(&cs->cmdlock, flags); while ((cb = cs->cmdbuf) != NULL) { cs->cmdbuf = cb->next; if (cb->wake_tasklet) tasklet_schedule(cb->wake_tasklet); kfree(cb); } cs->cmdbuf = cs->lastcmdbuf = NULL; cs->cmdbytes = cs->curlen = 0; spin_unlock_irqrestore(&cs->cmdlock, flags); /* data queue */ if (cs->bcs->tx_skb) dev_kfree_skb_any(cs->bcs->tx_skb); while ((skb = skb_dequeue(&cs->bcs->squeue)) != NULL) dev_kfree_skb_any(skb); } /* Gigaset Driver Interface */ /* ======================== */ /* * queue an AT command string for transmission to the Gigaset device * parameters: * cs controller state structure * buf buffer containing the string to send * len number of characters to send * wake_tasklet tasklet to run when transmission is complete, or NULL * return value: * number of bytes queued, or error code < 0 */ static int gigaset_write_cmd(struct cardstate *cs, struct cmdbuf_t *cb) { unsigned long flags; gigaset_dbg_buffer(cs->mstate != MS_LOCKED ? DEBUG_TRANSCMD : DEBUG_LOCKCMD, "CMD Transmit", cb->len, cb->buf); spin_lock_irqsave(&cs->cmdlock, flags); cb->prev = cs->lastcmdbuf; if (cs->lastcmdbuf) cs->lastcmdbuf->next = cb; else { cs->cmdbuf = cb; cs->curlen = cb->len; } cs->cmdbytes += cb->len; cs->lastcmdbuf = cb; spin_unlock_irqrestore(&cs->cmdlock, flags); spin_lock_irqsave(&cs->lock, flags); if (cs->connected) tasklet_schedule(&cs->write_tasklet); spin_unlock_irqrestore(&cs->lock, flags); return cb->len; } /* * tty_driver.write_room interface routine * return number of characters the driver will accept to be written * parameter: * controller state structure * return value: * number of characters */ static int gigaset_write_room(struct cardstate *cs) { unsigned bytes; bytes = cs->cmdbytes; return bytes < IF_WRITEBUF ? IF_WRITEBUF - bytes : 0; } /* * tty_driver.chars_in_buffer interface routine * return number of characters waiting to be sent * parameter: * controller state structure * return value: * number of characters */ static int gigaset_chars_in_buffer(struct cardstate *cs) { return cs->cmdbytes; } /* * implementation of ioctl(GIGASET_BRKCHARS) * parameter: * controller state structure * return value: * -EINVAL (unimplemented function) */ static int gigaset_brkchars(struct cardstate *cs, const unsigned char buf[6]) { /* not implemented */ return -EINVAL; } /* * Open B channel * Called by "do_action" in ev-layer.c */ static int gigaset_init_bchannel(struct bc_state *bcs) { /* nothing to do for M10x */ gigaset_bchannel_up(bcs); return 0; } /* * Close B channel * Called by "do_action" in ev-layer.c */ static int gigaset_close_bchannel(struct bc_state *bcs) { /* nothing to do for M10x */ gigaset_bchannel_down(bcs); return 0; } /* * Set up B channel structure * This is called by "gigaset_initcs" in common.c */ static int gigaset_initbcshw(struct bc_state *bcs) { /* unused */ bcs->hw.ser = NULL; return 1; } /* * Free B channel structure * Called by "gigaset_freebcs" in common.c */ static int gigaset_freebcshw(struct bc_state *bcs) { /* unused */ return 1; } /* * Reinitialize B channel structure * This is called by "bcs_reinit" in common.c */ static void gigaset_reinitbcshw(struct bc_state *bcs) { /* nothing to do for M10x */ } /* * Free hardware specific device data * This will be called by "gigaset_freecs" in common.c */ static void gigaset_freecshw(struct cardstate *cs) { tasklet_kill(&cs->write_tasklet); if (!cs->hw.ser) return; platform_device_unregister(&cs->hw.ser->dev); } static void gigaset_device_release(struct device *dev) { kfree(container_of(dev, struct ser_cardstate, dev.dev)); } /* * Set up hardware specific device data * This is called by "gigaset_initcs" in common.c */ static int gigaset_initcshw(struct cardstate *cs) { int rc; struct ser_cardstate *scs; scs = kzalloc(sizeof(struct ser_cardstate), GFP_KERNEL); if (!scs) { pr_err("out of memory\n"); return 0; } cs->hw.ser = scs; cs->hw.ser->dev.name = GIGASET_MODULENAME; cs->hw.ser->dev.id = cs->minor_index; cs->hw.ser->dev.dev.release = gigaset_device_release; rc = platform_device_register(&cs->hw.ser->dev); if (rc != 0) { pr_err("error %d registering platform device\n", rc); kfree(cs->hw.ser); cs->hw.ser = NULL; return 0; } tasklet_init(&cs->write_tasklet, gigaset_modem_fill, (unsigned long) cs); return 1; } /* * set modem control lines * Parameters: * card state structure * modem control line state ([TIOCM_DTR]|[TIOCM_RTS]) * Called by "gigaset_start" and "gigaset_enterconfigmode" in common.c * and by "if_lock" and "if_termios" in interface.c */ static int gigaset_set_modem_ctrl(struct cardstate *cs, unsigned old_state, unsigned new_state) { struct tty_struct *tty = cs->hw.ser->tty; unsigned int set, clear; if (!tty || !tty->driver || !tty->ops->tiocmset) return -EINVAL; set = new_state & ~old_state; clear = old_state & ~new_state; if (!set && !clear) return 0; gig_dbg(DEBUG_IF, "tiocmset set %x clear %x", set, clear); return tty->ops->tiocmset(tty, set, clear); } static int gigaset_baud_rate(struct cardstate *cs, unsigned cflag) { return -EINVAL; } static int gigaset_set_line_ctrl(struct cardstate *cs, unsigned cflag) { return -EINVAL; } static const struct gigaset_ops ops = { gigaset_write_cmd, gigaset_write_room, gigaset_chars_in_buffer, gigaset_brkchars, gigaset_init_bchannel, gigaset_close_bchannel, gigaset_initbcshw, gigaset_freebcshw, gigaset_reinitbcshw, gigaset_initcshw, gigaset_freecshw, gigaset_set_modem_ctrl, gigaset_baud_rate, gigaset_set_line_ctrl, gigaset_m10x_send_skb, /* asyncdata.c */ gigaset_m10x_input, /* asyncdata.c */ }; /* Line Discipline Interface */ /* ========================= */ /* helper functions for cardstate refcounting */ static struct cardstate *cs_get(struct tty_struct *tty) { struct cardstate *cs = tty->disc_data; if (!cs || !cs->hw.ser) { gig_dbg(DEBUG_ANY, "%s: no cardstate", __func__); return NULL; } atomic_inc(&cs->hw.ser->refcnt); return cs; } static void cs_put(struct cardstate *cs) { if (atomic_dec_and_test(&cs->hw.ser->refcnt)) complete(&cs->hw.ser->dead_cmp); } /* * Called by the tty driver when the line discipline is pushed onto the tty. * Called in process context. */ static int gigaset_tty_open(struct tty_struct *tty) { struct cardstate *cs; gig_dbg(DEBUG_INIT, "Starting HLL for Gigaset M101"); pr_info(DRIVER_DESC "\n"); if (!driver) { pr_err("%s: no driver structure\n", __func__); return -ENODEV; } /* allocate memory for our device state and initialize it */ cs = gigaset_initcs(driver, 1, 1, 0, cidmode, GIGASET_MODULENAME); if (!cs) goto error; cs->dev = &cs->hw.ser->dev.dev; cs->hw.ser->tty = tty; atomic_set(&cs->hw.ser->refcnt, 1); init_completion(&cs->hw.ser->dead_cmp); tty->disc_data = cs; /* OK.. Initialization of the datastructures and the HW is done.. Now * startup system and notify the LL that we are ready to run */ if (startmode == SM_LOCKED) cs->mstate = MS_LOCKED; if (!gigaset_start(cs)) { tasklet_kill(&cs->write_tasklet); goto error; } gig_dbg(DEBUG_INIT, "Startup of HLL done"); return 0; error: gig_dbg(DEBUG_INIT, "Startup of HLL failed"); tty->disc_data = NULL; gigaset_freecs(cs); return -ENODEV; } /* * Called by the tty driver when the line discipline is removed. * Called from process context. */ static void gigaset_tty_close(struct tty_struct *tty) { struct cardstate *cs = tty->disc_data; gig_dbg(DEBUG_INIT, "Stopping HLL for Gigaset M101"); if (!cs) { gig_dbg(DEBUG_INIT, "%s: no cardstate", __func__); return; } /* prevent other callers from entering ldisc methods */ tty->disc_data = NULL; if (!cs->hw.ser) pr_err("%s: no hw cardstate\n", __func__); else { /* wait for running methods to finish */ if (!atomic_dec_and_test(&cs->hw.ser->refcnt)) wait_for_completion(&cs->hw.ser->dead_cmp); } /* stop operations */ gigaset_stop(cs); tasklet_kill(&cs->write_tasklet); flush_send_queue(cs); cs->dev = NULL; gigaset_freecs(cs); gig_dbg(DEBUG_INIT, "Shutdown of HLL done"); } /* * Called by the tty driver when the tty line is hung up. * Wait for I/O to driver to complete and unregister ISDN device. * This is already done by the close routine, so just call that. * Called from process context. */ static int gigaset_tty_hangup(struct tty_struct *tty) { gigaset_tty_close(tty); return 0; } /* * Read on the tty. * Unused, received data goes only to the Gigaset driver. */ static ssize_t gigaset_tty_read(struct tty_struct *tty, struct file *file, unsigned char __user *buf, size_t count) { return -EAGAIN; } /* * Write on the tty. * Unused, transmit data comes only from the Gigaset driver. */ static ssize_t gigaset_tty_write(struct tty_struct *tty, struct file *file, const unsigned char *buf, size_t count) { return -EAGAIN; } /* * Ioctl on the tty. * Called in process context only. * May be re-entered by multiple ioctl calling threads. */ static int gigaset_tty_ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg) { struct cardstate *cs = cs_get(tty); int rc, val; int __user *p = (int __user *)arg; if (!cs) return -ENXIO; switch (cmd) { case FIONREAD: /* unused, always return zero */ val = 0; rc = put_user(val, p); break; case TCFLSH: /* flush our buffers and the serial port's buffer */ switch (arg) { case TCIFLUSH: /* no own input buffer to flush */ break; case TCIOFLUSH: case TCOFLUSH: flush_send_queue(cs); break; } /* Pass through */ default: /* pass through to underlying serial device */ rc = n_tty_ioctl_helper(tty, file, cmd, arg); break; } cs_put(cs); return rc; } /* * Called by the tty driver when a block of data has been received. * Will not be re-entered while running but other ldisc functions * may be called in parallel. * Can be called from hard interrupt level as well as soft interrupt * level or mainline. * Parameters: * tty tty structure * buf buffer containing received characters * cflags buffer containing error flags for received characters (ignored) * count number of received characters */ static void gigaset_tty_receive(struct tty_struct *tty, const unsigned char *buf, char *cflags, int count) { struct cardstate *cs = cs_get(tty); unsigned tail, head, n; struct inbuf_t *inbuf; if (!cs) return; inbuf = cs->inbuf; if (!inbuf) { dev_err(cs->dev, "%s: no inbuf\n", __func__); cs_put(cs); return; } tail = inbuf->tail; head = inbuf->head; gig_dbg(DEBUG_INTR, "buffer state: %u -> %u, receive %u bytes", head, tail, count); if (head <= tail) { /* possible buffer wraparound */ n = min_t(unsigned, count, RBUFSIZE - tail); memcpy(inbuf->data + tail, buf, n); tail = (tail + n) % RBUFSIZE; buf += n; count -= n; } if (count > 0) { /* tail < head and some data left */ n = head - tail - 1; if (count > n) { dev_err(cs->dev, "inbuf overflow, discarding %d bytes\n", count - n); count = n; } memcpy(inbuf->data + tail, buf, count); tail += count; } gig_dbg(DEBUG_INTR, "setting tail to %u", tail); inbuf->tail = tail; /* Everything was received .. Push data into handler */ gig_dbg(DEBUG_INTR, "%s-->BH", __func__); gigaset_schedule_event(cs); cs_put(cs); } /* * Called by the tty driver when there's room for more data to send. */ static void gigaset_tty_wakeup(struct tty_struct *tty) { struct cardstate *cs = cs_get(tty); clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); if (!cs) return; tasklet_schedule(&cs->write_tasklet); cs_put(cs); } static struct tty_ldisc_ops gigaset_ldisc = { .owner = THIS_MODULE, .magic = TTY_LDISC_MAGIC, .name = "ser_gigaset", .open = gigaset_tty_open, .close = gigaset_tty_close, .hangup = gigaset_tty_hangup, .read = gigaset_tty_read, .write = gigaset_tty_write, .ioctl = gigaset_tty_ioctl, .receive_buf = gigaset_tty_receive, .write_wakeup = gigaset_tty_wakeup, }; /* Initialization / Shutdown */ /* ========================= */ static int __init ser_gigaset_init(void) { int rc; gig_dbg(DEBUG_INIT, "%s", __func__); rc = platform_driver_register(&device_driver); if (rc != 0) { pr_err("error %d registering platform driver\n", rc); return rc; } /* allocate memory for our driver state and initialize it */ driver = gigaset_initdriver(GIGASET_MINOR, GIGASET_MINORS, GIGASET_MODULENAME, GIGASET_DEVNAME, &ops, THIS_MODULE); if (!driver) goto error; rc = tty_register_ldisc(N_GIGASET_M101, &gigaset_ldisc); if (rc != 0) { pr_err("error %d registering line discipline\n", rc); goto error; } return 0; error: if (driver) { gigaset_freedriver(driver); driver = NULL; } platform_driver_unregister(&device_driver); return rc; } static void __exit ser_gigaset_exit(void) { int rc; gig_dbg(DEBUG_INIT, "%s", __func__); if (driver) { gigaset_freedriver(driver); driver = NULL; } rc = tty_unregister_ldisc(N_GIGASET_M101); if (rc != 0) pr_err("error %d unregistering line discipline\n", rc); platform_driver_unregister(&device_driver); } module_init(ser_gigaset_init); module_exit(ser_gigaset_exit);
gpl-3.0
chuncky/nuc900kernel
linux-2.6.35.4/drivers/macintosh/macio_asic.c
902
20791
/* * Bus & driver management routines for devices within * a MacIO ASIC. Interface to new driver model mostly * stolen from the PCI version. * * Copyright (C) 2005 Ben. Herrenschmidt (benh@kernel.crashing.org) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * TODO: * * - Don't probe below media bay by default, but instead provide * some hooks for media bay to dynamically add/remove it's own * sub-devices. */ #include <linux/string.h> #include <linux/kernel.h> #include <linux/pci.h> #include <linux/pci_ids.h> #include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <asm/machdep.h> #include <asm/macio.h> #include <asm/pmac_feature.h> #include <asm/prom.h> #include <asm/pci-bridge.h> #undef DEBUG #define MAX_NODE_NAME_SIZE (20 - 12) static struct macio_chip *macio_on_hold; static int macio_bus_match(struct device *dev, struct device_driver *drv) { const struct of_device_id * matches = drv->of_match_table; if (!matches) return 0; return of_match_device(matches, dev) != NULL; } struct macio_dev *macio_dev_get(struct macio_dev *dev) { struct device *tmp; if (!dev) return NULL; tmp = get_device(&dev->ofdev.dev); if (tmp) return to_macio_device(tmp); else return NULL; } void macio_dev_put(struct macio_dev *dev) { if (dev) put_device(&dev->ofdev.dev); } static int macio_device_probe(struct device *dev) { int error = -ENODEV; struct macio_driver *drv; struct macio_dev *macio_dev; const struct of_device_id *match; drv = to_macio_driver(dev->driver); macio_dev = to_macio_device(dev); if (!drv->probe) return error; macio_dev_get(macio_dev); match = of_match_device(drv->driver.of_match_table, dev); if (match) error = drv->probe(macio_dev, match); if (error) macio_dev_put(macio_dev); return error; } static int macio_device_remove(struct device *dev) { struct macio_dev * macio_dev = to_macio_device(dev); struct macio_driver * drv = to_macio_driver(dev->driver); if (dev->driver && drv->remove) drv->remove(macio_dev); macio_dev_put(macio_dev); return 0; } static void macio_device_shutdown(struct device *dev) { struct macio_dev * macio_dev = to_macio_device(dev); struct macio_driver * drv = to_macio_driver(dev->driver); if (dev->driver && drv->shutdown) drv->shutdown(macio_dev); } static int macio_device_suspend(struct device *dev, pm_message_t state) { struct macio_dev * macio_dev = to_macio_device(dev); struct macio_driver * drv = to_macio_driver(dev->driver); if (dev->driver && drv->suspend) return drv->suspend(macio_dev, state); return 0; } static int macio_device_resume(struct device * dev) { struct macio_dev * macio_dev = to_macio_device(dev); struct macio_driver * drv = to_macio_driver(dev->driver); if (dev->driver && drv->resume) return drv->resume(macio_dev); return 0; } extern struct device_attribute macio_dev_attrs[]; struct bus_type macio_bus_type = { .name = "macio", .match = macio_bus_match, .uevent = of_device_uevent, .probe = macio_device_probe, .remove = macio_device_remove, .shutdown = macio_device_shutdown, .suspend = macio_device_suspend, .resume = macio_device_resume, .dev_attrs = macio_dev_attrs, }; static int __init macio_bus_driver_init(void) { return bus_register(&macio_bus_type); } postcore_initcall(macio_bus_driver_init); /** * macio_release_dev - free a macio device structure when all users of it are * finished. * @dev: device that's been disconnected * * Will be called only by the device core when all users of this macio device * are done. This currently means never as we don't hot remove any macio * device yet, though that will happen with mediabay based devices in a later * implementation. */ static void macio_release_dev(struct device *dev) { struct macio_dev *mdev; mdev = to_macio_device(dev); kfree(mdev); } /** * macio_resource_quirks - tweak or skip some resources for a device * @np: pointer to the device node * @res: resulting resource * @index: index of resource in node * * If this routine returns non-null, then the resource is completely * skipped. */ static int macio_resource_quirks(struct device_node *np, struct resource *res, int index) { /* Only quirks for memory resources for now */ if ((res->flags & IORESOURCE_MEM) == 0) return 0; /* Grand Central has too large resource 0 on some machines */ if (index == 0 && !strcmp(np->name, "gc")) res->end = res->start + 0x1ffff; /* Airport has bogus resource 2 */ if (index >= 2 && !strcmp(np->name, "radio")) return 1; #ifndef CONFIG_PPC64 /* DBDMAs may have bogus sizes */ if ((res->start & 0x0001f000) == 0x00008000) res->end = res->start + 0xff; #endif /* CONFIG_PPC64 */ /* ESCC parent eats child resources. We could have added a * level of hierarchy, but I don't really feel the need * for it */ if (!strcmp(np->name, "escc")) return 1; /* ESCC has bogus resources >= 3 */ if (index >= 3 && !(strcmp(np->name, "ch-a") && strcmp(np->name, "ch-b"))) return 1; /* Media bay has too many resources, keep only first one */ if (index > 0 && !strcmp(np->name, "media-bay")) return 1; /* Some older IDE resources have bogus sizes */ if (!(strcmp(np->name, "IDE") && strcmp(np->name, "ATA") && strcmp(np->type, "ide") && strcmp(np->type, "ata"))) { if (index == 0 && (res->end - res->start) > 0xfff) res->end = res->start + 0xfff; if (index == 1 && (res->end - res->start) > 0xff) res->end = res->start + 0xff; } return 0; } static void macio_create_fixup_irq(struct macio_dev *dev, int index, unsigned int line) { unsigned int irq; irq = irq_create_mapping(NULL, line); if (irq != NO_IRQ) { dev->interrupt[index].start = irq; dev->interrupt[index].flags = IORESOURCE_IRQ; dev->interrupt[index].name = dev_name(&dev->ofdev.dev); } if (dev->n_interrupts <= index) dev->n_interrupts = index + 1; } static void macio_add_missing_resources(struct macio_dev *dev) { struct device_node *np = dev->ofdev.dev.of_node; unsigned int irq_base; /* Gatwick has some missing interrupts on child nodes */ if (dev->bus->chip->type != macio_gatwick) return; /* irq_base is always 64 on gatwick. I have no cleaner way to get * that value from here at this point */ irq_base = 64; /* Fix SCC */ if (strcmp(np->name, "ch-a") == 0) { macio_create_fixup_irq(dev, 0, 15 + irq_base); macio_create_fixup_irq(dev, 1, 4 + irq_base); macio_create_fixup_irq(dev, 2, 5 + irq_base); printk(KERN_INFO "macio: fixed SCC irqs on gatwick\n"); } /* Fix media-bay */ if (strcmp(np->name, "media-bay") == 0) { macio_create_fixup_irq(dev, 0, 29 + irq_base); printk(KERN_INFO "macio: fixed media-bay irq on gatwick\n"); } /* Fix left media bay childs */ if (dev->media_bay != NULL && strcmp(np->name, "floppy") == 0) { macio_create_fixup_irq(dev, 0, 19 + irq_base); macio_create_fixup_irq(dev, 1, 1 + irq_base); printk(KERN_INFO "macio: fixed left floppy irqs\n"); } if (dev->media_bay != NULL && strcasecmp(np->name, "ata4") == 0) { macio_create_fixup_irq(dev, 0, 14 + irq_base); macio_create_fixup_irq(dev, 0, 3 + irq_base); printk(KERN_INFO "macio: fixed left ide irqs\n"); } } static void macio_setup_interrupts(struct macio_dev *dev) { struct device_node *np = dev->ofdev.dev.of_node; unsigned int irq; int i = 0, j = 0; for (;;) { struct resource *res; if (j >= MACIO_DEV_COUNT_IRQS) break; res = &dev->interrupt[j]; irq = irq_of_parse_and_map(np, i++); if (irq == NO_IRQ) break; res->start = irq; res->flags = IORESOURCE_IRQ; res->name = dev_name(&dev->ofdev.dev); if (macio_resource_quirks(np, res, i - 1)) { memset(res, 0, sizeof(struct resource)); continue; } else j++; } dev->n_interrupts = j; } static void macio_setup_resources(struct macio_dev *dev, struct resource *parent_res) { struct device_node *np = dev->ofdev.dev.of_node; struct resource r; int index; for (index = 0; of_address_to_resource(np, index, &r) == 0; index++) { struct resource *res; if (index >= MACIO_DEV_COUNT_RESOURCES) break; res = &dev->resource[index]; *res = r; res->name = dev_name(&dev->ofdev.dev); if (macio_resource_quirks(np, res, index)) { memset(res, 0, sizeof(struct resource)); continue; } /* Currently, we consider failure as harmless, this may * change in the future, once I've found all the device * tree bugs in older machines & worked around them */ if (insert_resource(parent_res, res)) { printk(KERN_WARNING "Can't request resource " "%d for MacIO device %s\n", index, dev_name(&dev->ofdev.dev)); } } dev->n_resources = index; } /** * macio_add_one_device - Add one device from OF node to the device tree * @chip: pointer to the macio_chip holding the device * @np: pointer to the device node in the OF tree * @in_bay: set to 1 if device is part of a media-bay * * When media-bay is changed to hotswap drivers, this function will * be exposed to the bay driver some way... */ static struct macio_dev * macio_add_one_device(struct macio_chip *chip, struct device *parent, struct device_node *np, struct macio_dev *in_bay, struct resource *parent_res) { struct macio_dev *dev; const u32 *reg; if (np == NULL) return NULL; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return NULL; dev->bus = &chip->lbus; dev->media_bay = in_bay; dev->ofdev.dev.of_node = np; dev->ofdev.archdata.dma_mask = 0xffffffffUL; dev->ofdev.dev.dma_mask = &dev->ofdev.archdata.dma_mask; dev->ofdev.dev.parent = parent; dev->ofdev.dev.bus = &macio_bus_type; dev->ofdev.dev.release = macio_release_dev; dev->ofdev.dev.dma_parms = &dev->dma_parms; /* Standard DMA paremeters */ dma_set_max_seg_size(&dev->ofdev.dev, 65536); dma_set_seg_boundary(&dev->ofdev.dev, 0xffffffff); #ifdef CONFIG_PCI /* Set the DMA ops to the ones from the PCI device, this could be * fishy if we didn't know that on PowerMac it's always direct ops * or iommu ops that will work fine */ dev->ofdev.dev.archdata.dma_ops = chip->lbus.pdev->dev.archdata.dma_ops; dev->ofdev.dev.archdata.dma_data = chip->lbus.pdev->dev.archdata.dma_data; #endif /* CONFIG_PCI */ #ifdef DEBUG printk("preparing mdev @%p, ofdev @%p, dev @%p, kobj @%p\n", dev, &dev->ofdev, &dev->ofdev.dev, &dev->ofdev.dev.kobj); #endif /* MacIO itself has a different reg, we use it's PCI base */ if (np == chip->of_node) { dev_set_name(&dev->ofdev.dev, "%1d.%08x:%.*s", chip->lbus.index, #ifdef CONFIG_PCI (unsigned int)pci_resource_start(chip->lbus.pdev, 0), #else 0, /* NuBus may want to do something better here */ #endif MAX_NODE_NAME_SIZE, np->name); } else { reg = of_get_property(np, "reg", NULL); dev_set_name(&dev->ofdev.dev, "%1d.%08x:%.*s", chip->lbus.index, reg ? *reg : 0, MAX_NODE_NAME_SIZE, np->name); } /* Setup interrupts & resources */ macio_setup_interrupts(dev); macio_setup_resources(dev, parent_res); macio_add_missing_resources(dev); /* Register with core */ if (of_device_register(&dev->ofdev) != 0) { printk(KERN_DEBUG"macio: device registration error for %s!\n", dev_name(&dev->ofdev.dev)); kfree(dev); return NULL; } return dev; } static int macio_skip_device(struct device_node *np) { if (strncmp(np->name, "battery", 7) == 0) return 1; if (strncmp(np->name, "escc-legacy", 11) == 0) return 1; return 0; } /** * macio_pci_add_devices - Adds sub-devices of mac-io to the device tree * @chip: pointer to the macio_chip holding the devices * * This function will do the job of extracting devices from the * Open Firmware device tree, build macio_dev structures and add * them to the Linux device tree. * * For now, childs of media-bay are added now as well. This will * change rsn though. */ static void macio_pci_add_devices(struct macio_chip *chip) { struct device_node *np, *pnode; struct macio_dev *rdev, *mdev, *mbdev = NULL, *sdev = NULL; struct device *parent = NULL; struct resource *root_res = &iomem_resource; /* Add a node for the macio bus itself */ #ifdef CONFIG_PCI if (chip->lbus.pdev) { parent = &chip->lbus.pdev->dev; root_res = &chip->lbus.pdev->resource[0]; } #endif pnode = of_node_get(chip->of_node); if (pnode == NULL) return; /* Add macio itself to hierarchy */ rdev = macio_add_one_device(chip, parent, pnode, NULL, root_res); if (rdev == NULL) return; root_res = &rdev->resource[0]; /* First scan 1st level */ for (np = NULL; (np = of_get_next_child(pnode, np)) != NULL;) { if (macio_skip_device(np)) continue; of_node_get(np); mdev = macio_add_one_device(chip, &rdev->ofdev.dev, np, NULL, root_res); if (mdev == NULL) of_node_put(np); else if (strncmp(np->name, "media-bay", 9) == 0) mbdev = mdev; else if (strncmp(np->name, "escc", 4) == 0) sdev = mdev; } /* Add media bay devices if any */ if (mbdev) { pnode = mbdev->ofdev.dev.of_node; for (np = NULL; (np = of_get_next_child(pnode, np)) != NULL;) { if (macio_skip_device(np)) continue; of_node_get(np); if (macio_add_one_device(chip, &mbdev->ofdev.dev, np, mbdev, root_res) == NULL) of_node_put(np); } } /* Add serial ports if any */ if (sdev) { pnode = sdev->ofdev.dev.of_node; for (np = NULL; (np = of_get_next_child(pnode, np)) != NULL;) { if (macio_skip_device(np)) continue; of_node_get(np); if (macio_add_one_device(chip, &sdev->ofdev.dev, np, NULL, root_res) == NULL) of_node_put(np); } } } /** * macio_register_driver - Registers a new MacIO device driver * @drv: pointer to the driver definition structure */ int macio_register_driver(struct macio_driver *drv) { /* initialize common driver fields */ drv->driver.bus = &macio_bus_type; /* register with core */ return driver_register(&drv->driver); } /** * macio_unregister_driver - Unregisters a new MacIO device driver * @drv: pointer to the driver definition structure */ void macio_unregister_driver(struct macio_driver *drv) { driver_unregister(&drv->driver); } /* Managed MacIO resources */ struct macio_devres { u32 res_mask; }; static void maciom_release(struct device *gendev, void *res) { struct macio_dev *dev = to_macio_device(gendev); struct macio_devres *dr = res; int i, max; max = min(dev->n_resources, 32); for (i = 0; i < max; i++) { if (dr->res_mask & (1 << i)) macio_release_resource(dev, i); } } int macio_enable_devres(struct macio_dev *dev) { struct macio_devres *dr; dr = devres_find(&dev->ofdev.dev, maciom_release, NULL, NULL); if (!dr) { dr = devres_alloc(maciom_release, sizeof(*dr), GFP_KERNEL); if (!dr) return -ENOMEM; } return devres_get(&dev->ofdev.dev, dr, NULL, NULL) != NULL; } static struct macio_devres * find_macio_dr(struct macio_dev *dev) { return devres_find(&dev->ofdev.dev, maciom_release, NULL, NULL); } /** * macio_request_resource - Request an MMIO resource * @dev: pointer to the device holding the resource * @resource_no: resource number to request * @name: resource name * * Mark memory region number @resource_no associated with MacIO * device @dev as being reserved by owner @name. Do not access * any address inside the memory regions unless this call returns * successfully. * * Returns 0 on success, or %EBUSY on error. A warning * message is also printed on failure. */ int macio_request_resource(struct macio_dev *dev, int resource_no, const char *name) { struct macio_devres *dr = find_macio_dr(dev); if (macio_resource_len(dev, resource_no) == 0) return 0; if (!request_mem_region(macio_resource_start(dev, resource_no), macio_resource_len(dev, resource_no), name)) goto err_out; if (dr && resource_no < 32) dr->res_mask |= 1 << resource_no; return 0; err_out: printk (KERN_WARNING "MacIO: Unable to reserve resource #%d:%lx@%lx" " for device %s\n", resource_no, macio_resource_len(dev, resource_no), macio_resource_start(dev, resource_no), dev_name(&dev->ofdev.dev)); return -EBUSY; } /** * macio_release_resource - Release an MMIO resource * @dev: pointer to the device holding the resource * @resource_no: resource number to release */ void macio_release_resource(struct macio_dev *dev, int resource_no) { struct macio_devres *dr = find_macio_dr(dev); if (macio_resource_len(dev, resource_no) == 0) return; release_mem_region(macio_resource_start(dev, resource_no), macio_resource_len(dev, resource_no)); if (dr && resource_no < 32) dr->res_mask &= ~(1 << resource_no); } /** * macio_request_resources - Reserve all memory resources * @dev: MacIO device whose resources are to be reserved * @name: Name to be associated with resource. * * Mark all memory regions associated with MacIO device @dev as * being reserved by owner @name. Do not access any address inside * the memory regions unless this call returns successfully. * * Returns 0 on success, or %EBUSY on error. A warning * message is also printed on failure. */ int macio_request_resources(struct macio_dev *dev, const char *name) { int i; for (i = 0; i < dev->n_resources; i++) if (macio_request_resource(dev, i, name)) goto err_out; return 0; err_out: while(--i >= 0) macio_release_resource(dev, i); return -EBUSY; } /** * macio_release_resources - Release reserved memory resources * @dev: MacIO device whose resources were previously reserved */ void macio_release_resources(struct macio_dev *dev) { int i; for (i = 0; i < dev->n_resources; i++) macio_release_resource(dev, i); } #ifdef CONFIG_PCI static int __devinit macio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct device_node* np; struct macio_chip* chip; if (ent->vendor != PCI_VENDOR_ID_APPLE) return -ENODEV; /* Note regarding refcounting: We assume pci_device_to_OF_node() is * ported to new OF APIs and returns a node with refcount incremented. */ np = pci_device_to_OF_node(pdev); if (np == NULL) return -ENODEV; /* The above assumption is wrong !!! * fix that here for now until I fix the arch code */ of_node_get(np); /* We also assume that pmac_feature will have done a get() on nodes * stored in the macio chips array */ chip = macio_find(np, macio_unknown); of_node_put(np); if (chip == NULL) return -ENODEV; /* XXX Need locking ??? */ if (chip->lbus.pdev == NULL) { chip->lbus.pdev = pdev; chip->lbus.chip = chip; pci_set_drvdata(pdev, &chip->lbus); pci_set_master(pdev); } printk(KERN_INFO "MacIO PCI driver attached to %s chipset\n", chip->name); /* * HACK ALERT: The WallStreet PowerBook and some OHare based machines * have 2 macio ASICs. I must probe the "main" one first or IDE * ordering will be incorrect. So I put on "hold" the second one since * it seem to appear first on PCI */ if (chip->type == macio_gatwick || chip->type == macio_ohareII) if (macio_chips[0].lbus.pdev == NULL) { macio_on_hold = chip; return 0; } macio_pci_add_devices(chip); if (macio_on_hold && macio_chips[0].lbus.pdev != NULL) { macio_pci_add_devices(macio_on_hold); macio_on_hold = NULL; } return 0; } static void __devexit macio_pci_remove(struct pci_dev* pdev) { panic("removing of macio-asic not supported !\n"); } /* * MacIO is matched against any Apple ID, it's probe() function * will then decide wether it applies or not */ static const struct pci_device_id __devinitdata pci_ids [] = { { .vendor = PCI_VENDOR_ID_APPLE, .device = PCI_ANY_ID, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, }, { /* end: all zeroes */ } }; MODULE_DEVICE_TABLE (pci, pci_ids); /* pci driver glue; this is a "new style" PCI driver module */ static struct pci_driver macio_pci_driver = { .name = (char *) "macio", .id_table = pci_ids, .probe = macio_pci_probe, .remove = macio_pci_remove, }; #endif /* CONFIG_PCI */ static int __init macio_module_init (void) { #ifdef CONFIG_PCI int rc; rc = pci_register_driver(&macio_pci_driver); if (rc) return rc; #endif /* CONFIG_PCI */ return 0; } module_init(macio_module_init); EXPORT_SYMBOL(macio_register_driver); EXPORT_SYMBOL(macio_unregister_driver); EXPORT_SYMBOL(macio_dev_get); EXPORT_SYMBOL(macio_dev_put); EXPORT_SYMBOL(macio_request_resource); EXPORT_SYMBOL(macio_release_resource); EXPORT_SYMBOL(macio_request_resources); EXPORT_SYMBOL(macio_release_resources); EXPORT_SYMBOL(macio_enable_devres);
gpl-3.0
teil3/MarlinTeilmachr503
ArduinoAddons/Arduino_1.5.x/hardware/marlin/avr/libraries/U8glib/utility/u8g_com_io.c
412
4275
/* u8g_com_io.c abstraction layer for low level i/o Universal 8bit Graphics Library Copyright (c) 2012, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "u8g.h" #if defined(__AVR__) #include <avr/interrupt.h> #include <avr/io.h> typedef volatile uint8_t * IO_PTR; /* create internal pin number */ uint8_t u8g_Pin(uint8_t port, uint8_t bitpos) { port <<= 3; port += bitpos; return port; } const IO_PTR u8g_avr_ddr_P[] PROGMEM = { #ifdef DDRA &DDRA, #else 0, #endif &DDRB, #ifdef DDRC &DDRC, #ifdef DDRD &DDRD, #ifdef DDRE &DDRE, #ifdef DDRF &DDRF, #ifdef DDRG &DDRG, #ifdef DDRH &DDRH, #endif #endif #endif #endif #endif #endif }; const IO_PTR u8g_avr_port_P[] PROGMEM = { #ifdef PORTA &PORTA, #else 0, #endif &PORTB, #ifdef PORTC &PORTC, #ifdef PORTD &PORTD, #ifdef PORTE &PORTE, #ifdef PORTF &PORTF, #ifdef PORTG &PORTG, #ifdef PORTH &PORTH, #endif #endif #endif #endif #endif #endif }; const IO_PTR u8g_avr_pin_P[] PROGMEM = { #ifdef PINA &PINA, #else 0, #endif &PINB, #ifdef PINC &PINC, #ifdef PIND &PIND, #ifdef PINE &PINE, #ifdef PINF &PINF, #ifdef PING &PING, #ifdef PINH &PINH, #endif #endif #endif #endif #endif #endif }; static volatile uint8_t *u8g_get_avr_io_ptr(const IO_PTR *base, uint8_t offset) { volatile uint8_t * tmp; base += offset; memcpy_P(&tmp, base, sizeof(volatile uint8_t * PROGMEM)); return tmp; } /* set direction to output of the specified pin (internal pin number) */ void u8g_SetPinOutput(uint8_t internal_pin_number) { *u8g_get_avr_io_ptr(u8g_avr_ddr_P, internal_pin_number>>3) |= _BV(internal_pin_number&7); } void u8g_SetPinInput(uint8_t internal_pin_number) { *u8g_get_avr_io_ptr(u8g_avr_ddr_P, internal_pin_number>>3) &= ~_BV(internal_pin_number&7); } void u8g_SetPinLevel(uint8_t internal_pin_number, uint8_t level) { volatile uint8_t * tmp = u8g_get_avr_io_ptr(u8g_avr_port_P, internal_pin_number>>3); if ( level == 0 ) *tmp &= ~_BV(internal_pin_number&7); else *tmp |= _BV(internal_pin_number&7); } uint8_t u8g_GetPinLevel(uint8_t internal_pin_number) { volatile uint8_t * tmp = u8g_get_avr_io_ptr(u8g_avr_pin_P, internal_pin_number>>3); if ( ((*tmp) & _BV(internal_pin_number&7)) != 0 ) return 1; return 0; } #else uint8_t u8g_Pin(uint8_t port, uint8_t bitpos) { port <<= 3; port += bitpos; return port; } void u8g_SetPinOutput(uint8_t internal_pin_number) { } void u8g_SetPinInput(uint8_t internal_pin_number) { } void u8g_SetPinLevel(uint8_t internal_pin_number, uint8_t level) { } uint8_t u8g_GetPinLevel(uint8_t internal_pin_number) { return 0; } #endif void u8g_SetPIOutput(u8g_t *u8g, uint8_t pi) { uint8_t pin; pin = u8g->pin_list[pi]; if ( pin != U8G_PIN_NONE ) u8g_SetPinOutput(pin); } void u8g_SetPILevel(u8g_t *u8g, uint8_t pi, uint8_t level) { uint8_t pin; pin = u8g->pin_list[pi]; if ( pin != U8G_PIN_NONE ) u8g_SetPinLevel(pin, level); }
gpl-3.0
xwv/shadowsocks-android
src/main/jni/openssl/crypto/ui/ui_lib.c
681
20587
/* crypto/ui/ui_lib.c -*- mode:C; c-file-style: "eay" -*- */ /* Written by Richard Levitte (richard@levitte.org) for the OpenSSL * project 2001. */ /* ==================================================================== * 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 * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <string.h> #include "cryptlib.h" #include <openssl/e_os2.h> #include <openssl/buffer.h> #include <openssl/ui.h> #include <openssl/err.h> #include "ui_locl.h" IMPLEMENT_STACK_OF(UI_STRING_ST) static const UI_METHOD *default_UI_meth=NULL; UI *UI_new(void) { return(UI_new_method(NULL)); } UI *UI_new_method(const UI_METHOD *method) { UI *ret; ret=(UI *)OPENSSL_malloc(sizeof(UI)); if (ret == NULL) { UIerr(UI_F_UI_NEW_METHOD,ERR_R_MALLOC_FAILURE); return NULL; } if (method == NULL) ret->meth=UI_get_default_method(); else ret->meth=method; ret->strings=NULL; ret->user_data=NULL; ret->flags=0; CRYPTO_new_ex_data(CRYPTO_EX_INDEX_UI, ret, &ret->ex_data); return ret; } static void free_string(UI_STRING *uis) { if (uis->flags & OUT_STRING_FREEABLE) { OPENSSL_free((char *)uis->out_string); switch(uis->type) { case UIT_BOOLEAN: OPENSSL_free((char *)uis->_.boolean_data.action_desc); OPENSSL_free((char *)uis->_.boolean_data.ok_chars); OPENSSL_free((char *)uis->_.boolean_data.cancel_chars); break; default: break; } } OPENSSL_free(uis); } void UI_free(UI *ui) { if (ui == NULL) return; sk_UI_STRING_pop_free(ui->strings,free_string); CRYPTO_free_ex_data(CRYPTO_EX_INDEX_UI, ui, &ui->ex_data); OPENSSL_free(ui); } static int allocate_string_stack(UI *ui) { if (ui->strings == NULL) { ui->strings=sk_UI_STRING_new_null(); if (ui->strings == NULL) { return -1; } } return 0; } static UI_STRING *general_allocate_prompt(UI *ui, const char *prompt, int prompt_freeable, enum UI_string_types type, int input_flags, char *result_buf) { UI_STRING *ret = NULL; if (prompt == NULL) { UIerr(UI_F_GENERAL_ALLOCATE_PROMPT,ERR_R_PASSED_NULL_PARAMETER); } else if ((type == UIT_PROMPT || type == UIT_VERIFY || type == UIT_BOOLEAN) && result_buf == NULL) { UIerr(UI_F_GENERAL_ALLOCATE_PROMPT,UI_R_NO_RESULT_BUFFER); } else if ((ret = (UI_STRING *)OPENSSL_malloc(sizeof(UI_STRING)))) { ret->out_string=prompt; ret->flags=prompt_freeable ? OUT_STRING_FREEABLE : 0; ret->input_flags=input_flags; ret->type=type; ret->result_buf=result_buf; } return ret; } static int general_allocate_string(UI *ui, const char *prompt, int prompt_freeable, enum UI_string_types type, int input_flags, char *result_buf, int minsize, int maxsize, const char *test_buf) { int ret = -1; UI_STRING *s = general_allocate_prompt(ui, prompt, prompt_freeable, type, input_flags, result_buf); if (s) { if (allocate_string_stack(ui) >= 0) { s->_.string_data.result_minsize=minsize; s->_.string_data.result_maxsize=maxsize; s->_.string_data.test_buf=test_buf; ret=sk_UI_STRING_push(ui->strings, s); /* sk_push() returns 0 on error. Let's addapt that */ if (ret <= 0) ret--; } else free_string(s); } return ret; } static int general_allocate_boolean(UI *ui, const char *prompt, const char *action_desc, const char *ok_chars, const char *cancel_chars, int prompt_freeable, enum UI_string_types type, int input_flags, char *result_buf) { int ret = -1; UI_STRING *s; const char *p; if (ok_chars == NULL) { UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN,ERR_R_PASSED_NULL_PARAMETER); } else if (cancel_chars == NULL) { UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN,ERR_R_PASSED_NULL_PARAMETER); } else { for(p = ok_chars; *p; p++) { if (strchr(cancel_chars, *p)) { UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN, UI_R_COMMON_OK_AND_CANCEL_CHARACTERS); } } s = general_allocate_prompt(ui, prompt, prompt_freeable, type, input_flags, result_buf); if (s) { if (allocate_string_stack(ui) >= 0) { s->_.boolean_data.action_desc = action_desc; s->_.boolean_data.ok_chars = ok_chars; s->_.boolean_data.cancel_chars = cancel_chars; ret=sk_UI_STRING_push(ui->strings, s); /* sk_push() returns 0 on error. Let's addapt that */ if (ret <= 0) ret--; } else free_string(s); } } return ret; } /* Returns the index to the place in the stack or -1 for error. Uses a direct reference to the prompt. */ int UI_add_input_string(UI *ui, const char *prompt, int flags, char *result_buf, int minsize, int maxsize) { return general_allocate_string(ui, prompt, 0, UIT_PROMPT, flags, result_buf, minsize, maxsize, NULL); } /* Same as UI_add_input_string(), excepts it takes a copy of the prompt */ int UI_dup_input_string(UI *ui, const char *prompt, int flags, char *result_buf, int minsize, int maxsize) { char *prompt_copy=NULL; if (prompt) { prompt_copy=BUF_strdup(prompt); if (prompt_copy == NULL) { UIerr(UI_F_UI_DUP_INPUT_STRING,ERR_R_MALLOC_FAILURE); return 0; } } return general_allocate_string(ui, prompt_copy, 1, UIT_PROMPT, flags, result_buf, minsize, maxsize, NULL); } int UI_add_verify_string(UI *ui, const char *prompt, int flags, char *result_buf, int minsize, int maxsize, const char *test_buf) { return general_allocate_string(ui, prompt, 0, UIT_VERIFY, flags, result_buf, minsize, maxsize, test_buf); } int UI_dup_verify_string(UI *ui, const char *prompt, int flags, char *result_buf, int minsize, int maxsize, const char *test_buf) { char *prompt_copy=NULL; if (prompt) { prompt_copy=BUF_strdup(prompt); if (prompt_copy == NULL) { UIerr(UI_F_UI_DUP_VERIFY_STRING,ERR_R_MALLOC_FAILURE); return -1; } } return general_allocate_string(ui, prompt_copy, 1, UIT_VERIFY, flags, result_buf, minsize, maxsize, test_buf); } int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc, const char *ok_chars, const char *cancel_chars, int flags, char *result_buf) { return general_allocate_boolean(ui, prompt, action_desc, ok_chars, cancel_chars, 0, UIT_BOOLEAN, flags, result_buf); } int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc, const char *ok_chars, const char *cancel_chars, int flags, char *result_buf) { char *prompt_copy = NULL; char *action_desc_copy = NULL; char *ok_chars_copy = NULL; char *cancel_chars_copy = NULL; if (prompt) { prompt_copy=BUF_strdup(prompt); if (prompt_copy == NULL) { UIerr(UI_F_UI_DUP_INPUT_BOOLEAN,ERR_R_MALLOC_FAILURE); goto err; } } if (action_desc) { action_desc_copy=BUF_strdup(action_desc); if (action_desc_copy == NULL) { UIerr(UI_F_UI_DUP_INPUT_BOOLEAN,ERR_R_MALLOC_FAILURE); goto err; } } if (ok_chars) { ok_chars_copy=BUF_strdup(ok_chars); if (ok_chars_copy == NULL) { UIerr(UI_F_UI_DUP_INPUT_BOOLEAN,ERR_R_MALLOC_FAILURE); goto err; } } if (cancel_chars) { cancel_chars_copy=BUF_strdup(cancel_chars); if (cancel_chars_copy == NULL) { UIerr(UI_F_UI_DUP_INPUT_BOOLEAN,ERR_R_MALLOC_FAILURE); goto err; } } return general_allocate_boolean(ui, prompt_copy, action_desc_copy, ok_chars_copy, cancel_chars_copy, 1, UIT_BOOLEAN, flags, result_buf); err: if (prompt_copy) OPENSSL_free(prompt_copy); if (action_desc_copy) OPENSSL_free(action_desc_copy); if (ok_chars_copy) OPENSSL_free(ok_chars_copy); if (cancel_chars_copy) OPENSSL_free(cancel_chars_copy); return -1; } int UI_add_info_string(UI *ui, const char *text) { return general_allocate_string(ui, text, 0, UIT_INFO, 0, NULL, 0, 0, NULL); } int UI_dup_info_string(UI *ui, const char *text) { char *text_copy=NULL; if (text) { text_copy=BUF_strdup(text); if (text_copy == NULL) { UIerr(UI_F_UI_DUP_INFO_STRING,ERR_R_MALLOC_FAILURE); return -1; } } return general_allocate_string(ui, text_copy, 1, UIT_INFO, 0, NULL, 0, 0, NULL); } int UI_add_error_string(UI *ui, const char *text) { return general_allocate_string(ui, text, 0, UIT_ERROR, 0, NULL, 0, 0, NULL); } int UI_dup_error_string(UI *ui, const char *text) { char *text_copy=NULL; if (text) { text_copy=BUF_strdup(text); if (text_copy == NULL) { UIerr(UI_F_UI_DUP_ERROR_STRING,ERR_R_MALLOC_FAILURE); return -1; } } return general_allocate_string(ui, text_copy, 1, UIT_ERROR, 0, NULL, 0, 0, NULL); } char *UI_construct_prompt(UI *ui, const char *object_desc, const char *object_name) { char *prompt = NULL; if (ui->meth->ui_construct_prompt) prompt = ui->meth->ui_construct_prompt(ui, object_desc, object_name); else { char prompt1[] = "Enter "; char prompt2[] = " for "; char prompt3[] = ":"; int len = 0; if (object_desc == NULL) return NULL; len = sizeof(prompt1) - 1 + strlen(object_desc); if (object_name) len += sizeof(prompt2) - 1 + strlen(object_name); len += sizeof(prompt3) - 1; prompt = (char *)OPENSSL_malloc(len + 1); BUF_strlcpy(prompt, prompt1, len + 1); BUF_strlcat(prompt, object_desc, len + 1); if (object_name) { BUF_strlcat(prompt, prompt2, len + 1); BUF_strlcat(prompt, object_name, len + 1); } BUF_strlcat(prompt, prompt3, len + 1); } return prompt; } void *UI_add_user_data(UI *ui, void *user_data) { void *old_data = ui->user_data; ui->user_data = user_data; return old_data; } void *UI_get0_user_data(UI *ui) { return ui->user_data; } const char *UI_get0_result(UI *ui, int i) { if (i < 0) { UIerr(UI_F_UI_GET0_RESULT,UI_R_INDEX_TOO_SMALL); return NULL; } if (i >= sk_UI_STRING_num(ui->strings)) { UIerr(UI_F_UI_GET0_RESULT,UI_R_INDEX_TOO_LARGE); return NULL; } return UI_get0_result_string(sk_UI_STRING_value(ui->strings, i)); } static int print_error(const char *str, size_t len, UI *ui) { UI_STRING uis; memset(&uis, 0, sizeof(uis)); uis.type = UIT_ERROR; uis.out_string = str; if (ui->meth->ui_write_string && !ui->meth->ui_write_string(ui, &uis)) return -1; return 0; } int UI_process(UI *ui) { int i, ok=0; if (ui->meth->ui_open_session && !ui->meth->ui_open_session(ui)) return -1; if (ui->flags & UI_FLAG_PRINT_ERRORS) ERR_print_errors_cb( (int (*)(const char *, size_t, void *))print_error, (void *)ui); for(i=0; i<sk_UI_STRING_num(ui->strings); i++) { if (ui->meth->ui_write_string && !ui->meth->ui_write_string(ui, sk_UI_STRING_value(ui->strings, i))) { ok=-1; goto err; } } if (ui->meth->ui_flush) switch(ui->meth->ui_flush(ui)) { case -1: /* Interrupt/Cancel/something... */ ok = -2; goto err; case 0: /* Errors */ ok = -1; goto err; default: /* Success */ ok = 0; break; } for(i=0; i<sk_UI_STRING_num(ui->strings); i++) { if (ui->meth->ui_read_string) { switch(ui->meth->ui_read_string(ui, sk_UI_STRING_value(ui->strings, i))) { case -1: /* Interrupt/Cancel/something... */ ok = -2; goto err; case 0: /* Errors */ ok = -1; goto err; default: /* Success */ ok = 0; break; } } } err: if (ui->meth->ui_close_session && !ui->meth->ui_close_session(ui)) return -1; return ok; } int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f)(void)) { if (ui == NULL) { UIerr(UI_F_UI_CTRL,ERR_R_PASSED_NULL_PARAMETER); return -1; } switch(cmd) { case UI_CTRL_PRINT_ERRORS: { int save_flag = !!(ui->flags & UI_FLAG_PRINT_ERRORS); if (i) ui->flags |= UI_FLAG_PRINT_ERRORS; else ui->flags &= ~UI_FLAG_PRINT_ERRORS; return save_flag; } case UI_CTRL_IS_REDOABLE: return !!(ui->flags & UI_FLAG_REDOABLE); default: break; } UIerr(UI_F_UI_CTRL,UI_R_UNKNOWN_CONTROL_COMMAND); return -1; } int UI_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func) { return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI, argl, argp, new_func, dup_func, free_func); } int UI_set_ex_data(UI *r, int idx, void *arg) { return(CRYPTO_set_ex_data(&r->ex_data,idx,arg)); } void *UI_get_ex_data(UI *r, int idx) { return(CRYPTO_get_ex_data(&r->ex_data,idx)); } void UI_set_default_method(const UI_METHOD *meth) { default_UI_meth=meth; } const UI_METHOD *UI_get_default_method(void) { if (default_UI_meth == NULL) { default_UI_meth=UI_OpenSSL(); } return default_UI_meth; } const UI_METHOD *UI_get_method(UI *ui) { return ui->meth; } const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth) { ui->meth=meth; return ui->meth; } UI_METHOD *UI_create_method(char *name) { UI_METHOD *ui_method = (UI_METHOD *)OPENSSL_malloc(sizeof(UI_METHOD)); if (ui_method) { memset(ui_method, 0, sizeof(*ui_method)); ui_method->name = BUF_strdup(name); } return ui_method; } /* BIG FSCKING WARNING!!!! If you use this on a statically allocated method (that is, it hasn't been allocated using UI_create_method(), you deserve anything Murphy can throw at you and more! You have been warned. */ void UI_destroy_method(UI_METHOD *ui_method) { OPENSSL_free(ui_method->name); ui_method->name = NULL; OPENSSL_free(ui_method); } int UI_method_set_opener(UI_METHOD *method, int (*opener)(UI *ui)) { if (method) { method->ui_open_session = opener; return 0; } else return -1; } int UI_method_set_writer(UI_METHOD *method, int (*writer)(UI *ui, UI_STRING *uis)) { if (method) { method->ui_write_string = writer; return 0; } else return -1; } int UI_method_set_flusher(UI_METHOD *method, int (*flusher)(UI *ui)) { if (method) { method->ui_flush = flusher; return 0; } else return -1; } int UI_method_set_reader(UI_METHOD *method, int (*reader)(UI *ui, UI_STRING *uis)) { if (method) { method->ui_read_string = reader; return 0; } else return -1; } int UI_method_set_closer(UI_METHOD *method, int (*closer)(UI *ui)) { if (method) { method->ui_close_session = closer; return 0; } else return -1; } int UI_method_set_prompt_constructor(UI_METHOD *method, char *(*prompt_constructor)(UI* ui, const char* object_desc, const char* object_name)) { if (method) { method->ui_construct_prompt = prompt_constructor; return 0; } else return -1; } int (*UI_method_get_opener(UI_METHOD *method))(UI*) { if (method) return method->ui_open_session; else return NULL; } int (*UI_method_get_writer(UI_METHOD *method))(UI*,UI_STRING*) { if (method) return method->ui_write_string; else return NULL; } int (*UI_method_get_flusher(UI_METHOD *method))(UI*) { if (method) return method->ui_flush; else return NULL; } int (*UI_method_get_reader(UI_METHOD *method))(UI*,UI_STRING*) { if (method) return method->ui_read_string; else return NULL; } int (*UI_method_get_closer(UI_METHOD *method))(UI*) { if (method) return method->ui_close_session; else return NULL; } char* (*UI_method_get_prompt_constructor(UI_METHOD *method))(UI*, const char*, const char*) { if (method) return method->ui_construct_prompt; else return NULL; } enum UI_string_types UI_get_string_type(UI_STRING *uis) { if (!uis) return UIT_NONE; return uis->type; } int UI_get_input_flags(UI_STRING *uis) { if (!uis) return 0; return uis->input_flags; } const char *UI_get0_output_string(UI_STRING *uis) { if (!uis) return NULL; return uis->out_string; } const char *UI_get0_action_string(UI_STRING *uis) { if (!uis) return NULL; switch(uis->type) { case UIT_PROMPT: case UIT_BOOLEAN: return uis->_.boolean_data.action_desc; default: return NULL; } } const char *UI_get0_result_string(UI_STRING *uis) { if (!uis) return NULL; switch(uis->type) { case UIT_PROMPT: case UIT_VERIFY: return uis->result_buf; default: return NULL; } } const char *UI_get0_test_string(UI_STRING *uis) { if (!uis) return NULL; switch(uis->type) { case UIT_VERIFY: return uis->_.string_data.test_buf; default: return NULL; } } int UI_get_result_minsize(UI_STRING *uis) { if (!uis) return -1; switch(uis->type) { case UIT_PROMPT: case UIT_VERIFY: return uis->_.string_data.result_minsize; default: return -1; } } int UI_get_result_maxsize(UI_STRING *uis) { if (!uis) return -1; switch(uis->type) { case UIT_PROMPT: case UIT_VERIFY: return uis->_.string_data.result_maxsize; default: return -1; } } int UI_set_result(UI *ui, UI_STRING *uis, const char *result) { int l = strlen(result); ui->flags &= ~UI_FLAG_REDOABLE; if (!uis) return -1; switch (uis->type) { case UIT_PROMPT: case UIT_VERIFY: { char number1[DECIMAL_SIZE(uis->_.string_data.result_minsize)+1]; char number2[DECIMAL_SIZE(uis->_.string_data.result_maxsize)+1]; BIO_snprintf(number1, sizeof(number1), "%d", uis->_.string_data.result_minsize); BIO_snprintf(number2, sizeof(number2), "%d", uis->_.string_data.result_maxsize); if (l < uis->_.string_data.result_minsize) { ui->flags |= UI_FLAG_REDOABLE; UIerr(UI_F_UI_SET_RESULT,UI_R_RESULT_TOO_SMALL); ERR_add_error_data(5,"You must type in ", number1," to ",number2," characters"); return -1; } if (l > uis->_.string_data.result_maxsize) { ui->flags |= UI_FLAG_REDOABLE; UIerr(UI_F_UI_SET_RESULT,UI_R_RESULT_TOO_LARGE); ERR_add_error_data(5,"You must type in ", number1," to ",number2," characters"); return -1; } } if (!uis->result_buf) { UIerr(UI_F_UI_SET_RESULT,UI_R_NO_RESULT_BUFFER); return -1; } BUF_strlcpy(uis->result_buf, result, uis->_.string_data.result_maxsize + 1); break; case UIT_BOOLEAN: { const char *p; if (!uis->result_buf) { UIerr(UI_F_UI_SET_RESULT,UI_R_NO_RESULT_BUFFER); return -1; } uis->result_buf[0] = '\0'; for(p = result; *p; p++) { if (strchr(uis->_.boolean_data.ok_chars, *p)) { uis->result_buf[0] = uis->_.boolean_data.ok_chars[0]; break; } if (strchr(uis->_.boolean_data.cancel_chars, *p)) { uis->result_buf[0] = uis->_.boolean_data.cancel_chars[0]; break; } } default: break; } } return 0; }
gpl-3.0
bwrenn/dart-mx6-linux-2.6-imx
mm/frontswap.c
435
13769
/* * Frontswap frontend * * This code provides the generic "frontend" layer to call a matching * "backend" driver implementation of frontswap. See * Documentation/vm/frontswap.txt for more information. * * Copyright (C) 2009-2012 Oracle Corp. All rights reserved. * Author: Dan Magenheimer * * This work is licensed under the terms of the GNU GPL, version 2. */ #include <linux/mman.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/security.h> #include <linux/module.h> #include <linux/debugfs.h> #include <linux/frontswap.h> #include <linux/swapfile.h> /* * frontswap_ops is set by frontswap_register_ops to contain the pointers * to the frontswap "backend" implementation functions. */ static struct frontswap_ops *frontswap_ops __read_mostly; /* * If enabled, frontswap_store will return failure even on success. As * a result, the swap subsystem will always write the page to swap, in * effect converting frontswap into a writethrough cache. In this mode, * there is no direct reduction in swap writes, but a frontswap backend * can unilaterally "reclaim" any pages in use with no data loss, thus * providing increases control over maximum memory usage due to frontswap. */ static bool frontswap_writethrough_enabled __read_mostly; /* * If enabled, the underlying tmem implementation is capable of doing * exclusive gets, so frontswap_load, on a successful tmem_get must * mark the page as no longer in frontswap AND mark it dirty. */ static bool frontswap_tmem_exclusive_gets_enabled __read_mostly; #ifdef CONFIG_DEBUG_FS /* * Counters available via /sys/kernel/debug/frontswap (if debugfs is * properly configured). These are for information only so are not protected * against increment races. */ static u64 frontswap_loads; static u64 frontswap_succ_stores; static u64 frontswap_failed_stores; static u64 frontswap_invalidates; static inline void inc_frontswap_loads(void) { frontswap_loads++; } static inline void inc_frontswap_succ_stores(void) { frontswap_succ_stores++; } static inline void inc_frontswap_failed_stores(void) { frontswap_failed_stores++; } static inline void inc_frontswap_invalidates(void) { frontswap_invalidates++; } #else static inline void inc_frontswap_loads(void) { } static inline void inc_frontswap_succ_stores(void) { } static inline void inc_frontswap_failed_stores(void) { } static inline void inc_frontswap_invalidates(void) { } #endif /* * Due to the asynchronous nature of the backends loading potentially * _after_ the swap system has been activated, we have chokepoints * on all frontswap functions to not call the backend until the backend * has registered. * * Specifically when no backend is registered (nobody called * frontswap_register_ops) all calls to frontswap_init (which is done via * swapon -> enable_swap_info -> frontswap_init) are registered and remembered * (via the setting of need_init bitmap) but fail to create tmem_pools. When a * backend registers with frontswap at some later point the previous * calls to frontswap_init are executed (by iterating over the need_init * bitmap) to create tmem_pools and set the respective poolids. All of that is * guarded by us using atomic bit operations on the 'need_init' bitmap. * * This would not guards us against the user deciding to call swapoff right as * we are calling the backend to initialize (so swapon is in action). * Fortunatly for us, the swapon_mutex has been taked by the callee so we are * OK. The other scenario where calls to frontswap_store (called via * swap_writepage) is racing with frontswap_invalidate_area (called via * swapoff) is again guarded by the swap subsystem. * * While no backend is registered all calls to frontswap_[store|load| * invalidate_area|invalidate_page] are ignored or fail. * * The time between the backend being registered and the swap file system * calling the backend (via the frontswap_* functions) is indeterminate as * frontswap_ops is not atomic_t (or a value guarded by a spinlock). * That is OK as we are comfortable missing some of these calls to the newly * registered backend. * * Obviously the opposite (unloading the backend) must be done after all * the frontswap_[store|load|invalidate_area|invalidate_page] start * ignorning or failing the requests - at which point frontswap_ops * would have to be made in some fashion atomic. */ static DECLARE_BITMAP(need_init, MAX_SWAPFILES); /* * Register operations for frontswap, returning previous thus allowing * detection of multiple backends and possible nesting. */ struct frontswap_ops *frontswap_register_ops(struct frontswap_ops *ops) { struct frontswap_ops *old = frontswap_ops; int i; for (i = 0; i < MAX_SWAPFILES; i++) { if (test_and_clear_bit(i, need_init)) { struct swap_info_struct *sis = swap_info[i]; /* __frontswap_init _should_ have set it! */ if (!sis->frontswap_map) return ERR_PTR(-EINVAL); ops->init(i); } } /* * We MUST have frontswap_ops set _after_ the frontswap_init's * have been called. Otherwise __frontswap_store might fail. Hence * the barrier to make sure compiler does not re-order us. */ barrier(); frontswap_ops = ops; return old; } EXPORT_SYMBOL(frontswap_register_ops); /* * Enable/disable frontswap writethrough (see above). */ void frontswap_writethrough(bool enable) { frontswap_writethrough_enabled = enable; } EXPORT_SYMBOL(frontswap_writethrough); /* * Enable/disable frontswap exclusive gets (see above). */ void frontswap_tmem_exclusive_gets(bool enable) { frontswap_tmem_exclusive_gets_enabled = enable; } EXPORT_SYMBOL(frontswap_tmem_exclusive_gets); /* * Called when a swap device is swapon'd. */ void __frontswap_init(unsigned type, unsigned long *map) { struct swap_info_struct *sis = swap_info[type]; BUG_ON(sis == NULL); /* * p->frontswap is a bitmap that we MUST have to figure out which page * has gone in frontswap. Without it there is no point of continuing. */ if (WARN_ON(!map)) return; /* * Irregardless of whether the frontswap backend has been loaded * before this function or it will be later, we _MUST_ have the * p->frontswap set to something valid to work properly. */ frontswap_map_set(sis, map); if (frontswap_ops) frontswap_ops->init(type); else { BUG_ON(type >= MAX_SWAPFILES); set_bit(type, need_init); } } EXPORT_SYMBOL(__frontswap_init); bool __frontswap_test(struct swap_info_struct *sis, pgoff_t offset) { bool ret = false; if (frontswap_ops && sis->frontswap_map) ret = test_bit(offset, sis->frontswap_map); return ret; } EXPORT_SYMBOL(__frontswap_test); static inline void __frontswap_clear(struct swap_info_struct *sis, pgoff_t offset) { clear_bit(offset, sis->frontswap_map); atomic_dec(&sis->frontswap_pages); } /* * "Store" data from a page to frontswap and associate it with the page's * swaptype and offset. Page must be locked and in the swap cache. * If frontswap already contains a page with matching swaptype and * offset, the frontswap implementation may either overwrite the data and * return success or invalidate the page from frontswap and return failure. */ int __frontswap_store(struct page *page) { int ret = -1, dup = 0; swp_entry_t entry = { .val = page_private(page), }; int type = swp_type(entry); struct swap_info_struct *sis = swap_info[type]; pgoff_t offset = swp_offset(entry); /* * Return if no backend registed. * Don't need to inc frontswap_failed_stores here. */ if (!frontswap_ops) return ret; BUG_ON(!PageLocked(page)); BUG_ON(sis == NULL); if (__frontswap_test(sis, offset)) dup = 1; ret = frontswap_ops->store(type, offset, page); if (ret == 0) { set_bit(offset, sis->frontswap_map); inc_frontswap_succ_stores(); if (!dup) atomic_inc(&sis->frontswap_pages); } else { /* failed dup always results in automatic invalidate of the (older) page from frontswap */ inc_frontswap_failed_stores(); if (dup) { __frontswap_clear(sis, offset); frontswap_ops->invalidate_page(type, offset); } } if (frontswap_writethrough_enabled) /* report failure so swap also writes to swap device */ ret = -1; return ret; } EXPORT_SYMBOL(__frontswap_store); /* * "Get" data from frontswap associated with swaptype and offset that were * specified when the data was put to frontswap and use it to fill the * specified page with data. Page must be locked and in the swap cache. */ int __frontswap_load(struct page *page) { int ret = -1; swp_entry_t entry = { .val = page_private(page), }; int type = swp_type(entry); struct swap_info_struct *sis = swap_info[type]; pgoff_t offset = swp_offset(entry); BUG_ON(!PageLocked(page)); BUG_ON(sis == NULL); /* * __frontswap_test() will check whether there is backend registered */ if (__frontswap_test(sis, offset)) ret = frontswap_ops->load(type, offset, page); if (ret == 0) { inc_frontswap_loads(); if (frontswap_tmem_exclusive_gets_enabled) { SetPageDirty(page); __frontswap_clear(sis, offset); } } return ret; } EXPORT_SYMBOL(__frontswap_load); /* * Invalidate any data from frontswap associated with the specified swaptype * and offset so that a subsequent "get" will fail. */ void __frontswap_invalidate_page(unsigned type, pgoff_t offset) { struct swap_info_struct *sis = swap_info[type]; BUG_ON(sis == NULL); /* * __frontswap_test() will check whether there is backend registered */ if (__frontswap_test(sis, offset)) { frontswap_ops->invalidate_page(type, offset); __frontswap_clear(sis, offset); inc_frontswap_invalidates(); } } EXPORT_SYMBOL(__frontswap_invalidate_page); /* * Invalidate all data from frontswap associated with all offsets for the * specified swaptype. */ void __frontswap_invalidate_area(unsigned type) { struct swap_info_struct *sis = swap_info[type]; if (frontswap_ops) { BUG_ON(sis == NULL); if (sis->frontswap_map == NULL) return; frontswap_ops->invalidate_area(type); atomic_set(&sis->frontswap_pages, 0); bitmap_zero(sis->frontswap_map, sis->max); } clear_bit(type, need_init); } EXPORT_SYMBOL(__frontswap_invalidate_area); static unsigned long __frontswap_curr_pages(void) { unsigned long totalpages = 0; struct swap_info_struct *si = NULL; assert_spin_locked(&swap_lock); plist_for_each_entry(si, &swap_active_head, list) totalpages += atomic_read(&si->frontswap_pages); return totalpages; } static int __frontswap_unuse_pages(unsigned long total, unsigned long *unused, int *swapid) { int ret = -EINVAL; struct swap_info_struct *si = NULL; int si_frontswap_pages; unsigned long total_pages_to_unuse = total; unsigned long pages = 0, pages_to_unuse = 0; assert_spin_locked(&swap_lock); plist_for_each_entry(si, &swap_active_head, list) { si_frontswap_pages = atomic_read(&si->frontswap_pages); if (total_pages_to_unuse < si_frontswap_pages) { pages = pages_to_unuse = total_pages_to_unuse; } else { pages = si_frontswap_pages; pages_to_unuse = 0; /* unuse all */ } /* ensure there is enough RAM to fetch pages from frontswap */ if (security_vm_enough_memory_mm(current->mm, pages)) { ret = -ENOMEM; continue; } vm_unacct_memory(pages); *unused = pages_to_unuse; *swapid = si->type; ret = 0; break; } return ret; } /* * Used to check if it's necessory and feasible to unuse pages. * Return 1 when nothing to do, 0 when need to shink pages, * error code when there is an error. */ static int __frontswap_shrink(unsigned long target_pages, unsigned long *pages_to_unuse, int *type) { unsigned long total_pages = 0, total_pages_to_unuse; assert_spin_locked(&swap_lock); total_pages = __frontswap_curr_pages(); if (total_pages <= target_pages) { /* Nothing to do */ *pages_to_unuse = 0; return 1; } total_pages_to_unuse = total_pages - target_pages; return __frontswap_unuse_pages(total_pages_to_unuse, pages_to_unuse, type); } /* * Frontswap, like a true swap device, may unnecessarily retain pages * under certain circumstances; "shrink" frontswap is essentially a * "partial swapoff" and works by calling try_to_unuse to attempt to * unuse enough frontswap pages to attempt to -- subject to memory * constraints -- reduce the number of pages in frontswap to the * number given in the parameter target_pages. */ void frontswap_shrink(unsigned long target_pages) { unsigned long pages_to_unuse = 0; int uninitialized_var(type), ret; /* * we don't want to hold swap_lock while doing a very * lengthy try_to_unuse, but swap_list may change * so restart scan from swap_active_head each time */ spin_lock(&swap_lock); ret = __frontswap_shrink(target_pages, &pages_to_unuse, &type); spin_unlock(&swap_lock); if (ret == 0) try_to_unuse(type, true, pages_to_unuse); return; } EXPORT_SYMBOL(frontswap_shrink); /* * Count and return the number of frontswap pages across all * swap devices. This is exported so that backend drivers can * determine current usage without reading debugfs. */ unsigned long frontswap_curr_pages(void) { unsigned long totalpages = 0; spin_lock(&swap_lock); totalpages = __frontswap_curr_pages(); spin_unlock(&swap_lock); return totalpages; } EXPORT_SYMBOL(frontswap_curr_pages); static int __init init_frontswap(void) { #ifdef CONFIG_DEBUG_FS struct dentry *root = debugfs_create_dir("frontswap", NULL); if (root == NULL) return -ENXIO; debugfs_create_u64("loads", S_IRUGO, root, &frontswap_loads); debugfs_create_u64("succ_stores", S_IRUGO, root, &frontswap_succ_stores); debugfs_create_u64("failed_stores", S_IRUGO, root, &frontswap_failed_stores); debugfs_create_u64("invalidates", S_IRUGO, root, &frontswap_invalidates); #endif return 0; } module_init(init_frontswap);
gpl-3.0
CognetTestbed/COGNET_CODE
KERNEL_SOURCE_CODE/grouper/arch/sh/boards/mach-sh7763rdp/irq.c
13237
1119
/* * linux/arch/sh/boards/renesas/sh7763rdp/irq.c * * Renesas Solutions SH7763RDP Support. * * Copyright (C) 2008 Renesas Solutions Corp. * Copyright (C) 2008 Nobuhiro Iwamatsu <iwamatsu.nobuhiro@renesas.com> * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/init.h> #include <linux/irq.h> #include <asm/io.h> #include <asm/irq.h> #include <mach/sh7763rdp.h> #define INTC_BASE (0xFFD00000) #define INTC_INT2PRI7 (INTC_BASE+0x4001C) #define INTC_INT2MSKCR (INTC_BASE+0x4003C) #define INTC_INT2MSKCR1 (INTC_BASE+0x400D4) /* * Initialize IRQ setting */ void __init init_sh7763rdp_IRQ(void) { /* GPIO enabled */ __raw_writel(1 << 25, INTC_INT2MSKCR); /* enable GPIO interrupts */ __raw_writel((__raw_readl(INTC_INT2PRI7) & 0xFF00FFFF) | 0x000F0000, INTC_INT2PRI7); /* USBH enabled */ __raw_writel(1 << 17, INTC_INT2MSKCR1); /* GETHER enabled */ __raw_writel(1 << 16, INTC_INT2MSKCR1); /* DMAC enabled */ __raw_writel(1 << 8, INTC_INT2MSKCR); }
gpl-3.0
monkeybad/ChatDemoForIBG
Submodules/encrypted-core-data/vendor/sqlcipher/src/test_wsd.c
443
2209
/* ** 2008 September 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** The code in this file contains sample implementations of the ** sqlite3_wsd_init() and sqlite3_wsd_find() functions required if the ** SQLITE_OMIT_WSD symbol is defined at build time. */ #if defined(SQLITE_OMIT_WSD) && defined(SQLITE_TEST) #include "sqliteInt.h" #define PLS_HASHSIZE 43 typedef struct ProcessLocalStorage ProcessLocalStorage; typedef struct ProcessLocalVar ProcessLocalVar; struct ProcessLocalStorage { ProcessLocalVar *aData[PLS_HASHSIZE]; int nFree; u8 *pFree; }; struct ProcessLocalVar { void *pKey; ProcessLocalVar *pNext; }; static ProcessLocalStorage *pGlobal = 0; int sqlite3_wsd_init(int N, int J){ if( !pGlobal ){ int nMalloc = N + sizeof(ProcessLocalStorage) + J*sizeof(ProcessLocalVar); pGlobal = (ProcessLocalStorage *)malloc(nMalloc); if( pGlobal ){ memset(pGlobal, 0, sizeof(ProcessLocalStorage)); pGlobal->nFree = nMalloc - sizeof(ProcessLocalStorage); pGlobal->pFree = (u8 *)&pGlobal[1]; } } return pGlobal ? SQLITE_OK : SQLITE_NOMEM; } void *sqlite3_wsd_find(void *K, int L){ int i; int iHash = 0; ProcessLocalVar *pVar; /* Calculate a hash of K */ for(i=0; i<sizeof(void*); i++){ iHash = (iHash<<3) + ((unsigned char *)&K)[i]; } iHash = iHash%PLS_HASHSIZE; /* Search the hash table for K. */ for(pVar=pGlobal->aData[iHash]; pVar && pVar->pKey!=K; pVar=pVar->pNext); /* If no entry for K was found, create and populate a new one. */ if( !pVar ){ int nByte = ROUND8(sizeof(ProcessLocalVar) + L); assert( pGlobal->nFree>=nByte ); pVar = (ProcessLocalVar *)pGlobal->pFree; pVar->pKey = K; pVar->pNext = pGlobal->aData[iHash]; pGlobal->aData[iHash] = pVar; pGlobal->nFree -= nByte; pGlobal->pFree += nByte; memcpy(&pVar[1], K, L); } return (void *)&pVar[1]; } #endif
gpl-3.0
BuzzBumbleBee/Marlin
ArduinoAddons/Arduino_1.0.x/hardware/rambo/cores/arduino/HID.cpp
998
13772
/* Copyright (c) 2011, Peter Barrett ** ** 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 "Platform.h" #include "USBAPI.h" #include "USBDesc.h" #if defined(USBCON) #ifdef HID_ENABLED //#define RAWHID_ENABLED // Singletons for mouse and keyboard Mouse_ Mouse; Keyboard_ Keyboard; //================================================================================ //================================================================================ // HID report descriptor #define LSB(_x) ((_x) & 0xFF) #define MSB(_x) ((_x) >> 8) #define RAWHID_USAGE_PAGE 0xFFC0 #define RAWHID_USAGE 0x0C00 #define RAWHID_TX_SIZE 64 #define RAWHID_RX_SIZE 64 extern const u8 _hidReportDescriptor[] PROGMEM; const u8 _hidReportDescriptor[] = { // Mouse 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 54 0x09, 0x02, // USAGE (Mouse) 0xa1, 0x01, // COLLECTION (Application) 0x09, 0x01, // USAGE (Pointer) 0xa1, 0x00, // COLLECTION (Physical) 0x85, 0x01, // REPORT_ID (1) 0x05, 0x09, // USAGE_PAGE (Button) 0x19, 0x01, // USAGE_MINIMUM (Button 1) 0x29, 0x03, // USAGE_MAXIMUM (Button 3) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x01, // LOGICAL_MAXIMUM (1) 0x95, 0x03, // REPORT_COUNT (3) 0x75, 0x01, // REPORT_SIZE (1) 0x81, 0x02, // INPUT (Data,Var,Abs) 0x95, 0x01, // REPORT_COUNT (1) 0x75, 0x05, // REPORT_SIZE (5) 0x81, 0x03, // INPUT (Cnst,Var,Abs) 0x05, 0x01, // USAGE_PAGE (Generic Desktop) 0x09, 0x30, // USAGE (X) 0x09, 0x31, // USAGE (Y) 0x09, 0x38, // USAGE (Wheel) 0x15, 0x81, // LOGICAL_MINIMUM (-127) 0x25, 0x7f, // LOGICAL_MAXIMUM (127) 0x75, 0x08, // REPORT_SIZE (8) 0x95, 0x03, // REPORT_COUNT (3) 0x81, 0x06, // INPUT (Data,Var,Rel) 0xc0, // END_COLLECTION 0xc0, // END_COLLECTION // Keyboard 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47 0x09, 0x06, // USAGE (Keyboard) 0xa1, 0x01, // COLLECTION (Application) 0x85, 0x02, // REPORT_ID (2) 0x05, 0x07, // USAGE_PAGE (Keyboard) 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x01, // LOGICAL_MAXIMUM (1) 0x75, 0x01, // REPORT_SIZE (1) 0x95, 0x08, // REPORT_COUNT (8) 0x81, 0x02, // INPUT (Data,Var,Abs) 0x95, 0x01, // REPORT_COUNT (1) 0x75, 0x08, // REPORT_SIZE (8) 0x81, 0x03, // INPUT (Cnst,Var,Abs) 0x95, 0x06, // REPORT_COUNT (6) 0x75, 0x08, // REPORT_SIZE (8) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x65, // LOGICAL_MAXIMUM (101) 0x05, 0x07, // USAGE_PAGE (Keyboard) 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application) 0x81, 0x00, // INPUT (Data,Ary,Abs) 0xc0, // END_COLLECTION #if RAWHID_ENABLED // RAW HID 0x06, LSB(RAWHID_USAGE_PAGE), MSB(RAWHID_USAGE_PAGE), // 30 0x0A, LSB(RAWHID_USAGE), MSB(RAWHID_USAGE), 0xA1, 0x01, // Collection 0x01 0x85, 0x03, // REPORT_ID (3) 0x75, 0x08, // report size = 8 bits 0x15, 0x00, // logical minimum = 0 0x26, 0xFF, 0x00, // logical maximum = 255 0x95, 64, // report count TX 0x09, 0x01, // usage 0x81, 0x02, // Input (array) 0x95, 64, // report count RX 0x09, 0x02, // usage 0x91, 0x02, // Output (array) 0xC0 // end collection #endif }; extern const HIDDescriptor _hidInterface PROGMEM; const HIDDescriptor _hidInterface = { D_INTERFACE(HID_INTERFACE,1,3,0,0), D_HIDREPORT(sizeof(_hidReportDescriptor)), D_ENDPOINT(USB_ENDPOINT_IN (HID_ENDPOINT_INT),USB_ENDPOINT_TYPE_INTERRUPT,0x40,0x01) }; //================================================================================ //================================================================================ // Driver u8 _hid_protocol = 1; u8 _hid_idle = 1; #define WEAK __attribute__ ((weak)) int WEAK HID_GetInterface(u8* interfaceNum) { interfaceNum[0] += 1; // uses 1 return USB_SendControl(TRANSFER_PGM,&_hidInterface,sizeof(_hidInterface)); } int WEAK HID_GetDescriptor(int i) { return USB_SendControl(TRANSFER_PGM,_hidReportDescriptor,sizeof(_hidReportDescriptor)); } void WEAK HID_SendReport(u8 id, const void* data, int len) { USB_Send(HID_TX, &id, 1); USB_Send(HID_TX | TRANSFER_RELEASE,data,len); } bool WEAK HID_Setup(Setup& setup) { u8 r = setup.bRequest; u8 requestType = setup.bmRequestType; if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType) { if (HID_GET_REPORT == r) { //HID_GetReport(); return true; } if (HID_GET_PROTOCOL == r) { //Send8(_hid_protocol); // TODO return true; } } if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType) { if (HID_SET_PROTOCOL == r) { _hid_protocol = setup.wValueL; return true; } if (HID_SET_IDLE == r) { _hid_idle = setup.wValueL; return true; } } return false; } //================================================================================ //================================================================================ // Mouse Mouse_::Mouse_(void) : _buttons(0) { } void Mouse_::begin(void) { } void Mouse_::end(void) { } void Mouse_::click(uint8_t b) { _buttons = b; move(0,0,0); _buttons = 0; move(0,0,0); } void Mouse_::move(signed char x, signed char y, signed char wheel) { u8 m[4]; m[0] = _buttons; m[1] = x; m[2] = y; m[3] = wheel; HID_SendReport(1,m,4); } void Mouse_::buttons(uint8_t b) { if (b != _buttons) { _buttons = b; move(0,0,0); } } void Mouse_::press(uint8_t b) { buttons(_buttons | b); } void Mouse_::release(uint8_t b) { buttons(_buttons & ~b); } bool Mouse_::isPressed(uint8_t b) { if ((b & _buttons) > 0) return true; return false; } //================================================================================ //================================================================================ // Keyboard Keyboard_::Keyboard_(void) { } void Keyboard_::begin(void) { } void Keyboard_::end(void) { } void Keyboard_::sendReport(KeyReport* keys) { HID_SendReport(2,keys,sizeof(KeyReport)); } extern const uint8_t _asciimap[128] PROGMEM; #define SHIFT 0x80 const uint8_t _asciimap[128] = { 0x00, // NUL 0x00, // SOH 0x00, // STX 0x00, // ETX 0x00, // EOT 0x00, // ENQ 0x00, // ACK 0x00, // BEL 0x2a, // BS Backspace 0x2b, // TAB Tab 0x28, // LF Enter 0x00, // VT 0x00, // FF 0x00, // CR 0x00, // SO 0x00, // SI 0x00, // DEL 0x00, // DC1 0x00, // DC2 0x00, // DC3 0x00, // DC4 0x00, // NAK 0x00, // SYN 0x00, // ETB 0x00, // CAN 0x00, // EM 0x00, // SUB 0x00, // ESC 0x00, // FS 0x00, // GS 0x00, // RS 0x00, // US 0x2c, // ' ' 0x1e|SHIFT, // ! 0x34|SHIFT, // " 0x20|SHIFT, // # 0x21|SHIFT, // $ 0x22|SHIFT, // % 0x24|SHIFT, // & 0x34, // ' 0x26|SHIFT, // ( 0x27|SHIFT, // ) 0x25|SHIFT, // * 0x2e|SHIFT, // + 0x36, // , 0x2d, // - 0x37, // . 0x38, // / 0x27, // 0 0x1e, // 1 0x1f, // 2 0x20, // 3 0x21, // 4 0x22, // 5 0x23, // 6 0x24, // 7 0x25, // 8 0x26, // 9 0x33|SHIFT, // : 0x33, // ; 0x36|SHIFT, // < 0x2e, // = 0x37|SHIFT, // > 0x38|SHIFT, // ? 0x1f|SHIFT, // @ 0x04|SHIFT, // A 0x05|SHIFT, // B 0x06|SHIFT, // C 0x07|SHIFT, // D 0x08|SHIFT, // E 0x09|SHIFT, // F 0x0a|SHIFT, // G 0x0b|SHIFT, // H 0x0c|SHIFT, // I 0x0d|SHIFT, // J 0x0e|SHIFT, // K 0x0f|SHIFT, // L 0x10|SHIFT, // M 0x11|SHIFT, // N 0x12|SHIFT, // O 0x13|SHIFT, // P 0x14|SHIFT, // Q 0x15|SHIFT, // R 0x16|SHIFT, // S 0x17|SHIFT, // T 0x18|SHIFT, // U 0x19|SHIFT, // V 0x1a|SHIFT, // W 0x1b|SHIFT, // X 0x1c|SHIFT, // Y 0x1d|SHIFT, // Z 0x2f, // [ 0x31, // bslash 0x30, // ] 0x23|SHIFT, // ^ 0x2d|SHIFT, // _ 0x35, // ` 0x04, // a 0x05, // b 0x06, // c 0x07, // d 0x08, // e 0x09, // f 0x0a, // g 0x0b, // h 0x0c, // i 0x0d, // j 0x0e, // k 0x0f, // l 0x10, // m 0x11, // n 0x12, // o 0x13, // p 0x14, // q 0x15, // r 0x16, // s 0x17, // t 0x18, // u 0x19, // v 0x1a, // w 0x1b, // x 0x1c, // y 0x1d, // z 0x2f|SHIFT, // 0x31|SHIFT, // | 0x30|SHIFT, // } 0x35|SHIFT, // ~ 0 // DEL }; uint8_t USBPutChar(uint8_t c); // press() adds the specified key (printing, non-printing, or modifier) // to the persistent key report and sends the report. Because of the way // USB HID works, the host acts like the key remains pressed until we // call release(), releaseAll(), or otherwise clear the report and resend. size_t Keyboard_::press(uint8_t k) { uint8_t i; if (k >= 136) { // it's a non-printing key (not a modifier) k = k - 136; } else if (k >= 128) { // it's a modifier key _keyReport.modifiers |= (1<<(k-128)); k = 0; } else { // it's a printing key k = pgm_read_byte(_asciimap + k); if (!k) { setWriteError(); return 0; } if (k & 0x80) { // it's a capital letter or other character reached with shift _keyReport.modifiers |= 0x02; // the left shift modifier k &= 0x7F; } } // Add k to the key report only if it's not already present // and if there is an empty slot. if (_keyReport.keys[0] != k && _keyReport.keys[1] != k && _keyReport.keys[2] != k && _keyReport.keys[3] != k && _keyReport.keys[4] != k && _keyReport.keys[5] != k) { for (i=0; i<6; i++) { if (_keyReport.keys[i] == 0x00) { _keyReport.keys[i] = k; break; } } if (i == 6) { setWriteError(); return 0; } } sendReport(&_keyReport); return 1; } // release() takes the specified key out of the persistent key report and // sends the report. This tells the OS the key is no longer pressed and that // it shouldn't be repeated any more. size_t Keyboard_::release(uint8_t k) { uint8_t i; if (k >= 136) { // it's a non-printing key (not a modifier) k = k - 136; } else if (k >= 128) { // it's a modifier key _keyReport.modifiers &= ~(1<<(k-128)); k = 0; } else { // it's a printing key k = pgm_read_byte(_asciimap + k); if (!k) { return 0; } if (k & 0x80) { // it's a capital letter or other character reached with shift _keyReport.modifiers &= ~(0x02); // the left shift modifier k &= 0x7F; } } // Test the key report to see if k is present. Clear it if it exists. // Check all positions in case the key is present more than once (which it shouldn't be) for (i=0; i<6; i++) { if (0 != k && _keyReport.keys[i] == k) { _keyReport.keys[i] = 0x00; } } sendReport(&_keyReport); return 1; } void Keyboard_::releaseAll(void) { _keyReport.keys[0] = 0; _keyReport.keys[1] = 0; _keyReport.keys[2] = 0; _keyReport.keys[3] = 0; _keyReport.keys[4] = 0; _keyReport.keys[5] = 0; _keyReport.modifiers = 0; sendReport(&_keyReport); } size_t Keyboard_::write(uint8_t c) { uint8_t p = press(c); // Keydown uint8_t r = release(c); // Keyup return (p); // just return the result of press() since release() almost always returns 1 } #endif #endif /* if defined(USBCON) */
gpl-3.0
Robbiedobbie/Marlin
ArduinoAddons/Arduino_1.x.x/hardware/Melzi/cores/arduino/wiring_digital.c
1023
4931
/* wiring_digital.c - digital input and output functions Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Modified 28 September 2010 by Mark Sproul $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ */ #define ARDUINO_MAIN #include "wiring_private.h" #include "pins_arduino.h" void pinMode(uint8_t pin, uint8_t mode) { uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *reg, *out; if (port == NOT_A_PIN) return; // JWS: can I let the optimizer do this? reg = portModeRegister(port); out = portOutputRegister(port); if (mode == INPUT) { uint8_t oldSREG = SREG; cli(); *reg &= ~bit; *out &= ~bit; SREG = oldSREG; } else if (mode == INPUT_PULLUP) { uint8_t oldSREG = SREG; cli(); *reg &= ~bit; *out |= bit; SREG = oldSREG; } else { uint8_t oldSREG = SREG; cli(); *reg |= bit; SREG = oldSREG; } } // Forcing this inline keeps the callers from having to push their own stuff // on the stack. It is a good performance win and only takes 1 more byte per // user than calling. (It will take more bytes on the 168.) // // But shouldn't this be moved into pinMode? Seems silly to check and do on // each digitalread or write. // // Mark Sproul: // - Removed inline. Save 170 bytes on atmega1280 // - changed to a switch statment; added 32 bytes but much easier to read and maintain. // - Added more #ifdefs, now compiles for atmega645 // //static inline void turnOffPWM(uint8_t timer) __attribute__ ((always_inline)); //static inline void turnOffPWM(uint8_t timer) static void turnOffPWM(uint8_t timer) { switch (timer) { #if defined(TCCR1A) && defined(COM1A1) case TIMER1A: cbi(TCCR1A, COM1A1); break; #endif #if defined(TCCR1A) && defined(COM1B1) case TIMER1B: cbi(TCCR1A, COM1B1); break; #endif #if defined(TCCR2) && defined(COM21) case TIMER2: cbi(TCCR2, COM21); break; #endif #if defined(TCCR0A) && defined(COM0A1) case TIMER0A: cbi(TCCR0A, COM0A1); break; #endif #if defined(TIMER0B) && defined(COM0B1) case TIMER0B: cbi(TCCR0A, COM0B1); break; #endif #if defined(TCCR2A) && defined(COM2A1) case TIMER2A: cbi(TCCR2A, COM2A1); break; #endif #if defined(TCCR2A) && defined(COM2B1) case TIMER2B: cbi(TCCR2A, COM2B1); break; #endif #if defined(TCCR3A) && defined(COM3A1) case TIMER3A: cbi(TCCR3A, COM3A1); break; #endif #if defined(TCCR3A) && defined(COM3B1) case TIMER3B: cbi(TCCR3A, COM3B1); break; #endif #if defined(TCCR3A) && defined(COM3C1) case TIMER3C: cbi(TCCR3A, COM3C1); break; #endif #if defined(TCCR4A) && defined(COM4A1) case TIMER4A: cbi(TCCR4A, COM4A1); break; #endif #if defined(TCCR4A) && defined(COM4B1) case TIMER4B: cbi(TCCR4A, COM4B1); break; #endif #if defined(TCCR4A) && defined(COM4C1) case TIMER4C: cbi(TCCR4A, COM4C1); break; #endif #if defined(TCCR4C) && defined(COM4D1) case TIMER4D: cbi(TCCR4C, COM4D1); break; #endif #if defined(TCCR5A) case TIMER5A: cbi(TCCR5A, COM5A1); break; case TIMER5B: cbi(TCCR5A, COM5B1); break; case TIMER5C: cbi(TCCR5A, COM5C1); break; #endif } } void digitalWrite(uint8_t pin, uint8_t val) { uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *out; if (port == NOT_A_PIN) return; // If the pin that support PWM output, we need to turn it off // before doing a digital write. if (timer != NOT_ON_TIMER) turnOffPWM(timer); out = portOutputRegister(port); uint8_t oldSREG = SREG; cli(); if (val == LOW) { *out &= ~bit; } else { *out |= bit; } SREG = oldSREG; } int digitalRead(uint8_t pin) { uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); if (port == NOT_A_PIN) return LOW; // If the pin that support PWM output, we need to turn it off // before getting a digital reading. if (timer != NOT_ON_TIMER) turnOffPWM(timer); if (*portInputRegister(port) & bit) return HIGH; return LOW; }
gpl-3.0
dzbarsky/rust-azure
src/azure-c.cpp
1
38566
/* 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 "azure-c.h" #include "2D.h" #include "Filters.h" #include "ScaledFontSkia.h" #include "Types.h" #include <assert.h> #include <string.h> using namespace mozilla; // Utilities static AzIntSize IntSizeToC(gfx::IntSize src) { AzIntSize dst; memcpy(&dst, &src, sizeof(dst)); return dst; } #define CHECK_SIZE(name) assert(sizeof(Az##name) == sizeof(gfx::name)) #define CHECK_ENUM(azureEnumName, rustAzurePrefix, name) assert((int)rustAzurePrefix##_##name == (int)gfx::azureEnumName::name) #define STATIC_ASSERT_EQUALS(a, b)\ typedef char assert_failed_ ## name [ (a - b) ? 1 : -1 ] extern "C" void AzSanityCheck() { CHECK_SIZE(Matrix); CHECK_SIZE(Float); CHECK_SIZE(Color); CHECK_SIZE(GradientStop); CHECK_SIZE(Rect); CHECK_SIZE(IntRect); CHECK_SIZE(Point); CHECK_SIZE(IntPoint); CHECK_SIZE(Size); CHECK_SIZE(IntSize); CHECK_SIZE(DrawOptions); CHECK_SIZE(StrokeOptions); CHECK_SIZE(DrawSurfaceOptions); CHECK_SIZE(Glyph); CHECK_SIZE(GlyphBuffer); CHECK_SIZE(NativeFont); CHECK_ENUM(SurfaceType, AZ_SURFACE, DATA); CHECK_ENUM(SurfaceType, AZ_SURFACE, D2D1_BITMAP); CHECK_ENUM(SurfaceType, AZ_SURFACE, D2D1_DRAWTARGET); CHECK_ENUM(SurfaceType, AZ_SURFACE, CAIRO); CHECK_ENUM(SurfaceType, AZ_SURFACE, CAIRO_IMAGE); CHECK_ENUM(SurfaceType, AZ_SURFACE, COREGRAPHICS_IMAGE); CHECK_ENUM(SurfaceType, AZ_SURFACE, COREGRAPHICS_CGCONTEXT); CHECK_ENUM(SurfaceType, AZ_SURFACE, SKIA); CHECK_ENUM(SurfaceType, AZ_SURFACE, DUAL_DT); CHECK_ENUM(SurfaceType, AZ_SURFACE, D2D1_1_IMAGE); CHECK_ENUM(SurfaceType, AZ_SURFACE, RECORDING); CHECK_ENUM(SurfaceType, AZ_SURFACE, NVPR_TEXTURE); CHECK_ENUM(SurfaceType, AZ_SURFACE, TILED); CHECK_ENUM(SurfaceFormat, AZ_FORMAT, B8G8R8A8); CHECK_ENUM(SurfaceFormat, AZ_FORMAT, B8G8R8X8); CHECK_ENUM(SurfaceFormat, AZ_FORMAT, R5G6B5); CHECK_ENUM(SurfaceFormat, AZ_FORMAT, A8); CHECK_ENUM(BackendType, AZ_BACKEND, NONE); CHECK_ENUM(BackendType, AZ_BACKEND, DIRECT2D); CHECK_ENUM(BackendType, AZ_BACKEND, COREGRAPHICS); CHECK_ENUM(BackendType, AZ_BACKEND, CAIRO); CHECK_ENUM(BackendType, AZ_BACKEND, SKIA); CHECK_ENUM(BackendType, AZ_BACKEND, RECORDING); CHECK_ENUM(BackendType, AZ_BACKEND, DIRECT2D1_1); CHECK_ENUM(BackendType, AZ_BACKEND, NVPR); CHECK_ENUM(FontType, AZ_FONT, DWRITE); CHECK_ENUM(FontType, AZ_FONT, GDI); CHECK_ENUM(FontType, AZ_FONT, MAC); CHECK_ENUM(FontType, AZ_FONT, SKIA); CHECK_ENUM(FontType, AZ_FONT, CAIRO); CHECK_ENUM(FontType, AZ_FONT, COREGRAPHICS); CHECK_ENUM(FontType, AZ_FONT, NVPR); CHECK_ENUM(NativeSurfaceType, AZ_NATIVE_SURFACE, D3D10_TEXTURE); CHECK_ENUM(NativeSurfaceType, AZ_NATIVE_SURFACE, CAIRO_SURFACE); CHECK_ENUM(NativeSurfaceType, AZ_NATIVE_SURFACE, CAIRO_CONTEXT); CHECK_ENUM(NativeSurfaceType, AZ_NATIVE_SURFACE, CGCONTEXT); CHECK_ENUM(NativeSurfaceType, AZ_NATIVE_SURFACE, CGCONTEXT_ACCELERATED); CHECK_ENUM(NativeSurfaceType, AZ_NATIVE_SURFACE, OPENGL_TEXTURE); CHECK_ENUM(NativeFontType, AZ_NATIVE_FONT, DWRITE_FONT_FACE); CHECK_ENUM(NativeFontType, AZ_NATIVE_FONT, GDI_FONT_FACE); CHECK_ENUM(NativeFontType, AZ_NATIVE_FONT, MAC_FONT_FACE); CHECK_ENUM(NativeFontType, AZ_NATIVE_FONT, SKIA_FONT_FACE); CHECK_ENUM(NativeFontType, AZ_NATIVE_FONT, CAIRO_FONT_FACE); CHECK_ENUM(NativeFontType, AZ_NATIVE_FONT, NVPR_FONT_FACE); CHECK_ENUM(CompositionOp, AZ, OP_OVER); CHECK_ENUM(CompositionOp, AZ, OP_ADD); CHECK_ENUM(CompositionOp, AZ, OP_ATOP); CHECK_ENUM(CompositionOp, AZ, OP_OUT); CHECK_ENUM(CompositionOp, AZ, OP_IN); CHECK_ENUM(CompositionOp, AZ, OP_SOURCE); CHECK_ENUM(CompositionOp, AZ, OP_DEST_IN); CHECK_ENUM(CompositionOp, AZ, OP_DEST_OUT); CHECK_ENUM(CompositionOp, AZ, OP_DEST_OVER); CHECK_ENUM(CompositionOp, AZ, OP_DEST_ATOP); CHECK_ENUM(CompositionOp, AZ, OP_XOR); CHECK_ENUM(CompositionOp, AZ, OP_MULTIPLY); CHECK_ENUM(CompositionOp, AZ, OP_SCREEN); CHECK_ENUM(CompositionOp, AZ, OP_OVERLAY); CHECK_ENUM(CompositionOp, AZ, OP_DARKEN); CHECK_ENUM(CompositionOp, AZ, OP_LIGHTEN); CHECK_ENUM(CompositionOp, AZ, OP_COLOR_DODGE); CHECK_ENUM(CompositionOp, AZ, OP_COLOR_BURN); CHECK_ENUM(CompositionOp, AZ, OP_HARD_LIGHT); CHECK_ENUM(CompositionOp, AZ, OP_SOFT_LIGHT); CHECK_ENUM(CompositionOp, AZ, OP_DIFFERENCE); CHECK_ENUM(CompositionOp, AZ, OP_EXCLUSION); CHECK_ENUM(CompositionOp, AZ, OP_HUE); CHECK_ENUM(CompositionOp, AZ, OP_SATURATION); CHECK_ENUM(CompositionOp, AZ, OP_COLOR); CHECK_ENUM(CompositionOp, AZ, OP_LUMINOSITY); CHECK_ENUM(CompositionOp, AZ, OP_COUNT); CHECK_ENUM(ExtendMode, AZ_EXTEND, CLAMP); CHECK_ENUM(ExtendMode, AZ_EXTEND, REPEAT); CHECK_ENUM(ExtendMode, AZ_EXTEND, REFLECT); CHECK_ENUM(FillRule, AZ, FILL_WINDING); CHECK_ENUM(FillRule, AZ, FILL_EVEN_ODD); CHECK_ENUM(AntialiasMode, AZ_AA, NONE); CHECK_ENUM(AntialiasMode, AZ_AA, GRAY); CHECK_ENUM(AntialiasMode, AZ_AA, SUBPIXEL); CHECK_ENUM(Filter, AZ_FILTER, GOOD); CHECK_ENUM(Filter, AZ_FILTER, LINEAR); CHECK_ENUM(Filter, AZ_FILTER, POINT); CHECK_ENUM(PatternType, AZ_PATTERN, COLOR); CHECK_ENUM(PatternType, AZ_PATTERN, SURFACE); CHECK_ENUM(PatternType, AZ_PATTERN, LINEAR_GRADIENT); CHECK_ENUM(PatternType, AZ_PATTERN, RADIAL_GRADIENT); CHECK_ENUM(JoinStyle, AZ_JOIN, BEVEL); CHECK_ENUM(JoinStyle, AZ_JOIN, ROUND); CHECK_ENUM(JoinStyle, AZ_JOIN, MITER); CHECK_ENUM(JoinStyle, AZ_JOIN, MITER_OR_BEVEL); CHECK_ENUM(CapStyle, AZ_CAP, BUTT); CHECK_ENUM(CapStyle, AZ_CAP, ROUND); CHECK_ENUM(CapStyle, AZ_CAP, SQUARE); CHECK_ENUM(SamplingBounds, AZ_SAMPLING, UNBOUNDED); CHECK_ENUM(SamplingBounds, AZ_SAMPLING, BOUNDED); assert((int)AZ_eSideTop == (int)mozilla::eSideTop); assert((int)AZ_eSideRight == (int)mozilla::eSideRight); assert((int)AZ_eSideBottom == (int)mozilla::eSideBottom); assert((int)AZ_eSideLeft == (int)mozilla::eSideLeft); } extern "C" AzColorPatternRef AzCreateColorPattern(AzColor *aColor) { gfx::Color *gfxColor = reinterpret_cast<gfx::Color*>(aColor); gfx::ColorPattern *gfxColorPattern = new gfx::ColorPattern(*gfxColor); return gfxColorPattern; } extern "C" AzDrawTargetRef AzCreateDrawTarget(AzBackendType aBackend, AzIntSize *aSize, AzSurfaceFormat aFormat) { gfx::BackendType backendType = static_cast<gfx::BackendType>(aBackend); gfx::IntSize *size = reinterpret_cast<gfx::IntSize*>(aSize); gfx::SurfaceFormat surfaceFormat = static_cast<gfx::SurfaceFormat>(aFormat); RefPtr<gfx::DrawTarget> target = gfx::Factory::CreateDrawTarget(backendType, *size, surfaceFormat); target->AddRef(); return target; } extern "C" AzDrawTargetRef AzCreateDrawTargetForData(AzBackendType aBackend, unsigned char *aData, AzIntSize *aSize, int32_t aStride, AzSurfaceFormat aFormat) { gfx::BackendType backendType = static_cast<gfx::BackendType>(aBackend); gfx::IntSize *size = reinterpret_cast<gfx::IntSize*>(aSize); gfx::SurfaceFormat surfaceFormat = static_cast<gfx::SurfaceFormat>(aFormat); RefPtr<gfx::DrawTarget> target = gfx::Factory::CreateDrawTargetForData(backendType, aData, *size, aStride, surfaceFormat); if (target != NULL) { target->AddRef(); } return target; } extern "C" AzDrawTargetRef AzCreateDrawTargetSkiaWithGrContextAndFBO(SkiaGrContextRef aGrContext, unsigned int aFBOID, AzIntSize *aSize, AzSurfaceFormat aFormat) { GrContext *grContext = static_cast<GrContext*>(aGrContext); gfx::IntSize *size = reinterpret_cast<gfx::IntSize*>(aSize); gfx::SurfaceFormat surfaceFormat = static_cast<gfx::SurfaceFormat>(aFormat); RefPtr<gfx::DrawTarget> target = gfx::Factory::CreateDrawTargetSkiaWithGrContextAndFBO(grContext, aFBOID, *size, surfaceFormat); if (target != NULL) { target->AddRef(); } return target; } extern "C" void AzRetainDrawTarget(AzDrawTargetRef aTarget) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aTarget); gfxDrawTarget->AddRef(); } extern "C" void AzReleaseDrawTarget(AzDrawTargetRef aTarget) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aTarget); gfxDrawTarget->Release(); } extern "C" AzIntSize AzDrawTargetGetSize(AzDrawTargetRef aDrawTarget) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); return IntSizeToC(gfxDrawTarget->GetSize()); } extern "C" AzSurfaceFormat AzDrawTargetGetFormat(AzDrawTargetRef aDrawTarget) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); return static_cast<AzSurfaceFormat>(static_cast<int>(gfxDrawTarget->GetFormat())); } extern "C" void AzDrawTargetGetTransform(AzDrawTargetRef aDrawTarget, AzMatrix* aOutMatrix) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); *reinterpret_cast<gfx::Matrix*>(aOutMatrix) = gfxDrawTarget->GetTransform(); } extern "C" void AzDrawTargetFlush(AzDrawTargetRef aDrawTarget) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfxDrawTarget->Flush(); } extern "C" void AzDrawTargetClearRect(AzDrawTargetRef aDrawTarget, AzRect *aRect) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::Rect *gfxRect = reinterpret_cast<gfx::Rect*>(aRect); gfxDrawTarget->ClearRect(*gfxRect); } extern "C" void AzDrawTargetFill(AzDrawTargetRef aDrawTarget, AzPathRef aPath, AzPatternRef aPattern, AzDrawOptions *aDrawOptions) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::Path *gfxPath = static_cast<gfx::Path*>(aPath); gfx::Pattern *gfxPattern = static_cast<gfx::Pattern*>(aPattern); gfx::DrawOptions *gfxDrawOptions = reinterpret_cast<gfx::DrawOptions*>(aDrawOptions); gfxDrawTarget->Fill(gfxPath, *gfxPattern, *gfxDrawOptions); } extern "C" void AzDrawTargetStroke(AzDrawTargetRef aDrawTarget, AzPathRef aPath, AzPatternRef aPattern, const AzStrokeOptions *aStrokeOptions, const AzDrawOptions *aDrawOptions) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); const gfx::Path *gfxPath = reinterpret_cast<const gfx::Path*>(aPath); const gfx::Pattern *gfxPattern = reinterpret_cast<const gfx::Pattern*>(aPattern); const gfx::StrokeOptions *gfxStrokeOptions = reinterpret_cast<const gfx::StrokeOptions*>(aStrokeOptions); const gfx::DrawOptions *gfxDrawOptions = reinterpret_cast<const gfx::DrawOptions*>(aDrawOptions); gfxDrawTarget->Stroke(gfxPath, *gfxPattern, *gfxStrokeOptions, *gfxDrawOptions); } extern "C" void AzDrawTargetPushClip(AzDrawTargetRef aDrawTarget, AzPathRef aPath) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); const gfx::Path *gfxPath = reinterpret_cast<const gfx::Path*>(aPath); gfxDrawTarget->PushClip(gfxPath); } extern "C" void AzDrawTargetPushClipRect(AzDrawTargetRef aDrawTarget, const AzRect *aRect) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); const gfx::Rect *gfxRect = reinterpret_cast<const gfx::Rect*>(aRect); gfxDrawTarget->PushClipRect(*gfxRect); } extern "C" void AzDrawTargetPopClip(AzDrawTargetRef aDrawTarget) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfxDrawTarget->PopClip(); } extern "C" void AzDrawTargetFillRect(AzDrawTargetRef aDrawTarget, AzRect* aRect, AzPatternRef aPattern, AzDrawOptions* aDrawOptions) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::Rect *gfxRect = reinterpret_cast<gfx::Rect*>(aRect); gfx::Pattern *gfxPattern = static_cast<gfx::Pattern*>(aPattern); gfx::DrawOptions *gfxDrawOptions = reinterpret_cast<gfx::DrawOptions*>(aDrawOptions); gfxDrawTarget->FillRect(*gfxRect, *gfxPattern, gfxDrawOptions != NULL ? *gfxDrawOptions : gfx::DrawOptions()); } extern "C" void AzDrawTargetStrokeRect(AzDrawTargetRef aDrawTarget, AzRect *aRect, AzPatternRef aPattern, AzStrokeOptions *aStrokeOptions, AzDrawOptions *aDrawOptions) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::Rect *gfxRect = reinterpret_cast<gfx::Rect*>(aRect); gfx::Pattern *gfxPattern = static_cast<gfx::Pattern*>(aPattern); gfx::StrokeOptions *gfxStrokeOptions = reinterpret_cast<gfx::StrokeOptions*>(aStrokeOptions); gfx::DrawOptions *gfxDrawOptions = reinterpret_cast<gfx::DrawOptions*>(aDrawOptions); gfxDrawTarget->StrokeRect(*gfxRect, *gfxPattern, *gfxStrokeOptions, *gfxDrawOptions); } extern "C" void AzDrawTargetStrokeLine(AzDrawTargetRef aDrawTarget, AzPoint *aStart, AzPoint *aEnd, AzPatternRef aPattern, AzStrokeOptions *aStrokeOptions, AzDrawOptions *aDrawOptions) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::Point *gfxStart = reinterpret_cast<gfx::Point*>(aStart); gfx::Point *gfxEnd = reinterpret_cast<gfx::Point*>(aEnd); gfx::Pattern *gfxPattern = static_cast<gfx::Pattern*>(aPattern); gfx::StrokeOptions *gfxStrokeOptions = reinterpret_cast<gfx::StrokeOptions*>(aStrokeOptions); gfx::DrawOptions *gfxDrawOptions = reinterpret_cast<gfx::DrawOptions*>(aDrawOptions); gfxDrawTarget->StrokeLine(*gfxStart, *gfxEnd, *gfxPattern, *gfxStrokeOptions, *gfxDrawOptions); } extern "C" void AzDrawTargetFillGlyphs(AzDrawTargetRef aDrawTarget, AzScaledFontRef aFont, AzGlyphBuffer *aGlyphBuffer, AzPatternRef aPattern, AzDrawOptions *aOptions, AzGlyphRenderingOptionsRef aRenderingOptions) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::ScaledFont *gfxScaledFont = static_cast<gfx::ScaledFont*>(aFont); gfx::GlyphBuffer *gfxGlyphBuffer = reinterpret_cast<gfx::GlyphBuffer*>(aGlyphBuffer); gfx::Pattern *gfxPattern = static_cast<gfx::Pattern*>(aPattern); gfx::DrawOptions *gfxOptions = reinterpret_cast<gfx::DrawOptions*>(aOptions); gfx::GlyphRenderingOptions *gfxRenderingOptions = static_cast<gfx::GlyphRenderingOptions*>(aRenderingOptions); gfxDrawTarget->FillGlyphs(gfxScaledFont, *gfxGlyphBuffer, *gfxPattern, *gfxOptions, gfxRenderingOptions); } extern "C" void AzDrawTargetDrawSurface(AzDrawTargetRef aDrawTarget, AzSourceSurfaceRef aSurface, AzRect *aDest, AzRect *aSource, AzDrawSurfaceOptionsRef aSurfOptions, AzDrawOptions *aOptions) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::SourceSurface *gfxSourceSurface = static_cast<gfx::SourceSurface*>(aSurface); gfx::Rect *gfxDest = reinterpret_cast<gfx::Rect*>(aDest); gfx::Rect *gfxSource = reinterpret_cast<gfx::Rect*>(aSource); gfx::DrawSurfaceOptions *gfxDrawSurfaceOptions = static_cast<gfx::DrawSurfaceOptions*>(aSurfOptions); gfx::DrawOptions *gfxDrawOptions = reinterpret_cast<gfx::DrawOptions*>(aOptions); gfxDrawTarget->DrawSurface(gfxSourceSurface, *gfxDest, *gfxSource, *gfxDrawSurfaceOptions, *gfxDrawOptions); } extern "C" void AzDrawTargetCopySurface(AzDrawTargetRef aDrawTarget, AzSourceSurfaceRef aSurface, AzIntRect *aSource, AzIntPoint *aDestination) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::SourceSurface *gfxSourceSurface = static_cast<gfx::SourceSurface*>(aSurface); gfx::IntRect *gfxSource = reinterpret_cast<gfx::IntRect*>(aSource); gfx::IntPoint *gfxDestination = reinterpret_cast<gfx::IntPoint*>(aDestination); gfxDrawTarget->CopySurface(gfxSourceSurface, *gfxSource, *gfxDestination); } extern "C" void AzDrawTargetDrawFilter(AzDrawTargetRef aDrawTarget, AzFilterNodeRef aFilter, const AzRect *aSourceRect, const AzPoint *aDestPoint, const AzDrawOptions *aOptions) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::FilterNode *gfxFilterNode = static_cast<gfx::FilterNode*>(aFilter); const gfx::Rect *gfxSourceRect = reinterpret_cast<const gfx::Rect*>(aSourceRect); const gfx::Point *gfxDestPoint = reinterpret_cast<const gfx::Point*>(aDestPoint); const gfx::DrawOptions *gfxDrawOptions = reinterpret_cast<const gfx::DrawOptions*>(aOptions); gfxDrawTarget->DrawFilter(gfxFilterNode, *gfxSourceRect, *gfxDestPoint, *gfxDrawOptions); } extern "C" void AzDrawTargetDrawSurfaceWithShadow(AzDrawTargetRef aDrawTarget, AzSourceSurfaceRef aSurface, const AzPoint* aPoint, const AzColor* aColor, const AzPoint* aOffset, AzFloat aSigma, AzCompositionOp aOperator) { gfx::DrawTarget* gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::SourceSurface* gfxSourceSurface = static_cast<gfx::SourceSurface*>(aSurface); const gfx::Point* gfxPoint = reinterpret_cast<const gfx::Point*>(aPoint); const gfx::Color* gfxColor = reinterpret_cast<const gfx::Color*>(aColor); const gfx::Point* gfxOffset = reinterpret_cast<const gfx::Point*>(aOffset); gfx::CompositionOp gfxOperator = static_cast<gfx::CompositionOp>(aOperator); gfxDrawTarget->DrawSurfaceWithShadow(gfxSourceSurface, *gfxPoint, *gfxColor, *gfxOffset, aSigma, gfxOperator); } extern "C" AzSourceSurfaceRef AzDrawTargetGetSnapshot(AzDrawTargetRef aDrawTarget) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); RefPtr<gfx::SourceSurface> gfxSourceSurface = gfxDrawTarget->Snapshot(); gfxSourceSurface->AddRef(); return gfxSourceSurface; } extern "C" AzSourceSurfaceRef AzDrawTargetCreateSourceSurfaceFromData(AzDrawTargetRef aDrawTarget, const unsigned char *aData, AzIntSize *aSize, int32_t aStride, AzSurfaceFormat aFormat) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::IntSize *gfxSize = reinterpret_cast<gfx::IntSize*>(aSize); gfx::SurfaceFormat gfxSurfaceFormat = static_cast<gfx::SurfaceFormat>(aFormat); RefPtr<gfx::SourceSurface> gfxSourceSurface = gfxDrawTarget->CreateSourceSurfaceFromData(const_cast<unsigned char *>(aData), *gfxSize, aStride, gfxSurfaceFormat); gfxSourceSurface->AddRef(); return gfxSourceSurface; } extern "C" AzDrawTargetRef AzDrawTargetCreateSimilarDrawTarget(AzDrawTargetRef aDrawTarget, const AzIntSize *aSize, AzSurfaceFormat aFormat) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); const gfx::IntSize *gfxSize = reinterpret_cast<const gfx::IntSize*>(aSize); gfx::SurfaceFormat gfxSurfaceFormat = static_cast<gfx::SurfaceFormat>(aFormat); RefPtr<gfx::DrawTarget> newDrawTarget = gfxDrawTarget->CreateSimilarDrawTarget(*gfxSize, gfxSurfaceFormat); newDrawTarget->AddRef(); return newDrawTarget; } extern "C" AzDrawTargetRef AzDrawTargetCreateShadowDrawTarget(AzDrawTargetRef aDrawTarget, const AzIntSize *aSize, AzSurfaceFormat aFormat, AzFloat aSigma) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); const gfx::IntSize *gfxSize = reinterpret_cast<const gfx::IntSize*>(aSize); gfx::SurfaceFormat gfxSurfaceFormat = static_cast<gfx::SurfaceFormat>(aFormat); RefPtr<gfx::DrawTarget> newDrawTarget = gfxDrawTarget->CreateShadowDrawTarget(*gfxSize, gfxSurfaceFormat, aSigma); newDrawTarget->AddRef(); return newDrawTarget; } extern "C" AzGradientStopsRef AzDrawTargetCreateGradientStops(AzDrawTargetRef aDrawTarget, AzGradientStop *aStops, uint32_t aNumStops, AzExtendMode aExtendMode) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::GradientStop *gfxStops = reinterpret_cast<gfx::GradientStop*>(aStops); gfx::ExtendMode gfxExtendMode = static_cast<gfx::ExtendMode>(aExtendMode); RefPtr<gfx::GradientStops> gfxGradientStops = gfxDrawTarget->CreateGradientStops(gfxStops, aNumStops, gfxExtendMode); gfxGradientStops->AddRef(); return gfxGradientStops; } extern "C" AzSourceSurfaceRef AzRetainSourceSurface(AzSourceSurfaceRef aSurface) { gfx::SourceSurface *gfxSourceSurface = static_cast<gfx::SourceSurface*>(aSurface); gfxSourceSurface->AddRef(); return gfxSourceSurface; } extern "C" void AzReleaseSourceSurface(AzSourceSurfaceRef aSurface) { gfx::SourceSurface *gfxSourceSurface = static_cast<gfx::SourceSurface*>(aSurface); gfxSourceSurface->Release(); } extern "C" AzIntSize AzSourceSurfaceGetSize(AzSourceSurfaceRef aSurface) { gfx::SourceSurface *gfxSourceSurface = static_cast<gfx::SourceSurface*>(aSurface); return IntSizeToC(gfxSourceSurface->GetSize()); } extern "C" AzSurfaceFormat AzSourceSurfaceGetFormat(AzSourceSurfaceRef aSurface) { gfx::SourceSurface *gfxSourceSurface = static_cast<gfx::SourceSurface*>(aSurface); switch (gfxSourceSurface->GetFormat()) { case gfx::SurfaceFormat::B8G8R8A8: return AZ_FORMAT_B8G8R8A8; case gfx::SurfaceFormat::B8G8R8X8: return AZ_FORMAT_B8G8R8X8; case gfx::SurfaceFormat::R8G8B8A8: return AZ_FORMAT_R8G8B8A8; case gfx::SurfaceFormat::R8G8B8X8: return AZ_FORMAT_R8G8B8X8; case gfx::SurfaceFormat::R5G6B5: return AZ_FORMAT_R5G6B5; case gfx::SurfaceFormat::A8: return AZ_FORMAT_A8; case gfx::SurfaceFormat::YUV: return AZ_FORMAT_YUV; case gfx::SurfaceFormat::UNKNOWN: return AZ_FORMAT_UNKNOWN; } } extern "C" AzDataSourceSurfaceRef AzSourceSurfaceGetDataSurface(AzSourceSurfaceRef aSurface) { gfx::SourceSurface *gfxSourceSurface = static_cast<gfx::SourceSurface*>(aSurface); RefPtr<gfx::DataSourceSurface> gfxDataSourceSurface = gfxSourceSurface->GetDataSurface(); gfxDataSourceSurface->AddRef(); return gfxDataSourceSurface; } extern "C" uint8_t *AzDataSourceSurfaceGetData(AzDataSourceSurfaceRef aSurface) { gfx::DataSourceSurface *gfxDataSourceSurface = static_cast<gfx::DataSourceSurface*>(aSurface); return gfxDataSourceSurface->GetData(); } extern "C" int32_t AzDataSourceSurfaceGetStride(AzDataSourceSurfaceRef aSurface) { gfx::DataSourceSurface *gfxDataSourceSurface = static_cast<gfx::DataSourceSurface*>(aSurface); return gfxDataSourceSurface->Stride(); } extern "C" AzScaledFontRef AzCreateScaledFontForNativeFont(AzNativeFont *aNativeFont, AzFloat aSize) { gfx::NativeFont *gfxNativeFont = reinterpret_cast<gfx::NativeFont*>(aNativeFont); RefPtr<gfx::ScaledFont> font = gfx::Factory::CreateScaledFontForNativeFont(*gfxNativeFont, aSize); font->AddRef(); return font; } extern "C" AzScaledFontRef AzCreateScaledFontForTrueTypeData(uint8_t *aData, uint32_t aSize, uint32_t aFaceIndex, AzFloat aGlyphSize, AzFontType) { RefPtr<gfx::ScaledFont> font = new gfx::ScaledFontSkia(aData, aSize, aFaceIndex, aGlyphSize); font->AddRef(); return font; } extern "C" void AzReleaseScaledFont(AzScaledFontRef aFont) { gfx::ScaledFont *gfxFont = static_cast<gfx::ScaledFont*>(aFont); gfxFont->Release(); } extern "C" void AzDrawTargetSetTransform(AzDrawTargetRef aDrawTarget, AzMatrix *aTransform) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::Matrix *gfxMatrix = reinterpret_cast<gfx::Matrix*>(aTransform); gfxDrawTarget->SetTransform(*gfxMatrix); } extern "C" AzFontOptions* AzCreateFontOptionsForName(char *aName, AzFontStyle aStyle) { #ifdef MOZ_ENABLE_FREETYPE gfx::FontOptions *options = new gfx::FontOptions; options->mName = std::string(aName); options->mStyle = static_cast<gfx::FontStyle>(aStyle); return options; #else abort(); #endif } extern "C" void AzDestroyFontOptions(AzFontOptions* aOptions) { #ifdef MOZ_ENABLE_FREETYPE gfx::FontOptions *fontOptions = reinterpret_cast<gfx::FontOptions*>(aOptions); delete fontOptions; #else abort(); #endif } // FIXME: Needs to take a FillRule extern "C" AzPathBuilderRef AzCreatePathBuilder(AzDrawTargetRef aDrawTarget) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); RefPtr<gfx::PathBuilder> gfxPathBuilder = gfxDrawTarget->CreatePathBuilder(); gfxPathBuilder->AddRef(); return gfxPathBuilder; } extern "C" void AzReleasePathBuilder(AzPathBuilderRef aPathBuilder) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); gfxPathBuilder->Release(); } extern "C" void AzPathBuilderMoveTo(AzPathBuilderRef aPathBuilder, const AzPoint *aPoint) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); const gfx::Point *gfxPoint = reinterpret_cast<const gfx::Point*>(aPoint); gfxPathBuilder->MoveTo(*gfxPoint); } extern "C" void AzPathBuilderLineTo(AzPathBuilderRef aPathBuilder, const AzPoint *aPoint) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); const gfx::Point *gfxPoint = reinterpret_cast<const gfx::Point*>(aPoint); gfxPathBuilder->LineTo(*gfxPoint); } extern "C" void AzPathBuilderArc(AzPathBuilderRef aPathBuilder, const AzPoint *aOrigin, AzFloat aRadius, AzFloat aStartAngle, AzFloat aEndAngle, bool aAntiClockwise) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); const gfx::Point *gfxOrigin = reinterpret_cast<const gfx::Point*>(aOrigin); gfxPathBuilder->Arc(*gfxOrigin, aRadius, aStartAngle, aEndAngle, aAntiClockwise); } extern "C" void AzPathBuilderBezierTo(AzPathBuilderRef aPathBuilder, const AzPoint *aControlPoint1, const AzPoint *aControlPoint2, const AzPoint *aControlPoint3) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); const gfx::Point *gfxControlPoint1 = reinterpret_cast<const gfx::Point*>(aControlPoint1); const gfx::Point *gfxControlPoint2 = reinterpret_cast<const gfx::Point*>(aControlPoint2); const gfx::Point *gfxControlPoint3 = reinterpret_cast<const gfx::Point*>(aControlPoint3); gfxPathBuilder->BezierTo(*gfxControlPoint1, *gfxControlPoint2, *gfxControlPoint3); } extern "C" void AzPathBuilderQuadraticBezierTo(AzPathBuilderRef aPathBuilder, const AzPoint *aControlPoint, const AzPoint *aEndPoint) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); const gfx::Point *gfxControlPoint = reinterpret_cast<const gfx::Point*>(aControlPoint); const gfx::Point *gfxEndPoint = reinterpret_cast<const gfx::Point*>(aEndPoint); gfxPathBuilder->QuadraticBezierTo(*gfxControlPoint, *gfxEndPoint); } extern "C" AzPoint AzPathBuilderCurrentPoint(AzPathBuilderRef aPathBuilder) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); AzPoint p; p.x = gfxPathBuilder->CurrentPoint().x; p.y = gfxPathBuilder->CurrentPoint().y; return p; } extern "C" void AzPathBuilderClose(AzPathBuilderRef aPathBuilder) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); gfxPathBuilder->Close(); } extern "C" AzPathRef AzPathBuilderFinish(AzPathBuilderRef aPathBuilder) { gfx::PathBuilder *gfxPathBuilder = static_cast<gfx::PathBuilder*>(aPathBuilder); RefPtr<gfx::Path> gfxPath = gfxPathBuilder->Finish(); gfxPath->AddRef(); return gfxPath; } extern "C" bool AzPathContainsPoint(AzPathRef aPath, const AzPoint *aPoint, const AzMatrix *aMatrix) { gfx::Path *gfxPath = static_cast<gfx::Path*>(aPath); const gfx::Point *gfxPoint = reinterpret_cast<const gfx::Point*>(aPoint); const gfx::Matrix *gfxMatrix = reinterpret_cast<const gfx::Matrix*>(aMatrix); return gfxPath->ContainsPoint(*gfxPoint, *gfxMatrix); } // TODO: need to handle fill rule extern "C" AzPathBuilderRef AzPathCopyToBuilder(AzPathRef aPath) { gfx::Path *gfxPath = static_cast<gfx::Path*>(aPath); RefPtr<gfx::PathBuilder> gfxPathBuilder = gfxPath->CopyToBuilder(); gfxPathBuilder->AddRef(); return gfxPathBuilder; } extern "C" void AzReleasePath(AzPathRef aPath) { gfx::Path *gfxPath = static_cast<gfx::Path*>(aPath); gfxPath->Release(); } extern "C" AzLinearGradientPatternRef AzCreateLinearGradientPattern(const AzPoint *aBegin, const AzPoint *aEnd, AzGradientStopsRef aStops, const AzMatrix *aMatrix) { const gfx::Point *gfxBegin = reinterpret_cast<const gfx::Point*>(aBegin); const gfx::Point *gfxEnd = reinterpret_cast<const gfx::Point*>(aEnd); gfx::GradientStops *gfxStops = reinterpret_cast<gfx::GradientStops*>(aStops); const gfx::Matrix *gfxMatrix = reinterpret_cast<const gfx::Matrix*>(aMatrix); gfx::LinearGradientPattern* gfxLinearGradientPattern = new gfx::LinearGradientPattern(*gfxBegin, *gfxEnd, gfxStops, *gfxMatrix); return gfxLinearGradientPattern; } extern "C" AzLinearGradientPatternRef AzCloneLinearGradientPattern(AzLinearGradientPatternRef aPattern) { gfx::LinearGradientPattern *gfxLinearGradientPattern = static_cast<gfx::LinearGradientPattern*>(aPattern); return new gfx::LinearGradientPattern(gfxLinearGradientPattern->mBegin, gfxLinearGradientPattern->mEnd, gfxLinearGradientPattern->mStops, gfxLinearGradientPattern->mMatrix); } extern "C" AzRadialGradientPatternRef AzCreateRadialGradientPattern(const AzPoint *aCenter1, const AzPoint *aCenter2, AzFloat aRadius1, AzFloat aRadius2, AzGradientStopsRef aStops, const AzMatrix *aMatrix) { const gfx::Point *gfxCenter1 = reinterpret_cast<const gfx::Point*>(aCenter1); const gfx::Point *gfxCenter2 = reinterpret_cast<const gfx::Point*>(aCenter2); gfx::GradientStops *gfxStops = reinterpret_cast<gfx::GradientStops*>(aStops); const gfx::Matrix *gfxMatrix = reinterpret_cast<const gfx::Matrix*>(aMatrix); gfx::RadialGradientPattern* gfxRadialGradientPattern = new gfx::RadialGradientPattern(*gfxCenter1, *gfxCenter2, aRadius1, aRadius2, gfxStops, *gfxMatrix); return gfxRadialGradientPattern; } extern "C" AzRadialGradientPatternRef AzCloneRadialGradientPattern(AzRadialGradientPatternRef aPattern) { gfx::RadialGradientPattern *gfxRadialGradientPattern = static_cast<gfx::RadialGradientPattern*>(aPattern); return new gfx::RadialGradientPattern(gfxRadialGradientPattern->mCenter1, gfxRadialGradientPattern->mCenter2, gfxRadialGradientPattern->mRadius1, gfxRadialGradientPattern->mRadius2, gfxRadialGradientPattern->mStops, gfxRadialGradientPattern->mMatrix); } extern "C" AzSurfacePatternRef AzCreateSurfacePattern(AzSourceSurfaceRef aSurface, AzExtendMode aExtendMode, const AzMatrix* aMatrix) { gfx::SourceSurface *gfxSourceSurface = reinterpret_cast<gfx::SourceSurface*>(aSurface); gfx::ExtendMode gfxExtendMode = static_cast<gfx::ExtendMode>(aExtendMode); const gfx::Matrix *gfxMatrix = reinterpret_cast<const gfx::Matrix*>(aMatrix); gfx::SurfacePattern* gfxSurfacePattern = new gfx::SurfacePattern(gfxSourceSurface, gfxExtendMode, *gfxMatrix); return gfxSurfacePattern; } extern "C" AzSurfacePatternRef AzCloneSurfacePattern(AzSurfacePatternRef aPattern) { gfx::SurfacePattern *gfxSurfacePattern = static_cast<gfx::SurfacePattern*>(aPattern); return new gfx::SurfacePattern(gfxSurfacePattern->mSurface, gfxSurfacePattern->mExtendMode, gfxSurfacePattern->mMatrix, gfxSurfacePattern->mFilter, gfxSurfacePattern->mSamplingRect); } extern "C" AzIntSize AzSurfacePatternGetSize(AzSurfacePatternRef aPattern) { gfx::SurfacePattern *gfxSurfacePattern = static_cast<gfx::SurfacePattern*>(aPattern); return AzSourceSurfaceGetSize(gfxSurfacePattern->mSurface); } extern "C" void AzReleasePattern(AzPatternRef aPattern) { gfx::Pattern *gfxPattern = reinterpret_cast<gfx::Pattern*>(aPattern); delete gfxPattern; } extern "C" void AzReleaseGradientStops(AzGradientStopsRef aStops) { gfx::GradientStops *gfxStops = reinterpret_cast<gfx::GradientStops*>(aStops); gfxStops->Release(); } extern "C" AzFilterNodeRef AzDrawTargetCreateFilter(AzDrawTargetRef aDrawTarget, AzFilterType aType) { gfx::DrawTarget *gfxDrawTarget = static_cast<gfx::DrawTarget*>(aDrawTarget); gfx::FilterType gfxFilterType = static_cast<gfx::FilterType>(aType); return gfxDrawTarget->CreateFilter(gfxFilterType).drop(); } extern "C" void AzReleaseFilterNode(AzFilterNodeRef aFilter) { gfx::FilterNode *gfxFilterNode = reinterpret_cast<gfx::FilterNode*>(aFilter); gfxFilterNode->Release(); } extern "C" void AzFilterNodeSetSourceSurfaceInput(AzFilterNodeRef aFilter, uint32_t aIndex, AzSourceSurfaceRef aSurface) { gfx::FilterNode *gfxFilterNode = reinterpret_cast<gfx::FilterNode*>(aFilter); gfx::SourceSurface *gfxSourceSurface = reinterpret_cast<gfx::SourceSurface*>(aSurface); gfxFilterNode->SetInput(aIndex, gfxSourceSurface); } extern "C" void AzFilterNodeSetFilterNodeInput(AzFilterNodeRef aFilter, uint32_t aIndex, AzFilterNodeRef aInputFilter) { gfx::FilterNode *gfxFilterNode = reinterpret_cast<gfx::FilterNode*>(aFilter); gfx::FilterNode *gfxInputFilterNode = reinterpret_cast<gfx::FilterNode*>(aInputFilter); gfxFilterNode->SetInput(aIndex, gfxInputFilterNode); } extern "C" void AzFilterNodeSetFloatAttribute(AzFilterNodeRef aFilter, uint32_t aIndex, AzFloat aValue) { gfx::FilterNode *gfxFilterNode = reinterpret_cast<gfx::FilterNode*>(aFilter); gfxFilterNode->SetAttribute(aIndex, aValue); } extern "C" void AzFilterNodeSetFloatArrayAttribute(AzFilterNodeRef aFilter, uint32_t aIndex, const AzFloat *aFloats, uint32_t aSize) { gfx::FilterNode *gfxFilterNode = reinterpret_cast<gfx::FilterNode*>(aFilter); gfxFilterNode->SetAttribute(aIndex, aFloats, aSize); } extern "C" void AzFilterNodeSetColorAttribute(AzFilterNodeRef aFilter, uint32_t aIndex, const AzColor *aValue) { gfx::FilterNode *gfxFilterNode = reinterpret_cast<gfx::FilterNode*>(aFilter); const gfx::Color *gfxColor = reinterpret_cast<const gfx::Color*>(aValue); gfxFilterNode->SetAttribute(aIndex, aValue); } extern "C" void AzFilterNodeSetMatrix5x4Attribute(AzFilterNodeRef aFilter, uint32_t aIndex, const AzMatrix5x4 *aValue) { gfx::FilterNode *gfxFilterNode = reinterpret_cast<gfx::FilterNode*>(aFilter); const gfx::Matrix5x4 *gfxMatrix5x4 = reinterpret_cast<const gfx::Matrix5x4*>(aValue); gfxFilterNode->SetAttribute(aIndex, *gfxMatrix5x4); } extern "C" void AzFilterNodeSetBoolAttribute(AzFilterNodeRef aFilter, uint32_t aIndex, bool aValue) { gfx::FilterNode *gfxFilterNode = reinterpret_cast<gfx::FilterNode*>(aFilter); gfxFilterNode->SetAttribute(aIndex, aValue); }
mpl-2.0
AndySpider/GAMCS
src/Agent.cpp
1
2733
// ----------------------------------------------------------------------------- // // GAMCS -- Generalized Agent Model and Computer Simulation // // Copyright (C) 2013-2014, Andy Huang <andyspider@126.com> // // 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 <stdio.h> #include <cfloat> #include "gamcs/Agent.h" #include "gamcs/debug.h" namespace gamcs { const Agent::State Agent::INVALID_STATE = INVALID_INPUT; /**< the same as input, since it's just an alias to input */ const Agent::Action Agent::INVALID_ACTION = INVALID_OUTPUT; /**< the same as output, since it's just an alias to output */ const float Agent::INVALID_PAYOFF = FLT_MAX; /**< use the maximum value to represent the invalid payoff */ /** * @brief The default constructor. * * @param [in] i the agent id * @param [in] dr the discount rate * @param [in] ac the accuracy */ Agent::Agent(int i, float dr, float ac) : id(i), discount_rate(dr), accuracy(ac), learning_mode(ONLINE) { // check validity if (discount_rate >= 1.0 || discount_rate < 0) // [0, 1) ERROR( "Agent - discount rate must be greater than, equal to 0 and less than 1.0!\n"); if (accuracy < 0) // [0, +inf) ERROR("Agent - the accuracy must be greater than, equal to 0.0!\n"); } /** * @brief The default destructor. */ Agent::~Agent() { } /** * @brief Set the learning mode of an agent. * * @param [in] mode the learning mode */ void Agent::setMode(Mode mode) { learning_mode = mode; } /** * @brief Get the current learning mode of an agent. * * @return current learning mode */ Agent::Mode Agent::getMode() { return learning_mode; } /** * @brief The constraining capacity of an agent. * * Use the Maximum Payoff Rule to do the constraining. * @param [in] st the state value * @param [in] acts the action space of current state * @return the sub action space after constraining */ OSpace Agent::constrain(Agent::State st, OSpace &acts) const { if (learning_mode == ONLINE) // using maxPayoffRule in ONLINE mode return maxPayoffRule(st, acts); else if (learning_mode == EXPLORE) // no constraint at all in EXPLORE mode return acts; else { ERROR("Unknown learning mode: %d!\n", learning_mode); return OSpace(); } } /** * @brief Update the inner data of an agent. * * @see updateMemory() */ void Agent::update(float oripayoff) { updateMemory(oripayoff); // update memory TSGIOM::update(); // as a TSGIOM, invoke the basic update function return; } } // namespace gamcs
mpl-2.0
mojovski/openMVG
src/openMVG/sfm/sfm_data_io_test.cpp
3
6008
// Copyright (c) 2015 Pierre MOULON. // 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 "openMVG/sfm/sfm.hpp" #include "testing/testing.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <sstream> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::sfm; // Create a SfM scene with desired count of views & poses & intrinsic (shared or not) // Add a 3D point with observation in 2 view (just in order to have non empty data) SfM_Data create_test_scene(IndexT viewsCount, bool bSharedIntrinsic) { SfM_Data sfm_data; sfm_data.s_root_path = "./"; for(IndexT i = 0; i < viewsCount; ++i) { // Add views std::ostringstream os; os << "dataset/" << i << ".jpg"; const IndexT id_view = i, id_pose = i; const IndexT id_intrinsic = bSharedIntrinsic ? 0 : i; //(shared or not intrinsics) sfm_data.views[id_view] = std::make_shared<View>(os.str(),id_view, id_intrinsic, id_pose, 1000, 1000); // Add poses sfm_data.poses[i] = Pose3(); // Add intrinsics if (bSharedIntrinsic) { if (i == 0) sfm_data.intrinsics[0] = std::make_shared<Pinhole_Intrinsic>(); } else { sfm_data.intrinsics[i] = std::make_shared<Pinhole_Intrinsic>(); } } // Fill with not meaningful tracks Observations obs; obs[0] = Observation( Vec2(10,20), 0); obs[1] = Observation( Vec2(30,10), 1); sfm_data.structure[0].obs = obs; sfm_data.structure[0].X = Vec3(11,22,33); return sfm_data; } TEST(SfM_Data_IO, SAVE_LOAD_JSON) { const std::vector<std::string> ext_Type = {"json", "bin", "xml"}; for (int i=0; i < ext_Type.size(); ++i) { std::ostringstream os; os << "SAVE_LOAD" << "." << ext_Type[i]; const std::string filename = os.str(); std::cout << "Testing:" << filename << std::endl; // SAVE { const SfM_Data sfm_data = create_test_scene(2, true); EXPECT_TRUE( Save(sfm_data, filename, ALL) ); } // LOAD { const SfM_Data sfm_data = create_test_scene(2, true); EXPECT_TRUE( Save(sfm_data, filename, ALL) ); SfM_Data sfm_data_load; ESfM_Data flags_part = ALL; EXPECT_TRUE( Load(sfm_data_load, filename, flags_part) ); EXPECT_EQ( sfm_data_load.views.size(), sfm_data.views.size()); EXPECT_EQ( sfm_data_load.poses.size(), sfm_data.poses.size()); EXPECT_EQ( sfm_data_load.intrinsics.size(), sfm_data.intrinsics.size()); EXPECT_EQ( sfm_data_load.structure.size(), sfm_data.structure.size()); } // LOAD (only a subpart: VIEWS) { const SfM_Data sfm_data = create_test_scene(2, true); EXPECT_TRUE( Save(sfm_data, filename, ALL) ); SfM_Data sfm_data_load; ESfM_Data flags_part = VIEWS; EXPECT_TRUE( Load(sfm_data_load, filename, flags_part) ); EXPECT_EQ( sfm_data_load.views.size(), sfm_data.views.size()); EXPECT_EQ( sfm_data_load.poses.size(), 0); EXPECT_EQ( sfm_data_load.intrinsics.size(), 0); EXPECT_EQ( sfm_data_load.structure.size(), 0); } // LOAD (only a subpart: POSES) { const SfM_Data sfm_data = create_test_scene(2, true); EXPECT_TRUE( Save(sfm_data, filename, ALL) ); SfM_Data sfm_data_load; ESfM_Data flags_part = EXTRINSICS; EXPECT_TRUE( Load(sfm_data_load, filename, flags_part) ); EXPECT_EQ( sfm_data_load.views.size(), 0); EXPECT_EQ( sfm_data_load.poses.size(), sfm_data.poses.size()); EXPECT_EQ( sfm_data_load.intrinsics.size(), 0); EXPECT_EQ( sfm_data_load.structure.size(), 0); } // LOAD (only a subpart: INTRINSICS) { const SfM_Data sfm_data = create_test_scene(2, true); EXPECT_TRUE( Save(sfm_data, filename, ALL) ); SfM_Data sfm_data_load; ESfM_Data flags_part = INTRINSICS; EXPECT_TRUE( Load(sfm_data_load, filename, flags_part) ); EXPECT_EQ( sfm_data_load.views.size(), 0); EXPECT_EQ( sfm_data_load.poses.size(), 0); EXPECT_EQ( sfm_data_load.intrinsics.size(), sfm_data.intrinsics.size()); EXPECT_EQ( sfm_data_load.structure.size(), 0); } // LOAD (subparts: COMBINED) { const SfM_Data sfm_data = create_test_scene(2,false); //2 intrinsics group here EXPECT_TRUE( Save(sfm_data, filename, ALL) ); SfM_Data sfm_data_load; ESfM_Data flags_part = ESfM_Data(INTRINSICS | EXTRINSICS); EXPECT_TRUE( Load(sfm_data_load, filename, flags_part) ); EXPECT_EQ( sfm_data_load.views.size(), 0); EXPECT_EQ( sfm_data_load.poses.size(), sfm_data.poses.size()); EXPECT_EQ( sfm_data_load.intrinsics.size(), sfm_data.intrinsics.size()); EXPECT_EQ( sfm_data_load.structure.size(), 0); } // LOAD (subparts: COMBINED) { const SfM_Data sfm_data = create_test_scene(2, true); EXPECT_TRUE( Save(sfm_data, filename, ALL) ); SfM_Data sfm_data_load; ESfM_Data flags_part = ESfM_Data(VIEWS | INTRINSICS | EXTRINSICS); EXPECT_TRUE( Load(sfm_data_load, filename, flags_part) ); EXPECT_EQ( sfm_data_load.views.size(), sfm_data.views.size()); EXPECT_EQ( sfm_data_load.poses.size(), sfm_data.poses.size()); EXPECT_EQ( sfm_data_load.intrinsics.size(), sfm_data.intrinsics.size()); EXPECT_EQ( sfm_data_load.structure.size(), 0); } } } TEST(SfM_Data_IO, SAVE_PLY) { // SAVE as PLY { std::ostringstream os; os << "SAVE_LOAD" << ".ply"; const std::string filename = os.str(); std::cout << "Testing:" << filename << std::endl; const SfM_Data sfm_data = create_test_scene(2, true); ESfM_Data flags_part = ESfM_Data(EXTRINSICS | STRUCTURE); EXPECT_TRUE( Save(sfm_data, filename, flags_part) ); EXPECT_TRUE( stlplus::is_file(filename) ); } } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */
mpl-2.0
dptechnics/Espruino
targetlibs/nrf5x/nrf52_sdk/components/drivers_nrf/spi_master/nrf_drv_spi.c
4
15479
/* Copyright (c) 2015 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "nrf_drv_spi.h" #include "nrf_drv_common.h" #include "nrf_gpio.h" #include "nrf_assert.h" #include "app_util_platform.h" // This set of macros makes it possible to exclude parts of code when one type // of supported peripherals is not used. #if ((SPI0_ENABLED == 1 && SPI0_USE_EASY_DMA == 1 && defined(NRF52)) || \ (SPI1_ENABLED == 1 && SPI1_USE_EASY_DMA == 1) || \ (SPI2_ENABLED == 1 && SPI2_USE_EASY_DMA == 1)) #define SPIM_IN_USE #endif #if ((SPI0_ENABLED == 1 && SPI0_USE_EASY_DMA == 0) || \ (SPI0_ENABLED == 1 && defined(NRF51)) || \ (SPI1_ENABLED == 1 && SPI1_USE_EASY_DMA == 0) || \ (SPI2_ENABLED == 1 && SPI2_USE_EASY_DMA == 0)) #define SPI_IN_USE #endif #if (defined(SPIM_IN_USE) && defined(SPI_IN_USE)) // SPIM and SPI combined #define CODE_FOR_SPIM(code) if (p_instance->use_easy_dma) { code } #define CODE_FOR_SPI(code) else { code } #elif (defined(SPIM_IN_USE) && !defined(SPI_IN_USE)) // SPIM only #define CODE_FOR_SPIM(code) { code } #define CODE_FOR_SPI(code) #elif (!defined(SPIM_IN_USE) && defined(SPI_IN_USE)) // SPI only #define CODE_FOR_SPIM(code) #define CODE_FOR_SPI(code) { code } #else #error "Wrong configuration." #endif // Control block - driver instance local data. typedef struct { nrf_drv_spi_handler_t handler; nrf_drv_state_t state; volatile bool transfer_in_progress; // [no need for 'volatile' attribute for the following members, as they // are not concurrently used in IRQ handlers and main line code] uint8_t ss_pin; uint8_t orc; uint8_t tx_buffer_length; uint8_t rx_buffer_length; uint8_t bytes_transferred; uint8_t const * p_tx_buffer; uint8_t * p_rx_buffer; bool tx_done : 1; bool rx_done : 1; } spi_control_block_t; static spi_control_block_t m_cb[SPI_COUNT]; static nrf_drv_spi_config_t const m_default_config[SPI_COUNT] = { #if (SPI0_ENABLED == 1) NRF_DRV_SPI_DEFAULT_CONFIG(0), #endif #if (SPI1_ENABLED == 1) NRF_DRV_SPI_DEFAULT_CONFIG(1), #endif #if (SPI2_ENABLED == 1) NRF_DRV_SPI_DEFAULT_CONFIG(2), #endif }; ret_code_t nrf_drv_spi_init(nrf_drv_spi_t const * const p_instance, nrf_drv_spi_config_t const * p_config, nrf_drv_spi_handler_t handler) { spi_control_block_t * p_cb = &m_cb[p_instance->drv_inst_idx]; if (p_cb->state != NRF_DRV_STATE_UNINITIALIZED) { return NRF_ERROR_INVALID_STATE; } if (p_config == NULL) { p_config = &m_default_config[p_instance->drv_inst_idx]; } p_cb->handler = handler; uint32_t mosi_pin; uint32_t miso_pin; // Configure pins used by the peripheral: // - SCK - output with initial value corresponding with the SPI mode used: // 0 - for modes 0 and 1 (CPOL = 0), 1 - for modes 2 and 3 (CPOL = 1); // according to the reference manual guidelines this pin and its input // buffer must always be connected for the SPI to work. if (p_config->mode <= NRF_DRV_SPI_MODE_1) { nrf_gpio_pin_clear(p_config->sck_pin); } else { nrf_gpio_pin_set(p_config->sck_pin); } NRF_GPIO->PIN_CNF[p_config->sck_pin] = (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos); // - MOSI (optional) - output with initial value 0, if (p_config->mosi_pin != NRF_DRV_SPI_PIN_NOT_USED) { mosi_pin = p_config->mosi_pin; nrf_gpio_pin_clear(mosi_pin); nrf_gpio_cfg_output(mosi_pin); } else { mosi_pin = NRF_SPI_PIN_NOT_CONNECTED; } // - MISO (optional) - input, if (p_config->miso_pin != NRF_DRV_SPI_PIN_NOT_USED) { miso_pin = p_config->miso_pin; nrf_gpio_cfg_input(miso_pin, NRF_GPIO_PIN_NOPULL); } else { miso_pin = NRF_SPI_PIN_NOT_CONNECTED; } // - Slave Select (optional) - output with initial value 1 (inactive). if (p_config->ss_pin != NRF_DRV_SPI_PIN_NOT_USED) { nrf_gpio_pin_set(p_config->ss_pin); nrf_gpio_cfg_output(p_config->ss_pin); } m_cb[p_instance->drv_inst_idx].ss_pin = p_config->ss_pin; CODE_FOR_SPIM ( NRF_SPIM_Type * p_spim = p_instance->p_registers; nrf_spim_pins_set(p_spim, p_config->sck_pin, mosi_pin, miso_pin); nrf_spim_frequency_set(p_spim, (nrf_spim_frequency_t)p_config->frequency); nrf_spim_configure(p_spim, (nrf_spim_mode_t)p_config->mode, (nrf_spim_bit_order_t)p_config->bit_order); nrf_spim_orc_set(p_spim, p_config->orc); if (p_cb->handler) { nrf_spim_int_enable(p_spim, NRF_SPIM_INT_ENDTX_MASK | NRF_SPIM_INT_ENDRX_MASK | NRF_SPIM_INT_STOPPED_MASK); } nrf_spim_enable(p_spim); ) CODE_FOR_SPI ( NRF_SPI_Type * p_spi = p_instance->p_registers; nrf_spi_pins_set(p_spi, p_config->sck_pin, mosi_pin, miso_pin); nrf_spi_frequency_set(p_spi, (nrf_spi_frequency_t)p_config->frequency); nrf_spi_configure(p_spi, (nrf_spi_mode_t)p_config->mode, (nrf_spi_bit_order_t)p_config->bit_order); m_cb[p_instance->drv_inst_idx].orc = p_config->orc; if (p_cb->handler) { nrf_spi_int_enable(p_spi, NRF_SPI_INT_READY_MASK); } nrf_spi_enable(p_spi); ) if (p_cb->handler) { nrf_drv_common_irq_enable(p_instance->irq, p_config->irq_priority); } p_cb->transfer_in_progress = false; p_cb->state = NRF_DRV_STATE_INITIALIZED; return NRF_SUCCESS; } void nrf_drv_spi_uninit(nrf_drv_spi_t const * const p_instance) { spi_control_block_t * p_cb = &m_cb[p_instance->drv_inst_idx]; ASSERT(p_cb->state != NRF_DRV_STATE_UNINITIALIZED); if (p_cb->handler) { nrf_drv_common_irq_disable(p_instance->irq); } #define DISABLE_ALL 0xFFFFFFFF CODE_FOR_SPIM ( NRF_SPIM_Type * p_spim = p_instance->p_registers; if (p_cb->handler) { nrf_spim_int_disable(p_spim, DISABLE_ALL); } nrf_spim_disable(p_spim); ) CODE_FOR_SPI ( NRF_SPI_Type * p_spi = p_instance->p_registers; if (p_cb->handler) { nrf_spi_int_disable(p_spi, DISABLE_ALL); } nrf_spi_disable(p_spi); ) #undef DISABLE_ALL p_cb->state = NRF_DRV_STATE_UNINITIALIZED; } #ifdef SPI_IN_USE // This function is called from IRQ handler or, in blocking mode, directly // from the 'nrf_drv_spi_transfer' function. // It returns true as long as the transfer should be continued, otherwise (when // there is nothing more to send/receive) it returns false. static bool transfer_byte(NRF_SPI_Type * p_spi, spi_control_block_t * p_cb) { // Read the data byte received in this transfer and store it in RX buffer, // if needed. volatile uint8_t rx_data = nrf_spi_rxd_get(p_spi); if (p_cb->bytes_transferred < p_cb->rx_buffer_length) { p_cb->p_rx_buffer[p_cb->bytes_transferred] = rx_data; } ++p_cb->bytes_transferred; // Check if there are more bytes to send or receive and write proper data // byte (next one from TX buffer or over-run character) to the TXD register // when needed. // NOTE - we've already used 'p_cb->bytes_transferred+1' bytes from our // buffers, because we take advantage of double buffering of TXD // register (so in effect one byte is still being transmitted now); // see how the transfer is started in the 'nrf_drv_spi_transfer' // function. uint8_t bytes_used = p_cb->bytes_transferred+1; if (bytes_used < p_cb->tx_buffer_length) { nrf_spi_txd_set(p_spi, p_cb->p_tx_buffer[bytes_used]); return true; } else if (bytes_used < p_cb->rx_buffer_length) { nrf_spi_txd_set(p_spi, p_cb->orc); return true; } return (p_cb->bytes_transferred < p_cb->tx_buffer_length || p_cb->bytes_transferred < p_cb->rx_buffer_length); } #endif // SPI_IN_USE ret_code_t nrf_drv_spi_transfer(nrf_drv_spi_t const * const p_instance, uint8_t const * p_tx_buffer, uint8_t tx_buffer_length, uint8_t * p_rx_buffer, uint8_t rx_buffer_length) { spi_control_block_t * p_cb = &m_cb[p_instance->drv_inst_idx]; ASSERT(p_cb->state == NRF_DRV_STATE_POWERED_ON); ASSERT(p_tx_buffer != NULL || tx_buffer_length == 0); ASSERT(p_rx_buffer != NULL || rx_buffer_length == 0); if (p_cb->transfer_in_progress) { return NRF_ERROR_BUSY; } // Finish zero-length transfers immediately. if (tx_buffer_length == 0 && rx_buffer_length == 0) { return NRF_SUCCESS; } // Activate Slave Select signal, if it is to be used. if (p_cb->ss_pin != NRF_DRV_SPI_PIN_NOT_USED) { nrf_gpio_pin_clear(p_cb->ss_pin); } CODE_FOR_SPIM ( // EasyDMA requires that transfer buffers are placed in Data RAM region; // signal error if they are not. if ((p_tx_buffer != NULL && !nrf_drv_is_in_RAM(p_tx_buffer)) || (p_rx_buffer != NULL && !nrf_drv_is_in_RAM(p_rx_buffer))) { return NRF_ERROR_INVALID_ADDR; } NRF_SPIM_Type * p_spim = p_instance->p_registers; nrf_spim_tx_buffer_set(p_spim, p_tx_buffer, tx_buffer_length); nrf_spim_rx_buffer_set(p_spim, p_rx_buffer, rx_buffer_length); nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_ENDTX); nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_ENDRX); p_cb->tx_done = false; p_cb->rx_done = false; nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_STOPPED); nrf_spim_task_trigger(p_spim, NRF_SPIM_TASK_START); if (p_cb->handler) { p_cb->transfer_in_progress = true; } else { while (!nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_ENDTX) || !nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_ENDRX)) {} // Stop the peripheral after transaction is finished. nrf_spim_task_trigger(p_spim, NRF_SPIM_TASK_STOP); while (!nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_STOPPED)) {} } ) CODE_FOR_SPI ( NRF_SPI_Type * p_spi = p_instance->p_registers; p_cb->p_tx_buffer = p_tx_buffer; p_cb->tx_buffer_length = tx_buffer_length; p_cb->p_rx_buffer = p_rx_buffer; p_cb->rx_buffer_length = rx_buffer_length; p_cb->bytes_transferred = 0; nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY); // Start the transfer by writing some byte to the TXD register; // if TX buffer is not empty, take the first byte from this buffer, // otherwise - use over-run character. nrf_spi_txd_set(p_spi, (tx_buffer_length > 0 ? p_tx_buffer[0] : p_cb->orc)); // TXD register is double buffered, so next byte to be transmitted can // be written immediately, if needed, i.e. if TX or RX transfer is to // be more that 1 byte long. Again - if there is something more in TX // buffer send it, otherwise use over-run character. if (tx_buffer_length > 1) { nrf_spi_txd_set(p_spi, p_tx_buffer[1]); } else if (rx_buffer_length > 1) { nrf_spi_txd_set(p_spi, p_cb->orc); } // For blocking mode (user handler not provided) wait here for READY // events (indicating that the byte from TXD register was transmitted // and a new incoming byte was moved to the RXD register) and continue // transaction until all requested bytes are transferred. // In non-blocking mode - IRQ service routine will do this stuff. if (p_cb->handler) { p_cb->transfer_in_progress = true; } else { do { while (!nrf_spi_event_check(p_spi, NRF_SPI_EVENT_READY)) {} nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY); } while (transfer_byte(p_spi, p_cb)); } ) return NRF_SUCCESS; } static void finish_transfer(spi_control_block_t * p_cb) { // If Slave Select signal is used, this is the time to deactivate it. if (p_cb->ss_pin != NRF_DRV_SPI_PIN_NOT_USED) { nrf_gpio_pin_set(p_cb->ss_pin); } // By clearing this flag before calling the handler we allow subsequent // transfers to be started directly from the handler function. p_cb->transfer_in_progress = false; p_cb->handler(NRF_DRV_SPI_EVENT_DONE); } #ifdef SPIM_IN_USE static void irq_handler_spim(NRF_SPIM_Type * p_spim, spi_control_block_t * p_cb) { ASSERT(p_cb->handler); if (nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_STOPPED)) { nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_STOPPED); finish_transfer(p_cb); } else { if (nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_ENDTX)) { nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_ENDTX); p_cb->tx_done = true; } if (nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_ENDRX)) { nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_ENDRX); p_cb->rx_done = true; } if (p_cb->tx_done && p_cb->rx_done) { nrf_spim_task_trigger(p_spim, NRF_SPIM_TASK_STOP); } } } #endif // SPIM_IN_USE #ifdef SPI_IN_USE static void irq_handler_spi(NRF_SPI_Type * p_spi, spi_control_block_t * p_cb) { ASSERT(p_cb->handler); nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY); if (!transfer_byte(p_spi, p_cb)) { finish_transfer(p_cb); } } #endif // SPI_IN_USE #if (SPI0_ENABLED == 1) void SPI0_IRQ_HANDLER(void) { #if (SPI0_USE_EASY_DMA == 1) && defined(NRF52) irq_handler_spim(NRF_SPIM0, #else irq_handler_spi(NRF_SPI0, #endif &m_cb[SPI0_INSTANCE_INDEX]); } #endif // (SPI0_ENABLED == 1) #if (SPI1_ENABLED == 1) void SPI1_IRQ_HANDLER(void) { #if (SPI1_USE_EASY_DMA == 1) irq_handler_spim(NRF_SPIM1, #else irq_handler_spi(NRF_SPI1, #endif &m_cb[SPI1_INSTANCE_INDEX]); } #endif // (SPI1_ENABLED == 1) #if (SPI2_ENABLED == 1) void SPI2_IRQ_HANDLER(void) { #if (SPI2_USE_EASY_DMA == 1) irq_handler_spim(NRF_SPIM2, #else irq_handler_spi(NRF_SPI2, #endif &m_cb[SPI2_INSTANCE_INDEX]); } #endif // (SPI2_ENABLED == 1)
mpl-2.0
mozilla/stoneridge
python/src/Modules/_ctypes/libffi_msvc/ffi.c
7
11292
/* ----------------------------------------------------------------------- ffi.c - Copyright (c) 1996, 1998, 1999, 2001 Red Hat, Inc. Copyright (c) 2002 Ranjit Mathew Copyright (c) 2002 Bo Thorsen Copyright (c) 2002 Roger Sayle x86 Foreign Function Interface Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include <ffi.h> #include <ffi_common.h> #include <stdlib.h> /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments */ extern void Py_FatalError(const char *msg); /*@-exportheader@*/ void ffi_prep_args(char *stack, extended_cif *ecif) /*@=exportheader@*/ { register unsigned int i; register void **p_argv; register char *argp; register ffi_type **p_arg; argp = stack; if (ecif->cif->rtype->type == FFI_TYPE_STRUCT) { *(void **) argp = ecif->rvalue; argp += sizeof(void *); } p_argv = ecif->avalue; for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; i != 0; i--, p_arg++) { size_t z; /* Align if necessary */ if ((sizeof(void *) - 1) & (size_t) argp) argp = (char *) ALIGN(argp, sizeof(void *)); z = (*p_arg)->size; if (z < sizeof(int)) { z = sizeof(int); switch ((*p_arg)->type) { case FFI_TYPE_SINT8: *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); break; case FFI_TYPE_UINT8: *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); break; case FFI_TYPE_SINT16: *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); break; case FFI_TYPE_UINT16: *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); break; case FFI_TYPE_SINT32: *(signed int *) argp = (signed int)*(SINT32 *)(* p_argv); break; case FFI_TYPE_UINT32: *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); break; case FFI_TYPE_STRUCT: *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); break; default: FFI_ASSERT(0); } } else { memcpy(argp, *p_argv, z); } p_argv++; argp += z; } if (argp - stack > ecif->cif->bytes) { Py_FatalError("FFI BUG: not enough stack space for arguments"); } return; } /* Perform machine dependent cif processing */ ffi_status ffi_prep_cif_machdep(ffi_cif *cif) { /* Set the return type flag */ switch (cif->rtype->type) { case FFI_TYPE_VOID: case FFI_TYPE_STRUCT: case FFI_TYPE_SINT64: case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: case FFI_TYPE_LONGDOUBLE: cif->flags = (unsigned) cif->rtype->type; break; case FFI_TYPE_UINT64: #ifdef _WIN64 case FFI_TYPE_POINTER: #endif cif->flags = FFI_TYPE_SINT64; break; default: cif->flags = FFI_TYPE_INT; break; } return FFI_OK; } #ifdef _WIN32 extern int ffi_call_x86(void (*)(char *, extended_cif *), /*@out@*/ extended_cif *, unsigned, unsigned, /*@out@*/ unsigned *, void (*fn)()); #endif #ifdef _WIN64 extern int ffi_call_AMD64(void (*)(char *, extended_cif *), /*@out@*/ extended_cif *, unsigned, unsigned, /*@out@*/ unsigned *, void (*fn)()); #endif int ffi_call(/*@dependent@*/ ffi_cif *cif, void (*fn)(), /*@out@*/ void *rvalue, /*@dependent@*/ void **avalue) { extended_cif ecif; ecif.cif = cif; ecif.avalue = avalue; /* If the return value is a struct and we don't have a return */ /* value address then we need to make one */ if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; switch (cif->abi) { #if !defined(_WIN64) case FFI_SYSV: case FFI_STDCALL: return ffi_call_x86(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue, fn); break; #else case FFI_SYSV: /*@-usedef@*/ /* Function call needs at least 40 bytes stack size, on win64 AMD64 */ return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes ? cif->bytes : 40, cif->flags, ecif.rvalue, fn); /*@=usedef@*/ break; #endif default: FFI_ASSERT(0); break; } return -1; /* theller: Hrm. */ } /** private members **/ static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, void** args, ffi_cif* cif); /* This function is jumped to by the trampoline */ #ifdef _WIN64 void * #else static void __fastcall #endif ffi_closure_SYSV (ffi_closure *closure, int *argp) { // this is our return value storage long double res; // our various things... ffi_cif *cif; void **arg_area; unsigned short rtype; void *resp = (void*)&res; void *args = &argp[1]; cif = closure->cif; arg_area = (void**) alloca (cif->nargs * sizeof (void*)); /* this call will initialize ARG_AREA, such that each * element in that array points to the corresponding * value on the stack; and if the function returns * a structure, it will re-set RESP to point to the * structure return address. */ ffi_prep_incoming_args_SYSV(args, (void**)&resp, arg_area, cif); (closure->fun) (cif, resp, arg_area, closure->user_data); rtype = cif->flags; #if defined(_WIN32) && !defined(_WIN64) #ifdef _MSC_VER /* now, do a generic return based on the value of rtype */ if (rtype == FFI_TYPE_INT) { _asm mov eax, resp ; _asm mov eax, [eax] ; } else if (rtype == FFI_TYPE_FLOAT) { _asm mov eax, resp ; _asm fld DWORD PTR [eax] ; // asm ("flds (%0)" : : "r" (resp) : "st" ); } else if (rtype == FFI_TYPE_DOUBLE) { _asm mov eax, resp ; _asm fld QWORD PTR [eax] ; // asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); } else if (rtype == FFI_TYPE_LONGDOUBLE) { // asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); } else if (rtype == FFI_TYPE_SINT64) { _asm mov edx, resp ; _asm mov eax, [edx] ; _asm mov edx, [edx + 4] ; // asm ("movl 0(%0),%%eax;" // "movl 4(%0),%%edx" // : : "r"(resp) // : "eax", "edx"); } #else /* now, do a generic return based on the value of rtype */ if (rtype == FFI_TYPE_INT) { asm ("movl (%0),%%eax" : : "r" (resp) : "eax"); } else if (rtype == FFI_TYPE_FLOAT) { asm ("flds (%0)" : : "r" (resp) : "st" ); } else if (rtype == FFI_TYPE_DOUBLE) { asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); } else if (rtype == FFI_TYPE_LONGDOUBLE) { asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); } else if (rtype == FFI_TYPE_SINT64) { asm ("movl 0(%0),%%eax;" "movl 4(%0),%%edx" : : "r"(resp) : "eax", "edx"); } #endif #endif #ifdef _WIN64 /* The result is returned in rax. This does the right thing for result types except for floats; we have to 'mov xmm0, rax' in the caller to correct this. */ return *(void **)resp; #endif } /*@-exportheader@*/ static void ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, void **avalue, ffi_cif *cif) /*@=exportheader@*/ { register unsigned int i; register void **p_argv; register char *argp; register ffi_type **p_arg; argp = stack; if ( cif->rtype->type == FFI_TYPE_STRUCT ) { *rvalue = *(void **) argp; argp += 4; } p_argv = avalue; for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) { size_t z; /* Align if necessary */ if ((sizeof(char *) - 1) & (size_t) argp) { argp = (char *) ALIGN(argp, sizeof(char*)); } z = (*p_arg)->size; /* because we're little endian, this is what it turns into. */ *p_argv = (void*) argp; p_argv++; argp += z; } return; } /* the cif must already be prep'ed */ extern void ffi_closure_OUTER(); ffi_status ffi_prep_closure_loc (ffi_closure* closure, ffi_cif* cif, void (*fun)(ffi_cif*,void*,void**,void*), void *user_data, void *codeloc) { short bytes; char *tramp; #ifdef _WIN64 int mask = 0; #endif FFI_ASSERT (cif->abi == FFI_SYSV); if (cif->abi == FFI_SYSV) bytes = 0; #if !defined(_WIN64) else if (cif->abi == FFI_STDCALL) bytes = cif->bytes; #endif else return FFI_BAD_ABI; tramp = &closure->tramp[0]; #define BYTES(text) memcpy(tramp, text, sizeof(text)), tramp += sizeof(text)-1 #define POINTER(x) *(void**)tramp = (void*)(x), tramp += sizeof(void*) #define SHORT(x) *(short*)tramp = x, tramp += sizeof(short) #define INT(x) *(int*)tramp = x, tramp += sizeof(int) #ifdef _WIN64 if (cif->nargs >= 1 && (cif->arg_types[0]->type == FFI_TYPE_FLOAT || cif->arg_types[0]->type == FFI_TYPE_DOUBLE)) mask |= 1; if (cif->nargs >= 2 && (cif->arg_types[1]->type == FFI_TYPE_FLOAT || cif->arg_types[1]->type == FFI_TYPE_DOUBLE)) mask |= 2; if (cif->nargs >= 3 && (cif->arg_types[2]->type == FFI_TYPE_FLOAT || cif->arg_types[2]->type == FFI_TYPE_DOUBLE)) mask |= 4; if (cif->nargs >= 4 && (cif->arg_types[3]->type == FFI_TYPE_FLOAT || cif->arg_types[3]->type == FFI_TYPE_DOUBLE)) mask |= 8; /* 41 BB ---- mov r11d,mask */ BYTES("\x41\xBB"); INT(mask); /* 48 B8 -------- mov rax, closure */ BYTES("\x48\xB8"); POINTER(closure); /* 49 BA -------- mov r10, ffi_closure_OUTER */ BYTES("\x49\xBA"); POINTER(ffi_closure_OUTER); /* 41 FF E2 jmp r10 */ BYTES("\x41\xFF\xE2"); #else /* mov ecx, closure */ BYTES("\xb9"); POINTER(closure); /* mov edx, esp */ BYTES("\x8b\xd4"); /* call ffi_closure_SYSV */ BYTES("\xe8"); POINTER((char*)&ffi_closure_SYSV - (tramp + 4)); /* ret bytes */ BYTES("\xc2"); SHORT(bytes); #endif if (tramp - &closure->tramp[0] > FFI_TRAMPOLINE_SIZE) Py_FatalError("FFI_TRAMPOLINE_SIZE too small in " __FILE__); closure->cif = cif; closure->user_data = user_data; closure->fun = fun; return FFI_OK; }
mpl-2.0
TamirEvan/mupdf
source/fitz/output-pdfocr.c
1
31323
// Copyright (C) 2004-2021 Artifex Software, Inc. // // This file is part of MuPDF. // // MuPDF 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. // // MuPDF 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. // // You should have received a copy of the GNU Affero General Public License // along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html> // // Alternative licensing terms are available from the licensor. // For commercial licensing, see <https://www.artifex.com/> or contact // Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, // CA 94945, U.S.A., +1(415)492-9861, for further information. #include "mupdf/fitz.h" #include <string.h> #include <limits.h> #ifdef OCR_DISABLED /* In non-OCR builds, we need to define this otherwise SWIG Python gets SEGV when it attempts to import mupdf.py and _mupdf.py. */ const char *fz_pdfocr_write_options_usage = ""; #else #include "tessocr.h" const char *fz_pdfocr_write_options_usage = "PDFOCR output options:\n" "\tcompression=none: No compression (default)\n" "\tcompression=flate: Flate compression\n" "\tstrip-height=N: Strip height (default 0=fullpage)\n" "\tocr-language=<lang>: OCR language (default=eng)\n" "\tocr-datadir=<datadir>: OCR data path (default=rely on TESSDATA_PREFIX)\n" "\n"; static const char funky_font[] = "3 0 obj\n<</BaseFont/GlyphLessFont/DescendantFonts[4 0 R]" "/Encoding/Identity-H/Subtype/Type0/ToUnicode 6 0 R/Type/Font" ">>\nendobj\n"; static const char funky_font2[] = "4 0 obj\n" "<</BaseFont/GlyphLessFont/CIDToGIDMap 5 0 R" "/CIDSystemInfo<</Ordering (Identity)/Registry (Adobe)/Supplement 0>>" "/FontDescriptor 7 0 R/Subtype/CIDFontType2/Type/Font/DW 500>>" "\nendobj\n"; static const char funky_font3[] = "5 0 obj\n<</Length 210/Filter/FlateDecode>>\nstream\n" "\x78\x9c\xec\xc2\x01\x09\x00\x00\x00\x02\xa0\xfa\x7f\xba\x21\x89" "\xa6\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x80\x7b\x03\x00\x00\xff\xff\xec\xc2\x01\x0d\x00\x00\x00\xc2\x20" "\xdf\xbf\xb4\x45\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\xeb\x00\x00\x00\xff\xff\xec\xc2\x01\x0d\x00" "\x00\x00\xc2\x20\xdf\xbf\xb4\x45\x18\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\xeb\x00\x00\x00\xff\xff\xed" "\xc2\x01\x0d\x00\x00\x00\xc2\x20\xdf\xbf\xb4\x45\x18\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xeb\x00\xff" "\x00\x10" "\nendstream\nendobj\n"; static const char funky_font4[] = "6 0 obj\n<</Length 353>>\nstream\n" "/CIDInit /ProcSet findresource begin\n" "12 dict begin\n" "begincmap\n" "/CIDSystemInfo\n" "<<\n" " /Registry (Adobe)\n" " /Ordering (UCS)\n" " /Supplement 0\n" ">> def\n" "/CMapName /Adobe-Identity-UCS def\n" "/CMapType 2 def\n" "1 begincodespacerange\n" "<0000> <FFFF>\n" "endcodespacerange\n" "1 beginbfrange\n" "<0000> <FFFF> <0000>\n" "endbfrange\n" "endcmap\n" "CMapName currentdict /CMap defineresource pop\n" "end\n" "end\n" "endstream\n" "endobj\n"; static const char funky_font5[] = "7 0 obj\n" "<</Ascent 1000/CapHeight 1000/Descent -1/Flags 5" "/FontBBox[0 0 500 1000]/FontFile2 8 0 R/FontName/GlyphLessFont" "/ItalicAngle 0/StemV 80/Type/FontDescriptor>>\nendobj\n"; static const char funky_font6[] = "8 0 obj\n<</Length 572/Length1 572>>\nstream\n" "\x00\x01\x00\x00\x00\x0a\x00\x80\x00\x03\x00\x20\x4f\x53\x2f\x32" "\x56\xde\xc8\x94\x00\x00\x01\x28\x00\x00\x00\x60\x63\x6d\x61\x70" "\x00\x0a\x00\x34\x00\x00\x01\x90\x00\x00\x00\x1e\x67\x6c\x79\x66" "\x15\x22\x41\x24\x00\x00\x01\xb8\x00\x00\x00\x18\x68\x65\x61\x64" "\x0b\x78\xf1\x65\x00\x00\x00\xac\x00\x00\x00\x36\x68\x68\x65\x61" "\x0c\x02\x04\x02\x00\x00\x00\xe4\x00\x00\x00\x24\x68\x6d\x74\x78" "\x04\x00\x00\x00\x00\x00\x01\x88\x00\x00\x00\x08\x6c\x6f\x63\x61" "\x00\x0c\x00\x00\x00\x00\x01\xb0\x00\x00\x00\x06\x6d\x61\x78\x70" "\x00\x04\x00\x05\x00\x00\x01\x08\x00\x00\x00\x20\x6e\x61\x6d\x65" "\xf2\xeb\x16\xda\x00\x00\x01\xd0\x00\x00\x00\x4b\x70\x6f\x73\x74" "\x00\x01\x00\x01\x00\x00\x02\x1c\x00\x00\x00\x20\x00\x01\x00\x00" "\x00\x01\x00\x00\xb0\x94\x71\x10\x5f\x0f\x3c\xf5\x04\x07\x08\x00" "\x00\x00\x00\x00\xcf\x9a\xfc\x6e\x00\x00\x00\x00\xd4\xc3\xa7\xf2" "\x00\x00\x00\x00\x04\x00\x08\x00\x00\x00\x00\x10\x00\x02\x00\x00" "\x00\x00\x00\x00\x00\x01\x00\x00\x08\x00\xff\xff\x00\x00\x04\x00" "\x00\x00\x00\x00\x04\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x02\x00\x01\x00\x00\x00\x02\x00\x04" "\x00\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x01\x90\x00\x05" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x05\x00\x01\x00\x01\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x47\x4f\x4f\x47\x00\x40\x00\x00\x00\x00\x00\x01\xff\xff" "\x00\x00\x00\x01\x00\x01\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00" "\x00\x00\x00\x02\x00\x01\x00\x00\x00\x00\x00\x14\x00\x03\x00\x00" "\x00\x00\x00\x14\x00\x06\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x01\x00\x00\x00\x00\x04\x00" "\x08\x00\x00\x03\x00\x00\x31\x21\x11\x21\x04\x00\xfc\x00\x08\x00" "\x00\x00\x00\x03\x00\x2a\x00\x00\x00\x03\x00\x00\x00\x05\x00\x16" "\x00\x00\x00\x01\x00\x00\x00\x00\x00\x05\x00\x0b\x00\x16\x00\x03" "\x00\x01\x04\x09\x00\x05\x00\x16\x00\x00\x00\x56\x00\x65\x00\x72" "\x00\x73\x00\x69\x00\x6f\x00\x6e\x00\x20\x00\x31\x00\x2e\x00\x30" "\x56\x65\x72\x73\x69\x6f\x6e\x20\x31\x2e\x30\x00\x00\x01\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\nendstream\nendobj\n"; #endif fz_pdfocr_options * fz_parse_pdfocr_options(fz_context *ctx, fz_pdfocr_options *opts, const char *args) { #ifdef OCR_DISABLED fz_throw(ctx, FZ_ERROR_GENERIC, "No OCR support in this build"); #else const char *val; memset(opts, 0, sizeof *opts); if (fz_has_option(ctx, args, "compression", &val)) { if (fz_option_eq(val, "none")) opts->compress = 0; else if (fz_option_eq(val, "flate")) opts->compress = 1; else fz_throw(ctx, FZ_ERROR_GENERIC, "Unsupported PDFOCR compression %s (none, or flate only)", val); } if (fz_has_option(ctx, args, "strip-height", &val)) { int i = fz_atoi(val); if (i <= 0) fz_throw(ctx, FZ_ERROR_GENERIC, "Unsupported PDFOCR strip height %d (suggest 0)", i); opts->strip_height = i; } if (fz_has_option(ctx, args, "ocr-language", &val)) { fz_copy_option(ctx, val, opts->language, nelem(opts->language)); } if (fz_has_option(ctx, args, "ocr-datadir", &val)) { fz_copy_option(ctx, val, opts->datadir, nelem(opts->datadir)); } return opts; #endif } void fz_write_pixmap_as_pdfocr(fz_context *ctx, fz_output *out, const fz_pixmap *pixmap, const fz_pdfocr_options *pdfocr) { #ifdef OCR_DISABLED fz_throw(ctx, FZ_ERROR_GENERIC, "No OCR support in this build"); #else fz_band_writer *writer; if (!pixmap || !out) return; writer = fz_new_pdfocr_band_writer(ctx, out, pdfocr); fz_try(ctx) { fz_write_header(ctx, writer, pixmap->w, pixmap->h, pixmap->n, pixmap->alpha, pixmap->xres, pixmap->yres, 0, pixmap->colorspace, pixmap->seps); fz_write_band(ctx, writer, pixmap->stride, pixmap->h, pixmap->samples); fz_close_band_writer(ctx, writer); } fz_always(ctx) fz_drop_band_writer(ctx, writer); fz_catch(ctx) fz_rethrow(ctx); #endif } #ifndef OCR_DISABLED typedef struct pdfocr_band_writer_s { fz_band_writer super; fz_pdfocr_options options; int obj_num; int xref_max; int64_t *xref; int pages; int page_max; int *page_obj; unsigned char *stripbuf; unsigned char *compbuf; size_t complen; void *tessapi; fz_pixmap *ocrbitmap; fz_pdfocr_progress_fn *progress; void *progress_arg; } pdfocr_band_writer; static int new_obj(fz_context *ctx, pdfocr_band_writer *writer) { int64_t pos = fz_tell_output(ctx, writer->super.out); if (writer->obj_num >= writer->xref_max) { int new_max = writer->xref_max * 2; if (new_max < writer->obj_num + 8) new_max = writer->obj_num + 8; writer->xref = fz_realloc_array(ctx, writer->xref, new_max, int64_t); writer->xref_max = new_max; } writer->xref[writer->obj_num] = pos; return writer->obj_num++; } static void pdfocr_write_header(fz_context *ctx, fz_band_writer *writer_, fz_colorspace *cs) { pdfocr_band_writer *writer = (pdfocr_band_writer *)writer_; fz_output *out = writer->super.out; int w = writer->super.w; int h = writer->super.h; int n = writer->super.n; int s = writer->super.s; int a = writer->super.alpha; int xres = writer->super.xres; int yres = writer->super.yres; int sh = writer->options.strip_height; int strips; int i; if (sh == 0) sh = h; strips = (h + sh-1)/sh; if (a != 0) fz_throw(ctx, FZ_ERROR_GENERIC, "PDFOCR cannot write alpha channel"); if (s != 0) fz_throw(ctx, FZ_ERROR_GENERIC, "PDFOCR cannot write spot colors"); if (n != 3 && n != 1) fz_throw(ctx, FZ_ERROR_GENERIC, "PDFOCR expected to be Grayscale or RGB"); fz_free(ctx, writer->stripbuf); writer->stripbuf = NULL; fz_free(ctx, writer->compbuf); writer->compbuf = NULL; fz_drop_pixmap(ctx, writer->ocrbitmap); writer->ocrbitmap = NULL; writer->stripbuf = Memento_label(fz_malloc(ctx, (size_t)w * sh * n), "pdfocr_stripbuf"); writer->complen = fz_deflate_bound(ctx, (size_t)w * sh * n); writer->compbuf = Memento_label(fz_malloc(ctx, writer->complen), "pdfocr_compbuf"); /* Always round the width of ocrbitmap up to a multiple of 4. */ writer->ocrbitmap = fz_new_pixmap(ctx, NULL, (w+3)&~3, h, NULL, 0); fz_set_pixmap_resolution(ctx, writer->ocrbitmap, xres, yres); /* Send the file header on the first page */ if (writer->pages == 0) { fz_write_string(ctx, out, "%PDF-1.4\n%PDFOCR-1.0\n"); if (writer->xref_max < 9) { int new_max = 9; writer->xref = fz_realloc_array(ctx, writer->xref, new_max, int64_t); writer->xref_max = new_max; } writer->xref[3] = fz_tell_output(ctx, out); fz_write_data(ctx, out, funky_font, sizeof(funky_font)-1); writer->xref[4] = fz_tell_output(ctx, out); fz_write_data(ctx, out, funky_font2, sizeof(funky_font2)-1); writer->xref[5] = fz_tell_output(ctx, out); fz_write_data(ctx, out, funky_font3, sizeof(funky_font3)-1); writer->xref[6] = fz_tell_output(ctx, out); fz_write_data(ctx, out, funky_font4, sizeof(funky_font4)-1); writer->xref[7] = fz_tell_output(ctx, out); fz_write_data(ctx, out, funky_font5, sizeof(funky_font5)-1); writer->xref[8] = fz_tell_output(ctx, out); fz_write_data(ctx, out, funky_font6, sizeof(funky_font6)-1); } if (writer->page_max <= writer->pages) { int new_max = writer->page_max * 2; if (new_max == 0) new_max = writer->pages + 8; writer->page_obj = fz_realloc_array(ctx, writer->page_obj, new_max, int); writer->page_max = new_max; } writer->page_obj[writer->pages] = writer->obj_num; writer->pages++; /* Send the Page Object */ fz_write_printf(ctx, out, "%d 0 obj\n<</Type/Page/Parent 2 0 R/Resources<</XObject<<", new_obj(ctx, writer)); for (i = 0; i < strips; i++) fz_write_printf(ctx, out, "/I%d %d 0 R", i, writer->obj_num + i); fz_write_printf(ctx, out, ">>/Font<</F0 3 0 R>>>>/MediaBox[0 0 %g %g]/Contents %d 0 R>>\nendobj\n", w * 72.0f / xres, h * 72.0f / yres, writer->obj_num + strips); } static void flush_strip(fz_context *ctx, pdfocr_band_writer *writer, int fill) { unsigned char *data = writer->stripbuf; fz_output *out = writer->super.out; int w = writer->super.w; int n = writer->super.n; size_t len = (size_t)w*n*fill; /* Buffer is full, compress it and write it. */ if (writer->options.compress) { size_t destLen = writer->complen; fz_deflate(ctx, writer->compbuf, &destLen, data, len, FZ_DEFLATE_DEFAULT); len = destLen; data = writer->compbuf; } fz_write_printf(ctx, out, "%d 0 obj\n<</Width %d/ColorSpace/Device%s/Height %d%s/Subtype/Image", new_obj(ctx, writer), w, n == 1 ? "Gray" : "RGB", fill, writer->options.compress ? "/Filter/FlateDecode" : ""); fz_write_printf(ctx, out, "/Length %zd/Type/XObject/BitsPerComponent 8>>\nstream\n", len); fz_write_data(ctx, out, data, len); fz_write_string(ctx, out, "\nendstream\nendobj\n"); } static void pdfocr_write_band(fz_context *ctx, fz_band_writer *writer_, int stride, int band_start, int band_height, const unsigned char *sp) { pdfocr_band_writer *writer = (pdfocr_band_writer *)writer_; fz_output *out = writer->super.out; int w = writer->super.w; int h = writer->super.h; int n = writer->super.n; int sh = writer->options.strip_height; int line; unsigned char *d = writer->ocrbitmap->samples; if (!out) return; if (sh == 0) sh = h; for (line = 0; line < band_height; line++) { int dstline = (band_start+line) % sh; memcpy(writer->stripbuf + (size_t)w*n*dstline, sp + (size_t)line * w * n, (size_t)w * n); if (dstline+1 == sh) flush_strip(ctx, writer, dstline+1); } if (band_start + band_height == h && h % sh != 0) flush_strip(ctx, writer, h % sh); /* Copy strip to ocrbitmap, converting if required. */ d += band_start*w; if (n == 1) { int y; for (y = band_height; y > 0; y--) { memcpy(d, sp, w); if (writer->ocrbitmap->w - w) memset(d + w, 0, writer->ocrbitmap->w - w); d += writer->ocrbitmap->w; } } else { int x, y; for (y = band_height; y > 0; y--) { for (x = w; x > 0; x--) { *d++ = (sp[0] + 2*sp[1] + sp[2] + 2)>>2; sp += 3; } for (x = writer->ocrbitmap->w - w; x > 0; x--) *d++ = 0; } } } enum { WORD_CONTAINS_L2R = 1, WORD_CONTAINS_R2L = 2, WORD_CONTAINS_T2B = 4, WORD_CONTAINS_B2T = 8 }; typedef struct word_t { struct word_t *next; float bbox[4]; int dirn; int len; int chars[1]; } word_t; typedef struct { fz_buffer *buf; pdfocr_band_writer *writer; /* We collate the current word into the following fields: */ int word_max; int word_len; int *word_chars; float word_bbox[4]; int word_dirn; int word_prev_char_bbox[4]; /* When we finish a word, we try to add it to the line. If the * word fits onto the end of the existing line, great. If not, * we flush the entire line, and start a new one just with the * new word. This enables us to output a whole line at once, * which is beneficial to avoid jittering the font sizes * up/down, which looks bad when we try to select text in the * produced PDF. */ word_t *line; word_t **line_tail; float line_bbox[4]; int line_dirn; float cur_size; float cur_scale; float tx, ty; } char_callback_data_t; static void flush_words(fz_context *ctx, char_callback_data_t *cb) { float size; if (cb->line == NULL) return; if ((cb->line_dirn & (WORD_CONTAINS_T2B | WORD_CONTAINS_B2T)) != 0) { /* Vertical line */ } else { /* Horizontal line */ size = cb->line_bbox[3] - cb->line_bbox[1]; if (size != 0 && size != cb->cur_size) { fz_append_printf(ctx, cb->buf, "/F0 %g Tf\n", size); cb->cur_size = size; } /* Guard against division by 0. This makes no difference to the * actual calculation as if size is 0, word->bbox[2] == word->bbox[0] * too. */ if (size == 0) size = 1; } while (cb->line) { word_t *word = cb->line; float x, y; int i, len = word->len; float scale; if ((cb->line_dirn & (WORD_CONTAINS_T2B | WORD_CONTAINS_B2T)) != 0) { /* Contains vertical text. */ size = (word->bbox[3] - word->bbox[1]) / len; if (size == 0) size = 1; if (size != cb->cur_size) { fz_append_printf(ctx, cb->buf, "/F0 %g Tf\n", size); cb->cur_size = size; } /* Set the scale so that our glyphs fill the line bbox. */ scale = (cb->line_bbox[2] - cb->line_bbox[0]) / size * 200; if (scale != 0) { float letter_height = (word->bbox[3] - word->bbox[1]) / len; if (scale != cb->cur_scale) { fz_append_printf(ctx, cb->buf, "%d Tz\n", (int)scale); cb->cur_scale = scale; } for (i = 0; i < len; i++) { x = word->bbox[0]; y = word->bbox[1] + letter_height * i; fz_append_printf(ctx, cb->buf, "%g %g Td\n", x-cb->tx, y-cb->ty); cb->tx = x; cb->ty = y; fz_append_printf(ctx, cb->buf, "<%04x>Tj\n", word->chars[i]); } } } else { scale = (word->bbox[2] - word->bbox[0]) / size / len * 200; if (scale != 0) { if (scale != cb->cur_scale) { fz_append_printf(ctx, cb->buf, "%d Tz\n", (int)scale); cb->cur_scale = scale; } if ((word->dirn & (WORD_CONTAINS_R2L | WORD_CONTAINS_L2R)) == WORD_CONTAINS_R2L) { /* Purely R2L text */ x = word->bbox[0]; y = cb->line_bbox[1]; fz_append_printf(ctx, cb->buf, "%g %g Td\n", x-cb->tx, y-cb->ty); cb->tx = x; cb->ty = y; /* Tesseract has sent us R2L text in R2L order (i.e. in Logical order). * We want to output it in that same logical order, but PDF operators * all move the point as if outputting L2R. We can either reverse the * order of chars (bad, because of cut/paste) or we can perform * gymnastics with the position. We opt for the latter. */ fz_append_printf(ctx, cb->buf, "["); for (i = 0; i < len; i++) { if (i == 0) { if (len > 1) fz_append_printf(ctx, cb->buf, "%d", -500*(len-1)); } else fz_append_printf(ctx, cb->buf, "%d", 1000); fz_append_printf(ctx, cb->buf, "<%04x>", word->chars[i]); } fz_append_printf(ctx, cb->buf, "]TJ\n"); } else { /* L2R (or mixed) text */ x = word->bbox[0]; y = cb->line_bbox[1]; fz_append_printf(ctx, cb->buf, "%g %g Td\n", x-cb->tx, y-cb->ty); cb->tx = x; cb->ty = y; fz_append_printf(ctx, cb->buf, "<"); for (i = 0; i < len; i++) fz_append_printf(ctx, cb->buf, "%04x", word->chars[i]); fz_append_printf(ctx, cb->buf, ">Tj\n"); } } } cb->line = word->next; fz_free(ctx, word); } cb->line_tail = &cb->line; cb->line = NULL; cb->line_dirn = 0; } static void queue_word(fz_context *ctx, char_callback_data_t *cb) { word_t *word; int line_is_v, line_is_h, word_is_v, word_is_h; if (cb->word_len == 0) return; word = fz_malloc(ctx, sizeof(*word) + (cb->word_len-1)*sizeof(int)); word->next = NULL; word->len = cb->word_len; memcpy(word->bbox, cb->word_bbox, 4*sizeof(float)); memcpy(word->chars, cb->word_chars, cb->word_len * sizeof(int)); cb->word_len = 0; line_is_v = !!(cb->line_dirn & (WORD_CONTAINS_B2T | WORD_CONTAINS_T2B)); word_is_v = !!(cb->word_dirn & (WORD_CONTAINS_B2T | WORD_CONTAINS_T2B)); line_is_h = !!(cb->line_dirn & (WORD_CONTAINS_L2R | WORD_CONTAINS_R2L)); word_is_h = !!(cb->word_dirn & (WORD_CONTAINS_L2R | WORD_CONTAINS_R2L)); word->dirn = cb->word_dirn; cb->word_dirn = 0; /* Can we put the new word onto the end of the existing line? */ if (cb->line != NULL && !line_is_v && !word_is_v && word->bbox[1] <= cb->line_bbox[3] && word->bbox[3] >= cb->line_bbox[1] && (word->bbox[0] >= cb->line_bbox[2] || word->bbox[2] <= cb->line_bbox[0])) { /* Can append (horizontal motion). */ if (word->bbox[0] < cb->line_bbox[0]) cb->line_bbox[0] = word->bbox[0]; if (word->bbox[1] < cb->line_bbox[1]) cb->line_bbox[1] = word->bbox[1]; if (word->bbox[2] > cb->line_bbox[2]) cb->line_bbox[2] = word->bbox[2]; if (word->bbox[3] > cb->line_bbox[3]) cb->line_bbox[3] = word->bbox[3]; } else if (cb->line != NULL && !line_is_h && !word_is_h && word->bbox[0] <= cb->line_bbox[2] && word->bbox[2] >= cb->line_bbox[0] && (word->bbox[1] >= cb->line_bbox[3] || word->bbox[3] <= cb->line_bbox[1])) { /* Can append (vertical motion). */ if (!word_is_v) word->dirn |= WORD_CONTAINS_T2B; if (word->bbox[0] < cb->line_bbox[0]) cb->line_bbox[0] = word->bbox[0]; if (word->bbox[1] < cb->line_bbox[1]) cb->line_bbox[1] = word->bbox[1]; if (word->bbox[2] > cb->line_bbox[2]) cb->line_bbox[2] = word->bbox[2]; if (word->bbox[3] > cb->line_bbox[3]) cb->line_bbox[3] = word->bbox[3]; } else { fz_try(ctx) flush_words(ctx, cb); fz_catch(ctx) { fz_free(ctx, word); fz_rethrow(ctx); } memcpy(cb->line_bbox, word->bbox, 4*sizeof(float)); } *cb->line_tail = word; cb->line_tail = &word->next; cb->line_dirn |= word->dirn; } static void char_callback(fz_context *ctx, void *arg, int unicode, const char *font_name, const int *line_bbox, const int *word_bbox, const int *char_bbox, int pointsize) { char_callback_data_t *cb = (char_callback_data_t *)arg; pdfocr_band_writer *writer = cb->writer; float bbox[4]; bbox[0] = word_bbox[0] * 72.0f / cb->writer->ocrbitmap->xres; bbox[3] = (writer->ocrbitmap->h - 1 - word_bbox[1]) * 72.0f / cb->writer->ocrbitmap->yres; bbox[2] = word_bbox[2] * 72.0f / cb->writer->ocrbitmap->yres; bbox[1] = (writer->ocrbitmap->h - 1 - word_bbox[3]) * 72.0f / cb->writer->ocrbitmap->yres; if (bbox[0] != cb->word_bbox[0] || bbox[1] != cb->word_bbox[1] || bbox[2] != cb->word_bbox[2] || bbox[3] != cb->word_bbox[3]) { queue_word(ctx, cb); memcpy(cb->word_bbox, bbox, 4 * sizeof(float)); } if (cb->word_len == 0) { cb->word_dirn = 0; memcpy(cb->word_prev_char_bbox, char_bbox, 4 * sizeof(int)); } else { int ox = cb->word_prev_char_bbox[0] + cb->word_prev_char_bbox[2]; int oy = cb->word_prev_char_bbox[1] + cb->word_prev_char_bbox[3]; int x = char_bbox[0] + char_bbox[2] - ox; int y = char_bbox[1] + char_bbox[3] - oy; int ax = x < 0 ? -x : x; int ay = y < 0 ? -y : y; if (ax > ay) { if (x > 0) cb->word_dirn |= WORD_CONTAINS_L2R; else if (x < 0) cb->word_dirn |= WORD_CONTAINS_R2L; } else if (ay < ax) { if (y > 0) cb->word_dirn |= WORD_CONTAINS_T2B; else if (y < 0) cb->word_dirn |= WORD_CONTAINS_B2T; } } if (cb->word_max == cb->word_len) { int newmax = cb->word_max * 2; if (newmax == 0) newmax = 16; cb->word_chars = fz_realloc_array(ctx, cb->word_chars, newmax, int); cb->word_max = newmax; } cb->word_chars[cb->word_len++] = unicode; } static int pdfocr_progress(fz_context *ctx, void *arg, int prog) { char_callback_data_t *cb = (char_callback_data_t *)arg; pdfocr_band_writer *writer = cb->writer; if (writer->progress == NULL) return 0; return writer->progress(ctx, writer->progress_arg, writer->pages - 1, prog); } static void pdfocr_write_trailer(fz_context *ctx, fz_band_writer *writer_) { pdfocr_band_writer *writer = (pdfocr_band_writer *)writer_; fz_output *out = writer->super.out; int w = writer->super.w; int h = writer->super.h; int xres = writer->super.xres; int yres = writer->super.yres; int sh = writer->options.strip_height; int strips; int i; size_t len; unsigned char *data; fz_buffer *buf = NULL; char_callback_data_t cb = { NULL }; if (sh == 0) sh = h; strips = (h + sh-1)/sh; /* Send the Page contents */ /* We need the length to this, so write to a buffer first */ fz_var(buf); fz_var(cb); fz_try(ctx) { cb.writer = writer; cb.buf = buf = fz_new_buffer(ctx, 0); cb.line_tail = &cb.line; cb.word_dirn = 0; cb.line_dirn = 0; fz_append_printf(ctx, buf, "q\n%g 0 0 %g 0 0 cm\n", 72.0f/xres, 72.0f/yres); for (i = 0; i < strips; i++) { int at = h - (i+1)*sh; int this_sh = sh; if (at < 0) { this_sh += at; at = 0; } fz_append_printf(ctx, buf, "/P <</MCID 0>> BDC\nq\n%d 0 0 %d 0 %d cm\n/I%d Do\nQ\n", w, this_sh, at, i); } fz_append_printf(ctx, buf, "Q\nBT\n3 Tr\n"); ocr_recognise(ctx, writer->tessapi, writer->ocrbitmap, char_callback, pdfocr_progress, &cb); queue_word(ctx, &cb); flush_words(ctx, &cb); fz_append_printf(ctx, buf, "ET\n"); len = fz_buffer_storage(ctx, buf, &data); fz_write_printf(ctx, out, "%d 0 obj\n<</Length %zd>>\nstream\n", new_obj(ctx, writer), len); fz_write_data(ctx, out, data, len); fz_drop_buffer(ctx, buf); buf = NULL; fz_write_string(ctx, out, "\nendstream\nendobj\n"); } fz_always(ctx) { fz_free(ctx, cb.word_chars); } fz_catch(ctx) { fz_drop_buffer(ctx, buf); fz_rethrow(ctx); } } static void pdfocr_close_band_writer(fz_context *ctx, fz_band_writer *writer_) { pdfocr_band_writer *writer = (pdfocr_band_writer *)writer_; fz_output *out = writer->super.out; int i; /* We actually do the trailer writing in the close */ if (writer->xref_max > 2) { int64_t t_pos; /* Catalog */ writer->xref[1] = fz_tell_output(ctx, out); fz_write_printf(ctx, out, "1 0 obj\n<</Type/Catalog/Pages 2 0 R>>\nendobj\n"); /* Page table */ writer->xref[2] = fz_tell_output(ctx, out); fz_write_printf(ctx, out, "2 0 obj\n<</Count %d/Kids[", writer->pages); for (i = 0; i < writer->pages; i++) { if (i > 0) fz_write_byte(ctx, out, ' '); fz_write_printf(ctx, out, "%d 0 R", writer->page_obj[i]); } fz_write_string(ctx, out, "]/Type/Pages>>\nendobj\n"); /* Xref */ t_pos = fz_tell_output(ctx, out); fz_write_printf(ctx, out, "xref\n0 %d\n0000000000 65535 f \n", writer->obj_num); for (i = 1; i < writer->obj_num; i++) fz_write_printf(ctx, out, "%010ld 00000 n \n", writer->xref[i]); fz_write_printf(ctx, out, "trailer\n<</Size %d/Root 1 0 R>>\nstartxref\n%ld\n%%%%EOF\n", writer->obj_num, t_pos); } } static void pdfocr_drop_band_writer(fz_context *ctx, fz_band_writer *writer_) { pdfocr_band_writer *writer = (pdfocr_band_writer *)writer_; fz_free(ctx, writer->stripbuf); fz_free(ctx, writer->compbuf); fz_free(ctx, writer->page_obj); fz_free(ctx, writer->xref); fz_drop_pixmap(ctx, writer->ocrbitmap); ocr_fin(ctx, writer->tessapi); } #endif fz_band_writer *fz_new_pdfocr_band_writer(fz_context *ctx, fz_output *out, const fz_pdfocr_options *options) { #ifdef OCR_DISABLED fz_throw(ctx, FZ_ERROR_GENERIC, "No OCR support in this build"); #else pdfocr_band_writer *writer = fz_new_band_writer(ctx, pdfocr_band_writer, out); writer->super.header = pdfocr_write_header; writer->super.band = pdfocr_write_band; writer->super.trailer = pdfocr_write_trailer; writer->super.close = pdfocr_close_band_writer; writer->super.drop = pdfocr_drop_band_writer; if (options) writer->options = *options; else memset(&writer->options, 0, sizeof(writer->options)); /* Objects: * 1 reserved for catalog * 2 for pages tree * 3 font * 4 cidfont * 5 cid to gid map * 6 tounicode * 7 font descriptor * 8 font file */ writer->obj_num = 9; fz_try(ctx) { writer->tessapi = ocr_init(ctx, writer->options.language, writer->options.datadir); } fz_catch(ctx) { fz_drop_band_writer(ctx, &writer->super); fz_throw(ctx, FZ_ERROR_GENERIC, "OCR initialisation failed"); } return &writer->super; #endif } void fz_pdfocr_band_writer_set_progress(fz_context *ctx, fz_band_writer *writer_, fz_pdfocr_progress_fn *progress, void *progress_arg) { #ifdef OCR_DISABLED fz_throw(ctx, FZ_ERROR_GENERIC, "No OCR support in this build"); #else pdfocr_band_writer *writer = (pdfocr_band_writer *)writer_; if (writer == NULL) return; if (writer->super.header != pdfocr_write_header) fz_throw(ctx, FZ_ERROR_GENERIC, "Not a pdfocr band writer!"); writer->progress = progress; writer->progress_arg = progress_arg; #endif } void fz_save_pixmap_as_pdfocr(fz_context *ctx, fz_pixmap *pixmap, char *filename, int append, const fz_pdfocr_options *pdfocr) { #ifdef OCR_DISABLED fz_throw(ctx, FZ_ERROR_GENERIC, "No OCR support in this build"); #else fz_output *out = fz_new_output_with_path(ctx, filename, append); fz_try(ctx) { fz_write_pixmap_as_pdfocr(ctx, out, pixmap, pdfocr); fz_close_output(ctx, out); } fz_always(ctx) fz_drop_output(ctx, out); fz_catch(ctx) fz_rethrow(ctx); #endif } /* High-level document writer interface */ #ifndef OCR_DISABLED typedef struct { fz_document_writer super; fz_draw_options draw; fz_pdfocr_options pdfocr; fz_pixmap *pixmap; fz_band_writer *bander; fz_output *out; int pagenum; } fz_pdfocr_writer; static fz_device * pdfocr_begin_page(fz_context *ctx, fz_document_writer *wri_, fz_rect mediabox) { fz_pdfocr_writer *wri = (fz_pdfocr_writer*)wri_; return fz_new_draw_device_with_options(ctx, &wri->draw, mediabox, &wri->pixmap); } static void pdfocr_end_page(fz_context *ctx, fz_document_writer *wri_, fz_device *dev) { fz_pdfocr_writer *wri = (fz_pdfocr_writer*)wri_; fz_pixmap *pix = wri->pixmap; fz_try(ctx) { fz_close_device(ctx, dev); fz_write_header(ctx, wri->bander, pix->w, pix->h, pix->n, pix->alpha, pix->xres, pix->yres, wri->pagenum++, pix->colorspace, pix->seps); fz_write_band(ctx, wri->bander, pix->stride, pix->h, pix->samples); } fz_always(ctx) { fz_drop_device(ctx, dev); fz_drop_pixmap(ctx, pix); wri->pixmap = NULL; } fz_catch(ctx) fz_rethrow(ctx); } static void pdfocr_close_writer(fz_context *ctx, fz_document_writer *wri_) { fz_pdfocr_writer *wri = (fz_pdfocr_writer*)wri_; fz_close_band_writer(ctx, wri->bander); fz_close_output(ctx, wri->out); } static void pdfocr_drop_writer(fz_context *ctx, fz_document_writer *wri_) { fz_pdfocr_writer *wri = (fz_pdfocr_writer*)wri_; fz_drop_pixmap(ctx, wri->pixmap); fz_drop_band_writer(ctx, wri->bander); fz_drop_output(ctx, wri->out); } #endif fz_document_writer * fz_new_pdfocr_writer_with_output(fz_context *ctx, fz_output *out, const char *options) { #ifdef OCR_DISABLED fz_throw(ctx, FZ_ERROR_GENERIC, "No OCR support in this build"); #else fz_pdfocr_writer *wri = NULL; fz_var(wri); fz_try(ctx) { wri = fz_new_derived_document_writer(ctx, fz_pdfocr_writer, pdfocr_begin_page, pdfocr_end_page, pdfocr_close_writer, pdfocr_drop_writer); fz_parse_draw_options(ctx, &wri->draw, options); fz_parse_pdfocr_options(ctx, &wri->pdfocr, options); wri->out = out; wri->bander = fz_new_pdfocr_band_writer(ctx, wri->out, &wri->pdfocr); } fz_catch(ctx) { fz_drop_output(ctx, out); fz_free(ctx, wri); fz_rethrow(ctx); } return (fz_document_writer*)wri; #endif } fz_document_writer * fz_new_pdfocr_writer(fz_context *ctx, const char *path, const char *options) { #ifdef OCR_DISABLED fz_throw(ctx, FZ_ERROR_GENERIC, "No OCR support in this build"); #else fz_output *out = fz_new_output_with_path(ctx, path ? path : "out.pdfocr", 0); return fz_new_pdfocr_writer_with_output(ctx, out, options); #endif } void fz_pdfocr_writer_set_progress(fz_context *ctx, fz_document_writer *writer, fz_pdfocr_progress_fn *progress, void *progress_arg) { #ifdef OCR_DISABLED fz_throw(ctx, FZ_ERROR_GENERIC, "No OCR support in this build"); #else fz_pdfocr_writer *wri = (fz_pdfocr_writer *)writer; if (!writer) return; if (writer->begin_page != pdfocr_begin_page) fz_throw(ctx, FZ_ERROR_GENERIC, "Not a pdfocr writer!"); fz_pdfocr_band_writer_set_progress(ctx, wri->bander, progress, progress_arg); #endif }
agpl-3.0
CoherentLogic/fis-gtm-netbsd
sr_unix/grab_crit.c
5
4717
/**************************************************************** * * * Copyright 2001, 2012 Fidelity Information Services, Inc * * * * This source code contains the intellectual property * * of its copyright holder(s), and is made available * * under a license. If you do not know the terms of * * the license, please stop and do not read further. * * * ****************************************************************/ #include "mdef.h" #include <signal.h> /* for VSIG_ATOMIC_T type */ #include "gdsroot.h" #include "gtm_facility.h" #include "fileinfo.h" #include "gdsbt.h" #include "gdsfhead.h" #include "gdsbgtr.h" #include "filestruct.h" #include "send_msg.h" #include "mutex.h" #include "wcs_recover.h" #include "deferred_signal_handler.h" #include "caller_id.h" #include "is_proc_alive.h" #ifdef DEBUG #include "gtm_stdio.h" #include "gt_timer.h" #include "wbox_test_init.h" #include "repl_msg.h" #include "gtmsource.h" #include "jnl.h" #endif #include "gtmimagename.h" #include "error.h" #include "anticipatory_freeze.h" GBLREF volatile int4 crit_count; GBLREF short crash_count; GBLREF uint4 process_id; GBLREF node_local_ptr_t locknl; #ifdef DEBUG GBLREF jnlpool_addrs jnlpool; GBLREF jnl_gbls_t jgbl; #endif GBLREF boolean_t mupip_jnl_recover; error_def(ERR_CRITRESET); error_def(ERR_DBCCERR); error_def(ERR_DBFLCORRP); void grab_crit(gd_region *reg) { unix_db_info *udi; sgmnt_addrs *csa; node_local_ptr_t cnl; sgmnt_data_ptr_t csd; enum cdb_sc status; mutex_spin_parms_ptr_t mutex_spin_parms; DEBUG_ONLY(sgmnt_addrs *jnlpool_csa;) DCL_THREADGBL_ACCESS; SETUP_THREADGBL_ACCESS; udi = FILE_INFO(reg); csa = &udi->s_addrs; csd = csa->hdr; cnl = csa->nl; # ifdef DEBUG if (gtm_white_box_test_case_enabled && (WBTEST_SENDTO_EPERM == gtm_white_box_test_case_number) && (0 == cnl->wbox_test_seq_num)) { FPRINTF(stderr, "MUPIP BACKUP entered grab_crit\n"); cnl->wbox_test_seq_num = 1; while (2 != cnl->wbox_test_seq_num) LONG_SLEEP(1); FPRINTF(stderr, "MUPIP BACKUP resumed in grab_crit\n"); cnl->wbox_test_seq_num = 3; } # endif assert(!csa->hold_onto_crit); if (!csa->now_crit) { # ifdef DEBUG if (NULL != jnlpool.jnlpool_ctl) { /* We should never request crit on a database region while already holding the lock on the journal pool. * Not following the protocol (obtaining lock on journal pool AFTER obtaining crit on database region), * can lead to potential deadlocks */ jnlpool_csa = &FILE_INFO(jnlpool.jnlpool_dummy_reg)->s_addrs; assert(!jnlpool_csa->now_crit); } # endif assert(0 == crit_count); crit_count++; /* prevent interrupts */ TREF(grabbing_crit) = reg; DEBUG_ONLY(locknl = cnl;) /* for DEBUG_ONLY LOCK_HIST macro */ mutex_spin_parms = (mutex_spin_parms_ptr_t)&csd->mutex_spin_parms; status = mutex_lockw(reg, mutex_spin_parms, crash_count); # ifdef DEBUG if (gtm_white_box_test_case_enabled && (WBTEST_SENDTO_EPERM == gtm_white_box_test_case_number) && (1 == cnl->wbox_test_seq_num)) { FPRINTF(stderr, "MUPIP SET entered grab_crit\n"); cnl->wbox_test_seq_num = 2; while (3 != cnl->wbox_test_seq_num) LONG_SLEEP(1); FPRINTF(stderr, "MUPIP SET resumed in grab_crit\n"); } # endif DEBUG_ONLY(locknl = NULL;) /* restore "locknl" to default value */ if (status != cdb_sc_normal) { crit_count = 0; TREF(grabbing_crit) = NULL; switch(status) { case cdb_sc_critreset: rts_error(VARLSTCNT(4) ERR_CRITRESET, 2, REG_LEN_STR(reg)); case cdb_sc_dbccerr: rts_error(VARLSTCNT(4) ERR_DBCCERR, 2, REG_LEN_STR(reg)); default: GTMASSERT; } return; } /* There is only one case we know of when cnl->in_crit can be non-zero and that is when a process holding * crit gets kill -9ed and another process ends up invoking "secshr_db_clnup" which in turn clears the * crit semaphore (making it available for waiters) but does not also clear cnl->in_crit since it does not * hold crit at that point. But in that case, the pid reported in cnl->in_crit should be dead. Check that. */ assert((0 == cnl->in_crit) || (FALSE == is_proc_alive(cnl->in_crit, 0))); cnl->in_crit = process_id; CRIT_TRACE(crit_ops_gw); /* see gdsbt.h for comment on placement */ TREF(grabbing_crit) = NULL; crit_count = 0; } /* Commands/Utilties that plays with the file_corrupt flags (DSE/MUPIP SET -PARTIAL_RECOV_BYPASS/RECOVER/ROLLBACK) should * NOT issue DBFLCORRP. Use skip_file_corrupt_check global variable for this purpose */ if (csd->file_corrupt && !TREF(skip_file_corrupt_check)) rts_error(VARLSTCNT(4) ERR_DBFLCORRP, 2, DB_LEN_STR(reg)); if (cnl->wc_blocked) wcs_recover(reg); return; }
agpl-3.0
D4edalus/CoD4x1.8_Server_Pub
src/tomcrypt/math/bn_s_mp_mul_high_digs.c
10
2181
#include <tommath.h> #ifdef BN_S_MP_MUL_HIGH_DIGS_C /* LibTomMath, multiple-precision integer library -- Tom St Denis * * LibTomMath is a library that provides multiple-precision * integer arithmetic as well as number theoretic functionality. * * The library was designed directly after the MPI library by * Michael Fromberger but has been written from scratch with * additional optimizations in place. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, tomstdenis@gmail.com, http://libtom.org */ /* multiplies |a| * |b| and does not compute the lower digs digits * [meant to get the higher part of the product] */ int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs) { mp_int t; int res, pa, pb, ix, iy; mp_digit u; mp_word r; mp_digit tmpx, *tmpt, *tmpy; /* can we use the fast multiplier? */ #ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C if (((a->used + b->used + 1) < MP_WARRAY) && MIN (a->used, b->used) < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) { return fast_s_mp_mul_high_digs (a, b, c, digs); } #endif if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) { return res; } t.used = a->used + b->used + 1; pa = a->used; pb = b->used; for (ix = 0; ix < pa; ix++) { /* clear the carry */ u = 0; /* left hand side of A[ix] * B[iy] */ tmpx = a->dp[ix]; /* alias to the address of where the digits will be stored */ tmpt = &(t.dp[digs]); /* alias for where to read the right hand side from */ tmpy = b->dp + (digs - ix); for (iy = digs - ix; iy < pb; iy++) { /* calculate the double precision result */ r = ((mp_word)*tmpt) + ((mp_word)tmpx) * ((mp_word)*tmpy++) + ((mp_word) u); /* get the lower part */ *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); /* carry the carry */ u = (mp_digit) (r >> ((mp_word) DIGIT_BIT)); } *tmpt = u; } mp_clamp (&t); mp_exch (&t, c); mp_clear (&t); return MP_OKAY; } #endif /* $Source$ */ /* $Revision: 0.41 $ */ /* $Date: 2007-04-18 09:58:18 +0000 $ */
agpl-3.0
studio666/zrtp-cpp
zorg/third_party/libtommath/bn_s_mp_exptmod.c
26
6126
#include <tommath.h> #ifdef BN_S_MP_EXPTMOD_C /* LibTomMath, multiple-precision integer library -- Tom St Denis * * LibTomMath is a library that provides multiple-precision * integer arithmetic as well as number theoretic functionality. * * The library was designed directly after the MPI library by * Michael Fromberger but has been written from scratch with * additional optimizations in place. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, tomstdenis@gmail.com, http://libtom.org */ #ifdef MP_LOW_MEM #define TAB_SIZE 32 #else #define TAB_SIZE 256 #endif int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode) { mp_int M[TAB_SIZE], res, mu; mp_digit buf; int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize; int (*redux)(mp_int*,mp_int*,mp_int*); /* find window size */ x = mp_count_bits (X); if (x <= 7) { winsize = 2; } else if (x <= 36) { winsize = 3; } else if (x <= 140) { winsize = 4; } else if (x <= 450) { winsize = 5; } else if (x <= 1303) { winsize = 6; } else if (x <= 3529) { winsize = 7; } else { winsize = 8; } #ifdef MP_LOW_MEM if (winsize > 5) { winsize = 5; } #endif /* init M array */ /* init first cell */ if ((err = mp_init(&M[1])) != MP_OKAY) { return err; } /* now init the second half of the array */ for (x = 1<<(winsize-1); x < (1 << winsize); x++) { if ((err = mp_init(&M[x])) != MP_OKAY) { for (y = 1<<(winsize-1); y < x; y++) { mp_clear (&M[y]); } mp_clear(&M[1]); return err; } } /* create mu, used for Barrett reduction */ if ((err = mp_init (&mu)) != MP_OKAY) { goto LBL_M; } if (redmode == 0) { if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) { goto LBL_MU; } redux = mp_reduce; } else { if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) { goto LBL_MU; } redux = mp_reduce_2k_l; } /* create M table * * The M table contains powers of the base, * e.g. M[x] = G**x mod P * * The first half of the table is not * computed though accept for M[0] and M[1] */ if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) { goto LBL_MU; } /* compute the value at M[1<<(winsize-1)] by squaring * M[1] (winsize-1) times */ if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) { goto LBL_MU; } for (x = 0; x < (winsize - 1); x++) { /* square it */ if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) { goto LBL_MU; } /* reduce modulo P */ if ((err = redux (&M[1 << (winsize - 1)], P, &mu)) != MP_OKAY) { goto LBL_MU; } } /* create upper table, that is M[x] = M[x-1] * M[1] (mod P) * for x = (2**(winsize - 1) + 1) to (2**winsize - 1) */ for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) { if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) { goto LBL_MU; } if ((err = redux (&M[x], P, &mu)) != MP_OKAY) { goto LBL_MU; } } /* setup result */ if ((err = mp_init (&res)) != MP_OKAY) { goto LBL_MU; } mp_set (&res, 1); /* set initial mode and bit cnt */ mode = 0; bitcnt = 1; buf = 0; digidx = X->used - 1; bitcpy = 0; bitbuf = 0; for (;;) { /* grab next digit as required */ if (--bitcnt == 0) { /* if digidx == -1 we are out of digits */ if (digidx == -1) { break; } /* read next digit and reset the bitcnt */ buf = X->dp[digidx--]; bitcnt = (int) DIGIT_BIT; } /* grab the next msb from the exponent */ y = (buf >> (mp_digit)(DIGIT_BIT - 1)) & 1; buf <<= (mp_digit)1; /* if the bit is zero and mode == 0 then we ignore it * These represent the leading zero bits before the first 1 bit * in the exponent. Technically this opt is not required but it * does lower the # of trivial squaring/reductions used */ if (mode == 0 && y == 0) { continue; } /* if the bit is zero and mode == 1 then we square */ if (mode == 1 && y == 0) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } continue; } /* else we add it to the window */ bitbuf |= (y << (winsize - ++bitcpy)); mode = 2; if (bitcpy == winsize) { /* ok window is filled so square as required and multiply */ /* square first */ for (x = 0; x < winsize; x++) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } } /* then multiply */ if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } /* empty window and reset */ bitcpy = 0; bitbuf = 0; mode = 1; } } /* if bits remain then square/multiply */ if (mode == 2 && bitcpy > 0) { /* square then multiply if the bit is set */ for (x = 0; x < bitcpy; x++) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } bitbuf <<= 1; if ((bitbuf & (1 << winsize)) != 0) { /* then multiply */ if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } } } } mp_exch (&res, Y); err = MP_OKAY; LBL_RES:mp_clear (&res); LBL_MU:mp_clear (&mu); LBL_M: mp_clear(&M[1]); for (x = 1<<(winsize-1); x < (1 << winsize); x++) { mp_clear (&M[x]); } return err; } #endif /* $Source: /cvs/libtom/libtommath/bn_s_mp_exptmod.c,v $ */ /* $Revision: 1.5 $ */ /* $Date: 2006/12/28 01:25:13 $ */
agpl-3.0
josephlewis42/UDenverQGC
src/lib/qwt/qwt_curve_fitter.cpp
28
5280
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #include "qwt_math.h" #include "qwt_spline.h" #include "qwt_curve_fitter.h" //! Constructor QwtCurveFitter::QwtCurveFitter() { } //! Destructor QwtCurveFitter::~QwtCurveFitter() { } class QwtSplineCurveFitter::PrivateData { public: PrivateData(): fitMode(QwtSplineCurveFitter::Auto), splineSize(250) { } QwtSpline spline; QwtSplineCurveFitter::FitMode fitMode; int splineSize; }; QwtSplineCurveFitter::QwtSplineCurveFitter() { d_data = new PrivateData; } QwtSplineCurveFitter::~QwtSplineCurveFitter() { delete d_data; } void QwtSplineCurveFitter::setFitMode(FitMode mode) { d_data->fitMode = mode; } QwtSplineCurveFitter::FitMode QwtSplineCurveFitter::fitMode() const { return d_data->fitMode; } void QwtSplineCurveFitter::setSpline(const QwtSpline &spline) { d_data->spline = spline; d_data->spline.reset(); } const QwtSpline &QwtSplineCurveFitter::spline() const { return d_data->spline; } QwtSpline &QwtSplineCurveFitter::spline() { return d_data->spline; } void QwtSplineCurveFitter::setSplineSize(int splineSize) { d_data->splineSize = qwtMax(splineSize, 10); } int QwtSplineCurveFitter::splineSize() const { return d_data->splineSize; } #if QT_VERSION < 0x040000 QwtArray<QwtDoublePoint> QwtSplineCurveFitter::fitCurve( const QwtArray<QwtDoublePoint> & points) const #else QPolygonF QwtSplineCurveFitter::fitCurve( const QPolygonF &points) const #endif { const int size = (int)points.size(); if ( size <= 2 ) return points; FitMode fitMode = d_data->fitMode; if ( fitMode == Auto ) { fitMode = Spline; const QwtDoublePoint *p = points.data(); for ( int i = 1; i < size; i++ ) { if ( p[i].x() <= p[i-1].x() ) { fitMode = ParametricSpline; break; } }; } if ( fitMode == ParametricSpline ) return fitParametric(points); else return fitSpline(points); } #if QT_VERSION < 0x040000 QwtArray<QwtDoublePoint> QwtSplineCurveFitter::fitSpline( const QwtArray<QwtDoublePoint> &points) const #else QPolygonF QwtSplineCurveFitter::fitSpline( const QPolygonF &points) const #endif { d_data->spline.setPoints(points); if ( !d_data->spline.isValid() ) return points; #if QT_VERSION < 0x040000 QwtArray<QwtDoublePoint> fittedPoints(d_data->splineSize); #else QPolygonF fittedPoints(d_data->splineSize); #endif const double x1 = points[0].x(); const double x2 = points[int(points.size() - 1)].x(); const double dx = x2 - x1; const double delta = dx / (d_data->splineSize - 1); for (int i = 0; i < d_data->splineSize; i++) { QwtDoublePoint &p = fittedPoints[i]; const double v = x1 + i * delta; const double sv = d_data->spline.value(v); p.setX(qRound(v)); p.setY(qRound(sv)); } d_data->spline.reset(); return fittedPoints; } #if QT_VERSION < 0x040000 QwtArray<QwtDoublePoint> QwtSplineCurveFitter::fitParametric( const QwtArray<QwtDoublePoint> &points) const #else QPolygonF QwtSplineCurveFitter::fitParametric( const QPolygonF &points) const #endif { int i; const int size = points.size(); #if QT_VERSION < 0x040000 QwtArray<QwtDoublePoint> fittedPoints(d_data->splineSize); QwtArray<QwtDoublePoint> splinePointsX(size); QwtArray<QwtDoublePoint> splinePointsY(size); #else QPolygonF fittedPoints(d_data->splineSize); QPolygonF splinePointsX(size); QPolygonF splinePointsY(size); #endif const QwtDoublePoint *p = points.data(); QwtDoublePoint *spX = splinePointsX.data(); QwtDoublePoint *spY = splinePointsY.data(); double param = 0.0; for (i = 0; i < size; i++) { const double x = p[i].x(); const double y = p[i].y(); if ( i > 0 ) { const double delta = sqrt( qwtSqr(x - spX[i-1].y()) + qwtSqr( y - spY[i-1].y() ) ); param += qwtMax(delta, 1.0); } spX[i].setX(param); spX[i].setY(x); spY[i].setX(param); spY[i].setY(y); } d_data->spline.setPoints(splinePointsX); if ( !d_data->spline.isValid() ) return points; const double deltaX = splinePointsX[size - 1].x() / (d_data->splineSize-1); for (i = 0; i < d_data->splineSize; i++) { const double dtmp = i * deltaX; fittedPoints[i].setX(qRound(d_data->spline.value(dtmp))); } d_data->spline.setPoints(splinePointsY); if ( !d_data->spline.isValid() ) return points; const double deltaY = splinePointsY[size - 1].x() / (d_data->splineSize-1); for (i = 0; i < d_data->splineSize; i++) { const double dtmp = i * deltaY; fittedPoints[i].setY(qRound(d_data->spline.value(dtmp))); } return fittedPoints; }
agpl-3.0
Darkpeninsula/Darkcore
src/tools/extractor/StormLib/src/lzma/C/LzFindMt.c
329
22171
/* LzFindMt.c -- multithreaded Match finder for LZ algorithms 2009-09-20 : Igor Pavlov : Public domain */ #include "LzHash.h" #include "LzFindMt.h" void MtSync_Construct(CMtSync *p) { p->wasCreated = False; p->csWasInitialized = False; p->csWasEntered = False; Thread_Construct(&p->thread); Event_Construct(&p->canStart); Event_Construct(&p->wasStarted); Event_Construct(&p->wasStopped); Semaphore_Construct(&p->freeSemaphore); Semaphore_Construct(&p->filledSemaphore); } void MtSync_GetNextBlock(CMtSync *p) { if (p->needStart) { p->numProcessedBlocks = 1; p->needStart = False; p->stopWriting = False; p->exit = False; Event_Reset(&p->wasStarted); Event_Reset(&p->wasStopped); Event_Set(&p->canStart); Event_Wait(&p->wasStarted); } else { CriticalSection_Leave(&p->cs); p->csWasEntered = False; p->numProcessedBlocks++; Semaphore_Release1(&p->freeSemaphore); } Semaphore_Wait(&p->filledSemaphore); CriticalSection_Enter(&p->cs); p->csWasEntered = True; } /* MtSync_StopWriting must be called if Writing was started */ void MtSync_StopWriting(CMtSync *p) { UInt32 myNumBlocks = p->numProcessedBlocks; if (!Thread_WasCreated(&p->thread) || p->needStart) return; p->stopWriting = True; if (p->csWasEntered) { CriticalSection_Leave(&p->cs); p->csWasEntered = False; } Semaphore_Release1(&p->freeSemaphore); Event_Wait(&p->wasStopped); while (myNumBlocks++ != p->numProcessedBlocks) { Semaphore_Wait(&p->filledSemaphore); Semaphore_Release1(&p->freeSemaphore); } p->needStart = True; } void MtSync_Destruct(CMtSync *p) { if (Thread_WasCreated(&p->thread)) { MtSync_StopWriting(p); p->exit = True; if (p->needStart) Event_Set(&p->canStart); Thread_Wait(&p->thread); Thread_Close(&p->thread); } if (p->csWasInitialized) { CriticalSection_Delete(&p->cs); p->csWasInitialized = False; } Event_Close(&p->canStart); Event_Close(&p->wasStarted); Event_Close(&p->wasStopped); Semaphore_Close(&p->freeSemaphore); Semaphore_Close(&p->filledSemaphore); p->wasCreated = False; } #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } static SRes MtSync_Create2(CMtSync *p, unsigned (MY_STD_CALL *startAddress)(void *), void *obj, UInt32 numBlocks) { if (p->wasCreated) return SZ_OK; RINOK_THREAD(CriticalSection_Init(&p->cs)); p->csWasInitialized = True; RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart)); RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStarted)); RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped)); RINOK_THREAD(Semaphore_Create(&p->freeSemaphore, numBlocks, numBlocks)); RINOK_THREAD(Semaphore_Create(&p->filledSemaphore, 0, numBlocks)); p->needStart = True; RINOK_THREAD(Thread_Create(&p->thread, startAddress, obj)); p->wasCreated = True; return SZ_OK; } static SRes MtSync_Create(CMtSync *p, unsigned (MY_STD_CALL *startAddress)(void *), void *obj, UInt32 numBlocks) { SRes res = MtSync_Create2(p, startAddress, obj, numBlocks); if (res != SZ_OK) MtSync_Destruct(p); return res; } void MtSync_Init(CMtSync *p) { p->needStart = True; } #define kMtMaxValForNormalize 0xFFFFFFFF #define DEF_GetHeads2(name, v, action) \ static void GetHeads ## name(const Byte *p, UInt32 pos, \ UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc) \ { action; for (; numHeads != 0; numHeads--) { \ const UInt32 value = (v); p++; *heads++ = pos - hash[value]; hash[value] = pos++; } } #define DEF_GetHeads(name, v) DEF_GetHeads2(name, v, ;) DEF_GetHeads2(2, (p[0] | ((UInt32)p[1] << 8)), hashMask = hashMask; crc = crc; ) DEF_GetHeads(3, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8)) & hashMask) DEF_GetHeads(4, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ (crc[p[3]] << 5)) & hashMask) DEF_GetHeads(4b, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ ((UInt32)p[3] << 16)) & hashMask) /* DEF_GetHeads(5, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ (crc[p[3]] << 5) ^ (crc[p[4]] << 3)) & hashMask) */ void HashThreadFunc(CMatchFinderMt *mt) { CMtSync *p = &mt->hashSync; for (;;) { UInt32 numProcessedBlocks = 0; Event_Wait(&p->canStart); Event_Set(&p->wasStarted); for (;;) { if (p->exit) return; if (p->stopWriting) { p->numProcessedBlocks = numProcessedBlocks; Event_Set(&p->wasStopped); break; } { CMatchFinder *mf = mt->MatchFinder; if (MatchFinder_NeedMove(mf)) { CriticalSection_Enter(&mt->btSync.cs); CriticalSection_Enter(&mt->hashSync.cs); { const Byte *beforePtr = MatchFinder_GetPointerToCurrentPos(mf); const Byte *afterPtr; MatchFinder_MoveBlock(mf); afterPtr = MatchFinder_GetPointerToCurrentPos(mf); mt->pointerToCurPos -= beforePtr - afterPtr; mt->buffer -= beforePtr - afterPtr; } CriticalSection_Leave(&mt->btSync.cs); CriticalSection_Leave(&mt->hashSync.cs); continue; } Semaphore_Wait(&p->freeSemaphore); MatchFinder_ReadIfRequired(mf); if (mf->pos > (kMtMaxValForNormalize - kMtHashBlockSize)) { UInt32 subValue = (mf->pos - mf->historySize - 1); MatchFinder_ReduceOffsets(mf, subValue); MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, mf->hashMask + 1); } { UInt32 *heads = mt->hashBuf + ((numProcessedBlocks++) & kMtHashNumBlocksMask) * kMtHashBlockSize; UInt32 num = mf->streamPos - mf->pos; heads[0] = 2; heads[1] = num; if (num >= mf->numHashBytes) { num = num - mf->numHashBytes + 1; if (num > kMtHashBlockSize - 2) num = kMtHashBlockSize - 2; mt->GetHeadsFunc(mf->buffer, mf->pos, mf->hash + mf->fixedHashSize, mf->hashMask, heads + 2, num, mf->crc); heads[0] += num; } mf->pos += num; mf->buffer += num; } } Semaphore_Release1(&p->filledSemaphore); } } } void MatchFinderMt_GetNextBlock_Hash(CMatchFinderMt *p) { MtSync_GetNextBlock(&p->hashSync); p->hashBufPosLimit = p->hashBufPos = ((p->hashSync.numProcessedBlocks - 1) & kMtHashNumBlocksMask) * kMtHashBlockSize; p->hashBufPosLimit += p->hashBuf[p->hashBufPos++]; p->hashNumAvail = p->hashBuf[p->hashBufPos++]; } #define kEmptyHashValue 0 /* #define MFMT_GM_INLINE */ #ifdef MFMT_GM_INLINE #define NO_INLINE MY_FAST_CALL Int32 NO_INLINE GetMatchesSpecN(UInt32 lenLimit, UInt32 pos, const Byte *cur, CLzRef *son, UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue, UInt32 *_distances, UInt32 _maxLen, const UInt32 *hash, Int32 limit, UInt32 size, UInt32 *posRes) { do { UInt32 *distances = _distances + 1; UInt32 curMatch = pos - *hash++; CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; CLzRef *ptr1 = son + (_cyclicBufferPos << 1); UInt32 len0 = 0, len1 = 0; UInt32 cutValue = _cutValue; UInt32 maxLen = _maxLen; for (;;) { UInt32 delta = pos - curMatch; if (cutValue-- == 0 || delta >= _cyclicBufferSize) { *ptr0 = *ptr1 = kEmptyHashValue; break; } { CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); const Byte *pb = cur - delta; UInt32 len = (len0 < len1 ? len0 : len1); if (pb[len] == cur[len]) { if (++len != lenLimit && pb[len] == cur[len]) while (++len != lenLimit) if (pb[len] != cur[len]) break; if (maxLen < len) { *distances++ = maxLen = len; *distances++ = delta - 1; if (len == lenLimit) { *ptr1 = pair[0]; *ptr0 = pair[1]; break; } } } if (pb[len] < cur[len]) { *ptr1 = curMatch; ptr1 = pair + 1; curMatch = *ptr1; len1 = len; } else { *ptr0 = curMatch; ptr0 = pair; curMatch = *ptr0; len0 = len; } } } pos++; _cyclicBufferPos++; cur++; { UInt32 num = (UInt32)(distances - _distances); *_distances = num - 1; _distances += num; limit -= num; } } while (limit > 0 && --size != 0); *posRes = pos; return limit; } #endif void BtGetMatches(CMatchFinderMt *p, UInt32 *distances) { UInt32 numProcessed = 0; UInt32 curPos = 2; UInt32 limit = kMtBtBlockSize - (p->matchMaxLen * 2); distances[1] = p->hashNumAvail; while (curPos < limit) { if (p->hashBufPos == p->hashBufPosLimit) { MatchFinderMt_GetNextBlock_Hash(p); distances[1] = numProcessed + p->hashNumAvail; if (p->hashNumAvail >= p->numHashBytes) continue; for (; p->hashNumAvail != 0; p->hashNumAvail--) distances[curPos++] = 0; break; } { UInt32 size = p->hashBufPosLimit - p->hashBufPos; UInt32 lenLimit = p->matchMaxLen; UInt32 pos = p->pos; UInt32 cyclicBufferPos = p->cyclicBufferPos; if (lenLimit >= p->hashNumAvail) lenLimit = p->hashNumAvail; { UInt32 size2 = p->hashNumAvail - lenLimit + 1; if (size2 < size) size = size2; size2 = p->cyclicBufferSize - cyclicBufferPos; if (size2 < size) size = size2; } #ifndef MFMT_GM_INLINE while (curPos < limit && size-- != 0) { UInt32 *startDistances = distances + curPos; UInt32 num = (UInt32)(GetMatchesSpec1(lenLimit, pos - p->hashBuf[p->hashBufPos++], pos, p->buffer, p->son, cyclicBufferPos, p->cyclicBufferSize, p->cutValue, startDistances + 1, p->numHashBytes - 1) - startDistances); *startDistances = num - 1; curPos += num; cyclicBufferPos++; pos++; p->buffer++; } #else { UInt32 posRes; curPos = limit - GetMatchesSpecN(lenLimit, pos, p->buffer, p->son, cyclicBufferPos, p->cyclicBufferSize, p->cutValue, distances + curPos, p->numHashBytes - 1, p->hashBuf + p->hashBufPos, (Int32)(limit - curPos) , size, &posRes); p->hashBufPos += posRes - pos; cyclicBufferPos += posRes - pos; p->buffer += posRes - pos; pos = posRes; } #endif numProcessed += pos - p->pos; p->hashNumAvail -= pos - p->pos; p->pos = pos; if (cyclicBufferPos == p->cyclicBufferSize) cyclicBufferPos = 0; p->cyclicBufferPos = cyclicBufferPos; } } distances[0] = curPos; } void BtFillBlock(CMatchFinderMt *p, UInt32 globalBlockIndex) { CMtSync *sync = &p->hashSync; if (!sync->needStart) { CriticalSection_Enter(&sync->cs); sync->csWasEntered = True; } BtGetMatches(p, p->btBuf + (globalBlockIndex & kMtBtNumBlocksMask) * kMtBtBlockSize); if (p->pos > kMtMaxValForNormalize - kMtBtBlockSize) { UInt32 subValue = p->pos - p->cyclicBufferSize; MatchFinder_Normalize3(subValue, p->son, p->cyclicBufferSize * 2); p->pos -= subValue; } if (!sync->needStart) { CriticalSection_Leave(&sync->cs); sync->csWasEntered = False; } } void BtThreadFunc(CMatchFinderMt *mt) { CMtSync *p = &mt->btSync; for (;;) { UInt32 blockIndex = 0; Event_Wait(&p->canStart); Event_Set(&p->wasStarted); for (;;) { if (p->exit) return; if (p->stopWriting) { p->numProcessedBlocks = blockIndex; MtSync_StopWriting(&mt->hashSync); Event_Set(&p->wasStopped); break; } Semaphore_Wait(&p->freeSemaphore); BtFillBlock(mt, blockIndex++); Semaphore_Release1(&p->filledSemaphore); } } } void MatchFinderMt_Construct(CMatchFinderMt *p) { p->hashBuf = 0; MtSync_Construct(&p->hashSync); MtSync_Construct(&p->btSync); } void MatchFinderMt_FreeMem(CMatchFinderMt *p, ISzAlloc *alloc) { alloc->Free(alloc, p->hashBuf); p->hashBuf = 0; } void MatchFinderMt_Destruct(CMatchFinderMt *p, ISzAlloc *alloc) { MtSync_Destruct(&p->hashSync); MtSync_Destruct(&p->btSync); MatchFinderMt_FreeMem(p, alloc); } #define kHashBufferSize (kMtHashBlockSize * kMtHashNumBlocks) #define kBtBufferSize (kMtBtBlockSize * kMtBtNumBlocks) static unsigned MY_STD_CALL HashThreadFunc2(void *p) { HashThreadFunc((CMatchFinderMt *)p); return 0; } static unsigned MY_STD_CALL BtThreadFunc2(void *p) { Byte allocaDummy[0x180]; int i = 0; for (i = 0; i < 16; i++) allocaDummy[i] = (Byte)i; BtThreadFunc((CMatchFinderMt *)p); return 0; } SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAlloc *alloc) { CMatchFinder *mf = p->MatchFinder; p->historySize = historySize; if (kMtBtBlockSize <= matchMaxLen * 4) return SZ_ERROR_PARAM; if (p->hashBuf == 0) { p->hashBuf = (UInt32 *)alloc->Alloc(alloc, (kHashBufferSize + kBtBufferSize) * sizeof(UInt32)); if (p->hashBuf == 0) return SZ_ERROR_MEM; p->btBuf = p->hashBuf + kHashBufferSize; } keepAddBufferBefore += (kHashBufferSize + kBtBufferSize); keepAddBufferAfter += kMtHashBlockSize; if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc)) return SZ_ERROR_MEM; RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p, kMtHashNumBlocks)); RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p, kMtBtNumBlocks)); return SZ_OK; } /* Call it after ReleaseStream / SetStream */ void MatchFinderMt_Init(CMatchFinderMt *p) { CMatchFinder *mf = p->MatchFinder; p->btBufPos = p->btBufPosLimit = 0; p->hashBufPos = p->hashBufPosLimit = 0; MatchFinder_Init(mf); p->pointerToCurPos = MatchFinder_GetPointerToCurrentPos(mf); p->btNumAvailBytes = 0; p->lzPos = p->historySize + 1; p->hash = mf->hash; p->fixedHashSize = mf->fixedHashSize; p->crc = mf->crc; p->son = mf->son; p->matchMaxLen = mf->matchMaxLen; p->numHashBytes = mf->numHashBytes; p->pos = mf->pos; p->buffer = mf->buffer; p->cyclicBufferPos = mf->cyclicBufferPos; p->cyclicBufferSize = mf->cyclicBufferSize; p->cutValue = mf->cutValue; } /* ReleaseStream is required to finish multithreading */ void MatchFinderMt_ReleaseStream(CMatchFinderMt *p) { MtSync_StopWriting(&p->btSync); /* p->MatchFinder->ReleaseStream(); */ } void MatchFinderMt_Normalize(CMatchFinderMt *p) { MatchFinder_Normalize3(p->lzPos - p->historySize - 1, p->hash, p->fixedHashSize); p->lzPos = p->historySize + 1; } void MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p) { UInt32 blockIndex; MtSync_GetNextBlock(&p->btSync); blockIndex = ((p->btSync.numProcessedBlocks - 1) & kMtBtNumBlocksMask); p->btBufPosLimit = p->btBufPos = blockIndex * kMtBtBlockSize; p->btBufPosLimit += p->btBuf[p->btBufPos++]; p->btNumAvailBytes = p->btBuf[p->btBufPos++]; if (p->lzPos >= kMtMaxValForNormalize - kMtBtBlockSize) MatchFinderMt_Normalize(p); } const Byte * MatchFinderMt_GetPointerToCurrentPos(CMatchFinderMt *p) { return p->pointerToCurPos; } #define GET_NEXT_BLOCK_IF_REQUIRED if (p->btBufPos == p->btBufPosLimit) MatchFinderMt_GetNextBlock_Bt(p); UInt32 MatchFinderMt_GetNumAvailableBytes(CMatchFinderMt *p) { GET_NEXT_BLOCK_IF_REQUIRED; return p->btNumAvailBytes; } Byte MatchFinderMt_GetIndexByte(CMatchFinderMt *p, Int32 index) { return p->pointerToCurPos[index]; } UInt32 * MixMatches2(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) { UInt32 hash2Value, curMatch2; UInt32 *hash = p->hash; const Byte *cur = p->pointerToCurPos; UInt32 lzPos = p->lzPos; MT_HASH2_CALC curMatch2 = hash[hash2Value]; hash[hash2Value] = lzPos; if (curMatch2 >= matchMinPos) if (cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) { *distances++ = 2; *distances++ = lzPos - curMatch2 - 1; } return distances; } UInt32 * MixMatches3(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) { UInt32 hash2Value, hash3Value, curMatch2, curMatch3; UInt32 *hash = p->hash; const Byte *cur = p->pointerToCurPos; UInt32 lzPos = p->lzPos; MT_HASH3_CALC curMatch2 = hash[ hash2Value]; curMatch3 = hash[kFix3HashSize + hash3Value]; hash[ hash2Value] = hash[kFix3HashSize + hash3Value] = lzPos; if (curMatch2 >= matchMinPos && cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) { distances[1] = lzPos - curMatch2 - 1; if (cur[(ptrdiff_t)curMatch2 - lzPos + 2] == cur[2]) { distances[0] = 3; return distances + 2; } distances[0] = 2; distances += 2; } if (curMatch3 >= matchMinPos && cur[(ptrdiff_t)curMatch3 - lzPos] == cur[0]) { *distances++ = 3; *distances++ = lzPos - curMatch3 - 1; } return distances; } /* UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) { UInt32 hash2Value, hash3Value, hash4Value, curMatch2, curMatch3, curMatch4; UInt32 *hash = p->hash; const Byte *cur = p->pointerToCurPos; UInt32 lzPos = p->lzPos; MT_HASH4_CALC curMatch2 = hash[ hash2Value]; curMatch3 = hash[kFix3HashSize + hash3Value]; curMatch4 = hash[kFix4HashSize + hash4Value]; hash[ hash2Value] = hash[kFix3HashSize + hash3Value] = hash[kFix4HashSize + hash4Value] = lzPos; if (curMatch2 >= matchMinPos && cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) { distances[1] = lzPos - curMatch2 - 1; if (cur[(ptrdiff_t)curMatch2 - lzPos + 2] == cur[2]) { distances[0] = (cur[(ptrdiff_t)curMatch2 - lzPos + 3] == cur[3]) ? 4 : 3; return distances + 2; } distances[0] = 2; distances += 2; } if (curMatch3 >= matchMinPos && cur[(ptrdiff_t)curMatch3 - lzPos] == cur[0]) { distances[1] = lzPos - curMatch3 - 1; if (cur[(ptrdiff_t)curMatch3 - lzPos + 3] == cur[3]) { distances[0] = 4; return distances + 2; } distances[0] = 3; distances += 2; } if (curMatch4 >= matchMinPos) if ( cur[(ptrdiff_t)curMatch4 - lzPos] == cur[0] && cur[(ptrdiff_t)curMatch4 - lzPos + 3] == cur[3] ) { *distances++ = 4; *distances++ = lzPos - curMatch4 - 1; } return distances; } */ #define INCREASE_LZ_POS p->lzPos++; p->pointerToCurPos++; UInt32 MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *distances) { const UInt32 *btBuf = p->btBuf + p->btBufPos; UInt32 len = *btBuf++; p->btBufPos += 1 + len; p->btNumAvailBytes--; { UInt32 i; for (i = 0; i < len; i += 2) { *distances++ = *btBuf++; *distances++ = *btBuf++; } } INCREASE_LZ_POS return len; } UInt32 MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *distances) { const UInt32 *btBuf = p->btBuf + p->btBufPos; UInt32 len = *btBuf++; p->btBufPos += 1 + len; if (len == 0) { if (p->btNumAvailBytes-- >= 4) len = (UInt32)(p->MixMatchesFunc(p, p->lzPos - p->historySize, distances) - (distances)); } else { /* Condition: there are matches in btBuf with length < p->numHashBytes */ UInt32 *distances2; p->btNumAvailBytes--; distances2 = p->MixMatchesFunc(p, p->lzPos - btBuf[1], distances); do { *distances2++ = *btBuf++; *distances2++ = *btBuf++; } while ((len -= 2) != 0); len = (UInt32)(distances2 - (distances)); } INCREASE_LZ_POS return len; } #define SKIP_HEADER2_MT do { GET_NEXT_BLOCK_IF_REQUIRED #define SKIP_HEADER_MT(n) SKIP_HEADER2_MT if (p->btNumAvailBytes-- >= (n)) { const Byte *cur = p->pointerToCurPos; UInt32 *hash = p->hash; #define SKIP_FOOTER_MT } INCREASE_LZ_POS p->btBufPos += p->btBuf[p->btBufPos] + 1; } while (--num != 0); void MatchFinderMt0_Skip(CMatchFinderMt *p, UInt32 num) { SKIP_HEADER2_MT { p->btNumAvailBytes--; SKIP_FOOTER_MT } void MatchFinderMt2_Skip(CMatchFinderMt *p, UInt32 num) { SKIP_HEADER_MT(2) UInt32 hash2Value; MT_HASH2_CALC hash[hash2Value] = p->lzPos; SKIP_FOOTER_MT } void MatchFinderMt3_Skip(CMatchFinderMt *p, UInt32 num) { SKIP_HEADER_MT(3) UInt32 hash2Value, hash3Value; MT_HASH3_CALC hash[kFix3HashSize + hash3Value] = hash[ hash2Value] = p->lzPos; SKIP_FOOTER_MT } /* void MatchFinderMt4_Skip(CMatchFinderMt *p, UInt32 num) { SKIP_HEADER_MT(4) UInt32 hash2Value, hash3Value, hash4Value; MT_HASH4_CALC hash[kFix4HashSize + hash4Value] = hash[kFix3HashSize + hash3Value] = hash[ hash2Value] = p->lzPos; SKIP_FOOTER_MT } */ void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder *vTable) { vTable->Init = (Mf_Init_Func)MatchFinderMt_Init; vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinderMt_GetIndexByte; vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinderMt_GetNumAvailableBytes; vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinderMt_GetPointerToCurrentPos; vTable->GetMatches = (Mf_GetMatches_Func)MatchFinderMt_GetMatches; switch(p->MatchFinder->numHashBytes) { case 2: p->GetHeadsFunc = GetHeads2; p->MixMatchesFunc = (Mf_Mix_Matches)0; vTable->Skip = (Mf_Skip_Func)MatchFinderMt0_Skip; vTable->GetMatches = (Mf_GetMatches_Func)MatchFinderMt2_GetMatches; break; case 3: p->GetHeadsFunc = GetHeads3; p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches2; vTable->Skip = (Mf_Skip_Func)MatchFinderMt2_Skip; break; default: /* case 4: */ p->GetHeadsFunc = p->MatchFinder->bigHash ? GetHeads4b : GetHeads4; /* p->GetHeadsFunc = GetHeads4; */ p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches3; vTable->Skip = (Mf_Skip_Func)MatchFinderMt3_Skip; break; /* default: p->GetHeadsFunc = GetHeads5; p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches4; vTable->Skip = (Mf_Skip_Func)MatchFinderMt4_Skip; break; */ } }
agpl-3.0
kolibre/libkolibre-daisyonline
src/stubs/adb_KeysType.c
1
53037
/* * Copyright (C) 2012 Kolibre * * This file is part of kolibre-daisyonline. * * Kolibre-daisyonline 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. * * Kolibre-daisyonline 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 kolibre-daisyonline. If not, see <http://www.gnu.org/licenses/>. */ /** * adb_KeysType.c * * This file was auto-generated from WSDL * by the Apache Axis2/C version: SNAPSHOT Built on : Mar 10, 2008 (08:35:52 GMT+00:00) */ #include "adb_KeysType.h" /* * This type was generated from the piece of schema that had * name = KeysType * Namespace URI = http://www.daisy.org/DRM/2005/KeyExchange * Namespace Prefix = ns7 */ struct adb_KeysType { axis2_char_t *property_TypeName; adb_KeyInfoType_t* property_KeyInfo; axis2_bool_t is_valid_KeyInfo; axutil_array_list_t* property_KeysTypeChoice_type0; axis2_bool_t is_valid_KeysTypeChoice_type0; }; /************************* Private Function prototypes ********************************/ axis2_status_t AXIS2_CALL adb_KeysType_set_KeyInfo_nil( adb_KeysType_t* _KeysType, const axutil_env_t *env); axis2_status_t AXIS2_CALL adb_KeysType_set_KeysTypeChoice_type0_nil_at( adb_KeysType_t* _KeysType, const axutil_env_t *env, int i); axis2_status_t AXIS2_CALL adb_KeysType_set_KeysTypeChoice_type0_nil( adb_KeysType_t* _KeysType, const axutil_env_t *env); /************************* Function Implmentations ********************************/ adb_KeysType_t* AXIS2_CALL adb_KeysType_create( const axutil_env_t *env) { adb_KeysType_t *_KeysType = NULL; AXIS2_ENV_CHECK(env, NULL); _KeysType = (adb_KeysType_t *) AXIS2_MALLOC(env-> allocator, sizeof(adb_KeysType_t)); if(NULL == _KeysType) { AXIS2_ERROR_SET(env->error, AXIS2_ERROR_NO_MEMORY, AXIS2_FAILURE); return NULL; } memset(_KeysType, 0, sizeof(adb_KeysType_t)); _KeysType->property_TypeName = axutil_strdup(env, "adb_KeysType"); _KeysType->property_KeyInfo = NULL; _KeysType->is_valid_KeyInfo = AXIS2_FALSE; _KeysType->property_KeysTypeChoice_type0 = NULL; _KeysType->is_valid_KeysTypeChoice_type0 = AXIS2_FALSE; return _KeysType; } adb_KeysType_t* AXIS2_CALL adb_KeysType_create_with_values( const axutil_env_t *env, adb_KeyInfoType_t* _KeyInfo, axutil_array_list_t* _KeysTypeChoice_type0) { adb_KeysType_t* adb_obj = NULL; axis2_status_t status = AXIS2_SUCCESS; adb_obj = adb_KeysType_create(env); status = adb_KeysType_set_KeyInfo( adb_obj, env, _KeyInfo); if(status == AXIS2_FAILURE) { adb_KeysType_free (adb_obj, env); return NULL; } status = adb_KeysType_set_KeysTypeChoice_type0( adb_obj, env, _KeysTypeChoice_type0); if(status == AXIS2_FAILURE) { adb_KeysType_free (adb_obj, env); return NULL; } return adb_obj; } adb_KeyInfoType_t* AXIS2_CALL adb_KeysType_free_popping_value( adb_KeysType_t* _KeysType, const axutil_env_t *env) { adb_KeyInfoType_t* value; value = _KeysType->property_KeyInfo; _KeysType->property_KeyInfo = (adb_KeyInfoType_t*)NULL; adb_KeysType_free(_KeysType, env); return value; } axis2_status_t AXIS2_CALL adb_KeysType_free( adb_KeysType_t* _KeysType, const axutil_env_t *env) { return axis2_extension_mapper_free( (adb_stubtype_t*) _KeysType, env, "adb_KeysType"); } axis2_status_t AXIS2_CALL adb_KeysType_free_obj( adb_KeysType_t* _KeysType, const axutil_env_t *env) { int i = 0; int count = 0; void *element = NULL; AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); if (_KeysType->property_TypeName != NULL) { AXIS2_FREE(env->allocator, _KeysType->property_TypeName); } adb_KeysType_reset_KeyInfo(_KeysType, env); adb_KeysType_reset_KeysTypeChoice_type0(_KeysType, env); if(_KeysType) { AXIS2_FREE(env->allocator, _KeysType); _KeysType = NULL; } return AXIS2_SUCCESS; } axis2_status_t AXIS2_CALL adb_KeysType_deserialize( adb_KeysType_t* _KeysType, const axutil_env_t *env, axiom_node_t **dp_parent, axis2_bool_t *dp_is_early_node_valid, axis2_bool_t dont_care_minoccurs) { return axis2_extension_mapper_deserialize( (adb_stubtype_t*) _KeysType, env, dp_parent, dp_is_early_node_valid, dont_care_minoccurs, "adb_KeysType"); } axis2_status_t AXIS2_CALL adb_KeysType_deserialize_obj( adb_KeysType_t* _KeysType, const axutil_env_t *env, axiom_node_t **dp_parent, axis2_bool_t *dp_is_early_node_valid, axis2_bool_t dont_care_minoccurs) { axiom_node_t *parent = *dp_parent; axis2_status_t status = AXIS2_SUCCESS; void *element = NULL; const axis2_char_t* text_value = NULL; axutil_qname_t *qname = NULL; int i = 0; axutil_array_list_t *arr_list = NULL; int sequence_broken = 0; axiom_node_t *tmp_node = NULL; axutil_qname_t *element_qname = NULL; axiom_node_t *first_node = NULL; axis2_bool_t is_early_node_valid = AXIS2_TRUE; axiom_node_t *current_node = NULL; axiom_element_t *current_element = NULL; AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); while(parent && axiom_node_get_node_type(parent, env) != AXIOM_ELEMENT) { parent = axiom_node_get_next_sibling(parent, env); } if (NULL == parent) { /* This should be checked before everything */ AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "Failed in building adb object for KeysType : " "NULL element can not be passed to deserialize"); return AXIS2_FAILURE; } first_node = axiom_node_get_first_child(parent, env); /* * building KeyInfo element */ current_node = first_node; is_early_node_valid = AXIS2_FALSE; while(current_node && axiom_node_get_node_type(current_node, env) != AXIOM_ELEMENT) { current_node = axiom_node_get_next_sibling(current_node, env); } if(current_node != NULL) { current_element = (axiom_element_t *)axiom_node_get_data_element(current_node, env); qname = axiom_element_get_qname(current_element, env, current_node); } element_qname = axutil_qname_create(env, "KeyInfo", "http://www.w3.org/2000/09/xmldsig#", NULL); if (adb_KeyInfoType_is_particle() || (current_node && current_element && (axutil_qname_equals(element_qname, env, qname)))) { if( current_node && current_element && (axutil_qname_equals(element_qname, env, qname))) { is_early_node_valid = AXIS2_TRUE; } element = (void*)axis2_extension_mapper_create_from_node(env, &current_node, "adb_KeyInfoType"); status = adb_KeyInfoType_deserialize((adb_KeyInfoType_t*)element, env, &current_node, &is_early_node_valid, AXIS2_FALSE); if(AXIS2_FAILURE == status) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "failed in building adb object for element KeyInfo"); } else { status = adb_KeysType_set_KeyInfo(_KeysType, env, (adb_KeyInfoType_t*)element); } if(AXIS2_FAILURE == status) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "failed in setting the value for KeyInfo "); if(element_qname) { axutil_qname_free(element_qname, env); } return AXIS2_FAILURE; } } else if(!dont_care_minoccurs) { if(element_qname) { axutil_qname_free(element_qname, env); } /* this is not a nillable element*/ AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "non nillable or minOuccrs != 0 element KeyInfo missing"); return AXIS2_FAILURE; } if(element_qname) { axutil_qname_free(element_qname, env); element_qname = NULL; } /* * building KeysTypeChoice_type0 array */ arr_list = axutil_array_list_create(env, 10); /* * building KeysTypeChoice_type0 element */ element_qname = axutil_qname_create(env, "KeysTypeChoice_type0", "http://www.daisy.org/DRM/2005/KeyExchange", NULL); for (i = 0, sequence_broken = 0, current_node = (is_early_node_valid?axiom_node_get_next_sibling(current_node, env):current_node); !sequence_broken && current_node != NULL;) { if(axiom_node_get_node_type(current_node, env) != AXIOM_ELEMENT) { current_node =axiom_node_get_next_sibling(current_node, env); is_early_node_valid = AXIS2_FALSE; continue; } current_element = (axiom_element_t *)axiom_node_get_data_element(current_node, env); qname = axiom_element_get_qname(current_element, env, current_node); if (adb_KeysTypeChoice_type0_is_particle() || (current_node && current_element && (axutil_qname_equals(element_qname, env, qname)))) { if( current_node && current_element && (axutil_qname_equals(element_qname, env, qname))) { is_early_node_valid = AXIS2_TRUE; } element = (void*)axis2_extension_mapper_create_from_node(env, &current_node, "adb_KeysTypeChoice_type0"); status = adb_KeysTypeChoice_type0_deserialize((adb_KeysTypeChoice_type0_t*)element, env, &current_node, &is_early_node_valid, AXIS2_FALSE); if(AXIS2_FAILURE == status) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "failed in building element KeysTypeChoice_type0 "); } else { axutil_array_list_add_at(arr_list, env, i, element); } if(AXIS2_FAILURE == status) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "failed in setting the value for KeysTypeChoice_type0 "); if(element_qname) { axutil_qname_free(element_qname, env); } if(arr_list) { axutil_array_list_free(arr_list, env); } return AXIS2_FAILURE; } i ++; current_node = axiom_node_get_next_sibling(current_node, env); } else { is_early_node_valid = AXIS2_FALSE; sequence_broken = 1; } } if (i < 1) { /* found element out of order */ AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "KeysTypeChoice_type0 (@minOccurs = '1') only have %d elements", i); if(element_qname) { axutil_qname_free(element_qname, env); } if(arr_list) { axutil_array_list_free(arr_list, env); } return AXIS2_FAILURE; } if(0 == axutil_array_list_size(arr_list,env)) { axutil_array_list_free(arr_list, env); } else { status = adb_KeysType_set_KeysTypeChoice_type0(_KeysType, env, arr_list); } if(element_qname) { axutil_qname_free(element_qname, env); element_qname = NULL; } return status; } axis2_bool_t AXIS2_CALL adb_KeysType_is_particle() { return AXIS2_FALSE; } void AXIS2_CALL adb_KeysType_declare_parent_namespaces( adb_KeysType_t* _KeysType, const axutil_env_t *env, axiom_element_t *parent_element, axutil_hash_t *namespaces, int *next_ns_index) { /* Here this is an empty function, Nothing to declare */ } axiom_node_t* AXIS2_CALL adb_KeysType_serialize( adb_KeysType_t* _KeysType, const axutil_env_t *env, axiom_node_t *parent, axiom_element_t *parent_element, int parent_tag_closed, axutil_hash_t *namespaces, int *next_ns_index) { if (_KeysType == NULL) { return adb_KeysType_serialize_obj( _KeysType, env, parent, parent_element, parent_tag_closed, namespaces, next_ns_index); } else { return axis2_extension_mapper_serialize( (adb_stubtype_t*) _KeysType, env, parent, parent_element, parent_tag_closed, namespaces, next_ns_index, "adb_KeysType"); } } axiom_node_t* AXIS2_CALL adb_KeysType_serialize_obj( adb_KeysType_t* _KeysType, const axutil_env_t *env, axiom_node_t *parent, axiom_element_t *parent_element, int parent_tag_closed, axutil_hash_t *namespaces, int *next_ns_index) { axis2_char_t *string_to_stream; axiom_node_t* current_node = NULL; int tag_closed = 0; axis2_char_t* xsi_prefix = NULL; axiom_namespace_t* xsi_ns = NULL; axiom_attribute_t* xsi_type_attri = NULL; axis2_char_t* type_attrib = NULL; axiom_namespace_t *ns1 = NULL; axis2_char_t *qname_uri = NULL; axis2_char_t *qname_prefix = NULL; axis2_char_t *p_prefix = NULL; axis2_bool_t ns_already_defined; int i = 0; int count = 0; void *element = NULL; axis2_char_t text_value_1[ADB_DEFAULT_DIGIT_LIMIT]; axis2_char_t text_value_2[ADB_DEFAULT_DIGIT_LIMIT]; axis2_char_t *start_input_str = NULL; axis2_char_t *end_input_str = NULL; unsigned int start_input_str_len = 0; unsigned int end_input_str_len = 0; axiom_data_source_t *data_source = NULL; axutil_stream_t *stream = NULL; AXIS2_ENV_CHECK(env, NULL); AXIS2_PARAM_CHECK(env->error, _KeysType, NULL); current_node = parent; data_source = (axiom_data_source_t *)axiom_node_get_data_element(current_node, env); if (!data_source) return NULL; stream = axiom_data_source_get_stream(data_source, env); /* assume parent is of type data source */ if (!stream) return NULL; if(!parent_tag_closed) { string_to_stream = ">"; axutil_stream_write(stream, env, string_to_stream, axutil_strlen(string_to_stream)); tag_closed = 1; } if(!(p_prefix = (axis2_char_t*)axutil_hash_get(namespaces, "http://www.w3.org/2000/09/xmldsig#", AXIS2_HASH_KEY_STRING))) { p_prefix = (axis2_char_t*)AXIS2_MALLOC(env->allocator, sizeof (axis2_char_t) * ADB_DEFAULT_NAMESPACE_PREFIX_LIMIT); sprintf(p_prefix, "n%d", (*next_ns_index)++); axutil_hash_set(namespaces, "http://www.w3.org/2000/09/xmldsig#", AXIS2_HASH_KEY_STRING, p_prefix); axiom_element_declare_namespace_assume_param_ownership(parent_element, env, axiom_namespace_create (env, "http://www.w3.org/2000/09/xmldsig#", p_prefix)); } if (!_KeysType->is_valid_KeyInfo) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "Nil value found in non-nillable property KeyInfo"); return NULL; } else { start_input_str = (axis2_char_t*)AXIS2_MALLOC(env->allocator, sizeof(axis2_char_t) * (4 + axutil_strlen(p_prefix) + axutil_strlen("KeyInfo"))); /* axutil_strlen("<:>") + 1 = 4 */ end_input_str = (axis2_char_t*)AXIS2_MALLOC(env->allocator, sizeof(axis2_char_t) * (5 + axutil_strlen(p_prefix) + axutil_strlen("KeyInfo"))); /* axutil_strlen("</:>") + 1 = 5 */ /* * parsing KeyInfo element */ sprintf(start_input_str, "<%s%sKeyInfo", p_prefix?p_prefix:"", (p_prefix && axutil_strcmp(p_prefix, ""))?":":""); start_input_str_len = axutil_strlen(start_input_str); sprintf(end_input_str, "</%s%sKeyInfo>", p_prefix?p_prefix:"", (p_prefix && axutil_strcmp(p_prefix, ""))?":":""); end_input_str_len = axutil_strlen(end_input_str); if(!adb_KeyInfoType_is_particle()) { axutil_stream_write(stream, env, start_input_str, start_input_str_len); } adb_KeyInfoType_serialize(_KeysType->property_KeyInfo, env, current_node, parent_element, adb_KeyInfoType_is_particle() || AXIS2_FALSE, namespaces, next_ns_index); if(!adb_KeyInfoType_is_particle()) { axutil_stream_write(stream, env, end_input_str, end_input_str_len); } AXIS2_FREE(env->allocator,start_input_str); AXIS2_FREE(env->allocator,end_input_str); } if(!(p_prefix = (axis2_char_t*)axutil_hash_get(namespaces, "http://www.daisy.org/DRM/2005/KeyExchange", AXIS2_HASH_KEY_STRING))) { p_prefix = (axis2_char_t*)AXIS2_MALLOC(env->allocator, sizeof (axis2_char_t) * ADB_DEFAULT_NAMESPACE_PREFIX_LIMIT); sprintf(p_prefix, "n%d", (*next_ns_index)++); axutil_hash_set(namespaces, "http://www.daisy.org/DRM/2005/KeyExchange", AXIS2_HASH_KEY_STRING, p_prefix); axiom_element_declare_namespace_assume_param_ownership(parent_element, env, axiom_namespace_create (env, "http://www.daisy.org/DRM/2005/KeyExchange", p_prefix)); } if (!_KeysType->is_valid_KeysTypeChoice_type0) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "Nil value found in non-nillable property KeysTypeChoice_type0"); return NULL; } else { start_input_str = (axis2_char_t*)AXIS2_MALLOC(env->allocator, sizeof(axis2_char_t) * (4 + axutil_strlen(p_prefix) + axutil_strlen("KeysTypeChoice_type0"))); /* axutil_strlen("<:>") + 1 = 4 */ end_input_str = (axis2_char_t*)AXIS2_MALLOC(env->allocator, sizeof(axis2_char_t) * (5 + axutil_strlen(p_prefix) + axutil_strlen("KeysTypeChoice_type0"))); /* axutil_strlen("</:>") + 1 = 5 */ /* * Parsing KeysTypeChoice_type0 array */ if (_KeysType->property_KeysTypeChoice_type0 != NULL) { sprintf(start_input_str, "<%s%sKeysTypeChoice_type0", p_prefix?p_prefix:"", (p_prefix && axutil_strcmp(p_prefix, ""))?":":""); start_input_str_len = axutil_strlen(start_input_str); sprintf(end_input_str, "</%s%sKeysTypeChoice_type0>", p_prefix?p_prefix:"", (p_prefix && axutil_strcmp(p_prefix, ""))?":":""); end_input_str_len = axutil_strlen(end_input_str); count = axutil_array_list_size(_KeysType->property_KeysTypeChoice_type0, env); for(i = 0; i < count; i ++) { element = axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i); if(NULL == element) { continue; } /* * parsing KeysTypeChoice_type0 element */ if(!adb_KeysTypeChoice_type0_is_particle()) { axutil_stream_write(stream, env, start_input_str, start_input_str_len); } adb_KeysTypeChoice_type0_serialize((adb_KeysTypeChoice_type0_t*)element, env, current_node, parent_element, adb_KeysTypeChoice_type0_is_particle() || AXIS2_FALSE, namespaces, next_ns_index); if(!adb_KeysTypeChoice_type0_is_particle()) { axutil_stream_write(stream, env, end_input_str, end_input_str_len); } } } AXIS2_FREE(env->allocator,start_input_str); AXIS2_FREE(env->allocator,end_input_str); } return parent; } /** * Getter for KeyInfo by Property Number 1 */ adb_KeyInfoType_t* AXIS2_CALL adb_KeysType_get_property1( adb_KeysType_t* _KeysType, const axutil_env_t *env) { return adb_KeysType_get_KeyInfo(_KeysType, env); } /** * getter for KeyInfo. */ adb_KeyInfoType_t* AXIS2_CALL adb_KeysType_get_KeyInfo( adb_KeysType_t* _KeysType, const axutil_env_t *env) { AXIS2_ENV_CHECK(env, NULL); AXIS2_PARAM_CHECK(env->error, _KeysType, NULL); return _KeysType->property_KeyInfo; } /** * setter for KeyInfo */ axis2_status_t AXIS2_CALL adb_KeysType_set_KeyInfo( adb_KeysType_t* _KeysType, const axutil_env_t *env, adb_KeyInfoType_t* arg_KeyInfo) { AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); if(_KeysType->is_valid_KeyInfo && arg_KeyInfo == _KeysType->property_KeyInfo) { return AXIS2_SUCCESS; } if(NULL == arg_KeyInfo) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "KeyInfo is being set to NULL, but it is not a nullable element"); return AXIS2_FAILURE; } adb_KeysType_reset_KeyInfo(_KeysType, env); if(NULL == arg_KeyInfo) { /* We are already done */ return AXIS2_SUCCESS; } _KeysType->property_KeyInfo = arg_KeyInfo; _KeysType->is_valid_KeyInfo = AXIS2_TRUE; return AXIS2_SUCCESS; } /** * resetter for KeyInfo */ axis2_status_t AXIS2_CALL adb_KeysType_reset_KeyInfo( adb_KeysType_t* _KeysType, const axutil_env_t *env) { int i = 0; int count = 0; void *element = NULL; AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); if(_KeysType->property_KeyInfo != NULL) { adb_KeyInfoType_free(_KeysType->property_KeyInfo, env); _KeysType->property_KeyInfo = NULL; } _KeysType->is_valid_KeyInfo = AXIS2_FALSE; return AXIS2_SUCCESS; } /** * Check whether KeyInfo is nill */ axis2_bool_t AXIS2_CALL adb_KeysType_is_KeyInfo_nil( adb_KeysType_t* _KeysType, const axutil_env_t *env) { AXIS2_ENV_CHECK(env, AXIS2_TRUE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_TRUE); return !_KeysType->is_valid_KeyInfo; } /** * Set KeyInfo to nill (currently the same as reset) */ axis2_status_t AXIS2_CALL adb_KeysType_set_KeyInfo_nil( adb_KeysType_t* _KeysType, const axutil_env_t *env) { return adb_KeysType_reset_KeyInfo(_KeysType, env); } /** * Getter for KeysTypeChoice_type0 by Property Number 2 */ axutil_array_list_t* AXIS2_CALL adb_KeysType_get_property2( adb_KeysType_t* _KeysType, const axutil_env_t *env) { return adb_KeysType_get_KeysTypeChoice_type0(_KeysType, env); } /** * getter for KeysTypeChoice_type0. */ axutil_array_list_t* AXIS2_CALL adb_KeysType_get_KeysTypeChoice_type0( adb_KeysType_t* _KeysType, const axutil_env_t *env) { AXIS2_ENV_CHECK(env, NULL); AXIS2_PARAM_CHECK(env->error, _KeysType, NULL); return _KeysType->property_KeysTypeChoice_type0; } /** * setter for KeysTypeChoice_type0 */ axis2_status_t AXIS2_CALL adb_KeysType_set_KeysTypeChoice_type0( adb_KeysType_t* _KeysType, const axutil_env_t *env, axutil_array_list_t* arg_KeysTypeChoice_type0) { int size = 0; int i = 0; axis2_bool_t non_nil_exists = AXIS2_FALSE; AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); if(_KeysType->is_valid_KeysTypeChoice_type0 && arg_KeysTypeChoice_type0 == _KeysType->property_KeysTypeChoice_type0) { return AXIS2_SUCCESS; } size = axutil_array_list_size(arg_KeysTypeChoice_type0, env); if (size < 1) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "KeysTypeChoice_type0 has less than minOccurs(1)"); return AXIS2_FAILURE; } for(i = 0; i < size; i ++ ) { if(NULL != axutil_array_list_get(arg_KeysTypeChoice_type0, env, i)) { non_nil_exists = AXIS2_TRUE; break; } } if(!non_nil_exists) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "All the elements in the array of KeysTypeChoice_type0 is being set to NULL, but it is not a nullable or minOccurs=0 element"); return AXIS2_FAILURE; } if(NULL == arg_KeysTypeChoice_type0) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "KeysTypeChoice_type0 is being set to NULL, but it is not a nullable element"); return AXIS2_FAILURE; } adb_KeysType_reset_KeysTypeChoice_type0(_KeysType, env); if(NULL == arg_KeysTypeChoice_type0) { /* We are already done */ return AXIS2_SUCCESS; } _KeysType->property_KeysTypeChoice_type0 = arg_KeysTypeChoice_type0; if(non_nil_exists) { _KeysType->is_valid_KeysTypeChoice_type0 = AXIS2_TRUE; } return AXIS2_SUCCESS; } /** * Get ith element of KeysTypeChoice_type0. */ adb_KeysTypeChoice_type0_t* AXIS2_CALL adb_KeysType_get_KeysTypeChoice_type0_at( adb_KeysType_t* _KeysType, const axutil_env_t *env, int i) { adb_KeysTypeChoice_type0_t* ret_val; AXIS2_ENV_CHECK(env, NULL); AXIS2_PARAM_CHECK(env->error, _KeysType, NULL); if(_KeysType->property_KeysTypeChoice_type0 == NULL) { return (adb_KeysTypeChoice_type0_t*)0; } ret_val = (adb_KeysTypeChoice_type0_t*)axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i); return ret_val; } /** * Set the ith element of KeysTypeChoice_type0. */ axis2_status_t AXIS2_CALL adb_KeysType_set_KeysTypeChoice_type0_at( adb_KeysType_t* _KeysType, const axutil_env_t *env, int i, adb_KeysTypeChoice_type0_t* arg_KeysTypeChoice_type0) { void *element = NULL; int size = 0; int j; int non_nil_count; axis2_bool_t non_nil_exists = AXIS2_FALSE; AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); if( _KeysType->is_valid_KeysTypeChoice_type0 && _KeysType->property_KeysTypeChoice_type0 && arg_KeysTypeChoice_type0 == (adb_KeysTypeChoice_type0_t*)axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i)) { return AXIS2_SUCCESS; } if(NULL != arg_KeysTypeChoice_type0) { non_nil_exists = AXIS2_TRUE; } else { if(_KeysType->property_KeysTypeChoice_type0 != NULL) { size = axutil_array_list_size(_KeysType->property_KeysTypeChoice_type0, env); for(j = 0, non_nil_count = 0; j < size; j ++ ) { if(i == j) continue; if(NULL != axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i)) { non_nil_count ++; non_nil_exists = AXIS2_TRUE; if(non_nil_count >= 1) { break; } } } if( non_nil_count < 1) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "Size of the array of KeysTypeChoice_type0 is beinng set to be smaller than the specificed number of minOccurs(1)"); return AXIS2_FAILURE; } } } if(!non_nil_exists) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "All the elements in the array of KeysTypeChoice_type0 is being set to NULL, but it is not a nullable or minOccurs=0 element"); return AXIS2_FAILURE; } if(_KeysType->property_KeysTypeChoice_type0 == NULL) { _KeysType->property_KeysTypeChoice_type0 = axutil_array_list_create(env, 10); } /* check whether there already exist an element */ element = axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i); if(NULL != element) { adb_KeysTypeChoice_type0_free((adb_KeysTypeChoice_type0_t*)element, env); } axutil_array_list_set(_KeysType->property_KeysTypeChoice_type0 , env, i, arg_KeysTypeChoice_type0); _KeysType->is_valid_KeysTypeChoice_type0 = AXIS2_TRUE; return AXIS2_SUCCESS; } /** * Add to KeysTypeChoice_type0. */ axis2_status_t AXIS2_CALL adb_KeysType_add_KeysTypeChoice_type0( adb_KeysType_t* _KeysType, const axutil_env_t *env, adb_KeysTypeChoice_type0_t* arg_KeysTypeChoice_type0) { AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); if(NULL == arg_KeysTypeChoice_type0) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "All the elements in the array of KeysTypeChoice_type0 is being set to NULL, but it is not a nullable or minOccurs=0 element"); return AXIS2_FAILURE; } if(_KeysType->property_KeysTypeChoice_type0 == NULL) { _KeysType->property_KeysTypeChoice_type0 = axutil_array_list_create(env, 10); } if(_KeysType->property_KeysTypeChoice_type0 == NULL) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "Failed in allocatting memory for KeysTypeChoice_type0"); return AXIS2_FAILURE; } axutil_array_list_add(_KeysType->property_KeysTypeChoice_type0 , env, arg_KeysTypeChoice_type0); _KeysType->is_valid_KeysTypeChoice_type0 = AXIS2_TRUE; return AXIS2_SUCCESS; } /** * Get the size of the KeysTypeChoice_type0 array. */ int AXIS2_CALL adb_KeysType_sizeof_KeysTypeChoice_type0( adb_KeysType_t* _KeysType, const axutil_env_t *env) { AXIS2_ENV_CHECK(env, -1); AXIS2_PARAM_CHECK(env->error, _KeysType, -1); if(_KeysType->property_KeysTypeChoice_type0 == NULL) { return 0; } return axutil_array_list_size(_KeysType->property_KeysTypeChoice_type0, env); } /** * remove the ith element, same as set_nil_at. */ axis2_status_t AXIS2_CALL adb_KeysType_remove_KeysTypeChoice_type0_at( adb_KeysType_t* _KeysType, const axutil_env_t *env, int i) { return adb_KeysType_set_KeysTypeChoice_type0_nil_at(_KeysType, env, i); } /** * resetter for KeysTypeChoice_type0 */ axis2_status_t AXIS2_CALL adb_KeysType_reset_KeysTypeChoice_type0( adb_KeysType_t* _KeysType, const axutil_env_t *env) { int i = 0; int count = 0; void *element = NULL; AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); if (_KeysType->property_KeysTypeChoice_type0 != NULL) { count = axutil_array_list_size(_KeysType->property_KeysTypeChoice_type0, env); for(i = 0; i < count; i ++) { element = axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i); if(element != NULL) { adb_KeysTypeChoice_type0_free((adb_KeysTypeChoice_type0_t*)element, env); element = NULL; } } axutil_array_list_free(_KeysType->property_KeysTypeChoice_type0, env); } _KeysType->is_valid_KeysTypeChoice_type0 = AXIS2_FALSE; return AXIS2_SUCCESS; } /** * Check whether KeysTypeChoice_type0 is nill */ axis2_bool_t AXIS2_CALL adb_KeysType_is_KeysTypeChoice_type0_nil( adb_KeysType_t* _KeysType, const axutil_env_t *env) { AXIS2_ENV_CHECK(env, AXIS2_TRUE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_TRUE); return !_KeysType->is_valid_KeysTypeChoice_type0; } /** * Set KeysTypeChoice_type0 to nill (currently the same as reset) */ axis2_status_t AXIS2_CALL adb_KeysType_set_KeysTypeChoice_type0_nil( adb_KeysType_t* _KeysType, const axutil_env_t *env) { return adb_KeysType_reset_KeysTypeChoice_type0(_KeysType, env); } /** * Check whether KeysTypeChoice_type0 is nill at i */ axis2_bool_t AXIS2_CALL adb_KeysType_is_KeysTypeChoice_type0_nil_at( adb_KeysType_t* _KeysType, const axutil_env_t *env, int i) { AXIS2_ENV_CHECK(env, AXIS2_TRUE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_TRUE); return (_KeysType->is_valid_KeysTypeChoice_type0 == AXIS2_FALSE || NULL == _KeysType->property_KeysTypeChoice_type0 || NULL == axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i)); } /** * Set KeysTypeChoice_type0 to nill at i */ axis2_status_t AXIS2_CALL adb_KeysType_set_KeysTypeChoice_type0_nil_at( adb_KeysType_t* _KeysType, const axutil_env_t *env, int i) { void *element = NULL; int size = 0; int j; axis2_bool_t non_nil_exists = AXIS2_FALSE; int k = 0; AXIS2_ENV_CHECK(env, AXIS2_FAILURE); AXIS2_PARAM_CHECK(env->error, _KeysType, AXIS2_FAILURE); if(_KeysType->property_KeysTypeChoice_type0 == NULL || _KeysType->is_valid_KeysTypeChoice_type0 == AXIS2_FALSE) { non_nil_exists = AXIS2_FALSE; } else { size = axutil_array_list_size(_KeysType->property_KeysTypeChoice_type0, env); for(j = 0, k = 0; j < size; j ++ ) { if(i == j) continue; if(NULL != axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i)) { k ++; non_nil_exists = AXIS2_TRUE; if( k >= 1) { break; } } } } if(!non_nil_exists) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "All the elements in the array of KeysTypeChoice_type0 is being set to NULL, but it is not a nullable or minOccurs=0 element"); return AXIS2_FAILURE; } if( k < 1) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "Size of the array of KeysTypeChoice_type0 is beinng set to be smaller than the specificed number of minOccurs(1)"); return AXIS2_FAILURE; } if(_KeysType->property_KeysTypeChoice_type0 == NULL) { _KeysType->is_valid_KeysTypeChoice_type0 = AXIS2_FALSE; return AXIS2_SUCCESS; } /* check whether there already exist an element */ element = axutil_array_list_get(_KeysType->property_KeysTypeChoice_type0, env, i); if(NULL != element) { adb_KeysTypeChoice_type0_free((adb_KeysTypeChoice_type0_t*)element, env); } axutil_array_list_set(_KeysType->property_KeysTypeChoice_type0 , env, i, NULL); return AXIS2_SUCCESS; }
lgpl-2.1
bsc-performance-tools/wxparaver
src/rowsselectiondialog.cpp
1
29762
/*****************************************************************************\ * ANALYSIS PERFORMANCE TOOLS * * wxparaver * * Paraver Trace Visualization and Analysis Tool * ***************************************************************************** * ___ This library is free software; you can redistribute it and/or * * / __ modify it under the terms of the GNU LGPL as published * * / / _____ by the Free Software Foundation; either version 2.1 * * / / / \ of the License, or (at your option) any later version. * * ( ( ( B S C ) * * \ \ \_____/ This library is distributed in 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 LGPL 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 * * The GNU LEsser General Public License is contained in the file COPYING. * * --------- * * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * \*****************************************************************************/ // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes #include "wx/bookctrl.h" ////@end includes #include "wx/filename.h" #include "rowsselectiondialog.h" #include "labelconstructor.h" #include "gtimeline.h" #include "histogram.h" #include "window.h" //#include "pg_extraprop.h" //#include "windows_tree.h" #include "paravermain.h" // for help using namespace std; ////@begin XPM images ////@end XPM images #include "../icons/help.xpm" /*! * RowsSelectionDialog type definition */ IMPLEMENT_DYNAMIC_CLASS( RowsSelectionDialog, wxPropertySheetDialog ) /*! * RowsSelectionDialog event table definition */ BEGIN_EVENT_TABLE( RowsSelectionDialog, wxPropertySheetDialog ) EVT_BUTTON( wxID_OK, RowsSelectionDialog::OnOkClick ) END_EVENT_TABLE() /* * RowsSelectionDialog constructors */ RowsSelectionDialog::RowsSelectionDialog() { Init(); } // Constructor for Timelines RowsSelectionDialog::RowsSelectionDialog( wxWindow* parent, Timeline *whichTimeline, SelectionManagement< TObjectOrder, TTraceLevel > *whichSelectedRows, wxWindowID id, const wxString& caption, bool whichParentIsGtimeline, const wxPoint& pos, const wxSize& size, long style ) : myTimeline( whichTimeline ), mySelectedRows( whichSelectedRows ), parentIsGtimeline( whichParentIsGtimeline ) { Init(); Create( parent, id, caption, pos, size, style ); myHistogram = nullptr; myLevel = myTimeline->getLevel(); myTrace = myTimeline->getTrace(); lockedByUpdate = false; if ( ( myLevel >= TTraceLevel::SYSTEM ) && ( myLevel <= TTraceLevel::CPU ) ) { minLevel = TTraceLevel::NODE; buildPanel( wxT("Node"), TTraceLevel::NODE ); buildPanel( wxT("CPU"), TTraceLevel::CPU ); } else if ( ( myLevel >= TTraceLevel::WORKLOAD ) && ( myLevel <= TTraceLevel::THREAD ) ) { minLevel = TTraceLevel::APPLICATION; buildPanel( _("Application"), TTraceLevel::APPLICATION ); buildPanel( _("Task"), TTraceLevel::TASK ); buildPanel( _("Thread"), TTraceLevel::THREAD ); } LayoutDialog(); Centre(); } // Constructor for Histograms RowsSelectionDialog::RowsSelectionDialog( wxWindow* parent, Histogram* histogram, SelectionManagement< TObjectOrder, TTraceLevel > *whichSelectedRows, wxWindowID id, const wxString& caption, bool whichParentIsGtimeline, const wxPoint& pos, const wxSize& size, long style ) : myHistogram( histogram ), mySelectedRows( whichSelectedRows ), parentIsGtimeline( whichParentIsGtimeline ) { Init(); Create( parent, id, caption, pos, size, style ); SelectionManagement< TObjectOrder, TTraceLevel > sm = ( *myHistogram->getRowSelectionManagement() ); vector< TObjectOrder > rowsel; sm.getSelected( rowsel, myHistogram->getControlWindow()->getLevel() ); myTimeline = nullptr; myLevel = myHistogram->getControlWindow()->getLevel(); myTrace = myHistogram->getTrace(); lockedByUpdate = false; if (( myLevel >= TTraceLevel::SYSTEM ) && ( myLevel <= TTraceLevel::CPU )) { minLevel = TTraceLevel::NODE; buildPanel( wxT("Node"), TTraceLevel::NODE ); buildPanel( wxT("CPU"), TTraceLevel::CPU ); } else if (( myLevel >= TTraceLevel::WORKLOAD ) && ( myLevel <= TTraceLevel::THREAD )) { minLevel = TTraceLevel::APPLICATION; buildPanel( wxT("Application"), TTraceLevel::APPLICATION ); buildPanel( wxT("Task"), TTraceLevel::TASK ); buildPanel( wxT("Thread"), TTraceLevel::THREAD ); } LayoutDialog(); Centre(); } /*! * RowsSelectionDialog creator */ bool RowsSelectionDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { SetExtraStyle( wxWS_EX_VALIDATE_RECURSIVELY | wxWS_EX_BLOCK_EVENTS ); SetSheetStyle( wxPROPSHEET_DEFAULT ); wxPropertySheetDialog::Create( parent, id, caption, pos, size, style ); CreateButtons( wxOK | wxCANCEL ); CreateControls(); LayoutDialog(); Centre(); return true; } void RowsSelectionDialog::OnRegularExpressionHelp( wxCommandEvent& event ) { if ( !paraverMain::myParaverMain->GetParaverConfig()->getGlobalHelpContentsQuestionAnswered() ) paraverMain::myParaverMain->helpQuestion(); wxChar SEP = wxFileName::GetPathSeparator(); wxString helpContentsDir = SEP + wxString( wxT( "share" ) ) + SEP + wxString( wxT( "doc" ) ) + SEP + wxString( wxT( "wxparaver_help_contents" ) ) + SEP + wxString( wxT( "html" ) ) + SEP; wxString helpChapter = wxString( wxT( "1.quick_reference" ) ) + SEP + wxString( wxT( "index.html")); wxString helpRegEx = wxString( wxT( "#objects_regex" ) ); paraverMain::myParaverMain->createHelpContentsWindow( helpContentsDir, helpChapter, helpRegEx, true ); } /* * Dynamic panel building */ void RowsSelectionDialog::buildPanel( const wxString& title, TTraceLevel whichLevel ) { wxPanel *myPanel; myPanel = new wxPanel( GetBookCtrl(), wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxTAB_TRAVERSAL ); GetBookCtrl()->AddPage( myPanel, title, whichLevel == myLevel ); //myTimeline->getLevel() ); wxBoxSizer *panelSizer = new wxBoxSizer( wxVERTICAL ); wxBoxSizer *buttonsSizer = new wxBoxSizer( wxHORIZONTAL ); myPanel->SetSizer( panelSizer ); // Add Checklist lines wxArrayString choices; for ( size_t row = (size_t)0; row < myTrace->getLevelObjects( whichLevel ); ++row ) { if( whichLevel == TTraceLevel::CPU || whichLevel == TTraceLevel::NODE ) choices.Add( wxString::FromUTF8( LabelConstructor::objectLabel( (TObjectOrder)row + 1, whichLevel, myTrace ).c_str() ) ); else choices.Add( wxString::FromUTF8( LabelConstructor::objectLabel( (TObjectOrder)row, whichLevel, myTrace ).c_str() ) ); } //vector< TObjectOrder > selectedIndex; mySelectedRows->getSelected( selectedIndex[ whichLevel ], whichLevel ); wxCheckListBox * auxCheckList = new wxCheckListBox( myPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, choices ); auxCheckList->Connect( wxEVT_COMMAND_LISTBOX_SELECTED, wxCommandEventHandler( RowsSelectionDialog::OnCheckListBoxSelected ), nullptr, this ); levelCheckList.push_back( auxCheckList ); PRV_INT16 firstFound = -1; for ( unsigned int i = 0; i < (unsigned int)selectedIndex[ whichLevel ].size(); ++i ) { if ( firstFound == -1 ) firstFound = selectedIndex[ whichLevel ][ i ]; auxCheckList->Check( selectedIndex[ whichLevel ][ i ] ); } if ( firstFound != -1 ) auxCheckList->SetFirstItem( (int)firstFound ); panelSizer->Add( auxCheckList, 3, wxALL | wxGROW, 5 ); // // BUTTONS // wxButton *auxButton = new wxButton( myPanel, wxID_ANY, _("Select All") ); selectionButtons.push_back( auxButton ); auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RowsSelectionDialog:: OnSelectAllButtonClicked ), nullptr, this ); buttonsSizer->Add( auxButton, 1, wxGROW | wxALL, 5 ); auxButton = new wxButton( myPanel, wxID_ANY, _("Unselect All") ); selectionButtons.push_back( auxButton ); auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked ), nullptr, this ); buttonsSizer->Add( auxButton, 1, wxGROW | wxALL, 5 ); auxButton = new wxButton( myPanel, wxID_ANY, _("Invert") ); selectionButtons.push_back( auxButton ); auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked ), nullptr, this ); buttonsSizer->Add( auxButton, 1, wxGROW | wxALL, 5 ); // Build Panel panelSizer->Add( buttonsSizer, 0, wxGROW | wxALL , 5 ); // // REGULAR EXPRESSION BOX // // RE: Text box bool initialCheckState = false; wxStaticBox* regularExpressionBox = new wxStaticBox(myPanel, wxID_ANY, wxT(" Add checks by objects matching ")); wxStaticBoxSizer* regularExpressionBoxSizer = new wxStaticBoxSizer( regularExpressionBox, wxVERTICAL ); wxBoxSizer *regularExpressionSizerUp = new wxBoxSizer( wxHORIZONTAL ); wxBoxSizer *regularExpressionSizerDown = new wxBoxSizer( wxVERTICAL ); wxTextCtrl *auxTextCtrl = new wxTextCtrl( myPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); auxTextCtrl->Connect( wxEVT_COMMAND_TEXT_ENTER , wxCommandEventHandler( RowsSelectionDialog::OnRegularExpressionApply ), nullptr, this ); auxTextCtrl->SetToolTip( getMyToolTip( initialCheckState ) ); textCtrlRegularExpr.push_back( auxTextCtrl ); regularExpressionSizerUp->Add( auxTextCtrl, 1, wxGROW | wxALL, 5 ); // userRegularExpr->SetValidator( getValidator( ) ); wxRegEx *aux = new wxRegEx( wxString( wxT( ".*" ) ) ); validRE.push_back( aux ); // RE: APPLY button auxButton = new wxButton( myPanel, wxID_ANY, _("Apply") ); auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnRegularExpressionApply ), nullptr, this ); auxButton->Enable( true ); applyButtons.push_back( auxButton ); regularExpressionSizerUp->Add( auxButton, 0, wxGROW | wxALL, 5 ); // RE: Help button wxBitmapButton *auxButtonBMP = new wxBitmapButton( myPanel, wxID_ANY, wxBitmap( help_xpm ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW ); auxButtonBMP->SetToolTip(_("Regular expressions help.")); auxButtonBMP->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnRegularExpressionHelp ), nullptr, this ); auxButtonBMP->Enable( true ); helpRE.push_back( auxButtonBMP ); regularExpressionSizerUp->Add( auxButtonBMP, 0, wxGROW | wxALL, 5 ); // RE: Check wxCheckBox *auxCheckBox = new wxCheckBox( myPanel, wxID_ANY, _("Match as Posix Basic Regular Expression"), wxDefaultPosition, wxDefaultSize, 0 ); auxCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnCheckBoxMatchPosixRegExpClicked ), nullptr, this ); auxCheckBox->SetValue( initialCheckState ); auxCheckBox->SetToolTip( getMyToolTip( initialCheckState ) ); checkBoxPosixBasicRegExp.push_back( auxCheckBox ); regularExpressionSizerDown->Add( auxCheckBox, 0, wxGROW | wxALL, 5 ); // RE: Message wxStaticText *auxStaticText = new wxStaticText( myPanel, wxID_ANY, _("" ) ); messageMatchesFound.push_back( auxStaticText ); regularExpressionSizerDown->Add( auxStaticText, 0, wxGROW | wxALL, 5 ); // RE: Final Build regularExpressionBoxSizer->Add( regularExpressionSizerUp, 0, wxGROW | wxALL , 0 ); regularExpressionBoxSizer->Add( regularExpressionSizerDown, 0, wxGROW | wxALL , 0 ); panelSizer->Add( regularExpressionBoxSizer, 0, wxGROW | wxALL , 5 ); } /*! * RowsSelectionDialog destructor */ RowsSelectionDialog::~RowsSelectionDialog() { // TODO: MEMORY ALLOCATED NOT FREED for ( vector< wxCheckListBox* >::iterator it = levelCheckList.begin(); it != levelCheckList.end(); ++it ) { (*it)->Disconnect( wxEVT_COMMAND_LISTBOX_SELECTED, wxCommandEventHandler( RowsSelectionDialog::OnCheckListBoxSelected ) ); } for ( vector< wxCheckBox* >::iterator it = checkBoxPosixBasicRegExp.begin(); it != checkBoxPosixBasicRegExp.end(); ++it ) { (*it)->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnCheckBoxMatchPosixRegExpClicked )); } for ( vector< wxButton * >::iterator it = selectionButtons.begin(); it != selectionButtons.end(); ++it ) { (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnSelectAllButtonClicked )); ++it; (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked )); ++it; (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked )); } for ( vector< wxTextCtrl * >::iterator it = textCtrlRegularExpr.begin(); it != textCtrlRegularExpr.end(); ++it ) { (*it)->Disconnect( wxEVT_COMMAND_TEXT_ENTER , wxCommandEventHandler( RowsSelectionDialog::OnRegularExpressionApply ) ); } for ( vector< wxButton * >::iterator it = applyButtons.begin(); it != applyButtons.end(); ++it ) { (*it)->Disconnect( wxEVT_COMMAND_TEXT_ENTER , wxCommandEventHandler( RowsSelectionDialog::OnRegularExpressionApply ) ); } for ( vector< wxButton * >::iterator it = helpRE.begin(); it != helpRE.end(); ++it ) { (*it)->Disconnect( wxEVT_COMMAND_TEXT_ENTER , wxCommandEventHandler( RowsSelectionDialog::OnRegularExpressionHelp ) ); } /*if ( myTimeline != nullptr ) TWindowLevel myLevel = myTimeline->getLevel(); else if ( myHistogram != nullptr ) TWindowLevel myLevel = myHistogram->getControlWindow()->getLevel();*/ TTraceLevel beginLevel, endLevel; if (( myLevel >= TTraceLevel::SYSTEM ) && ( myLevel <= TTraceLevel::CPU )) { beginLevel = TTraceLevel::NODE; endLevel = TTraceLevel::CPU; } else if (( myLevel >= TTraceLevel::WORKLOAD ) && ( myLevel <= TTraceLevel::THREAD )) { beginLevel = TTraceLevel::APPLICATION; endLevel = TTraceLevel::THREAD; } TTraceLevel levelDiff = static_cast<TTraceLevel>( static_cast<size_t>( endLevel ) - static_cast<size_t>( beginLevel ) ); for( TTraceLevel l = TTraceLevel::NONE; l <= levelDiff; ++l ) { size_t tmpL = static_cast<size_t>( l ); delete selectionButtons[ tmpL ]; delete levelCheckList[ tmpL ]; delete messageMatchesFound[ tmpL ]; delete checkBoxPosixBasicRegExp[ tmpL ]; delete textCtrlRegularExpr[ tmpL ]; delete applyButtons[ tmpL ]; delete validRE[ tmpL ]; delete helpRE[ tmpL ]; } } /*! * Member initialisation */ void RowsSelectionDialog::Init() { shouldChangeTimelineZoom = false; beginZoom = TObjectOrder( 0 ); endZoom = TObjectOrder( 0 ); } /*! * Control creation for RowsSelectionDialog */ void RowsSelectionDialog::CreateControls() { } /*! * Should we show tooltips? */ bool RowsSelectionDialog::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap RowsSelectionDialog::GetBitmapResource( const wxString& name ) { // Bitmap retrieval wxUnusedVar(name); return wxNullBitmap; } /*! * Get icon resources */ wxIcon RowsSelectionDialog::GetIconResource( const wxString& name ) { // Icon retrieval wxUnusedVar(name); return wxNullIcon; } int RowsSelectionDialog::GetSelections( TTraceLevel whichLevel, wxArrayInt &selections ) { int selected = 0; size_t levelDiff = static_cast<size_t>( whichLevel ) - static_cast<size_t>( minLevel ); if ( levelCheckList[ levelDiff ] != nullptr ) for ( unsigned int i = 0; i < levelCheckList[ levelDiff ]->GetCount(); ++i ) { if ( levelCheckList[ levelDiff ]->IsChecked( i ) ) { ++selected; selections.Add( i ); } } return selected; } bool RowsSelectionDialog::TransferDataFromWindow() { TTraceLevel beginLevel; TTraceLevel endLevel; // Set range of levels for update loop if (( myLevel >= TTraceLevel::WORKLOAD ) && ( myLevel <= TTraceLevel::THREAD )) { beginLevel = TTraceLevel::APPLICATION; endLevel = TTraceLevel::THREAD; } else { beginLevel = TTraceLevel::NODE; endLevel = TTraceLevel::CPU; } // Loop through levels to update gTimeline for ( TTraceLevel whichLevel = beginLevel; whichLevel <= endLevel; ++whichLevel ) { wxArrayInt selections; int numberSelected = GetSelections( whichLevel, selections ); if ( numberSelected > 0 ) { // Get new selections for that level vector< TObjectOrder > newSelection; for ( size_t row = (size_t)0; row < (size_t)numberSelected; row++ ) { newSelection.push_back( (TObjectOrder)selections[ row ] ); } mySelectedRows->setSelected( newSelection, myTrace->getLevelObjects( whichLevel ), whichLevel ); } } return true; } /* * Regular Expression methods */ wxString RowsSelectionDialog::buildRegularExpressionString( const wxString& enteredRE ) { wxString parsedRE; for( size_t i = 0; i < enteredRE.Len(); ++i ) { switch ( (wxChar)enteredRE.GetChar( i ) ) { case wxChar('.'): parsedRE += wxString( wxT( "[.]" ) ); break; case wxChar('+'): parsedRE += wxString( wxT( "[[:alnum:]]+" ) ); break; case wxChar('*'): parsedRE += wxString( wxT( "[[:alnum:]]*" ) ); break; case wxChar('#'): parsedRE += wxString( wxT( "[[:digit:]]" ) ); break; case wxChar('?'): parsedRE += wxString( wxT( "[[:alpha:]]" ) ); break; // case wxChar('^'): // need this? // parsedRE += wxString( wxT( "^" ) ); // break; default: parsedRE += enteredRE.GetChar( i ); break; } } return parsedRE; } int RowsSelectionDialog::countMatches( int iTab, wxRegEx *&levelRE ) { int matches = 0; wxCheckListBox * myLevelCheckList = levelCheckList[ iTab ]; for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i ) { wxString currentRow( myLevelCheckList->GetString( i ) ); if ( levelRE->Matches( currentRow ) ) { matches++; } } return matches; } void RowsSelectionDialog::checkMatches( const int &iTab, wxRegEx *&levelRE ) { lockedByUpdate = true; wxCheckListBox * myLevelCheckList = levelCheckList[ iTab ]; for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i ) { wxString currentRow( myLevelCheckList->GetString( i ) ); if ( levelRE->Matches( currentRow ) ) { myLevelCheckList->Check( i ); } } lockedByUpdate = false; } // false: simple mode // true : basicPosixRegExprMode wxTextValidator* RowsSelectionDialog::getValidator( bool basicPosixRegExprMode ) { wxTextValidator *myValidator; if ( !basicPosixRegExprMode ) { wxString allowedChars[] = { _("0"), _("1"), _("2"), _("3"), _("4"), _("5"), _("6"), _("7"), _("8"), _("9"), _("."), // level separator _("+"), // any alphanum, but '.' _("*"), // many alphanum, but '.' _("#"), // any number _("$") // any char }; myValidator = new wxTextValidator( (long int)wxFILTER_INCLUDE_CHAR_LIST ); wxArrayString charIncludes( (size_t)15, allowedChars ); myValidator->SetIncludes( charIncludes ); } else { wxString allowedChars[] = { _("0"), _("1"), _("2"), _("3"), _("4"), _("5"), _("6"), _("7"), _("8"), _("9"), _("."), // any character _("+"), // zero or one repetition of preceeding item _("*"), // zero or many repetitions of preceeding item _("#"), // used? _("^"), // begin of line _("$") // end of line }; myValidator = new wxTextValidator( (long int)wxFILTER_INCLUDE_CHAR_LIST ); wxArrayString charIncludes( (size_t)15, allowedChars ); myValidator->SetIncludes( charIncludes ); } return myValidator; } wxString RowsSelectionDialog::getMyToolTip( const bool posixBasicRegExpTip ) { return ( posixBasicRegExpTip? wxT( "Posix basic regular expression form:\n" " . : any character (use [.] for dot)\n" " ? : 0 - 1 repetition of preceeding item\n" " + : 1 - n repetitions of preceeding item\n" " * : 0 - n repetitions of preceeding item\n" " ^ : begin of line\n" " $ : end of line\n" " [1234] : set that matches from 1 to 4\n" " [1-3] : range that matches from 1 to 3\n\n" ) : wxT( "Quick form:\n" " . : '.' (dot character)\n" " # : only one number\n" " ? : only one character\n" " + : one or many alfanumeric\n" " * : zero or many alfanumeric\n" " ^ : begin of line\n" " $ : end of line\n" " [1234] : set that matches from 1 to 4\n" " [1-3] : range that matches from 1 to 3\n\n" ) ); } void RowsSelectionDialog::OnCheckBoxMatchPosixRegExpClicked( wxCommandEvent& event ) { int iTab = GetBookCtrl()->GetSelection(); bool posixBasicRegExpTip = checkBoxPosixBasicRegExp[ iTab ]->IsChecked(); textCtrlRegularExpr[ iTab ]->SetToolTip( getMyToolTip( posixBasicRegExpTip ) ); checkBoxPosixBasicRegExp[ iTab ]->SetToolTip( getMyToolTip( posixBasicRegExpTip ) ); } void RowsSelectionDialog::OnRegularExpressionApply( wxCommandEvent& event ) { // Get wxString that represents regular expression int iTab = GetBookCtrl()->GetSelection(); // wxString parsedRE = event.GetString(); // DOESN'T WORK WITH BUTTON APPLY wxString parsedRE = textCtrlRegularExpr[ iTab ]->GetValue(); if ( !checkBoxPosixBasicRegExp[ iTab ]->GetValue() ) { // It is Quick Form; we must adapt it. parsedRE = buildRegularExpressionString( parsedRE ); } // Build regular expression wxRegEx *levelRE = new wxRegEx(); if ( levelRE->Compile( parsedRE ) ) { // Any match? int matches = countMatches( iTab, levelRE ); if( matches > 0 ) { // Save this regular expression as a valid one. // validRE[ iTab ] = levelRE; checkMatches( iTab, levelRE ); // Message wxString msg = wxString::Format( wxT( "%i" ), matches ); if ( matches > 1 ) { msg += wxString( wxT( " matches " ) ); } else { msg += wxString( wxT( " match " ) ); } msg += wxString( wxT( " has been checked." ) ); messageMatchesFound[ iTab ]->SetLabel( msg ); } else { messageMatchesFound[ iTab ]->SetLabel( wxString( wxT( "No matches found." ) ) ); // delete levelRE; } } else { messageMatchesFound[ iTab ]->SetLabel( wxString( wxT( "Syntax error in regular expression!" ) ) ); } delete levelRE; } void RowsSelectionDialog::OnCheckListBoxSelected( wxCommandEvent& event ) { if ( lockedByUpdate ) { event.Skip(); } else { // Copy selected to Reg. Exp. Text box. int tabNumber = GetBookCtrl()->GetSelection(); wxString currentRow = event.GetString(); textCtrlRegularExpr[ tabNumber ]->SetValue( currentRow ); } } void RowsSelectionDialog::OnSelectAllButtonClicked( wxCommandEvent& event ) { wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ]; for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i ) myLevelCheckList->Check( i ); } void RowsSelectionDialog::OnUnselectAllButtonClicked( wxCommandEvent& event ) { wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ]; for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i ) myLevelCheckList->Check( i, false ); } void RowsSelectionDialog::OnInvertButtonClicked( wxCommandEvent& event ) { wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ]; for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i ) myLevelCheckList->Check( i, !myLevelCheckList->IsChecked( i ) ); } void RowsSelectionDialog::ZoomAwareTransferData( const wxArrayInt &dialogSelections, const vector< TObjectOrder > &timelineZoomRange ) { if ( timelineZoomRange.size() > 0 ) { TObjectOrder newBegin( dialogSelections[0] ); TObjectOrder newEnd( dialogSelections.Last() ); TObjectOrder curBegin( timelineZoomRange.front() ); TObjectOrder curEnd( timelineZoomRange.back() ); if ( curBegin <= newBegin && newEnd <= curEnd ) // Are new limits inside/visible? { if ( TransferDataFromWindow() ) EndModal( wxID_OK ); } else { wxString tmpMsg( wxT( "Do you want to extend the zoom to fit selected objects?" ) ); wxMessageDialog tmpDialog( this, tmpMsg, _( "Paraver question" ), wxYES_NO | wxICON_QUESTION ); if ( tmpDialog.ShowModal() == wxID_YES ) { if ( TransferDataFromWindow() ) { // Extend to the maximum shouldChangeTimelineZoom = true; beginZoom = curBegin < newBegin ? curBegin : newBegin; endZoom = curEnd > newEnd ? curEnd : newEnd; EndModal( wxID_OK ); } } } } } void RowsSelectionDialog::OnOkClick( wxCommandEvent& event ) { // Are selected into the current zoom? wxArrayInt dialogSelections; int numberSelected = GetSelections( myLevel, dialogSelections ); if ( numberSelected == 0 ) { wxString tmpMsg( wxT( "No object selected!" ) ); wxMessageDialog tmpDialog( this, tmpMsg, _( "Warning" ), wxOK | wxICON_EXCLAMATION ); if ( tmpDialog.ShowModal() == wxID_OK ) { } } else if ( parentIsGtimeline && myTimeline != nullptr ) { ZoomAwareTransferData( dialogSelections, ((gTimeline *)GetParent())->getCurrentZoomRange() ); } else if ( parentIsGtimeline && myHistogram != nullptr ) { std::vector< TObjectOrder > selection; mySelectedRows->getSelected( selection, myLevel ); ZoomAwareTransferData( dialogSelections, selection ); } else { #if 0 bool foundGTimeline; gTimeline *tmpTimeline = getGTimelineFromWindow( getAllTracesTree()->GetRootItem(), myTimeline, foundGTimeline ); if ( foundGTimeline ) { TransferDataComputingZoom( tmpTimeline->getCurrentZoomRange() ); } #else if ( TransferDataFromWindow() ) EndModal( wxID_OK ); #endif } }
lgpl-2.1
robclark/qtmobility-1.1.0
tests/auto/qmediaobject/main.cpp
1
3164
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with ** the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qcoreapplication.h> #include <QtTest/QtTest> #include "tst_qmediaobject.h" #ifdef Q_OS_SYMBIAN #ifdef HAS_OPENMAXAL_MEDIAPLAY_BACKEND #include "tst_qmediaobject_xa.h" #else #include "tst_qmediaobject_mmf.h" #endif #endif int main(int argc, char**argv) { QApplication app(argc,argv); int ret; tst_QMediaObject test_api; ret = QTest::qExec(&test_api, argc, argv); #ifdef Q_OS_SYMBIAN #ifdef HAS_OPENMAXAL_MEDIAPLAY_BACKEND char *new_argv[3]; QString str = "C:\\data\\" + QFileInfo(QCoreApplication::applicationFilePath()).baseName() + ".log"; QByteArray bytes = str.toAscii(); char arg1[] = "-o"; new_argv[0] = argv[0]; new_argv[1] = arg1; new_argv[2] = bytes.data(); tst_QMetadata_xa test_xa; ret = QTest::qExec(&test_xa, 3, new_argv); #else char *new_argv[3]; QString str = "C:\\data\\" + QFileInfo(QCoreApplication::applicationFilePath()).baseName() + ".log"; QByteArray bytes = str.toAscii(); char arg1[] = "-o"; new_argv[0] = argv[0]; new_argv[1] = arg1; new_argv[2] = bytes.data(); tst_QMediaObject_mmf test_mmf; ret = QTest::qExec(&test_mmf, 3, new_argv); #endif #endif return ret; }
lgpl-2.1
jcupitt/libvips
libvips/iofuncs/generate.c
1
19372
/* Manage pipelines of partial images. * * J.Cupitt, 17/4/93. * 1/7/93 JC * - adapted for partial v2 * - ANSIfied * 6/7/93 JC * - im_setupout() conventions clarified - see autorewind in * im_iocheck(). * 20/7/93 JC * - eval callbacks added * 7/9/93 JC * - demand hint mechanism added * 25/10/93 * - asynchronous output mechanisms removed, as no observable speed-up * 9/5/94 * - new thread stuff added, with a define to turn it off * 15/8/94 * - start & stop functions can now be NULL for no-op * 7/10/94 JC * - evalend callback system added * 23/12/94 JC * - IM_ARRAY uses added * 22/2/95 JC * - im_fill_copy() added * - im_region_region() uses modified * 24/4/95 JC & KM * - im_fill_lines() bug removed * 30/8/96 JC * - revised and simplified ... some code shared with im_iterate() * - new im_generate_region() added * 2/3/98 JC * - IM_ANY added * 20/7/99 JC * - tile geometry made into ints for easy tuning * 30/7/99 RP JC * - threads reorganised for POSIX * 29/9/99 JC * - threadgroup stuff added * 15/4/04 * - better how-many-pixels-calculated * 27/11/06 * - merge background write stuff * 7/11/07 * - new start/end eval callbacks * 7/10/09 * - gtkdoc comments * 16/4/10 * - remove threadgroup stuff * 24/3/11 * - move demand_hint stuff in here * - move to vips_ namespace * 7/7/12 * - lock around link make/break so we can process an image from many * threads */ /* This file is part of VIPS. VIPS 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 program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk */ /* #define VIPS_DEBUG #define DEBUG */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /*HAVE_CONFIG_H*/ #include <vips/intl.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <assert.h> #include <errno.h> #include <string.h> #include <sys/types.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif /*HAVE_UNISTD_H*/ #ifdef HAVE_IO_H #include <io.h> #endif /*HAVE_IO_H*/ #include <vips/vips.h> #include <vips/internal.h> #include <vips/thread.h> #include <vips/debug.h> /** * SECTION: generate * @short_description: calculate pixels and pixel buffers * @stability: Stable * @see_also: <link linkend="VipsImage">VipsImage</link>, * <link linkend="VipsRegion">VipsRegion</link> * @include: vips/vips.h * * These functions let you attach generate functions to images * and ask for regions of images to be calculated. */ /* Max number of images we can handle. */ #define MAX_IMAGES (1000) /* Make an upstream/downstream link. upstream is one of downstream's inputs. */ static void vips__link_make( VipsImage *image_up, VipsImage *image_down ) { g_assert( image_up ); g_assert( image_down ); image_up->downstream = g_slist_prepend( image_up->downstream, image_down ); image_down->upstream = g_slist_prepend( image_down->upstream, image_up ); /* Propogate the progress indicator. */ if( image_up->progress_signal && !image_down->progress_signal ) image_down->progress_signal = image_up->progress_signal; } static void * vips__link_break( VipsImage *image_up, VipsImage *image_down, void *b ) { g_assert( image_up ); g_assert( image_down ); g_assert( g_slist_find( image_up->downstream, image_down ) ); g_assert( g_slist_find( image_down->upstream, image_up ) ); image_up->downstream = g_slist_remove( image_up->downstream, image_down ); image_down->upstream = g_slist_remove( image_down->upstream, image_up ); /* Unlink the progress chain. */ if( image_down->progress_signal && image_down->progress_signal == image_up->progress_signal ) image_down->progress_signal = NULL; return( NULL ); } static void * vips__link_break_rev( VipsImage *image_down, VipsImage *image_up, void *b ) { return( vips__link_break( image_up, image_down, b ) ); } /* A VipsImage is going ... break all links. */ void vips__link_break_all( VipsImage *image ) { g_mutex_lock( vips__global_lock ); vips_slist_map2( image->upstream, (VipsSListMap2Fn) vips__link_break, image, NULL ); vips_slist_map2( image->downstream, (VipsSListMap2Fn) vips__link_break_rev, image, NULL ); g_assert( !image->upstream ); g_assert( !image->downstream ); g_mutex_unlock( vips__global_lock ); } typedef struct _LinkMap { gboolean upstream; int serial; VipsSListMap2Fn fn; void *a; void *b; } LinkMap; static void * vips__link_mapp( VipsImage *image, LinkMap *map, void *b ) { void *res; /* Loop? */ if( image->serial == map->serial ) return( NULL ); image->serial = map->serial; if( (res = map->fn( image, map->a, map->b )) ) return( res ); return( vips_slist_map2( map->upstream ? image->upstream : image->downstream, (VipsSListMap2Fn) vips__link_mapp, map, NULL ) ); } static void * vips__link_map_cb( VipsImage *image, GSList **images, void *b ) { *images = g_slist_prepend( *images, image ); return( NULL ); } /* Apply a function to an image and all upstream or downstream images, * direct and indirect. */ void * vips__link_map( VipsImage *image, gboolean upstream, VipsSListMap2Fn fn, void *a, void *b ) { static int serial = 0; LinkMap map; GSList *images; GSList *p; void *result; images = NULL; /* The function might do anything, including removing images * or invalidating other images, so we can't trigger them from within * the image loop. Instead we collect a list of images, ref them, * run the functions, and unref. */ map.upstream = upstream; map.fn = (VipsSListMap2Fn) vips__link_map_cb; map.a = (void *) &images; map.b = NULL; /* We will be walking the tree of images and updating the ->serial * member. There will be intense confusion if two threads try to do * this at the same time. */ g_mutex_lock( vips__global_lock ); serial += 1; map.serial = serial; vips__link_mapp( image, &map, NULL ); for( p = images; p; p = p->next ) g_object_ref( p->data ); g_mutex_unlock( vips__global_lock ); result = vips_slist_map2( images, fn, a, b ); for( p = images; p; p = p->next ) g_object_unref( p->data ); g_slist_free( images ); return( result ); } /* We have to have this as a separate entry point so we can support the old * vips7 API. */ void vips__demand_hint_array( VipsImage *image, VipsDemandStyle hint, VipsImage **in ) { int i, len, nany; VipsDemandStyle set_hint; /* How many input images are there? And how many are ANY? */ for( i = 0, len = 0, nany = 0; in[i]; i++, len++ ) if( in[i]->dhint == VIPS_DEMAND_STYLE_ANY ) nany++; /* Find the most restrictive of all the hints available to us. * * We have tried to be smarter about this in the past -- for example, * detecting all ANY inputs and ignoring the hint in this case, but * there are inevitably odd cases which cause problems. For example, * new_from_memory, resize, affine, write_to_memory would run with * FATSTRIP. */ set_hint = hint; for( i = 0; i < len; i++ ) set_hint = (VipsDemandStyle) VIPS_MIN( (int) set_hint, (int) in[i]->dhint ); image->dhint = set_hint; #ifdef DEBUG printf( "vips_image_pipeline_array: set dhint for \"%s\" to %s\n", image->filename, vips_enum_nick( VIPS_TYPE_DEMAND_STYLE, image->dhint ) ); printf( "\toperation requested %s\n", vips_enum_nick( VIPS_TYPE_DEMAND_STYLE, hint ) ); printf( "\tinputs were:\n" ); printf( "\t" ); for( i = 0; in[i]; i++ ) printf( "%s ", vips_enum_nick( VIPS_TYPE_DEMAND_STYLE, in[i]->dhint ) ); printf( "\n" ); #endif /*DEBUG*/ /* im depends on all these ims. */ g_mutex_lock( vips__global_lock ); for( i = 0; i < len; i++ ) vips__link_make( in[i], image ); g_mutex_unlock( vips__global_lock ); /* Set a flag on the image to say we remembered to call this thing. * vips_image_generate() and friends check this. */ image->hint_set = TRUE; } /** * vips_image_pipeline_array: * @image: (out): output image * @hint: demand hint for @image * @in: (array zero-terminated=1): %NULL-terminated array of input images * * Add an image to a pipeline. @image depends on all of the images in @in, * @image prefers to supply pixels according to @hint. * * Operations can set demand hints, that is, hints to the VIPS IO system about * the type of region geometry they work best with. For example, * operations which transform coordinates will usually work best with * %VIPS_DEMAND_STYLE_SMALLTILE, operations which work on local windows of * pixels will like %VIPS_DEMAND_STYLE_FATSTRIP. * * Header fields in @image are set from the fields in @in, with lower-numbered * images in @in taking priority. * For example, if @in[0] and @in[1] both have an item * called "icc-profile", it's the profile attached to @in[0] that will end up * on @image. * Image history is completely copied from all @in. @image will have the history * of all the input images. * The array of input images can be empty, meaning @image is at the start of a * pipeline. * * VIPS uses the list of input images to build the tree of operations it needs * for the cache invalidation system. * * See also: vips_image_pipelinev(), vips_image_generate(). * * Returns: 0 on success, -1 on error. */ int vips_image_pipeline_array( VipsImage *image, VipsDemandStyle hint, VipsImage **in ) { /* This function can be called more than once per output image. For * example, jpeg header load will call this once on ->out to set the * default hint, then later call it again to connect the output image * up to the real image. * * It's only ever called first time with in[0] == NULL and second time * with a real value for @in. */ vips__demand_hint_array( image, hint, in ); if( in[0] && vips__image_copy_fields_array( image, in ) ) return( -1 ); if( vips__reorder_set_input( image, in ) ) return( -1 ); return( 0 ); } /** * vips_image_pipelinev: * @image: output image of pipeline * @hint: hint for this image * @...: %NULL-terminated list of input images * * Build an array and call vips_image_pipeline_array(). * * See also: vips_image_generate(). */ int vips_image_pipelinev( VipsImage *image, VipsDemandStyle hint, ... ) { va_list ap; int i; VipsImage *ar[MAX_IMAGES]; va_start( ap, hint ); for( i = 0; i < MAX_IMAGES && (ar[i] = va_arg( ap, VipsImage * )); i++ ) ; va_end( ap ); if( i == MAX_IMAGES ) { g_warning( "%s", _( "too many images" ) ); /* Make sure we have a sentinel there. */ ar[i - 1] = NULL; } return( vips_image_pipeline_array( image, hint, ar ) ); } /** * vips_start_one: * @out: image to generate * @a: user data * @b: user data * * Start function for one image in. Input image is @a. * * See also: vips_image_generate(). */ void * vips_start_one( VipsImage *out, void *a, void *b ) { VipsImage *in = (VipsImage *) a; return( vips_region_new( in ) ); } /** * vips_stop_one: * @seq: sequence value * @a: user data * @b: user data * * Stop function for one image in. Input image is @a. * * See also: vips_image_generate(). */ int vips_stop_one( void *seq, void *a, void *b ) { VipsRegion *reg = (VipsRegion *) seq; g_object_unref( reg ); return( 0 ); } /** * vips_stop_many: * @seq: sequence value * @a: user data * @b: user data * * Stop function for many images in. @a is a pointer to * a %NULL-terminated array of input images. * * See also: vips_image_generate(). */ int vips_stop_many( void *seq, void *a, void *b ) { VipsRegion **ar = (VipsRegion **) seq; if( ar ) { int i; for( i = 0; ar[i]; i++ ) g_object_unref( ar[i] ); g_free( (char *) ar ); } return( 0 ); } /** * vips_start_many: * @out: image to generate * @a: user data * @b: user data * * Start function for many images in. @a is a pointer to * a %NULL-terminated array of input images. * * See also: vips_image_generate(), vips_allocate_input_array() */ void * vips_start_many( VipsImage *out, void *a, void *b ) { VipsImage **in = (VipsImage **) a; int i, n; VipsRegion **ar; /* How many images? */ for( n = 0; in[n]; n++ ) ; /* Alocate space for region array. */ if( !(ar = VIPS_ARRAY( NULL, n + 1, VipsRegion * )) ) return( NULL ); /* Create a set of regions. */ for( i = 0; i < n; i++ ) if( !(ar[i] = vips_region_new( in[i] )) ) { vips_stop_many( ar, NULL, NULL ); return( NULL ); } ar[n] = NULL; return( ar ); } /** * vips_allocate_input_array: * @out: free array when this image closes * @...: %NULL-terminated list of input images * * Convenience function --- make a %NULL-terminated array of input images. * Use with vips_start_many(). * * See also: vips_image_generate(), vips_start_many(). * * Returns: %NULL-terminated array of images. Do not free the result. */ VipsImage ** vips_allocate_input_array( VipsImage *out, ... ) { va_list ap; VipsImage **ar; int i, n; /* Count input images. */ va_start( ap, out ); for( n = 0; va_arg( ap, VipsImage * ); n++ ) ; va_end( ap ); /* Allocate array. */ if( !(ar = VIPS_ARRAY( out, n + 1, VipsImage * )) ) return( NULL ); /* Fill array. */ va_start( ap, out ); for( i = 0; i < n; i++ ) ar[i] = va_arg( ap, VipsImage * ); va_end( ap ); ar[n] = NULL; return( ar ); } /** * VipsStartFn: * @out: image being calculated * @a: user data * @b: user data * * Start a new processing sequence for this generate function. This allocates * per-thread state, such as an input region. * * See also: vips_start_one(), vips_start_many(). * * Returns: a new sequence value */ /** * VipsGenerateFn: * @out: #VipsRegion to fill * @seq: sequence value * @a: user data * @b: user data * @stop: set this to stop processing * * Fill @out->valid with pixels. @seq contains per-thread state, such as the * input regions. Set @stop to %TRUE to stop processing. * * See also: vips_image_generate(), vips_stop_many(). * * Returns: 0 on success, -1 on error. */ /** * VipsStopFn: * @seq: sequence value * @a: user data * @b: user data * * Stop a processing sequence. This frees * per-thread state, such as an input region. * * See also: vips_stop_one(), vips_stop_many(). * * Returns: 0 on success, -1 on error. */ /* A write function for VIPS images. Just write() the pixel data. */ static int write_vips( VipsRegion *region, VipsRect *area, void *a ) { size_t nwritten, count; void *buf; count = (size_t) region->bpl * area->height; buf = VIPS_REGION_ADDR( region, 0, area->top ); do { nwritten = write( region->im->fd, buf, count ); if( nwritten == (size_t) -1 ) return( errno ); buf = (void *) ((char *) buf + nwritten); count -= nwritten; } while( count > 0 ); return( 0 ); } /** * vips_image_generate: * @image: generate this image * @start_fn: start sequences with this function * @generate_fn: generate pixels with this function * @stop_fn: stop sequences with this function * @a: user data * @b: user data * * Generates an image. The action depends on the image type. * * For images created with vips_image_new(), vips_image_generate() just * attaches the start/generate/stop callbacks and returns. * * For images created with vips_image_new_memory(), memory is allocated for * the whole image and it is entirely generated using vips_sink_memory(). * * For images created with vips_image_new_temp_file() and friends, memory for * a few scanlines is allocated and * vips_sink_disc() used to generate the image in small chunks. As each * chunk is generated, it is written to disc. * * See also: vips_sink(), vips_image_new(), vips_region_prepare(). * * Returns: 0 on success, or -1 on error. */ int vips_image_generate( VipsImage *image, VipsStartFn start_fn, VipsGenerateFn generate_fn, VipsStopFn stop_fn, void *a, void *b ) { int res; VIPS_DEBUG_MSG( "vips_image_generate: %p\n", image ); g_assert( generate_fn ); g_assert( vips_object_sanity( VIPS_OBJECT( image ) ) ); if( !image->hint_set ) { vips_error( "vips_image_generate", "%s", _( "demand hint not set" ) ); return( -1 ); } /* We don't use this, but make sure it's set in case any old binaries * are expecting it. */ image->Bbits = vips_format_sizeof( image->BandFmt ) << 3; /* Look at output type to decide our action. */ switch( image->dtype ) { case VIPS_IMAGE_PARTIAL: /* Output to partial image. Just attach functions and return. */ if( image->generate_fn || image->start_fn || image->stop_fn ) { vips_error( "VipsImage", "%s", _( "generate() called twice" ) ); return( -1 ); } image->start_fn = start_fn; image->generate_fn = generate_fn; image->stop_fn = stop_fn; image->client1 = a; image->client2 = b; VIPS_DEBUG_MSG( "vips_image_generate: " "attaching partial callbacks\n" ); if( vips_image_written( image ) ) return( -1 ); break; case VIPS_IMAGE_SETBUF: case VIPS_IMAGE_SETBUF_FOREIGN: case VIPS_IMAGE_MMAPINRW: case VIPS_IMAGE_OPENOUT: /* Eval now .. sanity check. */ if( image->generate_fn || image->start_fn || image->stop_fn ) { vips_error( "VipsImage", "%s", _( "generate() called twice" ) ); return( -1 ); } /* Attach callbacks. */ image->start_fn = start_fn; image->generate_fn = generate_fn; image->stop_fn = stop_fn; image->client1 = a; image->client2 = b; if( vips_image_write_prepare( image ) ) return( -1 ); if( image->dtype == VIPS_IMAGE_OPENOUT ) res = vips_sink_disc( image, write_vips, NULL ); else res = vips_sink_memory( image ); /* Error? */ if( res ) return( -1 ); /* Must come before we rewind. */ if( vips_image_written( image ) ) return( -1 ); /* We've written to image ... rewind it ready for reading. */ if( vips_image_pio_input( image ) ) return( -1 ); break; default: /* Not a known output style. */ vips_error( "VipsImage", _( "unable to output to a %s image" ), vips_enum_nick( VIPS_TYPE_IMAGE_TYPE, image->dtype ) ); return( -1 ); } return( 0 ); }
lgpl-2.1
zesterer/degu-lang
degu-compiler/src/instance.cpp
1
2592
// Standard #include "stdio.h" // Local #include "instance.h" // degu-common #include "degu-common/include/config.h" #include "degu-common/include/input_file_node.h" #include "degu-common/include/file_reader.h" #include "degu-common/include/critical_error.h" // degu-parser #include "degu-parser/include/parser.h" namespace Degu { namespace Degu { Instance::Instance(int argc, char* argv[]) { for (int i = 0; i < argc; i ++) this->arguments.emplace_back(argv[i]); printf("Degu %i.%i.%i\n", DEGU_COMMON_VERSION_MAJOR, DEGU_COMMON_VERSION_MINOR, DEGU_COMMON_VERSION_PATCH); } int Instance::get_response() { std::vector<std::string> valid_tags = {"o", "asm"}; std::vector<std::string> valid_attributes = {"include", "link"}; this->argument_map = Common::Argument::generate_map(this->arguments, valid_tags, valid_attributes); for (std::string str : this->argument_map.tags) printf("Tag '%s' enabled!\n", str.c_str()); for (auto const item : this->argument_map.attributes) printf("Attribute '%s' set to '%s'!\n", item.first.c_str(), item.second.c_str()); for (std::string str : this->argument_map.arguments) printf("Argument '%s' found!\n", str.c_str()); std::vector<Common::InputFileNode> input_file_node_vector; for (std::string filename : this->argument_map.arguments) input_file_node_vector.push_back(Common::InputFileNode::construct(filename)); for (Common::InputFileNode file : input_file_node_vector) { if (file.type == Common::IN_FILE_SOURCE) printf("Input file '%s' if of type 'source'\n", file.filename.c_str()); else if (file.type == Common::IN_FILE_OBJECT) printf("Input file '%s' if of type 'object'\n", file.filename.c_str()); else printf("Input file '%s' if of type 'unknown'\n", file.filename.c_str()); } std::vector<Common::TextFile> source_files; for (Common::InputFileNode node : input_file_node_vector) { try { Common::TextFile file = Common::FileReader::read_plaintext(node.filename); source_files.push_back(file); } catch (Common::CriticalError error) { if (error.type == Common::CRIT_ERR_CANNOT_OPEN_FILE) printf("Critical error: Cannot open file '%s'\n", error.data[0].c_str()); else printf("Critical error when attempting to read file '%s'\n", node.filename.c_str()); } } for (Common::TextFile file : source_files) { printf("Source file '%s' contains:\n%s\n", file.name.c_str(), file.data.c_str()); } if (this->arguments.size() > 0) return 0; else return 1; } } }
lgpl-2.1
KDE/oxygen-gtk
src/animations/oxygensignal.cpp
1
1978
/* * this file is part of the oxygen gtk engine * SPDX-FileCopyrightText: 2010 Hugo Pereira Da Costa <hugo.pereira@free.fr> * * SPDX-License-Identifier: LGPL-2.0-or-later */ #include "oxygensignal.h" #include "../config.h" #include <iostream> namespace Oxygen { #if OXYGEN_DEBUG static int counter( 0 ); #endif //____________________________________________________________________ bool Signal::connect( GObject* object, const std::string& signal, GCallback callback, gpointer data, bool after ) { // make sure that signal is not already connected assert( _object == 0L && _id == 0 ); // check object if( !object ) return false; // first try lookup signal if( !g_signal_lookup( signal.c_str(), G_OBJECT_TYPE(object) ) ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::Signal::connect - signal " << signal << " not installed on widget " << object << std::endl; #endif return false; } // store attributes and create connection _object = object; if(after) _id = g_signal_connect_after( object, signal.c_str(), callback, data ); else _id = g_signal_connect( object, signal.c_str(), callback, data ); #if OXYGEN_DEBUG ++counter; std::cerr << "Oxygen::Signal::connect - _id: " << _id << " counter: " << counter << std::endl; #endif return true; } //____________________________________________________________________ void Signal::disconnect( void ) { // disconnect signal if( _object && _id > 0 ) { #if OXYGEN_DEBUG --counter; std::cerr << "Oxygen::Signal::disconnect - _id: " << _id << " counter: " << counter << std::endl; #endif g_signal_handler_disconnect( _object, _id ); } // reset members _object = 0L; _id = 0; } }
lgpl-2.1
prefetchnta/questlab
src/QstGraph/uMain.cpp
1
7032
//--------------------------------------------------------------------------- #include <vcl.h> #include "QstGraph.h" #pragma hdrstop #include "uMain.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TfrmMain *frmMain; //--------------------------------------------------------------------------- __fastcall TfrmMain::TfrmMain(TComponent* Owner) : TForm(Owner) { /* 使用系统字体 */ this->Font->Assign(Screen->MenuFont); frmMain->DoubleBuffered = true; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::setup(unsigned int type, const AnsiString& title, int left, int top, unsigned int width, unsigned int height) { int ww, hh; /* 设置曲线参数 */ this->setBottom(0); this->setLeft(0, 0); ww = ChartMain->BottomAxis->Maximum; hh = ChartMain->LeftAxis->Maximum - ChartMain->LeftAxis->Minimum; ChartMain->Title->Text->Text = title; m_type = type; switch (type) { default: case 1: m_line = (TChartSeries*)Series1; break; case 2: m_line = (TChartSeries*)Series2; break; case 3: m_line = (TChartSeries*)Series3; break; case 4: m_line = (TChartSeries*)Series4; break; case 5: m_line = (TChartSeries*)Series5; break; case 6: m_line = (TChartSeries*)Series6; break; case 7: m_line = (TChartSeries*)Series7; break; case 8: m_line = (TChartSeries*)Series8; break; case 9: m_line = (TChartSeries*)Series9; break; case 10: m_line = (TChartSeries*)Series10; break; case 11: m_line = (TChartSeries*)Series11; break; } m_line->Active = true; m_line->ParentChart = ChartMain; for (int xx = 0; xx <= ww; xx++) m_line->AddXY(xx, random(hh) - hh / 2, "", m_line->SeriesColor); m_xx = 0; /* 设置窗口位置 */ if (left >= 0 && top >= 0) { this->Position = poDesigned; this->Left = left; this->Top = top; if (width > 1) this->Width = width; if (height > 1) this->Height = height; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::clear() { /* 清除所有数据 */ m_line->Clear(); this->setBottom(m_ww); m_xx = 0; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::setBottom(unsigned int max) { /* 设置横坐标 */ try { if (ChartMain->BottomAxis->Maximum < 0) { if (max == 0) /* 根据窗口的宽度决定横轴长度 */ ChartMain->BottomAxis->Maximum = this->Width / 10; else ChartMain->BottomAxis->Maximum = max; ChartMain->BottomAxis->Minimum = 0; } else { ChartMain->BottomAxis->Minimum = 0; if (max == 0) /* 根据窗口的宽度决定横轴长度 */ ChartMain->BottomAxis->Maximum = this->Width / 10; else ChartMain->BottomAxis->Maximum = max; } } catch (...) { MessageBoxA(this->Handle, "Invalid Bottom Axis!", "ERROR", MB_OK | MB_ICONWARNING); return; } m_ww = ChartMain->BottomAxis->Maximum; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::setBottom(double min, double max) { /* 设置横坐标 */ if (min >= max) { this->setBottom(0); } else { try { if (max < ChartMain->BottomAxis->Minimum) { ChartMain->BottomAxis->Minimum = min; ChartMain->BottomAxis->Maximum = max; } else { ChartMain->BottomAxis->Maximum = max; ChartMain->BottomAxis->Minimum = min; } } catch (...) { MessageBoxA(this->Handle, "Invalid Bottom Axis!", "ERROR", MB_OK | MB_ICONWARNING); return; } } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::setLeft(double min, double max) { /* 设置纵坐标 */ if (min >= max) { m_auto_v = true; } else { m_auto_v = false; try { if (max < ChartMain->LeftAxis->Minimum) { ChartMain->LeftAxis->Minimum = min; ChartMain->LeftAxis->Maximum = max; } else { ChartMain->LeftAxis->Maximum = max; ChartMain->LeftAxis->Minimum = min; } } catch (...) { MessageBoxA(this->Handle, "Invalid Left Axis!", "ERROR", MB_OK | MB_ICONWARNING); return; } } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::setLineColor(int32u color) { TColor clrs; clrs = (TColor)argb32_to_gdi(&color); m_line->SeriesColor = clrs; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::setValue(double value, bool move) { int min = (int)(value - 10); int max = (int)(value + 10); /* 处理横坐标 */ if (move) { if (m_xx > m_ww) { ChartMain->BottomAxis->Maximum++; ChartMain->BottomAxis->Minimum++; } } /* 添加数据点 */ if (m_xx == 0) { m_min = value; m_max = value; if (m_auto_v) { try { if (max < ChartMain->LeftAxis->Minimum) { ChartMain->LeftAxis->Minimum = min; ChartMain->LeftAxis->Maximum = max; } else { ChartMain->LeftAxis->Maximum = max; ChartMain->LeftAxis->Minimum = min; } } catch (...) { MessageBoxA(this->Handle, "Invalid Left Axis!", "ERROR", MB_OK | MB_ICONWARNING); return; } } } else { if (m_min > value) { m_min = value; if (m_auto_v) ChartMain->LeftAxis->Minimum = min; } else if (m_max < value) { m_max = value; if (m_auto_v) ChartMain->LeftAxis->Maximum = max; } } m_line->AddXY(m_xx++, value, "", m_line->SeriesColor); /* 处理横坐标 */ if (!move) { if (m_xx > m_ww) { m_ww = m_xx; ChartMain->BottomAxis->Maximum = m_ww; } } } //---------------------------------------------------------------------------
lgpl-2.1
RLovelett/qt
examples/script/context2d/window.cpp
2
5380
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "window.h" #include "environment.h" #include "context2d.h" #include "qcontext2dcanvas.h" #include <QHBoxLayout> #include <QListWidget> #include <QDir> #include <QMessageBox> #ifndef QT_NO_SCRIPTTOOLS #include <QAction> #include <QApplication> #include <QMainWindow> #include <QPushButton> #include <QVBoxLayout> #include <QScriptEngineDebugger> #endif static QString scriptsDir() { if (QFile::exists("./scripts")) return "./scripts"; return ":/scripts"; } //! [0] Window::Window(QWidget *parent) : QWidget(parent) { m_env = new Environment(this); QObject::connect(m_env, SIGNAL(scriptError(QScriptValue)), this, SLOT(reportScriptError(QScriptValue))); Context2D *context = new Context2D(this); context->setSize(150, 150); m_canvas = new QContext2DCanvas(context, m_env, this); m_canvas->setFixedSize(context->size()); m_canvas->setObjectName("tutorial"); m_env->addCanvas(m_canvas); //! [0] #ifndef QT_NO_SCRIPTTOOLS QVBoxLayout *vbox = new QVBoxLayout(); vbox->addWidget(m_canvas); m_debugButton = new QPushButton(tr("Run in Debugger")); connect(m_debugButton, SIGNAL(clicked()), this, SLOT(runInDebugger())); vbox->addWidget(m_debugButton); #endif QHBoxLayout *hbox = new QHBoxLayout(this); m_view = new QListWidget(this); m_view->setEditTriggers(QAbstractItemView::NoEditTriggers); hbox->addWidget(m_view); #ifndef QT_NO_SCRIPTTOOLS hbox->addLayout(vbox); #else hbox->addWidget(m_canvas); #endif //! [1] QDir dir(scriptsDir()); QFileInfoList entries = dir.entryInfoList(QStringList() << "*.js"); for (int i = 0; i < entries.size(); ++i) m_view->addItem(entries.at(i).fileName()); connect(m_view, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(selectScript(QListWidgetItem*))); //! [1] #ifndef QT_NO_SCRIPTTOOLS m_debugger = new QScriptEngineDebugger(this); m_debugger->attachTo(m_env->engine()); m_debugWindow = m_debugger->standardWindow(); m_debugWindow->setWindowModality(Qt::ApplicationModal); m_debugWindow->resize(1280, 704); #endif setWindowTitle(tr("Context 2D")); } //! [2] void Window::selectScript(QListWidgetItem *item) { QString fileName = item->text(); runScript(fileName, /*debug=*/false); } //! [2] void Window::reportScriptError(const QScriptValue &error) { QMessageBox::warning(this, tr("Context 2D"), tr("Line %0: %1") .arg(error.property("lineNumber").toInt32()) .arg(error.toString())); } #ifndef QT_NO_SCRIPTTOOLS //! [3] void Window::runInDebugger() { QListWidgetItem *item = m_view->currentItem(); if (item) { QString fileName = item->text(); runScript(fileName, /*debug=*/true); } } //! [3] #endif //! [4] void Window::runScript(const QString &fileName, bool debug) { QFile file(scriptsDir() + "/" + fileName); file.open(QIODevice::ReadOnly); QString contents = file.readAll(); file.close(); m_env->reset(); #ifndef QT_NO_SCRIPTTOOLS if (debug) m_debugger->action(QScriptEngineDebugger::InterruptAction)->trigger(); #else Q_UNUSED(debug); #endif QScriptValue ret = m_env->evaluate(contents, fileName); #ifndef QT_NO_SCRIPTTOOLS m_debugWindow->hide(); #endif if (ret.isError()) reportScriptError(ret); } //! [4]
lgpl-2.1