text:
#include <boost/process/search_path.hpp>
#include <cmakeserver/ipc.hpp>
#include <numeric>
#include <random>

namespace {
	/** `constexpr` iota() function from the STL.
	 * @returns past-the-end ForwardIterator in the destination range
	 */
	template <typename ForwardIterator, typename T>
	constexpr ForwardIterator cx_iota(ForwardIterator first, ForwardIterator last, T val) {
		for(; first != last; ++first) {
			*first = val;
			++val;
		}
		return first;
	}
}    // namespace

namespace cmakeserver {
	boost::process::child spawn_cmake_server(std::string_view const pipe) {
		using namespace boost::process;
		return child{search_path("cmake"), "-E", "server", std::string{"--pipe="} += pipe, "--experimental"};
	}

	fs::path make_temporary_filename() {
		fs::path base = fs::temp_directory_path() / "cmakeserver";
		if(exists(base) && !is_directory(base)) {
			// TODO custom error codes
			throw fs::filesystem_error{"not a directory", base, {}};
		} else if(!exists(base)) {
			create_directory(base);
		}

		constexpr auto char_table = [] {
			auto result = std::array<char, 26 * 2 + 10>{};
			auto it = begin(result);
			it = cx_iota(it, it + 26, 'a');
			it = cx_iota(it, it + 26, 'A');
			cx_iota(it, it + 10, '0');
			return result;
		}();

		fs::path result;
		std::random_device rd;
		std::mt19937 g(rd());
		std::uniform_int_distribution<size_t> dist(0, char_table.size());
		do {
			std::array<char, 16> file_name;
			std::generate_n(begin(file_name), file_name.size() - 1, [&] { return char_table[dist(g)]; });
			file_name.back() = '\0';
			result = base / file_name.data();
		} while(exists(result));
		return result;
	}
}    // namespace cmakeserver

ext: cpp

max_stars_repo_name: mmha/libcmakeserver

max_issues_repo_name: mmha/libcmakeserver

max_forks_repo_name: mmha/libcmakeserver


text:
///////////////////////////////////////////////////////////////////////////////
/// \file infinity.hpp
/// A time series that uses characteristic storage
//
//  Copyright 2006 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_RANGE_RUN_STORAGE_UTILITY_INFINITY_HPP_EAN_07_21_2006
#define BOOST_RANGE_RUN_STORAGE_UTILITY_INFINITY_HPP_EAN_07_21_2006

#include <limits>
#include <boost/utility/enable_if.hpp>
#include <boost/integer_traits.hpp>
#include <boost/detail/pod_singleton.hpp>
#include <boost/type_traits/is_integral.hpp>

namespace boost { namespace range_run_storage
{
    namespace detail
    {
        template<typename T>
        typename enable_if<is_integral<T>, T>::type
        infinity(T * = 0)
        {
            return integer_traits<T>::const_max;
        }

        template<typename T>
        typename disable_if<is_integral<T>, T>::type
        infinity(T * = 0)
        {
            return std::numeric_limits<T>::infinity();
        }

        template<typename T>
        typename enable_if<is_integral<T>, T>::type
        neg_infinity(T * = 0)
        {
            return integer_traits<T>::const_min;
        }

        template<typename T>
        typename disable_if<is_integral<T>, T>::type
        neg_infinity(T * = 0)
        {
            return -std::numeric_limits<T>::infinity();
        }
    }

    template<bool Positive>
    struct infinity_base
    {
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1310)
        operator std::ptrdiff_t () const    { return integer_traits<std::ptrdiff_t>::const_max; }
        operator std::size_t () const       { return integer_traits<std::size_t>::const_max; }
        operator float () const             { return std::numeric_limits<float>::infinity(); }
        operator double () const            { return std::numeric_limits<double>::infinity(); }
#else
        template<typename T>
        operator T () const
        {
            return detail::infinity<T>();
        }
#endif
    };

