<commit_before>
#include "MarchingCubes.h"

#include "MarchingCubesLookupTables.h"
#include "CColorTable.h"

void CalculateGradient(SMarchingCubesVolume & Volume)
{
	for (s32 z = 0; z < Volume.Dimensions.Z; ++ z)
	for (s32 y = 0; y < Volume.Dimensions.Y; ++ y)
	for (s32 x = 0; x < Volume.Dimensions.X; ++ x)
	{
		Volume.Get(x, y, z).Gradient = vec3f(
			Volume.Get(x+1, y, z).Value - Volume.Get(x-1, y, z).Value,
			Volume.Get(x, y+1, z).Value - Volume.Get(x, y-1, z).Value,
			Volume.Get(x, y, z+1).Value - Volume.Get(x, y, z-1).Value) / 2.f;
	}
}

ion::Scene::CSimpleMesh * MarchingCubes(SMarchingCubesVolume & Volume)
{
	CalculateGradient(Volume);

	ion::Scene::CSimpleMesh * Mesh = new ion::Scene::CSimpleMesh();
	int CurrentBuffer = 0;
	Mesh->Vertices.reserve(1 << 14);
	Mesh->Triangles.reserve(1 << 11);

	ion::Scene::CSimpleMesh::SVertex Vertices[12];

	for (s32 z = 0; z < Volume.Dimensions.Z; ++ z)
	for (s32 y = 0; y < Volume.Dimensions.Y; ++ y)
	for (s32 x = 0; x < Volume.Dimensions.X; ++ x)
	{
		int Lookup = 0;

		if ((Volume.Get(x,   y,   z).Value   < 0)) Lookup |= 128;
		if ((Volume.Get(x+1, y,   z).Value   < 0)) Lookup |=  64;
		if ((Volume.Get(x+1, y,   z+1).Value < 0)) Lookup |=  32;
		if ((Volume.Get(x,   y,   z+1).Value < 0)) Lookup |=  16;
		if ((Volume.Get(x,   y+1, z).Value   < 0)) Lookup |=   8;
		if ((Volume.Get(x+1, y+1, z).Value   < 0)) Lookup |=   4;
		if ((Volume.Get(x+1, y+1, z+1).Value < 0)) Lookup |=   2;
		if ((Volume.Get(x,   y+1, z+1).Value < 0)) Lookup |=   1;

		auto Interpolate = [&](s32 const v1x, s32 const v1y, s32 const v1z, s32 const v2x, s32 const v2y, s32 const v2z) -> ion::Scene::CSimpleMesh::SVertex
		{
			static CColorTable ColorTable;

			ion::Scene::CSimpleMesh::SVertex v;
			f32 const d1 = Volume.Get(v1x, v1y, v1z).Value;
			f32 const d2 = Volume.Get(v2x, v2y, v2z).Value;
			f32 ratio = d1 / (d2 - d1);
			if (ratio < 0.f)
				ratio += 1.f;

			v.Position =
				vec3f(vec3i(v1x, v1y, v1z)) * (ratio) +
				vec3f(vec3i(v2x, v2y, v2z)) * (1.f - ratio);
			//v.Color = ColorTable.Get(
			//	Volume.Get(v1x, v1y, v1z).Color * (ratio) +
			//	Volume.Get(v2x, v2y, v2z).Color * (1.f - ratio));
			v.Normal =
				Normalize(Volume.Get(v1x, v1y, v1z).Gradient) * (ratio) +
				Normalize(Volume.Get(v2x, v2y, v2z).Gradient) * (1.f - ratio);

			return v;
		};

		if ((Lookup != 0) && (Lookup != 255))
		{
			if (EdgeTable[Lookup] & 1)    Vertices[0]  = Interpolate(x,   y+1, z+1, x+1, y+1, z+1);
			if (EdgeTable[Lookup] & 2)    Vertices[1]  = Interpolate(x+1, y+1, z+1, x+1, y+1, z);
			if (EdgeTable[Lookup] & 4)    Vertices[2]  = Interpolate(x+1, y+1, z,   x,   y+1, z);
			if (EdgeTable[Lookup] & 8)    Vertices[3]  = Interpolate(x,   y+1, z,   x,   y+1, z+1);
			if (EdgeTable[Lookup] & 16)   Vertices[4]  = Interpolate(x,   y,   z+1, x+1, y,   z+1);
			if (EdgeTable[Lookup] & 32)   Vertices[5]  = Interpolate(x+1, y,   z+1, x+1, y,   z);
			if (EdgeTable[Lookup] & 64)   Vertices[6]  = Interpolate(x+1, y,   z,   x,   y,   z);
			if (EdgeTable[Lookup] & 128)  Vertices[7]  = Interpolate(x,   y,   z,   x,   y,   z+1);
			if (EdgeTable[Lookup] & 256)  Vertices[8]  = Interpolate(x,   y+1, z+1, x,   y,   z+1);
			if (EdgeTable[Lookup] & 512)  Vertices[9]  = Interpolate(x+1, y+1, z+1, x+1, y,   z+1);
			if (EdgeTable[Lookup] & 1024) Vertices[10] = Interpolate(x+1, y+1, z,   x+1, y,   z);
			if (EdgeTable[Lookup] & 2048) Vertices[11] = Interpolate(x,   y+1, z,   x,   y,   z);

			for (u32 i = 0; TriTable[Lookup][i] != -1; i += 3)
			{
				for (u32 j = i; j < (i+3); ++ j)
					Mesh->Vertices.push_back(Vertices[TriTable[Lookup][j]]);

				ion::Scene::CSimpleMesh::STriangle Tri;
				Tri.Indices[0] = (uint) Mesh->Vertices.size() - 3;
				Tri.Indices[1] = (uint) Mesh->Vertices.size() - 2;
				Tri.Indices[2] = (uint) Mesh->Vertices.size() - 1;
				Mesh->Triangles.push_back(Tri);
			}
		}
	}

	return Mesh;
}
<commit_msg>[ionScience] Some fix work on marching cubes<commit_after>
#include "MarchingCubes.h"

#include "MarchingCubesLookupTables.h"
#include "CColorTable.h"

void CalculateGradient(SMarchingCubesVolume & Volume)
{
	for (s32 z = 0; z < Volume.Dimensions.Z; ++ z)
	for (s32 y = 0; y < Volume.Dimensions.Y; ++ y)
	for (s32 x = 0; x < Volume.Dimensions.X; ++ x)
	{
		Volume.Get(x, y, z).Gradient = vec3f(
			Volume.Get(x+1, y, z).Value - Volume.Get(x-1, y, z).Value,
			Volume.Get(x, y+1, z).Value - Volume.Get(x, y-1, z).Value,
			Volume.Get(x, y, z+1).Value - Volume.Get(x, y, z-1).Value) / 2.f;
	}
}

