<commit_before>// WlanHelper.cpp : Defines the entry point for the console application.
//

// #include "stdafx.h"
#include <stdio.h>
#include <tchar.h>

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wlanapi.h>

#define WLAN_CLIENT_VERSION_VISTA 2

DWORD SetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)
{
	DWORD dwResult = 0;
	HANDLE hClient = NULL;
	DWORD dwCurVersion = 0;
	DWORD outsize = 0;

	// Open Handle for the set operation
	dwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);
	dwResult = WlanSetInterface(hClient, InterfaceGuid, opcode, sizeof(ULONG), pData, NULL);
	WlanCloseHandle(hClient, NULL);

	return dwResult;
}

// enumerate wireless interfaces
UINT EnumInterface(HANDLE hClient, WLAN_INTERFACE_INFO sInfo[64])
{
	DWORD dwError = ERROR_SUCCESS;
	PWLAN_INTERFACE_INFO_LIST pIntfList = NULL;
	UINT i = 0;

	__try
	{
		// enumerate wireless interfaces
		if ((dwError = WlanEnumInterfaces(
			hClient,
			NULL,               // reserved
			&pIntfList
			)) != ERROR_SUCCESS)
		{
			__leave;
		}

		// print out interface information
		for (i = 0; i < pIntfList->dwNumberOfItems; i++)
		{
			memcpy(&sInfo[i], &pIntfList->InterfaceInfo[i], sizeof(WLAN_INTERFACE_INFO));
		}

		return pIntfList->dwNumberOfItems;
	}
	__finally
	{
		// clean up
		if (pIntfList != NULL)
		{
			WlanFreeMemory(pIntfList);
		}
	}
	return 0;
}

// open a WLAN client handle and check version
DWORD
OpenHandleAndCheckVersion(
PHANDLE phClient
)
{
	DWORD dwError = ERROR_SUCCESS;
	DWORD dwServiceVersion;
	HANDLE hClient = NULL;

	__try
	{
		*phClient = NULL;

		// open a handle to the service
		if ((dwError = WlanOpenHandle(
			WLAN_API_VERSION,
			NULL,               // reserved
			&dwServiceVersion,
			&hClient
			)) != ERROR_SUCCESS)
		{
			__leave;
		}

		// check service version
		if (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0))
		{
			// No-op, because the version check is for demonstration purpose only.
			// You can add your own logic here.
		}

		*phClient = hClient;

		// set hClient to NULL so it will not be closed
		hClient = NULL;
	}
	__finally
	{
		if (hClient != NULL)
		{
			// clean up
			WlanCloseHandle(
				hClient,
				NULL            // reserved
				);
		}
	}

	return dwError;
}

// get interface state string
LPWSTR
GetInterfaceStateString(__in WLAN_INTERFACE_STATE wlanInterfaceState)
{
	LPWSTR strRetCode;

	switch (wlanInterfaceState)
	{
	case wlan_interface_state_not_ready:
		strRetCode = L"\"not ready\"";
		break;
	case wlan_interface_state_connected:
		strRetCode = L"\"connected\"";
		break;
	case wlan_interface_state_ad_hoc_network_formed:
		strRetCode = L"\"ad hoc network formed\"";
		break;
	case wlan_interface_state_disconnecting:
		strRetCode = L"\"disconnecting\"";
		break;
	case wlan_interface_state_disconnected:
		strRetCode = L"\"disconnected\"";
		break;
	case wlan_interface_state_associating:
		strRetCode = L"\"associating\"";
		break;
	case wlan_interface_state_discovering:
		strRetCode = L"\"discovering\"";
		break;
	case wlan_interface_state_authenticating:
		strRetCode = L"\"authenticating\"";
		break;
	default:
		strRetCode = L"\"invalid interface state\"";
	}

	return strRetCode;
}

int main()
{
	HANDLE hClient = NULL;
	WLAN_INTERFACE_INFO sInfo[64];
	RPC_CSTR strGuid = NULL;

	TCHAR szBuffer[256];
	DWORD dwRead;
	if (OpenHandleAndCheckVersion(&hClient) != ERROR_SUCCESS)
		return -1;

	UINT nCount = EnumInterface(hClient, sInfo);
	for (UINT i = 0; i < nCount; ++i)
	{
		if (UuidToStringA(&sInfo[i].InterfaceGuid, &strGuid) == RPC_S_OK)
		{
			printf(("%d. %s\n\tDescription: %S\n\tState: %S\n"),
				i,
				strGuid,
				sInfo[i].strInterfaceDescription,
				GetInterfaceStateString(sInfo[i].isState));

			RpcStringFreeA(&strGuid);
		}
	}

	UINT nChoice = 0;
	printf("Enter the choice (0, 1,..) of the wireless card you want to operate on:\n");

	if (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)
	{
		puts("Error input.");
		return -1;
	}
	szBuffer[dwRead] = 0;
	nChoice = _ttoi(szBuffer);

	if (nChoice > nCount)
	{
		puts("No such index.");
		return -1;
	}

	UINT nSTate = 0;
	//ULONG targetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;
	ULONG targetOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;
	printf("Enter the state (0, 1 or 2) you want to switch to for the chosen wireless card:\n");
	printf("0: Managed Mode (ExtSTA)\n1: Monitor Mode (NetMon)\n2: Master Mode (ExtAP)\n");

	if (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)
	{
		puts("Error input.");
		return -1;
	}
	szBuffer[dwRead] = 0;
	nSTate = _ttoi(szBuffer);

	if (nSTate != 0 && nSTate != 1 && nSTate != 2)
	{
		puts("Only 0, 1 and 2 are valid inputs.");
		return -1;
	}
	if (nSTate == 0)
	{
		targetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;
	}
	else if (nSTate == 1)
	{
		targetOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;
	}
	else // nSTate == 2
	{
		targetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_AP;
	}

	DWORD dwResult = SetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&targetOperationMode, &sInfo[nChoice].InterfaceGuid);
	if (dwResult != ERROR_SUCCESS)
	{
		printf("SetInterface error, error code = %d\n", dwResult);
		system("PAUSE");
	}
	else
	{
		printf("SetInterface success!\n");
	}

	return 0;
}

<commit_msg>Added the function to check operation mode.<commit_after>// WlanHelper.cpp : Defines the entry point for the console application.
//

// #include "stdafx.h"
#include <stdio.h>
#include <tchar.h>

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wlanapi.h>

#define WLAN_CLIENT_VERSION_VISTA 2

DWORD SetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)
{
	DWORD dwResult = 0;
	HANDLE hClient = NULL;
	DWORD dwCurVersion = 0;
	DWORD outsize = 0;

	// Open Handle for the set operation
	dwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);
	dwResult = WlanSetInterface(hClient, InterfaceGuid, opcode, sizeof(ULONG), pData, NULL);
	WlanCloseHandle(hClient, NULL);

	return dwResult;
}

DWORD GetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)
{
	DWORD dwResult = 0;
	HANDLE hClient = NULL;
	DWORD dwCurVersion = 0;
	DWORD outsize = 0;
	WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_invalid;

	// Open Handle for the set operation
	dwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);
	dwResult = WlanQueryInterface(hClient, InterfaceGuid, opcode, NULL, &outsize, pData, &opCode);
	WlanCloseHandle(hClient, NULL);

	return dwResult;
}

// enumerate wireless interfaces
UINT EnumInterface(HANDLE hClient, WLAN_INTERFACE_INFO sInfo[64])
{
	DWORD dwError = ERROR_SUCCESS;
	PWLAN_INTERFACE_INFO_LIST pIntfList = NULL;
	UINT i = 0;

	__try
	{
		// enumerate wireless interfaces
		if ((dwError = WlanEnumInterfaces(
			hClient,
			NULL,               // reserved
			&pIntfList
			)) != ERROR_SUCCESS)
		{
			__leave;
		}

		// print out interface information
		for (i = 0; i < pIntfList->dwNumberOfItems; i++)
		{
			memcpy(&sInfo[i], &pIntfList->InterfaceInfo[i], sizeof(WLAN_INTERFACE_INFO));
		}

		return pIntfList->dwNumberOfItems;
	}
	__finally
	{
		// clean up
		if (pIntfList != NULL)
		{
			WlanFreeMemory(pIntfList);
		}
	}
	return 0;
}

// open a WLAN client handle and check version
DWORD
OpenHandleAndCheckVersion(
PHANDLE phClient
)
{
	DWORD dwError = ERROR_SUCCESS;
	DWORD dwServiceVersion;
	HANDLE hClient = NULL;

	__try
	{
		*phClient = NULL;

		// open a handle to the service
		if ((dwError = WlanOpenHandle(
			WLAN_API_VERSION,
			NULL,               // reserved
			&dwServiceVersion,
			&hClient
			)) != ERROR_SUCCESS)
		{
			__leave;
		}

		// check service version
		if (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0))
		{
			// No-op, because the version check is for demonstration purpose only.
			// You can add your own logic here.
		}

		*phClient = hClient;

		// set hClient to NULL so it will not be closed
		hClient = NULL;
	}
	__finally
	{
		if (hClient != NULL)
		{
			// clean up
			WlanCloseHandle(
				hClient,
				NULL            // reserved
				);
		}
	}

	return dwError;
}

// get interface state string
LPWSTR
GetInterfaceStateString(__in WLAN_INTERFACE_STATE wlanInterfaceState)
{
	LPWSTR strRetCode;

	switch (wlanInterfaceState)
	{
	case wlan_interface_state_not_ready:
		strRetCode = L"\"not ready\"";
		break;
	case wlan_interface_state_connected:
		strRetCode = L"\"connected\"";
		break;
	case wlan_interface_state_ad_hoc_network_formed:
		strRetCode = L"\"ad hoc network formed\"";
		break;
	case wlan_interface_state_disconnecting:
		strRetCode = L"\"disconnecting\"";
		break;
	case wlan_interface_state_disconnected:
		strRetCode = L"\"disconnected\"";
		break;
	case wlan_interface_state_associating:
		strRetCode = L"\"associating\"";
		break;
	case wlan_interface_state_discovering:
		strRetCode = L"\"discovering\"";
		break;
	case wlan_interface_state_authenticating:
		strRetCode = L"\"authenticating\"";
		break;
	default:
		strRetCode = L"\"invalid interface state\"";
	}

	return strRetCode;
}

// get interface operation mode string
LPWSTR
GetInterfaceOperationModeString(__in ULONG wlanInterfaceOperationMode)
{
	LPWSTR strRetCode;

	switch (wlanInterfaceOperationMode)
	{
	case DOT11_OPERATION_MODE_EXTENSIBLE_STATION:
		strRetCode = L"\"Extensible Station (ExtSTA)\"";
		break;
	case DOT11_OPERATION_MODE_NETWORK_MONITOR:
		strRetCode = L"\"Network Monitor (NetMon)\"";
		break;
	case DOT11_OPERATION_MODE_EXTENSIBLE_AP:
		strRetCode = L"\"Extensible Access Point (ExtAP)\"";
		break;
	default:
		strRetCode = L"\"invalid interface operation mode\"";
	}

	return strRetCode;
}

