/*
prodmvEz.cu
u = Av (Ez)
*/

#include "oth.h"
#include "oth_cuda.h"

__host__ __device__ __forceinline__
static void prodmvEz_(
	int i, int j, int k,
	const cuDoubleComplex *a, const cuDoubleComplex *v, cuDoubleComplex *u,
	param_t *q)
{
	int64_t n = nEZ(q, i, j, k);
	int64_t p[NNZ];
	p[ 0] = nEZ(q, i,     j,     k    );
	p[ 1] = nEZ(q, i + 1, j,     k    );
	p[ 2] = nEZ(q, i - 1, j,     k    );
	p[ 3] = nEZ(q, i,     j + 1, k    );
	p[ 4] = nEZ(q, i,     j - 1, k    );
	p[ 5] = nEX(q, i,     j,     k + 1);
	p[ 6] = nEX(q, i,     j,     k    );
	p[ 7] = nEX(q, i - 1, j,     k + 1);
	p[ 8] = nEX(q, i - 1, j,     k    );
	p[ 9] = nEY(q, i,     j,     k + 1);
	p[10] = nEY(q, i,     j,     k    );
	p[11] = nEY(q, i,     j - 1, k + 1);
	p[12] = nEY(q, i,     j - 1, k    );

	cuDoubleComplex sum = make_cuDoubleComplex(0, 0);
	for (int m = 0; m < NNZ; m++) {
		sum = cuCadd(sum, cuCmul(a[(n * NNZ) + m], v[p[m]]));
	}
	u[n] = sum;
}

__global__
static void prodmvEz_gpu(
	int i0, int i1, int j0, int j1, int k0, int k1,
	const cuDoubleComplex *a, const cuDoubleComplex *v, cuDoubleComplex *u)
{
	int i = i0 + threadIdx.z + (blockIdx.z * blockDim.z);
	int j = j0 + threadIdx.y + (blockIdx.y * blockDim.y);
	int k = k0 + threadIdx.x + (blockIdx.x * blockDim.x);
	if ((i <= i1) &&
	    (j <= j1) &&
	    (k <= k1)) {
		prodmvEz_(
			i, j, k,
			a, v, u,
			&d_Param);
	}
}

static void prodmvEz_cpu(
	int i0, int i1, int j0, int j1, int k0, int k1,
	const cuDoubleComplex *a, const cuDoubleComplex *v, cuDoubleComplex *u)
{
	for (int i = i0; i <= i1; i++) {
	for (int j = j0; j <= j1; j++) {
	for (int k = k0; k <= k1; k++) {
		prodmvEz_(
			i, j, k,
			a, v, u,
			&h_Param);
	}
	}
	}
}

void prodmvEz(const cuDoubleComplex *a, const cuDoubleComplex *v, cuDoubleComplex *u)
{
	if (GPU) {
		cudaMemcpyToSymbol(d_Param, &h_Param, sizeof(param_t));
		dim3 block(BLOCK_X, BLOCK_Y, 1);
		dim3 grid(
			CEIL(k1Ez - k0Ez + 1, block.x),
			CEIL(j1Ez - j0Ez + 1, block.y),
			CEIL(i1Ez - i0Ez + 1, block.z));
		prodmvEz_gpu<<<grid, block>>>(
			i0Ez, i1Ez, j0Ez, j1Ez, k0Ez, k1Ez,
			a, v, u);
		if (UM) cudaDeviceSynchronize();
	}
	else {
		prodmvEz_cpu(
			i0Ez, i1Ez, j0Ez, j1Ez, k0Ez, k1Ez,
			a, v, u);
	}
}