ion::Scene::CSimpleMesh * MarchingCubes(SMarchingCubesVolume & Volume)
{
	CalculateGradient(Volume);

	ion::Scene::CSimpleMesh * Mesh = new ion::Scene::CSimpleMesh();
	int CurrentBuffer = 0;
	Mesh->Vertices.reserve(1 << 14);
	Mesh->Triangles.reserve(1 << 11);

	ion::Scene::CSimpleMesh::SVertex Vertices[12];

	vec3i VertexIndices[8] =
	{
		vec3i(0, 0, 0),
		vec3i(1, 0, 0),
		vec3i(1, 0, 1),
		vec3i(0, 0, 1),
		vec3i(0, 1, 0),
		vec3i(1, 1, 0),
		vec3i(1, 1, 1),
		vec3i(0, 1, 1),
	};

	for (s32 z = 0; z < Volume.Dimensions.Z; ++ z)
	for (s32 y = 0; y < Volume.Dimensions.Y; ++ y)
	for (s32 x = 0; x < Volume.Dimensions.X; ++ x)
	{
		int Lookup = 0;

		if ((Volume.Get(vec3i(x, y, z) + VertexIndices[0]).Value < 0)) Lookup |=   1;
		if ((Volume.Get(vec3i(x, y, z) + VertexIndices[1]).Value < 0)) Lookup |=   2;
		if ((Volume.Get(vec3i(x, y, z) + VertexIndices[2]).Value < 0)) Lookup |=   4;
		if ((Volume.Get(vec3i(x, y, z) + VertexIndices[3]).Value < 0)) Lookup |=   8;
		if ((Volume.Get(vec3i(x, y, z) + VertexIndices[4]).Value < 0)) Lookup |=  16;
		if ((Volume.Get(vec3i(x, y, z) + VertexIndices[5]).Value < 0)) Lookup |=  32;
		if ((Volume.Get(vec3i(x, y, z) + VertexIndices[6]).Value < 0)) Lookup |=  64;
		if ((Volume.Get(vec3i(x, y, z) + VertexIndices[7]).Value < 0)) Lookup |= 128;

		auto Interpolate = [&](vec3i const & v1, vec3i const & v2) -> ion::Scene::CSimpleMesh::SVertex
		{
			//static CColorTable ColorTable;

			ion::Scene::CSimpleMesh::SVertex v;
			f32 const d1 = Volume.Get(v1).Value;
			f32 const d2 = Volume.Get(v2).Value;
			f32 ratio = d1 / (d2 - d1);
			if (ratio < 0.f)
				ratio += 1.f;

			v.Position =
				vec3f(v1) * (ratio) +
				vec3f(v2) * (1.f - ratio);
			//v.Color = ColorTable.Get(
			//	Volume.Get(v1x, v1y, v1z).Color * (ratio) +
			//	Volume.Get(v2x, v2y, v2z).Color * (1.f - ratio));
			v.Normal =
				Normalize(Volume.Get(v1).Gradient) * (ratio) +
				Normalize(Volume.Get(v2).Gradient) * (1.f - ratio);

			//f32 const valp1 = Volume.Get(v1).Value;
			//f32 const valp2 = Volume.Get(v2).Value;

			//vec3f p1 = vec3f(v1);
			//vec3f p2 = vec3f(v2);

			//float mu;

			//if (abs(0 - valp1) < 0.00001)
			//	return(p1);
			//if (abs(0 - valp2) < 0.00001)
			//	return(p2);
			//if (abs(valp1 - valp2) < 0.00001)
			//	return(p1);
			//mu = (0 - valp1) / (valp2 - valp1);
			//v.Position.X = p1.X + mu * (p2.X - p1.X);
			//v.Position.Y = p1.Y + mu * (p2.Y - p1.Y);
			//v.Position.Z = p1.Z + mu * (p2.Z - p1.Z);

			return v;
		};

		u32 EdgeTableLookup = EdgeTable[Lookup];
		if (EdgeTable[Lookup] != 0)
		{
			if (EdgeTable[Lookup] & 1)    Vertices[0]  = Interpolate(vec3i(x, y, z) + VertexIndices[0], vec3i(x, y, z) + VertexIndices[1]);
			if (EdgeTable[Lookup] & 2)    Vertices[1]  = Interpolate(vec3i(x, y, z) + VertexIndices[1], vec3i(x, y, z) + VertexIndices[2]);
			if (EdgeTable[Lookup] & 4)    Vertices[2]  = Interpolate(vec3i(x, y, z) + VertexIndices[2], vec3i(x, y, z) + VertexIndices[3]);
			if (EdgeTable[Lookup] & 8)    Vertices[3]  = Interpolate(vec3i(x, y, z) + VertexIndices[3], vec3i(x, y, z) + VertexIndices[0]);
			if (EdgeTable[Lookup] & 16)   Vertices[4]  = Interpolate(vec3i(x, y, z) + VertexIndices[4], vec3i(x, y, z) + VertexIndices[5]);
			if (EdgeTable[Lookup] & 32)   Vertices[5]  = Interpolate(vec3i(x, y, z) + VertexIndices[5], vec3i(x, y, z) + VertexIndices[6]);
			if (EdgeTable[Lookup] & 64)   Vertices[6]  = Interpolate(vec3i(x, y, z) + VertexIndices[6], vec3i(x, y, z) + VertexIndices[7]);
			if (EdgeTable[Lookup] & 128)  Vertices[7]  = Interpolate(vec3i(x, y, z) + VertexIndices[7], vec3i(x, y, z) + VertexIndices[4]);
			if (EdgeTable[Lookup] & 256)  Vertices[8]  = Interpolate(vec3i(x, y, z) + VertexIndices[0], vec3i(x, y, z) + VertexIndices[4]);
			if (EdgeTable[Lookup] & 512)  Vertices[9]  = Interpolate(vec3i(x, y, z) + VertexIndices[1], vec3i(x, y, z) + VertexIndices[5]);
			if (EdgeTable[Lookup] & 1024) Vertices[10] = Interpolate(vec3i(x, y, z) + VertexIndices[2], vec3i(x, y, z) + VertexIndices[6]);
			if (EdgeTable[Lookup] & 2048) Vertices[11] = Interpolate(vec3i(x, y, z) + VertexIndices[3], vec3i(x, y, z) + VertexIndices[7]);

			for (u32 i = 0; TriTable[Lookup][i] != -1; i += 3)
			{
				for (u32 j = i; j < (i+3); ++ j)
					Mesh->Vertices.push_back(Vertices[TriTable[Lookup][j]]);

				ion::Scene::CSimpleMesh::STriangle Tri;
				Tri.Indices[0] = (uint) Mesh->Vertices.size() - 3;
				Tri.Indices[1] = (uint) Mesh->Vertices.size() - 2;
				Tri.Indices[2] = (uint) Mesh->Vertices.size() - 1;
				Mesh->Triangles.push_back(Tri);
			}
		}
	}

	return Mesh;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrVkImage.h"
#include "GrGpuResourcePriv.h"
#include "GrVkGpu.h"
#include "GrVkMemory.h"
#include "GrVkTexture.h"
#include "GrVkUtil.h"

#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)

VkPipelineStageFlags GrVkImage::LayoutToPipelineSrcStageFlags(const VkImageLayout layout) {
    if (VK_IMAGE_LAYOUT_GENERAL == layout) {
        return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
    } else if (VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL == layout ||
               VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL == layout) {
        return VK_PIPELINE_STAGE_TRANSFER_BIT;
    } else if (VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL == layout) {
        return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
    } else if (VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL == layout ||
               VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL == layout) {
        return VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
    } else if (VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == layout) {
        return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
    } else if (VK_IMAGE_LAYOUT_PREINITIALIZED == layout) {
        return VK_PIPELINE_STAGE_HOST_BIT;
    } else if (VK_IMAGE_LAYOUT_PRESENT_SRC_KHR == layout) {
        return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
    }

    SkASSERT(VK_IMAGE_LAYOUT_UNDEFINED == layout);
    return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
}

VkAccessFlags GrVkImage::LayoutToSrcAccessMask(const VkImageLayout layout) {
    // Currently we assume we will never being doing any explict shader writes (this doesn't include
    // color attachment or depth/stencil writes). So we will ignore the
    // VK_MEMORY_OUTPUT_SHADER_WRITE_BIT.

    // We can only directly access the host memory if we are in preinitialized or general layout,
    // and the image is linear.
    // TODO: Add check for linear here so we are not always adding host to general, and we should
    //       only be in preinitialized if we are linear
    VkAccessFlags flags = 0;
    if (VK_IMAGE_LAYOUT_GENERAL == layout) {
        flags = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
                VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
                VK_ACCESS_TRANSFER_WRITE_BIT |
                VK_ACCESS_TRANSFER_READ_BIT |
                VK_ACCESS_SHADER_READ_BIT |
                VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_HOST_READ_BIT;
    } else if (VK_IMAGE_LAYOUT_PREINITIALIZED == layout) {
        flags = VK_ACCESS_HOST_WRITE_BIT;
    } else if (VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL == layout) {
        flags = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
    } else if (VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL == layout) {
        flags = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
    } else if (VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL == layout) {
        flags = VK_ACCESS_TRANSFER_WRITE_BIT;
    } else if (VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL == layout) {
        flags = VK_ACCESS_TRANSFER_READ_BIT;
    } else if (VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == layout) {
        flags = VK_ACCESS_SHADER_READ_BIT;
    } else if (VK_IMAGE_LAYOUT_PRESENT_SRC_KHR == layout) {
        flags = 0;
    }
    return flags;
}

VkImageAspectFlags vk_format_to_aspect_flags(VkFormat format) {
    switch (format) {
        case VK_FORMAT_S8_UINT:
            return VK_IMAGE_ASPECT_STENCIL_BIT;
        case VK_FORMAT_D24_UNORM_S8_UINT: // fallthrough
        case VK_FORMAT_D32_SFLOAT_S8_UINT:
            return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
        default:
            SkASSERT(GrVkFormatIsSupported(format));
            return VK_IMAGE_ASPECT_COLOR_BIT;
    }
}

void GrVkImage::setImageLayout(const GrVkGpu* gpu, VkImageLayout newLayout,
                               VkAccessFlags dstAccessMask,
                               VkPipelineStageFlags dstStageMask,
                               bool byRegion, bool releaseFamilyQueue) {
    SkASSERT(VK_IMAGE_LAYOUT_UNDEFINED != newLayout &&
             VK_IMAGE_LAYOUT_PREINITIALIZED != newLayout);
    VkImageLayout currentLayout = this->currentLayout();

    if (releaseFamilyQueue && fInfo.fCurrentQueueFamily == fInitialQueueFamily &&
        newLayout == currentLayout) {
        // We never transfered the image to this queue and we are releasing it so don't do anything.
        return;
    }

    // If the old and new layout are the same and the layout is a read only layout, there is no need
    // to put in a barrier unless we also need to switch queues.
    if (newLayout == currentLayout && !releaseFamilyQueue &&
        (fInfo.fCurrentQueueFamily == VK_QUEUE_FAMILY_IGNORED ||
         fInfo.fCurrentQueueFamily == gpu->queueIndex()) &&
        (VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL == currentLayout ||
         VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == currentLayout ||
         VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL == currentLayout)) {
        return;
    }

    VkAccessFlags srcAccessMask = GrVkImage::LayoutToSrcAccessMask(currentLayout);
    VkPipelineStageFlags srcStageMask = GrVkImage::LayoutToPipelineSrcStageFlags(currentLayout);

    VkImageAspectFlags aspectFlags = vk_format_to_aspect_flags(fInfo.fFormat);

    uint32_t srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    uint32_t dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    if (fInfo.fCurrentQueueFamily != VK_QUEUE_FAMILY_IGNORED &&
        gpu->queueIndex() != fInfo.fCurrentQueueFamily) {
        // The image still is owned by its original queue family and we need to transfer it into
        // ours.
        SkASSERT(!releaseFamilyQueue);
        SkASSERT(fInfo.fCurrentQueueFamily == fInitialQueueFamily);

        srcQueueFamilyIndex = fInfo.fCurrentQueueFamily;
        dstQueueFamilyIndex = gpu->queueIndex();
        fInfo.fCurrentQueueFamily = gpu->queueIndex();
    } else if (releaseFamilyQueue) {
        // We are releasing the image so we must transfer the image back to its original queue
        // family.
        SkASSERT(fInfo.fCurrentQueueFamily == gpu->queueIndex());
        srcQueueFamilyIndex = fInfo.fCurrentQueueFamily;
        dstQueueFamilyIndex = fInitialQueueFamily;
        fInfo.fCurrentQueueFamily = fInitialQueueFamily;
    }

    VkImageMemoryBarrier imageMemoryBarrier = {
        VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,          // sType
        nullptr,                                         // pNext
        srcAccessMask,                                   // outputMask
        dstAccessMask,                                   // inputMask
        currentLayout,                                   // oldLayout
        newLayout,                                       // newLayout
        srcQueueFamilyIndex,                             // srcQueueFamilyIndex
        dstQueueFamilyIndex,                             // dstQueueFamilyIndex
        fInfo.fImage,                                    // image
        { aspectFlags, 0, fInfo.fLevelCount, 0, 1 }      // subresourceRange
    };

    gpu->addImageMemoryBarrier(this->resource(), srcStageMask, dstStageMask, byRegion,
                               &imageMemoryBarrier);

    this->updateImageLayout(newLayout);
}

bool GrVkImage::InitImageInfo(const GrVkGpu* gpu, const ImageDesc& imageDesc, GrVkImageInfo* info) {
    if (0 == imageDesc.fWidth || 0 == imageDesc.fHeight) {
        return false;
    }
    VkImage image = 0;
    GrVkAlloc alloc;

    bool isLinear = VK_IMAGE_TILING_LINEAR == imageDesc.fImageTiling;
    VkImageLayout initialLayout = isLinear ? VK_IMAGE_LAYOUT_PREINITIALIZED
                                           : VK_IMAGE_LAYOUT_UNDEFINED;

    // Create Image
    VkSampleCountFlagBits vkSamples;
    if (!GrSampleCountToVkSampleCount(imageDesc.fSamples, &vkSamples)) {
        return false;
    }

    SkASSERT(VK_IMAGE_TILING_OPTIMAL == imageDesc.fImageTiling ||
             VK_SAMPLE_COUNT_1_BIT == vkSamples);

    const VkImageCreateInfo imageCreateInfo = {
        VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,         // sType
        nullptr,                                     // pNext
        0,                                           // VkImageCreateFlags
        imageDesc.fImageType,                        // VkImageType
        imageDesc.fFormat,                           // VkFormat
        { imageDesc.fWidth, imageDesc.fHeight, 1 },  // VkExtent3D
        imageDesc.fLevels,                           // mipLevels
        1,                                           // arrayLayers
        vkSamples,                                   // samples
        imageDesc.fImageTiling,                      // VkImageTiling
        imageDesc.fUsageFlags,                       // VkImageUsageFlags
        VK_SHARING_MODE_EXCLUSIVE,                   // VkSharingMode
        0,                                           // queueFamilyCount
        0,                                           // pQueueFamilyIndices
        initialLayout                                // initialLayout
    };

    GR_VK_CALL_ERRCHECK(gpu->vkInterface(), CreateImage(gpu->device(), &imageCreateInfo, nullptr,
                                                        &image));

    if (!GrVkMemory::AllocAndBindImageMemory(gpu, image, isLinear, &alloc)) {
        VK_CALL(gpu, DestroyImage(gpu->device(), image, nullptr));
        return false;
    }

    info->fImage = image;
    info->fAlloc = alloc;
    info->fImageTiling = imageDesc.fImageTiling;
    info->fImageLayout = initialLayout;
    info->fFormat = imageDesc.fFormat;
    info->fLevelCount = imageDesc.fLevels;
    info->fCurrentQueueFamily = VK_QUEUE_FAMILY_IGNORED;
    return true;
}

void GrVkImage::DestroyImageInfo(const GrVkGpu* gpu, GrVkImageInfo* info) {
    VK_CALL(gpu, DestroyImage(gpu->device(), info->fImage, nullptr));
    bool isLinear = VK_IMAGE_TILING_LINEAR == info->fImageTiling;
    GrVkMemory::FreeImageMemory(gpu, isLinear, info->fAlloc);
}

GrVkImage::~GrVkImage() {
    // should have been released or abandoned first
    SkASSERT(!fResource);
}

void GrVkImage::prepareForPresent(GrVkGpu* gpu) {
    VkImageLayout layout = this->currentLayout();
    if (fInitialQueueFamily != VK_QUEUE_FAMILY_EXTERNAL &&
        fInitialQueueFamily != VK_QUEUE_FAMILY_FOREIGN_EXT) {
        if (gpu->vkCaps().supportsSwapchain()) {
            layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
        }
    }
    this->setImageLayout(gpu, layout, 0, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, false, true);
}

void GrVkImage::releaseImage(GrVkGpu* gpu) {
    if (fInfo.fCurrentQueueFamily != fInitialQueueFamily) {
        // The Vulkan spec is vague on what to put for the dstStageMask here. The spec for image
        // memory barrier says the dstStageMask must not be zero. However, in the spec when it talks
        // about family queue transfers it says the dstStageMask is ignored and should be set to
        // zero. Assuming it really is ignored we set it to VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT here
        // since it makes the Vulkan validation layers happy.
        this->setImageLayout(gpu, this->currentLayout(), 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
                             false, true);
    }
    if (fResource) {
        fResource->removeOwningTexture();
        fResource->unref(gpu);
        fResource = nullptr;
    }
}

void GrVkImage::abandonImage() {
    if (fResource) {
        fResource->removeOwningTexture();
        fResource->unrefAndAbandon();
        fResource = nullptr;
    }
}

void GrVkImage::setResourceRelease(sk_sp<GrRefCntedCallback> releaseHelper) {
    SkASSERT(fResource);
    // Forward the release proc on to GrVkImage::Resource
    fResource->setRelease(std::move(releaseHelper));
}

void GrVkImage::Resource::freeGPUData(GrVkGpu* gpu) const {
    this->invokeReleaseProc();
    VK_CALL(gpu, DestroyImage(gpu->device(), fImage, nullptr));
    bool isLinear = (VK_IMAGE_TILING_LINEAR == fImageTiling);
    GrVkMemory::FreeImageMemory(gpu, isLinear, fAlloc);
}

void GrVkImage::Resource::addIdleProc(GrVkTexture* owningTexture,
                                      sk_sp<GrRefCntedCallback> idleProc) const {
    SkASSERT(!fOwningTexture || fOwningTexture == owningTexture);
    fOwningTexture = owningTexture;
    fIdleProcs.push_back(std::move(idleProc));
}

int GrVkImage::Resource::idleProcCnt() const { return fIdleProcs.count(); }

sk_sp<GrRefCntedCallback> GrVkImage::Resource::idleProc(int i) const { return fIdleProcs[i]; }

void GrVkImage::Resource::resetIdleProcs() const { fIdleProcs.reset(); }

void GrVkImage::Resource::removeOwningTexture() const { fOwningTexture = nullptr; }

void GrVkImage::Resource::notifyAddedToCommandBuffer() const { ++fNumCommandBufferOwners; }

void GrVkImage::Resource::notifyRemovedFromCommandBuffer() const {
    SkASSERT(fNumCommandBufferOwners);
    if (--fNumCommandBufferOwners || !fIdleProcs.count()) {
        return;
    }
    if (fOwningTexture) {
        if (fOwningTexture->resourcePriv().hasRefOrPendingIO()) {
            // Wait for the texture to become idle in the cache to call the procs.
            return;
        }
        fOwningTexture->callIdleProcsOnBehalfOfResource();
    } else {
        fIdleProcs.reset();
    }
}

void GrVkImage::BorrowedResource::freeGPUData(GrVkGpu* gpu) const {
    this->invokeReleaseProc();
}

void GrVkImage::BorrowedResource::abandonGPUData() const {
    this->invokeReleaseProc();
}

#if GR_TEST_UTILS
void GrVkImage::setCurrentQueueFamilyToGraphicsQueue(GrVkGpu* gpu) {
    fInfo.fCurrentQueueFamily = gpu->queueIndex();
}
#endif

<commit_msg>Remove read access flags from src of memory barriers.<commit_after>/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrVkImage.h"
#include "GrGpuResourcePriv.h"
#include "GrVkGpu.h"
#include "GrVkMemory.h"
#include "GrVkTexture.h"
#include "GrVkUtil.h"

#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)

VkPipelineStageFlags GrVkImage::LayoutToPipelineSrcStageFlags(const VkImageLayout layout) {
    if (VK_IMAGE_LAYOUT_GENERAL == layout) {
        return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
    } else if (VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL == layout ||
               VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL == layout) {
        return VK_PIPELINE_STAGE_TRANSFER_BIT;
    } else if (VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL == layout) {
        return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
    } else if (VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL == layout ||
               VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL == layout) {
        return VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
    } else if (VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == layout) {
        return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
    } else if (VK_IMAGE_LAYOUT_PREINITIALIZED == layout) {
        return VK_PIPELINE_STAGE_HOST_BIT;
    } else if (VK_IMAGE_LAYOUT_PRESENT_SRC_KHR == layout) {
        return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
    }

    SkASSERT(VK_IMAGE_LAYOUT_UNDEFINED == layout);
    return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
}

VkAccessFlags GrVkImage::LayoutToSrcAccessMask(const VkImageLayout layout) {
    // Currently we assume we will never being doing any explict shader writes (this doesn't include
    // color attachment or depth/stencil writes). So we will ignore the
    // VK_MEMORY_OUTPUT_SHADER_WRITE_BIT.

    // We can only directly access the host memory if we are in preinitialized or general layout,
    // and the image is linear.
    // TODO: Add check for linear here so we are not always adding host to general, and we should
    //       only be in preinitialized if we are linear
    VkAccessFlags flags = 0;
    if (VK_IMAGE_LAYOUT_GENERAL == layout) {
        flags = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
                VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
                VK_ACCESS_TRANSFER_WRITE_BIT |
                VK_ACCESS_TRANSFER_READ_BIT |
                VK_ACCESS_SHADER_READ_BIT |
                VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_HOST_READ_BIT;
    } else if (VK_IMAGE_LAYOUT_PREINITIALIZED == layout) {
        flags = VK_ACCESS_HOST_WRITE_BIT;
    } else if (VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL == layout) {
        flags = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
    } else if (VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL == layout) {
        flags = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
    } else if (VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL == layout) {
        flags = VK_ACCESS_TRANSFER_WRITE_BIT;
    } else if (VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL == layout ||
               VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == layout ||
               VK_IMAGE_LAYOUT_PRESENT_SRC_KHR == layout) {
        // There are no writes that need to be made available
        flags = 0;
    }
    return flags;
}

VkImageAspectFlags vk_format_to_aspect_flags(VkFormat format) {
    switch (format) {
        case VK_FORMAT_S8_UINT:
            return VK_IMAGE_ASPECT_STENCIL_BIT;
        case VK_FORMAT_D24_UNORM_S8_UINT: // fallthrough
        case VK_FORMAT_D32_SFLOAT_S8_UINT:
            return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
        default:
            SkASSERT(GrVkFormatIsSupported(format));
            return VK_IMAGE_ASPECT_COLOR_BIT;
    }
}

void GrVkImage::setImageLayout(const GrVkGpu* gpu, VkImageLayout newLayout,
                               VkAccessFlags dstAccessMask,
                               VkPipelineStageFlags dstStageMask,
                               bool byRegion, bool releaseFamilyQueue) {
    SkASSERT(VK_IMAGE_LAYOUT_UNDEFINED != newLayout &&
             VK_IMAGE_LAYOUT_PREINITIALIZED != newLayout);
    VkImageLayout currentLayout = this->currentLayout();

    if (releaseFamilyQueue && fInfo.fCurrentQueueFamily == fInitialQueueFamily &&
        newLayout == currentLayout) {
        // We never transfered the image to this queue and we are releasing it so don't do anything.
        return;
    }

    // If the old and new layout are the same and the layout is a read only layout, there is no need
    // to put in a barrier unless we also need to switch queues.
    if (newLayout == currentLayout && !releaseFamilyQueue &&
        (fInfo.fCurrentQueueFamily == VK_QUEUE_FAMILY_IGNORED ||
         fInfo.fCurrentQueueFamily == gpu->queueIndex()) &&
        (VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL == currentLayout ||
         VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == currentLayout ||
         VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL == currentLayout)) {
        return;
    }

    VkAccessFlags srcAccessMask = GrVkImage::LayoutToSrcAccessMask(currentLayout);
    VkPipelineStageFlags srcStageMask = GrVkImage::LayoutToPipelineSrcStageFlags(currentLayout);

    VkImageAspectFlags aspectFlags = vk_format_to_aspect_flags(fInfo.fFormat);

    uint32_t srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    uint32_t dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    if (fInfo.fCurrentQueueFamily != VK_QUEUE_FAMILY_IGNORED &&
        gpu->queueIndex() != fInfo.fCurrentQueueFamily) {
        // The image still is owned by its original queue family and we need to transfer it into
        // ours.
        SkASSERT(!releaseFamilyQueue);
        SkASSERT(fInfo.fCurrentQueueFamily == fInitialQueueFamily);

        srcQueueFamilyIndex = fInfo.fCurrentQueueFamily;
        dstQueueFamilyIndex = gpu->queueIndex();
        fInfo.fCurrentQueueFamily = gpu->queueIndex();
    } else if (releaseFamilyQueue) {
        // We are releasing the image so we must transfer the image back to its original queue
        // family.
        SkASSERT(fInfo.fCurrentQueueFamily == gpu->queueIndex());
        srcQueueFamilyIndex = fInfo.fCurrentQueueFamily;
        dstQueueFamilyIndex = fInitialQueueFamily;
        fInfo.fCurrentQueueFamily = fInitialQueueFamily;
    }

    VkImageMemoryBarrier imageMemoryBarrier = {
        VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,          // sType
        nullptr,                                         // pNext
        srcAccessMask,                                   // outputMask
        dstAccessMask,                                   // inputMask
        currentLayout,                                   // oldLayout
        newLayout,                                       // newLayout
        srcQueueFamilyIndex,                             // srcQueueFamilyIndex
        dstQueueFamilyIndex,                             // dstQueueFamilyIndex
        fInfo.fImage,                                    // image
        { aspectFlags, 0, fInfo.fLevelCount, 0, 1 }      // subresourceRange
    };

    gpu->addImageMemoryBarrier(this->resource(), srcStageMask, dstStageMask, byRegion,
                               &imageMemoryBarrier);

    this->updateImageLayout(newLayout);
}

bool GrVkImage::InitImageInfo(const GrVkGpu* gpu, const ImageDesc& imageDesc, GrVkImageInfo* info) {
    if (0 == imageDesc.fWidth || 0 == imageDesc.fHeight) {
        return false;
    }
    VkImage image = 0;
    GrVkAlloc alloc;

    bool isLinear = VK_IMAGE_TILING_LINEAR == imageDesc.fImageTiling;
    VkImageLayout initialLayout = isLinear ? VK_IMAGE_LAYOUT_PREINITIALIZED
                                           : VK_IMAGE_LAYOUT_UNDEFINED;

    // Create Image
    VkSampleCountFlagBits vkSamples;
    if (!GrSampleCountToVkSampleCount(imageDesc.fSamples, &vkSamples)) {
        return false;
    }

    SkASSERT(VK_IMAGE_TILING_OPTIMAL == imageDesc.fImageTiling ||
             VK_SAMPLE_COUNT_1_BIT == vkSamples);

    const VkImageCreateInfo imageCreateInfo = {
        VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,         // sType
        nullptr,                                     // pNext
        0,                                           // VkImageCreateFlags
        imageDesc.fImageType,                        // VkImageType
        imageDesc.fFormat,                           // VkFormat
        { imageDesc.fWidth, imageDesc.fHeight, 1 },  // VkExtent3D
        imageDesc.fLevels,                           // mipLevels
        1,                                           // arrayLayers
        vkSamples,                                   // samples
        imageDesc.fImageTiling,                      // VkImageTiling
        imageDesc.fUsageFlags,                       // VkImageUsageFlags
        VK_SHARING_MODE_EXCLUSIVE,                   // VkSharingMode
        0,                                           // queueFamilyCount
        0,                                           // pQueueFamilyIndices
        initialLayout                                // initialLayout
    };

    GR_VK_CALL_ERRCHECK(gpu->vkInterface(), CreateImage(gpu->device(), &imageCreateInfo, nullptr,
                                                        &image));

    if (!GrVkMemory::AllocAndBindImageMemory(gpu, image, isLinear, &alloc)) {
        VK_CALL(gpu, DestroyImage(gpu->device(), image, nullptr));
        return false;
    }

    info->fImage = image;
    info->fAlloc = alloc;
    info->fImageTiling = imageDesc.fImageTiling;
    info->fImageLayout = initialLayout;
    info->fFormat = imageDesc.fFormat;
    info->fLevelCount = imageDesc.fLevels;
    info->fCurrentQueueFamily = VK_QUEUE_FAMILY_IGNORED;
    return true;
}

void GrVkImage::DestroyImageInfo(const GrVkGpu* gpu, GrVkImageInfo* info) {
    VK_CALL(gpu, DestroyImage(gpu->device(), info->fImage, nullptr));
    bool isLinear = VK_IMAGE_TILING_LINEAR == info->fImageTiling;
    GrVkMemory::FreeImageMemory(gpu, isLinear, info->fAlloc);
}

GrVkImage::~GrVkImage() {
    // should have been released or abandoned first
    SkASSERT(!fResource);
}

void GrVkImage::prepareForPresent(GrVkGpu* gpu) {
    VkImageLayout layout = this->currentLayout();
    if (fInitialQueueFamily != VK_QUEUE_FAMILY_EXTERNAL &&
        fInitialQueueFamily != VK_QUEUE_FAMILY_FOREIGN_EXT) {
        if (gpu->vkCaps().supportsSwapchain()) {
            layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
        }
    }
    this->setImageLayout(gpu, layout, 0, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, false, true);
}

void GrVkImage::releaseImage(GrVkGpu* gpu) {
    if (fInfo.fCurrentQueueFamily != fInitialQueueFamily) {
        // The Vulkan spec is vague on what to put for the dstStageMask here. The spec for image
        // memory barrier says the dstStageMask must not be zero. However, in the spec when it talks
        // about family queue transfers it says the dstStageMask is ignored and should be set to
        // zero. Assuming it really is ignored we set it to VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT here
        // since it makes the Vulkan validation layers happy.
        this->setImageLayout(gpu, this->currentLayout(), 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
                             false, true);
    }
    if (fResource) {
        fResource->removeOwningTexture();
        fResource->unref(gpu);
        fResource = nullptr;
    }
}

void GrVkImage::abandonImage() {
    if (fResource) {
        fResource->removeOwningTexture();
        fResource->unrefAndAbandon();
        fResource = nullptr;
    }
}

void GrVkImage::setResourceRelease(sk_sp<GrRefCntedCallback> releaseHelper) {
    SkASSERT(fResource);
    // Forward the release proc on to GrVkImage::Resource
    fResource->setRelease(std::move(releaseHelper));
}

void GrVkImage::Resource::freeGPUData(GrVkGpu* gpu) const {
    this->invokeReleaseProc();
    VK_CALL(gpu, DestroyImage(gpu->device(), fImage, nullptr));
    bool isLinear = (VK_IMAGE_TILING_LINEAR == fImageTiling);
    GrVkMemory::FreeImageMemory(gpu, isLinear, fAlloc);
}

void GrVkImage::Resource::addIdleProc(GrVkTexture* owningTexture,
                                      sk_sp<GrRefCntedCallback> idleProc) const {
    SkASSERT(!fOwningTexture || fOwningTexture == owningTexture);
    fOwningTexture = owningTexture;
    fIdleProcs.push_back(std::move(idleProc));
}

int GrVkImage::Resource::idleProcCnt() const { return fIdleProcs.count(); }

sk_sp<GrRefCntedCallback> GrVkImage::Resource::idleProc(int i) const { return fIdleProcs[i]; }

void GrVkImage::Resource::resetIdleProcs() const { fIdleProcs.reset(); }

void GrVkImage::Resource::removeOwningTexture() const { fOwningTexture = nullptr; }

void GrVkImage::Resource::notifyAddedToCommandBuffer() const { ++fNumCommandBufferOwners; }

void GrVkImage::Resource::notifyRemovedFromCommandBuffer() const {
    SkASSERT(fNumCommandBufferOwners);
    if (--fNumCommandBufferOwners || !fIdleProcs.count()) {
        return;
    }
    if (fOwningTexture) {
        if (fOwningTexture->resourcePriv().hasRefOrPendingIO()) {
            // Wait for the texture to become idle in the cache to call the procs.
            return;
        }
        fOwningTexture->callIdleProcsOnBehalfOfResource();
    } else {
        fIdleProcs.reset();
    }
}

void GrVkImage::BorrowedResource::freeGPUData(GrVkGpu* gpu) const {
    this->invokeReleaseProc();
}

void GrVkImage::BorrowedResource::abandonGPUData() const {
    this->invokeReleaseProc();
}

#if GR_TEST_UTILS
void GrVkImage::setCurrentQueueFamilyToGraphicsQueue(GrVkGpu* gpu) {
    fInfo.fCurrentQueueFamily = gpu->queueIndex();
}
#endif

<|endoftext|>


<commit_before>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// POSIX
#include <poll.h>

// Google Log
#include <glog/logging.h>

// e
#include <e/guard.h>

// HyperDex
#include <hyperdex/physical.h>

hyperdex :: physical :: physical(const po6::net::ipaddr& ip, bool listen)
    : m_max_fds(sysconf(_SC_OPEN_MAX))
    , m_shutdown(false)
    , m_listen(ip.family(), SOCK_STREAM, IPPROTO_TCP)
    , m_bindto(ip, 0)
    , m_incoming()
    , m_locations()
    , m_hazard_ptrs()
    , m_channels(static_cast<size_t>(m_max_fds), NULL)
    , m_channels_mask(m_max_fds, 0)
    , m_paused(false)
    , m_not_paused_lock()
    , m_not_paused(&m_not_paused_lock)
    , m_count_paused(0)
{
    if (listen)
    {
        hazard_ptr hptr = m_hazard_ptrs.get();
        channel* chan;
        // Enable other hosts to connect to us.
        m_listen.bind(po6::net::location(ip, 0));
        m_listen.listen(4);
        m_listen.nonblocking();

        switch (get_channel(hptr, m_listen.getsockname(), &chan))
        {
            case SUCCESS:
                break;
            case SHUTDOWN:
            case QUEUED:
            case CONNECTFAIL:
            case DISCONNECT:
            case LOGICERROR:
            default:
                throw std::runtime_error("Could not create connection to self.");
        }

        m_bindto = chan->soc.getsockname();
    }
    else
    {
        m_listen.close();
    }
}

hyperdex :: physical :: ~physical()
                        throw ()
{
}

void
hyperdex :: physical :: pause()
{
    po6::threads::mutex::hold hold(&m_not_paused_lock);
    m_paused = true;
}

void
hyperdex :: physical :: unpause()
{
    po6::threads::mutex::hold hold(&m_not_paused_lock);
    m_paused = false;
    m_not_paused.broadcast();
}

size_t
hyperdex :: physical :: num_paused()
{
    po6::threads::mutex::hold hold(&m_not_paused_lock);
    return m_count_paused;
}

void
hyperdex :: physical :: shutdown()
{
    m_shutdown = true;
}

hyperdex::physical::returncode
hyperdex :: physical :: send(const po6::net::location& to,
                             e::buffer* msg)
{
    hazard_ptr hptr = m_hazard_ptrs.get();
    channel* chan;

    returncode res = get_channel(hptr, to, &chan);

    if (res != SUCCESS)
    {
        return res;
    }

    if (chan->mtx.trylock())
    {
        e::guard g = e::makeobjguard(chan->mtx, &po6::threads::mutex::unlock);

        if (chan->outprogress.empty())
        {
            chan->outprogress.pack() << *msg;
        }
        else
        {
            e::buffer buf;
            buf.pack() << *msg;
            chan->outgoing.push(buf);
        }

        work_write(chan);
        return SUCCESS;
    }
    else
    {
        e::buffer buf;
        buf.pack() << *msg;
        chan->outgoing.push(buf);
        return QUEUED;
    }
}

hyperdex::physical::returncode
hyperdex :: physical :: recv(po6::net::location* from,
                             e::buffer* msg)
{
    message m;
    bool ret = m_incoming.pop(&m);

    if (ret)
    {
        *from = m.loc;
        msg->swap(m.buf);
        return SUCCESS;
    }

    hazard_ptr hptr = m_hazard_ptrs.get();
    std::vector<pollfd> pfds;

    for (int i = 0; i < m_max_fds; ++i)
    {
        if (m_channels_mask[i])
        {
            pfds.push_back(pollfd());
            pfds.back().fd = i;
            pfds.back().events = POLLIN|POLLOUT;
            pfds.back().revents = 0;
        }
    }

    pfds.push_back(pollfd());
    pfds.back().fd = m_listen.get();
    pfds.back().events = POLLIN;
    pfds.back().revents = 0;

    while (true)
    {
        __sync_synchronize();

        if (m_shutdown)
        {
            return SHUTDOWN;
        }

        if (m_paused)
        {
            po6::threads::mutex::hold hold(&m_not_paused_lock);

            while (m_paused)
            {
                ++m_count_paused;
                m_not_paused.wait();
                --m_count_paused;
            }
        }

        if (poll(&pfds.front(), pfds.size(), 10) < 0)
        {
            if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK)
            {
                PLOG(INFO) << "poll failed";
                return LOGICERROR;
            }
        }

        size_t starting = hptr->state();

        for (size_t i = 0; i < pfds.size(); ++i)
        {
            size_t pfd_idx = hptr->state() = (starting + i) % pfds.size();

            if (pfds[pfd_idx].fd == -1)
            {
                continue;
            }

            channel* chan;

            while (true)
            {
                chan = m_channels[pfds[pfd_idx].fd];
                hptr->set(0, chan);

                if (chan == m_channels[pfds[pfd_idx].fd])
                {
                    break;
                }
            }

            // Protect file descriptors opened elsewhere.
            if (!chan && pfds[pfd_idx].fd != m_listen.get())
            {
                pfds[pfd_idx].fd = -1;
                continue;
            }

            if (pfds[pfd_idx].revents & POLLNVAL)
            {
                pfds[pfd_idx].fd = -1;
                continue;
            }

            if (pfds[pfd_idx].revents & POLLERR)
            {
                *from = chan->loc;
                work_close(hptr, chan);
                return DISCONNECT;
            }

            if (pfds[pfd_idx].revents & POLLHUP)
            {
                *from = chan->loc;
                work_close(hptr, chan);
                return DISCONNECT;
            }

            if (pfds[pfd_idx].revents & POLLIN)
            {
                if (pfds[pfd_idx].fd == m_listen.get())
                {
                    int fd = work_accept(hptr);

                    if (fd >= 0)
                    {
                        pfds.push_back(pollfd());
                        pfds.back().fd = fd;
                        pfds.back().events |= POLLIN;
                        pfds.back().revents = 0;
                    }
                }
                else
                {
                    returncode res;

                    if (work_read(hptr, chan, from, msg, &res))
                    {
                        return res;
                    }
                }
            }

            if (pfds[pfd_idx].revents & POLLOUT)
            {
                po6::threads::mutex::hold hold(&chan->mtx);

                if (!work_write(chan))
                {
                    pfds[pfd_idx].events &= ~POLLOUT;
                }
            }
        }
    }
}

