<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: restartindexingservice.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 16:31:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

/*
    After installation of the OOo filter for the indexing service
    it is necessary to restart the indexing service in order to
    activate the filter. This is the most reliable way to get the
    indexing service working. We only restart the service if it is
    already running. If we have insufficient privileges to restart
    the service we do nothing.
*/

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>

/*
    Advapi.dll needs to be loaded dynamically because the service
    control functions are not available under Windows 9x.
*/
typedef BOOL (__stdcall * CloseServiceHandle_t)(SC_HANDLE);
typedef BOOL (__stdcall * ControlService_t)(SC_HANDLE, DWORD, LPSERVICE_STATUS);
typedef SC_HANDLE (__stdcall * OpenSCManager_t)(LPCSTR, LPCSTR, DWORD);
typedef SC_HANDLE (__stdcall * OpenService_t)(SC_HANDLE, LPCSTR, DWORD);
typedef BOOL (__stdcall * QueryServiceStatus_t)(SC_HANDLE, LPSERVICE_STATUS);
typedef BOOL (__stdcall * StartService_t)(SC_HANDLE, DWORD, LPCSTR*);

CloseServiceHandle_t CloseServiceHandle_ = NULL;
ControlService_t ControlService_ = NULL;
OpenSCManager_t OpenSCManager_ = NULL;
OpenService_t OpenService_ = NULL;
QueryServiceStatus_t QueryServiceStatus_ = NULL;
StartService_t StartService_ = NULL;

const LPTSTR INDEXING_SERVICE_NAME = TEXT("cisvc");

bool StopIndexingService(SC_HANDLE hService)
{
    SERVICE_STATUS status;

    if (ControlService_(hService, SERVICE_CONTROL_STOP, &status))
    {
        // Check the status until the service is no longer stop pending.
        if (QueryServiceStatus_(hService, &status))
        {
            DWORD startTime = GetTickCount();
            DWORD oldCheckPoint = status.dwCheckPoint;

            while (status.dwCurrentState == SERVICE_STOP_PENDING)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.
                DWORD waitTime = status.dwWaitHint / 10;

                if (waitTime < 1000)
                    waitTime = 1000;
                else if (waitTime > 10000)
                    waitTime = 10000;

                Sleep(waitTime);

                // Check the status again.
                if (!QueryServiceStatus_(hService, &status) ||
                    (status.dwCurrentState == SERVICE_STOPPED))
                    break;

                if (status.dwCheckPoint > oldCheckPoint)
                {
                    startTime = GetTickCount();
                    oldCheckPoint = status.dwCheckPoint;
                }
                else if ((GetTickCount() - startTime) > status.dwWaitHint)
                {
                    break; // service doesn't react anymore
                }
            }
        }
    }
    return (status.dwCurrentState == SERVICE_STOPPED);
}

bool StartIndexingService(SC_HANDLE hService)
{
    SERVICE_STATUS status;

    if (StartService_(hService, 0, NULL))
    {
        // Check the status until the service is no longer stop pending.
        if (QueryServiceStatus_(hService, &status))
        {
            DWORD startTime = GetTickCount();
            DWORD oldCheckPoint = status.dwCheckPoint;

            while (status.dwCurrentState == SERVICE_START_PENDING)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.
                DWORD waitTime = status.dwWaitHint / 10;

                if (waitTime < 1000)
                    waitTime = 1000;
                else if (waitTime > 10000)
                    waitTime = 10000;

                Sleep(waitTime);

                // Check the status again.
                if (!QueryServiceStatus_(hService, &status) ||
                    (status.dwCurrentState == SERVICE_STOPPED))
                    break;

                if (status.dwCheckPoint > oldCheckPoint)
                {
                    startTime = GetTickCount();
                    oldCheckPoint = status.dwCheckPoint;
                }
                else if ((GetTickCount() - startTime) > status.dwWaitHint)
                {
                    // service doesn't react anymore
                    break;
                }
            }
        }
    }
    return (status.dwCurrentState == SERVICE_RUNNING);
}

extern "C" UINT __stdcall RestartIndexingService(MSIHANDLE handle)
{
    //MessageBox(NULL, TEXT("Restarting Indexing Service"), TEXT("Message"), MB_OK | MB_ICONINFORMATION);

    HMODULE hAdvapi32 = LoadLibrary("advapi32.dll");

    if (hAdvapi32)
    {
        CloseServiceHandle_ = reinterpret_cast<CloseServiceHandle_t>(GetProcAddress(hAdvapi32, "CloseServiceHandle"));
        ControlService_ = reinterpret_cast<ControlService_t>(GetProcAddress(hAdvapi32, "ControlService"));
        OpenSCManager_ = reinterpret_cast<OpenSCManager_t>(GetProcAddress(hAdvapi32, "OpenSCManagerA"));
        OpenService_ = reinterpret_cast<OpenService_t>(GetProcAddress(hAdvapi32, "OpenServiceA"));
        QueryServiceStatus_ = reinterpret_cast<QueryServiceStatus_t>(GetProcAddress(hAdvapi32, "QueryServiceStatus"));
        StartService_ = reinterpret_cast<StartService_t>(GetProcAddress(hAdvapi32, "StartServiceA"));
    }

    /* On systems other than Windows 2000/XP the service API
       functions might not be available */
    if (!hAdvapi32 ||
        !(CloseServiceHandle_ && ControlService_ && OpenSCManager_ && OpenService_ && QueryServiceStatus_ && StartService_))
        return ERROR_SUCCESS;

    SC_HANDLE hSCManager = OpenSCManager_(
        NULL, // local machine
        NULL, // ServicesActive database
        SC_MANAGER_ALL_ACCESS);

    if (hSCManager != NULL)
    {
        SC_HANDLE hIndexingService = OpenService_(
            hSCManager, INDEXING_SERVICE_NAME, SERVICE_QUERY_STATUS | SERVICE_START | SERVICE_STOP);

        if (hIndexingService)
        {
            SERVICE_STATUS status;
            ZeroMemory(&status, sizeof(status));

            if (QueryServiceStatus_(hIndexingService, &status) &&
                (status.dwCurrentState == SERVICE_RUNNING))
            {
                if (StopIndexingService(hIndexingService))
                    StartIndexingService(hIndexingService);
            }
            CloseServiceHandle_(hIndexingService);
        }
        CloseServiceHandle_(hSCManager);
    }
    return ERROR_SUCCESS;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.3.18); FILE MERGED 2006/01/31 13:35:11 sb 1.3.18.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: restartindexingservice.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 03:35:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

/*
    After installation of the OOo filter for the indexing service
    it is necessary to restart the indexing service in order to
    activate the filter. This is the most reliable way to get the
    indexing service working. We only restart the service if it is
    already running. If we have insufficient privileges to restart
    the service we do nothing.
*/

#pragma warning(push, 1) /* disable warnings within system headers */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#pragma warning(pop)

/*
    Advapi.dll needs to be loaded dynamically because the service
    control functions are not available under Windows 9x.
*/
typedef BOOL (__stdcall * CloseServiceHandle_t)(SC_HANDLE);
typedef BOOL (__stdcall * ControlService_t)(SC_HANDLE, DWORD, LPSERVICE_STATUS);
typedef SC_HANDLE (__stdcall * OpenSCManager_t)(LPCSTR, LPCSTR, DWORD);
typedef SC_HANDLE (__stdcall * OpenService_t)(SC_HANDLE, LPCSTR, DWORD);
typedef BOOL (__stdcall * QueryServiceStatus_t)(SC_HANDLE, LPSERVICE_STATUS);
typedef BOOL (__stdcall * StartService_t)(SC_HANDLE, DWORD, LPCSTR*);

CloseServiceHandle_t CloseServiceHandle_ = NULL;
ControlService_t ControlService_ = NULL;
OpenSCManager_t OpenSCManager_ = NULL;
OpenService_t OpenService_ = NULL;
QueryServiceStatus_t QueryServiceStatus_ = NULL;
StartService_t StartService_ = NULL;

const LPTSTR INDEXING_SERVICE_NAME = TEXT("cisvc");

bool StopIndexingService(SC_HANDLE hService)
{
    SERVICE_STATUS status;

    if (ControlService_(hService, SERVICE_CONTROL_STOP, &status))
    {
        // Check the status until the service is no longer stop pending.
        if (QueryServiceStatus_(hService, &status))
        {
            DWORD startTime = GetTickCount();
            DWORD oldCheckPoint = status.dwCheckPoint;

            while (status.dwCurrentState == SERVICE_STOP_PENDING)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.
                DWORD waitTime = status.dwWaitHint / 10;

                if (waitTime < 1000)
                    waitTime = 1000;
                else if (waitTime > 10000)
                    waitTime = 10000;

                Sleep(waitTime);

                // Check the status again.
                if (!QueryServiceStatus_(hService, &status) ||
                    (status.dwCurrentState == SERVICE_STOPPED))
                    break;

                if (status.dwCheckPoint > oldCheckPoint)
                {
                    startTime = GetTickCount();
                    oldCheckPoint = status.dwCheckPoint;
                }
                else if ((GetTickCount() - startTime) > status.dwWaitHint)
                {
                    break; // service doesn't react anymore
                }
            }
        }
    }
    return (status.dwCurrentState == SERVICE_STOPPED);
}