int main()
{
	HANDLE hClient = NULL;
	WLAN_INTERFACE_INFO sInfo[64];
	RPC_CSTR strGuid = NULL;

	TCHAR szBuffer[256];
	DWORD dwRead;
	if (OpenHandleAndCheckVersion(&hClient) != ERROR_SUCCESS)
		return -1;

	UINT nCount = EnumInterface(hClient, sInfo);
	for (UINT i = 0; i < nCount; ++i)
	{
		if (UuidToStringA(&sInfo[i].InterfaceGuid, &strGuid) == RPC_S_OK)
		{
			ULONG OperationMode = -1;
			PULONG pOperationMode;
			DWORD dwResult = GetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&pOperationMode, &sInfo[i].InterfaceGuid);
			if (dwResult != ERROR_SUCCESS)
			{
				printf("GetInterface error, error code = %d\n", dwResult);
				system("PAUSE");
			}
			else
			{
				OperationMode = *pOperationMode;
				WlanFreeMemory(pOperationMode);
			}

			printf(("%d. %s\n\tDescription: %S\n\tState: %S\n\tOperation Mode: %S\n"),
				i,
				strGuid,
				sInfo[i].strInterfaceDescription,
				GetInterfaceStateString(sInfo[i].isState),
				GetInterfaceOperationModeString(OperationMode));

			RpcStringFreeA(&strGuid);
		}
	}

	UINT nChoice = 0;
	printf("Enter the choice (0, 1,..) of the wireless card you want to operate on:\n");

	if (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)
	{
		puts("Error input.");
		return -1;
	}
	szBuffer[dwRead] = 0;
	nChoice = _ttoi(szBuffer);

	if (nChoice > nCount)
	{
		puts("No such index.");
		return -1;
	}

	UINT nSTate = 0;
	//ULONG targetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;
	ULONG targetOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;
	printf("Enter the operation mode (0, 1 or 2) you want to switch to for the chosen wireless card:\n");
	printf("0: Extensible Station (ExtSTA)\n1: Network Monitor (NetMon)\n2: Extensible Access Point (ExtAP)\n");

	if (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)
	{
		puts("Error input.");
		return -1;
	}
	szBuffer[dwRead] = 0;
	nSTate = _ttoi(szBuffer);

	if (nSTate != 0 && nSTate != 1 && nSTate != 2)
	{
		puts("Only 0, 1 and 2 are valid inputs.");
		return -1;
	}
	if (nSTate == 0)
	{
		targetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;
	}
	else if (nSTate == 1)
	{
		targetOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;
	}
	else // nSTate == 2
	{
		targetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_AP;
	}

	DWORD dwResult = SetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&targetOperationMode, &sInfo[nChoice].InterfaceGuid);
	if (dwResult != ERROR_SUCCESS)
	{
		printf("SetInterface error, error code = %d\n", dwResult);
		system("PAUSE");
	}
	else
	{
		printf("SetInterface success!\n");
	}

	return 0;
}

<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#undef NDEBUG

#include <iostream>
#include "catch.hpp"

namespace std {

void redefined_abort(){
    throw 1;
}

} //end of namespace std

#define abort redefined_abort

#include "cpp_utils/assert.hpp"

namespace {

int assert_wrapper(bool value){
    cpp_assert(value, "message");
    return 0;
}

} //end of namespace

TEST_CASE( "assert/message/1", "[assert]" ) {
    std::stringstream stream;
    auto out = std::cerr.rdbuf();
    std::cerr.rdbuf(stream.rdbuf());

    REQUIRE_THROWS(assert_wrapper(false));
    auto message = stream.str();

    REQUIRE(message == "***** Internal Program Error - assertion (value) failed in int {anonymous}::assert_wrapper(bool):\ntest/assert.cpp(28): message\n");

    std::cerr.rdbuf(out);

    REQUIRE_NOTHROW(assert_wrapper(true));
}
<commit_msg>Adapt test for clang<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#undef NDEBUG

#include <iostream>
#include "catch.hpp"

namespace std {

void redefined_abort(){
    throw 1;
}

} //end of namespace std

#define abort redefined_abort

#include "cpp_utils/assert.hpp"

namespace {

int assert_wrapper(bool value){
    cpp_assert(value, "message");
    return 0;
}

} //end of namespace

TEST_CASE( "assert/message/1", "[assert]" ) {
    std::stringstream stream;
    auto out = std::cerr.rdbuf();
    std::cerr.rdbuf(stream.rdbuf());

    REQUIRE_THROWS(assert_wrapper(false));
    auto message = stream.str();

#ifdef __clang__
    REQUIRE(message == "***** Internal Program Error - assertion (value) failed in int (anonymous namespace)::assert_wrapper(bool):\ntest/assert.cpp(28): message\n");
#else
    REQUIRE(message == "***** Internal Program Error - assertion (value) failed in int {anonymous}::assert_wrapper(bool):\ntest/assert.cpp(28): message\n");
#endif

    std::cerr.rdbuf(out);

    REQUIRE_NOTHROW(assert_wrapper(true));
}
<|endoftext|>


<commit_before>#include <config.h>
#include <iostream>
#include <fstream>
#include "../src/VelbusMessage/VelbusMessage.hpp"

int main(int argc, char* argv[]) {
	char buffer[32];
	std::cin.read(buffer,sizeof(buffer));

	std::string data(buffer, std::cin.gcount() );

	try {
		std::auto_ptr<VelbusMessage::VelbusMessage> m( VelbusMessage::parse_and_consume( data ) );
		std::cout << m->string() << "\n";

	} catch( VelbusMessage::InsufficientData &e ) {
		std::cout << "InsufficientData\n";

	} catch( VelbusMessage::FormError &e ) {
		std::cout << "FormError: " << e.details() << "\n";
	}
}
<commit_msg>Added composing check to parsers<commit_after>#include <config.h>
#include <iostream>
#include <fstream>
#include "../src/VelbusMessage/VelbusMessage.hpp"

int main(int argc, char* argv[]) {
	char buffer[32];
	std::cin.read(buffer,sizeof(buffer));

	std::string data(buffer, std::cin.gcount() );
	std::string data_copy(data);

	try {
		std::auto_ptr<VelbusMessage::VelbusMessage> m( VelbusMessage::parse_and_consume( data ) );
		std::cout << m->string() << "\n";

		std::string b = m->message();
		if( b.compare(data_copy) != 0 ) {
			std::cout << "message() does not return same data as passed in\n";
			return 1;
		}

	} catch( VelbusMessage::InsufficientData &e ) {
		std::cout << "InsufficientData\n";

	} catch( VelbusMessage::FormError &e ) {
		std::cout << "FormError: " << e.details() << "\n";
	}
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>

#include <TAlienCollection.h>
#include <TFile.h>
#include <TGrid.h>
#include <TGridResult.h>
#include <TMath.h>
#include <TROOT.h>
#include <TString.h>
#include <TSystem.h>

#include "AliCDBManager.h"
#include "AliDAQ.h"
#include "AliLog.h"
#include "AliQA.h"
#include "AliQADataMakerSteer.h"
#include "AliRawReader.h"
#include "AliRawReaderRoot.h"
#include "AliTRDrawStreamBase.h"
#include "AliGeomManager.h"

TString ClassName() { return "rawqa" ; }

//________________________________qa______________________________________
void rawqa(const Int_t runNumber, Int_t maxFiles = 10, const char* year = "08")
{
	AliGeomManager::LoadGeometry("geometry.root");
	char kDefaultOCDBStorage[120] ;
	sprintf(kDefaultOCDBStorage, "alien://folder=/alice/data/20%s/LHC%sa/OCDB/", year, year) ;
	AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), year)) ;
	AliQA::SetQARefDataDirName("Data") ; //Data, Pedestals, BlackEvent, .....

	UInt_t maxEvents = 99999 ;
	if ( maxFiles < 0 ) {
		maxEvents = TMath::Abs(maxFiles) ;
		maxFiles = 99 ;
	}
	AliLog::SetGlobalDebugLevel(0) ;
	// connect to the grid
	TGrid * grid = 0x0 ;
       	grid = TGrid::Connect("alien://") ;

	Bool_t detIn[AliDAQ::kNDetectors] = {kFALSE} ;
	char * detNameOff[AliDAQ::kNDetectors] = {"ITS", "ITS", "ITS", "TPC", "TRD", "TOF", "HMPID", "PHOS", "PHOS", "PMD", "MUON", "MUON", "FMD", "T0", "VZERO", "ZDC", "ACORDE", "TRG", "EMCAL", "DAQ_TEST", "HLT"} ;
	// make the file name pattern year and run number
	TString pattern;
	pattern.Form("%9d",runNumber);
	pattern.ReplaceAll(" ", "0") ;
	pattern.Prepend(year);
	pattern.Append("*.root");
	// find the files associated to this run
	TGridResult * result = 0x0 ;
	Bool_t local = kFALSE ;
	if (grid) { // get the list of files from AliEn directly
		TString collectionFile(pattern) ;
		collectionFile.ReplaceAll("*.root", ".xml") ;
		if ( gSystem->AccessPathName(collectionFile) == 0 ) { // get the list of files from an a-priori created collection file
			TAlienCollection collection(collectionFile.Data(), maxFiles) ;
			result = collection.GetGridResult("", 0, 0);
		} else {
			TString baseDir;
			baseDir.Form("/alice/data/20%s/",year);
			result = grid->Query(baseDir, pattern) ;
		}
	} else {
	   // get the list of files from the local current directory
	    local = kTRUE ;
	    char line[100] ;
	    sprintf(line, ".! ls %s*.root > tempo.txt", pattern.Data()) ;
	    gROOT->ProcessLine(line) ;
	}

	AliLog::Flush();
	ifstream in ;
	if (local)
		in.open("tempo.txt", ifstream::in) ;

	AliQADataMakerSteer qas ;
	TString detectors  = "";
	TString detectorsW = "";
	UShort_t file = 0 ;
	UShort_t filesProcessed = 0 ;
	UShort_t eventsProcessed = 0 ;
	AliCDBManager* man = AliCDBManager::Instance();
	for ( file = 0 ; file < maxFiles ; file++) {
		man->SetDefaultStorage(kDefaultOCDBStorage) ;
		if ( qas.GetCurrentEvent() >= maxEvents)
			break ;

		TString fileName ;
		if ( local) {
			in >> fileName ;
		}
		else
			fileName = result->GetKey(file, "turl");
	       	if ( fileName == "" )
		        break ;
		if ( fileName.Contains("tag") )
			continue;
                filesProcessed++ ;
		char input[200] ;
		if (local)
			sprintf(input, "%s", fileName.Data()) ;
		else
			sprintf(input, "%s", result->GetKey(file, "turl"));
		AliInfo(Form("Proccessing file # %d --> %s", file, input)) ;
		AliLog::Flush();
		// check which detectors are present
		AliRawReader * rawReader = new AliRawReaderRoot(input);
		AliTRDrawStreamBase::SetRawStreamVersion("TB");
		while ( rawReader->NextEvent() ) {
			man->SetRun(rawReader->GetRunNumber());
			AliLog::Flush();
			UChar_t * data ;
			while (rawReader->ReadNextData(data)) {
				Int_t detID = rawReader->GetDetectorID();
				if (detID < 0 || detID >= AliDAQ::kNDetectors) {
					AliError("Wrong detector ID! Skipping payload...");
					continue;
				}
				detIn[detID] = kTRUE ;
			}
			for (Int_t detID = 0; detID < AliDAQ::kNDetectors ; detID++) {
				if (detIn[detID]) {
					if ( ! detectors.Contains(detNameOff[detID]) ) {
						detectors.Append(detNameOff[detID]) ;
						detectors.Append(" ") ;
					}
				}
			}
			if ( !detectors.IsNull() )
				break ;
		}
		if ( !detectors.IsNull() ) {
			qas.SetMaxEvents(maxEvents) ;
			detectorsW = qas.Run(detectors, rawReader) ;
			qas.Reset() ;
		} else {
			AliError("No valid detectors found") ;
		}
		delete rawReader ;
		eventsProcessed += qas.GetCurrentEvent() ;
	}
	AliLog::Flush();
	qas.Merge(runNumber) ;

	AliLog::Flush();
	// The summary
	AliInfo(Form("\n\n********** Summary for run %d **********", runNumber)) ;
	printf("     detectors present in the run        : %s\n", detectors.Data()) ;
	printf("     detectors present in the run with QA: %s\n", detectorsW.Data()) ;
	printf("     number of files/events processed    : %d/%d\n", filesProcessed, eventsProcessed) ;
	TFile * qaResult = TFile::Open(AliQA::GetQAResultFileName()) ;
	if ( qaResult ) {
		AliQA * qa = dynamic_cast<AliQA *>(qaResult->Get(AliQA::GetQAName())) ;
		if ( qa) {
			for (Int_t index = 0 ; index < AliQA::kNDET ; index++)
				if (detectorsW.Contains(AliQA::GetDetName(AliQA::DETECTORINDEX_t(index))))
					qa->ShowStatus(AliQA::DETECTORINDEX_t(index)) ;
		} else {
			AliError(Form("%s not found in %s !", AliQA::GetQAName(), AliQA::GetQAResultFileName())) ;
		}
	} else {
		AliError(Form("%s has not been produced !", AliQA::GetQAResultFileName())) ;
	}
}
<commit_msg>typo<commit_after>#include <iostream>
#include <fstream>