void
hyperdex :: physical :: deliver(const po6::net::location& from,
                                const e::buffer& msg)
{
    message m;
    m.loc = from;
    m.buf = msg;
    m_incoming.push(m);
}

hyperdex::physical::returncode
hyperdex :: physical :: get_channel(const hazard_ptr& hptr, const po6::net::location& to, channel** chan)
{
    int fd;

    while (true)
    {
        if (m_locations.lookup(to, &fd))
        {
            *chan = m_channels[fd];
            hptr->set(0, *chan);

            if (*chan != m_channels[fd])
            {
                continue;
            }

            if (!*chan)
            {
                continue;
            }

            return SUCCESS;
        }
        else
        {
            try
            {
                po6::net::socket soc(to.address.family(), SOCK_STREAM, IPPROTO_TCP);
                soc.reuseaddr(true);
                soc.bind(m_bindto);
                soc.connect(to);
                return get_channel(hptr, &soc, chan);
            }
            catch (po6::error& e)
            {
                return CONNECTFAIL;
            }
        }
    }
}

hyperdex::physical::returncode
hyperdex :: physical :: get_channel(const hazard_ptr& hptr, po6::net::socket* soc, channel** ret)
{
    soc->nonblocking();
    soc->tcp_nodelay(true);
    std::auto_ptr<channel> chan(new channel(soc));
    hptr->set(0, chan.get());
    *ret = chan.get();

    if (m_locations.insert(chan->loc, chan->soc.get()))
    {
        assert(m_channels[chan->soc.get()] == NULL);
        __sync_or_and_fetch(&m_channels_mask[chan->soc.get()], 1);
        m_channels[chan->soc.get()] = chan.get();
        chan.release();
        return SUCCESS;
    }

    LOG(INFO) << "Logic error in get_channel.";
    return LOGICERROR;
}

