-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphics.rs
More file actions
3048 lines (2753 loc) · 124 KB
/
graphics.rs
File metadata and controls
3048 lines (2753 loc) · 124 KB
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Graphics-related system calls.
//!
//! Provides syscalls for querying and drawing to the framebuffer.
//!
//! ## Window compositing syscalls (op=10-19)
//!
//! These syscalls support the GPU-composited window manager:
//! - op=10: `virgl_composite` — upload pixel buffer as full-screen GPU texture
//! - op=11: `create_window_buffer` — allocate shared pixel buffer for a window
//! - op=12: `register_window` — register a window buffer with the compositor
//! - op=13: `list_windows` — enumerate registered windows
//! - op=14: `read_window_buffer` — copy a window's pixel data
//! - op=15: `mark_window_dirty` — bump generation, block until compositor reads
//! - op=16: `composite_windows` — GPU composite all windows (BWM only)
//! - op=17: `set_window_position` — set window position
//! - op=18: `write_window_input` — write input events to a window's queue (BWM)
//! - op=19: `read_window_input` — read input events from window's queue (client)
//! - op=20: `map_compositor_texture` — map GPU texture into BWM's address space
//! - op=21: `map_window_buffer` — map window buffer into BWM's address space (read-only)
//! - op=22: `check_window_dirty` — lightweight generation check without pixel copy
//! - op=23: `compositor_wait` — block until window dirty/mouse/keyboard/registry change
//! - op=24: `resize_window_buffer` — resize a window's backing pages (client-side)
//! - op=25: `set_cursor_shape` — set the active cursor shape (arrow, resize arrows)
//! - op=26: `poll_modifier_state` — returns current modifier key bitmask (Shift/Ctrl/Alt/Super)
extern crate alloc;
// Architecture-specific framebuffer imports
#[cfg(all(target_arch = "x86_64", feature = "interactive"))]
use crate::logger::SHELL_FRAMEBUFFER;
#[cfg(target_arch = "aarch64")]
use crate::graphics::arm64_fb::SHELL_FRAMEBUFFER;
#[cfg(any(target_arch = "aarch64", feature = "interactive"))]
use crate::graphics::primitives::{Canvas, Color, Rect, fill_rect, draw_rect, fill_circle, draw_circle, draw_line};
use super::SyscallResult;
/// Counter for fb_flush syscalls (diagnostic — read from timer heartbeat)
#[cfg(target_arch = "aarch64")]
pub static FB_FLUSH_COUNT: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
/// Thread ID of the compositor when it's waiting for a dirty window.
/// Set by op=16 when nothing is dirty; cleared when the compositor wakes.
/// op=15 (mark_window_dirty) reads this to wake the compositor immediately.
#[cfg(target_arch = "aarch64")]
static COMPOSITOR_WAITING_THREAD: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
/// Registry generation counter — bumped when windows are registered/unregistered.
/// compositor_wait (op=23) compares this against its saved value to detect changes.
#[cfg(target_arch = "aarch64")]
static REGISTRY_GENERATION: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
/// Last mouse state seen by compositor_wait, packed as (x << 32 | y << 16 | buttons).
/// Compared against current mouse state to detect movement without a syscall.
#[cfg(target_arch = "aarch64")]
static COMPOSITOR_LAST_MOUSE: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
/// Set to 1 by mark_window_dirty (op=15) when it wakes the compositor.
/// compositor_wait checks this after waking to know if a dirty window caused the wake.
#[cfg(target_arch = "aarch64")]
static COMPOSITOR_DIRTY_WAKE: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
/// Timestamp (ns) of the last compositor_wait return.
/// Used to enforce a minimum inter-frame interval so the compositor doesn't
/// saturate the CPU when GPU wake is fast (e.g., MSI-X interrupt-driven).
#[cfg(target_arch = "aarch64")]
static COMPOSITOR_LAST_WAKE_NS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
/// Minimum nanoseconds between compositor_wait returns.
/// 5ms = 200 FPS cap — smooth enough for all use cases while preventing
/// the compositor from running flat-out when events arrive continuously.
#[cfg(target_arch = "aarch64")]
const MIN_FRAME_INTERVAL_NS: u64 = 5_000_000;
/// Wake the compositor thread if it's blocked in compositor_wait (op=23).
/// Called from input interrupt handlers (mouse, keyboard) to provide low-latency
/// input response without polling.
#[cfg(target_arch = "aarch64")]
pub fn wake_compositor_if_waiting() {
let tid = COMPOSITOR_WAITING_THREAD.load(core::sync::atomic::Ordering::Acquire);
if tid != 0 {
crate::task::scheduler::with_scheduler(|sched| {
sched.unblock(tid);
});
}
}
/// Clean up all window buffers owned by a terminated process.
/// Removes entries from the registry and wakes the compositor so it
/// discovers the removal and repaints.
#[cfg(target_arch = "aarch64")]
pub fn cleanup_windows_for_pid(pid: u64) {
let mut reg = WINDOW_REGISTRY.lock();
if reg.remove_for_pid(pid) {
REGISTRY_GENERATION.fetch_add(1, core::sync::atomic::Ordering::Release);
drop(reg);
wake_compositor_if_waiting();
}
}
/// Restore TTBR0 to the current process's page tables after blocking.
///
/// After a blocking syscall (mark_window_dirty), TTBR0 may point to a different
/// process's address space if the context switch hit PM lock contention.
#[cfg(target_arch = "aarch64")]
fn ensure_current_address_space() {
let thread_id = match crate::task::scheduler::current_thread_id() {
Some(id) => id,
None => return,
};
let manager_guard = crate::process::manager();
if let Some(ref manager) = *manager_guard {
if let Some((_pid, process)) = manager.find_process_by_thread(thread_id) {
if let Some(ref page_table) = process.page_table {
let ttbr0_value = page_table.level_4_frame().start_address().as_u64();
unsafe {
core::arch::asm!(
"dsb ishst",
"msr ttbr0_el1, {}",
"isb",
in(reg) ttbr0_value
);
}
}
}
}
}
// =============================================================================
// Window Buffer Registry — kernel-side window management for GPU compositing
// Only compiled for ARM64 (Parallels VirGL compositor path).
// =============================================================================
#[cfg(target_arch = "aarch64")]
use spin::Mutex;
#[cfg(target_arch = "aarch64")]
/// Maximum number of simultaneous window buffers
const MAX_WINDOW_BUFFERS: usize = 16;
/// Maximum window title length in bytes
#[cfg(target_arch = "aarch64")]
const MAX_TITLE_LEN: usize = 64;
/// Input event ring buffer size per window (power of 2 for fast masking)
#[cfg(target_arch = "aarch64")]
const INPUT_RING_SIZE: usize = 64;
/// Input event pushed by BWM into a window's ring buffer.
/// 12 bytes per event, matching the userspace `WindowInputEvent` struct.
#[cfg(target_arch = "aarch64")]
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub struct WindowInputEvent {
/// Event type: 1=KeyPress, 2=KeyRelease, 3=MouseMove, 4=MouseButton, 5=Focus, 6=Close
pub event_type: u16,
/// USB HID keycode or ASCII character
pub keycode: u16,
/// Window-local mouse X coordinate
pub mouse_x: i16,
/// Window-local mouse Y coordinate
pub mouse_y: i16,
/// Modifier bitmask (bit 0=shift, bit 1=ctrl, bit 2=alt)
pub modifiers: u16,
/// Scroll wheel delta (positive = scroll up, negative = scroll down)
pub scroll_y: i16,
}
#[cfg(target_arch = "aarch64")]
/// A registered window buffer backed by physical pages accessible via HHDM.
#[derive(Clone)]
struct WindowBuffer {
/// Unique buffer ID
id: u32,
/// Process that owns this buffer
owner_pid: u64,
/// Width in pixels
width: u32,
/// Height in pixels
height: u32,
/// Physical address of the first page (kept for compatibility, prefer page_phys_addrs)
#[allow(dead_code)]
phys_addr: u64,
/// Size in bytes
size: usize,
/// Virtual address mapped into owner's address space (for resize unmapping)
mapped_vaddr: u64,
/// Whether this buffer has been registered as a visible window
registered: bool,
/// Window title (UTF-8, truncated to MAX_TITLE_LEN)
title: [u8; MAX_TITLE_LEN],
/// Length of the title in bytes
title_len: usize,
/// Window position (set by compositor)
x: i32,
y: i32,
/// Z-order (0 = bottom, higher = closer to viewer). Set by compositor.
z_order: u32,
/// VirGL TEXTURE_2D resource ID (0 = not initialized)
virgl_resource_id: u32,
/// Whether VirGL texture has been created + backed + primed
virgl_initialized: bool,
/// Generation counter — bumped by client via mark_window_dirty
generation: u64,
/// Last generation uploaded via TRANSFER_TO_HOST_3D
last_uploaded_gen: u64,
/// Last generation read via read_window_buffer (op=14)
last_read_gen: u64,
/// Physical addresses of all backing pages (for VirGL scatter-gather)
page_phys_addrs: alloc::vec::Vec<u64>,
/// Thread ID waiting for compositor to consume this frame (frame pacing)
waiting_thread_id: Option<u64>,
/// Input event ring buffer (written by BWM via op=18, read by client via op=19)
input_ring: [WindowInputEvent; INPUT_RING_SIZE],
/// Write position in input ring (advanced by BWM)
input_head: usize,
/// Read position in input ring (advanced by client)
input_tail: usize,
/// Thread ID blocked on read_window_input (client waiting for input)
input_waiting_thread: Option<u64>,
}
#[cfg(target_arch = "aarch64")]
/// Info about a window, returned to userspace by list_windows.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct WindowInfo {
pub buffer_id: u32,
pub owner_pid: u32,
pub width: u32,
pub height: u32,
pub x: i32,
pub y: i32,
pub title_len: u32,
pub title: [u8; MAX_TITLE_LEN],
}
#[cfg(target_arch = "aarch64")]
impl Default for WindowInfo {
fn default() -> Self {
Self {
buffer_id: 0,
owner_pid: 0,
width: 0,
height: 0,
x: 0,
y: 0,
title_len: 0,
title: [0u8; MAX_TITLE_LEN],
}
}
}
#[cfg(target_arch = "aarch64")]
/// Global window buffer registry. Protected by a spinlock.
static WINDOW_REGISTRY: Mutex<WindowRegistry> = Mutex::new(WindowRegistry::new());
#[cfg(target_arch = "aarch64")]
struct WindowRegistry {
buffers: [Option<WindowBuffer>; MAX_WINDOW_BUFFERS],
next_id: u32,
}
#[cfg(target_arch = "aarch64")]
impl WindowRegistry {
const fn new() -> Self {
const NONE: Option<WindowBuffer> = None;
Self {
buffers: [NONE; MAX_WINDOW_BUFFERS],
next_id: 1,
}
}
fn allocate(&mut self, owner_pid: u64, width: u32, height: u32, phys_addr: u64, size: usize, page_phys_addrs: alloc::vec::Vec<u64>, mapped_vaddr: u64) -> Option<u32> {
let slot = self.buffers.iter().position(|b| b.is_none())?;
let id = self.next_id;
self.next_id += 1;
self.buffers[slot] = Some(WindowBuffer {
id,
owner_pid,
width,
height,
phys_addr,
size,
mapped_vaddr,
registered: false,
title: [0; MAX_TITLE_LEN],
title_len: 0,
x: 0,
y: 0,
z_order: 0,
virgl_resource_id: 0,
virgl_initialized: false,
generation: 1,
last_uploaded_gen: 0,
last_read_gen: 0,
page_phys_addrs,
waiting_thread_id: None,
input_ring: [WindowInputEvent::default(); INPUT_RING_SIZE],
input_head: 0,
input_tail: 0,
input_waiting_thread: None,
});
Some(id)
}
fn find(&self, buffer_id: u32) -> Option<&WindowBuffer> {
self.buffers.iter().find_map(|slot| {
slot.as_ref().filter(|b| b.id == buffer_id)
})
}
fn find_mut(&mut self, buffer_id: u32) -> Option<&mut WindowBuffer> {
self.buffers.iter_mut().find_map(|slot| {
slot.as_mut().filter(|b| b.id == buffer_id)
})
}
/// Remove all window buffers owned by a given process.
/// Returns true if any buffers were removed.
fn remove_for_pid(&mut self, pid: u64) -> bool {
let mut removed = false;
for slot in &mut self.buffers {
if let Some(ref buf) = slot {
if buf.owner_pid == pid {
// Capture id before clearing, then clear GPU texture slot
// so the next window that reuses this slot index does not
// inherit stale pixel data.
let buf_id = buf.id;
*slot = None;
removed = true;
let slot_idx = (buf_id as usize).saturating_sub(1) % 8;
crate::drivers::virtio::gpu_pci::clear_window_texture_slot(slot_idx);
}
}
}
removed
}
fn registered_windows(&self) -> alloc::vec::Vec<WindowInfo> {
let mut result = alloc::vec::Vec::new();
for slot in &self.buffers {
if let Some(ref buf) = slot {
if buf.registered {
let mut info = WindowInfo {
buffer_id: buf.id,
owner_pid: buf.owner_pid as u32,
width: buf.width,
height: buf.height,
x: buf.x,
y: buf.y,
title_len: buf.title_len as u32,
title: [0; MAX_TITLE_LEN],
};
info.title[..buf.title_len].copy_from_slice(&buf.title[..buf.title_len]);
result.push(info);
}
}
}
result
}
}
/// Framebuffer info structure returned by sys_fbinfo.
/// This matches the userspace FbInfo struct in libbreenix.
#[cfg(any(target_arch = "aarch64", feature = "interactive"))]
#[repr(C)]
pub struct FbInfo {
/// Width in pixels
pub width: u64,
/// Height in pixels
pub height: u64,
/// Stride (pixels per scanline, may be > width for alignment)
pub stride: u64,
/// Bytes per pixel (typically 3 or 4)
pub bytes_per_pixel: u64,
/// Pixel format: 0 = RGB, 1 = BGR, 2 = U8 (grayscale)
pub pixel_format: u64,
}
/// Maximum valid userspace address (canonical lower half)
/// Addresses above this are kernel space and must be rejected.
#[cfg(any(target_arch = "aarch64", feature = "interactive"))]
const USER_SPACE_MAX: u64 = crate::memory::layout::USER_STACK_REGION_END;
/// sys_fbinfo - Get framebuffer information
///
/// # Arguments
/// * `info_ptr` - Pointer to userspace FbInfo structure to fill
///
/// # Returns
/// * 0 on success
/// * -EFAULT if info_ptr is invalid or in kernel space
/// * -ENODEV if no framebuffer is available
#[cfg(any(target_arch = "aarch64", feature = "interactive"))]
pub fn sys_fbinfo(info_ptr: u64) -> SyscallResult {
// Validate pointer: must be non-null and in userspace address range
if info_ptr == 0 {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
// Reject kernel-space pointers to prevent kernel memory corruption
if info_ptr >= USER_SPACE_MAX {
log::warn!("sys_fbinfo: rejected kernel-space pointer {:#x}", info_ptr);
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
// Validate the entire FbInfo struct fits in userspace
let end_ptr = info_ptr.saturating_add(core::mem::size_of::<FbInfo>() as u64);
if end_ptr > USER_SPACE_MAX {
log::warn!("sys_fbinfo: buffer extends into kernel space");
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
// On ARM64, use the lock-free FbInfoCache to avoid contention with BWM's
// fb_flush, which holds SHELL_FRAMEBUFFER for ~400μs during full-screen
// pixel copies. Framebuffer dimensions are immutable after init.
#[cfg(target_arch = "aarch64")]
let info = {
let cache = match crate::graphics::arm64_fb::FB_INFO_CACHE.get() {
Some(c) => c,
None => {
log::warn!("sys_fbinfo: No framebuffer available");
return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64);
}
};
FbInfo {
width: cache.width as u64,
height: cache.height as u64,
stride: cache.stride as u64,
bytes_per_pixel: cache.bytes_per_pixel as u64,
pixel_format: if cache.is_bgr { 1 } else { 0 },
}
};
// On x86_64, acquire the framebuffer lock to read dimensions.
// Use try_lock with bounded spin since this is a one-time startup call.
#[cfg(not(target_arch = "aarch64"))]
let info = {
let fb = match SHELL_FRAMEBUFFER.get() {
Some(fb) => fb,
None => {
log::warn!("sys_fbinfo: No framebuffer available");
return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64);
}
};
let fb_guard = {
let mut guard = None;
for _ in 0..65536 {
if let Some(g) = fb.try_lock() {
guard = Some(g);
break;
}
core::hint::spin_loop();
}
match guard {
Some(g) => g,
None => {
log::warn!("sys_fbinfo: framebuffer lock busy after 65536 spins");
return SyscallResult::Err(super::ErrorCode::Busy as u64);
}
}
};
use crate::graphics::primitives::Canvas;
FbInfo {
width: fb_guard.width() as u64,
height: fb_guard.height() as u64,
stride: fb_guard.stride() as u64,
bytes_per_pixel: fb_guard.bytes_per_pixel() as u64,
pixel_format: if fb_guard.is_bgr() { 1 } else { 0 },
}
};
// Copy to userspace (pointer already validated above)
unsafe {
let info_out = info_ptr as *mut FbInfo;
core::ptr::write(info_out, info);
}
SyscallResult::Ok(0)
}
/// sys_fbinfo - Stub for non-interactive mode (returns ENODEV)
#[cfg(not(any(target_arch = "aarch64", feature = "interactive")))]
pub fn sys_fbinfo(_info_ptr: u64) -> SyscallResult {
// No framebuffer available in non-interactive mode
SyscallResult::Err(super::ErrorCode::InvalidArgument as u64)
}
/// Draw command operations for sys_fbdraw
#[cfg(any(target_arch = "aarch64", feature = "interactive"))]
#[repr(u32)]
#[allow(dead_code)]
pub enum FbDrawOp {
/// Clear the left pane with a color
Clear = 0,
/// Fill a rectangle: x, y, width, height, color
FillRect = 1,
/// Draw rectangle outline: x, y, width, height, color
DrawRect = 2,
/// Fill a circle: cx, cy, radius, color
FillCircle = 3,
/// Draw circle outline: cx, cy, radius, color
DrawCircle = 4,
/// Draw a line: x1, y1, x2, y2, color
DrawLine = 5,
/// Flush the framebuffer (for double-buffering)
Flush = 6,
/// Submit a VirGL GPU-rendered frame (balls array + background color)
VirglSubmitFrame = 7,
/// Batch flush multiple dirty rects with one DSB barrier
FlushBatch = 8,
}
/// Draw command structure passed from userspace.
/// Must match the FbDrawCmd struct in libbreenix.
#[cfg(any(target_arch = "aarch64", feature = "interactive"))]
#[repr(C)]
pub struct FbDrawCmd {
/// Operation code (FbDrawOp)
pub op: u32,
/// First parameter (x, cx, x1, or unused)
pub p1: i32,
/// Second parameter (y, cy, y1, or unused)
pub p2: i32,
/// Third parameter (width, radius, x2, or unused)
pub p3: i32,
/// Fourth parameter (height, y2, or unused)
pub p4: i32,
/// Color as packed RGB (0x00RRGGBB)
pub color: u32,
}
/// Get the width of the left (demo) pane
#[cfg(any(target_arch = "aarch64", feature = "interactive"))]
#[allow(dead_code)]
fn left_pane_width() -> usize {
if let Some(fb) = SHELL_FRAMEBUFFER.get() {
if let Some(fb_guard) = fb.try_lock() {
fb_guard.width() / 2
} else {
0
}
} else {
0
}
}
/// Get the height of the framebuffer
#[cfg(any(target_arch = "aarch64", feature = "interactive"))]
#[allow(dead_code)]
fn fb_height() -> usize {
if let Some(fb) = SHELL_FRAMEBUFFER.get() {
if let Some(fb_guard) = fb.try_lock() {
fb_guard.height()
} else {
0
}
} else {
0
}
}
/// Handle VirGL GPU rendering ops (7=balls, 9=rects) without needing SHELL_FRAMEBUFFER.
/// Called early in sys_fbdraw before acquiring the framebuffer lock.
#[cfg(target_arch = "aarch64")]
fn handle_virgl_op(cmd: &FbDrawCmd) -> SyscallResult {
match cmd.op {
7 => {
// VirglSubmitFrame: GPU-rendered balls
let desc_ptr = (cmd.p1 as u32 as u64) | ((cmd.p2 as u32 as u64) << 32);
if desc_ptr == 0 || desc_ptr >= USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let ball_count = unsafe { core::ptr::read(desc_ptr as *const u32) } as usize;
if ball_count > 16 {
return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64);
}
let balls_ptr = (desc_ptr + 8) as *const crate::drivers::virtio::gpu_pci::VirglBall;
let balls_end = desc_ptr + 8 + (ball_count as u64) * core::mem::size_of::<crate::drivers::virtio::gpu_pci::VirglBall>() as u64;
if balls_end > USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let balls = unsafe { core::slice::from_raw_parts(balls_ptr, ball_count) };
let bg_r = ((cmd.color >> 16) & 0xFF) as f32 / 255.0;
let bg_g = ((cmd.color >> 8) & 0xFF) as f32 / 255.0;
let bg_b = (cmd.color & 0xFF) as f32 / 255.0;
match crate::drivers::virtio::gpu_pci::virgl_render_frame(balls, bg_r, bg_g, bg_b) {
Ok(()) => SyscallResult::Ok(0),
Err(e) => {
crate::serial_println!("[virgl-syscall] render_frame FAILED: {}", e);
SyscallResult::Err(super::ErrorCode::InvalidArgument as u64)
}
}
}
9 => {
// VirglSubmitRects: GPU-rendered rectangles
let desc_ptr = (cmd.p1 as u32 as u64) | ((cmd.p2 as u32 as u64) << 32);
if desc_ptr == 0 || desc_ptr >= USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let rect_count = unsafe { core::ptr::read(desc_ptr as *const u32) } as usize;
if rect_count > 60 {
return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64);
}
let rects_ptr = (desc_ptr + 8) as *const crate::drivers::virtio::gpu_pci::VirglRect;
let rects_end = desc_ptr + 8 + (rect_count as u64) * core::mem::size_of::<crate::drivers::virtio::gpu_pci::VirglRect>() as u64;
if rects_end > USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let rects = unsafe { core::slice::from_raw_parts(rects_ptr, rect_count) };
let bg_r = ((cmd.color >> 16) & 0xFF) as f32 / 255.0;
let bg_g = ((cmd.color >> 8) & 0xFF) as f32 / 255.0;
let bg_b = (cmd.color & 0xFF) as f32 / 255.0;
match crate::drivers::virtio::gpu_pci::virgl_render_rects(rects, bg_r, bg_g, bg_b) {
Ok(()) => SyscallResult::Ok(0),
Err(e) => {
crate::serial_println!("[virgl-syscall] render_rects FAILED: {}", e);
SyscallResult::Err(super::ErrorCode::InvalidArgument as u64)
}
}
}
10 => {
// Composite: upload pixel buffer and display via active GPU backend
let buf_ptr = (cmd.p1 as u32 as u64) | ((cmd.p2 as u32 as u64) << 32);
let width = cmd.p3 as u32;
let height = cmd.p4 as u32;
if buf_ptr == 0 || buf_ptr >= USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
if width == 0 || height == 0 || width > 4096 || height > 4096 {
return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64);
}
let pixel_count = (width as u64) * (height as u64);
let buf_end = buf_ptr + pixel_count * 4;
if buf_end > USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let pixels = unsafe {
core::slice::from_raw_parts(buf_ptr as *const u32, pixel_count as usize)
};
match crate::graphics::compositor_backend() {
crate::graphics::CompositorBackend::VirGL => {
match crate::drivers::virtio::gpu_pci::virgl_composite_frame_textured(pixels, width, height) {
Ok(()) => SyscallResult::Ok(0),
Err(_) => {
match crate::drivers::virtio::gpu_pci::virgl_composite_frame(pixels, width, height) {
Ok(()) => SyscallResult::Ok(0),
Err(e) => {
crate::serial_println!("[composite] VirGL composite_frame FAILED: {}", e);
SyscallResult::Err(super::ErrorCode::InvalidArgument as u64)
}
}
}
}
}
crate::graphics::CompositorBackend::Svga3Stdu => {
match crate::drivers::vmware::svga3::composite_frame(pixels, width, height) {
Ok(()) => SyscallResult::Ok(0),
Err(e) => {
crate::serial_println!("[composite] SVGA3 composite_frame FAILED: {}", e);
SyscallResult::Err(super::ErrorCode::InvalidArgument as u64)
}
}
}
crate::graphics::CompositorBackend::None => {
SyscallResult::Err(super::ErrorCode::InvalidArgument as u64)
}
}
}
11 => {
// CreateWindowBuffer: allocate shared pixel buffer
// p1=width, p2=height, p3/p4 = output pointer (lo/hi) for mmap addr
// Returns: buffer_id in OK value, writes 64-bit mmap addr to *out_ptr
let width = cmd.p1 as u32;
let height = cmd.p2 as u32;
let out_ptr = (cmd.p3 as u32 as u64) | ((cmd.p4 as u32 as u64) << 32);
if width == 0 || height == 0 || width > 4096 || height > 4096 {
return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64);
}
handle_create_window_buffer(width, height, out_ptr)
}
12 => {
// RegisterWindow: register a buffer as a visible window
// p1=buffer_id, p2/p3 = title_ptr (lo/hi), p4=title_len
let buffer_id = cmd.p1 as u32;
let title_ptr = (cmd.p2 as u32 as u64) | ((cmd.p3 as u32 as u64) << 32);
let title_len = (cmd.p4 as u32) as usize;
if title_len > MAX_TITLE_LEN {
return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64);
}
if title_len > 0 && (title_ptr == 0 || title_ptr >= USER_SPACE_MAX) {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let title = if title_len > 0 {
unsafe { core::slice::from_raw_parts(title_ptr as *const u8, title_len) }
} else {
&[]
};
let registered = {
let mut reg = WINDOW_REGISTRY.lock();
match reg.find_mut(buffer_id) {
Some(buf) => {
buf.registered = true;
buf.title_len = title.len().min(MAX_TITLE_LEN);
buf.title[..buf.title_len].copy_from_slice(&title[..buf.title_len]);
true
}
None => false,
}
};
if registered {
// Bump registry generation + wake compositor so it discovers the new window
#[cfg(target_arch = "aarch64")]
{
REGISTRY_GENERATION.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
let compositor_tid = COMPOSITOR_WAITING_THREAD.load(core::sync::atomic::Ordering::Acquire);
if compositor_tid != 0 {
crate::task::scheduler::with_scheduler(|sched| {
sched.unblock(compositor_tid);
});
}
}
SyscallResult::Ok(0)
} else {
SyscallResult::Err(super::ErrorCode::InvalidArgument as u64)
}
}
13 => {
// ListWindows: copy registered window info to userspace
// p1/p2 = output buffer ptr (lo/hi), p3 = max entries
let out_ptr = (cmd.p1 as u32 as u64) | ((cmd.p2 as u32 as u64) << 32);
let max_entries = cmd.p3 as u32;
if out_ptr == 0 || out_ptr >= USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let entry_size = core::mem::size_of::<WindowInfo>() as u64;
let out_end = out_ptr + (max_entries as u64) * entry_size;
if out_end > USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let reg = WINDOW_REGISTRY.lock();
let windows = reg.registered_windows();
let count = windows.len().min(max_entries as usize);
unsafe {
let dst = out_ptr as *mut WindowInfo;
for (i, info) in windows.iter().take(count).enumerate() {
core::ptr::write(dst.add(i), *info);
}
}
SyscallResult::Ok(count as u64)
}
14 => {
// ReadWindowBuffer: copy a window's pixels to caller's buffer.
// Returns 0 if buffer hasn't changed since last read (skip copy).
// p1=buffer_id, p2/p3=dst_ptr (lo/hi), p4=max_bytes
let buffer_id = cmd.p1 as u32;
let dst_ptr = (cmd.p2 as u32 as u64) | ((cmd.p3 as u32 as u64) << 32);
let max_bytes = cmd.p4 as u32;
if dst_ptr == 0 || dst_ptr >= USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let dst_end = dst_ptr + max_bytes as u64;
if dst_end > USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let mut reg = WINDOW_REGISTRY.lock();
match reg.find_mut(buffer_id) {
Some(buf) => {
// Skip copy if generation hasn't changed since last read
if buf.generation == buf.last_read_gen {
return SyscallResult::Ok(0); // 0 = no new data
}
buf.last_read_gen = buf.generation;
let copy_bytes = buf.size.min(max_bytes as usize);
let phys_mem_offset = crate::memory::physical_memory_offset().as_u64();
// Copy page by page since MAP_SHARED pages are not contiguous
let mut offset = 0usize;
for &page_phys in buf.page_phys_addrs.iter() {
if offset >= copy_bytes { break; }
let chunk = (copy_bytes - offset).min(4096);
let src = (phys_mem_offset + page_phys) as *const u8;
unsafe {
core::ptr::copy_nonoverlapping(
src, (dst_ptr as *mut u8).add(offset), chunk,
);
}
offset += chunk;
}
SyscallResult::Ok(((buf.width as u64) << 32) | buf.height as u64)
}
None => SyscallResult::Err(super::ErrorCode::InvalidArgument as u64),
}
}
15 => {
// MarkWindowDirty: bump generation, then BLOCK until compositor consumes frame.
// This provides Wayland-style back-pressure / frame pacing — the client
// renders at exactly the compositor's display rate.
//
// Uses BlockedOnTimer with a 50ms timeout as fallback. The compositor
// calls unblock() to wake the client early when it uploads the frame.
// p1=buffer_id
let buffer_id = cmd.p1 as u32;
// Get current thread ID for compositor wake-up
let thread_id = match crate::task::scheduler::current_thread_id() {
Some(id) => id,
None => return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64),
};
// Bump generation and store waiting thread ID
{
let mut reg = WINDOW_REGISTRY.lock();
match reg.find_mut(buffer_id) {
Some(buf) => {
buf.generation += 1;
buf.waiting_thread_id = Some(thread_id);
}
None => return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64),
}
}
// Wake compositor if it's blocked waiting for a dirty window.
// This gives immediate frame delivery instead of waiting for a timer tick.
#[cfg(target_arch = "aarch64")]
{
COMPOSITOR_DIRTY_WAKE.store(true, core::sync::atomic::Ordering::Relaxed);
let compositor_tid = COMPOSITOR_WAITING_THREAD.load(core::sync::atomic::Ordering::Acquire);
if compositor_tid != 0 {
crate::task::scheduler::with_scheduler(|sched| {
sched.unblock(compositor_tid);
});
}
}
// Calculate timeout: 50ms from now (fallback if compositor doesn't wake us)
let (cur_secs, cur_nanos) = crate::time::get_monotonic_time_ns();
let now_ns = cur_secs as u64 * 1_000_000_000 + cur_nanos as u64;
let timeout_ns = now_ns.saturating_add(50_000_000); // 50ms
// Block the thread using the scheduler's timer infrastructure.
// The compositor will call unblock() when it consumes our frame,
// or wake_expired_timers() will wake us after 50ms as fallback.
crate::task::scheduler::with_scheduler(|sched| {
sched.block_current_for_compositor(timeout_ns);
});
// Enable preemption so timer interrupts can context-switch us out
#[cfg(target_arch = "aarch64")]
crate::per_cpu_aarch64::preempt_enable();
// WFI loop: sleep until the compositor wakes us or timeout expires.
// Each WFI suspends the CPU until the next interrupt (timer at 1000Hz).
loop {
let still_blocked = crate::task::scheduler::with_scheduler(|sched| {
sched.wake_expired_timers();
sched.current_thread_mut()
.map(|t| t.state == crate::task::thread::ThreadState::BlockedOnTimer)
.unwrap_or(false)
});
if !still_blocked.unwrap_or(false) {
break;
}
crate::task::scheduler::yield_current();
crate::arch_halt_with_interrupts();
}
// Clear blocked_in_syscall and re-disable preemption before returning
crate::task::scheduler::with_scheduler(|sched| {
if let Some(thread) = sched.current_thread_mut() {
thread.blocked_in_syscall = false;
}
});
#[cfg(target_arch = "aarch64")]
crate::per_cpu_aarch64::preempt_disable();
// Restore TTBR0 to this process's page tables after blocking
#[cfg(target_arch = "aarch64")]
ensure_current_address_space();
SyscallResult::Ok(0)
}
16 => {
// CompositeWindows: multi-window GPU compositing
// p1/p2 = pointer to CompositeWindowsDesc
let desc_ptr = (cmd.p1 as u32 as u64) | ((cmd.p2 as u32 as u64) << 32);
if desc_ptr == 0 || desc_ptr >= USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
// ksyscall-perf: measure composite time and report CPU% every 500 frames
#[cfg(target_arch = "aarch64")]
{
let t0: u64;
unsafe { core::arch::asm!("mrs {}, cntvct_el0", out(reg) t0, options(nomem, nostack)); }
let result = handle_composite_windows(desc_ptr);
use core::sync::atomic::{AtomicU64, AtomicU32};
static PERF_FRAME: AtomicU32 = AtomicU32::new(0);
static PERF_GPU_TICKS: AtomicU64 = AtomicU64::new(0);
static PERF_EPOCH: AtomicU64 = AtomicU64::new(0);
let t1: u64;
unsafe { core::arch::asm!("mrs {}, cntvct_el0", out(reg) t1, options(nomem, nostack)); }
let frame = PERF_FRAME.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
PERF_GPU_TICKS.fetch_add(t1.saturating_sub(t0), core::sync::atomic::Ordering::Relaxed);
if frame == 0 {
PERF_EPOCH.store(t0, core::sync::atomic::Ordering::Relaxed);
}
if frame > 0 && (frame + 1) % 500 == 0 {
let freq: u64;
unsafe { core::arch::asm!("mrs {}, cntfrq_el0", out(reg) freq, options(nomem, nostack)); }
let gpu_ticks = PERF_GPU_TICKS.swap(0, core::sync::atomic::Ordering::Relaxed);
let sleep_ticks = crate::drivers::virtio::gpu_pci::take_gpu_sleep_ticks();
let cpu_ticks = gpu_ticks.saturating_sub(sleep_ticks);
let epoch = PERF_EPOCH.swap(t1, core::sync::atomic::Ordering::Relaxed);
let wall_ticks = t1.saturating_sub(epoch);
let wall_us = gpu_ticks * 1_000_000 / freq / 500;
let sleep_us = sleep_ticks * 1_000_000 / freq / 500;
let cpu_us = cpu_ticks * 1_000_000 / freq / 500;
let busy_pct = if wall_ticks > 0 { cpu_ticks * 100 / wall_ticks } else { 0 };
crate::serial_println!(
"[ksyscall-perf] 500f: wall={}us sleep={}us cpu={}us busy={}%",
wall_us, sleep_us, cpu_us, busy_pct,
);
}
result
}
#[cfg(not(target_arch = "aarch64"))]
handle_composite_windows(desc_ptr)
}
17 => {
// SetWindowPosition: set window position + z-order for compositor
// p1=buffer_id, p2=x (i16 low) | y (i16 high), p3=z_order
let buffer_id = cmd.p1 as u32;
let x = (cmd.p2 & 0xFFFF) as i16 as i32;
let y = ((cmd.p2 >> 16) & 0xFFFF) as i16 as i32;
let z_order = cmd.p3 as u32;
let mut reg = WINDOW_REGISTRY.lock();
match reg.find_mut(buffer_id) {
Some(buf) => {
buf.x = x;
buf.y = y;
buf.z_order = z_order;
SyscallResult::Ok(0)
}
None => SyscallResult::Err(super::ErrorCode::InvalidArgument as u64),
}
}
18 => {
// WriteWindowInput: push an input event to a window's ring buffer.
// Called by BWM to route keyboard/mouse to the focused window.
// p1=buffer_id, p2/p3=pointer to WindowInputEvent
let buffer_id = cmd.p1 as u32;
let event_ptr = (cmd.p2 as u32 as u64) | ((cmd.p3 as u32 as u64) << 32);
if event_ptr == 0 || event_ptr >= USER_SPACE_MAX {
return SyscallResult::Err(super::ErrorCode::Fault as u64);
}
let mut event: WindowInputEvent = unsafe { core::ptr::read(event_ptr as *const WindowInputEvent) };
// Inject accumulated scroll wheel delta into mouse events.
// MOUSE_MOVE=3, MOUSE_BUTTON=4, MOUSE_SCROLL=9
if event.event_type == 3 || event.event_type == 4 || event.event_type == 9 {
let wheel = crate::drivers::usb::hid::mouse_wheel_consume();
if wheel != 0 {
event.scroll_y = event.scroll_y.saturating_add(wheel.clamp(-32768, 32767) as i16);
// If this was a plain MOUSE_MOVE (3) with wheel data, upgrade to MOUSE_SCROLL (9)
// so clients that filter on event type receive it correctly.
if event.event_type == 3 && event.scroll_y != 0 {
event.event_type = 9;
}
}
}
let wake_tid = {
let mut reg = WINDOW_REGISTRY.lock();
match reg.find_mut(buffer_id) {
Some(buf) => {
let next_head = (buf.input_head + 1) & (INPUT_RING_SIZE - 1);
if next_head == buf.input_tail {
// Ring full — drop oldest event by advancing tail
buf.input_tail = (buf.input_tail + 1) & (INPUT_RING_SIZE - 1);
}
buf.input_ring[buf.input_head] = event;
buf.input_head = next_head;
// Wake client if it's blocked waiting for input
buf.input_waiting_thread.take()
}
None => return SyscallResult::Err(super::ErrorCode::InvalidArgument as u64),
}