#include <TAlienCollection.h>
#include <TFile.h>
#include <TGrid.h>
#include <TGridResult.h>
#include <TMath.h>
#include <TROOT.h>
#include <TString.h>
#include <TSystem.h>

#include "AliCDBManager.h"
#include "AliDAQ.h"
#include "AliLog.h"
#include "AliQA.h"
#include "AliQADataMakerSteer.h"
#include "AliRawReader.h"
#include "AliRawReaderRoot.h"
#include "AliTRDrawStreamBase.h"
#include "AliGeomManager.h"

TString ClassName() { return "rawqa" ; }

//________________________________qa______________________________________
void rawqa(const Int_t runNumber, Int_t maxFiles = 10, const char* year = "08")
{
	char kDefaultOCDBStorage[120] ;
	sprintf(kDefaultOCDBStorage, "alien://folder=/alice/data/20%s/LHC%sa/OCDB/", year, year) ;
	AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), year)) ;
	AliQA::SetQARefDataDirName("Data") ; //Data, Pedestals, BlackEvent, .....

	UInt_t maxEvents = 99999 ;
	if ( maxFiles < 0 ) {
		maxEvents = TMath::Abs(maxFiles) ;
		maxFiles = 99 ;
	}
	AliLog::SetGlobalDebugLevel(0) ;
	// connect to the grid
	TGrid * grid = 0x0 ;
       	grid = TGrid::Connect("alien://") ;

	Bool_t detIn[AliDAQ::kNDetectors] = {kFALSE} ;
	char * detNameOff[AliDAQ::kNDetectors] = {"ITS", "ITS", "ITS", "TPC", "TRD", "TOF", "HMPID", "PHOS", "PHOS", "PMD", "MUON", "MUON", "FMD", "T0", "VZERO", "ZDC", "ACORDE", "TRG", "EMCAL", "DAQ_TEST", "HLT"} ;
	// make the file name pattern year and run number
	TString pattern;
	pattern.Form("%9d",runNumber);
	pattern.ReplaceAll(" ", "0") ;
	pattern.Prepend(year);
	pattern.Append("*.root");
	// find the files associated to this run
	TGridResult * result = 0x0 ;
	Bool_t local = kFALSE ;
	if (grid) { // get the list of files from AliEn directly
		TString collectionFile(pattern) ;
		collectionFile.ReplaceAll("*.root", ".xml") ;
		if ( gSystem->AccessPathName(collectionFile) == 0 ) { // get the list of files from an a-priori created collection file
			TAlienCollection collection(collectionFile.Data(), maxFiles) ;
			result = collection.GetGridResult("", 0, 0);
		} else {
			TString baseDir;
			baseDir.Form("/alice/data/20%s/",year);
			result = grid->Query(baseDir, pattern) ;
		}
	} else {
	   // get the list of files from the local current directory
	    local = kTRUE ;
	    char line[100] ;
	    sprintf(line, ".! ls %s*.root > tempo.txt", pattern.Data()) ;
	    gROOT->ProcessLine(line) ;
	}

	AliLog::Flush();
	ifstream in ;
	if (local)
		in.open("tempo.txt", ifstream::in) ;

	AliQADataMakerSteer qas ;
	TString detectors  = "";
	TString detectorsW = "";
	UShort_t file = 0 ;
	UShort_t filesProcessed = 0 ;
	UShort_t eventsProcessed = 0 ;
	AliCDBManager* man = AliCDBManager::Instance();
	AliGeomManager::LoadGeometry("geometry.root");
	for ( file = 0 ; file < maxFiles ; file++) {
		man->SetDefaultStorage(kDefaultOCDBStorage) ;
		if ( qas.GetCurrentEvent() >= maxEvents)
			break ;

		TString fileName ;
		if ( local) {
			in >> fileName ;
		}
		else
			fileName = result->GetKey(file, "turl");
	       	if ( fileName == "" )
		        break ;
		if ( fileName.Contains("tag") )
			continue;
                filesProcessed++ ;
		char input[200] ;
		if (local)
			sprintf(input, "%s", fileName.Data()) ;
		else
			sprintf(input, "%s", result->GetKey(file, "turl"));
		AliInfo(Form("Proccessing file # %d --> %s", file, input)) ;
		AliLog::Flush();
		// check which detectors are present
		AliRawReader * rawReader = new AliRawReaderRoot(input);
		AliTRDrawStreamBase::SetRawStreamVersion("TB");
		while ( rawReader->NextEvent() ) {
			man->SetRun(rawReader->GetRunNumber());
			AliLog::Flush();
			UChar_t * data ;
			while (rawReader->ReadNextData(data)) {
				Int_t detID = rawReader->GetDetectorID();
				if (detID < 0 || detID >= AliDAQ::kNDetectors) {
					AliError("Wrong detector ID! Skipping payload...");
					continue;
				}
				detIn[detID] = kTRUE ;
			}
			for (Int_t detID = 0; detID < AliDAQ::kNDetectors ; detID++) {
				if (detIn[detID]) {
					if ( ! detectors.Contains(detNameOff[detID]) ) {
						detectors.Append(detNameOff[detID]) ;
						detectors.Append(" ") ;
					}
				}
			}
			if ( !detectors.IsNull() )
				break ;
		}
		if ( !detectors.IsNull() ) {
			qas.SetMaxEvents(maxEvents) ;
			detectorsW = qas.Run(detectors, rawReader) ;
			qas.Reset() ;
		} else {
			AliError("No valid detectors found") ;
		}
		delete rawReader ;
		eventsProcessed += qas.GetCurrentEvent() ;
	}
	AliLog::Flush();
	qas.Merge(runNumber) ;

	AliLog::Flush();
	// The summary
	AliInfo(Form("\n\n********** Summary for run %d **********", runNumber)) ;
	printf("     detectors present in the run        : %s\n", detectors.Data()) ;
	printf("     detectors present in the run with QA: %s\n", detectorsW.Data()) ;
	printf("     number of files/events processed    : %d/%d\n", filesProcessed, eventsProcessed) ;
	TFile * qaResult = TFile::Open(AliQA::GetQAResultFileName()) ;
	if ( qaResult ) {
		AliQA * qa = dynamic_cast<AliQA *>(qaResult->Get(AliQA::GetQAName())) ;
		if ( qa) {
			for (Int_t index = 0 ; index < AliQA::kNDET ; index++)
				if (detectorsW.Contains(AliQA::GetDetName(AliQA::DETECTORINDEX_t(index))))
					qa->ShowStatus(AliQA::DETECTORINDEX_t(index)) ;
		} else {
			AliError(Form("%s not found in %s !", AliQA::GetQAName(), AliQA::GetQAResultFileName())) ;
		}
	} else {
		AliError(Form("%s has not been produced !", AliQA::GetQAResultFileName())) ;
	}
}
<|endoftext|>


<commit_before>/* $Id$ */

// This class runs the test preprocessor
// It uses AliTestShuttle to simulate a full Shuttle process

// The input data is created in the functions
//   CreateDCSAliasMap() creates input that would in the same way come from DCS
//   ReadDCSAliasMap() reads from a file
//   CreateInputFilesMap() creates a list of local files, that can be accessed by the shuttle

void TestZDCPreprocessor()
{
  // load library
  gSystem->Load("libTestShuttle.so");

  // create AliTestShuttle instance
  // The parameters are run, startTime, endTime
  AliTestShuttle* shuttle = new AliTestShuttle(7, 0, 1);

  printf("Test Shuttle temp dir: %s\n", AliShuttleInterface::GetShuttleTempDir());

  // TODO if needed, change location of OCDB and Reference test folders
  // by default they are set to $ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB and TestReference
  AliTestShuttle::SetMainCDB("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB");
  AliTestShuttle::SetMainRefStorage("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestReference");

  printf("Test OCDB storage Uri: %s\n", AliShuttleInterface::GetMainCDB().Data());
  printf("Test Reference storage Uri: %s\n", AliShuttleInterface::GetMainRefStorage().Data());

  // TODO(1)
  //
  // The shuttle can read DCS data, if the preprocessor should be tested to process DCS data,
  // some fake data has to be created.
  //
  // The "fake" input data can be taken using either (a) or (b):
  // (a) data from a file: Use ReadDCSAliasMap()
  //     the format of the file is explained in ReadDCSAliasMap()
  //     To use it uncomment the following line:
  //
  //TMap* dcsAliasMap = ReadDCSAliasMap();
  //
  // (b) generated in this macro: Use CreateDCSAliasMap() and its documentation
  //     To use it uncomment the following line:
  //
  TMap* dcsAliasMap = CreateDCSAliasMap();
  //WriteDCSAliasMap();

  // now give the alias map to the shuttle
  shuttle->SetDCSInput(dcsAliasMap);

  // TODO(2)
  //
  // The shuttle can also process files that originate from DCS, DAQ and HLT.
  // To test it, we provide some local files and locations where these would be found when
  // the online machinery would be there.
  // In real life this functions would be produces by the sub-detectors
  // calibration programs in DCS, DAQ or HLT. These files can then be retrieved using the Shuttle.
  //
  // Files are added with the function AliTestShuttle::AddInputFile. The syntax is:
  // AddInputFile(<system>, <detector>, <id>, <source>, <local-file>)
  // In this example we add a file originating from the GDC with the id PEDESTALS
  // Three files originating from different LDCs but with the same id are also added
  // Note that the test preprocessor name is TPC. The name of the detector's preprocessor must follow
  // the "online" naming convention ALICE-INT-2003-039.
  shuttle->AddInputFile(AliTestShuttle::kDAQ, "ZDC", "PEDESTALS", "LDC0", "ZDCPedestal.dat");
  shuttle->AddInputFile(AliTestShuttle::kDAQ, "ZDC", "EMDCALIB", "LDC0", "ZDCEMDCalib.dat");

  // TODO(3)
  //
  // The shuttle can read run type stored in the DAQ logbook.
  // To test it, we must provide the run type manually. They will be retrieved in the preprocessor
  // using GetRunType function.
  shuttle->SetInputRunType("PEDESTALS");

  // TODO(4)
  //
  // The shuttle can read run parameters stored in the DAQ run logbook.
  // To test it, we must provide the run parameters manually. They will be retrieved in the preprocessor
  // using GetRunParameter function.
  // In real life the parameters will be retrieved automatically from the run logbook;
  shuttle->AddInputRunParameter("totalEvents", "1000");
  shuttle->AddInputRunParameter("NumberOfGDCs", "1");

  // TODO(5)
  //
  // The shuttle can query condition parameters valid from the current run from the OCDB
  // To test it, we must first store the object into the OCDB. It will be retrieved in the preprocessor
  // using GetFromOCDB function.

  TObjString obj("This is a condition parameter stored in OCDB");
  AliCDBId id("ZDC/Calib/Data", 0, AliCDBRunRange::Infinity());
  AliCDBMetaData md;
  AliCDBEntry entry(&obj, id, &md);

  shuttle->AddInputCDBEntry(&entry);

  // TODO(6)
  // Create the preprocessor that should be tested, it registers itself automatically to the shuttle
  AliPreprocessor* test = new AliZDCPreprocessor("ZDC",shuttle);

  // Test the preprocessor
  shuttle->Process();

  // TODO(7)
  // In the preprocessor AliShuttleInterface::Store should be called to put the final
  // data to the CDB. To check if all went fine have a look at the files produced in
  // $ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB/<detector>/SHUTTLE/Data
  //
  // Check the file which should have been created
  AliCDBEntry* chkEntry = AliCDBManager::Instance()->GetStorage(AliShuttleInterface::GetMainRefStorage())
  			->Get("ZDC/DCS/Data", 7);
  if (!chkEntry)
  {
    printf("The file is not there. Something went wrong.\n");
    return;
  }

  AliTestDataDCS* output = dynamic_cast<AliTestDataDCS*> (chkEntry->GetObject());
  // If everything went fine, draw the result
  if (output)
    output->Draw();
}