int
hyperdex :: physical :: work_accept(const hazard_ptr& hptr)
{
    try
    {
        po6::net::socket soc;
        m_listen.accept(&soc);
        channel* chan;
        get_channel(hptr, &soc, &chan);
        return chan->soc.get();
    }
    catch (po6::error& e)
    {
        if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
        {
            LOG(INFO) << "Error accepting connection:  " << e.what();
        }
    }

    return -1;
}

void
hyperdex :: physical :: work_close(const hazard_ptr& hptr, channel* chan)
{
    if (chan)
    {
        {
            po6::threads::mutex::hold hold(&chan->mtx);
            int fd = chan->soc.get();

            if (fd < 0)
            {
                return;
            }

            m_channels_mask[chan->soc.get()] = 0;
            m_channels[fd] = NULL;
            m_locations.remove(chan->loc);
            chan->soc.close();
        }

        hptr->retire(chan);
    }
}

#define IO_BLOCKSIZE 65536

bool
hyperdex :: physical :: work_read(const hazard_ptr& hptr, channel* chan, po6::net::location* from, e::buffer* msg, returncode* res)
{
    if (!chan->mtx.trylock())
    {
        return false;
    }

    e::guard g = e::makeobjguard(chan->mtx, &po6::threads::mutex::unlock);

    if (chan->soc.get() < 0)
    {
        return false;
    }

    try
    {
        size_t ret = read(&chan->soc, &chan->inprogress, IO_BLOCKSIZE);

        if (ret == 0)
        {
            *from = chan->loc;
            *res = DISCONNECT;
            chan->mtx.unlock();
            g.dismiss();
            work_close(hptr, chan);
            return true;
        }

        std::vector<message> ms;

        while (chan->inprogress.size() >= sizeof(uint32_t))
        {
            uint32_t message_size;
            chan->inprogress.unpack() >> message_size;

            if (chan->inprogress.size() < message_size + sizeof(uint32_t))
            {
                break;
            }

            ms.push_back(message());
            message& m(ms.back());
            chan->inprogress.unpack() >> m.buf; // Different unpacker.
            m.loc = chan->loc;
            chan->inprogress.trim_prefix(message_size + sizeof(uint32_t));
        }

        if (ms.empty())
        {
            return false;
        }

        for (size_t i = 1; i < ms.size(); ++i)
        {
            m_incoming.push(ms[i]);
        }

        *from = ms[0].loc;
        *res = SUCCESS;
        msg->swap(ms[0].buf);
        return true;
    }
    catch (po6::error& e)
    {
        if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
        {
            LOG(ERROR) << "could not read from " << chan->loc << "; closing";
            *from = chan->loc;
            *res = DISCONNECT;
            chan->mtx.unlock();
            g.dismiss();
            work_close(hptr, chan);
            return true;
        }
    }

    return false;
}

