XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
GUI groundwork: a display (XnuDisplay), en0 as an IOKit Ethernet driver (XnuEthernet); WindowServer finds its display
Heyang Zhou0f1a6c034629
diff --git a/fki-ko/fki.h b/fki-ko/fki.hindex 3c7fc25..f59e497 100644--- a/fki-ko/fki.h+++ b/fki-ko/fki.h@@ -117,6 +117,8 @@ fki_u64 fki_phys_peek(fki_u64 pa);void *fki_file_open(const char *path, int writable, fki_u64 *size);long fki_file_rw(void *file, int write, void *buf, unsigned long len, fki_u64 off);void fki_file_close(void *file);+/* Write to a host file from ordinary Linux context (a host thread, not inside fki_enter()); bytes written or -errno. */+long fki_file_pwrite(void *file, const void *buf, unsigned long len, fki_u64 off);#ifdef __cplusplus}#endifdiff --git a/fki-ko/fki_mod.c b/fki-ko/fki_mod.cindex f9e37f0..4c79f75 100644--- a/fki-ko/fki_mod.c+++ b/fki-ko/fki_mod.c@@ -800,6 +800,16 @@ static long fki_file_rw_body(void *file, int write, void *buf, unsigned long len}+long fki_file_pwrite(void *file, const void *buf, unsigned long len, fki_u64 off)+{+ loff_t pos = off;++ if (!file)+ return -EBADF;+ return kernel_write(file, buf, len, &pos);+}+EXPORT_SYMBOL(fki_file_pwrite);+void fki_file_close(void *file){if (file)diff --git a/kexts/XnuDisplay/DroidVMVirtioGpu.h b/kexts/XnuDisplay/DroidVMVirtioGpu.hnew file mode 100644index 0000000..05a5c3b--- /dev/null+++ b/kexts/XnuDisplay/DroidVMVirtioGpu.h@@ -0,0 +1,30 @@+// SPDX-License-Identifier: BSD-2-Clause-Patent+// Stands in for the DroidVM board's virtio-gpu transport (DroidVMVirtioGpu.h of Droid-VM/UniXNU-droidvm) that XnuDisplay.cpp+// (DroidVMDisplay) is written against. The hosted kernel has no virtio-gpu: start() fails, so the display stays in stage 1 (the CPU+// copy into the boot framebuffer), and nothing here is reached otherwise. The 3D submission counters say every submission is done.+#pragma once+#include <IOKit/IOReturn.h>+#include <stdint.h>++namespace DroidVMVirtioGpu {+struct Header {uint32_t type, flags; uint64_t fence; uint32_t context; uint8_t ring, padding[3];};+struct Entry {uint64_t address; uint32_t length, padding;};+static constexpr uint32_t MaxCommand = 8 * 1024 * sizeof(Entry) + 64;+static inline bool start() {return false;}+static inline bool ready() {return false;}+static inline uint64_t features() {return 0;}+static inline IOReturn command(const void *, uint32_t, const void *, uint32_t, void *, uint32_t) {return kIOReturnNoDevice;}+static inline IOReturn post(const void *, uint32_t, const void *, uint32_t, uint32_t, bool, uint32_t *) {return kIOReturnNoDevice;}+static inline IOReturn wait(uint32_t, uint64_t, void *, uint32_t) {return kIOReturnNoDevice;}+static inline IOReturn cursor(uint32_t, int32_t, int32_t, uint32_t, uint32_t, bool) {return kIOReturnNoDevice;}+static inline void unref(uint32_t) {}+static inline uint32_t resourceId() {return 0;}+static inline void selftest3D() {}+}++extern "C" {+volatile uint64_t droidvm_virtio_gpu_commands;+uint64_t droidvm_virtgpu_submitted(void) {return 0;}+bool droidvm_virtgpu_finished(uint64_t) {return true;}+bool droidvm_virtgpu_wait_finished(uint64_t, uint64_t) {return true;}+}diff --git a/kexts/XnuDisplay/IOMobileFramebufferABI.h b/kexts/XnuDisplay/IOMobileFramebufferABI.hnew file mode 100644index 0000000..435da35--- /dev/null+++ b/kexts/XnuDisplay/IOMobileFramebufferABI.h@@ -0,0 +1,368 @@+// Generated by scripts/gen-iomfb-abi.py from the IOMobileFramebuffer classes of the macOS 26.5 kernelcache (vma2). Do not edit.+// Slot numbers and PAC diversities are the kernelcache's; return types are IOReturn where the mangled name says nothing.+#pragma once+#include <IOKit/IOService.h>+#include <IOKit/IOUserClient.h>+#include <IOKit/IOMemoryDescriptor.h>+#include <stdint.h>++class IOSurface;+struct DisplayArea;+enum DisplayColorRemapMode : uint32_t;+struct IOMFBBigBlock;+struct IOMFBColorFixedMatrix;+enum IOMFBColorMatrixFunction : uint32_t;+enum IOMFBCoreAnalyticsDataType : uint32_t;+struct IOMFBGammaTable;+struct IOMFBKernelTestsArguments;+struct IOMFBMirroringCapability;+struct IOMFBNotifyRequest;+struct IOMFBNotifyRequestArgs;+struct IOMFBOverscanSafeRect;+enum IOMFBParameterName : uint32_t;+enum IOMFBSwapCompletionState : uint32_t;+struct IOMFBSwapIORequest;+struct IOMFBSwapIORequestHeadName;+struct IOMFBSwapInfo;+struct IOMFBSwapRec;+enum IOMFBSwapRequestIntent : uint32_t;+enum IOMFB_AOT_1Hz_Feature_Flags : uint32_t;+enum IOMFB_NotificationType : uint32_t;+struct IOMFB_TiledDisplayInfo;+enum IOMFB_VSH_Forced_Event_Type : uint32_t;+enum IOMFB_VSH_Phase_Type : uint32_t;+struct IOMobileFramebufferUserClient;+struct SwapInfoBlob;+struct UpstreamHeader;+struct _IOMFBKernGainMap;+struct _IOMFBKernGainMapCapBuffer;+struct _IOMFBKernLPRMetadata;+struct __VideoDestEdgeAlpha;+enum iomfb_power_trace_event_t : uint32_t;+namespace IOMFB { struct RefreshTimingAttributes; }+namespace IOMFB { namespace AP { struct DisplayedData; }}++class IOMobileFramebuffer : public IOService {+ OSDeclareAbstractStructors(IOMobileFramebuffer)+public:+ virtual void has_multiple_dcp(bool*, bool*); // 272 0xe7f5+ virtual IOReturn get_dcp_rolename(char*, unsigned int); // 273 0x9857+ virtual bool supports_write_debug_info(); // 274 0x38e1+ virtual IOReturn swapping_client_did_start(IOMobileFramebufferUserClient*) = 0; // 275 0x3833+ virtual IOReturn swapping_client_will_stop(IOMobileFramebufferUserClient*) = 0; // 276 0x8193+ virtual IOReturn first_client_open() = 0; // 277 0xbeb7+ virtual IOReturn last_client_close(); // 278 0xc0f5+ virtual IOReturn rotate_surface(unsigned int, unsigned int, unsigned int) = 0; // 279 0xc9fd+ virtual IOReturn default_fb_surface(unsigned int, unsigned int) = 0; // 280 0x98d3+ virtual IOReturn get_framebuffer_id() = 0; // 281 0xb7a3+ virtual IOReturn swap_wait(IOMobileFramebufferUserClient*, unsigned int, unsigned int, unsigned int) = 0; // 282 0x8d8f+ virtual IOReturn swap_start(unsigned int*, IOUserClient*) = 0; // 283 0x9b82+ virtual IOReturn swap_submit(IOMFBSwapRec*, IOUserClient*, unsigned int*) = 0; // 284 0x7dea+ virtual IOReturn swap_signal(unsigned int, unsigned int) = 0; // 285 0xb882+ virtual IOReturn set_debug_flags(unsigned int, unsigned int, unsigned int*) = 0; // 286 0xd8a1+ virtual IOReturn set_flags(unsigned int, unsigned int, unsigned int*) = 0; // 287 0xe9a3+ virtual IOReturn wait_for_start_complete() = 0; // 288 0x2f5f+ virtual IOReturn set_display_device(unsigned int) = 0; // 289 0xa299+ virtual bool is_main_display() const = 0; // 290 0xa972+ virtual IOReturn set_digital_out_mode(unsigned int, unsigned int) = 0; // 291 0x6110+ virtual IOReturn get_digital_out_state(unsigned int*) = 0; // 292 0x3ffb+ virtual IOReturn set_canvas_size(unsigned int, unsigned int) = 0; // 293 0xfc37+ virtual IOReturn get_dot_pitch(unsigned int*) = 0; // 294 0x9cdc+ virtual IOReturn get_dot_pitch_float(float*); // 295 0x1a3d+ virtual IOReturn get_display_area(DisplayArea*) = 0; // 296 0x85a3+ virtual IOReturn get_HDCP_downstream_state(UpstreamHeader*) = 0; // 297 0xd6fb+ virtual IOReturn hdcp_send_request(unsigned char const*, unsigned long, IOMFBNotifyRequestArgs*) = 0; // 298 0x2009+ virtual IOReturn hdcp_get_reply(IOMemoryMap*, unsigned long*) = 0; // 299 0x4a16+ virtual IOReturn hdcp_client_will_stop(IOMobileFramebufferUserClient*) = 0; // 300 0x4c05+ virtual IOReturn get_protection_options(unsigned long long*) = 0; // 301 0xd85a+ virtual IOReturn set_tvout_mode(unsigned int) = 0; // 302 0xfcf8+ virtual IOReturn set_tvout_signaltype(unsigned int) = 0; // 303 0xf4e9+ virtual IOReturn set_wss_info(unsigned int, unsigned int) = 0; // 304 0x2dcc+ virtual IOReturn set_content_flags(unsigned int) = 0; // 305 0x1e43+ virtual IOReturn get_gamma_table(IOMFBGammaTable*) = 0; // 306 0x349e+ virtual IOReturn set_gamma_table(IOMFBGammaTable*) = 0; // 307 0xa6af+ virtual IOReturn get_matrix(unsigned int, unsigned long long (*) [3][3]) const = 0; // 308 0x8378+ virtual IOReturn set_matrix(unsigned int, unsigned long long const (*) [3][3]) = 0; // 309 0x8901+ virtual IOReturn set_contrast(float*) = 0; // 310 0x9d92+ virtual IOReturn set_white_on_black_mode(unsigned int) = 0; // 311 0x0549+ virtual IOReturn set_color_remap_mode(DisplayColorRemapMode) = 0; // 312 0xa9af+ virtual IOReturn get_color_remap_mode(DisplayColorRemapMode*) const = 0; // 313 0x8273+ virtual IOReturn setBrightnessCorrection(unsigned int) = 0; // 314 0x15d0+ virtual IOReturn add_notification(IOMFB_NotificationType, IOMFBNotifyRequest*, IOMFBNotifyRequestArgs*) = 0; // 315 0xa59b+ virtual IOReturn remove_notification(IOMFB_NotificationType, IOMFBNotifyRequest*) = 0; // 316 0x2a83+ virtual IOReturn set_notify_tag_mask(IOMFB_NotificationType, IOMFBNotifyRequest*, unsigned int) = 0; // 317 0x729c+ virtual IOReturn set_notify_tag_mask_gated(IOMFB_NotificationType, IOMFBNotifyRequest*, unsigned int) = 0; // 318 0xb486+ virtual IOReturn resend_notify_tag_mask_gated(); // 319 0xcf2a+ virtual IOReturn supported_frame_info(unsigned int, unsigned int*, char (*) [64], unsigned int*) = 0; // 320 0xbd70+ virtual IOReturn crc_notify(unsigned int, unsigned int, unsigned int) = 0; // 321 0x9106+ virtual IOReturn powerstate_notify(bool, bool) = 0; // 322 0xc7f4+ virtual IOReturn enable_stats(unsigned int) = 0; // 323 0xfb26+ virtual IOReturn swap_cancel(unsigned int) = 0; // 324 0xfe6f+ virtual IOReturn swap_cancel_all(unsigned long long) = 0; // 325 0xbe74+ virtual IOReturn swap_cancel_all_get_current(unsigned int*) = 0; // 326 0xf380+ virtual IOReturn swap_get_current(unsigned int*) = 0; // 327 0x6242+ virtual IOReturn surface_is_replaceable(unsigned int, bool*) = 0; // 328 0xccdb+ virtual IOReturn kernel_tests(IOMFBKernelTestsArguments*) = 0; // 329 0x4b6c+ virtual IOReturn splc_set_brightness(unsigned int) = 0; // 330 0x22d3+ virtual IOReturn splc_get_brightness(unsigned int*) = 0; // 331 0xb980+ virtual IOReturn set_block(task*, unsigned int, unsigned int, unsigned long long const*, unsigned int, unsigned char const*, unsigned long) = 0; // 332 0x769e+ virtual IOReturn get_block(task*, unsigned int, unsigned int, unsigned long long const*, unsigned int, unsigned char*, unsigned long) const = 0; // 333 0x09f0+ virtual IOReturn abort_block(task*, unsigned int) const = 0; // 334 0xaf10+ virtual IOReturn get_buf_block(task*, unsigned int, unsigned int, unsigned long long const*, unsigned int, unsigned char const*, unsigned long) = 0; // 335 0xd175+ virtual IOReturn start_task(task*, unsigned int, IOMFBBigBlock*) = 0; // 336 0x3156+ virtual IOReturn abort_task(task*, unsigned int) = 0; // 337 0x5672+ virtual IOReturn check_task_status(task*, unsigned int, IOMFBBigBlock*) = 0; // 338 0x9741+ virtual IOReturn get_block_size(task*, unsigned int, unsigned int*) = 0; // 339 0x007d+ virtual IOReturn create_gain_map(task*, IOUserClient*, _IOMFBKernGainMap const*, unsigned int*); // 340 0xbb4b+ virtual IOReturn set_gain_map_cap_buffer(task*, IOUserClient*, _IOMFBKernGainMapCapBuffer const*); // 341 0x0886+ virtual IOReturn create_lpr_metadata(task*, IOUserClient*, _IOMFBKernLPRMetadata const*, unsigned int*); // 342 0x5fa6+ virtual IOReturn swap_set_color_matrix(IOMFBColorFixedMatrix*, IOMFBColorMatrixFunction, unsigned int) = 0; // 343 0x0df3+ virtual IOReturn set_parameter(IOMFBParameterName, unsigned long long const*, unsigned int) = 0; // 344 0x4ee4+ virtual IOReturn setAPIPowerState(unsigned long, IOService*) = 0; // 345 0x9852+ virtual IOReturn printRegs() = 0; // 346 0x5b95+ virtual IOReturn enable_disable_dithering(unsigned int) = 0; // 347 0x72dd+ virtual IOReturn enable_disable_video_power_savings(unsigned int) = 0; // 348 0xfd4f+ virtual IOReturn set_video_dac_gain(unsigned int) = 0; // 349 0xecda+ virtual IOReturn set_line21_data(unsigned int) = 0; // 350 0xb08e+ virtual IOReturn enableInternalToExternalMirroring(bool) = 0; // 351 0x50fb+ virtual IOReturn getExternalMirroringCapability(IOMFBMirroringCapability*) = 0; // 352 0x53d8+ virtual IOReturn setRenderingAngle(float*) = 0; // 353 0xa9e4+ virtual IOReturn setOverscanSafeRegion(IOMFBOverscanSafeRect*) = 0; // 354 0xa31a+ virtual IOReturn set_underrun_color(unsigned int) = 0; // 355 0x7be2+ virtual IOReturn announce_next_swap_pts(unsigned long long) = 0; // 356 0x4b1c+ virtual uint64_t get_current_absolute_time() const = 0; // 357 0x9562+ virtual IOReturn get_lpr_frame_timestamp(); // 358 0x3c62+ virtual IOReturn get_default_surface(task*, unsigned int*) = 0; // 359 0x7fcc+ virtual IOReturn get_displayed_surface(task*, unsigned int*, unsigned int) = 0; // 360 0x7c09+ virtual IOReturn factory_portal(void*, task*) = 0; // 361 0x358b+ virtual IOReturn executeFactoryConfigurations_gated() = 0; // 362 0xe1af+ virtual uint32_t display_width() const = 0; // 363 0x0655+ virtual uint32_t display_height() const = 0; // 364 0xffec+ virtual IOReturn get_display_size(unsigned int*, unsigned int*) const = 0; // 365 0x6594+ virtual IOReturn get_link_quality() = 0; // 366 0xe578+ virtual uint32_t protection_bits(); // 367 0x3ede+ virtual IOReturn check_drm(IOSurface*); // 368 0x6482+ virtual uint32_t global_index() const; // 369 0xe864+ virtual bool get_second_external_state(); // 370 0x49d6+ virtual bool get_clamshell_state(bool); // 371 0x8839+ virtual IOReturn set_clamshell_state(unsigned int); // 372 0xbd9a+ virtual IOReturn get_ap_shared_disp_state(); // 373 0x4c8b+ virtual IOReturn get_ap_soft_power_state(); // 374 0xeba1+ virtual void set_power_on_pending(); // 375 0xe5de+ virtual bool is_power_on_pending(); // 376 0xcf25+ virtual IOReturn ap_power_debug_trace(iomfb_power_trace_event_t, unsigned int, unsigned int, unsigned int, unsigned int); // 377 0x5554+ virtual IOReturn get_ap_power_debug_trace(void*, unsigned long, unsigned long) const; // 378 0x3a25+};++class IOMobileFramebufferLegacy : public IOMobileFramebuffer {+ OSDeclareAbstractStructors(IOMobileFramebufferLegacy)+public:+ struct SwapInfoBlob;+ struct pstatechgreq;+ virtual void free() override; // 22 0xedc5+ virtual bool init(OSDictionary *) override; // 77 0x43aa+ virtual IOReturn setProperties(OSObject *) override; // 100 0x7c85+ virtual void systemWillShutdown(IOOptionBits) override; // 135 0x1a4e+ virtual IOService *probe(IOService *, SInt32 *) override; // 189 0x4897+ virtual bool start(IOService *) override; // 190 0x3c68+ virtual void stop(IOService *) override; // 191 0xb085+ virtual IOWorkLoop *getWorkLoop() const override; // 215 0x638e+ virtual IOReturn newUserClient(task_t, void *, UInt32, IOUserClient **) override; // 245 0x808e+ virtual IOReturn setPowerState(unsigned long, IOService *) override; // 259 0x699e+ virtual IOReturn swapping_client_did_start(IOMobileFramebufferUserClient*) override; // 275 0x3833+ virtual IOReturn swapping_client_will_stop(IOMobileFramebufferUserClient*) override; // 276 0x8193+ virtual IOReturn first_client_open() override; // 277 0xbeb7+ virtual IOReturn last_client_close() override; // 278 0xc0f5+ virtual IOReturn rotate_surface(unsigned int, unsigned int, unsigned int) override; // 279 0xc9fd+ virtual IOReturn default_fb_surface(unsigned int, unsigned int) override; // 280 0x98d3+ virtual IOReturn get_framebuffer_id() override; // 281 0xb7a3+ virtual IOReturn swap_wait(IOMobileFramebufferUserClient*, unsigned int, unsigned int, unsigned int) override; // 282 0x8d8f+ virtual IOReturn swap_start(unsigned int*, IOUserClient*) override; // 283 0x9b82+ virtual IOReturn swap_submit(IOMFBSwapRec*, IOUserClient*, unsigned int*) override; // 284 0x7dea+ virtual IOReturn swap_signal(unsigned int, unsigned int) override; // 285 0xb882+ virtual IOReturn set_debug_flags(unsigned int, unsigned int, unsigned int*) override; // 286 0xd8a1+ virtual IOReturn set_flags(unsigned int, unsigned int, unsigned int*) override; // 287 0xe9a3+ virtual IOReturn wait_for_start_complete() override; // 288 0x2f5f+ virtual IOReturn set_display_device(unsigned int) override; // 289 0xa299+ virtual bool is_main_display() const override; // 290 0xa972+ virtual IOReturn set_digital_out_mode(unsigned int, unsigned int) override; // 291 0x6110+ virtual IOReturn get_digital_out_state(unsigned int*) override; // 292 0x3ffb+ virtual IOReturn set_canvas_size(unsigned int, unsigned int) override; // 293 0xfc37+ virtual IOReturn get_dot_pitch(unsigned int*) override; // 294 0x9cdc+ virtual IOReturn get_dot_pitch_float(float*) override; // 295 0x1a3d+ virtual IOReturn get_display_area(DisplayArea*) override; // 296 0x85a3+ virtual IOReturn get_HDCP_downstream_state(UpstreamHeader*) override; // 297 0xd6fb+ virtual IOReturn hdcp_send_request(unsigned char const*, unsigned long, IOMFBNotifyRequestArgs*) override; // 298 0x2009+ virtual IOReturn hdcp_get_reply(IOMemoryMap*, unsigned long*) override; // 299 0x4a16+ virtual IOReturn hdcp_client_will_stop(IOMobileFramebufferUserClient*) override; // 300 0x4c05+ virtual IOReturn get_protection_options(unsigned long long*) override; // 301 0xd85a+ virtual IOReturn set_tvout_mode(unsigned int) override; // 302 0xfcf8+ virtual IOReturn set_tvout_signaltype(unsigned int) override; // 303 0xf4e9+ virtual IOReturn set_wss_info(unsigned int, unsigned int) override; // 304 0x2dcc+ virtual IOReturn set_content_flags(unsigned int) override; // 305 0x1e43+ virtual IOReturn get_gamma_table(IOMFBGammaTable*) override; // 306 0x349e+ virtual IOReturn set_gamma_table(IOMFBGammaTable*) override; // 307 0xa6af+ virtual IOReturn get_matrix(unsigned int, unsigned long long (*) [3][3]) const override; // 308 0x8378+ virtual IOReturn set_matrix(unsigned int, unsigned long long const (*) [3][3]) override; // 309 0x8901+ virtual IOReturn set_contrast(float*) override; // 310 0x9d92+ virtual IOReturn set_white_on_black_mode(unsigned int) override; // 311 0x0549+ virtual IOReturn set_color_remap_mode(DisplayColorRemapMode) override; // 312 0xa9af+ virtual IOReturn get_color_remap_mode(DisplayColorRemapMode*) const override; // 313 0x8273+ virtual IOReturn setBrightnessCorrection(unsigned int) override; // 314 0x15d0+ virtual IOReturn add_notification(IOMFB_NotificationType, IOMFBNotifyRequest*, IOMFBNotifyRequestArgs*) override; // 315 0xa59b+ virtual IOReturn remove_notification(IOMFB_NotificationType, IOMFBNotifyRequest*) override; // 316 0x2a83+ virtual IOReturn set_notify_tag_mask(IOMFB_NotificationType, IOMFBNotifyRequest*, unsigned int) override; // 317 0x729c+ virtual IOReturn set_notify_tag_mask_gated(IOMFB_NotificationType, IOMFBNotifyRequest*, unsigned int) override = 0; // 318 0xb486+ virtual IOReturn supported_frame_info(unsigned int, unsigned int*, char (*) [64], unsigned int*) override = 0; // 320 0xbd70+ virtual IOReturn crc_notify(unsigned int, unsigned int, unsigned int) override; // 321 0x9106+ virtual IOReturn powerstate_notify(bool, bool) override; // 322 0xc7f4+ virtual IOReturn enable_stats(unsigned int) override; // 323 0xfb26+ virtual IOReturn swap_cancel(unsigned int) override; // 324 0xfe6f+ virtual IOReturn swap_cancel_all(unsigned long long) override; // 325 0xbe74+ virtual IOReturn swap_cancel_all_get_current(unsigned int*) override; // 326 0xf380+ virtual IOReturn swap_get_current(unsigned int*) override; // 327 0x6242+ virtual IOReturn surface_is_replaceable(unsigned int, bool*) override; // 328 0xccdb+ virtual IOReturn kernel_tests(IOMFBKernelTestsArguments*) override; // 329 0x4b6c+ virtual IOReturn splc_set_brightness(unsigned int) override; // 330 0x22d3+ virtual IOReturn splc_get_brightness(unsigned int*) override; // 331 0xb980+ virtual IOReturn set_block(task*, unsigned int, unsigned int, unsigned long long const*, unsigned int, unsigned char const*, unsigned long) override; // 332 0x769e+ virtual IOReturn get_block(task*, unsigned int, unsigned int, unsigned long long const*, unsigned int, unsigned char*, unsigned long) const override; // 333 0x09f0+ virtual IOReturn abort_block(task*, unsigned int) const override; // 334 0xaf10+ virtual IOReturn get_buf_block(task*, unsigned int, unsigned int, unsigned long long const*, unsigned int, unsigned char const*, unsigned long) override; // 335 0xd175+ virtual IOReturn start_task(task*, unsigned int, IOMFBBigBlock*) override; // 336 0x3156+ virtual IOReturn abort_task(task*, unsigned int) override; // 337 0x5672+ virtual IOReturn check_task_status(task*, unsigned int, IOMFBBigBlock*) override; // 338 0x9741+ virtual IOReturn get_block_size(task*, unsigned int, unsigned int*) override; // 339 0x007d+ virtual IOReturn create_gain_map(task*, IOUserClient*, _IOMFBKernGainMap const*, unsigned int*) override; // 340 0xbb4b+ virtual IOReturn swap_set_color_matrix(IOMFBColorFixedMatrix*, IOMFBColorMatrixFunction, unsigned int) override; // 343 0x0df3+ virtual IOReturn set_parameter(IOMFBParameterName, unsigned long long const*, unsigned int) override; // 344 0x4ee4+ virtual IOReturn setAPIPowerState(unsigned long, IOService*) override; // 345 0x9852+ virtual IOReturn printRegs() override; // 346 0x5b95+ virtual IOReturn enable_disable_dithering(unsigned int) override; // 347 0x72dd+ virtual IOReturn enable_disable_video_power_savings(unsigned int) override; // 348 0xfd4f+ virtual IOReturn set_video_dac_gain(unsigned int) override; // 349 0xecda+ virtual IOReturn set_line21_data(unsigned int) override; // 350 0xb08e+ virtual IOReturn enableInternalToExternalMirroring(bool) override; // 351 0x50fb+ virtual IOReturn getExternalMirroringCapability(IOMFBMirroringCapability*) override; // 352 0x53d8+ virtual IOReturn setRenderingAngle(float*) override; // 353 0xa9e4+ virtual IOReturn setOverscanSafeRegion(IOMFBOverscanSafeRect*) override; // 354 0xa31a+ virtual IOReturn set_underrun_color(unsigned int) override; // 355 0x7be2+ virtual IOReturn announce_next_swap_pts(unsigned long long) override; // 356 0x4b1c+ virtual uint64_t get_current_absolute_time() const override; // 357 0x9562+ virtual IOReturn get_default_surface(task*, unsigned int*) override; // 359 0x7fcc+ virtual IOReturn get_displayed_surface(task*, unsigned int*, unsigned int) override; // 360 0x7c09+ virtual IOReturn factory_portal(void*, task*) override = 0; // 361 0x358b+ virtual IOReturn executeFactoryConfigurations_gated() override = 0; // 362 0xe1af+ virtual uint32_t display_width() const override; // 363 0x0655+ virtual uint32_t display_height() const override; // 364 0xffec+ virtual IOReturn get_display_size(unsigned int*, unsigned int*) const override; // 365 0x6594+ virtual IOReturn get_link_quality() override; // 366 0xe578+ virtual IOReturn initIOAVHandlerInternalDisplay(); // 379 0x5558+ virtual void * getDisplayedDataAP() const; // 380 0xd129+ virtual bool is_dual_pipe_config(); // 381 0xf7bb+ virtual IOReturn hotPlug_notify(unsigned long long); // 382 0x786c+ virtual IOReturn hotPlug_notify_gated(unsigned long long, IOMFB_TiledDisplayInfo*, bool); // 383 0x4e8b+ virtual IOReturn genlock_error_notify_gated(unsigned long long); // 384 0x54d6+ virtual bool need_swap_notify(); // 385 0x3a25+ virtual IOReturn getTiledDisplayInfo(IOMFB_TiledDisplayInfo*); // 386 0x27f6+ virtual void flush_rtps() const; // 387 0x2f7e+ virtual bool aot_enabled(); // 388 0xf890+ virtual bool vmaod_enabled(); // 389 0x371c+ virtual IOReturn in_sleep_media(bool); // 390 0x16df+ virtual IOReturn on_swap_queued(); // 391 0x9a5d+ virtual IOReturn delete_gain_map(unsigned int); // 392 0x0662+ virtual IOReturn flush_cached_state(); // 393 0xf2d8+ virtual IOReturn set_corner_temps_gated(int const*); // 394 0x6ac5+ virtual IOReturn set_postblend_scale_gated(int); // 395 0xe505+ virtual IOReturn set_color_filter_scale_gated(int); // 396 0xf70d+ virtual IOReturn set_brightness_gated(int); // 397 0x05d1+ virtual IOReturn set_thermal_throttle_cap_gated(unsigned int); // 398 0x2418+ virtual IOReturn update_bic_gated(); // 399 0xd8a8+ virtual IOReturn update_lac_gated(); // 400 0xca26+ virtual IOReturn reset_lah_gated(); // 401 0x8954+ virtual IOReturn reset_vsh_comp(); // 402 0x972d+ virtual IOReturn test_control_gated(unsigned long long const*, unsigned int); // 403 0xa4d1+ virtual IOReturn disable_calibration_gated(bool); // 404 0xc78f+ virtual IOReturn absolute_time_to_ns(unsigned long long, unsigned long long*) const; // 405 0xab06+ virtual IOReturn ns_to_absolute_time(unsigned long long, unsigned long long*) const; // 406 0x4f41+ virtual IOReturn presentation_time_feedback(double); // 407 0x849e+ virtual void idle_surface_release(); // 408 0xa299+ virtual bool start_hardware(); // 409 0x700f+ virtual IOReturn stop_hardware_gated(); // 410 0x4491+ virtual IOReturn swap_begin_gated(); // 411 0x7713+ virtual bool async_swap_supported() const; // 412 0xae77+ virtual uint32_t syncRate(); // 413 0x8739+ virtual uint32_t getActivePeriod_us(); // 414 0x393d+ virtual IOReturn swap_begin_async_gated(); // 415 0xa9bc+ virtual IOReturn swap_complete_gated(); // 416 0x0caa+ virtual IOReturn verify_swap(IOMFBSwapIORequest*); // 417 0x5339+ virtual IOReturn verify_swap_surfaces(IOMFBSwapIORequest*); // 418 0x5d73+ virtual IOReturn do_power_state_change_gated(); // 419 0xb6af+ virtual IOReturn create_default_fb_surface(); // 420 0xe2fa+ virtual IOReturn check_swap_unblocked_gated(IOMFBSwapIORequest*); // 421 0xf300+ virtual IOReturn deallocate_default_fb_surface(); // 422 0xab75+ virtual IOReturn get_timing_attributes_gated(IOMFB::RefreshTimingAttributes*, bool) const; // 423 0xdcfc+ virtual IOReturn system_will_sleep(); // 424 0xda63+ virtual IOReturn writeDebugInfo(OSDictionary*); // 425 0x9773+ virtual IOReturn printDisplayRegs(); // 426 0xe9df+ virtual IOReturn set_crc_notification_state_gated(bool); // 427 0x6eb7+ virtual IOReturn set_frame_info_notification_state_gated(IOMFBNotifyRequest*, bool) = 0; // 428 0x795c+ virtual IOReturn do_swap_info_notify_gated(IOMFBNotifyRequest*, IOMobileFramebufferLegacy::SwapInfoBlob const*) = 0; // 429 0xa688+ virtual IOReturn do_crc_notify(IOMobileFramebufferLegacy::SwapInfoBlob*); // 430 0x6516+ virtual IOReturn dropAbortedSwaps_gated(bool); // 431 0x9d58+ virtual IOReturn swapWillChangeDisplayedData(IOMFBSwapIORequest*) const; // 432 0x2f94+ virtual IOReturn dropObsoleteSwaps_gated(); // 433 0xe0e7+ virtual IOReturn dropSwap_gated(IOMFBSwapIORequest*, bool); // 434 0x8acc+ virtual IOReturn dropNoOpSwaps_gated(); // 435 0x0c83+ virtual IOReturn dropDummySwaps_gated(); // 436 0x4e1e+ virtual uint64_t getDefaultVBLDelta(); // 437 0xafb6+ virtual IOReturn updateIdleness_gated(bool); // 438 0x4214+ virtual IOReturn applyProperty(unsigned int, unsigned int); // 439 0xb19f+ virtual IOReturn exportProperty(unsigned int, unsigned int); // 440 0xecd3+ virtual IOReturn isEdgeAlphaEnabled_gated(__VideoDestEdgeAlpha const*) const; // 441 0xd13f+ virtual IOReturn recordQoSStats(IOMFBSwapInfo*); // 442 0x9b23+ virtual IOReturn computeCanPowerGateDCS(IOMFBSwapIORequest*); // 443 0x0435+ virtual IOReturn writeDebugInfo_gated(OSDictionary*); // 444 0x7162+ virtual bool isReplaying() const; // 445 0xadc9+ virtual IOReturn idlePowerGatingSequenceStartedOrEnded_gated(); // 446 0xc767+ virtual IOReturn powerUpDART_gated(bool); // 447 0x226a+ virtual IOReturn display_edr_factor_changed(float); // 448 0x3b8d+ virtual IOReturn set_adaptive_sync_params(unsigned int, unsigned int, bool); // 449 0xaf4c+ virtual IOReturn set_external_genlock_gated(bool, unsigned int); // 450 0x4722+ virtual IOReturn set_temperature_compensation_state_gated(bool); // 451 0xfccd+ virtual IOReturn set_daemon_state_gated(bool); // 452 0xd579+ virtual IOReturn set_od_threshold_gated(int); // 453 0xceeb+ virtual IOReturn set_vsh_phase_gated(IOMFB_VSH_Phase_Type, unsigned long long, IOMFB_VSH_Forced_Event_Type); // 454 0x9ce7+ virtual IOReturn reset_core_analytics_data_gated(IOMFBCoreAnalyticsDataType); // 455 0xd93a+ virtual IOReturn set_aot_1Hz_optimization_features_gated(IOMFB_AOT_1Hz_Feature_Flags, bool); // 456 0xbb4b+ virtual bool is_ready_to_notify_power_on() const; // 457 0xe5c3+ virtual IOReturn default_fb_surface_gated(unsigned int, unsigned int); // 458 0x9122+ virtual IOReturn resize_default_fb_surface_gated(); // 459 0xafba+ virtual IOReturn deallocate_default_fb_surface_gated(); // 460 0xc7d6+ virtual bool finfo_support_io_shared_queue(); // 461 0xd3c1+ virtual IOReturn notify_swap_done_gated(unsigned int, ::SwapInfoBlob*, unsigned int*, unsigned int) = 0; // 462 0x13ff+ virtual IOReturn notify_crc_ready_gated(unsigned int) = 0; // 463 0x0122+ virtual IOReturn reprogramDisplayWithDummySwap_gated(IOMFBSwapRequestIntent, IOMFBSwapRec*); // 464 0x1cda+ virtual IOReturn abort_swap_gated(IOMFBSwapIORequest*, IOMFBSwapIORequestHeadName*, IOMFBSwapCompletionState); // 465 0x8edb+ virtual bool keep_swaps_on_disconnect(); // 466 0xe440+ virtual IOReturn computeAndVerifyFinalSubtitleRegions_gated(IOMFBSwapIORequest*); // 467 0xe644+ virtual IOReturn update_refresh_stats_gated(); // 468 0x5786+ virtual IOReturn set_api_power_state_gated(unsigned long, IOService*); // 469 0x9e55+ virtual bool are_timings_enabled() const = 0; // 470 0x1a07+ virtual IOReturn clear_up_swap_queue_gated(); // 471 0xa117+ virtual IOReturn swap_layer_map(IOMFBSwapIORequest*, unsigned int); // 472 0x36b2+ virtual IOReturn surface_layer_map(IOMFB::AP::DisplayedData*, unsigned int, IOSurface*); // 473 0x845c+ virtual IOReturn surface_layer_unmap(IOMFB::AP::DisplayedData*, unsigned int); // 474 0xdbd0+ virtual IOReturn handle_slp_media_brightness_update(); // 475 0x83a9+ virtual IOReturn trigger_fdr_loader(); // 476 0xad9f+ virtual IOReturn set_profile(); // 477 0x80f3+ virtual IOReturn prepare_dcp_power_change(bool); // 478 0x6207+ virtual IOReturn do_power_state_change_action_gated(IOMobileFramebufferLegacy::pstatechgreq*, bool); // 479 0x74f2+ virtual IOReturn trigger_pswap_dependent_thread(); // 480 0x106a+ virtual IOReturn send_clamshell_state(); // 481 0xf761+ virtual IOReturn get_shared_disp_property(); // 482 0xc09c+ uint8_t iomfbLegacyState[0x1de0 - sizeof(IOService)]; // the instance size of its MetaClass+};++static_assert(sizeof(IOMobileFramebufferLegacy) == 0x1de0, "IOMobileFramebufferLegacy instance size");+enum : unsigned {IOMobileFramebufferLegacySlots = 483};diff --git a/kexts/XnuDisplay/XnuDisplay.cpp b/kexts/XnuDisplay/XnuDisplay.cppnew file mode 100644index 0000000..97300a2--- /dev/null+++ b/kexts/XnuDisplay/XnuDisplay.cpp@@ -0,0 +1,1451 @@+// SPDX-License-Identifier: BSD-2-Clause-Patent+// XnuDisplay: the hosted macOS's display. It is DroidVMDisplay of Droid-VM/macOS-DroidVM (overlay/kext/DroidVMDisplay, BSD-2-Clause-+// Patent) as it stands, renamed: an IOMobileFramebufferLegacy whose scanout is the boot framebuffer (stage 1 below). xnu.ko reserves+// that framebuffer in the boot data and passes it as boot_args Video; Linux reads it for screenshots. There is no virtio-gpu here:+// DroidVMVirtioGpu.h in this directory stands in for the DroidVM board's transport and reports no device, so stage 2 never starts.+//+// The original notes follow.+//+// XnuDisplay: the macOS display of a DroidVM guest, an IOMobileFramebufferLegacy (IOMobileGraphicsFamily) over the firmware+// framebuffer, as AppleParavirtDisplay (AppleParavirtGPUIOGPUFamily, the vma2 display) is over the paravirtual GPU. The family runs+// the swap queue, the user client and the notifications; the driver supplies the hardware hooks AppleParavirtDisplay overrides.+//+// Stage 2: crosvm's virtio-gpu (--virtio-mmio-gpu, /arm-io/virtio-gpu) scans out the swap's surface itself: its pages become a+// guest-handle blob resource, the host blits them to the app's window on each RESOURCE_FLUSH (no copy in the guest). Without the device,+// or for a format it cannot show, stage 1 copies.+//+// Stage 1: the GOP framebuffer the bootloader set up (boot_args Video: PE_Video of the platform) is the scanout. A 16 ms timer takes+// the queued swaps (AppleParavirtDisplay::swap_begin_gated) and the CPU copies the swap's main IOSurface into it, then completes the+// swap. Display attributes, timing and color elements are published as AppleParavirtDisplay::createDisplayAttributes does.+//+// Discovery: IOMobileFramebuffer.framework (iomfb_populate_all_display_infos) expects as many framebuffers as the DisplayPortCount+// of the AppleParavirtGPU services when an /arm-io node is compatible "paravirtualizedgraphics,gpu", and waits for them. Apple's+// AppleParavirtGPUIOGPUFamily is not in the collection, so the class of that name here is the nub of that node and the provider+// of the display.+//+// Offsets into IOMobileFramebufferLegacy and its swap requests are those AppleParavirtDisplay of the same kernelcache (kc265)+// uses; the addresses noted are its code (research/re/apd/).+#include "IOMobileFramebufferABI.h"+#include "DroidVMVirtioGpu.h"+#include <IOKit/IOBufferMemoryDescriptor.h>+#include <IOKit/IOLib.h>+#include <IOKit/IOPlatformExpert.h>+#include <IOKit/IOTimerEventSource.h>+#include <IOKit/IOUserClient.h>+#include <IOKit/IOWorkLoop.h>+#include <IOKit/pwr_mgt/RootDomain.h>+#include <kern/clock.h>+#include <libkern/c++/OSArray.h>+#include <libkern/c++/OSDictionary.h>+#include <libkern/c++/OSNumber.h>+#include <libkern/c++/OSString.h>+#include <pexpert/device_tree.h>++extern "C" task_t kernel_task;+extern "C" vm_offset_t ml_io_map(vm_offset_t, vm_size_t); // machine_routines.h declares it to the kernel's own files only++// macOS 27's offsets. The addresses in these comments are those of the 26.5 collection where each was first found; k27/TODO.md+// names the same instruction of the same function in 27's.+// IOMobileFramebufferLegacy (instance 0x1dd8)+static constexpr size_t kCurrentSwap = 6720; // the swap being programmed (swap_begin_gated 0x...dba5c, clean_queue_gated)+static constexpr size_t kSwapQueueFirst = 6728; // TAILQ head of the pending swaps+static constexpr size_t kSwapQueueLast = 6736; // its tqh_last+static constexpr size_t kDisplayWidth = 7152; // display_width() / display_height() (set_digital_out_mode block 0x...d6a60)+static constexpr size_t kDisplayHeight = 7156;+static constexpr size_t kSystemPowerState = 7180; // u32: setPowerState's state (do_power_state_change_action_gated, request type 0)+static constexpr size_t kAPIPowerState = 7184; // u32: setAPIPowerState's state (power_state_change_interrupt, request type 1)+static constexpr size_t kHardwarePowered = 7188; // u32: the display is powered ("PowerStates-Cntr" in swap_wait_gated's report); with+ // kHardwareStarted set, swap_wait fails kIOReturnOffline while it is 0 (0x...2d1e4)+static constexpr size_t kSwapInfoHeld = 7634; // u16: swap info notifications are held (notify_swap_done_gated 0x...d9430)+static constexpr size_t kSwapInfoTime = 264; // the swap info's time (notify_swap_done_gated 0x...d93f0)+// IOMobileFramebuffer (instance 144): set before power management in AppleParavirtDisplay's start_hardware block (0x...d8e90)+static constexpr size_t kHardwareStarted = 140;+// IOMFBSwapIORequest+static constexpr size_t kSwapLayers = 984; // bit 0: main surface, bit 1: cursor surface (program_hardware_gated 0x...db858)+static constexpr size_t kSwapDropReasons = 1004; // programmed when nothing but bit 3 is set, else dropped (swap_begin_gated 0x...dbac0)+static constexpr size_t kSwapInfoA = 912; // swap info words 3 and 4 (notify_swap_done_gated 0x...d93f4)+static constexpr size_t kSwapInfoB = 976;+static constexpr size_t kSwapMainSurface = 2944; // layer i's surface at + 8 * i+static constexpr unsigned kSwapLayerCount = 4;+static constexpr size_t kSwapNext = 3384; // TAILQ entry of the queue+static constexpr size_t kSwapPrev = 3392;+// IOMFBNotifyRequest+static constexpr size_t kNotifyAsyncReference = 24; // OSAsyncReference64 of the user client (do_swap_info_notify_gated 0x...d9370)+static constexpr size_t kNotifyMask = 120; // which swap info words the client wants; bit 31: as 32-bit halves+static constexpr size_t kNotifyLastTime = 128; // the time of the previous notification (word 1 is the delta)+// IOAVElement: the element ID and its score (createTimingElementWithDimensionsAndRate 0x...d8974, createColorElementWithDepthAndEDR)+static constexpr size_t kElementID = 16;+static constexpr size_t kElementScore = 24;++template <typename T> static T &at(void *base, size_t offset) {return *reinterpret_cast<T *>(static_cast<uint8_t *>(base) + offset);}++// Kernel interfaces of the collection's kexts with no header here.+void iomfbUpdateSwapInfoState(IOMobileFramebufferLegacy *, IOMFBSwapIORequest *, uint32_t)+ __asm("__ZN25IOMobileFramebufferLegacy28update_swap_info_state_gatedEP18IOMFBSwapIORequest24IOMFBSwapCompletionState");+void iomfbSwapInfoDispatch(IOMobileFramebufferLegacy *, void *)+ __asm("__ZN25IOMobileFramebufferLegacy31swap_info_notify_dispatch_gatedEPNS_12SwapInfoBlobE");+IOReturn userClientSendAsyncResult(io_user_reference_t *reference, IOReturn, io_user_reference_t *args, UInt32 count, IOOptionBits)+ __asm("__ZN12IOUserClient28sendAsyncResult64WithOptionsEPyiS0_jj"); // protected in IOUserClient.h+uint64_t ioSurfaceWidth(const IOSurface *) __asm("__ZNK9IOSurface8getWidthEv");+uint64_t ioSurfaceHeight(const IOSurface *) __asm("__ZNK9IOSurface9getHeightEv");+uint64_t ioSurfaceBytesPerRow(const IOSurface *) __asm("__ZNK9IOSurface14getBytesPerRowEv");+uint64_t ioSurfaceBaseOffset(const IOSurface *) __asm("__ZNK9IOSurface13getBaseOffsetEv");+uint32_t ioSurfacePixelFormat(const IOSurface *) __asm("__ZNK9IOSurface14getPixelFormatEv");+uint32_t ioSurfaceUnlockSeed(const IOSurface *) __asm("__ZNK9IOSurface13getUnlockSeedEv");+IOMemoryDescriptor *ioSurfaceMemory(const IOSurface *) __asm("__ZNK9IOSurface19getMemoryDescriptorEv");+uint32_t ioSurfacePlaneCount(const IOSurface *) __asm("__ZNK9IOSurface13getPlaneCountEv");+uint64_t ioSurfacePlaneOffset(const IOSurface *, uint32_t) __asm("__ZNK9IOSurface14getPlaneOffsetEj");+uint64_t ioSurfacePlaneBytesPerRow(const IOSurface *, uint32_t) __asm("__ZNK9IOSurface19getPlaneBytesPerRowEj");+uint64_t ioSurfacePlaneBytesPerElement(const IOSurface *, uint32_t) __asm("__ZNK9IOSurface23getPlaneBytesPerElementEj");+uint64_t ioSurfacePlaneWidth(const IOSurface *, uint32_t) __asm("__ZNK9IOSurface13getPlaneWidthEj");+uint64_t ioSurfacePlaneHeight(const IOSurface *, uint32_t) __asm("__ZNK9IOSurface14getPlaneHeightEj");+// IOAVVideoTimingData: per axis (horizontal, vertical) 32 bytes of which total +4, active +8, sync width +12, back porch +16,+// front porch +20, sync rate +24, sync polarity +28, then the pixel clock at +68 (IOAVVideoTimingElement's getters; the element keeps+// the data at +32).+OSObject *ioavTimingWithData(const void *data, uint32_t standardType, uint32_t timingStandard)+ __asm("__ZN22IOAVVideoTimingElement8withDataEPK19IOAVVideoTimingData16IOAVStandardType23IOAVVideoTimingStandard");+void ioavTimingSetColorElements(OSObject *, OSArray *) __asm("__ZN22IOAVVideoTimingElement16setColorElementsEP7OSArray");+OSObject *ioavColorWithCapabilities(uint32_t standardType, uint32_t depth, uint32_t encoding, uint32_t range, uint32_t eotf,+ uint32_t colorimetry, bool, const OSDictionary *, const OSDictionary *, const OSDictionary *,+ const OSSet *)+ __asm("__ZN21IOAVVideoColorElement16withCapabilitiesE16IOAVStandardTypej22IOAVVideoPixelEncoding26IOAVVideoColorDynamicRange"+ "18IOAVVideoColorEOTF20IOAVVideoColorimetrybPK12OSDictionaryS7_S7_PK5OSSet");++// The virtio-gpu of /arm-io/virtio-gpu (crosvm --virtio-mmio-gpu): the DroidVM board's transport (DroidVMVirtioGpu.cpp, exported by+// k27/build-native-display.sh), one control queue shared by the display and the 3D contexts of DroidVMVirtioGpu3D.cpp, which serve+// the GPU's user clients (NativeAdreno's methods 0x7200 on); this class is the display's view of it.+using VirtioGpuHeader = DroidVMVirtioGpu::Header;+using VirtioGpuEntry = DroidVMVirtioGpu::Entry;+struct VirtioGpuRect {uint32_t x, y, width, height;};+extern "C" volatile uint64_t droidvm_virtio_gpu_commands;+// DroidVMVirtioGpu3D.cpp: the number of the latest fenced 3D submission of any client, and whether every one up to a number has finished.+extern "C" uint64_t droidvm_virtgpu_submitted(void);+extern "C" bool droidvm_virtgpu_finished(uint64_t);+extern "C" bool droidvm_virtgpu_wait_finished(uint64_t, uint64_t);++class VirtioGpu {+public:+ static constexpr uint32_t kRequestBytes = DroidVMVirtioGpu::MaxCommand; // a blob's page list: 8 K entries+ static constexpr uint32_t kMaxEntries = (kRequestBytes - 64) / sizeof(VirtioGpuEntry);+ const char *start() {return DroidVMVirtioGpu::start() ? nullptr : "the transport did not start (see virtio-gpu: lines)";}+ bool ready() const {return DroidVMVirtioGpu::ready();}+ uint64_t features() const {return DroidVMVirtioGpu::features();}+ IOReturn command(const void *, uint32_t, const void *extra = nullptr, uint32_t extraSize = 0, bool fenced = true);+ uint64_t commands() const {return droidvm_virtio_gpu_commands;}+};++// Sends a command (and the entries that follow it) and waits for its answer. Fenced, as the iOS board's: the host answers once it has+// done the command; a fenced RESOURCE_FLUSH, once the host's blit to the window has finished (crosvm defers it to the display fence).+// Unfenced, it answers once it has taken the command.+IOReturn VirtioGpu::command(const void *data, uint32_t size, const void *extra, uint32_t extraSize, bool fenced)+{+ if (!ready())+ return kIOReturnNotReady;+ VirtioGpuHeader reply;+ if (fenced)+ return DroidVMVirtioGpu::command(data, size, extra, extraSize, &reply, sizeof(reply));+ uint8_t copy[256];+ if (size < sizeof(VirtioGpuHeader) || size > sizeof(copy))+ return kIOReturnBadArgument;+ memcpy(copy, data, size);+ reinterpret_cast<VirtioGpuHeader *>(copy)->flags &= ~3u;+ uint32_t ticket = 0;+ if (IOReturn status = DroidVMVirtioGpu::post(copy, size, extra, extraSize, sizeof(reply), false, &ticket))+ return status;+ return DroidVMVirtioGpu::wait(ticket, 1000000, &reply, sizeof(reply));+}++class AppleParavirtGPU : public IOService {+ OSDeclareDefaultStructors(AppleParavirtGPU)+public:+ bool start(IOService *provider) override;+};++OSDefineMetaClassAndStructors(AppleParavirtGPU, IOService)++bool AppleParavirtGPU::start(IOService *provider)+{+ if (!IOService::start(provider))+ return false;+ setProperty("DisplayPortCount", 1ULL, 32);+ registerService();+ IOLog("XnuDisplay: AppleParavirtGPU on %s, 1 display port\n", provider->getName());+ return true;+}++class XnuDisplay : public IOMobileFramebufferLegacy {+ OSDeclareDefaultStructors(XnuDisplay)+public:+ bool start(IOService *) override;+ void stop(IOService *) override;+ bool start_hardware() override;+ IOReturn stop_hardware_gated() override;+ IOReturn swap_begin_gated() override;+ IOReturn swap_wait(IOMobileFramebufferUserClient *, unsigned int, unsigned int, unsigned int) override;+ IOReturn swap_submit(IOMFBSwapRec *, IOUserClient *, unsigned int *) override;+ IOReturn verify_swap(IOMFBSwapIORequest *) override;+ IOReturn swap_layer_map(IOMFBSwapIORequest *, unsigned int) override;+ IOReturn surface_layer_map(IOMFB::AP::DisplayedData *, unsigned int, IOSurface *) override;+ IOReturn surface_layer_unmap(IOMFB::AP::DisplayedData *, unsigned int) override;+ IOReturn set_display_device(unsigned int) override;+ IOReturn set_digital_out_mode(unsigned int, unsigned int) override;+ IOReturn get_dot_pitch(unsigned int *) override;+ IOReturn get_gamma_table(IOMFBGammaTable *) override;+ IOReturn set_gamma_table(IOMFBGammaTable *) override;+ IOReturn set_color_remap_mode(DisplayColorRemapMode) override;+ IOReturn get_color_remap_mode(DisplayColorRemapMode *) const override;+ IOReturn swap_set_color_matrix(IOMFBColorFixedMatrix *, IOMFBColorMatrixFunction, unsigned int) override;+ IOReturn set_notify_tag_mask_gated(IOMFB_NotificationType, IOMFBNotifyRequest *, unsigned int) override;+ IOReturn supported_frame_info(unsigned int, unsigned int *, char (*)[64], unsigned int *) override;+ IOReturn factory_portal(void *, task *) override;+ IOReturn executeFactoryConfigurations_gated() override;+ IOReturn set_frame_info_notification_state_gated(IOMFBNotifyRequest *, bool) override;+ IOReturn do_swap_info_notify_gated(IOMFBNotifyRequest *, const SwapInfoBlob *) override;+ IOReturn notify_swap_done_gated(unsigned int, ::SwapInfoBlob *, unsigned int *, unsigned int) override;+ IOReturn notify_crc_ready_gated(unsigned int) override;+ bool are_timings_enabled() const override;+ IOReturn do_power_state_change_gated() override;+ IOReturn set_parameter(IOMFBParameterName, const unsigned long long *, unsigned int) override;++private:+ // The refresh rate of the timing published (boot-arg droidvm-display-hz, 30 to 240): the app's window shows 120 Hz (its gpu-0+ // screen's refresh rate).+ uint32_t fRefreshHz;+ static constexpr uint32_t kWidthMM = 286, kHeightMM = 179; // a 13.3-inch 16:10 panel: about 114 dpi at 1280x800+ static constexpr uint32_t kColorID = 100, kTimingID = 1000; // AppleParavirtDisplay's IDs of its first color and timing element++ bool clean_queue_gated();+ void program_hardware_gated();+ void updateCursor(IOSurface *, int32_t, int32_t);+ IOReturn moveCursor(bool image);+ IOBufferMemoryDescriptor *fCursorPixels;+ IOSurface *fCursorSurface;+ uint32_t fCursorSeed;+ uint32_t fCursorResource, fCursorWidth, fCursorHeight;+ int32_t fCursorX, fCursorY, fCursorOffsetX, fCursorOffsetY;+ uint32_t fCursorCropX, fCursorCropY;+ bool fCursorVisible;+ uint64_t fCursorUpdates, fCursorMoves;+ void copySurface(IOSurface *, bool refresh = false);+ bool scanOut(IOSurface *);+ struct ScanoutResource;+ ScanoutResource *scanoutResource(IOSurface *, uint32_t format);+ bool releaseResource(ScanoutResource &);+ void requestCopy(IOSurface *, bool refresh, uint64_t work = 0);+ void copyLoop();+ static void copyThreadMain(void *, wait_result_t);+ const uint8_t *surfaceBytes(IOSurface *, IOMemoryDescriptor *);+ void releaseSurfaceMaps();+ void stopCopies();+ bool createDisplayAttributes();+ static void vblFired(OSObject *, IOTimerEventSource *);++ struct SwapInfo { // IOMobileFramebufferLegacy::SwapInfoBlob as AppleParavirtDisplay fills it (48 bytes)+ uint32_t swapID;+ uint64_t words[5];+ };+ static_assert(sizeof(SwapInfo) == 48, "IOMobileFramebufferLegacy::SwapInfoBlob");+ static constexpr unsigned kSwapInfoRing = 6;++ // Stage 2: the blob resources of the last surfaces shown (WindowServer swaps a few framebuffers in turn), each holding its+ // surface retained and its memory prepared (the host reads the pages) until RESOURCE_UNREF.+ struct ScanoutResource {+ IOSurface *surface;+ IOMemoryDescriptor *memory;+ uint64_t offset, used;+ uint32_t id, format, width, height, stride;+ };+ static constexpr unsigned kScanoutResources = 8;+ VirtioGpu fGpu;+ ScanoutResource fResources[kScanoutResources];+ VirtioGpuEntry *fEntries; // a blob's page list being built (copy thread)+ uint64_t fResourceClock, fFlushes, fFlushNs, fFlushMaxNs;+ uint64_t fLastFrameTime, fFrameGapMaxNs, fHitches; // main frames apart by 50 to 500 ms (a still screen is longer)+ uint64_t fSecondStart, fSecondFrames, fPeakFps; // main frames in each second, the most of a report's seconds+ // Scheduling latency in the guest: the copy thread from its wakeup to running, the VBL timer past its period.+ uint64_t fCopyRequestTime, fWakeMaxNs, fWakeLate, fVBLDue, fVBLLateMaxNs, fVBLLate;+ uint64_t fSubmitTime[16], fFenceWaits, fFenceWaitNs, fFenceWaitMaxNs; // diagnostic: swap submitted -> programmed (IOSurface fences)+ // A swap's GPU work: the 3D submissions made before it (droidvm_virtgpu_submitted at swap_submit). The host reads the surface for+ // the screen in another context, which does not wait for the guest's renderers: shown before that work has finished, a frame came+ // out half drawn (the wallpaper twitched). The copy thread waits for it; the waits, their time and the ones given up after 200 ms.+ uint64_t fSubmitWork[16], fCopyWork, fGpuWaits, fGpuWaitNs, fGpuWaitMaxNs, fGpuLate;+ uint32_t fScanoutResource;+ unsigned fScanoutFailures;++ PE_Video fVideo;+ IOMemoryMap *fScanoutMap;+ uint8_t *fHalfToByte; // 'RGhA' surfaces: the 8-bit value of each half float >> 2 (a channel), clamped to [0, 1]+ uint16_t *fRow; // one 'RGhA' row+ uint32_t *fLine; // one converted row, written to the scanout at once (it is write-combined)+ uint8_t fXr10ToByte[1024]; // 'b3a8' surfaces: the 8-bit value of each 10-bit extended-range channel, clamped to [0, 1]+ uint64_t fRowBytes;+ uint8_t *fScanout;+ IOTimerEventSource *fVBL;+ DisplayColorRemapMode fColorRemapMode;+ uint32_t fSurfaceFormat;+ bool fDisplayOn;+ uint64_t fFrames;+ uint64_t fLayerShape; // bring-up: the layers of the last swap, logged when they change+ uint64_t fLastLit, fLastCenter; // bring-up: lit pixels and centre pixel of the last frame shown+ uint64_t fTicks, fDropped, fReported; // swap_begin_gated runs, swaps dropped, fSubmitted + fFrames + fDropped + fStalled at the last report+ uint64_t fWaitFailures; // diagnostic: swap_wait calls that failed (WindowServer's display readiness)+ uint64_t fWaitReleased; // swap_wait calls answered for the swap on screen (swap_wait)+ uint64_t fCopies, fCopyNs, fCopyMaxNs; // diagnostic: copySurface runs and their time since the last report+ uint64_t fPrepareNs, fReadNs, fConvertNs, fWriteNs; // diagnostic: the parts of fCopyNs+ // The kernel mappings of the last surfaces copied (WindowServer swaps a few framebuffers in turn); readBytes of each row of an+ // unmapped descriptor was most of the copy's time.+ struct SurfaceMap {+ IOSurface *surface; // retained while mapped+ IOMemoryMap *map;+ uint64_t used;+ };+ static constexpr unsigned kSurfaceMaps = 4;+ SurfaceMap fSurfaceMaps[kSurfaceMaps];+ uint64_t fSurfaceMapClock;+ // The copies run on a thread of their own: a copy is tens of milliseconds of reading write-combined GPU memory (the surfaces'+ // pages are WC for the GPU, a cached alias reads stale lines), and in the work loop it held the command gate WindowServer swaps+ // through. A swap completes at once; the thread copies the newest surface asked for, the ones it had no time for are skipped.+ IOLock *fCopyLock;+ IOSurface *fCopyNext; // retained; the next surface to copy+ bool fCopyRefresh, fCopyStop, fCopyThreadDone;+ uint64_t fCopiesSkipped;+ uint64_t fSubmitted, fStalled; // swaps verified, VBL ticks with a queued swap clean_queue_gated did not hand over+ SwapInfo fSwapInfo[kSwapInfoRing]; // held while kSwapInfoHeld is set, sent in order afterwards+ // The surface on screen, copied again on the ticks without a swap, as a display controller scans out the buffer it shows. Core+ // Animation swaps as soon as it has committed the frame's GPU work, not when the GPU is done, so the copy at the swap can take a+ // frame the GPU is still drawing; once the screen is still (no more swaps) the half-drawn frame stayed (a menu's upper half+ // missing, the outline of a closed window left over the desktop). WindowServer does not draw into the surface on screen until a+ // later swap replaces it.+ static constexpr unsigned kRefreshTicks = 30; // about half a second after each swap, on its ticks 1, 2, 4, 8, 16 and 30 (a copy+ // takes milliseconds of the work loop)+ IOSurface *fShown;+ unsigned fRefreshLeft;+ unsigned fSwapInfoRead, fSwapInfoWrite;+};++// Registered by the name of vma2's display class: WindowServer (SLCADisplay::read_pv_preferences, GenerateClientUUIDForDisplay)+// takes an external display whose service is an AppleParavirtDisplay with a ParavirtDisplayPrefs dictionary for paravirtualized,+// and names it by its CADisplay uniqueId (IOMFBUUID) rather than a random UUID kept in the Data volume. BackBoard's hit tests look+// the touchscreen's displayUUID (DroidVMInput: IOMFBUUID, as HSTouchHIDService reads a display service's) up among those names.+OSDefineMetaClassWithInit(XnuDisplay, IOMobileFramebufferLegacy, )+XnuDisplay::MetaClass::MetaClass() : OSMetaClass("AppleParavirtDisplay", XnuDisplay::superClass, sizeof(XnuDisplay)) {}+OSDefineDefaultStructors(XnuDisplay, IOMobileFramebufferLegacy)++static IOPMPowerState gPowerStates[2] = { // AppleParavirtDisplay's gPowerState+ {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},+ {1, kIOPMDeviceUsable, kIOPMPowerOn, kIOPMPowerOn, 0, 0, 0, 0, 0, 0, 0, 0},+};++bool XnuDisplay::start(IOService *provider)+{+ fRefreshHz = 120;+ PE_parse_boot_argn("droidvm-display-hz", &fRefreshHz, sizeof(fRefreshHz));+ if (fRefreshHz < 30 || fRefreshHz > 240)+ fRefreshHz = 120;+ if (getPlatform()->getConsoleInfo(&fVideo) != kIOReturnSuccess || !fVideo.v_baseAddr || fVideo.v_depth != 32) {+ IOLog("XnuDisplay: no 32-bit boot framebuffer (base %#lx depth %lu)\n", fVideo.v_baseAddr, fVideo.v_depth);+ return false;+ }+ IOMemoryDescriptor *memory = IOMemoryDescriptor::withPhysicalAddress(fVideo.v_baseAddr & ~3UL, fVideo.v_rowBytes * fVideo.v_height,+ kIODirectionInOut);+ if (memory) {+ // xnulinux: cacheable like Linux's own mapping of the same pages (the host reads the frames through it), not write-combined+ fScanoutMap = memory->createMappingInTask(kernel_task, 0, kIOMapAnywhere | kIOMapDefaultCache);+ memory->release();+ }+ if (!fScanoutMap) {+ IOLog("XnuDisplay: cannot map the framebuffer at %#lx\n", fVideo.v_baseAddr);+ return false;+ }+ fScanout = reinterpret_cast<uint8_t *>(fScanoutMap->getVirtualAddress());+ IOLog("XnuDisplay: scanout %#lx %lux%lu row %lu\n", fVideo.v_baseAddr, fVideo.v_width, fVideo.v_height, fVideo.v_rowBytes);+ // Clear to a solid colour until the first frame: the boot console's text goes away and the screen shows that this mapping reaches it.+ for (unsigned long y = 0; y < fVideo.v_height; y++) {+ auto *row = reinterpret_cast<volatile uint32_t *>(fScanout + y * fVideo.v_rowBytes);+ for (unsigned long x = 0; x < fVideo.v_width; x++)+ row[x] = 0xff203050;+ }+ unsigned useGpu = 1; // droidvm-display-virtio-gpu=0: stage 1 (the CPU copy) even with the device+ PE_parse_boot_argn("droidvm-display-virtio-gpu", &useGpu, sizeof(useGpu));+ if (useGpu) {+ const char *why = fGpu.start();+ if (!why && (fGpu.features() & 0x48) != 0x48)+ why = "no guest-handle blobs";+ if (!why)+ fEntries = static_cast<VirtioGpuEntry *>(IOMalloc(VirtioGpu::kMaxEntries * sizeof(VirtioGpuEntry)));+ if (!why && !fEntries)+ why = "no page list";+ IOLog("XnuDisplay: virtio-gpu scanout %s%s (features %#llx)\n", why ? "off: " : "on", why ? why : "", fGpu.features());+ if (why)+ fGpu = VirtioGpu();+ DroidVMVirtioGpu::selftest3D(); // vgpu-selftest=1: one DRM context through the host's drm2kgsl+ }+ fCopyLock = IOLockAlloc();+ thread_t copier = nullptr;+ if (!fCopyLock || kernel_thread_start(copyThreadMain, this, &copier) != KERN_SUCCESS) {+ IOLog("XnuDisplay: no copy thread\n");+ if (fCopyLock)+ IOLockFree(fCopyLock);+ fCopyLock = nullptr;+ OSSafeReleaseNULL(fScanoutMap);+ return false;+ }+ thread_deallocate(copier);+ if (fGpu.ready())+ setProperty("CursorPlane", 1ULL, 32);+ if (!IOMobileFramebufferLegacy::start(provider)) {+ IOLog("XnuDisplay: IOMobileFramebufferLegacy::start failed\n");+ stopCopies();+ OSSafeReleaseNULL(fScanoutMap);+ return false;+ }+ IOLog("XnuDisplay: started, display %ux%u at %u Hz\n", display_width(), display_height(), fRefreshHz);+ return true;+}++void XnuDisplay::stop(IOService *provider)+{+ IOMobileFramebufferLegacy::stop(provider);+ stopCopies();+ releaseSurfaceMaps();+ for (ScanoutResource &resource : fResources)+ releaseResource(resource);+ if (fEntries)+ IOFree(fEntries, VirtioGpu::kMaxEntries * sizeof(VirtioGpuEntry));+ fEntries = nullptr;+ if (fHalfToByte)+ IOFree(fHalfToByte, 16384);+ if (fRow)+ IOFree(fRow, fRowBytes);+ if (fLine)+ IOFree(fLine, fVideo.v_width * 4);+ fHalfToByte = nullptr;+ fRow = nullptr;+ fLine = nullptr;+ if (fShown)+ reinterpret_cast<OSObject *>(fShown)->release();+ fShown = nullptr;+ if (fCursorResource) {+ DroidVMVirtioGpu::cursor(0, 0, 0, 0, 0, true);+ DroidVMVirtioGpu::unref(fCursorResource);+ }+ OSSafeReleaseNULL(fCursorPixels);+ if (fCursorSurface)+ reinterpret_cast<OSObject *>(fCursorSurface)->release();+ fCursorSurface = nullptr;+ OSSafeReleaseNULL(fScanoutMap);+ fScanout = nullptr;+}++// Called by IOMobileFramebufferLegacy::start before it creates the default surface and registers the service (it tests bit 0).+bool XnuDisplay::start_hardware()+{+ if (!createDisplayAttributes())+ return false;+ fVBL = IOTimerEventSource::timerEventSource(this, vblFired);+ if (!fVBL || getWorkLoop()->addEventSource(fVBL) != kIOReturnSuccess) { // the work loop of the family's command gate+ IOLog("XnuDisplay: Failed to create VBL timer\n");+ OSSafeReleaseNULL(fVBL);+ return false;+ }+ fVBL->enable();+ at<uint8_t>(this, kHardwareStarted) = 1;+ PMinit();+ getPlatform()->PMRegisterDevice(getProvider(), this); // the provider is no power-managed AppleARMIODevice here+ registerPowerDriver(this, gPowerStates, 2);+ // The panel is always there: report it plugged in (the digital out state IOMobileFramebufferGetDigitalOutState answers), as+ // AppleParavirtDisplay does when the host reports its display. Unplugged (0), WindowServer kept this display disabled and composited+ // a virtual one as the main display ("get_hotplug_state - not active").+ hotPlug_notify(1);+ IOLog("XnuDisplay: hardware started\n");+ return true;+}++IOReturn XnuDisplay::stop_hardware_gated()+{+ if (fVBL) {+ fVBL->cancelTimeout();+ getWorkLoop()->removeEventSource(fVBL);+ OSSafeReleaseNULL(fVBL);+ }+ return kIOReturnSuccess;+}++void XnuDisplay::vblFired(OSObject *owner, IOTimerEventSource *)+{+ auto *display = static_cast<XnuDisplay *>(owner);+ uint64_t now = mach_absolute_time(), late = 0;+ if (display->fVBLDue && now > display->fVBLDue)+ absolutetime_to_nanoseconds(now - display->fVBLDue, &late);+ if (late > 20000000) {+ display->fVBLLate++;+ if (late > display->fVBLLateMaxNs)+ display->fVBLLateMaxNs = late;+ }+ display->swap_begin_gated();+}++// AppleParavirtDisplay::clean_queue_gated: whether a queued swap is ready to be programmed.+bool XnuDisplay::clean_queue_gated()+{+ if (at<IOMFBSwapIORequest *>(this, kCurrentSwap) || !at<IOMFBSwapIORequest *>(this, kSwapQueueFirst))+ return false;+ if (dropObsoleteSwaps_gated())+ return false;+ dropNoOpSwaps_gated();+ dropAbortedSwaps_gated(false);+ dropDummySwaps_gated();+ return at<IOMFBSwapIORequest *>(this, kSwapQueueFirst) != nullptr;+}++// AppleParavirtDisplay::swap_begin_gated: the family calls it when a swap is submitted, the VBL timer every refresh.+IOReturn XnuDisplay::swap_begin_gated()+{+ if (!fVBL)+ return kIOReturnNotReady;+ fVBL->cancelTimeout();+ uint64_t frames = fFrames;+ while (clean_queue_gated()) {+ IOMFBSwapIORequest *swap = at<IOMFBSwapIORequest *>(this, kSwapQueueFirst);+ at<IOMFBSwapIORequest *>(this, kCurrentSwap) = swap;+ iomfbUpdateSwapInfoState(this, swap, 2);+ IOMFBSwapIORequest *next = at<IOMFBSwapIORequest *>(swap, kSwapNext);+ IOMFBSwapIORequest **prev = at<IOMFBSwapIORequest **>(swap, kSwapPrev);+ if (next)+ at<IOMFBSwapIORequest **>(next, kSwapPrev) = prev;+ else+ at<IOMFBSwapIORequest **>(this, kSwapQueueLast) = prev;+ *prev = next;+ if ((at<uint32_t>(swap, kSwapDropReasons) & ~8u) == 0) {+ program_hardware_gated();+ } else {+ dropSwap_gated(swap, false);+ fDropped++;+ }+ }+ if (fFrames == frames && fShown && fRefreshLeft) {+ unsigned elapsed = kRefreshTicks - --fRefreshLeft;+ if (!(elapsed & (elapsed - 1)) || !fRefreshLeft)+ requestCopy(fShown, true);+ } else if (fFrames == frames && fShown && fGpu.ready() && fTicks % fRefreshHz == 0) {+ // A still screen sends nothing, and the app's window (re)created meanwhile (the activity resumed, rotated) stayed black:+ // flush the surface on screen once a second, a single command when the host scans it out.+ requestCopy(fShown, true);+ }+ if (at<IOMFBSwapIORequest *>(this, kSwapQueueFirst))+ fStalled++;+ if (++fTicks % (10 * fRefreshHz) == 0 && fSubmitted + fFrames + fDropped + fStalled != fReported) { // about every 10 s while swaps arrive+ fReported = fSubmitted + fFrames + fDropped + fStalled;+ IOLog("XnuDisplay: %llu swaps submitted, %llu shown, %llu dropped, %llu ticks stalled (current %p), last frame %llu lit centre %#llx; "+ "%llu copies mean %llu us (prepare %llu read %llu convert %llu write %llu) max %llu us, %llu waits released\n",+ fSubmitted, fFrames, fDropped, fStalled, at<IOMFBSwapIORequest *>(this, kCurrentSwap), fLastLit, fLastCenter,+ fCopies, fCopies ? fCopyNs / fCopies / 1000 : 0, fCopies ? fPrepareNs / fCopies / 1000 : 0,+ fCopies ? fReadNs / fCopies / 1000 : 0, fCopies ? fConvertNs / fCopies / 1000 : 0, fCopies ? fWriteNs / fCopies / 1000 : 0,+ fCopyMaxNs / 1000, fWaitReleased);+ if (fCopiesSkipped)+ IOLog("XnuDisplay: %llu copies skipped for newer ones\n", fCopiesSkipped);+ if (fFlushes)+ IOLog("XnuDisplay: %llu virtio-gpu flushes mean %llu us max %llu us, %llu commands; %llu frame gaps of 50-500 ms, longest %llu ms\n",+ fFlushes, fFlushNs / fFlushes / 1000, fFlushMaxNs / 1000, fGpu.commands(), fHitches, fFrameGapMaxNs / 1000000);+ if (fCursorUpdates)+ IOLog("XnuDisplay: cursor %ux%u, %llu image updates, %llu moves, position %d,%d\n",+ fCursorWidth, fCursorHeight, fCursorUpdates, fCursorMoves, fCursorOffsetX, fCursorOffsetY);+ IOLog("XnuDisplay: at most %llu frames in a second\n", fPeakFps);+ if (fFenceWaits)+ IOLog("XnuDisplay: %llu swaps from submit to programmed mean %llu us max %llu us\n", fFenceWaits,+ fFenceWaitNs / fFenceWaits / 1000, fFenceWaitMaxNs / 1000);+ fFenceWaits = fFenceWaitNs = fFenceWaitMaxNs = 0;+ if (fGpuWaits)+ IOLog("XnuDisplay: %llu frames waited for their GPU work, mean %llu us max %llu us, %llu given up\n", fGpuWaits,+ fGpuWaitNs / fGpuWaits / 1000, fGpuWaitMaxNs / 1000, fGpuLate);+ fGpuWaits = fGpuWaitNs = fGpuWaitMaxNs = fGpuLate = 0;+ fPeakFps = 0;+ IOLog("XnuDisplay: scheduling: %llu copy wakeups over 20 ms (longest %llu ms), %llu VBL ticks over 20 ms late (latest by %llu ms)\n",+ fWakeLate, fWakeMaxNs / 1000000, fVBLLate, fVBLLateMaxNs / 1000000);+ fFlushes = fFlushNs = fFlushMaxNs = fHitches = fFrameGapMaxNs = 0;+ fWakeLate = fWakeMaxNs = fVBLLate = fVBLLateMaxNs = 0;+ fCopies = fCopyNs = fCopyMaxNs = fPrepareNs = fReadNs = fConvertNs = fWriteNs = 0;+ }+ uint64_t period;+ nanoseconds_to_absolutetime(1000000000ULL / fRefreshHz, &period);+ fVBLDue = mach_absolute_time() + period;+ return fVBL->setTimeoutUS(1000000 / fRefreshHz);+}++// CoreAnimation asks swap_wait, without blocking, whether its last swaps are done before it composes the next frame+// (IOMFBDisplay::can_update_); after three swaps WindowServer found the display unready for good.+// The family answers kIOReturnBusy for the last completed swap (+7164, swap_complete_gated) as long as no later one replaces it: a+// display controller is still scanning out its surface (swap_wait_gated 0x...d3dc). Here the swap's surface was copied to the+// scanout when it was programmed, so it is free; WindowServer, told it is busy, waited for its next display update to ask again,+// and the screen updated at about 10 frames a second however little it drew.+IOReturn XnuDisplay::swap_wait(IOMobileFramebufferUserClient *client, unsigned int swapID, unsigned int options, unsigned int timeout)+{+ IOReturn result = IOMobileFramebufferLegacy::swap_wait(client, swapID, options, timeout);+ if (result == kIOReturnBusy && (options & 0x7fffffffu) == 0 && swapID == at<uint32_t>(this, 7164)) {+ fWaitReleased++;+ return kIOReturnSuccess;+ }+ if (result != kIOReturnSuccess && (++fWaitFailures <= 20 || fWaitFailures % 1000 == 0))+ IOLog("XnuDisplay: swap_wait(%u, 0x%x, %u) = 0x%x (%llu failures): +7164 %u power %u/%u +7188 %u +140 0x%x current %p queue %p\n",+ swapID, options, timeout, result, fWaitFailures, at<uint32_t>(this, 7164), at<uint32_t>(this, kSystemPowerState),+ at<uint32_t>(this, kAPIPowerState), at<uint32_t>(this, kHardwarePowered), at<uint8_t>(this, kHardwareStarted),+ at<IOMFBSwapIORequest *>(this, kCurrentSwap), at<IOMFBSwapIORequest *>(this, kSwapQueueFirst));+ return result;+}++// Diagnostic: when each swap arrives. The family holds a swap until the GPU has written its surfaces (swap_apply_fences_gated:+// IOSurface::createFence on each layer), so submit -> programmed is how long the swap waited for its frame's GPU work.+IOReturn XnuDisplay::swap_submit(IOMFBSwapRec *rec, IOUserClient *client, unsigned int *out)+{+ if (rec)+ {+ fSubmitTime[reinterpret_cast<const uint32_t *>(rec)[38] % 16] = mach_absolute_time();+ fSubmitWork[reinterpret_cast<const uint32_t *>(rec)[38] % 16] = droidvm_virtgpu_submitted();+ }+ return IOMobileFramebufferLegacy::swap_submit(rec, client, out);+}++// AppleParavirtDisplay::do_power_state_change_gated: the display is on while both the system and WindowServer (setAPIPowerState)+// want it on; each change goes to WindowServer as a power state notification, which CoreAnimation waits for before it swaps.+IOReturn XnuDisplay::do_power_state_change_gated()+{+ bool on = at<uint32_t>(this, kSystemPowerState) && at<uint32_t>(this, kAPIPowerState);+ if (on == fDisplayOn)+ return kIOReturnSuccess;+ fDisplayOn = on;+ at<uint32_t>(this, kHardwarePowered) = on;+ IOLog("XnuDisplay: display %s\n", on ? "on" : "off");+ powerstate_notify(true, on);+ return kIOReturnSuccess;+}++// AppleParavirtDisplay's private parameter -1 carries timestamp, x, y and visibility in four uint64_t words.+IOReturn XnuDisplay::set_parameter(IOMFBParameterName name, const unsigned long long *values, unsigned int count)+{+ if (static_cast<uint32_t>(name) != UINT32_MAX)+ return IOMobileFramebufferLegacy::set_parameter(name, values, count);+ if (count != 4 || !values)+ return kIOReturnBadArgument;+ fCursorX = static_cast<uint16_t>(values[1]);+ fCursorY = static_cast<uint16_t>(values[2]);+ bool changed = fCursorVisible != !!values[3];+ fCursorVisible = !!values[3];+ fCursorMoves++;+ return moveCursor(changed);+}++IOReturn XnuDisplay::moveCursor(bool image)+{+ if (!fCursorResource)+ return kIOReturnSuccess;+ // WindowServer positions the cursor in the physical display mode, while its desktop surface can be scaled (e.g.+ // 1344x756 -> 1920x1080). Android overlays the cursor in scanout-buffer coordinates. The glyph is already at source scale.+ int32_t x = fCursorX + fCursorOffsetX, y = fCursorY + fCursorOffsetY;+ if (fShown) {+ x = static_cast<int64_t>(x) * static_cast<int64_t>(ioSurfaceWidth(fShown)) / static_cast<int64_t>(fVideo.v_width);+ y = static_cast<int64_t>(y) * static_cast<int64_t>(ioSurfaceHeight(fShown)) / static_cast<int64_t>(fVideo.v_height);+ }+ x += fCursorCropX;+ y += fCursorCropY;+ IOReturn status = DroidVMVirtioGpu::cursor(fCursorVisible ? fCursorResource : 0,+ x, y, 0, 0, image || !fCursorVisible);+ if (status)+ IOLog("XnuDisplay: cursor command failed %#x\n", status);+ return status;+}++void XnuDisplay::updateCursor(IOSurface *surface, int32_t x, int32_t y)+{+ if (!surface) {+ fCursorVisible = false;+ moveCursor(true);+ return;+ }+ uint32_t width = ioSurfaceWidth(surface), height = ioSurfaceHeight(surface);+ IOMemoryDescriptor *memory = ioSurfaceMemory(surface);+ if (!memory || ioSurfacePixelFormat(surface) != 'BGRA' || !width || !height || width > 256 || height > 256)+ return;+ fCursorOffsetX = x;+ fCursorOffsetY = y;+ uint32_t seed = ioSurfaceUnlockSeed(surface);+ if (surface == fCursorSurface && seed == fCursorSeed) {+ bool hidden = !fCursorVisible;+ fCursorVisible = true;+ fCursorMoves++;+ moveCursor(hidden);+ return;+ }+ // The Android app displays a 64x64 cursor view. macOS supplies a 128x128 canvas with the glyph inside transparent padding;+ // send the glyph at its original pixel scale and account for the removed padding in its position.+ constexpr uint32_t cursorSize = 64;+ if (!fCursorResource) {+ OSSafeReleaseNULL(fCursorPixels);+ fCursorPixels = IOBufferMemoryDescriptor::inTaskWithPhysicalMask(kernel_task,+ static_cast<IOOptionBits>(kIOMemoryPhysicallyContiguous) | kIODirectionInOut, cursorSize * cursorSize * 4, 0xfffffffffffff000ULL);+ if (!fCursorPixels)+ return;+ uint32_t id = DroidVMVirtioGpu::resourceId();+ struct { VirtioGpuHeader h; uint32_t id, format, width, height; }+ create = {{0x101, 0, 0, 0, 0, {}}, id, 1 /* B8G8R8A8_UNORM */, cursorSize, cursorSize};+ if (fGpu.command(&create, sizeof(create)))+ return;+ IOByteCount length;+ VirtioGpuEntry entry = {fCursorPixels->getPhysicalSegment(0, &length), cursorSize * cursorSize * 4, 0};+ struct { VirtioGpuHeader h; uint32_t id, count; } attach = {{0x106, 0, 0, 0, 0, {}}, id, 1};+ if (fGpu.command(&attach, sizeof(attach), &entry, sizeof(entry))) {+ DroidVMVirtioGpu::unref(id);+ return;+ }+ fCursorResource = id;+ fCursorWidth = cursorSize;+ fCursorHeight = cursorSize;+ }+ IOMemoryMap *map = memory->createMappingInTask(kernel_task, 0, kIOMapAnywhere);+ if (!map)+ return;+ const uint8_t *source = reinterpret_cast<const uint8_t *>(map->getVirtualAddress()) + ioSurfaceBaseOffset(surface);+ uint32_t left = width, top = height;+ uint64_t stride = ioSurfaceBytesPerRow(surface);+ for (uint32_t row = 0; row < height; row++)+ for (uint32_t column = 0; column < width; column++)+ if (source[row * stride + column * 4 + 3]) {+ if (column < left) left = column;+ if (row < top) top = row;+ }+ auto *pixels = static_cast<uint8_t *>(fCursorPixels->getBytesNoCopy());+ bzero(pixels, cursorSize * cursorSize * 4);+ uint32_t copyWidth = width - left < cursorSize ? width - left : cursorSize;+ uint32_t copyHeight = height - top < cursorSize ? height - top : cursorSize;+ for (uint32_t row = 0; row < copyHeight; row++)+ memcpy(pixels + row * cursorSize * 4, source + (row + top) * stride + left * 4, copyWidth * 4);+ map->release();+ fCursorCropX = left;+ fCursorCropY = top;+ struct { VirtioGpuHeader h; VirtioGpuRect rect; uint64_t offset; uint32_t id, padding; }+ transfer = {{0x105, 0, 0, 0, 0, {}}, {0, 0, cursorSize, cursorSize}, 0, fCursorResource, 0};+ if (fGpu.command(&transfer, sizeof(transfer)))+ return;+ reinterpret_cast<OSObject *>(surface)->retain();+ if (fCursorSurface)+ reinterpret_cast<OSObject *>(fCursorSurface)->release();+ fCursorSurface = surface;+ fCursorSeed = seed;+ fCursorVisible = true;+ fCursorUpdates++;+ moveCursor(true);+}++// Show the desktop and cursor layers independently, then complete the swap.+void XnuDisplay::program_hardware_gated()+{+ IOMFBSwapIORequest *swap = at<IOMFBSwapIORequest *>(this, kCurrentSwap);+ uint64_t &submitted = fSubmitTime[at<uint32_t>(swap, 980) % 16];+ const uint64_t work = fSubmitWork[at<uint32_t>(swap, 980) % 16];+ if (submitted) {+ uint64_t waited = 0;+ absolutetime_to_nanoseconds(mach_absolute_time() - submitted, &waited);+ submitted = 0;+ fFenceWaits++;+ fFenceWaitNs += waited;+ if (waited > fFenceWaitMaxNs)+ fFenceWaitMaxNs = waited;+ }+ // Layer 1 is the independent cursor. The largest surface is the desktop; cursor-only swaps leave its scanout unchanged.+ uint8_t layers = at<uint8_t>(swap, kSwapLayers);+ if (layers & 2)+ updateCursor(at<IOSurface *>(swap, kSwapMainSurface + 8), at<int32_t>(swap, 97), at<int32_t>(swap, 101));+ IOSurface *surface = nullptr;+ uint64_t area = 0, shape = layers;+ for (unsigned layer = 0; layer < kSwapLayerCount; layer++) {+ IOSurface *candidate = (layers >> layer & 1) ? at<IOSurface *>(swap, kSwapMainSurface + 8 * layer) : nullptr;+ if (!candidate)+ continue;+ uint64_t width = ioSurfaceWidth(candidate), height = ioSurfaceHeight(candidate);+ shape = shape * 31 + width * 65537 + height;+ if (width * height > area) {+ area = width * height;+ surface = candidate;+ }+ }+ if (shape != fLayerShape) { // bring-up: each new combination of layers+ fLayerShape = shape;+ IOLog("XnuDisplay: swap layers %#x:", layers);+ for (unsigned layer = 0; layer < kSwapLayerCount; layer++) {+ IOSurface *candidate = (layers >> layer & 1) ? at<IOSurface *>(swap, kSwapMainSurface + 8 * layer) : nullptr;+ if (candidate)+ IOLog(" %u: %llux%llu %#x", layer, ioSurfaceWidth(candidate), ioSurfaceHeight(candidate), ioSurfacePixelFormat(candidate));+ }+ IOLog("\n");+ }+ if (surface && area * 4 >= static_cast<uint64_t>(fVideo.v_width) * fVideo.v_height) { // a quarter of the screen at least+ if (!fFrames++) // WindowServer's first frame: the verbose boot console stops drawing over the framebuffer (it goes to serial)+ PE_initialize_console(nullptr, kPEDisableScreen);+ uint64_t now = mach_absolute_time(), gap = 0;+ if (fLastFrameTime)+ absolutetime_to_nanoseconds(now - fLastFrameTime, &gap);+ fLastFrameTime = now;+ uint64_t second = 0;+ absolutetime_to_nanoseconds(now - fSecondStart, &second);+ if (second >= 1000000000) {+ if (fSecondFrames > fPeakFps)+ fPeakFps = fSecondFrames;+ fSecondStart = now;+ fSecondFrames = 0;+ }+ fSecondFrames++;+ if (gap >= 50000000 && gap < 500000000) {+ fHitches++;+ if (gap > fFrameGapMaxNs)+ fFrameGapMaxNs = gap;+ }+ requestCopy(surface, false, work);+ if (surface != fShown) {+ reinterpret_cast<OSObject *>(surface)->retain();+ if (fShown)+ reinterpret_cast<OSObject *>(fShown)->release();+ fShown = surface;+ }+ fRefreshLeft = kRefreshTicks;+ }+ swap_complete_gated();+}++// 8-bit BGRA, 16-bit half-float RGBA, and 'b3a8': two planes, 10-bit extended-range BGR in 32 bits and 8-bit alpha (QuartzCore's+// four_cc_to_mtl_format: Metal's format 550), what WindowServer draws with a deep framebuffer (CADeviceUseCIF10).+static constexpr uint32_t kFormatBGRA = 'BGRA', kFormatRGhA = 'RGhA', kFormatB3A8 = 'b3a8';++// A half float's value in [0, 1] as a byte, in integer arithmetic (no floating point in the kernel).+static uint8_t halfToByte(uint16_t half)+{+ unsigned exponent = (half >> 10) & 31, mantissa = half & 1023;+ if (half & 0x8000 || (exponent == 31 && mantissa)) // negative or NaN+ return 0;+ if (exponent >= 15) // 1.0 and above+ return 255;+ uint32_t scaled = (exponent ? 1024 + mantissa : mantissa) * 255; // value * 255 = scaled * 2^(exponent - 25), subnormals 2^-24+ unsigned shift = exponent ? 25 - exponent : 24;+ return static_cast<uint8_t>((scaled + (1u << (shift - 1))) >> shift);+}++void XnuDisplay::requestCopy(IOSurface *surface, bool refresh, uint64_t work)+{+ reinterpret_cast<OSObject *>(surface)->retain();+ IOLockLock(fCopyLock);+ IOSurface *skipped = fCopyNext;+ if (skipped && refresh && !fCopyRefresh) { // a swap's surface waiting is newer than the one on screen+ IOLockUnlock(fCopyLock);+ reinterpret_cast<OSObject *>(surface)->release();+ return;+ }+ fCopyNext = surface;+ fCopyRefresh = refresh;+ fCopyWork = work;+ if (!skipped)+ fCopyRequestTime = mach_absolute_time();+ IOLockWakeup(fCopyLock, &fCopyNext, true);+ IOLockUnlock(fCopyLock);+ if (skipped) {+ fCopiesSkipped++;+ reinterpret_cast<OSObject *>(skipped)->release();+ }+}++void XnuDisplay::copyThreadMain(void *owner, wait_result_t)+{+ static_cast<XnuDisplay *>(owner)->copyLoop();+ thread_terminate(current_thread());+}++void XnuDisplay::copyLoop()+{+ IOLockLock(fCopyLock);+ while (!fCopyStop) {+ IOSurface *surface = fCopyNext;+ if (!surface) {+ IOLockSleep(fCopyLock, &fCopyNext, THREAD_UNINT);+ continue;+ }+ bool refresh = fCopyRefresh;+ const uint64_t work = fCopyWork;+ fCopyNext = nullptr;+ uint64_t waited = 0;+ absolutetime_to_nanoseconds(mach_absolute_time() - fCopyRequestTime, &waited);+ IOLockUnlock(fCopyLock);+ if (waited > 20000000) {+ fWakeLate++;+ if (waited > fWakeMaxNs)+ fWakeMaxNs = waited;+ }+ if (!droidvm_virtgpu_finished(work)) {+ const uint64_t begin = mach_absolute_time();+ const bool drawn = droidvm_virtgpu_wait_finished(work, 200000);+ uint64_t took = 0;+ absolutetime_to_nanoseconds(mach_absolute_time() - begin, &took);+ fGpuWaits++;+ fGpuWaitNs += took;+ if (took > fGpuWaitMaxNs)+ fGpuWaitMaxNs = took;+ if (!drawn)+ fGpuLate++;+ }+ if (!scanOut(surface))+ copySurface(surface, refresh);+ reinterpret_cast<OSObject *>(surface)->release();+ IOLockLock(fCopyLock);+ }+ fCopyThreadDone = true;+ IOLockWakeup(fCopyLock, &fCopyThreadDone, false);+ IOLockUnlock(fCopyLock);+}++// The kernel address of a surface's memory, mapped once for the next copies.+const uint8_t *XnuDisplay::surfaceBytes(IOSurface *surface, IOMemoryDescriptor *memory)+{+ SurfaceMap *slot = &fSurfaceMaps[0];+ for (SurfaceMap &entry : fSurfaceMaps) {+ if (entry.surface == surface && entry.map->getMemoryDescriptor() == memory) {+ entry.used = ++fSurfaceMapClock;+ return reinterpret_cast<const uint8_t *>(entry.map->getVirtualAddress());+ }+ if (entry.used < slot->used)+ slot = &entry;+ }+ if (slot->surface) {+ slot->map->release();+ reinterpret_cast<OSObject *>(slot->surface)->release();+ *slot = {};+ }+ IOMemoryMap *map = memory->createMappingInTask(kernel_task, 0, kIOMapAnywhere | kIOMapReadOnly);+ if (!map)+ return nullptr;+ reinterpret_cast<OSObject *>(surface)->retain();+ *slot = {surface, map, ++fSurfaceMapClock};+ return reinterpret_cast<const uint8_t *>(map->getVirtualAddress());+}++void XnuDisplay::stopCopies()+{+ if (!fCopyLock)+ return;+ IOLockLock(fCopyLock);+ fCopyStop = true;+ IOLockWakeup(fCopyLock, &fCopyNext, true);+ while (!fCopyThreadDone)+ IOLockSleep(fCopyLock, &fCopyThreadDone, THREAD_UNINT);+ IOSurface *left = fCopyNext;+ fCopyNext = nullptr;+ IOLockUnlock(fCopyLock);+ if (left)+ reinterpret_cast<OSObject *>(left)->release();+ IOLockFree(fCopyLock);+ fCopyLock = nullptr;+}++void XnuDisplay::releaseSurfaceMaps()+{+ for (SurfaceMap &entry : fSurfaceMaps) {+ if (!entry.surface)+ continue;+ entry.map->release();+ reinterpret_cast<OSObject *>(entry.surface)->release();+ entry = {};+ }+}++// virtio-gpu formats: crosvm's B8G8R8X8, and its half-float RGBA ('RGhA', DRM_FORMAT_ABGR16161616F on the host).+static constexpr uint32_t kVirtioFormatBGRX = 2, kVirtioFormatRGhA = 0x52476841;++bool XnuDisplay::releaseResource(ScanoutResource &resource)+{+ if (!resource.surface)+ return true;+ struct {VirtioGpuHeader h; uint32_t id, padding;} unref = {{0x102, 0, 0, 0, 0, {}}, resource.id, 0};+ if (fGpu.command(&unref, sizeof(unref)))+ return false; // the host may still read the pages: they stay prepared+ if (fScanoutResource == resource.id)+ fScanoutResource = 0;+ resource.memory->complete();+ reinterpret_cast<OSObject *>(resource.surface)->release();+ resource = {};+ return true;+}++// The blob resource of a surface: its pages as a guest-handle blob (RESOURCE_CREATE_BLOB, VIRTIO_GPU_BLOB_MEM_GUEST).+XnuDisplay::ScanoutResource *XnuDisplay::scanoutResource(IOSurface *surface, uint32_t format)+{+ uint64_t width = ioSurfaceWidth(surface), height = ioSurfaceHeight(surface), stride = ioSurfaceBytesPerRow(surface);+ uint64_t offset = ioSurfaceBaseOffset(surface);+ IOMemoryDescriptor *memory = ioSurfaceMemory(surface);+ for (ScanoutResource &resource : fResources) {+ if (resource.surface == surface && resource.memory == memory && resource.format == format && resource.width == width &&+ resource.height == height && resource.stride == stride && resource.offset == offset) {+ resource.used = ++fResourceClock;+ return &resource;+ }+ }+ ScanoutResource *slot = nullptr; // a free one, else the least recently used one not on screen+ for (ScanoutResource &resource : fResources) {+ if (!resource.surface) {+ slot = &resource;+ break;+ }+ if (resource.id != fScanoutResource && (!slot || resource.used < slot->used))+ slot = &resource;+ }+ if (!slot || !releaseResource(*slot))+ return nullptr;+ uint64_t pixelBytes = format == kVirtioFormatRGhA ? 8 : 4;+ uint64_t bytes = (offset + stride * height + 4095) & ~4095ULL;+ if (!memory || !width || !height || width > 16384 || height > 16384 || stride < width * pixelBytes || stride > 65536 ||+ bytes > memory->getLength() || memory->prepare() != kIOReturnSuccess)+ return nullptr;+ uint32_t count = 0;+ for (uint64_t at = 0; at < bytes;) {+ IOByteCount length = 0;+ uint64_t pa = memory->getPhysicalSegment(at, &length, kIOMemoryMapperNone);+ if (length > bytes - at)+ length = bytes - at;+ if (count && fEntries[count - 1].address + fEntries[count - 1].length == pa && fEntries[count - 1].length + length <= UINT32_MAX) {+ fEntries[count - 1].length += static_cast<uint32_t>(length); // physically contiguous with the last entry+ } else {+ if (!pa || !length || length > UINT32_MAX || count == VirtioGpu::kMaxEntries || ((pa | length) & 4095)) {+ memory->complete();+ return nullptr;+ }+ fEntries[count++] = {pa, static_cast<uint32_t>(length), 0};+ }+ at += length;+ }+ uint32_t id = DroidVMVirtioGpu::resourceId(); // the 3D contexts' blobs take theirs from the same counter+ struct {VirtioGpuHeader h; uint32_t id, memory, flags, count; uint64_t blob, size;}+ create = {{0x10c, 0, 0, 0, 0, {}}, id, 1 /* VIRTIO_GPU_BLOB_MEM_GUEST */, 8 /* crosvm: a guest handle */, count, 0, bytes};+ if (IOReturn status = fGpu.command(&create, sizeof(create), fEntries, count * sizeof(VirtioGpuEntry))) {+ IOLog("XnuDisplay: virtio-gpu blob of %llu bytes in %u entries: %#x\n", bytes, count, status);+ memory->complete();+ return nullptr;+ }+ reinterpret_cast<OSObject *>(surface)->retain();+ *slot = {surface, memory, offset, ++fResourceClock, id, format, static_cast<uint32_t>(width), static_cast<uint32_t>(height),+ static_cast<uint32_t>(stride)};+ IOLog("XnuDisplay: scanout resource %u: %llux%llu row %llu offset %llu format %#x, %llu bytes in %u entries\n", id, width,+ height, stride, offset, format, bytes, count);+ return slot;+}++// Stage 2: the host shows the surface (SET_SCANOUT_BLOB when it changes) and blits it now (RESOURCE_FLUSH). False: copy it instead.+bool XnuDisplay::scanOut(IOSurface *surface)+{+ if (!fGpu.ready() || fScanoutFailures >= 8)+ return false;+ uint32_t pixelFormat = ioSurfacePixelFormat(surface);+ uint32_t format = pixelFormat == kFormatBGRA ? kVirtioFormatBGRX : pixelFormat == kFormatRGhA ? kVirtioFormatRGhA : 0;+ if (!format)+ return false;+ uint64_t began = mach_absolute_time();+ ScanoutResource *resource = scanoutResource(surface, format);+ IOReturn status = resource ? kIOReturnSuccess : kIOReturnNoResources;+ uint32_t width = resource ? (resource->width < fVideo.v_width ? resource->width : static_cast<uint32_t>(fVideo.v_width)) : 0;+ uint32_t height = resource ? (resource->height < fVideo.v_height ? resource->height : static_cast<uint32_t>(fVideo.v_height)) : 0;+ if (resource && fScanoutResource != resource->id) {+ struct {VirtioGpuHeader h; VirtioGpuRect rect; uint32_t scanout, id, width, height, format, padding, strides[4], offsets[4];}+ scanout = {{0x10d, 0, 0, 0, 0, {}}, {0, 0, width, height}, 0, resource->id, resource->width, resource->height, format, 0,+ {resource->stride}, {static_cast<uint32_t>(resource->offset)}};+ status = fGpu.command(&scanout, sizeof(scanout), nullptr, 0, false);+ if (!status)+ fScanoutResource = resource->id;+ }+ if (!status) {+ struct {VirtioGpuHeader h; VirtioGpuRect rect; uint32_t id, padding;} flush = {{0x104, 0, 0, 0, 0, {}}, {0, 0, width, height}, resource->id, 0};+ // Unfenced: waiting for the host's blit (5 ms on average, 25 at worst) held this thread while newer swaps arrived, and the+ // frames it had no time for were skipped -- the hitches of a window drag. The host reads a surface WindowServer does not+ // draw into before a later swap replaces it.+ status = fGpu.command(&flush, sizeof(flush), nullptr, 0, false);+ }+ if (status) {+ if (++fScanoutFailures == 8)+ IOLog("XnuDisplay: virtio-gpu scanout failed 8 times (last %#x); copying from now on\n", status);+ return false;+ }+ if (pixelFormat != fSurfaceFormat) {+ IOLog("XnuDisplay: virtio-gpu scanout of format %#x\n", pixelFormat);+ fSurfaceFormat = pixelFormat;+ }+ uint64_t ns;+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &ns);+ fFlushes++;+ fFlushNs += ns;+ if (ns > fFlushMaxNs)+ fFlushMaxNs = ns;+ return true;+}++void XnuDisplay::copySurface(IOSurface *surface, bool refresh)+{+ uint64_t width = ioSurfaceWidth(surface), height = ioSurfaceHeight(surface), rowBytes = ioSurfaceBytesPerRow(surface);+ uint64_t base = ioSurfaceBaseOffset(surface);+ uint32_t format = ioSurfacePixelFormat(surface);+ IOMemoryDescriptor *memory = ioSurfaceMemory(surface);+ if (format != fSurfaceFormat || !fFrames) {+ IOLog("XnuDisplay: surface %llux%llu row %llu offset %llu format %#x memory %p\n", width, height, rowBytes, base, format, memory);+ for (uint32_t plane = 0, planes = ioSurfacePlaneCount(surface); plane < planes; plane++)+ IOLog("XnuDisplay: plane %u: %llux%llu offset %llu row %llu element %llu\n", plane, ioSurfacePlaneWidth(surface, plane),+ ioSurfacePlaneHeight(surface, plane), ioSurfacePlaneOffset(surface, plane), ioSurfacePlaneBytesPerRow(surface, plane),+ ioSurfacePlaneBytesPerElement(surface, plane));+ fSurfaceFormat = format;+ }+ if (format == kFormatB3A8) { // the colour plane; alpha is not shown+ if (ioSurfacePlaneCount(surface) < 1 || ioSurfacePlaneBytesPerElement(surface, 0) != 4)+ return;+ base = ioSurfacePlaneOffset(surface, 0);+ rowBytes = ioSurfacePlaneBytesPerRow(surface, 0);+ }+ uint64_t pixelBytes = format == kFormatRGhA ? 8 : 4;+ if (!memory || !fScanout || rowBytes < width * pixelBytes || (format != kFormatBGRA && format != kFormatRGhA && format != kFormatB3A8))+ return;+ uint64_t copyWidth = width < fVideo.v_width ? width : fVideo.v_width;+ uint64_t copyHeight = height < fVideo.v_height ? height : fVideo.v_height;+ if (!fLine) {+ fRowBytes = fVideo.v_width * 8;+ fRow = static_cast<uint16_t *>(IOMalloc(fRowBytes));+ fLine = static_cast<uint32_t *>(IOMalloc(fVideo.v_width * 4));+ fHalfToByte = static_cast<uint8_t *>(IOMalloc(16384));+ if (!fRow || !fLine || !fHalfToByte) {+ if (fRow)+ IOFree(fRow, fRowBytes);+ if (fLine)+ IOFree(fLine, fVideo.v_width * 4);+ if (fHalfToByte)+ IOFree(fHalfToByte, 16384);+ fRow = nullptr;+ fLine = nullptr;+ fHalfToByte = nullptr;+ return;+ }+ // Indexed by the half float >> 2 (16 KiB, in the L1 cache where all 64 KiB were not): 8 bits of mantissa left, finer than+ // a byte's step anywhere in [0, 1].+ for (uint32_t index = 0; index < 16384; index++)+ fHalfToByte[index] = halfToByte(static_cast<uint16_t>(index << 2 | 2));+ for (uint32_t value = 0; value < 1024; value++) // extended range: 384 is 0.0, 894 is 1.0+ fXr10ToByte[value] = value <= 384 ? 0 : value >= 894 ? 255 : static_cast<uint8_t>((value - 384) * 255 / 510);+ }+ uint64_t began = mach_absolute_time(), mark = began, now;+ auto lap = [&](uint64_t &total) {+ now = mach_absolute_time();+ uint64_t ns;+ absolutetime_to_nanoseconds(now - mark, &ns);+ total += ns;+ mark = now;+ };+ if (memory->prepare() != kIOReturnSuccess)+ return;+ const uint8_t *bytes = surfaceBytes(surface, memory);+ lap(fPrepareNs);+ if (!bytes) {+ memory->complete();+ return;+ }+ uint64_t lit = 0, raw = 0, center = 0;+ bool sample = !refresh; // bring-up: the first frames and every 50th are logged, the last one goes into the periodic report+ for (uint64_t y = 0; y < copyHeight; y++) {+ uint8_t *line = fScanout + y * fVideo.v_rowBytes;+ const uint8_t *source = bytes + base + y * rowBytes;+ if (format == kFormatBGRA) {+ memcpy(fLine, source, copyWidth * 4);+ lap(fReadNs);+ memcpy(line, fLine, copyWidth * 4);+ lap(fWriteNs);+ continue;+ }+ if (format == kFormatB3A8) { // blue in the low bits, as BGR10A2+ memcpy(fLine, source, copyWidth * 4);+ lap(fReadNs);+ for (uint64_t x = 0; x < copyWidth; x++) {+ uint32_t bgr = fLine[x];+ fLine[x] = 0xff000000u | fXr10ToByte[bgr >> 20 & 1023] << 16 | fXr10ToByte[bgr >> 10 & 1023] << 8 | fXr10ToByte[bgr & 1023];+ if (sample) {+ lit += (fLine[x] & 0xffffff) != 0;+ raw += bgr != 0;+ if (y == copyHeight / 2 && x == copyWidth / 2)+ center = bgr;+ }+ }+ lap(fConvertNs);+ memcpy(line, fLine, copyWidth * 4);+ lap(fWriteNs);+ continue;+ }+ memcpy(fRow, source, copyWidth * 8);+ lap(fReadNs);+ const uint64_t *pixels = reinterpret_cast<const uint64_t *>(fRow);+ for (uint64_t x = 0; x < copyWidth; x++) {+ uint64_t rgba = pixels[x];+ fLine[x] = 0xff000000u | fHalfToByte[rgba >> 2 & 0x3fff] << 16 | fHalfToByte[rgba >> 18 & 0x3fff] << 8 |+ fHalfToByte[rgba >> 34 & 0x3fff];+ if (sample) {+ lit += (fLine[x] & 0xffffff) != 0;+ raw += rgba != 0;+ if (y == copyHeight / 2 && x == copyWidth / 2)+ center = rgba;+ }+ }+ lap(fConvertNs);+ memcpy(line, fLine, copyWidth * 4);+ lap(fWriteNs);+ }+ memory->complete();+ uint64_t ns;+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &ns);+ fCopies++;+ fCopyNs += ns;+ if (ns > fCopyMaxNs)+ fCopyMaxNs = ns;+ if (refresh)+ return;+ fLastLit = lit;+ fLastCenter = center;+ if (format != kFormatBGRA && (fFrames <= 8 || fFrames % 50 == 0))+ IOLog("XnuDisplay: frame %llu: %llu pixels lit, %llu nonzero, centre %#llx\n", fFrames, lit, raw, center);+}++static bool appendNumber(OSDictionary *dictionary, const char *key, uint64_t value, unsigned bits = 32)+{+ OSNumber *number = OSNumber::withNumber(value, bits);+ bool done = number && dictionary->setObject(key, number);+ OSSafeReleaseNULL(number);+ return done;+}++static bool appendString(OSDictionary *dictionary, const char *key, const char *value)+{+ OSString *string = OSString::withCString(value);+ bool done = string && dictionary->setObject(key, string);+ OSSafeReleaseNULL(string);+ return done;+}++static bool appendDictionary(OSDictionary *dictionary, const char *key, OSDictionary *value)+{+ bool done = value && dictionary->setObject(key, value);+ OSSafeReleaseNULL(value);+ return done;+}++static OSDictionary *point(uint32_t x, uint32_t y)+{+ OSDictionary *dictionary = OSDictionary::withCapacity(3);+ if (dictionary && !(appendNumber(dictionary, "X", x) && appendNumber(dictionary, "Y", y)))+ OSSafeReleaseNULL(dictionary);+ return dictionary;+}++// AppleParavirtDisplay::createDisplayAttributes, with the display of the boot framebuffer: one timing (the GOP mode) with one+// 8-bit SDR color element. Chromaticities are sRGB's (16.16 fixed point, as the panel's EDID would give them).+bool XnuDisplay::createDisplayAttributes()+{+ uint32_t width = static_cast<uint32_t>(fVideo.v_width), height = static_cast<uint32_t>(fVideo.v_height);+ bool done = false;+ OSDictionary *attributes = OSDictionary::withCapacity(16), *product = OSDictionary::withCapacity(8);+ OSDictionary *chromaticity = OSDictionary::withCapacity(3), *whitePoint = point(20493, 21561);+ OSDictionary *transport = OSDictionary::withCapacity(2), *sourceLimits = OSDictionary::withCapacity(5);+ OSDictionary *scalingLimits = OSDictionary::withCapacity(2);+ OSArray *colors = OSArray::withCapacity(1), *timings = OSArray::withCapacity(1), *timingColors = OSArray::withCapacity(1);+ OSObject *color = ioavColorWithCapabilities(2, 8, 0, 0, 0, 16, false, nullptr, nullptr, nullptr, nullptr);+ // CVT reduced blanking as IOAVFamily's sCVTTimingData has it (1280x800@60: 1440x823, 71 MHz). Sync rates are 16.16 fixed point+ // (IOAVVideoTimingGetSyncRateRounded); the table leaves the horizontal one 0.+ uint8_t timingData[80] = {};+ uint32_t hTotal = width + 160, vTotal = height + 23;+ at<uint32_t>(timingData, 4) = hTotal;+ at<uint32_t>(timingData, 8) = width;+ at<uint32_t>(timingData, 12) = 32; // horizontal sync width, back porch, front porch+ at<uint32_t>(timingData, 16) = 80;+ at<uint32_t>(timingData, 20) = 48;+ at<uint32_t>(timingData, 28) = 1; // horizontal sync polarity (positive)+ at<uint32_t>(timingData, 36) = vTotal;+ at<uint32_t>(timingData, 40) = height;+ at<uint32_t>(timingData, 44) = 6; // vertical sync width, back porch, front porch+ at<uint32_t>(timingData, 48) = 14;+ at<uint32_t>(timingData, 52) = 3;+ at<uint32_t>(timingData, 56) = fRefreshHz << 16;+ at<uint32_t>(timingData, 68) = hTotal * vTotal * fRefreshHz; // pixel clock in Hz+ OSObject *timing = ioavTimingWithData(timingData, 2, 4);+ do {+ if (!attributes || !product || !chromaticity || !whitePoint || !transport || !sourceLimits || !scalingLimits || !colors ||+ !timings || !timingColors || !color || !timing)+ break;+ at<uint64_t>(color, kElementID) = kColorID;+ at<uint32_t>(color, kElementScore) = kColorID;+ at<uint64_t>(timing, kElementID) = kTimingID;+ at<uint32_t>(timing, kElementScore) = kTimingID;+ if (!colors->setObject(color) || !timingColors->setObject(color) || !timings->setObject(timing))+ break;+ ioavTimingSetColorElements(timing, timingColors);+ if (!(appendString(product, "ManufacturerID", "APP") && appendNumber(product, "ProductID", 0) &&+ appendNumber(product, "SerialNumber", 0) && appendString(product, "ProductName", "xnulinux Display") &&+ appendNumber(product, "WeekOfManufacture", 24) && appendNumber(product, "YearOfManufacture", 2021)))+ break;+ if (!(appendDictionary(chromaticity, "Red", point(41943, 21627)) && appendDictionary(chromaticity, "Green", point(19661, 39322)) &&+ appendDictionary(chromaticity, "Blue", point(9830, 3932))))+ break;+ if (!appendNumber(whitePoint, "Gamma", 144179)) // 2.2+ break;+ if (!(attributes->setObject("SupportsPQEOTF", kOSBooleanFalse) && attributes->setObject("ProductAttributes", product) &&+ attributes->setObject("Chromaticity", chromaticity) && attributes->setObject("DefaultColorSpaceIsSRGB", kOSBooleanFalse) &&+ attributes->setObject("DefaultWhitePoint", whitePoint) && attributes->setObject("SupportsStandby", kOSBooleanTrue) &&+ appendNumber(attributes, "ContinuousFrequencySupport", 3) &&+ appendNumber(attributes, "MaxHorizontalImageSize", (kWidthMM + 5) / 10) &&+ appendNumber(attributes, "MaxVerticalImageSize", (kHeightMM + 5) / 10) &&+ appendNumber(attributes, "NativeFormatHorizontalPixels", width) && appendNumber(attributes, "NativeFormatVerticalPixels", height) &&+ appendNumber(attributes, "PreciseAspectRatio", (static_cast<uint64_t>(width) << 16) / height)))+ break;+ if (!(appendString(transport, "Upstream", "Other") && appendString(transport, "Downstream", "Other")))+ break;+ if (!(appendNumber(sourceLimits, "MaxSrcBufferWidth", 16384) && appendNumber(sourceLimits, "MaxSrcBufferHeight", 16384) &&+ appendNumber(sourceLimits, "MaxSrcRectWidth", 8192) && appendNumber(sourceLimits, "MaxSrcRectTotal", 0) &&+ appendNumber(sourceLimits, "IOMFBMaxCompressedSizeInBytes", 0)))+ break;+ if (!(appendNumber(scalingLimits, "RGBLayer_MinScaleFraction", 4) && appendNumber(scalingLimits, "RGBLayer_MaxScale", 4)))+ break;+ setProperty("IOMFBUUID", "44726F69-6456-4D00-0000-000000000001");+ if (OSDictionary *prefs = OSDictionary::withCapacity(0)) { // paravirtualized for WindowServer (see the class registration)+ setProperty("ParavirtDisplayPrefs", prefs);+ prefs->release();+ }+ setProperty("external", true);+ setProperty("primary", 0ULL, 32); // AppleParavirtDisplay's display index+ done = setProperty("DisplayAttributes", attributes) && setProperty("Transport", transport) &&+ setProperty("ColorElements", colors) && setProperty("TimingElements", timings) &&+ setProperty("IOMFBMaxSrcPixels", sourceLimits) && setProperty("IOMFBScalingLimits", scalingLimits);+ } while (false);+ OSSafeReleaseNULL(attributes);+ OSSafeReleaseNULL(product);+ OSSafeReleaseNULL(chromaticity);+ OSSafeReleaseNULL(whitePoint);+ OSSafeReleaseNULL(transport);+ OSSafeReleaseNULL(sourceLimits);+ OSSafeReleaseNULL(scalingLimits);+ OSSafeReleaseNULL(colors);+ OSSafeReleaseNULL(timings);+ OSSafeReleaseNULL(timingColors);+ OSSafeReleaseNULL(color);+ OSSafeReleaseNULL(timing);+ if (!done || set_digital_out_mode(kColorID, kTimingID) != kIOReturnSuccess) {+ IOLog("XnuDisplay: createDisplayAttributes failed\n");+ return false;+ }+ return true;+}++// The mode of a color and a timing element (the IDs published above); AppleParavirtDisplay's block takes the timing's active size.+IOReturn XnuDisplay::set_digital_out_mode(unsigned int colorID, unsigned int timingID)+{+ if (colorID != kColorID || timingID != kTimingID)+ return kIOReturnBadArgument;+ at<uint32_t>(this, kDisplayWidth) = static_cast<uint32_t>(fVideo.v_width);+ at<uint32_t>(this, kDisplayHeight) = static_cast<uint32_t>(fVideo.v_height);+ setProperty("DisplayWidth", fVideo.v_width, 32);+ setProperty("DisplayHeight", fVideo.v_height, 32);+ setProperty("DPTimingModeId", timingID, 32);+ return kIOReturnSuccess;+}++// AppleParavirtDisplay: dots per inch from the physical width (IOMobileFramebufferLegacy's reads "dot-pitch" of the AppleARMIODevice).+IOReturn XnuDisplay::get_dot_pitch(unsigned int *pitch)+{+ *pitch = static_cast<unsigned int>(fVideo.v_width * 25.46 / kWidthMM + 0.5);+ return kIOReturnSuccess;+}++// AppleParavirtDisplay's hooks with nothing to do on a CPU-copied scanout: the swap and its layers need no mapping, there is no+// gamma or color hardware (the family's defaults are unsupported, AppleParavirtDisplay accepts them).+IOReturn XnuDisplay::verify_swap(IOMFBSwapIORequest *) // AppleParavirtDisplay returns 1 (IOMobileFramebufferLegacy: 0)+{+ if (!fSubmitted++)+ IOLog("XnuDisplay: first swap submitted\n");+ return 1;+}+IOReturn XnuDisplay::swap_layer_map(IOMFBSwapIORequest *, unsigned int) {return kIOReturnSuccess;}+IOReturn XnuDisplay::surface_layer_map(IOMFB::AP::DisplayedData *, unsigned int, IOSurface *) {return kIOReturnSuccess;}+IOReturn XnuDisplay::surface_layer_unmap(IOMFB::AP::DisplayedData *, unsigned int) {return kIOReturnSuccess;}+IOReturn XnuDisplay::set_display_device(unsigned int) {return kIOReturnSuccess;}+IOReturn XnuDisplay::get_gamma_table(IOMFBGammaTable *) {return kIOReturnUnsupported;}+IOReturn XnuDisplay::set_gamma_table(IOMFBGammaTable *) {return kIOReturnSuccess;}+IOReturn XnuDisplay::set_color_remap_mode(DisplayColorRemapMode mode)+{+ fColorRemapMode = mode;+ return kIOReturnSuccess;+}+IOReturn XnuDisplay::get_color_remap_mode(DisplayColorRemapMode *mode) const+{+ *mode = fColorRemapMode;+ return kIOReturnSuccess;+}+IOReturn XnuDisplay::swap_set_color_matrix(IOMFBColorFixedMatrix *, IOMFBColorMatrixFunction, unsigned int) {return kIOReturnSuccess;}++// The slots IOMobileFramebufferLegacy leaves pure, as AppleParavirtDisplay implements them.+IOReturn XnuDisplay::set_notify_tag_mask_gated(IOMFB_NotificationType type, IOMFBNotifyRequest *request, unsigned int mask)+{+ if (type != 3)+ return kIOReturnBadArgument;+ at<uint32_t>(request, 120) = mask;+ return kIOReturnSuccess;+}+IOReturn XnuDisplay::supported_frame_info(unsigned int, unsigned int *, char (*)[64], unsigned int *) {return kIOReturnUnsupported;}+IOReturn XnuDisplay::factory_portal(void *, task *) {return kIOReturnUnsupported;}+IOReturn XnuDisplay::executeFactoryConfigurations_gated() {return kIOReturnUnsupported;}+IOReturn XnuDisplay::set_frame_info_notification_state_gated(IOMFBNotifyRequest *, bool) {return kIOReturnSuccess;}++// AppleParavirtDisplay::notify_swap_done_gated: the family calls it as the current swap completes; the swap info goes to the+// clients (swap_info_notify_dispatch_gated, which calls do_swap_info_notify_gated per request) unless notifications are held.+IOReturn XnuDisplay::notify_swap_done_gated(unsigned int swapID, ::SwapInfoBlob *, unsigned int *, unsigned int)+{+ IOMFBSwapIORequest *swap = at<IOMFBSwapIORequest *>(this, kCurrentSwap);+ if (at<uint32_t>(swap, kSwapDropReasons))+ return kIOReturnUnsupported;+ SwapInfo *info = &fSwapInfo[fSwapInfoWrite];+ *info = {swapID, {at<uint64_t>(this, kSwapInfoTime), 0, at<uint64_t>(swap, kSwapInfoA), at<uint32_t>(swap, kSwapInfoB), 0}};+ if (at<uint16_t>(this, kSwapInfoHeld)) {+ fSwapInfoWrite = (fSwapInfoWrite + 1) % kSwapInfoRing;+ return kIOReturnSuccess;+ }+ for (; fSwapInfoRead != fSwapInfoWrite; fSwapInfoRead = (fSwapInfoRead + 1) % kSwapInfoRing)+ iomfbSwapInfoDispatch(this, &fSwapInfo[fSwapInfoRead]);+ iomfbSwapInfoDispatch(this, info);+ return kIOReturnSuccess;+}++// AppleParavirtDisplay::do_swap_info_notify_gated: the request's async result is the mask, the swap ID and the words it asks for.+IOReturn XnuDisplay::do_swap_info_notify_gated(IOMFBNotifyRequest *request, const SwapInfoBlob *blob)+{+ const SwapInfo *info = reinterpret_cast<const SwapInfo *>(blob);+ uint32_t mask = at<uint32_t>(request, kNotifyMask);+ io_user_reference_t args[12] = {mask, info->swapID};+ unsigned count = 2;+ for (unsigned word = 0; word < 5; word++) {+ if (!(mask >> word & 1))+ continue;+ uint64_t value = word == 1 ? info->words[0] - at<uint64_t>(request, kNotifyLastTime) : info->words[word];+ unsigned need = mask >> 31 ? 2 : 1;+ if (count + need > 12) {+ IOLog("IOMFB Packer put: ran out of space\n");+ continue;+ }+ if (need == 2) {+ args[count++] = static_cast<uint32_t>(value);+ args[count++] = value >> 32;+ } else {+ args[count++] = value;+ }+ }+ at<uint64_t>(request, kNotifyLastTime) = info->words[0];+ return userClientSendAsyncResult(&at<io_user_reference_t>(request, kNotifyAsyncReference), kIOReturnSuccess, args, count,+ kIOUserNotifyOptionCanDrop);+}+IOReturn XnuDisplay::notify_crc_ready_gated(unsigned int) {return kIOReturnSuccess;}+bool XnuDisplay::are_timings_enabled() const {return false;}++// Module start/stop for the collection's kext entry (as DroidVM's NativeKextGlue.cpp); the driver starts through IOKit matching.+#include <mach/kmod.h>+extern "C" {+kern_return_t native_kext_start(kmod_info_t *, void *) { return KERN_SUCCESS; }+kern_return_t native_kext_stop(kmod_info_t *, void *) { return KERN_SUCCESS; }+}diff --git a/kexts/XnuDisplay/XnuDisplay.json b/kexts/XnuDisplay/XnuDisplay.jsonnew file mode 100644index 0000000..c9fcb6f--- /dev/null+++ b/kexts/XnuDisplay/XnuDisplay.json@@ -0,0 +1,42 @@+{+ "name": "XnuDisplay",+ "bundle": "org.xnulinux.driver.XnuDisplay",+ "version": "1.0.0",+ "objects": "out/x12377/native-kexts/XnuDisplay/objects.json",+ "start": "_native_kext_start",+ "stop": "_native_kext_stop",+ "libraries": {+ "com.apple.iokit.IOAVFamily": "1.0.0",+ "com.apple.iokit.IOMobileGraphicsFamily": "1.0.0",+ "com.apple.iokit.IOSurface": "1.0",+ "com.apple.kpi.bsd": "18.0.0",+ "com.apple.kpi.iokit": "18.0.0",+ "com.apple.kpi.libkern": "18.0.0",+ "com.apple.kpi.mach": "18.0.0",+ "com.apple.kpi.private": "18.0.0",+ "com.apple.kpi.unsupported": "18.0.0"+ },+ "personalities": {+ "AppleParavirtGPU": {+ "CFBundleIdentifier": "org.xnulinux.driver.XnuDisplay",+ "IOClass": "AppleParavirtGPU",+ "IOProviderClass": "IOResources",+ "IOResourceMatch": "IOKit",+ "IOMatchCategory": "AppleParavirtGPU"+ },+ "XnuDisplay": {+ "CFBundleIdentifier": "org.xnulinux.driver.XnuDisplay",+ "IOClass": "AppleParavirtDisplay",+ "IOProviderClass": "AppleParavirtGPU"+ }+ },+ "vtable": {+ "class": "XnuDisplay",+ "base": "IOMobileFramebufferLegacy",+ "base_kext": "com.apple.iokit.IOMobileGraphicsFamily",+ "slots": 473,+ "ignore_slots": [+ 16+ ]+ }+}diff --git a/kexts/XnuEthernet/XnuEthernet.cpp b/kexts/XnuEthernet/XnuEthernet.cppnew file mode 100644index 0000000..252a6cf--- /dev/null+++ b/kexts/XnuEthernet/XnuEthernet.cpp@@ -0,0 +1,200 @@+// SPDX-License-Identifier: BSD-2-Clause-Patent+// XnuEthernet: en0 of the hosted macOS, an IOEthernetController whose frames go through the host. It follows DroidVMEthernet of+// Droid-VM/macOS-DroidVM (overlay/kext/DroidVMEthernet.cpp, BSD-2-Clause-Patent) without its virtio-net: the transport is the+// hosted kernel's (bsd/net/if_linux64.c, upcalls 816/817/815 to the Linux netdev xnu0, where Linux routes, NATs and answers DHCP).+//+// Why a driver and not only the kernel's own ifnet: IOTimeSyncClockManager takes the TimeSync clock identifier from a built-in+// IOEthernetInterface's MAC, once, at its start; without one it never registers, clocksyncd waits for it and WindowServer+// (QuartzCore's TimeSync clock) waits on clocksyncd. The collection gates IOTimeSyncRootService on the resource published here.+#include <IOKit/IOLib.h>+#include <IOKit/IOLocks.h>+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wdeprecated-anon-enum-enum-conversion" // the family's headers mix anonymous enums+#define __PRIVATE_SPI__ // the shipped family uses IONetworkController's reserved slots 2-5 (outputStart ... networkInterfaceNotification)+#include <IOKit/network/IOEthernetController.h>+#include <IOKit/network/IOEthernetInterface.h>+#include <IOKit/network/IONetworkMedium.h>+#include <IOKit/network/IOOutputQueue.h> // kIOReturnOutputSuccess, kIOReturnOutputDropped+#pragma clang diagnostic pop+#include <kern/thread.h>+#include <net/ethernet.h>++// bsd/net/if_linux64.c (the xnulinux kernel patch): one frame to the host, the next frame from it (bytes, 0 when none waits).+extern "C" long linux64_net_send(const void *frame, unsigned long length);+extern "C" long linux64_net_recv(void *buffer, unsigned long size);++namespace {+constexpr unsigned frameBytes = 1514; // a full ethernet frame without the FCS+constexpr unsigned fastPollMs = 1, idlePollMs = 10, fastPollTicks = 1000; // 1 ms polls for a second after any traffic+constexpr UInt64 linkSpeed = 1000 * 1000000ULL;+}++class XnuEthernet : public IOEthernetController {+ OSDeclareDefaultStructors(XnuEthernet)++ IOEthernetInterface *fInterface = nullptr;+ IOEthernetAddress fAddress = {{0x02, 0x58, 0x4e, 0x55, 0x00, 0x01}}; // locally administered, "XNU" (the kernel's en0 had it)+ IOLock *fTxLock = nullptr;+ uint8_t fTx[frameBytes + 64], fRx[frameBytes + 64];+ volatile bool fEnabled = false, fActive = false;+ UInt64 fRxPackets = 0, fTxPackets = 0, fRxDrops = 0, fTxDrops = 0;++ void pollReceive();+ static void pollThread(void *self, wait_result_t);++public:+ bool start(IOService *provider) override;+ void stop(IOService *provider) override;+ void free() override;+ IOReturn getHardwareAddress(IOEthernetAddress *address) override;+ IOReturn enable(IONetworkInterface *interface) override;+ IOReturn disable(IONetworkInterface *interface) override;+ // IOBSD is up (our IOResourceMatch); the family's wait for it from start() needs IOResources matched, which it is not while+ // IOResources' own matching starts us (DroidVMEthernet)+ UInt32 getFeatures() const override { return kIONetworkFeatureNoBSDWait; }+ UInt32 outputPacket(mbuf_t packet, void *param) override;+ IOReturn setPromiscuousMode(bool active) override { return kIOReturnSuccess; }+ IOReturn setMulticastMode(bool active) override { return kIOReturnSuccess; }+ IOReturn setMulticastList(IOEthernetAddress *addresses, UInt32 count) override { return kIOReturnSuccess; }+};++OSDefineMetaClassAndStructors(XnuEthernet, IOEthernetController)++bool XnuEthernet::start(IOService *provider)+{+ if (!IOEthernetController::start(provider))+ return false;+ fTxLock = IOLockAlloc();+ if (!fTxLock)+ return false;+ OSDictionary *media = OSDictionary::withCapacity(1);+ IONetworkMedium *medium = IONetworkMedium::medium(IOMediumType(kIOMediumEthernetAuto) | IOMediumType(kIOMediumOptionFullDuplex), linkSpeed);+ if (!media || !medium || !IONetworkMedium::addMedium(media, medium) || !publishMediumDictionary(media)) {+ OSSafeReleaseNULL(media);+ OSSafeReleaseNULL(medium);+ IOLog("XnuEthernet: cannot publish the medium\n");+ return false;+ }+ media->release();+ setSelectedMedium(medium);+ setLinkStatus(kIONetworkLinkValid | kIONetworkLinkActive, medium, linkSpeed);+ medium->release();+ if (!attachInterface(reinterpret_cast<IONetworkInterface **>(&fInterface), false)) {+ IOLog("XnuEthernet: cannot attach the interface\n");+ return false;+ }+ // IOTimeSyncClockManager takes the clock identifier from the built-in interfaces only and looks once, at its start+ fInterface->setProperty(kIOBuiltin, true);+ fInterface->registerService(kIOServiceSynchronous);+ publishResource("XnuEthernet");+ thread_t thread;+ if (kernel_thread_start(pollThread, this, &thread) == KERN_SUCCESS)+ thread_deallocate(thread);+ const uint8_t *m = fAddress.bytes;+ IOLog("XnuEthernet: en0 through the host's xnu0, MAC %02x:%02x:%02x:%02x:%02x:%02x\n", m[0], m[1], m[2], m[3], m[4], m[5]);+ return true;+}++void XnuEthernet::stop(IOService *provider)+{+ if (fInterface) {+ detachInterface(fInterface);+ OSSafeReleaseNULL(fInterface);+ }+ IOEthernetController::stop(provider);+}++void XnuEthernet::free()+{+ if (fTxLock)+ IOLockFree(fTxLock);+ fTxLock = nullptr;+ IOEthernetController::free();+}++IOReturn XnuEthernet::getHardwareAddress(IOEthernetAddress *address)+{+ *address = fAddress;+ return kIOReturnSuccess;+}++IOReturn XnuEthernet::enable(IONetworkInterface *interface)+{+ fEnabled = true;+ return kIOReturnSuccess;+}++IOReturn XnuEthernet::disable(IONetworkInterface *interface)+{+ fEnabled = false;+ return kIOReturnSuccess;+}++// No output queue: the interface calls in from the stack's threads, so the one transmit buffer is taken under a lock.+UInt32 XnuEthernet::outputPacket(mbuf_t packet, void *param)+{+ size_t length = mbuf_pkthdr_len(packet);+ if (!fEnabled || length < ETHER_HDR_LEN || length > frameBytes) {+ ++fTxDrops;+ freePacket(packet);+ return kIOReturnOutputDropped;+ }+ IOLockLock(fTxLock);+ long sent = mbuf_copydata(packet, 0, length, fTx) == 0 ? linux64_net_send(fTx, length) : 0;+ IOLockUnlock(fTxLock);+ freePacket(packet);+ if (sent <= 0) {+ ++fTxDrops;+ return kIOReturnOutputDropped;+ }+ ++fTxPackets;+ fActive = true;+ return kIOReturnOutputSuccess;+}++// Takes every frame the host has queued and hands it to the interface. One thread only, so the interface's inputPacket calls are+// serialized as the family requires. The host's xnu0 delivers only what Linux routes to this guest: no filter here.+void XnuEthernet::pollReceive()+{+ for (unsigned n = 0; n < 256; n++) {+ long length = linux64_net_recv(fRx, sizeof(fRx));+ if (length < ETHER_HDR_LEN)+ return;+ mbuf_t packet = nullptr;+ int copied = -1;+ if (fEnabled && fInterface && length <= frameBytes && (packet = allocatePacket(static_cast<UInt32>(length))) &&+ (copied = mbuf_copyback(packet, 0, static_cast<size_t>(length), fRx, MBUF_DONTWAIT)) == 0) {+ fInterface->inputPacket(packet, static_cast<UInt32>(length));+ ++fRxPackets;+ } else {+ if (packet)+ freePacket(packet);+ if (++fRxDrops <= 3 && fEnabled) // frames before the interface is enabled (boot) are dropped as expected+ IOLog("XnuEthernet: frame of %ld bytes dropped (packet %p, copyback %d)\n", length, packet, copied);+ }+ fActive = true;+ }+}++// 1 ms polls for a second after traffic, 10 ms otherwise (as DroidVMEthernet).+void XnuEthernet::pollThread(void *self, wait_result_t)+{+ XnuEthernet *ethernet = static_cast<XnuEthernet *>(self);+ for (unsigned quiet = fastPollTicks;;) {+ ethernet->pollReceive();+ if (ethernet->fActive) {+ ethernet->fActive = false;+ quiet = 0;+ } else if (quiet < fastPollTicks) {+ ++quiet;+ }+ IOSleep(quiet < fastPollTicks ? fastPollMs : idlePollMs);+ }+}++// Module start/stop for the collection's kext entry; the driver starts through IOKit matching.+#include <mach/kmod.h>+extern "C" {+kern_return_t native_kext_start(kmod_info_t *, void *) { return KERN_SUCCESS; }+kern_return_t native_kext_stop(kmod_info_t *, void *) { return KERN_SUCCESS; }+}diff --git a/kexts/XnuEthernet/XnuEthernet.json b/kexts/XnuEthernet/XnuEthernet.jsonnew file mode 100644index 0000000..0d0db92--- /dev/null+++ b/kexts/XnuEthernet/XnuEthernet.json@@ -0,0 +1,41 @@+{+ "name": "XnuEthernet",+ "bundle": "org.xnulinux.driver.XnuEthernet",+ "version": "1.0.0",+ "objects": "out/x12377/native-kexts/XnuEthernet/objects.json",+ "start": "_native_kext_start",+ "stop": "_native_kext_stop",+ "libraries": {+ "com.apple.iokit.IONetworkingFamily": "1.0.0b1",+ "com.apple.kpi.bsd": "18.0.0",+ "com.apple.kpi.iokit": "18.0.0",+ "com.apple.kpi.libkern": "18.0.0",+ "com.apple.kpi.mach": "18.0.0",+ "com.apple.kpi.unsupported": "18.0.0"+ },+ "personalities": {+ "XnuEthernet": {+ "CFBundleIdentifier": "org.xnulinux.driver.XnuEthernet",+ "IOClass": "XnuEthernet",+ "IOProviderClass": "IOResources",+ "IOResourceMatch": "IOBSD",+ "IOMatchCategory": "XnuEthernet"+ }+ },+ "patch_personalities": {+ "com.apple.iokit.IOTimeSyncFamily": {+ "IOTimeSyncRootService": {+ "IOResourceMatch": "XnuEthernet"+ }+ }+ },+ "vtable": {+ "class": "XnuEthernet",+ "base": "IOEthernetController",+ "base_kext": "com.apple.iokit.IONetworkingFamily",+ "slots": 400,+ "ignore_slots": [+ 16+ ]+ }+}diff --git a/scripts/vm-m2-kbisect.sh b/scripts/vm-m2-kbisect.shindex c92bcfd..c310e5d 100755--- a/scripts/vm-m2-kbisect.sh+++ b/scripts/vm-m2-kbisect.sh@@ -13,10 +13,11 @@ if [ -n "$HOSTDISK" ] && [ "${HOSTDISK#/dev/}" = "$HOSTDISK" ]; thenfi# XNU's DRAM is one physically contiguous block (GBs): free the page cache and compact first, or the allocation failssync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /proc/sys/vm/compact_memory >/dev/null+[ -n "${FB_DUMP:-}" ] && { : > "$FB_DUMP"; } # xnu.ko writes the framebuffer into this existing filefor K in "$@"; dosudo dmesg -Cecho ">>> kmax=$K"; sync- sudo insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=$K idle_max=${IDLE_MAX:-200} ram_mb=${RAM_MB:-128} ${IMAGE:+image=$IMAGE} ${RAMDISK:+ramdisk=$RAMDISK} ${TRUSTCACHE:+trustcache=$TRUSTCACHE} ${HOSTDISK:+hostdisk=$HOSTDISK hostdisk_rw=1} ${CONSOLE_IN:+console_in=$CONSOLE_IN} ${BOOTARGS:+bootargs=\"$BOOTARGS\"}+ sudo insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=$K idle_max=${IDLE_MAX:-200} ram_mb=${RAM_MB:-128} ${IMAGE:+image=$IMAGE} ${RAMDISK:+ramdisk=$RAMDISK} ${TRUSTCACHE:+trustcache=$TRUSTCACHE} ${HOSTDISK:+hostdisk=$HOSTDISK hostdisk_rw=1} ${CONSOLE_IN:+console_in=$CONSOLE_IN} ${FB_DUMP:+fb_dump=$FB_DUMP} ${BOOTARGS:+bootargs=\"$BOOTARGS\"}echo "lines: $(sudo dmesg | grep -ac 'xnu\]')"sudo dmesg | grep -a "xnu\]\|XNU stage 4\|budget\|panic\|run ended" | tail -${SHOW:-4}sudo rmmod xnudiff --git a/scripts/vm-sysdisk-launchd.sh b/scripts/vm-sysdisk-launchd.shindex fa0301e..0590d60 100755--- a/scripts/vm-sysdisk-launchd.sh+++ b/scripts/vm-sysdisk-launchd.sh@@ -20,11 +20,12 @@ if [ "${MODE:-launchd}" = launchd ]; then[ -e /mnt/sys/private/var/select/sh ] || sudo ln -s /bin/bash /mnt/sys/private/var/select/sh[ -e /mnt/sys/private/var/select/developer_dir ] || sudo ln -s /Applications/Xcode.app/Contents/Developer /mnt/sys/private/var/select/developer_dir# no third-party software of the host (its own /Library/LaunchDaemons, /usr/local); GUI and hardware-only- # daemons (no display, no watchdog hardware) are parked in /private/var/xnulinux-parked (DISABLE adds more)+ # daemons (no watchdog hardware; loginwindow until the graphical session works) are parked in /private/var/xnulinux-parked+ # (DISABLE adds more). WindowServer stays: it drives XnuDisplay (kexts/XnuDisplay).sudo rm -rf /mnt/sys/usr/localsudo find /mnt/sys/Library/LaunchDaemons /mnt/sys/Library/LaunchAgents -name '*.plist' ! -name 'com.apple.*' -delete 2>/dev/null || truesudo mkdir -p /mnt/sys/private/var/xnulinux-parked- for d in com.apple.loginwindow com.apple.WindowServer com.apple.watchdogd com.apple.iomfb_bics_daemon com.apple.audiomxd com.apple.audio.coreaudiod com.apple.PerfPowerServices com.apple.PerfPowerServicesExtended ${DISABLE:-}; do+ for d in com.apple.loginwindow com.apple.watchdogd com.apple.iomfb_bics_daemon com.apple.audiomxd com.apple.audio.coreaudiod com.apple.PerfPowerServices com.apple.PerfPowerServicesExtended ${DISABLE:-}; do[ -e /mnt/sys/System/Library/LaunchDaemons/$d.plist ] && sudo mv /mnt/sys/System/Library/LaunchDaemons/$d.plist /mnt/sys/private/var/xnulinux-parked/doneelsediff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.shindex 1208666..d4b38d7 100755--- a/scripts/vm-xnu-rebuild.sh+++ b/scripts/vm-xnu-rebuild.sh@@ -22,10 +22,16 @@ if [ -e out/kc/kc27.bin ]; thenfi# xnulinux's own kexts (kexts/*/NAME.json + NAME.cpp), built against the k27 kernel's objects and linked into the collectionNATIVE=+ # IONetworkingFamily's kernel headers (IOKit/network/*.h) for XnuEthernet: Apple's open source IONetworkingFamily-188 (APSL,+ # fetched here, not kept in the repository), whose __PRIVATE_SPI__ declarations name the reserved slots 2-5 the shipped family+ # uses (the SDK's headers leave slot 5 a reserved stub the collection does not export)+ NETINC=~/w/poc/build/netinc; NETSRC=~/w/poc/build/IONetworkingFamily-188; mkdir -p $NETINC/IOKit+ [ -e $NETSRC/IOEthernetController.h ] || git clone -q --depth 1 --branch IONetworkingFamily-188 https://github.com/apple-oss-distributions/IONetworkingFamily.git $NETSRC+ ln -sfn $NETSRC $NETINC/IOKit/networkfor j in ~/w/poc/kexts/*/*.json; do[ -e "$j" ] || continuen=$(basename $j .json)- python3 scripts/build-native-kext.py $n $(dirname $j)/$n.cpp --obj ${KEXT_OBJ:-k27-obj}+ python3 scripts/build-native-kext.py $n $(dirname $j)/$n.cpp -I $NETINC --obj ${KEXT_OBJ:-k27-obj}NATIVE="$NATIVE $j"doneK27_NO_BOOT=1 NATIVE="$NATIVE" bash k27/try.sh 0 2>&1 | tail -3diff --git a/tools/hosted/fb2png.py b/tools/hosted/fb2png.pynew file mode 100644index 0000000..ad261a7--- /dev/null+++ b/tools/hosted/fb2png.py@@ -0,0 +1,23 @@+#!/usr/bin/env python3+"""Convert the hosted macOS's framebuffer dump (xnu.ko fb_dump: raw 32-bit BGRA rows) to a PNG.++ fb2png.py DUMP WIDTH HEIGHT OUT.png+"""+import struct, sys, zlib++src, w, h, out = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]+d = open(src, 'rb').read()+if len(d) < w * h * 4:+ sys.exit(f'{src}: {len(d)} bytes, expected {w * h * 4}')+rows = bytearray()+for y in range(h):+ row = d[y * w * 4:(y + 1) * w * 4]+ rgb = bytearray(w * 3)+ rgb[0::3] = row[2::4] # R+ rgb[1::3] = row[1::4] # G+ rgb[2::3] = row[0::4] # B+ rows += b'\0' + rgb+def chunk(t, b):+ return struct.pack('>I', len(b)) + t + b + struct.pack('>I', zlib.crc32(t + b) & 0xffffffff)+png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(bytes(rows), 6)) + chunk(b'IEND', b'')+open(out, 'wb').write(png)diff --git a/tools/hosted/net-up.sh b/tools/hosted/net-up.shindex ac92efd..0e59626 100644--- a/tools/hosted/net-up.sh+++ b/tools/hosted/net-up.sh@@ -1,7 +1,15 @@#!/bin/sh# In the hosted macOS, at boot (launchd job xnulinux.network): en0 is XNU's link to the host's xnu0 (bsd/net/if_linux64.c).-# configd's IPConfiguration does not manage it (no IOKit interface behind it), so configure it here: address, default+# Without an IOKit interface behind it configd's IPConfiguration does not manage it, so configure it here: address, default# route, and the DNS/IPv4 state mDNSResponder resolves through (it does not read /etc/resolv.conf).+# With XnuEthernet (kexts/XnuEthernet, the default) en0 is an IOKit interface: configd's IPConfiguration runs DHCP on it+# (the host's dnsmasq answers) and sets the route and DNS itself, so there is nothing to do here. The static set-up below is+# for the kernel's own ifnet (boot-arg linux64-ifnet=1).+for i in $(seq 1 30); do ifconfig en0 >/dev/null 2>&1 && break; sleep 1; done+if ioreg -r -c XnuEthernet -d 1 2>/dev/null | grep -q XnuEthernet; then+ echo "xnulinux: en0 is XnuEthernet; configd configures it (DHCP)" > /dev/console+ exit 0+fiADDR=192.168.77.2 GW=192.168.77.1 DNS=192.168.77.1for i in $(seq 1 60); do ifconfig en0 >/dev/null 2>&1 && scutil -r $GW >/dev/null 2>&1 && break; sleep 1; doneifconfig en0 inet $ADDR netmask 255.255.255.0 updiff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.cindex 45f5ac1..f24febb 100644--- a/xnu-ko/xnu_main.c+++ b/xnu-ko/xnu_main.c@@ -66,7 +66,21 @@ static char *trustcache;module_param(trustcache, charp, 0444);static const void *tc_data; static unsigned long tc_size; static void *tc_blob;#define TC_SEG_SIZE (tc_size ? tc_size + 8 : 0) /* trust_cache_offsets_t { num_caches = 1, offsets[1] } + the module */-#define BOOT_EXTRA (((rd_size + 0x3fff) & ~0x3fffULL) + ((TC_SEG_SIZE + 0x3fff) & ~0x3fffULL))+/*+ * The display's framebuffer (boot_args Video, 32 bpp): reserved in the boot data like the RAM disk, so XNU never hands its pages+ * out; XnuDisplay (kexts/XnuDisplay) copies each frame WindowServer swaps into it. fb_width=0 boots without one. A host thread+ * writes it to fb_dump (raw BGRA, fb_width x fb_height) every fb_dump_ms milliseconds when both are set.+ */+static int fb_width = 1280, fb_height = 800;+module_param(fb_width, int, 0444);+module_param(fb_height, int, 0444);+static char *fb_dump;+module_param(fb_dump, charp, 0444);+static int fb_dump_ms = 1000;+module_param(fb_dump_ms, int, 0444);+static u64_t fb_off; /* the framebuffer's offset in the contiguous region (its Linux address: img.region.va + fb_off) */+#define FB_SIZE (fb_width > 0 && fb_height > 0 ? (u64_t)fb_width * fb_height * 4 : 0)+#define BOOT_EXTRA (((rd_size + 0x3fff) & ~0x3fffULL) + ((TC_SEG_SIZE + 0x3fff) & ~0x3fffULL) + ((FB_SIZE + 0x3fff) & ~0x3fffULL))/* A root disk backed by a host file (an HFS+ image): XNU's memdev md0 in host mode, stages 995 (size) and 994 (I/O). */static char *hostdisk;static int hostdisk_rw;@@ -537,6 +551,7 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_tadt_prop_u32(&a, "mix-n-match-prevention-status", 0);u64_t off_rd = (off_dt + 0x40000 + 0x3fff) & ~0x3fffULL; /* the RAM disk, after the ADT's room */u64_t off_tc = (off_rd + rd_size + 0x3fff) & ~0x3fffULL; /* the trust cache segment, after the RAM disk */+ u64_t off_fb = (off_tc + TC_SEG_SIZE + 0x3fff) & ~0x3fffULL; /* the framebuffer, after the trust cache */adt_node(&a, 1 + (rd_size ? 1 : 0) + (tc_size ? 1 : 0), 0); /* /chosen/memory-map (no AuxKC) */adt_prop_str(&a, "name", "memory-map");if (rd_size) {@@ -571,10 +586,21 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_tadt_prop_str(&a, "name", "product");adt_node(&a, 1, 0); /* /options: NVRAM's node (AppleImage4 keeps its nonce seeds there) */adt_prop_str(&a, "name", "options");- adt_node(&a, 3, 0); /* /arm-io: no devices; XNU needs a nonzero SoC base */+ adt_node(&a, 3, FB_SIZE ? 1 : 0); /* /arm-io: XNU needs a nonzero SoC base */adt_prop_str(&a, "name", "arm-io");adt_prop_str(&a, "device_type", "linux64-io");{ u64_t ranges[3] = { 0, 0x7000000000ULL, 0x10000000ULL }; adt_prop(&a, "ranges", ranges, sizeof(ranges)); }+ if (FB_SIZE) {+ /*+ * /arm-io/gpu, compatible "paravirtualizedgraphics,gpu" as on Apple's VM: IOMobileFramebuffer.framework then waits+ * for the framebuffers of the AppleParavirtGPU services (XnuDisplay; it matches IOResources, not this node, which+ * no driver claims: /arm-io's device_type keeps Apple's ARM IO driver off). Without the node WindowServer counted+ * no framebuffer and ran headless.+ */+ adt_node(&a, 2, 0);+ adt_prop_str(&a, "name", "gpu");+ adt_prop_str(&a, "compatible", "paravirtualizedgraphics,gpu");+ }if (a.err) { logs("xnu: ADT overflow"); return 0; }u64_t dt_len = adt_size(&a);@@ -596,6 +622,20 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_tba->topOfKernelData = phys + ((off_tc + TC_SEG_SIZE + 0x3fff) & ~0x3fffULL);logkv("xnu: static trust cache bytes", tc_size);}+ if (FB_SIZE) {+ unsigned int *px = (unsigned int *)(base_va + off_fb);+ for (u64_t i = 0; i < FB_SIZE / 4; i++)+ px[i] = 0xff000000; /* opaque black until the first frame */+ ba->Video.v_baseAddr = phys + off_fb;+ ba->Video.v_display = 0; /* no boot console drawn into it (the console is the serial line) */+ ba->Video.v_rowBytes = (u64_t)fb_width * 4;+ ba->Video.v_width = (u64_t)fb_width;+ ba->Video.v_height = (u64_t)fb_height;+ ba->Video.v_depth = 32;+ ba->topOfKernelData = phys + ((off_fb + FB_SIZE + 0x3fff) & ~0x3fffULL);+ fb_off = off_fb;+ logkv("xnu: framebuffer bytes", FB_SIZE);+ }ba->deviceTreeP = base_va + off_dt;ba->deviceTreeLength = (unsigned)dt_len;x_memcpy(ba->CommandLine, cmdline, x_strlen(cmdline) + 1);@@ -677,6 +717,21 @@ static int monitor_fn(void *arg)return 0;}+/* The framebuffer to fb_dump every fb_dump_ms (a host thread: plain Linux context, XNU keeps running on its CPU). */+static void *fb_thread;+static int fb_fn(void *arg)+{+ void *f = fki_file_open(fb_dump, 1, 0);+ (void)arg;+ if (!f) { logs("xnu: cannot open fb_dump (create the file first)"); return 0; }+ while (!fki_thread_should_stop()) {+ fki_msleep(fb_dump_ms);+ fki_file_pwrite(f, (unsigned char *)img.region.va + fb_off, FB_SIZE, 0);+ }+ fki_file_close(f);+ return 0;+}+static int enter_arm_init(struct boot_args_v2 *ba){if (img.filetype == MH_FILESET) {@@ -707,6 +762,8 @@ static int enter_arm_init(struct boot_args_v2 *ba)xnu_dbg = (const unsigned long *)macho_sym(&img, "_linux64_dbg");if (xnu_dbg && monitor_cpu >= 0)monitor = fki_thread_start(monitor_fn, 0, monitor_cpu, "xnu-monitor");+ if (fb_off && fb_dump && fb_dump_ms > 0 && img.region.va)+ fb_thread = fki_thread_start(fb_fn, 0, monitor_cpu >= 0 ? monitor_cpu : 1, "xnu-fb");xnu_kfault = (void *)macho_sym(&img, "_linux64_kernel_fault");xnu_kfault_recover = (void *)macho_sym(&img, "_linux64_kernel_fault_recover");if (xnu_kfault && fki_fault_register(0xffffffe000000000ULL, 0xfffffffc00000000ULL, xnu_fault) == 0)@@ -736,6 +793,8 @@ static int enter_arm_init(struct boot_args_v2 *ba)logkv("xnu: kernel faults forwarded to XNU", kfaults);fki_thread_stop(monitor);monitor = 0;+ fki_thread_stop(fb_thread);+ fb_thread = 0;logkv(r ? "xnu: run ended by stage hook, r =" : "xnu: arm_init returned (unexpected), r =", (u64_t)r);return 0;}diff --git a/xnu-patches/0001-linux64-stage-hook.patch b/xnu-patches/0001-linux64-stage-hook.patchindex 5aade57..ee41ac8 100644--- a/xnu-patches/0001-linux64-stage-hook.patch+++ b/xnu-patches/0001-linux64-stage-hook.patch@@ -732,10 +732,10 @@ index c08a74c..1e26f75 100644355 AUE_NULL ALL { int nosys(void); } { old getaudit }diff --git a/bsd/net/if_linux64.c b/bsd/net/if_linux64.cnew file mode 100644-index 0000000..1f459b3+index 0000000..55fe82d--- /dev/null+++ b/bsd/net/if_linux64.c-@@ -0,0 +1,202 @@+@@ -0,0 +1,239 @@+/*+ * LINUX64 (xnulinux): the hosted kernel's Ethernet interface en0.+ *@@ -758,6 +758,7 @@ index 0000000..1f459b3+#include <kern/thread.h>+#include <kern/locks.h>+#include <kern/sched_prim.h>++#include <pexpert/pexpert.h>++extern uintptr_t linux64_hook;+extern void linux64_stage_arg(unsigned long, unsigned long);@@ -869,6 +870,37 @@ index 0000000..1f459b3+ }+}+++/*++ * The transport for the IOKit driver (kexts/XnuEthernet), which is en0 normally: an IOEthernetInterface is what IOTimeSync takes++ * its clock identifier from (WindowServer waits on it). One frame to the host (its length when sent, 0 when not), and the next++ * frame from it (its length, 0 when none waits).++ */++long linux64_net_send(const void *frame, unsigned long length);++long++linux64_net_send(const void *frame, unsigned long length)++{++ struct linux64_net_req q = { .buf = (void *)(uintptr_t)frame, .len = length, .result = 0 };++++ if (linux64_hook == 0 || length < ETHER_HDR_LEN || length > L64_FRAME_MAX) {++ return 0;++ }++ linux64_stage_arg(816, (unsigned long)&q);++ return q.result > 0 ? (long)length : 0;++}++++long linux64_net_recv(void *buffer, unsigned long size);++long++linux64_net_recv(void *buffer, unsigned long size)++{++ struct linux64_net_req q = { .buf = buffer, .len = size, .result = 0 };++++ if (linux64_hook == 0) {++ return 0;++ }++ linux64_stage_arg(817, (unsigned long)&q);++ return q.result > 0 ? q.result : 0;++}+++/* From the hosted idle loop, after the host let it sleep: wake the receive thread when Linux queued frames. */+void linux64_net_idle_poll(void);+void@@ -897,6 +929,11 @@ index 0000000..1f459b3+ if (linux64_hook == 0) {+ return;+ }++ /* the kernel's own en0 only on request (boot-arg linux64-ifnet=1): XnuEthernet is en0 otherwise */++ int own = 0;++ if (!PE_parse_boot_argn("linux64-ifnet", &own, sizeof(own)) || !own) {++ return;++ }+ init.ver = IFNET_INIT_CURRENT_VERSION;+ init.len = sizeof(init);+ init.flags = IFNET_INIT_LEGACY | IFNET_INIT_NX_NOAUTO;diff --git a/xnu-patches/kc-keep-extra.txt b/xnu-patches/kc-keep-extra.txtindex 3116a78..5e85c11 100644--- a/xnu-patches/kc-keep-extra.txt+++ b/xnu-patches/kc-keep-extra.txt@@ -2,3 +2,5 @@com.apple.iokit.IOSurfacecom.apple.iokit.IOGraphicsFamilycom.apple.filesystems.lifs+com.apple.iokit.IOMobileGraphicsFamily+com.apple.iokit.IOAVFamily