TMap* CreateDCSAliasMap()
{
  // Creates a DCS structure
  // The structure is the following:
  //   TMap (key --> value)
  //     <DCSAlias> --> <valueList>
  //     <DCSAlias> is a string
  //     <valueList> is a TObjArray of AliDCSValue
  //     An AliDCSValue consists of timestamp and a value in form of a AliSimpleValue

  // In this example 6 aliases exists: DCSAlias1 ... DCSAlias6
  // Each contains 1000 values randomly generated by TRandom::Gaus + 5*nAlias

  TMap* aliasMap = new TMap;
  aliasMap->SetOwner(1);

  TRandom random;
  TString aliasNames[26];

  // ******************************** alignment values
  aliasNames[0] = "ZDC_ZNA_POS.actual.position";
  aliasNames[1] = "ZDC_ZPA_POS.actual.position";
  aliasNames[2] = "ZDC_ZNC_POS.actual.position";
  aliasNames[3] = "ZDC_ZPC_POS.actual.position";
  //
  for(int nAlias=0; nAlias<4; nAlias++)
  {
    TObjArray* valueSet = new TObjArray;
    valueSet->SetOwner(1);

    TString aliasName = aliasNames[nAlias];
    printf("\n\n alias: %s\n\n",aliasName.Data());

    Float_t simVal = (Float_t) (random.Rndm()*0.025+random.Rndm()*0.1);
    for(int i=0;i<3;i++)
    {
      int timeStamp1[3] = {0,500,1000};
      AliDCSValue* dcsVal = new AliDCSValue(simVal, timeStamp1[i]);
      printf("%s\n",dcsVal->ToString());
      valueSet->Add(dcsVal);
    }
    aliasMap->Add(new TObjString(aliasName), valueSet);
  }
  // ******************************** HV values
  /*TString ZNAAlias = "ZNA_HV.actual.vMon";
  TString ZPAAlias = "ZPA_HV.actual.vMon";
  TString ZNCAlias = "ZNC_HV.actual.vMon";
  TString ZPCAlias = "ZPC_HV.actual.vMon";
  TString idat[5];
  for(int i=0;i<5;i++)
  {
    idat[i] = i;
    aliasNames[i+3]  = ZNAAlias.Insert(6,idat[i]);
    aliasNames[i+7]  = ZPAAlias.Insert(6,idat[i]);
    aliasNames[i+11] = ZNCAlias.Insert(6,idat[i]);
    aliasNames[i+15] = ZPCAlias.Insert(6,idat[i]);
  }*/
  aliasNames[4]  = "ZDC_ZNA_HV0.actual.vMon";
  aliasNames[5]  = "ZDC_ZNA_HV1.actual.vMon";
  aliasNames[6]  = "ZDC_ZNA_HV2.actual.vMon";
  aliasNames[7]  = "ZDC_ZNA_HV3.actual.vMon";
  aliasNames[8]  = "ZDC_ZNA_HV4.actual.vMon";
  //
  aliasNames[9]   = "ZDC_ZPA_HV0.actual.vMon";
  aliasNames[10]  = "ZDC_ZPA_HV1.actual.vMon";
  aliasNames[11]  = "ZDC_ZPA_HV2.actual.vMon";
  aliasNames[12]  = "ZDC_ZPA_HV3.actual.vMon";
  aliasNames[13]  = "ZDC_ZPA_HV4.actual.vMon";
  //
  aliasNames[14]  = "ZDC_ZNC_HV0.actual.vMon";
  aliasNames[15]  = "ZDC_ZNC_HV1.actual.vMon";
  aliasNames[16]  = "ZDC_ZNC_HV2.actual.vMon";
  aliasNames[17]  = "ZDC_ZNC_HV3.actual.vMon";
  aliasNames[18]  = "ZDC_ZNC_HV4.actual.vMon";
  //
  aliasNames[19]  = "ZDC_ZPC_HV0.actual.vMon";
  aliasNames[20]  = "ZDC_ZPC_HV1.actual.vMon";
  aliasNames[21]  = "ZDC_ZPC_HV2.actual.vMon";
  aliasNames[22]  = "ZDC_ZPC_HV3.actual.vMon";
  aliasNames[23]  = "ZDC_ZPC_HV4.actual.vMon";
  //
  aliasNames[24]  = "ZDC_ZEM1_HV0.actual.vMon";
  aliasNames[25]  = "ZDC_ZEM2_HV1.actual.vMon";
  //
  for(int nAlias=4;nAlias<26;nAlias++)
  {
    TObjArray* valueSet = new TObjArray;
    valueSet->SetOwner(1);

    TString aliasName = aliasNames[nAlias];
    printf("\n\n alias: %s\n\n",aliasName.Data());

    for(int timeStamp=0;timeStamp<=1000;timeStamp+=500)
    {
      Float_t simVal = (Float_t) (random.Gaus()*600.+1800.);
      AliDCSValue* dcsVal = new AliDCSValue(simVal, timeStamp);
      printf("%s\n",dcsVal->ToString());
      valueSet->Add(dcsVal);
    }
    aliasMap->Add(new TObjString(aliasName), valueSet);
  }

  return aliasMap;
}

TMap* ReadDCSAliasMap()
{
  // Open a file that contains DCS input data
  // The CDB framework is used to open the file, this means the file is located
  // in $ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB/<detector>/DCS/Data
  // The file contains an AliCDBEntry that contains a TMap with the DCS structure.
  // An explanation of the structure can be found in CreateDCSAliasMap()

  AliCDBEntry *entry = AliCDBManager::Instance()->Get("ZDC/DCS/Data", 0);
  return dynamic_cast<TMap*> (entry->GetObject());
}

void WriteDCSAliasMap()
{
  // This writes the output from CreateDCSAliasMap to a CDB file

  TMap* dcsAliasMap = CreateDCSAliasMap();

  AliCDBMetaData metaData;
	metaData.SetBeamPeriod(0);
	metaData.SetResponsible("Responsible person");
	metaData.SetComment("Test object for TestPreprocessor.C");

  AliCDBId id("ZDC/DCS/Data", 0, 0);

  // initialize location of CDB
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB");

  AliCDBManager::Instance()->Put(dcsAliasMap, id, &metaData);
}
<commit_msg>Updated test macro for ZDC Shuttle preprocessor<commit_after>/* $Id$ */

// This class runs the test preprocessor
// It uses AliTestShuttle to simulate a full Shuttle process

// The input data is created in the functions
//   CreateDCSAliasMap() creates input that would in the same way come from DCS
//   ReadDCSAliasMap() reads from a file
//   CreateInputFilesMap() creates a list of local files, that can be accessed by the shuttle

void TestZDCPreprocessor()
{
  // load library
  gSystem->Load("libTestShuttle.so");

  // create AliTestShuttle instance
  // The parameters are run, startTime, endTime
  AliTestShuttle* shuttle = new AliTestShuttle(7, 0, 1);

  // TODO if needed, change location of OCDB and Reference test folders
  // by default they are set to $ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB and TestReference
  AliTestShuttle::SetMainCDB("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB");
  AliTestShuttle::SetMainRefStorage("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestReference");

  printf("Test OCDB storage Uri: %s\n", AliShuttleInterface::GetMainCDB().Data());
  printf("Test Reference storage Uri: %s\n", AliShuttleInterface::GetMainRefStorage().Data());

  // TODO(1)
  //
  // The shuttle can read DCS data, if the preprocessor should be tested to process DCS data,
  // some fake data has to be created.
  //
  // The "fake" input data can be taken using either (a) or (b):
  // (a) data from a file: Use ReadDCSAliasMap()
  //     the format of the file is explained in ReadDCSAliasMap()
  //     To use it uncomment the following line:
  //
  //TMap* dcsAliasMap = ReadDCSAliasMap();
  //
  // (b) generated in this macro: Use CreateDCSAliasMap() and its documentation
  //     To use it uncomment the following line:
  //
  TMap* dcsAliasMap = CreateDCSAliasMap();
  //WriteDCSAliasMap();

  // now give the alias map to the shuttle
  shuttle->SetDCSInput(dcsAliasMap);

  // TODO(2)
  //
  // The shuttle can also process files that originate from DCS, DAQ and HLT.
  // To test it, we provide some local files and locations where these would be found when
  // the online machinery would be there.
  // In real life this functions would be produces by the sub-detectors
  // calibration programs in DCS, DAQ or HLT. These files can then be retrieved using the Shuttle.
  //
  // Files are added with the function AliTestShuttle::AddInputFile. The syntax is:
  // AddInputFile(<system>, <detector>, <id>, <source>, <local-file>)
  // In this example we add a file originating from the GDC with the id PEDESTALS
  // Three files originating from different LDCs but with the same id are also added
  // Note that the test preprocessor name is TPC. The name of the detector's preprocessor must follow
  // the "online" naming convention ALICE-INT-2003-039.
  shuttle->AddInputFile(AliTestShuttle::kDAQ, "ZDC", "PEDESTALS", "LDC0", "ZDCPedestal.dat");
  shuttle->AddInputFile(AliTestShuttle::kDAQ, "ZDC", "EMDCALIB",  "LDC0", "ZDCEMDCalib.dat");
  shuttle->AddInputFile(AliTestShuttle::kDAQ, "ZDC", "EMDCALIB",  "LDC0", "ZDCEMDEqual.dat");

  // TODO(3)
  //
  // The shuttle can read run type stored in the DAQ logbook.
  // To test it, we must provide the run type manually. They will be retrieved in the preprocessor
  // using GetRunType function.
//  shuttle->SetInputRunType("PEDESTALS");
  shuttle->SetInputRunType("PULSER_RUN");

  // TODO(4)
  //
  // The shuttle can read run parameters stored in the DAQ run logbook.
  // To test it, we must provide the run parameters manually. They will be retrieved in the preprocessor
  // using GetRunParameter function.
  // In real life the parameters will be retrieved automatically from the run logbook;
  shuttle->AddInputRunParameter("totalEvents", "1000");
  shuttle->AddInputRunParameter("NumberOfGDCs", "1");

  // TODO(5) NEW!
  //
  // This is for preprocessor that require data from HLT.
  // Since HLT may be switched off, the preprocessor should first query the Run logbook where
  // the HLT status is stored. SHUTTLE implements a shortcut function (GetHLTStatus) that returns
  // a bool directly. 1 = HLT ON, 0 = HLT OFF
  //
  Bool_t hltStatus=kFALSE;
  //shuttle->SetInputHLTStatus(hltStatus);

  // TODO(6)
  //
  // The shuttle can query condition parameters valid from the current run from the OCDB
  // To test it, we must first store the object into the OCDB. It will be retrieved in the preprocessor
  // using GetFromOCDB function.
/*
  TObjString obj("This is a condition parameter stored in OCDB");
  AliCDBId id("ZDC/Calib/Data", 0, AliCDBRunRange::Infinity());
  AliCDBMetaData md;
  AliCDBEntry entry(&obj, id, &md);

  shuttle->AddInputCDBEntry(&entry);
*/
  // TODO(6)
  // Create the preprocessor that should be tested, it registers itself automatically to the shuttle
  AliPreprocessor* test = new AliZDCPreprocessor(shuttle);

  // Test the preprocessor
  shuttle->Process();

  // TODO(7)
  // In the preprocessor AliShuttleInterface::Store should be called to put the final
  // data to the CDB. To check if all went fine have a look at the files produced in
  // $ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB/<detector>/SHUTTLE/Data
  //
  // Check the file which should have been created
  AliCDBEntry* chkEntry = AliCDBManager::Instance()->GetStorage(AliShuttleInterface::GetMainCDB())
  			->Get("ZDC/Calib/Data", 7);
  if (!chkEntry)
  {
    printf("The file is not there. Something went wrong.\n");
    return;
  }

  AliTestDataDCS* output = dynamic_cast<AliTestDataDCS*> (chkEntry->GetObject());
  // If everything went fine, draw the result
  if (output)
    output->Draw();
}