bool
hyperdex :: physical :: work_write(channel* chan)
{
    if (chan->soc.get() < 0)
    {
        return false;
    }

    if (chan->outprogress.empty())
    {
        if (!chan->outgoing.pop(&chan->outprogress))
        {
            return false;
        }
    }

    try
    {
        size_t ret = chan->soc.write(chan->outprogress.get(), chan->outprogress.size());
        chan->outprogress.trim_prefix(ret);
    }
    catch (po6::error& e)
    {
        if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
        {
            PLOG(ERROR) << "could not write to " << chan->loc << "(fd:"  << chan->soc.get() << ")";
            return false;
        }
    }

    return true;
}

hyperdex :: physical :: channel :: channel(po6::net::socket* conn)
    : mtx()
    , soc()
    , loc(conn->getpeername())
    , outgoing()
    , outprogress()
    , inprogress()
{
    soc.swap(conn);
}

hyperdex :: physical :: channel :: ~channel()
                                   throw ()
{
}
<commit_msg>Increase the number of pending accepts on listener.<commit_after>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// POSIX
#include <poll.h>

// Google Log
#include <glog/logging.h>

// e
#include <e/guard.h>

// HyperDex
#include <hyperdex/physical.h>

hyperdex :: physical :: physical(const po6::net::ipaddr& ip, bool listen)
    : m_max_fds(sysconf(_SC_OPEN_MAX))
    , m_shutdown(false)
    , m_listen(ip.family(), SOCK_STREAM, IPPROTO_TCP)
    , m_bindto(ip, 0)
    , m_incoming()
    , m_locations()
    , m_hazard_ptrs()
    , m_channels(static_cast<size_t>(m_max_fds), NULL)
    , m_channels_mask(m_max_fds, 0)
    , m_paused(false)
    , m_not_paused_lock()
    , m_not_paused(&m_not_paused_lock)
    , m_count_paused(0)
{
    if (listen)
    {
        hazard_ptr hptr = m_hazard_ptrs.get();
        channel* chan;
        // Enable other hosts to connect to us.
        m_listen.bind(po6::net::location(ip, 0));
        m_listen.listen(128);
        m_listen.nonblocking();

        switch (get_channel(hptr, m_listen.getsockname(), &chan))
        {
            case SUCCESS:
                break;
            case SHUTDOWN:
            case QUEUED:
            case CONNECTFAIL:
            case DISCONNECT:
            case LOGICERROR:
            default:
                throw std::runtime_error("Could not create connection to self.");
        }

        m_bindto = chan->soc.getsockname();
    }
    else
    {
        m_listen.close();
    }
}

hyperdex :: physical :: ~physical()
                        throw ()
{
}

void
hyperdex :: physical :: pause()
{
    po6::threads::mutex::hold hold(&m_not_paused_lock);
    m_paused = true;
}

void
hyperdex :: physical :: unpause()
{
    po6::threads::mutex::hold hold(&m_not_paused_lock);
    m_paused = false;
    m_not_paused.broadcast();
}

size_t
hyperdex :: physical :: num_paused()
{
    po6::threads::mutex::hold hold(&m_not_paused_lock);
    return m_count_paused;
}

void
hyperdex :: physical :: shutdown()
{
    m_shutdown = true;
}

hyperdex::physical::returncode
hyperdex :: physical :: send(const po6::net::location& to,
                             e::buffer* msg)
{
    hazard_ptr hptr = m_hazard_ptrs.get();
    channel* chan;

    returncode res = get_channel(hptr, to, &chan);

    if (res != SUCCESS)
    {
        return res;
    }

    if (chan->mtx.trylock())
    {
        e::guard g = e::makeobjguard(chan->mtx, &po6::threads::mutex::unlock);

        if (chan->outprogress.empty())
        {
            chan->outprogress.pack() << *msg;
        }
        else
        {
            e::buffer buf;
            buf.pack() << *msg;
            chan->outgoing.push(buf);
        }

        work_write(chan);
        return SUCCESS;
    }
    else
    {
        e::buffer buf;
        buf.pack() << *msg;
        chan->outgoing.push(buf);
        return QUEUED;
    }
}