void StartIndexingService(SC_HANDLE hService)
{
    if (StartService_(hService, 0, NULL))
    {
        SERVICE_STATUS status;

        // Check the status until the service is no longer stop pending.
        if (QueryServiceStatus_(hService, &status))
        {
            DWORD startTime = GetTickCount();
            DWORD oldCheckPoint = status.dwCheckPoint;

            while (status.dwCurrentState == SERVICE_START_PENDING)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.
                DWORD waitTime = status.dwWaitHint / 10;

                if (waitTime < 1000)
                    waitTime = 1000;
                else if (waitTime > 10000)
                    waitTime = 10000;

                Sleep(waitTime);

                // Check the status again.
                if (!QueryServiceStatus_(hService, &status) ||
                    (status.dwCurrentState == SERVICE_STOPPED))
                    break;

                if (status.dwCheckPoint > oldCheckPoint)
                {
                    startTime = GetTickCount();
                    oldCheckPoint = status.dwCheckPoint;
                }
                else if ((GetTickCount() - startTime) > status.dwWaitHint)
                {
                    // service doesn't react anymore
                    break;
                }
            }
        }
    }
}

extern "C" UINT __stdcall RestartIndexingService(MSIHANDLE)
{
    //MessageBox(NULL, TEXT("Restarting Indexing Service"), TEXT("Message"), MB_OK | MB_ICONINFORMATION);

    HMODULE hAdvapi32 = LoadLibrary("advapi32.dll");

    if (hAdvapi32)
    {
        CloseServiceHandle_ = reinterpret_cast<CloseServiceHandle_t>(GetProcAddress(hAdvapi32, "CloseServiceHandle"));
        ControlService_ = reinterpret_cast<ControlService_t>(GetProcAddress(hAdvapi32, "ControlService"));
        OpenSCManager_ = reinterpret_cast<OpenSCManager_t>(GetProcAddress(hAdvapi32, "OpenSCManagerA"));
        OpenService_ = reinterpret_cast<OpenService_t>(GetProcAddress(hAdvapi32, "OpenServiceA"));
        QueryServiceStatus_ = reinterpret_cast<QueryServiceStatus_t>(GetProcAddress(hAdvapi32, "QueryServiceStatus"));
        StartService_ = reinterpret_cast<StartService_t>(GetProcAddress(hAdvapi32, "StartServiceA"));
    }

    /* On systems other than Windows 2000/XP the service API
       functions might not be available */
    if (!hAdvapi32 ||
        !(CloseServiceHandle_ && ControlService_ && OpenSCManager_ && OpenService_ && QueryServiceStatus_ && StartService_))
        return ERROR_SUCCESS;

    SC_HANDLE hSCManager = OpenSCManager_(
        NULL, // local machine
        NULL, // ServicesActive database
        SC_MANAGER_ALL_ACCESS);

    if (hSCManager != NULL)
    {
        SC_HANDLE hIndexingService = OpenService_(
            hSCManager, INDEXING_SERVICE_NAME, SERVICE_QUERY_STATUS | SERVICE_START | SERVICE_STOP);

        if (hIndexingService)
        {
            SERVICE_STATUS status;
            ZeroMemory(&status, sizeof(status));

            if (QueryServiceStatus_(hIndexingService, &status) &&
                (status.dwCurrentState == SERVICE_RUNNING))
            {
                if (StopIndexingService(hIndexingService))
                    StartIndexingService(hIndexingService);
            }
            CloseServiceHandle_(hIndexingService);
        }
        CloseServiceHandle_(hSCManager);
    }
    return ERROR_SUCCESS;
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mc/xlate.C $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file xlate.C
/// @brief Subroutines to manipulate the memory controller translation registers
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>

#include "p9_mc_scom_addresses.H"
#include "p9_mc_scom_addresses_fld.H"

#include "mss_attribute_accessors.H"

#include "mc.H"
#include "../utils/scom.H"
#include "../dimm/kind.H"

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_PROC_CHIP;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;

using fapi2::FAPI2_RC_SUCCESS;

namespace mss
{

///
/// @brief Perform initializations of the MC translation
/// @tparm P, the fapi2::TargetType of the port
/// @tparm TT, the typename of the traits
/// @param[in] i_target, the target which has the MCA to map
/// @return FAPI2_RC_SUCCESS iff ok
///
template<>
template<>
fapi2::ReturnCode mc<TARGET_TYPE_MCS>::setup_xlate_map(const fapi2::Target<TARGET_TYPE_MCA>& i_target)
{
    fapi2::buffer<uint64_t> l_xlate;
    fapi2::buffer<uint64_t> l_xlate1;
    fapi2::buffer<uint64_t> l_xlate2;

    const auto l_dimms = i_target.getChildren<TARGET_TYPE_DIMM>();

    FAPI_INF("Setting up xlate registers for MCA%d (%d)", mss::pos(i_target), mss::index(i_target));

    // The addressing for the xlt registers is funky. We have a different unit0 address for units 0/2
    // than we do for 1/3.
    const uint64_t& l_t0_address = mss::pos(i_target) % 2 ? MCS_0_PORT13_MCP0XLT0 : MCS_0_PORT02_MCP0XLT0;
    const uint64_t& l_t1_address = mss::pos(i_target) % 2 ? MCS_0_PORT13_MCP0XLT1 : MCS_0_PORT02_MCP0XLT1;
    const uint64_t& l_t2_address = mss::pos(i_target) % 2 ? MCS_0_PORT13_MCP0XLT2 : MCS_0_PORT02_MCP0XLT2;

    FAPI_DBG("xlate scoms registers 0x%016lx, 0x%016lx, 0x%016lx", l_t0_address, l_t1_address, l_t2_address);

    // We enable the DIMM select bit for slot1 if we have two DIMM installed
    l_xlate.writeBit<MCS_PORT13_MCP0XLT0_SLOT1_D_VALUE>(l_dimms.size() == 2);

    // Get the functional DIMM on this port.
    for (auto d : l_dimms)
    {
        // Our slot (0, 1) is the same as our general index.
        const uint64_t l_slot = mss::index(d);

        // Our slot offset tells us which 16 bit section in the xlt register to use for this DIMM
        // We'll either use the left most bits (slot 0) or move 16 bits to the right for slot 1.
        const uint64_t l_slot_offset = l_slot * 16;

        // Get the translation array, based on this specific DIMM's config
        dimm::kind l_dimm(d);

        // TK: Get the information from the translation table for this DIMM.

        FAPI_DBG("address translation for DIMM %s %dR %dgbx%d in slot %d",
                 mss::c_str(d), l_dimm.iv_master_ranks, l_dimm.iv_dram_density, l_dimm.iv_dram_width, l_slot);

        // Set the proper bit if there is a DIMM in this slot. If there wasn't, we wouldn't see
        // this DIMM in the vector, so this is always safe.
        l_xlate.setBit(MCS_PORT02_MCP0XLT0_SLOT0_VALID + l_slot_offset);

        // Set the 12G DIMM bit if either DIMM is 12G
        // Is this correct? BRS
        l_xlate.writeBit<MCS_PORT13_MCP0XLT0_12GB_ENABLE>(l_dimm.iv_size == 12);

        // Check our master ranks, and enable the proper bits.
        // Note this seems a little backward. M0 is the left most bit, M1 the right most.
        // So, M1 changes for ranks 0,1 and M0 changes for ranks 3,4
        if (l_dimm.iv_master_ranks > 0)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_M1_VALID + l_slot_offset);
        }

        if (l_dimm.iv_master_ranks > 2)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_M0_VALID + l_slot_offset);
        }

        // Check slave ranks
        // Note this sems a little backward. S0 is the left-most slave bit. So,
        // if there are more than 0 slave ranks, S2 will increment first.
        if (l_dimm.iv_slave_ranks > 0)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_S2_VALID + l_slot_offset);
        }

        if (l_dimm.iv_slave_ranks > 2)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_S1_VALID + l_slot_offset);
        }

        if (l_dimm.iv_slave_ranks > 4)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_S0_VALID + l_slot_offset);
        }

        // Tell the MC which of the row bits are valid.
        if (l_dimm.iv_rows >= 16)
        {
            l_xlate.setBit(MCS_PORT02_MCP0XLT0_SLOT0_ROW15_VALID + l_slot_offset);
        }

        if (l_dimm.iv_rows >= 17)
        {
            l_xlate.setBit(MCS_PORT02_MCP0XLT0_SLOT0_ROW16_VALID + l_slot_offset);
        }

        if (l_dimm.iv_rows >= 18)
        {
            l_xlate.setBit(MCS_PORT02_MCP0XLT0_SLOT0_ROW17_VALID + l_slot_offset);
        }

    }

    // TK: remove and make general in the loop above BRS

    // Two rank DIMM, so master bit 1 (least significant) bit needs to be mapped.
    l_xlate.insertFromRight<MCS_PORT02_MCP0XLT0_M1_BIT_MAP, MCS_PORT02_MCP0XLT0_M1_BIT_MAP_LEN>(0b01111);

    // Slot 1 isn't populated, so forget those bits for now.

    // DIMM bit map isn't exactly ignored for only one populated slot. It still needs to be
    // set in the map. Per S. Powell.
    // Master rank 0, 1 bit maps are ignored.
    // Row 16,17 bit maps are ignored.
    // Row 15 maps to Port Address bit 6
    l_xlate.insertFromRight<MCS_PORT02_MCP0XLT0_D_BIT_MAP, MCS_PORT02_MCP0XLT0_D_BIT_MAP_LEN>(0b00101);
    l_xlate.insertFromRight<MCS_PORT02_MCP0XLT0_R15_BIT_MAP, MCS_PORT02_MCP0XLT0_R15_BIT_MAP_LEN>(0b00110);

    // Drop down the column assignments
    l_xlate1.insertFromRight<MCS_PORT02_MCP0XLT1_COL4_BIT_MAP,
                             MCS_PORT02_MCP0XLT1_COL4_BIT_MAP_LEN>(0b01101);

    l_xlate1.insertFromRight<MCS_PORT02_MCP0XLT1_COL5_BIT_MAP,
                             MCS_PORT02_MCP0XLT1_COL5_BIT_MAP_LEN>(0b01100);

    l_xlate1.insertFromRight<MCS_PORT02_MCP0XLT1_COL6_BIT_MAP,
                             MCS_PORT02_MCP0XLT1_COL6_BIT_MAP_LEN>(0b01011);

    l_xlate1.insertFromRight<MCS_PORT02_MCP0XLT1_COL7_BIT_MAP,
                             MCS_PORT02_MCP0XLT1_COL7_BIT_MAP_LEN>(0b01010);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_COL8_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_COL8_BIT_MAP_LEN>(0b01001);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_COL9_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_COL9_BIT_MAP_LEN>(0b00111);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP_LEN>(0b01110);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP_LEN>(0b10000);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP_LEN>(0b10001);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP_LEN>(0b10010);

    FAPI_DBG("HACK: Cramming 0x%016lx in for MCP0XLT0", l_xlate);
    FAPI_DBG("HACK: Cramming 0x%016lx in for MCP0XLT1", l_xlate1);
    FAPI_DBG("HACK: Cramming 0x%016lx in for MCP0XLT2", l_xlate2);

    FAPI_TRY( mss::putScom(i_target.getParent<TARGET_TYPE_MCS>(), l_t0_address, l_xlate)  );
    FAPI_TRY( mss::putScom(i_target.getParent<TARGET_TYPE_MCS>(), l_t1_address, l_xlate1) );
    FAPI_TRY( mss::putScom(i_target.getParent<TARGET_TYPE_MCS>(), l_t2_address, l_xlate2) );