TMap* CreateDCSAliasMap()
{
  // Creates a DCS structure
  // The structure is the following:
  //   TMap (key --> value)
  //     <DCSAlias> --> <valueList>
  //     <DCSAlias> is a string
  //     <valueList> is a TObjArray of AliDCSValue
  //     An AliDCSValue consists of timestamp and a value in form of a AliSimpleValue

  // In this example 6 aliases exists: DCSAlias1 ... DCSAlias6
  // Each contains 1000 values randomly generated by TRandom::Gaus + 5*nAlias

  TMap* aliasMap = new TMap;
  aliasMap->SetOwner(1);

  TRandom random;
  TString aliasNames[28];

  // ******************************** alignment values
  aliasNames[0] = "ZDC_ZNA_POS.actual.position";
  aliasNames[1] = "ZDC_ZPA_POS.actual.position";
  aliasNames[2] = "ZDC_ZNC_POS.actual.position";
  aliasNames[3] = "ZDC_ZPC_POS.actual.position";
  //
  for(int nAlias=0; nAlias<4; nAlias++)
  {
    TObjArray* valueSet = new TObjArray;
    valueSet->SetOwner(1);

    TString aliasName = aliasNames[nAlias];
    printf("\n\n alias: %s\n\n",aliasName.Data());

    Float_t simVal = (Float_t) (random.Rndm()*0.025+random.Rndm()*0.1);
    for(int i=0;i<3;i++)
    {
      int timeStamp1[3] = {0,500,1000};
      AliDCSValue* dcsVal = new AliDCSValue(simVal, timeStamp1[i]);
      printf("%s\n",dcsVal->ToString());
      valueSet->Add(dcsVal);
    }
    aliasMap->Add(new TObjString(aliasName), valueSet);
  }
  // ******************************** HV values
  /*TString ZNAAlias = "ZNA_HV.actual.vMon";
  TString ZPAAlias = "ZPA_HV.actual.vMon";
  TString ZNCAlias = "ZNC_HV.actual.vMon";
  TString ZPCAlias = "ZPC_HV.actual.vMon";
  TString idat[5];
  for(int i=0;i<5;i++)
  {
    idat[i] = i;
    aliasNames[i+3]  = ZNAAlias.Insert(6,idat[i]);
    aliasNames[i+7]  = ZPAAlias.Insert(6,idat[i]);
    aliasNames[i+11] = ZNCAlias.Insert(6,idat[i]);
    aliasNames[i+15] = ZPCAlias.Insert(6,idat[i]);
  }*/
  aliasNames[4]  = "ZDC_ZNA_HV0.actual.vMon";
  aliasNames[5]  = "ZDC_ZNA_HV1.actual.vMon";
  aliasNames[6]  = "ZDC_ZNA_HV2.actual.vMon";
  aliasNames[7]  = "ZDC_ZNA_HV3.actual.vMon";
  aliasNames[8]  = "ZDC_ZNA_HV4.actual.vMon";
  //
  aliasNames[9]   = "ZDC_ZPA_HV0.actual.vMon";
  aliasNames[10]  = "ZDC_ZPA_HV1.actual.vMon";
  aliasNames[11]  = "ZDC_ZPA_HV2.actual.vMon";
  aliasNames[12]  = "ZDC_ZPA_HV3.actual.vMon";
  aliasNames[13]  = "ZDC_ZPA_HV4.actual.vMon";
  //
  aliasNames[14]  = "ZDC_ZNC_HV0.actual.vMon";
  aliasNames[15]  = "ZDC_ZNC_HV1.actual.vMon";
  aliasNames[16]  = "ZDC_ZNC_HV2.actual.vMon";
  aliasNames[17]  = "ZDC_ZNC_HV3.actual.vMon";
  aliasNames[18]  = "ZDC_ZNC_HV4.actual.vMon";
  //
  aliasNames[19]  = "ZDC_ZPC_HV0.actual.vMon";
  aliasNames[20]  = "ZDC_ZPC_HV1.actual.vMon";
  aliasNames[21]  = "ZDC_ZPC_HV2.actual.vMon";
  aliasNames[22]  = "ZDC_ZPC_HV3.actual.vMon";
  aliasNames[23]  = "ZDC_ZPC_HV4.actual.vMon";
  //
  aliasNames[24]  = "ZDC_ZEM_HV0.actual.vMon";
  aliasNames[25]  = "ZDC_ZEM_HV1.actual.vMon";
  //
  aliasNames[26]  = "ZDC_REFA_HV0.actual.vMon";
  aliasNames[27]  = "ZDC_REFC_HV1.actual.vMon";
  //
  for(int nAlias=4;nAlias<28;nAlias++)
  {
    TObjArray* valueSet = new TObjArray;
    valueSet->SetOwner(1);

    TString aliasName = aliasNames[nAlias];
    printf("\n\n alias: %s\n\n",aliasName.Data());

    for(int timeStamp=0;timeStamp<=1000;timeStamp+=500)
    {
      Float_t simVal = (Float_t) (random.Gaus()*600.+1800.);
      AliDCSValue* dcsVal = new AliDCSValue(simVal, timeStamp);
      printf("%s\n",dcsVal->ToString());
      valueSet->Add(dcsVal);
    }
    aliasMap->Add(new TObjString(aliasName), valueSet);
  }

  return aliasMap;
}

TMap* ReadDCSAliasMap()
{
  // Open a file that contains DCS input data
  // The CDB framework is used to open the file, this means the file is located
  // in $ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB/<detector>/DCS/Data
  // The file contains an AliCDBEntry that contains a TMap with the DCS structure.
  // An explanation of the structure can be found in CreateDCSAliasMap()

  AliCDBEntry *entry = AliCDBManager::Instance()->Get("ZDC/DCS/Data", 0);
  return dynamic_cast<TMap*> (entry->GetObject());
}

void WriteDCSAliasMap()
{
  // This writes the output from CreateDCSAliasMap to a CDB file

  TMap* dcsAliasMap = CreateDCSAliasMap();

  AliCDBMetaData metaData;
	metaData.SetBeamPeriod(0);
	metaData.SetResponsible("Responsible person");
	metaData.SetComment("Test object for TestPreprocessor.C");

  AliCDBId id("ZDC/DCS/Data", 0, 0);

  // initialize location of CDB
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB");

  AliCDBManager::Instance()->Put(dcsAliasMap, id, &metaData);
}
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file CallTip.cxx
 ** Code for displaying call tips.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>

#include "Platform.h"

#include "Scintilla.h"
#include "CallTip.h"

CallTip::CallTip() {
	wCallTip = 0;
	inCallTipMode = false;
	posStartCallTip = 0;
	val = 0;
	startHighlight = 0;
	endHighlight = 0;

	colourBG.desired = Colour(0xff, 0xff, 0xff);
	colourUnSel.desired = Colour(0x80, 0x80, 0x80);
	colourSel.desired = Colour(0, 0, 0x80);
	colourShade.desired = Colour(0, 0, 0);
	colourLight.desired = Colour(0xc0, 0xc0, 0xc0);
}

CallTip::~CallTip() {
	wCallTip.Destroy();
	delete []val;
	val = 0;
}

void CallTip::RefreshColourPalette(Palette &pal, bool want) {
	pal.WantFind(colourBG, want);
	pal.WantFind(colourUnSel, want);
	pal.WantFind(colourSel, want);
	pal.WantFind(colourShade, want);
	pal.WantFind(colourLight, want);
}

void CallTip::PaintCT(Surface *surfaceWindow) {
	if (!val)
		return;
	PRectangle rcClientPos = wCallTip.GetClientPosition();
	PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
	                        rcClientPos.bottom - rcClientPos.top);
	PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);

	surfaceWindow->FillRectangle(rcClient, colourBG.allocated);
	// To make a nice small call tip window, it is only sized to fit most normal characters without accents
	int lineHeight = surfaceWindow->Height(font);
	int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font);

	// For each line...
	// Draw the definition in three parts: before highlight, highlighted, after highlight
	int ytext = rcClient.top + ascent + 1;
	char *chunkVal = val;
	bool moreChunks = true;
	while (moreChunks) {
		char *chunkEnd = strchr(chunkVal, '\n');
		if (chunkEnd == NULL) {
			chunkEnd = chunkVal + strlen(chunkVal);
			moreChunks = false;
		}
		int chunkOffset = chunkVal - val;
		int chunkLength = chunkEnd - chunkVal;
		int chunkEndOffset = chunkOffset + chunkLength;
		int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset);
		thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset);
		thisStartHighlight -= chunkOffset;
		int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset);
		thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset);
		thisEndHighlight -= chunkOffset;
		int x = 5;
		int xEnd = x + surfaceWindow->WidthText(font, chunkVal, thisStartHighlight);
		rcClient.left = x;
		rcClient.top = ytext - ascent - 1;
		rcClient.right = xEnd;
		surfaceWindow->DrawText(rcClient, font, ytext,
		                        chunkVal, thisStartHighlight,
		                        colourUnSel.allocated, colourBG.allocated);
		x = xEnd;

		xEnd = x + surfaceWindow->WidthText(font, chunkVal + thisStartHighlight,
		                                    thisEndHighlight - thisStartHighlight);
		rcClient.top = ytext;
		rcClient.left = x;
		rcClient.right = xEnd;
		surfaceWindow->DrawText(rcClient, font, ytext,
		                        chunkVal + thisStartHighlight, thisEndHighlight - thisStartHighlight,
		                        colourSel.allocated, colourBG.allocated);
		x = xEnd;

		xEnd = x + surfaceWindow->WidthText(font, chunkVal + thisEndHighlight,
		                                    chunkLength - thisEndHighlight);
		rcClient.left = x;
		rcClient.right = xEnd;
		surfaceWindow->DrawText(rcClient, font, ytext,
		                        chunkVal + thisEndHighlight, chunkLength - thisEndHighlight,
		                        colourUnSel.allocated, colourBG.allocated);
		chunkVal = chunkEnd + 1;
		ytext += lineHeight;
	}
	// Draw a raised border around the edges of the window
	surfaceWindow->MoveTo(0, rcClientSize.bottom - 1);
	surfaceWindow->PenColour(colourShade.allocated);
	surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1);
	surfaceWindow->LineTo(rcClientSize.right - 1, 0);
	surfaceWindow->PenColour(colourLight.allocated);
	surfaceWindow->LineTo(0, 0);
	surfaceWindow->LineTo(0, rcClientSize.bottom - 1);
}

PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn,
                                 const char *faceName, int size) {
	Surface surfaceMeasure;
	surfaceMeasure.Init();
	int deviceHeight = (size * surfaceMeasure.LogPixelsY()) / 72;
	font.Create(faceName, SC_CHARSET_DEFAULT, deviceHeight, false, false);
	if (val)
		delete []val;
	val = new char[strlen(defn) + 1];
	if (!val)
		return PRectangle();
	strcpy(val, defn);
	startHighlight = 0;
	endHighlight = 0;
	inCallTipMode = true;
	posStartCallTip = pos;
	// Look for multiple lines in the text
	// Only support \n here - simply means container must avoid \r!
	int width = 0;
	int numLines = 1;
	const char *newline;
	const char *look = val;
	while ((newline = strchr(look, '\n')) != NULL) {
		int thisWidth = surfaceMeasure.WidthText(font, look, newline - look);
		width = Platform::Maximum(width, thisWidth);
		look = newline + 1;
		numLines++;
	}
	int lastWidth = surfaceMeasure.WidthText(font, look, strlen(look));
	width = Platform::Maximum(width, lastWidth) + 10;
	int lineHeight = surfaceMeasure.Height(font);
	// Extra line for border and an empty line at top and bottom
	int height = lineHeight * numLines - surfaceMeasure.InternalLeading(font) + 2 + 2;
	return PRectangle(pt.x -5, pt.y + lineHeight + 1, pt.x + width - 5, pt.y + lineHeight + 1 + height);
}

void CallTip::CallTipCancel() {
	inCallTipMode = false;
	if (wCallTip.Created()) {
		wCallTip.Destroy();
	}
}