hyperdex::physical::returncode
hyperdex :: physical :: recv(po6::net::location* from,
                             e::buffer* msg)
{
    message m;
    bool ret = m_incoming.pop(&m);

    if (ret)
    {
        *from = m.loc;
        msg->swap(m.buf);
        return SUCCESS;
    }

    hazard_ptr hptr = m_hazard_ptrs.get();
    std::vector<pollfd> pfds;

    for (int i = 0; i < m_max_fds; ++i)
    {
        if (m_channels_mask[i])
        {
            pfds.push_back(pollfd());
            pfds.back().fd = i;
            pfds.back().events = POLLIN|POLLOUT;
            pfds.back().revents = 0;
        }
    }

    pfds.push_back(pollfd());
    pfds.back().fd = m_listen.get();
    pfds.back().events = POLLIN;
    pfds.back().revents = 0;

    while (true)
    {
        __sync_synchronize();

        if (m_shutdown)
        {
            return SHUTDOWN;
        }

        if (m_paused)
        {
            po6::threads::mutex::hold hold(&m_not_paused_lock);

            while (m_paused)
            {
                ++m_count_paused;
                m_not_paused.wait();
                --m_count_paused;
            }
        }

        if (poll(&pfds.front(), pfds.size(), 10) < 0)
        {
            if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK)
            {
                PLOG(INFO) << "poll failed";
                return LOGICERROR;
            }
        }

        size_t starting = hptr->state();

        for (size_t i = 0; i < pfds.size(); ++i)
        {
            size_t pfd_idx = hptr->state() = (starting + i) % pfds.size();

            if (pfds[pfd_idx].fd == -1)
            {
                continue;
            }

            channel* chan;

            while (true)
            {
                chan = m_channels[pfds[pfd_idx].fd];
                hptr->set(0, chan);

                if (chan == m_channels[pfds[pfd_idx].fd])
                {
                    break;
                }
            }

            // Protect file descriptors opened elsewhere.
            if (!chan && pfds[pfd_idx].fd != m_listen.get())
            {
                pfds[pfd_idx].fd = -1;
                continue;
            }

            if (pfds[pfd_idx].revents & POLLNVAL)
            {
                pfds[pfd_idx].fd = -1;
                continue;
            }

            if (pfds[pfd_idx].revents & POLLERR)
            {
                *from = chan->loc;
                work_close(hptr, chan);
                return DISCONNECT;
            }

            if (pfds[pfd_idx].revents & POLLHUP)
            {
                *from = chan->loc;
                work_close(hptr, chan);
                return DISCONNECT;
            }

            if (pfds[pfd_idx].revents & POLLIN)
            {
                if (pfds[pfd_idx].fd == m_listen.get())
                {
                    int fd = work_accept(hptr);

                    if (fd >= 0)
                    {
                        pfds.push_back(pollfd());
                        pfds.back().fd = fd;
                        pfds.back().events |= POLLIN;
                        pfds.back().revents = 0;
                    }
                }
                else
                {
                    returncode res;

                    if (work_read(hptr, chan, from, msg, &res))
                    {
                        return res;
                    }
                }
            }

            if (pfds[pfd_idx].revents & POLLOUT)
            {
                po6::threads::mutex::hold hold(&chan->mtx);

                if (!work_write(chan))
                {
                    pfds[pfd_idx].events &= ~POLLOUT;
                }
            }
        }
    }
}

void
hyperdex :: physical :: deliver(const po6::net::location& from,
                                const e::buffer& msg)
{
    message m;
    m.loc = from;
    m.buf = msg;
    m_incoming.push(m);
}

hyperdex::physical::returncode
hyperdex :: physical :: get_channel(const hazard_ptr& hptr, const po6::net::location& to, channel** chan)
{
    int fd;

    while (true)
    {
        if (m_locations.lookup(to, &fd))
        {
            *chan = m_channels[fd];
            hptr->set(0, *chan);

            if (*chan != m_channels[fd])
            {
                continue;
            }

            if (!*chan)
            {
                continue;
            }

            return SUCCESS;
        }
        else
        {
            try
            {
                po6::net::socket soc(to.address.family(), SOCK_STREAM, IPPROTO_TCP);
                soc.reuseaddr(true);
                soc.bind(m_bindto);
                soc.connect(to);
                return get_channel(hptr, &soc, chan);
            }
            catch (po6::error& e)
            {
                return CONNECTFAIL;
            }
        }
    }
}

hyperdex::physical::returncode
hyperdex :: physical :: get_channel(const hazard_ptr& hptr, po6::net::socket* soc, channel** ret)
{
    soc->nonblocking();
    soc->tcp_nodelay(true);
    std::auto_ptr<channel> chan(new channel(soc));
    hptr->set(0, chan.get());
    *ret = chan.get();

    if (m_locations.insert(chan->loc, chan->soc.get()))
    {
        assert(m_channels[chan->soc.get()] == NULL);
        __sync_or_and_fetch(&m_channels_mask[chan->soc.get()], 1);
        m_channels[chan->soc.get()] = chan.get();
        chan.release();
        return SUCCESS;
    }

    LOG(INFO) << "Logic error in get_channel.";
    return LOGICERROR;
}

int
hyperdex :: physical :: work_accept(const hazard_ptr& hptr)
{
    try
    {
        po6::net::socket soc;
        m_listen.accept(&soc);
        channel* chan;
        get_channel(hptr, &soc, &chan);
        return chan->soc.get();
    }
    catch (po6::error& e)
    {
        if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
        {
            LOG(INFO) << "Error accepting connection:  " << e.what();
        }
    }

    return -1;
}

void
hyperdex :: physical :: work_close(const hazard_ptr& hptr, channel* chan)
{
    if (chan)
    {
        {
            po6::threads::mutex::hold hold(&chan->mtx);
            int fd = chan->soc.get();

            if (fd < 0)
            {
                return;
            }

            m_channels_mask[chan->soc.get()] = 0;
            m_channels[fd] = NULL;
            m_locations.remove(chan->loc);
            chan->soc.close();
        }

        hptr->retire(chan);
    }
}

#define IO_BLOCKSIZE 65536

bool
hyperdex :: physical :: work_read(const hazard_ptr& hptr, channel* chan, po6::net::location* from, e::buffer* msg, returncode* res)
{
    if (!chan->mtx.trylock())
    {
        return false;
    }

    e::guard g = e::makeobjguard(chan->mtx, &po6::threads::mutex::unlock);

    if (chan->soc.get() < 0)
    {
        return false;
    }

    try
    {
        size_t ret = read(&chan->soc, &chan->inprogress, IO_BLOCKSIZE);

        if (ret == 0)
        {
            *from = chan->loc;
            *res = DISCONNECT;
            chan->mtx.unlock();
            g.dismiss();
            work_close(hptr, chan);
            return true;
        }

        std::vector<message> ms;

        while (chan->inprogress.size() >= sizeof(uint32_t))
        {
            uint32_t message_size;
            chan->inprogress.unpack() >> message_size;

            if (chan->inprogress.size() < message_size + sizeof(uint32_t))
            {
                break;
            }

            ms.push_back(message());
            message& m(ms.back());
            chan->inprogress.unpack() >> m.buf; // Different unpacker.
            m.loc = chan->loc;
            chan->inprogress.trim_prefix(message_size + sizeof(uint32_t));
        }

        if (ms.empty())
        {
            return false;
        }

        for (size_t i = 1; i < ms.size(); ++i)
        {
            m_incoming.push(ms[i]);
        }

        *from = ms[0].loc;
        *res = SUCCESS;
        msg->swap(ms[0].buf);
        return true;
    }
    catch (po6::error& e)
    {
        if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
        {
            LOG(ERROR) << "could not read from " << chan->loc << "; closing";
            *from = chan->loc;
            *res = DISCONNECT;
            chan->mtx.unlock();
            g.dismiss();
            work_close(hptr, chan);
            return true;
        }
    }

    return false;
}

bool
hyperdex :: physical :: work_write(channel* chan)
{
    if (chan->soc.get() < 0)
    {
        return false;
    }

    if (chan->outprogress.empty())
    {
        if (!chan->outgoing.pop(&chan->outprogress))
        {
            return false;
        }
    }

    try
    {
        size_t ret = chan->soc.write(chan->outprogress.get(), chan->outprogress.size());
        chan->outprogress.trim_prefix(ret);
    }
    catch (po6::error& e)
    {
        if (e != EAGAIN && e != EINTR && e != EWOULDBLOCK)
        {
            PLOG(ERROR) << "could not write to " << chan->loc << "(fd:"  << chan->soc.get() << ")";
            return false;
        }
    }

    return true;
}

hyperdex :: physical :: channel :: channel(po6::net::socket* conn)
    : mtx()
    , soc()
    , loc(conn->getpeername())
    , outgoing()
    , outprogress()
    , inprogress()
{
    soc.swap(conn);
}

hyperdex :: physical :: channel :: ~channel()
                                   throw ()
{
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/base/platform_thread.h"

#include "webrtc/base/atomicops.h"
#include "webrtc/base/checks.h"

#if defined(WEBRTC_LINUX)
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif

namespace rtc {

PlatformThreadId CurrentThreadId() {
  PlatformThreadId ret;
#if defined(WEBRTC_WIN)
  ret = GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
  ret = pthread_mach_thread_np(pthread_self());
#elif defined(WEBRTC_LINUX)
  ret =  syscall(__NR_gettid);
#elif defined(WEBRTC_ANDROID)
  ret = gettid();
#else
  // Default implementation for nacl and solaris.
  ret = reinterpret_cast<pid_t>(pthread_self());
#endif
#endif  // defined(WEBRTC_POSIX)
  RTC_DCHECK(ret);
  return ret;
}

PlatformThreadRef CurrentThreadRef() {
#if defined(WEBRTC_WIN)
  return GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
  return pthread_self();
#endif
}

bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
#if defined(WEBRTC_WIN)
  return a == b;
#elif defined(WEBRTC_POSIX)
  return pthread_equal(a, b);
#endif
}

void SetCurrentThreadName(const char* name) {
#if defined(WEBRTC_WIN)
  struct {
    DWORD dwType;
    LPCSTR szName;
    DWORD dwThreadID;
    DWORD dwFlags;
  } threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};

  __try {
    ::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
                     reinterpret_cast<ULONG_PTR*>(&threadname_info));
  } __except (EXCEPTION_EXECUTE_HANDLER) {
  }
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
  prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
  pthread_setname_np(name);
#endif
}

namespace {
#if defined(WEBRTC_WIN)
void CALLBACK RaiseFlag(ULONG_PTR param) {
  *reinterpret_cast<bool*>(param) = true;
}
#else
struct ThreadAttributes {
  ThreadAttributes() { pthread_attr_init(&attr); }
  ~ThreadAttributes() { pthread_attr_destroy(&attr); }
  pthread_attr_t* operator&() { return &attr; }
  pthread_attr_t attr;
};
#endif  // defined(WEBRTC_WIN)
}

PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
                               void* obj,
                               const char* thread_name)
    : run_function_deprecated_(func),
      obj_(obj),
      name_(thread_name ? thread_name : "webrtc") {
  RTC_DCHECK(func);
  RTC_DCHECK(name_.length() < 64);
  spawned_thread_checker_.DetachFromThread();
}

PlatformThread::PlatformThread(ThreadRunFunction func,
                               void* obj,
                               const char* thread_name,
                               ThreadPriority priority /*= kNormalPriority*/)
    : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
  RTC_DCHECK(func);
  RTC_DCHECK(!name_.empty());
  // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
  RTC_DCHECK(name_.length() < 64);
  spawned_thread_checker_.DetachFromThread();
}

PlatformThread::~PlatformThread() {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
  RTC_DCHECK(!thread_);
  RTC_DCHECK(!thread_id_);
#endif  // defined(WEBRTC_WIN)
}

#if defined(WEBRTC_WIN)
DWORD WINAPI PlatformThread::StartThread(void* param) {
  // The GetLastError() function only returns valid results when it is called
  // after a Win32 API function that returns a "failed" result. A crash dump
  // contains the result from GetLastError() and to make sure it does not
  // falsely report a Windows error we call SetLastError here.
  ::SetLastError(ERROR_SUCCESS);
  static_cast<PlatformThread*>(param)->Run();
  return 0;
}
#else
void* PlatformThread::StartThread(void* param) {
  static_cast<PlatformThread*>(param)->Run();
  return 0;
}
#endif  // defined(WEBRTC_WIN)

