/*
prodmvEx.cu
u = Av (Ex)
*/

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

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

	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 prodmvEx_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)) {
		prodmvEx_(
			i, j, k,
			a, v, u,
			&d_Param);
	}
}

static void prodmvEx_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++) {
		prodmvEx_(
			i, j, k,
			a, v, u,
			&h_Param);
	}
	}
	}
}

void prodmvEx(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(k1Ex - k0Ex + 1, block.x),
			CEIL(j1Ex - j0Ex + 1, block.y),
			CEIL(i1Ex - i0Ex + 1, block.z));
		prodmvEx_gpu<<<grid, block>>>(
			i0Ex, i1Ex, j0Ex, j1Ex, k0Ex, k1Ex,
			a, v, u);
		if (UM) cudaDeviceSynchronize();
	}
	else {
		prodmvEx_cpu(
			i0Ex, i1Ex, j0Ex, j1Ex, k0Ex, k1Ex,
			a, v, u);
	}
}
