1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
// Copyright (c) 2020-2021 Via Technology Ltd. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::context::Context;

use cl3::device::{
    CL_DEVICE_SVM_COARSE_GRAIN_BUFFER, CL_DEVICE_SVM_FINE_GRAIN_BUFFER,
    CL_DEVICE_SVM_FINE_GRAIN_SYSTEM,
};
use cl3::memory::{svm_alloc, svm_free, CL_MEM_READ_WRITE, CL_MEM_SVM_FINE_GRAIN_BUFFER};
use cl3::types::{cl_device_svm_capabilities, cl_svm_mem_flags, cl_uint};
use libc::c_void;
use std::fmt;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;

struct SvmRawVec<'a, T> {
    ptr: *mut T,
    cap: usize,
    context: &'a Context,
    fine_grain_buffer: bool,
}

impl<'a, T> SvmRawVec<'a, T> {
    fn new(context: &'a Context, svm_capabilities: cl_device_svm_capabilities) -> Self {
        assert!(0 < mem::size_of::<T>(), "No Zero Sized Types!");

        assert!(
            0 != svm_capabilities
                & (CL_DEVICE_SVM_COARSE_GRAIN_BUFFER | CL_DEVICE_SVM_FINE_GRAIN_BUFFER),
            "No OpenCL SVM, use OpenCL buffers"
        );

        let fine_grain_system: bool = svm_capabilities & CL_DEVICE_SVM_FINE_GRAIN_SYSTEM != 0;
        assert!(!fine_grain_system, "SVM supports system memory, use Vec!");

        let fine_grain_buffer: bool = svm_capabilities & CL_DEVICE_SVM_FINE_GRAIN_BUFFER != 0;
        SvmRawVec {
            ptr: ptr::null_mut(),
            cap: 0,
            context,
            fine_grain_buffer,
        }
    }

    fn with_capacity(
        context: &'a Context,
        svm_capabilities: cl_device_svm_capabilities,
        capacity: usize,
    ) -> Self {
        let mut v = Self::new(context, svm_capabilities);
        v.grow(capacity);

        v
    }

    fn with_capacity_zeroed(
        context: &'a Context,
        svm_capabilities: cl_device_svm_capabilities,
        capacity: usize,
    ) -> Self {
        let mut v = Self::with_capacity(context, svm_capabilities, capacity);
        v.zero(capacity);

        v
    }

    fn grow(&mut self, count: usize) {
        let elem_size = mem::size_of::<T>();

        let mut new_cap = count;
        // if pushing or inserting, double the capacity
        if (0 < self.cap) && (count - self.cap == 1) {
            new_cap = 2 * self.cap;
        }

        let size = elem_size * new_cap;

        // Ensure within capacity.
        assert!(size <= (isize::MAX as usize) / 2, "capacity overflow");

        let svm_mem_flags: cl_svm_mem_flags = if self.fine_grain_buffer {
            CL_MEM_SVM_FINE_GRAIN_BUFFER | CL_MEM_READ_WRITE
        } else {
            CL_MEM_READ_WRITE
        };
        let alignment = mem::align_of::<T>();
        let ptr = svm_alloc(
            self.context.get(),
            svm_mem_flags,
            size,
            alignment as cl_uint,
        )
        .unwrap();
        assert!(!ptr.is_null(), "svm_alloc failed");

        // reallocation, copy old data to new pointer and free old memory
        if 0 < self.cap {
            unsafe { ptr::copy(self.ptr, ptr as *mut T, self.cap) };
            svm_free(self.context.get(), self.ptr as *mut c_void);
        }

        self.ptr = ptr as *mut T;
        self.cap = new_cap;
    }

    fn zero(&mut self, count: usize) {
        unsafe { ptr::write_bytes(self.ptr, 0u8, count) };
    }
}

impl<'a, T> Drop for SvmRawVec<'a, T> {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            svm_free(self.context.get(), self.ptr as *mut c_void);
            self.ptr = ptr::null_mut();
        }
    }
}

/// An OpenCL Shared Virtual Memory (SVM) vector.  
/// It has the lifetime of the [Context] that it was constructed from.  
/// Note: T cannot be a "zero sized type" (ZST).
pub struct SvmVec<'a, T> {
    buf: SvmRawVec<'a, T>,
    len: usize,
}

impl<'a, T> SvmVec<'a, T> {
    fn ptr(&self) -> *mut T {
        self.buf.ptr
    }

    /// The capacity of the vector.
    pub fn cap(&self) -> usize {
        self.buf.cap
    }

    /// The length of the vector.
    pub fn len(&self) -> usize {
        self.len
    }

    pub unsafe fn set_len(&mut self, new_len: usize) {
        if self.cap() < new_len {
            self.buf.grow(new_len);
        }
        self.len = new_len;
    }

    /// Construct an empty SvmVec from a [Context] and the svm_capabilities of
    /// the device (or devices) in the [Context].  
    /// The SvmVec has the lifetime of the [Context].
    pub fn new(context: &'a Context, svm_capabilities: cl_device_svm_capabilities) -> Self {
        SvmVec {
            buf: SvmRawVec::new(&context, svm_capabilities),
            len: 0,
        }
    }

    pub fn with_capacity(
        context: &'a Context,
        svm_capabilities: cl_device_svm_capabilities,
        capacity: usize,
    ) -> Self {
        SvmVec {
            buf: SvmRawVec::with_capacity(&context, svm_capabilities, capacity),
            len: 0,
        }
    }

    pub fn with_capacity_zeroed(
        context: &'a Context,
        svm_capabilities: cl_device_svm_capabilities,
        capacity: usize,
    ) -> Self {
        SvmVec {
            buf: SvmRawVec::with_capacity_zeroed(&context, svm_capabilities, capacity),
            len: 0,
        }
    }

