3 #include <cuda_runtime.h>
5 static const int LOG_BANK_COUNT = 4;
7 static inline __device__ __host__ unsigned shared_offset(unsigned i)
9 return i + (i >> LOG_BANK_COUNT);
12 static inline __device__ __host__ unsigned offset_a(unsigned offset, unsigned i)
14 return shared_offset(offset * (2*i + 1) - 1);
17 static inline __device__ __host__ unsigned offset_b(unsigned offset, unsigned i)
19 return shared_offset(offset * (2*i + 2) - 1);
22 static inline __device__ __host__ unsigned lpot(unsigned x)
24 --x; x |= x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return ++x;
28 __global__ void prefix_sum_block(T *in, T *out, unsigned n)
30 extern __shared__ T temp[];
32 int idx = threadIdx.x;
33 int blocksize = blockDim.x;
35 temp[shared_offset(idx )] = (idx < n) ? in[idx ] : 0;
36 temp[shared_offset(idx + blocksize)] = (idx + blocksize < n) ? in[idx + blocksize] : 0;
39 for (offset = 1, d = blocksize; d > 0; d >>= 1, offset <<= 1) {
42 unsigned a = offset_a(offset, idx), b = offset_b(offset, idx);
47 if (idx == 0) temp[shared_offset(blocksize*2 - 1)] = 0;
49 for (d = 1; d <= blocksize; d <<= 1) {
54 unsigned a = offset_a(offset, idx), b = offset_b(offset, idx);
62 if (idx < n) out[idx ] = temp[shared_offset(idx )];
63 if (idx + blocksize < n) out[idx + blocksize] = temp[shared_offset(idx + blocksize)];
67 void prefix_sum(T *in, T *out, unsigned n)
70 unsigned n_lpot = lpot(n);
73 cudaError_t error = cudaMallocPitch((void**)&device_values, &n_pitch, sizeof(T)*n, 2);
75 printf("error %u allocating width %lu height %u\n", error, sizeof(T)*n, 2);
79 cudaMemcpy(device_values, in, sizeof(T)*n, cudaMemcpyHostToDevice);
81 prefix_sum_block<<<1, n_lpot/2, shared_offset(n_lpot)*sizeof(T)>>>
82 ((T*)device_values, (T*)(device_values + n_pitch), n);
84 cudaMemcpy(out, device_values + n_pitch, sizeof(T)*n, cudaMemcpyDeviceToHost);
85 cudaFree(device_values);
92 static unsigned in_values[1024], out_values[1024];
94 for (int i = 0; i < 1024; ++i)
95 in_values[i] = rand() >> 21;
97 prefix_sum(in_values, out_values, 1024);
99 for (int i = 0; i < 1024; ++i)
100 printf("%5d => %5d\n", in_values[i], out_values[i]);