fapi_try_exit:
    return fapi2::current_err;
}

} // namespace
<commit_msg>Change include paths in memory/lib, tests<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mc/xlate.C $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file xlate.C
/// @brief Subroutines to manipulate the memory controller translation registers
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>

#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>

#include <mss_attribute_accessors.H>

#include <lib/mc/mc.H>
#include <lib/utils/scom.H>
#include <lib/dimm/kind.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_PROC_CHIP;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;

using fapi2::FAPI2_RC_SUCCESS;

namespace mss
{

///
/// @brief Perform initializations of the MC translation
/// @tparm P, the fapi2::TargetType of the port
/// @tparm TT, the typename of the traits
/// @param[in] i_target, the target which has the MCA to map
/// @return FAPI2_RC_SUCCESS iff ok
///
template<>
template<>
fapi2::ReturnCode mc<TARGET_TYPE_MCS>::setup_xlate_map(const fapi2::Target<TARGET_TYPE_MCA>& i_target)
{
    fapi2::buffer<uint64_t> l_xlate;
    fapi2::buffer<uint64_t> l_xlate1;
    fapi2::buffer<uint64_t> l_xlate2;

    const auto l_dimms = i_target.getChildren<TARGET_TYPE_DIMM>();

    FAPI_INF("Setting up xlate registers for MCA%d (%d)", mss::pos(i_target), mss::index(i_target));

    // The addressing for the xlt registers is funky. We have a different unit0 address for units 0/2
    // than we do for 1/3.
    const uint64_t& l_t0_address = mss::pos(i_target) % 2 ? MCS_0_PORT13_MCP0XLT0 : MCS_0_PORT02_MCP0XLT0;
    const uint64_t& l_t1_address = mss::pos(i_target) % 2 ? MCS_0_PORT13_MCP0XLT1 : MCS_0_PORT02_MCP0XLT1;
    const uint64_t& l_t2_address = mss::pos(i_target) % 2 ? MCS_0_PORT13_MCP0XLT2 : MCS_0_PORT02_MCP0XLT2;

    FAPI_DBG("xlate scoms registers 0x%016lx, 0x%016lx, 0x%016lx", l_t0_address, l_t1_address, l_t2_address);

    // We enable the DIMM select bit for slot1 if we have two DIMM installed
    l_xlate.writeBit<MCS_PORT13_MCP0XLT0_SLOT1_D_VALUE>(l_dimms.size() == 2);

    // Get the functional DIMM on this port.
    for (auto d : l_dimms)
    {
        // Our slot (0, 1) is the same as our general index.
        const uint64_t l_slot = mss::index(d);

        // Our slot offset tells us which 16 bit section in the xlt register to use for this DIMM
        // We'll either use the left most bits (slot 0) or move 16 bits to the right for slot 1.
        const uint64_t l_slot_offset = l_slot * 16;

        // Get the translation array, based on this specific DIMM's config
        dimm::kind l_dimm(d);

        // TK: Get the information from the translation table for this DIMM.

        FAPI_DBG("address translation for DIMM %s %dR %dgbx%d in slot %d",
                 mss::c_str(d), l_dimm.iv_master_ranks, l_dimm.iv_dram_density, l_dimm.iv_dram_width, l_slot);

        // Set the proper bit if there is a DIMM in this slot. If there wasn't, we wouldn't see
        // this DIMM in the vector, so this is always safe.
        l_xlate.setBit(MCS_PORT02_MCP0XLT0_SLOT0_VALID + l_slot_offset);

        // Set the 12G DIMM bit if either DIMM is 12G
        // Is this correct? BRS
        l_xlate.writeBit<MCS_PORT13_MCP0XLT0_12GB_ENABLE>(l_dimm.iv_size == 12);

        // Check our master ranks, and enable the proper bits.
        // Note this seems a little backward. M0 is the left most bit, M1 the right most.
        // So, M1 changes for ranks 0,1 and M0 changes for ranks 3,4
        if (l_dimm.iv_master_ranks > 0)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_M1_VALID + l_slot_offset);
        }

        if (l_dimm.iv_master_ranks > 2)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_M0_VALID + l_slot_offset);
        }

        // Check slave ranks
        // Note this sems a little backward. S0 is the left-most slave bit. So,
        // if there are more than 0 slave ranks, S2 will increment first.
        if (l_dimm.iv_slave_ranks > 0)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_S2_VALID + l_slot_offset);
        }

        if (l_dimm.iv_slave_ranks > 2)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_S1_VALID + l_slot_offset);
        }

        if (l_dimm.iv_slave_ranks > 4)
        {
            l_xlate.setBit(MCS_PORT13_MCP0XLT0_SLOT0_S0_VALID + l_slot_offset);
        }

        // Tell the MC which of the row bits are valid.
        if (l_dimm.iv_rows >= 16)
        {
            l_xlate.setBit(MCS_PORT02_MCP0XLT0_SLOT0_ROW15_VALID + l_slot_offset);
        }

        if (l_dimm.iv_rows >= 17)
        {
            l_xlate.setBit(MCS_PORT02_MCP0XLT0_SLOT0_ROW16_VALID + l_slot_offset);
        }

        if (l_dimm.iv_rows >= 18)
        {
            l_xlate.setBit(MCS_PORT02_MCP0XLT0_SLOT0_ROW17_VALID + l_slot_offset);
        }

    }

    // TK: remove and make general in the loop above BRS

    // Two rank DIMM, so master bit 1 (least significant) bit needs to be mapped.
    l_xlate.insertFromRight<MCS_PORT02_MCP0XLT0_M1_BIT_MAP, MCS_PORT02_MCP0XLT0_M1_BIT_MAP_LEN>(0b01111);

    // Slot 1 isn't populated, so forget those bits for now.

    // DIMM bit map isn't exactly ignored for only one populated slot. It still needs to be
    // set in the map. Per S. Powell.
    // Master rank 0, 1 bit maps are ignored.
    // Row 16,17 bit maps are ignored.
    // Row 15 maps to Port Address bit 6
    l_xlate.insertFromRight<MCS_PORT02_MCP0XLT0_D_BIT_MAP, MCS_PORT02_MCP0XLT0_D_BIT_MAP_LEN>(0b00101);
    l_xlate.insertFromRight<MCS_PORT02_MCP0XLT0_R15_BIT_MAP, MCS_PORT02_MCP0XLT0_R15_BIT_MAP_LEN>(0b00110);

    // Drop down the column assignments
    l_xlate1.insertFromRight<MCS_PORT02_MCP0XLT1_COL4_BIT_MAP,
                             MCS_PORT02_MCP0XLT1_COL4_BIT_MAP_LEN>(0b01101);

    l_xlate1.insertFromRight<MCS_PORT02_MCP0XLT1_COL5_BIT_MAP,
                             MCS_PORT02_MCP0XLT1_COL5_BIT_MAP_LEN>(0b01100);

    l_xlate1.insertFromRight<MCS_PORT02_MCP0XLT1_COL6_BIT_MAP,
                             MCS_PORT02_MCP0XLT1_COL6_BIT_MAP_LEN>(0b01011);

    l_xlate1.insertFromRight<MCS_PORT02_MCP0XLT1_COL7_BIT_MAP,
                             MCS_PORT02_MCP0XLT1_COL7_BIT_MAP_LEN>(0b01010);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_COL8_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_COL8_BIT_MAP_LEN>(0b01001);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_COL9_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_COL9_BIT_MAP_LEN>(0b00111);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP_LEN>(0b01110);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP_LEN>(0b10000);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP_LEN>(0b10001);

    l_xlate2.insertFromRight<MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP,
                             MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP_LEN>(0b10010);

    FAPI_DBG("HACK: Cramming 0x%016lx in for MCP0XLT0", l_xlate);
    FAPI_DBG("HACK: Cramming 0x%016lx in for MCP0XLT1", l_xlate1);
    FAPI_DBG("HACK: Cramming 0x%016lx in for MCP0XLT2", l_xlate2);

    FAPI_TRY( mss::putScom(i_target.getParent<TARGET_TYPE_MCS>(), l_t0_address, l_xlate)  );
    FAPI_TRY( mss::putScom(i_target.getParent<TARGET_TYPE_MCS>(), l_t1_address, l_xlate1) );
    FAPI_TRY( mss::putScom(i_target.getParent<TARGET_TYPE_MCS>(), l_t2_address, l_xlate2) );