    /// Reserve vector capacity.
    pub fn reserve(&mut self, capacity: usize) {
        self.buf.grow(capacity);
    }

    pub fn push(&mut self, elem: T) {
        if self.len == self.cap() {
            self.buf.grow(self.len + 1);
        }

        unsafe {
            ptr::write(self.ptr().offset(self.len as isize), elem);
        }

        // Can't fail, we'll OOM first.
        self.len += 1;
    }

    pub fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            None
        } else {
            self.len -= 1;
            unsafe { Some(ptr::read(self.ptr().offset(self.len as isize))) }
        }
    }

    pub fn insert(&mut self, index: usize, elem: T) {
        assert!(index <= self.len, "index out of bounds");
        if self.cap() == self.len {
            self.buf.grow(self.len + 1);
        }

        unsafe {
            if index < self.len {
                ptr::copy(
                    self.ptr().offset(index as isize),
                    self.ptr().offset(index as isize + 1),
                    self.len - index,
                );
            }
            ptr::write(self.ptr().offset(index as isize), elem);
            self.len += 1;
        }
    }

    pub fn remove(&mut self, index: usize) -> T {
        assert!(index < self.len, "index out of bounds");
        unsafe {
            self.len -= 1;
            let result = ptr::read(self.ptr().offset(index as isize));
            ptr::copy(
                self.ptr().offset(index as isize + 1),
                self.ptr().offset(index as isize),
                self.len - index,
            );
            result
        }
    }

    pub fn into_iter(self) -> IntoIter<'a, T> {
        unsafe {
            let iter = RawValIter::new(&self);
            let buf = ptr::read(&self.buf);
            mem::forget(self);

            IntoIter {
                iter: iter,
                _buf: buf,
            }
        }
    }

    pub fn drain(&mut self) -> Drain<T> {
        unsafe {
            let iter = RawValIter::new(&self);

            // this is a mem::forget safety thing. If Drain is forgotten, we just
            // leak the whole Vec's contents. Also we need to do this *eventually*
            // anyway, so why not do it now?
            self.len = 0;

            Drain {
                iter: iter,
                vec: PhantomData,
            }
        }
    }
}

impl<'a, T> Drop for SvmVec<'a, T> {
    fn drop(&mut self) {
        while let Some(_) = self.pop() {}
        // allocation is handled by SvmRawVec
    }
}

impl<'a, T> Deref for SvmVec<'a, T> {
    type Target = [T];
    fn deref(&self) -> &[T] {
        unsafe { std::slice::from_raw_parts(self.ptr(), self.len) }
    }
}

impl<'a, T> DerefMut for SvmVec<'a, T> {
    fn deref_mut(&mut self) -> &mut [T] {
        unsafe { std::slice::from_raw_parts_mut(self.ptr(), self.len) }
    }
}

impl<'a, T: Debug> fmt::Debug for SvmVec<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

struct RawValIter<T> {
    start: *const T,
    end: *const T,
}

impl<T> RawValIter<T> {
    unsafe fn new(slice: &[T]) -> Self {
        RawValIter {
            start: slice.as_ptr(),
            end: if mem::size_of::<T>() == 0 {
                ((slice.as_ptr() as usize) + slice.len()) as *const _
            } else if slice.len() == 0 {
                slice.as_ptr()
            } else {
                slice.as_ptr().offset(slice.len() as isize)
            },
        }
    }
}

impl<T> Iterator for RawValIter<T> {
    type Item = T;
    fn next(&mut self) -> Option<T> {
        if self.start == self.end {
            None
        } else {
            unsafe {
                let result = ptr::read(self.start);
                self.start = if mem::size_of::<T>() == 0 {
                    (self.start as usize + 1) as *const _
                } else {
                    self.start.offset(1)
                };
                Some(result)
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let elem_size = mem::size_of::<T>();
        let len =
            (self.end as usize - self.start as usize) / if elem_size == 0 { 1 } else { elem_size };
        (len, Some(len))
    }
}

impl<T> DoubleEndedIterator for RawValIter<T> {
    fn next_back(&mut self) -> Option<T> {
        if self.start == self.end {
            None
        } else {
            unsafe {
                self.end = if mem::size_of::<T>() == 0 {
                    (self.end as usize - 1) as *const _
                } else {
                    self.end.offset(-1)
                };
                Some(ptr::read(self.end))
            }
        }
    }
}

pub struct IntoIter<'a, T> {
    _buf: SvmRawVec<'a, T>, // we don't actually care about this. Just need it to live.
    iter: RawValIter<T>,
}

impl<'a, T> Iterator for IntoIter<'a, T> {
    type Item = T;
    fn next(&mut self) -> Option<T> {
        self.iter.next()
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, T> DoubleEndedIterator for IntoIter<'a, T> {
    fn next_back(&mut self) -> Option<T> {
        self.iter.next_back()
    }
}

impl<'a, T> Drop for IntoIter<'a, T> {
    fn drop(&mut self) {
        for _ in &mut *self {}
    }
}

pub struct Drain<'a, T: 'a> {
    vec: PhantomData<&'a mut SvmVec<'a, T>>,
    iter: RawValIter<T>,
}

impl<'a, T> Iterator for Drain<'a, T> {
    type Item = T;
    fn next(&mut self) -> Option<T> {
        self.iter.next()
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
    fn next_back(&mut self) -> Option<T> {
        self.iter.next_back()
    }
}

impl<'a, T> Drop for Drain<'a, T> {
    fn drop(&mut self) {
        // pre-drain the iter
        for _ in &mut self.iter {}
    }
}