void CallTip::SetHighlight(int start, int end) {
	// Avoid flashing by checking something has really changed
	if ((start != startHighlight) || (end != endHighlight)) {
		startHighlight = start;
		endHighlight = end;
		if (wCallTip.Created()) {
			wCallTip.InvalidateAll();
		}
	}
}
<commit_msg>Fixed font leak.<commit_after>// Scintilla source code edit control
/** @file CallTip.cxx
 ** Code for displaying call tips.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>

#include "Platform.h"

#include "Scintilla.h"
#include "CallTip.h"

CallTip::CallTip() {
	wCallTip = 0;
	inCallTipMode = false;
	posStartCallTip = 0;
	val = 0;
	startHighlight = 0;
	endHighlight = 0;

	colourBG.desired = Colour(0xff, 0xff, 0xff);
	colourUnSel.desired = Colour(0x80, 0x80, 0x80);
	colourSel.desired = Colour(0, 0, 0x80);
	colourShade.desired = Colour(0, 0, 0);
	colourLight.desired = Colour(0xc0, 0xc0, 0xc0);
}

CallTip::~CallTip() {
    font.Release();
	wCallTip.Destroy();
	delete []val;
	val = 0;
}

void CallTip::RefreshColourPalette(Palette &pal, bool want) {
	pal.WantFind(colourBG, want);
	pal.WantFind(colourUnSel, want);
	pal.WantFind(colourSel, want);
	pal.WantFind(colourShade, want);
	pal.WantFind(colourLight, want);
}

void CallTip::PaintCT(Surface *surfaceWindow) {
	if (!val)
		return;
	PRectangle rcClientPos = wCallTip.GetClientPosition();
	PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
	                        rcClientPos.bottom - rcClientPos.top);
	PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);

	surfaceWindow->FillRectangle(rcClient, colourBG.allocated);
	// To make a nice small call tip window, it is only sized to fit most normal characters without accents
	int lineHeight = surfaceWindow->Height(font);
	int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font);

	// For each line...
	// Draw the definition in three parts: before highlight, highlighted, after highlight
	int ytext = rcClient.top + ascent + 1;
	char *chunkVal = val;
	bool moreChunks = true;
	while (moreChunks) {
		char *chunkEnd = strchr(chunkVal, '\n');
		if (chunkEnd == NULL) {
			chunkEnd = chunkVal + strlen(chunkVal);
			moreChunks = false;
		}
		int chunkOffset = chunkVal - val;
		int chunkLength = chunkEnd - chunkVal;
		int chunkEndOffset = chunkOffset + chunkLength;
		int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset);
		thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset);
		thisStartHighlight -= chunkOffset;
		int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset);
		thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset);
		thisEndHighlight -= chunkOffset;
		int x = 5;
		int xEnd = x + surfaceWindow->WidthText(font, chunkVal, thisStartHighlight);
		rcClient.left = x;
		rcClient.top = ytext - ascent - 1;
		rcClient.right = xEnd;
		surfaceWindow->DrawText(rcClient, font, ytext,
		                        chunkVal, thisStartHighlight,
		                        colourUnSel.allocated, colourBG.allocated);
		x = xEnd;

		xEnd = x + surfaceWindow->WidthText(font, chunkVal + thisStartHighlight,
		                                    thisEndHighlight - thisStartHighlight);
		rcClient.top = ytext;
		rcClient.left = x;
		rcClient.right = xEnd;
		surfaceWindow->DrawText(rcClient, font, ytext,
		                        chunkVal + thisStartHighlight, thisEndHighlight - thisStartHighlight,
		                        colourSel.allocated, colourBG.allocated);
		x = xEnd;

		xEnd = x + surfaceWindow->WidthText(font, chunkVal + thisEndHighlight,
		                                    chunkLength - thisEndHighlight);
		rcClient.left = x;
		rcClient.right = xEnd;
		surfaceWindow->DrawText(rcClient, font, ytext,
		                        chunkVal + thisEndHighlight, chunkLength - thisEndHighlight,
		                        colourUnSel.allocated, colourBG.allocated);
		chunkVal = chunkEnd + 1;
		ytext += lineHeight;
	}
	// Draw a raised border around the edges of the window
	surfaceWindow->MoveTo(0, rcClientSize.bottom - 1);
	surfaceWindow->PenColour(colourShade.allocated);
	surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1);
	surfaceWindow->LineTo(rcClientSize.right - 1, 0);
	surfaceWindow->PenColour(colourLight.allocated);
	surfaceWindow->LineTo(0, 0);
	surfaceWindow->LineTo(0, rcClientSize.bottom - 1);
}

PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn,
                                 const char *faceName, int size) {
	Surface surfaceMeasure;
	surfaceMeasure.Init();
	int deviceHeight = (size * surfaceMeasure.LogPixelsY()) / 72;
	font.Create(faceName, SC_CHARSET_DEFAULT, deviceHeight, false, false);
	if (val)
		delete []val;
	val = new char[strlen(defn) + 1];
	if (!val)
		return PRectangle();
	strcpy(val, defn);
	startHighlight = 0;
	endHighlight = 0;
	inCallTipMode = true;
	posStartCallTip = pos;
	// Look for multiple lines in the text
	// Only support \n here - simply means container must avoid \r!
	int width = 0;
	int numLines = 1;
	const char *newline;
	const char *look = val;
	while ((newline = strchr(look, '\n')) != NULL) {
		int thisWidth = surfaceMeasure.WidthText(font, look, newline - look);
		width = Platform::Maximum(width, thisWidth);
		look = newline + 1;
		numLines++;
	}
	int lastWidth = surfaceMeasure.WidthText(font, look, strlen(look));
	width = Platform::Maximum(width, lastWidth) + 10;
	int lineHeight = surfaceMeasure.Height(font);
	// Extra line for border and an empty line at top and bottom
	int height = lineHeight * numLines - surfaceMeasure.InternalLeading(font) + 2 + 2;
	return PRectangle(pt.x -5, pt.y + lineHeight + 1, pt.x + width - 5, pt.y + lineHeight + 1 + height);
}

void CallTip::CallTipCancel() {
	inCallTipMode = false;
	if (wCallTip.Created()) {
		wCallTip.Destroy();
	}
}

void CallTip::SetHighlight(int start, int end) {
	// Avoid flashing by checking something has really changed
	if ((start != startHighlight) || (end != endHighlight)) {
		startHighlight = start;
		endHighlight = end;
		if (wCallTip.Created()) {
			wCallTip.InvalidateAll();
		}
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/chrome_url_data_manager.h"

#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/ref_counted_util.h"
#include "googleurl/src/url_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_job.h"
#ifdef CHROME_PERSONALIZATION
// TODO(timsteele): Remove all CHROME_PERSONALIZATION code in this file.
// It is only temporarily needed to configure some personalization data sources
// that will go away soon.
#include "chrome/personalization/personalization.h"
#endif

// The URL scheme used for internal chrome resources.
// TODO(glen): Choose a better location for this.
static const char kChromeURLScheme[] = "chrome-ui";

// The single global instance of ChromeURLDataManager.
ChromeURLDataManager chrome_url_data_manager;

// URLRequestChromeJob is a URLRequestJob that manages running chrome-internal
// resource requests asynchronously.
// It hands off URL requests to ChromeURLDataManager, which asynchronously
// calls back once the data is available.
class URLRequestChromeJob : public URLRequestJob {
 public:
  explicit URLRequestChromeJob(URLRequest* request);
  virtual ~URLRequestChromeJob();

  // URLRequestJob implementation.
  virtual void Start();
  virtual void Kill();
  virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
  virtual bool GetMimeType(std::string* mime_type);

  // Called by ChromeURLDataManager to notify us that the data blob is ready
  // for us.
  void DataAvailable(RefCountedBytes* bytes);

  void SetMimeType(const std::string& mime_type) {
    mime_type_ = mime_type;
  }

 private:
  // Helper for Start(), to let us start asynchronously.
  // (This pattern is shared by most URLRequestJob implementations.)
  void StartAsync();

  // Do the actual copy from data_ (the data we're serving) into |buf|.
  // Separate from ReadRawData so we can handle async I/O.
  void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read);

  // The actual data we're serving.  NULL until it's been fetched.
  scoped_refptr<RefCountedBytes> data_;
  // The current offset into the data that we're handing off to our
  // callers via the Read interfaces.
  int data_offset_;

  // For async reads, we keep around a pointer to the buffer that
  // we're reading into.
  scoped_refptr<net::IOBuffer> pending_buf_;
  int pending_buf_size_;
  std::string mime_type_;

  DISALLOW_EVIL_CONSTRUCTORS(URLRequestChromeJob);
};

// URLRequestChromeFileJob is a URLRequestJob that acts like a file:// URL
class URLRequestChromeFileJob : public URLRequestFileJob {
 public:
  URLRequestChromeFileJob(URLRequest* request, const FilePath& path);
  virtual ~URLRequestChromeFileJob();

 private:
  DISALLOW_EVIL_CONSTRUCTORS(URLRequestChromeFileJob);
};

void RegisterURLRequestChromeJob() {
  // Being a standard scheme allows us to resolve relative paths. This method
  // is invoked multiple times during testing, so only add the scheme once.
  url_parse::Component url_scheme_component(0, arraysize(kChromeURLScheme) - 1);
  if (!url_util::IsStandard(kChromeURLScheme, arraysize(kChromeURLScheme) - 1,
                            url_scheme_component)) {
    url_util::AddStandardScheme(kChromeURLScheme);
  }

  std::wstring inspector_dir;
  if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
    chrome_url_data_manager.AddFileSource("inspector", inspector_dir);

  URLRequest::RegisterProtocolFactory(kChromeURLScheme,
                                      &ChromeURLDataManager::Factory);
#ifdef CHROME_PERSONALIZATION
  url_util::AddStandardScheme(kPersonalizationScheme);
  URLRequest::RegisterProtocolFactory(kPersonalizationScheme,
                                      &ChromeURLDataManager::Factory);
#endif
}

void UnregisterURLRequestChromeJob() {
  std::wstring inspector_dir;
  if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
    chrome_url_data_manager.RemoveFileSource("inspector");
}

// static
void ChromeURLDataManager::URLToRequest(const GURL& url,
                                        std::string* source_name,
                                        std::string* path) {
#ifdef CHROME_PERSONALIZATION
  DCHECK(url.SchemeIs(kChromeURLScheme) ||
         url.SchemeIs(kPersonalizationScheme));
#else
  DCHECK(url.SchemeIs(kChromeURLScheme));
#endif

  if (!url.is_valid()) {
    NOTREACHED();
    return;
  }

  // Our input looks like: chrome-ui://source_name/extra_bits?foo .
  // So the url's "host" is our source, and everything after the host is
  // the path.
  source_name->assign(url.host());

  const std::string& spec = url.possibly_invalid_spec();
  const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
  int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false);
  ++offset;  // Skip the slash at the beginning of the path.
  if (offset < static_cast<int>(spec.size()))
    path->assign(spec.substr(offset));
}

// static
bool ChromeURLDataManager::URLToFilePath(const GURL& url,
                                         std::wstring* file_path) {
  // Parse the URL into a request for a source and path.
  std::string source_name;
  std::string relative_path;
  URLToRequest(url, &source_name, &relative_path);

  FileSourceMap::const_iterator i(
      chrome_url_data_manager.file_sources_.find(source_name));
  if (i == chrome_url_data_manager.file_sources_.end())
    return false;

  file_path->assign(i->second);
  file_util::AppendToPath(file_path, UTF8ToWide(relative_path));
  return true;
}

ChromeURLDataManager::ChromeURLDataManager() : next_request_id_(0) { }

ChromeURLDataManager::~ChromeURLDataManager() { }

void ChromeURLDataManager::AddDataSource(scoped_refptr<DataSource> source) {
  // TODO(jackson): A new data source with same name should not clobber the
  // existing one.
  data_sources_[source->source_name()] = source;
}

void ChromeURLDataManager::AddFileSource(const std::string& source_name,
                                         const std::wstring& file_path) {
  DCHECK(file_sources_.count(source_name) == 0);
  file_sources_[source_name] = file_path;
}

void ChromeURLDataManager::RemoveFileSource(const std::string& source_name) {
  DCHECK(file_sources_.count(source_name) == 1);
  file_sources_.erase(source_name);
}

bool ChromeURLDataManager::StartRequest(const GURL& url,
                                        URLRequestChromeJob* job) {
  // Parse the URL into a request for a source and path.
  std::string source_name;
  std::string path;
  URLToRequest(url, &source_name, &path);

  // Look up the data source for the request.
  DataSourceMap::iterator i = data_sources_.find(source_name);
  if (i == data_sources_.end())
    return false;
  DataSource* source = i->second;

  // Save this request so we know where to send the data.
  RequestID request_id = next_request_id_++;
  pending_requests_.insert(std::make_pair(request_id, job));

  // TODO(eroman): would be nicer if the mimetype were set at the same time
  // as the data blob. For now do it here, since NotifyHeadersComplete() is
  // going to get called once we return.
  job->SetMimeType(source->GetMimeType(path));

  // Forward along the request to the data source.
  source->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(source, &DataSource::StartDataRequest,
                        path, request_id));
  return true;
}

void ChromeURLDataManager::RemoveRequest(URLRequestChromeJob* job) {
  // Remove the request from our list of pending requests.
  // If/when the source sends the data that was requested, the data will just
  // be thrown away.
  for (PendingRequestMap::iterator i = pending_requests_.begin();
       i != pending_requests_.end(); ++i) {
    if (i->second == job) {
      pending_requests_.erase(i);
      return;
    }
  }
}

void ChromeURLDataManager::DataAvailable(
    RequestID request_id,
    scoped_refptr<RefCountedBytes> bytes) {
  // Forward this data on to the pending URLRequest, if it exists.
  PendingRequestMap::iterator i = pending_requests_.find(request_id);
  if (i != pending_requests_.end()) {
    URLRequestChromeJob* job = i->second;
    pending_requests_.erase(i);
    job->DataAvailable(bytes);
  }
}

void ChromeURLDataManager::DataSource::SendResponse(
    RequestID request_id,
    RefCountedBytes* bytes) {
  g_browser_process->io_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(&chrome_url_data_manager,
                        &ChromeURLDataManager::DataAvailable,
                        request_id, scoped_refptr<RefCountedBytes>(bytes)));
}

// static
URLRequestJob* ChromeURLDataManager::Factory(URLRequest* request,
                                             const std::string& scheme) {
  // Try first with a file handler
  std::wstring path;
  if (ChromeURLDataManager::URLToFilePath(request->url(), &path))
    return new URLRequestChromeFileJob(request,
                                       FilePath::FromWStringHack(path));

  // Fall back to using a custom handler
  return new URLRequestChromeJob(request);
}

URLRequestChromeJob::URLRequestChromeJob(URLRequest* request)
    : URLRequestJob(request), data_offset_(0) {}

URLRequestChromeJob::~URLRequestChromeJob() {
}

void URLRequestChromeJob::Start() {
  // Start reading asynchronously so that all error reporting and data
  // callbacks happen as they would for network requests.
  MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
      this, &URLRequestChromeJob::StartAsync));
}

void URLRequestChromeJob::Kill() {
  chrome_url_data_manager.RemoveRequest(this);
}

bool URLRequestChromeJob::GetMimeType(std::string* mime_type) {
  *mime_type = mime_type_;
  return !mime_type_.empty();
}

void URLRequestChromeJob::DataAvailable(RefCountedBytes* bytes) {
  if (bytes) {
    // The request completed, and we have all the data.
    // Clear any IO pending status.
    SetStatus(URLRequestStatus());

    data_ = bytes;
    int bytes_read;
    if (pending_buf_.get()) {
      CompleteRead(pending_buf_, pending_buf_size_, &bytes_read);
      NotifyReadComplete(bytes_read);
      pending_buf_ = NULL;
    }
  } else {
    // The request failed.
    NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, 0));
  }
}

bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size,
                                      int* bytes_read) {
  if (!data_.get()) {
    SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
    DCHECK(!pending_buf_.get());
    pending_buf_ = buf;
    pending_buf_size_ = buf_size;
    return false;  // Tell the caller we're still waiting for data.
  }

  // Otherwise, the data is available.
  CompleteRead(buf, buf_size, bytes_read);
  return true;
}

void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size,
                                       int* bytes_read) {
  int remaining = static_cast<int>(data_->data.size()) - data_offset_;
  if (buf_size > remaining)
    buf_size = remaining;
  if (buf_size > 0) {
    memcpy(buf->data(), &data_->data[0] + data_offset_, buf_size);
    data_offset_ += buf_size;
  }
  *bytes_read = buf_size;
}

void URLRequestChromeJob::StartAsync() {
  if (!request_)
    return;

  if (chrome_url_data_manager.StartRequest(request_->url(), this)) {
    NotifyHeadersComplete();
  } else {
    NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,
                                      net::ERR_INVALID_URL));
  }
}

URLRequestChromeFileJob::URLRequestChromeFileJob(URLRequest* request,
                                                 const FilePath& path)
    : URLRequestFileJob(request, path) {
}

URLRequestChromeFileJob::~URLRequestChromeFileJob() { }

<commit_msg>Fix a browser crash when the URLRequestChromeJob goes away from the NotifyReadComplete notification.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/chrome_url_data_manager.h"

#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/ref_counted_util.h"
#include "googleurl/src/url_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_job.h"
#ifdef CHROME_PERSONALIZATION
// TODO(timsteele): Remove all CHROME_PERSONALIZATION code in this file.
// It is only temporarily needed to configure some personalization data sources
// that will go away soon.
#include "chrome/personalization/personalization.h"
#endif

// The URL scheme used for internal chrome resources.
// TODO(glen): Choose a better location for this.
static const char kChromeURLScheme[] = "chrome-ui";

// The single global instance of ChromeURLDataManager.
ChromeURLDataManager chrome_url_data_manager;

// URLRequestChromeJob is a URLRequestJob that manages running chrome-internal
// resource requests asynchronously.
// It hands off URL requests to ChromeURLDataManager, which asynchronously
// calls back once the data is available.
class URLRequestChromeJob : public URLRequestJob {
 public:
  explicit URLRequestChromeJob(URLRequest* request);
  virtual ~URLRequestChromeJob();

  // URLRequestJob implementation.
  virtual void Start();
  virtual void Kill();
  virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
  virtual bool GetMimeType(std::string* mime_type);

  // Called by ChromeURLDataManager to notify us that the data blob is ready
  // for us.
  void DataAvailable(RefCountedBytes* bytes);

  void SetMimeType(const std::string& mime_type) {
    mime_type_ = mime_type;
  }

 private:
  // Helper for Start(), to let us start asynchronously.
  // (This pattern is shared by most URLRequestJob implementations.)
  void StartAsync();

  // Do the actual copy from data_ (the data we're serving) into |buf|.
  // Separate from ReadRawData so we can handle async I/O.
  void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read);

  // The actual data we're serving.  NULL until it's been fetched.
  scoped_refptr<RefCountedBytes> data_;
  // The current offset into the data that we're handing off to our
  // callers via the Read interfaces.
  int data_offset_;

  // For async reads, we keep around a pointer to the buffer that
  // we're reading into.
  scoped_refptr<net::IOBuffer> pending_buf_;
  int pending_buf_size_;
  std::string mime_type_;

  DISALLOW_EVIL_CONSTRUCTORS(URLRequestChromeJob);
};

// URLRequestChromeFileJob is a URLRequestJob that acts like a file:// URL
class URLRequestChromeFileJob : public URLRequestFileJob {
 public:
  URLRequestChromeFileJob(URLRequest* request, const FilePath& path);
  virtual ~URLRequestChromeFileJob();

 private:
  DISALLOW_EVIL_CONSTRUCTORS(URLRequestChromeFileJob);
};

void RegisterURLRequestChromeJob() {
  // Being a standard scheme allows us to resolve relative paths. This method
  // is invoked multiple times during testing, so only add the scheme once.
  url_parse::Component url_scheme_component(0, arraysize(kChromeURLScheme) - 1);
  if (!url_util::IsStandard(kChromeURLScheme, arraysize(kChromeURLScheme) - 1,
                            url_scheme_component)) {
    url_util::AddStandardScheme(kChromeURLScheme);
  }

  std::wstring inspector_dir;
  if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
    chrome_url_data_manager.AddFileSource("inspector", inspector_dir);

  URLRequest::RegisterProtocolFactory(kChromeURLScheme,
                                      &ChromeURLDataManager::Factory);
#ifdef CHROME_PERSONALIZATION
  url_util::AddStandardScheme(kPersonalizationScheme);
  URLRequest::RegisterProtocolFactory(kPersonalizationScheme,
                                      &ChromeURLDataManager::Factory);
#endif
}

void UnregisterURLRequestChromeJob() {
  std::wstring inspector_dir;
  if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
    chrome_url_data_manager.RemoveFileSource("inspector");
}

// static
void ChromeURLDataManager::URLToRequest(const GURL& url,
                                        std::string* source_name,
                                        std::string* path) {
#ifdef CHROME_PERSONALIZATION
  DCHECK(url.SchemeIs(kChromeURLScheme) ||
         url.SchemeIs(kPersonalizationScheme));
#else
  DCHECK(url.SchemeIs(kChromeURLScheme));
#endif

  if (!url.is_valid()) {
    NOTREACHED();
    return;
  }

  // Our input looks like: chrome-ui://source_name/extra_bits?foo .
  // So the url's "host" is our source, and everything after the host is
  // the path.
  source_name->assign(url.host());

  const std::string& spec = url.possibly_invalid_spec();
  const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
  int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false);
  ++offset;  // Skip the slash at the beginning of the path.
  if (offset < static_cast<int>(spec.size()))
    path->assign(spec.substr(offset));
}

// static
bool ChromeURLDataManager::URLToFilePath(const GURL& url,
                                         std::wstring* file_path) {
  // Parse the URL into a request for a source and path.
  std::string source_name;
  std::string relative_path;
  URLToRequest(url, &source_name, &relative_path);

  FileSourceMap::const_iterator i(
      chrome_url_data_manager.file_sources_.find(source_name));
  if (i == chrome_url_data_manager.file_sources_.end())
    return false;

  file_path->assign(i->second);
  file_util::AppendToPath(file_path, UTF8ToWide(relative_path));
  return true;
}

ChromeURLDataManager::ChromeURLDataManager() : next_request_id_(0) { }

ChromeURLDataManager::~ChromeURLDataManager() { }

void ChromeURLDataManager::AddDataSource(scoped_refptr<DataSource> source) {
  // TODO(jackson): A new data source with same name should not clobber the
  // existing one.
  data_sources_[source->source_name()] = source;
}

void ChromeURLDataManager::AddFileSource(const std::string& source_name,
                                         const std::wstring& file_path) {
  DCHECK(file_sources_.count(source_name) == 0);
  file_sources_[source_name] = file_path;
}

void ChromeURLDataManager::RemoveFileSource(const std::string& source_name) {
  DCHECK(file_sources_.count(source_name) == 1);
  file_sources_.erase(source_name);
}

bool ChromeURLDataManager::StartRequest(const GURL& url,
                                        URLRequestChromeJob* job) {
  // Parse the URL into a request for a source and path.
  std::string source_name;
  std::string path;
  URLToRequest(url, &source_name, &path);

  // Look up the data source for the request.
  DataSourceMap::iterator i = data_sources_.find(source_name);
  if (i == data_sources_.end())
    return false;
  DataSource* source = i->second;

  // Save this request so we know where to send the data.
  RequestID request_id = next_request_id_++;
  pending_requests_.insert(std::make_pair(request_id, job));

  // TODO(eroman): would be nicer if the mimetype were set at the same time
  // as the data blob. For now do it here, since NotifyHeadersComplete() is
  // going to get called once we return.
  job->SetMimeType(source->GetMimeType(path));

  // Forward along the request to the data source.
  source->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(source, &DataSource::StartDataRequest,
                        path, request_id));
  return true;
}

void ChromeURLDataManager::RemoveRequest(URLRequestChromeJob* job) {
  // Remove the request from our list of pending requests.
  // If/when the source sends the data that was requested, the data will just
  // be thrown away.
  for (PendingRequestMap::iterator i = pending_requests_.begin();
       i != pending_requests_.end(); ++i) {
    if (i->second == job) {
      pending_requests_.erase(i);
      return;
    }
  }
}

void ChromeURLDataManager::DataAvailable(
    RequestID request_id,
    scoped_refptr<RefCountedBytes> bytes) {
  // Forward this data on to the pending URLRequest, if it exists.
  PendingRequestMap::iterator i = pending_requests_.find(request_id);
  if (i != pending_requests_.end()) {
    // We acquire a reference to the job so that it doesn't disappear under the
    // feet of any method invoked here (we could trigger a callback).
    scoped_refptr<URLRequestChromeJob> job = i->second;
    pending_requests_.erase(i);
    job->DataAvailable(bytes);
  }
}

void ChromeURLDataManager::DataSource::SendResponse(
    RequestID request_id,
    RefCountedBytes* bytes) {
  g_browser_process->io_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(&chrome_url_data_manager,
                        &ChromeURLDataManager::DataAvailable,
                        request_id, scoped_refptr<RefCountedBytes>(bytes)));
}

// static
URLRequestJob* ChromeURLDataManager::Factory(URLRequest* request,
                                             const std::string& scheme) {
  // Try first with a file handler
  std::wstring path;
  if (ChromeURLDataManager::URLToFilePath(request->url(), &path))
    return new URLRequestChromeFileJob(request,
                                       FilePath::FromWStringHack(path));

  // Fall back to using a custom handler
  return new URLRequestChromeJob(request);
}

URLRequestChromeJob::URLRequestChromeJob(URLRequest* request)
    : URLRequestJob(request), data_offset_(0) {}

URLRequestChromeJob::~URLRequestChromeJob() {
}

void URLRequestChromeJob::Start() {
  // Start reading asynchronously so that all error reporting and data
  // callbacks happen as they would for network requests.
  MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
      this, &URLRequestChromeJob::StartAsync));
}

void URLRequestChromeJob::Kill() {
  chrome_url_data_manager.RemoveRequest(this);
}

bool URLRequestChromeJob::GetMimeType(std::string* mime_type) {
  *mime_type = mime_type_;
  return !mime_type_.empty();
}

void URLRequestChromeJob::DataAvailable(RefCountedBytes* bytes) {
  if (bytes) {
    // The request completed, and we have all the data.
    // Clear any IO pending status.
    SetStatus(URLRequestStatus());

    data_ = bytes;
    int bytes_read;
    if (pending_buf_.get()) {
      CompleteRead(pending_buf_, pending_buf_size_, &bytes_read);
      pending_buf_ = NULL;
      NotifyReadComplete(bytes_read);
    }
  } else {
    // The request failed.
    NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, 0));
  }
}

bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size,
                                      int* bytes_read) {
  if (!data_.get()) {
    SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
    DCHECK(!pending_buf_.get());
    pending_buf_ = buf;
    pending_buf_size_ = buf_size;
    return false;  // Tell the caller we're still waiting for data.
  }

  // Otherwise, the data is available.
  CompleteRead(buf, buf_size, bytes_read);
  return true;
}

void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size,
                                       int* bytes_read) {
  int remaining = static_cast<int>(data_->data.size()) - data_offset_;
  if (buf_size > remaining)
    buf_size = remaining;
  if (buf_size > 0) {
    memcpy(buf->data(), &data_->data[0] + data_offset_, buf_size);
    data_offset_ += buf_size;
  }
  *bytes_read = buf_size;
}

void URLRequestChromeJob::StartAsync() {
  if (!request_)
    return;

  if (chrome_url_data_manager.StartRequest(request_->url(), this)) {
    NotifyHeadersComplete();
  } else {
    NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,
                                      net::ERR_INVALID_URL));
  }
}

URLRequestChromeFileJob::URLRequestChromeFileJob(URLRequest* request,
                                                 const FilePath& path)
    : URLRequestFileJob(request, path) {
}

URLRequestChromeFileJob::~URLRequestChromeFileJob() { }

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kernel/doorbell.C $                                       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2018                        */
/* [+] 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                                                     */
#include <stdint.h>
#include <arch/ppc.H>
#include <kernel/task.H>
#include <kernel/taskmgr.H>
#include <kernel/cpu.H>
#include <kernel/doorbell.H>
#include <kernel/console.H>
#include <kernel/cpumgr.H>