fapi_try_exit:
    return fapi2::current_err;
}

} // namespace
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum 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.

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Full-stack compiler that converts a source code string to bytecode.
 */

#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>

#include <jsonrpc/json/json.h>

using namespace std;

namespace dev
{
namespace solidity
{

void CompilerStack::setSource(string const& _sourceCode)
{
	reset();
	m_scanner = make_shared<Scanner>(CharStream(_sourceCode));
}

void CompilerStack::parse()
{
	if (!m_scanner)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source not available."));
	m_contractASTNode = Parser().parse(m_scanner);
	m_globalContext = make_shared<GlobalContext>();
	m_globalContext->setCurrentContract(*m_contractASTNode);
	NameAndTypeResolver(m_globalContext->getDeclarations()).resolveNamesAndTypes(*m_contractASTNode);
	m_parseSuccessful = true;
}

void CompilerStack::parse(string const& _sourceCode)
{
	setSource(_sourceCode);
	parse();
}

bytes const& CompilerStack::compile(bool _optimize)
{
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
	m_bytecode.clear();
	m_compiler = make_shared<Compiler>();
	m_compiler->compileContract(*m_contractASTNode, m_globalContext->getMagicVariables());
	return m_bytecode = m_compiler->getAssembledBytecode(_optimize);
}

bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
	parse(_sourceCode);
	return compile(_optimize);
}

void CompilerStack::streamAssembly(ostream& _outStream)
{
	if (!m_compiler || m_bytecode.empty())
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful."));
	m_compiler->streamAssembly(_outStream);
}

string const& CompilerStack::getInterface()
{
	Json::StyledWriter writer;
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));

	if (m_interface.empty())
	{
		Json::Value methods(Json::arrayValue);

		vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
		for (FunctionDefinition const* f: exportedFunctions)
		{
			Json::Value method;
			Json::Value inputs(Json::arrayValue);
			Json::Value outputs(Json::arrayValue);

			auto streamVariables = [&](vector<ASTPointer<VariableDeclaration>> const& _vars,
									   Json::Value &json)
			{
				for (ASTPointer<VariableDeclaration> const& var: _vars)
				{
					Json::Value input;
					input["name"] = var->getName();
					input["type"] = var->getType()->toString();
					json.append(input);
				}
			};

			method["name"] = f->getName();
			streamVariables(f->getParameters(), inputs);
			method["inputs"] = inputs;
			streamVariables(f->getReturnParameters(), outputs);
			method["outputs"] = outputs;

			methods.append(method);
		}
		m_interface = writer.write(methods);
	}
	return m_interface;
}

string const& CompilerStack::getDocumentation()
{
	Json::StyledWriter writer;
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));

	if (m_documentation.empty())
	{
		Json::Value doc;
		Json::Value methods(Json::objectValue);

		vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
		for (FunctionDefinition const* f: exportedFunctions)
		{
			Json::Value user;
			auto strPtr = f->getDocumentation();
			if (strPtr)
			{
				user["user"] = Json::Value(*strPtr);
				methods[f->getName()] = user;
			}
		}
		doc["methods"] = methods;
		m_documentation = writer.write(doc);
	}
	return m_documentation;
}

bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
	CompilerStack stack;
	return stack.compile(_sourceCode, _optimize);
}

}
}
<commit_msg>Removing unneeded local variable in CompilerStack::getDocumentation()<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum 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.

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Full-stack compiler that converts a source code string to bytecode.
 */

#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>

#include <jsonrpc/json/json.h>

using namespace std;

namespace dev
{
namespace solidity
{

void CompilerStack::setSource(string const& _sourceCode)
{
	reset();
	m_scanner = make_shared<Scanner>(CharStream(_sourceCode));
}

void CompilerStack::parse()
{
	if (!m_scanner)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source not available."));
	m_contractASTNode = Parser().parse(m_scanner);
	m_globalContext = make_shared<GlobalContext>();
	m_globalContext->setCurrentContract(*m_contractASTNode);
	NameAndTypeResolver(m_globalContext->getDeclarations()).resolveNamesAndTypes(*m_contractASTNode);
	m_parseSuccessful = true;
}

void CompilerStack::parse(string const& _sourceCode)
{
	setSource(_sourceCode);
	parse();
}

bytes const& CompilerStack::compile(bool _optimize)
{
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
	m_bytecode.clear();
	m_compiler = make_shared<Compiler>();
	m_compiler->compileContract(*m_contractASTNode, m_globalContext->getMagicVariables());
	return m_bytecode = m_compiler->getAssembledBytecode(_optimize);
}

bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
	parse(_sourceCode);
	return compile(_optimize);
}

void CompilerStack::streamAssembly(ostream& _outStream)
{
	if (!m_compiler || m_bytecode.empty())
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful."));
	m_compiler->streamAssembly(_outStream);
}

string const& CompilerStack::getInterface()
{
	Json::StyledWriter writer;
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));

	if (m_interface.empty())
	{
		Json::Value methods(Json::arrayValue);

		vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
		for (FunctionDefinition const* f: exportedFunctions)
		{
			Json::Value method;
			Json::Value inputs(Json::arrayValue);
			Json::Value outputs(Json::arrayValue);

			auto streamVariables = [&](vector<ASTPointer<VariableDeclaration>> const& _vars,
									   Json::Value &json)
			{
				for (ASTPointer<VariableDeclaration> const& var: _vars)
				{
					Json::Value input;
					input["name"] = var->getName();
					input["type"] = var->getType()->toString();
					json.append(input);
				}
			};

			method["name"] = f->getName();
			streamVariables(f->getParameters(), inputs);
			method["inputs"] = inputs;
			streamVariables(f->getReturnParameters(), outputs);
			method["outputs"] = outputs;

			methods.append(method);
		}
		m_interface = writer.write(methods);
	}
	return m_interface;
}

string const& CompilerStack::getDocumentation()
{
	Json::StyledWriter writer;
	if (!m_parseSuccessful)
		BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));

	if (m_documentation.empty())
	{
		Json::Value doc;
		Json::Value methods(Json::objectValue);

		for (FunctionDefinition const* f: m_contractASTNode->getInterfaceFunctions())
		{
			Json::Value user;
			auto strPtr = f->getDocumentation();
			if (strPtr)
			{
				user["user"] = Json::Value(*strPtr);
				methods[f->getName()] = user;
			}
		}
		doc["methods"] = methods;
		m_documentation = writer.write(doc);
	}
	return m_documentation;
}

bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
	CompilerStack stack;
	return stack.compile(_sourceCode, _optimize);
}

}
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/fir/gen_mss_unmask.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
<commit_msg>Add snapshot of generic/memory for master-p10<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/fir/gen_mss_unmask.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file gen_mss_unmask.H
/// @brief Subroutines for unmasking and setting up MSS FIR
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#ifndef _GEN_MSS_UNMASK_FIR_H_
#define _GEN_MSS_UNMASK_FIR_H_

#include <fapi2.H>

#include <generic/memory/lib/utils/shared/mss_generic_consts.H>

