Debian Codegraph @

src/nouveau/compiler/nak/hw_runner.rs

raw
1 // Copyright © 2022 Collabora, Ltd.
2 // SPDX-License-Identifier: MIT
3
4 use compiler::bindings::*;
5 use nak_bindings::*;
6 use nv_push_rs::Push as NvPush;
7 use nvidia_headers::classes::cla0c0::mthd as cla0c0;
8 use nvidia_headers::classes::clb1c0::mthd as clb1c0;
9 use nvidia_headers::classes::clb1c0::MAXWELL_COMPUTE_B;
10 use nvidia_headers::classes::clc3c0::mthd as clc3c0;
11 use nvidia_headers::classes::clc3c0::VOLTA_COMPUTE_A;
12 use nvidia_headers::classes::clc6c0::mthd as clc6c0;
13 use nvidia_headers::classes::clc6c0::AMPERE_COMPUTE_A;
14 use nvidia_headers::classes::clcbc0::HOPPER_COMPUTE_A;
15
16 use std::io;
17 use std::ops::Deref;
18 use std::ptr;
19 use std::ptr::NonNull;
20 use std::slice;
21 use std::sync::atomic::{AtomicU64, Ordering};
22 use std::sync::{Arc, Mutex};
23
24 unsafe fn is_nvidia_device(dev: drmDevicePtr) -> bool {
25 unsafe {
26 match (*dev).bustype as u32 {
27 DRM_BUS_PCI => {
28 let pci = (*dev).deviceinfo.pci.as_ref().unwrap();
29 pci.vendor_id == (NVIDIA_VENDOR_ID as u16)
30 }
31 _ => false,
32 }
33 }
34 }
35
36 #[repr(C)]
37 pub struct CB0 {
38 pub data_addr_lo: u32,
39 pub data_addr_hi: u32,
40 pub data_stride: u32,
41 pub invocations: u32,
42 }
43
44 struct DrmDevices {
45 num_devices: usize,
46 devices: [drmDevicePtr; 16],
47 }
48
49 impl DrmDevices {
50 fn get() -> io::Result<Self> {
51 unsafe {
52 let mut devices: [drmDevicePtr; 16] = [std::ptr::null_mut(); 16];
53 let num_devices = drmGetDevices(
54 devices.as_mut_ptr(),
55 devices.len().try_into().unwrap(),
56 );
57 if num_devices < 0 {
58 return Err(io::Error::last_os_error());
59 }
60 Ok(DrmDevices {
61 num_devices: num_devices.try_into().unwrap(),
62 devices,
63 })
64 }
65 }
66
67 fn iter(&self) -> slice::Iter<'_, drmDevicePtr> {
68 self.devices[..self.num_devices].iter()
69 }
70 }
71
72 impl Deref for DrmDevices {
73 type Target = [drmDevicePtr];
74
75 fn deref(&self) -> &[drmDevicePtr] {
76 &self.devices[..self.num_devices]
77 }
78 }
79
80 impl Drop for DrmDevices {
81 fn drop(&mut self) {
82 unsafe {
83 drmFreeDevices(
84 self.devices.as_mut_ptr(),
85 self.num_devices.try_into().unwrap(),
86 );
87 }
88 }
89 }
90
91 pub struct Device {
92 dev: NonNull<nouveau_ws_device>,
93 next_addr: AtomicU64,
94 }
95
96 impl Device {
97 pub fn new(dev_id: Option<usize>) -> io::Result<Arc<Self>> {
98 let drm_devices = DrmDevices::get()?;
99 unsafe {
100 let drm_dev = if let Some(dev_id) = dev_id {
101 if dev_id >= drm_devices.len() {
102 return Err(io::Error::new(
103 io::ErrorKind::NotFound,
104 "Unknown device {dev_id}",
105 ));
106 }
107 drm_devices[dev_id]
108 } else {
109 if let Some(dev) =
110 drm_devices.iter().find(|dev| is_nvidia_device(**dev))
111 {
112 *dev
113 } else {
114 return Err(io::Error::new(
115 io::ErrorKind::NotFound,
116 "Failed to find an NVIDIA device",
117 ));
118 }
119 };
120
121 let dev = nouveau_ws_device_new(drm_dev);
122 let Some(dev) = NonNull::new(dev) else {
123 return Err(io::Error::last_os_error());
124 };
125
126 Ok(Arc::new(Device {
127 dev,
128 next_addr: AtomicU64::new(1 << 16),
129 }))
130 }
131 }
132
133 pub fn dev_info(&self) -> &nv_device_info {
134 unsafe { &self.dev.as_ref().info }
135 }
136
137 fn fd(&self) -> i32 {
138 unsafe { self.dev.as_ref().fd }
139 }
140
141 fn ws_dev(&self) -> *mut nouveau_ws_device {
142 self.dev.as_ptr()
143 }
144 }
145
146 impl Drop for Device {
147 fn drop(&mut self) {
148 unsafe { nouveau_ws_device_destroy(self.ws_dev()) }
149 }
150 }
151
152 pub struct Context {
153 dev: Arc<Device>,
154 ctx: NonNull<nouveau_ws_context>,
155 syncobj: u32,
156 sync_value: Mutex<u64>,
157 }
158
159 impl Context {
160 pub fn new(dev: Arc<Device>) -> io::Result<Self> {
161 unsafe {
162 let mut ctx: *mut nouveau_ws_context = std::ptr::null_mut();
163 let err = nouveau_ws_context_create(
164 dev.ws_dev(),
165 NOUVEAU_WS_ENGINE_COMPUTE,
166 &mut ctx,
167 );
168 if err != 0 {
169 return Err(io::Error::last_os_error());
170 }
171 let ctx = NonNull::new(ctx).unwrap();
172
173 let mut syncobj = 0_u32;
174 let err = drmSyncobjCreate(dev.fd(), 0, &mut syncobj);
175 if err != 0 {
176 nouveau_ws_context_destroy(ctx.as_ptr());
177 return Err(io::Error::last_os_error());
178 }
179
180 Ok(Context {
181 dev,
182 ctx,
183 syncobj,
184 sync_value: Mutex::new(0),
185 })
186 }
187 }
188
189 pub fn exec(&self, addr: u64, len: u16) -> io::Result<()> {
190 let sync_value = unsafe {
191 let mut sync_value = self.sync_value.lock().unwrap();
192 *sync_value += 1;
193
194 let push = drm_nouveau_exec_push {
195 va: addr,
196 va_len: len.into(),
197 flags: 0,
198 };
199 let sig = drm_nouveau_sync {
200 flags: DRM_NOUVEAU_SYNC_TIMELINE_SYNCOBJ,
201 handle: self.syncobj,
202 timeline_value: *sync_value,
203 };
204 let exec = drm_nouveau_exec {
205 channel: self.ctx.as_ref().channel as u32,
206 wait_count: 0,
207 wait_ptr: 0,
208 push_count: 1,
209 push_ptr: &push as *const _ as u64,
210 sig_count: 1,
211 sig_ptr: &sig as *const _ as u64,
212 };
213 let err = drmIoctl(
214 self.dev.fd(),
215 DRM_RS_IOCTL_NOUVEAU_EXEC.into(),
216 &exec as *const _ as *mut std::os::raw::c_void,
217 );
218 if err != 0 {
219 return Err(io::Error::last_os_error());
220 }
221 *sync_value
222 };
223 // The close of this unsafe { } drops the lock
224
225 unsafe {
226 let err = drmSyncobjTimelineWait(
227 self.dev.fd(),
228 &self.syncobj as *const _ as *mut _,
229 &sync_value as *const _ as *mut _,
230 1, // num_handles
231 i64::MAX, // timeout_nsec
232 DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT,
233 std::ptr::null_mut(),
234 );
235 if err != 0 {
236 return Err(io::Error::last_os_error());
237 }
238
239 // Exec again to check for errors
240 let mut exec = drm_nouveau_exec {
241 channel: self.ctx.as_ref().channel as u32,
242 wait_count: 0,
243 wait_ptr: 0,
244 push_count: 0,
245 push_ptr: 0,
246 sig_count: 0,
247 sig_ptr: 0,
248 };
249 let err = drmIoctl(
250 self.dev.fd(),
251 DRM_RS_IOCTL_NOUVEAU_EXEC.into(),
252 ptr::from_mut(&mut exec).cast(),
253 );
254 if err != 0 {
255 return Err(io::Error::last_os_error());
256 }
257 }
258
259 Ok(())
260 }
261 }
262
263 impl Drop for Context {
264 fn drop(&mut self) {
265 unsafe {
266 drmSyncobjDestroy(self.dev.fd(), self.syncobj);
267 nouveau_ws_context_destroy(self.ctx.as_ptr());
268 }
269 }
270 }
271
272 pub struct BO {
273 dev: Arc<Device>,
274 bo: NonNull<nouveau_ws_bo>,
275 pub addr: u64,
276 pub map: *mut std::os::raw::c_void,
277 }
278
279 impl BO {
280 pub fn new(dev: Arc<Device>, size: u64) -> io::Result<BO> {
281 let size = size.next_multiple_of(4096);
282
283 let mut map: *mut std::os::raw::c_void = std::ptr::null_mut();
284 let bo = unsafe {
285 nouveau_ws_bo_new_mapped(
286 dev.ws_dev(),
287 size,
288 0, // align
289 NOUVEAU_WS_BO_GART,
290 NOUVEAU_WS_BO_RDWR,
291 ptr::from_mut(&mut map),
292 )
293 };
294 let Some(bo) = NonNull::new(bo) else {
295 return Err(io::Error::last_os_error());
296 };
297 assert!(!map.is_null());
298
299 let addr = dev.next_addr.fetch_add(size, Ordering::Relaxed);
300 assert!(addr % 4096 == 0);
301
302 unsafe {
303 nouveau_ws_bo_bind_vma(
304 dev.ws_dev(),
305 bo.as_ptr(),
306 addr,
307 size,
308 0, // bo_offset
309 0, // pte_kind
310 );
311 }
312
313 Ok(BO { dev, bo, addr, map })
314 }
315 }
316
317 impl Drop for BO {
318 fn drop(&mut self) {
319 unsafe {
320 nouveau_ws_bo_unbind_vma(
321 self.dev.dev.as_ptr(),
322 self.addr,
323 self.bo.as_ref().size,
324 );
325 nouveau_ws_bo_destroy(self.bo.as_ptr());
326 }
327 }
328 }
329
330 struct QMDHeapImpl {
331 dev: Arc<Device>,
332 bos: Vec<BO>,
333 last_offset: u32,
334 free: Vec<(u64, *mut std::os::raw::c_void)>,
335 }
336
337 struct QMDHeap {
338 pub qmd_size_B: u32,
339 imp: Mutex<QMDHeapImpl>,
340 }
341
342 struct QMD<'a> {
343 heap: &'a QMDHeap,
344 pub addr: u64,
345 pub map: *mut std::os::raw::c_void,
346 }
347
348 impl Drop for QMD<'_> {
349 fn drop(&mut self) {
350 let mut heap = self.heap.imp.lock().unwrap();
351 heap.free.push((self.addr, self.map));
352 }
353 }
354
355 impl QMDHeap {
356 const BO_SIZE: u32 = 1 << 16;
357
358 fn new(dev: Arc<Device>) -> Self {
359 let qmd_size_B = unsafe { nak_qmd_size_B(dev.dev_info()) };
360 Self {
361 qmd_size_B,
362 imp: Mutex::new(QMDHeapImpl {
363 dev,
364 bos: Vec::new(),
365 last_offset: Self::BO_SIZE,
366 free: Vec::new(),
367 }),
368 }
369 }
370
371 fn alloc_qmd<'a>(&'a self) -> io::Result<QMD<'a>> {
372 let mut imp = self.imp.lock().unwrap();
373 if let Some((addr, map)) = imp.free.pop() {
374 return Ok(QMD {
375 heap: self,
376 addr,
377 map,
378 });
379 }
380
381 if imp.last_offset >= Self::BO_SIZE {
382 let dev = imp.dev.clone();
383 imp.bos.push(BO::new(dev, Self::BO_SIZE.into())?);
384 imp.last_offset = 0;
385 }
386
387 let bo = imp.bos.last().unwrap();
388 let addr = bo.addr + u64::from(imp.last_offset);
389 let map =
390 unsafe { bo.map.byte_offset(imp.last_offset.try_into().unwrap()) };
391 imp.last_offset += self.qmd_size_B.next_multiple_of(NAK_QMD_ALIGN_B);
392
393 Ok(QMD {
394 heap: self,
395 addr,
396 map,
397 })
398 }
399 }
400
401 pub struct Runner {
402 dev: Arc<Device>,
403 ctx: Context,
404 qmd_heap: QMDHeap,
405 }
406
407 impl Runner {
408 pub fn new(dev_id: Option<usize>) -> Runner {
409 let dev = Device::new(dev_id).expect("Failed to create nouveau device");
410 let ctx = Context::new(dev.clone()).expect("Failed to create context");
411 let qmd_heap = QMDHeap::new(dev.clone());
412 Runner { dev, ctx, qmd_heap }
413 }
414
415 pub fn device(&self) -> Arc<Device> {
416 self.dev.clone()
417 }
418
419 pub fn dev_info(&self) -> &nv_device_info {
420 self.dev.dev_info()
421 }
422
423 pub unsafe fn run_raw(
424 &self,
425 shader: &nak_shader_bin,
426 invocations: u32,
427 data_stride: u32,
428 data: *mut std::os::raw::c_void,
429 data_size: usize,
430 ) -> io::Result<()> {
431 let cs_info = unsafe {
432 assert!(shader.info.stage == MESA_SHADER_COMPUTE);
433 &shader.info.__bindgen_anon_1.cs
434 };
435 assert!(cs_info.local_size[1] == 1 && cs_info.local_size[2] == 1);
436 let local_size = cs_info.local_size[0];
437
438 // Compute the needed size of the buffer
439 let mut size = 0_usize;
440
441 const MAX_PUSH_DW: usize = 256;
442 let push_offset = size;
443 size = push_offset + 4 * MAX_PUSH_DW;
444
445 let shader_offset = size.next_multiple_of(0x80);
446 size = shader_offset + usize::try_from(shader.code_size).unwrap();
447
448 let cb0_offset = size.next_multiple_of(256);
449 size = cb0_offset + size_of::<CB0>();
450
451 let data_offset = size.next_multiple_of(256);
452 size = data_offset + data_size;
453
454 let bo = BO::new(self.dev.clone(), size.try_into().unwrap())?;
455
456 // Copy the data from the caller into our BO
457 let data_addr = bo.addr + u64::try_from(data_offset).unwrap();
458 unsafe {
459 let data_map = bo.map.byte_offset(data_offset.try_into().unwrap());
460 if data_size > 0 {
461 std::ptr::copy(data, data_map, data_size);
462 }
463 }
464
465 // Fill out cb0
466 let cb0_addr = bo.addr + u64::try_from(cb0_offset).unwrap();
467 unsafe {
468 let cb0_map = bo.map.byte_offset(cb0_offset.try_into().unwrap());
469 cb0_map.cast::<CB0>().write(CB0 {
470 data_addr_lo: data_addr as u32,
471 data_addr_hi: (data_addr >> 32) as u32,
472 data_stride,
473 invocations,
474 });
475 }
476
477 // Upload the shader
478 let shader_addr = bo.addr + u64::try_from(shader_offset).unwrap();
479 unsafe {
480 let shader_map =
481 bo.map.byte_offset(shader_offset.try_into().unwrap());
482 std::ptr::copy(
483 shader.code,
484 shader_map,
485 shader.code_size.try_into().unwrap(),
486 );
487 }
488
489 // Populate and upload the QMD
490 let mut qmd_cbufs: [nak_qmd_cbuf; 8] = Default::default();
491 qmd_cbufs[0] = nak_qmd_cbuf {
492 index: 0,
493 size: size_of::<CB0>().next_multiple_of(256).try_into().unwrap(),
494 addr: cb0_addr,
495 };
496 let qmd_info = nak_qmd_info {
497 // Pre-Volta, we set the program region to the start of the bo
498 addr: if self.dev_info().cls_compute < VOLTA_COMPUTE_A {
499 shader_offset.try_into().unwrap()
500 } else {
501 shader_addr
502 },
503 smem_size: unsafe { shader.info.__bindgen_anon_1.cs }
504 .smem_size
505 .into(),
506 global_size: [invocations.div_ceil(local_size.into()), 1, 1],
507 num_cbufs: 1,
508 cbufs: qmd_cbufs,
509 };
510
511 let qmd = self.qmd_heap.alloc_qmd()?;
512 unsafe {
513 nak_fill_qmd(
514 self.dev_info(),
515 &shader.info,
516 &qmd_info,
517 qmd.map,
518 self.qmd_heap.qmd_size_B.try_into().unwrap(),
519 );
520 }
521
522 // Fill out the pushbuf
523 let mut p = NvPush::new();
524
525 p.push_method(cla0c0::SetObject {
526 class_id: self.dev_info().cls_compute.into(),
527 engine_id: 0,
528 });
529 if self.dev_info().cls_compute < VOLTA_COMPUTE_A {
530 p.push_method(cla0c0::SetProgramRegionA {
531 address_upper: (bo.addr >> 32) as u32,
532 });
533 p.push_method(cla0c0::SetProgramRegionB {
534 address_lower: bo.addr as u32,
535 });
536 }
537
538 let mut smem_base_addr = 0xfe000000_u64;
539 if self.dev_info().cls_compute >= HOPPER_COMPUTE_A {
540 // This needs to be 4GB aligned on Hopper+
541 smem_base_addr <<= 8;
542 }
543
544 let lmem_base_addr = 0xff000000_u32;
545 if self.dev_info().cls_compute >= VOLTA_COMPUTE_A {
546 p.push_method(clc3c0::SetShaderSharedMemoryWindowA {
547 base_address_upper: (smem_base_addr >> 32) as u32,
548 });
549 p.push_method(clc3c0::SetShaderSharedMemoryWindowB {
550 base_address: smem_base_addr as u32,
551 });
552
553 p.push_method(clc3c0::SetShaderLocalMemoryWindowA {
554 base_address_upper: 0,
555 });
556 p.push_method(clc3c0::SetShaderLocalMemoryWindowB {
557 base_address: lmem_base_addr,
558 });
559 } else {
560 p.push_method(cla0c0::SetShaderSharedMemoryWindow {
561 base_address: smem_base_addr as u32,
562 });
563 p.push_method(cla0c0::SetShaderLocalMemoryWindow {
564 base_address: lmem_base_addr,
565 });
566 }
567
568 if self.dev_info().cls_compute >= MAXWELL_COMPUTE_B {
569 p.push_method(clb1c0::InvalidateSkedCaches { v: 0 });
570 }
571
572 p.push_method(cla0c0::SendPcasA {
573 qmd_address_shifted8: (qmd.addr >> 8) as u32,
574 });
575 if self.dev_info().cls_compute >= AMPERE_COMPUTE_A {
576 p.push_method(clc6c0::SendSignalingPcas2B {
577 pcas_action: clc6c0::SendSignalingPcas2BPcasAction::InvalidateCopySchedule,
578 });
579 } else {
580 p.push_method(cla0c0::SendSignalingPcasB {
581 invalidate: true,
582 schedule: true,
583 });
584 }
585
586 let push_addr = bo.addr + u64::try_from(push_offset).unwrap();
587 unsafe {
588 let push_map = bo.map.byte_offset(push_offset.try_into().unwrap());
589 std::ptr::copy(p.as_ptr(), push_map.cast(), p.len());
590 }
591
592 let res = self.ctx.exec(push_addr, (p.len() * 4).try_into().unwrap());
593
594 // Always copy the data back to the caller, even if exec fails
595 unsafe {
596 let data_map = bo.map.byte_offset(data_offset.try_into().unwrap());
597 if data_size > 0 {
598 std::ptr::copy(data_map, data, data_size);
599 }
600 }
601
602 res
603 }
604
605 pub fn run<T>(
606 &self,
607 shader: &nak_shader_bin,
608 data: &mut [T],
609 ) -> io::Result<()> {
610 unsafe {
611 let stride = size_of::<T>();
612 self.run_raw(
613 shader,
614 data.len().try_into().unwrap(),
615 stride.try_into().unwrap(),
616 data.as_mut_ptr().cast(),
617 size_of_val(data),
618 )
619 }
620 }
621 }
622
623 unsafe impl Sync for Runner {}
624 unsafe impl Send for Runner {}