[
  {
    "path": ".gitignore",
    "content": "# Xcode\n#\n# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore\n\n## Build generated\nbuild/\nBuild/\nDerivedData/\n\n## Various settings\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata/\n\n## Other\n*.moved-aside\n*.xccheckout\n*.xcscmblueprint\n\n.DS_Store\nDependencies/*.kext\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"MacKernelSDK\"]\n\tpath = MacKernelSDK\n\turl = https://github.com/acidanthera/MacKernelSDK\n[submodule \"Dependencies/VoodooGPIO\"]\n\tpath = Dependencies/VoodooGPIO\n\turl = https://github.com/Xiashangning/VoodooGPIO.git\n[submodule \"Dependencies/VoodooSerial\"]\n\tpath = Dependencies/VoodooSerial\n\turl = https://github.com/Xiashangning/VoodooSerial.git\n[submodule \"Dependencies/VoodooInput\"]\n\tpath = Dependencies/VoodooInput\n\turl = https://github.com/Xiashangning/VoodooInput.git\n[submodule \"Dependencies/BigSurfaceHIDDriver\"]\n\tpath = Dependencies/BigSurfaceHIDDriver\n\turl = https://github.com/Xiashangning/BigSurfaceHIDDriver.git\n"
  },
  {
    "path": "BigSurface/BigSurface/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>$(DEVELOPMENT_LANGUAGE)</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>$(MARKETING_VERSION)</string>\n\t<key>CFBundleVersion</key>\n\t<string>$(CURRENT_PROJECT_VERSION)</string>\n\t<key>IOKitPersonalities</key>\n\t<dict>\n\t\t<key>Surface Ambient Light Sensor</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIdentifier</key>\n\t\t\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t\t\t<key>IOClass</key>\n\t\t\t<string>SurfaceAmbientLightSensorDriver</string>\n\t\t\t<key>IOProbeScore</key>\n\t\t\t<integer>400</integer>\n\t\t\t<key>IOPropertyMatch</key>\n\t\t\t<dict>\n\t\t\t\t<key>name</key>\n\t\t\t\t<string>MSHW0184</string>\n\t\t\t</dict>\n\t\t\t<key>IOProviderClass</key>\n\t\t\t<string>VoodooI2CDeviceNub</string>\n\t\t</dict>\n\t\t<key>Surface Battery</key>\n\t\t<dict>\n\t\t\t<key>BatteryCount</key>\n\t\t\t<integer>1</integer>\n\t\t\t<key>CFBundleIdentifier</key>\n\t\t\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t\t\t<key>IOClass</key>\n\t\t\t<string>SurfaceBatteryDriver</string>\n\t\t\t<key>IOProviderClass</key>\n\t\t\t<string>SurfaceBatteryNub</string>\n\t\t\t<key>PerformanceMode</key>\n\t\t\t<integer>1</integer>\n\t\t</dict>\n\t\t<key>Surface Battery SMBus Controller</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIdentifier</key>\n\t\t\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t\t\t<key>IOClass</key>\n\t\t\t<string>SurfaceSMBusController</string>\n\t\t\t<key>IOProviderClass</key>\n\t\t\t<string>SurfaceBatteryDriver</string>\n\t\t</dict>\n\t\t<key>Surface Button</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIdentifier</key>\n\t\t\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t\t\t<key>IOClass</key>\n\t\t\t<string>SurfaceButtonDriver</string>\n\t\t\t<key>IONameMatch</key>\n\t\t\t<string>MSHW0040</string>\n\t\t\t<key>IOProbeScore</key>\n\t\t\t<integer>400</integer>\n\t\t\t<key>IOProviderClass</key>\n\t\t\t<string>IOACPIPlatformDevice</string>\n\t\t</dict>\n\t\t<key>Surface Management Engine</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIdentifier</key>\n\t\t\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t\t\t<key>IOClass</key>\n\t\t\t<string>SurfaceManagementEngineDriver</string>\n\t\t\t<key>IOPCIMatch</key>\n\t\t\t<string>0x34e48086 0x9d3e8086</string>\n\t\t\t<key>IOProbeScore</key>\n\t\t\t<integer>400</integer>\n\t\t\t<key>IOProviderClass</key>\n\t\t\t<string>IOPCIDevice</string>\n\t\t</dict>\n\t\t<key>Surface Serial Hub</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIdentifier</key>\n\t\t\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t\t\t<key>IOClass</key>\n\t\t\t<string>SurfaceSerialHubDriver</string>\n\t\t\t<key>IONameMatch</key>\n\t\t\t<string>MSHW0084</string>\n\t\t\t<key>IOProbeScore</key>\n\t\t\t<integer>600</integer>\n\t\t\t<key>IOProviderClass</key>\n\t\t\t<string>IOACPIPlatformDevice</string>\n\t\t</dict>\n\t</dict>\n\t<key>NSHumanReadableCopyright</key>\n\t<string>Copyright © 2021 Xia Shangning. All rights reserved.</string>\n\t<key>OSBundleCompatibleVersion</key>\n\t<string>1.0.0</string>\n\t<key>OSBundleLibraries</key>\n\t<dict>\n\t\t<key>as.vit9696.Lilu</key>\n\t\t<string>1.2.0</string>\n\t\t<key>as.vit9696.VirtualSMC</key>\n\t\t<string>1.2.0</string>\n\t\t<key>com.apple.iokit.IOACPIFamily</key>\n\t\t<string>1.4</string>\n\t\t<key>com.apple.iokit.IOHIDFamily</key>\n\t\t<string>2.0</string>\n\t\t<key>com.apple.iokit.IOPCIFamily</key>\n\t\t<string>2.9</string>\n\t\t<key>com.apple.iokit.IOSMBusFamily</key>\n\t\t<string>1.0.0</string>\n\t\t<key>com.apple.kpi.bsd</key>\n\t\t<string>16.7</string>\n\t\t<key>com.apple.kpi.iokit</key>\n\t\t<string>16.7</string>\n\t\t<key>com.apple.kpi.libkern</key>\n\t\t<string>16.7</string>\n\t\t<key>com.apple.kpi.mach</key>\n\t\t<string>16.7</string>\n\t\t<key>com.xavier.VoodooSerial</key>\n\t\t<string>1.2</string>\n\t\t<key>org.coolstar.VoodooGPIO</key>\n\t\t<string>1.2</string>\n\t</dict>\n\t<key>OSBundleRequired</key>\n\t<string>Root</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/APDS9960Constants.h",
    "content": "//\n//  APDS9960Constants.h\n//  SurfaceAmbientLightSensor\n//\n//  Created by Xavier on 2021/10/27.\n//  Copyright © 2021 Xia Shangning. All rights reserved.\n//\n\n#ifndef APDS9960Constants_h\n#define APDS9960Constants_h\n\nenum {\n  GESTURE_NONE = -1,\n  GESTURE_UP = 0,\n  GESTURE_DOWN = 1,\n  GESTURE_LEFT = 2,\n  GESTURE_RIGHT = 3\n};\n\n/* APDS-9960 register addresses */\n#define APDS9960_ENABLE         0x80\n#define APDS9960_ATIME          0x81\n#define APDS9960_WTIME          0x83\n#define APDS9960_AILTL          0x84\n#define APDS9960_AILTH          0x85\n#define APDS9960_AIHTL          0x86\n#define APDS9960_AIHTH          0x87\n#define APDS9960_PILT           0x89\n#define APDS9960_PIHT           0x8B\n#define APDS9960_PERS           0x8C\n#define APDS9960_CONFIG1        0x8D\n#define APDS9960_PPULSE         0x8E\n#define APDS9960_CONTROL        0x8F\n#define APDS9960_CONFIG2        0x90\n#define APDS9960_ID             0x92\n#define APDS9960_STATUS         0x93\n#define APDS9960_CDATAL         0x94\n#define APDS9960_CDATAH         0x95\n#define APDS9960_RDATAL         0x96\n#define APDS9960_RDATAH         0x97\n#define APDS9960_GDATAL         0x98\n#define APDS9960_GDATAH         0x99\n#define APDS9960_BDATAL         0x9A\n#define APDS9960_BDATAH         0x9B\n#define APDS9960_PDATA          0x9C\n#define APDS9960_POFFSET_UR     0x9D\n#define APDS9960_POFFSET_DL     0x9E\n#define APDS9960_CONFIG3        0x9F\n#define APDS9960_GPENTH         0xA0\n#define APDS9960_GEXTH          0xA1\n#define APDS9960_GCONF1         0xA2\n#define APDS9960_GCONF2         0xA3\n#define APDS9960_GOFFSET_U      0xA4\n#define APDS9960_GOFFSET_D      0xA5\n#define APDS9960_GOFFSET_L      0xA7\n#define APDS9960_GOFFSET_R      0xA9\n#define APDS9960_GPULSE         0xA6\n#define APDS9960_GCONF3         0xAA\n#define APDS9960_GCONF4         0xAB\n#define APDS9960_GFLVL          0xAE\n#define APDS9960_GSTATUS        0xAF\n#define APDS9960_IFORCE         0xE4\n#define APDS9960_PICLEAR        0xE5\n#define APDS9960_CICLEAR        0xE6\n#define APDS9960_AICLEAR        0xE7\n#define APDS9960_GFIFO_U        0xFC\n#define APDS9960_GFIFO_D        0xFD\n#define APDS9960_GFIFO_L        0xFE\n#define APDS9960_GFIFO_R        0xFF\n\n/* Gesture parameters */\n#define GESTURE_THRESHOLD_OUT   10\n#define GESTURE_SENSITIVITY_1   50\n#define GESTURE_SENSITIVITY_2   20\n\n#define GESTURE_VALID           0x01\n\n/* Misc parameters */\n#define FIFO_PAUSE_TIME         30   /* Wait period (ms) between FIFO reads */\n\n/* Bit fields */\n#define ENABLE_POWER            0x01\n#define ENABLE_ALS              0x02\n#define ENABLE_PROXIMITY        0x04\n#define ENABLE_WAIT             0x08\n#define ENABLE_ALS_INT          0x10\n#define ENABLE_PROXIMITY_INT    0x20\n#define ENABLE_GESTURE          0x40\n\n/* Status register */\n#define STA_ALS_SAT                 0x80\n#define STA_PROXI_OR_GESTURE_SAT    0x40\n#define STA_TRIG_PROXIMITY_INT      0x20\n#define STA_TRIG_ALS_INT            0x10\n#define STA_GESTURE_INT             0x04\n#define STA_PROXIMITY_VALID         0x02\n#define STA_ALS_VALID               0x01\n\n#define TIME_TO_VALUE(ms)    (256 - (ms / 2.78))\n\n#define CONFIG1_DEFAULT         0x60\n\n/* LED Drive values */\n#define LED_DRIVE_100MA         0\n#define LED_DRIVE_50MA          1\n#define LED_DRIVE_25MA          2\n#define LED_DRIVE_12_5MA        3\n\n/* Proximity Gain (PGAIN) values */\n#define PGAIN_1X                0\n#define PGAIN_2X                1\n#define PGAIN_4X                2\n#define PGAIN_8X                3\n\n/* ALS Gain (AGAIN) values */\n#define ALS_GAIN_1X             0\n#define ALS_GAIN_4X             1\n#define ALS_GAIN_16X            2\n#define ALS_GAIN_64X            3\n\n/* Gesture Gain (GGAIN) values */\n#define GGAIN_1X                0\n#define GGAIN_2X                1\n#define GGAIN_4X                2\n#define GGAIN_8X                3\n\n/* LED Boost values */\n#define LED_BOOST_100           0\n#define LED_BOOST_150           1\n#define LED_BOOST_200           2\n#define LED_BOOST_300           3\n\n/* Gesture wait time values */\n#define GWTIME_0MS              0\n#define GWTIME_2_8MS            1\n#define GWTIME_5_6MS            2\n#define GWTIME_8_4MS            3\n#define GWTIME_14_0MS           4\n#define GWTIME_22_4MS           5\n#define GWTIME_30_8MS           6\n#define GWTIME_39_2MS           7\n\n#endif /* APDS9960Constants_h */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/AmbientLightValue.cpp",
    "content": "//\n//  AmbientLightValue.cpp\n//  SMCLightSensor\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"AmbientLightValue.hpp\"\n\nSMC_RESULT SMCAmbientLightValue::readAccess() {\n\tauto value = reinterpret_cast<Value *>(data);\n\tUInt32 lux = atomic_load_explicit(currentLux, memory_order_acquire);\n\tUInt8 bits = forceBits->bits();\n\n\tif (lux == 0xFFFFFFFF) {\n\t\tvalue->valid = false;\n\t} else {\n\t\tvalue->valid = true;\n\t\tif (!(bits & ALSForceBits::kALSForceHighGain))\n\t\t\tvalue->highGain = true;\n\t\tif (!(bits & ALSForceBits::kALSForceChan))\n\t\t\tvalue->chan0 = OSSwapHostToBigInt16(lux);\n\t\tif (!(bits & ALSForceBits::kALSForceLux))\n\t\t\tvalue->roomLux = OSSwapHostToBigInt32(lux << 14);\n\t}\n\n\treturn SmcSuccess;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/AmbientLightValue.hpp",
    "content": "//\n//  AmbientLightValue.hpp\n//  SMCLightSensor\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef AmbientLightValue_hpp\n#define AmbientLightValue_hpp\n\n#include <libkern/libkern.h>\n#include <VirtualSMCSDK/kern_vsmcapi.hpp>\n\nclass ALSForceBits : public VirtualSMCValue {\npublic:\n\t/**\n\t *  Each \"1\" bit in gui8ALSForced indicates that a certain writable ALS\n\t *  variable has been overridden (i.e., forced) by the host OS or\n\t *  host diagnostics, and that variable should not be written by the SMC\n\t *  again until the applicable bit is cleared in gui8ALSForced.\n\t *  Currently, the used bits are:\n\t *      Bit 0 protects gui16ALSScale\n\t *      Bit 1 protects ui16Chan0 and ui16Chan1 of aalsvALSData\n\t *      Bit 2 protects gui16ALSLux\n\t *      Bit 3 protects fHighGain of aalsvALSData\n\t *      Bit 4 protects gai16ALSTemp[MAX_ALS_SENSORS]\n\t *  All other bits are reserved and should be cleared to 0.\n\t */\n\tenum {\n\t\tkALSForceScale      = 1,\n\t\tkALSForceChan       = 2,\n\t\tkALSForceLux        = 4,\n\t\tkALSForceHighGain   = 8,\n\t\tkALSForceTemp       = 16\n\t};\n\n\tUInt8 bits() { return data[0]; }\n};\n\nclass SMCAmbientLightValue : public VirtualSMCValue {\n\t_Atomic(UInt32) *currentLux;\n\tALSForceBits *forceBits;\nprotected:\n\tSMC_RESULT readAccess() override;\n\npublic:\n\t/**\n\t *  Contains latest ambient light info from 1 sensor\n\t */\n\tstruct PACKED Value {\n\t\t/**\n\t\t *  If TRUE, data in this struct is valid.\n\t\t */\n\t\tbool valid {false};\n\n\t\t/**\n\t\t *  If TRUE, ui16Chan0/1 are high-gain readings.\n\t\t *  If FALSE, ui16Chan0/1 are low-gain readings.\n\t\t */\n\t\tbool highGain {true};\n\n\t\t/**\n\t\t *  I2C channel 0 data or analog(ADC) data.\n\t\t */\n\t\tUInt16 chan0 {0};\n\n\t\t/**\n\t\t *  I2C channel 1 data.\n\t\t */\n        UInt16 chan1 {0};\n\n\t\t/**\n\t\t * The following field only exists on systems that send ALS change notifications to the OS:\n\t\t * Room illumination in lux, FP18.14.\n\t\t */\n\t\tUInt32 roomLux {0};\n\t};\n\n\tSMCAmbientLightValue(_Atomic(UInt32) *currentLux, ALSForceBits *forceBits) :\n\t\tcurrentLux(currentLux), forceBits(forceBits) {}\n};\n\n#endif /* AmbientLightValue_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/SurfaceAmbientLightSensorDriver.cpp",
    "content": "//\n//  SurfaceAmbientLightSensorDriver.cpp\n//  SurfaceAmbientLightSensor\n//\n//  Created by Xia on 2021/10/27.\n//  Copyright © 2021 Xia Shangning. All rights reserved.\n//\n\n#include <Headers/kern_util.hpp>\n\n#include \"SurfaceAmbientLightSensorDriver.hpp\"\n\n#define super IOService\nOSDefineMetaClassAndStructors(SurfaceAmbientLightSensorDriver, IOService);\n\nIOService* SurfaceAmbientLightSensorDriver::probe(IOService *provider, SInt32 *score) {\n    if (!super::probe(provider, score))\n        return nullptr;\n    \n    api = OSDynamicCast(VoodooI2CDeviceNub, provider);\n    if (!api)\n        return nullptr;\n      \n    OSDictionary *dict = nameMatching(\"ACPI0008\");\n    IOService *matched = waitForMatchingService(dict, 1000000000);\n    alsd_device = OSDynamicCast(IOACPIPlatformDevice, matched);\n    OSSafeReleaseNULL(dict);\n    OSSafeReleaseNULL(matched);\n    if (!alsd_device) {\n        LOG(\"Ambient Light Sensor ACPI device not found\");\n        return nullptr;\n    }\n    \n    ALSSensor sensor {ALSSensor::Type::Unknown7, true, 6, false};\n    ALSSensor noSensor {ALSSensor::Type::NoSensor, false, 0, false};\n    SMCAmbientLightValue::Value emptyValue;\n\n    VirtualSMCAPI::addKey(KeyAL, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(0, &forceBits, SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE));\n    VirtualSMCAPI::addKey(KeyALI0, vsmcPlugin.data, VirtualSMCAPI::valueWithData(\n        reinterpret_cast<const SMC_DATA *>(&sensor), sizeof(sensor), SmcKeyTypeAli, nullptr, SMC_KEY_ATTRIBUTE_CONST | SMC_KEY_ATTRIBUTE_READ));\n    VirtualSMCAPI::addKey(KeyALI1, vsmcPlugin.data, VirtualSMCAPI::valueWithData(\n        reinterpret_cast<const SMC_DATA *>(&noSensor), sizeof(noSensor), SmcKeyTypeAli, nullptr, SMC_KEY_ATTRIBUTE_CONST | SMC_KEY_ATTRIBUTE_READ));\n    VirtualSMCAPI::addKey(KeyALRV, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(1, nullptr, SMC_KEY_ATTRIBUTE_CONST | SMC_KEY_ATTRIBUTE_READ));\n    VirtualSMCAPI::addKey(KeyALV0, vsmcPlugin.data, VirtualSMCAPI::valueWithData(\n        reinterpret_cast<const SMC_DATA *>(&emptyValue), sizeof(emptyValue), SmcKeyTypeAlv, new SMCAmbientLightValue(&current_lux, &forceBits),\n        SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE));\n    VirtualSMCAPI::addKey(KeyALV1, vsmcPlugin.data, VirtualSMCAPI::valueWithData(\n        reinterpret_cast<const SMC_DATA *>(&emptyValue), sizeof(emptyValue), SmcKeyTypeAlv, nullptr,\n        SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE));\n    VirtualSMCAPI::addKey(KeyMSLD, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(0));\n    \n    LOG(\"Surface Ambient Light Sensor device found!\");\n    return this;\n}\n\nbool SurfaceAmbientLightSensorDriver::start(IOService *provider) {\n    if (!super::start(provider))\n        return false;\n\n    work_loop = getWorkLoop();\n    if (!work_loop) {\n        LOG(\"Could not get a IOWorkLoop instance\");\n        return false;\n    }\n    work_loop->retain();\n    poller = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceAmbientLightSensorDriver::pollALI));\n    if (!poller) {\n        LOG(\"Could not create timer event source\");\n        goto exit;\n    }\n    work_loop->addEventSource(poller);\n    \n    if (!api->open(this)) {\n        LOG(\"Could not open API\");\n        goto exit;\n    }\n\n    if (initDevice() != kIOReturnSuccess) {\n        LOG(\"Failed to init device\");\n        goto exit;\n    }\n    \n    PMinit();\n    api->joinPMtree(this);\n    registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);\n    \n    vsmcNotifier = VirtualSMCAPI::registerHandler(vsmcNotificationHandler, this);\n    return vsmcNotifier != nullptr;\nexit:\n    releaseResources();\n    return false;\n}\n\nvoid SurfaceAmbientLightSensorDriver::stop(IOService* provider) {\n//    writeRegister(APDS9960_ENABLE, 0x00);\n//    PMstop();\n//    releaseResources();\n//    super::stop(provider);\n    PANIC(\"SurfaceAmbientLightSensorDriver\", \"called stop!!!\");\n}\n\nbool SurfaceAmbientLightSensorDriver::vsmcNotificationHandler(void *sensors, void *refCon, IOService *vsmc, IONotifier *notifier) {\n    if (sensors && vsmc) {\n        auto self = static_cast<SurfaceAmbientLightSensorDriver *>(sensors);\n        auto ret = vsmc->callPlatformFunction(VirtualSMCAPI::SubmitPlugin, true, sensors, &self->vsmcPlugin, nullptr, nullptr);\n        if (ret == kIOReturnSuccess) {\n            IOLog(\"%s::Plugin submitted\\n\", self->getName());\n            self->poller->setTimeoutMS(POLLING_INTERVAL);\n            return true;\n        } else\n            IOLog(\"%s::Plugin submission failure %X\\n\", self->getName(), ret);\n    }\n    return false;\n}\n\n#define ENSURE(exp) ret=exp;\\\n                    if(ret != kIOReturnSuccess) {\\\n                        LOG(\"\"#exp\" failed!\");\\\n                        return ret;\\\n                    }\n\nIOReturn SurfaceAmbientLightSensorDriver::initDevice() {\n    IOReturn ret;\n    UInt8 id;\n    ENSURE(readRegister(APDS9960_ID, &id, 1))\n    LOG(\"Device id is %x\", id);\n    \n    ENSURE(writeRegister(APDS9960_ENABLE, 0x00))\n    // set short wait time to 700ms\n    ENSURE(writeRegister(APDS9960_WTIME, TIME_TO_VALUE(700)))\n    ENSURE(configDevice(ENABLE_WAIT, true))\n    // set ADC integration time to 300 ms\n    ENSURE(writeRegister(APDS9960_ATIME, TIME_TO_VALUE(300)))\n    ENSURE(writeRegister(APDS9960_CONFIG1, CONFIG1_DEFAULT))\n    ENSURE(writeRegister(APDS9960_CONTROL, ALS_GAIN_4X))\n    // these values come from Windows and is NECESSARY\n    ENSURE(writeRegister(APDS9960_CONFIG2, 0x03))\n    ENSURE(writeRegister(APDS9960_CONFIG3, 0x14))\n    ENSURE(configDevice(ENABLE_POWER, true))\n    ENSURE(configDevice(ENABLE_ALS, true));\n\n    return kIOReturnSuccess;\n}\n\ninline IOReturn SurfaceAmbientLightSensorDriver::readRegister(UInt8 reg, UInt8* values, size_t len) {\n    return api->writeReadI2C(&reg, 1, values, len);\n}\n\ninline IOReturn SurfaceAmbientLightSensorDriver::writeRegister(UInt8 reg, UInt8 cmd) {\n    UInt8 buffer[] {\n        reg,\n        cmd\n    };\n    return api->writeI2C(buffer, sizeof(buffer));\n}\n\nIOReturn SurfaceAmbientLightSensorDriver::configDevice(UInt8 func, bool enable) {\n    UInt8 reg;\n    if (readRegister(APDS9960_ENABLE, &reg, 1) != kIOReturnSuccess) {\n        LOG(\"Read enable register failed!\");\n        return kIOReturnError;\n    }\n    if (!(reg & func)!=enable)\n        return kIOReturnSuccess;\n    if (enable)\n        reg |= func;\n    else\n        reg &= ~func;\n    return writeRegister(APDS9960_ENABLE, reg);\n}\n\nvoid SurfaceAmbientLightSensorDriver::pollALI(IOTimerEventSource *timer) {\n    if (!awake)\n        return;\n    \n    UInt16 color[4];\n    if (readRegister(APDS9960_CDATAL, reinterpret_cast<UInt8 *>(color), sizeof(color)) != kIOReturnSuccess) {\n        LOG(\"Read from ALS failed!\");\n        poller->setTimeoutMS(POLLING_INTERVAL);\n        return;\n    }\n    atomic_store_explicit(&current_lux, color[0]*1.5, memory_order_release);\n    \n    VirtualSMCAPI::postInterrupt(SmcEventALSChange);\n    \n    OSObject *result;\n    OSObject *params[] = {\n        OSNumber::withNumber(current_lux, 32),\n    };\n    alsd_device->evaluateObject(\"XALI\", &result, params, 1);\n    OSSafeReleaseNULL(result);\n    params[0]->release();\n    \n//    LOG(\"Value: ALI=%04d\", current_lux);\n    poller->setTimeoutMS(POLLING_INTERVAL);\n}\n\nIOReturn SurfaceAmbientLightSensorDriver::setPowerState(unsigned long whichState, IOService *whatDevice) {\n    if (whatDevice != this)\n        return kIOReturnInvalid;\n    if (whichState == 0) {\n        if (awake) {\n            poller->cancelTimeout();\n            poller->disable();\n            awake = false;\n            writeRegister(APDS9960_ENABLE, 0x00);\n            DBG_LOG(\"Going to sleep\");\n        }\n    } else {\n        if (!awake) {\n            awake = true;\n            initDevice();\n            poller->enable();\n            poller->setTimeoutMS(POLLING_INTERVAL);\n            DBG_LOG(\"Woke up\");\n        }\n    }\n    return kIOPMAckImplied;\n}\n\nvoid SurfaceAmbientLightSensorDriver::releaseResources() {\n    if (poller) {\n        poller->cancelTimeout();\n        poller->disable();\n        work_loop->removeEventSource(poller);\n        OSSafeReleaseNULL(poller);\n    }\n    OSSafeReleaseNULL(work_loop);\n\n    if (api) {\n        if (api->isOpen(this)) {\n            api->close(this);\n        }\n        api = nullptr;\n    }\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/SurfaceAmbientLightSensorDriver.hpp",
    "content": "//\n//  SurfaceAmbientLightSensorDriver.hpp\n//  SurfaceAmbientLightSensor\n//\n//  Created by Xia on 2021/10/27.\n//  Copyright © 2021 Xia Shangning. All rights reserved.\n//\n\n#ifndef SurfaceAmbientLightSensorDriver_hpp\n#define SurfaceAmbientLightSensorDriver_hpp\n\n#include <IOKit/IOTimerEventSource.h>\n#include <IOKit/acpi/IOACPIPlatformDevice.h>\n\n#include \"../../../Dependencies/VoodooGPIO/VoodooGPIO/VoodooGPIO.hpp\"\n#include \"../../../Dependencies/VoodooSerial/VoodooSerial/ACPIParser/VoodooACPIResourcesParser.hpp\"\n#include \"./../../Dependencies/VoodooSerial/VoodooSerial/VoodooI2C/VoodooI2CDevice/VoodooI2CDeviceNub.hpp\"\n#include <VirtualSMCSDK/kern_vsmcapi.hpp>\n\n#include \"AmbientLightValue.hpp\"\n#include \"APDS9960Constants.h\"\n\n#define POLLING_INTERVAL 1000\n\nclass EXPORT SurfaceAmbientLightSensorDriver : public IOService {\n    OSDeclareDefaultStructors(SurfaceAmbientLightSensorDriver);\n    \npublic:\n    IOService* probe(IOService* provider, SInt32* score) override;\n    \n    bool start(IOService* provider) override;\n    \n    void stop(IOService* provider) override;\n    \n    IOReturn setPowerState(unsigned long whichState, IOService *whatDevice) override;\n    \n    static bool vsmcNotificationHandler(void *sensors, void *refCon, IOService *vsmc, IONotifier *notifier);\n    \nprivate:\n    IOACPIPlatformDevice*   alsd_device {nullptr};\n    VoodooI2CDeviceNub*     api {nullptr};\n    IOWorkLoop*             work_loop {nullptr};\n    IOTimerEventSource*     poller {nullptr};\n    \n    bool awake {true};\n    \n    _Atomic(UInt32) current_lux;\n    IONotifier *vsmcNotifier {nullptr};\n    static constexpr SMC_KEY KeyAL   = SMC_MAKE_IDENTIFIER('A','L','!',' ');\n    static constexpr SMC_KEY KeyALI0 = SMC_MAKE_IDENTIFIER('A','L','I','0');\n    static constexpr SMC_KEY KeyALI1 = SMC_MAKE_IDENTIFIER('A','L','I','1');\n    static constexpr SMC_KEY KeyALRV = SMC_MAKE_IDENTIFIER('A','L','R','V');\n    static constexpr SMC_KEY KeyALV0 = SMC_MAKE_IDENTIFIER('A','L','V','0');\n    static constexpr SMC_KEY KeyALV1 = SMC_MAKE_IDENTIFIER('A','L','V','1');\n    static constexpr SMC_KEY KeyLKSB = SMC_MAKE_IDENTIFIER('L','K','S','B');\n    static constexpr SMC_KEY KeyLKSS = SMC_MAKE_IDENTIFIER('L','K','S','S');\n    static constexpr SMC_KEY KeyMSLD = SMC_MAKE_IDENTIFIER('M','S','L','D');\n    VirtualSMCAPI::Plugin vsmcPlugin {\n        \"SurfaceAmbientLightSensorDriver\",\n        parseModuleVersion(xStringify(MODULE_VERSION)),\n        VirtualSMCAPI::Version,\n    };\n    struct ALSSensor {\n        enum Type : UInt8 {\n            NoSensor  = 0,\n            BS520     = 1,\n            TSL2561CS = 2,\n            LX1973A   = 3,\n            ISL29003  = 4,\n            Unknown7  = 7\n        };\n        Type sensorType {Type::NoSensor};\n        bool validWhenLidClosed {false};\n        UInt8 unknown {0};\n        bool controlSIL {false};\n    };\n    ALSForceBits forceBits;\n    \n    void pollALI(IOTimerEventSource *timer);\n    \n    IOReturn initDevice();\n    \n    IOReturn configDevice(UInt8 func, bool enable);\n    \n    void releaseResources();\n    \n    inline IOReturn readRegister(UInt8 reg, UInt8* values, size_t len);\n    \n    inline IOReturn writeRegister(UInt8 reg, UInt8 cmd);\n};\n\n#endif /* SurfaceAmbientLightSensorDriver_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/BatteryManager.cpp",
    "content": "//\n//  BatteryManager.cpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"BatteryManager.hpp\"\n\nBatteryManager *BatteryManager::instance = nullptr;\n\nOSDefineMetaClassAndStructors(BatteryManager, OSObject)\n\nvoid BatteryInfo::validateData(SInt32 id) {\n\tif (!state.designVoltage)\n\t\tstate.designVoltage = DummyVoltage;\n\tif (state.powerUnitIsWatt) {\n\t\tauto mV = state.designVoltage;\n\t\tIOLog(\"BatteryInfo::battery %d design voltage %d,%03d\\n\", id, mV / 1000, mV % 1000);\n\t\tif (designCapacity * 1000 / mV < 900) {\n            IOLog(\"BatteryInfo::battery %d reports mWh but uses mAh (%u)\\n\", id, designCapacity);\n\t\t\tstate.powerUnitIsWatt = false;\n\t\t} else {\n\t\t\tdesignCapacity = designCapacity * 1000 / mV;\n\t\t\tstate.lastFullChargeCapacity = state.lastFullChargeCapacity * 1000 / mV;\n\t\t\tstate.designCapacityWarning = state.designCapacityWarning * 1000 / mV;\n\t\t\tstate.designCapacityLow = state.designCapacityLow * 1000 / mV;\n\t\t}\n\t}\n\n\tif (designCapacity < state.lastFullChargeCapacity) {\n        IOLog(\"BatteryInfo::battery %d reports lower design capacity than maximum charged (%u/%u)\\n\", id,\n\t\t\t   designCapacity, state.lastFullChargeCapacity);\n\t\tif (state.lastFullChargeCapacity < ValueMax) {\n\t\t\tauto temp = designCapacity;\n\t\t\tdesignCapacity = state.lastFullChargeCapacity;\n\t\t\tstate.lastFullChargeCapacity = temp;\n\t\t}\n\t}\n\n    IOLog(\"BatteryInfo::battery %d cycle count %u remaining capacity %u\\n\", id, cycle, state.lastFullChargeCapacity);\n}\n\nbool BatteryManager::needUpdateBIX(UInt8 index) {\n    if (!index or index > batteryCount)\n        return false;\n    index = index - 1;\n    \n    IOSimpleLockLock(stateLock);\n    bool ret = !state.btInfo[index].connected;\n    if (!ret) {\n        AbsoluteTime cur_time;\n        UInt64 nsecs;\n        clock_get_uptime(&cur_time);\n        SUB_ABSOLUTETIME(&cur_time, &state.btInfo[index].lastBIXUpdateTime);\n        absolutetime_to_nanoseconds(cur_time, &nsecs);\n        if (nsecs > 60000000000) // > 60s\n            ret = true;\n    }\n    IOSimpleLockUnlock(stateLock);\n    \n    return ret;\n}\n\nvoid BatteryManager::updateBatteryInfoExtended(UInt8 index, OSArray *bix) {\n    if (!index or index > batteryCount)\n        return;\n    index = index - 1;\n    \n    IOLockLock(mainLock);\n    if (!bix)\n        batteries[index].reset();\n    else\n        batteries[index].updateInfoExtended(bix);\n    IOLockUnlock(mainLock);\n}\n\nbool BatteryManager::updateBatteryStatus(UInt8 index, UInt32 *bst) {\n    if (!index or index > batteryCount)\n        return false;\n    index = index - 1;\n    \n    bool is_full;\n    IOLockLock(mainLock);\n    is_full = batteries[index].updateStatus(bst);\n    IOLockUnlock(mainLock);\n    return is_full;\n}\n\nvoid BatteryManager::updateBatteryTemperature(UInt8 index, UInt16 temp) {\n    if (!index or index > batteryCount)\n        return;\n    index = index - 1;\n    \n    IOLockLock(mainLock);\n    batteries[index].updateTemperature(temp);\n    IOLockUnlock(mainLock);\n}\n\nbool BatteryManager::updateAdapterStatus(UInt8 index, UInt32 psr) {\n    if (!index or index > adapterCount)\n        return false;\n    index = index - 1;\n    \n    bool power_connected;\n    \n    IOLockLock(mainLock);\n    power_connected = adapters[index].updateStatus(psr!=0);\n    IOLockUnlock(mainLock);\n    \n    return power_connected;\n}\n\nvoid BatteryManager::externalPowerNotify(bool status) {\n\tIOPMrootDomain *rd = IOACPIPlatformDevice::getPMRootDomain();\n\trd->receivePowerNotification(kIOPMSetACAdaptorConnected | (kIOPMSetValue * status));\n}\n\nvoid BatteryManager::subscribe(PowerSourceInterestHandler h, void *t) {\n\tatomic_store_explicit(&handlerTarget, t, memory_order_release);\n\tatomic_store_explicit(&handler, h, memory_order_release);\n}\n\nvoid BatteryManager::informStatusChanged() {\n\tauto h = atomic_load_explicit(&handler, memory_order_acquire);\n\tif (h) h(atomic_load_explicit(&handlerTarget, memory_order_acquire));\n}\n\nbool BatteryManager::batteriesConnected() {\n\tfor (UInt8 i = 0; i < batteryCount; i++)\n\t\tif (state.btInfo[i].connected)\n\t\t\treturn true;\n\treturn false;\n}\n\nbool BatteryManager::adaptersConnected() {\n\tif (adapterCount) {\n\t\tfor (UInt8 i = 0; i < adapterCount; i++)\n\t\t\tif (state.acInfo[i].connected)\n\t\t\t\treturn true;\n\t}\n\telse {\n\t\tfor (UInt8 i = 0; i < batteryCount; i++)\n\t\t\tif (state.btInfo[i].state.calculatedACAdapterConnected)\n\t\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool BatteryManager::batteriesAreFull() {\n\t// I am not fully convinced we should assume that batteries are full when there are none, but so be it.\n\tfor (UInt8 i = 0; i < batteryCount; i++)\n\t\tif (state.btInfo[i].connected && (state.btInfo[i].state.state & SurfaceBattery::BSTStateMask) != SurfaceBattery::BSTNotCharging)\n\t\t\treturn false;\n\treturn true;\n}\n\nbool BatteryManager::externalPowerConnected() {\n\t// Firstly try real adapters\n\tfor (UInt8 i = 0; i < adapterCount; i++)\n\t\tif (state.acInfo[i].connected)\n\t\t\treturn true;\n\n\t// Then try calculated adapters\n\tbool hasBateries = false;\n\tfor (UInt8 i = 0; i < batteryCount; i++) {\n\t\tif (state.btInfo[i].connected) {\n\t\t\t// Ignore calculatedACAdapterConnected when real adapters exist!\n\t\t\tif (adapterCount == 0 && state.btInfo[i].state.calculatedACAdapterConnected)\n\t\t\t\treturn true;\n\t\t\thasBateries = true;\n\t\t}\n\t}\n\n\t// Safe to assume without batteries you need AC\n\treturn hasBateries == false;\n}\n\nUInt16 BatteryManager::calculateBatteryStatus(UInt8 index) {\n\treturn batteries[index].calculateBatteryStatus();\n}\n\nvoid BatteryManager::createShared(UInt8 bat_cnt, UInt8 adp_cnt) {\n\tif (instance)\n\t\tPANIC(\"BatteryManager\", \"attempted to allocate battery manager again\");\n\tinstance = new BatteryManager;\n\tif (!instance)\n\t\tPANIC(\"BatteryManager\", \"failed to allocate battery manager\");\n\tinstance->mainLock = IOLockAlloc();\n\tif (!instance->mainLock)\n\t\tPANIC(\"BatteryManager\", \"failed to allocate main battery manager lock\");\n\tinstance->stateLock = IOSimpleLockAlloc();\n\tif (!instance->stateLock)\n\t\tPANIC(\"BatteryManager\", \"failed to allocate state battery manager lock\");\n    \n\tatomic_init(&instance->handlerTarget, nullptr);\n\tatomic_init(&instance->handler, nullptr);\n    \n    if (bat_cnt >= BatteryManagerState::MaxBatteriesSupported) {\n        IOLog(\"BatteryManager::battery number more than %d!\\n\", BatteryManagerState::MaxBatteriesSupported);\n        bat_cnt = BatteryManagerState::MaxBatteriesSupported;\n    }\n    if (adp_cnt >= BatteryManagerState::MaxAcAdaptersSupported) {\n        IOLog(\"BatteryManager::adapter number more than %d!\\n\", BatteryManagerState::MaxAcAdaptersSupported);\n        adp_cnt = BatteryManagerState::MaxAcAdaptersSupported;\n    }\n    \n    auto dict = IOService::nameMatching(\"PNP0C0A\");\n    OSIterator *deviceIterator = nullptr;\n    if (dict) {\n        deviceIterator = IOService::getMatchingServices(dict);\n        dict->release();\n    }\n    if (deviceIterator) {\n        for (UInt8 i=0; i<bat_cnt; i++)\n            instance->batteries[i] = SurfaceBattery(OSDynamicCast(IOACPIPlatformDevice, deviceIterator->getNextObject()), i, instance->stateLock, &instance->state.btInfo[i]);\n        deviceIterator->release();\n    } else {\n        for (UInt8 i=0; i<bat_cnt; i++)\n            instance->batteries[i] = SurfaceBattery(nullptr, i, instance->stateLock, &instance->state.btInfo[i]);\n    }\n    instance->batteryCount = bat_cnt;\n    \n    dict = IOService::nameMatching(\"ACPI0003\");\n    deviceIterator = nullptr;\n    if (dict) {\n        deviceIterator = IOService::getMatchingServices(dict);\n        dict->release();\n    }\n    if (deviceIterator) {\n        for (UInt8 i=0; i<adp_cnt; i++)\n            instance->adapters[i] = SurfaceACAdapter(OSDynamicCast(IOACPIPlatformDevice, deviceIterator->getNextObject()), i, instance->stateLock, &instance->state.acInfo[i]);\n        deviceIterator->release();\n    } else {\n        for (UInt8 i=0; i<adp_cnt; i++)\n            instance->adapters[i] = SurfaceACAdapter(nullptr, i, instance->stateLock, &instance->state.acInfo[i]);\n    }\n    instance->adapterCount = adp_cnt;\n}\n\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/BatteryManager.hpp",
    "content": "//\n//  BatteryManager.hpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n//  Portions copyright © 2009 Superhai.\n//  VoodooBattery. Contact http://www.superhai.com/\n//\n\n#ifndef BatteryManagerBase_hpp\n#define BatteryManagerBase_hpp\n\n#include \"SurfaceBattery.hpp\"\n#include \"SurfaceACAdapter.hpp\"\n#include \"BatteryManagerState.hpp\"\n#include <IOKit/pwr_mgt/RootDomain.h>\n#include <Headers/kern_util.hpp>\n#include <stdatomic.h>\n\nclass EXPORT BatteryManager : public OSObject {\n\tOSDeclareDefaultStructors(BatteryManager)\n    friend class SurfaceBatteryDriver;\n\t\npublic:\n\tUInt8 batteryCount {0};\n\tUInt8 adapterCount {0};\n\n\t/**\n\t *  State lock, every state access must be guarded by this lock\n\t */\n\tIOSimpleLock *stateLock {nullptr};\n\n\t/**\n\t *  Main refreshed battery state containing battery information\n\t */\n\tBatteryManagerState state {};\n\n\tusing PowerSourceInterestHandler = IOReturn (*)(void *target);\n\n\t/**\n\t *  Subscribe to power source interest changes\n\t *  Only one handler could be subscribed to atm.\n\t *\n\t *  @param h  handler to be called\n\t *  @param t  handler target (context)\n\t */\n\tvoid subscribe(PowerSourceInterestHandler h, void *t);\n    \n    void informStatusChanged();\n\t\n\tbool batteriesConnected();\n\t\n\tbool adaptersConnected();\n\t\n\tbool batteriesAreFull();\n\n\tbool externalPowerConnected();\n\n\tstatic void createShared(UInt8 bat_cnt, UInt8 adp_cnt);\n\n\tstatic BatteryManager *getShared() {\n\t\treturn instance;\n\t}\n\t\n\t/**\n\t *  Calculate battery status in AlarmWarning format\n\t *\n\t *  @param  index battery index\n\t *\n\t *  @return calculated value\n\t */\n\tUInt16 calculateBatteryStatus(UInt8 index);\n    \n    AbsoluteTime lastAccess {0};\n\nprivate:\n\t/**\n\t *  The only allowed battery manager instance\n\t */\n\tstatic BatteryManager *instance;\n\n\t/**\n\t *  Not publicly exported notifications\n\t */\n\tenum {\n\t\tkIOPMSetValue\t\t\t\t= 1 << 16,\n\t\tkIOPMSetDesktopMode\t\t\t= 1 << 17,\n\t\tkIOPMSetACAdaptorConnected\t= 1 << 18\n\t};\n\n\tSurfaceBattery batteries[BatteryManagerState::MaxBatteriesSupported] {};\n\n\tSurfaceACAdapter adapters[BatteryManagerState::MaxAcAdaptersSupported] {};\n\n\t/**\n\t *  A lock to permit concurrent access\n\t */\n\tIOLock *mainLock {nullptr};\n\n\t/**\n\t *  Stored subscribed power source change handler target\n\t */\n\t_Atomic(void *) handlerTarget;\n\n\t/**\n\t *  Stored subscribed power source change handler\n\t */\n\t_Atomic(PowerSourceInterestHandler) handler;\n    \n    /**\n     *  Post external power plug-in/plug-out update\n     *\n     *  @param status  true on AC adapter connect\n     */\n    void externalPowerNotify(bool status);\n    \n    /**\n     *  @return whether battery is full\n     */\n    bool updateBatteryStatus(UInt8 index, UInt32 *bst);\n    \n    void updateBatteryInfoExtended(UInt8 index, OSArray *bix);\n    \n    void updateBatteryTemperature(UInt8 index, UInt16 temp);\n    \n    bool updateAdapterStatus(UInt8 index, UInt32 psr);\n    \n    bool needUpdateBIX(UInt8 index);\n};\n\n#endif /* BatteryManagerBase_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/BatteryManagerState.hpp",
    "content": "//\n//  BatteryManagerState.h\n//  SurfaceBattery\n//\n//  Copyright © 2018 usersse2. All rights reserved.\n//\n\n#ifndef BatteryManagerState_hpp\n#define BatteryManagerState_hpp\n\n/**\n *  Aggregated battery information\n */\nstruct BatteryInfo {\n\t/**\n\t *  Unknown value (according to ACPI, -1)\n\t */\n\tstatic constexpr UInt32 ValueUnknown = 0xFFFFFFFF;\n\n\t/**\n\t *  Maximum integer value (according to ACPI)\n\t */\n\tstatic constexpr UInt32 ValueMax = 0x80000000;\n\n\t/**\n\t *  Must be no more than kSMBusMaximumDataSize\n\t */\n\tstatic const size_t MaxStringLen = 32;\n\n\t/**\n\t *  Default voltage to assume\n\t */\n\tstatic constexpr UInt32 DummyVoltage = 12000;\n\n\t/**\n\t *  Smaller state substruct for quick updates\n\t */\n\tstruct State {\n\t\tUInt32 state {0};\n\t\tUInt32 presentVoltage {0};\n\t\tUInt32 presentRate {0};\n\t\tUInt32 averageRate {0};\n\t\tUInt32 remainingCapacity {0};\n\t\tUInt32 lastFullChargeCapacity {0};\n\t\tUInt32 lastRemainingCapacity {0};\n\t\tUInt32 designVoltage {0};\n\t\tUInt32 runTimeToEmpty {0};\n\t\tUInt32 averageTimeToEmpty {0};\n\t\tUInt32 averageTimeToEmptyHW {0};\n\t\tSInt32 signedPresentRate {0};\n\t\tSInt32 signedAverageRate {0};\n\t\tSInt32 signedAverageRateHW {0};\n\t\tUInt32 timeToFull {0};\n\t\tUInt32 timeToFullHW {0};\n\t\tUInt8  chargeLevel {0};\n\t\tUInt32 designCapacityWarning {0};\n\t\tUInt32 designCapacityLow {0};\n\t\tUInt16 temperatureDecikelvin {2931};\n\t\tUInt16 chargingCurrent {0};\n\t\tUInt16 chargingVoltage {8000};\n\t\tdouble temperature {0};\n\t\tbool powerUnitIsWatt {false};\n\t\tbool calculatedACAdapterConnected {false};\n\t\tbool bad {false};\n\t\tbool bogus {false};\n\t\tbool critical {false};\n\t\tbool batteryIsFull {true};\n        AbsoluteTime lastUpdateTime {0};\n\t};\n\n\t/**\n\t *  Battery manufacturer data\n\t *  All fields are big endian numeric values.\n\t *  While such values are not available from ACPI directly, we are faking\n\t *  them by leaving them as 0, as seen in System Profiler.\n\t */\n\tstruct BatteryManufacturerData {\n\t\tUInt16 PackLotCode {0};\n\t\tUInt16 PCBLotCode {0};\n\t\tUInt16 FirmwareVersion {0};\n\t\tUInt16 HardwareVersion {0};\n\t\tUInt16 BatteryVersion {0};\n\t};\n\n\t/**\n\t *  Complete battery information\n\t */\n\tState state {};\n\tUInt16 manufactureDate {0};\n\tUInt32 designCapacity {0};\n\tUInt32 technology {0};\n\tUInt32 cycle {0};\n\tchar deviceName[MaxStringLen] {};\n\tchar serial[MaxStringLen] {};\n\tchar batteryType[MaxStringLen] {};\n\tchar manufacturer[MaxStringLen] {};\n\tbool connected {false};\n    AbsoluteTime lastBIXUpdateTime {0};\n\tBatteryManufacturerData batteryManufacturerData {};\n\n\t/**\n\t *  Validate battery information and set the defaults\n\t *\n\t *  @param id        battery id\n\t */\n\tvoid validateData(SInt32 id=-1);\n};\n\n/**\n *  Aggregated adapter information\n */\nstruct ACAdapterInfo {\n\tbool connected {false};\n};\n\n/**\n *  Aggregated battery manager state\n */\nstruct BatteryManagerState {\n\tstatic constexpr UInt8 MaxBatteriesSupported = 4;\n\tstatic constexpr UInt8 MaxAcAdaptersSupported = 2;\n\tBatteryInfo btInfo[MaxBatteriesSupported] {};\n\tACAdapterInfo acInfo[MaxAcAdaptersSupported] {};\n};\n\n#endif /* BatteryManagerState_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/KeyImplementations.cpp",
    "content": "//\n//  KeyImplementations.cpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"KeyImplementations.hpp\"\n#include \"SurfaceBatteryDriver.hpp\"\n\nSMC_RESULT ACID::readAccess() {\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\tauto extConnected = BatteryManager::getShared()->externalPowerConnected();\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\tif (extConnected) {\n\t\t// Have some dummy value here for now, because ACPI has no means of getting adapter info\n\t\t// like power, voltage, serial number through only 2 pins - Vcc and GND.\n\t\tdata[0] = 0xba;\n\t\tdata[1] = 0xbe;\n\t\tdata[2] = 0x3c;\n\t\tdata[3] = 0x45;\n\t\tdata[4] = 0xc0;\n\t\tdata[5] = 0x03;\n\t\tdata[6] = 0x10;\n\t\tdata[7] = 0x43;\n\t} else {\n\t\tmemset(data, 0, size);\n\t}\n\treturn SmcSuccess;\n}\n\nSMC_RESULT ACIN::readAccess() {\n\tbool *ptr = reinterpret_cast<bool *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = BatteryManager::getShared()->externalPowerConnected();\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT AC_N::readAccess() {\n\tdata[0] = BatteryManager::getShared()->adapterCount;\n\treturn SmcSuccess;\n}\n\nSMC_RESULT B0AC::readAccess() {\n\tSInt16 *ptr = reinterpret_cast<SInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.signedPresentRate);\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT B0AV::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.presentVoltage);\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT B0BI::readAccess() {\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\tdata[0] = BatteryManager::getShared()->state.btInfo[index].connected;\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT B0CT::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].cycle);\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\n\nSMC_RESULT B0FC::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.lastFullChargeCapacity);\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT B0PS::readAccess() {\n\t//TODO: find what is its value when battery is the active power source\n\tdata[0] = data[1] = 0;\n\treturn SmcSuccess;\n}\n\nSMC_RESULT B0RM::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.remainingCapacity);\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT B0St::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->calculateBatteryStatus(index));\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT B0TF::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\tauto state = BatteryManager::getShared()->state.btInfo[index].state.state & SurfaceBattery::BSTStateMask;\n\tif (state == SurfaceBattery::BSTCharging)\n\t\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.timeToFull);\n\telse\n\t\t*ptr = 0xffff;\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT BATP::readAccess() {\n\tbool *ptr = reinterpret_cast<bool *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = BatteryManager::getShared()->externalPowerConnected() == false;\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT BBAD::readAccess() {\n\t// TODO: what's with multiple batteries?\n\tbool *ptr = reinterpret_cast<bool *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = BatteryManager::getShared()->state.btInfo[0].state.bad;\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT BBIN::readAccess() {\n\tbool *ptr = reinterpret_cast<bool *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = BatteryManager::getShared()->batteriesConnected();\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT BFCL::readAccess() {\n\t//TODO: implement this\n\tdata[0] = 100;\n\treturn SmcSuccess;\n}\n\nSMC_RESULT BNum::readAccess() {\n\tdata[0] = BatteryManager::getShared()->batteryCount;\n\treturn SmcSuccess;\n}\n\nSMC_RESULT BSIn::readAccess() {\n\tenum {\n\t\tBSInCharging          = 1,\n\t\tBSInACPresent         = 2,\n\t\tBSInACPresenceChanged = 4,\n\t\tBSInOSStopCharge      = 8,\n\t\tBSInOSCalibrationReq  = 16,\n\t\tBSInBTQueryInProgress = 32,\n\t\tBSInBTOk              = 64,\n\t\tBSInAdcInProgress     = 128\n\t};\n\n\tdata[0] = BSInBTOk;\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\tif (BatteryManager::getShared()->externalPowerConnected()) {\n\t\tif (!BatteryManager::getShared()->batteriesAreFull())\n\t\t\tdata[0] |= BSInCharging;\n\t\tdata[0] |= BSInACPresent;\n\t}\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT BRSC::readAccess() {\n\t// TODO: what's with multiple batteries?\n\tdata[0] = 0;\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\tif (!BatteryManager::getShared()->batteryCount ||\n\t\t!BatteryManager::getShared()->state.btInfo[0].connected)\n\t\tdata[1] = 0;\n\telse if (BatteryManager::getShared()->state.btInfo[0].state.chargeLevel)\n\t\tdata[1] = BatteryManager::getShared()->state.btInfo[0].state.chargeLevel;\n\telse if (BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity > 0 &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity != BatteryInfo::ValueUnknown &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity <= BatteryInfo::ValueMax)\n\t\tdata[1] = BatteryManager::getShared()->state.btInfo[0].state.remainingCapacity * 100 / BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity;\n\telse\n\t\tdata[1] = 0;\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT CHBI::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[0].state.chargingCurrent);\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT CHBV::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[0].state.chargingVoltage);\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT CHLC::readAccess() {\n\t// TODO: does it have any other values?\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\tif (BatteryManager::getShared()->batteryCount > 0 &&\n\t\tBatteryManager::getShared()->state.btInfo[0].connected &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity > 0 &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity != BatteryInfo::ValueUnknown &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity <= BatteryInfo::ValueMax &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.remainingCapacity > 0 &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.remainingCapacity != BatteryInfo::ValueUnknown &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.remainingCapacity <= BatteryInfo::ValueMax &&\n\t\tBatteryManager::getShared()->state.btInfo[0].state.remainingCapacity >= BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity)\n\t\tdata[0] = 2;\n\telse\n\t\tdata[0] = 1;\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT TB0T::readAccess() {\n\tUInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t*ptr = VirtualSMCAPI::encodeSp(SmcKeyTypeSp78, BatteryManager::getShared()->state.btInfo[index].state.temperature);\n\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\treturn SmcSuccess;\n}\n\nSMC_RESULT BC1V::readAccess() {\n    UInt16 *ptr = reinterpret_cast<UInt16 *>(data);\n    IOSimpleLockLock(BatteryManager::getShared()->stateLock);\n    *ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.presentVoltage);\n    IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n    return SmcSuccess;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/KeyImplementations.hpp",
    "content": "//\n//  KeyImplementations.hpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef KeyImplementations_hpp\n#define KeyImplementations_hpp\n\n#include <libkern/libkern.h>\n#include <VirtualSMCSDK/kern_vsmcapi.hpp>\n\n#include \"BatteryManager.hpp\"\n\nclass BatKey : public VirtualSMCValue { };\n\nclass BatIdxKey : public VirtualSMCValue {\nprotected:\n\tsize_t index;\npublic:\n\tBatIdxKey(size_t index) : index(index) {}\n};\n\nclass AC_N : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass ACID : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass ACIN : public BatKey { protected: SMC_RESULT readAccess() override; };\n\nclass B0AC : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass B0AV : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass B0BI : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass B0CT : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass B0FC : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass B0PS : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass B0RM : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass B0St : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass B0TF : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\nclass TB0T : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\n\nclass BATP : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass BBAD : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass BBIN : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass BFCL : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass BNum : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass BSIn : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass BRSC : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass CHBI : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass CHBV : public BatKey { protected: SMC_RESULT readAccess() override; };\nclass CHLC : public BatKey { protected: SMC_RESULT readAccess() override; };\n\nclass BC1V : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };\n\n//TODO: implement these\n// class D0IR : public BatKey { using BatKey::BatKey; protected: SMC_RESULT readAccess() override; };\n// class D0VM : public BatKey { using BatKey::BatKey; protected: SMC_RESULT readAccess() override; };\n// class D0VR : public BatKey { using BatKey::BatKey; protected: SMC_RESULT readAccess() override; };\n// class D0VX : public BatKey { using BatKey::BatKey; protected: SMC_RESULT readAccess() override; };\n\n#endif /* KeyImplementations_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/SurfaceACAdapter.cpp",
    "content": "//\n//  SurfaceACAdapter.cpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"SurfaceACAdapter.hpp\"\n\nbool SurfaceACAdapter::updateStatus(bool connected) {\n\tIOSimpleLockLock(adapterInfoLock);\n\tadapterInfo->connected = connected;\n\tIOSimpleLockUnlock(adapterInfoLock);\n    \n    if (device) {\n        OSObject *result;\n        OSObject *params[] = {\n            OSNumber::withNumber(connected, 32),\n        };\n        device->evaluateObject(\"XPSR\", &result, params, 1);\n        OSSafeReleaseNULL(result);\n        params[0]->release();\n    }\n    \n    return connected;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/SurfaceACAdapter.hpp",
    "content": "//\n//  SurfaceACAdapter.hpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef SurfaceACAdapter_hpp\n#define SurfaceACAdapter_hpp\n\n#include <IOKit/acpi/IOACPIPlatformDevice.h>\n#include \"BatteryManagerState.hpp\"\n\nclass SurfaceACAdapter {\npublic:\n\tSurfaceACAdapter() {}\n\t/**\n\t *  Actual constructor representing a real device with its own index and shared info struct\n\t */\n\tSurfaceACAdapter(IOACPIPlatformDevice *device, SInt32 id, IOSimpleLock *lock, ACAdapterInfo *info) :\n        device(device), id(id), adapterInfoLock(lock), adapterInfo(info) {}\n\n\tbool updateStatus(bool connected);\n    \nprivate:\n    /**\n     *  Current adapter device\n     */\n    IOACPIPlatformDevice *device {nullptr};\n    \n\t/**\n\t *  Current adapter id\n\t */\n\tSInt32 id {-1};\n\n\t/**\n\t *  Reference to shared lock for refreshing adapter info\n\t */\n\tIOSimpleLock *adapterInfoLock {nullptr};\n\n\t/**\n\t *  Reference to shared adapter info\n\t */\n\tACAdapterInfo *adapterInfo {nullptr};\n};\n\n#endif /* SurfaceACAdapter_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/SurfaceBattery.cpp",
    "content": "//\n//  SurfaceBattery.cpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"SurfaceBattery.hpp\"\n#include <IOKit/battery/AppleSmartBatteryCommands.h>\n\nUInt32 SurfaceBattery::getNumberFromArray(OSArray *array, UInt32 index) {\n\tauto number = OSDynamicCast(OSNumber, array->getObject(index));\n\tif (number)\n\t\treturn number->unsigned32BitValue();\n\treturn BatteryInfo::ValueUnknown;\n}\n\nvoid SurfaceBattery::getStringFromArray(OSArray *array, UInt32 index, char *dst, UInt32 dstSize) {\n\tif (dstSize == 0)\n\t\treturn;\n\n\tconst char *src = nullptr;\n\tauto object = array->getObject(index);\n\tif (object) {\n\t\tif (auto string = OSDynamicCast(OSString, object)) {\n\t\t\tsrc = string->getCStringNoCopy();\n\t\t\tdstSize = min(dstSize - 1, string->getLength());\n\t\t}\n\t}\n\n\tif (src) {\n\t\tstrncpy(dst, src, dstSize);\n\t\tdst[dstSize] = '\\0';\n\t} else {\n\t\tdst[0] = '\\0';\n\t}\n}\n\nvoid SurfaceBattery::reset() {\n    IOSimpleLockLock(batteryInfoLock);\n    *batteryInfo = BatteryInfo{};\n    hasBIX = false;\n    IOSimpleLockUnlock(batteryInfoLock);\n}\n\nvoid SurfaceBattery::updateInfoExtended(OSArray *bix) {\n    BatteryInfo bi;\n    bi.connected = true;\n    clock_get_uptime(&bi.lastBIXUpdateTime);\n\n    if (getNumberFromArray(bix, BIXPowerUnit) == 0)\n        bi.state.powerUnitIsWatt = true;\n    bi.designCapacity               = getNumberFromArray(bix, BIXDesignCapacity);\n    bi.state.lastFullChargeCapacity = getNumberFromArray(bix, BIXLastFullChargeCapacity);\n    bi.technology                   = getNumberFromArray(bix, BIXBatteryTechnology);\n    bi.state.designVoltage          = getNumberFromArray(bix, BIXDesignVoltage);\n    bi.state.designCapacityWarning  = getNumberFromArray(bix, BIXDesignCapacityOfWarning);\n    bi.state.designCapacityLow      = getNumberFromArray(bix, BIXDesignCapacityOfLow);\n    bi.cycle                        = getNumberFromArray(bix, BIXCycleCount);\n    getStringFromArray(bix, BIXModelNumber, bi.deviceName, BatteryInfo::MaxStringLen);\n    getStringFromArray(bix, BIXSerialNumber, bi.serial, BatteryInfo::MaxStringLen);\n//    getStringFromArray(bix, BIXBatteryType, bi.batteryType, BatteryInfo::MaxStringLen);\n//    getStringFromArray(bix, BIXOEMInformation, bi.manufacturer, BatteryInfo::MaxStringLen);\n    strncpy(bi.batteryType, \"SurfaceBattery\", BatteryInfo::MaxStringLen);\n    strncpy(bi.manufacturer, \"XavierXia\", BatteryInfo::MaxStringLen);\n\n\tbi.validateData(id);\n    \n    IOSimpleLockLock(batteryInfoLock);\n    *batteryInfo = bi;\n    hasBIX = true;\n    IOSimpleLockUnlock(batteryInfoLock);\n}\n\nbool SurfaceBattery::updateStatus(UInt32 *bst) {\n\tIOSimpleLockLock(batteryInfoLock);\n    BatteryInfo::State st = batteryInfo->state;\n    if (!hasBIX) {\n        IOSimpleLockUnlock(batteryInfoLock);\n        return false;\n    }\n\tIOSimpleLockUnlock(batteryInfoLock);\n    \n    UInt32 defaultRate = 5000*1000 / st.designVoltage;  // 5w\n\tst.state = bst[BSTState];\n\tst.presentRate = bst[BSTPresentRate];\n\tst.remainingCapacity = bst[BSTRemainingCapacity];\n\tst.presentVoltage = bst[BSTPresentVoltage];\n\tif (st.powerUnitIsWatt) {\n\t\tst.presentRate = st.presentRate * 1000 / st.designVoltage;\n\t\tst.remainingCapacity = st.remainingCapacity * 1000 / st.designVoltage;\n\t}\n\n\t// Sometimes this value can be either reported incorrectly or miscalculated\n\t// and exceed the actual capacity. Simply workaround it by capping the value.\n\t// REF: https://github.com/acidanthera/bugtracker/issues/565\n\tif (st.remainingCapacity > st.lastFullChargeCapacity)\n\t\tst.remainingCapacity = st.lastFullChargeCapacity;\n\n    if (!st.averageRate) {\n        st.averageRate = st.presentRate;\n    } else { // We will take a 1 minutes window\n        AbsoluteTime cur_time;\n        UInt64 nsecs;\n        clock_get_uptime(&cur_time);\n        SUB_ABSOLUTETIME(&cur_time, &st.lastUpdateTime);\n        absolutetime_to_nanoseconds(cur_time, &nsecs);\n        UInt32 msecs = (UInt32)(nsecs/1000000);\n        st.averageRate = (60000*st.averageRate + msecs*st.presentRate)/(60000+msecs);\n    }\n    clock_get_uptime(&st.lastUpdateTime);\n\n\t// Remaining capacity\n\tst.averageTimeToEmpty = st.averageRate ? 60 * st.remainingCapacity / st.averageRate : 60 * st.remainingCapacity / defaultRate;\n\tst.runTimeToEmpty = st.presentRate ? 60 * st.remainingCapacity / st.presentRate : 60 * st.remainingCapacity / defaultRate;\n\n\t// Check battery state\n\tbool bogus = false;\n\tswitch (st.state & BSTStateMask) {\n\t\tcase BSTNotCharging: {\n\t\t\tst.calculatedACAdapterConnected = true;\n\t\t\tst.batteryIsFull = true;\n\t\t\tst.chargingCurrent = 0;\n\t\t\tst.timeToFull = 0;\n\t\t\tst.signedPresentRate = st.presentRate;\n\t\t\tst.signedAverageRate = st.averageRate;\n\t\t\tbreak;\n\t\t}\n\t\tcase BSTDischarging: {\n\t\t\tst.calculatedACAdapterConnected = false;\n\t\t\tst.batteryIsFull = false;\n\t\t\tst.chargingCurrent = 0;\n\t\t\tst.timeToFull = 0;\n\t\t\tst.signedPresentRate = -st.presentRate;\n\t\t\tst.signedAverageRate = -st.averageRate;\n\t\t\tbreak;\n\t\t}\n\t\tcase BSTCharging: {\n\t\t\tst.calculatedACAdapterConnected = true;\n\t\t\tst.batteryIsFull = false;\n\t\t\tint diff = st.lastFullChargeCapacity - st.remainingCapacity;\n            st.timeToFull = st.averageRate ? 60 * diff / st.averageRate : 60 * diff / defaultRate;\n\t\t\tst.signedPresentRate = st.presentRate;\n\t\t\tst.signedAverageRate = st.averageRate;\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n            IOLog(\"SurfaceBattery::Bogus status data from battery %d (%x)\", id, st.state);\n\t\t\tst.batteryIsFull = false;\n\t\t\tbogus = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tst.lastRemainingCapacity = st.remainingCapacity;\n\n\t// bool warning  = st.remainingCapacity <= st.designCapacityWarning || st.runTimeToEmpty < 10;\n\tbool critical = st.remainingCapacity <= st.designCapacityLow || st.runTimeToEmpty < 5;\n\tif (st.state & BSTCritical) {\n        IOLog(\"SurfaceBattery::Battery %d is in critical state\", id);\n\t\tcritical = true;\n\t}\n\n\t// When we report battery failure, AppleSmartBatteryManager sets isCharging=false.\n\t// So we don't report battery failure when it's charging.\n\tst.bad = (st.state & BSTStateMask) != BSTCharging && st.lastFullChargeCapacity < 2 * st.designCapacityWarning;\n\tst.bogus = bogus;\n\tst.critical = critical;\n\n\tIOSimpleLockLock(batteryInfoLock);\n\tbatteryInfo->state = st;\n\tIOSimpleLockUnlock(batteryInfoLock);\n    \n    return st.batteryIsFull;\n}\n\nvoid SurfaceBattery::updateTemperature(UInt16 temp) {\n    IOSimpleLockLock(batteryInfoLock);\n    batteryInfo->state.temperatureDecikelvin = temp;\n    batteryInfo->state.temperature = ((double) temp - 2731) / 10;\n    IOSimpleLockUnlock(batteryInfoLock);\n}\n\nUInt16 SurfaceBattery::calculateBatteryStatus() {\n\tUInt16 value = 0;\n\tif (batteryInfo->connected) {\n\t\tvalue = kBInitializedStatusBit;\n\t\tauto st = batteryInfo->state.state;\n\t\tif (st & BSTDischarging)\n\t\t\tvalue |= kBDischargingStatusBit;\n\t\tif (st & BSTCritical)\n\t\t\tvalue |= kBFullyDischargedStatusBit;\n\t\tif ((st & BSTStateMask) == BSTNotCharging) {\n\t\t\tif (batteryInfo->state.lastFullChargeCapacity > 0 &&\n\t\t\t\tbatteryInfo->state.lastFullChargeCapacity != BatteryInfo::ValueUnknown &&\n\t\t\t\tbatteryInfo->state.lastFullChargeCapacity <= BatteryInfo::ValueMax &&\n\t\t\t\tbatteryInfo->state.remainingCapacity > 0 &&\n\t\t\t\tbatteryInfo->state.remainingCapacity != BatteryInfo::ValueUnknown &&\n\t\t\t\tbatteryInfo->state.remainingCapacity <= BatteryInfo::ValueMax &&\n\t\t\t\tbatteryInfo->state.remainingCapacity >= batteryInfo->state.lastFullChargeCapacity)\n\t\t\t\tvalue |= kBFullyChargedStatusBit;\n\t\t\tvalue |= kBTerminateChargeAlarmBit;\n\t\t}\n\n\t\tif (batteryInfo->state.bad) {\n\t\t\tvalue |= kBTerminateChargeAlarmBit;\n\t\t\tvalue |= kBTerminateDischargeAlarmBit;\n\t\t}\n\t}\n\n\treturn value;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/SurfaceBattery.hpp",
    "content": "//\n//  SurfaceBattery.hpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef SurfaceBattery_hpp\n#define SurfaceBattery_hpp\n\n#include <IOKit/acpi/IOACPIPlatformDevice.h>\n#include \"BatteryManagerState.hpp\"\n\nclass SurfaceBattery {\n    friend class BatteryManager;\npublic:\n\t/**\n\t *  Peak accuracy for average in percents\n\t */\n\tstatic constexpr UInt8 AverageBoundPercent = 25;\n\n\t/**\n\t *  Battery status obtained from ACPI _BST\n\t */\n\tenum {\n\t\t/**\n\t\t Means that the battery is not charging and not discharging.\n\t\t It may happen when the battery is fully charged,\n\t\t or when AC adapter is connected but charging has not started yet,\n\t\t or when charging is limited to some percent in BIOS settings.\n\t\t */\n\t\tBSTNotCharging  = 0,\n\t\tBSTDischarging  = 1 << 0,\n\t\tBSTCharging     = 1 << 1,\n\t\tBSTCritical     = 1 << 2,\n\t\tBSTStateMask    = BSTNotCharging | BSTDischarging | BSTCharging,\n\t};\n\n\t/**\n\t *  Reference to shared lock for refreshing battery info\n\t */\n\tIOSimpleLock *batteryInfoLock {nullptr};\n\n\t/**\n\t *  Reference to shared battery info\n\t */\n\tBatteryInfo *batteryInfo {nullptr};\n\n\t/**\n\t *  Dummy constructor\n\t */\n\tSurfaceBattery() {}\n\n\t/**\n\t *  Actual constructor representing a real device with its own index and shared info struct\n\t */\n\tSurfaceBattery(IOACPIPlatformDevice *device, SInt32 id, IOSimpleLock *lock, BatteryInfo *info) :\n        device(device), id(id), batteryInfoLock(lock), batteryInfo(info) {}\n\t\n\t/**\n\t * Calculate value for B0St SMC key and corresponding SMBus command\n\t *\n\t *  @return value\n\t */\n\tUInt16 calculateBatteryStatus();\n\n\t/**\n\t *  QuickPoll will be disable when average rate is available from EC\n\t */\n\tbool averageRateAvailable {false};\n\nprivate:\n    /**\n     *  Current battery device\n     */\n    IOACPIPlatformDevice *device {nullptr};\n    \n    bool hasBIX {false};\n    \n\tUInt32 getNumberFromArray(OSArray *array, UInt32 index);\n\n\tvoid getStringFromArray(OSArray *array, UInt32 index, char *dst, UInt32 dstSize);\n    \n    /**\n     * Reset BatteryInfo\n     */\n    void reset();\n\n\t/**\n\t *  Obtain aggregated battery information from SAM\n\t *\n\t *  @param bix   _bix returned from SAM\n\t */\n\tvoid updateInfoExtended(OSArray *bix);\n    \n    /**\n     *  Obtain aggregated battery status from SAM\n     *\n     *  @param bst   _bst returned from SSH\n     *\n     *  @return whether battery is full\n     */\n    bool updateStatus(UInt32 *bst);\n    \n    void updateTemperature(UInt16 temp);\n\n\t/**\n\t *  Current battery id\n\t */\n\tSInt32 id {-1};\n\n\t/**\n\t *  Extended Battery Static Information pack layout\n\t */\n\tenum {\n\t\tBIXRevision,                    //Integer\n\t\tBIXPowerUnit,\n\t\tBIXDesignCapacity,\n\t\tBIXLastFullChargeCapacity,      //Integer (DWORD)\n\t\tBIXBatteryTechnology,\n\t\tBIXDesignVoltage,\n\t\tBIXDesignCapacityOfWarning,\n\t\tBIXDesignCapacityOfLow,\n\t\tBIXCycleCount,                  //Integer (DWORD)\n\t\tBIXMeasurementAccuracy,         //Integer (DWORD)\n\t\tBIXMaxSamplingTime,             //Integer (DWORD)\n\t\tBIXMinSamplingTime,             //Integer (DWORD)\n\t\tBIXMaxAveragingInterval,        //Integer (DWORD)\n\t\tBIXMinAveragingInterval,        //Integer (DWORD)\n\t\tBIXBatteryCapacityGranularity1,\n\t\tBIXBatteryCapacityGranularity2,\n\t\tBIXModelNumber,\n\t\tBIXSerialNumber,\n\t\tBIXBatteryType,\n\t\tBIXOEMInformation,\n\t};\n\n\t/**\n\t *  Battery Real-time Information pack layout\n\t */\n\tenum {\n\t\tBSTState,\n\t\tBSTPresentRate,\n\t\tBSTRemainingCapacity,\n\t\tBSTPresentVoltage\n\t};\n};\n\n#endif /* SurfaceBattery_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/SurfaceBatteryDriver.cpp",
    "content": "//\n//  SurfaceBatteryDriver.cpp\n//  SurfaceBattery\n//\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#include <VirtualSMCSDK/kern_vsmcapi.hpp>\n#include <Headers/kern_util.hpp>\n\n#include \"SurfaceBatteryDriver.hpp\"\n#include \"KeyImplementations.hpp\"\n#include <IOKit/battery/AppleSmartBatteryCommands.h>\n\n#define super IOService\nOSDefineMetaClassAndStructors(SurfaceBatteryDriver, IOService)\n\nvoid SurfaceBatteryDriver::eventReceived(SurfaceBatteryNub *sender, SurfaceBatteryEventType type) {\n    switch (type) {\n        case SurfaceBatteryInformationChanged:\n            update_bix->interruptOccurred(nullptr, this, 0);\n            break;\n        case SurfaceBatteryStatusChanged:\n        case SurfaceAdaptorStatusChanged:\n            DBG_LOG(\"Got BST/PSR update event\");\n            AbsoluteTime cur_time;\n            UInt64 nsecs;\n            clock_get_uptime(&cur_time);\n            SUB_ABSOLUTETIME(&cur_time, &last_update);\n            absolutetime_to_nanoseconds(cur_time, &nsecs);\n            if (nsecs > 1000000000) {   // PSR often comes with BST changes, so avoid update it twice in a short period (1s).\n                quick_cnt = BST_UPDATE_QUICK_CNT;\n                clock_get_uptime(&last_update);\n                update_bst->interruptOccurred(nullptr, this, 0);\n            }\n            break;\n        default:\n            DBG_LOG(\"WTF? Unknown event type\");\n            break;\n    }\n}\n\nvoid SurfaceBatteryDriver::updateBatteryInformation(IOInterruptEventSource *sender, int count) {\n    if (!awake or bat_missing)\n        return;\n    \n    bix_fail = false;\n    bool connected = false;\n    if (nub->getBatteryConnection(1, &connected) != kIOReturnSuccess) {\n        LOG(\"Failed to get battery connection status from SSH!\");\n        bix_fail = true;\n        // It is impossible to occur unless the battery is not present\n        bat_missing = true;\n        return;\n    }\n    if (!connected)\n        BatteryManager::getShared()->updateBatteryInfoExtended(1, nullptr); // reset battery\n    else if (BatteryManager::getShared()->needUpdateBIX(1)) {\n        OSArray *bix;\n        if (nub->getBatteryInformation(1, &bix) != kIOReturnSuccess) {\n            LOG(\"Failed to get battery information extended from SSH!\");\n            bix_fail = true;\n        } else {\n            BatteryManager::getShared()->updateBatteryInfoExtended(1, bix);\n            bix->flushCollection();\n            OSSafeReleaseNULL(bix);\n        }\n    }\n}\n\nvoid SurfaceBatteryDriver::updateBatteryStatus(IOInterruptEventSource *sender, int count) {\n    if (!awake or bat_missing)\n        return;\n    \n    UInt32 psr;\n    bool connected = false;\n    \n    timer->cancelTimeout();\n    if (bix_fail) {\n        updateBatteryInformation(nullptr, 0);\n        if (bix_fail)\n            goto fail;\n    }\n    \n    if (nub->getAdaptorStatus(&psr) != kIOReturnSuccess) {\n        LOG(\"Failed to get power source status from SSH!\");\n        goto fail;\n    } else\n        power_connected = BatteryManager::getShared()->updateAdapterStatus(1, psr);\n    BatteryManager::getShared()->externalPowerNotify(power_connected);\n    \n    if (nub->getBatteryConnection(1, &connected) != kIOReturnSuccess) {\n        LOG(\"Failed to get battery connection status from SSH!\");\n        return;\n    }\n    if (connected) {\n        UInt16 temp = 0;\n        UInt32 bst[4];\n        if (nub->getBatteryStatus(1, bst, &temp) != kIOReturnSuccess) {\n            LOG(\"Failed to get BST from SSH!\");\n            goto fail;\n        } else\n            BatteryManager::getShared()->updateBatteryStatus(1, bst);\n        if (temp)\n            BatteryManager::getShared()->updateBatteryTemperature(1, temp);\n        BatteryManager::getShared()->informStatusChanged();\n    }\n\n    if (quick_cnt) {\n        if (--quick_cnt == 0)\n            sync = true;    // after finishing quick update, sync with normal update\n        timer->setTimeoutMS(BST_UPDATE_QUICK);\n    } else {    // sync normal update interval\n        if (sync) {\n            AbsoluteTime cur_time;\n            UInt64 nsecs;\n            sync = false;\n            clock_get_uptime(&cur_time);\n            IOSimpleLockLock(BatteryManager::getShared()->stateLock);\n            SUB_ABSOLUTETIME(&cur_time, &BatteryManager::getShared()->lastAccess);\n            IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n            absolutetime_to_nanoseconds(cur_time, &nsecs);\n            UInt8 timerDelta = nsecs / (1000000 * BST_UPDATE_QUICK);\n            if (timerDelta < BST_UPDATE_NORMAL/BST_UPDATE_QUICK - 5) {\n                timer->setTimeoutMS(BST_UPDATE_NORMAL - (2 + timerDelta) * BST_UPDATE_QUICK);\n                return;\n            }\n        }\n        timer->setTimeoutMS(BST_UPDATE_NORMAL);\n    }\n    return;\nfail:\n    timer->setTimeoutMS(BST_UPDATE_QUICK/2);\n}\n\nvoid SurfaceBatteryDriver::pollBatteryStatus(IOTimerEventSource *sender) {\n    if (bat_missing) {\n        // Fake a 100% charging battery based on BIX from SP7.\n        \n        // -------- BIX --------\n        UInt8 buffer[BIX_LENGTH] = {0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xa8, 0x00,\n                                    0x00, 0xc0, 0xa8, 0x00, 0x00, 0x01, 0x00, 0x00,\n                                    0x00, 0x92, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x00,\n                                    0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,\n                                    0x00, 0xe8, 0x03, 0x00, 0x00, 0xff, 0xff, 0xff,\n                                    0xff, 0xff, 0xff, 0xff, 0xff, 0xe8, 0x03, 0x00,\n                                    0x00, 0xe8, 0x03, 0x00, 0x00, 0x0a, 0x00, 0x00,\n                                    0x00, 0x0a, 0x00, 0x00, 0x00, 0x4d, 0x31, 0x31,\n                                    0x30, 0x39, 0x35, 0x39, 0x37, 0x00, 0x00, 0x00,\n                                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n                                    0x00, 0x00, 0x30, 0x30, 0x32, 0x37, 0x30, 0x36,\n                                    0x36, 0x30, 0x32, 0x30, 0x00, 0x4c, 0x49, 0x4f,\n                                    0x4e, 0x00, 0x44, 0x59, 0x4e, 0x00, 0x00, 0x00,\n                                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n                                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};\n        UInt32 *temp = reinterpret_cast<UInt32 *>(buffer+1);\n        const char *str = reinterpret_cast<const char *>(buffer);\n        \n        OSNumber *revision = OSNumber::withNumber(*buffer, 8);\n        OSNumber *power_unit = OSNumber::withNumber(temp[0], 32);\n        OSNumber *design_cap = OSNumber::withNumber(temp[1], 32);\n        OSNumber *last_full_cap = OSNumber::withNumber(temp[2], 32);\n        OSNumber *bat_tech = OSNumber::withNumber(temp[3], 32);\n        OSNumber *design_volt = OSNumber::withNumber(temp[4], 32);\n        OSNumber *design_cap_warn = OSNumber::withNumber(temp[5], 32);\n        OSNumber *design_cap_low = OSNumber::withNumber(temp[6], 32);\n        OSNumber *cycle_cnt = OSNumber::withNumber(temp[7], 32);\n        OSNumber *mesure_acc = OSNumber::withNumber(temp[8], 32);\n        OSNumber *max_sample_t = OSNumber::withNumber(temp[9], 32);\n        OSNumber *min_sample_t = OSNumber::withNumber(temp[10], 32);\n        OSNumber *max_avg_interval = OSNumber::withNumber(temp[11], 32);\n        OSNumber *min_avg_interval = OSNumber::withNumber(temp[12], 32);\n        OSNumber *bat_cap_gra_1 = OSNumber::withNumber(temp[13], 32);\n        OSNumber *bat_cap_gra_2 = OSNumber::withNumber(temp[14], 32);\n        OSString *model_number = OSString::withCString(str+0x3D);\n        OSString *serial_number = OSString::withCString(str+0x52);\n        OSString *bat_type = OSString::withCString(str+0x5D);\n        OSString *oem_info = OSString::withCString(str+0x62);\n        const OSObject *arr[] = {revision, power_unit, design_cap, last_full_cap, bat_tech,\n                            design_volt, design_cap_warn, design_cap_low, cycle_cnt,\n                            mesure_acc, max_sample_t, min_sample_t, max_avg_interval,\n                            min_avg_interval, bat_cap_gra_1, bat_cap_gra_2, model_number,\n                            serial_number, bat_type, oem_info};\n        \n        OSArray *bix = OSArray::withObjects(arr, 20);\n        BatteryManager::getShared()->updateBatteryInfoExtended(1, bix);\n        bix->flushCollection();\n        OSSafeReleaseNULL(bix);\n        \n        // -------- BST --------\n        UInt32 bst[4] = {0x02, 0x00, 0xa8c0, 0x1d92};\n        BatteryManager::getShared()->updateBatteryStatus(1, bst);\n        BatteryManager::getShared()->updateAdapterStatus(1, true);\n        BatteryManager::getShared()->externalPowerNotify(true);\n    } else\n        updateBatteryStatus(nullptr, 0);\n}\n\nIOService *SurfaceBatteryDriver::probe(IOService *provider, SInt32 *score) {\n\tif (!super::probe(provider, score))\n        return nullptr;\n    \n    nub = OSDynamicCast(SurfaceBatteryNub, provider);\n    if (!nub)\n        return nullptr;\n    \n    //TODO: SurfaceBook series have two batteries\n//    OSNumber *bat_cnt_prop = OSDynamicCast(OSNumber, getProperty(\"BatteryCount\"));\n    UInt32 bat_cnt = 1;\n//    if (bat_cnt_prop) {\n//        bat_cnt = bat_cnt_prop->unsigned32BitValue();\n//    } else {\n//        LOG(\"Fall back to default: battery count = 1\");\n//    }\n    BatteryManager::createShared(bat_cnt, 1);\n\n\t//TODO: implement the keys below as well\n\t// IB0R: sp4s or sp5s\n\t// IBAC: sp7s\n\t// PB0R = IB0R * VP0R\n\n\treturn this;\n}\n\nbool SurfaceBatteryDriver::start(IOService *provider) {\n\tif (!super::start(provider))\n\t\treturn false;\n\n\t// AppleSMC presence is a requirement, wait for it.\n\tauto dict = nameMatching(\"AppleSMC\");\n\tauto applesmc = waitForMatchingService(dict);\n\tif (!applesmc) {\n\t\tLOG(\"Timeout in waiting for AppleSMC\");\n\t\treturn false;\n\t}\n    OSSafeReleaseNULL(dict);\n    OSSafeReleaseNULL(applesmc);\n    \n    const UInt8 adaptCount = BatteryManager::getShared()->adapterCount;\n    const UInt8 batCount = min(BatteryManager::getShared()->batteryCount, MaxIndexCount);\n\n    work_loop = IOWorkLoop::workLoop();\n    if (!work_loop) {\n        LOG(\"Could not get work loop!\");\n        return false;\n    }\n    \n    timer = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceBatteryDriver::pollBatteryStatus));\n    if (!timer) {\n        LOG(\"Could not create timer!\");\n        goto exit;\n    }\n    work_loop->addEventSource(timer);\n    \n    update_bix = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceBatteryDriver::updateBatteryInformation));\n    update_bst = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceBatteryDriver::updateBatteryStatus));\n    if (!update_bix || !update_bst) {\n        LOG(\"Could not create interrupt event!\");\n        goto exit;\n    }\n    work_loop->addEventSource(update_bix);\n    work_loop->addEventSource(update_bst);\n    \n    if (nub->registerBatteryEvent(this, OSMemberFunctionCast(SurfaceBatteryNub::EventHandler, this, &SurfaceBatteryDriver::eventReceived)) != kIOReturnSuccess) {\n        LOG(\"Battery event registration failed!\");\n        goto exit;\n    }\n    \n\t//WARNING: watch out, key addition is sorted here!\n\tif (adaptCount > 0) {\n\t\tVirtualSMCAPI::addKey(KeyACEN, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(0, new ACIN));\n\t\tVirtualSMCAPI::addKey(KeyACFP, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(false, new ACIN));\n\t\tVirtualSMCAPI::addKey(KeyACID, vsmcPlugin.data, VirtualSMCAPI::valueWithData(nullptr, 8, SmcKeyTypeCh8s, new ACID));\n\t\tVirtualSMCAPI::addKey(KeyACIN, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(false, new ACIN));\n\t}\n\n\tfor (UInt8 i = 0; i < batCount; i++) {\n\t\tVirtualSMCAPI::addKey(KeyB0AC(i), vsmcPlugin.data, VirtualSMCAPI::valueWithSint16(400, new B0AC(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));\n\t\tVirtualSMCAPI::addKey(KeyB0AV(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(13000, new B0AV(i)));\n\t\tVirtualSMCAPI::addKey(KeyB0BI(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(1, new B0BI(i)));\n\t\tVirtualSMCAPI::addKey(KeyB0CT(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(1, new B0CT(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));\n\t\tVirtualSMCAPI::addKey(KeyB0FC(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(4000, new B0FC(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));\n\t\tVirtualSMCAPI::addKey(KeyB0PS(i), vsmcPlugin.data, VirtualSMCAPI::valueWithData(nullptr, 2, SmcKeyTypeHex, new B0PS(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));\n\t\tVirtualSMCAPI::addKey(KeyB0RM(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(2000, new B0RM(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));\n\t\tVirtualSMCAPI::addKey(KeyB0St(i), vsmcPlugin.data, VirtualSMCAPI::valueWithData(nullptr, 2, SmcKeyTypeHex, new B0St(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));\n\t\tVirtualSMCAPI::addKey(KeyB0TF(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(0, new B0TF(i)));\n\t\tVirtualSMCAPI::addKey(KeyTB0T(i+1), vsmcPlugin.data, VirtualSMCAPI::valueWithSp(0, SmcKeyTypeSp78, new TB0T(i)));\n        if (i == 0)\n            VirtualSMCAPI::addKey(KeyTB0T(0), vsmcPlugin.data, VirtualSMCAPI::valueWithSp(0, SmcKeyTypeSp78, new TB0T(0)));\n\t}\n\n\tVirtualSMCAPI::addKey(KeyBATP, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(true, new BATP));\n\tVirtualSMCAPI::addKey(KeyBBAD, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(false, new BBAD));\n\tVirtualSMCAPI::addKey(KeyBBIN, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(true, new BBIN));\n\tVirtualSMCAPI::addKey(KeyBFCL, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(100, new BFCL, SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE));\n\tVirtualSMCAPI::addKey(KeyBNum, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(1, new BNum));\n\tVirtualSMCAPI::addKey(KeyBRSC, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(40, new BRSC, SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE | SMC_KEY_ATTRIBUTE_PRIVATE_WRITE));\n\tVirtualSMCAPI::addKey(KeyBSIn, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(0, new BSIn));\n\n\tVirtualSMCAPI::addKey(KeyCHBI, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(0, new CHBI));\n\tVirtualSMCAPI::addKey(KeyCHBV, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(8000, new CHBV));\n\tVirtualSMCAPI::addKey(KeyCHLC, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(1, new CHLC));\n\n    for (UInt8 i = 0; i < batCount; i++) {\n        VirtualSMCAPI::addKey(KeyBC1V(i+1), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(defaultBatteryCellVoltage, new BC1V(i)));\n    }\n\n\tqsort(const_cast<VirtualSMCKeyValue *>(vsmcPlugin.data.data()), vsmcPlugin.data.size(), sizeof(VirtualSMCKeyValue), VirtualSMCKeyValue::compare);\n    \n    PMinit();\n    nub->joinPMtree(this);\n    registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);\n\n\tvsmcNotifier = VirtualSMCAPI::registerHandler(vsmcNotificationHandler, this);\n    if (!vsmcNotifier) {\n        PMstop();\n        goto exit;\n    }\n    \n    registerService();\n\treturn true;\nexit:\n    releaseResources();\n    return false;\n}\n\nbool SurfaceBatteryDriver::vsmcNotificationHandler(void *sensors, void *refCon, IOService *vsmc, IONotifier *notifier) {\n\tif (sensors && vsmc) {\n\t\tauto &plugin = static_cast<SurfaceBatteryDriver *>(sensors)->vsmcPlugin;\n\t\tauto ret = vsmc->callPlatformFunction(VirtualSMCAPI::SubmitPlugin, true, sensors, &plugin, nullptr, nullptr);\n\t\tif (ret == kIOReturnSuccess) {\n\t\t\tIOLog(\"SurfaceBatteryDriver::Plugin submitted\\n\");\n\t\t\treturn true;\n\t\t} else\n            IOLog(\"SurfaceBatteryDriver::Plugin submission failure %X\\n\", ret);\n\t}\n\treturn false;\n}\n\nvoid SurfaceBatteryDriver::stop(IOService *provider) {\n//    PMstop();\n//    releaseResources();\n//    super::stop(provider);\n    PANIC(\"SurfaceBatteryDriver\", \"called stop!!!\");\n}\n\nvoid SurfaceBatteryDriver::releaseResources() {\n    nub->unregisterBatteryEvent(this);\n    if (timer) {\n        timer->cancelTimeout();\n        timer->disable();\n        work_loop->removeEventSource(timer);\n        OSSafeReleaseNULL(timer);\n    }\n    if (update_bix) {\n        update_bix->disable();\n        work_loop->removeEventSource(update_bix);\n        OSSafeReleaseNULL(update_bix);\n    }\n    if (update_bst) {\n        update_bst->disable();\n        work_loop->removeEventSource(update_bst);\n        OSSafeReleaseNULL(update_bst);\n    }\n    OSSafeReleaseNULL(work_loop);\n}\n\nIOReturn SurfaceBatteryDriver::setProperties(OSObject *props) {\n    OSDictionary* dict = OSDynamicCast(OSDictionary, props);\n    if (!dict)\n        return kIOReturnError;\n    \n    OSCollectionIterator* i = OSCollectionIterator::withCollection(dict);\n    if (i) {\n        while (OSString* key = OSDynamicCast(OSString, i->getNextObject())) {\n            if (key->isEqualTo(\"PerformanceMode\")) {\n                OSNumber *mode = OSDynamicCast(OSNumber, dict->getObject(key));\n                if (mode) {\n                    UInt32 m = mode->unsigned32BitValue();\n                    LOG(\"Set performance mode to %d\", m);\n                    if (nub->setPerformanceMode(m) != kIOReturnSuccess)\n                        LOG(\"Set performance mode failed!\");\n                }\n            }\n        }\n        i->release();\n    }\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceBatteryDriver::setPowerState(unsigned long whichState, IOService *device) {\n    if (device != this)\n        return kIOReturnInvalid;\n    if (whichState == 0) {\n        if (awake) {\n            awake = false;\n            bat_missing = false;\n            timer->cancelTimeout();\n            timer->disable();\n            update_bix->disable();\n            update_bst->disable();\n            DBG_LOG(\"Going to sleep\");\n        }\n    } else {\n        if (!awake) {\n            awake = true;\n            timer->enable();\n            update_bix->enable();\n            update_bst->enable();\n            bix_fail = true;\n            quick_cnt = BST_UPDATE_QUICK_CNT;\n            clock_get_uptime(&last_update);\n            updateBatteryStatus(nullptr, 0);\n            \n            OSNumber *mode = OSDynamicCast(OSNumber, getProperty(\"PerformanceMode\"));\n            if (mode) {\n                UInt32 m = mode->unsigned32BitValue();\n                if (nub->setPerformanceMode(m) != kIOReturnSuccess)\n                    LOG(\"Set performance mode failed!\");\n            }\n            DBG_LOG(\"Woke up\");\n        }\n    }\n    return kIOPMAckImplied;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/SurfaceBatteryDriver.hpp",
    "content": "//\n//  SurfaceBatteryDriver.hpp\n//  SurfaceBattery\n//\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#ifndef SurfaceBatteryDriver_hpp\n#define SurfaceBatteryDriver_hpp\n\n#include \"BatteryManager.hpp\"\n#include \"../SurfaceSerialHubDevices/SurfaceBatteryNub.hpp\"\n\n#define BST_UPDATE_QUICK    1000\n#define BST_UPDATE_NORMAL   30000\n#define BST_UPDATE_QUICK_CNT    5\n\nclass EXPORT SurfaceBatteryDriver : public IOService {\n\tOSDeclareDefaultStructors(SurfaceBatteryDriver)\n\n\t/**\n\t *  Key name index mapping\n\t */\n\tstatic constexpr size_t MaxIndexCount = sizeof(\"0123456789ABCDEF\") - 1;\n\tstatic constexpr const char *KeyIndexes = \"0123456789ABCDEF\";\n\n\t/**\n\t *  Key name declarations\n\t */\n\tstatic constexpr SMC_KEY KeyAC_N = SMC_MAKE_IDENTIFIER('A','C','-','N');\n\tstatic constexpr SMC_KEY KeyACEN = SMC_MAKE_IDENTIFIER('A','C','E','N');\n\tstatic constexpr SMC_KEY KeyACFP = SMC_MAKE_IDENTIFIER('A','C','F','P');\n\tstatic constexpr SMC_KEY KeyACID = SMC_MAKE_IDENTIFIER('A','C','I','D');\n\tstatic constexpr SMC_KEY KeyACIN = SMC_MAKE_IDENTIFIER('A','C','I','N');\n\tstatic constexpr SMC_KEY KeyBATP = SMC_MAKE_IDENTIFIER('B','A','T','P');\n\tstatic constexpr SMC_KEY KeyBBAD = SMC_MAKE_IDENTIFIER('B','B','A','D');\n\tstatic constexpr SMC_KEY KeyBBIN = SMC_MAKE_IDENTIFIER('B','B','I','N');\n\tstatic constexpr SMC_KEY KeyBFCL = SMC_MAKE_IDENTIFIER('B','F','C','L');\n\tstatic constexpr SMC_KEY KeyBNum = SMC_MAKE_IDENTIFIER('B','N','u','m');\n\tstatic constexpr SMC_KEY KeyBRSC = SMC_MAKE_IDENTIFIER('B','R','S','C');\n\tstatic constexpr SMC_KEY KeyBSIn = SMC_MAKE_IDENTIFIER('B','S','I','n');\n\tstatic constexpr SMC_KEY KeyCHBI = SMC_MAKE_IDENTIFIER('C','H','B','I');\n\tstatic constexpr SMC_KEY KeyCHBV = SMC_MAKE_IDENTIFIER('C','H','B','V');\n\tstatic constexpr SMC_KEY KeyCHLC = SMC_MAKE_IDENTIFIER('C','H','L','C');\n\n\tstatic constexpr SMC_KEY KeyB0AC(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'A','C'); }\n\tstatic constexpr SMC_KEY KeyB0AV(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'A','V'); }\n\tstatic constexpr SMC_KEY KeyB0BI(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'B','I'); }\n\tstatic constexpr SMC_KEY KeyB0CT(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'C','T'); }\n\tstatic constexpr SMC_KEY KeyB0FC(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'F','C'); }\n\tstatic constexpr SMC_KEY KeyB0PS(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'P','S'); }\n\tstatic constexpr SMC_KEY KeyB0RM(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'R','M'); }\n\tstatic constexpr SMC_KEY KeyB0St(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'S','t'); }\n\tstatic constexpr SMC_KEY KeyB0TF(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'T','F'); }\n\tstatic constexpr SMC_KEY KeyD0IR(size_t i) { return SMC_MAKE_IDENTIFIER('D',KeyIndexes[i],'I','R'); }\n\tstatic constexpr SMC_KEY KeyD0VM(size_t i) { return SMC_MAKE_IDENTIFIER('D',KeyIndexes[i],'V','M'); }\n\tstatic constexpr SMC_KEY KeyD0VR(size_t i) { return SMC_MAKE_IDENTIFIER('D',KeyIndexes[i],'V','R'); }\n\tstatic constexpr SMC_KEY KeyD0VX(size_t i) { return SMC_MAKE_IDENTIFIER('D',KeyIndexes[i],'V','X'); }\n\tstatic constexpr SMC_KEY KeyTB0T(size_t i) { return SMC_MAKE_IDENTIFIER('T','B',KeyIndexes[i],'T'); }\n\n\t// Keys used in BigSur 10.16 and later\n\tstatic constexpr SMC_KEY KeyBC1V(size_t i) { return SMC_MAKE_IDENTIFIER('B','C',KeyIndexes[i],'V'); }\n\t\n\t/**\n\t *  VirtualSMC service registration notifier\n\t */\n\tIONotifier *vsmcNotifier {nullptr};\n\n\tVirtualSMCAPI::Plugin vsmcPlugin {\n\t\t\"SurfaceBatteryDriver\",\n\t\tparseModuleVersion(xStringify(MODULE_VERSION)),\n\t\tVirtualSMCAPI::Version,\n\t};\n\npublic:\n\tIOService *probe(IOService *provider, SInt32 *score) override;\n\t\n\tbool start(IOService *provider) override;\n\t\n\tvoid stop(IOService *provider) override;\n    \n    IOReturn setPowerState(unsigned long whichState, IOService * device) override;\n    \n    IOReturn setProperties(OSObject* props) override;\n\t\n\tstatic bool vsmcNotificationHandler(void *sensors, void *refCon, IOService *vsmc, IONotifier *notifier);\n    \nprivate:\n    IOWorkLoop*             work_loop {nullptr};\n    IOTimerEventSource*     timer {nullptr};\n    IOInterruptEventSource* update_bix {nullptr};\n    IOInterruptEventSource* update_bst {nullptr};\n    SurfaceBatteryNub*      nub {nullptr};\n    \n    bool    awake {false};\n    bool    power_connected {true};\n    bool    bix_fail {true};\n    int     quick_cnt {0};\n    bool    bat_missing {false};\n    bool    sync {false};\n    AbsoluteTime last_update {0};\n\n    void eventReceived(SurfaceBatteryNub *sender, SurfaceBatteryEventType type);\n    \n    void updateBatteryInformation(IOInterruptEventSource *sender, int count);\n    \n    void updateBatteryStatus(IOInterruptEventSource *sender, int count);\n    \n    void pollBatteryStatus(IOTimerEventSource* sender);\n    \n    void releaseResources();\n};\n\n#endif /* SurfaceBatteryDriver_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/SurfaceSMBusController.cpp",
    "content": "//\n//  SurfaceSMBusController.cpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include <stdatomic.h>\n#include <libkern/c++/OSContainers.h>\n#include <IOKit/IOCatalogue.h>\n#include <IOKit/IOTimerEventSource.h>\n\n#include \"SurfaceSMBusController.hpp\"\n\n#define super IOSMBusController\nOSDefineMetaClassAndStructors(SurfaceSMBusController, IOSMBusController)\n\nbool SurfaceSMBusController::start(IOService *provider) {\n\tworkLoop = IOWorkLoop::workLoop();\n\tif (!workLoop) {\n        IOLog(\"%s::workLoop allocation failed\\n\", getName());\n\t\treturn false;\n\t}\n\n\trequestQueue = OSArray::withCapacity(0);\n\tif (!requestQueue) {\n        IOLog(\"%s::requestQueue allocation failure\\n\", getName());\n\t\tOSSafeReleaseNULL(workLoop);\n\t\treturn false;\n\t}\n\t\n\tif (!super::start(provider)) {\n        IOLog(\"%s::parent start failed\\n\", getName());\n\t\tOSSafeReleaseNULL(workLoop);\n\t\tOSSafeReleaseNULL(requestQueue);\n\t\treturn false;\n\t}\n\n\tsetProperty(\"IOSMBusSmartBatteryManager\", kOSBooleanTrue);\n\tsetProperty(\"_SBS\", 1, 32);\n\tregisterService();\n\n    interruptSource = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceSMBusController::handleBatteryCommandsEvent));\n\tif (!interruptSource) {\n        IOLog(\"%s::failed to allocate interrupt event\\n\", getName());\n\t\tOSSafeReleaseNULL(workLoop);\n\t\tOSSafeReleaseNULL(requestQueue);\n\t\treturn false;\n\t}\n    getWorkLoop()->addEventSource(interruptSource);\n\n\tBatteryManager::getShared()->subscribe(handleACPINotification, this);\n\t\n\treturn true;\n}\n\nvoid SurfaceSMBusController::setReceiveData(IOSMBusTransaction *transaction, UInt16 valueToWrite) {\n\ttransaction->receiveDataCount = sizeof(UInt16);\n\tUInt16 *ptr = reinterpret_cast<UInt16*>(transaction->receiveData);\n\t*ptr = valueToWrite;\n}\n\nIOSMBusStatus SurfaceSMBusController::startRequest(IOSMBusRequest *request) {\n\tauto result = super::startRequest(request);\n\tif (result != kIOSMBusStatusOK)\n        return result;\n\t\n\tIOSMBusTransaction *transaction = request->transaction;\n\n\tif (transaction) {\n\t\ttransaction->status = kIOSMBusStatusOK;\n\t\tUInt32 valueToWrite = 0;\n\t\t\n\t\tif (transaction->address == kSMBusManagerAddr && transaction->protocol == kIOSMBusProtocolReadWord) {\n\t\t\tswitch (transaction->command) {\n\t\t\t\tcase kMStateContCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tvalueToWrite = BatteryManager::getShared()->externalPowerConnected() ? kMACPresentBit : 0;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, valueToWrite);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kMStateCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tif (BatteryManager::getShared()->batteriesConnected()) {\n\t\t\t\t\t\tvalueToWrite = kMPresentBatt_A_Bit;\n\t\t\t\t\t\tif ((BatteryManager::getShared()->state.btInfo[0].state.state & SurfaceBattery::BSTStateMask) == SurfaceBattery::BSTCharging)\n\t\t\t\t\t\t\tvalueToWrite |= kMChargingBatt_A_Bit;\n\t\t\t\t\t}\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, valueToWrite);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\t// Nothing should be done here since AppleSmartBattery always calls bzero fo transaction\n\t\t\t\t\t// Let's also not set transaction status to error value since it can be an unknown command\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (transaction->address == kSMBusBatteryAddr && transaction->protocol == kIOSMBusProtocolReadWord) {\n\t\t\t//FIXME: maybe the incoming data show us which battery is queried about? Or it's in the address?\n\n\t\t\tswitch (transaction->command) {\n\t\t\t\tcase kBBatteryStatusCmd: {\n\t\t\t\t\tsetReceiveData(transaction, BatteryManager::getShared()->calculateBatteryStatus(0));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBManufacturerAccessCmd: {\n\t\t\t\t\tif (transaction->sendDataCount == 2 &&\n\t\t\t\t\t\t(transaction->sendData[0] == kBExtendedPFStatusCmd ||\n\t\t\t\t\t\t transaction->sendData[0] == kBExtendedOperationStatusCmd)) {\n\t\t\t\t\t\t// AppleSmartBatteryManager ignores these values.\n\t\t\t\t\t\tsetReceiveData(transaction, 0);\n\t\t\t\t\t}\n\t\t\t\t\t//CHECKME: Should else case be handled?\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBPackReserveCmd:\n\t\t\t\tcase kBDesignCycleCount9CCmd: {\n\t\t\t\t\tsetReceiveData(transaction, 1000);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n                case kBReadCellVoltage1Cmd:\n                case kBReadCellVoltage2Cmd:\n                case kBReadCellVoltage3Cmd:\n                case kBReadCellVoltage4Cmd: {\n                    setReceiveData(transaction, defaultBatteryCellVoltage);\n                    break;\n                }\n                case kBVoltageCmd: {\n                    IOSimpleLockLock(BatteryManager::getShared()->stateLock);\n                    auto value = BatteryManager::getShared()->state.btInfo[0].state.presentVoltage;\n                    IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n                    setReceiveData(transaction, value);\n                    break;\n                }\n\t\t\t\tcase kBCurrentCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].state.signedPresentRate;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBAverageCurrentCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].state.signedAverageRate;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBSerialNumberCmd:\n\t\t\t\tcase kBMaxErrorCmd:\n\t\t\t\t\tbreak;\n\t\t\t\tcase kBRunTimeToEmptyCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].state.runTimeToEmpty;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBAverageTimeToEmptyCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].state.averageTimeToEmpty;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBTemperatureCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].state.temperatureDecikelvin;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBDesignCapacityCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].designCapacity;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBCycleCountCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].cycle;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBAverageTimeToFullCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].state.timeToFull;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBRemainingCapacityCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].state.remainingCapacity;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBFullChargeCapacityCmd: {\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tauto value = BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity;\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBManufactureDateCmd: {\n\t\t\t\t\tUInt16 value = 0;\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tif (BatteryManager::getShared()->state.btInfo[0].manufactureDate) {\n\t\t\t\t\t\tvalue = BatteryManager::getShared()->state.btInfo[0].manufactureDate;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstrncpy(reinterpret_cast<char *>(transaction->receiveData), BatteryManager::getShared()->state.btInfo[0].serial, kSMBusMaximumDataSize);\n\t\t\t\t\t\ttransaction->receiveData[kSMBusMaximumDataSize-1] = '\\0';\n\t\t\t\t\t}\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\n\t\t\t\t\tif (!value) {\n\t\t\t\t\t\tconst char* p = reinterpret_cast<char *>(transaction->receiveData);\n\t\t\t\t\t\tbool found = false;\n\t\t\t\t\t\tint year = 2016, month = 02, day = 29;\n\t\t\t\t\t\twhile ((p = strstr(p, \"20\")) != nullptr) { // hope that this code will not survive until 22nd century\n\t\t\t\t\t\t\tif (sscanf(p, \"%04d%02d%02d\", &year, &month, &day) == 3 || \t\t// YYYYMMDD (Lenovo)\n\t\t\t\t\t\t\t\tsscanf(p, \"%04d/%02d/%02d\", &year, &month, &day) == 3) {\t// YYYY/MM/DD (HP)\n\t\t\t\t\t\t\t\tif (1 <= month && month <= 12 && 1 <= day && day <= 31) {\n\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tp++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!found) { // in case we parsed a non-date\n\t\t\t\t\t\t\tyear = 2016;\n\t\t\t\t\t\t\tmonth = 02;\n\t\t\t\t\t\t\tday = 29;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalue = makeBatteryDate(day, month, year);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tsetReceiveData(transaction, value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//CHECKME: Should there be a default setting receiveDataCount to 0 or status failure?\n\t\t\t}\n\t\t}\n\n\t\tif (transaction->address == kSMBusBatteryAddr &&\n\t\t\ttransaction->protocol == kIOSMBusProtocolWriteWord &&\n\t\t\ttransaction->command == kBManufacturerAccessCmd) {\n\t\t\tif (transaction->sendDataCount == 2 && (transaction->sendData[0] == kBExtendedPFStatusCmd || transaction->sendData[0] == kBExtendedOperationStatusCmd)) {\n\t\t\t\t// Nothing can be done here since we don't write any values to hardware, we fake response for this command in handler for\n\t\t\t\t// kIOSMBusProtocolReadWord/kBManufacturerAccessCmd. Anyway, AppleSmartBattery::transactionCompletion ignores this response.\n\t\t\t\t// If we can see this log statement, it means that fields sendDataCount and sendData have a proper offset in IOSMBusTransaction\n\t\t\t}\n\t\t}\n\n\t\tif (transaction->address == kSMBusBatteryAddr && transaction->protocol == kIOSMBusProtocolReadBlock) {\n\t\t\tswitch (transaction->command) {\n\t\t\t\tcase kBManufacturerNameCmd: {\n\t\t\t\t\ttransaction->receiveDataCount = kSMBusMaximumDataSize;\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tstrncpy(reinterpret_cast<char *>(transaction->receiveData), BatteryManager::getShared()->state.btInfo[0].manufacturer, kSMBusMaximumDataSize);\n\t\t\t\t\ttransaction->receiveData[kSMBusMaximumDataSize-1] = '\\0';\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase kBAppleHardwareSerialCmd:\n\t\t\t\t\ttransaction->receiveDataCount = kSMBusMaximumDataSize;\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tstrncpy(reinterpret_cast<char *>(transaction->receiveData), BatteryManager::getShared()->state.btInfo[0].serial, kSMBusMaximumDataSize);\n\t\t\t\t\ttransaction->receiveData[kSMBusMaximumDataSize-1] = '\\0';\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kBDeviceNameCmd:\n\t\t\t\t\ttransaction->receiveDataCount = kSMBusMaximumDataSize;\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tstrncpy(reinterpret_cast<char *>(transaction->receiveData), BatteryManager::getShared()->state.btInfo[0].deviceName, kSMBusMaximumDataSize);\n\t\t\t\t\ttransaction->receiveData[kSMBusMaximumDataSize-1] = '\\0';\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kBManufacturerDataCmd:\n\t\t\t\t\ttransaction->receiveDataCount = sizeof(BatteryInfo::BatteryManufacturerData);\n\t\t\t\t\tIOSimpleLockLock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tmemcpy(reinterpret_cast<UInt16 *>(transaction->receiveData), &BatteryManager::getShared()->state.btInfo[0].batteryManufacturerData, sizeof(BatteryInfo::BatteryManufacturerData));\n\t\t\t\t\tIOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\t\t\t\t\tbreak;\n\t\t\t\tcase kBManufacturerInfoCmd:\n\t\t\t\t\tbreak;\n\t\t\t\t// Let other commands slip if any.\n\t\t\t\t// receiveDataCount is already 0, and status failure results in retries - it's not what we want.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!requestQueue->setObject(request)) {\n        IOLog(\"%s::startRequest failed to append a request\\n\", getName());\n\t\treturn kIOSMBusStatusUnknownFailure;\n\t}\n    interruptSource->interruptOccurred(nullptr, this, 0);\n    \n    IOSimpleLockLock(BatteryManager::getShared()->stateLock);\n    clock_get_uptime(&BatteryManager::getShared()->lastAccess);\n    IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);\n\n\treturn result;\n}\n\nvoid SurfaceSMBusController::handleBatteryCommandsEvent(IOInterruptEventSource *sender, int count) {\n\t// requestQueue contains objects owned by two parties:\n\t// 1. requestQueue itself, as the addition of any object retains it\n\t// 2. IOSMBusController, since it does not release the object after passing it\n\t// to us in IOSMBusController::performTransactionGated.\n\t// OSArray::removeObject takes away our ownership, and then\n\t// IOSMBusController::completeRequest releases the request inside.\n\n\twhile (requestQueue->getCount() != 0) {\n\t\tauto request = OSDynamicCast(IOSMBusRequest, requestQueue->getObject(0));\n\t\trequestQueue->removeObject(0);\n\t\tif (request != nullptr)\n\t\t\tcompleteRequest(request);\n\t}\n}\n\nIOReturn SurfaceSMBusController::handleACPINotification(void *target) {\n\tSurfaceSMBusController *self = static_cast<SurfaceSMBusController *>(target);\n\tif (self) {\n\t\tauto &bmgr = *BatteryManager::getShared();\n\t\t// TODO: when we have multiple batteries, handle insertion or removal of a single battery\n\t\tIOSimpleLockLock(bmgr.stateLock);\n\t\tbool batteriesConnected = bmgr.batteriesConnected();\n\t\tbool adaptersConnected = bmgr.adaptersConnected();\n\t\tself->prevBatteriesConnected = batteriesConnected;\n\t\tself->prevAdaptersConnected = adaptersConnected;\n\t\tIOSimpleLockUnlock(bmgr.stateLock);\n\t\tUInt8 data[] = {kBMessageStatusCmd, batteriesConnected};\n\t\tself->messageClients(kIOMessageSMBusAlarm, data, arrsize(data));\n\t\treturn kIOReturnSuccess;\n\t}\n\treturn kIOReturnBadArgument;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceBattery/SurfaceSMBusController.hpp",
    "content": "//\n//  SurfaceSMBusController.hpp\n//  SurfaceBattery\n//\n//  Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef SurfaceSMBusController_hpp\n#define SurfaceSMBusController_hpp\n\n#include <IOKit/IOSMBusController.h>\n#include <IOKit/IOInterruptEventSource.h>\n#include <IOKit/battery/AppleSmartBatteryCommands.h>\n\n#include \"BatteryManager.hpp\"\n\nclass EXPORT SurfaceSMBusController : public IOSMBusController {\n\tOSDeclareDefaultStructors(SurfaceSMBusController)\n\n\t/**\n\t *  This is here to avoid collisions in case of future expansion of IOSMBusController class.\n\t *  WARNING! It is important that this is the first member of the class!\n\t */\n\tvoid *reserved[8] {};\n\n\t/**\n\t Set received data for a transaction to a 16-bit integer value\n\n\t @param transaction SMBus transaction\n\t @param valueToWrite Value to write\n\t */\n\tstatic void setReceiveData(IOSMBusTransaction *transaction, UInt16 valueToWrite);\n\n\t/**\n\t *  A workloop in charge of handling timer events with requests.\n\t */\n\tIOWorkLoop *workLoop {nullptr};\n\n\t/**\n\t *  Event source for processing requests.\n\t */\n    IOInterruptEventSource *interruptSource {nullptr};\n\n\t/**\n\t *  Registered SMBus requests.\n\t */\n\tOSArray *requestQueue {nullptr};\n\n\t/**\n\t *  Create battery date in AppleSmartBattery format\n\t *\n\t *  @param day     manufacturing date\n\t *  @param month   manufacturing month\n\t *  @param year    manufacturing year\n\t *\n\t *  @return date in AppleSmartBattery format\n\t */\n\tstatic constexpr UInt16 makeBatteryDate(UInt16 day, UInt16 month, UInt16 year) {\n\t\treturn (day & 0x1FU) | ((month & 0xFU) << 5U) | (((year - 1980U) & 0x7FU) << 9U);\n\t}\n\npublic:\t\n\t/**\n\t *  Start the driver by setting up the workloop and preparing the matching.\n\t *\n\t *  @param provider  parent IOService object\n\t *\n\t *  @return true on success\n\t */\n\tbool start(IOService *provider) override;\n\n\t/**\n\t *  Handle external notification from Surface battery instance\n\t *\n\t *  @param target  SurfaceSMBusController instance\n\t *\n\t *  @return kIOReturnSuccess\n\t */\n\tstatic IOReturn handleACPINotification(void *target);\n\t\nprotected:\n\t/**\n\t *  Returns the current work loop.\n\t *  We should properly override this, as our provider has no work loop.\n\t *\n\t *  @return current workloop for request handling.\n\t */\n\tIOWorkLoop *getWorkLoop() const override {\n\t\treturn workLoop;\n\t}\n\n\t/**\n\t *  Request handling routine used for handling battery commands.\n\t *\n\t *  @param request request to handle\n\t *\n\t *  @return request handling result.\n\t */\n\tIOSMBusStatus startRequest(IOSMBusRequest *request) override;\n\n\t/**\n\t *  handle queued AppleSmartBatteryManager SMBus requests.\n\t */\n\tvoid handleBatteryCommandsEvent(IOInterruptEventSource *sender, int count);\n\t\n\t/**\n\t *  Holds value of batteriesConnected() when the previous notification was sent, must be guarded by stateLock\n\t *\n\t *  @return true on success\n\t */\n\tbool prevBatteriesConnected {false};\n\n\t/**\n\t *  Holds value of adaptersConnected() when the previous notification was sent, must be guarded by stateLock\n\t *\n\t *  @return true on success\n\t */\n\tbool prevAdaptersConnected {false};\n};\n\n#endif /* SurfaceSMBusController_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceButton/HIDReport.hpp",
    "content": "//\n//  HIDReport.hpp\n//  SurfaceButtonDriver\n//\n//  Copyright © 2019 Le Bao Hiep. All rights reserved.\n//\n\nclass __attribute__((packed)) keys final {\npublic:\n    keys(void) : keys_{} {}\n\n    const UInt8(&get_raw_value(void) const)[32] {\n        return keys_;\n    }\n\n    bool empty(void) const {\n        for (const auto& k : keys_) {\n            if (k != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    void clear(void) {\n        memset(keys_, 0, sizeof(keys_));\n    }\n\n    void insert(UInt8 key) {\n        if (!exists(key)) {\n            for (auto&& k : keys_) {\n                if (k == 0) {\n                    k = key;\n                    return;\n                }\n            }\n        }\n    }\n\n    void erase(UInt8 key) {\n        for (auto&& k : keys_) {\n            if (k == key) {\n                k = 0;\n            }\n        }\n    }\n\n    bool exists(UInt8 key) const {\n        for (const auto& k : keys_) {\n            if (k == key) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    size_t count(void) const {\n        size_t result = 0;\n        for (const auto& k : keys_) {\n            if (k) {\n                ++result;\n            }\n        }\n        return result;\n    }\n\n    bool operator==(const keys& other) const { return (memcmp(this, &other, sizeof(*this)) == 0); }\n    bool operator!=(const keys& other) const { return !(*this == other); }\n\nprivate:\n    UInt8 keys_[32];\n};\n\nclass __attribute__((packed)) consumer_input final {\npublic:\n    consumer_input(void) : report_id_(2) {}\n    bool operator==(const consumer_input& other) const { return (memcmp(this, &other, sizeof(*this)) == 0); }\n    bool operator!=(const consumer_input& other) const { return !(*this == other); }\n\nprivate:\n    UInt8 report_id_ __attribute__((unused));\n\npublic:\n    keys keys;\n};\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceButton/SurfaceButtonDevice.cpp",
    "content": "//\n//  SurfaceButtonDevice.cpp\n//  SurfaceButton\n//\n//  Copyright © 2018-2020 Le Bao Hiep. All rights reserved.\n//\n\n#include \"SurfaceButtonDevice.hpp\"\n\n#define super IOHIDDevice\nOSDefineMetaClassAndStructors(SurfaceButtonDevice, super);\n\nconst UInt8 virt_reportDescriptor[] = {\n    0x05, 0x0c,       // Usage Page (Consumer)\n    0x09, 0x01,       // Usage 1 (kHIDUsage_Csmr_ConsumerControl)\n    0xa1, 0x01,       // Collection (Application)\n    0x85, 0x02,       //   Report Id (2)\n    0x05, 0x0c,       //   Usage Page (Consumer)\n    0x95, 0x20,       //   Report Count............ (32)\n    0x75, 0x08,       //   Report Size............. (8)\n    0x15, 0x00,       //   Logical Minimum......... (0)\n    0x26, 0xff, 0x00, //   Logical Maximum......... (255)\n    0x19, 0x00,       //   Usage Minimum........... (0)\n    0x29, 0xff,       //   Usage Maximum........... (255)\n    0x81, 0x00,       //   Input...................(Data, Array, Absolute)\n    0xc0,             // End Collection\n};\n\nIOReturn SurfaceButtonDevice::simulateKeyboardEvent(UInt32 usagePage, UInt32 usage, bool status) {\n    IOReturn result = kIOReturnError;\n    \n    if (usagePage == kHIDPage_Consumer) {\n        if (status)\n            csmrreport.keys.insert(usage);\n        else\n            csmrreport.keys.erase(usage);\n        \n        if (auto buffer = IOBufferMemoryDescriptor::withBytes(&csmrreport, sizeof(csmrreport), kIODirectionNone)) {\n            result = handleReport(buffer, kIOHIDReportTypeInput, kIOHIDOptionsTypeNone);\n            OSSafeReleaseNULL(buffer);\n        }\n    } else\n        result = kIOReturnBadArgument;\n    \n    return result;\n}\n\nbool SurfaceButtonDevice::handleStart(IOService *provider) {\n    if (!super::handleStart(provider)) {\n        return false;\n    }\n\n    setProperty(\"Built-In\", kOSBooleanTrue);\n    setProperty(\"HIDDefaultBehavior\", kOSBooleanTrue);\n\n    return true;\n}\n\nIOReturn SurfaceButtonDevice::newReportDescriptor(IOMemoryDescriptor **descriptor) const {\n    *descriptor = IOBufferMemoryDescriptor::withBytes(virt_reportDescriptor, sizeof(virt_reportDescriptor), kIODirectionNone);\n    return kIOReturnSuccess;\n}\n\nOSString *SurfaceButtonDevice::newManufacturerString() const {\n    return OSString::withCString(\"Microsoft Inc.\");\n}\n\nOSString *SurfaceButtonDevice::newProductString() const {\n    return OSString::withCString(\"Surface Button HID Device\");\n}\n\nOSNumber *SurfaceButtonDevice::newVendorIDNumber() const {\n    return OSNumber::withNumber(0x5ac, 32);\n}\n\nOSNumber *SurfaceButtonDevice::newProductIDNumber() const {\n    return OSNumber::withNumber(0x276, 32);\n}\n\nOSNumber *SurfaceButtonDevice::newLocationIDNumber() const {\n    return OSNumber::withNumber(0x14400000, 32);\n}\n\nOSNumber *SurfaceButtonDevice::newCountryCodeNumber() const {\n    return OSNumber::withNumber(0x21, 32);\n}\n\nOSNumber *SurfaceButtonDevice::newVersionNumber() const {\n    return OSNumber::withNumber(0x895, 32);\n}\n\nOSNumber *SurfaceButtonDevice::newPrimaryUsagePageNumber() const {\n    return OSNumber::withNumber(kHIDPage_Consumer, 32);\n}\n\nOSNumber *SurfaceButtonDevice::newPrimaryUsageNumber() const {\n    return OSNumber::withNumber(kHIDUsage_Csmr_ConsumerControl, 32);\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceButton/SurfaceButtonDevice.hpp",
    "content": "//\n//  SurfaceButtonDevice.hpp\n//  SurfaceButton\n//\n//  Copyright © 2018-2020 Le Bao Hiep. All rights reserved.\n//\n\n#include <IOKit/hid/IOHIDDevice.h>\n\n#include \"HIDReport.hpp\"\n\nclass SurfaceButtonDevice final : public IOHIDDevice {\n    OSDeclareDefaultStructors(SurfaceButtonDevice);\nprivate:\n    consumer_input csmrreport;\n\npublic:\n    IOReturn simulateKeyboardEvent(UInt32 usagePage, UInt32 usage, bool status);\n    \n    bool handleStart(IOService *provider) override;\n\n    IOReturn newReportDescriptor(IOMemoryDescriptor **descriptor) const override;\n\n    OSString *newManufacturerString() const override;\n    OSString *newProductString() const override;\n    OSNumber *newVendorIDNumber() const override;\n    OSNumber *newProductIDNumber() const override;\n    OSNumber *newLocationIDNumber() const override;\n    OSNumber *newCountryCodeNumber() const override;\n    OSNumber *newVersionNumber() const override;\n    OSNumber *newPrimaryUsagePageNumber() const override;\n    OSNumber *newPrimaryUsageNumber() const override;\n};\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceButton/SurfaceButtonDriver.cpp",
    "content": "//\n//  SurfaceButtonDriver.hpp\n//  SurfaceButton\n//\n//  Created by Xavier on 22/03/2021.\n//  Copyright © 2021 Xia Shangning. All rights reserved.\n//\n\n#include \"SurfaceButtonDriver.hpp\"\n\n#define super IOService\nOSDefineMetaClassAndStructors(SurfaceButtonDriver, IOService)\n\nVoodooGPIO* SurfaceButtonDriver::getGPIOController() {\n    VoodooGPIO* gpio_controller = NULL;\n\n    // Wait for GPIO controller, up to 1 second\n    OSDictionary* name_match = serviceMatching(\"VoodooGPIO\");\n    IOService* matched = waitForMatchingService(name_match, 1000000000);\n    gpio_controller = OSDynamicCast(VoodooGPIO, matched);\n    if (gpio_controller != NULL)\n        DBG_LOG(\"Got GPIO Controller! %s\", gpio_controller->getName());\n    OSSafeReleaseNULL(name_match);\n    OSSafeReleaseNULL(matched);\n\n    return gpio_controller;\n}\n\nIOReturn SurfaceButtonDriver::parseButtonResources(VoodooACPIResourcesParser* parser1, VoodooACPIResourcesParser* parser2, VoodooACPIResourcesParser* parser3) {\n    OSObject *result = nullptr;\n    OSData *data = nullptr;\n    if (acpi_device->evaluateObject(\"_CRS\", &result) != kIOReturnSuccess ||\n        !(data = OSDynamicCast(OSData, result))) {\n        LOG(\"Could not find or evaluate _CRS method\");\n        OSSafeReleaseNULL(result);\n        return kIOReturnNotFound;\n    }\n\n    // There are three GPIO buttons so the CRS function returns in total 6 resources, GpioInt & GpioIo for each\n    UInt8 const* crs = reinterpret_cast<UInt8 const*>(data->getBytesNoCopy());\n    unsigned int length = data->getLength();\n    UInt32 offset =  parser1->parseACPIResources(crs, 0, length);\n    offset = parser2->parseACPIResources(crs, offset, length);\n    parser3->parseACPIResources(crs, offset, length);\n\n    OSSafeReleaseNULL(data);\n\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceButtonDriver::getDeviceResources() {\n    VoodooACPIResourcesParser parser1, parser2, parser3;\n    \n    parseButtonResources(&parser1, &parser2, &parser3);\n\n    if (parser1.found_gpio_interrupts && parser2.found_gpio_interrupts && parser3.found_gpio_interrupts) {\n        DBG_LOG(\"Found valid GPIO interrupts\");\n\n        // Power Button, Volume Up Button, Volume Down Button\n        setProperty(\"powerBtnGPIOPin\", parser1.gpio_interrupts.pin_number, 16);\n        setProperty(\"powerBtnGPIOIRQ\", parser1.gpio_interrupts.irq_type, 16);\n\n        gpio_pin[POWER_BUTTON_IDX] = parser1.gpio_interrupts.pin_number;\n        gpio_irq[POWER_BUTTON_IDX] = parser1.gpio_interrupts.irq_type;\n        \n        setProperty(\"volUpBtnGPIOPin\", parser2.gpio_interrupts.pin_number, 16);\n        setProperty(\"volUpBtnGPIOIRQ\", parser2.gpio_interrupts.irq_type, 16);\n\n        gpio_pin[VOLUME_UP_BUTTON_IDX] = parser2.gpio_interrupts.pin_number;\n        gpio_irq[VOLUME_UP_BUTTON_IDX] = parser2.gpio_interrupts.irq_type;\n        \n        setProperty(\"volDownBtnGPIOPin\", parser3.gpio_interrupts.pin_number, 16);\n        setProperty(\"volDownBtnGPIOIRQ\", parser3.gpio_interrupts.irq_type, 16);\n\n        gpio_pin[VOLUME_DOWN_BUTTON_IDX] = parser3.gpio_interrupts.pin_number;\n        gpio_irq[VOLUME_DOWN_BUTTON_IDX] = parser3.gpio_interrupts.irq_type;\n        \n        return kIOReturnSuccess;\n    }else{\n        LOG(\"GPIO interrupts missing!\");\n        return kIOReturnError;\n    }\n}\n\nvoid SurfaceButtonDriver::powerInterruptOccured(IOInterruptEventSource* src, int intCount) {\n    response(POWER_BUTTON_IDX, intCount % 2);\n}\n\nvoid SurfaceButtonDriver::volumeUpInterruptOccured(IOInterruptEventSource* src, int intCount) {\n    if (!awake)\n        return;\n    stopInterrupt(VOLUME_DOWN_BUTTON_IDX);\n    bool button_status = gpio_controller->getPinStatus(gpio_pin[VOLUME_UP_BUTTON_IDX]);\n    response(VOLUME_UP_BUTTON_IDX, button_status);\n    startInterrupt(VOLUME_DOWN_BUTTON_IDX);\n}\n\nvoid SurfaceButtonDriver::volumeDownInterruptOccured(IOInterruptEventSource* src, int intCount) {\n    if (!awake)\n        return;\n    stopInterrupt(VOLUME_UP_BUTTON_IDX);\n    bool button_status = gpio_controller->getPinStatus(gpio_pin[VOLUME_DOWN_BUTTON_IDX]);\n    response(VOLUME_DOWN_BUTTON_IDX, button_status);\n    startInterrupt(VOLUME_UP_BUTTON_IDX);\n}\n\nvoid SurfaceButtonDriver::response(int btn_idx, bool status) {\n    if (btn_idx >= BTN_CNT)\n        return;\n    \n    if (btn_idx == POWER_BUTTON_IDX) {\n        // mannually maintain the power button status(pin status always return true)\n        if (status)\n            btn_status[btn_idx] = !btn_status[btn_idx];\n    } else\n        btn_status[btn_idx] = status;\n    DBG_LOG(\"%s %s!\", BTN_DESCRIPTION[btn_idx], btn_status[btn_idx]?\"pressed\":\"released\");\n    button_device->simulateKeyboardEvent(BTN_CMD_PAGE[btn_idx], BTN_CMD[btn_idx], btn_status[btn_idx]);\n}\n\nIOService *SurfaceButtonDriver::probe(IOService *provider, SInt32 *score){\n    if (!super::probe(provider, score))\n        return nullptr;\n    \n    acpi_device = OSDynamicCast(IOACPIPlatformDevice, provider);\n    if (!acpi_device)\n        return nullptr;\n    \n    if (getDeviceResources() != kIOReturnSuccess) {\n        LOG(\"Could not parse GPIO infos\");\n        return nullptr;\n    }\n    \n    gpio_controller = getGPIOController();\n    if (!gpio_controller) {\n        LOG(\"Could not find GPIO controller, exiting\");\n        return nullptr;\n    }\n    // Give the GPIO controller some time to load\n    IOSleep(100);\n    \n    LOG(\"Surface ACPI button device found!\");\n    \n    return this;\n}\n\nbool SurfaceButtonDriver::start(IOService *provider) {\n    if (!super::start(provider))\n        return false;\n\n    work_loop = IOWorkLoop::workLoop();\n    if (!work_loop) {\n        LOG(\"Could not get work loop\");\n        goto exit;\n    }\n    interrupt_source[POWER_BUTTON_IDX] = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceButtonDriver::powerInterruptOccured), this, POWER_BUTTON_IDX);\n    interrupt_source[VOLUME_UP_BUTTON_IDX] = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceButtonDriver::volumeUpInterruptOccured), this, VOLUME_UP_BUTTON_IDX);\n    interrupt_source[VOLUME_DOWN_BUTTON_IDX] = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceButtonDriver::volumeDownInterruptOccured), this, VOLUME_DOWN_BUTTON_IDX);\n    if (!interrupt_source[POWER_BUTTON_IDX] || !interrupt_source[VOLUME_UP_BUTTON_IDX] || !interrupt_source[VOLUME_DOWN_BUTTON_IDX]) {\n        LOG(\"Could not create interrupt event source\");\n        goto exit;\n    }\n    work_loop->addEventSource(interrupt_source[POWER_BUTTON_IDX]);\n    work_loop->addEventSource(interrupt_source[VOLUME_UP_BUTTON_IDX]);\n    work_loop->addEventSource(interrupt_source[VOLUME_DOWN_BUTTON_IDX]);\n    \n    button_device = OSTypeAlloc(SurfaceButtonDevice);\n    if (!button_device || !button_device->init() || !button_device->attach(this) || !button_device->start(this)) {\n        LOG(\"Failed to init and start Surface Button HID Device!\");\n        goto exit;\n    }\n    \n    PMinit();\n    acpi_device->joinPMtree(this);\n    registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);\n    \n    return true;\nexit:\n    releaseResources();\n    return false;\n}\n\nvoid SurfaceButtonDriver::stop(IOService *provider) {\n    PMstop();\n    releaseResources();\n    super::stop(provider);\n}\n\nIOReturn SurfaceButtonDriver::setPowerState(unsigned long whichState, IOService *whatDevice) {\n    if (whatDevice != this)\n        return kIOReturnInvalid;\n    if (whichState == 0) {\n        if (awake) {\n            stopInterrupt(POWER_BUTTON_IDX);\n            stopInterrupt(VOLUME_UP_BUTTON_IDX);\n            stopInterrupt(VOLUME_DOWN_BUTTON_IDX);\n            DBG_LOG(\"Going to sleep\");\n            awake = false;\n        }\n    } else {\n        if (!awake) {\n            awake = true;\n            IOSleep(100);   // Wait for SSH to notify d0-entry and display-on\n            startInterrupt(POWER_BUTTON_IDX);\n            startInterrupt(VOLUME_UP_BUTTON_IDX);\n            startInterrupt(VOLUME_DOWN_BUTTON_IDX);\n            DBG_LOG(\"Woke up\");\n        }\n    }\n    return kIOPMAckImplied;\n}\n\nIOReturn SurfaceButtonDriver::enableInterrupt(int source) {\n    return gpio_controller->enableInterrupt(gpio_pin[source]);\n}\n\nIOReturn SurfaceButtonDriver::disableInterrupt(int source) {\n    return gpio_controller->disableInterrupt(gpio_pin[source]);\n}\n\nIOReturn SurfaceButtonDriver::getInterruptType(int source, int* interrupt_type) {\n    return gpio_controller->getInterruptType(gpio_pin[source], interrupt_type);\n}\n\nIOReturn SurfaceButtonDriver::registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refcon) {\n    gpio_controller->setInterruptTypeForPin(gpio_pin[source], gpio_irq[source]);\n    return gpio_controller->registerInterrupt(gpio_pin[source], target, handler, refcon);\n}\n\nIOReturn SurfaceButtonDriver::unregisterInterrupt(int source) {\n    return gpio_controller->unregisterInterrupt(gpio_pin[source]);\n}\n\nvoid SurfaceButtonDriver::startInterrupt(int source) {\n    if (is_interrupt_started[source])\n        return;\n\n    interrupt_source[source]->enable();\n    is_interrupt_started[source] = true;\n}\n\nvoid SurfaceButtonDriver::stopInterrupt(int source) {\n    if (!is_interrupt_started[source])\n        return;\n\n    interrupt_source[source]->disable();\n    is_interrupt_started[source] = false;\n}\n\nvoid SurfaceButtonDriver::releaseResources() {\n    if (interrupt_source[POWER_BUTTON_IDX]) {\n        stopInterrupt(POWER_BUTTON_IDX);\n        work_loop->removeEventSource(interrupt_source[POWER_BUTTON_IDX]);\n        OSSafeReleaseNULL(interrupt_source[POWER_BUTTON_IDX]);\n    }\n    if (interrupt_source[VOLUME_UP_BUTTON_IDX]) {\n        stopInterrupt(VOLUME_UP_BUTTON_IDX);\n        work_loop->removeEventSource(interrupt_source[VOLUME_UP_BUTTON_IDX]);\n        OSSafeReleaseNULL(interrupt_source[VOLUME_UP_BUTTON_IDX]);\n    }\n    if (interrupt_source[VOLUME_DOWN_BUTTON_IDX]) {\n        stopInterrupt(VOLUME_DOWN_BUTTON_IDX);\n        work_loop->removeEventSource(interrupt_source[VOLUME_DOWN_BUTTON_IDX]);\n        OSSafeReleaseNULL(interrupt_source[VOLUME_DOWN_BUTTON_IDX]);\n    }\n    OSSafeReleaseNULL(work_loop);\n    \n    OSSafeReleaseNULL(button_device);\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceButton/SurfaceButtonDriver.hpp",
    "content": "//\n//  SurfaceButtonDriver.hpp\n//  SurfaceButton\n//\n//  Created by Xavier on 22/03/2021.\n//  Copyright © 2021 Xia Shangning. All rights reserved.\n//\n\n#ifndef SurfaceButtonDriver_hpp\n#define SurfaceButtonDriver_hpp\n\n#include <IOKit/acpi/IOACPIPlatformDevice.h>\n\n#include \"../../../Dependencies/VoodooGPIO/VoodooGPIO/VoodooGPIO.hpp\"\n#include \"../../../Dependencies/VoodooSerial/VoodooSerial/ACPIParser/VoodooACPIResourcesParser.hpp\"\n#include \"../helpers.hpp\"\n#include \"SurfaceButtonDevice.hpp\"\n\n#define BTN_CNT 3\n\n#define POWER_BUTTON_IDX        0\n#define VOLUME_UP_BUTTON_IDX    1\n#define VOLUME_DOWN_BUTTON_IDX  2\n\nconst char *BTN_DESCRIPTION[BTN_CNT] = {\"Power Button\", \"Volume Up Button\", \"Volume Down Button\"};\nconst UInt32 BTN_CMD[BTN_CNT] = {kHIDUsage_Csmr_Power, kHIDUsage_Csmr_VolumeIncrement, kHIDUsage_Csmr_VolumeDecrement};\nconst UInt32 BTN_CMD_PAGE[BTN_CNT] = {kHIDPage_Consumer, kHIDPage_Consumer, kHIDPage_Consumer};\n\nclass EXPORT SurfaceButtonDriver : public IOService {\n    OSDeclareDefaultStructors(SurfaceButtonDriver);\n    \nprivate:\n    IOWorkLoop*             work_loop {nullptr};\n    VoodooGPIO*             gpio_controller {nullptr};\n    IOInterruptEventSource* interrupt_source[BTN_CNT] = {nullptr, nullptr, nullptr};\n    IOACPIPlatformDevice*   acpi_device {nullptr};\n    SurfaceButtonDevice*    button_device {nullptr};\n    \n    bool    is_interrupt_started[BTN_CNT] = {false, false, false};\n    bool    btn_status[BTN_CNT] = {false, false, false};\n    int     gpio_irq[BTN_CNT] = {0,0,0};\n    UInt16  gpio_pin[BTN_CNT] = {0,0,0};\n    bool    awake {false};    \n    \n    void startInterrupt(int source);\n    \n    void stopInterrupt(int source);\n    \n    void releaseResources();\n    \n    IOReturn getDeviceResources();\n    \n    IOReturn parseButtonResources(VoodooACPIResourcesParser* parser1, VoodooACPIResourcesParser* parser2, VoodooACPIResourcesParser* parser3);\n    \n    VoodooGPIO* getGPIOController();\n    \n    void powerInterruptOccured(IOInterruptEventSource* src, int intCount);\n    \n    void volumeUpInterruptOccured(IOInterruptEventSource* src, int intCount);\n    \n    void volumeDownInterruptOccured(IOInterruptEventSource* src, int intCount);\n    \n    void response(int btn_idx, bool status);\n    \npublic:\n    IOReturn enableInterrupt(int source) override;\n    \n    IOReturn disableInterrupt(int source) override;\n\n    IOReturn getInterruptType(int source, int *interruptType) override;\n    \n    IOReturn registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refcon) override;\n    \n    IOReturn unregisterInterrupt(int source) override;\n    \n    IOService* probe(IOService* provider, SInt32* score) override;\n    \n    bool start(IOService* provider) override;\n    \n    void stop(IOService* provider) override;\n    \n    IOReturn setPowerState(unsigned long whichState, IOService *whatDevice) override;\n};\n\n#endif\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceManagementEngine/MEIProtocol.h",
    "content": "//\n//  MEIProtocol.h\n//  SurfaceTouchScreen\n//\n//  Created by Xavier on 2022/5/29.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#ifndef MEIProtocol_h\n#define MEIProtocol_h\n\n#include \"../helpers.hpp\"\n\n/*\n * IPTS MEI constants and communication protocol ported from linux\n */\n\n/* Host Firmware Status Registers in PCI Config Space */\n#define MEI_PCI_CFG_1           0x40\n#define MEI_PCI_CFG_1_D0I3      0x80000000\n\n/* MEI registers */\n#define MEI_H_CB_WW    0x00     /* Host Circular Buffer Write Window register */\n#define MEI_H_CSR      0x04     /* Host Control Status register */\n#define MEI_ME_CB_RW   0x08     /* ME Circular Buffer Read Window register */\n#define MEI_ME_CSR     0x0C     /* ME Control Status Host Access register */\n#define MEI_H_PG_CSR   0x10     /* Host Power Gate Control Status register */\n#define MEI_H_D0I3C    0x800    /* Host D0I3 Control  */\n\n/* Control Status register bits for Host and ME */\n#define MEI_CSR_BUF_DEPTH         0xFF000000    /* Circular Buffer Depth */\n#define MEI_CSR_BUF_WPOINTER      0x00FF0000    /* Circular Buffer Write Pointer */\n#define MEI_CSR_BUF_RPOINTER      0x0000FF00    /* Circular Buffer Read Pointer */\n\n/* Host Control Status register bits */\n#define MEI_H_CSR_INT_ENABLE        BIT(0)    /* Interrupt Enable */\n#define MEI_H_CSR_INT_STA           BIT(1)    /* Interrupt Status */\n#define MEI_H_CSR_INT_GEN           BIT(2)    /* Interrupt Generate */\n#define MEI_H_CSR_READY             BIT(3)    /* Ready */\n#define MEI_H_CSR_RESET             BIT(4)    /* Reset */\n#define MEI_H_CSR_D0I3C_INT_ENABLE  BIT(5)    /* D0I3 Interrupt Enable */\n#define MEI_H_CSR_D0I3C_INT_STA     BIT(6)    /* D0I3 Interrupt Status */\n#define MEI_H_CSR_INT_ENABLE_MASK   (MEI_H_CSR_INT_ENABLE | MEI_H_CSR_D0I3C_INT_ENABLE)\n#define MEI_H_CSR_INT_STA_MASK      (MEI_H_CSR_INT_STA | MEI_H_CSR_D0I3C_INT_STA)\n\n/* ME Control Status Host Access register bits */\n#define MEI_ME_CSR_INT_ENABLE           BIT(0)    /* Interrupt Enable */\n#define MEI_ME_CSR_INT_STA              BIT(1)    /* Interrupt Status */\n#define MEI_ME_CSR_INT_GEN              BIT(2)    /* Interrupt Generate */\n#define MEI_ME_CSR_READY                BIT(3)    /* Ready */\n#define MEI_ME_CSR_RESET                BIT(4)    /* Reset */\n#define MEI_ME_CSR_POWER_GATE_ISO_CAP   BIT(6)    /* Power Gate Isolation Capability */\n\n/* Host Power Gate Control Status register bits */\n#define MEI_H_HPG_CSR_POWER_GATING_EXIT     BIT(0)\n#define MEI_H_HPG_CSR_POWER_GATING_ENTER    BIT(1)\n\n/* Host D0I3C register bits */\n#define MEI_H_D0I3C_CIP         BIT(0)\n#define MEI_H_D0I3C_IR          BIT(1)\n#define MEI_H_D0I3C_I3          BIT(2)\n#define MEI_H_D0I3C_RR          BIT(3)\n\n#define MEI_SLOT_SIZE               sizeof(UInt32)\n#define MEI_SLOT_TYPE               UInt32\n#define MEI_RX_MSG_BUF_SIZE         (128 * MEI_SLOT_SIZE)\n#define MEI_DATA_TO_SLOTS(len)      (((len)+MEI_SLOT_SIZE-1)/MEI_SLOT_SIZE)\n#define MEI_SLOTS_TO_DATA(slots)    ((slots) * MEI_SLOT_SIZE)\n\n#define MEI_MAX_CLIENT_NUM      256     /* SHOULD be dividable by 8 */\n#define MEI_MAX_CONSEC_RESET    3\n\n#ifndef PACKED\n#define PACKED __attribute__((packed))\n#endif\n\n/* Timeouts in Seconds */\n#define MEI_HW_READY_TIMEOUT            2  /* Timeout on ready message */\n#define MEI_CONNECT_TIMEOUT             3  /* HPS: at least 2 seconds */\n\n#define MEI_CLIENT_CONNECT_TIMEOUT      15  /* HPS: Client Connect Timeout */\n#define MEI_CLIENTS_INIT_TIMEOUT        15  /* HPS: Clients Enumeration Timeout */\n\n#define MEI_POWER_GATING_ISO_TIMEOUT    1  /* PG Isolation time response 1 sec */\n#define MEI_D0I3_TIMEOUT                5  /* D0i3 set/unset max response time */\n#define MEI_HOST_BUS_MSG_TIMEOUT        1  /* 1 second */\n\n#define MEI_DEVICE_IDLE_TIMEOUT         5\n\n#define MEI_CLIENT_SEND_MSG_TIMEOUT     500 /* 500 ms*/\n\n/*\n * MEI Version\n */\n#define MEI_HBM_MINOR_VERSION               2\n#define MEI_HBM_MAJOR_VERSION               2\n/*\n * MEI version with PGI support\n */\n#define MEI_HBM_MINOR_VERSION_PGI           1\n#define MEI_HBM_MAJOR_VERSION_PGI           1\n/*\n * MEI version with Dynamic clients support\n */\n#define MEI_HBM_MINOR_VERSION_DC            0\n#define MEI_HBM_MAJOR_VERSION_DC            2\n/*\n * MEI version with immediate reply to enum request support\n */\n#define MEI_HBM_MINOR_VERSION_IE            0\n#define MEI_HBM_MAJOR_VERSION_IE            2\n/*\n * MEI version with disconnect on connection timeout support\n */\n#define MEI_HBM_MINOR_VERSION_DOT           0\n#define MEI_HBM_MAJOR_VERSION_DOT           2\n/*\n * MEI version with notification support\n */\n#define MEI_HBM_MINOR_VERSION_EV            0\n#define MEI_HBM_MAJOR_VERSION_EV            2\n/*\n * MEI version with fixed address client support\n */\n#define MEI_HBM_MINOR_VERSION_FA            0\n#define MEI_HBM_MAJOR_VERSION_FA            2\n/*\n * MEI version with OS ver message support\n */\n#define MEI_HBM_MINOR_VERSION_OS            0\n#define MEI_HBM_MAJOR_VERSION_OS            2\n/*\n * MEI version with dma ring support\n */\n#define MEI_HBM_MINOR_VERSION_DR            1\n#define MEI_HBM_MAJOR_VERSION_DR            2\n/*\n * MEI version with vm tag support\n */\n#define MEI_HBM_MINOR_VERSION_VT            2\n#define MEI_HBM_MAJOR_VERSION_VT            2\n/*\n * MEI version with capabilities message support\n */\n#define MEI_HBM_MINOR_VERSION_CAP           2\n#define MEI_HBM_MAJOR_VERSION_CAP           2\n/*\n * MEI version with client DMA support\n */\n#define MEI_HBM_MINOR_VERSION_CD            2\n#define MEI_HBM_MAJOR_VERSION_CD            2\n\n/* Host bus message command opcode */\n#define MEI_HBM_CMD_OP_MSK                  0x7f\n/* Host bus message command RESPONSE */\n#define MEI_HBM_CMD_RES_MSK                 0x80\n\n/*\n * MEI Bus Message Command IDs\n */\n#define MEI_HOST_START_REQ_CMD              0x01\n#define MEI_HOST_START_RES_CMD              0x81\n\n#define MEI_HOST_STOP_REQ_CMD               0x02\n#define MEI_HOST_STOP_RES_CMD               0x82\n\n#define MEI_ME_STOP_REQ_CMD                 0x03\n\n#define MEI_HOST_ENUM_REQ_CMD               0x04\n#define MEI_HOST_ENUM_RES_CMD               0x84\n\n#define MEI_HOST_CLIENT_PROP_REQ_CMD        0x05\n#define MEI_HOST_CLIENT_PROP_RES_CMD        0x85\n\n#define MEI_CLIENT_CONNECT_REQ_CMD          0x06\n#define MEI_CLIENT_CONNECT_RES_CMD          0x86\n\n#define MEI_CLIENT_DISCONNECT_REQ_CMD       0x07\n#define MEI_CLIENT_DISCONNECT_RES_CMD       0x87\n\n#define MEI_FLOW_CONTROL_CMD                0x08\n\n#define MEI_PG_ISOLATION_ENTRY_REQ_CMD      0x0a\n#define MEI_PG_ISOLATION_ENTRY_RES_CMD      0x8a\n#define MEI_PG_ISOLATION_EXIT_REQ_CMD       0x0b\n#define MEI_PG_ISOLATION_EXIT_RES_CMD       0x8b\n\n#define MEI_ADD_CLIENT_REQ_CMD              0x0f\n#define MEI_ADD_CLIENT_RES_CMD              0x8f\n\n#define MEI_NOTIFY_REQ_CMD                  0x10\n#define MEI_NOTIFY_RES_CMD                  0x90\n#define MEI_NOTIFICATION_CMD                0x11\n\n#define MEI_DMA_SETUP_REQ_CMD               0x12\n#define MEI_DMA_SETUP_RES_CMD               0x92\n\n#define MEI_CAPABILITIES_REQ_CMD            0x13\n#define MEI_CAPABILITIES_RES_CMD            0x93\n\n#define MEI_CLIENT_DMA_MAP_REQ_CMD          0x14\n#define MEI_CLIENT_DMA_MAP_RES_CMD          0x94\n\n#define MEI_CLIENT_DMA_UNMAP_REQ_CMD        0x15\n#define MEI_CLIENT_DMA_UNMAP_RES_CMD        0x95\n\nenum MEIHostBusMessageReturnType : UInt8 {\n    MEIHostBusMessageReturnSuccess        = 0,\n    MEIHostBusMessageReturnClientNotFound = 1,\n    MEIHostBusMessageReturnAlreadyExists  = 2,  /* connection already established */\n    MEIHostBusMessageReturnRejected       = 3,  /* connection is rejected */\n    MEIHostBusMessageReturnInvalidParam   = 4,\n    MEIHostBusMessageReturnNotAllowed     = 5,\n    MEIHostBusMessageReturnAlreadyStarted = 6,  /* system is already started */\n    MEIHostBusMessageReturnNotStarted     = 7,  /* system not started */\n    MEIHostBusMessageReturnTypeLength,\n};\n\nenum MEIExtendedHeaderType : UInt8 {\n    MEIExtendedHeaderNone = 0,\n    MEIExtendedHeaderVtag = 1,\n};\n\n/**\n * struct MEIExtendedHeaderDescriptor - extend header descriptor (TLV)\n * @type: header type\n * @length: header length excluding descriptor SHOULD BE 1\n * @data: payload data\n */\nstruct PACKED MEIBusExtendedHeader {\n    MEIExtendedHeaderType type;\n    UInt8 length;\n    UInt8 data[2];\n};\n\n#define MEI_EXTHEADER_DATA_VTAG_IDX  0\n\n/**\n * struct MEIExtendedMetaHeader - extend header meta data\n * @count: number of headers\n * @size: total slot count of the extended header list excluding meta header\n * @reserved: reserved\n * @hdrs: extended headers TLV list\n */\nstruct PACKED MEIBusExtendedMetaHeader {\n    UInt8 count;\n    UInt8 size;\n    UInt8 reserved[2];\n    UInt8 hdrs[];\n};\n\n/*\n * Extended header iterator functions\n */\nstatic inline MEIBusExtendedHeader *mei_ext_begin(MEIBusExtendedMetaHeader *meta)\n{\n    return reinterpret_cast<MEIBusExtendedHeader *>(meta->hdrs);\n}\n\n/**\n * mei_ext_last - check if the ext is the last one in the TLV list\n *\n * @meta: meta header of the extended header list\n * @hdr: a meta header on the list\n *\n * Return: true if ext is the last header on the list\n */\nstatic inline bool mei_ext_last(MEIBusExtendedMetaHeader *meta, MEIBusExtendedHeader *hdr)\n{\n    return reinterpret_cast<UInt8 *>(hdr) >= reinterpret_cast<UInt8 *>(meta) + sizeof(MEIBusExtendedMetaHeader) + MEI_SLOTS_TO_DATA(meta->size);\n}\n\n/**\n * struct MEIMessageHeader - MEI Bus Interface Section size=4\n *\n * @me_addr: device address\n * @host_addr: host address\n * @length: message length\n * @reserved: reserved\n * @extended: message has extended header\n * @dma_ring: message is on dma ring\n * @internal: message is internal\n * @msg_complete: last packet of the message\n * @extension: extension of the header\n */\nstruct PACKED MEIBusMessageHeader {\n    UInt32 me_addr:8;\n    UInt32 host_addr:8;\n    UInt32 length:9;\n    UInt32 reserved:3;\n    UInt32 extended:1;\n    UInt32 dma_ring:1;\n    UInt32 internal:1;\n    UInt32 msg_complete:1;\n    UInt32 extension[];\n};\n\n/* The length is up to 9 bits */\n#define MEI_MSG_MAX_LEN_MASK GENMASK(9, 0)\n\n/**\n * struct MEIBusMessage - Generic MEI bus message\n *\n * @cmd: bus message command ID\n * @data: generic data\n */\nstruct PACKED MEIBusMessage {\n    UInt8 cmd;\n    UInt8 data[];\n};\n\n#define MEI_TO_MSG(specific_msg)    (reinterpret_cast<MEIBusMessage *>(specific_msg))\n\nstruct PACKED MEIBusGenericMessage {\n    UInt8 cmd;\n    UInt8 reserved[3];\n};\n\ntypedef MEIBusGenericMessage MEIBusPowerGatingRequest;\ntypedef MEIBusGenericMessage MEIBusPowerGatingResponse;\n\nstruct PACKED MEIBusHostVersionRequest {\n    UInt8 cmd;\n    UInt8 reserved;\n    UInt8 host_version_minor;\n    UInt8 host_version_major;\n};\n\nstruct PACKED MEIBusHostVersionResponse {\n    UInt8 cmd;\n    UInt8 host_version_supported;\n    UInt8 me_max_version_minor;\n    UInt8 me_max_version_major;\n};\n\nenum MEIStopReason : UInt8 {\n    DriverStopRequest = 0x00,\n    DeviceD1Entry     = 0x01,\n    DeviceD2Entry     = 0x02,\n    DeviceD3Entry     = 0x03,\n    SystemS1Entry     = 0x04,\n    SystemS2Entry     = 0x05,\n    SystemS3Entry     = 0x06,\n    SystemS4Entry     = 0x07,\n    SystemS5Entry     = 0x08,\n};\n\nstruct PACKED MEIBusHostStopRequest {\n    UInt8 cmd;\n    MEIStopReason reason;\n    UInt8 reserved[2];\n};\n\nstruct PACKED MEIBusHostStopResponse {\n    UInt8 cmd;\n    UInt8 reserved[3];\n};\n\nstruct PACKED MEIBusMEStopRequest {\n    UInt8 cmd;\n    MEIStopReason reason;\n    UInt8 reserved[2];\n};\n\n/**\n * @MEI_HBM_ENUM_ALLOW_ADD_FLAG: allow dynamic clients add\n * @MEI_HBM_ENUM_IMMEDIATE_FLAG: allow FW to send answer immediately\n */\n#define MEI_HBM_ENUM_ALLOW_ADD_FLAG     BIT(0)\n#define MEI_HBM_ENUM_IMMEDIATE_FLAG     BIT(1)\n\nstruct PACKED MEIBusHostEnumerationRequest {\n    UInt8 cmd;\n    UInt8 flags;\n    UInt8 reserved[2];\n};\n\nstruct PACKED MEIBusHostEnumerationResponse {\n    UInt8 cmd;\n    UInt8 reserved[3];\n    UInt8 valid_addresses[MEI_MAX_CLIENT_NUM/8];\n};\n\n/**\n * struct MEIClientProperty - mei client properties\n *\n * @uuid: guid of the client\n * @protocol_version: client protocol version\n * @max_connection_num: number of possible connections. 0: fixed clients\n * @fixed_address: fixed me address (0 if the client is dynamic)\n * @single_recv_buf: 1 if all connections share a single receive buffer.\n * @vt_supported: the client support vtag\n * @reserved: reserved\n * @max_msg_length: MTU of the client\n */\nstruct PACKED MEIClientProperty {\n    uuid_t uuid;\n    UInt8  protocol_version;\n    UInt8  max_connection_num;\n    UInt8  fixed_address;\n    UInt8  single_recv_buf:1;\n    UInt8  vt_supported:1;\n    UInt8  reserved:6;\n    UInt32 max_msg_length;\n};\n\nstruct PACKED MEIBusClientPropertyRequest {\n    UInt8 cmd;\n    UInt8 me_addr;\n    UInt8 reserved[2];\n};\n\nstruct PACKED MEIBusClientPropertyResponse {\n    UInt8 cmd;\n    UInt8 me_addr;\n    MEIHostBusMessageReturnType status;\n    UInt8 reserved;\n    MEIClientProperty client_properties;\n};\n\n/**\n * struct MEIBusAddClientRequest - request to add a client\n *     might be sent by fw after enumeration has already completed\n *\n * @cmd: bus message command ID\n * @me_addr: address of the client in ME\n * @reserved: reserved\n * @client_properties: client properties\n */\nstruct PACKED MEIBusAddClientRequest {\n    UInt8 cmd;\n    UInt8 me_addr;\n    UInt8 reserved[2];\n    MEIClientProperty client_properties;\n};\n\n/**\n * struct MEIBusAddClientResponse - response to add a client\n *     sent by the host to report client addition status to fw\n *\n * @cmd: bus message command ID\n * @me_addr: address of the client in ME\n * @status: if MEIHostBusMessageReturnSuccess then the client can now accept connections.\n * @reserved: reserved\n */\nstruct PACKED MEIBusAddClientResponse {\n    UInt8 cmd;\n    UInt8 me_addr;\n    MEIHostBusMessageReturnType status;\n    UInt8 reserved;\n};\n\n/**\n * struct MEIBusClientCommand - client specific host bus command\n *    CONNECT, DISCONNECT, FlOW CONTROL, NOTIFICATION\n *\n * @cmd: bus message command ID\n * @me_addr: address of the client in ME\n * @host_addr: address of the client in the driver\n * @data: generic data\n */\nstruct PACKED MEIBusClientCommand {\n    UInt8 cmd;\n    UInt8 me_addr;\n    UInt8 host_addr;\n    UInt8 data;\n};\n\ntypedef MEIBusClientCommand MEIBusClientConnectionRequest;\n\nenum MEIClientConnectionStatus : UInt8 {\n    MEIClientConnectionSuccess         = MEIHostBusMessageReturnSuccess,\n    MEIClientConnectionNotFound        = MEIHostBusMessageReturnClientNotFound,\n    MEIClientConnectionAlreadyStarted  = MEIHostBusMessageReturnAlreadyExists,\n    MEIClientConnectionOutOfResources  = MEIHostBusMessageReturnRejected,\n    MEIClientConnectionMessageTooSmall = MEIHostBusMessageReturnInvalidParam,\n    MEIClientConnectionNotAllowed      = MEIHostBusMessageReturnNotAllowed,\n};\n\n/**\n * struct MEIBusClientConnectionResponse - connect/disconnect response\n *\n * @cmd: bus message command header\n * @me_addr: address of the client in ME\n * @host_addr: address of the client in the driver\n * @status: status of the request\n */\nstruct PACKED MEIBusClientConnectionResponse {\n    UInt8 cmd;\n    UInt8 me_addr;\n    UInt8 host_addr;\n    MEIClientConnectionStatus status;\n};\n\n#define MEI_FLOW_CONTROL_MSG_RESERVED_LEN   5\n\nstruct PACKED MEIBusFlowControl {\n    UInt8 cmd;\n    UInt8 me_addr;\n    UInt8 host_addr;\n    UInt8 reserved[MEI_FLOW_CONTROL_MSG_RESERVED_LEN];\n};\n\n#define MEI_HBM_NOTIFICATION_START 1\n#define MEI_HBM_NOTIFICATION_STOP  0\n/**\n * struct MEIBusNotificationRequest - start/stop notification request\n *\n * @cmd: bus message command ID\n * @me_addr: address of the client in ME\n * @host_addr: address of the client in the driver\n * @start:  start = 1 or stop = 0 asynchronous notifications\n */\nstruct PACKED MEIBusNotificationRequest {\n    UInt8 cmd;\n    UInt8 me_addr;\n    UInt8 host_addr;\n    UInt8 start;\n};\n\n/**\n * struct MEIBusNotificationResponse - start/stop notification response\n *\n * @cmd: bus message command header\n * @me_addr: address of the client in ME\n * @host_addr: - address of the client in the driver\n * @status: (mei_hbm_status) response status for the request\n *  - MEIHostBusMessageReturnSuccess:           successful stop/start\n *  - MEIHostBusMessageReturnClientNotFound:    if the connection could not be found.\n *  - MEIHostBusMessageReturnAlreadyStarted:    for start requests for a previously started notification.\n *  - MEIHostBusMessageReturnNotStarted:        for stop request for a connected client for whom asynchronous notifications are currently disabled.\n * @start:  start = 1 or stop = 0 asynchronous notifications\n * @reserved: reserved\n */\nstruct PACKED MEIBusNotificationResponse {\n    UInt8 cmd;\n    UInt8 me_addr;\n    UInt8 host_addr;\n    MEIHostBusMessageReturnType status;\n    UInt8 start;\n    UInt8 reserved[3];\n};\n\n/**\n * struct MEIBusDMAMemDesc - dma ring\n *\n * @addr_hi: the high 32bits of 64 bit address\n * @addr_lo: the low  32bits of 64 bit address\n * @size   : size in bytes (must be power of 2)\n */\nstruct PACKED MEIBusDMAInfo {\n    UInt32 addr_hi;\n    UInt32 addr_lo;\n    UInt32 size;\n};\n\n#define DMA_BIT_MASK(n)    (((n) == 64) ? ~0ULL : ((1ULL<<(n))-1))\n\n// SHOULD be power of 2\n#define MEI_DMA_RING_HOST_SIZE      0x00020000  // 128k\n#define MEI_DMA_RING_DEVICE_SIZE    0x00020000\n#define MEI_DMA_RING_CTRL_SIZE      PAGE_SIZE   // 4k\n\nenum MEIDMADescriptor {\n    MEIDMADescriptorHost = 0,\n    MEIDMADescriptorDevice = 1,\n    MEIDMADescriptorControl = 2,\n    MEIDMADescriptorSize,\n};\n\n/**\n * struct MEIBusDMASetupRequest - dma setup request\n *\n * @cmd: bus message command ID\n * @reserved: reserved for alignment\n * @dma_dscr: dma descriptor for HOST, DEVICE, and CTRL\n */\nstruct PACKED MEIBusDMASetupRequest {\n    UInt8 cmd;\n    UInt8 reserved[3];\n    MEIBusDMAInfo dma_info[MEIDMADescriptorSize];\n};\n\n/**\n * struct hbm_dma_setup_response - dma setup response\n *\n * @cmd: bus message command ID\n * @status: 0 on success; otherwise DMA setup failed.\n * @reserved: reserved for alignment\n */\nstruct PACKED MEIBusDMASetupResponse {\n    UInt8 cmd;\n    MEIHostBusMessageReturnType status;\n    UInt8 reserved[2];\n};\n\n/**\n * struct MEIBusDMARingControl - dma ring control block\n *\n * @hbuf_wr_idx: host circular buffer write index in slots\n * @reserved1: reserved for alignment\n * @hbuf_rd_idx: host circular buffer read index in slots\n * @reserved2: reserved for alignment\n * @dbuf_wr_idx: device circular buffer write index in slots\n * @reserved3: reserved for alignment\n * @dbuf_rd_idx: device circular buffer read index in slots\n * @reserved4: reserved for alignment\n */\nstruct PACKED MEIBusDMARingControl {\n    UInt32 hbuf_wr_idx;\n    UInt32 reserved1;\n    UInt32 hbuf_rd_idx;\n    UInt32 reserved2;\n    UInt32 dbuf_wr_idx;\n    UInt32 reserved3;\n    UInt32 dbuf_rd_idx;\n    UInt32 reserved4;\n};\n\n/* virtual tag supported */\n#define MEI_HBM_CAP_VTAG        BIT(0)\n/* client dma supported */\n#define MEI_HBM_CAP_CLIENT_DMA  BIT(2)\n\n/**\n * struct MEIBusCapabilityRequest - capability request from host to fw\n *\n * @cmd : bus message command ID\n * @capability_requested: bitmask of capabilities requested by host\n */\nstruct PACKED MEIBusCapabilityRequest {\n    UInt8 cmd;\n    UInt8 capability_requested[3];\n};\n\n/**\n * struct MEIBusCapabilityResponse - capability response from fw to host\n *\n * @cmd : bus message command ID\n * @capability_granted: bitmask of capabilities granted by FW\n */\nstruct PACKED MEIBusCapabilityResponse {\n    UInt8 cmd;\n    UInt8 capability_granted[3];\n};\n\n/**\n * struct MEIBusClientDMAMapRequest - client dma map request from host to fw\n *\n * @cmd: bus message command ID\n * @client_buffer_id: client buffer id\n * @reserved: reserved\n * @address_lsb: DMA address LSB\n * @address_msb: DMA address MSB\n * @size: DMA size\n */\nstruct PACKED MEIBusClientDMAMapRequest {\n    UInt8 cmd;\n    UInt8 client_buffer_id;\n    UInt8 reserved[2];\n    UInt32 address_lsb;\n    UInt32 address_msb;\n    UInt32 size;\n};\n\n/**\n * struct MEIBusClientDMAUnmapRequest - client dma unmap request from the host to the fw\n *\n * @cmd: bus message command ID\n * @status: unmap status\n * @client_buffer_id: client buffer id\n * @reserved: reserved\n */\nstruct PACKED MEIBusClientDMAUnmapRequest {\n    UInt8 cmd;\n    UInt8 status;\n    UInt8 client_buffer_id;\n    UInt8 reserved;\n};\n\n/**\n * struct MEIBusClientDMAResponse - client dma map/unmap response from the fw to the host\n *\n * @cmd: bus message command ID\n * @status: command status\n */\nstruct PACKED MEIBusClientDMAResponse {\n    UInt8 cmd;\n    MEIClientConnectionStatus status;\n};\n\n#endif /* MEIProtocol_h */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineClient.cpp",
    "content": "//\n//  SurfaceManagementEngineClient.cpp\n//  SurfaceTouchScreen\n//\n//  Created by Xavier on 2022/6/1.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#include \"SurfaceManagementEngineClient.hpp\"\n\n#define super IOService\nOSDefineMetaClassAndStructors(SurfaceManagementEngineClient, IOService)\n\nbool SurfaceManagementEngineClient::attach(IOService* provider) {\n    if (!super::attach(provider))\n        return false;\n\n    api = OSDynamicCast(SurfaceManagementEngineDriver, provider);\n    if (!api)\n        return false;\n    \n    queue_head_init(rx_queue);\n\n    return true;\n}\n\nvoid SurfaceManagementEngineClient::detach(IOService* provider) {\n    api = nullptr;\n    super::detach(provider);\n}\n\nbool SurfaceManagementEngineClient::start(IOService *provider) {\n    if (!super::start(provider))\n        return false;\n    \n    queue_lock = IOLockAlloc();\n    if (!queue_lock) {\n        LOG(\"Failed to create lock\");\n        goto exit;\n    }\n    \n    work_loop = IOWorkLoop::workLoop();\n    if (!work_loop) {\n        LOG(\"Failed to create work loop\");\n        goto exit;\n    }\n    interrupt_source = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineClient::notifyMessage));\n    if (!interrupt_source) {\n        LOG(\"Failed to create interrupt source\");\n        goto exit;\n    }\n    work_loop->addEventSource(interrupt_source);\n    \n    uuid_t swapped_uuid;\n    uuid_string_t uuid_str;\n    uuid_copy(swapped_uuid, properties.uuid);\n    *(reinterpret_cast<UInt32 *>(swapped_uuid)) = OSSwapInt32(*(reinterpret_cast<UInt32 *>(swapped_uuid)));\n    *(reinterpret_cast<UInt16 *>(swapped_uuid) + 2) = OSSwapInt16(*(reinterpret_cast<UInt16 *>(swapped_uuid) + 2));\n    *(reinterpret_cast<UInt16 *>(swapped_uuid) + 3) = OSSwapInt16(*(reinterpret_cast<UInt16 *>(swapped_uuid) + 3));\n    uuid_unparse_lower(swapped_uuid, uuid_str);\n    setProperty(\"MEIClientUUID\", uuid_str);\n    setProperty(\"MEIClientAddress\", properties.fixed_address, 32);\n    setProperty(\"MEIClientMaxMessageLength\", properties.max_msg_length, 32);\n    \n    rx_cache = new UInt8[properties.max_msg_length];\n    \n    initial = false;\n    \n    PMinit();\n    api->joinPMtree(this);\n    registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);\n    \n    registerService();\n    return true;\nexit:\n    releaseResources();\n    return false;\n}\n\nvoid SurfaceManagementEngineClient::stop(IOService *provider) {\n    releaseResources();\n    super::stop(provider);\n}\n\nIOReturn SurfaceManagementEngineClient::setPowerState(unsigned long whichState, IOService *device) {\n    if (device != this)\n        return kIOReturnInvalid;\n    return kIOPMAckImplied;\n}\n\nvoid SurfaceManagementEngineClient::releaseResources() {\n    MEIClientMessage *msg;\n    qe_foreach_element_safe(msg, &rx_queue, entry) {\n        remqueue(&msg->entry);\n        delete[] msg->msg;\n        delete msg;\n    }\n    if (rx_cache)\n        delete[] rx_cache;\n    \n    if (interrupt_source) {\n        interrupt_source->disable();\n        work_loop->removeEventSource(interrupt_source);\n        OSSafeReleaseNULL(interrupt_source);\n    }\n    OSSafeReleaseNULL(work_loop);\n    if (queue_lock)\n        IOLockFree(queue_lock);\n}\n\nIOReturn SurfaceManagementEngineClient::registerMessageHandler(OSObject *owner, MessageHandler _handler) {\n    if (!owner || !_handler)\n        return kIOReturnError;\n    if (target) {\n        LOG(\"Already has a handler!\");\n        return kIOReturnNoResources;\n    }\n\n    target = owner;\n    handler = _handler;\n    return kIOReturnSuccess;\n}\n\nvoid SurfaceManagementEngineClient::unregisterMessageHandler(OSObject *owner) {\n    if (target && target == owner) {\n        target = nullptr;\n        handler = nullptr;\n    }\n}\n\nIOReturn SurfaceManagementEngineClient::sendMessage(UInt8 *data, UInt16 data_len, bool blocking) {\n    if (!active)\n        return kIOReturnNoDevice;\n    \n    return api->sendClientMessage(this, data, data_len, blocking);\n}\n\nvoid SurfaceManagementEngineClient::resetProperties(MEIClientProperty *client_props, UInt8 me_addr) {\n    active = true;\n    properties = *client_props;\n    addr = me_addr;\n}\n\nvoid SurfaceManagementEngineClient::hostRequestDisconnect() {\n    rx_cache_pos = 0;\n    \n    IOLockLock(queue_lock);\n    while (dequeue(&rx_queue));\n    IOLockUnlock(queue_lock);\n}\n\nvoid SurfaceManagementEngineClient::hostRequestReconnect() {\n    \n}\n\nvoid SurfaceManagementEngineClient::messageComplete() {\n    if (!rx_cache_pos)\n        return;\n    \n    MEIClientMessage *client_msg = new MEIClientMessage;\n    client_msg->msg = new UInt8[rx_cache_pos];\n    client_msg->len = rx_cache_pos;\n    memcpy(client_msg->msg, rx_cache, rx_cache_pos);\n    rx_cache_pos = 0;\n    \n    IOLockLock(queue_lock);\n    enqueue(&rx_queue, &client_msg->entry);\n    IOLockUnlock(queue_lock);\n    interrupt_source->interruptOccurred(nullptr, this, 0);\n}\n\nvoid SurfaceManagementEngineClient::notifyMessage(IOInterruptEventSource *sender, int count) {\n    MEIClientMessage *client_msg;\n    queue_entry *item;\n    \n    IOLockLock(queue_lock);\n    while ((item = dequeue(&rx_queue)) != nullptr) {\n        IOLockUnlock(queue_lock);\n        client_msg = qe_element(item, MEIClientMessage, entry);\n        \n        if (handler)\n            handler(target, this, client_msg->msg, client_msg->len);\n        \n        delete[] client_msg->msg;\n        delete client_msg;\n        IOLockLock(queue_lock);\n    }\n    IOLockUnlock(queue_lock);\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineClient.hpp",
    "content": "//\n//  SurfaceManagementEngineClient.hpp\n//  SurfaceTouchScreen\n//\n//  Created by Xavier on 2022/6/1.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#ifndef SurfaceManagementEngineClient_hpp\n#define SurfaceManagementEngineClient_hpp\n\n#include \"SurfaceManagementEngineDriver.hpp\"\n\nstruct MEIClientMessage {\n    queue_entry entry;\n    UInt8*      msg;\n    UInt16      len;\n};\n\nclass EXPORT SurfaceManagementEngineClient : public IOService {\n    OSDeclareDefaultStructors(SurfaceManagementEngineClient);\n    friend class SurfaceManagementEngineDriver;\n    \npublic:\n    // handle received message\n    typedef void (*MessageHandler)(OSObject *owner, SurfaceManagementEngineClient *sender, UInt8 *msg, UInt16 msg_len);\n    \n    bool attach(IOService* provider) override;\n    \n    void detach(IOService* provider) override;\n    \n    bool start(IOService* provider) override;\n    \n    void stop(IOService* provider) override;\n    \n    IOReturn setPowerState(unsigned long whichState, IOService *device) override;\n    \n    IOReturn registerMessageHandler(OSObject *owner, MessageHandler _handler);\n    \n    void unregisterMessageHandler(OSObject *owner);\n    \n    IOReturn sendMessage(UInt8 *data, UInt16 data_len, bool blocking);\n    \nprivate:\n    SurfaceManagementEngineDriver*      api {nullptr};\n    IOLock*                             queue_lock {nullptr};\n    IOWorkLoop*                         work_loop {nullptr};\n    IOInterruptEventSource*             interrupt_source {nullptr};\n    MEIClientProperty                   properties;\n    \n    OSObject*       target {nullptr};\n    MessageHandler  handler {nullptr};\n    queue_head_t    rx_queue;\n    UInt8*          rx_cache {nullptr};\n    UInt16          rx_cache_pos {0};\n    \n    UInt8   addr;\n    bool    active {false};\n    bool    initial {true};    \n    \n    void releaseResources();\n    \n    void resetProperties(MEIClientProperty *client_props, UInt8 me_addr);\n    \n    void hostRequestDisconnect();\n    \n    void hostRequestReconnect();\n    \n    void messageComplete();\n    \n    void notifyMessage(IOInterruptEventSource *sender, int count);\n};\n\n#endif /* SurfaceManagementEngineClient_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineDriver.cpp",
    "content": "//\n//  SurfaceManagementEngineDriver.cpp\n//  SurfaceTouchScreen\n//\n//  Created by Xavier on 2022/05/28.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#include \"SurfaceManagementEngineDriver.hpp\"\n#include \"SurfaceManagementEngineClient.hpp\"\n\n#define super IOService\nOSDefineMetaClassAndStructors(SurfaceManagementEngineDriver, IOService);\n\nvoid bitmap_set_bit(UInt8 *map, UInt addr, bool set) {\n    UInt i = addr / 8;\n    UInt offset = addr % 8;\n    if (set)\n        map[i] |= BIT(offset);\n    else\n        map[i] &= ~BIT(offset);\n}\n\nbool bitmap_get_bit(UInt8 *map, UInt addr) {\n    UInt i = addr / 8;\n    UInt offset = addr % 8;\n    return (map[i] & BIT(offset)) != 0;\n}\n\nUInt bitmap_find_next_bit(UInt8 *map, UInt map_size, UInt start_addr) {\n    UInt pos = start_addr;\n    while (pos < map_size && !bitmap_get_bit(map, pos))\n        pos++;\n    return pos;\n}\n\nbool SurfaceManagementEngineDriver::init(OSDictionary* properties) {\n    if (!super::init(properties))\n        return false;\n\n    memset(&device, 0, sizeof(MEIPhysicalDevice));\n    memset(&bus, 0, sizeof(MEIBus));\n    queue_init(&bus.tx_queue);\n    \n    return true;\n}\n\nIOService* SurfaceManagementEngineDriver::probe(IOService* provider, SInt32* score) {\n    if (!super::probe(provider, score))\n        return nullptr;\n    \n    device.pci_dev = OSDynamicCast(IOPCIDevice, provider);\n    if (!device.pci_dev)\n        return nullptr;\n\n    return this;\n}\n\nbool SurfaceManagementEngineDriver::start(IOService* provider) {\n    if (!super::start(provider))\n        return false;\n    \n    int interrupt_type, interrupt_idx=0;\n    \n    work_loop = IOWorkLoop::workLoop();\n    if (!work_loop) {\n        LOG(\"Could not get work loop\");\n        goto exit;\n    }\n    command_gate = IOCommandGate::commandGate(this);\n    if (!command_gate) {\n        LOG(\"Could not open command gate\");\n        goto exit;\n    }\n    work_loop->addEventSource(command_gate);\n    client_msg_action = OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::sendClientMessageGated);\n    reset_work = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineDriver::scheduleReset));\n    rescan_work = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineDriver::scheduleRescan));\n    resume_work = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineDriver::scheduleResume));\n    if (!reset_work || !rescan_work || !resume_work) {\n        LOG(\"Could not create scheduled work\");\n        goto exit;\n    }\n    work_loop->addEventSource(reset_work);\n    work_loop->addEventSource(rescan_work);\n    work_loop->addEventSource(resume_work);\n    \n    if (!device.pci_dev->open(this)) {\n        LOG(\"Could not open provider\");\n        goto exit;\n    }\n    if (initDevice() != kIOReturnSuccess)\n        goto exit;\n    \n    while (device.pci_dev->getInterruptType(interrupt_idx, &interrupt_type) == kIOReturnSuccess) {\n        if (interrupt_type & kIOInterruptTypePCIMessaged)\n            break;\n        interrupt_idx++;\n    }\n    interrupt_source = IOFilterInterruptEventSource::filterInterruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineDriver::handleInterrupt), OSMemberFunctionCast(IOFilterInterruptAction, this, &SurfaceManagementEngineDriver::filterInterrupt), device.pci_dev, interrupt_idx);\n    if (!interrupt_source) {\n        LOG(\"WTF? Cannot register PCI MSI interrupt!\");\n        goto exit;\n    }\n    work_loop->addEventSource(interrupt_source);\n    interrupt_source->enable();\n    \n    if (command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::startDeviceGated)) != kIOReturnSuccess) {\n        LOG(\"Initialise hardware failed\");\n        goto exit;\n    }\n    \n    PMinit();\n    device.pci_dev->joinPMtree(this);\n    registerPowerDriver(this, MyIOPMPowerStates, kIOPMNumberPowerStates);\n\n    device.pci_dev->retain();\n    registerService();\n    return true;\nexit:\n    releaseResources();\n    return false;\n}\n\nvoid SurfaceManagementEngineDriver::stop(IOService *provider) {\n    if (!queue_empty(&bus.tx_queue)) {\n        DBG_LOG(\"Warning, there are still pending transactions!\");\n        MEIClientTransaction *tx;\n        qe_foreach_element_safe(tx, &bus.tx_queue, entry) {\n            completeTransaction(tx);\n        }\n        IOSleep(100);\n    }\n    command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::stopDeviceGated));\n    PMstop();\n    releaseResources();\n    super::stop(provider);\n}\n\nvoid SurfaceManagementEngineDriver::free() {\n    super::free();\n}\n\nIOReturn SurfaceManagementEngineDriver::setPowerState(unsigned long whichState, IOService *whatDevice) {\n    if (whatDevice != this)\n        return kIOReturnInvalid;\n    if (whichState == 0) {\n        if (awake) {\n            command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::stopDeviceGated));\n            disableInterrupts();\n            interrupt_source->disable();\n            device.pci_dev->enablePCIPowerManagement(kPCIPMCSPowerStateD3);\n            awake = false;\n            DBG_LOG(\"Going to sleep\");\n        }\n    } else {\n        if (!awake) {\n            awake = true;\n            device.pci_dev->enablePCIPowerManagement(kPCIPMCSPowerStateD0);\n            interrupt_source->enable();\n            if (command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::restartDeviceGated)) != kIOReturnSuccess)\n                LOG(\"Restarting device failed! Retry later\");\n            init_timeout->enable();\n            DBG_LOG(\"Woke up\");\n        }\n    }\n    return kIOPMAckImplied;\n}\n\nvoid SurfaceManagementEngineDriver::releaseResources() {\n    if (interrupt_source) {\n        disableInterrupts();\n        interrupt_source->disable();\n        work_loop->removeEventSource(interrupt_source);\n        OSSafeReleaseNULL(interrupt_source);\n    }\n    if (init_timeout) {\n        init_timeout->cancelTimeout();\n        init_timeout->disable();\n        work_loop->removeEventSource(init_timeout);\n        OSSafeReleaseNULL(init_timeout);\n    }\n    if (idle_timeout) {\n        idle_timeout->cancelTimeout();\n        idle_timeout->disable();\n        work_loop->removeEventSource(idle_timeout);\n        OSSafeReleaseNULL(idle_timeout);\n    }\n    if (reset_work) {\n        reset_work->disable();\n        work_loop->removeEventSource(reset_work);\n        OSSafeReleaseNULL(reset_work);\n    }\n    if (rescan_work) {\n        rescan_work->disable();\n        work_loop->removeEventSource(rescan_work);\n        OSSafeReleaseNULL(rescan_work);\n    }\n    if (resume_work) {\n        resume_work->disable();\n        work_loop->removeEventSource(resume_work);\n        OSSafeReleaseNULL(resume_work);\n    }\n    unmapMemory();\n    if (device.pci_dev->isOpen(this))\n        device.pci_dev->close(this);\n    if (command_gate) {\n        work_loop->removeEventSource(command_gate);\n        OSSafeReleaseNULL(command_gate);\n    }\n    OSSafeReleaseNULL(work_loop);\n    if (ipts_client) {\n        ipts_client->stop(this);\n        ipts_client->detach(this);\n        OSSafeReleaseNULL(ipts_client);\n    }\n    \n    OSSafeReleaseNULL(device.pci_dev);\n}\n\nIOReturn SurfaceManagementEngineDriver::startDeviceGated() {\n    IOReturn ret;\n    \n    clearInterrupts();\n    configDevice();\n    \n    device.reset_cnt = 0;\n    do {\n        device.state = MEIDeviceInitializing;\n        ret = resetDevice();\n\n        if (ret == kIOReturnDeviceError || device.state == MEIDeviceDisabled) {\n            LOG(\"Reset failed!\");\n            goto err;\n        }\n    } while (ret != kIOReturnSuccess);\n    \n    // wait mei host bus started\n    if (bus.state <= MEIBusStarting) {\n        AbsoluteTime abstime, deadline;\n        nanoseconds_to_absolutetime(MEI_HOST_BUS_MSG_TIMEOUT * 1000000000ULL, &abstime);\n        clock_absolutetime_interval_to_deadline(abstime, &deadline);\n        ret = command_gate->commandSleep(&wait_bus_start, deadline, THREAD_INTERRUPTIBLE);\n        if (ret == THREAD_TIMED_OUT && bus.state <= MEIBusStarting) {\n            bus.state = MEIBusIdle;\n            LOG(\"Timeout waiting for mei bus to start!\");\n            goto err;\n        }\n    }\n\n    if (!isHostReady()) {\n        LOG(\"Host is not ready\");\n        goto err;\n    }\n    if (!isHardwareReady()) {\n        LOG(\"ME is not ready\");\n        goto err;\n    }\n\n    if (!isBusMessageVersionSupported()) {\n        LOG(\"Device start failed\");\n        goto err;\n    }\n\n    LOG(\"Link layer initialization succeeded\");\n    return kIOReturnSuccess;\nerr:\n    LOG(\"Link layer initialization failed\");\n    device.state = MEIDeviceDisabled;\n    return kIOReturnDeviceError;\n}\n\nvoid SurfaceManagementEngineDriver::stopDeviceGated() {\n    device.state = MEIDevicePowerDown;\n    \n    init_timeout->disable();\n\n    resetDevice();\n    device.state = MEIDeviceDisabled;\n}\n\nIOReturn SurfaceManagementEngineDriver::restartDeviceGated() {\n    device.state = MEIDevicePowerUp;\n    device.reset_cnt = 0;\n    IOReturn ret = resetDevice();\n    \n    if (ret == kIOReturnDeviceError ||\n        device.state == MEIDeviceDisabled) {\n        LOG(\"Error! Device disabled\");\n        return kIOReturnDeviceError;\n    }\n    if (ret != kIOReturnSuccess)\n        reset_work->interruptOccurred(nullptr, this, 0);\n    \n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceManagementEngineDriver::mapMemory() {\n    if (device.pci_dev->getDeviceMemoryCount() == 0) {\n        return kIOReturnDeviceError;\n    } else {\n        device.mmap = device.pci_dev->mapDeviceMemoryWithIndex(0);\n        if (!device.mmap) return kIOReturnDeviceError;\n        return kIOReturnSuccess;\n    }\n}\n\nvoid SurfaceManagementEngineDriver::unmapMemory() {\n    OSSafeReleaseNULL(device.mmap);\n}\n\ninline UInt32 SurfaceManagementEngineDriver::readRegister(int offset) {\n    if (device.mmap) {\n         IOVirtualAddress address = device.mmap->getVirtualAddress();\n         if (address != 0)\n             return *(const volatile UInt32 *)(address + offset);\n     }\n     return kIOReturnSuccess;\n}\n\ninline void SurfaceManagementEngineDriver::writeRegister(UInt32 value, int offset) {\n    if (device.mmap) {\n        IOVirtualAddress address = device.mmap->getVirtualAddress();\n        if (address != 0)\n            *(volatile UInt32 *)(address + offset) = value;\n    }\n}\n\nUInt8 SurfaceManagementEngineDriver::calcFilledSlots() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    SInt8 read_ptr = (hcsr & MEI_CSR_BUF_RPOINTER) >> 8;\n    SInt8 write_ptr = (hcsr & MEI_CSR_BUF_WPOINTER) >> 16;\n    \n    return write_ptr - read_ptr;\n}\n\nIOReturn SurfaceManagementEngineDriver::findEmptySlots(UInt8 *empty_slots) {\n    UInt8 filled_slots = calcFilledSlots();\n    if (filled_slots > device.tx_buf_depth)\n        return kIOReturnOverrun;\n    \n    *empty_slots = device.tx_buf_depth - filled_slots;\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceManagementEngineDriver::countRxSlots(UInt8 *filled_slots) {\n    UInt32 mecsr = readRegister(MEI_ME_CSR);\n    UInt8 buffer_depth = (mecsr & MEI_CSR_BUF_DEPTH) >> 24;\n    SInt8 read_ptr = (mecsr & MEI_CSR_BUF_RPOINTER) >> 8;\n    SInt8 write_ptr = (mecsr & MEI_CSR_BUF_WPOINTER) >> 16;\n    UInt8 slots = write_ptr - read_ptr;\n    \n    if (slots > buffer_depth)\n        return kIOReturnOverrun;\n    \n    *filled_slots = slots;\n    return kIOReturnSuccess;\n}\n\nbool SurfaceManagementEngineDriver::acquireWriteBuffer() {\n    if (device.pg_state == MEIPowerGatingOn || (device.pg_event >= MEIPowerGatingEventWait && device.pg_event <= MEIPowerGatingInterruptWait))\n        return false;\n    if (!bus.tx_buf_ready)\n        return false;\n    bus.tx_buf_ready = false;\n    return true;\n}\n\nbool SurfaceManagementEngineDriver::isHardwareReady() {\n    UInt32 mecsr = readRegister(MEI_ME_CSR);\n    return (mecsr & MEI_ME_CSR_READY) == MEI_ME_CSR_READY;\n}\n\nbool SurfaceManagementEngineDriver::isHostReady() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    return (hcsr & MEI_H_CSR_READY) == MEI_H_CSR_READY;\n}\n\nbool SurfaceManagementEngineDriver::isBusMessageVersionSupported() {\n    return (device.version_major < MEI_HBM_MAJOR_VERSION) ||\n            (device.version_major == MEI_HBM_MAJOR_VERSION &&\n             device.version_minor <= MEI_HBM_MINOR_VERSION);\n}\n\nbool SurfaceManagementEngineDriver::isWriteQueueEmpty() {\n    return device.state == MEIDeviceEnabled && queue_empty(&bus.tx_queue);\n}\n\ninline void SurfaceManagementEngineDriver::setHostCSR(UInt32 hcsr) {\n    hcsr &= ~MEI_H_CSR_INT_STA_MASK;\n    writeRegister(hcsr, MEI_H_CSR);\n}\n\nvoid SurfaceManagementEngineDriver::clearInterrupts() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    if (hcsr & MEI_H_CSR_INT_STA_MASK)\n        writeRegister(hcsr, MEI_H_CSR);\n}\n\nvoid SurfaceManagementEngineDriver::enableInterrupts() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    hcsr |= MEI_H_CSR_INT_ENABLE_MASK;\n    setHostCSR(hcsr);\n}\n\nvoid SurfaceManagementEngineDriver::disableInterrupts() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    hcsr &= ~MEI_H_CSR_INT_ENABLE_MASK;\n    setHostCSR(hcsr);\n}\n\nvoid SurfaceManagementEngineDriver::setHostInterrupt() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    hcsr |= MEI_H_CSR_INT_GEN;\n    setHostCSR(hcsr);\n}\n\nvoid SurfaceManagementEngineDriver::configDevice() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    device.tx_buf_depth = (hcsr & MEI_CSR_BUF_DEPTH) >> 24;\n\n    device.pg_state = MEIPowerGatingOff;\n    UInt32 d0i3c = readRegister(MEI_H_D0I3C);\n    if (d0i3c & MEI_H_D0I3C_I3)\n        device.pg_state = MEIPowerGatingOn;\n}\n\nIOReturn SurfaceManagementEngineDriver::initDevice() {\n    device.pci_dev->setMemoryEnable(true);\n    device.pci_dev->setBusMasterEnable(true);\n    \n    if (mapMemory() != kIOReturnSuccess) {\n        LOG(\"Could not map pci_device memory\");\n        return kIOReturnError;\n    }\n    \n    device.state = MEIDeviceInitializing;\n    memset(me_client_map, 0, sizeof(me_client_map));\n    device.pg_event = MEIPowerGatingEventIdle;\n    \n    init_timeout = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceManagementEngineDriver::initialiseTimeout));\n    idle_timeout = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceManagementEngineDriver::enterIdle));\n    if (!init_timeout || !idle_timeout) {\n        LOG(\"Failed to create timer for device\");\n        return kIOReturnError;\n    }\n    work_loop->addEventSource(init_timeout);\n    work_loop->addEventSource(idle_timeout);\n    \n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceManagementEngineDriver::resetDevice() {\n    IOReturn ret = kIOReturnSuccess;\n    UInt32 hcsr;\n    MEIDeviceState state = device.state;\n    if (state != MEIDeviceInitializing &&\n        state != MEIDeviceDisabled &&\n        state != MEIDevicePowerDown &&\n        state != MEIDevicePowerUp) {\n        LOG(\"Warning! Unexpected reset call from state: %x\", device.state);\n    }\n    clearInterrupts();\n    // put bus into idle before actual reset\n    init_timeout->cancelTimeout();\n    bus.state = MEIBusIdle;\n    \n    bool interrupts_enabled = state != MEIDevicePowerDown;\n    device.state = MEIDeviceResetting;\n    if (++device.reset_cnt > MEI_MAX_CONSEC_RESET) {\n        LOG(\"Reached maximal consecutive resets\");\n        device.state = MEIDeviceDisabled;\n        return kIOReturnDeviceError;\n    }\n    \n    if (interrupts_enabled) {\n        enableInterrupts();\n        ret = exitPowerGatingSync();\n        if (ret != kIOReturnSuccess)\n            goto sw_reset;\n    }\n    \n    hcsr = readRegister(MEI_H_CSR);\n    /*\n     * MEI_H_CSR_RESET may be found lit before reset is started,\n     * for example if preceding reset flow hasn't completed.\n     * In that case asserting MEI_H_CSR_RESET will be ignored, therefore\n     * we need to clean MEI_H_CSR_RESET bit to start a successful reset sequence.\n     */\n    if ((hcsr & MEI_H_CSR_RESET) == MEI_H_CSR_RESET) {\n        LOG(\"Warning, MEI_H_CSR_RESET is set = 0x%08X, previous reset probably failed\", hcsr);\n        hcsr &= ~MEI_H_CSR_RESET;\n        setHostCSR(hcsr);\n        hcsr = readRegister(MEI_H_CSR);\n    }\n    hcsr |= MEI_H_CSR_RESET | MEI_H_CSR_INT_GEN | MEI_H_CSR_INT_STA_MASK;\n    if (!interrupts_enabled)\n        hcsr &= ~MEI_H_CSR_INT_ENABLE_MASK;\n\n    writeRegister(hcsr, MEI_H_CSR);\n\n    // Host reads the MEI_H_CSR once to ensure that the posted write to MEI_H_CSR completes.\n    hcsr = readRegister(MEI_H_CSR);\n    if ((hcsr & MEI_H_CSR_RESET) == 0)\n        LOG(\"Warning, MEI_H_CSR_RESET is not set = 0x%08X\", hcsr);\n    if ((hcsr & MEI_H_CSR_READY) == MEI_H_CSR_READY)\n        LOG(\"Warning, MEI_H_CSR_READY is not cleared 0x%08X\", hcsr);\n\n    if (!interrupts_enabled) {\n        deresetDevice();\n        enterPowerGating();\n    }\nsw_reset:\n    /* fall through and remove the sw state even if hw reset has failed\n     * no need to clean up software state in case of power up */\n    if (state != MEIDeviceInitializing && state != MEIDevicePowerUp) {\n        if (!queue_empty(&bus.tx_queue)) {\n            LOG(\"Flushing all pending transactions!\");\n            MEIClientTransaction *tx;\n            qe_foreach_element_safe(tx, &bus.tx_queue, entry) {\n                completeTransaction(tx);\n            }\n            \n            AbsoluteTime abstime, deadline;\n            nanoseconds_to_absolutetime(50000000ULL, &abstime);    // 50ms\n            clock_absolutetime_interval_to_deadline(abstime, &deadline);\n            // Give up work_loop's thread to let pending transactions to finish their work on gate.\n            command_gate->commandSleep(&awake, deadline, THREAD_INTERRUPTIBLE);\n        }\n        if (ipts_client)\n            ipts_client->hostRequestDisconnect();\n    }\n    resetBus();\n\n    memset(bus.rx_msg_hdr, 0, sizeof(bus.rx_msg_hdr));\n    if (ret != kIOReturnSuccess) {\n        LOG(\"Hardware reset failed\");\n        return ret;\n    }\n\n    if (state == MEIDevicePowerDown) {\n        device.state = MEIDeviceDisabled;\n        return kIOReturnSuccess;\n    }\n\n    ret = waitDeviceReady();\n    if (ret != kIOReturnSuccess)\n        return ret;\n    LOG(\"Link is established\");\n    \n    device.state = MEIDeviceInitClients;\n    // Send start request\n    bus.state = MEIBusIdle;\n    ret = sendStartRequest();\n    if (ret) {\n        LOG(\"Start request failed\");\n        device.state = MEIDeviceResetting;\n        return ret;\n    }\n\n    bus.state = MEIBusStarting;\n    init_timeout->setTimeoutMS(MEI_CLIENTS_INIT_TIMEOUT * 1000);\n\n    return kIOReturnSuccess;\n}\n\nvoid SurfaceManagementEngineDriver::deresetDevice() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    hcsr |= MEI_H_CSR_INT_GEN;\n    hcsr &= ~MEI_H_CSR_RESET;\n    setHostCSR(hcsr);\n}\n\nvoid SurfaceManagementEngineDriver::enableDevice() {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    hcsr |= MEI_H_CSR_INT_ENABLE_MASK | MEI_H_CSR_INT_GEN | MEI_H_CSR_READY;\n    setHostCSR(hcsr);\n}\n\nIOReturn SurfaceManagementEngineDriver::waitDeviceReady() {\n    AbsoluteTime abstime, deadline;\n    IOReturn sleep;\n    nanoseconds_to_absolutetime(MEI_HW_READY_TIMEOUT * 1000000000ULL, &abstime);\n    clock_absolutetime_interval_to_deadline(abstime, &deadline);\n    sleep = command_gate->commandSleep(&wait_hw_ready, deadline, THREAD_INTERRUPTIBLE);\n    if (sleep == THREAD_TIMED_OUT) {\n        LOG(\"Timeout waiting for hardware to be ready!\");\n        return kIOReturnTimeout;\n    }\n\n    deresetDevice();\n    LOG(\"Hardware is ready\");\n    enableDevice();\n    return kIOReturnSuccess;\n}\n\nvoid SurfaceManagementEngineDriver::configDeviceFeatures() {\n    device.pg_supported = false;\n    if (device.version_major > MEI_HBM_MAJOR_VERSION_PGI ||\n        (device.version_major == MEI_HBM_MAJOR_VERSION_PGI &&\n        device.version_minor >= MEI_HBM_MINOR_VERSION_PGI))\n        device.pg_supported = true;\n\n    device.dc_supported = false;\n    if (device.version_major >= MEI_HBM_MAJOR_VERSION_DC)\n        device.dc_supported = true;\n\n    device.ie_supported = false;\n    if (device.version_major >= MEI_HBM_MAJOR_VERSION_IE)\n        device.ie_supported = true;\n\n    device.dot_supported = false;\n    if (device.version_major >= MEI_HBM_MAJOR_VERSION_DOT)\n        device.dot_supported = true;\n\n    device.ev_supported = false;\n    if (device.version_major >= MEI_HBM_MAJOR_VERSION_EV)\n        device.ev_supported = true;\n\n    device.fa_supported = false;\n    if (device.version_major >= MEI_HBM_MAJOR_VERSION_FA)\n        device.fa_supported = true;\n\n    device.os_supported = false;\n    if (device.version_major >= MEI_HBM_MAJOR_VERSION_OS)\n        device.os_supported = true;\n\n    device.dr_supported = false;\n    if (device.version_major > MEI_HBM_MAJOR_VERSION_DR ||\n        (device.version_major == MEI_HBM_MAJOR_VERSION_DR &&\n         device.version_minor >= MEI_HBM_MINOR_VERSION_DR))\n        device.dr_supported = true;\n\n    device.vt_supported = false;\n    if (device.version_major > MEI_HBM_MAJOR_VERSION_VT ||\n        (device.version_major == MEI_HBM_MAJOR_VERSION_VT &&\n         device.version_minor >= MEI_HBM_MINOR_VERSION_VT))\n        device.vt_supported = true;\n\n    device.cap_supported = false;\n    if (device.version_major > MEI_HBM_MAJOR_VERSION_CAP ||\n        (device.version_major == MEI_HBM_MAJOR_VERSION_CAP &&\n         device.version_minor >= MEI_HBM_MINOR_VERSION_CAP))\n        device.cap_supported = true;\n\n    device.cd_supported = false;\n    if (device.version_major > MEI_HBM_MAJOR_VERSION_CD ||\n        (device.version_major == MEI_HBM_MAJOR_VERSION_CD &&\n         device.version_minor >= MEI_HBM_MINOR_VERSION_CD))\n        device.cd_supported = true;\n    \n//    LOG(\"power gating isolation           %d\", device.pg_supported);\n//    LOG(\"dynamic clients                  %d\", device.dc_supported);\n//    LOG(\"disconnect on timeout            %d\", device.dot_supported);\n//    LOG(\"event notification               %d\", device.ev_supported);\n//    LOG(\"fixed address client             %d\", device.fa_supported);\n//    LOG(\"immediate reply to enum request  %d\", device.ie_supported);\n//    LOG(\"support OS ver message           %d\", device.os_supported);\n//    LOG(\"dma ring                         %d\", device.dr_supported);\n//    LOG(\"vtag                             %d\", device.vt_supported);\n//    LOG(\"capabilities message             %d\", device.cap_supported);\n//    LOG(\"client dma                       %d\", device.cd_supported);\n    \n    device.dr_supported = false;\n    device.cd_supported = false;\n}\n\nvoid SurfaceManagementEngineDriver::resetBus() {\n    if (ipts_client)\n        ipts_client->active = false;\n    \n    init_timeout->cancelTimeout();\n    bus.state = MEIBusIdle;\n}\n\nIOReturn SurfaceManagementEngineDriver::enterPowerGating() {\n    UInt32 reg = readRegister(MEI_H_D0I3C);\n    if (!(reg & MEI_H_D0I3C_I3)) {\n        reg |= MEI_H_D0I3C_I3;\n        reg &= ~MEI_H_D0I3C_IR;\n        writeRegister(reg, MEI_H_D0I3C);\n    }\n    device.pg_state = MEIPowerGatingOn;\n    device.pg_event = MEIPowerGatingEventIdle;\n    LOG(\"Enter d0i3 mode\");\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceManagementEngineDriver::enterPowerGatingSync() {\n    IOReturn ret;\n    AbsoluteTime abstime, deadline;\n\n    UInt32 reg = readRegister(MEI_H_D0I3C);\n    if (reg & MEI_H_D0I3C_I3) {\n        LOG(\"No need to enter d0i3\");\n        goto on;\n    }\n\n    // PGI entry procedure\n    device.pg_event = MEIPowerGatingEventWait;\n    ret = sendPowerGatingCommand(true);\n    if (ret != kIOReturnSuccess) {\n        LOG(\"Failed to send power gating command\");\n        /* FIXME: should we reset here? */\n        goto out;\n    }\n\n    nanoseconds_to_absolutetime(MEI_POWER_GATING_ISO_TIMEOUT * 1000000000ULL, &abstime);\n    clock_absolutetime_interval_to_deadline(abstime, &deadline);\n    command_gate->commandSleep(&wait_power_gating, deadline, THREAD_INTERRUPTIBLE);\n    if (device.pg_event != MEIPowerGatingEventReceived) {\n        ret = kIOReturnTimeout;\n        goto out;\n    }\n    // end PGI entry procedure\n    \n    device.pg_event = MEIPowerGatingInterruptWait;\n    reg = readRegister(MEI_H_D0I3C);\n    reg |= MEI_H_D0I3C_I3;\n    reg |= MEI_H_D0I3C_IR;\n    writeRegister(reg, MEI_H_D0I3C);\n    /* read it to ensure HW consistency */\n    reg = readRegister(MEI_H_D0I3C);\n    if (!(reg & MEI_H_D0I3C_CIP))\n        goto on;\n\n    nanoseconds_to_absolutetime((UInt64)MEI_D0I3_TIMEOUT * 1000000000ULL, &abstime);\n    clock_absolutetime_interval_to_deadline(abstime, &deadline);\n    command_gate->commandSleep(&wait_power_gating, deadline, THREAD_INTERRUPTIBLE);\n    if (device.pg_event != MEIPowerGatingInterruptReceived) {\n        reg = readRegister(MEI_H_D0I3C);\n        if (!(reg & MEI_H_D0I3C_I3)) {\n            ret = kIOReturnTimeout;\n            goto out;\n        }\n    }\non:\n    ret = kIOReturnSuccess;\n    device.pg_state = MEIPowerGatingOn;\n    LOG(\"Enter d0i3 mode\");\nout:\n    device.pg_event = MEIPowerGatingEventIdle;\n    return ret;\n}\n\nIOReturn SurfaceManagementEngineDriver::exitPowerGatingSync() {\n    IOReturn ret;\n    AbsoluteTime abstime, deadline;\n\n    device.pg_event = MEIPowerGatingInterruptWait;\n    UInt32 reg = readRegister(MEI_H_D0I3C);\n    if (!(reg & MEI_H_D0I3C_I3)) {\n        LOG(\"No need to exit d0i3\");\n        goto off;\n    }\n\n    reg &= ~MEI_H_D0I3C_I3;\n    reg |= MEI_H_D0I3C_IR;\n    writeRegister(reg, MEI_H_D0I3C);\n    reg = readRegister(MEI_H_D0I3C);\n    if (!(reg & MEI_H_D0I3C_CIP))\n        goto off;\n\n    nanoseconds_to_absolutetime(MEI_D0I3_TIMEOUT * 1000000000ULL, &abstime);\n    clock_absolutetime_interval_to_deadline(abstime, &deadline);\n    command_gate->commandSleep(&wait_power_gating, deadline, THREAD_INTERRUPTIBLE);\n    if (device.pg_event != MEIPowerGatingInterruptReceived) {\n        reg = readRegister(MEI_H_D0I3C);\n        if (reg & MEI_H_D0I3C_I3) {\n            ret = kIOReturnTimeout;\n            goto out;\n        }\n    }\noff:\n    ret = kIOReturnSuccess;\n    device.pg_state = MEIPowerGatingOff;\n    LOG(\"Exit d0i3 mode\");\nout:\n    device.pg_event = MEIPowerGatingEventIdle;\n    return ret;\n}\n\nvoid SurfaceManagementEngineDriver::readMessage(UInt8 *buffer, UInt16 buffer_len) {\n    UInt32 *buf = reinterpret_cast<UInt32 *>(buffer);\n    for (; buffer_len >= MEI_SLOT_SIZE; buffer_len -= MEI_SLOT_SIZE)\n        *buf++ = readRegister(MEI_ME_CB_RW);\n    if (buffer_len > 0) {\n        UInt32 reg = readRegister(MEI_ME_CB_RW);\n        memcpy(buf, &reg, buffer_len);\n    }\n    setHostInterrupt();\n}\n\nIOReturn SurfaceManagementEngineDriver::writeMessage(UInt8 *header, UInt16 header_len, UInt8 *data, UInt16 data_len) {\n    if (!header || !data || header_len % MEI_SLOT_SIZE) {\n        LOG(\"Message invalid!\");\n        return kIOReturnInvalid;\n    }\n\n    UInt8 empty_slots;\n    if (findEmptySlots(&empty_slots) != kIOReturnSuccess) {\n        LOG(\"WTF? Filled slots is bigger than host buffer\");\n        return kIOReturnOverrun;\n    }\n\n    UInt8 slots_needed = MEI_DATA_TO_SLOTS(header_len + data_len);\n    if (slots_needed > empty_slots) {\n        LOG(\"Message too large! need %d, empty %d\", slots_needed, empty_slots);\n        return kIOReturnMessageTooLarge;\n    }\n\n    const MEI_SLOT_TYPE *buf = reinterpret_cast<MEI_SLOT_TYPE *>(header);\n    for (int i = 0; i < header_len / MEI_SLOT_SIZE; i++)\n        writeRegister(buf[i], MEI_H_CB_WW);\n    buf = reinterpret_cast<MEI_SLOT_TYPE *>(data);\n    for (int i = 0; i < data_len / MEI_SLOT_SIZE; i++)\n        writeRegister(buf[i], MEI_H_CB_WW);\n    UInt8 tail = data_len % MEI_SLOT_SIZE;\n    if (tail > 0) {\n        UInt32 reg = 0;\n        memcpy(&reg, data + data_len - tail, tail);\n        writeRegister(reg, MEI_H_CB_WW);\n    }\n\n    setHostInterrupt();\n    \n    if (!isHardwareReady()) {\n        LOG(\"WTF? Hardware is not ready yet\");\n        return kIOReturnIOError;\n    }\n\n    return kIOReturnSuccess;\n}\n\ninline void SurfaceManagementEngineDriver::setupMessageHeader(MEIBusMessageHeader *header, UInt16 length) {\n    memset(header, 0, sizeof(MEIBusMessageHeader));\n    header->length = length;\n    header->msg_complete = 1;\n}\n\nIOReturn SurfaceManagementEngineDriver::writeHostMessage(MEIBusMessageHeader *header, MEIBusMessage *msg) {\n    return writeMessage(reinterpret_cast<UInt8 *>(header), sizeof(MEIBusMessageHeader), reinterpret_cast<UInt8 *>(msg), header->length);\n}\n\nIOReturn SurfaceManagementEngineDriver::sendClientMessage(SurfaceManagementEngineClient *client, UInt8 *buffer, UInt16 buffer_len, bool blocking) {\n    return command_gate->runAction(client_msg_action, client, buffer, &buffer_len, &blocking);\n}\n\nIOReturn SurfaceManagementEngineDriver::sendClientMessageGated(SurfaceManagementEngineClient *client, UInt8 *buffer, UInt16 *buffer_len, bool *blocking) {\n    if (device.state != MEIDeviceEnabled || !client->active)\n        return kIOReturnNoDevice;\n    if (*buffer_len > client->properties.max_msg_length)\n        return kIOReturnMessageTooLarge;\n    if (device.pg_state == MEIPowerGatingOn && exitPowerGatingSync() != kIOReturnSuccess) {\n        LOG(\"Failed to get device active\");\n        return kIOReturnAborted;\n    }\n    \n    MEIClientTransaction *tx = new MEIClientTransaction;\n    tx->client = client;\n    tx->data_len = *buffer_len;\n    tx->data = new UInt8[tx->data_len];\n    memcpy(tx->data, buffer, tx->data_len);\n    tx->completed = false;\n    tx->blocking = *blocking;\n    \n    IOReturn ret = kIOReturnSuccess;\n    if (acquireWriteBuffer() && submitTransaction(tx)) {\n        delete[] tx->data;\n        delete tx;\n    } else {\n        enqueue(&bus.tx_queue, &tx->entry);\n        if (tx->blocking) {\n            AbsoluteTime abstime, deadline;\n            nanoseconds_to_absolutetime(MEI_CLIENT_SEND_MSG_TIMEOUT * 1000000ULL, &abstime);\n            clock_absolutetime_interval_to_deadline(abstime, &deadline);\n            command_gate->commandSleep(&tx->wait, deadline, THREAD_INTERRUPTIBLE);\n            if (!tx->completed) {\n                LOG(\"Failed to send message!\");\n                ret = kIOReturnTimeout;\n            }\n            remqueue(&tx->entry);\n            delete[] tx->data;\n            delete tx;\n        }\n    }\n    \n    idle_timeout->setTimeoutMS(MEI_DEVICE_IDLE_TIMEOUT * 1000);\n    return ret;\n}\n\nIOReturn SurfaceManagementEngineDriver::sendStartRequest() {\n    MEIBusMessageHeader header;\n    MEIBusHostVersionRequest req;\n    setupMessageHeader(&header, sizeof(req));\n    memset(&req, 0, sizeof(req));\n    req.cmd = MEI_HOST_START_REQ_CMD;\n    req.host_version_major = MEI_HBM_MAJOR_VERSION;\n    req.host_version_minor = MEI_HBM_MINOR_VERSION;\n    \n    return writeHostMessage(&header, MEI_TO_MSG(&req));\n}\n\nIOReturn SurfaceManagementEngineDriver::sendPowerGatingCommand(bool enter) {\n    if (!device.pg_supported)\n        return kIOReturnNotPermitted;\n    \n    UInt8 cmd;\n    if (enter)\n        cmd = MEI_PG_ISOLATION_ENTRY_REQ_CMD;\n    else\n        cmd = MEI_PG_ISOLATION_EXIT_REQ_CMD;\n    \n    MEIBusMessageHeader header;\n    MEIBusPowerGatingRequest req;\n    setupMessageHeader(&header, sizeof(req));\n    memset(&req, 0, sizeof(req));\n    req.cmd = cmd;\n    \n    return writeHostMessage(&header, MEI_TO_MSG(&req));\n}\n\nIOReturn SurfaceManagementEngineDriver::sendStopRequest() {\n    MEIBusMessageHeader header;\n    MEIBusHostStopRequest req;\n    setupMessageHeader(&header, sizeof(req));\n    memset(&req, 0, sizeof(req));\n    req.cmd = MEI_HOST_STOP_REQ_CMD;\n    req.reason = DriverStopRequest;\n    \n    return writeHostMessage(&header, MEI_TO_MSG(&req));\n}\n\nIOReturn SurfaceManagementEngineDriver::sendCapabilityRequest() {\n    MEIBusMessageHeader header;\n    MEIBusCapabilityRequest req;\n    setupMessageHeader(&header, sizeof(req));\n    memset(&req, 0, sizeof(req));\n    req.cmd = MEI_CAPABILITIES_REQ_CMD;\n    if (device.vt_supported)\n        req.capability_requested[0] |= MEI_HBM_CAP_VTAG;\n    if (device.cd_supported)\n        req.capability_requested[0] |= MEI_HBM_CAP_CLIENT_DMA;\n\n    IOReturn ret = writeHostMessage(&header, MEI_TO_MSG(&req));\n    if (ret != kIOReturnSuccess)\n        return ret;\n    bus.state = MEIBusSetupCap;\n    init_timeout->setTimeoutMS(MEI_CLIENTS_INIT_TIMEOUT * 1000);\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceManagementEngineDriver::sendClientEnumerationRequest() {\n    MEIBusMessageHeader header;\n    MEIBusHostEnumerationRequest req;\n    setupMessageHeader(&header, sizeof(req));\n    memset(&req, 0, sizeof(req));\n    req.cmd = MEI_HOST_ENUM_REQ_CMD;\n    req.flags |= device.dc_supported ? MEI_HBM_ENUM_ALLOW_ADD_FLAG : 0;\n    req.flags |= device.ie_supported ? MEI_HBM_ENUM_IMMEDIATE_FLAG : 0;\n\n    IOReturn ret = writeHostMessage(&header, MEI_TO_MSG(&req));\n    if (ret != kIOReturnSuccess)\n        return ret;\n    bus.state = MEIBusEnumerateClients;\n    init_timeout->setTimeoutMS(MEI_CLIENTS_INIT_TIMEOUT * 1000);\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceManagementEngineDriver::sendClientPropertyRequest(UInt start_idx) {\n    UInt addr = bitmap_find_next_bit(me_client_map, MEI_MAX_CLIENT_NUM, start_idx);\n    // We got all client properties\n    if (addr == MEI_MAX_CLIENT_NUM) {\n        bus.state = MEIBusStarted;\n        device.state = MEIDeviceEnabled;\n        device.reset_cnt = 0;\n        rescan_work->interruptOccurred(nullptr, this, 0);\n        // Enable idle (d0i3 mode)\n        idle_timeout->setTimeoutMS(MEI_DEVICE_IDLE_TIMEOUT * 1000);\n        return kIOReturnSuccess;\n    }\n    \n    MEIBusMessageHeader header;\n    MEIBusClientPropertyRequest req;\n    setupMessageHeader(&header, sizeof(req));\n    memset(&req, 0, sizeof(req));\n    req.cmd = MEI_HOST_CLIENT_PROP_REQ_CMD;\n    req.me_addr = addr;\n    \n    IOReturn ret = writeHostMessage(&header, MEI_TO_MSG(&req));\n    if (ret != kIOReturnSuccess)\n        return ret;\n    init_timeout->setTimeoutMS(MEI_CLIENTS_INIT_TIMEOUT * 1000);\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceManagementEngineDriver::sendAddClientResponse(UInt8 me_addr, MEIHostBusMessageReturnType status) {\n    MEIBusMessageHeader header;\n    MEIBusAddClientResponse res;\n    setupMessageHeader(&header, sizeof(res));\n    memset(&res, 0, sizeof(res));\n    res.cmd = MEI_ADD_CLIENT_RES_CMD;\n    res.me_addr = me_addr;\n    res.status = status;\n    \n    return writeHostMessage(&header, MEI_TO_MSG(&res));\n}\n\nvoid SurfaceManagementEngineDriver::scheduleReset(IOInterruptEventSource *sender, int count) {\n    clearInterrupts();\n    \n    IOReturn ret = resetDevice();\n    \n    if (device.state == MEIDeviceDisabled) {\n        LOG(\"Error! Device disabled\");\n        return;\n    }\n    // retry in case of failure\n    if (ret != kIOReturnSuccess)\n        reset_work->interruptOccurred(nullptr, this, 0);\n}\n\nvoid SurfaceManagementEngineDriver::scheduleRescan(IOInterruptEventSource *sender, int count) {\n    if (!ipts_client->active) {\n        LOG(\"Seems the client has been removed by hardware\");\n        ipts_client->stop(this);\n        ipts_client->detach(this);\n        OSSafeReleaseNULL(ipts_client);\n    } else if (!ipts_client->initial) {\n        // Disabled due to bus reset\n        LOG(\"Reconnecting client...\");\n        ipts_client->hostRequestReconnect();\n        return;\n    } else {\n        LOG(\"Starting client...\");\n        if (!ipts_client->attach(this) || !ipts_client->start(this)) {\n            LOG(\"Failed to start client\");\n            ipts_client->detach(this);\n            OSSafeReleaseNULL(ipts_client);\n        }\n    }\n}\n\nvoid SurfaceManagementEngineDriver::scheduleResume(IOInterruptEventSource *sender, int count) {\n    if (exitPowerGatingSync() != kIOReturnSuccess) {\n        LOG(\"Warning! Exit d0i3 failed. Resetting...\");\n        reset_work->interruptOccurred(nullptr, this, 0);\n    }\n}\n\nbool SurfaceManagementEngineDriver::filterInterrupt(IOFilterInterruptEventSource *sender) {\n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    return (hcsr & MEI_H_CSR_INT_STA_MASK) != 0;\n}\n\nvoid SurfaceManagementEngineDriver::handleInterrupt(IOInterruptEventSource *sender, int count) {\n    UInt8 rx_slots = 0;\n    \n    disableInterrupts();\n    \n    UInt32 hcsr = readRegister(MEI_H_CSR);\n    \n    clearInterrupts();\n    \n    /* check if ME wants a reset */\n    if (!isHardwareReady() && device.state != MEIDeviceResetting) {\n        LOG(\"Hardware not ready! Resetting...\");\n        reset_work->interruptOccurred(nullptr, this, 0);\n        goto end;\n    }\n\n    if (readRegister(MEI_ME_CSR) & MEI_ME_CSR_RESET)\n        setHostInterrupt();\n\n    handlePowerGatingInterrupt(hcsr & MEI_H_CSR_INT_STA_MASK);\n    \n    //  Check if we need to start the device\n    if (!isHostReady()) {\n        if (isHardwareReady()) {\n            LOG(\"We need to start the device\");\n            command_gate->commandWakeup(&wait_hw_ready);\n        } else {\n            LOG(\"Spurious Interrupt\");\n        }\n        goto end;\n    }\n    \n    // Check slots available for reading\n    if (countRxSlots(&rx_slots) == kIOReturnSuccess) {\n        while (rx_slots > 0) {\n            IOReturn ret = handleRead(&rx_slots);\n            /* There is a race between ME write and interrupt delivery:\n             * Not all data is always available immediately after the\n             * interrupt, so try to read again on the next interrupt.\n             */\n            if (ret == kIOReturnNotReadable)\n                break;\n\n            if (ret != kIOReturnSuccess &&\n                (device.state != MEIDeviceResetting && device.state != MEIDevicePowerDown)) {\n                LOG(\"Read message failed! Resetting...\");\n                reset_work->interruptOccurred(nullptr, this, 0);\n                goto end;\n            }\n        }\n    }\n\n    bus.tx_buf_ready = calcFilledSlots() == 0;\n    /*\n     * During PG handshake only allowed write is the replay to the\n     * PG exit message, so block calling write function\n     * if the pg event is in PG handshake\n     */\n    if (device.pg_event != MEIPowerGatingEventWait && device.pg_event != MEIPowerGatingEventReceived) {\n        handleWrite();\n        bus.tx_buf_ready = calcFilledSlots() == 0;\n    }\nend:\n    enableInterrupts();\n}\n\nvoid SurfaceManagementEngineDriver::handlePowerGatingInterrupt(UInt32 source) {\n    if (device.pg_event == MEIPowerGatingInterruptWait && source & MEI_H_CSR_D0I3C_INT_STA) {\n        device.pg_event = MEIPowerGatingInterruptReceived;\n        if (device.pg_state == MEIPowerGatingOn) {\n            device.pg_state = MEIPowerGatingOff;\n            if (bus.state != MEIBusIdle) {\n                // Force MEI_H_CSR_READY because it could be wiped off during PG\n                LOG(\"d0i3 set host ready\");\n                enableDevice();\n            }\n        } else\n            device.pg_state = MEIPowerGatingOn;\n        command_gate->commandWakeup(&wait_power_gating);\n    }\n\n    if (device.pg_state == MEIPowerGatingOn && (source & MEI_H_CSR_INT_STA)) {\n        /*\n         * HW sent some data and we are in D0i3,\n         * so we got here because of HW initiated exit from D0i3.\n         */\n        LOG(\"Resuming from d0i3\");\n        resume_work->interruptOccurred(nullptr, this, 0);\n    }\n}\n\nIOReturn SurfaceManagementEngineDriver::handleRead(UInt8 *filled_slots) {\n    MEIBusMessageHeader *msg_hdr;\n    MEIBusExtendedMetaHeader *meta_hdr = nullptr;\n    IOReturn ret = kIOReturnSuccess;\n\n    if (!bus.rx_msg_hdr[0]) {\n        bus.rx_msg_hdr[0] = readRegister(MEI_ME_CB_RW);\n        bus.rx_msg_hdr_len = 1;\n        (*filled_slots)--;\n\n        UInt16 expected_len = 0;\n        msg_hdr = reinterpret_cast<MEIBusMessageHeader *>(bus.rx_msg_hdr);\n        if (msg_hdr->dma_ring)\n            expected_len += MEI_SLOT_SIZE;\n        if (msg_hdr->extended)\n            expected_len += MEI_SLOT_SIZE;\n        if (!bus.rx_msg_hdr[0] || msg_hdr->reserved || msg_hdr->length < expected_len) {\n            LOG(\"Error! Corrupted message header 0x%08X\", bus.rx_msg_hdr[0]);\n            return kIOReturnInvalid;\n        }\n    }\n\n    msg_hdr = reinterpret_cast<MEIBusMessageHeader *>(bus.rx_msg_hdr);\n    if (MEI_SLOTS_TO_DATA(*filled_slots) < msg_hdr->length) {\n        LOG(\"Error! Less data available than length=%08x.\", *filled_slots);\n        /* we can't read the message right now */\n        return kIOReturnNotReadable;\n    }\n    \n    int ext_hdr_len = 1;\n    UInt16 hdr_size_left = msg_hdr->length;\n    if (msg_hdr->extended) {\n        LOG(\"Got extended header\");\n        if (!bus.rx_msg_hdr[1]) {\n            bus.rx_msg_hdr[1] = readRegister(MEI_ME_CB_RW);\n            bus.rx_msg_hdr_len++;\n            (*filled_slots)--;\n        }\n        meta_hdr = reinterpret_cast<MEIBusExtendedMetaHeader *>(&bus.rx_msg_hdr[1]);\n        UInt16 hdr_size_ext = sizeof(MEIBusExtendedMetaHeader) + MEI_SLOTS_TO_DATA(meta_hdr->size);\n        \n        if (hdr_size_left < hdr_size_ext) {\n            LOG(\"Error! Corrupted message header len %d\", msg_hdr->length);\n            return kIOReturnInvalid;\n        }\n        hdr_size_left -= hdr_size_ext;\n        ext_hdr_len = meta_hdr->size + 2; // 2 = MEIBusMessageHeader + MEIBusExtendedMetaHeader\n        for (int i = bus.rx_msg_hdr_len; i < ext_hdr_len; i++) {\n            bus.rx_msg_hdr[i] = readRegister(MEI_ME_CB_RW);\n            bus.rx_msg_hdr_len++;\n            (*filled_slots)--;\n        }\n    }\n    if (msg_hdr->dma_ring) {\n        LOG(\"Got dma ring set\");\n        if (hdr_size_left != MEI_SLOT_SIZE) {\n            LOG(\"Error! Corrupted message header len %d\", msg_hdr->length);\n            return kIOReturnInvalid;\n        }\n        bus.rx_msg_hdr[ext_hdr_len] = readRegister(MEI_ME_CB_RW);\n        bus.rx_msg_hdr_len++;\n        (*filled_slots)--;\n        msg_hdr->length -= MEI_SLOT_SIZE;\n    }\n\n    if (msg_hdr->host_addr == 0 && msg_hdr->me_addr == 0) {\n        //  Host message\n        ret = handleHostMessage(msg_hdr);\n        if (ret != kIOReturnSuccess) {\n            LOG(\"Handle message failed!\");\n            return ret;\n        }\n    } else {\n        // Client message\n        if (!ipts_client || !ipts_client->active || msg_hdr->me_addr != ipts_client->addr) {\n            /*\n             * A message for not connected fixed address clients should be silently discarded\n             * On power down client may be force cleaned, silently discard such messages\n             */\n            if ((msg_hdr->host_addr == 0 && msg_hdr->me_addr != 0) || device.state == MEIDevicePowerDown) {\n                discardMessage(msg_hdr, msg_hdr->length);\n                ret = kIOReturnSuccess;\n            } else {\n                LOG(\"No destination client found 0x%08X\",  bus.rx_msg_hdr[0]);\n                return kIOReturnInvalid;\n            }\n            \n        } else\n            ret = handleClientMessage(ipts_client, msg_hdr, meta_hdr);\n    }\n    // Reset the number of slots and header\n    memset(bus.rx_msg_hdr, 0, sizeof(bus.rx_msg_hdr));\n    bus.rx_msg_hdr_len = 0;\n    if (countRxSlots(filled_slots) != kIOReturnSuccess) {\n        LOG(\"Resetting due to slots overflow\");\n        return kIOReturnOverrun;\n    }\n    return ret;\n}\n\nIOReturn SurfaceManagementEngineDriver::handleHostMessage(MEIBusMessageHeader *header) {\n    MEIBusHostVersionResponse *version_res;\n    MEIBusClientPropertyResponse *props_res;\n    MEIBusHostEnumerationResponse *enum_res;\n    MEIBusAddClientRequest *add_client_req;\n    MEIBusCapabilityResponse *cap_res;\n    \n    MEIHostBusMessageReturnType status;\n    IOReturn ret;\n\n    // read the message to our buffer\n    if (header->length >= sizeof(bus.rx_msg_buf)) {\n        LOG(\"WTF? Message length larger than rx_msg_buf\");\n        return kIOReturnError;\n    }\n    readMessage(bus.rx_msg_buf, header->length);\n    \n    MEIBusMessage *mei_msg = reinterpret_cast<MEIBusMessage *>(bus.rx_msg_buf);\n//    MEIBusClientCommand *cl_cmd = reinterpret_cast<MEIBusClientCommand *>(mei_msg);\n\n    /*\n     * ignore spurious message and prevent reset nesting\n     * bus is put to idle during system reset\n     */\n    if (bus.state == MEIBusIdle) {\n        LOG(\"Bus state is idle, ignore spurious messages\");\n        return kIOReturnSuccess;\n    }\n\n    switch (mei_msg->cmd) {\n        case MEI_HOST_START_RES_CMD:\n            LOG(\"Start response message received\");\n            init_timeout->cancelTimeout();\n            version_res = reinterpret_cast<MEIBusHostVersionResponse *>(mei_msg);\n//            LOG(\"MEI Bus Version: DRIVER=%02d:%02d DEVICE=%02d:%02d\", MEI_HBM_MAJOR_VERSION, MEI_HBM_MINOR_VERSION,\n//                version_res->me_max_version_major, version_res->me_max_version_minor);\n            if (version_res->host_version_supported) {\n                device.version_major = MEI_HBM_MAJOR_VERSION;\n                device.version_minor = MEI_HBM_MINOR_VERSION;\n            } else {\n                device.version_major = version_res->me_max_version_major;\n                device.version_minor = version_res->me_max_version_minor;\n            }\n\n            if (!isBusMessageVersionSupported()) {\n                LOG(\"Warning, start version mismatch - stopping the driver\");\n                bus.state = MEIBusStopped;\n                if (sendStopRequest() != kIOReturnSuccess) {\n                    LOG(\"Error! Failed to send stop request\");\n                    return kIOReturnIOError;\n                }\n                break;\n            }\n            \n            configDeviceFeatures();\n            \n            if (device.state != MEIDeviceInitClients || bus.state != MEIBusStarting) {\n                if (device.state == MEIDevicePowerDown) {\n                    LOG(\"Start on shutdown, ignoring\");\n                    return kIOReturnSuccess;\n                }\n                LOG(\"Error! Start state mismatch, [%d, %d]\", device.state, bus.state);\n                return kIOReturnError;\n            }\n\n            if (device.cap_supported) {\n                if (sendCapabilityRequest() != kIOReturnSuccess) {\n                    LOG(\"Capabilities request failed\");\n                    return kIOReturnIOError;\n                }\n                command_gate->commandWakeup(&wait_bus_start);\n                break;\n            }\n            \n            if (sendClientEnumerationRequest() != kIOReturnSuccess) {\n                LOG(\"Enumeration request failed\");\n                return kIOReturnIOError;\n            }\n            command_gate->commandWakeup(&wait_bus_start);\n            break;\n            \n        case MEI_CAPABILITIES_RES_CMD:\n            LOG(\"Capabilities response message received\");\n            init_timeout->cancelTimeout();\n            if (device.state != MEIDeviceInitClients || bus.state != MEIBusSetupCap) {\n                if (device.state == MEIDevicePowerDown) {\n                    LOG(\"Capabilities response on shutdown, ignoring\");\n                    return kIOReturnSuccess;\n                }\n                LOG(\"Error! Capabilities response state mismatch, [%d, %d]\", device.state, bus.state);\n                return kIOReturnError;\n            }\n\n            cap_res = reinterpret_cast<MEIBusCapabilityResponse *>(mei_msg);\n            if (!(cap_res->capability_granted[0] & MEI_HBM_CAP_VTAG))\n                device.vt_supported = false;\n            if (!(cap_res->capability_granted[0] & MEI_HBM_CAP_CLIENT_DMA))\n                device.cd_supported = false;\n\n            if (sendClientEnumerationRequest() != kIOReturnSuccess) {\n                LOG(\"Enumeration request failed\");\n                return kIOReturnIOError;\n            }\n            break;\n            \n        case MEI_HOST_ENUM_RES_CMD:\n            LOG(\"Enumeration response message received\");\n            init_timeout->cancelTimeout();\n            enum_res = reinterpret_cast<MEIBusHostEnumerationResponse *>(mei_msg);\n            memcpy(me_client_map, enum_res->valid_addresses, sizeof(enum_res->valid_addresses));\n            if (device.state != MEIDeviceInitClients || bus.state != MEIBusEnumerateClients) {\n                if (device.state == MEIDevicePowerDown) {\n                    LOG(\"enumeration response on shutdown, ignoring\");\n                    return kIOReturnSuccess;\n                }\n                LOG(\"Error! Enumeration response state mismatch, [%d, %d]\", device.state, bus.state);\n                return kIOReturnError;\n            }\n\n            bus.state = MEIBusRequestingClientProps;\n            // First client property request\n            if (sendClientPropertyRequest(0) != kIOReturnSuccess) {\n                LOG(\"Error! Properties request failed\");\n                return kIOReturnIOError;\n            }\n            break;\n\n        case MEI_HOST_CLIENT_PROP_RES_CMD:\n            LOG(\"Property response message received\");\n            init_timeout->cancelTimeout();\n            if (device.state != MEIDeviceInitClients || bus.state != MEIBusRequestingClientProps) {\n                if (device.state == MEIDevicePowerDown) {\n                    LOG(\"Properties response on shutdown, ignoring\");\n                    return kIOReturnSuccess;\n                }\n                LOG(\"Error! Properties response state mismatch, [%d, %d]\", device.state, bus.state);\n                return kIOReturnError;\n            }\n\n            props_res = reinterpret_cast<MEIBusClientPropertyResponse *>(mei_msg);\n            if (props_res->status == MEIHostBusMessageReturnClientNotFound) {\n                LOG(\"Warning, client %d not found\", props_res->me_addr);\n            } else if (props_res->status != MEIHostBusMessageReturnSuccess) {\n                LOG(\"Error! Properties response wrong status = %d\", props_res->status);\n                return kIOReturnError;\n            } else {\n                if (addClient(&props_res->client_properties, props_res->me_addr) == kIOReturnInvalid) {\n                    uuid_t swapped_uuid;\n                    uuid_string_t uuid_str;\n                    uuid_copy(swapped_uuid, props_res->client_properties.uuid);\n                    *(reinterpret_cast<UInt32 *>(swapped_uuid)) = OSSwapInt32(*(reinterpret_cast<UInt32 *>(swapped_uuid)));\n                    *(reinterpret_cast<UInt16 *>(swapped_uuid) + 2) = OSSwapInt16(*(reinterpret_cast<UInt16 *>(swapped_uuid) + 2));\n                    *(reinterpret_cast<UInt16 *>(swapped_uuid) + 3) = OSSwapInt16(*(reinterpret_cast<UInt16 *>(swapped_uuid) + 3));\n                    uuid_unparse_lower(swapped_uuid, uuid_str);\n                    LOG(\"Unknown MEI client with uuid %s\", uuid_str);\n                    LOG(\"Ignore non IPTS client, continue to request client properties\");\n                }\n            }\n            // Request property for next client\n            if (sendClientPropertyRequest(props_res->me_addr + 1) != kIOReturnSuccess) {\n                LOG(\"Error! Properties request failed\");\n                return kIOReturnIOError;\n            }\n            break;\n            \n        case MEI_PG_ISOLATION_ENTRY_RES_CMD:\n            LOG(\"Power gating isolation entry response received\");\n            if (device.pg_state != MEIPowerGatingOff || device.pg_event != MEIPowerGatingEventWait) {\n                LOG(\"Power gating entry response, state mismatch [%d, %d]\", device.pg_state, device.pg_event);\n                return kIOReturnError;\n            }\n\n            device.pg_event = MEIPowerGatingEventReceived;\n            command_gate->commandWakeup(&wait_power_gating);\n            break;\n\n        case MEI_PG_ISOLATION_EXIT_REQ_CMD:\n            LOG(\"Power gating isolation exit request received\");\n            if (device.pg_state != MEIPowerGatingOn ||\n                (device.pg_event != MEIPowerGatingEventWait && device.pg_event != MEIPowerGatingEventIdle)) {\n                LOG(\"Power gating exit response state mismatch [%d, %d]\", device.pg_state, device.pg_event);\n                return kIOReturnError;\n            }\n\n            switch (device.pg_event) {\n                case MEIPowerGatingEventWait:\n                    device.pg_event = MEIPowerGatingEventReceived;\n                    command_gate->commandWakeup(&wait_power_gating);\n                    break;\n                case MEIPowerGatingEventIdle:\n                    /*\n                    * If the driver is not waiting on this then\n                    * this is HW initiated exit from PG.\n                    */\n                    device.pg_event = MEIPowerGatingEventReceived;\n                    resume_work->interruptOccurred(nullptr, this, 0);\n                    break;\n                default:\n                    return kIOReturnError;\n            }\n            break;\n\n        case MEI_HOST_STOP_RES_CMD:\n            LOG(\"Stop response message received\");\n            init_timeout->cancelTimeout();\n            if (bus.state != MEIBusStopped) {\n                LOG(\"Error! Stop response state mismatch, [%d, %d]\", device.state, bus.state);\n                return kIOReturnError;\n            }\n            \n            device.state = MEIDevicePowerDown;\n            // force the reset\n            return kIOReturnError;\n\n        case MEI_ME_STOP_REQ_CMD:\n            LOG(\"Stop request message received\");\n            bus.state = MEIBusStopped;\n            if (sendStopRequest() != kIOReturnSuccess) {\n                LOG(\"Error! Stop request failed\");\n                return kIOReturnIOError;\n            }\n            break;\n            \n        case MEI_ADD_CLIENT_REQ_CMD:\n            LOG(\"Add client request received\");\n            // After the host receives the enum resp message clients may be added or removed\n            if (bus.state <= MEIBusEnumerateClients || bus.state >= MEIBusStopped) {\n                LOG(\"Error! Add client state mismatch, [%d, %d]\", device.state, bus.state);\n                return kIOReturnError;\n            }\n            add_client_req = reinterpret_cast<MEIBusAddClientRequest *>(mei_msg);\n            status = MEIHostBusMessageReturnSuccess;\n            ret = addClient(&add_client_req->client_properties, add_client_req->me_addr);\n            if (ret == kIOReturnInvalid)\n                status = MEIHostBusMessageReturnRejected;\n            else if (ret != kIOReturnSuccess)\n                status = MEIHostBusMessageReturnClientNotFound;\n            \n            if (device.state == MEIDeviceEnabled)\n                rescan_work->interruptOccurred(nullptr, this, 0);\n            \n            if (sendAddClientResponse(add_client_req->me_addr, status) != kIOReturnSuccess) {\n                LOG(\"Error! Failed to send add client response\");\n                return kIOReturnIOError;\n            }\n            break;\n\n        default:\n            LOG(\"WTF? Unknown command %X\", mei_msg->cmd);\n            return kIOReturnError;\n\n    }\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceManagementEngineDriver::handleClientMessage(SurfaceManagementEngineClient *client, MEIBusMessageHeader *mei_hdr, MEIBusExtendedMetaHeader *meta) {\n    UInt16 data_len;\n    UInt16 length = mei_hdr->length;\n    \n    if (mei_hdr->extended || mei_hdr->dma_ring)\n        goto discard;\n\n    data_len = length + client->rx_cache_pos;\n    if (client->properties.max_msg_length < data_len) {\n        LOG(\"Warning, message overflow. client max msg size %d, rx msg size %d\", client->properties.max_msg_length, data_len);\n        goto discard;\n    }\n\n    readMessage(client->rx_cache + client->rx_cache_pos, length);\n    client->rx_cache_pos += length;\n\n    if (mei_hdr->msg_complete)\n        client->messageComplete();\n    \n    idle_timeout->setTimeoutMS(MEI_DEVICE_IDLE_TIMEOUT * 1000);\n\n    return kIOReturnSuccess;\ndiscard:\n    discardMessage(mei_hdr, length);\n    return kIOReturnSuccess;\n}\n\nvoid SurfaceManagementEngineDriver::discardMessage(MEIBusMessageHeader *hdr, UInt16 discard_len) {\n    readMessage(bus.rx_msg_buf, discard_len);\n}\n\nIOReturn SurfaceManagementEngineDriver::handleWrite() {\n    if (!acquireWriteBuffer())\n        return kIOReturnAborted;\n    \n    MEIClientTransaction *tx;\n    qe_foreach_element_safe(tx, &bus.tx_queue, entry) {\n        if (submitTransaction(tx))\n            completeTransaction(tx);\n    }\n    return kIOReturnSuccess;\n}\n\nvoid SurfaceManagementEngineDriver::completeTransaction(MEIClientTransaction *tx) {\n    if (tx->blocking)\n        command_gate->commandWakeup(&tx->wait);\n    else {\n        remqueue(&tx->entry);\n        delete[] tx->data;\n        delete tx;\n    }\n}\n\nbool SurfaceManagementEngineDriver::submitTransaction(MEIClientTransaction *tx) {\n    MEIBusMessageHeader msg_hdr;\n    msg_hdr.host_addr = 0;\n    msg_hdr.me_addr = tx->client->addr;\n    msg_hdr.internal = false;\n    msg_hdr.extended = false;\n    msg_hdr.length = 0;\n    \n    UInt16 hdr_len = sizeof(MEIBusMessageHeader) + msg_hdr.length;\n    UInt16 data_len;\n    UInt8 empty_slots;\n    if (findEmptySlots(&empty_slots) != kIOReturnSuccess) {\n        LOG(\"Write buffer overflow detected\");\n        return false;\n    }\n    UInt16 empty_len = MEI_SLOTS_TO_DATA(empty_slots) & MEI_MSG_MAX_LEN_MASK;\n    \n    /**\n     * Split the message only if we can write the whole host buffer\n     * otherwise wait for next time the host buffer is empty.\n     */\n    if (hdr_len + tx->data_len <= empty_len) {\n        data_len = tx->data_len;\n        msg_hdr.msg_complete = 1;\n    } else if (empty_slots == device.tx_buf_depth) {\n        data_len = empty_len - hdr_len;\n        msg_hdr.msg_complete = 0;\n    } else\n        return false;\n    \n    msg_hdr.length += data_len;\n    \n    if (writeMessage(reinterpret_cast<UInt8 *>(&msg_hdr), hdr_len, tx->data, data_len) != kIOReturnSuccess)\n        return true;    // delete this transaction in case of error but leave tx->completed=false\n    \n    if (msg_hdr.msg_complete) {\n        tx->completed = true;\n        return true;\n    } else {\n        tx->data += data_len;\n        tx->data_len -= data_len;\n        return false;\n    }\n}\n\nvoid SurfaceManagementEngineDriver::enterIdle(IOTimerEventSource *timer) {\n    IOReturn ret;\n    if (isWriteQueueEmpty())\n        ret = enterPowerGatingSync();\n    else\n        ret = kIOReturnBusy;\n    \n    if (ret != kIOReturnSuccess && ret != kIOReturnBusy) {\n        LOG(\"Warning! Enter d0i3 failed. Resetting...\");\n        reset_work->interruptOccurred(nullptr, this, 0);\n    } else if (ret == kIOReturnBusy)\n        idle_timeout->setTimeoutMS(MEI_DEVICE_IDLE_TIMEOUT * 1000);\n}\n\nvoid SurfaceManagementEngineDriver::initialiseTimeout(IOTimerEventSource *timer) {\n    if (device.state == MEIDeviceInitClients && bus.state != MEIBusIdle) {\n        LOG(\"Init clients timeout\");\n        resetDevice();\n    }\n}\n\nIOReturn SurfaceManagementEngineDriver::addClient(MEIClientProperty *client_props, UInt8 addr) {\n    if (uuid_compare(SURFACE_IPTS_CLIENT_UUID, client_props->uuid) != 0)\n        return kIOReturnInvalid;\n\n    if (!ipts_client) {\n        ipts_client = OSTypeAlloc(SurfaceManagementEngineClient);\n        if (!ipts_client || !ipts_client->init()) {\n            LOG(\"Failed to create ipts client\");\n            OSSafeReleaseNULL(ipts_client);\n            return kIOReturnError;\n        }\n    }\n    ipts_client->resetProperties(client_props, addr);\n    return kIOReturnSuccess;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineDriver.hpp",
    "content": "//\n//  SurfaceManagementEngineDriver.hpp\n//  SurfaceTouchScreen\n//\n//  Created by Xavier on 2022/05/28.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#ifndef SurfaceManagementEngineDriver_hpp\n#define SurfaceManagementEngineDriver_hpp\n\n#include <IOKit/IOCommandGate.h>\n#include <IOKit/IOTimerEventSource.h>\n#include <IOKit/IOFilterInterruptEventSource.h>\n#include <IOKit/pci/IOPCIDevice.h>\n\n#include <IOKit/IOBufferMemoryDescriptor.h>\n#include <IOKit/IODMACommand.h>\n\n#include \"MEIProtocol.h\"\n\n#define kIOPMPowerOff                       0\n#define kIOPMNumberPowerStates              2\nstatic IOPMPowerState MyIOPMPowerStates[kIOPMNumberPowerStates] = {\n    {1, kIOPMPowerOff, kIOPMPowerOff, kIOPMPowerOff, 0, 0, 0, 0, 0, 0, 0, 0},\n    {1, kIOPMPowerOn, kIOPMPowerOn, kIOPMPowerOn, 0, 0, 0, 0, 0, 0, 0, 0}\n};\n\nenum MEIDeviceState {\n    MEIDeviceInitializing = 0,\n    MEIDeviceInitClients,\n    MEIDeviceEnabled,\n    MEIDeviceResetting,\n    MEIDeviceDisabled,\n    MEIDevicePowerDown,\n    MEIDevicePowerUp,\n};\n\n/**\n * enum MEIBusState - host bus message protocol state\n *\n * @MEIBusIdle              : protocol not started\n * @MEIBusStarting          : start request message was sent\n * @MEIBusSetupCap          : capabilities request message was sent\n * @MEIBusSetupDMARing      : dma ring setup request message was sent\n * @MEIBusEnumerateClients  : enumeration request was sent\n * @MEIBusRequestingClientProps : acquiring clients properties\n * @MEIBusStarted           : enumeration was completed\n * @MEIBusStopped           : stopping exchange\n */\nenum MEIBusState {\n    MEIBusIdle = 0,\n    MEIBusStarting,\n    MEIBusSetupCap,\n    MEIBusSetupDMARing,\n    MEIBusEnumerateClients,\n    MEIBusRequestingClientProps,\n    MEIBusStarted,\n    MEIBusStopped,\n};\n\n/**\n * enum MEIPowerGatingEvent - power gating transition events\n *\n * @MEIPowerGatingEventIdle         : the driver is not in power gating transition\n * @MEIPowerGatingEventWait         : the driver is waiting for a pg event to complete\n * @MEIPowerGatingEventReceived     : the driver received pg event\n * @MEIPowerGatingInterruptWait     : the driver is waiting for a pg event interrupt\n * @MEIPowerGatingInterruptReceived : the driver received pg event interrupt\n */\nenum MEIPowerGatingEvent {\n    MEIPowerGatingEventIdle,\n    MEIPowerGatingEventWait,\n    MEIPowerGatingEventReceived,\n    MEIPowerGatingInterruptWait,\n    MEIPowerGatingInterruptReceived,\n};\n\n/**\n * enum MEIPowerGatingState - device internal power gating state\n *\n * @MEIPowerGatingOff   : device is not power gated - it is active\n * @MEIPowerGatingOn    : device is power gated - it is in lower power state\n */\nenum MEIPowerGatingState {\n    MEIPowerGatingOff = 0,\n    MEIPowerGatingOn  = 1,\n};\n\nstruct MEIPhysicalDevice {\n    IOPCIDevice*        pci_dev;\n    IOMemoryMap*        mmap;\n    MEIDeviceState      state;\n    MEIPowerGatingEvent pg_event;\n    MEIPowerGatingState pg_state;\n    queue_head_t        write_q;\n    queue_head_t        write_waiting_q;\n    queue_head_t        write_ctrl_q;\n    queue_head_t        read_ctrl_q;\n    int     reset_cnt;\n    UInt8   tx_buf_depth;\n    UInt8   version_minor;\n    UInt8   version_major;\n    bool    pg_supported;       // power gating isolation\n    bool    dc_supported;       // dynamic clients\n    bool    dot_supported;      // disconnect on timeout\n    bool    ev_supported;       // event notification\n    bool    fa_supported;       // fixed address client\n    bool    ie_supported;       // immediate reply to enum request\n    bool    os_supported;       // support OS ver message\n    bool    dr_supported;       // dma ring\n    bool    vt_supported;       // vtag\n    bool    cap_supported;      // capabilities message\n    bool    cd_supported;       // client dma\n};\n\nclass SurfaceManagementEngineClient;\n\nstruct MEIClientTransaction {\n    queue_entry entry;\n    SurfaceManagementEngineClient *client;\n    UInt8*  data;\n    UInt16  data_len;\n    bool    completed;\n    bool    blocking;\n    bool    wait;\n};\n\nstruct MEIBus {\n    MEIBusState     state;\n    UInt8           rx_msg_buf[MEI_RX_MSG_BUF_SIZE];\n    MEI_SLOT_TYPE   rx_msg_hdr[MEI_RX_MSG_BUF_SIZE];\n    int             rx_msg_hdr_len;\n    bool            tx_buf_ready;\n    UInt8           tx_queue_limit;\n    queue_head_t    tx_queue;\n};\n\nUUID_DEFINE(SURFACE_IPTS_CLIENT_UUID, 0x70, 0x08, 0x8d, 0x3e, 0x1a, 0x27, 0x08, 0x42, 0x8e, 0xb5, 0x9a, 0xcb, 0x94, 0x02, 0xae, 0x04);\n\n/*\n * Implements a MEI based IPTS driver\n * fixed_addr=12 vt_supported=0\n */\nclass EXPORT SurfaceManagementEngineDriver : public IOService {\n    OSDeclareDefaultStructors(SurfaceManagementEngineDriver);\n\n public:\n    bool init(OSDictionary* properties) override;\n    \n    IOService* probe(IOService* provider, SInt32* score) override;\n    \n    bool start(IOService* provider) override;\n\n    void stop(IOService* provider) override;\n\n    void free() override;\n    \n    IOReturn setPowerState(unsigned long whichState, IOService *whatDevice) override;\n    \n    IOReturn sendClientMessage(SurfaceManagementEngineClient *client, UInt8 *buffer, UInt16 buffer_len, bool blocking);\n    \nprotected:\n    IOReturn mapMemory();\n\n    void unmapMemory();\n\nprivate:\n    IOWorkLoop*                     work_loop {nullptr};\n    IOCommandGate*                  command_gate {nullptr};\n    IOFilterInterruptEventSource*   interrupt_source {nullptr};\n    IOInterruptEventSource*         reset_work {nullptr};\n    IOInterruptEventSource*         rescan_work {nullptr};\n    IOInterruptEventSource*         resume_work {nullptr};\n    IOTimerEventSource*             init_timeout {nullptr};\n    IOTimerEventSource*             idle_timeout {nullptr};\n    SurfaceManagementEngineClient*  ipts_client {nullptr};\n    IOCommandGate::Action           client_msg_action {nullptr};\n    \n    MEIPhysicalDevice   device;\n    MEIBus              bus;\n    UInt8               me_client_map[MEI_MAX_CLIENT_NUM/8];\n    \n    bool awake {true};\n    bool wait_hw_ready {false};\n    bool wait_bus_start {false};\n    bool wait_power_gating {false};\n\n    void releaseResources();\n    \n    IOReturn startDeviceGated();\n    void stopDeviceGated();\n    IOReturn restartDeviceGated();\n    \n    inline UInt32 readRegister(int offset);\n    inline void writeRegister(UInt32 value, int offset);\n    \n    UInt8 calcFilledSlots();\n    IOReturn findEmptySlots(UInt8 *empty_slots);\n    IOReturn countRxSlots(UInt8 *filled_slots);\n    bool acquireWriteBuffer();\n    \n    bool isHardwareReady();\n    bool isHostReady();\n    bool isBusMessageVersionSupported();\n    bool isWriteQueueEmpty();\n    \n    inline void setHostCSR(UInt32 hcsr);\n    \n    IOReturn initDevice();\n    void configDevice();\n    IOReturn resetDevice();\n    void deresetDevice();\n    void enableDevice();\n    IOReturn waitDeviceReady();\n    void configDeviceFeatures();\n    \n    void resetBus();\n    \n    void clearInterrupts();\n    void enableInterrupts();\n    void disableInterrupts();\n    void setHostInterrupt();\n    \n    IOReturn enterPowerGating();\n    IOReturn enterPowerGatingSync();\n    IOReturn exitPowerGatingSync();\n    \n    void readMessage(UInt8 *buffer, UInt16 buffer_len);\n    \n    IOReturn writeMessage(UInt8 *header, UInt16 header_len, UInt8 *data, UInt16 data_len);\n    inline void setupMessageHeader(MEIBusMessageHeader *header, UInt16 length);\n    IOReturn writeHostMessage(MEIBusMessageHeader *header, MEIBusMessage *msg);\n    IOReturn sendClientMessageGated(SurfaceManagementEngineClient *client, UInt8 *buffer, UInt16 *buffer_len, bool *blocking);\n    IOReturn sendStartRequest();\n    IOReturn sendStopRequest();\n    IOReturn sendPowerGatingCommand(bool enter);\n    IOReturn sendCapabilityRequest();\n    IOReturn sendClientEnumerationRequest();\n    IOReturn sendClientPropertyRequest(UInt client_idx);\n    IOReturn sendAddClientResponse(UInt8 me_addr, MEIHostBusMessageReturnType status);\n    \n    void scheduleReset(IOInterruptEventSource *sender, int count);\n    void scheduleRescan(IOInterruptEventSource *sender, int count);\n    void scheduleResume(IOInterruptEventSource *sender, int count);\n    \n    bool filterInterrupt(IOFilterInterruptEventSource *sender);\n    void handleInterrupt(IOInterruptEventSource *sender, int count);\n    \n    void handlePowerGatingInterrupt(UInt32 source);\n    \n    IOReturn handleRead(UInt8 *filled_slots);\n    IOReturn handleHostMessage(MEIBusMessageHeader *hdr);\n    IOReturn handleClientMessage(SurfaceManagementEngineClient *client, MEIBusMessageHeader *mei_hdr, MEIBusExtendedMetaHeader *meta);\n    void discardMessage(MEIBusMessageHeader *hdr, UInt16 discard_len);\n        \n    IOReturn handleWrite();\n    void completeTransaction(MEIClientTransaction *tx);\n    bool submitTransaction(MEIClientTransaction *tx);\n    \n    void enterIdle(IOTimerEventSource *timer);\n    void initialiseTimeout(IOTimerEventSource *timer);\n    \n    IOReturn addClient(MEIClientProperty *client_props, UInt8 addr);\n};\n\n#endif /* SurfaceManagementEngineDriver_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceSerialHub/SerialProtocol.h",
    "content": "//\n//  SerialProtocol.h\n//  SurfaceSerialHub\n//\n//  Created by Xavier on 2021/10/29.\n//  Copyright © 2021 Xia Shangning. All rights reserved.\n//\n\n#ifndef SerialProtocol_h\n#define SerialProtocol_h\n\n#include \"../helpers.hpp\"\n\n/* SSH Protocol Config see https://github.com/linux-surface/surface-aggregator-module/blob/master/doc/requests.txt for reference*/\n#define SSH_TC_SAM              0x01    /* Generic system functionality, real-time clock. */\n#define SSH_TC_BAT              0x02    /* Battery/power subsystem. */\n#define SSH_TC_TMP              0x03    /* Thermal subsystem. */\n#define SSH_TC_PMC              0x04\n#define SSH_TC_FAN              0x05\n#define SSH_TC_PoM              0x06\n#define SSH_TC_DBG              0x07\n#define SSH_TC_KBD              0x08    /* Legacy keyboard (Laptop 1/2). */\n#define SSH_TC_FWU              0x09\n#define SSH_TC_UNI              0x0a\n#define SSH_TC_LPC              0x0b\n#define SSH_TC_TCL              0x0c    /* Telemetry, Crashdumps, and Logs? */\n#define SSH_TC_SFL              0x0d\n#define SSH_TC_KIP              0x0e    /* Keyboard and Integrated Peripherals. (hotplug stuff) */\n#define SSH_TC_EXT              0x0f\n#define SSH_TC_BLD              0x10\n#define SSH_TC_BAS              0x11    /* Detachment system (Surface Book 2/3). */\n#define SSH_TC_SEN              0x12\n#define SSH_TC_SRQ              0x13\n#define SSH_TC_MCU              0x14\n#define SSH_TC_HID              0x15    /* User Input/HID subsystem (Keyboard + Touchpad). */\n#define SSH_TC_TCH              0x16\n#define SSH_TC_BKL              0x17\n#define SSH_TC_TAM              0x18\n#define SSH_TC_ACC0             0x19\n#define SSH_TC_UFI              0x1a\n#define SSH_TC_USC              0x1b\n#define SSH_TC_PEN              0x1c\n#define SSH_TC_VID              0x1d\n#define SSH_TC_AUD              0x1e\n#define SSH_TC_SMC              0x1f\n#define SSH_TC_KPD              0x20\n#define SSH_TC_REG              0x21    /* Event/notifier registry. */\n#define SSH_TC_SPT              0x22\n#define SSH_TC_SYS              0x23\n#define SSH_TC_ACC1             0x24\n#define SSH_TC_SHB              0x25\n#define SSH_TC_POS              0x26    /* Laptop Studio screen position. */\n\n#define SSH_TC_COUNT            0x26\n\n#define SSH_TID_PRIMARY         0x01\n#define SSH_TID_SECONDARY       0x02\n\n/* TC=0x01 */\n#define SSH_CID_SAM_ENABLE_EVENT    0x0B\n#define SSH_CID_SAM_DISABLE_EVENT   0x0C\n#define SSH_CID_SAM_VERSION         0x13\n#define SSH_CID_SAM_DISPLAY_OFF     0x15\n#define SSH_CID_SAM_DISPLAY_ON      0x16\n#define SSH_CID_SAM_D0_EXIT         0x33\n#define SSH_CID_SAM_D0_ENTRY        0x34\n/* TC=0x02 */\n#define SSH_CID_BAT_STA             0x01\n#define SSH_CID_BAT_BIX             0x02\n#define SSH_CID_BAT_BST             0x03\n#define SSH_CID_BAT_PMAX            0x0B\n#define SSH_CID_BAT_PSOC            0x0C\n#define SSH_CID_BAT_PSR             0x0D\n#define SSH_EVENT_CID_BAT_BIX       0x15\n#define SSH_EVENT_CID_BAT_BST       0x16\n#define SSH_EVENT_CID_BAT_PSR       0x17\n/* TC=0x03 */\n#define SSH_CID_TMP_SENSOR          0x01\n#define SSH_CID_TMP_GET_PERF        0x02\n#define SSH_CID_TMP_SET_PERF        0x03\n#define SSH_TEMP_SENSOR_MB1         0x01\n#define SSH_TEMP_SENSOR_MB2         0x02\n#define SSH_TEMP_SENSOR_MB3         0x03\n#define SSH_TEMP_SENSOR_MB4         0x04\n#define SSH_TEMP_SENSOR_BAT         0x05\n#define SSH_TEMP_SENSOR_GPU         0x06\n#define SSH_TEMP_SENSOR_SSD         0x07\n#define SSH_TEMP_SENSOR_SOC         0x08\n/* TC=0x08 */\n#define SSH_CID_KBD_GET_DESCRIPTOR      0x00\n#define SSH_CID_KBD_SET_CAPS_LED        0x01\n#define SSH_CID_KBD_GET_FEAT_REPORT     0x0B\n#define SSH_EVENT_CID_KBD_INPUT_GENERIC 0x03\n#define SSH_EVENT_CID_KBD_INPUT_HOTKEYS 0x04\n/* TC=0x0e */\n#define SSH_CID_KIP_ENABLE_EVENT    0x27\n#define SSH_CID_KIP_DISABLE_EVENT   0x28\n/* TC=0x15 */\n#define SSH_CID_HID_OUT_REPORT      0x01\n#define SSH_CID_HID_GET_FEAT_REPORT 0x02\n#define SSH_CID_HID_SET_FEAT_REPORT 0x03\n#define SSH_CID_HID_GET_DESCRIPTOR  0x04\n#define SSH_EVENT_CID_HID_INPUT     0x00\n/* TC=0x21 */\n#define SSH_CID_REG_ENABLE_EVENT    0x01\n#define SSH_CID_REG_DISABLE_EVENT   0x02\n\n#define SSH_EVENT_FLAG_SEQUENCED    BIT(0)\n\n#define SSH_SYN_BYTE_1  0xAA\n#define SSH_SYN_BYTE_2  0x55\n#define SSH_SYN_BYTES   0x55AA              /* Together as a 16-bit integer*/\n\n#define SSH_FRAME_TYPE_NAK          0x04    /* Sent on error in previously received message. */\n#define SSH_FRAME_TYPE_ACK          0x40    /* Sent to acknowledge receival of DATA frame. */\n#define SSH_FRAME_TYPE_DATA_SEQ     0x80    /* Sent to transfer data. Sequenced. */\n#define SSH_FRAME_TYPE_DATA_NSQ     0x00    /* Same as DATA_SEQ, but does not need to be ACKed. */\n\n#define SSH_PAYLOAD_TYPE_COMMAND    0x80\n\n/*\n * -- SYN FRAME CRC(F) PAYLOAD CRC(P) --\n *                      CMD+DATA\n */\n#define SSH_PAYLOAD_OFFSET          sizeof(SurfaceSerialMessage)\n\n#ifndef PACKED\n#define PACKED __attribute__((packed))\n#endif\n\nstruct PACKED SurfaceSerialFrame {\n    UInt8  type;\n    UInt16 length;\n    UInt8  seq_id;\n};\n\nstruct PACKED SurfaceSerialPayload {\n    UInt8 type;\n    UInt8 data[];\n};\n\nstruct PACKED SurfaceSerialCommand {\n    UInt8  type;            /* command type payload = 0x80 */\n    UInt8  target_category;\n    UInt8  target_id_out;   /* to SAM (request) */\n    UInt8  target_id_in;    /* from SAM (response) */\n    UInt8  instance_id;\n    UInt16 request_id;      /* request<->response, events->reserved id set by command `enable event source`*/\n    UInt8  command_id;\n    UInt8  data[];\n};\n\nstruct PACKED SurfaceSerialMessage {\n    UInt16 syn;\n    SurfaceSerialFrame frame;\n    UInt16 frame_crc;\n    UInt8  payload[];\n};\n\nstruct PACKED SurfaceSerialEventData {\n    UInt8  target_category;\n    UInt8  flags;\n    UInt16 request_id;      /* the request id used for the event*/\n    UInt8  instance_id;\n};\n\n#define CRC_INITIAL     0xFFFF\n\nUInt16 const crc_ccitt_false_table[256] = {\n    0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,\n    0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,\n    0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,\n    0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,\n    0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,\n    0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,\n    0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,\n    0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,\n    0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,\n    0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,\n    0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,\n    0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,\n    0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,\n    0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,\n    0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,\n    0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,\n    0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,\n    0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,\n    0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,\n    0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,\n    0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,\n    0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,\n    0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,\n    0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,\n    0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,\n    0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,\n    0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,\n    0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,\n    0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,\n    0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,\n    0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,\n    0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0\n};\n\nstatic inline UInt16 crc_ccitt_false_byte(UInt16 crc, const UInt8 c)\n{\n    return (crc << 8) ^ crc_ccitt_false_table[(crc >> 8) ^ c];\n}\n\ninline UInt16 crc_ccitt_false(UInt16 crc, UInt8 const* buffer, size_t len)\n{\n    while (len--)\n        crc = crc_ccitt_false_byte(crc, *buffer++);\n    return crc;\n}\n\n#endif /* SerialProtocol_h */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceSerialHub/SurfaceSerialHubDriver.cpp",
    "content": "//\n//  SurfaceSerialHubDriver.cpp\n//  SurfaceSerialHub\n//\n//  Created by Xavier on 2021/10/29.\n//  Copyright © 2021 Xia Shangning. All rights reserved.\n//\n\n#include \"SurfaceSerialHubDriver.hpp\"\n#include \"../../../Dependencies/VoodooSerial/VoodooSerial/ACPIParser/VoodooACPIResourcesParser.hpp\"\n#include \"../SurfaceSerialHubDevices/SurfaceBatteryNub.hpp\"\n#include \"../SurfaceSerialHubDevices/SurfaceHIDNub.hpp\"\n\nstruct SurfaceSerialEventRegistryConfig {\n    UInt8 target_category;\n    UInt8 target_id;\n    UInt8 cid_enable;\n    UInt8 cid_disable;\n};\n\nstatic const SurfaceSerialEventRegistryConfig event_conf[] = {\n    {SSH_TC_SAM, SSH_TID_PRIMARY, SSH_CID_SAM_ENABLE_EVENT, SSH_CID_SAM_DISABLE_EVENT},\n    {SSH_TC_REG, SSH_TID_SECONDARY, SSH_CID_REG_ENABLE_EVENT, SSH_CID_REG_DISABLE_EVENT},\n    {SSH_TC_KIP, SSH_TID_SECONDARY, SSH_CID_KIP_ENABLE_EVENT, SSH_CID_KIP_DISABLE_EVENT},\n};\n\nOSDefineMetaClassAndAbstractStructors(SurfaceSerialHubClient, IOService);\n\n#define super IOService\nOSDefineMetaClassAndStructors(SurfaceSerialHubDriver, IOService);\n\nvoid err_dump(const char *name, const char *str, UInt8 *buffer, UInt16 len) {\n    IOLog(\"%s::%s\\n\", name, str);\n    if (len == 0)\n        return;\n    IOLog(\"%s::msg dump: length: %d\\n\", name, len);\n    int row = (len-1)/16 + 1;\n    for (int r=0; r<row; r++) {\n        UInt8 line[16] = {0};\n        for (int i=0; i < 16 && r*16+i < len; i++) {\n            line[i] = buffer[r*16+i];\n        }\n        IOLog(\"%s::%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x \\n\", name, line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9], line[10], line[11], line[12], line[13], line[14], line[15]);\n    }\n}\n\n// We try our best to determine if it is the real syn bytes... Let's hope we are not that unlucky\nbool judge_sync(UInt8 *buffer, UInt16 len) {\n    if (buffer[0] == SSH_SYN_BYTE_2) {\n        if (len >= 2 && buffer[1]!=SSH_FRAME_TYPE_NAK && buffer[1]!=SSH_FRAME_TYPE_ACK && buffer[1]!=SSH_FRAME_TYPE_DATA_SEQ && buffer[1]!=SSH_FRAME_TYPE_DATA_NSQ)\n            return false;\n        // minimum length required for data transfer is 0x08=sizeof(SurfaceSerialFrame)\n        if (len >= 4 && buffer[1]==SSH_FRAME_TYPE_DATA_NSQ && buffer[2]<sizeof(SurfaceSerialFrame) && buffer[3]==0x00)\n            return false;\n        return true;\n    }\n    return false;\n}\n\nint find_sync_bytes(UInt8 *buffer, UInt16 len) {\n    for (int i=0; i<len-1; i++) {\n        if (buffer[i] == SSH_SYN_BYTE_1 && judge_sync(buffer+i+1, len-i-1))\n            return i;\n    }\n    return -1;\n}\n\nvoid SurfaceSerialHubDriver::bufferReceived(VoodooUARTController *sender, UInt8 *buffer, UInt16 length) {\n    if (!awake)\n        return;\n    if (SSH_RING_BUFFER_NEXT(last) == current && ring_buffer[current].filled_len) {\n        LOG(\"Overrun!\");\n        return;\n    }\n    \n    last = SSH_RING_BUFFER_NEXT(last);\n    memcpy(ring_buffer[last].buffer, buffer, length);\n    ring_buffer[last].filled_len = length;\n    uart_interrupt->interruptOccurred(nullptr, this, 0);\n}\n\nvoid SurfaceSerialHubDriver::processReceivedBuffer(IOInterruptEventSource *sender, int count) {\n    while (ring_buffer[current].filled_len) {\n        _process(ring_buffer[current].buffer, ring_buffer[current].filled_len);\n        ring_buffer[current].filled_len = 0;\n        current = SSH_RING_BUFFER_NEXT(current);\n    }\n}\n\nvoid SurfaceSerialHubDriver::_process(UInt8 *buffer, UInt16 length) {\n    if (length == 0)\n        return;\n    if (rx_msg.partial_syn) {\n        if (judge_sync(buffer, length)) {\n            processMessage();\n            rx_msg.pos = 1;\n            rx_msg.cache[0] = SSH_SYN_BYTE_1;\n        } else {\n            rx_msg.cache[rx_msg.pos++] = SSH_SYN_BYTE_1;\n        }\n        rx_msg.partial_syn = false;\n    }\n    int end = find_sync_bytes(buffer, length);\n    if (end != -1) {    // found sync bytes\n        if (end > 0) {\n            memcpy(rx_msg.cache+rx_msg.pos, buffer, end);\n            rx_msg.pos += end;\n        }\n        if (rx_msg.pos > 0) {  // a message is completed\n            processMessage();\n            buffer += end;\n            length -= end;\n        }\n        rx_msg.pos = 2;\n        rx_msg.cache[0] = SSH_SYN_BYTE_1;\n        rx_msg.cache[1] = SSH_SYN_BYTE_2;\n        _process(buffer+2, length-2);\n    } else {\n        if (buffer[length-1] == SSH_SYN_BYTE_1) {\n            memcpy(rx_msg.cache+rx_msg.pos, buffer, length-1);\n            rx_msg.pos += length-1;\n            rx_msg.partial_syn = true;\n        } else {\n            memcpy(rx_msg.cache+rx_msg.pos, buffer, length);\n            rx_msg.pos += length;\n        }\n        if (rx_msg.pos >= 5 && rx_msg.len == SSH_MSG_LENGTH_UNKNOWN)\n            rx_msg.len = reinterpret_cast<SurfaceSerialMessage *>(rx_msg.cache)->frame.length+10;\n        if (rx_msg.pos == rx_msg.len) {  // a message is completed\n            processMessage();\n            if (rx_msg.partial_syn) {  // certainly another message\n                rx_msg.pos = 1;\n                rx_msg.cache[0] = SSH_SYN_BYTE_1;\n                rx_msg.partial_syn = false;\n            }\n        }\n    }\n}\n\n#define ERR_DUMP_MSG(str) err_dump(getName(), str, rx_msg.cache, rx_msg.pos)\n\nIOReturn SurfaceSerialHubDriver::processMessage() {\n    if (rx_msg.pos < 10) {\n        sendNAK();\n        ERR_DUMP_MSG(\"Message received incomplete! Protential data loss!\");\n        return kIOReturnError;\n    }\n    SurfaceSerialMessage *message = reinterpret_cast<SurfaceSerialMessage *>(rx_msg.cache);\n    SurfaceSerialCommand *command;\n    UInt8 *rx_data;\n    UInt16 calc_crc, crc, rx_data_len;\n    WaitingRequest *req;\n    PendingCommand *cmd;\n    bool found = false;\n    if (message->syn != SSH_SYN_BYTES) {\n        sendNAK();\n        ERR_DUMP_MSG(\"syn btyes error!\");\n        return kIOReturnError;\n    }\n    if (message->frame_crc != crc_ccitt_false(CRC_INITIAL, rx_msg.cache+2, sizeof(SurfaceSerialFrame))) {\n        sendNAK();\n        ERR_DUMP_MSG(\"frame crc error!\");\n        return kIOReturnError;\n    }\n    if (rx_msg.pos != message->frame.length+10) {\n        sendNAK();\n        ERR_DUMP_MSG(\"data length error!\");\n        return kIOReturnError;\n    }\n    switch (message->frame.type) {\n        case SSH_FRAME_TYPE_ACK:\n            if (rx_msg.cache[SSH_PAYLOAD_OFFSET]!=0xFF || rx_msg.cache[SSH_PAYLOAD_OFFSET+1]!=0xFF) {\n                sendNAK();\n                ERR_DUMP_MSG(\"payload crc for ACK should be 0xFFFF!\");\n                return kIOReturnError;\n            }\n            qe_foreach_element_safe(cmd, &pending_list, entry) {\n                SurfaceSerialMessage *pending_msg = reinterpret_cast<SurfaceSerialMessage *>(cmd->buffer);\n                if (pending_msg->frame.seq_id == message->frame.seq_id) {\n                    found = true;\n                    remqueue(&cmd->entry);\n                    cmd->timer->cancelTimeout();\n                    cmd->timer->disable();\n                    work_loop->removeEventSource(cmd->timer);\n                    OSSafeReleaseNULL(cmd->timer);\n                    delete[] cmd->buffer;\n                    delete cmd;\n                    break;\n                }\n            }\n            if (!found)\n                DBG_LOG(\"Warning, no pending command found for seq_id %d\", message->frame.seq_id);\n            break;\n        case SSH_FRAME_TYPE_NAK:\n            LOG(\"Warning, NAK received! Resending all pending messages!\");\n            qe_foreach_element(cmd, &pending_list, entry) {\n                if (cmd->trial_count) {     // not a NSQ command\n                    cmd->trial_count = 1;\n                    cmd->timer->cancelTimeout();\n                    cmd->timer->setTimeoutUS(1);\n                }\n            }\n            break;\n        case SSH_FRAME_TYPE_DATA_SEQ:\n            sendACK(message->frame.seq_id);\n        case SSH_FRAME_TYPE_DATA_NSQ:\n            command = reinterpret_cast<SurfaceSerialCommand *>(rx_msg.cache+SSH_PAYLOAD_OFFSET);\n            rx_data = command->data;\n            rx_data_len = message->frame.length - sizeof(SurfaceSerialCommand);\n            calc_crc = crc_ccitt_false(CRC_INITIAL, rx_msg.cache+SSH_PAYLOAD_OFFSET, message->frame.length);\n            crc = *(reinterpret_cast<UInt16 *>(rx_data+rx_data_len));\n            if (crc != calc_crc) {\n                sendNAK();\n                ERR_DUMP_MSG(\"payload crc error!\");\n                return kIOReturnError;\n            }\n            if (command->request_id >= SSH_REQID_MIN) { // a message\n                qe_foreach_element_safe(req, &waiting_list, entry) {\n                    if (req->req_id == command->request_id) {\n                        found = true;\n                        if (rx_data_len) {\n                            req->data = new UInt8[rx_data_len];\n                            req->data_len = rx_data_len;\n                            memcpy(req->data, rx_data, rx_data_len);\n                        }\n                        command_gate->commandWakeup(&req->waiting);\n                        remqueue(&req->entry);\n                        break;\n                    }\n                }\n                if (!found)\n                    DBG_LOG(\"Warning, received data with unknown tc %x, cid %x\", command->target_category, command->command_id);\n            } else {    // an event\n                if (!queue_empty(&event_handler_lists[command->request_id]) || !queue_empty(&event_handler_lists[0])) {\n                    EventHandler *h;\n                    bool handled = false;\n                    qe_foreach_element(h, &event_handler_lists[0], entry) {\n                        if (h->target_iid == 0 || h->target_iid == command->instance_id) {\n                            h->client->eventReceived(command->target_category, command->target_id_in, command->instance_id, command->command_id, rx_data, rx_data_len);\n                            handled = true;\n                        }\n                    }\n                    qe_foreach_element(h, &event_handler_lists[command->request_id], entry) {\n                        if (h->target_iid == 0 || h->target_iid == command->instance_id) {\n                            h->client->eventReceived(command->target_category, command->target_id_in, command->instance_id, command->command_id, rx_data, rx_data_len);\n                            handled = true;\n                        }\n                    }\n                    if (!handled)\n                        DBG_LOG(\"Warning, registered event unhandled with unknown iid %x (tc %x, cid %x)\", command->instance_id, command->target_category, command->command_id);\n                } else\n                    ERR_DUMP_MSG(\"Event unregistered!\");\n            }\n            break;\n        default:\n            sendNAK();\n            ERR_DUMP_MSG(\"Unknown message type!\");\n            return kIOReturnError;\n    }\n    \n    rx_msg.pos = 0;\n    rx_msg.len = SSH_MSG_LENGTH_UNKNOWN;\n    \n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceSerialHubDriver::sendACK(UInt8 seq_id) {\n    UInt8 buffer[SSH_PAYLOAD_OFFSET+2];\n    SurfaceSerialMessage *msg = reinterpret_cast<SurfaceSerialMessage *>(buffer);\n    msg->syn = SSH_SYN_BYTES;\n    msg->frame.type = SSH_FRAME_TYPE_ACK;\n    msg->frame.length = 0;\n    msg->frame.seq_id = seq_id;\n    msg->frame_crc = crc_ccitt_false(CRC_INITIAL, buffer+2, sizeof(SurfaceSerialFrame));\n    buffer[SSH_PAYLOAD_OFFSET] = 0xFF;\n    buffer[SSH_PAYLOAD_OFFSET+1] = 0xFF;\n    return uart_controller->transmitData(buffer, SSH_PAYLOAD_OFFSET+2);\n}\n\nIOReturn SurfaceSerialHubDriver::sendNAK() {\n    UInt8 buffer[SSH_PAYLOAD_OFFSET+2];\n    SurfaceSerialMessage *msg = reinterpret_cast<SurfaceSerialMessage *>(buffer);\n    msg->syn = SSH_SYN_BYTES;\n    msg->frame.type = SSH_FRAME_TYPE_NAK;\n    msg->frame.length = 0;\n    msg->frame.seq_id = 0;\n    msg->frame_crc = crc_ccitt_false(CRC_INITIAL, buffer+2, sizeof(SurfaceSerialFrame));\n    buffer[SSH_PAYLOAD_OFFSET] = 0xFF;\n    buffer[SSH_PAYLOAD_OFFSET+1] = 0xFF;\n    return uart_controller->transmitData(buffer, SSH_PAYLOAD_OFFSET+2);\n}\n\nUInt16 SurfaceSerialHubDriver::sendCommand(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *payload, UInt16 payload_len, bool seq) {\n    if (!awake)\n        return 0;\n    \n    UInt16 len = sizeof(SurfaceSerialMessage)+sizeof(SurfaceSerialCommand)+payload_len+2;\n    UInt8 *buffer = new UInt8[len];\n    \n    SurfaceSerialMessage *msg = reinterpret_cast<SurfaceSerialMessage *>(buffer);\n    msg->syn = SSH_SYN_BYTES;\n    msg->frame.type = seq ? SSH_FRAME_TYPE_DATA_SEQ : SSH_FRAME_TYPE_DATA_NSQ;\n    msg->frame.length = payload_len + 8;\n    msg->frame.seq_id = seq_counter.getID();\n    msg->frame_crc = crc_ccitt_false(CRC_INITIAL, buffer+2, sizeof(SurfaceSerialFrame));\n    \n    SurfaceSerialCommand *cmd = reinterpret_cast<SurfaceSerialCommand *>(msg->payload);\n    cmd->type = SSH_PAYLOAD_TYPE_COMMAND;\n    cmd->target_category = tc;\n    cmd->target_id_out = tid;\n    cmd->target_id_in = 0x00;\n    cmd->instance_id = iid;\n    cmd->request_id = req_counter.getID();\n    cmd->command_id = cid;\n    \n    if (payload_len > 0)\n        memcpy(cmd->data, payload, payload_len);\n    \n    *(reinterpret_cast<UInt16 *>(cmd->data+payload_len)) = crc_ccitt_false(CRC_INITIAL, msg->payload, sizeof(SurfaceSerialCommand)+payload_len);\n    \n    if (command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceSerialHubDriver::sendCommandGated), buffer, &len, &seq) != kIOReturnSuccess) {\n        LOG(\"Sending command failed!\");\n        delete[] buffer;\n        return 0;\n    }\n    \n    return cmd->request_id;\n}\n\nIOReturn SurfaceSerialHubDriver::sendCommandGated(UInt8 *tx_buffer, UInt16 *len, bool *seq) {\n    PendingCommand *cmd = new PendingCommand;\n    cmd->buffer = tx_buffer;\n    cmd->len = *len;\n    cmd->trial_count = *seq ? 1 : 0;   // if no ACK is needed, count is set to 0\n    cmd->timer = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceSerialHubDriver::commandTimeout));\n    if (!cmd->timer) {\n        LOG(\"Could not create timer for sending command!\");\n        delete cmd;\n        return kIOReturnError;\n    }\n    enqueue(&pending_list, &cmd->entry);\n    \n    work_loop->addEventSource(cmd->timer);\n    cmd->timer->enable();\n    cmd->timer->setTimeoutUS(1);\n    return kIOReturnSuccess;\n}\n\nvoid SurfaceSerialHubDriver::commandTimeout(IOTimerEventSource* timer) {\n    PendingCommand *cmd;\n    bool found = false;\n    qe_foreach_element_safe(cmd, &pending_list, entry) {\n        if (cmd->timer == timer) {\n            found = true;\n            SurfaceSerialCommand *cmd_data = reinterpret_cast<SurfaceSerialCommand *>(cmd->buffer+sizeof(SurfaceSerialMessage));\n            if (cmd->trial_count == 0) {\n                if (uart_controller->transmitData(cmd->buffer, cmd->len) != kIOReturnSuccess)\n                    LOG(\"Sending NSQ command failed for tc %x, tid %x, cid %x, iid %x!\", cmd_data->target_category, cmd_data->target_id_out, cmd_data->command_id, cmd_data->instance_id);\n            } else if (cmd->trial_count > SSH_CMD_TRAIL_CNT) {\n                LOG(\"Receive no ACK for command tc %x, tid %x, cid %x, iid %x!\", cmd_data->target_category, cmd_data->target_id_out, cmd_data->command_id, cmd_data->instance_id);\n            } else {\n                if (cmd->trial_count > 1)\n                    DBG_LOG(\"Timeout, trial count: %d\", cmd->trial_count);\n                if (uart_controller->transmitData(cmd->buffer, cmd->len) != kIOReturnSuccess)\n                    LOG(\"Sending SEQ command failed for tc %x, tid %x, cid %x, iid %x!\", cmd_data->target_category, cmd_data->target_id_out, cmd_data->command_id, cmd_data->instance_id);\n                cmd->trial_count++;\n                cmd->timer->setTimeoutMS(SSH_ACK_TIMEOUT);\n                break;\n            }\n            remqueue(&cmd->entry);\n            cmd->timer->disable();\n            work_loop->removeEventSource(cmd->timer);\n            OSSafeReleaseNULL(cmd->timer);\n            delete[] cmd->buffer;\n            delete cmd;\n            break;\n        }\n    }\n    if (!found)\n        DBG_LOG(\"Warning, timeout occurred but find no timer\");\n}\n\nIOReturn SurfaceSerialHubDriver::getResponse(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *payload, UInt16 payload_len, bool seq, UInt8 *buffer, UInt16 buffer_len) {\n    UInt16 req_id = sendCommand(tc, tid, iid, cid, payload, payload_len, seq);\n    \n    if (req_id != 0)\n        return command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceSerialHubDriver::waitResponse), &req_id, buffer, &buffer_len);\n    return kIOReturnError;\n}\n\nIOReturn SurfaceSerialHubDriver::waitResponse(UInt16 *req_id, UInt8 *buffer, UInt16 *buffer_len) {\n    AbsoluteTime abstime, deadline;\n    IOReturn sleep;\n    \n    WaitingRequest *w = new WaitingRequest;\n    w->waiting = false;\n    w->req_id = *req_id;\n    w->data = nullptr;\n    w->data_len = 0;\n    enqueue(&waiting_list, &w->entry);\n    \n    nanoseconds_to_absolutetime(SSH_WAIT_TIMEOUT * 1000000, &abstime);\n    clock_absolutetime_interval_to_deadline(abstime, &deadline);\n    sleep = command_gate->commandSleep(&w->waiting, deadline, THREAD_INTERRUPTIBLE);\n    \n    if (sleep == THREAD_TIMED_OUT) {\n        LOG(\"Timeout waiting for response\");\n        remqueue(&w->entry);\n        delete w;\n        return kIOReturnTimeout;\n    }\n    if (*buffer_len != w->data_len)\n        DBG_LOG(\"Warning, given buffer_len(%d) and received data_len(%d) mismatched!\", *buffer_len, w->data_len);\n    if (w->data_len) {\n        if (*buffer_len < w->data_len)\n            w->data_len = *buffer_len;\n        memcpy(buffer, w->data, w->data_len);\n        delete[] w->data;\n    }\n    delete w;\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceSerialHubDriver::registerEvent(SurfaceSerialHubClient *client, SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid) {\n    if (type >= SurfaceSerialEventTypeCount)\n        return kIOReturnInvalid;\n    \n    if (client) {\n        EventHandler *h;\n        if (tc == 0) {  // debug event handler for all events\n            if (!queue_empty(&event_handler_lists[0])) {\n                LOG(\"Already has a debug handler!\");\n                return kIOReturnNoResources;\n            }\n        } else {\n            qe_foreach_element(h, &event_handler_lists[tc], entry) {\n                if (h->client == client && (h->target_iid == iid || h->target_iid == 0 || iid == 0)) {\n                    LOG(\"Event already registered!\");\n                    return kIOReturnAborted;\n                }\n            }\n            \n            IOReturn ret = sendEventCommand(type, tc, iid, true);\n            if (ret != kIOReturnSuccess)\n                return ret;\n        }\n        \n        h = new EventHandler;\n        h->target_iid = iid;\n        h->client = client;\n        enqueue(&event_handler_lists[tc], &h->entry);\n        \n        return kIOReturnSuccess;\n    } else {    // client = nullptr means only enabling the event\n        if (tc == 0)\n            return kIOReturnInvalid;\n        return sendEventCommand(type, tc, iid, true);\n    }\n}\n\nvoid SurfaceSerialHubDriver::unregisterEvent(SurfaceSerialHubClient *client, SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid) {\n    if (type >= SurfaceSerialEventTypeCount)\n        return;\n    \n    if (client) {\n        EventHandler *h;\n        qe_foreach_element_safe(h, &event_handler_lists[tc], entry) {\n            if (h->client == client && (h->target_iid == iid || iid == 0)) {\n                if (tc != 0)\n                    sendEventCommand(type, tc, iid, false);\n                remqueue(&h->entry);\n                delete h;\n                break;\n            }\n        }\n    } else if (tc != 0) {\n        sendEventCommand(type, tc, iid, false);\n    }\n}\n\nIOReturn SurfaceSerialHubDriver::sendEventCommand(SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid, bool enable) {\n    SurfaceSerialEventData payload;\n    payload.target_category = tc;\n    payload.instance_id = iid;\n    payload.request_id = tc;\n    payload.flags = SSH_EVENT_FLAG_SEQUENCED;\n    \n    UInt8 ret;\n    UInt8 cid = enable ? event_conf[type].cid_enable : event_conf[type].cid_disable;\n    if (getResponse(event_conf[type].target_category, event_conf[type].target_id, 0, cid, reinterpret_cast<UInt8 *>(&payload), sizeof(SurfaceSerialEventData), true, &ret, 1) != kIOReturnSuccess || ret != 0) {\n        LOG(\"Unexpected response from event-%sable request\", enable ? \"en\" : \"dis\");\n        return kIOReturnError;\n    }\n    return kIOReturnSuccess;\n}\n\nbool SurfaceSerialHubDriver::init(OSDictionary *properties) {\n    if (!super::init(properties))\n        return false;\n    \n    memset(ring_buffer, 0, sizeof(ring_buffer));\n    memset(rx_msg.cache, 0, SSH_MSG_CACHE_SIZE);\n    rx_msg.pos = 0;\n    rx_msg.len = SSH_MSG_LENGTH_UNKNOWN;\n    rx_msg.partial_syn = false;\n    \n    queue_head_init(pending_list);\n    queue_head_init(waiting_list);\n    for (int i=0; i < SSH_REQID_MIN; i++)\n        queue_head_init(event_handler_lists[i]);\n    \n    return true;\n}\n\nIOService* SurfaceSerialHubDriver::probe(IOService *provider, SInt32 *score) {\n    if (!super::probe(provider, score))\n        return nullptr;\n    \n    acpi_device = OSDynamicCast(IOACPIPlatformDevice, provider);\n    if (!acpi_device)\n        return nullptr;\n    \n    if (getDeviceResources() != kIOReturnSuccess) {\n        LOG(\"Could not parse ACPI resources!\");\n        return nullptr;\n    }\n    \n    gpio_controller = getGPIOController();\n    if (!gpio_controller) {\n        LOG(\"Could not find GPIO controller, exiting\");\n        return nullptr;\n    }\n    uart_controller = getUARTController();\n    if (!uart_controller) {\n        LOG(\"Could not find UART controller, exiting\");\n        return nullptr;\n    }\n    // Give the UART controller some time to load\n    IOSleep(100);\n    \n    // Allocate a ring buffer with size SSH_BUFFER_SIZE to store buffer from UART\n    for (int i=0; i < SSH_RING_BUFFER_SIZE; i++)\n        ring_buffer[i].buffer = new UInt8[fifo_size];\n    \n    LOG(\"Surface Serial Hub found!\");\n    return this;\n}\n\nbool SurfaceSerialHubDriver::start(IOService *provider) {\n    UInt32 version;\n    UInt8 ret;\n    if (!super::start(provider))\n        return false;\n    \n    work_loop = IOWorkLoop::workLoop();\n    if (!work_loop) {\n        LOG(\"Could not get work loop\");\n        goto exit;\n    }\n    \n    command_gate = IOCommandGate::commandGate(this);\n    if (!command_gate) {\n        LOG(\"Could not open command gate\");\n        goto exit;\n    }\n    work_loop->addEventSource(command_gate);\n    \n    publish_timer = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceSerialHubDriver::delayedPublishingNubs));\n    if (!publish_timer) {\n        LOG(\"Could not create timer for publishing nubs!\");\n        goto exit;\n    }\n    work_loop->addEventSource(publish_timer);\n    // publishing nubs after 20s\n    publish_timer->setTimeoutMS(20000);\n    \n    uart_interrupt = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceSerialHubDriver::processReceivedBuffer));\n    if (!uart_interrupt) {\n        LOG(\"Could not create uart interrupt!\");\n        goto exit;\n    }\n    work_loop->addEventSource(uart_interrupt);\n    uart_interrupt->enable();\n    gpio_interrupt = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceSerialHubDriver::gpioWakeUp), this, 0);\n    if (!gpio_interrupt) {\n        LOG(\"Could not create gpio interrupt!\");\n        goto exit;\n    }\n    work_loop->addEventSource(gpio_interrupt);\n    gpio_interrupt->enable();\n    \n    if (uart_controller->requestConnect(this, OSMemberFunctionCast(VoodooUARTController::MessageHandler, this, &SurfaceSerialHubDriver::bufferReceived), baudrate, data_bits, stop_bits, parity, flow_control) != kIOReturnSuccess) {\n        LOG(\"Failed to connect to UART controller!\");\n        goto exit;\n    }\n    \n    if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_VERSION, nullptr, 0, true, reinterpret_cast<UInt8 *>(&version), 4) != kIOReturnSuccess) {\n        LOG(\"Failed to get SAM version! UART probably misconfigured!\");\n        goto exit_connected;\n    }\n    LOG(\"SAM version %u.%u.%u\", (version >> 24) & 0xff, (version >> 8) & 0xffff, version & 0xff);\n    \n    if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_D0_ENTRY, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)\n        DBG_LOG(\"Unexpected response from D0-entry notification, ret=%x\", ret);\n    if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_DISPLAY_ON, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)\n        DBG_LOG(\"Unexpected response from display-on notification, ret=%x\", ret);\n    \n    PMinit();\n    uart_controller->joinPMtree(this);\n    registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);\n    \n    registerService();\n    return true;\n    \nexit_connected:\n    uart_controller->requestDisconnect(this);\nexit:\n    releaseResources();\n    return false;\n}\n\nvoid SurfaceSerialHubDriver::stop(IOService *provider) {\n    UInt8 ret;\n    getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_DISPLAY_OFF, nullptr, 0, true, &ret, 1);\n    getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_D0_EXIT, nullptr, 0, true, &ret, 1);\n    uart_controller->requestDisconnect(this);\n    \n    PMstop();\n    releaseResources();\n    super::stop(provider);\n}\n\nvoid SurfaceSerialHubDriver::free() {\n    super::free();\n}\n\nIOReturn SurfaceSerialHubDriver::flushCacheGated() {\n    // Clear pending commands, rx_buffer and msg cache\n    PendingCommand *cmd;\n    if (!queue_empty(&pending_list)) {\n        DBG_LOG(\"There are still pending commands!\");\n        qe_foreach_element_safe(cmd, &pending_list, entry) {\n            remqueue(&cmd->entry);\n            cmd->timer->cancelTimeout();\n            cmd->timer->disable();\n            work_loop->removeEventSource(cmd->timer);\n            OSSafeReleaseNULL(cmd->timer);\n            delete[] cmd->buffer;\n            delete cmd;\n        }\n    }\n    if (ring_buffer[current].filled_len) {\n        DBG_LOG(\"There are still raw data unprocessed!\");\n        while (ring_buffer[current].filled_len) {\n            ring_buffer[current].filled_len = 0;\n            current = (current + 1) % SSH_RING_BUFFER_SIZE;\n        }\n    }\n    rx_msg.pos = 0;\n    rx_msg.len = SSH_MSG_LENGTH_UNKNOWN;\n    rx_msg.partial_syn = false;\n    \n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceSerialHubDriver::setPowerState(unsigned long whichState, IOService *whatDevice) {\n    if (whatDevice != this)\n        return kIOReturnInvalid;\n    if (whichState == 0) {\n        if (awake) {\n            UInt8 ret;\n            if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_DISPLAY_OFF, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)\n                DBG_LOG(\"Unexpected response from display-off notification\");\n            if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_D0_EXIT, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)\n                DBG_LOG(\"Unexpected response from d0-exit notification\");\n            uart_interrupt->disable();\n            awake = false;\n            command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceSerialHubDriver::flushCacheGated));\n            DBG_LOG(\"Going to sleep\");\n        }\n    } else {\n        if (!awake) {\n            uart_interrupt->enable();\n            awake = true;\n            UInt8 ret;\n            if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_D0_ENTRY, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)\n                DBG_LOG(\"Unexpected response from D0-entry notification, ret=%x\", ret);\n            if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_DISPLAY_ON, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)\n                DBG_LOG(\"Unexpected response from display-on notification, ret=%x\", ret);\n            DBG_LOG(\"Woke up\");\n        }\n    }\n    return kIOPMAckImplied;\n}\n\nvoid SurfaceSerialHubDriver::releaseResources() {\n    if (battery_nub) {\n        battery_nub->stop(this);\n        battery_nub->detach(this);\n        OSSafeReleaseNULL(battery_nub);\n    }\n    if (hid_nub) {\n        hid_nub->stop(this);\n        hid_nub->detach(this);\n        OSSafeReleaseNULL(hid_nub);\n    }\n    EventHandler *h;\n    for (int i=0; i < SSH_REQID_MIN; i++) {\n        qe_foreach_element_safe(h, &event_handler_lists[i], entry) {\n            remqueue(&h->entry);\n            delete h;\n        }\n    }\n    WaitingRequest *req;\n    qe_foreach_element_safe(req, &waiting_list, entry) {\n        remqueue(&req->entry);\n        if (req->data_len)\n            delete[] req->data;\n        delete req;\n    }\n    PendingCommand *cmd;\n    qe_foreach_element_safe(cmd, &pending_list, entry) {\n        remqueue(&cmd->entry);\n        cmd->timer->cancelTimeout();\n        cmd->timer->disable();\n        work_loop->removeEventSource(cmd->timer);\n        OSSafeReleaseNULL(cmd->timer);\n        delete[] cmd->buffer;\n        delete cmd;\n    }\n    for (int i=0; i < SSH_RING_BUFFER_SIZE; i++) {\n        delete[] ring_buffer[i].buffer;\n    }\n    if (uart_interrupt) {\n        uart_interrupt->disable();\n        work_loop->removeEventSource(uart_interrupt);\n        OSSafeReleaseNULL(uart_interrupt);\n    }\n    if (gpio_interrupt) {\n        gpio_interrupt->disable();\n        work_loop->removeEventSource(gpio_interrupt);\n        OSSafeReleaseNULL(gpio_interrupt);\n    }\n    if (publish_timer) {\n        publish_timer->cancelTimeout();\n        publish_timer->disable();\n        work_loop->removeEventSource(publish_timer);\n        OSSafeReleaseNULL(publish_timer);\n    }\n    if (command_gate) {\n        work_loop->removeEventSource(command_gate);\n        OSSafeReleaseNULL(command_gate);\n    }\n    OSSafeReleaseNULL(work_loop);\n}\n\nVoodooGPIO* SurfaceSerialHubDriver::getGPIOController() {\n    VoodooGPIO* gpio_controller = nullptr;\n\n    // Wait for GPIO controller, up to 1 second\n    OSDictionary* name_match = serviceMatching(\"VoodooGPIO\");\n    IOService* matched = waitForMatchingService(name_match, 1000000000);\n    gpio_controller = OSDynamicCast(VoodooGPIO, matched);\n    if (gpio_controller != NULL)\n        DBG_LOG(\"Got GPIO Controller! %s\", gpio_controller->getName());\n    \n    OSSafeReleaseNULL(name_match);\n    OSSafeReleaseNULL(matched);\n\n    return gpio_controller;\n}\n\nVoodooUARTController* SurfaceSerialHubDriver::getUARTController() {\n    // Wait for UART controller, up to 1 second, try for 5 times\n    // Sometimes it takes really a long time for UART to load\n    for (int i=0; i < 5; i++) {\n        OSDictionary* name_match = serviceMatching(\"VoodooUARTController\");\n        IOService* matched = waitForMatchingService(name_match, 1000000000);\n        VoodooUARTController* uart = OSDynamicCast(VoodooUARTController, matched);\n        OSSafeReleaseNULL(name_match);\n        OSSafeReleaseNULL(matched);\n        if (uart) {\n            DBG_LOG(\"Got UART Controller! %s\", uart->getName());\n            return uart;\n        }\n        IOSleep(1000);\n    }\n\n    return nullptr;\n}\n\nIOReturn SurfaceSerialHubDriver::getDeviceResources() {\n    VoodooACPIResourcesParser parser;\n    OSObject *result = nullptr;\n    OSData *data = nullptr;\n    if (acpi_device->evaluateObject(\"_CRS\", &result) != kIOReturnSuccess ||\n        !(data = OSDynamicCast(OSData, result))) {\n        LOG(\"Could not find or evaluate _CRS method\");\n        OSSafeReleaseNULL(result);\n        return kIOReturnNotFound;\n    }\n\n    UInt8 const* crs = reinterpret_cast<UInt8 const*>(data->getBytesNoCopy());\n    UInt32 length = data->getLength();\n    parser.parseACPIResources(crs, 0, length);\n    OSSafeReleaseNULL(data);\n    \n    if (!parser.found_uart || !parser.found_gpio_interrupts)\n        return kIOReturnNoResources;\n    \n    DBG_LOG(\"Found valid UART bus and GPIO interrupt!\");\n//    LOG(\"resource_consumer %d\", parser.uart_info.resource_consumer);\n//    LOG(\"device_initiated %d\", parser.uart_info.device_initiated);\n//    LOG(\"flow_control %d\", parser.uart_info.flow_control);\n//    LOG(\"stop_bits %d\", parser.uart_info.stop_bits);\n//    LOG(\"data_bits %d\", parser.uart_info.data_bits);\n//    LOG(\"big_endian %d\", parser.uart_info.big_endian);\n//    LOG(\"baudrate %u\", parser.uart_info.baudrate);\n//    LOG(\"rx_fifo %d\", parser.uart_info.rx_fifo);\n//    LOG(\"tx_fifo %d\", parser.uart_info.tx_fifo);\n//    LOG(\"parity %d\", parser.uart_info.parity);\n//    LOG(\"dtd_enabled %d\", parser.uart_info.dtd_enabled);\n//    LOG(\"ri_enabled %d\", parser.uart_info.ri_enabled);\n//    LOG(\"dsr_enabled %d\", parser.uart_info.dsr_enabled);\n//    LOG(\"dtr_enabled %d\", parser.uart_info.dtr_enabled);\n//    LOG(\"cts_enabled %d\", parser.uart_info.cts_enabled);\n//    LOG(\"rts_enabled %d\", parser.uart_info.rts_enabled);\n    \n    baudrate = parser.uart_info.baudrate;\n    data_bits = parser.uart_info.data_bits;\n    stop_bits = parser.uart_info.stop_bits;\n    parity = parser.uart_info.parity;\n    flow_control = parser.uart_info.flow_control != 0;\n    // For SP6, UART bus reports a rx_fifo of size 32 yet the UART device reports itself with a fifo size 64\n    fifo_size = 64; //parser.uart_info.rx_fifo;\n    \n    gpio_pin = parser.gpio_interrupts.pin_number;\n    gpio_irq = 0x00000001; // Set irq type to edge rising\n    \n    return kIOReturnSuccess;\n}\n\nvoid SurfaceSerialHubDriver::delayedPublishingNubs(IOTimerEventSource *sender) {\n    battery_nub = OSTypeAlloc(SurfaceBatteryNub);\n    if (!battery_nub || !battery_nub->init() || !battery_nub->attach(this)) {\n        LOG(\"Failed to init Surface Battery nub!\");\n        OSSafeReleaseNULL(battery_nub);\n    } else {\n        if (!battery_nub->start(this)) {\n            LOG(\"Failed to attach Surface Battery nub!\");\n            battery_nub->detach(this);\n            OSSafeReleaseNULL(battery_nub);\n        } else\n            DBG_LOG(\"Surface Battery nub published!\");\n    }\n    \n    hid_nub = OSTypeAlloc(SurfaceHIDNub);\n    if (!hid_nub || !hid_nub->init() || !hid_nub->attach(this)) {\n        LOG(\"Failed to init Surface HID nub!\");\n        OSSafeReleaseNULL(hid_nub);\n    } else {\n        if (!hid_nub->start(this)) {\n            LOG(\"Failed to attach Surface HID nub! Ignore this if you don't need HID nub\");\n            hid_nub->detach(this);\n            OSSafeReleaseNULL(hid_nub);\n        } else\n            DBG_LOG(\"Surface HID nub published!\");\n    }\n}\n\nvoid SurfaceSerialHubDriver::gpioWakeUp(IOInterruptEventSource *sender, int count) {\n    LOG(\"GPIO wake up event happened!\");\n}\n\nIOReturn SurfaceSerialHubDriver::enableInterrupt(int source) {\n    return gpio_controller->enableInterrupt(gpio_pin);\n}\n\nIOReturn SurfaceSerialHubDriver::disableInterrupt(int source) {\n    return gpio_controller->disableInterrupt(gpio_pin);\n}\n\nIOReturn SurfaceSerialHubDriver::getInterruptType(int source, int* interrupt_type) {\n    return gpio_controller->getInterruptType(gpio_pin, interrupt_type);\n}\n\nIOReturn SurfaceSerialHubDriver::registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refcon) {\n    gpio_controller->setInterruptTypeForPin(gpio_pin, gpio_irq);\n    return gpio_controller->registerInterrupt(gpio_pin, target, handler, refcon);\n}\n\nIOReturn SurfaceSerialHubDriver::unregisterInterrupt(int source) {\n    return gpio_controller->unregisterInterrupt(gpio_pin);\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceSerialHub/SurfaceSerialHubDriver.hpp",
    "content": "//\n//  SurfaceSerialHubDriver.hpp\n//  SurfaceSerialHub\n//\n//  Created by Xavier on 2021/10/29.\n//  Copyright © 2021 Xia Shangning. All rights reserved.\n//\n\n#ifndef SurfaceSerialHubDriver_hpp\n#define SurfaceSerialHubDriver_hpp\n\n#include <IOKit/acpi/IOACPIPlatformDevice.h>\n\n#include \"../../../Dependencies/VoodooGPIO/VoodooGPIO/VoodooGPIO.hpp\"\n#include \"../../../Dependencies/VoodooSerial/VoodooSerial/VoodooUART/VoodooUARTController.hpp\"\n#include \"SerialProtocol.h\"\n\nenum SurfaceSerialEventRegistryType {\n    SurfaceSerialEventHostManagedV1 = 0,\n    SurfaceSerialEventHostManagedV2,\n    SurfaceSerialEventHubManaged,\n    SurfaceSerialEventTypeCount\n};\n\n#define SSH_REQID_MIN           SSH_TC_COUNT+1\n#define SSH_MSG_CACHE_SIZE      256     // max length for a single message\n#define SSH_MSG_LENGTH_UNKNOWN  (SSH_MSG_CACHE_SIZE+1)\n#define SSH_RING_BUFFER_SIZE    10\n#define SSH_RING_BUFFER_NEXT(pos)   ((pos) + 1) % SSH_RING_BUFFER_SIZE\n#define SSH_ACK_TIMEOUT         50\n#define SSH_CMD_TRAIL_CNT       3\n#define SSH_WAIT_TIMEOUT        (SSH_ACK_TIMEOUT * SSH_CMD_TRAIL_CNT)\n\n\nclass EXPORT SurfaceSerialHubClient : public IOService {\n    OSDeclareAbstractStructors(SurfaceSerialHubClient);\n    \npublic:\n    /*\n     * This method is called when SSH receives corresponding registered events\n     * it should NOT block the thread\n     * the ACTUAL event handling codes should be done in device driver's own workloop thread\n     */\n    virtual void eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) = 0;\n};\n\nclass SurfaceBatteryNub;\nclass SurfaceHIDNub;\n\nclass EXPORT SurfaceSerialHubDriver : public IOService {\n    OSDeclareDefaultStructors(SurfaceSerialHubDriver);\n    \npublic:\n    UInt16 sendCommand(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *payload, UInt16 payload_len, bool seq);\n\n    IOReturn getResponse(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *payload, UInt16 payload_len, bool seq, UInt8 *buffer, UInt16 buffer_len);\n\n    IOReturn registerEvent(SurfaceSerialHubClient *client, SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid);\n    \n    void unregisterEvent(SurfaceSerialHubClient *client, SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid);\n    \n    bool init(OSDictionary* properties) override;\n    \n    IOService* probe(IOService* provider, SInt32* score) override;\n\n    bool start(IOService* provider) override;\n\n    void stop(IOService* provider) override;\n    \n    void free() override;\n    \n    IOReturn setPowerState(unsigned long whichState, IOService *whatDevice) override;\n\n    IOReturn enableInterrupt(int source) override;\n    \n    IOReturn disableInterrupt(int source) override;\n\n    IOReturn getInterruptType(int source, int *interruptType) override;\n    \n    IOReturn registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refcon) override;\n    \n    IOReturn unregisterInterrupt(int source) override;\n    \nprivate:\n    class CircleIDCounter {\n    private:\n        UInt16 min;\n        UInt16 max;\n        UInt16 id;\n    public:\n        CircleIDCounter(UInt16 _min, UInt16 _max){\n            min = _min;\n            max = _max;\n            id = min-1;\n        }\n        \n        UInt16 getID() {\n            UInt16 ret = ++id;\n            if (id == max)\n                id = min-1;\n            return ret;\n        }\n    };\n\n    struct WaitingRequest {\n        queue_entry entry;\n        bool    waiting;\n        UInt16  req_id;\n        UInt8*  data;\n        UInt16  data_len;\n    };\n\n    struct PendingCommand {\n        queue_entry entry;\n        UInt8*  buffer {nullptr};\n        UInt16  len {0};\n        UInt8   trial_count {0};\n        IOTimerEventSource* timer {nullptr};\n    };\n\n    struct MessageCache {\n        UInt8   cache[SSH_MSG_CACHE_SIZE];\n        UInt16  len;\n        UInt16  pos;\n        bool    partial_syn;\n    };\n\n    struct RingBuffer {\n        UInt8* buffer;\n        UInt16 filled_len;\n    };\n    \n    struct EventHandler {\n        queue_entry entry;\n        UInt8 target_iid;\n        SurfaceSerialHubClient *client;\n    };\n    \n    IOWorkLoop*             work_loop {nullptr};\n    IOCommandGate*          command_gate {nullptr};\n    IOTimerEventSource*     publish_timer {nullptr};\n    IOInterruptEventSource* uart_interrupt {nullptr};\n    IOInterruptEventSource* gpio_interrupt {nullptr};\n    IOACPIPlatformDevice*   acpi_device {nullptr};\n    VoodooUARTController*   uart_controller {nullptr};\n    VoodooGPIO*             gpio_controller {nullptr};\n    SurfaceBatteryNub*      battery_nub {nullptr};\n    SurfaceHIDNub*          hid_nub {nullptr};\n    \n    bool            awake {true};\n    RingBuffer      ring_buffer[SSH_RING_BUFFER_SIZE];\n    int             current {0};\n    int             last {SSH_RING_BUFFER_SIZE-1};\n    MessageCache    rx_msg;\n    queue_head_t    pending_list;\n    queue_head_t    waiting_list;\n    queue_head_t    event_handler_lists[SSH_REQID_MIN];\n    \n    CircleIDCounter seq_counter {CircleIDCounter(0x00, 0xff)};\n    CircleIDCounter req_counter {CircleIDCounter(SSH_REQID_MIN, 0xffff)};\n    \n    UInt32  baudrate {0};\n    UInt8   data_bits {0};\n    UInt8   stop_bits {0};\n    UInt8   parity {0};\n    bool    flow_control {false};\n    UInt16  fifo_size {0};\n    UInt16  gpio_pin {0};\n    UInt16  gpio_irq {0};\n    \n    void bufferReceived(VoodooUARTController *sender, UInt8 *buffer, UInt16 length);\n    \n    IOReturn sendACK(UInt8 seq_id);\n    \n    IOReturn sendNAK();\n    \n    IOReturn processMessage();\n    \n    void processReceivedBuffer(IOInterruptEventSource *sender, int count);\n    \n    void delayedPublishingNubs(IOTimerEventSource *sender);\n    \n    void gpioWakeUp(IOInterruptEventSource *sender, int count);\n    \n    void _process(UInt8* buffer, UInt16 length);\n    \n    IOReturn sendCommandGated(UInt8 *tx_buffer, UInt16 *len, bool *seq);\n    \n    void commandTimeout(IOTimerEventSource* timer);\n    \n    IOReturn waitResponse(UInt16 *req_id, UInt8 *buffer, UInt16 *buffer_len);\n    \n    IOReturn sendEventCommand(SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid, bool enable);\n    \n    IOReturn getDeviceResources();\n    \n    VoodooUARTController* getUARTController();\n    \n    VoodooGPIO* getGPIOController();\n    \n    IOReturn flushCacheGated();\n    \n    void releaseResources();\n};\n\n#endif /* SurfaceSerialHubDriver_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceBatteryNub.cpp",
    "content": "//\n//  SurfaceBatteryNub.cpp\n//  SurfaceSerialHubDevices\n//\n//  Created by Xavier on 2022/5/19.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#include \"SurfaceBatteryNub.hpp\"\n\n#define super SurfaceSerialHubClient\nOSDefineMetaClassAndStructors(SurfaceBatteryNub, SurfaceSerialHubClient)\n\nbool SurfaceBatteryNub::attach(IOService* provider) {\n    if (!super::attach(provider))\n        return false;\n\n    ssh = OSDynamicCast(SurfaceSerialHubDriver, provider);\n    if (!ssh)\n        return false;\n\n    return true;\n}\n\nvoid SurfaceBatteryNub::detach(IOService* provider) {\n    ssh = nullptr;\n    super::detach(provider);\n}\n\nbool SurfaceBatteryNub::start(IOService *provider) {\n    if (!super::start(provider))\n        return false;\n    \n    PMinit();\n    ssh->joinPMtree(this);\n    registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);\n    \n    registerService();\n    return true;\n}\n\nvoid SurfaceBatteryNub::stop(IOService *provider) {\n    unregisterBatteryEvent(target);\n    super::stop(provider);\n}\n\nIOReturn SurfaceBatteryNub::setPowerState(unsigned long whichState, IOService *device) {\n    if (device != this)\n        return kIOReturnInvalid;\n    return kIOPMAckImplied;\n}\n\nIOReturn SurfaceBatteryNub::registerBatteryEvent(OSObject* owner, EventHandler _handler) {\n    if (!owner || !_handler)\n        return kIOReturnError;\n    if (target) {\n        LOG(\"Battery event already registered for a handler!\");\n        return kIOReturnNoResources;\n    }\n    \n    IOReturn ret = ssh->registerEvent(this, SurfaceSerialEventHostManagedV1, SSH_TC_BAT, 0x00);\n    if (ret != kIOReturnSuccess)\n        return ret;\n    \n    target = owner;\n    handler = _handler;\n    return kIOReturnSuccess;\n}\n\nvoid SurfaceBatteryNub::unregisterBatteryEvent(OSObject* owner) {\n    if (target) {\n        if (target == owner) {\n            ssh->unregisterEvent(this, SurfaceSerialEventHostManagedV1, SSH_TC_BAT, 0x00);\n            target = nullptr;\n            handler = nullptr;\n        } else\n            LOG(\"Battery event not registered for this handler!\");\n    }\n}\n\nvoid SurfaceBatteryNub::eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) {\n    // iid corresponds to battery/adaptor index, starts with 1\n    SurfaceBatteryEventType type;\n    switch (cid) {\n        case SSH_EVENT_CID_BAT_BIX:\n            type = SurfaceBatteryInformationChanged;\n            break;\n        case SSH_EVENT_CID_BAT_BST:\n            type = SurfaceBatteryStatusChanged;\n            break;\n        case SSH_EVENT_CID_BAT_PSR:\n            type = SurfaceAdaptorStatusChanged;\n            break;\n        default:\n            DBG_LOG(\"Unknown battery event! tid: %d, iid: %d, cid: %x, data_len: %d\", tid, iid, cid, length);\n            return;\n    }\n    if (handler)\n        handler(target, this, type);\n}\n\nIOReturn SurfaceBatteryNub::getBatteryConnection(UInt8 index, bool *connected) {\n    UInt32 sta = 0x00;\n    if (ssh->getResponse(SSH_TC_BAT, index, 0x01, SSH_CID_BAT_STA, nullptr, 0, true, reinterpret_cast<UInt8 *>(&sta), 4) != kIOReturnSuccess)\n        return kIOReturnError;\n\n    *connected = (sta & 0x10) ? true : false;\n    \n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceBatteryNub::getBatteryInformation(UInt8 index, OSArray **bix) {\n    UInt8 buffer[BIX_LENGTH];\n    if (ssh->getResponse(SSH_TC_BAT, index, 0x01, SSH_CID_BAT_BIX, nullptr, 0, true, buffer, BIX_LENGTH) != kIOReturnSuccess)\n        return kIOReturnError;\n    \n    UInt32 *temp = reinterpret_cast<UInt32 *>(buffer+1);\n    const char *str = reinterpret_cast<const char *>(buffer);\n    \n    OSNumber *revision = OSNumber::withNumber(*buffer, 8);\n    OSNumber *power_unit = OSNumber::withNumber(temp[0], 32);\n    OSNumber *design_cap = OSNumber::withNumber(temp[1], 32);\n    OSNumber *last_full_cap = OSNumber::withNumber(temp[2], 32);\n    OSNumber *bat_tech = OSNumber::withNumber(temp[3], 32);\n    OSNumber *design_volt = OSNumber::withNumber(temp[4], 32);\n    OSNumber *design_cap_warn = OSNumber::withNumber(temp[5], 32);\n    OSNumber *design_cap_low = OSNumber::withNumber(temp[6], 32);\n    OSNumber *cycle_cnt = OSNumber::withNumber(temp[7], 32);\n    OSNumber *mesure_acc = OSNumber::withNumber(temp[8], 32);\n    OSNumber *max_sample_t = OSNumber::withNumber(temp[9], 32);\n    OSNumber *min_sample_t = OSNumber::withNumber(temp[10], 32);\n    OSNumber *max_avg_interval = OSNumber::withNumber(temp[11], 32);\n    OSNumber *min_avg_interval = OSNumber::withNumber(temp[12], 32);\n    OSNumber *bat_cap_gra_1 = OSNumber::withNumber(temp[13], 32);\n    OSNumber *bat_cap_gra_2 = OSNumber::withNumber(temp[14], 32);\n    OSString *model_number = OSString::withCString(str+0x3D);\n    OSString *serial_number = OSString::withCString(str+0x52);\n    OSString *bat_type = OSString::withCString(str+0x5D);\n    OSString *oem_info = OSString::withCString(str+0x62);\n    \n    const OSObject *arr[] = {revision, power_unit, design_cap, last_full_cap, bat_tech,\n                        design_volt, design_cap_warn, design_cap_low, cycle_cnt,\n                        mesure_acc, max_sample_t, min_sample_t, max_avg_interval,\n                        min_avg_interval, bat_cap_gra_1, bat_cap_gra_2, model_number,\n                        serial_number, bat_type, oem_info};\n    *bix = OSArray::withObjects(arr, 20);\n    if (!(*bix)) {\n        LOG(\"Could not create a 20 sized array!\");\n        for (int i=0; i<20; i++)\n            OSSafeReleaseNULL(arr[i]);\n        return kIOReturnError;\n    }\n    \n    return kIOReturnSuccess;\n}\n\n\nIOReturn SurfaceBatteryNub::getBatteryStatus(UInt8 index, UInt32 *bst, UInt16 *temp) {\n    if (ssh->getResponse(SSH_TC_BAT, index, 0x01, SSH_CID_BAT_BST, nullptr, 0, true, reinterpret_cast<UInt8 *>(bst), BST_LENGTH) != kIOReturnSuccess)\n        return kIOReturnError;\n    \n    \n    if (ssh->getResponse(SSH_TC_TMP, SSH_TID_PRIMARY, SSH_TEMP_SENSOR_BAT, SSH_CID_TMP_SENSOR, nullptr, 0, true, reinterpret_cast<UInt8 *>(temp), 2) != kIOReturnSuccess)\n        LOG(\"Failed to get battery temperature!\");\n    \n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceBatteryNub::getAdaptorStatus(UInt32 *psr) {\n    return ssh->getResponse(SSH_TC_BAT, SSH_TID_PRIMARY, 0x01, SSH_CID_BAT_PSR, nullptr, 0, true, reinterpret_cast<UInt8 *>(psr), 4);\n}\n\nIOReturn SurfaceBatteryNub::setPerformanceMode(UInt32 mode) {\n    if (!ssh->sendCommand(SSH_TC_TMP, SSH_TID_PRIMARY, 0, SSH_CID_TMP_SET_PERF, reinterpret_cast<UInt8 *>(&mode), 4, true))\n        return kIOReturnError;\n    else\n        return kIOReturnSuccess;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceBatteryNub.hpp",
    "content": "//\n//  SurfaceBatteryNub.hpp\n//  SurfaceSerialHubDevices\n//\n//  Created by Xavier on 2022/5/19.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#ifndef SurfaceBatteryNub_hpp\n#define SurfaceBatteryNub_hpp\n\n#include \"../SurfaceSerialHub/SurfaceSerialHubDriver.hpp\"\n\n#define BIX_LENGTH          119\n#define BST_LENGTH          16\n\nenum SurfaceBatteryEventType {\n    SurfaceBatteryInformationChanged = 0,\n    SurfaceBatteryStatusChanged,\n    SurfaceAdaptorStatusChanged,\n};\n\nclass EXPORT SurfaceBatteryNub : public SurfaceSerialHubClient {\n    OSDeclareDefaultStructors(SurfaceBatteryNub);\n    \npublic:\n    typedef void (*EventHandler)(OSObject *owner, SurfaceBatteryNub *sender, SurfaceBatteryEventType type);\n    \n    bool attach(IOService* provider) override;\n    \n    void detach(IOService* provider) override;\n    \n    bool start(IOService* provider) override;\n    \n    void stop(IOService* provider) override;\n    \n    IOReturn setPowerState(unsigned long whichState, IOService *device) override;\n    \n    IOReturn registerBatteryEvent(OSObject* owner, EventHandler _handler);\n    \n    void unregisterBatteryEvent(OSObject* owner);\n    \n    void eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) override;\n    \n    /*\n     * index: The index of battery, start with 1\n     */\n    IOReturn getBatteryConnection(UInt8 index, bool *connected);\n    \n    /*\n     * index: The index of battery, start with 1\n     * Returned OSArray bix need to be released by the caller!\n     */\n    IOReturn getBatteryInformation(UInt8 index, OSArray **bix);\n    \n    /*\n     * index: The index of battery, start with 1\n     */\n    IOReturn getBatteryStatus(UInt8 index, UInt32 *bst, UInt16 *temp);\n    \n    IOReturn getAdaptorStatus(UInt32 *psr);\n    \n    IOReturn setPerformanceMode(UInt32 mode);\n    \nprivate:\n    SurfaceSerialHubDriver* ssh {nullptr};\n    OSObject*               target {nullptr};\n    EventHandler            handler {nullptr};\n};\n\n#endif /* SurfaceBatteryNub_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceHIDNub.cpp",
    "content": "//\n//  SurfaceHIDNub.cpp\n//  SurfaceSerialHubDevices\n//\n//  Created by Xavier on 2022/5/20.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#include <IOKit/hid/IOHIDDevice.h>\n#include <IOKit/hid/IOHIDElement.h>\n#include \"SurfaceHIDNub.hpp\"\n\n#define super SurfaceSerialHubClient\nOSDefineMetaClassAndStructors(SurfaceHIDNub, SurfaceSerialHubClient)\n\nbool SurfaceHIDNub::attach(IOService* provider) {\n    if (!super::attach(provider))\n        return false;\n\n    ssh = OSDynamicCast(SurfaceSerialHubDriver, provider);\n    if (!ssh)\n        return false;\n\n    return true;\n}\n\nvoid SurfaceHIDNub::detach(IOService* provider) {\n    ssh = nullptr;\n    super::detach(provider);\n}\n\nbool SurfaceHIDNub::start(IOService *provider) {\n    if (!super::start(provider))\n        return false;\n    \n    SurfaceHIDDescriptor desc;\n    if (getHIDDescriptor(SurfaceLegacyKeyboardDevice, &desc) != kIOReturnSuccess) {\n        legacy = false;\n        if (getHIDDescriptor(SurfaceKeyboardDevice, &desc) != kIOReturnSuccess)\n            return false;\n    }\n    LOG(\"HID version %d\", !legacy+1);\n    setProperty(SURFACE_LEGACY_HID_STRING, legacy);\n    \n    PMinit();\n    ssh->joinPMtree(this);\n    registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);\n    \n    registerService();\n    return true;\n}\n\nvoid SurfaceHIDNub::stop(IOService *provider) {\n    unregisterHIDEvent(target);\n    super::stop(provider);\n}\n\nIOReturn SurfaceHIDNub::setPowerState(unsigned long whichState, IOService *device) {\n    if (device != this)\n        return kIOReturnInvalid;\n    return kIOPMAckImplied;\n}\n\nIOReturn SurfaceHIDNub::registerHIDEvent(OSObject* owner, EventHandler _handler) {\n    if (!owner || !_handler)\n        return kIOReturnError;\n    if (target) {\n        LOG(\"HID event already registered for a handler!\");\n        return kIOReturnNoResources;\n    }\n    \n    IOReturn ret;\n    if (legacy)\n        ret = ssh->registerEvent(this, SurfaceSerialEventHostManagedV1, SSH_TC_KBD, SurfaceLegacyKeyboardDevice);\n    else {\n        ret = ssh->registerEvent(this, SurfaceSerialEventHostManagedV2, SSH_TC_HID, SurfaceKeyboardDevice);\n        if (ret == kIOReturnSuccess)\n            ret = ssh->registerEvent(this, SurfaceSerialEventHostManagedV2, SSH_TC_HID, SurfaceTouchpadDevice);\n    }\n    if (ret != kIOReturnSuccess)\n        return ret;\n    \n    target = owner;\n    handler = _handler;\n    return kIOReturnSuccess;\n}\n\nvoid SurfaceHIDNub::unregisterHIDEvent(OSObject* owner) {\n    if (!target)\n        return;\n    if (target == owner) {\n        if (legacy)\n            ssh->unregisterEvent(this, SurfaceSerialEventHostManagedV1, SSH_TC_KBD, SurfaceLegacyKeyboardDevice);\n        else {\n            ssh->unregisterEvent(this, SurfaceSerialEventHostManagedV2, SSH_TC_HID, SurfaceKeyboardDevice);\n            ssh->unregisterEvent(this, SurfaceSerialEventHostManagedV2, SSH_TC_HID, SurfaceTouchpadDevice);\n        }\n        target = nullptr;\n        handler = nullptr;\n    } else\n        LOG(\"HID event not registered for this handler!\");\n}\n\nvoid SurfaceHIDNub::eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) {\n    SurfaceHIDDeviceType device;\n    if (legacy) {\n        if ((cid != SSH_EVENT_CID_KBD_INPUT_GENERIC && cid != SSH_EVENT_CID_KBD_INPUT_HOTKEYS)\n            || tid != SSH_TID_SECONDARY\n            || iid != SurfaceLegacyKeyboardDevice)\n            goto error;\n        \n        device = SurfaceLegacyKeyboardDevice;\n    } else {\n        if (cid != SSH_EVENT_CID_HID_INPUT || tid != SSH_TID_SECONDARY)\n            goto error;\n        \n        switch (iid) {\n            case SurfaceKeyboardDevice:\n                device = SurfaceKeyboardDevice;\n                break;\n            case SurfaceTouchpadDevice:\n                device = SurfaceTouchpadDevice;\n                break;\n            default:\n                goto error;\n        }\n    }\n    \n    if (handler)\n        handler(target, this, device, data_buffer, length);\n    return;\n    \nerror:\n    DBG_LOG(\"Unknown HID event with tid: %d, iid: %d, cid: %d, data_len: %d\", tid, iid, cid, length);\n}\n\nIOReturn SurfaceHIDNub::getHIDDescriptor(SurfaceHIDDeviceType device, SurfaceHIDDescriptor *desc) {\n    return getDescriptorData(device, SurfaceHIDDescriptorEntry, reinterpret_cast<UInt8 *>(desc), sizeof(SurfaceHIDDescriptor));\n}\n\nIOReturn SurfaceHIDNub::getHIDAttributes(SurfaceHIDDeviceType device, SurfaceHIDAttributes *attr) {\n    return getDescriptorData(device, SurfaceHIDAttributesEntry, reinterpret_cast<UInt8 *>(attr), sizeof(SurfaceHIDAttributes));\n}\n\nIOReturn SurfaceHIDNub::getReportDescriptor(SurfaceHIDDeviceType device, UInt8 *buffer, UInt16 len) {\n    return getDescriptorData(device, SurfaceReportDescriptorEntry, buffer, len);\n}\n\nIOReturn SurfaceHIDNub::getDescriptorData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len) {\n    if (legacy)\n        return getLegacyData(device, entry, buffer, buffer_len);\n    else\n        return getData(device, entry, buffer, buffer_len);\n}\n\nIOReturn SurfaceHIDNub::getLegacyData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len) {\n    return ssh->getResponse(SSH_TC_KBD, SSH_TID_SECONDARY, device, SSH_CID_KBD_GET_DESCRIPTOR, reinterpret_cast<UInt8 *>(&entry), 1, true, buffer, buffer_len);\n}\n\nIOReturn SurfaceHIDNub::getData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len) {\n    UInt8 cache[SURFACE_HID_DESC_HEADER_SIZE + 0x76];    // 0x76 is used by windows driver\n    SurfaceHIDDescriptorBufferHeader *cache_as_buf = reinterpret_cast<SurfaceHIDDescriptorBufferHeader *>(cache);\n    \n    UInt16 rx_data_len = sizeof(cache) - SURFACE_HID_DESC_HEADER_SIZE;\n    UInt16 offset = 0;\n    UInt16 length = rx_data_len;\n    UInt16 remain_len = buffer_len;\n    UInt16 response_len;\n    \n    cache_as_buf->entry = entry;\n    cache_as_buf->finished = false;\n    \n    while (!cache_as_buf->finished && offset < buffer_len) {\n        response_len = rx_data_len > remain_len ? SURFACE_HID_DESC_HEADER_SIZE + remain_len : sizeof(cache);\n        \n        cache_as_buf->offset = offset;\n        cache_as_buf->length = length;\n\n        if (ssh->getResponse(SSH_TC_HID, SSH_TID_SECONDARY, device, SSH_CID_HID_GET_DESCRIPTOR, cache, SURFACE_HID_DESC_HEADER_SIZE, true, cache, response_len) != kIOReturnSuccess) {\n            LOG(\"Failed to get data from SSH!\");\n            return kIOReturnError;\n        }\n\n        offset = cache_as_buf->offset;\n        length = cache_as_buf->length;\n\n        // Don't mess stuff up in case we receive garbage.\n        if (length > rx_data_len || offset > buffer_len) {\n            LOG(\"Received bogus data!\");\n            return kIOReturnError;\n        }\n\n        if (offset + length > buffer_len) {\n            LOG(\"Not enough space for buffer, need at least %d\", offset+length);\n            length = buffer_len - offset;\n        }\n\n        memcpy(buffer + offset, &cache_as_buf->data[0], length);\n\n        offset += length;\n        remain_len -= length;\n        length = rx_data_len;\n    }\n\n    if (offset != buffer_len) {\n        LOG(\"Unexpected descriptor length: got %u, expected %u\", offset, buffer_len);\n        return kIOReturnError;\n    }\n    return kIOReturnSuccess;\n}\n\nIOReturn SurfaceHIDNub::getHIDRawReport(SurfaceHIDDeviceType device, UInt8 report_id, UInt8 *buffer, UInt16 len) {\n    if (legacy) {\n        UInt8 payload = 0;\n        UInt8 report[SURFACE_LEGACY_FEAT_REPORT_SIZE];\n        \n        if (len < SURFACE_LEGACY_FEAT_REPORT_SIZE)\n            return kIOReturnNoSpace;\n        \n        IOReturn ret = ssh->getResponse(SSH_TC_KBD, SSH_TID_SECONDARY, device, SSH_CID_KBD_GET_FEAT_REPORT, &payload, 1, true, report, SURFACE_LEGACY_FEAT_REPORT_SIZE);\n        if (ret != kIOReturnSuccess)\n            return ret;\n        if (report[0] != report_id)\n            return kIOReturnUnsupported;\n        \n        memcpy(buffer, report, SURFACE_LEGACY_FEAT_REPORT_SIZE);\n        return kIOReturnSuccess;\n    } else\n        return ssh->getResponse(SSH_TC_HID, SSH_TID_SECONDARY, device, SSH_CID_HID_GET_FEAT_REPORT, &report_id, 1, true, buffer, len);\n}\n\nvoid SurfaceHIDNub::setHIDRawReport(SurfaceHIDDeviceType device, UInt8 report_id, bool feature, UInt8 *buffer, UInt16 len) {\n    if (!legacy) {\n        UInt8 cid = feature ? SSH_CID_HID_SET_FEAT_REPORT : SSH_CID_HID_OUT_REPORT;\n        buffer[0] = report_id;\n        ssh->sendCommand(SSH_TC_HID, SSH_TID_SECONDARY, device, cid, buffer, len, true);\n    }\n}\n"
  },
  {
    "path": "BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceHIDNub.hpp",
    "content": "//\n//  SurfaceHIDNub.hpp\n//  SurfaceSerialHubDevices\n//\n//  Created by Xavier on 2022/5/20.\n//  Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#ifndef SurfaceHIDNub_hpp\n#define SurfaceHIDNub_hpp\n\n#include \"../SurfaceSerialHub/SurfaceSerialHubDriver.hpp\"\n\nenum SurfaceHIDDescriptorEntryType : UInt8 {\n    SurfaceHIDDescriptorEntry       = 0,\n    SurfaceHIDAttributesEntry       = 2,\n    SurfaceReportDescriptorEntry    = 1,\n};\n\nenum SurfaceHIDDeviceType {\n    SurfaceLegacyKeyboardDevice = 0x00,\n    SurfaceKeyboardDevice       = 0x01,\n    SurfaceTouchpadDevice       = 0x03,\n};\n\nstruct PACKED SurfaceHIDDescriptorBufferHeader {\n    UInt8  entry;\n    UInt32 offset;\n    UInt32 length;\n    UInt8  finished;\n    UInt8  data[];\n};\n\nstruct PACKED SurfaceHIDDescriptor {\n    UInt8  desc_len;            /* = 9 */\n    UInt8  desc_type;           /* = HID_DT_HID */\n    UInt16 hid_version;\n    UInt8  country_code;\n    UInt8  num_descriptors;     /* = 1 */\n    UInt8  report_desc_type;    /* = HID_DT_REPORT */\n    UInt16 report_desc_len;\n};\n\nstruct PACKED SurfaceHIDAttributes {\n    UInt32 length;\n    UInt16 vendor;\n    UInt16 product;\n    UInt16 version;\n    UInt8  _unknown[22];\n};\n\n#define SURFACE_LEGACY_HID_STRING       \"SurfaceLegacyHID\"\n#define SURFACE_LEGACY_FEAT_REPORT_SIZE 7\n\n#define SURFACE_HID_DESC_HEADER_SIZE sizeof(SurfaceHIDDescriptorBufferHeader)\n\nclass EXPORT SurfaceHIDNub : public SurfaceSerialHubClient {\n    OSDeclareDefaultStructors(SurfaceHIDNub)\n\npublic:\n    typedef void (*EventHandler)(OSObject *owner, SurfaceHIDNub *sender, SurfaceHIDDeviceType device, UInt8 *buffer, UInt16 len);\n    \n    bool attach(IOService* provider) override;\n    \n    void detach(IOService* provider) override;\n    \n    bool start(IOService* provider) override;\n    \n    void stop(IOService* provider) override;\n    \n    IOReturn setPowerState(unsigned long whichState, IOService *device) override;\n    \n    IOReturn registerHIDEvent(OSObject* owner, EventHandler _handler);\n    \n    void unregisterHIDEvent(OSObject* owner);\n    \n    void eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) override;\n    \n    IOReturn getHIDDescriptor(SurfaceHIDDeviceType device, SurfaceHIDDescriptor *desc);\n    \n    IOReturn getHIDAttributes(SurfaceHIDDeviceType device, SurfaceHIDAttributes *attr);\n    \n    IOReturn getReportDescriptor(SurfaceHIDDeviceType device, UInt8 *buffer, UInt16 len);\n    \n    IOReturn getHIDRawReport(SurfaceHIDDeviceType device, UInt8 report_id, UInt8 *buffer, UInt16 len);\n    \n    void setHIDRawReport(SurfaceHIDDeviceType device, UInt8 report_id, bool feature, UInt8 *buffer, UInt16 len);\n    \nprivate:\n    SurfaceSerialHubDriver* ssh {nullptr};\n    OSObject*               target {nullptr};\n    EventHandler            handler {nullptr};\n\n    bool    legacy {true};\n\n    IOReturn getDescriptorData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len);\n    \n    IOReturn getLegacyData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len);\n    IOReturn getData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len);\n};\n\n#endif /* SurfaceHIDNub_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface/helpers.hpp",
    "content": "//\n//  helpers.hpp\n//  BigSurface\n//\n//  Created by Xavier on 2023/2/7.\n//  Copyright © 2023 Xia Shangning. All rights reserved.\n//\n\n#ifndef helpers_hpp\n#define helpers_hpp\n\n#include <IOKit/IOService.h>\n#include <IOKit/IOLib.h>\n\n#ifndef EXPORT\n#define EXPORT __attribute__((visibility(\"default\")))\n#endif\n\n#define kIOPMPowerOff                       0\n#define kIOPMNumberPowerStates              2\n\n#define BIT(nr) (1UL << (nr))\n\n#ifndef GENMASK\n#define GENMASK(h, l) (((~0UL) << (l)) & (~0UL >> (64 - 1 - (h))))\n#endif\n\nstatic IOPMPowerState myIOPMPowerStates[kIOPMNumberPowerStates] = {\n    {1, kIOPMPowerOff, kIOPMPowerOff, kIOPMPowerOff, 0, 0, 0, 0, 0, 0, 0, 0},\n    {1, kIOPMPowerOn, kIOPMPowerOn, kIOPMPowerOn, 0, 0, 0, 0, 0, 0, 0, 0}\n};\n\n#define LOG(str, ...)    IOLog(\"%s::\" str \"\\n\", getName(), ##__VA_ARGS__)\n\n#ifdef DEBUG\n#define DBG_LOG(str, ...)   LOG(\"dbg-\" str, ##__VA_ARGS__)\n#else\n#define DBG_LOG(str, ...)   ;\n#endif\n\n#endif /* helpers_hpp */\n"
  },
  {
    "path": "BigSurface/BigSurface.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 54;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t2518A2F62734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 2518A2F32734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp */; };\n\t\t2518A2F72734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2518A2F42734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp */; };\n\t\t2518A2F82734F6AA00B0D631 /* APDS9960Constants.h in Headers */ = {isa = PBXBuildFile; fileRef = 2518A2F52734F6AA00B0D631 /* APDS9960Constants.h */; };\n\t\t2524C0A626F3233A00CAAF12 /* SurfaceButtonDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2524C0A426F3233A00CAAF12 /* SurfaceButtonDriver.cpp */; };\n\t\t2524C0A726F3233A00CAAF12 /* SurfaceButtonDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 2524C0A526F3233A00CAAF12 /* SurfaceButtonDriver.hpp */; };\n\t\t25506BAA29929D7A007F59BF /* helpers.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25506BA929929D7A007F59BF /* helpers.hpp */; };\n\t\t259040E926FC065400D605D0 /* SurfaceButtonDevice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259040E726FC065400D605D0 /* SurfaceButtonDevice.cpp */; };\n\t\t259040EA26FC065400D605D0 /* SurfaceButtonDevice.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259040E826FC065400D605D0 /* SurfaceButtonDevice.hpp */; };\n\t\t259040EC26FC0BB200D605D0 /* HIDReport.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259040EB26FC0BB200D605D0 /* HIDReport.hpp */; };\n\t\t2597317D2738B01F00A7F7C1 /* KeyImplementations.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731702738B01F00A7F7C1 /* KeyImplementations.hpp */; };\n\t\t2597317E2738B01F00A7F7C1 /* SurfaceACAdapter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259731712738B01F00A7F7C1 /* SurfaceACAdapter.cpp */; };\n\t\t2597317F2738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731722738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp */; };\n\t\t259731812738B01F00A7F7C1 /* BatteryManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259731742738B01F00A7F7C1 /* BatteryManager.cpp */; };\n\t\t259731822738B01F00A7F7C1 /* SurfaceBattery.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259731752738B01F00A7F7C1 /* SurfaceBattery.cpp */; };\n\t\t259731832738B01F00A7F7C1 /* SurfaceBattery.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731762738B01F00A7F7C1 /* SurfaceBattery.hpp */; };\n\t\t259731842738B01F00A7F7C1 /* BatteryManagerState.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731772738B01F00A7F7C1 /* BatteryManagerState.hpp */; };\n\t\t259731852738B01F00A7F7C1 /* KeyImplementations.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259731782738B01F00A7F7C1 /* KeyImplementations.cpp */; };\n\t\t259731862738B01F00A7F7C1 /* SurfaceACAdapter.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731792738B01F00A7F7C1 /* SurfaceACAdapter.hpp */; };\n\t\t259731882738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2597317B2738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp */; };\n\t\t259731892738B01F00A7F7C1 /* BatteryManager.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 2597317C2738B01F00A7F7C1 /* BatteryManager.hpp */; };\n\t\t2597318C2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 2597318A2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp */; };\n\t\t2597318D2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2597318B2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp */; };\n\t\t25B97D89260B950E00657C76 /* libkmod.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7BE66D8F258AC5DC003CA4AD /* libkmod.a */; };\n\t\t25C8D7EB27359FCD00F58956 /* SerialProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 25C8D7E827359FCD00F58956 /* SerialProtocol.h */; };\n\t\t25C8D7EC27359FCD00F58956 /* SurfaceSerialHubDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25C8D7E927359FCD00F58956 /* SurfaceSerialHubDriver.cpp */; };\n\t\t25C8D7ED27359FCD00F58956 /* SurfaceSerialHubDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25C8D7EA27359FCD00F58956 /* SurfaceSerialHubDriver.hpp */; };\n\t\t25D907292736E2B2006D799F /* AmbientLightValue.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25D907272736E2B2006D799F /* AmbientLightValue.hpp */; };\n\t\t25D9072A2736E2B2006D799F /* AmbientLightValue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25D907282736E2B2006D799F /* AmbientLightValue.cpp */; };\n\t\t25DBA9742836A77700459629 /* SurfaceHIDNub.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25DBA9722836A77700459629 /* SurfaceHIDNub.cpp */; };\n\t\t25DBA9752836A77700459629 /* SurfaceHIDNub.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25DBA9732836A77700459629 /* SurfaceHIDNub.hpp */; };\n\t\t25E5B4CB2991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25E5B4C62991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp */; };\n\t\t25E5B4CC2991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25E5B4C72991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp */; };\n\t\t25E5B4CD2991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25E5B4C82991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp */; };\n\t\t25E5B4CE2991ACE7007F21D4 /* MEIProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 25E5B4C92991ACE7007F21D4 /* MEIProtocol.h */; };\n\t\t25E5B4CF2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25E5B4CA2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp */; };\n\t\t25EA2A7E2836412B00525325 /* SurfaceBatteryNub.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25EA2A7C2836412B00525325 /* SurfaceBatteryNub.cpp */; };\n\t\t25EA2A7F2836412B00525325 /* SurfaceBatteryNub.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25EA2A7D2836412B00525325 /* SurfaceBatteryNub.hpp */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXContainerItemProxy section */\n\t\t25CBB35F2733D4C1009B568B /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = F1F172C51F42263A00AD98FA;\n\t\t\tremoteInfo = VoodooGPIO;\n\t\t};\n\t\t25CBB3642733D4C9009B568B /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = 25813607272D6A2800EED5C9;\n\t\t\tremoteInfo = VoodooSerial;\n\t\t};\n\t\t25CBB36A2733D50A009B568B /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = 25B97D6F260B950E00657C76;\n\t\t\tremoteInfo = VoodooSerial;\n\t\t};\n\t\t25CDE61D285F291D003FB4C4 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = 7BBAB1F922E3A2F800B2941A;\n\t\t\tremoteInfo = VoodooInput;\n\t\t};\n\t\t25CDE625285F2972003FB4C4 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = 7BBAB1F822E3A2F800B2941A;\n\t\t\tremoteInfo = VoodooInput;\n\t\t};\n\t\t25D49D8E2854EE92008CAAA5 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = F1F172C41F42263A00AD98FA;\n\t\t\tremoteInfo = VoodooGPIO;\n\t\t};\n\t\t25E5B47929919DCC007F21D4 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = 25E5B46829919DCB007F21D4;\n\t\t\tremoteInfo = BigSurfaceHIDDriver;\n\t\t};\n\t\t25E5B47E29919F2C007F21D4 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = 25E5B46729919DCB007F21D4;\n\t\t\tremoteInfo = BigSurfaceHIDDriver;\n\t\t};\n\t\tAC94C83C2119E50400D26081 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = AC94C8382119E50400D26081 /* VoodooI2CSynaptics.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = ACD148A21FF17DE00008EA7B;\n\t\t\tremoteInfo = VoodooI2CSynaptics;\n\t\t};\n/* End PBXContainerItemProxy section */\n\n/* Begin PBXFileReference section */\n\t\t2518A2F32734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceAmbientLightSensorDriver.hpp; sourceTree = \"<group>\"; };\n\t\t2518A2F42734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceAmbientLightSensorDriver.cpp; sourceTree = \"<group>\"; };\n\t\t2518A2F52734F6AA00B0D631 /* APDS9960Constants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APDS9960Constants.h; sourceTree = \"<group>\"; };\n\t\t2524C0A426F3233A00CAAF12 /* SurfaceButtonDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceButtonDriver.cpp; sourceTree = \"<group>\"; };\n\t\t2524C0A526F3233A00CAAF12 /* SurfaceButtonDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceButtonDriver.hpp; sourceTree = \"<group>\"; };\n\t\t25506BA929929D7A007F59BF /* helpers.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; path = helpers.hpp; sourceTree = \"<group>\"; };\n\t\t25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooSerial.xcodeproj; path = VoodooSerial/VoodooSerial.xcodeproj; sourceTree = \"<group>\"; };\n\t\t259040E726FC065400D605D0 /* SurfaceButtonDevice.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceButtonDevice.cpp; sourceTree = \"<group>\"; };\n\t\t259040E826FC065400D605D0 /* SurfaceButtonDevice.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceButtonDevice.hpp; sourceTree = \"<group>\"; };\n\t\t259040EB26FC0BB200D605D0 /* HIDReport.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = HIDReport.hpp; sourceTree = \"<group>\"; };\n\t\t259731702738B01F00A7F7C1 /* KeyImplementations.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = KeyImplementations.hpp; sourceTree = \"<group>\"; };\n\t\t259731712738B01F00A7F7C1 /* SurfaceACAdapter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceACAdapter.cpp; sourceTree = \"<group>\"; };\n\t\t259731722738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceBatteryDriver.hpp; sourceTree = \"<group>\"; };\n\t\t259731742738B01F00A7F7C1 /* BatteryManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BatteryManager.cpp; sourceTree = \"<group>\"; };\n\t\t259731752738B01F00A7F7C1 /* SurfaceBattery.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceBattery.cpp; sourceTree = \"<group>\"; };\n\t\t259731762738B01F00A7F7C1 /* SurfaceBattery.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceBattery.hpp; sourceTree = \"<group>\"; };\n\t\t259731772738B01F00A7F7C1 /* BatteryManagerState.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = BatteryManagerState.hpp; sourceTree = \"<group>\"; };\n\t\t259731782738B01F00A7F7C1 /* KeyImplementations.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = KeyImplementations.cpp; sourceTree = \"<group>\"; };\n\t\t259731792738B01F00A7F7C1 /* SurfaceACAdapter.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceACAdapter.hpp; sourceTree = \"<group>\"; };\n\t\t2597317B2738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceBatteryDriver.cpp; sourceTree = \"<group>\"; };\n\t\t2597317C2738B01F00A7F7C1 /* BatteryManager.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = BatteryManager.hpp; sourceTree = \"<group>\"; };\n\t\t2597318A2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceSMBusController.hpp; sourceTree = \"<group>\"; };\n\t\t2597318B2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceSMBusController.cpp; sourceTree = \"<group>\"; };\n\t\t25B97DA5260B950E00657C76 /* BigSurface.kext */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = BigSurface.kext; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooGPIO.xcodeproj; path = VoodooGPIO/VoodooGPIO.xcodeproj; sourceTree = \"<group>\"; };\n\t\t25B97E43260BA33B00657C76 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = \"<group>\"; };\n\t\t25C8D7E827359FCD00F58956 /* SerialProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SerialProtocol.h; sourceTree = \"<group>\"; };\n\t\t25C8D7E927359FCD00F58956 /* SurfaceSerialHubDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceSerialHubDriver.cpp; sourceTree = \"<group>\"; };\n\t\t25C8D7EA27359FCD00F58956 /* SurfaceSerialHubDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceSerialHubDriver.hpp; sourceTree = \"<group>\"; };\n\t\t25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooInput.xcodeproj; path = VoodooInput/VoodooInput.xcodeproj; sourceTree = \"<group>\"; };\n\t\t25D9064A2736DB7F006D799F /* kern_smcinfo.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = kern_smcinfo.hpp; sourceTree = \"<group>\"; };\n\t\t25D9064B2736DB7F006D799F /* kern_vsmcapi.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = kern_vsmcapi.hpp; sourceTree = \"<group>\"; };\n\t\t25D9064C2736DB7F006D799F /* AppleSmc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppleSmc.h; sourceTree = \"<group>\"; };\n\t\t25D9064D2736DB7F006D799F /* kern_keyvalue.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = kern_keyvalue.hpp; sourceTree = \"<group>\"; };\n\t\t25D9064E2736DB7F006D799F /* kern_value.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = kern_value.hpp; sourceTree = \"<group>\"; };\n\t\t25D9064F2736DB7F006D799F /* AppleSmcBridge.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = AppleSmcBridge.hpp; sourceTree = \"<group>\"; };\n\t\t25D906F92736E125006D799F /* kern_config.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_config.hpp; sourceTree = \"<group>\"; };\n\t\t25D906FA2736E125006D799F /* hde64.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = hde64.h; sourceTree = \"<group>\"; };\n\t\t25D906FB2736E125006D799F /* kern_time.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_time.hpp; sourceTree = \"<group>\"; };\n\t\t25D906FC2736E125006D799F /* kern_nvram.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_nvram.hpp; sourceTree = \"<group>\"; };\n\t\t25D906FD2736E125006D799F /* kern_cpu.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_cpu.hpp; sourceTree = \"<group>\"; };\n\t\t25D906FE2736E125006D799F /* kern_devinfo.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_devinfo.hpp; sourceTree = \"<group>\"; };\n\t\t25D906FF2736E125006D799F /* kern_efi.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_efi.hpp; sourceTree = \"<group>\"; };\n\t\t25D907002736E125006D799F /* kern_policy.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_policy.hpp; sourceTree = \"<group>\"; };\n\t\t25D907012736E125006D799F /* kern_user.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_user.hpp; sourceTree = \"<group>\"; };\n\t\t25D907022736E125006D799F /* plugin_start.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = plugin_start.hpp; sourceTree = \"<group>\"; };\n\t\t25D907032736E125006D799F /* kern_iokit.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_iokit.hpp; sourceTree = \"<group>\"; };\n\t\t25D907042736E125006D799F /* kern_crypto.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_crypto.hpp; sourceTree = \"<group>\"; };\n\t\t25D907052736E125006D799F /* kern_mach.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_mach.hpp; sourceTree = \"<group>\"; };\n\t\t25D907062736E125006D799F /* kern_version.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_version.hpp; sourceTree = \"<group>\"; };\n\t\t25D907072736E125006D799F /* kern_compression.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_compression.hpp; sourceTree = \"<group>\"; };\n\t\t25D907082736E125006D799F /* kern_file.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_file.hpp; sourceTree = \"<group>\"; };\n\t\t25D907092736E125006D799F /* kern_rtc.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_rtc.hpp; sourceTree = \"<group>\"; };\n\t\t25D9070A2736E125006D799F /* kern_disasm.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_disasm.hpp; sourceTree = \"<group>\"; };\n\t\t25D9070C2736E125006D799F /* capstone.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = capstone.h; sourceTree = \"<group>\"; };\n\t\t25D9070D2736E125006D799F /* mips.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = mips.h; sourceTree = \"<group>\"; };\n\t\t25D9070E2736E125006D799F /* sparc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = sparc.h; sourceTree = \"<group>\"; };\n\t\t25D9070F2736E125006D799F /* systemz.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = systemz.h; sourceTree = \"<group>\"; };\n\t\t25D907102736E125006D799F /* arm.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = arm.h; sourceTree = \"<group>\"; };\n\t\t25D907112736E125006D799F /* x86.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = x86.h; sourceTree = \"<group>\"; };\n\t\t25D907122736E125006D799F /* ppc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ppc.h; sourceTree = \"<group>\"; };\n\t\t25D907132736E125006D799F /* arm64.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = arm64.h; sourceTree = \"<group>\"; };\n\t\t25D907142736E125006D799F /* xcore.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = xcore.h; sourceTree = \"<group>\"; };\n\t\t25D907152736E125006D799F /* platform.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = platform.h; sourceTree = \"<group>\"; };\n\t\t25D907162736E125006D799F /* kern_patcher.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_patcher.hpp; sourceTree = \"<group>\"; };\n\t\t25D907172736E125006D799F /* hde32.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = hde32.h; sourceTree = \"<group>\"; };\n\t\t25D907182736E125006D799F /* kern_compat.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_compat.hpp; sourceTree = \"<group>\"; };\n\t\t25D907192736E125006D799F /* kern_api.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_api.hpp; sourceTree = \"<group>\"; };\n\t\t25D9071A2736E125006D799F /* kern_util.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_util.hpp; sourceTree = \"<group>\"; };\n\t\t25D9071D2736E125006D799F /* entry64.S */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.asm; path = entry64.S; sourceTree = \"<group>\"; };\n\t\t25D9071E2736E125006D799F /* build.tool */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = build.tool; sourceTree = \"<group>\"; };\n\t\t25D9071F2736E125006D799F /* entry32.S */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.asm; path = entry32.S; sourceTree = \"<group>\"; };\n\t\t25D907202736E125006D799F /* wrappers.inc */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.pascal; path = wrappers.inc; sourceTree = \"<group>\"; };\n\t\t25D907212736E125006D799F /* plugin_start.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = plugin_start.cpp; sourceTree = \"<group>\"; };\n\t\t25D907272736E2B2006D799F /* AmbientLightValue.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = AmbientLightValue.hpp; sourceTree = \"<group>\"; };\n\t\t25D907282736E2B2006D799F /* AmbientLightValue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AmbientLightValue.cpp; sourceTree = \"<group>\"; };\n\t\t25DBA9722836A77700459629 /* SurfaceHIDNub.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceHIDNub.cpp; sourceTree = \"<group>\"; };\n\t\t25DBA9732836A77700459629 /* SurfaceHIDNub.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = SurfaceHIDNub.hpp; sourceTree = \"<group>\"; };\n\t\t25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = BigSurfaceHIDDriver.xcodeproj; path = BigSurfaceHIDDriver/BigSurfaceHIDDriver.xcodeproj; sourceTree = \"<group>\"; };\n\t\t25E5B4C62991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceManagementEngineClient.hpp; sourceTree = \"<group>\"; };\n\t\t25E5B4C72991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceManagementEngineDriver.cpp; sourceTree = \"<group>\"; };\n\t\t25E5B4C82991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceManagementEngineDriver.hpp; sourceTree = \"<group>\"; };\n\t\t25E5B4C92991ACE7007F21D4 /* MEIProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MEIProtocol.h; sourceTree = \"<group>\"; };\n\t\t25E5B4CA2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceManagementEngineClient.cpp; sourceTree = \"<group>\"; };\n\t\t25EA2A7C2836412B00525325 /* SurfaceBatteryNub.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceBatteryNub.cpp; sourceTree = \"<group>\"; };\n\t\t25EA2A7D2836412B00525325 /* SurfaceBatteryNub.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = SurfaceBatteryNub.hpp; sourceTree = \"<group>\"; };\n\t\t7BE66D8F258AC5DC003CA4AD /* libkmod.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libkmod.a; path = ../MacKernelSDK/Library/x86_64/libkmod.a; sourceTree = \"<group>\"; };\n\t\tAC94C8382119E50400D26081 /* VoodooI2CSynaptics.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooI2CSynaptics.xcodeproj; path = \"../../VoodooI2C Satellites/VoodooI2CSynaptics/VoodooI2CSynaptics.xcodeproj\"; sourceTree = \"<group>\"; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\t25B97D88260B950E00657C76 /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t25B97D89260B950E00657C76 /* libkmod.a in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t2518A2F22734F6AA00B0D631 /* SurfaceAmbientLightSensor */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t2518A2F52734F6AA00B0D631 /* APDS9960Constants.h */,\n\t\t\t\t2518A2F42734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp */,\n\t\t\t\t2518A2F32734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp */,\n\t\t\t\t25D907282736E2B2006D799F /* AmbientLightValue.cpp */,\n\t\t\t\t25D907272736E2B2006D799F /* AmbientLightValue.hpp */,\n\t\t\t);\n\t\t\tpath = SurfaceAmbientLightSensor;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t2524C0A326F3233A00CAAF12 /* SurfaceButton */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t259040EB26FC0BB200D605D0 /* HIDReport.hpp */,\n\t\t\t\t259040E726FC065400D605D0 /* SurfaceButtonDevice.cpp */,\n\t\t\t\t259040E826FC065400D605D0 /* SurfaceButtonDevice.hpp */,\n\t\t\t\t2524C0A426F3233A00CAAF12 /* SurfaceButtonDriver.cpp */,\n\t\t\t\t2524C0A526F3233A00CAAF12 /* SurfaceButtonDriver.hpp */,\n\t\t\t);\n\t\t\tpath = SurfaceButton;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t2597316F2738B01F00A7F7C1 /* SurfaceBattery */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t259731712738B01F00A7F7C1 /* SurfaceACAdapter.cpp */,\n\t\t\t\t259731792738B01F00A7F7C1 /* SurfaceACAdapter.hpp */,\n\t\t\t\t259731752738B01F00A7F7C1 /* SurfaceBattery.cpp */,\n\t\t\t\t259731762738B01F00A7F7C1 /* SurfaceBattery.hpp */,\n\t\t\t\t259731742738B01F00A7F7C1 /* BatteryManager.cpp */,\n\t\t\t\t2597317C2738B01F00A7F7C1 /* BatteryManager.hpp */,\n\t\t\t\t259731772738B01F00A7F7C1 /* BatteryManagerState.hpp */,\n\t\t\t\t259731782738B01F00A7F7C1 /* KeyImplementations.cpp */,\n\t\t\t\t259731702738B01F00A7F7C1 /* KeyImplementations.hpp */,\n\t\t\t\t2597317B2738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp */,\n\t\t\t\t259731722738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp */,\n\t\t\t\t2597318B2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp */,\n\t\t\t\t2597318A2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp */,\n\t\t\t);\n\t\t\tpath = SurfaceBattery;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25B97D6E260B943E00657C76 /* BigSurface */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC0955711F4ED49E0052E343 /* Dependencies */,\n\t\t\t\t2524C0A326F3233A00CAAF12 /* SurfaceButton */,\n\t\t\t\t2518A2F22734F6AA00B0D631 /* SurfaceAmbientLightSensor */,\n\t\t\t\t25C8D7E727359FCD00F58956 /* SurfaceSerialHub */,\n\t\t\t\t25DBA9762836A78900459629 /* SurfaceSerialHubDevices */,\n\t\t\t\t2597316F2738B01F00A7F7C1 /* SurfaceBattery */,\n\t\t\t\t25E5B4C52991ACE7007F21D4 /* SurfaceManagementEngine */,\n\t\t\t\t25506BA929929D7A007F59BF /* helpers.hpp */,\n\t\t\t\t25B97E43260BA33B00657C76 /* Info.plist */,\n\t\t\t);\n\t\t\tpath = BigSurface;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25C8D7E727359FCD00F58956 /* SurfaceSerialHub */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25C8D7E827359FCD00F58956 /* SerialProtocol.h */,\n\t\t\t\t25C8D7E927359FCD00F58956 /* SurfaceSerialHubDriver.cpp */,\n\t\t\t\t25C8D7EA27359FCD00F58956 /* SurfaceSerialHubDriver.hpp */,\n\t\t\t);\n\t\t\tpath = SurfaceSerialHub;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25CBB35C2733D4C1009B568B /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25CBB3602733D4C1009B568B /* VoodooGPIO.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25CBB3612733D4C9009B568B /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25CBB3652733D4C9009B568B /* VoodooSerial.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25CDE61A285F291D003FB4C4 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25CDE61E285F291D003FB4C4 /* VoodooInput.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25D906492736DB7F006D799F /* VirtualSMCSDK */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25D9064A2736DB7F006D799F /* kern_smcinfo.hpp */,\n\t\t\t\t25D9064B2736DB7F006D799F /* kern_vsmcapi.hpp */,\n\t\t\t\t25D9064C2736DB7F006D799F /* AppleSmc.h */,\n\t\t\t\t25D9064D2736DB7F006D799F /* kern_keyvalue.hpp */,\n\t\t\t\t25D9064E2736DB7F006D799F /* kern_value.hpp */,\n\t\t\t\t25D9064F2736DB7F006D799F /* AppleSmcBridge.hpp */,\n\t\t\t);\n\t\t\tname = VirtualSMCSDK;\n\t\t\tpath = VirtualSMC.kext/Contents/Resources/VirtualSMCSDK;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25D906A72736DC1A006D799F /* LiluSDK */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25D906F82736E125006D799F /* Headers */,\n\t\t\t\t25D9071B2736E125006D799F /* Library */,\n\t\t\t);\n\t\t\tname = LiluSDK;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25D906F82736E125006D799F /* Headers */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25D906F92736E125006D799F /* kern_config.hpp */,\n\t\t\t\t25D906FA2736E125006D799F /* hde64.h */,\n\t\t\t\t25D906FB2736E125006D799F /* kern_time.hpp */,\n\t\t\t\t25D906FC2736E125006D799F /* kern_nvram.hpp */,\n\t\t\t\t25D906FD2736E125006D799F /* kern_cpu.hpp */,\n\t\t\t\t25D906FE2736E125006D799F /* kern_devinfo.hpp */,\n\t\t\t\t25D906FF2736E125006D799F /* kern_efi.hpp */,\n\t\t\t\t25D907002736E125006D799F /* kern_policy.hpp */,\n\t\t\t\t25D907012736E125006D799F /* kern_user.hpp */,\n\t\t\t\t25D907022736E125006D799F /* plugin_start.hpp */,\n\t\t\t\t25D907032736E125006D799F /* kern_iokit.hpp */,\n\t\t\t\t25D907042736E125006D799F /* kern_crypto.hpp */,\n\t\t\t\t25D907052736E125006D799F /* kern_mach.hpp */,\n\t\t\t\t25D907062736E125006D799F /* kern_version.hpp */,\n\t\t\t\t25D907072736E125006D799F /* kern_compression.hpp */,\n\t\t\t\t25D907082736E125006D799F /* kern_file.hpp */,\n\t\t\t\t25D907092736E125006D799F /* kern_rtc.hpp */,\n\t\t\t\t25D9070A2736E125006D799F /* kern_disasm.hpp */,\n\t\t\t\t25D9070B2736E125006D799F /* capstone */,\n\t\t\t\t25D907162736E125006D799F /* kern_patcher.hpp */,\n\t\t\t\t25D907172736E125006D799F /* hde32.h */,\n\t\t\t\t25D907182736E125006D799F /* kern_compat.hpp */,\n\t\t\t\t25D907192736E125006D799F /* kern_api.hpp */,\n\t\t\t\t25D9071A2736E125006D799F /* kern_util.hpp */,\n\t\t\t);\n\t\t\tname = Headers;\n\t\t\tpath = Lilu.kext/Contents/Resources/Headers;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25D9070B2736E125006D799F /* capstone */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25D9070C2736E125006D799F /* capstone.h */,\n\t\t\t\t25D9070D2736E125006D799F /* mips.h */,\n\t\t\t\t25D9070E2736E125006D799F /* sparc.h */,\n\t\t\t\t25D9070F2736E125006D799F /* systemz.h */,\n\t\t\t\t25D907102736E125006D799F /* arm.h */,\n\t\t\t\t25D907112736E125006D799F /* x86.h */,\n\t\t\t\t25D907122736E125006D799F /* ppc.h */,\n\t\t\t\t25D907132736E125006D799F /* arm64.h */,\n\t\t\t\t25D907142736E125006D799F /* xcore.h */,\n\t\t\t\t25D907152736E125006D799F /* platform.h */,\n\t\t\t);\n\t\t\tpath = capstone;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25D9071B2736E125006D799F /* Library */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25D9071C2736E125006D799F /* wrappers */,\n\t\t\t\t25D907212736E125006D799F /* plugin_start.cpp */,\n\t\t\t);\n\t\t\tname = Library;\n\t\t\tpath = Lilu.kext/Contents/Resources/Library;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25D9071C2736E125006D799F /* wrappers */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25D9071D2736E125006D799F /* entry64.S */,\n\t\t\t\t25D9071E2736E125006D799F /* build.tool */,\n\t\t\t\t25D9071F2736E125006D799F /* entry32.S */,\n\t\t\t\t25D907202736E125006D799F /* wrappers.inc */,\n\t\t\t);\n\t\t\tpath = wrappers;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25DBA9762836A78900459629 /* SurfaceSerialHubDevices */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25EA2A7C2836412B00525325 /* SurfaceBatteryNub.cpp */,\n\t\t\t\t25EA2A7D2836412B00525325 /* SurfaceBatteryNub.hpp */,\n\t\t\t\t25DBA9722836A77700459629 /* SurfaceHIDNub.cpp */,\n\t\t\t\t25DBA9732836A77700459629 /* SurfaceHIDNub.hpp */,\n\t\t\t);\n\t\t\tpath = SurfaceSerialHubDevices;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25E5B47629919DCB007F21D4 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25E5B47A29919DCC007F21D4 /* BigSurfaceHIDDriver.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t25E5B4C52991ACE7007F21D4 /* SurfaceManagementEngine */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25E5B4C92991ACE7007F21D4 /* MEIProtocol.h */,\n\t\t\t\t25E5B4CA2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp */,\n\t\t\t\t25E5B4C62991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp */,\n\t\t\t\t25E5B4C72991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp */,\n\t\t\t\t25E5B4C82991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp */,\n\t\t\t);\n\t\t\tpath = SurfaceManagementEngine;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t7BE66D8E258AC5DC003CA4AD /* Frameworks */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t7BE66D8F258AC5DC003CA4AD /* libkmod.a */,\n\t\t\t);\n\t\t\tname = Frameworks;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC0955711F4ED49E0052E343 /* Dependencies */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25D906A72736DC1A006D799F /* LiluSDK */,\n\t\t\t\t25D906492736DB7F006D799F /* VirtualSMCSDK */,\n\t\t\t\t25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */,\n\t\t\t\t25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */,\n\t\t\t\t25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */,\n\t\t\t\t25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */,\n\t\t\t);\n\t\t\tname = Dependencies;\n\t\t\tpath = ../../Dependencies;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC2603A61F2F294000CF238F = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25B97D6E260B943E00657C76 /* BigSurface */,\n\t\t\t\tAC2603B11F2F294000CF238F /* Products */,\n\t\t\t\t7BE66D8E258AC5DC003CA4AD /* Frameworks */,\n\t\t\t);\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC2603B11F2F294000CF238F /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t25B97DA5260B950E00657C76 /* BigSurface.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC94C8392119E50400D26081 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC94C83D2119E50400D26081 /* VoodooI2CSynaptics.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXHeadersBuildPhase section */\n\t\t25B97D8A260B950E00657C76 /* Headers */ = {\n\t\t\tisa = PBXHeadersBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t259731842738B01F00A7F7C1 /* BatteryManagerState.hpp in Headers */,\n\t\t\t\t2518A2F62734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp in Headers */,\n\t\t\t\t259731892738B01F00A7F7C1 /* BatteryManager.hpp in Headers */,\n\t\t\t\t2597317F2738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp in Headers */,\n\t\t\t\t259731832738B01F00A7F7C1 /* SurfaceBattery.hpp in Headers */,\n\t\t\t\t25EA2A7F2836412B00525325 /* SurfaceBatteryNub.hpp in Headers */,\n\t\t\t\t25D907292736E2B2006D799F /* AmbientLightValue.hpp in Headers */,\n\t\t\t\t2597318C2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp in Headers */,\n\t\t\t\t2518A2F82734F6AA00B0D631 /* APDS9960Constants.h in Headers */,\n\t\t\t\t25506BAA29929D7A007F59BF /* helpers.hpp in Headers */,\n\t\t\t\t2524C0A726F3233A00CAAF12 /* SurfaceButtonDriver.hpp in Headers */,\n\t\t\t\t259731862738B01F00A7F7C1 /* SurfaceACAdapter.hpp in Headers */,\n\t\t\t\t2597317D2738B01F00A7F7C1 /* KeyImplementations.hpp in Headers */,\n\t\t\t\t25C8D7EB27359FCD00F58956 /* SerialProtocol.h in Headers */,\n\t\t\t\t25E5B4CE2991ACE7007F21D4 /* MEIProtocol.h in Headers */,\n\t\t\t\t25C8D7ED27359FCD00F58956 /* SurfaceSerialHubDriver.hpp in Headers */,\n\t\t\t\t25DBA9752836A77700459629 /* SurfaceHIDNub.hpp in Headers */,\n\t\t\t\t259040EC26FC0BB200D605D0 /* HIDReport.hpp in Headers */,\n\t\t\t\t25E5B4CB2991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp in Headers */,\n\t\t\t\t259040EA26FC065400D605D0 /* SurfaceButtonDevice.hpp in Headers */,\n\t\t\t\t25E5B4CD2991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp in Headers */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXHeadersBuildPhase section */\n\n/* Begin PBXNativeTarget section */\n\t\t25B97D6F260B950E00657C76 /* BigSurface */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 25B97DA2260B950E00657C76 /* Build configuration list for PBXNativeTarget \"BigSurface\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t25B97D8A260B950E00657C76 /* Headers */,\n\t\t\t\t25B97D74260B950E00657C76 /* Sources */,\n\t\t\t\t25B97D88260B950E00657C76 /* Frameworks */,\n\t\t\t\t25B97DA0260B950E00657C76 /* Resources */,\n\t\t\t\t25B97DA1260B950E00657C76 /* Add Plugins */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t\t25D49D8F2854EE92008CAAA5 /* PBXTargetDependency */,\n\t\t\t\t25CBB36B2733D50A009B568B /* PBXTargetDependency */,\n\t\t\t\t25CDE626285F2972003FB4C4 /* PBXTargetDependency */,\n\t\t\t\t25E5B47F29919F2C007F21D4 /* PBXTargetDependency */,\n\t\t\t);\n\t\t\tname = BigSurface;\n\t\t\tproductName = VoodooI2C;\n\t\t\tproductReference = 25B97DA5260B950E00657C76 /* BigSurface.kext */;\n\t\t\tproductType = \"com.apple.product-type.kernel-extension\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\tAC2603A71F2F294000CF238F /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tattributes = {\n\t\t\t\tLastUpgradeCheck = 1410;\n\t\t\t\tORGANIZATIONNAME = \"Xia Shangning\";\n\t\t\t\tTargetAttributes = {\n\t\t\t\t\t25B97D6F260B950E00657C76 = {\n\t\t\t\t\t\tDevelopmentTeam = K8RXBXZGN4;\n\t\t\t\t\t\tProvisioningStyle = Manual;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tbuildConfigurationList = AC2603AA1F2F294000CF238F /* Build configuration list for PBXProject \"BigSurface\" */;\n\t\t\tcompatibilityVersion = \"Xcode 3.2\";\n\t\t\tdevelopmentRegion = en;\n\t\t\thasScannedForEncodings = 0;\n\t\t\tknownRegions = (\n\t\t\t\ten,\n\t\t\t\tBase,\n\t\t\t);\n\t\t\tmainGroup = AC2603A61F2F294000CF238F;\n\t\t\tproductRefGroup = AC2603B11F2F294000CF238F /* Products */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectReferences = (\n\t\t\t\t{\n\t\t\t\t\tProductGroup = 25E5B47629919DCB007F21D4 /* Products */;\n\t\t\t\t\tProjectRef = 25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */;\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tProductGroup = 25CBB35C2733D4C1009B568B /* Products */;\n\t\t\t\t\tProjectRef = 25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */;\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tProductGroup = AC94C8392119E50400D26081 /* Products */;\n\t\t\t\t\tProjectRef = AC94C8382119E50400D26081 /* VoodooI2CSynaptics.xcodeproj */;\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tProductGroup = 25CDE61A285F291D003FB4C4 /* Products */;\n\t\t\t\t\tProjectRef = 25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */;\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tProductGroup = 25CBB3612733D4C9009B568B /* Products */;\n\t\t\t\t\tProjectRef = 25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */;\n\t\t\t\t},\n\t\t\t);\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\t25B97D6F260B950E00657C76 /* BigSurface */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXReferenceProxy section */\n\t\t25CBB3602733D4C1009B568B /* VoodooGPIO.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooGPIO.kext;\n\t\t\tremoteRef = 25CBB35F2733D4C1009B568B /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\t25CBB3652733D4C9009B568B /* VoodooSerial.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooSerial.kext;\n\t\t\tremoteRef = 25CBB3642733D4C9009B568B /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\t25CDE61E285F291D003FB4C4 /* VoodooInput.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooInput.kext;\n\t\t\tremoteRef = 25CDE61D285F291D003FB4C4 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\t25E5B47A29919DCC007F21D4 /* BigSurfaceHIDDriver.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = BigSurfaceHIDDriver.kext;\n\t\t\tremoteRef = 25E5B47929919DCC007F21D4 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\tAC94C83D2119E50400D26081 /* VoodooI2CSynaptics.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooI2CSynaptics.kext;\n\t\t\tremoteRef = AC94C83C2119E50400D26081 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n/* End PBXReferenceProxy section */\n\n/* Begin PBXResourcesBuildPhase section */\n\t\t25B97DA0260B950E00657C76 /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXResourcesBuildPhase section */\n\n/* Begin PBXShellScriptBuildPhase section */\n\t\t25B97DA1260B950E00657C76 /* Add Plugins */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\talwaysOutOfDate = 1;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t);\n\t\t\tname = \"Add Plugins\";\n\t\t\toutputPaths = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"mkdir -p \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns\\\"\\nrm -rf \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns/VoodooGPIO.kext\\\"\\nmv \\\"${BUILT_PRODUCTS_DIR}/VoodooGPIO.kext\\\" \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns\\\"\\n\\nrm -rf \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns/VoodooSerial.kext\\\"\\nmv \\\"${BUILT_PRODUCTS_DIR}/VoodooSerial.kext\\\" \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns\\\"\\n\\nrm -rf \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns/VoodooInput.kext\\\"\\nmv \\\"${BUILT_PRODUCTS_DIR}/VoodooInput.kext\\\" \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns\\\"\\n\\nrm -rf \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns/BigSurfaceHIDDriver.kext\\\"\\nmv \\\"${BUILT_PRODUCTS_DIR}/BigSurfaceHIDDriver.kext\\\" \\\"${BUILT_PRODUCTS_DIR}/BigSurface.kext/Contents/PlugIns\\\"\\n\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n/* End PBXShellScriptBuildPhase section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\t25B97D74260B950E00657C76 /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t25DBA9742836A77700459629 /* SurfaceHIDNub.cpp in Sources */,\n\t\t\t\t259731812738B01F00A7F7C1 /* BatteryManager.cpp in Sources */,\n\t\t\t\t25C8D7EC27359FCD00F58956 /* SurfaceSerialHubDriver.cpp in Sources */,\n\t\t\t\t25D9072A2736E2B2006D799F /* AmbientLightValue.cpp in Sources */,\n\t\t\t\t259040E926FC065400D605D0 /* SurfaceButtonDevice.cpp in Sources */,\n\t\t\t\t2518A2F72734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp in Sources */,\n\t\t\t\t259731822738B01F00A7F7C1 /* SurfaceBattery.cpp in Sources */,\n\t\t\t\t25E5B4CC2991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp in Sources */,\n\t\t\t\t259731882738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp in Sources */,\n\t\t\t\t25EA2A7E2836412B00525325 /* SurfaceBatteryNub.cpp in Sources */,\n\t\t\t\t259731852738B01F00A7F7C1 /* KeyImplementations.cpp in Sources */,\n\t\t\t\t2597318D2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp in Sources */,\n\t\t\t\t25E5B4CF2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp in Sources */,\n\t\t\t\t2597317E2738B01F00A7F7C1 /* SurfaceACAdapter.cpp in Sources */,\n\t\t\t\t2524C0A626F3233A00CAAF12 /* SurfaceButtonDriver.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin PBXTargetDependency section */\n\t\t25CBB36B2733D50A009B568B /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = VoodooSerial;\n\t\t\ttargetProxy = 25CBB36A2733D50A009B568B /* PBXContainerItemProxy */;\n\t\t};\n\t\t25CDE626285F2972003FB4C4 /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = VoodooInput;\n\t\t\ttargetProxy = 25CDE625285F2972003FB4C4 /* PBXContainerItemProxy */;\n\t\t};\n\t\t25D49D8F2854EE92008CAAA5 /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = VoodooGPIO;\n\t\t\ttargetProxy = 25D49D8E2854EE92008CAAA5 /* PBXContainerItemProxy */;\n\t\t};\n\t\t25E5B47F29919F2C007F21D4 /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = BigSurfaceHIDDriver;\n\t\t\ttargetProxy = 25E5B47E29919F2C007F21D4 /* PBXContainerItemProxy */;\n\t\t};\n/* End PBXTargetDependency section */\n\n/* Begin XCBuildConfiguration section */\n\t\t25B97DA3260B950E00657C76 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_DEADCODE_DEADSTORES = YES;\n\t\t\t\tCLANG_ANALYZER_DIVIDE_BY_ZERO = NO;\n\t\t\t\tCLANG_ANALYZER_NULL_DEREFERENCE = NO;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++14\";\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = NO;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\t\"CODE_SIGN_IDENTITY[sdk=macosx*]\" = \"-\";\n\t\t\t\tCODE_SIGN_INJECT_BASE_ENTITLEMENTS = YES;\n\t\t\t\tCODE_SIGN_STYLE = Manual;\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tCURRENT_PROJECT_VERSION = 1.2.0;\n\t\t\t\tDEAD_CODE_STRIPPING = YES;\n\t\t\t\tDEVELOPMENT_TEAM = K8RXBXZGN4;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 3;\n\t\t\t\tHEADER_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"$(PROJECT_DIR)/../Dependencies/VoodooInput/Debug/VoodooInput.kext/Contents/Resources\",\n\t\t\t\t\t\"$(PROJECT_DIR)/../Dependencies/VirtualSMC.kext/Contents/Resources/\",\n\t\t\t\t\t\"$(PROJECT_DIR)/../Dependencies/Lilu.kext/Contents/Resources/\",\n\t\t\t\t);\n\t\t\t\tINFOPLIST_FILE = BigSurface/Info.plist;\n\t\t\t\tINFOPLIST_KEY_NSHumanReadableCopyright = \"Copyright © 2021 Xia Shangning. All rights reserved.\";\n\t\t\t\tLIBRARY_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"$(PROJECT_DIR)/../MacKernelSDK/Library/x86_64\",\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.12;\n\t\t\t\tMARKETING_VERSION = 1.2.0;\n\t\t\t\tMODULE_NAME = com.xavier.BigSurface;\n\t\t\t\tMODULE_VERSION = 1.0.6;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.xavier.BigSurface;\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tPROVISIONING_PROFILE_SPECIFIER = \"\";\n\t\t\t\tRUN_CLANG_STATIC_ANALYZER = YES;\n\t\t\t\tWARNING_CFLAGS = \"\";\n\t\t\t\tWRAPPER_EXTENSION = kext;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t25B97DA4260B950E00657C76 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_DEADCODE_DEADSTORES = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++14\";\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = NO;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\t\"CODE_SIGN_IDENTITY[sdk=macosx*]\" = \"-\";\n\t\t\t\tCODE_SIGN_INJECT_BASE_ENTITLEMENTS = YES;\n\t\t\t\tCODE_SIGN_STYLE = Manual;\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tCURRENT_PROJECT_VERSION = 1.2.0;\n\t\t\t\tDEAD_CODE_STRIPPING = YES;\n\t\t\t\tDEVELOPMENT_TEAM = K8RXBXZGN4;\n\t\t\t\tGCC_INLINES_ARE_PRIVATE_EXTERN = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = fast;\n\t\t\t\tHEADER_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"$(PROJECT_DIR)/../Dependencies/VoodooInput/Debug/VoodooInput.kext/Contents/Resources\",\n\t\t\t\t\t\"$(PROJECT_DIR)/../Dependencies/VirtualSMC.kext/Contents/Resources/\",\n\t\t\t\t\t\"$(PROJECT_DIR)/../Dependencies/Lilu.kext/Contents/Resources/\",\n\t\t\t\t);\n\t\t\t\tINFOPLIST_FILE = BigSurface/Info.plist;\n\t\t\t\tINFOPLIST_KEY_NSHumanReadableCopyright = \"Copyright © 2021 Xia Shangning. All rights reserved.\";\n\t\t\t\tLIBRARY_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"$(PROJECT_DIR)/../MacKernelSDK/Library/x86_64\",\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.12;\n\t\t\t\tMARKETING_VERSION = 1.2.0;\n\t\t\t\tMODULE_NAME = com.xavier.BigSurface;\n\t\t\t\tMODULE_VERSION = 1.0.6;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.xavier.BigSurface;\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tPROVISIONING_PROFILE_SPECIFIER = \"\";\n\t\t\t\tWARNING_CFLAGS = \"\";\n\t\t\t\tWRAPPER_EXTENSION = kext;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\tAC2603B81F2F294000CF238F /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tARCHS = x86_64;\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++14\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = YES;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tDEAD_CODE_STRIPPING = YES;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tENABLE_TESTABILITY = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu11;\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 3;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tKERNEL_EXTENSION_HEADER_SEARCH_PATHS = \"$(PROJECT_DIR)/../MacKernelSDK/Headers\";\n\t\t\t\tKERNEL_FRAMEWORK_HEADERS = \"$(PROJECT_DIR)/../MacKernelSDK/Headers\";\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.12;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;\n\t\t\t\tMTL_FAST_MATH = YES;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tWARNING_CFLAGS = \"\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\tAC2603B91F2F294000CF238F /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tARCHS = x86_64;\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++14\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = YES;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tDEAD_CODE_STRIPPING = YES;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";\n\t\t\t\tENABLE_NS_ASSERTIONS = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu11;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = fast;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tKERNEL_EXTENSION_HEADER_SEARCH_PATHS = \"$(PROJECT_DIR)/../MacKernelSDK/Headers\";\n\t\t\t\tKERNEL_FRAMEWORK_HEADERS = \"$(PROJECT_DIR)/../MacKernelSDK/Headers\";\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.12;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tMTL_FAST_MATH = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tWARNING_CFLAGS = \"\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\t25B97DA2260B950E00657C76 /* Build configuration list for PBXNativeTarget \"BigSurface\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t25B97DA3260B950E00657C76 /* Debug */,\n\t\t\t\t25B97DA4260B950E00657C76 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\tAC2603AA1F2F294000CF238F /* Build configuration list for PBXProject \"BigSurface\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\tAC2603B81F2F294000CF238F /* Debug */,\n\t\t\t\tAC2603B91F2F294000CF238F /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = AC2603A71F2F294000CF238F /* Project object */;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface.xcodeproj/project.pbxproj.orig",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 46;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t4E67867E1FACB2A80000D307 /* VoodooI2CUPDDData.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E6786791FACB2A80000D307 /* VoodooI2CUPDDData.h */; };\n\t\t4E67867F1FACB2A80000D307 /* VoodooI2CUPDDEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4E67867A1FACB2A80000D307 /* VoodooI2CUPDDEngine.cpp */; };\n\t\t4E6786801FACB2A80000D307 /* VoodooI2CUPDDEngine.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 4E67867B1FACB2A80000D307 /* VoodooI2CUPDDEngine.hpp */; };\n\t\t4E6786811FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4E67867C1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.cpp */; };\n\t\t4E6786821FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 4E67867D1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.hpp */; };\n\t\tAC015C471F32345500516383 /* VoodooI2CACPIController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC015C451F32345500516383 /* VoodooI2CACPIController.cpp */; };\n\t\tAC015C481F32345500516383 /* VoodooI2CACPIController.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC015C461F32345500516383 /* VoodooI2CACPIController.hpp */; };\n\t\tAC0955751F4ED4C50052E343 /* helpers.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0955731F4ED4C50052E343 /* helpers.cpp */; };\n\t\tAC0955761F4ED4C50052E343 /* helpers.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0955741F4ED4C50052E343 /* helpers.hpp */; };\n\t\tAC09557A1F4ED4F60052E343 /* linuxirq.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0955771F4ED4F60052E343 /* linuxirq.hpp */; };\n\t\tAC09557B1F4ED4F60052E343 /* VoodooI2CACPICRSParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0955781F4ED4F60052E343 /* VoodooI2CACPICRSParser.cpp */; };\n\t\tAC09557C1F4ED4F60052E343 /* VoodooI2CACPICRSParser.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0955791F4ED4F60052E343 /* VoodooI2CACPICRSParser.hpp */; };\n\t\tAC0AD4581F3842800070A642 /* VoodooI2CDeviceNub.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0AD4561F3842800070A642 /* VoodooI2CDeviceNub.cpp */; };\n\t\tAC0AD4591F3842800070A642 /* VoodooI2CDeviceNub.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0AD4571F3842800070A642 /* VoodooI2CDeviceNub.hpp */; };\n\t\tAC0E75761F69997B002268D0 /* VoodooI2CDigitiserTransducer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0E75741F69997B002268D0 /* VoodooI2CDigitiserTransducer.cpp */; };\n\t\tAC0E75771F69997B002268D0 /* VoodooI2CDigitiserTransducer.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0E75751F69997B002268D0 /* VoodooI2CDigitiserTransducer.hpp */; };\n\t\tAC0E757A1F69ACEE002268D0 /* VoodooI2CDigitiserStylus.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0E75781F69ACEE002268D0 /* VoodooI2CDigitiserStylus.cpp */; };\n\t\tAC0E757B1F69ACEE002268D0 /* VoodooI2CDigitiserStylus.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0E75791F69ACEE002268D0 /* VoodooI2CDigitiserStylus.hpp */; };\n\t\tAC4954511F31E91D0040E11F /* VoodooI2CPCIController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC49544F1F31E91D0040E11F /* VoodooI2CPCIController.cpp */; };\n\t\tAC4954521F31E91D0040E11F /* VoodooI2CPCIController.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC4954501F31E91D0040E11F /* VoodooI2CPCIController.hpp */; };\n\t\tAC6268941F2F6CF1000CBF2D /* VoodooI2CController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC6268921F2F6CF1000CBF2D /* VoodooI2CController.cpp */; };\n\t\tAC6268951F2F6CF1000CBF2D /* VoodooI2CController.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC6268931F2F6CF1000CBF2D /* VoodooI2CController.hpp */; };\n\t\tAC7400B91F3B6F1000937DD5 /* Introduction.md in Sources */ = {isa = PBXBuildFile; fileRef = AC7400B81F3B6F1000937DD5 /* Introduction.md */; };\n\t\tACD09F031F756B7800E9829A /* VoodooI2CMultitouchInterface.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACD09F011F756B7800E9829A /* VoodooI2CMultitouchInterface.cpp */; };\n\t\tACD09F041F756B7800E9829A /* VoodooI2CMultitouchInterface.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACD09F021F756B7800E9829A /* VoodooI2CMultitouchInterface.hpp */; };\n\t\tACF6CF111F7587E5001CAAEE /* VoodooI2CMultitouchEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6CF0F1F7587E5001CAAEE /* VoodooI2CMultitouchEngine.cpp */; };\n\t\tACF6CF121F7587E5001CAAEE /* VoodooI2CMultitouchEngine.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACF6CF101F7587E5001CAAEE /* VoodooI2CMultitouchEngine.hpp */; };\n\t\tACF6E5871F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6E5851F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.cpp */; };\n\t\tACF6E5881F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E5861F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.hpp */; };\n\t\tACF6E5901F759EA000A0CD61 /* csgesture-softc.h in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E5891F759EA000A0CD61 /* csgesture-softc.h */; };\n\t\tACF6E5911F759EA000A0CD61 /* csgesturescroll.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6E58A1F759EA000A0CD61 /* csgesturescroll.cpp */; };\n\t\tACF6E5921F759EA000A0CD61 /* csgesturescroll.h in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E58B1F759EA000A0CD61 /* csgesturescroll.h */; };\n\t\tACF6E5931F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6E58C1F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.cpp */; };\n\t\tACF6E5941F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E58D1F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.h */; };\n\t\tACF6E5951F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6E58E1F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.cpp */; };\n\t\tACF6E5961F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E58F1F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.hpp */; };\n\t\tACF810E81F3304720031A6F5 /* VoodooI2CControllerNub.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF810E61F3304720031A6F5 /* VoodooI2CControllerNub.cpp */; };\n\t\tACF810E91F3304720031A6F5 /* VoodooI2CControllerNub.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACF810E71F3304720031A6F5 /* VoodooI2CControllerNub.hpp */; };\n\t\tACFCBA901F33644D00F9B59C /* VoodooI2CControllerDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACFCBA8E1F33644D00F9B59C /* VoodooI2CControllerDriver.cpp */; };\n\t\tACFCBA911F33644D00F9B59C /* VoodooI2CControllerDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACFCBA8F1F33644D00F9B59C /* VoodooI2CControllerDriver.hpp */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXContainerItemProxy section */\n\t\t7B30D69B1F91141300190488 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 7B30D6971F91141300190488 /* VoodooI2CELAN.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = 7B30D6871F910BAB00190488;\n\t\t\tremoteInfo = VoodooI2CELAN;\n\t\t};\n\t\t7B30D69D1F91166900190488 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 7B30D6971F91141300190488 /* VoodooI2CELAN.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = 7B30D6861F910BAB00190488;\n\t\t\tremoteInfo = VoodooI2CELAN;\n\t\t};\n\t\tACBE3FED1FEDF49B0027F52E /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = AC09558A1F4EE10C0052E343 /* VoodooGPIO.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = F1F172C41F42263A00AD98FA;\n\t\t\tremoteInfo = VoodooGPIO;\n\t\t};\n\t\tACBE3FF41FEDF4FA0027F52E /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = ACBE3FF01FEDF4FA0027F52E /* VoodooI2CUPDDEngine.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = 4E0A28F01FAD1AD200D377B0;\n\t\t\tremoteInfo = VoodooI2CUPDDEngine;\n\t\t};\n\t\tACBE3FF61FEDF4FE0027F52E /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = ACBE3FF01FEDF4FA0027F52E /* VoodooI2CUPDDEngine.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = 4E0A28EF1FAD1AD200D377B0;\n\t\t\tremoteInfo = VoodooI2CUPDDEngine;\n\t\t};\n\t\tAC0387581F5422FB00ECEDF9 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = AC0387541F5422FB00ECEDF9 /* VoodooI2CHID.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = AC0DE5DF1F4FFB4B006149C8;\n\t\t\tremoteInfo = VoodooI2CHID;\n\t\t};\n\t\tAC09558E1F4EE10C0052E343 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = AC09558A1F4EE10C0052E343 /* VoodooGPIO.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = F1F172C51F42263A00AD98FA;\n\t\t\tremoteInfo = VoodooGPIO;\n\t\t};\n\t\tAC2DC7351F7F0E5B0071CDCA /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = AC2DC7311F7F0E5B0071CDCA /* VoodooI2CServices.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = AC2DC71C1F7F0D450071CDCA;\n\t\t\tremoteInfo = VoodooI2CServices;\n\t\t};\n\t\tAC2DC7371F7F0E670071CDCA /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = AC2DC7311F7F0E5B0071CDCA /* VoodooI2CServices.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = AC2DC71B1F7F0D450071CDCA;\n\t\t\tremoteInfo = VoodooI2CServices;\n\t\t};\n\t\tACFB95CB1F54294F00867E18 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = AC0387541F5422FB00ECEDF9 /* VoodooI2CHID.xcodeproj */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = AC0DE5DE1F4FFB4B006149C8;\n\t\t\tremoteInfo = VoodooI2CHID;\n\t\t};\n/* End PBXContainerItemProxy section */\n\n/* Begin PBXFileReference section */\n<<<<<<< HEAD\n\t\t7B30D6971F91141300190488 /* VoodooI2CELAN.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooI2CELAN.xcodeproj; path = \"../../VoodooI2C Satellites/VoodooI2CELAN/VoodooI2CELAN.xcodeproj\"; sourceTree = \"<group>\"; };\n\t\t4E6786791FACB2A80000D307 /* updd_data.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = updd_data.h; path = \"../../Multitouch Support/UPDD/updd_data.h\"; sourceTree = \"<group>\"; };\n=======\n\t\t4E6786791FACB2A80000D307 /* VoodooI2CUPDDData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = VoodooI2CUPDDData.h; path = \"../../Multitouch Support/UPDD/VoodooI2CUPDDData.h\"; sourceTree = \"<group>\"; };\n>>>>>>> a29c41f... Changes to comply with VoodooI2C design guidelines.\n\t\t4E67867A1FACB2A80000D307 /* VoodooI2CUPDDEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CUPDDEngine.cpp; path = \"../../Multitouch Support/UPDD/VoodooI2CUPDDEngine.cpp\"; sourceTree = \"<group>\"; };\n\t\t4E67867B1FACB2A80000D307 /* VoodooI2CUPDDEngine.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CUPDDEngine.hpp; path = \"../../Multitouch Support/UPDD/VoodooI2CUPDDEngine.hpp\"; sourceTree = \"<group>\"; };\n\t\t4E67867C1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CUPDDGestureSocket.cpp; path = \"../../Multitouch Support/UPDD/VoodooI2CUPDDGestureSocket.cpp\"; sourceTree = \"<group>\"; };\n\t\t4E67867D1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CUPDDGestureSocket.hpp; path = \"../../Multitouch Support/UPDD/VoodooI2CUPDDGestureSocket.hpp\"; sourceTree = \"<group>\"; };\n\t\tAC015C451F32345500516383 /* VoodooI2CACPIController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CACPIController.cpp; path = VoodooI2CController/VoodooI2CACPIController.cpp; sourceTree = \"<group>\"; };\n\t\tAC015C461F32345500516383 /* VoodooI2CACPIController.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CACPIController.hpp; path = VoodooI2CController/VoodooI2CACPIController.hpp; sourceTree = \"<group>\"; };\n\t\tAC0387541F5422FB00ECEDF9 /* VoodooI2CHID.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooI2CHID.xcodeproj; path = \"../../VoodooI2C Satellites/VoodooI2CHID/VoodooI2CHID.xcodeproj\"; sourceTree = \"<group>\"; };\n\t\tAC0955731F4ED4C50052E343 /* helpers.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = helpers.cpp; path = ../../Dependencies/helpers.cpp; sourceTree = \"<group>\"; };\n\t\tAC0955741F4ED4C50052E343 /* helpers.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = helpers.hpp; path = ../../Dependencies/helpers.hpp; sourceTree = \"<group>\"; };\n\t\tAC0955771F4ED4F60052E343 /* linuxirq.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = linuxirq.hpp; path = ../../Dependencies/VoodooI2CACPICRSParser/linuxirq.hpp; sourceTree = \"<group>\"; };\n\t\tAC0955781F4ED4F60052E343 /* VoodooI2CACPICRSParser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CACPICRSParser.cpp; path = ../../Dependencies/VoodooI2CACPICRSParser/VoodooI2CACPICRSParser.cpp; sourceTree = \"<group>\"; };\n\t\tAC0955791F4ED4F60052E343 /* VoodooI2CACPICRSParser.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CACPICRSParser.hpp; path = ../../Dependencies/VoodooI2CACPICRSParser/VoodooI2CACPICRSParser.hpp; sourceTree = \"<group>\"; };\n\t\tAC09558A1F4EE10C0052E343 /* VoodooGPIO.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooGPIO.xcodeproj; path = ../../Dependencies/VoodooGPIO/VoodooGPIO.xcodeproj; sourceTree = \"<group>\"; };\n\t\tAC0A265A1F35F7FB00122252 /* VoodooI2CControllerConstants.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CControllerConstants.hpp; path = VoodooI2CController/VoodooI2CControllerConstants.hpp; sourceTree = \"<group>\"; };\n\t\tAC0AD4561F3842800070A642 /* VoodooI2CDeviceNub.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CDeviceNub.cpp; path = VoodooI2CDevice/VoodooI2CDeviceNub.cpp; sourceTree = \"<group>\"; };\n\t\tAC0AD4571F3842800070A642 /* VoodooI2CDeviceNub.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CDeviceNub.hpp; path = VoodooI2CDevice/VoodooI2CDeviceNub.hpp; sourceTree = \"<group>\"; };\n\t\tAC0E75741F69997B002268D0 /* VoodooI2CDigitiserTransducer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CDigitiserTransducer.cpp; path = \"../../Multitouch Support/VoodooI2CDigitiserTransducer.cpp\"; sourceTree = \"<group>\"; };\n\t\tAC0E75751F69997B002268D0 /* VoodooI2CDigitiserTransducer.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CDigitiserTransducer.hpp; path = \"../../Multitouch Support/VoodooI2CDigitiserTransducer.hpp\"; sourceTree = \"<group>\"; };\n\t\tACBE3FF01FEDF4FA0027F52E /* VoodooI2CUPDDEngine.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooI2CUPDDEngine.xcodeproj; path = \"../../VoodooI2C Satellites/VoodooI2CUPDDEngine/VoodooI2CUPDDEngine.xcodeproj\"; sourceTree = \"<group>\"; };\n\t\tAC0E75781F69ACEE002268D0 /* VoodooI2CDigitiserStylus.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CDigitiserStylus.cpp; path = \"../../Multitouch Support/VoodooI2CDigitiserStylus.cpp\"; sourceTree = \"<group>\"; };\n\t\tAC0E75791F69ACEE002268D0 /* VoodooI2CDigitiserStylus.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CDigitiserStylus.hpp; path = \"../../Multitouch Support/VoodooI2CDigitiserStylus.hpp\"; sourceTree = \"<group>\"; };\n\t\tAC2603B01F2F294000CF238F /* VoodooI2C.kext */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = VoodooI2C.kext; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\tAC2603B71F2F294000CF238F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = VoodooI2C/Info.plist; sourceTree = \"<group>\"; };\n\t\tAC2DC7311F7F0E5B0071CDCA /* VoodooI2CServices.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = VoodooI2CServices.xcodeproj; path = ../../Dependencies/VoodooI2CServices/VoodooI2CServices.xcodeproj; sourceTree = \"<group>\"; };\n\t\tAC49544F1F31E91D0040E11F /* VoodooI2CPCIController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CPCIController.cpp; path = VoodooI2CController/VoodooI2CPCIController.cpp; sourceTree = \"<group>\"; };\n\t\tAC4954501F31E91D0040E11F /* VoodooI2CPCIController.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CPCIController.hpp; path = VoodooI2CController/VoodooI2CPCIController.hpp; sourceTree = \"<group>\"; };\n\t\tAC6268921F2F6CF1000CBF2D /* VoodooI2CController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CController.cpp; path = VoodooI2CController/VoodooI2CController.cpp; sourceTree = \"<group>\"; };\n\t\tAC6268931F2F6CF1000CBF2D /* VoodooI2CController.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CController.hpp; path = VoodooI2CController/VoodooI2CController.hpp; sourceTree = \"<group>\"; };\n\t\tAC7400B81F3B6F1000937DD5 /* Introduction.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; name = Introduction.md; path = ../../Documentation/Introduction.md; sourceTree = \"<group>\"; };\n\t\tACD09F011F756B7800E9829A /* VoodooI2CMultitouchInterface.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CMultitouchInterface.cpp; path = \"../../Multitouch Support/VoodooI2CMultitouchInterface.cpp\"; sourceTree = \"<group>\"; };\n\t\tACD09F021F756B7800E9829A /* VoodooI2CMultitouchInterface.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CMultitouchInterface.hpp; path = \"../../Multitouch Support/VoodooI2CMultitouchInterface.hpp\"; sourceTree = \"<group>\"; };\n\t\tACD09F051F757B4900E9829A /* MultitouchHelpers.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = MultitouchHelpers.hpp; path = \"../../Multitouch Support/MultitouchHelpers.hpp\"; sourceTree = \"<group>\"; };\n\t\tACF6CF0F1F7587E5001CAAEE /* VoodooI2CMultitouchEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CMultitouchEngine.cpp; path = \"../../Multitouch Support/VoodooI2CMultitouchEngine.cpp\"; sourceTree = \"<group>\"; };\n\t\tACF6CF101F7587E5001CAAEE /* VoodooI2CMultitouchEngine.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CMultitouchEngine.hpp; path = \"../../Multitouch Support/VoodooI2CMultitouchEngine.hpp\"; sourceTree = \"<group>\"; };\n\t\tACF6E5851F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CCSGestureEngine.cpp; path = \"../../Multitouch Support/CSGesture/VoodooI2CCSGestureEngine.cpp\"; sourceTree = \"<group>\"; };\n\t\tACF6E5861F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CCSGestureEngine.hpp; path = \"../../Multitouch Support/CSGesture/VoodooI2CCSGestureEngine.hpp\"; sourceTree = \"<group>\"; };\n\t\tACF6E5891F759EA000A0CD61 /* csgesture-softc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = \"csgesture-softc.h\"; path = \"../../Multitouch Support/CSGesture/csgesture-softc.h\"; sourceTree = \"<group>\"; };\n\t\tACF6E58A1F759EA000A0CD61 /* csgesturescroll.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = csgesturescroll.cpp; path = \"../../Multitouch Support/CSGesture/csgesturescroll.cpp\"; sourceTree = \"<group>\"; };\n\t\tACF6E58B1F759EA000A0CD61 /* csgesturescroll.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = csgesturescroll.h; path = \"../../Multitouch Support/CSGesture/csgesturescroll.h\"; sourceTree = \"<group>\"; };\n\t\tACF6E58C1F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooCSGestureHIDWrapper.cpp; path = \"../../Multitouch Support/CSGesture/VoodooCSGestureHIDWrapper.cpp\"; sourceTree = \"<group>\"; };\n\t\tACF6E58D1F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = VoodooCSGestureHIDWrapper.h; path = \"../../Multitouch Support/CSGesture/VoodooCSGestureHIDWrapper.h\"; sourceTree = \"<group>\"; };\n\t\tACF6E58E1F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooCSGestureHIPointingWrapper.cpp; path = \"../../Multitouch Support/CSGesture/VoodooCSGestureHIPointingWrapper.cpp\"; sourceTree = \"<group>\"; };\n\t\tACF6E58F1F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooCSGestureHIPointingWrapper.hpp; path = \"../../Multitouch Support/CSGesture/VoodooCSGestureHIPointingWrapper.hpp\"; sourceTree = \"<group>\"; };\n\t\tACF810E61F3304720031A6F5 /* VoodooI2CControllerNub.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CControllerNub.cpp; path = VoodooI2CController/VoodooI2CControllerNub.cpp; sourceTree = \"<group>\"; };\n\t\tACF810E71F3304720031A6F5 /* VoodooI2CControllerNub.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CControllerNub.hpp; path = VoodooI2CController/VoodooI2CControllerNub.hpp; sourceTree = \"<group>\"; };\n\t\tACFCBA8E1F33644D00F9B59C /* VoodooI2CControllerDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CControllerDriver.cpp; path = VoodooI2CController/VoodooI2CControllerDriver.cpp; sourceTree = \"<group>\"; };\n\t\tACFCBA8F1F33644D00F9B59C /* VoodooI2CControllerDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CControllerDriver.hpp; path = VoodooI2CController/VoodooI2CControllerDriver.hpp; sourceTree = \"<group>\"; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\tAC2603AC1F2F294000CF238F /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t7B30D6981F91141300190488 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t7B30D69C1F91141300190488 /* VoodooI2CELAN.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t4E6786831FACB2B90000D307 /* UPDD */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t4E6786791FACB2A80000D307 /* VoodooI2CUPDDData.h */,\n\t\t\t\t4E67867A1FACB2A80000D307 /* VoodooI2CUPDDEngine.cpp */,\n\t\t\t\t4E67867B1FACB2A80000D307 /* VoodooI2CUPDDEngine.hpp */,\n\t\t\t\t4E67867C1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.cpp */,\n\t\t\t\t4E67867D1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.hpp */,\n\t\t\t);\n\t\t\tname = UPDD;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC0387531F54182100ECEDF9 /* VoodooI2C Satellites */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tACBE3FF01FEDF4FA0027F52E /* VoodooI2CUPDDEngine.xcodeproj */,\n\t\t\t\tAC0387541F5422FB00ECEDF9 /* VoodooI2CHID.xcodeproj */,\n\t\t\t\t7B30D6971F91141300190488 /* VoodooI2CELAN.xcodeproj */,\n\t\t\t);\n\t\t\tname = \"VoodooI2C Satellites\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC0387551F5422FB00ECEDF9 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC0387591F5422FB00ECEDF9 /* VoodooI2CHID.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC0955711F4ED49E0052E343 /* Dependencies */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC2DC7311F7F0E5B0071CDCA /* VoodooI2CServices.xcodeproj */,\n\t\t\t\tAC09558A1F4EE10C0052E343 /* VoodooGPIO.xcodeproj */,\n\t\t\t\tAC0955731F4ED4C50052E343 /* helpers.cpp */,\n\t\t\t\tAC0955741F4ED4C50052E343 /* helpers.hpp */,\n\t\t\t\tAC0955721F4ED4AA0052E343 /* VoodooI2CACPICRSParser */,\n\t\t\t);\n\t\t\tname = Dependencies;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tACBE3FF11FEDF4FA0027F52E /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tACBE3FF51FEDF4FA0027F52E /* VoodooI2CUPDDEngine.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC0955721F4ED4AA0052E343 /* VoodooI2CACPICRSParser */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC0955771F4ED4F60052E343 /* linuxirq.hpp */,\n\t\t\t\tAC0955781F4ED4F60052E343 /* VoodooI2CACPICRSParser.cpp */,\n\t\t\t\tAC0955791F4ED4F60052E343 /* VoodooI2CACPICRSParser.hpp */,\n\t\t\t);\n\t\t\tname = VoodooI2CACPICRSParser;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC09558B1F4EE10C0052E343 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC09558F1F4EE10C0052E343 /* VoodooGPIO.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC0AD4551F38425A0070A642 /* VoodooI2C Device */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC0AD4561F3842800070A642 /* VoodooI2CDeviceNub.cpp */,\n\t\t\t\tAC0AD4571F3842800070A642 /* VoodooI2CDeviceNub.hpp */,\n\t\t\t);\n\t\t\tname = \"VoodooI2C Device\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC0E75731F6998AB002268D0 /* Multitouch Support */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t4E6786831FACB2B90000D307 /* UPDD */,\n\t\t\t\tACF6E5841F759AFA00A0CD61 /* CSGesture */,\n\t\t\t\tAC0E75741F69997B002268D0 /* VoodooI2CDigitiserTransducer.cpp */,\n\t\t\t\tAC0E75751F69997B002268D0 /* VoodooI2CDigitiserTransducer.hpp */,\n\t\t\t\tAC0E75781F69ACEE002268D0 /* VoodooI2CDigitiserStylus.cpp */,\n\t\t\t\tAC0E75791F69ACEE002268D0 /* VoodooI2CDigitiserStylus.hpp */,\n\t\t\t\tACD09F011F756B7800E9829A /* VoodooI2CMultitouchInterface.cpp */,\n\t\t\t\tACD09F021F756B7800E9829A /* VoodooI2CMultitouchInterface.hpp */,\n\t\t\t\tACF6CF0F1F7587E5001CAAEE /* VoodooI2CMultitouchEngine.cpp */,\n\t\t\t\tACF6CF101F7587E5001CAAEE /* VoodooI2CMultitouchEngine.hpp */,\n\t\t\t\tACD09F051F757B4900E9829A /* MultitouchHelpers.hpp */,\n\t\t\t);\n\t\t\tname = \"Multitouch Support\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC2603A61F2F294000CF238F = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC2603B21F2F294000CF238F /* VoodooI2C */,\n\t\t\t\tAC2603B71F2F294000CF238F /* Info.plist */,\n\t\t\t\tAC2603B11F2F294000CF238F /* Products */,\n\t\t\t);\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC2603B11F2F294000CF238F /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC2603B01F2F294000CF238F /* VoodooI2C.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC2603B21F2F294000CF238F /* VoodooI2C */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC0E75731F6998AB002268D0 /* Multitouch Support */,\n\t\t\t\tAC0955711F4ED49E0052E343 /* Dependencies */,\n\t\t\t\tAC7400B71F3B6EB700937DD5 /* Documentation */,\n\t\t\t\tAC6268901F2F6CB9000CBF2D /* VoodooI2C Core */,\n\t\t\t\tAC0387531F54182100ECEDF9 /* VoodooI2C Satellites */,\n\t\t\t);\n\t\t\tpath = VoodooI2C;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC2DC7321F7F0E5B0071CDCA /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC2DC7361F7F0E5B0071CDCA /* VoodooI2CServices.kext */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC6268901F2F6CB9000CBF2D /* VoodooI2C Core */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC0AD4551F38425A0070A642 /* VoodooI2C Device */,\n\t\t\t\tAC6268911F2F6CDA000CBF2D /* VoodooI2C Controller */,\n\t\t\t);\n\t\t\tname = \"VoodooI2C Core\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC6268911F2F6CDA000CBF2D /* VoodooI2C Controller */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC6268921F2F6CF1000CBF2D /* VoodooI2CController.cpp */,\n\t\t\t\tAC6268931F2F6CF1000CBF2D /* VoodooI2CController.hpp */,\n\t\t\t\tAC49544F1F31E91D0040E11F /* VoodooI2CPCIController.cpp */,\n\t\t\t\tAC4954501F31E91D0040E11F /* VoodooI2CPCIController.hpp */,\n\t\t\t\tAC015C451F32345500516383 /* VoodooI2CACPIController.cpp */,\n\t\t\t\tAC015C461F32345500516383 /* VoodooI2CACPIController.hpp */,\n\t\t\t\tACF810E61F3304720031A6F5 /* VoodooI2CControllerNub.cpp */,\n\t\t\t\tACF810E71F3304720031A6F5 /* VoodooI2CControllerNub.hpp */,\n\t\t\t\tACFCBA8E1F33644D00F9B59C /* VoodooI2CControllerDriver.cpp */,\n\t\t\t\tACFCBA8F1F33644D00F9B59C /* VoodooI2CControllerDriver.hpp */,\n\t\t\t\tAC0A265A1F35F7FB00122252 /* VoodooI2CControllerConstants.hpp */,\n\t\t\t);\n\t\t\tname = \"VoodooI2C Controller\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tAC7400B71F3B6EB700937DD5 /* Documentation */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tAC7400B81F3B6F1000937DD5 /* Introduction.md */,\n\t\t\t);\n\t\t\tname = Documentation;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tACF6E5841F759AFA00A0CD61 /* CSGesture */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tACF6E5891F759EA000A0CD61 /* csgesture-softc.h */,\n\t\t\t\tACF6E58A1F759EA000A0CD61 /* csgesturescroll.cpp */,\n\t\t\t\tACF6E58B1F759EA000A0CD61 /* csgesturescroll.h */,\n\t\t\t\tACF6E58C1F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.cpp */,\n\t\t\t\tACF6E58D1F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.h */,\n\t\t\t\tACF6E58E1F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.cpp */,\n\t\t\t\tACF6E58F1F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.hpp */,\n\t\t\t\tACF6E5851F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.cpp */,\n\t\t\t\tACF6E5861F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.hpp */,\n\t\t\t);\n\t\t\tname = CSGesture;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXHeadersBuildPhase section */\n\t\tAC2603AD1F2F294000CF238F /* Headers */ = {\n\t\t\tisa = PBXHeadersBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\tAC0E75771F69997B002268D0 /* VoodooI2CDigitiserTransducer.hpp in Headers */,\n\t\t\t\tACF6E5961F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.hpp in Headers */,\n\t\t\t\tAC0E757B1F69ACEE002268D0 /* VoodooI2CDigitiserStylus.hpp in Headers */,\n\t\t\t\t4E67867E1FACB2A80000D307 /* VoodooI2CUPDDData.h in Headers */,\n\t\t\t\tACF6E5901F759EA000A0CD61 /* csgesture-softc.h in Headers */,\n\t\t\t\tACF810E91F3304720031A6F5 /* VoodooI2CControllerNub.hpp in Headers */,\n\t\t\t\tACFCBA911F33644D00F9B59C /* VoodooI2CControllerDriver.hpp in Headers */,\n\t\t\t\tAC4954521F31E91D0040E11F /* VoodooI2CPCIController.hpp in Headers */,\n\t\t\t\tACF6E5881F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.hpp in Headers */,\n\t\t\t\tAC0955761F4ED4C50052E343 /* helpers.hpp in Headers */,\n\t\t\t\tACD09F041F756B7800E9829A /* VoodooI2CMultitouchInterface.hpp in Headers */,\n\t\t\t\t4E6786821FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.hpp in Headers */,\n\t\t\t\tAC0AD4591F3842800070A642 /* VoodooI2CDeviceNub.hpp in Headers */,\n\t\t\t\tAC015C481F32345500516383 /* VoodooI2CACPIController.hpp in Headers */,\n\t\t\t\tACF6E5921F759EA000A0CD61 /* csgesturescroll.h in Headers */,\n\t\t\t\tACF6E5941F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.h in Headers */,\n\t\t\t\tAC09557A1F4ED4F60052E343 /* linuxirq.hpp in Headers */,\n\t\t\t\t4E6786801FACB2A80000D307 /* VoodooI2CUPDDEngine.hpp in Headers */,\n\t\t\t\tAC6268951F2F6CF1000CBF2D /* VoodooI2CController.hpp in Headers */,\n\t\t\t\tACF6CF121F7587E5001CAAEE /* VoodooI2CMultitouchEngine.hpp in Headers */,\n\t\t\t\tAC09557C1F4ED4F60052E343 /* VoodooI2CACPICRSParser.hpp in Headers */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXHeadersBuildPhase section */\n\n/* Begin PBXNativeTarget section */\n\t\tAC2603AF1F2F294000CF238F /* VoodooI2C */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = AC2603BA1F2F294000CF238F /* Build configuration list for PBXNativeTarget \"VoodooI2C\" */;\n\t\t\tbuildPhases = (\n\t\t\t\tAC2603AB1F2F294000CF238F /* Sources */,\n\t\t\t\tAC2603AC1F2F294000CF238F /* Frameworks */,\n\t\t\t\tAC2603AD1F2F294000CF238F /* Headers */,\n\t\t\t\tAC2603AE1F2F294000CF238F /* Resources */,\n\t\t\t\tAC4EEE2D1F3B2F1D00D0A6E0 /* Generate Documentation */,\n\t\t\t\tAC2603BF1F2F508700CF238F /* Linting */,\n\t\t\t\tAC0955921F4EE9B00052E343 /* Add GPIO and Services Plugin */,\n\t\t\t\tACC7F1451FEC9EA800200004 /* Output Version Number */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t\tAC2DC7381F7F0E670071CDCA /* PBXTargetDependency */,\n\t\t\t\t7B30D69E1F91166900190488 /* PBXTargetDependency */,\n\t\t\t\tACBE3FEE1FEDF49B0027F52E /* PBXTargetDependency */,\n\t\t\t\tACFB95CC1F54294F00867E18 /* PBXTargetDependency */,\n\t\t\t\tACBE3FF71FEDF4FE0027F52E /* PBXTargetDependency */,\n\t\t\t);\n\t\t\tname = VoodooI2C;\n\t\t\tproductName = VoodooI2C;\n\t\t\tproductReference = AC2603B01F2F294000CF238F /* VoodooI2C.kext */;\n\t\t\tproductType = \"com.apple.product-type.kernel-extension\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\tAC2603A71F2F294000CF238F /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tattributes = {\n\t\t\t\tLastUpgradeCheck = 0800;\n\t\t\t\tORGANIZATIONNAME = \"Alexandre Daoud\";\n\t\t\t\tTargetAttributes = {\n\t\t\t\t\tAC2603AF1F2F294000CF238F = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 8.0;\n\t\t\t\t\t\tProvisioningStyle = Automatic;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tbuildConfigurationList = AC2603AA1F2F294000CF238F /* Build configuration list for PBXProject \"VoodooI2C\" */;\n\t\t\tcompatibilityVersion = \"Xcode 3.2\";\n\t\t\tdevelopmentRegion = English;\n\t\t\thasScannedForEncodings = 0;\n\t\t\tknownRegions = (\n\t\t\t\ten,\n\t\t\t);\n\t\t\tmainGroup = AC2603A61F2F294000CF238F;\n\t\t\tproductRefGroup = AC2603B11F2F294000CF238F /* Products */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectReferences = (\n\t\t\t\t{\n\t\t\t\t\tProductGroup = AC09558B1F4EE10C0052E343 /* Products */;\n\t\t\t\t\tProjectRef = AC09558A1F4EE10C0052E343 /* VoodooGPIO.xcodeproj */;\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tProductGroup = 7B30D6981F91141300190488 /* Products */;\n\t\t\t\t\tProjectRef = 7B30D6971F91141300190488 /* VoodooI2CELAN.xcodeproj */;\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tProductGroup = AC0387551F5422FB00ECEDF9 /* Products */;\n\t\t\t\t\tProjectRef = AC0387541F5422FB00ECEDF9 /* VoodooI2CHID.xcodeproj */;\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tProductGroup = AC2DC7321F7F0E5B0071CDCA /* Products */;\n\t\t\t\t\tProjectRef = AC2DC7311F7F0E5B0071CDCA /* VoodooI2CServices.xcodeproj */;\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tProductGroup = ACBE3FF11FEDF4FA0027F52E /* Products */;\n\t\t\t\t\tProjectRef = ACBE3FF01FEDF4FA0027F52E /* VoodooI2CUPDDEngine.xcodeproj */;\n\t\t\t\t},\n\t\t\t);\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\tAC2603AF1F2F294000CF238F /* VoodooI2C */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXReferenceProxy section */\n\t\t7B30D69C1F91141300190488 /* VoodooI2CELAN.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooI2CELAN.kext;\n\t\t\tremoteRef = 7B30D69B1F91141300190488 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\tACBE3FF51FEDF4FA0027F52E /* VoodooI2CUPDDEngine.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooI2CUPDDEngine.kext;\n\t\t\tremoteRef = ACBE3FF41FEDF4FA0027F52E /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\tAC0387591F5422FB00ECEDF9 /* VoodooI2CHID.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooI2CHID.kext;\n\t\t\tremoteRef = AC0387581F5422FB00ECEDF9 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\tAC09558F1F4EE10C0052E343 /* VoodooGPIO.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooGPIO.kext;\n\t\t\tremoteRef = AC09558E1F4EE10C0052E343 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\tAC2DC7361F7F0E5B0071CDCA /* VoodooI2CServices.kext */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.cfbundle;\n\t\t\tpath = VoodooI2CServices.kext;\n\t\t\tremoteRef = AC2DC7351F7F0E5B0071CDCA /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n/* End PBXReferenceProxy section */\n\n/* Begin PBXResourcesBuildPhase section */\n\t\tAC2603AE1F2F294000CF238F /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXResourcesBuildPhase section */\n\n/* Begin PBXShellScriptBuildPhase section */\n\t\tACC7F1451FEC9EA800200004 /* Output Version Number */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t);\n\t\t\tname = \"Output Version Number\";\n\t\t\toutputPaths = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"> ../version.txt\\necho \\\"v${CURRENT_PROJECT_VERSION}\\\" > ../version.txt\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n\t\tAC0955921F4EE9B00052E343 /* Add GPIO and Services Plugin */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t);\n\t\t\tname = \"Add GPIO and Services Plugin\";\n\t\t\toutputPaths = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"mkdir -p ${BUILT_PRODUCTS_DIR}/VoodooI2C.kext/Contents/PlugIns\\nrm -rf ${BUILT_PRODUCTS_DIR}/VoodooI2C.kext/Contents/PlugIns/VoodooGPIO.kext\\nmv ${BUILT_PRODUCTS_DIR}/VoodooGPIO.kext ${BUILT_PRODUCTS_DIR}/VoodooI2C.kext/Contents/PlugIns\\n\\nrm -rf ${BUILT_PRODUCTS_DIR}/VoodooI2C.kext/Contents/PlugIns/VoodooI2CServices.kext\\nmv ${BUILT_PRODUCTS_DIR}/VoodooI2CServices.kext ${BUILT_PRODUCTS_DIR}/VoodooI2C.kext/Contents/PlugIns\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n\t\tAC2603BF1F2F508700CF238F /* Linting */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t);\n\t\t\tname = Linting;\n\t\t\toutputPaths = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"cpplint --recursive --filter=-build/header_guard,-whitespace/line_length,-runtime/int ./\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n\t\tAC4EEE2D1F3B2F1D00D0A6E0 /* Generate Documentation */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t);\n\t\t\tname = \"Generate Documentation\";\n\t\t\toutputPaths = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"pwd; find .*/VoodooI2C .*/Dependencies .*/Multitouch\\\\ Support .*/VoodooI2C\\\\ Satellites -name \\\"*.hpp\\\" -print0 | xargs -0 cldoc generate -I. -x c++ -arch x86_64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -nostdinc -std=gnu++11 -stdlib=libc++ -fmodules -gmodules -fmodules-cache-path=${MODULE_CACHE_DIR} -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fbuild-session-file=${MODULE_CACHE_DIR}/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -fno-builtin -Wno-trigraphs -fno-exceptions -fno-rtti -msoft-float -O0 -fno-common -mkernel -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wunreachable-code -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wno-inconsistent-missing-override -Wunused-variable -Wunused-value -Wempty-body -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wno-newline-eof -Wno-c++11-extensions -DDEBUG=1 -DKERNEL -DKERNEL_PRIVATE -DDRIVER_PRIVATE -DAPPLE -DNeXT -fapple-kext -fasm-blocks -fstrict-aliasing -Wdeprecated-declarations -Winvalid-offsetof -mmacosx-version-min=10.10 -g -Wno-sign-conversion -Winfinite-recursion -Wno-move -I${SDK_ROOT}/System/Library/Frameworks/Kernel.framework/PrivateHeaders -I${SDK_ROOT}/System/Library/Frameworks/Kernel.framework/Headers -I${DERIVED_SOURCES_DIR}/x86_64 -I${DERIVED_SOURCES_DIR} -I\\\"../Dependencies/Headers\\\" -Wno-inconsistent-missing-override -Wno-unused-variable -- --output ../docs --report --merge \\\"../Documentation\\\" --basedir .\";\n\t\t};\n/* End PBXShellScriptBuildPhase section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\tAC2603AB1F2F294000CF238F /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\tAC0E757A1F69ACEE002268D0 /* VoodooI2CDigitiserStylus.cpp in Sources */,\n\t\t\t\tAC0E75761F69997B002268D0 /* VoodooI2CDigitiserTransducer.cpp in Sources */,\n\t\t\t\tAC7400B91F3B6F1000937DD5 /* Introduction.md in Sources */,\n\t\t\t\tAC0AD4581F3842800070A642 /* VoodooI2CDeviceNub.cpp in Sources */,\n\t\t\t\tACF6E5911F759EA000A0CD61 /* csgesturescroll.cpp in Sources */,\n\t\t\t\t4E67867F1FACB2A80000D307 /* VoodooI2CUPDDEngine.cpp in Sources */,\n\t\t\t\tACF810E81F3304720031A6F5 /* VoodooI2CControllerNub.cpp in Sources */,\n\t\t\t\tAC6268941F2F6CF1000CBF2D /* VoodooI2CController.cpp in Sources */,\n\t\t\t\tAC09557B1F4ED4F60052E343 /* VoodooI2CACPICRSParser.cpp in Sources */,\n\t\t\t\tAC015C471F32345500516383 /* VoodooI2CACPIController.cpp in Sources */,\n\t\t\t\tACF6E5871F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.cpp in Sources */,\n\t\t\t\tACF6CF111F7587E5001CAAEE /* VoodooI2CMultitouchEngine.cpp in Sources */,\n\t\t\t\tACD09F031F756B7800E9829A /* VoodooI2CMultitouchInterface.cpp in Sources */,\n\t\t\t\t4E6786811FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.cpp in Sources */,\n\t\t\t\tACFCBA901F33644D00F9B59C /* VoodooI2CControllerDriver.cpp in Sources */,\n\t\t\t\tAC4954511F31E91D0040E11F /* VoodooI2CPCIController.cpp in Sources */,\n\t\t\t\tAC0955751F4ED4C50052E343 /* helpers.cpp in Sources */,\n\t\t\t\tACF6E5931F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.cpp in Sources */,\n\t\t\t\tACF6E5951F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin PBXTargetDependency section */\n\t\t7B30D69E1F91166900190488 /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = VoodooI2CELAN;\n\t\t\ttargetProxy = 7B30D69D1F91166900190488 /* PBXContainerItemProxy */;\n\t\t};\n\t\tACBE3FEE1FEDF49B0027F52E /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = VoodooGPIO;\n\t\t\ttargetProxy = ACBE3FED1FEDF49B0027F52E /* PBXContainerItemProxy */;\n\t\t};\n\t\tACBE3FF71FEDF4FE0027F52E /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = VoodooI2CUPDDEngine;\n\t\t\ttargetProxy = ACBE3FF61FEDF4FE0027F52E /* PBXContainerItemProxy */;\n\t\t};\n\t\tAC2DC7381F7F0E670071CDCA /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = VoodooI2CServices;\n\t\t\ttargetProxy = AC2DC7371F7F0E670071CDCA /* PBXContainerItemProxy */;\n\t\t};\n\t\tACFB95CC1F54294F00867E18 /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\tname = VoodooI2CHID;\n\t\t\ttargetProxy = ACFB95CB1F54294F00867E18 /* PBXContainerItemProxy */;\n\t\t};\n/* End PBXTargetDependency section */\n\n/* Begin XCBuildConfiguration section */\n\t\tAC2603B81F2F294000CF238F /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++0x\";\n\t\t\t\tCLANG_CXX_LIBRARY = \"libc++\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = YES;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tENABLE_TESTABILITY = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.11;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = YES;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\tAC2603B91F2F294000CF238F /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++0x\";\n\t\t\t\tCLANG_CXX_LIBRARY = \"libc++\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = YES;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";\n\t\t\t\tENABLE_NS_ASSERTIONS = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.11;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\tAC2603BB1F2F294000CF238F /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = YES;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = NO;\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tCURRENT_PROJECT_VERSION = 2.0.0;\n\t\t\t\t\"HEADER_SEARCH_PATHS[arch=*]\" = \"\\\"../Dependencies/Headers\\\"/**\";\n\t\t\t\tINFOPLIST_FILE = VoodooI2C/Info.plist;\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.11;\n\t\t\t\tMODULE_NAME = com.alexandred.VoodooI2C;\n\t\t\t\tMODULE_VERSION = 2.0.0;\n\t\t\t\t\"OTHER_CPLUSPLUSFLAGS[arch=*]\" = \"-Wno-inconsistent-missing-override\";\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.alexandred.VoodooI2C;\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tWRAPPER_EXTENSION = kext;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\tAC2603BC1F2F294000CF238F /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = YES;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = NO;\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tCURRENT_PROJECT_VERSION = 2.0.0;\n\t\t\t\t\"HEADER_SEARCH_PATHS[arch=*]\" = \"\\\"../Dependencies/Headers\\\"/**\";\n\t\t\t\tINFOPLIST_FILE = VoodooI2C/Info.plist;\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.11;\n\t\t\t\tMODULE_NAME = com.alexandred.VoodooI2C;\n\t\t\t\tMODULE_VERSION = 2.0.0;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\t\"OTHER_CPLUSPLUSFLAGS[arch=*]\" = \"-Wno-inconsistent-missing-override\";\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.alexandred.VoodooI2C;\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tWRAPPER_EXTENSION = kext;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\tAC2603AA1F2F294000CF238F /* Build configuration list for PBXProject \"VoodooI2C\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\tAC2603B81F2F294000CF238F /* Debug */,\n\t\t\t\tAC2603B91F2F294000CF238F /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\tAC2603BA1F2F294000CF238F /* Build configuration list for PBXNativeTarget \"VoodooI2C\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\tAC2603BB1F2F294000CF238F /* Debug */,\n\t\t\t\tAC2603BC1F2F294000CF238F /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = AC2603A71F2F294000CF238F /* Project object */;\n}\n"
  },
  {
    "path": "BigSurface/BigSurface.xcodeproj/project.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "BigSurface/BigSurface.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "BigSurface/BigSurface.xcodeproj/xcshareddata/xcschemes/BigSurface.xcscheme",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n   LastUpgradeVersion = \"1420\"\n   version = \"1.3\">\n   <BuildAction\n      parallelizeBuildables = \"YES\"\n      buildImplicitDependencies = \"YES\">\n      <BuildActionEntries>\n         <BuildActionEntry\n            buildForTesting = \"YES\"\n            buildForRunning = \"YES\"\n            buildForProfiling = \"YES\"\n            buildForArchiving = \"YES\"\n            buildForAnalyzing = \"YES\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"25B97D6F260B950E00657C76\"\n               BuildableName = \"BigSurface.kext\"\n               BlueprintName = \"BigSurface\"\n               ReferencedContainer = \"container:BigSurface.xcodeproj\">\n            </BuildableReference>\n         </BuildActionEntry>\n      </BuildActionEntries>\n   </BuildAction>\n   <TestAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\">\n      <Testables>\n      </Testables>\n   </TestAction>\n   <LaunchAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      launchStyle = \"0\"\n      useCustomWorkingDirectory = \"NO\"\n      ignoresPersistentStateOnLaunch = \"NO\"\n      debugDocumentVersioning = \"YES\"\n      debugServiceExtension = \"internal\"\n      allowLocationSimulation = \"YES\">\n   </LaunchAction>\n   <ProfileAction\n      buildConfiguration = \"Release\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\"\n      savedToolIdentifier = \"\"\n      useCustomWorkingDirectory = \"NO\"\n      debugDocumentVersioning = \"YES\">\n      <MacroExpansion>\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"25B97D6F260B950E00657C76\"\n            BuildableName = \"BigSurface.kext\"\n            BlueprintName = \"BigSurface\"\n            ReferencedContainer = \"container:BigSurface.xcodeproj\">\n         </BuildableReference>\n      </MacroExpansion>\n   </ProfileAction>\n   <AnalyzeAction\n      buildConfiguration = \"Debug\">\n   </AnalyzeAction>\n   <ArchiveAction\n      buildConfiguration = \"Release\"\n      revealArchiveInOrganizer = \"YES\">\n   </ArchiveAction>\n</Scheme>\n"
  },
  {
    "path": "BigSurface.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"group:BigSurface/BigSurface.xcodeproj\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "BigSurface.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "BigSurface.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict/>\n</plist>\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "AL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n"
  },
  {
    "path": "README.md",
    "content": "# BigSurface\nThe name comes from macOS Big Sur.\nBig Sur + Surface -> Big Surface (LOL)\n\nPS : If you have a better name, please let me know.\n\n**A proposition for a fully intergrated kext for all Surface related hardwares**\n\n## How to install\n\nYou will need to first **DELETE** all the original **VoodooI2C** kexts including its plugins (all of them), **SMCBatteryManager.kext**, **SMCLightSensor.kext** and **SSDT_ALS0.aml**, then add BigSurface and SSDT-SURFACE.aml into opencore's `config.plist` in the order specified as below<img width=\"897\" alt=\"截屏2023-02-09 23 22 47\" src=\"https://user-images.githubusercontent.com/18528518/217953005-a00e42ff-39c5-44f8-90e9-4e8efba6b1ea.png\">\n\n\n## Which Surface series are supported ?\nCheck your UART device id in Windows, currently device id `34a8` is supported perfectly, `9d27` still needs some ameliorations but usable\n- Surface Pro 7 & Laptop 3 & Book 3 & Laptop Go 1     -> 34a8\n- Surface Pro 4, 5, 6 & Book 2 & Laptop 1, 2    -> 9d27\n\nSee my sub-repo `VoodooSerial` for details\n\n## What works\n- Surface Type Cover\n  > The code is based on VoodooI2CHID.kext, but added **integrated and hot pluggable touchpad&keyboard support**.\n- Buttons\n  > Power/VolumeUp/VolumeDown buttons all works properly\n- Ambient Light Sensor\n  > ACPI device name: ACSD, attached under I2C4. **ONLY SP7 and SL3 devices use this hardware** for other devices, you need to write your own driver and then make a pull request. I am happy to merge your driver in :)\n- Battery status--Surface Serial Hub\n  > UART driver as well as MS's SAM module driver are implemented. \n  > **TODO**: support dual batteries for SB3.\n- Performance mode\n  > Right now it is set by `PerformanceMode` in `SurfaceBattery` (default 0x01), changing it to other values is not observed to have any effects. If you find any difference (fan speed or battery life), please let me know\n  > \n  > Right now it can only be set by changing the plist or using `ioio`\n  > We need a userspace software to control it if it actually has something useful.\n- Surface Laptop3's keyboard & touchpad\n  > Works now, all keys and gestures are recognised properly.\n  > \n  > Known issue: neither keyboard nor touchpad can wake up the system.\n- Touch Screen & Stylus Yes, this also works :)\n  > The code is ported from linux, including `mei` and surface-linux's `ipts` & `iptsd` drivers.\n  > \n  > 10 finger touch & stylus\n  > \n  > **Important**: need a SSDT patch (SSDT-SURFACE) and a user-space daemon ([IPTSDaemon](https://github.com/Xiashangning/IPTSDaemon)) to work with.\n  \nPossible values for Performance mode are:\n\n      State              Value\n      \n    Recommended          0x01\n    \n    Battery Saver        0x02 (Only in battery mode)\n    \n    Better Performance   0x03\n    \n    Best Performance     0x04\n    \n## TODO\n- Cameras                            Impossible so far\n  > ACPI devices: CAMR,CAMF,CAM3(infrared camera)\n  > \n  > Corresponding device id: OV8865,OV5693,OV7251\n  > \n  > Even Linux failed to drive the cameras on SP7 (IPU4), SP6 and before (IPU3) might be possible but I do not have the device.\n\n## Important\nSurface Pro 7 and Book 3 seem to have issues for macOS to recognize properly the battery in System Preferences. PM Profile in FACP is tablet not laptop.\n\nThus, an ACPI patch is needed:\n\n```\nTable Signature: 46414350\nFind: 00080900 B2000000 F0F1\nReplace: 00020900 B2000000 F0F1\n```\n\nThanks to @he1833\n\n## If you like my project, please consider to star this project, thanks!\n### If you appreciate my effort and would like to pay me a coffee, here is my PayPal address: `ritchiexia@163.com`\n"
  }
]