namespace mss
{

namespace unmask
{

///
/// @brief Unmask and setup actions performed after draminit_mc
/// @tparam MC the memory controller type
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target the fapi2::Target
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T >
fapi2::ReturnCode after_draminit_mc( const fapi2::Target<T>& i_target );

///
/// @brief Unmask and setup actions performed after draminit_training
/// @tparam MC the memory controller type
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target the fapi2::Target
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T >
fapi2::ReturnCode after_draminit_training( const fapi2::Target<T>& i_target );

///
/// @brief Unmask and setup actions performed after mss_scominit
/// @tparam MC the memory controller type
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target the fapi2::Target
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T >
fapi2::ReturnCode after_scominit( const fapi2::Target<T>& i_target );

///
/// @brief Unmask and setup actions performed after mss_ddr_phy_reset
/// @tparam MC the memory controller type
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target the fapi2::Target
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T >
fapi2::ReturnCode after_phy_reset( const fapi2::Target<T>& i_target );

///
/// @brief Unmask and setup actions for memdiags related FIR
/// @tparam MC the memory controller type
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target the fapi2::Target
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T >
fapi2::ReturnCode after_memdiags( const fapi2::Target<T>& i_target );

///
/// @brief Unmask and setup actions for scrub related FIR
/// @tparam MC the memory controller type
/// @tparam T the fapi2::TargetType which hold the FIR bits
/// @param[in] i_target the fapi2::Target
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T >
fapi2::ReturnCode after_background_scrub( const fapi2::Target<T>& i_target );

}
}
#endif
<|endoftext|>


<commit_before>#include <mysql_priv.h>
#include <mysql/plugin.h>
#include <groonga.h>
#include "ha_groonga.h"
#include <pthread.h>

grn_ctx *mrn_ctx_sys;
grn_hash *mrn_hash_sys;
pthread_mutex_t *mrn_mutex_sys;
const char *mrn_log_name="groonga.log";
static FILE *mrn_log_file = NULL;

void mrn_logger_func(int level, const char *time, const char *title,
		     const char *msg, const char *location, void *func_arg)
{
  const char slev[] = " EACewnid-";
  if (mrn_log_file) {
    fprintf(mrn_log_file, "%s|%c|%u|%s %s\n", time,
	    *(slev + level), (uint)pthread_self(), location, msg);
    fflush(mrn_log_file);
  }
}

grn_logger_info mrn_logger_info = {
  GRN_LOG_DUMP,
  GRN_LOG_TIME|GRN_LOG_MESSAGE|GRN_LOG_LOCATION,
  mrn_logger_func,
  NULL
};

#ifdef __cplusplus
extern "C" {
#endif

static int mrn_init(void *p);
static int mrn_fin(void *p);
static handler *mrn_handler_create(handlerton *hton,
				   TABLE_SHARE *share,
				   MEM_ROOT *root);

struct st_mysql_storage_engine storage_engine_structure =
{ MYSQL_HANDLERTON_INTERFACE_VERSION };

mysql_declare_plugin(groonga)
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
  &storage_engine_structure,
  "Groonga",
  "Tetsuro IKEDA",
  "An Embeddable Fulltext Search Engine",
  PLUGIN_LICENSE_GPL,
  mrn_init,
  mrn_fin,
  0x0001,
  NULL,
  NULL,
  NULL
}
mysql_declare_plugin_end;

ha_groonga::ha_groonga(handlerton *hton, TABLE_SHARE *share)
  :handler(hton, share)
{
  MRN_ENTER;
  MRN_RETURN_VOID;
}

ha_groonga::~ha_groonga()
{
  MRN_ENTER;
  MRN_RETURN_VOID;
}

const char *ha_groonga::table_type() const
{
  MRN_ENTER;
  MRN_RETURN_S("Groonga");
}

static const char*ha_groonga_exts[] = {
  NullS
};
const char **ha_groonga::bas_ext() const
{
  MRN_ENTER;
  MRN_RETURN_P(ha_groonga_exts);
}

ulonglong ha_groonga::table_flags() const
{
  MRN_ENTER;
  MRN_RETURN(0);
}

ulong ha_groonga::index_flags(uint idx, uint part, bool all_parts) const
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::create(const char *name, TABLE *form, HA_CREATE_INFO *info)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::open(const char *name, int mode, uint test_if_locked)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::close()
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::info(uint flag)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

THR_LOCK_DATA **ha_groonga::store_lock(THD *thd,
				    THR_LOCK_DATA **to,
				    enum thr_lock_type lock_type)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::rnd_init(bool scan)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::rnd_next(uchar *buf)
{
  MRN_ENTER;
  MRN_RETURN(HA_ERR_END_OF_FILE);
}

int ha_groonga::rnd_pos(uchar *buf, uchar *pos)
{
  MRN_ENTER;
  MRN_RETURN(HA_ERR_WRONG_COMMAND);
}

void ha_groonga::position(const uchar *record)
{
  MRN_ENTER;
  MRN_RETURN_VOID;
}

bool mrn_flush_logs(handlerton *hton)
{
  MRN_ENTER;
  pthread_mutex_lock(mrn_mutex_sys);
  MRN_LOG(GRN_LOG_NOTICE, "logfile closed by FLUSH LOGS");
  fflush(mrn_log_file);
  fclose(mrn_log_file);
  mrn_log_file = fopen(mrn_log_name, "a");
  MRN_LOG(GRN_LOG_NOTICE, "logfile re-opened by FLUSH LOGS");
  pthread_mutex_unlock(mrn_mutex_sys);
  MRN_RETURN(true);
}

static int mrn_init(void *p)
{
  MRN_ENTER;
  handlerton *hton;
  hton = (handlerton *)p;
  hton->state = SHOW_OPTION_YES;
  hton->create = mrn_handler_create;
  hton->flush_logs = mrn_flush_logs;
  hton->flags = 0;

  /* libgroonga init */
  grn_init();

  /* ctx init */
  mrn_ctx_sys = (grn_ctx*) malloc(sizeof(grn_ctx));
  grn_ctx_init(mrn_ctx_sys, GRN_CTX_USE_DB, GRN_ENC_UTF8);

  /* hash init */
  mrn_hash_sys = grn_hash_create(mrn_ctx_sys,NULL,MRN_MAX_IDENTIFIER_LEN,sizeof(size_t),
				 GRN_OBJ_KEY_VAR_SIZE, GRN_ENC_UTF8);

  /* log init */
  if (!(mrn_log_file = fopen(mrn_log_name, "a"))) {
    MRN_RETURN(-1);
  }
  grn_logger_info_set(mrn_ctx_sys, &mrn_logger_info);
  MRN_LOG(GRN_LOG_NOTICE, "gronnga engine started");

  /* mutex init */
  mrn_mutex_sys = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
  pthread_mutex_init(mrn_mutex_sys, MY_MUTEX_INIT_FAST);

  MRN_RETURN(0);
}

static int mrn_fin(void *p)
{
  MRN_ENTER;

  /* mutex deinit*/
  pthread_mutex_destroy(mrn_mutex_sys);
  free(mrn_mutex_sys);

  /* log deinit */
  MRN_LOG(GRN_LOG_NOTICE, "stopping groonga engine");
  fflush(mrn_log_file);
  fclose(mrn_log_file);

  /* hash deinit */

  /* ctx deinit */
  grn_ctx_fin(mrn_ctx_sys);
  free(mrn_ctx_sys);

  /* libgroonga deinit */
  grn_fin();

  MRN_RETURN(0);
}

static handler *mrn_handler_create(handlerton *hton,
				    TABLE_SHARE *share,
				    MEM_ROOT *root)
{
  MRN_ENTER;
  MRN_RETURN_P(new (root) ha_groonga(hton, share));
}

#ifdef __cplusplus
}
#endif

<commit_msg>init/deinit implemented 	modified:   src/ha_groonga.cc<commit_after>#include <mysql_priv.h>
#include <mysql/plugin.h>
#include <groonga.h>
#include "ha_groonga.h"
#include <pthread.h>

grn_ctx *mrn_ctx_sys;
grn_hash *mrn_hash_sys;
pthread_mutex_t *mrn_mutex_sys;
const char *mrn_log_name="groonga.log";
static FILE *mrn_log_file = NULL;

void mrn_logger_func(int level, const char *time, const char *title,
		     const char *msg, const char *location, void *func_arg)
{
  const char slev[] = " EACewnid-";
  if (mrn_log_file) {
    fprintf(mrn_log_file, "%s|%c|%u|%s %s\n", time,
	    *(slev + level), (uint)pthread_self(), location, msg);
    fflush(mrn_log_file);
  }
}

grn_logger_info mrn_logger_info = {
  GRN_LOG_DUMP,
  GRN_LOG_TIME|GRN_LOG_MESSAGE|GRN_LOG_LOCATION,
  mrn_logger_func,
  NULL
};