    template<>
    struct infinity_base<false>
    {
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1310)
        operator std::ptrdiff_t () const    { return integer_traits<std::ptrdiff_t>::const_min; }
        operator std::size_t () const       { return integer_traits<std::size_t>::const_min; }
        operator float () const             { return -std::numeric_limits<float>::infinity(); }
        operator double () const            { return -std::numeric_limits<double>::infinity(); }
#else
        template<typename T>
        operator T () const
        {
            return detail::neg_infinity<T>();
        }
#endif
    };

    template<bool Positive = true>
    struct infinity
      : infinity_base<Positive>
    {
        template<typename T> friend bool operator ==(infinity inf, T t)
        {
            return static_cast<T>(inf) == t;
        }

        template<typename T> friend bool operator !=(infinity inf, T t)
        {
            return static_cast<T>(inf) != t;
        }

        template<typename T> friend bool operator ==(T t, infinity inf)
        {
            return t == static_cast<T>(inf);
        }

        template<typename T> friend bool operator !=(T t, infinity inf)
        {
            return t != static_cast<T>(inf);
        }

        infinity<!Positive> operator-() const
        {
            return infinity<!Positive>();
        }

        template<typename T> friend T &operator +=(T &t, infinity inf)
        {
            return t = static_cast<T>(inf);
        }

        template<typename T> friend T &operator -=(T &t, infinity inf)
        {
            return t = static_cast<T>(-inf);
        }

        template<typename T> friend infinity operator +(T t, infinity inf)
        {
            return inf;
        }

        template<typename T> friend infinity<!Positive> operator -(T t, infinity inf)
        {
            return -inf;
        }

        template<typename T> friend infinity operator +(infinity inf, T t)
        {
            return inf;
        }

        template<typename T> friend infinity operator -(infinity inf, T t)
        {
            return inf;
        }
    };

    typedef infinity<true> plus_infinity;
    typedef infinity<false> minus_infinity;

    namespace
    {
        plus_infinity const &inf = boost::detail::pod_singleton<plus_infinity>::instance;
    }

}}

#endif

ext: hpp


text:
/*
 * CSIGadget.cpp
 *
 *  Created on: Nov 11, 2014
 *      Author: dch
 */