void PlatformThread::Start() {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(!thread_) << "Thread already started?";
#if defined(WEBRTC_WIN)
  stop_ = false;

  // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
  // Set the reserved stack stack size to 1M, which is the default on Windows
  // and Linux.
  thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
                           STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
  RTC_CHECK(thread_) << "CreateThread failed";
  RTC_DCHECK(thread_id_);
#else
  ThreadAttributes attr;
  // Set the stack stack size to 1M.
  pthread_attr_setstacksize(&attr, 1024 * 1024);
  RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
#endif  // defined(WEBRTC_WIN)
}

bool PlatformThread::IsRunning() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
  return thread_ != nullptr;
#else
  return thread_ != 0;
#endif  // defined(WEBRTC_WIN)
}

PlatformThreadRef PlatformThread::GetThreadRef() const {
#if defined(WEBRTC_WIN)
  return thread_id_;
#else
  return thread_;
#endif  // defined(WEBRTC_WIN)
}

void PlatformThread::Stop() {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  if (!IsRunning())
    return;

#if defined(WEBRTC_WIN)
  // Set stop_ to |true| on the worker thread.
  bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
  // Queuing the APC can fail if the thread is being terminated.
  RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
  WaitForSingleObject(thread_, INFINITE);
  CloseHandle(thread_);
  thread_ = nullptr;
  thread_id_ = 0;
#else
  if (!run_function_)
    RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
  RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
  if (!run_function_)
    AtomicOps::ReleaseStore(&stop_flag_, 0);
  thread_ = 0;
#endif  // defined(WEBRTC_WIN)
  spawned_thread_checker_.DetachFromThread();
}

// TODO(tommi): Deprecate the loop behavior in PlatformThread.
// * Introduce a new callback type that returns void.
// * Remove potential for a busy loop in PlatformThread.
// * Delegate the responsibility for how to stop the thread, to the
//   implementation that actually uses the thread.
// All implementations will need to be aware of how the thread should be stopped
// and encouraging a busy polling loop, can be costly in terms of power and cpu.
void PlatformThread::Run() {
  // Attach the worker thread checker to this thread.
  RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
  rtc::SetCurrentThreadName(name_.c_str());

  if (run_function_) {
    SetPriority(priority_);
    run_function_(obj_);
    return;
  }
// TODO(tommi): Delete the below.
#if !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN)
  const struct timespec ts_null = {0};
#endif
  do {
    // The interface contract of Start/Stop is that for a successful call to
    // Start, there should be at least one call to the run function.  So we
    // call the function before checking |stop_|.
    if (!run_function_deprecated_(obj_))
      break;
#if defined(WEBRTC_WIN)
    // Alertable sleep to permit RaiseFlag to run and update |stop_|.
    SleepEx(0, true);
  } while (!stop_);
#else
#if defined(WEBRTC_MAC)
    sched_yield();
#else
    nanosleep(&ts_null, nullptr);
#endif
  } while (!AtomicOps::AcquireLoad(&stop_flag_));
#endif  // defined(WEBRTC_WIN)
}

bool PlatformThread::SetPriority(ThreadPriority priority) {
#if RTC_DCHECK_IS_ON
  if (run_function_) {
    // The non-deprecated way of how this function gets called, is that it must
    // be called on the worker thread itself.
    RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
  } else {
    // In the case of deprecated use of this method, it must be called on the
    // same thread as the PlatformThread object is constructed on.
    RTC_DCHECK(thread_checker_.CalledOnValidThread());
    RTC_DCHECK(IsRunning());
  }
#endif

#if defined(WEBRTC_WIN)
  return SetThreadPriority(thread_, priority) != FALSE;
#elif defined(__native_client__)
  // Setting thread priorities is not supported in NaCl.
  return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
  // TODO(tommi): Switch to the same mechanism as Chromium uses for changing
  // thread priorities.
  return true;
#else
#ifdef WEBRTC_THREAD_RR
  const int policy = SCHED_RR;
#else
  const int policy = SCHED_FIFO;
#endif
  const int min_prio = sched_get_priority_min(policy);
  const int max_prio = sched_get_priority_max(policy);
  if (min_prio == -1 || max_prio == -1) {
    return false;
  }

  if (max_prio - min_prio <= 2)
    return false;

  // Convert webrtc priority to system priorities:
  sched_param param;
  const int top_prio = max_prio - 1;
  const int low_prio = min_prio + 1;
  switch (priority) {
    case kLowPriority:
      param.sched_priority = low_prio;
      break;
    case kNormalPriority:
      // The -1 ensures that the kHighPriority is always greater or equal to
      // kNormalPriority.
      param.sched_priority = (low_prio + top_prio - 1) / 2;
      break;
    case kHighPriority:
      param.sched_priority = std::max(top_prio - 2, low_prio);
      break;
    case kHighestPriority:
      param.sched_priority = std::max(top_prio - 1, low_prio);
      break;
    case kRealtimePriority:
      param.sched_priority = top_prio;
      break;
  }
  return pthread_setschedparam(thread_, policy, &param) == 0;
#endif  // defined(WEBRTC_WIN)
}

#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(IsRunning());

  return QueueUserAPC(function, thread_, data) != FALSE;
}
#endif

}  // namespace rtc
<commit_msg>Reland of Use sched_yield on all POSIX platforms in PlatformThread. (patchset #1 id:1 of https://codereview.webrtc.org/2712133003/ )<commit_after>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/base/platform_thread.h"

#include "webrtc/base/atomicops.h"
#include "webrtc/base/checks.h"

#if defined(WEBRTC_LINUX)
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif

namespace rtc {

PlatformThreadId CurrentThreadId() {
  PlatformThreadId ret;
#if defined(WEBRTC_WIN)
  ret = GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
  ret = pthread_mach_thread_np(pthread_self());
#elif defined(WEBRTC_LINUX)
  ret =  syscall(__NR_gettid);
#elif defined(WEBRTC_ANDROID)
  ret = gettid();
#else
  // Default implementation for nacl and solaris.
  ret = reinterpret_cast<pid_t>(pthread_self());
#endif
#endif  // defined(WEBRTC_POSIX)
  RTC_DCHECK(ret);
  return ret;
}

PlatformThreadRef CurrentThreadRef() {
#if defined(WEBRTC_WIN)
  return GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
  return pthread_self();
#endif
}

bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
#if defined(WEBRTC_WIN)
  return a == b;
#elif defined(WEBRTC_POSIX)
  return pthread_equal(a, b);
#endif
}

void SetCurrentThreadName(const char* name) {
#if defined(WEBRTC_WIN)
  struct {
    DWORD dwType;
    LPCSTR szName;
    DWORD dwThreadID;
    DWORD dwFlags;
  } threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};

  __try {
    ::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
                     reinterpret_cast<ULONG_PTR*>(&threadname_info));
  } __except (EXCEPTION_EXECUTE_HANDLER) {
  }
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
  prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
  pthread_setname_np(name);
#endif
}

namespace {
#if defined(WEBRTC_WIN)
void CALLBACK RaiseFlag(ULONG_PTR param) {
  *reinterpret_cast<bool*>(param) = true;
}
#else
struct ThreadAttributes {
  ThreadAttributes() { pthread_attr_init(&attr); }
  ~ThreadAttributes() { pthread_attr_destroy(&attr); }
  pthread_attr_t* operator&() { return &attr; }
  pthread_attr_t attr;
};
#endif  // defined(WEBRTC_WIN)
}

PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
                               void* obj,
                               const char* thread_name)
    : run_function_deprecated_(func),
      obj_(obj),
      name_(thread_name ? thread_name : "webrtc") {
  RTC_DCHECK(func);
  RTC_DCHECK(name_.length() < 64);
  spawned_thread_checker_.DetachFromThread();
}

PlatformThread::PlatformThread(ThreadRunFunction func,
                               void* obj,
                               const char* thread_name,
                               ThreadPriority priority /*= kNormalPriority*/)
    : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
  RTC_DCHECK(func);
  RTC_DCHECK(!name_.empty());
  // TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
  RTC_DCHECK(name_.length() < 64);
  spawned_thread_checker_.DetachFromThread();
}

PlatformThread::~PlatformThread() {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
  RTC_DCHECK(!thread_);
  RTC_DCHECK(!thread_id_);
#endif  // defined(WEBRTC_WIN)
}

#if defined(WEBRTC_WIN)
DWORD WINAPI PlatformThread::StartThread(void* param) {
  // The GetLastError() function only returns valid results when it is called
  // after a Win32 API function that returns a "failed" result. A crash dump
  // contains the result from GetLastError() and to make sure it does not
  // falsely report a Windows error we call SetLastError here.
  ::SetLastError(ERROR_SUCCESS);
  static_cast<PlatformThread*>(param)->Run();
  return 0;
}
#else
void* PlatformThread::StartThread(void* param) {
  static_cast<PlatformThread*>(param)->Run();
  return 0;
}
#endif  // defined(WEBRTC_WIN)

void PlatformThread::Start() {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(!thread_) << "Thread already started?";
#if defined(WEBRTC_WIN)
  stop_ = false;

  // See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
  // Set the reserved stack stack size to 1M, which is the default on Windows
  // and Linux.
  thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
                           STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
  RTC_CHECK(thread_) << "CreateThread failed";
  RTC_DCHECK(thread_id_);
#else
  ThreadAttributes attr;
  // Set the stack stack size to 1M.
  pthread_attr_setstacksize(&attr, 1024 * 1024);
  RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
#endif  // defined(WEBRTC_WIN)
}

bool PlatformThread::IsRunning() const {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
  return thread_ != nullptr;
#else
  return thread_ != 0;
#endif  // defined(WEBRTC_WIN)
}

PlatformThreadRef PlatformThread::GetThreadRef() const {
#if defined(WEBRTC_WIN)
  return thread_id_;
#else
  return thread_;
#endif  // defined(WEBRTC_WIN)
}

void PlatformThread::Stop() {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  if (!IsRunning())
    return;

#if defined(WEBRTC_WIN)
  // Set stop_ to |true| on the worker thread.
  bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
  // Queuing the APC can fail if the thread is being terminated.
  RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
  WaitForSingleObject(thread_, INFINITE);
  CloseHandle(thread_);
  thread_ = nullptr;
  thread_id_ = 0;
#else
  if (!run_function_)
    RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
  RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
  if (!run_function_)
    AtomicOps::ReleaseStore(&stop_flag_, 0);
  thread_ = 0;
#endif  // defined(WEBRTC_WIN)
  spawned_thread_checker_.DetachFromThread();
}

// TODO(tommi): Deprecate the loop behavior in PlatformThread.
// * Introduce a new callback type that returns void.
// * Remove potential for a busy loop in PlatformThread.
// * Delegate the responsibility for how to stop the thread, to the
//   implementation that actually uses the thread.
// All implementations will need to be aware of how the thread should be stopped
// and encouraging a busy polling loop, can be costly in terms of power and cpu.
void PlatformThread::Run() {
  // Attach the worker thread checker to this thread.
  RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
  rtc::SetCurrentThreadName(name_.c_str());

  if (run_function_) {
    SetPriority(priority_);
    run_function_(obj_);
    return;
  }
// TODO(tommi): Delete the below.
  do {
    // The interface contract of Start/Stop is that for a successful call to
    // Start, there should be at least one call to the run function.  So we
    // call the function before checking |stop_|.
    if (!run_function_deprecated_(obj_))
      break;
#if defined(WEBRTC_WIN)
    // Alertable sleep to permit RaiseFlag to run and update |stop_|.
    SleepEx(0, true);
  } while (!stop_);
#else
    sched_yield();
  } while (!AtomicOps::AcquireLoad(&stop_flag_));