#ifdef __cplusplus
extern "C" {
#endif

static int mrn_init(void *p);
static int mrn_deinit(void *p);
static handler *mrn_handler_create(handlerton *hton,
				   TABLE_SHARE *share,
				   MEM_ROOT *root);

struct st_mysql_storage_engine storage_engine_structure =
{ MYSQL_HANDLERTON_INTERFACE_VERSION };

mysql_declare_plugin(groonga)
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
  &storage_engine_structure,
  "Groonga",
  "Tetsuro IKEDA",
  "An Embeddable Fulltext Search Engine",
  PLUGIN_LICENSE_GPL,
  mrn_init,
  mrn_deinit,
  0x0001,
  NULL,
  NULL,
  NULL
}
mysql_declare_plugin_end;

ha_groonga::ha_groonga(handlerton *hton, TABLE_SHARE *share)
  :handler(hton, share)
{
  MRN_ENTER;
  MRN_RETURN_VOID;
}

ha_groonga::~ha_groonga()
{
  MRN_ENTER;
  MRN_RETURN_VOID;
}

const char *ha_groonga::table_type() const
{
  MRN_ENTER;
  MRN_RETURN_S("Groonga");
}

static const char*ha_groonga_exts[] = {
  NullS
};
const char **ha_groonga::bas_ext() const
{
  MRN_ENTER;
  MRN_RETURN_P(ha_groonga_exts);
}

ulonglong ha_groonga::table_flags() const
{
  MRN_ENTER;
  MRN_RETURN(0);
}

ulong ha_groonga::index_flags(uint idx, uint part, bool all_parts) const
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::create(const char *name, TABLE *form, HA_CREATE_INFO *info)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::open(const char *name, int mode, uint test_if_locked)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::close()
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::info(uint flag)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

THR_LOCK_DATA **ha_groonga::store_lock(THD *thd,
				    THR_LOCK_DATA **to,
				    enum thr_lock_type lock_type)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::rnd_init(bool scan)
{
  MRN_ENTER;
  MRN_RETURN(0);
}

int ha_groonga::rnd_next(uchar *buf)
{
  MRN_ENTER;
  MRN_RETURN(HA_ERR_END_OF_FILE);
}

int ha_groonga::rnd_pos(uchar *buf, uchar *pos)
{
  MRN_ENTER;
  MRN_RETURN(HA_ERR_WRONG_COMMAND);
}

void ha_groonga::position(const uchar *record)
{
  MRN_ENTER;
  MRN_RETURN_VOID;
}

bool mrn_flush_logs(handlerton *hton)
{
  MRN_ENTER;
  pthread_mutex_lock(mrn_mutex_sys);
  MRN_LOG(GRN_LOG_NOTICE, "logfile closed by FLUSH LOGS");
  fflush(mrn_log_file);
  fclose(mrn_log_file);
  mrn_log_file = fopen(mrn_log_name, "a");
  MRN_LOG(GRN_LOG_NOTICE, "logfile re-opened by FLUSH LOGS");
  pthread_mutex_unlock(mrn_mutex_sys);
  MRN_RETURN(true);
}

static int mrn_init(void *p)
{
  MRN_ENTER;
  handlerton *hton;
  hton = (handlerton *)p;
  hton->state = SHOW_OPTION_YES;
  hton->create = mrn_handler_create;
  hton->flush_logs = mrn_flush_logs;
  hton->flags = 0;

  /* libgroonga init */
  grn_init();

  /* ctx init */
  mrn_ctx_sys = (grn_ctx*) malloc(sizeof(grn_ctx));
  grn_ctx_init(mrn_ctx_sys, GRN_CTX_USE_DB, GRN_ENC_UTF8);

  /* hash init */
  mrn_hash_sys = grn_hash_create(mrn_ctx_sys,NULL,MRN_MAX_IDENTIFIER_LEN,sizeof(size_t),
				 GRN_OBJ_KEY_VAR_SIZE, GRN_ENC_UTF8);

  /* log init */
  if (!(mrn_log_file = fopen(mrn_log_name, "a"))) {
    MRN_RETURN(-1);
  }
  grn_logger_info_set(mrn_ctx_sys, &mrn_logger_info);
  MRN_LOG(GRN_LOG_NOTICE, "gronnga engine started");

  /* mutex init */
  mrn_mutex_sys = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
  pthread_mutex_init(mrn_mutex_sys, MY_MUTEX_INIT_FAST);

  MRN_RETURN(0);
}

static int mrn_deinit(void *p)
{
  MRN_ENTER;

  /* mutex deinit*/
  pthread_mutex_destroy(mrn_mutex_sys);
  free(mrn_mutex_sys);

  /* log deinit */
  MRN_LOG(GRN_LOG_NOTICE, "stopping groonga engine");
  fflush(mrn_log_file);
  fclose(mrn_log_file);

  /* hash deinit */
  grn_hash_close(mrn_ctx_sys, mrn_hash_sys);

  /* ctx deinit */
  grn_ctx_fin(mrn_ctx_sys);
  free(mrn_ctx_sys);

  /* libgroonga deinit */
  grn_fin();

  MRN_RETURN(0);
}

static handler *mrn_handler_create(handlerton *hton,
				    TABLE_SHARE *share,
				    MEM_ROOT *root)
{
  MRN_ENTER;
  MRN_RETURN_P(new (root) ha_groonga(hton, share));
}

#ifdef __cplusplus
}
#endif