void doorbell_clear()
{
    register uint64_t msgtype = _DOORBELL_MSG_TYPE;
    asm volatile("msgclr %0" :: "r" (msgtype));

    return;
}

void doorbell_broadcast()
{
    /*TODO RTC 152189
    size_t threadCount = CpuManager::getThreadCount();

    uint64_t msgtype = _DOORBELL_MSG_TYPE;
    uint64_t thread = getPIR() & (threadCount - 1);
    for (size_t i = 0; i < threadCount; ++i)
    {
        if (i != thread)
        {
            register uint64_t msg = msgtype | i;
            asm volatile("msgsnd %0" :: "r" (msg));
        }
    }
    **/
}

void doorbell_send(uint64_t i_pir)
{
    uint64_t msgtype = _DOORBELL_MSG_TYPE;
    register uint64_t msg = msgtype | i_pir;
    asm volatile("msgsnd %0" :: "r" (msg));

    return;
}

void send_doorbell_wakeup(uint64_t i_pir)
{
    cpu_t *l_cpu = CpuManager::getCpu(i_pir);

    printkd("send_doorbell_wakeup to pir: %lx\n", i_pir);
    //Create WorkItem and put on the stack to be executed during doorbell
    // execution
    KernelWorkItem* l_work = new CpuWakeupDoorbellWorkItem();
    l_cpu->doorbell_actions.push(l_work);
    //Send doorbell to wakeup core/thread
    doorbell_send(i_pir);
}

void send_doorbell_restore_tb(uint64_t i_pir, uint64_t i_tb)
{
    cpu_t *l_cpu = CpuManager::getCpu(i_pir);
    l_cpu->cpu_restore_tb = i_tb;

    printkd("send_doorbell_restore_tb to pir: %lx\n", i_pir);
    //Create WorkItem and put on the stack to be executed during doorbell
    // execution
    KernelWorkItem* l_work = new CpuTbRestoreDoorbellWorkItem();
    l_cpu->doorbell_actions.push(l_work);
    //Send doorbell to wakeup core/thread
    doorbell_send(i_pir);
}

void send_doorbell_ipc(uint64_t i_pir)
{
    printk("send_doorbell_ipc to pir: %lx\n", i_pir);
    doorbell_send(i_pir);
}
<commit_msg>Add sync to doorbell function to avoid weak consistency bug<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kernel/doorbell.C $                                       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,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                                                     */
#include <stdint.h>
#include <arch/ppc.H>
#include <kernel/task.H>
#include <kernel/taskmgr.H>
#include <kernel/cpu.H>
#include <kernel/doorbell.H>
#include <kernel/console.H>
#include <kernel/cpumgr.H>

void doorbell_clear()
{
    register uint64_t msgtype = _DOORBELL_MSG_TYPE;
    asm volatile("msgclr %0" :: "r" (msgtype));

    return;
}

void doorbell_broadcast()
{
    /*TODO RTC 152189
    size_t threadCount = CpuManager::getThreadCount();

    uint64_t msgtype = _DOORBELL_MSG_TYPE;
    uint64_t thread = getPIR() & (threadCount - 1);
    for (size_t i = 0; i < threadCount; ++i)
    {
        if (i != thread)
        {
            register uint64_t msg = msgtype | i;
            asm volatile("msgsnd %0" :: "r" (msg));
        }
    }
    **/
}

void doorbell_send(uint64_t i_pir)
{
    uint64_t msgtype = _DOORBELL_MSG_TYPE;
    register uint64_t msg = msgtype | i_pir;
    asm volatile("msgsnd %0" :: "r" (msg));

    return;
}

void send_doorbell_wakeup(uint64_t i_pir)
{
    cpu_t *l_cpu = CpuManager::getCpu(i_pir);

    printkd("send_doorbell_wakeup to pir: %lx\n", i_pir);
    //Create WorkItem and put on the stack to be executed during doorbell
    // execution
    KernelWorkItem* l_work = new CpuWakeupDoorbellWorkItem();
    l_cpu->doorbell_actions.push(l_work);
    //Put a barrier here to prevent a possible weak consistency
    // issue with the l_work memory getting consumed incorrectly
    // by the new thread that wakes up
    sync();
    //Send doorbell to wakeup core/thread
    doorbell_send(i_pir);
}

void send_doorbell_restore_tb(uint64_t i_pir, uint64_t i_tb)
{
    cpu_t *l_cpu = CpuManager::getCpu(i_pir);
    l_cpu->cpu_restore_tb = i_tb;

    printkd("send_doorbell_restore_tb to pir: %lx\n", i_pir);
    //Create WorkItem and put on the stack to be executed during doorbell
    // execution
    KernelWorkItem* l_work = new CpuTbRestoreDoorbellWorkItem();
    l_cpu->doorbell_actions.push(l_work);
    //Put a barrier here to prevent a possible weak consistency
    // issue with the l_work memory getting consumed incorrectly
    // by the new thread that wakes up
    sync();
    //Send doorbell to wakeup core/thread
    doorbell_send(i_pir);
}

void send_doorbell_ipc(uint64_t i_pir)
{
    printk("send_doorbell_ipc to pir: %lx\n", i_pir);
    doorbell_send(i_pir);
}
<|endoftext|>