#endif  // defined(WEBRTC_WIN)
}

bool PlatformThread::SetPriority(ThreadPriority priority) {
#if RTC_DCHECK_IS_ON
  if (run_function_) {
    // The non-deprecated way of how this function gets called, is that it must
    // be called on the worker thread itself.
    RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
  } else {
    // In the case of deprecated use of this method, it must be called on the
    // same thread as the PlatformThread object is constructed on.
    RTC_DCHECK(thread_checker_.CalledOnValidThread());
    RTC_DCHECK(IsRunning());
  }
#endif

#if defined(WEBRTC_WIN)
  return SetThreadPriority(thread_, priority) != FALSE;
#elif defined(__native_client__)
  // Setting thread priorities is not supported in NaCl.
  return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
  // TODO(tommi): Switch to the same mechanism as Chromium uses for changing
  // thread priorities.
  return true;
#else
#ifdef WEBRTC_THREAD_RR
  const int policy = SCHED_RR;
#else
  const int policy = SCHED_FIFO;
#endif
  const int min_prio = sched_get_priority_min(policy);
  const int max_prio = sched_get_priority_max(policy);
  if (min_prio == -1 || max_prio == -1) {
    return false;
  }

  if (max_prio - min_prio <= 2)
    return false;

  // Convert webrtc priority to system priorities:
  sched_param param;
  const int top_prio = max_prio - 1;
  const int low_prio = min_prio + 1;
  switch (priority) {
    case kLowPriority:
      param.sched_priority = low_prio;
      break;
    case kNormalPriority:
      // The -1 ensures that the kHighPriority is always greater or equal to
      // kNormalPriority.
      param.sched_priority = (low_prio + top_prio - 1) / 2;
      break;
    case kHighPriority:
      param.sched_priority = std::max(top_prio - 2, low_prio);
      break;
    case kHighestPriority:
      param.sched_priority = std::max(top_prio - 1, low_prio);
      break;
    case kRealtimePriority:
      param.sched_priority = top_prio;
      break;
  }
  return pthread_setschedparam(thread_, policy, &param) == 0;
#endif  // defined(WEBRTC_WIN)
}

#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(IsRunning());

  return QueueUserAPC(function, thread_, data) != FALSE;
}
#endif

}  // namespace rtc
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bridge_provider.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 13:16:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>

#include "remote_bridge.hxx"

#include <osl/diagnose.h>

#include <uno/mapping.hxx>
#include <uno/environment.h>

#include <bridges/remote/remote.h>

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::bridge;

namespace remotebridges_bridge
{

    OInstanceProviderWrapper::OInstanceProviderWrapper(
        const Reference <XInstanceProvider > & rProvider,
        ORemoteBridge * pBridgeCallback ) :
        m_rProvider( rProvider ),
        m_nRef( 0 ),
        m_pBridgeCallback( pBridgeCallback )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
        acquire = thisAcquire;
        release = thisRelease;
        getInstance = thisGetInstance;
    }

    OInstanceProviderWrapper::~OInstanceProviderWrapper()
    {
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    void OInstanceProviderWrapper::thisAcquire( remote_InstanceProvider *p )
    {
        OInstanceProviderWrapper * m = (OInstanceProviderWrapper *) p;
        osl_incrementInterlockedCount( &(m->m_nRef ) );
    }

    void OInstanceProviderWrapper::thisRelease( remote_InstanceProvider *p )
    {
        OInstanceProviderWrapper * m = ( OInstanceProviderWrapper *) p;
        if( ! osl_decrementInterlockedCount( &(m->m_nRef ) ) )
        {
            delete m;
        }
    }

    static void convertToRemoteRuntimeException ( uno_Any **ppException,
                                             const ::rtl::OUString &sMessage,
                                             const Reference< XInterface > &rContext,
                                             Mapping &map )
    {

        uno_type_any_construct( *ppException ,
                                0 ,
                                getCppuType( (RuntimeException  *)0 ).getTypeLibType() ,
                                0 );

        typelib_CompoundTypeDescription * pCompType = 0 ;
        getCppuType( (Exception*)0 ).getDescription( (typelib_TypeDescription **) &pCompType );
        if( ! ((typelib_TypeDescription *)pCompType)->bComplete )
        {
            typelib_typedescription_complete( (typelib_TypeDescription**) &pCompType );
        }

        char *pValue = (char*) (*ppException)->pData;
        rtl_uString_assign( (rtl_uString ** ) pValue  , sMessage.pData );

        *((remote_Interface**) pValue+pCompType->pMemberOffsets[1]) =
            (remote_Interface*) map.mapInterface(
                rContext.get(), getCppuType( &rContext) );

        typelib_typedescription_release( (typelib_TypeDescription *) pCompType );
    }

    void OInstanceProviderWrapper::thisGetInstance(
        remote_InstanceProvider * pProvider ,
        uno_Environment *pEnvRemote,
        remote_Interface **ppRemoteI,
        rtl_uString *pInstanceName,
        typelib_InterfaceTypeDescription *pType,
        uno_Any **ppException
        )
    {
        OInstanceProviderWrapper * m = (OInstanceProviderWrapper *)pProvider;

        OSL_ASSERT( ppRemoteI );
        if( *ppRemoteI )
        {
            (*ppRemoteI)->release( *ppRemoteI );
            *ppRemoteI = 0;
        }

        if( OUString( pType->aBase.pTypeName ) ==
            getCppuType( (Reference<XInterface>*)0).getTypeName() )
        {
            OUString sCppuName( RTL_CONSTASCII_USTRINGPARAM( CPPU_CURRENT_LANGUAGE_BINDING_NAME ) );

            uno_Environment *pEnvThis = 0;
            uno_getEnvironment( &pEnvThis ,
                                sCppuName.pData ,
                                0 );
            Mapping map( pEnvThis , pEnvRemote );
            pEnvThis->release( pEnvThis );

            try
            {
                Reference< XInterface > r = m->m_rProvider->getInstance(
                    OUString( pInstanceName ) );

                *ppRemoteI = (remote_Interface*) map.mapInterface (
                    r.get(),
                    getCppuType( (Reference< XInterface > *) 0 )
                );

                if( *ppRemoteI && m->m_pBridgeCallback )
                {
                    m->m_pBridgeCallback->objectMappedSuccesfully();
                    m->m_pBridgeCallback = 0;
                }
                *ppException = 0;
            }
            catch( ::com::sun::star::container::NoSuchElementException &e )
            {
                // NoSuchElementException not specified, so convert it to a runtime exception
                convertToRemoteRuntimeException(
                    ppException , e.Message.pData , e.Context.get(), map );
            }
            catch( ::com::sun::star::uno::RuntimeException &e )
            {
                convertToRemoteRuntimeException(
                    ppException , e.Message.pData , e.Context.get(), map );
            }

        }
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.28); FILE MERGED 2008/03/31 07:25:26 rt 1.6.28.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: bridge_provider.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <stdio.h>

#include "remote_bridge.hxx"

#include <osl/diagnose.h>

#include <uno/mapping.hxx>
#include <uno/environment.h>

#include <bridges/remote/remote.h>

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::bridge;

namespace remotebridges_bridge
{

    OInstanceProviderWrapper::OInstanceProviderWrapper(
        const Reference <XInstanceProvider > & rProvider,
        ORemoteBridge * pBridgeCallback ) :
        m_rProvider( rProvider ),
        m_nRef( 0 ),
        m_pBridgeCallback( pBridgeCallback )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
        acquire = thisAcquire;
        release = thisRelease;
        getInstance = thisGetInstance;
    }

    OInstanceProviderWrapper::~OInstanceProviderWrapper()
    {
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    void OInstanceProviderWrapper::thisAcquire( remote_InstanceProvider *p )
    {
        OInstanceProviderWrapper * m = (OInstanceProviderWrapper *) p;
        osl_incrementInterlockedCount( &(m->m_nRef ) );
    }

    void OInstanceProviderWrapper::thisRelease( remote_InstanceProvider *p )
    {
        OInstanceProviderWrapper * m = ( OInstanceProviderWrapper *) p;
        if( ! osl_decrementInterlockedCount( &(m->m_nRef ) ) )
        {
            delete m;
        }
    }

    static void convertToRemoteRuntimeException ( uno_Any **ppException,
                                             const ::rtl::OUString &sMessage,
                                             const Reference< XInterface > &rContext,
                                             Mapping &map )
    {

        uno_type_any_construct( *ppException ,
                                0 ,
                                getCppuType( (RuntimeException  *)0 ).getTypeLibType() ,
                                0 );

        typelib_CompoundTypeDescription * pCompType = 0 ;
        getCppuType( (Exception*)0 ).getDescription( (typelib_TypeDescription **) &pCompType );
        if( ! ((typelib_TypeDescription *)pCompType)->bComplete )
        {
            typelib_typedescription_complete( (typelib_TypeDescription**) &pCompType );
        }

        char *pValue = (char*) (*ppException)->pData;
        rtl_uString_assign( (rtl_uString ** ) pValue  , sMessage.pData );

        *((remote_Interface**) pValue+pCompType->pMemberOffsets[1]) =
            (remote_Interface*) map.mapInterface(
                rContext.get(), getCppuType( &rContext) );

        typelib_typedescription_release( (typelib_TypeDescription *) pCompType );
    }

    void OInstanceProviderWrapper::thisGetInstance(
        remote_InstanceProvider * pProvider ,
        uno_Environment *pEnvRemote,
        remote_Interface **ppRemoteI,
        rtl_uString *pInstanceName,
        typelib_InterfaceTypeDescription *pType,
        uno_Any **ppException
        )
    {
        OInstanceProviderWrapper * m = (OInstanceProviderWrapper *)pProvider;

        OSL_ASSERT( ppRemoteI );
        if( *ppRemoteI )
        {
            (*ppRemoteI)->release( *ppRemoteI );
            *ppRemoteI = 0;
        }

        if( OUString( pType->aBase.pTypeName ) ==
            getCppuType( (Reference<XInterface>*)0).getTypeName() )
        {
            OUString sCppuName( RTL_CONSTASCII_USTRINGPARAM( CPPU_CURRENT_LANGUAGE_BINDING_NAME ) );

            uno_Environment *pEnvThis = 0;
            uno_getEnvironment( &pEnvThis ,
                                sCppuName.pData ,
                                0 );
            Mapping map( pEnvThis , pEnvRemote );
            pEnvThis->release( pEnvThis );

            try
            {
                Reference< XInterface > r = m->m_rProvider->getInstance(
                    OUString( pInstanceName ) );

                *ppRemoteI = (remote_Interface*) map.mapInterface (
                    r.get(),
                    getCppuType( (Reference< XInterface > *) 0 )
                );

                if( *ppRemoteI && m->m_pBridgeCallback )
                {
                    m->m_pBridgeCallback->objectMappedSuccesfully();
                    m->m_pBridgeCallback = 0;
                }
                *ppException = 0;
            }
            catch( ::com::sun::star::container::NoSuchElementException &e )
            {
                // NoSuchElementException not specified, so convert it to a runtime exception
                convertToRemoteRuntimeException(
                    ppException , e.Message.pData , e.Context.get(), map );
            }
            catch( ::com::sun::star::uno::RuntimeException &e )
            {
                convertToRemoteRuntimeException(
                    ppException , e.Message.pData , e.Context.get(), map );
            }

        }
    }
}
<|endoftext|>