<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIIrrlichtTextureTarget.cpp
    created:    Tue Mar 3 2009
    author:     Paul D Turner (parts based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "CEGUIIrrlichtTextureTarget.h"
#include "CEGUIIrrlichtTexture.h"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float IrrlichtTextureTarget::DEFAULT_SIZE = 128.0f;

//----------------------------------------------------------------------------//
IrrlichtTextureTarget::IrrlichtTextureTarget(IrrlichtRenderer& owner,
                                             irr::video::IVideoDriver& driver) :
    IrrlichtRenderTarget(owner, driver),
    d_texture(0),
    d_CEGUITexture(static_cast<IrrlichtTexture*>(&d_owner.createTexture()))
{
    // setup area and cause the initial texture to be generated.
    declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
}

//----------------------------------------------------------------------------//
IrrlichtTextureTarget::~IrrlichtTextureTarget()
{
    cleanupTargetTexture();
    d_owner.destroyTexture(*d_CEGUITexture);
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::activate()
{
    d_driver.setRenderTarget(d_texture, false, false);
    IrrlichtRenderTarget::activate();
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::deactivate()
{
    IrrlichtRenderTarget::deactivate();
    d_driver.setRenderTarget(0);
}

//----------------------------------------------------------------------------//
bool IrrlichtTextureTarget::isImageryCache() const
{
    return true;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::clear()
{
    d_driver.setRenderTarget(d_texture, true, false,
                             irr::video::SColor(0, 0, 0, 0));
    d_driver.setRenderTarget(0);
}

//----------------------------------------------------------------------------//
Texture& IrrlichtTextureTarget::getTexture() const
{
    return *d_CEGUITexture;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::declareRenderSize(const Size& sz)
{
    const bool realloc =
                !d_texture ||
                static_cast<float>(d_texture->getSize().Width) < sz.d_width ||
                static_cast<float>(d_texture->getSize().Height) < sz.d_height;

    // update area to render into.
    setArea(Rect(d_area.getPosition(), sz));

    // exit if current texture size is large enough
    if (!realloc)
        return;

    // get adjusted size - to account for device capabilities
    const Size final_sz(d_owner.getAdjustedTextureSize(sz));

    cleanupTargetTexture();

    #if CEGUI_IRR_SDK_VERSION >= 16
        const irr::core::dimension2d<irr::u32> irr_sz(
            static_cast<irr::u32>(final_sz.d_width),
            static_cast<irr::u32>(final_sz.d_height));
    #else
        const irr::core::dimension2d<irr::s32> irr_sz(
            static_cast<irr::s32>(final_sz.d_width),
            static_cast<irr::s32>(final_sz.d_height));
    #endif

    d_texture = d_driver.addRenderTargetTexture(
        irr_sz, IrrlichtTexture::getUniqueName().c_str());

    d_CEGUITexture->setIrrlichtTexture(d_texture);
    d_CEGUITexture->setOriginalDataSize(d_area.getSize());

    clear();
}

//----------------------------------------------------------------------------//
bool IrrlichtTextureTarget::isRenderingInverted() const
{
    return false;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::cleanupTargetTexture()
{
    if (d_texture)
    {
        d_CEGUITexture->setIrrlichtTexture(0);
        d_driver.removeTexture(d_texture);
        d_texture = 0;
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>FIX: IrrlichtRenderer would incorrectly clear the main render target (screen) during render to texture operations.  Thanks to Timo.  See: http://www.cegui.org.uk/mantis/view.php?id=348<commit_after>/***********************************************************************
    filename:   CEGUIIrrlichtTextureTarget.cpp
    created:    Tue Mar 3 2009
    author:     Paul D Turner (parts based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "CEGUIIrrlichtTextureTarget.h"
#include "CEGUIIrrlichtTexture.h"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float IrrlichtTextureTarget::DEFAULT_SIZE = 128.0f;

//----------------------------------------------------------------------------//
IrrlichtTextureTarget::IrrlichtTextureTarget(IrrlichtRenderer& owner,
                                             irr::video::IVideoDriver& driver) :
    IrrlichtRenderTarget(owner, driver),
    d_texture(0),
    d_CEGUITexture(static_cast<IrrlichtTexture*>(&d_owner.createTexture()))
{
    // setup area and cause the initial texture to be generated.
    declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
}

//----------------------------------------------------------------------------//
IrrlichtTextureTarget::~IrrlichtTextureTarget()
{
    cleanupTargetTexture();
    d_owner.destroyTexture(*d_CEGUITexture);
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::activate()
{
    d_driver.setRenderTarget(d_texture, false, false);
    IrrlichtRenderTarget::activate();
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::deactivate()
{
    IrrlichtRenderTarget::deactivate();
    d_driver.setRenderTarget(0, false, false);
}

//----------------------------------------------------------------------------//
bool IrrlichtTextureTarget::isImageryCache() const
{
    return true;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::clear()
{
    d_driver.setRenderTarget(d_texture, true, false,
                             irr::video::SColor(0, 0, 0, 0));
    d_driver.setRenderTarget(0, false, false);
}

//----------------------------------------------------------------------------//
Texture& IrrlichtTextureTarget::getTexture() const
{
    return *d_CEGUITexture;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::declareRenderSize(const Size& sz)
{
    const bool realloc =
                !d_texture ||
                static_cast<float>(d_texture->getSize().Width) < sz.d_width ||
                static_cast<float>(d_texture->getSize().Height) < sz.d_height;

    // update area to render into.
    setArea(Rect(d_area.getPosition(), sz));

    // exit if current texture size is large enough
    if (!realloc)
        return;

    // get adjusted size - to account for device capabilities
    const Size final_sz(d_owner.getAdjustedTextureSize(sz));

    cleanupTargetTexture();

    #if CEGUI_IRR_SDK_VERSION >= 16
        const irr::core::dimension2d<irr::u32> irr_sz(
            static_cast<irr::u32>(final_sz.d_width),
            static_cast<irr::u32>(final_sz.d_height));
    #else
        const irr::core::dimension2d<irr::s32> irr_sz(
            static_cast<irr::s32>(final_sz.d_width),
            static_cast<irr::s32>(final_sz.d_height));
    #endif

    d_texture = d_driver.addRenderTargetTexture(
        irr_sz, IrrlichtTexture::getUniqueName().c_str());

    d_CEGUITexture->setIrrlichtTexture(d_texture);
    d_CEGUITexture->setOriginalDataSize(d_area.getSize());

    clear();
}

//----------------------------------------------------------------------------//
bool IrrlichtTextureTarget::isRenderingInverted() const
{
    return false;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::cleanupTargetTexture()
{
    if (d_texture)
    {
        d_CEGUITexture->setIrrlichtTexture(0);
        d_driver.removeTexture(d_texture);
        d_texture = 0;
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbDEMConvertAdapter.h"

#include "itkImageIOBase.h"
#include "itkImageIOFactory.h"

namespace otb
{
namespace Wrapper
{

class DEMConvert : public Application
{
public:
  /** Standard class typedefs. */
  typedef DEMConvert                    Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(DEMConvert, otb::Application);

private:
  void DoInit()
  {
    SetName("DEMConvert");
    SetDescription("Converts a geo-referenced DEM image into a general raster file compatible with OTB DEM handling.");

    SetDocName("DEM Conversion");
    SetDocLongDescription("In order to be understood by the Orfeo ToolBox and the underlying OSSIM library, a geo-referenced Digital Elevation Model image can be converted into a general raster image, which consists in 3 files with the following extensions: .ras, .geom and .omd. Once converted, you have to place these files in a separate directory, and you can then use this directory to set the \"DEM Directory\" parameter of a DEM based OTB application or filter.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Manip);

    AddParameter(ParameterType_InputImage,  "in",  "Input geo-referenced DEM");
    SetParameterDescription("in", "Input geo-referenced DEM to convert to general raster format.");

    AddParameter(ParameterType_Filename,    "out", "Prefix of the output files");
    std::ostringstream oss;
    oss << "will be used to get the prefix (name withtout extensions) of the files to write. ";
    oss << "Three files - prefix.geom, prefix.omd and prefix.ras - will be generated.";
    SetParameterDescription("out", oss.str());
    SetParameterRole("out", Role_Output);
    MandatoryOn("out");

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_Elev.tif");
    SetDocExampleParameterValue("out", "outputDEM");
}

void DoUpdateParameters()
{
  // nothing to update
}

/* The main is simple : read image using OTB and write it as a tif.
*  Read this tif using OSSIM and convert it as a general raster file
*  (.ras, .geom and . omd)
*/

void DoExecute()
{
  // Load input image
  FloatVectorImageType::Pointer inImage = GetParameterImage("in");

  // Set temporary tif filename (for ossim)
  std::string ofname = GetParameterString("out"); ;
  std::string path   = itksys::SystemTools::GetFilenamePath(ofname);
  std::string fname  = itksys::SystemTools::GetFilenameWithoutExtension(ofname);
  std::string tempFilename = path+"/"+fname+"_DEMConvert.tif";
  std::string tempFilenameGeom = path+"/"+fname+"_DEMConvert.geom";

  // Generate the tif image using OTB while keeping the same  pixel
  // type then the input image
  // Initialize an outputParameter and set its output pixeltype
  OutputImageParameter::Pointer paramOut = OutputImageParameter::New();
  std::ostringstream osswriter;
  osswriter<< "writing temporary tif file";

  // Set the filename of the current output image
  paramOut->SetFileName(tempFilename);
  paramOut->SetValue(inImage);

  // Set the output pixel type
  itk::ImageIOBase::Pointer  imageIO = ImageIOFactory::CreateImageIO( GetParameterString("in").c_str(),
                                                                      ImageIOFactory::ReadMode);
  std::string componentTypeInfo(imageIO->GetComponentTypeInfo().name());
  if( componentTypeInfo == typeid(unsigned char).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint8);
    }
  else if( componentTypeInfo == typeid(char).name())
    {
    paramOut->SetPixelType(ImagePixelType_int8);
    }
  else if( componentTypeInfo == typeid(unsigned short).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint16);
    }
  else if( componentTypeInfo == typeid(short).name())
    {
    paramOut->SetPixelType(ImagePixelType_int16);
    }
  else if( componentTypeInfo == typeid(unsigned int).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint32);
    }
  else if( componentTypeInfo == typeid(int).name())
    {
    paramOut->SetPixelType(ImagePixelType_int32);
    }
  else if( componentTypeInfo == typeid(float).name())
    {
    paramOut->SetPixelType(ImagePixelType_float);
    }
  else if( componentTypeInfo == typeid(double).name())
    {
    paramOut->SetPixelType(ImagePixelType_double);
    }
  else
    {
    itkExceptionMacro("This application doesn't support image pixel type " << componentTypeInfo);
    }

  // Add the tempfilename to be written
  paramOut->InitializeWriters();
  AddProcess(paramOut->GetWriter(), osswriter.str());
  paramOut->Write();

  // Set the output ras file
  std::string output = path+"/"+fname+".ras";

  DEMConvertAdapter::Pointer DEMConverter = DEMConvertAdapter::New();
  DEMConverter->Convert(tempFilename, output);

  // remove the temprorary tif file
  if( !itksys::SystemTools::RemoveFile(tempFilename.c_str()) )
    {
    itkExceptionMacro("Problem while removing the file " << tempFilename);
    }

  // remove the geom file if any
  if( itksys::SystemTools::FileExists(tempFilenameGeom.c_str())
      && !itksys::SystemTools::RemoveFile(tempFilenameGeom.c_str()))
    {
    itkExceptionMacro("Problem while removing the Geom file " << tempFilenameGeom);
    }
  }

};

} // namespace otb
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DEMConvert)

<commit_msg>BUG: fix bug 453. In DEMConvert prefix mustn't be declared as Output_Role<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbDEMConvertAdapter.h"

#include "itkImageIOBase.h"
#include "itkImageIOFactory.h"

namespace otb
{
namespace Wrapper
{

class DEMConvert : public Application
{
public:
  /** Standard class typedefs. */
  typedef DEMConvert                    Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(DEMConvert, otb::Application);

private:
  void DoInit()
  {
    SetName("DEMConvert");
    SetDescription("Converts a geo-referenced DEM image into a general raster file compatible with OTB DEM handling.");

    SetDocName("DEM Conversion");
    SetDocLongDescription("In order to be understood by the Orfeo ToolBox and the underlying OSSIM library, a geo-referenced Digital Elevation Model image can be converted into a general raster image, which consists in 3 files with the following extensions: .ras, .geom and .omd. Once converted, you have to place these files in a separate directory, and you can then use this directory to set the \"DEM Directory\" parameter of a DEM based OTB application or filter.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Manip);

    AddParameter(ParameterType_InputImage,  "in",  "Input geo-referenced DEM");
    SetParameterDescription("in", "Input geo-referenced DEM to convert to general raster format.");

    AddParameter(ParameterType_Filename,    "out", "Prefix of the output files");
    std::ostringstream oss;
    oss << "will be used to get the prefix (name withtout extensions) of the files to write. ";
    oss << "Three files - prefix.geom, prefix.omd and prefix.ras - will be generated.";
    SetParameterDescription("out", oss.str());
    //MandatoryOn("out");

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_Elev.tif");
    SetDocExampleParameterValue("out", "outputDEM");
}

void DoUpdateParameters()
{
  // nothing to update
}

/* The main is simple : read image using OTB and write it as a tif.
*  Read this tif using OSSIM and convert it as a general raster file
*  (.ras, .geom and . omd)
*/

void DoExecute()
{
  // Load input image
  FloatVectorImageType::Pointer inImage = GetParameterImage("in");

  // Set temporary tif filename (for ossim)
  std::string ofname = GetParameterString("out"); ;
  std::string path   = itksys::SystemTools::GetFilenamePath(ofname);
  std::string fname  = itksys::SystemTools::GetFilenameWithoutExtension(ofname);
  std::string tempFilename = path+"/"+fname+"_DEMConvert.tif";
  std::string tempFilenameGeom = path+"/"+fname+"_DEMConvert.geom";

  // Generate the tif image using OTB while keeping the same  pixel
  // type then the input image
  // Initialize an outputParameter and set its output pixeltype
  OutputImageParameter::Pointer paramOut = OutputImageParameter::New();
  std::ostringstream osswriter;
  osswriter<< "writing temporary tif file";

  // Set the filename of the current output image
  paramOut->SetFileName(tempFilename);
  paramOut->SetValue(inImage);

  // Set the output pixel type
  itk::ImageIOBase::Pointer  imageIO = ImageIOFactory::CreateImageIO( GetParameterString("in").c_str(),
                                                                      ImageIOFactory::ReadMode);
  std::string componentTypeInfo(imageIO->GetComponentTypeInfo().name());
  if( componentTypeInfo == typeid(unsigned char).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint8);
    }
  else if( componentTypeInfo == typeid(char).name())
    {
    paramOut->SetPixelType(ImagePixelType_int8);
    }
  else if( componentTypeInfo == typeid(unsigned short).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint16);
    }
  else if( componentTypeInfo == typeid(short).name())
    {
    paramOut->SetPixelType(ImagePixelType_int16);
    }
  else if( componentTypeInfo == typeid(unsigned int).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint32);
    }
  else if( componentTypeInfo == typeid(int).name())
    {
    paramOut->SetPixelType(ImagePixelType_int32);
    }
  else if( componentTypeInfo == typeid(float).name())
    {
    paramOut->SetPixelType(ImagePixelType_float);
    }
  else if( componentTypeInfo == typeid(double).name())
    {
    paramOut->SetPixelType(ImagePixelType_double);
    }
  else
    {
    itkExceptionMacro("This application doesn't support image pixel type " << componentTypeInfo);
    }

  // Add the tempfilename to be written
  paramOut->InitializeWriters();
  AddProcess(paramOut->GetWriter(), osswriter.str());
  paramOut->Write();

  // Set the output ras file
  std::string output = path+"/"+fname+".ras";

  DEMConvertAdapter::Pointer DEMConverter = DEMConvertAdapter::New();
  DEMConverter->Convert(tempFilename, output);

  // remove the temprorary tif file
  if( !itksys::SystemTools::RemoveFile(tempFilename.c_str()) )
    {
    itkExceptionMacro("Problem while removing the file " << tempFilename);
    }

  // remove the geom file if any
  if( itksys::SystemTools::FileExists(tempFilenameGeom.c_str())
      && !itksys::SystemTools::RemoveFile(tempFilenameGeom.c_str()))
    {
    itkExceptionMacro("Problem while removing the Geom file " << tempFilenameGeom);
    }
  }

};

} // namespace otb
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DEMConvert)

<|endoftext|>


<commit_before>#include <cmath>

#include "torus.h"

using namespace osg;

ph::Torus::Torus(const double iRadius, const double oRadius, const int phiIteration, const int thetaIteration) {
	this->iRadius = iRadius;
	this->oRadius = oRadius;
	this->phiIteration = phiIteration;
	this->thetaIteration = thetaIteration;
	this->torus = new Geometry;
	this->addDrawable(this->torus.get());
	this->compute();
}

ph::Torus::~Torus() {
	this->torus.release();
}

void ph::Torus::compute() {
    this->setCoordinates();
    this->setIndicies();
}

void ph::Torus::setCoordinates() {
	ref_ptr<Vec3Array> vertices = new Vec3Array();
    ref_ptr<Vec3Array> normals = new Vec3Array();
	ref_ptr<Vec2Array> texcoords = new Vec2Array;

	double phiStep = (oRadius - iRadius) / phiIteration;
	double thetaStep = (oRadius - iRadius) / thetaIteration;
	Vec3d coords;

	for (double i = 0, phi = 0; i <= this->phiIteration; i++, phi += phiStep) {
        for (double j = 0, theta = 0; j <= this->thetaIteration; j++, theta += thetaStep) {
            coords = Vec3d(
                this->(iRadius + oRadius* cos(2*PI*phi))* cos(2*PI*theta), // x
                this->(iRadius + oRadius* cos(2*PI*phi))* sin(2*PI*theta), // y
                this->0.5* sin(2*PI*phi)              // z
                /*normally: oRadius* sin(2*PI*phi), but we need the other notation for
                			our rings*/
            );
            texcoords->push_back(Vec2(phi, theta));
            vertices->push_back(coords);
            coords.normalize();
            normals->push_back(coords);
        }
    }
    this->torus->setVertexArray(vertices.get());
    this->torus->setNormalArray(normals.get());
    this->torus->setTexCoordArray(0, texcoords.get());
    this->torus->setNormalBinding(Geometry::BIND_PER_VERTEX);
}

void ph::Torus::setIndicies() {
    ref_ptr<DrawElementsUInt> indices = new DrawElementsUInt(GL_TRIANGLE_STRIP);

    for (int i = 0; i < this->phiIteration; i++) {
        for (int j = 0; j <= this->thetaIteration; j++) {
            indices->push_back(i*(this->thetaIteration+1)+j);
            indices->push_back((i+1)*(this->thetaIteration+1)+j);
        }
        indices->push_back((i+1)*(this->thetaIteration+1)+this->thetaIteration);
        indices->push_back((i+1)*(this->thetaIteration+1));
    }

    this->torus->addPrimitiveSet(indices.get());
}
<commit_msg>fixing math fails in torus<commit_after>#include <cmath>

#include "torus.h"

using namespace osg;

ph::Torus::Torus(const double iRadius, const double tRadius, const int phiIteration, const int thetaIteration) {
	this->iRadius = iRadius; //radius from origin to the torus
	this->tRadius = tRadius; //radius of the torus
	this->phiIteration = phiIteration; //iterations for the torus-circle
	this->thetaIteration = thetaIteration; //iterations of the planar circle
	this->torus = new Geometry;
	this->addDrawable(this->torus.get());
	this->compute();
}

ph::Torus::~Torus() {
	this->torus.release();
}

void ph::Torus::compute() {
    this->setCoordinates();
    this->setIndicies();
}

void ph::Torus::setCoordinates() {
	ref_ptr<Vec3Array> vertices = new Vec3Array();
    ref_ptr<Vec3Array> normals = new Vec3Array();
	ref_ptr<Vec2Array> texcoords = new Vec2Array;

	double phiStep = this->iRaidus / phiIteration;
	double thetaStep = this->tRadius / thetaIteration;
	Vec3d coords;

	for (double i = 0, theta = 0; i <= this->phiIteration; i++, theta += thetaStep) {
        for (double j = 0, phi = 0; j <= this->thetaIteration; j++, phi += phiStep) {
            coords = Vec3d(
                (this->iRadius + this->tRadius* cos(2*PI*phi))* cos(2*PI*theta), // x
                (this->iRadius + this->tRadius* cos(2*PI*phi))* sin(2*PI*theta), // y
                0.5* sin(2*PI*phi)              // z
                /*normally: this->tRadius* sin(2*PI*phi), but we need the other notation for
                			our rings*/
            );
            texcoords->push_back(Vec2(theta, phi));
            vertices->push_back(coords);
            coords.normalize();
            normals->push_back(coords);
        }
    }
    this->torus->setVertexArray(vertices.get());
    this->torus->setNormalArray(normals.get());
    this->torus->setTexCoordArray(0, texcoords.get());
    this->torus->setNormalBinding(Geometry::BIND_PER_VERTEX);
}

void ph::Torus::setIndicies() {
    ref_ptr<DrawElementsUInt> indices = new DrawElementsUInt(GL_TRIANGLE_STRIP);

    for (int i = 0; i < this->phiIteration; i++) {
        for (int j = 0; j <= this->thetaIteration; j++) {
            indices->push_back(i*(this->thetaIteration+1)+j);
            indices->push_back((i+1)*(this->thetaIteration+1)+j);
        }
        indices->push_back((i+1)*(this->thetaIteration+1)+this->thetaIteration);
        indices->push_back((i+1)*(this->thetaIteration+1));
    }

    this->torus->addPrimitiveSet(indices.get());
}
<|endoftext|>