#include "CSIGadget.h"
#include <ismrmrd/xml.h>
#include "cudaDeviceManager.h"
#include "cuNDArray_utils.h"
#include "cuNlcgSolver.h"
#include "eigenTester.h"
#include "CSfreqOperator.h"
#include "cuPartialDerivativeOperator.h"
#include "cuDWTOperator.h"
#include <boost/make_shared.hpp>
namespace Gadgetron {

CSIGadget::CSIGadget() {
	// TODO Auto-generated constructor stub

}

CSIGadget::~CSIGadget() {
	// TODO Auto-generated destructor stub
}

int CSIGadget::process_config(ACE_Message_Block *mb){
	//GDEBUG("gpuCgSenseGadget::process_config\n");

        device_number_ = deviceno.value();

	int number_of_devices = cudaDeviceManager::Instance()->getTotalNumberOfDevice();
	if (number_of_devices == 0) {
		GDEBUG( "Error: No available CUDA devices.\n" );
		return GADGET_FAIL;
	}

	if (device_number_ >= number_of_devices) {
		GDEBUG("Adjusting device number from %d to %d\n", device_number_,  (device_number_%number_of_devices));
		device_number_ = (device_number_%number_of_devices);
	}

	if (cudaSetDevice(device_number_)!= cudaSuccess) {
		GDEBUG( "Error: unable to set CUDA device.\n" );
		return GADGET_FAIL;
	}

	cg_limit_ = cg_limit.value();
	oversampling_factor_ = oversampling_factor.value();
	kernel_width_ = kernel_width.value();
	output_convergence_ = output_convergence.value();
	number_of_sb_iterations_ = number_of_sb_iterations.value();
	number_of_cg_iterations_ = number_of_cg_iterations.value();

	use_compressed_sensing_ = compressed_sensing.value();

	mu_ = mu.value();

	// Get the Ismrmrd header
	//
	ISMRMRD::IsmrmrdHeader h;
	ISMRMRD::deserialize(mb->rd_ptr(),h);

	if (h.encoding.size() != 1) {
		GDEBUG("This Gadget only supports one encoding space\n");
		return GADGET_FAIL;
	}

	// Get the encoding space and trajectory description
	ISMRMRD::EncodingSpace e_space = h.encoding[0].encodedSpace;
	ISMRMRD::EncodingSpace r_space = h.encoding[0].reconSpace;
	ISMRMRD::EncodingLimits e_limits = h.encoding[0].encodingLimits;

	img_dims_ = {r_space.matrixSize.x,r_space.matrixSize.y,r_space.matrixSize.z};

	matrix_size_ = vector_td<uint64_t,2>{r_space.matrixSize.x,r_space.matrixSize.y};

	unsigned int warp_size = cudaDeviceManager::Instance()->warp_size(device_number_);

	matrix_size_os_ =
			uint64d2(((static_cast<unsigned int>(std::ceil(matrix_size_[0]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size,
					((static_cast<unsigned int>(std::ceil(matrix_size_[1]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size);

		if (h.acquisitionSystemInformation) {
			channels_ = h.acquisitionSystemInformation->receiverChannels ? *h.acquisitionSystemInformation->receiverChannels : 1;
		} else {
			channels_ = 1;
		}

		/*if (~h.userParameters.is_present()){
			GDEBUG("CSI gadget requires userparameters to be set to obtain timesteps.");
			return GADGET_FAIL;
		}*/

		auto parameters = h.userParameters->userParameterDouble;
		auto bw = std::find_if(parameters.begin(),parameters.end(), [](ISMRMRD::UserParameterDouble d) { return d.name=="bw";});

		if (bw->name != "bw"){
			GDEBUG("CSI gadget: User parameter bw is missing.");
			return GADGET_FAIL;
		}

		auto dte = std::find_if(parameters.begin(),parameters.end(), [](ISMRMRD::UserParameterDouble d) { return d.name=="dte";});
		if (dte->name != "dte"){
			GDEBUG("CSI gadget: User parameter dte is missing.");
			return GADGET_FAIL;
		}

// Allocate encoding operator for non-Cartesian Sense
		E_ = boost::make_shared< CSIOperator<float> >(1/bw->value, dte->value);
		E_->set_weight(mu_);

		std::vector<float> freqs = frequencies.value();

		if (freqs.empty()){
			for (float f = frequency_min.value(); f <= frequency_max.value(); f+= frequency_step.value())
				freqs.push_back(f);
		}

		if (freqs.size() == 0)
			throw std::runtime_error("CSIGadget: Frequencies not set!");

		std::stringstream ss;
		ss << "Frequencies set: ";
		for (auto f : freqs)
				ss << f << " ";
		GDEBUG(ss.str().c_str());

		E_->set_frequencies(freqs);

		img_dims_[2]=freqs.size();

		S_ = boost::make_shared<cuNonCartesianSenseOperator<float,2>>();

		E_->set_senseOp(S_);

		auto idOp = boost::make_shared<identityOperator<cuNDArray<float_complext>>>();
		idOp->set_domain_dimensions(&img_dims_);
		idOp->set_codomain_dimensions(&img_dims_);
		idOp->set_weight(2*mu_);
		solver_.add_regularization_operator(idOp);

		auto dX = boost::make_shared<cuPartialDerivativeOperator<float_complext,3>>(0);
		dX->set_domain_dimensions(&img_dims_);
		dX->set_codomain_dimensions(&img_dims_);
		dX->set_weight(2*mu_);
		auto dY = boost::make_shared<cuPartialDerivativeOperator<float_complext,3>>(1);
		dY->set_domain_dimensions(&img_dims_);
		dY->set_codomain_dimensions(&img_dims_);
		dY->set_weight(2*mu_);
		auto dZ = boost::make_shared<cuPartialDerivativeOperator<float_complext,3>>(2);
		dZ->set_domain_dimensions(&img_dims_);
		dZ->set_codomain_dimensions(&img_dims_);
		dZ->set_weight(2*mu_);

		solver_.add_regularization_group_operator(dX);
		solver_.add_regularization_group_operator(dY);

		//solver_.add_regularization_group_operator(dZ);
		solver_.add_group();
/*
		auto W = boost::make_shared<cuDWTOperator<float_complext,3>>();
		W->set_domain_dimensions(&img_dims_);
		W->set_codomain_dimensions(&img_dims_);
		W->set_weight(2*mu_);

		auto W2 = boost::make_shared<cuDWTOperator<float_complext,3>>();
		W2->set_shift(2);
		W2->set_domain_dimensions(&img_dims_);
		W2->set_codomain_dimensions(&img_dims_);
		W2->set_weight(2*mu_);
		solver_.add_regularization_operator(W);
		solver_.add_regularization_operator(W2);
		*/
		// Setup solver
		solver_.set_encoding_operator( E_ );        // encoding matrix
		solver_.set_max_outer_iterations( number_of_sb_iterations_ );
		solver_.set_max_inner_iterations(1);
		solver_.get_inner_solver()->set_max_iterations(number_of_cg_iterations_);
		solver_.get_inner_solver()->set_tc_tolerance( cg_limit_ );
		solver_.set_output_mode( (output_convergence_) ? cuCgSolver<float_complext>::OUTPUT_VERBOSE : cuCgSolver<float_complext>::OUTPUT_SILENT);
		is_configured_ = true;
	return GADGET_OK;

}

int CSIGadget::process(GadgetContainerMessage<cuSenseData>* m1){

	if (!is_configured_) {
		GDEBUG("\nData received before configuration complete\n");
		return GADGET_FAIL;
	}

	GDEBUG("CSI is on the job\n");

	auto traj = m1->getObjectPtr()->traj;

	auto trajdims2 = std::vector<size_t>{traj->get_size(0),1};
	//Extract initial trajectory
	cuNDArray<floatd2> traj2(trajdims2,traj->get_data_ptr());

	auto data = m1->getObjectPtr()->data;
	auto csm =m1->getObjectPtr()->csm;
	auto dcw = m1->getObjectPtr()->dcw;
	//dcw.reset();

	if (dcw)
		sqrt_inplace(dcw.get());

	E_->set_domain_dimensions(&img_dims_);
	E_->set_codomain_dimensions(data->get_dimensions().get());

	std::vector<size_t> sense_dims = *data->get_dimensions();
	sense_dims[1] = img_dims_[2];

	S_->set_domain_dimensions(&img_dims_);
	S_->set_codomain_dimensions(&sense_dims);
/*
	{
		GDEBUG("Removing CSM maps");
		auto csm_dims = *csm->get_dimensions();
		csm_dims.pop_back();
		cuNDArray<float_complext> csm_view(csm_dims,csm->get_data_ptr());
		fill(&csm_view,complext<float>(1,0));
		size_t nelements = csm_view.get_number_of_elements();
		for (int  i = 1; i< csm->get_size(2); i++){
			cuNDArray<float_complext> csm_view2(csm_dims,csm->get_data_ptr()+i*nelements);
			clear(&csm_view2);
		}
	}
*/
	S_->set_csm(csm);
	S_->set_dcw(dcw);
	S_->setup( matrix_size_, matrix_size_os_, kernel_width_ );
	S_->preprocess(&traj2);

	GDEBUG("Setup done, solving....\n");
	/*
	eigenTester<cuNDArray<float_complext>> tester;
	std::vector<float> freqs{  -575.1223,-450.1223,-360.1223,  -183.1223,140.8777};
	auto T_ = boost::make_shared<CSfreqOperator>(E_->get_pointtime(),E_->get_echotime());
	T_->set_frequencies(freqs);
	T_->set_codomain_dimensions(data->get_dimensions().get());

	std::vector<size_t> tim_dims = *data->get_dimensions();
	tim_dims[2] = freqs.size();
	T_->set_domain_dimensions(&tim_dims);

	tester.add_encoding_operator(E_);

	float_complext eigVal = tester.get_smallest_eigenvalue();

	GDEBUG("Smallest eigenvalue: %f %f /n",real(eigVal),imag(eigVal));
*/
	/*
	cuNlcgSolver<float_complext> solv;
	//cuCgSolver<float_complext> solv;
	solv.set_output_mode(cuCgSolver<float_complext>::OUTPUT_VERBOSE);
	solv.set_max_iterations(10);
	solv.set_encoding_operator(E_);
	solv.set_tc_tolerance(1e-8f);
	*/
	boost::shared_ptr<cuNDArray<float_complext>> result;
	if (use_compressed_sensing_)
		result = solver_.solve(data.get());
	else {
		cgSolver<cuNDArray<float_complext>> cgsolver;
		cgsolver.set_max_iterations(solver_.get_inner_solver()->get_max_iterations());
		cgsolver.set_encoding_operator(E_);
		result = cgsolver.solve(data.get());
	}
	//auto result = solv.solve(data.get());

	//E_->mult_MH(data.get(),result.get(),false);

	GDEBUG("Image sum: %f \n",asum(result.get()));
	m1->release();

	GDEBUG("Solver done, next patient...");

	GadgetContainerMessage< hoNDArray< std::complex<float> > > *cm =
			new GadgetContainerMessage< hoNDArray< std::complex<float> > >();

	GadgetContainerMessage<ISMRMRD::ImageHeader> *m =
			new GadgetContainerMessage<ISMRMRD::ImageHeader>();

	m->cont(cm);

	result->to_host((hoNDArray<float_complext>*)cm->getObjectPtr());

	GDEBUG("Result size: %i %i %i \n",result->get_size(0),result->get_size(1),result->get_size(2));

	m->getObjectPtr()->matrix_size[0] = img_dims_[0];
	m->getObjectPtr()->matrix_size[1] = img_dims_[1];
	m->getObjectPtr()->matrix_size[2] = img_dims_[2];
	m->getObjectPtr()->channels       = 1;
	m->getObjectPtr()->image_index    = 1;
	m->getObjectPtr()->data_type = ISMRMRD::ISMRMRD_CXFLOAT;

	if (!this->next()->putq(m)){
		GDEBUG("Failed to put image on que");
		return GADGET_FAIL;
	}

	return GADGET_OK;
}

  GADGET_FACTORY_DECLARE(CSIGadget)

} /* namespace Gadgetron */

max_stars_repo_name: roopchansinghv/gadgetron


text:
//          Copyright Nicolas Vanhoren 2008 - 2008.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_CSTREAM_STRINGS_HPP
#define BOOST_CSTREAM_STRINGS_HPP

#include "gen_char_traits.hpp"
#include "encoding_traits.hpp"
#include "low/endian.hpp"
#include "cstream.hpp"
#include <string>
#include <boost/cstdint.hpp>
#include <sstream>

namespace boost {
namespace cstream {

    /*
        UTF-8 declarations
    */

    struct utf8_char_traits : gen_char_traits<char> {};

    typedef std::basic_ios<char,utf8_char_traits> utf8_ios;
    typedef std::basic_string<char,utf8_char_traits> utf8_string;
    typedef std::basic_streambuf<char,utf8_char_traits> utf8_streambuf;
    typedef std::basic_istream<char,utf8_char_traits> utf8_istream;
    typedef std::basic_ostream<char,utf8_char_traits> utf8_ostream;
    typedef std::basic_iostream<char,utf8_char_traits> utf8_iostream;
    typedef std::basic_stringbuf<char,utf8_char_traits> utf8_stringbuf;
    typedef std::basic_istringstream<char,utf8_char_traits> utf8_istringstream;
    typedef std::basic_ostringstream<char,utf8_char_traits> utf8_ostringstream;
    typedef std::basic_stringstream<char,utf8_char_traits> utf8_stringstream;

    template<>
    struct encoding_traits<char,utf8_char_traits > {
        typedef char char_type;
        typedef utf8_char_traits char_trait;

        static std::string default_encoding() {
            return "utf8";
        }
    };
    typedef base_csource<char,utf8_char_traits> utf8_csource;
    typedef boost::iostreams::stream_buffer<utf8_csource> utf8_icstream_buffer;
    typedef boost::iostreams::stream<utf8_csource> utf8_icstream;
    typedef base_csink<char,utf8_char_traits> utf8_csink;
    typedef boost::iostreams::stream_buffer<utf8_csink> utf8_ocstream_buffer;
    typedef boost::iostreams::stream<utf8_csink> utf8_ocstream;

    /*
        UTF-16 declarations
    */

    struct utf16_char_traits : gen_char_traits<boost::uint16_t> {};

    typedef std::basic_ios<boost::uint16_t,utf16_char_traits> utf16_ios;
    typedef std::basic_string<boost::uint16_t,utf16_char_traits> utf16_string;
    typedef std::basic_streambuf<boost::uint16_t,utf16_char_traits> utf16_streambuf;
    typedef std::basic_istream<boost::uint16_t,utf16_char_traits> utf16_istream;
    typedef std::basic_ostream<boost::uint16_t,utf16_char_traits> utf16_ostream;
    typedef std::basic_iostream<boost::uint16_t,utf16_char_traits> utf16_iostream;
    typedef std::basic_stringbuf<boost::uint16_t,utf16_char_traits> utf16_stringbuf;
    typedef std::basic_istringstream<boost::uint16_t,utf16_char_traits> utf16_istringstream;
    typedef std::basic_ostringstream<boost::uint16_t,utf16_char_traits> utf16_ostringstream;
    typedef std::basic_stringstream<boost::uint16_t,utf16_char_traits> utf16_stringstream;

    template<>
    struct encoding_traits<boost::uint16_t,utf16_char_traits > {
        typedef boost::uint16_t char_type;
        typedef utf16_char_traits char_trait;

        static std::string default_encoding() {
            if(low::is_2_bytes_little_endian())
                return "utf16LE";
            else
                return "utf16BE";
        }
    };
    typedef base_csource<uint16_t,utf16_char_traits> utf16_csource;
    typedef boost::iostreams::stream_buffer<utf16_csource> utf16_icstream_buffer;
    typedef boost::iostreams::stream<utf16_csource> utf16_icstream;
    typedef base_csink<uint16_t,utf16_char_traits> utf16_csink;
    typedef boost::iostreams::stream_buffer<utf16_csink> utf16_ocstream_buffer;
    typedef boost::iostreams::stream<utf16_csink> utf16_ocstream;

    /*
        UTF_32 declarations
    */

    struct utf32_char_traits : gen_char_traits<boost::uint32_t> {};

    typedef std::basic_ios<boost::uint32_t,utf32_char_traits> utf32_ios;
    typedef std::basic_string<boost::uint32_t,utf32_char_traits> utf32_string;
    typedef std::basic_streambuf<boost::uint32_t,utf32_char_traits> utf32_streambuf;
    typedef std::basic_istream<boost::uint32_t,utf32_char_traits> utf32_istream;
    typedef std::basic_ostream<boost::uint32_t,utf32_char_traits> utf32_ostream;
    typedef std::basic_iostream<boost::uint32_t,utf32_char_traits> utf32_iostream;
    typedef std::basic_stringbuf<boost::uint32_t,utf32_char_traits> utf32_stringbuf;
    typedef std::basic_istringstream<boost::uint32_t,utf32_char_traits> utf32_istringstream;
    typedef std::basic_ostringstream<boost::uint32_t,utf32_char_traits> utf32_ostringstream;
    typedef std::basic_stringstream<boost::uint32_t,utf32_char_traits> utf32_stringstream;

    template<>
    struct encoding_traits<boost::uint32_t,utf32_char_traits > {
        typedef boost::uint32_t char_type;
        typedef utf32_char_traits char_trait;

        static std::string default_encoding() {
            if(low::is_4_bytes_little_endian())
                return "utf32LE";
            else
                return "utf32BE";
        }
    };
    typedef base_csource<uint32_t,utf32_char_traits> utf32_csource;
    typedef boost::iostreams::stream_buffer<utf32_csource> utf32_icstream_buffer;
    typedef boost::iostreams::stream<utf32_csource> utf32_icstream;
    typedef base_csink<uint32_t,utf32_char_traits> utf32_csink;
    typedef boost::iostreams::stream_buffer<utf32_csink> utf32_ocstream_buffer;
    typedef boost::iostreams::stream<utf32_csink> utf32_ocstream;

}
}

#endif

max_stars_repo_name: nicolas-van/boostcstream

max_issues_repo_name: nicolas-van/boostcstream

max_forks_repo_name: nicolas-van/boostcstream


text:
/*
 * Copyright (c) 2011, Intel Corporation.
 *
 *  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.
 */

#include <boost/format.hpp>
#include "invalidNamspc_r10b.h"
#include "globals.h"
#include "grpDefs.h"
#include "../Queues/iocq.h"
#include "../Queues/iosq.h"
#include "../Queues/ce.h"
#include "../Utils/kernelAPI.h"
#include "../Cmds/write.h"

namespace GrpNVMWriteCmd {

InvalidNamspc_r10b::InvalidNamspc_r10b(
    string grpName, string testName) :
    Test(grpName, testName, SPECREV_10b)
{
    // 63 chars allowed:     xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    mTestDesc.SetCompliance("revision 1.0b, section 4,6");
    mTestDesc.SetShort(     "Issue write and cause SC=Invalid Namspc or Format");
    // No string size limit for the long description
    mTestDesc.SetLong(
        "Determine Identify.NN and issue write cmd requesting 1 block, to "
        "all namspcs not supported by DUT, expect failure.");
}

InvalidNamspc_r10b::~InvalidNamspc_r10b()
{
    ///////////////////////////////////////////////////////////////////////////
    // Allocations taken from the heap and not under the control of the
    // RsrcMngr need to be freed/deleted here.
    ///////////////////////////////////////////////////////////////////////////
}

InvalidNamspc_r10b::
InvalidNamspc_r10b(const InvalidNamspc_r10b &other) : Test(other)
{
    ///////////////////////////////////////////////////////////////////////////
    // All pointers in this object must be NULL, never allow shallow or deep
    // copies, see Test::Clone() header comment.
    ///////////////////////////////////////////////////////////////////////////
}

InvalidNamspc_r10b &
InvalidNamspc_r10b::operator=(const InvalidNamspc_r10b &other)
{
    ///////////////////////////////////////////////////////////////////////////
    // All pointers in this object must be NULL, never allow shallow or deep
    // copies, see Test::Clone() header comment.
    ///////////////////////////////////////////////////////////////////////////
    Test::operator=(other);
    return *this;
}

Test::RunType
InvalidNamspc_r10b::RunnableCoreTest(bool preserve)
{
    ///////////////////////////////////////////////////////////////////////////
    // All code contained herein must never permanently modify the state or
    // configuration of the DUT. Permanence is defined as state or configuration
    // changes that will not be restored after a cold hard reset.
    ///////////////////////////////////////////////////////////////////////////

    preserve = preserve;    // Suppress compiler error/warning
    return RUN_TRUE;        // This test is never destructive
}

void
InvalidNamspc_r10b::RunCoreTest()
{
    /** \verbatim
     * Assumptions:
     * 1) Test CreateResources_r10b has run prior.
     * \endverbatim
     */
    uint64_t inc, i;
    string work;
    uint32_t numCE;
    uint32_t isrCountB4;

    LOG_NRM("Lookup objs which were created in a prior test within group");
    SharedIOSQPtr iosq = CAST_TO_IOSQ(gRsrcMngr->GetObj(IOSQ_GROUP_ID));
    SharedIOCQPtr iocq = CAST_TO_IOCQ(gRsrcMngr->GetObj(IOCQ_GROUP_ID));

    if ((numCE = iocq->ReapInquiry(isrCountB4, true)) != 0) {
        iocq->Dump(
            FileSystem::PrepDumpFile(mGrpName, mTestName, "iocq",
            "notEmpty"), "Test assumption have not been met");
        throw FrmwkEx(HERE, "Require 0 CE's within CQ %d, not upheld, found %d",
            iocq->GetQId(), numCE);
    }

    LOG_NRM("Setup write cmd's values that won't change per namspc");
    SharedMemBufferPtr writeMem = SharedMemBufferPtr(new MemBuffer());
    uint64_t lbaDataSize = 512;
    writeMem->Init(lbaDataSize);

    SharedWritePtr writeCmd = SharedWritePtr(new Write());
    send_64b_bitmask prpBitmask = (send_64b_bitmask)
        (MASK_PRP1_PAGE | MASK_PRP2_PAGE | MASK_PRP2_LIST);
    writeCmd->SetPrpBuffer(prpBitmask, writeMem);
    writeCmd->SetNLB(0);    // convert to 0-based value
    writeCmd->SetSLBA(0);

    LOG_NRM("For all namspc's issue cmd to an illegal namspc");
    ConstSharedIdentifyPtr idCtrlrStruct = gInformative->GetIdentifyCmdCtrlr();
    uint32_t nn = (uint32_t)idCtrlrStruct->GetValue(IDCTRLRCAP_NN);
    if (nn == 0)
        throw FrmwkEx(HERE, "Required to support >= 1 namespace");

    for (i = (nn + 1), inc = 1; i <= 0xffffffff; i += (2 * inc), inc += 1327) {
        LOG_NRM("Issue write cmd with illegal namspc ID=%llu",
            (unsigned long long)i);
        writeCmd->SetNSID(i);
        work = str(boost::format("namspc%d") % i);
        SendCmdToHdw(iosq, iocq, writeCmd, work);
    }
}

void
InvalidNamspc_r10b::SendCmdToHdw(SharedSQPtr sq, SharedCQPtr cq,
    SharedCmdPtr cmd, string qualify)
{
    uint32_t isrCount;
    uint32_t numCE;
    uint32_t ceRemain;
    uint32_t numReaped;
    string work;
    uint16_t uniqueId;

    LOG_NRM("Send the cmd to hdw via SQ %d", sq->GetQId());
    sq->Send(cmd, uniqueId);
    sq->Ring();

    LOG_NRM("Wait for the CE to arrive in CQ %d", cq->GetQId());
    if (cq->ReapInquiryWaitSpecify(CALC_TIMEOUT_ms(1), 1, numCE, isrCount)
        == false) {

        work = str(boost::format(
            "Unable to see any CE's in CQ %d, dump entire CQ") % cq->GetQId());
        cq->Dump(
            FileSystem::PrepDumpFile(mGrpName, mTestName, "cq." +
            cmd->GetName(), qualify), work);
        throw FrmwkEx(HERE, "Unable to see CE for issued cmd");
    } else if (numCE != 1) {
        work = str(boost::format(
            "Unable to see any CE's in CQ %d, dump entire CQ") % cq->GetQId());
        cq->Dump(
            FileSystem::PrepDumpFile(mGrpName, mTestName, "cq." +
            cmd->GetName(), qualify), work);
        throw FrmwkEx(HERE, "1 cmd caused %d CE's to arrive in CQ %d",
            numCE, cq->GetQId());
    }

    LOG_NRM("The CQ's metrics before reaping holds head_ptr");
    struct nvme_gen_cq cqMetrics = cq->GetQMetrics();
    KernelAPI::LogCQMetrics(cqMetrics);

    LOG_NRM("Reaping CE from CQ %d, requires memory to hold CE", cq->GetQId());
    SharedMemBufferPtr ceMem = SharedMemBufferPtr(new MemBuffer());
    if ((numReaped = cq->Reap(ceRemain, ceMem, isrCount, numCE, true)) != 1) {
        work = str(boost::format("Verified CE's exist, desired %d, reaped %d")
            % numCE % numReaped);
        cq->Dump(
            FileSystem::PrepDumpFile(mGrpName, mTestName, "cq.error", qualify),
            work);
        throw FrmwkEx(HERE, work);
    }
    union CE ce = cq->PeekCE(cqMetrics.head_ptr);
    ProcessCE::Validate(ce, CESTAT_INVAL_NAMSPC);  // throws upon error
}

}   // namespace


text:
//  Copyright (c) 2007-2008 Anshul Tandon
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(HPX_ACTION_MANAGER_ACTION_MANAGER_JUN_03_2008_0445PM)
#define HPX_ACTION_MANAGER_ACTION_MANAGER_JUN_03_2008_0445PM

#include <boost/noncopyable.hpp>

#include <hpx/include/naming.hpp>
#include <hpx/include/parcelset.hpp>
#include <hpx/runtime/threads/threadmanager.hpp>
#include <hpx/runtime/applier/applier.hpp>

#include <hpx/config/warnings_prefix.hpp>

namespace hpx { namespace actions
{
    class HPX_EXPORT action_manager : private boost::noncopyable
    {
    public:
        // Constructor
        action_manager(applier::applier& appl)
          : appl_(appl)
        {
            // Need to register the call-back function in parcelHandler so that
            // when a new parcel is received, it calls action_manager's
            // fetchNewParcel()
            appl.get_parcel_handler().register_event_handler(boost::bind(
                    &action_manager::fetch_parcel, this, _1, _2), conn_);
        }

        // Call-back function for parcelHandler to call when new parcels are received
        void fetch_parcel (parcelset::parcelhandler& parcel_handler,
            naming::gid_type const& parcel_id);

        // Invoked by the Thread Manager when it is running out of work-items
        // and needs something to execute on a specific starving resources
        // specified as the argument
        //void fetch_parcel (naming::id_type const& resourceID);

        // Invoked by the Applier when it has a local action to be executed
//        void fetchNewAction ();

        // Invoked during run-time or setup-time to add a new resource and its
        // associated functions
//        void addResource (naming::id_type resourceGUID,
//            boost::tuple resourceExecuteFunctions);

        // Invoked during run-time or setup-time to remove an existing resource
        // and its associated functions
//        void removeResource (naming::id_type resourceGUID);

        ~action_manager()
        {}

    private:
        // this scoped connection instance ensures the event handler to be
        // automatically unregistered whenever it gets destroyed
        parcelset::parcelhandler::scoped_connection_type conn_;

        applier::applier& appl_;
    };
}}

#include <hpx/config/warnings_suffix.hpp>

#endif

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx


text: #include <boost/geometry/arithmetic/arithmetic.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino