Repository: Xiashangning/BigSurface
Branch: dev
Commit: 82826312a429
Files: 49
Total size: 418.3 KB
Directory structure:
gitextract_u84mydzx/
├── .gitignore
├── .gitmodules
├── BigSurface/
│ ├── BigSurface/
│ │ ├── Info.plist
│ │ ├── SurfaceAmbientLightSensor/
│ │ │ ├── APDS9960Constants.h
│ │ │ ├── AmbientLightValue.cpp
│ │ │ ├── AmbientLightValue.hpp
│ │ │ ├── SurfaceAmbientLightSensorDriver.cpp
│ │ │ └── SurfaceAmbientLightSensorDriver.hpp
│ │ ├── SurfaceBattery/
│ │ │ ├── BatteryManager.cpp
│ │ │ ├── BatteryManager.hpp
│ │ │ ├── BatteryManagerState.hpp
│ │ │ ├── KeyImplementations.cpp
│ │ │ ├── KeyImplementations.hpp
│ │ │ ├── SurfaceACAdapter.cpp
│ │ │ ├── SurfaceACAdapter.hpp
│ │ │ ├── SurfaceBattery.cpp
│ │ │ ├── SurfaceBattery.hpp
│ │ │ ├── SurfaceBatteryDriver.cpp
│ │ │ ├── SurfaceBatteryDriver.hpp
│ │ │ ├── SurfaceSMBusController.cpp
│ │ │ └── SurfaceSMBusController.hpp
│ │ ├── SurfaceButton/
│ │ │ ├── HIDReport.hpp
│ │ │ ├── SurfaceButtonDevice.cpp
│ │ │ ├── SurfaceButtonDevice.hpp
│ │ │ ├── SurfaceButtonDriver.cpp
│ │ │ └── SurfaceButtonDriver.hpp
│ │ ├── SurfaceManagementEngine/
│ │ │ ├── MEIProtocol.h
│ │ │ ├── SurfaceManagementEngineClient.cpp
│ │ │ ├── SurfaceManagementEngineClient.hpp
│ │ │ ├── SurfaceManagementEngineDriver.cpp
│ │ │ └── SurfaceManagementEngineDriver.hpp
│ │ ├── SurfaceSerialHub/
│ │ │ ├── SerialProtocol.h
│ │ │ ├── SurfaceSerialHubDriver.cpp
│ │ │ └── SurfaceSerialHubDriver.hpp
│ │ ├── SurfaceSerialHubDevices/
│ │ │ ├── SurfaceBatteryNub.cpp
│ │ │ ├── SurfaceBatteryNub.hpp
│ │ │ ├── SurfaceHIDNub.cpp
│ │ │ └── SurfaceHIDNub.hpp
│ │ └── helpers.hpp
│ └── BigSurface.xcodeproj/
│ ├── project.pbxproj
│ ├── project.pbxproj.orig
│ ├── project.xcworkspace/
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata/
│ │ └── IDEWorkspaceChecks.plist
│ └── xcshareddata/
│ └── xcschemes/
│ └── BigSurface.xcscheme
├── BigSurface.xcworkspace/
│ ├── contents.xcworkspacedata
│ └── xcshareddata/
│ ├── IDEWorkspaceChecks.plist
│ └── WorkspaceSettings.xcsettings
├── LICENSE.txt
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
Build/
DerivedData/
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/
## Other
*.moved-aside
*.xccheckout
*.xcscmblueprint
.DS_Store
Dependencies/*.kext
================================================
FILE: .gitmodules
================================================
[submodule "MacKernelSDK"]
path = MacKernelSDK
url = https://github.com/acidanthera/MacKernelSDK
[submodule "Dependencies/VoodooGPIO"]
path = Dependencies/VoodooGPIO
url = https://github.com/Xiashangning/VoodooGPIO.git
[submodule "Dependencies/VoodooSerial"]
path = Dependencies/VoodooSerial
url = https://github.com/Xiashangning/VoodooSerial.git
[submodule "Dependencies/VoodooInput"]
path = Dependencies/VoodooInput
url = https://github.com/Xiashangning/VoodooInput.git
[submodule "Dependencies/BigSurfaceHIDDriver"]
path = Dependencies/BigSurfaceHIDDriver
url = https://github.com/Xiashangning/BigSurfaceHIDDriver.git
================================================
FILE: BigSurface/BigSurface/Info.plist
================================================
CFBundleDevelopmentRegion
$(DEVELOPMENT_LANGUAGE)
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
$(PRODUCT_BUNDLE_PACKAGE_TYPE)
CFBundleShortVersionString
$(MARKETING_VERSION)
CFBundleVersion
$(CURRENT_PROJECT_VERSION)
IOKitPersonalities
Surface Ambient Light Sensor
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
IOClass
SurfaceAmbientLightSensorDriver
IOProbeScore
400
IOPropertyMatch
name
MSHW0184
IOProviderClass
VoodooI2CDeviceNub
Surface Battery
BatteryCount
1
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
IOClass
SurfaceBatteryDriver
IOProviderClass
SurfaceBatteryNub
PerformanceMode
1
Surface Battery SMBus Controller
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
IOClass
SurfaceSMBusController
IOProviderClass
SurfaceBatteryDriver
Surface Button
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
IOClass
SurfaceButtonDriver
IONameMatch
MSHW0040
IOProbeScore
400
IOProviderClass
IOACPIPlatformDevice
Surface Management Engine
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
IOClass
SurfaceManagementEngineDriver
IOPCIMatch
0x34e48086 0x9d3e8086
IOProbeScore
400
IOProviderClass
IOPCIDevice
Surface Serial Hub
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
IOClass
SurfaceSerialHubDriver
IONameMatch
MSHW0084
IOProbeScore
600
IOProviderClass
IOACPIPlatformDevice
NSHumanReadableCopyright
Copyright © 2021 Xia Shangning. All rights reserved.
OSBundleCompatibleVersion
1.0.0
OSBundleLibraries
as.vit9696.Lilu
1.2.0
as.vit9696.VirtualSMC
1.2.0
com.apple.iokit.IOACPIFamily
1.4
com.apple.iokit.IOHIDFamily
2.0
com.apple.iokit.IOPCIFamily
2.9
com.apple.iokit.IOSMBusFamily
1.0.0
com.apple.kpi.bsd
16.7
com.apple.kpi.iokit
16.7
com.apple.kpi.libkern
16.7
com.apple.kpi.mach
16.7
com.xavier.VoodooSerial
1.2
org.coolstar.VoodooGPIO
1.2
OSBundleRequired
Root
================================================
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/APDS9960Constants.h
================================================
//
// APDS9960Constants.h
// SurfaceAmbientLightSensor
//
// Created by Xavier on 2021/10/27.
// Copyright © 2021 Xia Shangning. All rights reserved.
//
#ifndef APDS9960Constants_h
#define APDS9960Constants_h
enum {
GESTURE_NONE = -1,
GESTURE_UP = 0,
GESTURE_DOWN = 1,
GESTURE_LEFT = 2,
GESTURE_RIGHT = 3
};
/* APDS-9960 register addresses */
#define APDS9960_ENABLE 0x80
#define APDS9960_ATIME 0x81
#define APDS9960_WTIME 0x83
#define APDS9960_AILTL 0x84
#define APDS9960_AILTH 0x85
#define APDS9960_AIHTL 0x86
#define APDS9960_AIHTH 0x87
#define APDS9960_PILT 0x89
#define APDS9960_PIHT 0x8B
#define APDS9960_PERS 0x8C
#define APDS9960_CONFIG1 0x8D
#define APDS9960_PPULSE 0x8E
#define APDS9960_CONTROL 0x8F
#define APDS9960_CONFIG2 0x90
#define APDS9960_ID 0x92
#define APDS9960_STATUS 0x93
#define APDS9960_CDATAL 0x94
#define APDS9960_CDATAH 0x95
#define APDS9960_RDATAL 0x96
#define APDS9960_RDATAH 0x97
#define APDS9960_GDATAL 0x98
#define APDS9960_GDATAH 0x99
#define APDS9960_BDATAL 0x9A
#define APDS9960_BDATAH 0x9B
#define APDS9960_PDATA 0x9C
#define APDS9960_POFFSET_UR 0x9D
#define APDS9960_POFFSET_DL 0x9E
#define APDS9960_CONFIG3 0x9F
#define APDS9960_GPENTH 0xA0
#define APDS9960_GEXTH 0xA1
#define APDS9960_GCONF1 0xA2
#define APDS9960_GCONF2 0xA3
#define APDS9960_GOFFSET_U 0xA4
#define APDS9960_GOFFSET_D 0xA5
#define APDS9960_GOFFSET_L 0xA7
#define APDS9960_GOFFSET_R 0xA9
#define APDS9960_GPULSE 0xA6
#define APDS9960_GCONF3 0xAA
#define APDS9960_GCONF4 0xAB
#define APDS9960_GFLVL 0xAE
#define APDS9960_GSTATUS 0xAF
#define APDS9960_IFORCE 0xE4
#define APDS9960_PICLEAR 0xE5
#define APDS9960_CICLEAR 0xE6
#define APDS9960_AICLEAR 0xE7
#define APDS9960_GFIFO_U 0xFC
#define APDS9960_GFIFO_D 0xFD
#define APDS9960_GFIFO_L 0xFE
#define APDS9960_GFIFO_R 0xFF
/* Gesture parameters */
#define GESTURE_THRESHOLD_OUT 10
#define GESTURE_SENSITIVITY_1 50
#define GESTURE_SENSITIVITY_2 20
#define GESTURE_VALID 0x01
/* Misc parameters */
#define FIFO_PAUSE_TIME 30 /* Wait period (ms) between FIFO reads */
/* Bit fields */
#define ENABLE_POWER 0x01
#define ENABLE_ALS 0x02
#define ENABLE_PROXIMITY 0x04
#define ENABLE_WAIT 0x08
#define ENABLE_ALS_INT 0x10
#define ENABLE_PROXIMITY_INT 0x20
#define ENABLE_GESTURE 0x40
/* Status register */
#define STA_ALS_SAT 0x80
#define STA_PROXI_OR_GESTURE_SAT 0x40
#define STA_TRIG_PROXIMITY_INT 0x20
#define STA_TRIG_ALS_INT 0x10
#define STA_GESTURE_INT 0x04
#define STA_PROXIMITY_VALID 0x02
#define STA_ALS_VALID 0x01
#define TIME_TO_VALUE(ms) (256 - (ms / 2.78))
#define CONFIG1_DEFAULT 0x60
/* LED Drive values */
#define LED_DRIVE_100MA 0
#define LED_DRIVE_50MA 1
#define LED_DRIVE_25MA 2
#define LED_DRIVE_12_5MA 3
/* Proximity Gain (PGAIN) values */
#define PGAIN_1X 0
#define PGAIN_2X 1
#define PGAIN_4X 2
#define PGAIN_8X 3
/* ALS Gain (AGAIN) values */
#define ALS_GAIN_1X 0
#define ALS_GAIN_4X 1
#define ALS_GAIN_16X 2
#define ALS_GAIN_64X 3
/* Gesture Gain (GGAIN) values */
#define GGAIN_1X 0
#define GGAIN_2X 1
#define GGAIN_4X 2
#define GGAIN_8X 3
/* LED Boost values */
#define LED_BOOST_100 0
#define LED_BOOST_150 1
#define LED_BOOST_200 2
#define LED_BOOST_300 3
/* Gesture wait time values */
#define GWTIME_0MS 0
#define GWTIME_2_8MS 1
#define GWTIME_5_6MS 2
#define GWTIME_8_4MS 3
#define GWTIME_14_0MS 4
#define GWTIME_22_4MS 5
#define GWTIME_30_8MS 6
#define GWTIME_39_2MS 7
#endif /* APDS9960Constants_h */
================================================
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/AmbientLightValue.cpp
================================================
//
// AmbientLightValue.cpp
// SMCLightSensor
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#include "AmbientLightValue.hpp"
SMC_RESULT SMCAmbientLightValue::readAccess() {
auto value = reinterpret_cast(data);
UInt32 lux = atomic_load_explicit(currentLux, memory_order_acquire);
UInt8 bits = forceBits->bits();
if (lux == 0xFFFFFFFF) {
value->valid = false;
} else {
value->valid = true;
if (!(bits & ALSForceBits::kALSForceHighGain))
value->highGain = true;
if (!(bits & ALSForceBits::kALSForceChan))
value->chan0 = OSSwapHostToBigInt16(lux);
if (!(bits & ALSForceBits::kALSForceLux))
value->roomLux = OSSwapHostToBigInt32(lux << 14);
}
return SmcSuccess;
}
================================================
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/AmbientLightValue.hpp
================================================
//
// AmbientLightValue.hpp
// SMCLightSensor
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#ifndef AmbientLightValue_hpp
#define AmbientLightValue_hpp
#include
#include
class ALSForceBits : public VirtualSMCValue {
public:
/**
* Each "1" bit in gui8ALSForced indicates that a certain writable ALS
* variable has been overridden (i.e., forced) by the host OS or
* host diagnostics, and that variable should not be written by the SMC
* again until the applicable bit is cleared in gui8ALSForced.
* Currently, the used bits are:
* Bit 0 protects gui16ALSScale
* Bit 1 protects ui16Chan0 and ui16Chan1 of aalsvALSData
* Bit 2 protects gui16ALSLux
* Bit 3 protects fHighGain of aalsvALSData
* Bit 4 protects gai16ALSTemp[MAX_ALS_SENSORS]
* All other bits are reserved and should be cleared to 0.
*/
enum {
kALSForceScale = 1,
kALSForceChan = 2,
kALSForceLux = 4,
kALSForceHighGain = 8,
kALSForceTemp = 16
};
UInt8 bits() { return data[0]; }
};
class SMCAmbientLightValue : public VirtualSMCValue {
_Atomic(UInt32) *currentLux;
ALSForceBits *forceBits;
protected:
SMC_RESULT readAccess() override;
public:
/**
* Contains latest ambient light info from 1 sensor
*/
struct PACKED Value {
/**
* If TRUE, data in this struct is valid.
*/
bool valid {false};
/**
* If TRUE, ui16Chan0/1 are high-gain readings.
* If FALSE, ui16Chan0/1 are low-gain readings.
*/
bool highGain {true};
/**
* I2C channel 0 data or analog(ADC) data.
*/
UInt16 chan0 {0};
/**
* I2C channel 1 data.
*/
UInt16 chan1 {0};
/**
* The following field only exists on systems that send ALS change notifications to the OS:
* Room illumination in lux, FP18.14.
*/
UInt32 roomLux {0};
};
SMCAmbientLightValue(_Atomic(UInt32) *currentLux, ALSForceBits *forceBits) :
currentLux(currentLux), forceBits(forceBits) {}
};
#endif /* AmbientLightValue_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/SurfaceAmbientLightSensorDriver.cpp
================================================
//
// SurfaceAmbientLightSensorDriver.cpp
// SurfaceAmbientLightSensor
//
// Created by Xia on 2021/10/27.
// Copyright © 2021 Xia Shangning. All rights reserved.
//
#include
#include "SurfaceAmbientLightSensorDriver.hpp"
#define super IOService
OSDefineMetaClassAndStructors(SurfaceAmbientLightSensorDriver, IOService);
IOService* SurfaceAmbientLightSensorDriver::probe(IOService *provider, SInt32 *score) {
if (!super::probe(provider, score))
return nullptr;
api = OSDynamicCast(VoodooI2CDeviceNub, provider);
if (!api)
return nullptr;
OSDictionary *dict = nameMatching("ACPI0008");
IOService *matched = waitForMatchingService(dict, 1000000000);
alsd_device = OSDynamicCast(IOACPIPlatformDevice, matched);
OSSafeReleaseNULL(dict);
OSSafeReleaseNULL(matched);
if (!alsd_device) {
LOG("Ambient Light Sensor ACPI device not found");
return nullptr;
}
ALSSensor sensor {ALSSensor::Type::Unknown7, true, 6, false};
ALSSensor noSensor {ALSSensor::Type::NoSensor, false, 0, false};
SMCAmbientLightValue::Value emptyValue;
VirtualSMCAPI::addKey(KeyAL, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(0, &forceBits, SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE));
VirtualSMCAPI::addKey(KeyALI0, vsmcPlugin.data, VirtualSMCAPI::valueWithData(
reinterpret_cast(&sensor), sizeof(sensor), SmcKeyTypeAli, nullptr, SMC_KEY_ATTRIBUTE_CONST | SMC_KEY_ATTRIBUTE_READ));
VirtualSMCAPI::addKey(KeyALI1, vsmcPlugin.data, VirtualSMCAPI::valueWithData(
reinterpret_cast(&noSensor), sizeof(noSensor), SmcKeyTypeAli, nullptr, SMC_KEY_ATTRIBUTE_CONST | SMC_KEY_ATTRIBUTE_READ));
VirtualSMCAPI::addKey(KeyALRV, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(1, nullptr, SMC_KEY_ATTRIBUTE_CONST | SMC_KEY_ATTRIBUTE_READ));
VirtualSMCAPI::addKey(KeyALV0, vsmcPlugin.data, VirtualSMCAPI::valueWithData(
reinterpret_cast(&emptyValue), sizeof(emptyValue), SmcKeyTypeAlv, new SMCAmbientLightValue(¤t_lux, &forceBits),
SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE));
VirtualSMCAPI::addKey(KeyALV1, vsmcPlugin.data, VirtualSMCAPI::valueWithData(
reinterpret_cast(&emptyValue), sizeof(emptyValue), SmcKeyTypeAlv, nullptr,
SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE));
VirtualSMCAPI::addKey(KeyMSLD, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(0));
LOG("Surface Ambient Light Sensor device found!");
return this;
}
bool SurfaceAmbientLightSensorDriver::start(IOService *provider) {
if (!super::start(provider))
return false;
work_loop = getWorkLoop();
if (!work_loop) {
LOG("Could not get a IOWorkLoop instance");
return false;
}
work_loop->retain();
poller = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceAmbientLightSensorDriver::pollALI));
if (!poller) {
LOG("Could not create timer event source");
goto exit;
}
work_loop->addEventSource(poller);
if (!api->open(this)) {
LOG("Could not open API");
goto exit;
}
if (initDevice() != kIOReturnSuccess) {
LOG("Failed to init device");
goto exit;
}
PMinit();
api->joinPMtree(this);
registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);
vsmcNotifier = VirtualSMCAPI::registerHandler(vsmcNotificationHandler, this);
return vsmcNotifier != nullptr;
exit:
releaseResources();
return false;
}
void SurfaceAmbientLightSensorDriver::stop(IOService* provider) {
// writeRegister(APDS9960_ENABLE, 0x00);
// PMstop();
// releaseResources();
// super::stop(provider);
PANIC("SurfaceAmbientLightSensorDriver", "called stop!!!");
}
bool SurfaceAmbientLightSensorDriver::vsmcNotificationHandler(void *sensors, void *refCon, IOService *vsmc, IONotifier *notifier) {
if (sensors && vsmc) {
auto self = static_cast(sensors);
auto ret = vsmc->callPlatformFunction(VirtualSMCAPI::SubmitPlugin, true, sensors, &self->vsmcPlugin, nullptr, nullptr);
if (ret == kIOReturnSuccess) {
IOLog("%s::Plugin submitted\n", self->getName());
self->poller->setTimeoutMS(POLLING_INTERVAL);
return true;
} else
IOLog("%s::Plugin submission failure %X\n", self->getName(), ret);
}
return false;
}
#define ENSURE(exp) ret=exp;\
if(ret != kIOReturnSuccess) {\
LOG(""#exp" failed!");\
return ret;\
}
IOReturn SurfaceAmbientLightSensorDriver::initDevice() {
IOReturn ret;
UInt8 id;
ENSURE(readRegister(APDS9960_ID, &id, 1))
LOG("Device id is %x", id);
ENSURE(writeRegister(APDS9960_ENABLE, 0x00))
// set short wait time to 700ms
ENSURE(writeRegister(APDS9960_WTIME, TIME_TO_VALUE(700)))
ENSURE(configDevice(ENABLE_WAIT, true))
// set ADC integration time to 300 ms
ENSURE(writeRegister(APDS9960_ATIME, TIME_TO_VALUE(300)))
ENSURE(writeRegister(APDS9960_CONFIG1, CONFIG1_DEFAULT))
ENSURE(writeRegister(APDS9960_CONTROL, ALS_GAIN_4X))
// these values come from Windows and is NECESSARY
ENSURE(writeRegister(APDS9960_CONFIG2, 0x03))
ENSURE(writeRegister(APDS9960_CONFIG3, 0x14))
ENSURE(configDevice(ENABLE_POWER, true))
ENSURE(configDevice(ENABLE_ALS, true));
return kIOReturnSuccess;
}
inline IOReturn SurfaceAmbientLightSensorDriver::readRegister(UInt8 reg, UInt8* values, size_t len) {
return api->writeReadI2C(®, 1, values, len);
}
inline IOReturn SurfaceAmbientLightSensorDriver::writeRegister(UInt8 reg, UInt8 cmd) {
UInt8 buffer[] {
reg,
cmd
};
return api->writeI2C(buffer, sizeof(buffer));
}
IOReturn SurfaceAmbientLightSensorDriver::configDevice(UInt8 func, bool enable) {
UInt8 reg;
if (readRegister(APDS9960_ENABLE, ®, 1) != kIOReturnSuccess) {
LOG("Read enable register failed!");
return kIOReturnError;
}
if (!(reg & func)!=enable)
return kIOReturnSuccess;
if (enable)
reg |= func;
else
reg &= ~func;
return writeRegister(APDS9960_ENABLE, reg);
}
void SurfaceAmbientLightSensorDriver::pollALI(IOTimerEventSource *timer) {
if (!awake)
return;
UInt16 color[4];
if (readRegister(APDS9960_CDATAL, reinterpret_cast(color), sizeof(color)) != kIOReturnSuccess) {
LOG("Read from ALS failed!");
poller->setTimeoutMS(POLLING_INTERVAL);
return;
}
atomic_store_explicit(¤t_lux, color[0]*1.5, memory_order_release);
VirtualSMCAPI::postInterrupt(SmcEventALSChange);
OSObject *result;
OSObject *params[] = {
OSNumber::withNumber(current_lux, 32),
};
alsd_device->evaluateObject("XALI", &result, params, 1);
OSSafeReleaseNULL(result);
params[0]->release();
// LOG("Value: ALI=%04d", current_lux);
poller->setTimeoutMS(POLLING_INTERVAL);
}
IOReturn SurfaceAmbientLightSensorDriver::setPowerState(unsigned long whichState, IOService *whatDevice) {
if (whatDevice != this)
return kIOReturnInvalid;
if (whichState == 0) {
if (awake) {
poller->cancelTimeout();
poller->disable();
awake = false;
writeRegister(APDS9960_ENABLE, 0x00);
DBG_LOG("Going to sleep");
}
} else {
if (!awake) {
awake = true;
initDevice();
poller->enable();
poller->setTimeoutMS(POLLING_INTERVAL);
DBG_LOG("Woke up");
}
}
return kIOPMAckImplied;
}
void SurfaceAmbientLightSensorDriver::releaseResources() {
if (poller) {
poller->cancelTimeout();
poller->disable();
work_loop->removeEventSource(poller);
OSSafeReleaseNULL(poller);
}
OSSafeReleaseNULL(work_loop);
if (api) {
if (api->isOpen(this)) {
api->close(this);
}
api = nullptr;
}
}
================================================
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/SurfaceAmbientLightSensorDriver.hpp
================================================
//
// SurfaceAmbientLightSensorDriver.hpp
// SurfaceAmbientLightSensor
//
// Created by Xia on 2021/10/27.
// Copyright © 2021 Xia Shangning. All rights reserved.
//
#ifndef SurfaceAmbientLightSensorDriver_hpp
#define SurfaceAmbientLightSensorDriver_hpp
#include
#include
#include "../../../Dependencies/VoodooGPIO/VoodooGPIO/VoodooGPIO.hpp"
#include "../../../Dependencies/VoodooSerial/VoodooSerial/ACPIParser/VoodooACPIResourcesParser.hpp"
#include "./../../Dependencies/VoodooSerial/VoodooSerial/VoodooI2C/VoodooI2CDevice/VoodooI2CDeviceNub.hpp"
#include
#include "AmbientLightValue.hpp"
#include "APDS9960Constants.h"
#define POLLING_INTERVAL 1000
class EXPORT SurfaceAmbientLightSensorDriver : public IOService {
OSDeclareDefaultStructors(SurfaceAmbientLightSensorDriver);
public:
IOService* probe(IOService* provider, SInt32* score) override;
bool start(IOService* provider) override;
void stop(IOService* provider) override;
IOReturn setPowerState(unsigned long whichState, IOService *whatDevice) override;
static bool vsmcNotificationHandler(void *sensors, void *refCon, IOService *vsmc, IONotifier *notifier);
private:
IOACPIPlatformDevice* alsd_device {nullptr};
VoodooI2CDeviceNub* api {nullptr};
IOWorkLoop* work_loop {nullptr};
IOTimerEventSource* poller {nullptr};
bool awake {true};
_Atomic(UInt32) current_lux;
IONotifier *vsmcNotifier {nullptr};
static constexpr SMC_KEY KeyAL = SMC_MAKE_IDENTIFIER('A','L','!',' ');
static constexpr SMC_KEY KeyALI0 = SMC_MAKE_IDENTIFIER('A','L','I','0');
static constexpr SMC_KEY KeyALI1 = SMC_MAKE_IDENTIFIER('A','L','I','1');
static constexpr SMC_KEY KeyALRV = SMC_MAKE_IDENTIFIER('A','L','R','V');
static constexpr SMC_KEY KeyALV0 = SMC_MAKE_IDENTIFIER('A','L','V','0');
static constexpr SMC_KEY KeyALV1 = SMC_MAKE_IDENTIFIER('A','L','V','1');
static constexpr SMC_KEY KeyLKSB = SMC_MAKE_IDENTIFIER('L','K','S','B');
static constexpr SMC_KEY KeyLKSS = SMC_MAKE_IDENTIFIER('L','K','S','S');
static constexpr SMC_KEY KeyMSLD = SMC_MAKE_IDENTIFIER('M','S','L','D');
VirtualSMCAPI::Plugin vsmcPlugin {
"SurfaceAmbientLightSensorDriver",
parseModuleVersion(xStringify(MODULE_VERSION)),
VirtualSMCAPI::Version,
};
struct ALSSensor {
enum Type : UInt8 {
NoSensor = 0,
BS520 = 1,
TSL2561CS = 2,
LX1973A = 3,
ISL29003 = 4,
Unknown7 = 7
};
Type sensorType {Type::NoSensor};
bool validWhenLidClosed {false};
UInt8 unknown {0};
bool controlSIL {false};
};
ALSForceBits forceBits;
void pollALI(IOTimerEventSource *timer);
IOReturn initDevice();
IOReturn configDevice(UInt8 func, bool enable);
void releaseResources();
inline IOReturn readRegister(UInt8 reg, UInt8* values, size_t len);
inline IOReturn writeRegister(UInt8 reg, UInt8 cmd);
};
#endif /* SurfaceAmbientLightSensorDriver_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/BatteryManager.cpp
================================================
//
// BatteryManager.cpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#include "BatteryManager.hpp"
BatteryManager *BatteryManager::instance = nullptr;
OSDefineMetaClassAndStructors(BatteryManager, OSObject)
void BatteryInfo::validateData(SInt32 id) {
if (!state.designVoltage)
state.designVoltage = DummyVoltage;
if (state.powerUnitIsWatt) {
auto mV = state.designVoltage;
IOLog("BatteryInfo::battery %d design voltage %d,%03d\n", id, mV / 1000, mV % 1000);
if (designCapacity * 1000 / mV < 900) {
IOLog("BatteryInfo::battery %d reports mWh but uses mAh (%u)\n", id, designCapacity);
state.powerUnitIsWatt = false;
} else {
designCapacity = designCapacity * 1000 / mV;
state.lastFullChargeCapacity = state.lastFullChargeCapacity * 1000 / mV;
state.designCapacityWarning = state.designCapacityWarning * 1000 / mV;
state.designCapacityLow = state.designCapacityLow * 1000 / mV;
}
}
if (designCapacity < state.lastFullChargeCapacity) {
IOLog("BatteryInfo::battery %d reports lower design capacity than maximum charged (%u/%u)\n", id,
designCapacity, state.lastFullChargeCapacity);
if (state.lastFullChargeCapacity < ValueMax) {
auto temp = designCapacity;
designCapacity = state.lastFullChargeCapacity;
state.lastFullChargeCapacity = temp;
}
}
IOLog("BatteryInfo::battery %d cycle count %u remaining capacity %u\n", id, cycle, state.lastFullChargeCapacity);
}
bool BatteryManager::needUpdateBIX(UInt8 index) {
if (!index or index > batteryCount)
return false;
index = index - 1;
IOSimpleLockLock(stateLock);
bool ret = !state.btInfo[index].connected;
if (!ret) {
AbsoluteTime cur_time;
UInt64 nsecs;
clock_get_uptime(&cur_time);
SUB_ABSOLUTETIME(&cur_time, &state.btInfo[index].lastBIXUpdateTime);
absolutetime_to_nanoseconds(cur_time, &nsecs);
if (nsecs > 60000000000) // > 60s
ret = true;
}
IOSimpleLockUnlock(stateLock);
return ret;
}
void BatteryManager::updateBatteryInfoExtended(UInt8 index, OSArray *bix) {
if (!index or index > batteryCount)
return;
index = index - 1;
IOLockLock(mainLock);
if (!bix)
batteries[index].reset();
else
batteries[index].updateInfoExtended(bix);
IOLockUnlock(mainLock);
}
bool BatteryManager::updateBatteryStatus(UInt8 index, UInt32 *bst) {
if (!index or index > batteryCount)
return false;
index = index - 1;
bool is_full;
IOLockLock(mainLock);
is_full = batteries[index].updateStatus(bst);
IOLockUnlock(mainLock);
return is_full;
}
void BatteryManager::updateBatteryTemperature(UInt8 index, UInt16 temp) {
if (!index or index > batteryCount)
return;
index = index - 1;
IOLockLock(mainLock);
batteries[index].updateTemperature(temp);
IOLockUnlock(mainLock);
}
bool BatteryManager::updateAdapterStatus(UInt8 index, UInt32 psr) {
if (!index or index > adapterCount)
return false;
index = index - 1;
bool power_connected;
IOLockLock(mainLock);
power_connected = adapters[index].updateStatus(psr!=0);
IOLockUnlock(mainLock);
return power_connected;
}
void BatteryManager::externalPowerNotify(bool status) {
IOPMrootDomain *rd = IOACPIPlatformDevice::getPMRootDomain();
rd->receivePowerNotification(kIOPMSetACAdaptorConnected | (kIOPMSetValue * status));
}
void BatteryManager::subscribe(PowerSourceInterestHandler h, void *t) {
atomic_store_explicit(&handlerTarget, t, memory_order_release);
atomic_store_explicit(&handler, h, memory_order_release);
}
void BatteryManager::informStatusChanged() {
auto h = atomic_load_explicit(&handler, memory_order_acquire);
if (h) h(atomic_load_explicit(&handlerTarget, memory_order_acquire));
}
bool BatteryManager::batteriesConnected() {
for (UInt8 i = 0; i < batteryCount; i++)
if (state.btInfo[i].connected)
return true;
return false;
}
bool BatteryManager::adaptersConnected() {
if (adapterCount) {
for (UInt8 i = 0; i < adapterCount; i++)
if (state.acInfo[i].connected)
return true;
}
else {
for (UInt8 i = 0; i < batteryCount; i++)
if (state.btInfo[i].state.calculatedACAdapterConnected)
return true;
}
return false;
}
bool BatteryManager::batteriesAreFull() {
// I am not fully convinced we should assume that batteries are full when there are none, but so be it.
for (UInt8 i = 0; i < batteryCount; i++)
if (state.btInfo[i].connected && (state.btInfo[i].state.state & SurfaceBattery::BSTStateMask) != SurfaceBattery::BSTNotCharging)
return false;
return true;
}
bool BatteryManager::externalPowerConnected() {
// Firstly try real adapters
for (UInt8 i = 0; i < adapterCount; i++)
if (state.acInfo[i].connected)
return true;
// Then try calculated adapters
bool hasBateries = false;
for (UInt8 i = 0; i < batteryCount; i++) {
if (state.btInfo[i].connected) {
// Ignore calculatedACAdapterConnected when real adapters exist!
if (adapterCount == 0 && state.btInfo[i].state.calculatedACAdapterConnected)
return true;
hasBateries = true;
}
}
// Safe to assume without batteries you need AC
return hasBateries == false;
}
UInt16 BatteryManager::calculateBatteryStatus(UInt8 index) {
return batteries[index].calculateBatteryStatus();
}
void BatteryManager::createShared(UInt8 bat_cnt, UInt8 adp_cnt) {
if (instance)
PANIC("BatteryManager", "attempted to allocate battery manager again");
instance = new BatteryManager;
if (!instance)
PANIC("BatteryManager", "failed to allocate battery manager");
instance->mainLock = IOLockAlloc();
if (!instance->mainLock)
PANIC("BatteryManager", "failed to allocate main battery manager lock");
instance->stateLock = IOSimpleLockAlloc();
if (!instance->stateLock)
PANIC("BatteryManager", "failed to allocate state battery manager lock");
atomic_init(&instance->handlerTarget, nullptr);
atomic_init(&instance->handler, nullptr);
if (bat_cnt >= BatteryManagerState::MaxBatteriesSupported) {
IOLog("BatteryManager::battery number more than %d!\n", BatteryManagerState::MaxBatteriesSupported);
bat_cnt = BatteryManagerState::MaxBatteriesSupported;
}
if (adp_cnt >= BatteryManagerState::MaxAcAdaptersSupported) {
IOLog("BatteryManager::adapter number more than %d!\n", BatteryManagerState::MaxAcAdaptersSupported);
adp_cnt = BatteryManagerState::MaxAcAdaptersSupported;
}
auto dict = IOService::nameMatching("PNP0C0A");
OSIterator *deviceIterator = nullptr;
if (dict) {
deviceIterator = IOService::getMatchingServices(dict);
dict->release();
}
if (deviceIterator) {
for (UInt8 i=0; ibatteries[i] = SurfaceBattery(OSDynamicCast(IOACPIPlatformDevice, deviceIterator->getNextObject()), i, instance->stateLock, &instance->state.btInfo[i]);
deviceIterator->release();
} else {
for (UInt8 i=0; ibatteries[i] = SurfaceBattery(nullptr, i, instance->stateLock, &instance->state.btInfo[i]);
}
instance->batteryCount = bat_cnt;
dict = IOService::nameMatching("ACPI0003");
deviceIterator = nullptr;
if (dict) {
deviceIterator = IOService::getMatchingServices(dict);
dict->release();
}
if (deviceIterator) {
for (UInt8 i=0; iadapters[i] = SurfaceACAdapter(OSDynamicCast(IOACPIPlatformDevice, deviceIterator->getNextObject()), i, instance->stateLock, &instance->state.acInfo[i]);
deviceIterator->release();
} else {
for (UInt8 i=0; iadapters[i] = SurfaceACAdapter(nullptr, i, instance->stateLock, &instance->state.acInfo[i]);
}
instance->adapterCount = adp_cnt;
}
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/BatteryManager.hpp
================================================
//
// BatteryManager.hpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
// Portions copyright © 2009 Superhai.
// VoodooBattery. Contact http://www.superhai.com/
//
#ifndef BatteryManagerBase_hpp
#define BatteryManagerBase_hpp
#include "SurfaceBattery.hpp"
#include "SurfaceACAdapter.hpp"
#include "BatteryManagerState.hpp"
#include
#include
#include
class EXPORT BatteryManager : public OSObject {
OSDeclareDefaultStructors(BatteryManager)
friend class SurfaceBatteryDriver;
public:
UInt8 batteryCount {0};
UInt8 adapterCount {0};
/**
* State lock, every state access must be guarded by this lock
*/
IOSimpleLock *stateLock {nullptr};
/**
* Main refreshed battery state containing battery information
*/
BatteryManagerState state {};
using PowerSourceInterestHandler = IOReturn (*)(void *target);
/**
* Subscribe to power source interest changes
* Only one handler could be subscribed to atm.
*
* @param h handler to be called
* @param t handler target (context)
*/
void subscribe(PowerSourceInterestHandler h, void *t);
void informStatusChanged();
bool batteriesConnected();
bool adaptersConnected();
bool batteriesAreFull();
bool externalPowerConnected();
static void createShared(UInt8 bat_cnt, UInt8 adp_cnt);
static BatteryManager *getShared() {
return instance;
}
/**
* Calculate battery status in AlarmWarning format
*
* @param index battery index
*
* @return calculated value
*/
UInt16 calculateBatteryStatus(UInt8 index);
AbsoluteTime lastAccess {0};
private:
/**
* The only allowed battery manager instance
*/
static BatteryManager *instance;
/**
* Not publicly exported notifications
*/
enum {
kIOPMSetValue = 1 << 16,
kIOPMSetDesktopMode = 1 << 17,
kIOPMSetACAdaptorConnected = 1 << 18
};
SurfaceBattery batteries[BatteryManagerState::MaxBatteriesSupported] {};
SurfaceACAdapter adapters[BatteryManagerState::MaxAcAdaptersSupported] {};
/**
* A lock to permit concurrent access
*/
IOLock *mainLock {nullptr};
/**
* Stored subscribed power source change handler target
*/
_Atomic(void *) handlerTarget;
/**
* Stored subscribed power source change handler
*/
_Atomic(PowerSourceInterestHandler) handler;
/**
* Post external power plug-in/plug-out update
*
* @param status true on AC adapter connect
*/
void externalPowerNotify(bool status);
/**
* @return whether battery is full
*/
bool updateBatteryStatus(UInt8 index, UInt32 *bst);
void updateBatteryInfoExtended(UInt8 index, OSArray *bix);
void updateBatteryTemperature(UInt8 index, UInt16 temp);
bool updateAdapterStatus(UInt8 index, UInt32 psr);
bool needUpdateBIX(UInt8 index);
};
#endif /* BatteryManagerBase_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/BatteryManagerState.hpp
================================================
//
// BatteryManagerState.h
// SurfaceBattery
//
// Copyright © 2018 usersse2. All rights reserved.
//
#ifndef BatteryManagerState_hpp
#define BatteryManagerState_hpp
/**
* Aggregated battery information
*/
struct BatteryInfo {
/**
* Unknown value (according to ACPI, -1)
*/
static constexpr UInt32 ValueUnknown = 0xFFFFFFFF;
/**
* Maximum integer value (according to ACPI)
*/
static constexpr UInt32 ValueMax = 0x80000000;
/**
* Must be no more than kSMBusMaximumDataSize
*/
static const size_t MaxStringLen = 32;
/**
* Default voltage to assume
*/
static constexpr UInt32 DummyVoltage = 12000;
/**
* Smaller state substruct for quick updates
*/
struct State {
UInt32 state {0};
UInt32 presentVoltage {0};
UInt32 presentRate {0};
UInt32 averageRate {0};
UInt32 remainingCapacity {0};
UInt32 lastFullChargeCapacity {0};
UInt32 lastRemainingCapacity {0};
UInt32 designVoltage {0};
UInt32 runTimeToEmpty {0};
UInt32 averageTimeToEmpty {0};
UInt32 averageTimeToEmptyHW {0};
SInt32 signedPresentRate {0};
SInt32 signedAverageRate {0};
SInt32 signedAverageRateHW {0};
UInt32 timeToFull {0};
UInt32 timeToFullHW {0};
UInt8 chargeLevel {0};
UInt32 designCapacityWarning {0};
UInt32 designCapacityLow {0};
UInt16 temperatureDecikelvin {2931};
UInt16 chargingCurrent {0};
UInt16 chargingVoltage {8000};
double temperature {0};
bool powerUnitIsWatt {false};
bool calculatedACAdapterConnected {false};
bool bad {false};
bool bogus {false};
bool critical {false};
bool batteryIsFull {true};
AbsoluteTime lastUpdateTime {0};
};
/**
* Battery manufacturer data
* All fields are big endian numeric values.
* While such values are not available from ACPI directly, we are faking
* them by leaving them as 0, as seen in System Profiler.
*/
struct BatteryManufacturerData {
UInt16 PackLotCode {0};
UInt16 PCBLotCode {0};
UInt16 FirmwareVersion {0};
UInt16 HardwareVersion {0};
UInt16 BatteryVersion {0};
};
/**
* Complete battery information
*/
State state {};
UInt16 manufactureDate {0};
UInt32 designCapacity {0};
UInt32 technology {0};
UInt32 cycle {0};
char deviceName[MaxStringLen] {};
char serial[MaxStringLen] {};
char batteryType[MaxStringLen] {};
char manufacturer[MaxStringLen] {};
bool connected {false};
AbsoluteTime lastBIXUpdateTime {0};
BatteryManufacturerData batteryManufacturerData {};
/**
* Validate battery information and set the defaults
*
* @param id battery id
*/
void validateData(SInt32 id=-1);
};
/**
* Aggregated adapter information
*/
struct ACAdapterInfo {
bool connected {false};
};
/**
* Aggregated battery manager state
*/
struct BatteryManagerState {
static constexpr UInt8 MaxBatteriesSupported = 4;
static constexpr UInt8 MaxAcAdaptersSupported = 2;
BatteryInfo btInfo[MaxBatteriesSupported] {};
ACAdapterInfo acInfo[MaxAcAdaptersSupported] {};
};
#endif /* BatteryManagerState_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/KeyImplementations.cpp
================================================
//
// KeyImplementations.cpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#include "KeyImplementations.hpp"
#include "SurfaceBatteryDriver.hpp"
SMC_RESULT ACID::readAccess() {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto extConnected = BatteryManager::getShared()->externalPowerConnected();
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
if (extConnected) {
// Have some dummy value here for now, because ACPI has no means of getting adapter info
// like power, voltage, serial number through only 2 pins - Vcc and GND.
data[0] = 0xba;
data[1] = 0xbe;
data[2] = 0x3c;
data[3] = 0x45;
data[4] = 0xc0;
data[5] = 0x03;
data[6] = 0x10;
data[7] = 0x43;
} else {
memset(data, 0, size);
}
return SmcSuccess;
}
SMC_RESULT ACIN::readAccess() {
bool *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = BatteryManager::getShared()->externalPowerConnected();
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT AC_N::readAccess() {
data[0] = BatteryManager::getShared()->adapterCount;
return SmcSuccess;
}
SMC_RESULT B0AC::readAccess() {
SInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.signedPresentRate);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT B0AV::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.presentVoltage);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT B0BI::readAccess() {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
data[0] = BatteryManager::getShared()->state.btInfo[index].connected;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT B0CT::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].cycle);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT B0FC::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.lastFullChargeCapacity);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT B0PS::readAccess() {
//TODO: find what is its value when battery is the active power source
data[0] = data[1] = 0;
return SmcSuccess;
}
SMC_RESULT B0RM::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.remainingCapacity);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT B0St::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->calculateBatteryStatus(index));
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT B0TF::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto state = BatteryManager::getShared()->state.btInfo[index].state.state & SurfaceBattery::BSTStateMask;
if (state == SurfaceBattery::BSTCharging)
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.timeToFull);
else
*ptr = 0xffff;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT BATP::readAccess() {
bool *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = BatteryManager::getShared()->externalPowerConnected() == false;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT BBAD::readAccess() {
// TODO: what's with multiple batteries?
bool *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = BatteryManager::getShared()->state.btInfo[0].state.bad;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT BBIN::readAccess() {
bool *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = BatteryManager::getShared()->batteriesConnected();
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT BFCL::readAccess() {
//TODO: implement this
data[0] = 100;
return SmcSuccess;
}
SMC_RESULT BNum::readAccess() {
data[0] = BatteryManager::getShared()->batteryCount;
return SmcSuccess;
}
SMC_RESULT BSIn::readAccess() {
enum {
BSInCharging = 1,
BSInACPresent = 2,
BSInACPresenceChanged = 4,
BSInOSStopCharge = 8,
BSInOSCalibrationReq = 16,
BSInBTQueryInProgress = 32,
BSInBTOk = 64,
BSInAdcInProgress = 128
};
data[0] = BSInBTOk;
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
if (BatteryManager::getShared()->externalPowerConnected()) {
if (!BatteryManager::getShared()->batteriesAreFull())
data[0] |= BSInCharging;
data[0] |= BSInACPresent;
}
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT BRSC::readAccess() {
// TODO: what's with multiple batteries?
data[0] = 0;
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
if (!BatteryManager::getShared()->batteryCount ||
!BatteryManager::getShared()->state.btInfo[0].connected)
data[1] = 0;
else if (BatteryManager::getShared()->state.btInfo[0].state.chargeLevel)
data[1] = BatteryManager::getShared()->state.btInfo[0].state.chargeLevel;
else if (BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity > 0 &&
BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity != BatteryInfo::ValueUnknown &&
BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity <= BatteryInfo::ValueMax)
data[1] = BatteryManager::getShared()->state.btInfo[0].state.remainingCapacity * 100 / BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity;
else
data[1] = 0;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT CHBI::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[0].state.chargingCurrent);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT CHBV::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[0].state.chargingVoltage);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT CHLC::readAccess() {
// TODO: does it have any other values?
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
if (BatteryManager::getShared()->batteryCount > 0 &&
BatteryManager::getShared()->state.btInfo[0].connected &&
BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity > 0 &&
BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity != BatteryInfo::ValueUnknown &&
BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity <= BatteryInfo::ValueMax &&
BatteryManager::getShared()->state.btInfo[0].state.remainingCapacity > 0 &&
BatteryManager::getShared()->state.btInfo[0].state.remainingCapacity != BatteryInfo::ValueUnknown &&
BatteryManager::getShared()->state.btInfo[0].state.remainingCapacity <= BatteryInfo::ValueMax &&
BatteryManager::getShared()->state.btInfo[0].state.remainingCapacity >= BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity)
data[0] = 2;
else
data[0] = 1;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT TB0T::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = VirtualSMCAPI::encodeSp(SmcKeyTypeSp78, BatteryManager::getShared()->state.btInfo[index].state.temperature);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
SMC_RESULT BC1V::readAccess() {
UInt16 *ptr = reinterpret_cast(data);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
*ptr = OSSwapHostToBigInt16(BatteryManager::getShared()->state.btInfo[index].state.presentVoltage);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return SmcSuccess;
}
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/KeyImplementations.hpp
================================================
//
// KeyImplementations.hpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#ifndef KeyImplementations_hpp
#define KeyImplementations_hpp
#include
#include
#include "BatteryManager.hpp"
class BatKey : public VirtualSMCValue { };
class BatIdxKey : public VirtualSMCValue {
protected:
size_t index;
public:
BatIdxKey(size_t index) : index(index) {}
};
class AC_N : public BatKey { protected: SMC_RESULT readAccess() override; };
class ACID : public BatKey { protected: SMC_RESULT readAccess() override; };
class ACIN : public BatKey { protected: SMC_RESULT readAccess() override; };
class B0AC : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class B0AV : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class B0BI : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class B0CT : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class B0FC : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class B0PS : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class B0RM : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class B0St : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class B0TF : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class TB0T : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
class BATP : public BatKey { protected: SMC_RESULT readAccess() override; };
class BBAD : public BatKey { protected: SMC_RESULT readAccess() override; };
class BBIN : public BatKey { protected: SMC_RESULT readAccess() override; };
class BFCL : public BatKey { protected: SMC_RESULT readAccess() override; };
class BNum : public BatKey { protected: SMC_RESULT readAccess() override; };
class BSIn : public BatKey { protected: SMC_RESULT readAccess() override; };
class BRSC : public BatKey { protected: SMC_RESULT readAccess() override; };
class CHBI : public BatKey { protected: SMC_RESULT readAccess() override; };
class CHBV : public BatKey { protected: SMC_RESULT readAccess() override; };
class CHLC : public BatKey { protected: SMC_RESULT readAccess() override; };
class BC1V : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: SMC_RESULT readAccess() override; };
//TODO: implement these
// class D0IR : public BatKey { using BatKey::BatKey; protected: SMC_RESULT readAccess() override; };
// class D0VM : public BatKey { using BatKey::BatKey; protected: SMC_RESULT readAccess() override; };
// class D0VR : public BatKey { using BatKey::BatKey; protected: SMC_RESULT readAccess() override; };
// class D0VX : public BatKey { using BatKey::BatKey; protected: SMC_RESULT readAccess() override; };
#endif /* KeyImplementations_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceACAdapter.cpp
================================================
//
// SurfaceACAdapter.cpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#include "SurfaceACAdapter.hpp"
bool SurfaceACAdapter::updateStatus(bool connected) {
IOSimpleLockLock(adapterInfoLock);
adapterInfo->connected = connected;
IOSimpleLockUnlock(adapterInfoLock);
if (device) {
OSObject *result;
OSObject *params[] = {
OSNumber::withNumber(connected, 32),
};
device->evaluateObject("XPSR", &result, params, 1);
OSSafeReleaseNULL(result);
params[0]->release();
}
return connected;
}
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceACAdapter.hpp
================================================
//
// SurfaceACAdapter.hpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#ifndef SurfaceACAdapter_hpp
#define SurfaceACAdapter_hpp
#include
#include "BatteryManagerState.hpp"
class SurfaceACAdapter {
public:
SurfaceACAdapter() {}
/**
* Actual constructor representing a real device with its own index and shared info struct
*/
SurfaceACAdapter(IOACPIPlatformDevice *device, SInt32 id, IOSimpleLock *lock, ACAdapterInfo *info) :
device(device), id(id), adapterInfoLock(lock), adapterInfo(info) {}
bool updateStatus(bool connected);
private:
/**
* Current adapter device
*/
IOACPIPlatformDevice *device {nullptr};
/**
* Current adapter id
*/
SInt32 id {-1};
/**
* Reference to shared lock for refreshing adapter info
*/
IOSimpleLock *adapterInfoLock {nullptr};
/**
* Reference to shared adapter info
*/
ACAdapterInfo *adapterInfo {nullptr};
};
#endif /* SurfaceACAdapter_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceBattery.cpp
================================================
//
// SurfaceBattery.cpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#include "SurfaceBattery.hpp"
#include
UInt32 SurfaceBattery::getNumberFromArray(OSArray *array, UInt32 index) {
auto number = OSDynamicCast(OSNumber, array->getObject(index));
if (number)
return number->unsigned32BitValue();
return BatteryInfo::ValueUnknown;
}
void SurfaceBattery::getStringFromArray(OSArray *array, UInt32 index, char *dst, UInt32 dstSize) {
if (dstSize == 0)
return;
const char *src = nullptr;
auto object = array->getObject(index);
if (object) {
if (auto string = OSDynamicCast(OSString, object)) {
src = string->getCStringNoCopy();
dstSize = min(dstSize - 1, string->getLength());
}
}
if (src) {
strncpy(dst, src, dstSize);
dst[dstSize] = '\0';
} else {
dst[0] = '\0';
}
}
void SurfaceBattery::reset() {
IOSimpleLockLock(batteryInfoLock);
*batteryInfo = BatteryInfo{};
hasBIX = false;
IOSimpleLockUnlock(batteryInfoLock);
}
void SurfaceBattery::updateInfoExtended(OSArray *bix) {
BatteryInfo bi;
bi.connected = true;
clock_get_uptime(&bi.lastBIXUpdateTime);
if (getNumberFromArray(bix, BIXPowerUnit) == 0)
bi.state.powerUnitIsWatt = true;
bi.designCapacity = getNumberFromArray(bix, BIXDesignCapacity);
bi.state.lastFullChargeCapacity = getNumberFromArray(bix, BIXLastFullChargeCapacity);
bi.technology = getNumberFromArray(bix, BIXBatteryTechnology);
bi.state.designVoltage = getNumberFromArray(bix, BIXDesignVoltage);
bi.state.designCapacityWarning = getNumberFromArray(bix, BIXDesignCapacityOfWarning);
bi.state.designCapacityLow = getNumberFromArray(bix, BIXDesignCapacityOfLow);
bi.cycle = getNumberFromArray(bix, BIXCycleCount);
getStringFromArray(bix, BIXModelNumber, bi.deviceName, BatteryInfo::MaxStringLen);
getStringFromArray(bix, BIXSerialNumber, bi.serial, BatteryInfo::MaxStringLen);
// getStringFromArray(bix, BIXBatteryType, bi.batteryType, BatteryInfo::MaxStringLen);
// getStringFromArray(bix, BIXOEMInformation, bi.manufacturer, BatteryInfo::MaxStringLen);
strncpy(bi.batteryType, "SurfaceBattery", BatteryInfo::MaxStringLen);
strncpy(bi.manufacturer, "XavierXia", BatteryInfo::MaxStringLen);
bi.validateData(id);
IOSimpleLockLock(batteryInfoLock);
*batteryInfo = bi;
hasBIX = true;
IOSimpleLockUnlock(batteryInfoLock);
}
bool SurfaceBattery::updateStatus(UInt32 *bst) {
IOSimpleLockLock(batteryInfoLock);
BatteryInfo::State st = batteryInfo->state;
if (!hasBIX) {
IOSimpleLockUnlock(batteryInfoLock);
return false;
}
IOSimpleLockUnlock(batteryInfoLock);
UInt32 defaultRate = 5000*1000 / st.designVoltage; // 5w
st.state = bst[BSTState];
st.presentRate = bst[BSTPresentRate];
st.remainingCapacity = bst[BSTRemainingCapacity];
st.presentVoltage = bst[BSTPresentVoltage];
if (st.powerUnitIsWatt) {
st.presentRate = st.presentRate * 1000 / st.designVoltage;
st.remainingCapacity = st.remainingCapacity * 1000 / st.designVoltage;
}
// Sometimes this value can be either reported incorrectly or miscalculated
// and exceed the actual capacity. Simply workaround it by capping the value.
// REF: https://github.com/acidanthera/bugtracker/issues/565
if (st.remainingCapacity > st.lastFullChargeCapacity)
st.remainingCapacity = st.lastFullChargeCapacity;
if (!st.averageRate) {
st.averageRate = st.presentRate;
} else { // We will take a 1 minutes window
AbsoluteTime cur_time;
UInt64 nsecs;
clock_get_uptime(&cur_time);
SUB_ABSOLUTETIME(&cur_time, &st.lastUpdateTime);
absolutetime_to_nanoseconds(cur_time, &nsecs);
UInt32 msecs = (UInt32)(nsecs/1000000);
st.averageRate = (60000*st.averageRate + msecs*st.presentRate)/(60000+msecs);
}
clock_get_uptime(&st.lastUpdateTime);
// Remaining capacity
st.averageTimeToEmpty = st.averageRate ? 60 * st.remainingCapacity / st.averageRate : 60 * st.remainingCapacity / defaultRate;
st.runTimeToEmpty = st.presentRate ? 60 * st.remainingCapacity / st.presentRate : 60 * st.remainingCapacity / defaultRate;
// Check battery state
bool bogus = false;
switch (st.state & BSTStateMask) {
case BSTNotCharging: {
st.calculatedACAdapterConnected = true;
st.batteryIsFull = true;
st.chargingCurrent = 0;
st.timeToFull = 0;
st.signedPresentRate = st.presentRate;
st.signedAverageRate = st.averageRate;
break;
}
case BSTDischarging: {
st.calculatedACAdapterConnected = false;
st.batteryIsFull = false;
st.chargingCurrent = 0;
st.timeToFull = 0;
st.signedPresentRate = -st.presentRate;
st.signedAverageRate = -st.averageRate;
break;
}
case BSTCharging: {
st.calculatedACAdapterConnected = true;
st.batteryIsFull = false;
int diff = st.lastFullChargeCapacity - st.remainingCapacity;
st.timeToFull = st.averageRate ? 60 * diff / st.averageRate : 60 * diff / defaultRate;
st.signedPresentRate = st.presentRate;
st.signedAverageRate = st.averageRate;
break;
}
default: {
IOLog("SurfaceBattery::Bogus status data from battery %d (%x)", id, st.state);
st.batteryIsFull = false;
bogus = true;
break;
}
}
st.lastRemainingCapacity = st.remainingCapacity;
// bool warning = st.remainingCapacity <= st.designCapacityWarning || st.runTimeToEmpty < 10;
bool critical = st.remainingCapacity <= st.designCapacityLow || st.runTimeToEmpty < 5;
if (st.state & BSTCritical) {
IOLog("SurfaceBattery::Battery %d is in critical state", id);
critical = true;
}
// When we report battery failure, AppleSmartBatteryManager sets isCharging=false.
// So we don't report battery failure when it's charging.
st.bad = (st.state & BSTStateMask) != BSTCharging && st.lastFullChargeCapacity < 2 * st.designCapacityWarning;
st.bogus = bogus;
st.critical = critical;
IOSimpleLockLock(batteryInfoLock);
batteryInfo->state = st;
IOSimpleLockUnlock(batteryInfoLock);
return st.batteryIsFull;
}
void SurfaceBattery::updateTemperature(UInt16 temp) {
IOSimpleLockLock(batteryInfoLock);
batteryInfo->state.temperatureDecikelvin = temp;
batteryInfo->state.temperature = ((double) temp - 2731) / 10;
IOSimpleLockUnlock(batteryInfoLock);
}
UInt16 SurfaceBattery::calculateBatteryStatus() {
UInt16 value = 0;
if (batteryInfo->connected) {
value = kBInitializedStatusBit;
auto st = batteryInfo->state.state;
if (st & BSTDischarging)
value |= kBDischargingStatusBit;
if (st & BSTCritical)
value |= kBFullyDischargedStatusBit;
if ((st & BSTStateMask) == BSTNotCharging) {
if (batteryInfo->state.lastFullChargeCapacity > 0 &&
batteryInfo->state.lastFullChargeCapacity != BatteryInfo::ValueUnknown &&
batteryInfo->state.lastFullChargeCapacity <= BatteryInfo::ValueMax &&
batteryInfo->state.remainingCapacity > 0 &&
batteryInfo->state.remainingCapacity != BatteryInfo::ValueUnknown &&
batteryInfo->state.remainingCapacity <= BatteryInfo::ValueMax &&
batteryInfo->state.remainingCapacity >= batteryInfo->state.lastFullChargeCapacity)
value |= kBFullyChargedStatusBit;
value |= kBTerminateChargeAlarmBit;
}
if (batteryInfo->state.bad) {
value |= kBTerminateChargeAlarmBit;
value |= kBTerminateDischargeAlarmBit;
}
}
return value;
}
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceBattery.hpp
================================================
//
// SurfaceBattery.hpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#ifndef SurfaceBattery_hpp
#define SurfaceBattery_hpp
#include
#include "BatteryManagerState.hpp"
class SurfaceBattery {
friend class BatteryManager;
public:
/**
* Peak accuracy for average in percents
*/
static constexpr UInt8 AverageBoundPercent = 25;
/**
* Battery status obtained from ACPI _BST
*/
enum {
/**
Means that the battery is not charging and not discharging.
It may happen when the battery is fully charged,
or when AC adapter is connected but charging has not started yet,
or when charging is limited to some percent in BIOS settings.
*/
BSTNotCharging = 0,
BSTDischarging = 1 << 0,
BSTCharging = 1 << 1,
BSTCritical = 1 << 2,
BSTStateMask = BSTNotCharging | BSTDischarging | BSTCharging,
};
/**
* Reference to shared lock for refreshing battery info
*/
IOSimpleLock *batteryInfoLock {nullptr};
/**
* Reference to shared battery info
*/
BatteryInfo *batteryInfo {nullptr};
/**
* Dummy constructor
*/
SurfaceBattery() {}
/**
* Actual constructor representing a real device with its own index and shared info struct
*/
SurfaceBattery(IOACPIPlatformDevice *device, SInt32 id, IOSimpleLock *lock, BatteryInfo *info) :
device(device), id(id), batteryInfoLock(lock), batteryInfo(info) {}
/**
* Calculate value for B0St SMC key and corresponding SMBus command
*
* @return value
*/
UInt16 calculateBatteryStatus();
/**
* QuickPoll will be disable when average rate is available from EC
*/
bool averageRateAvailable {false};
private:
/**
* Current battery device
*/
IOACPIPlatformDevice *device {nullptr};
bool hasBIX {false};
UInt32 getNumberFromArray(OSArray *array, UInt32 index);
void getStringFromArray(OSArray *array, UInt32 index, char *dst, UInt32 dstSize);
/**
* Reset BatteryInfo
*/
void reset();
/**
* Obtain aggregated battery information from SAM
*
* @param bix _bix returned from SAM
*/
void updateInfoExtended(OSArray *bix);
/**
* Obtain aggregated battery status from SAM
*
* @param bst _bst returned from SSH
*
* @return whether battery is full
*/
bool updateStatus(UInt32 *bst);
void updateTemperature(UInt16 temp);
/**
* Current battery id
*/
SInt32 id {-1};
/**
* Extended Battery Static Information pack layout
*/
enum {
BIXRevision, //Integer
BIXPowerUnit,
BIXDesignCapacity,
BIXLastFullChargeCapacity, //Integer (DWORD)
BIXBatteryTechnology,
BIXDesignVoltage,
BIXDesignCapacityOfWarning,
BIXDesignCapacityOfLow,
BIXCycleCount, //Integer (DWORD)
BIXMeasurementAccuracy, //Integer (DWORD)
BIXMaxSamplingTime, //Integer (DWORD)
BIXMinSamplingTime, //Integer (DWORD)
BIXMaxAveragingInterval, //Integer (DWORD)
BIXMinAveragingInterval, //Integer (DWORD)
BIXBatteryCapacityGranularity1,
BIXBatteryCapacityGranularity2,
BIXModelNumber,
BIXSerialNumber,
BIXBatteryType,
BIXOEMInformation,
};
/**
* Battery Real-time Information pack layout
*/
enum {
BSTState,
BSTPresentRate,
BSTRemainingCapacity,
BSTPresentVoltage
};
};
#endif /* SurfaceBattery_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceBatteryDriver.cpp
================================================
//
// SurfaceBatteryDriver.cpp
// SurfaceBattery
//
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#include
#include
#include "SurfaceBatteryDriver.hpp"
#include "KeyImplementations.hpp"
#include
#define super IOService
OSDefineMetaClassAndStructors(SurfaceBatteryDriver, IOService)
void SurfaceBatteryDriver::eventReceived(SurfaceBatteryNub *sender, SurfaceBatteryEventType type) {
switch (type) {
case SurfaceBatteryInformationChanged:
update_bix->interruptOccurred(nullptr, this, 0);
break;
case SurfaceBatteryStatusChanged:
case SurfaceAdaptorStatusChanged:
DBG_LOG("Got BST/PSR update event");
AbsoluteTime cur_time;
UInt64 nsecs;
clock_get_uptime(&cur_time);
SUB_ABSOLUTETIME(&cur_time, &last_update);
absolutetime_to_nanoseconds(cur_time, &nsecs);
if (nsecs > 1000000000) { // PSR often comes with BST changes, so avoid update it twice in a short period (1s).
quick_cnt = BST_UPDATE_QUICK_CNT;
clock_get_uptime(&last_update);
update_bst->interruptOccurred(nullptr, this, 0);
}
break;
default:
DBG_LOG("WTF? Unknown event type");
break;
}
}
void SurfaceBatteryDriver::updateBatteryInformation(IOInterruptEventSource *sender, int count) {
if (!awake or bat_missing)
return;
bix_fail = false;
bool connected = false;
if (nub->getBatteryConnection(1, &connected) != kIOReturnSuccess) {
LOG("Failed to get battery connection status from SSH!");
bix_fail = true;
// It is impossible to occur unless the battery is not present
bat_missing = true;
return;
}
if (!connected)
BatteryManager::getShared()->updateBatteryInfoExtended(1, nullptr); // reset battery
else if (BatteryManager::getShared()->needUpdateBIX(1)) {
OSArray *bix;
if (nub->getBatteryInformation(1, &bix) != kIOReturnSuccess) {
LOG("Failed to get battery information extended from SSH!");
bix_fail = true;
} else {
BatteryManager::getShared()->updateBatteryInfoExtended(1, bix);
bix->flushCollection();
OSSafeReleaseNULL(bix);
}
}
}
void SurfaceBatteryDriver::updateBatteryStatus(IOInterruptEventSource *sender, int count) {
if (!awake or bat_missing)
return;
UInt32 psr;
bool connected = false;
timer->cancelTimeout();
if (bix_fail) {
updateBatteryInformation(nullptr, 0);
if (bix_fail)
goto fail;
}
if (nub->getAdaptorStatus(&psr) != kIOReturnSuccess) {
LOG("Failed to get power source status from SSH!");
goto fail;
} else
power_connected = BatteryManager::getShared()->updateAdapterStatus(1, psr);
BatteryManager::getShared()->externalPowerNotify(power_connected);
if (nub->getBatteryConnection(1, &connected) != kIOReturnSuccess) {
LOG("Failed to get battery connection status from SSH!");
return;
}
if (connected) {
UInt16 temp = 0;
UInt32 bst[4];
if (nub->getBatteryStatus(1, bst, &temp) != kIOReturnSuccess) {
LOG("Failed to get BST from SSH!");
goto fail;
} else
BatteryManager::getShared()->updateBatteryStatus(1, bst);
if (temp)
BatteryManager::getShared()->updateBatteryTemperature(1, temp);
BatteryManager::getShared()->informStatusChanged();
}
if (quick_cnt) {
if (--quick_cnt == 0)
sync = true; // after finishing quick update, sync with normal update
timer->setTimeoutMS(BST_UPDATE_QUICK);
} else { // sync normal update interval
if (sync) {
AbsoluteTime cur_time;
UInt64 nsecs;
sync = false;
clock_get_uptime(&cur_time);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
SUB_ABSOLUTETIME(&cur_time, &BatteryManager::getShared()->lastAccess);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
absolutetime_to_nanoseconds(cur_time, &nsecs);
UInt8 timerDelta = nsecs / (1000000 * BST_UPDATE_QUICK);
if (timerDelta < BST_UPDATE_NORMAL/BST_UPDATE_QUICK - 5) {
timer->setTimeoutMS(BST_UPDATE_NORMAL - (2 + timerDelta) * BST_UPDATE_QUICK);
return;
}
}
timer->setTimeoutMS(BST_UPDATE_NORMAL);
}
return;
fail:
timer->setTimeoutMS(BST_UPDATE_QUICK/2);
}
void SurfaceBatteryDriver::pollBatteryStatus(IOTimerEventSource *sender) {
if (bat_missing) {
// Fake a 100% charging battery based on BIX from SP7.
// -------- BIX --------
UInt8 buffer[BIX_LENGTH] = {0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xa8, 0x00,
0x00, 0xc0, 0xa8, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x92, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0xe8, 0x03, 0x00, 0x00, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xe8, 0x03, 0x00,
0x00, 0xe8, 0x03, 0x00, 0x00, 0x0a, 0x00, 0x00,
0x00, 0x0a, 0x00, 0x00, 0x00, 0x4d, 0x31, 0x31,
0x30, 0x39, 0x35, 0x39, 0x37, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x30, 0x30, 0x32, 0x37, 0x30, 0x36,
0x36, 0x30, 0x32, 0x30, 0x00, 0x4c, 0x49, 0x4f,
0x4e, 0x00, 0x44, 0x59, 0x4e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
UInt32 *temp = reinterpret_cast(buffer+1);
const char *str = reinterpret_cast(buffer);
OSNumber *revision = OSNumber::withNumber(*buffer, 8);
OSNumber *power_unit = OSNumber::withNumber(temp[0], 32);
OSNumber *design_cap = OSNumber::withNumber(temp[1], 32);
OSNumber *last_full_cap = OSNumber::withNumber(temp[2], 32);
OSNumber *bat_tech = OSNumber::withNumber(temp[3], 32);
OSNumber *design_volt = OSNumber::withNumber(temp[4], 32);
OSNumber *design_cap_warn = OSNumber::withNumber(temp[5], 32);
OSNumber *design_cap_low = OSNumber::withNumber(temp[6], 32);
OSNumber *cycle_cnt = OSNumber::withNumber(temp[7], 32);
OSNumber *mesure_acc = OSNumber::withNumber(temp[8], 32);
OSNumber *max_sample_t = OSNumber::withNumber(temp[9], 32);
OSNumber *min_sample_t = OSNumber::withNumber(temp[10], 32);
OSNumber *max_avg_interval = OSNumber::withNumber(temp[11], 32);
OSNumber *min_avg_interval = OSNumber::withNumber(temp[12], 32);
OSNumber *bat_cap_gra_1 = OSNumber::withNumber(temp[13], 32);
OSNumber *bat_cap_gra_2 = OSNumber::withNumber(temp[14], 32);
OSString *model_number = OSString::withCString(str+0x3D);
OSString *serial_number = OSString::withCString(str+0x52);
OSString *bat_type = OSString::withCString(str+0x5D);
OSString *oem_info = OSString::withCString(str+0x62);
const OSObject *arr[] = {revision, power_unit, design_cap, last_full_cap, bat_tech,
design_volt, design_cap_warn, design_cap_low, cycle_cnt,
mesure_acc, max_sample_t, min_sample_t, max_avg_interval,
min_avg_interval, bat_cap_gra_1, bat_cap_gra_2, model_number,
serial_number, bat_type, oem_info};
OSArray *bix = OSArray::withObjects(arr, 20);
BatteryManager::getShared()->updateBatteryInfoExtended(1, bix);
bix->flushCollection();
OSSafeReleaseNULL(bix);
// -------- BST --------
UInt32 bst[4] = {0x02, 0x00, 0xa8c0, 0x1d92};
BatteryManager::getShared()->updateBatteryStatus(1, bst);
BatteryManager::getShared()->updateAdapterStatus(1, true);
BatteryManager::getShared()->externalPowerNotify(true);
} else
updateBatteryStatus(nullptr, 0);
}
IOService *SurfaceBatteryDriver::probe(IOService *provider, SInt32 *score) {
if (!super::probe(provider, score))
return nullptr;
nub = OSDynamicCast(SurfaceBatteryNub, provider);
if (!nub)
return nullptr;
//TODO: SurfaceBook series have two batteries
// OSNumber *bat_cnt_prop = OSDynamicCast(OSNumber, getProperty("BatteryCount"));
UInt32 bat_cnt = 1;
// if (bat_cnt_prop) {
// bat_cnt = bat_cnt_prop->unsigned32BitValue();
// } else {
// LOG("Fall back to default: battery count = 1");
// }
BatteryManager::createShared(bat_cnt, 1);
//TODO: implement the keys below as well
// IB0R: sp4s or sp5s
// IBAC: sp7s
// PB0R = IB0R * VP0R
return this;
}
bool SurfaceBatteryDriver::start(IOService *provider) {
if (!super::start(provider))
return false;
// AppleSMC presence is a requirement, wait for it.
auto dict = nameMatching("AppleSMC");
auto applesmc = waitForMatchingService(dict);
if (!applesmc) {
LOG("Timeout in waiting for AppleSMC");
return false;
}
OSSafeReleaseNULL(dict);
OSSafeReleaseNULL(applesmc);
const UInt8 adaptCount = BatteryManager::getShared()->adapterCount;
const UInt8 batCount = min(BatteryManager::getShared()->batteryCount, MaxIndexCount);
work_loop = IOWorkLoop::workLoop();
if (!work_loop) {
LOG("Could not get work loop!");
return false;
}
timer = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceBatteryDriver::pollBatteryStatus));
if (!timer) {
LOG("Could not create timer!");
goto exit;
}
work_loop->addEventSource(timer);
update_bix = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceBatteryDriver::updateBatteryInformation));
update_bst = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceBatteryDriver::updateBatteryStatus));
if (!update_bix || !update_bst) {
LOG("Could not create interrupt event!");
goto exit;
}
work_loop->addEventSource(update_bix);
work_loop->addEventSource(update_bst);
if (nub->registerBatteryEvent(this, OSMemberFunctionCast(SurfaceBatteryNub::EventHandler, this, &SurfaceBatteryDriver::eventReceived)) != kIOReturnSuccess) {
LOG("Battery event registration failed!");
goto exit;
}
//WARNING: watch out, key addition is sorted here!
if (adaptCount > 0) {
VirtualSMCAPI::addKey(KeyACEN, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(0, new ACIN));
VirtualSMCAPI::addKey(KeyACFP, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(false, new ACIN));
VirtualSMCAPI::addKey(KeyACID, vsmcPlugin.data, VirtualSMCAPI::valueWithData(nullptr, 8, SmcKeyTypeCh8s, new ACID));
VirtualSMCAPI::addKey(KeyACIN, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(false, new ACIN));
}
for (UInt8 i = 0; i < batCount; i++) {
VirtualSMCAPI::addKey(KeyB0AC(i), vsmcPlugin.data, VirtualSMCAPI::valueWithSint16(400, new B0AC(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));
VirtualSMCAPI::addKey(KeyB0AV(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(13000, new B0AV(i)));
VirtualSMCAPI::addKey(KeyB0BI(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(1, new B0BI(i)));
VirtualSMCAPI::addKey(KeyB0CT(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(1, new B0CT(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));
VirtualSMCAPI::addKey(KeyB0FC(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(4000, new B0FC(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));
VirtualSMCAPI::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));
VirtualSMCAPI::addKey(KeyB0RM(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(2000, new B0RM(i), SMC_KEY_ATTRIBUTE_PRIVATE_WRITE|SMC_KEY_ATTRIBUTE_WRITE|SMC_KEY_ATTRIBUTE_READ));
VirtualSMCAPI::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));
VirtualSMCAPI::addKey(KeyB0TF(i), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(0, new B0TF(i)));
VirtualSMCAPI::addKey(KeyTB0T(i+1), vsmcPlugin.data, VirtualSMCAPI::valueWithSp(0, SmcKeyTypeSp78, new TB0T(i)));
if (i == 0)
VirtualSMCAPI::addKey(KeyTB0T(0), vsmcPlugin.data, VirtualSMCAPI::valueWithSp(0, SmcKeyTypeSp78, new TB0T(0)));
}
VirtualSMCAPI::addKey(KeyBATP, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(true, new BATP));
VirtualSMCAPI::addKey(KeyBBAD, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(false, new BBAD));
VirtualSMCAPI::addKey(KeyBBIN, vsmcPlugin.data, VirtualSMCAPI::valueWithFlag(true, new BBIN));
VirtualSMCAPI::addKey(KeyBFCL, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(100, new BFCL, SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE));
VirtualSMCAPI::addKey(KeyBNum, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(1, new BNum));
VirtualSMCAPI::addKey(KeyBRSC, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(40, new BRSC, SMC_KEY_ATTRIBUTE_READ | SMC_KEY_ATTRIBUTE_WRITE | SMC_KEY_ATTRIBUTE_PRIVATE_WRITE));
VirtualSMCAPI::addKey(KeyBSIn, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(0, new BSIn));
VirtualSMCAPI::addKey(KeyCHBI, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(0, new CHBI));
VirtualSMCAPI::addKey(KeyCHBV, vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(8000, new CHBV));
VirtualSMCAPI::addKey(KeyCHLC, vsmcPlugin.data, VirtualSMCAPI::valueWithUint8(1, new CHLC));
for (UInt8 i = 0; i < batCount; i++) {
VirtualSMCAPI::addKey(KeyBC1V(i+1), vsmcPlugin.data, VirtualSMCAPI::valueWithUint16(defaultBatteryCellVoltage, new BC1V(i)));
}
qsort(const_cast(vsmcPlugin.data.data()), vsmcPlugin.data.size(), sizeof(VirtualSMCKeyValue), VirtualSMCKeyValue::compare);
PMinit();
nub->joinPMtree(this);
registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);
vsmcNotifier = VirtualSMCAPI::registerHandler(vsmcNotificationHandler, this);
if (!vsmcNotifier) {
PMstop();
goto exit;
}
registerService();
return true;
exit:
releaseResources();
return false;
}
bool SurfaceBatteryDriver::vsmcNotificationHandler(void *sensors, void *refCon, IOService *vsmc, IONotifier *notifier) {
if (sensors && vsmc) {
auto &plugin = static_cast(sensors)->vsmcPlugin;
auto ret = vsmc->callPlatformFunction(VirtualSMCAPI::SubmitPlugin, true, sensors, &plugin, nullptr, nullptr);
if (ret == kIOReturnSuccess) {
IOLog("SurfaceBatteryDriver::Plugin submitted\n");
return true;
} else
IOLog("SurfaceBatteryDriver::Plugin submission failure %X\n", ret);
}
return false;
}
void SurfaceBatteryDriver::stop(IOService *provider) {
// PMstop();
// releaseResources();
// super::stop(provider);
PANIC("SurfaceBatteryDriver", "called stop!!!");
}
void SurfaceBatteryDriver::releaseResources() {
nub->unregisterBatteryEvent(this);
if (timer) {
timer->cancelTimeout();
timer->disable();
work_loop->removeEventSource(timer);
OSSafeReleaseNULL(timer);
}
if (update_bix) {
update_bix->disable();
work_loop->removeEventSource(update_bix);
OSSafeReleaseNULL(update_bix);
}
if (update_bst) {
update_bst->disable();
work_loop->removeEventSource(update_bst);
OSSafeReleaseNULL(update_bst);
}
OSSafeReleaseNULL(work_loop);
}
IOReturn SurfaceBatteryDriver::setProperties(OSObject *props) {
OSDictionary* dict = OSDynamicCast(OSDictionary, props);
if (!dict)
return kIOReturnError;
OSCollectionIterator* i = OSCollectionIterator::withCollection(dict);
if (i) {
while (OSString* key = OSDynamicCast(OSString, i->getNextObject())) {
if (key->isEqualTo("PerformanceMode")) {
OSNumber *mode = OSDynamicCast(OSNumber, dict->getObject(key));
if (mode) {
UInt32 m = mode->unsigned32BitValue();
LOG("Set performance mode to %d", m);
if (nub->setPerformanceMode(m) != kIOReturnSuccess)
LOG("Set performance mode failed!");
}
}
}
i->release();
}
return kIOReturnSuccess;
}
IOReturn SurfaceBatteryDriver::setPowerState(unsigned long whichState, IOService *device) {
if (device != this)
return kIOReturnInvalid;
if (whichState == 0) {
if (awake) {
awake = false;
bat_missing = false;
timer->cancelTimeout();
timer->disable();
update_bix->disable();
update_bst->disable();
DBG_LOG("Going to sleep");
}
} else {
if (!awake) {
awake = true;
timer->enable();
update_bix->enable();
update_bst->enable();
bix_fail = true;
quick_cnt = BST_UPDATE_QUICK_CNT;
clock_get_uptime(&last_update);
updateBatteryStatus(nullptr, 0);
OSNumber *mode = OSDynamicCast(OSNumber, getProperty("PerformanceMode"));
if (mode) {
UInt32 m = mode->unsigned32BitValue();
if (nub->setPerformanceMode(m) != kIOReturnSuccess)
LOG("Set performance mode failed!");
}
DBG_LOG("Woke up");
}
}
return kIOPMAckImplied;
}
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceBatteryDriver.hpp
================================================
//
// SurfaceBatteryDriver.hpp
// SurfaceBattery
//
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#ifndef SurfaceBatteryDriver_hpp
#define SurfaceBatteryDriver_hpp
#include "BatteryManager.hpp"
#include "../SurfaceSerialHubDevices/SurfaceBatteryNub.hpp"
#define BST_UPDATE_QUICK 1000
#define BST_UPDATE_NORMAL 30000
#define BST_UPDATE_QUICK_CNT 5
class EXPORT SurfaceBatteryDriver : public IOService {
OSDeclareDefaultStructors(SurfaceBatteryDriver)
/**
* Key name index mapping
*/
static constexpr size_t MaxIndexCount = sizeof("0123456789ABCDEF") - 1;
static constexpr const char *KeyIndexes = "0123456789ABCDEF";
/**
* Key name declarations
*/
static constexpr SMC_KEY KeyAC_N = SMC_MAKE_IDENTIFIER('A','C','-','N');
static constexpr SMC_KEY KeyACEN = SMC_MAKE_IDENTIFIER('A','C','E','N');
static constexpr SMC_KEY KeyACFP = SMC_MAKE_IDENTIFIER('A','C','F','P');
static constexpr SMC_KEY KeyACID = SMC_MAKE_IDENTIFIER('A','C','I','D');
static constexpr SMC_KEY KeyACIN = SMC_MAKE_IDENTIFIER('A','C','I','N');
static constexpr SMC_KEY KeyBATP = SMC_MAKE_IDENTIFIER('B','A','T','P');
static constexpr SMC_KEY KeyBBAD = SMC_MAKE_IDENTIFIER('B','B','A','D');
static constexpr SMC_KEY KeyBBIN = SMC_MAKE_IDENTIFIER('B','B','I','N');
static constexpr SMC_KEY KeyBFCL = SMC_MAKE_IDENTIFIER('B','F','C','L');
static constexpr SMC_KEY KeyBNum = SMC_MAKE_IDENTIFIER('B','N','u','m');
static constexpr SMC_KEY KeyBRSC = SMC_MAKE_IDENTIFIER('B','R','S','C');
static constexpr SMC_KEY KeyBSIn = SMC_MAKE_IDENTIFIER('B','S','I','n');
static constexpr SMC_KEY KeyCHBI = SMC_MAKE_IDENTIFIER('C','H','B','I');
static constexpr SMC_KEY KeyCHBV = SMC_MAKE_IDENTIFIER('C','H','B','V');
static constexpr SMC_KEY KeyCHLC = SMC_MAKE_IDENTIFIER('C','H','L','C');
static constexpr SMC_KEY KeyB0AC(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'A','C'); }
static constexpr SMC_KEY KeyB0AV(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'A','V'); }
static constexpr SMC_KEY KeyB0BI(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'B','I'); }
static constexpr SMC_KEY KeyB0CT(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'C','T'); }
static constexpr SMC_KEY KeyB0FC(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'F','C'); }
static constexpr SMC_KEY KeyB0PS(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'P','S'); }
static constexpr SMC_KEY KeyB0RM(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'R','M'); }
static constexpr SMC_KEY KeyB0St(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'S','t'); }
static constexpr SMC_KEY KeyB0TF(size_t i) { return SMC_MAKE_IDENTIFIER('B',KeyIndexes[i],'T','F'); }
static constexpr SMC_KEY KeyD0IR(size_t i) { return SMC_MAKE_IDENTIFIER('D',KeyIndexes[i],'I','R'); }
static constexpr SMC_KEY KeyD0VM(size_t i) { return SMC_MAKE_IDENTIFIER('D',KeyIndexes[i],'V','M'); }
static constexpr SMC_KEY KeyD0VR(size_t i) { return SMC_MAKE_IDENTIFIER('D',KeyIndexes[i],'V','R'); }
static constexpr SMC_KEY KeyD0VX(size_t i) { return SMC_MAKE_IDENTIFIER('D',KeyIndexes[i],'V','X'); }
static constexpr SMC_KEY KeyTB0T(size_t i) { return SMC_MAKE_IDENTIFIER('T','B',KeyIndexes[i],'T'); }
// Keys used in BigSur 10.16 and later
static constexpr SMC_KEY KeyBC1V(size_t i) { return SMC_MAKE_IDENTIFIER('B','C',KeyIndexes[i],'V'); }
/**
* VirtualSMC service registration notifier
*/
IONotifier *vsmcNotifier {nullptr};
VirtualSMCAPI::Plugin vsmcPlugin {
"SurfaceBatteryDriver",
parseModuleVersion(xStringify(MODULE_VERSION)),
VirtualSMCAPI::Version,
};
public:
IOService *probe(IOService *provider, SInt32 *score) override;
bool start(IOService *provider) override;
void stop(IOService *provider) override;
IOReturn setPowerState(unsigned long whichState, IOService * device) override;
IOReturn setProperties(OSObject* props) override;
static bool vsmcNotificationHandler(void *sensors, void *refCon, IOService *vsmc, IONotifier *notifier);
private:
IOWorkLoop* work_loop {nullptr};
IOTimerEventSource* timer {nullptr};
IOInterruptEventSource* update_bix {nullptr};
IOInterruptEventSource* update_bst {nullptr};
SurfaceBatteryNub* nub {nullptr};
bool awake {false};
bool power_connected {true};
bool bix_fail {true};
int quick_cnt {0};
bool bat_missing {false};
bool sync {false};
AbsoluteTime last_update {0};
void eventReceived(SurfaceBatteryNub *sender, SurfaceBatteryEventType type);
void updateBatteryInformation(IOInterruptEventSource *sender, int count);
void updateBatteryStatus(IOInterruptEventSource *sender, int count);
void pollBatteryStatus(IOTimerEventSource* sender);
void releaseResources();
};
#endif /* SurfaceBatteryDriver_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceSMBusController.cpp
================================================
//
// SurfaceSMBusController.cpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#include
#include
#include
#include
#include "SurfaceSMBusController.hpp"
#define super IOSMBusController
OSDefineMetaClassAndStructors(SurfaceSMBusController, IOSMBusController)
bool SurfaceSMBusController::start(IOService *provider) {
workLoop = IOWorkLoop::workLoop();
if (!workLoop) {
IOLog("%s::workLoop allocation failed\n", getName());
return false;
}
requestQueue = OSArray::withCapacity(0);
if (!requestQueue) {
IOLog("%s::requestQueue allocation failure\n", getName());
OSSafeReleaseNULL(workLoop);
return false;
}
if (!super::start(provider)) {
IOLog("%s::parent start failed\n", getName());
OSSafeReleaseNULL(workLoop);
OSSafeReleaseNULL(requestQueue);
return false;
}
setProperty("IOSMBusSmartBatteryManager", kOSBooleanTrue);
setProperty("_SBS", 1, 32);
registerService();
interruptSource = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceSMBusController::handleBatteryCommandsEvent));
if (!interruptSource) {
IOLog("%s::failed to allocate interrupt event\n", getName());
OSSafeReleaseNULL(workLoop);
OSSafeReleaseNULL(requestQueue);
return false;
}
getWorkLoop()->addEventSource(interruptSource);
BatteryManager::getShared()->subscribe(handleACPINotification, this);
return true;
}
void SurfaceSMBusController::setReceiveData(IOSMBusTransaction *transaction, UInt16 valueToWrite) {
transaction->receiveDataCount = sizeof(UInt16);
UInt16 *ptr = reinterpret_cast(transaction->receiveData);
*ptr = valueToWrite;
}
IOSMBusStatus SurfaceSMBusController::startRequest(IOSMBusRequest *request) {
auto result = super::startRequest(request);
if (result != kIOSMBusStatusOK)
return result;
IOSMBusTransaction *transaction = request->transaction;
if (transaction) {
transaction->status = kIOSMBusStatusOK;
UInt32 valueToWrite = 0;
if (transaction->address == kSMBusManagerAddr && transaction->protocol == kIOSMBusProtocolReadWord) {
switch (transaction->command) {
case kMStateContCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
valueToWrite = BatteryManager::getShared()->externalPowerConnected() ? kMACPresentBit : 0;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, valueToWrite);
break;
}
case kMStateCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
if (BatteryManager::getShared()->batteriesConnected()) {
valueToWrite = kMPresentBatt_A_Bit;
if ((BatteryManager::getShared()->state.btInfo[0].state.state & SurfaceBattery::BSTStateMask) == SurfaceBattery::BSTCharging)
valueToWrite |= kMChargingBatt_A_Bit;
}
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, valueToWrite);
break;
}
default: {
// Nothing should be done here since AppleSmartBattery always calls bzero fo transaction
// Let's also not set transaction status to error value since it can be an unknown command
break;
}
}
}
if (transaction->address == kSMBusBatteryAddr && transaction->protocol == kIOSMBusProtocolReadWord) {
//FIXME: maybe the incoming data show us which battery is queried about? Or it's in the address?
switch (transaction->command) {
case kBBatteryStatusCmd: {
setReceiveData(transaction, BatteryManager::getShared()->calculateBatteryStatus(0));
break;
}
case kBManufacturerAccessCmd: {
if (transaction->sendDataCount == 2 &&
(transaction->sendData[0] == kBExtendedPFStatusCmd ||
transaction->sendData[0] == kBExtendedOperationStatusCmd)) {
// AppleSmartBatteryManager ignores these values.
setReceiveData(transaction, 0);
}
//CHECKME: Should else case be handled?
break;
}
case kBPackReserveCmd:
case kBDesignCycleCount9CCmd: {
setReceiveData(transaction, 1000);
break;
}
case kBReadCellVoltage1Cmd:
case kBReadCellVoltage2Cmd:
case kBReadCellVoltage3Cmd:
case kBReadCellVoltage4Cmd: {
setReceiveData(transaction, defaultBatteryCellVoltage);
break;
}
case kBVoltageCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.presentVoltage;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBCurrentCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.signedPresentRate;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBAverageCurrentCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.signedAverageRate;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBSerialNumberCmd:
case kBMaxErrorCmd:
break;
case kBRunTimeToEmptyCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.runTimeToEmpty;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBAverageTimeToEmptyCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.averageTimeToEmpty;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBTemperatureCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.temperatureDecikelvin;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBDesignCapacityCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].designCapacity;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBCycleCountCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].cycle;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBAverageTimeToFullCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.timeToFull;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBRemainingCapacityCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.remainingCapacity;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBFullChargeCapacityCmd: {
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
auto value = BatteryManager::getShared()->state.btInfo[0].state.lastFullChargeCapacity;
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
setReceiveData(transaction, value);
break;
}
case kBManufactureDateCmd: {
UInt16 value = 0;
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
if (BatteryManager::getShared()->state.btInfo[0].manufactureDate) {
value = BatteryManager::getShared()->state.btInfo[0].manufactureDate;
} else {
strncpy(reinterpret_cast(transaction->receiveData), BatteryManager::getShared()->state.btInfo[0].serial, kSMBusMaximumDataSize);
transaction->receiveData[kSMBusMaximumDataSize-1] = '\0';
}
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
if (!value) {
const char* p = reinterpret_cast(transaction->receiveData);
bool found = false;
int year = 2016, month = 02, day = 29;
while ((p = strstr(p, "20")) != nullptr) { // hope that this code will not survive until 22nd century
if (sscanf(p, "%04d%02d%02d", &year, &month, &day) == 3 || // YYYYMMDD (Lenovo)
sscanf(p, "%04d/%02d/%02d", &year, &month, &day) == 3) { // YYYY/MM/DD (HP)
if (1 <= month && month <= 12 && 1 <= day && day <= 31) {
found = true;
break;
}
}
p++;
}
if (!found) { // in case we parsed a non-date
year = 2016;
month = 02;
day = 29;
}
value = makeBatteryDate(day, month, year);
}
setReceiveData(transaction, value);
break;
}
//CHECKME: Should there be a default setting receiveDataCount to 0 or status failure?
}
}
if (transaction->address == kSMBusBatteryAddr &&
transaction->protocol == kIOSMBusProtocolWriteWord &&
transaction->command == kBManufacturerAccessCmd) {
if (transaction->sendDataCount == 2 && (transaction->sendData[0] == kBExtendedPFStatusCmd || transaction->sendData[0] == kBExtendedOperationStatusCmd)) {
// Nothing can be done here since we don't write any values to hardware, we fake response for this command in handler for
// kIOSMBusProtocolReadWord/kBManufacturerAccessCmd. Anyway, AppleSmartBattery::transactionCompletion ignores this response.
// If we can see this log statement, it means that fields sendDataCount and sendData have a proper offset in IOSMBusTransaction
}
}
if (transaction->address == kSMBusBatteryAddr && transaction->protocol == kIOSMBusProtocolReadBlock) {
switch (transaction->command) {
case kBManufacturerNameCmd: {
transaction->receiveDataCount = kSMBusMaximumDataSize;
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
strncpy(reinterpret_cast(transaction->receiveData), BatteryManager::getShared()->state.btInfo[0].manufacturer, kSMBusMaximumDataSize);
transaction->receiveData[kSMBusMaximumDataSize-1] = '\0';
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
break;
}
case kBAppleHardwareSerialCmd:
transaction->receiveDataCount = kSMBusMaximumDataSize;
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
strncpy(reinterpret_cast(transaction->receiveData), BatteryManager::getShared()->state.btInfo[0].serial, kSMBusMaximumDataSize);
transaction->receiveData[kSMBusMaximumDataSize-1] = '\0';
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
break;
case kBDeviceNameCmd:
transaction->receiveDataCount = kSMBusMaximumDataSize;
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
strncpy(reinterpret_cast(transaction->receiveData), BatteryManager::getShared()->state.btInfo[0].deviceName, kSMBusMaximumDataSize);
transaction->receiveData[kSMBusMaximumDataSize-1] = '\0';
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
break;
case kBManufacturerDataCmd:
transaction->receiveDataCount = sizeof(BatteryInfo::BatteryManufacturerData);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
memcpy(reinterpret_cast(transaction->receiveData), &BatteryManager::getShared()->state.btInfo[0].batteryManufacturerData, sizeof(BatteryInfo::BatteryManufacturerData));
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
break;
case kBManufacturerInfoCmd:
break;
// Let other commands slip if any.
// receiveDataCount is already 0, and status failure results in retries - it's not what we want.
}
}
}
if (!requestQueue->setObject(request)) {
IOLog("%s::startRequest failed to append a request\n", getName());
return kIOSMBusStatusUnknownFailure;
}
interruptSource->interruptOccurred(nullptr, this, 0);
IOSimpleLockLock(BatteryManager::getShared()->stateLock);
clock_get_uptime(&BatteryManager::getShared()->lastAccess);
IOSimpleLockUnlock(BatteryManager::getShared()->stateLock);
return result;
}
void SurfaceSMBusController::handleBatteryCommandsEvent(IOInterruptEventSource *sender, int count) {
// requestQueue contains objects owned by two parties:
// 1. requestQueue itself, as the addition of any object retains it
// 2. IOSMBusController, since it does not release the object after passing it
// to us in IOSMBusController::performTransactionGated.
// OSArray::removeObject takes away our ownership, and then
// IOSMBusController::completeRequest releases the request inside.
while (requestQueue->getCount() != 0) {
auto request = OSDynamicCast(IOSMBusRequest, requestQueue->getObject(0));
requestQueue->removeObject(0);
if (request != nullptr)
completeRequest(request);
}
}
IOReturn SurfaceSMBusController::handleACPINotification(void *target) {
SurfaceSMBusController *self = static_cast(target);
if (self) {
auto &bmgr = *BatteryManager::getShared();
// TODO: when we have multiple batteries, handle insertion or removal of a single battery
IOSimpleLockLock(bmgr.stateLock);
bool batteriesConnected = bmgr.batteriesConnected();
bool adaptersConnected = bmgr.adaptersConnected();
self->prevBatteriesConnected = batteriesConnected;
self->prevAdaptersConnected = adaptersConnected;
IOSimpleLockUnlock(bmgr.stateLock);
UInt8 data[] = {kBMessageStatusCmd, batteriesConnected};
self->messageClients(kIOMessageSMBusAlarm, data, arrsize(data));
return kIOReturnSuccess;
}
return kIOReturnBadArgument;
}
================================================
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceSMBusController.hpp
================================================
//
// SurfaceSMBusController.hpp
// SurfaceBattery
//
// Copyright © 2018 usrsse2. All rights reserved.
//
#ifndef SurfaceSMBusController_hpp
#define SurfaceSMBusController_hpp
#include
#include
#include
#include "BatteryManager.hpp"
class EXPORT SurfaceSMBusController : public IOSMBusController {
OSDeclareDefaultStructors(SurfaceSMBusController)
/**
* This is here to avoid collisions in case of future expansion of IOSMBusController class.
* WARNING! It is important that this is the first member of the class!
*/
void *reserved[8] {};
/**
Set received data for a transaction to a 16-bit integer value
@param transaction SMBus transaction
@param valueToWrite Value to write
*/
static void setReceiveData(IOSMBusTransaction *transaction, UInt16 valueToWrite);
/**
* A workloop in charge of handling timer events with requests.
*/
IOWorkLoop *workLoop {nullptr};
/**
* Event source for processing requests.
*/
IOInterruptEventSource *interruptSource {nullptr};
/**
* Registered SMBus requests.
*/
OSArray *requestQueue {nullptr};
/**
* Create battery date in AppleSmartBattery format
*
* @param day manufacturing date
* @param month manufacturing month
* @param year manufacturing year
*
* @return date in AppleSmartBattery format
*/
static constexpr UInt16 makeBatteryDate(UInt16 day, UInt16 month, UInt16 year) {
return (day & 0x1FU) | ((month & 0xFU) << 5U) | (((year - 1980U) & 0x7FU) << 9U);
}
public:
/**
* Start the driver by setting up the workloop and preparing the matching.
*
* @param provider parent IOService object
*
* @return true on success
*/
bool start(IOService *provider) override;
/**
* Handle external notification from Surface battery instance
*
* @param target SurfaceSMBusController instance
*
* @return kIOReturnSuccess
*/
static IOReturn handleACPINotification(void *target);
protected:
/**
* Returns the current work loop.
* We should properly override this, as our provider has no work loop.
*
* @return current workloop for request handling.
*/
IOWorkLoop *getWorkLoop() const override {
return workLoop;
}
/**
* Request handling routine used for handling battery commands.
*
* @param request request to handle
*
* @return request handling result.
*/
IOSMBusStatus startRequest(IOSMBusRequest *request) override;
/**
* handle queued AppleSmartBatteryManager SMBus requests.
*/
void handleBatteryCommandsEvent(IOInterruptEventSource *sender, int count);
/**
* Holds value of batteriesConnected() when the previous notification was sent, must be guarded by stateLock
*
* @return true on success
*/
bool prevBatteriesConnected {false};
/**
* Holds value of adaptersConnected() when the previous notification was sent, must be guarded by stateLock
*
* @return true on success
*/
bool prevAdaptersConnected {false};
};
#endif /* SurfaceSMBusController_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceButton/HIDReport.hpp
================================================
//
// HIDReport.hpp
// SurfaceButtonDriver
//
// Copyright © 2019 Le Bao Hiep. All rights reserved.
//
class __attribute__((packed)) keys final {
public:
keys(void) : keys_{} {}
const UInt8(&get_raw_value(void) const)[32] {
return keys_;
}
bool empty(void) const {
for (const auto& k : keys_) {
if (k != 0) {
return false;
}
}
return true;
}
void clear(void) {
memset(keys_, 0, sizeof(keys_));
}
void insert(UInt8 key) {
if (!exists(key)) {
for (auto&& k : keys_) {
if (k == 0) {
k = key;
return;
}
}
}
}
void erase(UInt8 key) {
for (auto&& k : keys_) {
if (k == key) {
k = 0;
}
}
}
bool exists(UInt8 key) const {
for (const auto& k : keys_) {
if (k == key) {
return true;
}
}
return false;
}
size_t count(void) const {
size_t result = 0;
for (const auto& k : keys_) {
if (k) {
++result;
}
}
return result;
}
bool operator==(const keys& other) const { return (memcmp(this, &other, sizeof(*this)) == 0); }
bool operator!=(const keys& other) const { return !(*this == other); }
private:
UInt8 keys_[32];
};
class __attribute__((packed)) consumer_input final {
public:
consumer_input(void) : report_id_(2) {}
bool operator==(const consumer_input& other) const { return (memcmp(this, &other, sizeof(*this)) == 0); }
bool operator!=(const consumer_input& other) const { return !(*this == other); }
private:
UInt8 report_id_ __attribute__((unused));
public:
keys keys;
};
================================================
FILE: BigSurface/BigSurface/SurfaceButton/SurfaceButtonDevice.cpp
================================================
//
// SurfaceButtonDevice.cpp
// SurfaceButton
//
// Copyright © 2018-2020 Le Bao Hiep. All rights reserved.
//
#include "SurfaceButtonDevice.hpp"
#define super IOHIDDevice
OSDefineMetaClassAndStructors(SurfaceButtonDevice, super);
const UInt8 virt_reportDescriptor[] = {
0x05, 0x0c, // Usage Page (Consumer)
0x09, 0x01, // Usage 1 (kHIDUsage_Csmr_ConsumerControl)
0xa1, 0x01, // Collection (Application)
0x85, 0x02, // Report Id (2)
0x05, 0x0c, // Usage Page (Consumer)
0x95, 0x20, // Report Count............ (32)
0x75, 0x08, // Report Size............. (8)
0x15, 0x00, // Logical Minimum......... (0)
0x26, 0xff, 0x00, // Logical Maximum......... (255)
0x19, 0x00, // Usage Minimum........... (0)
0x29, 0xff, // Usage Maximum........... (255)
0x81, 0x00, // Input...................(Data, Array, Absolute)
0xc0, // End Collection
};
IOReturn SurfaceButtonDevice::simulateKeyboardEvent(UInt32 usagePage, UInt32 usage, bool status) {
IOReturn result = kIOReturnError;
if (usagePage == kHIDPage_Consumer) {
if (status)
csmrreport.keys.insert(usage);
else
csmrreport.keys.erase(usage);
if (auto buffer = IOBufferMemoryDescriptor::withBytes(&csmrreport, sizeof(csmrreport), kIODirectionNone)) {
result = handleReport(buffer, kIOHIDReportTypeInput, kIOHIDOptionsTypeNone);
OSSafeReleaseNULL(buffer);
}
} else
result = kIOReturnBadArgument;
return result;
}
bool SurfaceButtonDevice::handleStart(IOService *provider) {
if (!super::handleStart(provider)) {
return false;
}
setProperty("Built-In", kOSBooleanTrue);
setProperty("HIDDefaultBehavior", kOSBooleanTrue);
return true;
}
IOReturn SurfaceButtonDevice::newReportDescriptor(IOMemoryDescriptor **descriptor) const {
*descriptor = IOBufferMemoryDescriptor::withBytes(virt_reportDescriptor, sizeof(virt_reportDescriptor), kIODirectionNone);
return kIOReturnSuccess;
}
OSString *SurfaceButtonDevice::newManufacturerString() const {
return OSString::withCString("Microsoft Inc.");
}
OSString *SurfaceButtonDevice::newProductString() const {
return OSString::withCString("Surface Button HID Device");
}
OSNumber *SurfaceButtonDevice::newVendorIDNumber() const {
return OSNumber::withNumber(0x5ac, 32);
}
OSNumber *SurfaceButtonDevice::newProductIDNumber() const {
return OSNumber::withNumber(0x276, 32);
}
OSNumber *SurfaceButtonDevice::newLocationIDNumber() const {
return OSNumber::withNumber(0x14400000, 32);
}
OSNumber *SurfaceButtonDevice::newCountryCodeNumber() const {
return OSNumber::withNumber(0x21, 32);
}
OSNumber *SurfaceButtonDevice::newVersionNumber() const {
return OSNumber::withNumber(0x895, 32);
}
OSNumber *SurfaceButtonDevice::newPrimaryUsagePageNumber() const {
return OSNumber::withNumber(kHIDPage_Consumer, 32);
}
OSNumber *SurfaceButtonDevice::newPrimaryUsageNumber() const {
return OSNumber::withNumber(kHIDUsage_Csmr_ConsumerControl, 32);
}
================================================
FILE: BigSurface/BigSurface/SurfaceButton/SurfaceButtonDevice.hpp
================================================
//
// SurfaceButtonDevice.hpp
// SurfaceButton
//
// Copyright © 2018-2020 Le Bao Hiep. All rights reserved.
//
#include
#include "HIDReport.hpp"
class SurfaceButtonDevice final : public IOHIDDevice {
OSDeclareDefaultStructors(SurfaceButtonDevice);
private:
consumer_input csmrreport;
public:
IOReturn simulateKeyboardEvent(UInt32 usagePage, UInt32 usage, bool status);
bool handleStart(IOService *provider) override;
IOReturn newReportDescriptor(IOMemoryDescriptor **descriptor) const override;
OSString *newManufacturerString() const override;
OSString *newProductString() const override;
OSNumber *newVendorIDNumber() const override;
OSNumber *newProductIDNumber() const override;
OSNumber *newLocationIDNumber() const override;
OSNumber *newCountryCodeNumber() const override;
OSNumber *newVersionNumber() const override;
OSNumber *newPrimaryUsagePageNumber() const override;
OSNumber *newPrimaryUsageNumber() const override;
};
================================================
FILE: BigSurface/BigSurface/SurfaceButton/SurfaceButtonDriver.cpp
================================================
//
// SurfaceButtonDriver.hpp
// SurfaceButton
//
// Created by Xavier on 22/03/2021.
// Copyright © 2021 Xia Shangning. All rights reserved.
//
#include "SurfaceButtonDriver.hpp"
#define super IOService
OSDefineMetaClassAndStructors(SurfaceButtonDriver, IOService)
VoodooGPIO* SurfaceButtonDriver::getGPIOController() {
VoodooGPIO* gpio_controller = NULL;
// Wait for GPIO controller, up to 1 second
OSDictionary* name_match = serviceMatching("VoodooGPIO");
IOService* matched = waitForMatchingService(name_match, 1000000000);
gpio_controller = OSDynamicCast(VoodooGPIO, matched);
if (gpio_controller != NULL)
DBG_LOG("Got GPIO Controller! %s", gpio_controller->getName());
OSSafeReleaseNULL(name_match);
OSSafeReleaseNULL(matched);
return gpio_controller;
}
IOReturn SurfaceButtonDriver::parseButtonResources(VoodooACPIResourcesParser* parser1, VoodooACPIResourcesParser* parser2, VoodooACPIResourcesParser* parser3) {
OSObject *result = nullptr;
OSData *data = nullptr;
if (acpi_device->evaluateObject("_CRS", &result) != kIOReturnSuccess ||
!(data = OSDynamicCast(OSData, result))) {
LOG("Could not find or evaluate _CRS method");
OSSafeReleaseNULL(result);
return kIOReturnNotFound;
}
// There are three GPIO buttons so the CRS function returns in total 6 resources, GpioInt & GpioIo for each
UInt8 const* crs = reinterpret_cast(data->getBytesNoCopy());
unsigned int length = data->getLength();
UInt32 offset = parser1->parseACPIResources(crs, 0, length);
offset = parser2->parseACPIResources(crs, offset, length);
parser3->parseACPIResources(crs, offset, length);
OSSafeReleaseNULL(data);
return kIOReturnSuccess;
}
IOReturn SurfaceButtonDriver::getDeviceResources() {
VoodooACPIResourcesParser parser1, parser2, parser3;
parseButtonResources(&parser1, &parser2, &parser3);
if (parser1.found_gpio_interrupts && parser2.found_gpio_interrupts && parser3.found_gpio_interrupts) {
DBG_LOG("Found valid GPIO interrupts");
// Power Button, Volume Up Button, Volume Down Button
setProperty("powerBtnGPIOPin", parser1.gpio_interrupts.pin_number, 16);
setProperty("powerBtnGPIOIRQ", parser1.gpio_interrupts.irq_type, 16);
gpio_pin[POWER_BUTTON_IDX] = parser1.gpio_interrupts.pin_number;
gpio_irq[POWER_BUTTON_IDX] = parser1.gpio_interrupts.irq_type;
setProperty("volUpBtnGPIOPin", parser2.gpio_interrupts.pin_number, 16);
setProperty("volUpBtnGPIOIRQ", parser2.gpio_interrupts.irq_type, 16);
gpio_pin[VOLUME_UP_BUTTON_IDX] = parser2.gpio_interrupts.pin_number;
gpio_irq[VOLUME_UP_BUTTON_IDX] = parser2.gpio_interrupts.irq_type;
setProperty("volDownBtnGPIOPin", parser3.gpio_interrupts.pin_number, 16);
setProperty("volDownBtnGPIOIRQ", parser3.gpio_interrupts.irq_type, 16);
gpio_pin[VOLUME_DOWN_BUTTON_IDX] = parser3.gpio_interrupts.pin_number;
gpio_irq[VOLUME_DOWN_BUTTON_IDX] = parser3.gpio_interrupts.irq_type;
return kIOReturnSuccess;
}else{
LOG("GPIO interrupts missing!");
return kIOReturnError;
}
}
void SurfaceButtonDriver::powerInterruptOccured(IOInterruptEventSource* src, int intCount) {
response(POWER_BUTTON_IDX, intCount % 2);
}
void SurfaceButtonDriver::volumeUpInterruptOccured(IOInterruptEventSource* src, int intCount) {
if (!awake)
return;
stopInterrupt(VOLUME_DOWN_BUTTON_IDX);
bool button_status = gpio_controller->getPinStatus(gpio_pin[VOLUME_UP_BUTTON_IDX]);
response(VOLUME_UP_BUTTON_IDX, button_status);
startInterrupt(VOLUME_DOWN_BUTTON_IDX);
}
void SurfaceButtonDriver::volumeDownInterruptOccured(IOInterruptEventSource* src, int intCount) {
if (!awake)
return;
stopInterrupt(VOLUME_UP_BUTTON_IDX);
bool button_status = gpio_controller->getPinStatus(gpio_pin[VOLUME_DOWN_BUTTON_IDX]);
response(VOLUME_DOWN_BUTTON_IDX, button_status);
startInterrupt(VOLUME_UP_BUTTON_IDX);
}
void SurfaceButtonDriver::response(int btn_idx, bool status) {
if (btn_idx >= BTN_CNT)
return;
if (btn_idx == POWER_BUTTON_IDX) {
// mannually maintain the power button status(pin status always return true)
if (status)
btn_status[btn_idx] = !btn_status[btn_idx];
} else
btn_status[btn_idx] = status;
DBG_LOG("%s %s!", BTN_DESCRIPTION[btn_idx], btn_status[btn_idx]?"pressed":"released");
button_device->simulateKeyboardEvent(BTN_CMD_PAGE[btn_idx], BTN_CMD[btn_idx], btn_status[btn_idx]);
}
IOService *SurfaceButtonDriver::probe(IOService *provider, SInt32 *score){
if (!super::probe(provider, score))
return nullptr;
acpi_device = OSDynamicCast(IOACPIPlatformDevice, provider);
if (!acpi_device)
return nullptr;
if (getDeviceResources() != kIOReturnSuccess) {
LOG("Could not parse GPIO infos");
return nullptr;
}
gpio_controller = getGPIOController();
if (!gpio_controller) {
LOG("Could not find GPIO controller, exiting");
return nullptr;
}
// Give the GPIO controller some time to load
IOSleep(100);
LOG("Surface ACPI button device found!");
return this;
}
bool SurfaceButtonDriver::start(IOService *provider) {
if (!super::start(provider))
return false;
work_loop = IOWorkLoop::workLoop();
if (!work_loop) {
LOG("Could not get work loop");
goto exit;
}
interrupt_source[POWER_BUTTON_IDX] = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceButtonDriver::powerInterruptOccured), this, POWER_BUTTON_IDX);
interrupt_source[VOLUME_UP_BUTTON_IDX] = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceButtonDriver::volumeUpInterruptOccured), this, VOLUME_UP_BUTTON_IDX);
interrupt_source[VOLUME_DOWN_BUTTON_IDX] = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceButtonDriver::volumeDownInterruptOccured), this, VOLUME_DOWN_BUTTON_IDX);
if (!interrupt_source[POWER_BUTTON_IDX] || !interrupt_source[VOLUME_UP_BUTTON_IDX] || !interrupt_source[VOLUME_DOWN_BUTTON_IDX]) {
LOG("Could not create interrupt event source");
goto exit;
}
work_loop->addEventSource(interrupt_source[POWER_BUTTON_IDX]);
work_loop->addEventSource(interrupt_source[VOLUME_UP_BUTTON_IDX]);
work_loop->addEventSource(interrupt_source[VOLUME_DOWN_BUTTON_IDX]);
button_device = OSTypeAlloc(SurfaceButtonDevice);
if (!button_device || !button_device->init() || !button_device->attach(this) || !button_device->start(this)) {
LOG("Failed to init and start Surface Button HID Device!");
goto exit;
}
PMinit();
acpi_device->joinPMtree(this);
registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);
return true;
exit:
releaseResources();
return false;
}
void SurfaceButtonDriver::stop(IOService *provider) {
PMstop();
releaseResources();
super::stop(provider);
}
IOReturn SurfaceButtonDriver::setPowerState(unsigned long whichState, IOService *whatDevice) {
if (whatDevice != this)
return kIOReturnInvalid;
if (whichState == 0) {
if (awake) {
stopInterrupt(POWER_BUTTON_IDX);
stopInterrupt(VOLUME_UP_BUTTON_IDX);
stopInterrupt(VOLUME_DOWN_BUTTON_IDX);
DBG_LOG("Going to sleep");
awake = false;
}
} else {
if (!awake) {
awake = true;
IOSleep(100); // Wait for SSH to notify d0-entry and display-on
startInterrupt(POWER_BUTTON_IDX);
startInterrupt(VOLUME_UP_BUTTON_IDX);
startInterrupt(VOLUME_DOWN_BUTTON_IDX);
DBG_LOG("Woke up");
}
}
return kIOPMAckImplied;
}
IOReturn SurfaceButtonDriver::enableInterrupt(int source) {
return gpio_controller->enableInterrupt(gpio_pin[source]);
}
IOReturn SurfaceButtonDriver::disableInterrupt(int source) {
return gpio_controller->disableInterrupt(gpio_pin[source]);
}
IOReturn SurfaceButtonDriver::getInterruptType(int source, int* interrupt_type) {
return gpio_controller->getInterruptType(gpio_pin[source], interrupt_type);
}
IOReturn SurfaceButtonDriver::registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refcon) {
gpio_controller->setInterruptTypeForPin(gpio_pin[source], gpio_irq[source]);
return gpio_controller->registerInterrupt(gpio_pin[source], target, handler, refcon);
}
IOReturn SurfaceButtonDriver::unregisterInterrupt(int source) {
return gpio_controller->unregisterInterrupt(gpio_pin[source]);
}
void SurfaceButtonDriver::startInterrupt(int source) {
if (is_interrupt_started[source])
return;
interrupt_source[source]->enable();
is_interrupt_started[source] = true;
}
void SurfaceButtonDriver::stopInterrupt(int source) {
if (!is_interrupt_started[source])
return;
interrupt_source[source]->disable();
is_interrupt_started[source] = false;
}
void SurfaceButtonDriver::releaseResources() {
if (interrupt_source[POWER_BUTTON_IDX]) {
stopInterrupt(POWER_BUTTON_IDX);
work_loop->removeEventSource(interrupt_source[POWER_BUTTON_IDX]);
OSSafeReleaseNULL(interrupt_source[POWER_BUTTON_IDX]);
}
if (interrupt_source[VOLUME_UP_BUTTON_IDX]) {
stopInterrupt(VOLUME_UP_BUTTON_IDX);
work_loop->removeEventSource(interrupt_source[VOLUME_UP_BUTTON_IDX]);
OSSafeReleaseNULL(interrupt_source[VOLUME_UP_BUTTON_IDX]);
}
if (interrupt_source[VOLUME_DOWN_BUTTON_IDX]) {
stopInterrupt(VOLUME_DOWN_BUTTON_IDX);
work_loop->removeEventSource(interrupt_source[VOLUME_DOWN_BUTTON_IDX]);
OSSafeReleaseNULL(interrupt_source[VOLUME_DOWN_BUTTON_IDX]);
}
OSSafeReleaseNULL(work_loop);
OSSafeReleaseNULL(button_device);
}
================================================
FILE: BigSurface/BigSurface/SurfaceButton/SurfaceButtonDriver.hpp
================================================
//
// SurfaceButtonDriver.hpp
// SurfaceButton
//
// Created by Xavier on 22/03/2021.
// Copyright © 2021 Xia Shangning. All rights reserved.
//
#ifndef SurfaceButtonDriver_hpp
#define SurfaceButtonDriver_hpp
#include
#include "../../../Dependencies/VoodooGPIO/VoodooGPIO/VoodooGPIO.hpp"
#include "../../../Dependencies/VoodooSerial/VoodooSerial/ACPIParser/VoodooACPIResourcesParser.hpp"
#include "../helpers.hpp"
#include "SurfaceButtonDevice.hpp"
#define BTN_CNT 3
#define POWER_BUTTON_IDX 0
#define VOLUME_UP_BUTTON_IDX 1
#define VOLUME_DOWN_BUTTON_IDX 2
const char *BTN_DESCRIPTION[BTN_CNT] = {"Power Button", "Volume Up Button", "Volume Down Button"};
const UInt32 BTN_CMD[BTN_CNT] = {kHIDUsage_Csmr_Power, kHIDUsage_Csmr_VolumeIncrement, kHIDUsage_Csmr_VolumeDecrement};
const UInt32 BTN_CMD_PAGE[BTN_CNT] = {kHIDPage_Consumer, kHIDPage_Consumer, kHIDPage_Consumer};
class EXPORT SurfaceButtonDriver : public IOService {
OSDeclareDefaultStructors(SurfaceButtonDriver);
private:
IOWorkLoop* work_loop {nullptr};
VoodooGPIO* gpio_controller {nullptr};
IOInterruptEventSource* interrupt_source[BTN_CNT] = {nullptr, nullptr, nullptr};
IOACPIPlatformDevice* acpi_device {nullptr};
SurfaceButtonDevice* button_device {nullptr};
bool is_interrupt_started[BTN_CNT] = {false, false, false};
bool btn_status[BTN_CNT] = {false, false, false};
int gpio_irq[BTN_CNT] = {0,0,0};
UInt16 gpio_pin[BTN_CNT] = {0,0,0};
bool awake {false};
void startInterrupt(int source);
void stopInterrupt(int source);
void releaseResources();
IOReturn getDeviceResources();
IOReturn parseButtonResources(VoodooACPIResourcesParser* parser1, VoodooACPIResourcesParser* parser2, VoodooACPIResourcesParser* parser3);
VoodooGPIO* getGPIOController();
void powerInterruptOccured(IOInterruptEventSource* src, int intCount);
void volumeUpInterruptOccured(IOInterruptEventSource* src, int intCount);
void volumeDownInterruptOccured(IOInterruptEventSource* src, int intCount);
void response(int btn_idx, bool status);
public:
IOReturn enableInterrupt(int source) override;
IOReturn disableInterrupt(int source) override;
IOReturn getInterruptType(int source, int *interruptType) override;
IOReturn registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refcon) override;
IOReturn unregisterInterrupt(int source) override;
IOService* probe(IOService* provider, SInt32* score) override;
bool start(IOService* provider) override;
void stop(IOService* provider) override;
IOReturn setPowerState(unsigned long whichState, IOService *whatDevice) override;
};
#endif
================================================
FILE: BigSurface/BigSurface/SurfaceManagementEngine/MEIProtocol.h
================================================
//
// MEIProtocol.h
// SurfaceTouchScreen
//
// Created by Xavier on 2022/5/29.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#ifndef MEIProtocol_h
#define MEIProtocol_h
#include "../helpers.hpp"
/*
* IPTS MEI constants and communication protocol ported from linux
*/
/* Host Firmware Status Registers in PCI Config Space */
#define MEI_PCI_CFG_1 0x40
#define MEI_PCI_CFG_1_D0I3 0x80000000
/* MEI registers */
#define MEI_H_CB_WW 0x00 /* Host Circular Buffer Write Window register */
#define MEI_H_CSR 0x04 /* Host Control Status register */
#define MEI_ME_CB_RW 0x08 /* ME Circular Buffer Read Window register */
#define MEI_ME_CSR 0x0C /* ME Control Status Host Access register */
#define MEI_H_PG_CSR 0x10 /* Host Power Gate Control Status register */
#define MEI_H_D0I3C 0x800 /* Host D0I3 Control */
/* Control Status register bits for Host and ME */
#define MEI_CSR_BUF_DEPTH 0xFF000000 /* Circular Buffer Depth */
#define MEI_CSR_BUF_WPOINTER 0x00FF0000 /* Circular Buffer Write Pointer */
#define MEI_CSR_BUF_RPOINTER 0x0000FF00 /* Circular Buffer Read Pointer */
/* Host Control Status register bits */
#define MEI_H_CSR_INT_ENABLE BIT(0) /* Interrupt Enable */
#define MEI_H_CSR_INT_STA BIT(1) /* Interrupt Status */
#define MEI_H_CSR_INT_GEN BIT(2) /* Interrupt Generate */
#define MEI_H_CSR_READY BIT(3) /* Ready */
#define MEI_H_CSR_RESET BIT(4) /* Reset */
#define MEI_H_CSR_D0I3C_INT_ENABLE BIT(5) /* D0I3 Interrupt Enable */
#define MEI_H_CSR_D0I3C_INT_STA BIT(6) /* D0I3 Interrupt Status */
#define MEI_H_CSR_INT_ENABLE_MASK (MEI_H_CSR_INT_ENABLE | MEI_H_CSR_D0I3C_INT_ENABLE)
#define MEI_H_CSR_INT_STA_MASK (MEI_H_CSR_INT_STA | MEI_H_CSR_D0I3C_INT_STA)
/* ME Control Status Host Access register bits */
#define MEI_ME_CSR_INT_ENABLE BIT(0) /* Interrupt Enable */
#define MEI_ME_CSR_INT_STA BIT(1) /* Interrupt Status */
#define MEI_ME_CSR_INT_GEN BIT(2) /* Interrupt Generate */
#define MEI_ME_CSR_READY BIT(3) /* Ready */
#define MEI_ME_CSR_RESET BIT(4) /* Reset */
#define MEI_ME_CSR_POWER_GATE_ISO_CAP BIT(6) /* Power Gate Isolation Capability */
/* Host Power Gate Control Status register bits */
#define MEI_H_HPG_CSR_POWER_GATING_EXIT BIT(0)
#define MEI_H_HPG_CSR_POWER_GATING_ENTER BIT(1)
/* Host D0I3C register bits */
#define MEI_H_D0I3C_CIP BIT(0)
#define MEI_H_D0I3C_IR BIT(1)
#define MEI_H_D0I3C_I3 BIT(2)
#define MEI_H_D0I3C_RR BIT(3)
#define MEI_SLOT_SIZE sizeof(UInt32)
#define MEI_SLOT_TYPE UInt32
#define MEI_RX_MSG_BUF_SIZE (128 * MEI_SLOT_SIZE)
#define MEI_DATA_TO_SLOTS(len) (((len)+MEI_SLOT_SIZE-1)/MEI_SLOT_SIZE)
#define MEI_SLOTS_TO_DATA(slots) ((slots) * MEI_SLOT_SIZE)
#define MEI_MAX_CLIENT_NUM 256 /* SHOULD be dividable by 8 */
#define MEI_MAX_CONSEC_RESET 3
#ifndef PACKED
#define PACKED __attribute__((packed))
#endif
/* Timeouts in Seconds */
#define MEI_HW_READY_TIMEOUT 2 /* Timeout on ready message */
#define MEI_CONNECT_TIMEOUT 3 /* HPS: at least 2 seconds */
#define MEI_CLIENT_CONNECT_TIMEOUT 15 /* HPS: Client Connect Timeout */
#define MEI_CLIENTS_INIT_TIMEOUT 15 /* HPS: Clients Enumeration Timeout */
#define MEI_POWER_GATING_ISO_TIMEOUT 1 /* PG Isolation time response 1 sec */
#define MEI_D0I3_TIMEOUT 5 /* D0i3 set/unset max response time */
#define MEI_HOST_BUS_MSG_TIMEOUT 1 /* 1 second */
#define MEI_DEVICE_IDLE_TIMEOUT 5
#define MEI_CLIENT_SEND_MSG_TIMEOUT 500 /* 500 ms*/
/*
* MEI Version
*/
#define MEI_HBM_MINOR_VERSION 2
#define MEI_HBM_MAJOR_VERSION 2
/*
* MEI version with PGI support
*/
#define MEI_HBM_MINOR_VERSION_PGI 1
#define MEI_HBM_MAJOR_VERSION_PGI 1
/*
* MEI version with Dynamic clients support
*/
#define MEI_HBM_MINOR_VERSION_DC 0
#define MEI_HBM_MAJOR_VERSION_DC 2
/*
* MEI version with immediate reply to enum request support
*/
#define MEI_HBM_MINOR_VERSION_IE 0
#define MEI_HBM_MAJOR_VERSION_IE 2
/*
* MEI version with disconnect on connection timeout support
*/
#define MEI_HBM_MINOR_VERSION_DOT 0
#define MEI_HBM_MAJOR_VERSION_DOT 2
/*
* MEI version with notification support
*/
#define MEI_HBM_MINOR_VERSION_EV 0
#define MEI_HBM_MAJOR_VERSION_EV 2
/*
* MEI version with fixed address client support
*/
#define MEI_HBM_MINOR_VERSION_FA 0
#define MEI_HBM_MAJOR_VERSION_FA 2
/*
* MEI version with OS ver message support
*/
#define MEI_HBM_MINOR_VERSION_OS 0
#define MEI_HBM_MAJOR_VERSION_OS 2
/*
* MEI version with dma ring support
*/
#define MEI_HBM_MINOR_VERSION_DR 1
#define MEI_HBM_MAJOR_VERSION_DR 2
/*
* MEI version with vm tag support
*/
#define MEI_HBM_MINOR_VERSION_VT 2
#define MEI_HBM_MAJOR_VERSION_VT 2
/*
* MEI version with capabilities message support
*/
#define MEI_HBM_MINOR_VERSION_CAP 2
#define MEI_HBM_MAJOR_VERSION_CAP 2
/*
* MEI version with client DMA support
*/
#define MEI_HBM_MINOR_VERSION_CD 2
#define MEI_HBM_MAJOR_VERSION_CD 2
/* Host bus message command opcode */
#define MEI_HBM_CMD_OP_MSK 0x7f
/* Host bus message command RESPONSE */
#define MEI_HBM_CMD_RES_MSK 0x80
/*
* MEI Bus Message Command IDs
*/
#define MEI_HOST_START_REQ_CMD 0x01
#define MEI_HOST_START_RES_CMD 0x81
#define MEI_HOST_STOP_REQ_CMD 0x02
#define MEI_HOST_STOP_RES_CMD 0x82
#define MEI_ME_STOP_REQ_CMD 0x03
#define MEI_HOST_ENUM_REQ_CMD 0x04
#define MEI_HOST_ENUM_RES_CMD 0x84
#define MEI_HOST_CLIENT_PROP_REQ_CMD 0x05
#define MEI_HOST_CLIENT_PROP_RES_CMD 0x85
#define MEI_CLIENT_CONNECT_REQ_CMD 0x06
#define MEI_CLIENT_CONNECT_RES_CMD 0x86
#define MEI_CLIENT_DISCONNECT_REQ_CMD 0x07
#define MEI_CLIENT_DISCONNECT_RES_CMD 0x87
#define MEI_FLOW_CONTROL_CMD 0x08
#define MEI_PG_ISOLATION_ENTRY_REQ_CMD 0x0a
#define MEI_PG_ISOLATION_ENTRY_RES_CMD 0x8a
#define MEI_PG_ISOLATION_EXIT_REQ_CMD 0x0b
#define MEI_PG_ISOLATION_EXIT_RES_CMD 0x8b
#define MEI_ADD_CLIENT_REQ_CMD 0x0f
#define MEI_ADD_CLIENT_RES_CMD 0x8f
#define MEI_NOTIFY_REQ_CMD 0x10
#define MEI_NOTIFY_RES_CMD 0x90
#define MEI_NOTIFICATION_CMD 0x11
#define MEI_DMA_SETUP_REQ_CMD 0x12
#define MEI_DMA_SETUP_RES_CMD 0x92
#define MEI_CAPABILITIES_REQ_CMD 0x13
#define MEI_CAPABILITIES_RES_CMD 0x93
#define MEI_CLIENT_DMA_MAP_REQ_CMD 0x14
#define MEI_CLIENT_DMA_MAP_RES_CMD 0x94
#define MEI_CLIENT_DMA_UNMAP_REQ_CMD 0x15
#define MEI_CLIENT_DMA_UNMAP_RES_CMD 0x95
enum MEIHostBusMessageReturnType : UInt8 {
MEIHostBusMessageReturnSuccess = 0,
MEIHostBusMessageReturnClientNotFound = 1,
MEIHostBusMessageReturnAlreadyExists = 2, /* connection already established */
MEIHostBusMessageReturnRejected = 3, /* connection is rejected */
MEIHostBusMessageReturnInvalidParam = 4,
MEIHostBusMessageReturnNotAllowed = 5,
MEIHostBusMessageReturnAlreadyStarted = 6, /* system is already started */
MEIHostBusMessageReturnNotStarted = 7, /* system not started */
MEIHostBusMessageReturnTypeLength,
};
enum MEIExtendedHeaderType : UInt8 {
MEIExtendedHeaderNone = 0,
MEIExtendedHeaderVtag = 1,
};
/**
* struct MEIExtendedHeaderDescriptor - extend header descriptor (TLV)
* @type: header type
* @length: header length excluding descriptor SHOULD BE 1
* @data: payload data
*/
struct PACKED MEIBusExtendedHeader {
MEIExtendedHeaderType type;
UInt8 length;
UInt8 data[2];
};
#define MEI_EXTHEADER_DATA_VTAG_IDX 0
/**
* struct MEIExtendedMetaHeader - extend header meta data
* @count: number of headers
* @size: total slot count of the extended header list excluding meta header
* @reserved: reserved
* @hdrs: extended headers TLV list
*/
struct PACKED MEIBusExtendedMetaHeader {
UInt8 count;
UInt8 size;
UInt8 reserved[2];
UInt8 hdrs[];
};
/*
* Extended header iterator functions
*/
static inline MEIBusExtendedHeader *mei_ext_begin(MEIBusExtendedMetaHeader *meta)
{
return reinterpret_cast(meta->hdrs);
}
/**
* mei_ext_last - check if the ext is the last one in the TLV list
*
* @meta: meta header of the extended header list
* @hdr: a meta header on the list
*
* Return: true if ext is the last header on the list
*/
static inline bool mei_ext_last(MEIBusExtendedMetaHeader *meta, MEIBusExtendedHeader *hdr)
{
return reinterpret_cast(hdr) >= reinterpret_cast(meta) + sizeof(MEIBusExtendedMetaHeader) + MEI_SLOTS_TO_DATA(meta->size);
}
/**
* struct MEIMessageHeader - MEI Bus Interface Section size=4
*
* @me_addr: device address
* @host_addr: host address
* @length: message length
* @reserved: reserved
* @extended: message has extended header
* @dma_ring: message is on dma ring
* @internal: message is internal
* @msg_complete: last packet of the message
* @extension: extension of the header
*/
struct PACKED MEIBusMessageHeader {
UInt32 me_addr:8;
UInt32 host_addr:8;
UInt32 length:9;
UInt32 reserved:3;
UInt32 extended:1;
UInt32 dma_ring:1;
UInt32 internal:1;
UInt32 msg_complete:1;
UInt32 extension[];
};
/* The length is up to 9 bits */
#define MEI_MSG_MAX_LEN_MASK GENMASK(9, 0)
/**
* struct MEIBusMessage - Generic MEI bus message
*
* @cmd: bus message command ID
* @data: generic data
*/
struct PACKED MEIBusMessage {
UInt8 cmd;
UInt8 data[];
};
#define MEI_TO_MSG(specific_msg) (reinterpret_cast(specific_msg))
struct PACKED MEIBusGenericMessage {
UInt8 cmd;
UInt8 reserved[3];
};
typedef MEIBusGenericMessage MEIBusPowerGatingRequest;
typedef MEIBusGenericMessage MEIBusPowerGatingResponse;
struct PACKED MEIBusHostVersionRequest {
UInt8 cmd;
UInt8 reserved;
UInt8 host_version_minor;
UInt8 host_version_major;
};
struct PACKED MEIBusHostVersionResponse {
UInt8 cmd;
UInt8 host_version_supported;
UInt8 me_max_version_minor;
UInt8 me_max_version_major;
};
enum MEIStopReason : UInt8 {
DriverStopRequest = 0x00,
DeviceD1Entry = 0x01,
DeviceD2Entry = 0x02,
DeviceD3Entry = 0x03,
SystemS1Entry = 0x04,
SystemS2Entry = 0x05,
SystemS3Entry = 0x06,
SystemS4Entry = 0x07,
SystemS5Entry = 0x08,
};
struct PACKED MEIBusHostStopRequest {
UInt8 cmd;
MEIStopReason reason;
UInt8 reserved[2];
};
struct PACKED MEIBusHostStopResponse {
UInt8 cmd;
UInt8 reserved[3];
};
struct PACKED MEIBusMEStopRequest {
UInt8 cmd;
MEIStopReason reason;
UInt8 reserved[2];
};
/**
* @MEI_HBM_ENUM_ALLOW_ADD_FLAG: allow dynamic clients add
* @MEI_HBM_ENUM_IMMEDIATE_FLAG: allow FW to send answer immediately
*/
#define MEI_HBM_ENUM_ALLOW_ADD_FLAG BIT(0)
#define MEI_HBM_ENUM_IMMEDIATE_FLAG BIT(1)
struct PACKED MEIBusHostEnumerationRequest {
UInt8 cmd;
UInt8 flags;
UInt8 reserved[2];
};
struct PACKED MEIBusHostEnumerationResponse {
UInt8 cmd;
UInt8 reserved[3];
UInt8 valid_addresses[MEI_MAX_CLIENT_NUM/8];
};
/**
* struct MEIClientProperty - mei client properties
*
* @uuid: guid of the client
* @protocol_version: client protocol version
* @max_connection_num: number of possible connections. 0: fixed clients
* @fixed_address: fixed me address (0 if the client is dynamic)
* @single_recv_buf: 1 if all connections share a single receive buffer.
* @vt_supported: the client support vtag
* @reserved: reserved
* @max_msg_length: MTU of the client
*/
struct PACKED MEIClientProperty {
uuid_t uuid;
UInt8 protocol_version;
UInt8 max_connection_num;
UInt8 fixed_address;
UInt8 single_recv_buf:1;
UInt8 vt_supported:1;
UInt8 reserved:6;
UInt32 max_msg_length;
};
struct PACKED MEIBusClientPropertyRequest {
UInt8 cmd;
UInt8 me_addr;
UInt8 reserved[2];
};
struct PACKED MEIBusClientPropertyResponse {
UInt8 cmd;
UInt8 me_addr;
MEIHostBusMessageReturnType status;
UInt8 reserved;
MEIClientProperty client_properties;
};
/**
* struct MEIBusAddClientRequest - request to add a client
* might be sent by fw after enumeration has already completed
*
* @cmd: bus message command ID
* @me_addr: address of the client in ME
* @reserved: reserved
* @client_properties: client properties
*/
struct PACKED MEIBusAddClientRequest {
UInt8 cmd;
UInt8 me_addr;
UInt8 reserved[2];
MEIClientProperty client_properties;
};
/**
* struct MEIBusAddClientResponse - response to add a client
* sent by the host to report client addition status to fw
*
* @cmd: bus message command ID
* @me_addr: address of the client in ME
* @status: if MEIHostBusMessageReturnSuccess then the client can now accept connections.
* @reserved: reserved
*/
struct PACKED MEIBusAddClientResponse {
UInt8 cmd;
UInt8 me_addr;
MEIHostBusMessageReturnType status;
UInt8 reserved;
};
/**
* struct MEIBusClientCommand - client specific host bus command
* CONNECT, DISCONNECT, FlOW CONTROL, NOTIFICATION
*
* @cmd: bus message command ID
* @me_addr: address of the client in ME
* @host_addr: address of the client in the driver
* @data: generic data
*/
struct PACKED MEIBusClientCommand {
UInt8 cmd;
UInt8 me_addr;
UInt8 host_addr;
UInt8 data;
};
typedef MEIBusClientCommand MEIBusClientConnectionRequest;
enum MEIClientConnectionStatus : UInt8 {
MEIClientConnectionSuccess = MEIHostBusMessageReturnSuccess,
MEIClientConnectionNotFound = MEIHostBusMessageReturnClientNotFound,
MEIClientConnectionAlreadyStarted = MEIHostBusMessageReturnAlreadyExists,
MEIClientConnectionOutOfResources = MEIHostBusMessageReturnRejected,
MEIClientConnectionMessageTooSmall = MEIHostBusMessageReturnInvalidParam,
MEIClientConnectionNotAllowed = MEIHostBusMessageReturnNotAllowed,
};
/**
* struct MEIBusClientConnectionResponse - connect/disconnect response
*
* @cmd: bus message command header
* @me_addr: address of the client in ME
* @host_addr: address of the client in the driver
* @status: status of the request
*/
struct PACKED MEIBusClientConnectionResponse {
UInt8 cmd;
UInt8 me_addr;
UInt8 host_addr;
MEIClientConnectionStatus status;
};
#define MEI_FLOW_CONTROL_MSG_RESERVED_LEN 5
struct PACKED MEIBusFlowControl {
UInt8 cmd;
UInt8 me_addr;
UInt8 host_addr;
UInt8 reserved[MEI_FLOW_CONTROL_MSG_RESERVED_LEN];
};
#define MEI_HBM_NOTIFICATION_START 1
#define MEI_HBM_NOTIFICATION_STOP 0
/**
* struct MEIBusNotificationRequest - start/stop notification request
*
* @cmd: bus message command ID
* @me_addr: address of the client in ME
* @host_addr: address of the client in the driver
* @start: start = 1 or stop = 0 asynchronous notifications
*/
struct PACKED MEIBusNotificationRequest {
UInt8 cmd;
UInt8 me_addr;
UInt8 host_addr;
UInt8 start;
};
/**
* struct MEIBusNotificationResponse - start/stop notification response
*
* @cmd: bus message command header
* @me_addr: address of the client in ME
* @host_addr: - address of the client in the driver
* @status: (mei_hbm_status) response status for the request
* - MEIHostBusMessageReturnSuccess: successful stop/start
* - MEIHostBusMessageReturnClientNotFound: if the connection could not be found.
* - MEIHostBusMessageReturnAlreadyStarted: for start requests for a previously started notification.
* - MEIHostBusMessageReturnNotStarted: for stop request for a connected client for whom asynchronous notifications are currently disabled.
* @start: start = 1 or stop = 0 asynchronous notifications
* @reserved: reserved
*/
struct PACKED MEIBusNotificationResponse {
UInt8 cmd;
UInt8 me_addr;
UInt8 host_addr;
MEIHostBusMessageReturnType status;
UInt8 start;
UInt8 reserved[3];
};
/**
* struct MEIBusDMAMemDesc - dma ring
*
* @addr_hi: the high 32bits of 64 bit address
* @addr_lo: the low 32bits of 64 bit address
* @size : size in bytes (must be power of 2)
*/
struct PACKED MEIBusDMAInfo {
UInt32 addr_hi;
UInt32 addr_lo;
UInt32 size;
};
#define DMA_BIT_MASK(n) (((n) == 64) ? ~0ULL : ((1ULL<<(n))-1))
// SHOULD be power of 2
#define MEI_DMA_RING_HOST_SIZE 0x00020000 // 128k
#define MEI_DMA_RING_DEVICE_SIZE 0x00020000
#define MEI_DMA_RING_CTRL_SIZE PAGE_SIZE // 4k
enum MEIDMADescriptor {
MEIDMADescriptorHost = 0,
MEIDMADescriptorDevice = 1,
MEIDMADescriptorControl = 2,
MEIDMADescriptorSize,
};
/**
* struct MEIBusDMASetupRequest - dma setup request
*
* @cmd: bus message command ID
* @reserved: reserved for alignment
* @dma_dscr: dma descriptor for HOST, DEVICE, and CTRL
*/
struct PACKED MEIBusDMASetupRequest {
UInt8 cmd;
UInt8 reserved[3];
MEIBusDMAInfo dma_info[MEIDMADescriptorSize];
};
/**
* struct hbm_dma_setup_response - dma setup response
*
* @cmd: bus message command ID
* @status: 0 on success; otherwise DMA setup failed.
* @reserved: reserved for alignment
*/
struct PACKED MEIBusDMASetupResponse {
UInt8 cmd;
MEIHostBusMessageReturnType status;
UInt8 reserved[2];
};
/**
* struct MEIBusDMARingControl - dma ring control block
*
* @hbuf_wr_idx: host circular buffer write index in slots
* @reserved1: reserved for alignment
* @hbuf_rd_idx: host circular buffer read index in slots
* @reserved2: reserved for alignment
* @dbuf_wr_idx: device circular buffer write index in slots
* @reserved3: reserved for alignment
* @dbuf_rd_idx: device circular buffer read index in slots
* @reserved4: reserved for alignment
*/
struct PACKED MEIBusDMARingControl {
UInt32 hbuf_wr_idx;
UInt32 reserved1;
UInt32 hbuf_rd_idx;
UInt32 reserved2;
UInt32 dbuf_wr_idx;
UInt32 reserved3;
UInt32 dbuf_rd_idx;
UInt32 reserved4;
};
/* virtual tag supported */
#define MEI_HBM_CAP_VTAG BIT(0)
/* client dma supported */
#define MEI_HBM_CAP_CLIENT_DMA BIT(2)
/**
* struct MEIBusCapabilityRequest - capability request from host to fw
*
* @cmd : bus message command ID
* @capability_requested: bitmask of capabilities requested by host
*/
struct PACKED MEIBusCapabilityRequest {
UInt8 cmd;
UInt8 capability_requested[3];
};
/**
* struct MEIBusCapabilityResponse - capability response from fw to host
*
* @cmd : bus message command ID
* @capability_granted: bitmask of capabilities granted by FW
*/
struct PACKED MEIBusCapabilityResponse {
UInt8 cmd;
UInt8 capability_granted[3];
};
/**
* struct MEIBusClientDMAMapRequest - client dma map request from host to fw
*
* @cmd: bus message command ID
* @client_buffer_id: client buffer id
* @reserved: reserved
* @address_lsb: DMA address LSB
* @address_msb: DMA address MSB
* @size: DMA size
*/
struct PACKED MEIBusClientDMAMapRequest {
UInt8 cmd;
UInt8 client_buffer_id;
UInt8 reserved[2];
UInt32 address_lsb;
UInt32 address_msb;
UInt32 size;
};
/**
* struct MEIBusClientDMAUnmapRequest - client dma unmap request from the host to the fw
*
* @cmd: bus message command ID
* @status: unmap status
* @client_buffer_id: client buffer id
* @reserved: reserved
*/
struct PACKED MEIBusClientDMAUnmapRequest {
UInt8 cmd;
UInt8 status;
UInt8 client_buffer_id;
UInt8 reserved;
};
/**
* struct MEIBusClientDMAResponse - client dma map/unmap response from the fw to the host
*
* @cmd: bus message command ID
* @status: command status
*/
struct PACKED MEIBusClientDMAResponse {
UInt8 cmd;
MEIClientConnectionStatus status;
};
#endif /* MEIProtocol_h */
================================================
FILE: BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineClient.cpp
================================================
//
// SurfaceManagementEngineClient.cpp
// SurfaceTouchScreen
//
// Created by Xavier on 2022/6/1.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#include "SurfaceManagementEngineClient.hpp"
#define super IOService
OSDefineMetaClassAndStructors(SurfaceManagementEngineClient, IOService)
bool SurfaceManagementEngineClient::attach(IOService* provider) {
if (!super::attach(provider))
return false;
api = OSDynamicCast(SurfaceManagementEngineDriver, provider);
if (!api)
return false;
queue_head_init(rx_queue);
return true;
}
void SurfaceManagementEngineClient::detach(IOService* provider) {
api = nullptr;
super::detach(provider);
}
bool SurfaceManagementEngineClient::start(IOService *provider) {
if (!super::start(provider))
return false;
queue_lock = IOLockAlloc();
if (!queue_lock) {
LOG("Failed to create lock");
goto exit;
}
work_loop = IOWorkLoop::workLoop();
if (!work_loop) {
LOG("Failed to create work loop");
goto exit;
}
interrupt_source = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineClient::notifyMessage));
if (!interrupt_source) {
LOG("Failed to create interrupt source");
goto exit;
}
work_loop->addEventSource(interrupt_source);
uuid_t swapped_uuid;
uuid_string_t uuid_str;
uuid_copy(swapped_uuid, properties.uuid);
*(reinterpret_cast(swapped_uuid)) = OSSwapInt32(*(reinterpret_cast(swapped_uuid)));
*(reinterpret_cast(swapped_uuid) + 2) = OSSwapInt16(*(reinterpret_cast(swapped_uuid) + 2));
*(reinterpret_cast(swapped_uuid) + 3) = OSSwapInt16(*(reinterpret_cast(swapped_uuid) + 3));
uuid_unparse_lower(swapped_uuid, uuid_str);
setProperty("MEIClientUUID", uuid_str);
setProperty("MEIClientAddress", properties.fixed_address, 32);
setProperty("MEIClientMaxMessageLength", properties.max_msg_length, 32);
rx_cache = new UInt8[properties.max_msg_length];
initial = false;
PMinit();
api->joinPMtree(this);
registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);
registerService();
return true;
exit:
releaseResources();
return false;
}
void SurfaceManagementEngineClient::stop(IOService *provider) {
releaseResources();
super::stop(provider);
}
IOReturn SurfaceManagementEngineClient::setPowerState(unsigned long whichState, IOService *device) {
if (device != this)
return kIOReturnInvalid;
return kIOPMAckImplied;
}
void SurfaceManagementEngineClient::releaseResources() {
MEIClientMessage *msg;
qe_foreach_element_safe(msg, &rx_queue, entry) {
remqueue(&msg->entry);
delete[] msg->msg;
delete msg;
}
if (rx_cache)
delete[] rx_cache;
if (interrupt_source) {
interrupt_source->disable();
work_loop->removeEventSource(interrupt_source);
OSSafeReleaseNULL(interrupt_source);
}
OSSafeReleaseNULL(work_loop);
if (queue_lock)
IOLockFree(queue_lock);
}
IOReturn SurfaceManagementEngineClient::registerMessageHandler(OSObject *owner, MessageHandler _handler) {
if (!owner || !_handler)
return kIOReturnError;
if (target) {
LOG("Already has a handler!");
return kIOReturnNoResources;
}
target = owner;
handler = _handler;
return kIOReturnSuccess;
}
void SurfaceManagementEngineClient::unregisterMessageHandler(OSObject *owner) {
if (target && target == owner) {
target = nullptr;
handler = nullptr;
}
}
IOReturn SurfaceManagementEngineClient::sendMessage(UInt8 *data, UInt16 data_len, bool blocking) {
if (!active)
return kIOReturnNoDevice;
return api->sendClientMessage(this, data, data_len, blocking);
}
void SurfaceManagementEngineClient::resetProperties(MEIClientProperty *client_props, UInt8 me_addr) {
active = true;
properties = *client_props;
addr = me_addr;
}
void SurfaceManagementEngineClient::hostRequestDisconnect() {
rx_cache_pos = 0;
IOLockLock(queue_lock);
while (dequeue(&rx_queue));
IOLockUnlock(queue_lock);
}
void SurfaceManagementEngineClient::hostRequestReconnect() {
}
void SurfaceManagementEngineClient::messageComplete() {
if (!rx_cache_pos)
return;
MEIClientMessage *client_msg = new MEIClientMessage;
client_msg->msg = new UInt8[rx_cache_pos];
client_msg->len = rx_cache_pos;
memcpy(client_msg->msg, rx_cache, rx_cache_pos);
rx_cache_pos = 0;
IOLockLock(queue_lock);
enqueue(&rx_queue, &client_msg->entry);
IOLockUnlock(queue_lock);
interrupt_source->interruptOccurred(nullptr, this, 0);
}
void SurfaceManagementEngineClient::notifyMessage(IOInterruptEventSource *sender, int count) {
MEIClientMessage *client_msg;
queue_entry *item;
IOLockLock(queue_lock);
while ((item = dequeue(&rx_queue)) != nullptr) {
IOLockUnlock(queue_lock);
client_msg = qe_element(item, MEIClientMessage, entry);
if (handler)
handler(target, this, client_msg->msg, client_msg->len);
delete[] client_msg->msg;
delete client_msg;
IOLockLock(queue_lock);
}
IOLockUnlock(queue_lock);
}
================================================
FILE: BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineClient.hpp
================================================
//
// SurfaceManagementEngineClient.hpp
// SurfaceTouchScreen
//
// Created by Xavier on 2022/6/1.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#ifndef SurfaceManagementEngineClient_hpp
#define SurfaceManagementEngineClient_hpp
#include "SurfaceManagementEngineDriver.hpp"
struct MEIClientMessage {
queue_entry entry;
UInt8* msg;
UInt16 len;
};
class EXPORT SurfaceManagementEngineClient : public IOService {
OSDeclareDefaultStructors(SurfaceManagementEngineClient);
friend class SurfaceManagementEngineDriver;
public:
// handle received message
typedef void (*MessageHandler)(OSObject *owner, SurfaceManagementEngineClient *sender, UInt8 *msg, UInt16 msg_len);
bool attach(IOService* provider) override;
void detach(IOService* provider) override;
bool start(IOService* provider) override;
void stop(IOService* provider) override;
IOReturn setPowerState(unsigned long whichState, IOService *device) override;
IOReturn registerMessageHandler(OSObject *owner, MessageHandler _handler);
void unregisterMessageHandler(OSObject *owner);
IOReturn sendMessage(UInt8 *data, UInt16 data_len, bool blocking);
private:
SurfaceManagementEngineDriver* api {nullptr};
IOLock* queue_lock {nullptr};
IOWorkLoop* work_loop {nullptr};
IOInterruptEventSource* interrupt_source {nullptr};
MEIClientProperty properties;
OSObject* target {nullptr};
MessageHandler handler {nullptr};
queue_head_t rx_queue;
UInt8* rx_cache {nullptr};
UInt16 rx_cache_pos {0};
UInt8 addr;
bool active {false};
bool initial {true};
void releaseResources();
void resetProperties(MEIClientProperty *client_props, UInt8 me_addr);
void hostRequestDisconnect();
void hostRequestReconnect();
void messageComplete();
void notifyMessage(IOInterruptEventSource *sender, int count);
};
#endif /* SurfaceManagementEngineClient_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineDriver.cpp
================================================
//
// SurfaceManagementEngineDriver.cpp
// SurfaceTouchScreen
//
// Created by Xavier on 2022/05/28.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#include "SurfaceManagementEngineDriver.hpp"
#include "SurfaceManagementEngineClient.hpp"
#define super IOService
OSDefineMetaClassAndStructors(SurfaceManagementEngineDriver, IOService);
void bitmap_set_bit(UInt8 *map, UInt addr, bool set) {
UInt i = addr / 8;
UInt offset = addr % 8;
if (set)
map[i] |= BIT(offset);
else
map[i] &= ~BIT(offset);
}
bool bitmap_get_bit(UInt8 *map, UInt addr) {
UInt i = addr / 8;
UInt offset = addr % 8;
return (map[i] & BIT(offset)) != 0;
}
UInt bitmap_find_next_bit(UInt8 *map, UInt map_size, UInt start_addr) {
UInt pos = start_addr;
while (pos < map_size && !bitmap_get_bit(map, pos))
pos++;
return pos;
}
bool SurfaceManagementEngineDriver::init(OSDictionary* properties) {
if (!super::init(properties))
return false;
memset(&device, 0, sizeof(MEIPhysicalDevice));
memset(&bus, 0, sizeof(MEIBus));
queue_init(&bus.tx_queue);
return true;
}
IOService* SurfaceManagementEngineDriver::probe(IOService* provider, SInt32* score) {
if (!super::probe(provider, score))
return nullptr;
device.pci_dev = OSDynamicCast(IOPCIDevice, provider);
if (!device.pci_dev)
return nullptr;
return this;
}
bool SurfaceManagementEngineDriver::start(IOService* provider) {
if (!super::start(provider))
return false;
int interrupt_type, interrupt_idx=0;
work_loop = IOWorkLoop::workLoop();
if (!work_loop) {
LOG("Could not get work loop");
goto exit;
}
command_gate = IOCommandGate::commandGate(this);
if (!command_gate) {
LOG("Could not open command gate");
goto exit;
}
work_loop->addEventSource(command_gate);
client_msg_action = OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::sendClientMessageGated);
reset_work = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineDriver::scheduleReset));
rescan_work = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineDriver::scheduleRescan));
resume_work = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineDriver::scheduleResume));
if (!reset_work || !rescan_work || !resume_work) {
LOG("Could not create scheduled work");
goto exit;
}
work_loop->addEventSource(reset_work);
work_loop->addEventSource(rescan_work);
work_loop->addEventSource(resume_work);
if (!device.pci_dev->open(this)) {
LOG("Could not open provider");
goto exit;
}
if (initDevice() != kIOReturnSuccess)
goto exit;
while (device.pci_dev->getInterruptType(interrupt_idx, &interrupt_type) == kIOReturnSuccess) {
if (interrupt_type & kIOInterruptTypePCIMessaged)
break;
interrupt_idx++;
}
interrupt_source = IOFilterInterruptEventSource::filterInterruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceManagementEngineDriver::handleInterrupt), OSMemberFunctionCast(IOFilterInterruptAction, this, &SurfaceManagementEngineDriver::filterInterrupt), device.pci_dev, interrupt_idx);
if (!interrupt_source) {
LOG("WTF? Cannot register PCI MSI interrupt!");
goto exit;
}
work_loop->addEventSource(interrupt_source);
interrupt_source->enable();
if (command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::startDeviceGated)) != kIOReturnSuccess) {
LOG("Initialise hardware failed");
goto exit;
}
PMinit();
device.pci_dev->joinPMtree(this);
registerPowerDriver(this, MyIOPMPowerStates, kIOPMNumberPowerStates);
device.pci_dev->retain();
registerService();
return true;
exit:
releaseResources();
return false;
}
void SurfaceManagementEngineDriver::stop(IOService *provider) {
if (!queue_empty(&bus.tx_queue)) {
DBG_LOG("Warning, there are still pending transactions!");
MEIClientTransaction *tx;
qe_foreach_element_safe(tx, &bus.tx_queue, entry) {
completeTransaction(tx);
}
IOSleep(100);
}
command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::stopDeviceGated));
PMstop();
releaseResources();
super::stop(provider);
}
void SurfaceManagementEngineDriver::free() {
super::free();
}
IOReturn SurfaceManagementEngineDriver::setPowerState(unsigned long whichState, IOService *whatDevice) {
if (whatDevice != this)
return kIOReturnInvalid;
if (whichState == 0) {
if (awake) {
command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::stopDeviceGated));
disableInterrupts();
interrupt_source->disable();
device.pci_dev->enablePCIPowerManagement(kPCIPMCSPowerStateD3);
awake = false;
DBG_LOG("Going to sleep");
}
} else {
if (!awake) {
awake = true;
device.pci_dev->enablePCIPowerManagement(kPCIPMCSPowerStateD0);
interrupt_source->enable();
if (command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceManagementEngineDriver::restartDeviceGated)) != kIOReturnSuccess)
LOG("Restarting device failed! Retry later");
init_timeout->enable();
DBG_LOG("Woke up");
}
}
return kIOPMAckImplied;
}
void SurfaceManagementEngineDriver::releaseResources() {
if (interrupt_source) {
disableInterrupts();
interrupt_source->disable();
work_loop->removeEventSource(interrupt_source);
OSSafeReleaseNULL(interrupt_source);
}
if (init_timeout) {
init_timeout->cancelTimeout();
init_timeout->disable();
work_loop->removeEventSource(init_timeout);
OSSafeReleaseNULL(init_timeout);
}
if (idle_timeout) {
idle_timeout->cancelTimeout();
idle_timeout->disable();
work_loop->removeEventSource(idle_timeout);
OSSafeReleaseNULL(idle_timeout);
}
if (reset_work) {
reset_work->disable();
work_loop->removeEventSource(reset_work);
OSSafeReleaseNULL(reset_work);
}
if (rescan_work) {
rescan_work->disable();
work_loop->removeEventSource(rescan_work);
OSSafeReleaseNULL(rescan_work);
}
if (resume_work) {
resume_work->disable();
work_loop->removeEventSource(resume_work);
OSSafeReleaseNULL(resume_work);
}
unmapMemory();
if (device.pci_dev->isOpen(this))
device.pci_dev->close(this);
if (command_gate) {
work_loop->removeEventSource(command_gate);
OSSafeReleaseNULL(command_gate);
}
OSSafeReleaseNULL(work_loop);
if (ipts_client) {
ipts_client->stop(this);
ipts_client->detach(this);
OSSafeReleaseNULL(ipts_client);
}
OSSafeReleaseNULL(device.pci_dev);
}
IOReturn SurfaceManagementEngineDriver::startDeviceGated() {
IOReturn ret;
clearInterrupts();
configDevice();
device.reset_cnt = 0;
do {
device.state = MEIDeviceInitializing;
ret = resetDevice();
if (ret == kIOReturnDeviceError || device.state == MEIDeviceDisabled) {
LOG("Reset failed!");
goto err;
}
} while (ret != kIOReturnSuccess);
// wait mei host bus started
if (bus.state <= MEIBusStarting) {
AbsoluteTime abstime, deadline;
nanoseconds_to_absolutetime(MEI_HOST_BUS_MSG_TIMEOUT * 1000000000ULL, &abstime);
clock_absolutetime_interval_to_deadline(abstime, &deadline);
ret = command_gate->commandSleep(&wait_bus_start, deadline, THREAD_INTERRUPTIBLE);
if (ret == THREAD_TIMED_OUT && bus.state <= MEIBusStarting) {
bus.state = MEIBusIdle;
LOG("Timeout waiting for mei bus to start!");
goto err;
}
}
if (!isHostReady()) {
LOG("Host is not ready");
goto err;
}
if (!isHardwareReady()) {
LOG("ME is not ready");
goto err;
}
if (!isBusMessageVersionSupported()) {
LOG("Device start failed");
goto err;
}
LOG("Link layer initialization succeeded");
return kIOReturnSuccess;
err:
LOG("Link layer initialization failed");
device.state = MEIDeviceDisabled;
return kIOReturnDeviceError;
}
void SurfaceManagementEngineDriver::stopDeviceGated() {
device.state = MEIDevicePowerDown;
init_timeout->disable();
resetDevice();
device.state = MEIDeviceDisabled;
}
IOReturn SurfaceManagementEngineDriver::restartDeviceGated() {
device.state = MEIDevicePowerUp;
device.reset_cnt = 0;
IOReturn ret = resetDevice();
if (ret == kIOReturnDeviceError ||
device.state == MEIDeviceDisabled) {
LOG("Error! Device disabled");
return kIOReturnDeviceError;
}
if (ret != kIOReturnSuccess)
reset_work->interruptOccurred(nullptr, this, 0);
return kIOReturnSuccess;
}
IOReturn SurfaceManagementEngineDriver::mapMemory() {
if (device.pci_dev->getDeviceMemoryCount() == 0) {
return kIOReturnDeviceError;
} else {
device.mmap = device.pci_dev->mapDeviceMemoryWithIndex(0);
if (!device.mmap) return kIOReturnDeviceError;
return kIOReturnSuccess;
}
}
void SurfaceManagementEngineDriver::unmapMemory() {
OSSafeReleaseNULL(device.mmap);
}
inline UInt32 SurfaceManagementEngineDriver::readRegister(int offset) {
if (device.mmap) {
IOVirtualAddress address = device.mmap->getVirtualAddress();
if (address != 0)
return *(const volatile UInt32 *)(address + offset);
}
return kIOReturnSuccess;
}
inline void SurfaceManagementEngineDriver::writeRegister(UInt32 value, int offset) {
if (device.mmap) {
IOVirtualAddress address = device.mmap->getVirtualAddress();
if (address != 0)
*(volatile UInt32 *)(address + offset) = value;
}
}
UInt8 SurfaceManagementEngineDriver::calcFilledSlots() {
UInt32 hcsr = readRegister(MEI_H_CSR);
SInt8 read_ptr = (hcsr & MEI_CSR_BUF_RPOINTER) >> 8;
SInt8 write_ptr = (hcsr & MEI_CSR_BUF_WPOINTER) >> 16;
return write_ptr - read_ptr;
}
IOReturn SurfaceManagementEngineDriver::findEmptySlots(UInt8 *empty_slots) {
UInt8 filled_slots = calcFilledSlots();
if (filled_slots > device.tx_buf_depth)
return kIOReturnOverrun;
*empty_slots = device.tx_buf_depth - filled_slots;
return kIOReturnSuccess;
}
IOReturn SurfaceManagementEngineDriver::countRxSlots(UInt8 *filled_slots) {
UInt32 mecsr = readRegister(MEI_ME_CSR);
UInt8 buffer_depth = (mecsr & MEI_CSR_BUF_DEPTH) >> 24;
SInt8 read_ptr = (mecsr & MEI_CSR_BUF_RPOINTER) >> 8;
SInt8 write_ptr = (mecsr & MEI_CSR_BUF_WPOINTER) >> 16;
UInt8 slots = write_ptr - read_ptr;
if (slots > buffer_depth)
return kIOReturnOverrun;
*filled_slots = slots;
return kIOReturnSuccess;
}
bool SurfaceManagementEngineDriver::acquireWriteBuffer() {
if (device.pg_state == MEIPowerGatingOn || (device.pg_event >= MEIPowerGatingEventWait && device.pg_event <= MEIPowerGatingInterruptWait))
return false;
if (!bus.tx_buf_ready)
return false;
bus.tx_buf_ready = false;
return true;
}
bool SurfaceManagementEngineDriver::isHardwareReady() {
UInt32 mecsr = readRegister(MEI_ME_CSR);
return (mecsr & MEI_ME_CSR_READY) == MEI_ME_CSR_READY;
}
bool SurfaceManagementEngineDriver::isHostReady() {
UInt32 hcsr = readRegister(MEI_H_CSR);
return (hcsr & MEI_H_CSR_READY) == MEI_H_CSR_READY;
}
bool SurfaceManagementEngineDriver::isBusMessageVersionSupported() {
return (device.version_major < MEI_HBM_MAJOR_VERSION) ||
(device.version_major == MEI_HBM_MAJOR_VERSION &&
device.version_minor <= MEI_HBM_MINOR_VERSION);
}
bool SurfaceManagementEngineDriver::isWriteQueueEmpty() {
return device.state == MEIDeviceEnabled && queue_empty(&bus.tx_queue);
}
inline void SurfaceManagementEngineDriver::setHostCSR(UInt32 hcsr) {
hcsr &= ~MEI_H_CSR_INT_STA_MASK;
writeRegister(hcsr, MEI_H_CSR);
}
void SurfaceManagementEngineDriver::clearInterrupts() {
UInt32 hcsr = readRegister(MEI_H_CSR);
if (hcsr & MEI_H_CSR_INT_STA_MASK)
writeRegister(hcsr, MEI_H_CSR);
}
void SurfaceManagementEngineDriver::enableInterrupts() {
UInt32 hcsr = readRegister(MEI_H_CSR);
hcsr |= MEI_H_CSR_INT_ENABLE_MASK;
setHostCSR(hcsr);
}
void SurfaceManagementEngineDriver::disableInterrupts() {
UInt32 hcsr = readRegister(MEI_H_CSR);
hcsr &= ~MEI_H_CSR_INT_ENABLE_MASK;
setHostCSR(hcsr);
}
void SurfaceManagementEngineDriver::setHostInterrupt() {
UInt32 hcsr = readRegister(MEI_H_CSR);
hcsr |= MEI_H_CSR_INT_GEN;
setHostCSR(hcsr);
}
void SurfaceManagementEngineDriver::configDevice() {
UInt32 hcsr = readRegister(MEI_H_CSR);
device.tx_buf_depth = (hcsr & MEI_CSR_BUF_DEPTH) >> 24;
device.pg_state = MEIPowerGatingOff;
UInt32 d0i3c = readRegister(MEI_H_D0I3C);
if (d0i3c & MEI_H_D0I3C_I3)
device.pg_state = MEIPowerGatingOn;
}
IOReturn SurfaceManagementEngineDriver::initDevice() {
device.pci_dev->setMemoryEnable(true);
device.pci_dev->setBusMasterEnable(true);
if (mapMemory() != kIOReturnSuccess) {
LOG("Could not map pci_device memory");
return kIOReturnError;
}
device.state = MEIDeviceInitializing;
memset(me_client_map, 0, sizeof(me_client_map));
device.pg_event = MEIPowerGatingEventIdle;
init_timeout = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceManagementEngineDriver::initialiseTimeout));
idle_timeout = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceManagementEngineDriver::enterIdle));
if (!init_timeout || !idle_timeout) {
LOG("Failed to create timer for device");
return kIOReturnError;
}
work_loop->addEventSource(init_timeout);
work_loop->addEventSource(idle_timeout);
return kIOReturnSuccess;
}
IOReturn SurfaceManagementEngineDriver::resetDevice() {
IOReturn ret = kIOReturnSuccess;
UInt32 hcsr;
MEIDeviceState state = device.state;
if (state != MEIDeviceInitializing &&
state != MEIDeviceDisabled &&
state != MEIDevicePowerDown &&
state != MEIDevicePowerUp) {
LOG("Warning! Unexpected reset call from state: %x", device.state);
}
clearInterrupts();
// put bus into idle before actual reset
init_timeout->cancelTimeout();
bus.state = MEIBusIdle;
bool interrupts_enabled = state != MEIDevicePowerDown;
device.state = MEIDeviceResetting;
if (++device.reset_cnt > MEI_MAX_CONSEC_RESET) {
LOG("Reached maximal consecutive resets");
device.state = MEIDeviceDisabled;
return kIOReturnDeviceError;
}
if (interrupts_enabled) {
enableInterrupts();
ret = exitPowerGatingSync();
if (ret != kIOReturnSuccess)
goto sw_reset;
}
hcsr = readRegister(MEI_H_CSR);
/*
* MEI_H_CSR_RESET may be found lit before reset is started,
* for example if preceding reset flow hasn't completed.
* In that case asserting MEI_H_CSR_RESET will be ignored, therefore
* we need to clean MEI_H_CSR_RESET bit to start a successful reset sequence.
*/
if ((hcsr & MEI_H_CSR_RESET) == MEI_H_CSR_RESET) {
LOG("Warning, MEI_H_CSR_RESET is set = 0x%08X, previous reset probably failed", hcsr);
hcsr &= ~MEI_H_CSR_RESET;
setHostCSR(hcsr);
hcsr = readRegister(MEI_H_CSR);
}
hcsr |= MEI_H_CSR_RESET | MEI_H_CSR_INT_GEN | MEI_H_CSR_INT_STA_MASK;
if (!interrupts_enabled)
hcsr &= ~MEI_H_CSR_INT_ENABLE_MASK;
writeRegister(hcsr, MEI_H_CSR);
// Host reads the MEI_H_CSR once to ensure that the posted write to MEI_H_CSR completes.
hcsr = readRegister(MEI_H_CSR);
if ((hcsr & MEI_H_CSR_RESET) == 0)
LOG("Warning, MEI_H_CSR_RESET is not set = 0x%08X", hcsr);
if ((hcsr & MEI_H_CSR_READY) == MEI_H_CSR_READY)
LOG("Warning, MEI_H_CSR_READY is not cleared 0x%08X", hcsr);
if (!interrupts_enabled) {
deresetDevice();
enterPowerGating();
}
sw_reset:
/* fall through and remove the sw state even if hw reset has failed
* no need to clean up software state in case of power up */
if (state != MEIDeviceInitializing && state != MEIDevicePowerUp) {
if (!queue_empty(&bus.tx_queue)) {
LOG("Flushing all pending transactions!");
MEIClientTransaction *tx;
qe_foreach_element_safe(tx, &bus.tx_queue, entry) {
completeTransaction(tx);
}
AbsoluteTime abstime, deadline;
nanoseconds_to_absolutetime(50000000ULL, &abstime); // 50ms
clock_absolutetime_interval_to_deadline(abstime, &deadline);
// Give up work_loop's thread to let pending transactions to finish their work on gate.
command_gate->commandSleep(&awake, deadline, THREAD_INTERRUPTIBLE);
}
if (ipts_client)
ipts_client->hostRequestDisconnect();
}
resetBus();
memset(bus.rx_msg_hdr, 0, sizeof(bus.rx_msg_hdr));
if (ret != kIOReturnSuccess) {
LOG("Hardware reset failed");
return ret;
}
if (state == MEIDevicePowerDown) {
device.state = MEIDeviceDisabled;
return kIOReturnSuccess;
}
ret = waitDeviceReady();
if (ret != kIOReturnSuccess)
return ret;
LOG("Link is established");
device.state = MEIDeviceInitClients;
// Send start request
bus.state = MEIBusIdle;
ret = sendStartRequest();
if (ret) {
LOG("Start request failed");
device.state = MEIDeviceResetting;
return ret;
}
bus.state = MEIBusStarting;
init_timeout->setTimeoutMS(MEI_CLIENTS_INIT_TIMEOUT * 1000);
return kIOReturnSuccess;
}
void SurfaceManagementEngineDriver::deresetDevice() {
UInt32 hcsr = readRegister(MEI_H_CSR);
hcsr |= MEI_H_CSR_INT_GEN;
hcsr &= ~MEI_H_CSR_RESET;
setHostCSR(hcsr);
}
void SurfaceManagementEngineDriver::enableDevice() {
UInt32 hcsr = readRegister(MEI_H_CSR);
hcsr |= MEI_H_CSR_INT_ENABLE_MASK | MEI_H_CSR_INT_GEN | MEI_H_CSR_READY;
setHostCSR(hcsr);
}
IOReturn SurfaceManagementEngineDriver::waitDeviceReady() {
AbsoluteTime abstime, deadline;
IOReturn sleep;
nanoseconds_to_absolutetime(MEI_HW_READY_TIMEOUT * 1000000000ULL, &abstime);
clock_absolutetime_interval_to_deadline(abstime, &deadline);
sleep = command_gate->commandSleep(&wait_hw_ready, deadline, THREAD_INTERRUPTIBLE);
if (sleep == THREAD_TIMED_OUT) {
LOG("Timeout waiting for hardware to be ready!");
return kIOReturnTimeout;
}
deresetDevice();
LOG("Hardware is ready");
enableDevice();
return kIOReturnSuccess;
}
void SurfaceManagementEngineDriver::configDeviceFeatures() {
device.pg_supported = false;
if (device.version_major > MEI_HBM_MAJOR_VERSION_PGI ||
(device.version_major == MEI_HBM_MAJOR_VERSION_PGI &&
device.version_minor >= MEI_HBM_MINOR_VERSION_PGI))
device.pg_supported = true;
device.dc_supported = false;
if (device.version_major >= MEI_HBM_MAJOR_VERSION_DC)
device.dc_supported = true;
device.ie_supported = false;
if (device.version_major >= MEI_HBM_MAJOR_VERSION_IE)
device.ie_supported = true;
device.dot_supported = false;
if (device.version_major >= MEI_HBM_MAJOR_VERSION_DOT)
device.dot_supported = true;
device.ev_supported = false;
if (device.version_major >= MEI_HBM_MAJOR_VERSION_EV)
device.ev_supported = true;
device.fa_supported = false;
if (device.version_major >= MEI_HBM_MAJOR_VERSION_FA)
device.fa_supported = true;
device.os_supported = false;
if (device.version_major >= MEI_HBM_MAJOR_VERSION_OS)
device.os_supported = true;
device.dr_supported = false;
if (device.version_major > MEI_HBM_MAJOR_VERSION_DR ||
(device.version_major == MEI_HBM_MAJOR_VERSION_DR &&
device.version_minor >= MEI_HBM_MINOR_VERSION_DR))
device.dr_supported = true;
device.vt_supported = false;
if (device.version_major > MEI_HBM_MAJOR_VERSION_VT ||
(device.version_major == MEI_HBM_MAJOR_VERSION_VT &&
device.version_minor >= MEI_HBM_MINOR_VERSION_VT))
device.vt_supported = true;
device.cap_supported = false;
if (device.version_major > MEI_HBM_MAJOR_VERSION_CAP ||
(device.version_major == MEI_HBM_MAJOR_VERSION_CAP &&
device.version_minor >= MEI_HBM_MINOR_VERSION_CAP))
device.cap_supported = true;
device.cd_supported = false;
if (device.version_major > MEI_HBM_MAJOR_VERSION_CD ||
(device.version_major == MEI_HBM_MAJOR_VERSION_CD &&
device.version_minor >= MEI_HBM_MINOR_VERSION_CD))
device.cd_supported = true;
// LOG("power gating isolation %d", device.pg_supported);
// LOG("dynamic clients %d", device.dc_supported);
// LOG("disconnect on timeout %d", device.dot_supported);
// LOG("event notification %d", device.ev_supported);
// LOG("fixed address client %d", device.fa_supported);
// LOG("immediate reply to enum request %d", device.ie_supported);
// LOG("support OS ver message %d", device.os_supported);
// LOG("dma ring %d", device.dr_supported);
// LOG("vtag %d", device.vt_supported);
// LOG("capabilities message %d", device.cap_supported);
// LOG("client dma %d", device.cd_supported);
device.dr_supported = false;
device.cd_supported = false;
}
void SurfaceManagementEngineDriver::resetBus() {
if (ipts_client)
ipts_client->active = false;
init_timeout->cancelTimeout();
bus.state = MEIBusIdle;
}
IOReturn SurfaceManagementEngineDriver::enterPowerGating() {
UInt32 reg = readRegister(MEI_H_D0I3C);
if (!(reg & MEI_H_D0I3C_I3)) {
reg |= MEI_H_D0I3C_I3;
reg &= ~MEI_H_D0I3C_IR;
writeRegister(reg, MEI_H_D0I3C);
}
device.pg_state = MEIPowerGatingOn;
device.pg_event = MEIPowerGatingEventIdle;
LOG("Enter d0i3 mode");
return kIOReturnSuccess;
}
IOReturn SurfaceManagementEngineDriver::enterPowerGatingSync() {
IOReturn ret;
AbsoluteTime abstime, deadline;
UInt32 reg = readRegister(MEI_H_D0I3C);
if (reg & MEI_H_D0I3C_I3) {
LOG("No need to enter d0i3");
goto on;
}
// PGI entry procedure
device.pg_event = MEIPowerGatingEventWait;
ret = sendPowerGatingCommand(true);
if (ret != kIOReturnSuccess) {
LOG("Failed to send power gating command");
/* FIXME: should we reset here? */
goto out;
}
nanoseconds_to_absolutetime(MEI_POWER_GATING_ISO_TIMEOUT * 1000000000ULL, &abstime);
clock_absolutetime_interval_to_deadline(abstime, &deadline);
command_gate->commandSleep(&wait_power_gating, deadline, THREAD_INTERRUPTIBLE);
if (device.pg_event != MEIPowerGatingEventReceived) {
ret = kIOReturnTimeout;
goto out;
}
// end PGI entry procedure
device.pg_event = MEIPowerGatingInterruptWait;
reg = readRegister(MEI_H_D0I3C);
reg |= MEI_H_D0I3C_I3;
reg |= MEI_H_D0I3C_IR;
writeRegister(reg, MEI_H_D0I3C);
/* read it to ensure HW consistency */
reg = readRegister(MEI_H_D0I3C);
if (!(reg & MEI_H_D0I3C_CIP))
goto on;
nanoseconds_to_absolutetime((UInt64)MEI_D0I3_TIMEOUT * 1000000000ULL, &abstime);
clock_absolutetime_interval_to_deadline(abstime, &deadline);
command_gate->commandSleep(&wait_power_gating, deadline, THREAD_INTERRUPTIBLE);
if (device.pg_event != MEIPowerGatingInterruptReceived) {
reg = readRegister(MEI_H_D0I3C);
if (!(reg & MEI_H_D0I3C_I3)) {
ret = kIOReturnTimeout;
goto out;
}
}
on:
ret = kIOReturnSuccess;
device.pg_state = MEIPowerGatingOn;
LOG("Enter d0i3 mode");
out:
device.pg_event = MEIPowerGatingEventIdle;
return ret;
}
IOReturn SurfaceManagementEngineDriver::exitPowerGatingSync() {
IOReturn ret;
AbsoluteTime abstime, deadline;
device.pg_event = MEIPowerGatingInterruptWait;
UInt32 reg = readRegister(MEI_H_D0I3C);
if (!(reg & MEI_H_D0I3C_I3)) {
LOG("No need to exit d0i3");
goto off;
}
reg &= ~MEI_H_D0I3C_I3;
reg |= MEI_H_D0I3C_IR;
writeRegister(reg, MEI_H_D0I3C);
reg = readRegister(MEI_H_D0I3C);
if (!(reg & MEI_H_D0I3C_CIP))
goto off;
nanoseconds_to_absolutetime(MEI_D0I3_TIMEOUT * 1000000000ULL, &abstime);
clock_absolutetime_interval_to_deadline(abstime, &deadline);
command_gate->commandSleep(&wait_power_gating, deadline, THREAD_INTERRUPTIBLE);
if (device.pg_event != MEIPowerGatingInterruptReceived) {
reg = readRegister(MEI_H_D0I3C);
if (reg & MEI_H_D0I3C_I3) {
ret = kIOReturnTimeout;
goto out;
}
}
off:
ret = kIOReturnSuccess;
device.pg_state = MEIPowerGatingOff;
LOG("Exit d0i3 mode");
out:
device.pg_event = MEIPowerGatingEventIdle;
return ret;
}
void SurfaceManagementEngineDriver::readMessage(UInt8 *buffer, UInt16 buffer_len) {
UInt32 *buf = reinterpret_cast(buffer);
for (; buffer_len >= MEI_SLOT_SIZE; buffer_len -= MEI_SLOT_SIZE)
*buf++ = readRegister(MEI_ME_CB_RW);
if (buffer_len > 0) {
UInt32 reg = readRegister(MEI_ME_CB_RW);
memcpy(buf, ®, buffer_len);
}
setHostInterrupt();
}
IOReturn SurfaceManagementEngineDriver::writeMessage(UInt8 *header, UInt16 header_len, UInt8 *data, UInt16 data_len) {
if (!header || !data || header_len % MEI_SLOT_SIZE) {
LOG("Message invalid!");
return kIOReturnInvalid;
}
UInt8 empty_slots;
if (findEmptySlots(&empty_slots) != kIOReturnSuccess) {
LOG("WTF? Filled slots is bigger than host buffer");
return kIOReturnOverrun;
}
UInt8 slots_needed = MEI_DATA_TO_SLOTS(header_len + data_len);
if (slots_needed > empty_slots) {
LOG("Message too large! need %d, empty %d", slots_needed, empty_slots);
return kIOReturnMessageTooLarge;
}
const MEI_SLOT_TYPE *buf = reinterpret_cast(header);
for (int i = 0; i < header_len / MEI_SLOT_SIZE; i++)
writeRegister(buf[i], MEI_H_CB_WW);
buf = reinterpret_cast(data);
for (int i = 0; i < data_len / MEI_SLOT_SIZE; i++)
writeRegister(buf[i], MEI_H_CB_WW);
UInt8 tail = data_len % MEI_SLOT_SIZE;
if (tail > 0) {
UInt32 reg = 0;
memcpy(®, data + data_len - tail, tail);
writeRegister(reg, MEI_H_CB_WW);
}
setHostInterrupt();
if (!isHardwareReady()) {
LOG("WTF? Hardware is not ready yet");
return kIOReturnIOError;
}
return kIOReturnSuccess;
}
inline void SurfaceManagementEngineDriver::setupMessageHeader(MEIBusMessageHeader *header, UInt16 length) {
memset(header, 0, sizeof(MEIBusMessageHeader));
header->length = length;
header->msg_complete = 1;
}
IOReturn SurfaceManagementEngineDriver::writeHostMessage(MEIBusMessageHeader *header, MEIBusMessage *msg) {
return writeMessage(reinterpret_cast(header), sizeof(MEIBusMessageHeader), reinterpret_cast(msg), header->length);
}
IOReturn SurfaceManagementEngineDriver::sendClientMessage(SurfaceManagementEngineClient *client, UInt8 *buffer, UInt16 buffer_len, bool blocking) {
return command_gate->runAction(client_msg_action, client, buffer, &buffer_len, &blocking);
}
IOReturn SurfaceManagementEngineDriver::sendClientMessageGated(SurfaceManagementEngineClient *client, UInt8 *buffer, UInt16 *buffer_len, bool *blocking) {
if (device.state != MEIDeviceEnabled || !client->active)
return kIOReturnNoDevice;
if (*buffer_len > client->properties.max_msg_length)
return kIOReturnMessageTooLarge;
if (device.pg_state == MEIPowerGatingOn && exitPowerGatingSync() != kIOReturnSuccess) {
LOG("Failed to get device active");
return kIOReturnAborted;
}
MEIClientTransaction *tx = new MEIClientTransaction;
tx->client = client;
tx->data_len = *buffer_len;
tx->data = new UInt8[tx->data_len];
memcpy(tx->data, buffer, tx->data_len);
tx->completed = false;
tx->blocking = *blocking;
IOReturn ret = kIOReturnSuccess;
if (acquireWriteBuffer() && submitTransaction(tx)) {
delete[] tx->data;
delete tx;
} else {
enqueue(&bus.tx_queue, &tx->entry);
if (tx->blocking) {
AbsoluteTime abstime, deadline;
nanoseconds_to_absolutetime(MEI_CLIENT_SEND_MSG_TIMEOUT * 1000000ULL, &abstime);
clock_absolutetime_interval_to_deadline(abstime, &deadline);
command_gate->commandSleep(&tx->wait, deadline, THREAD_INTERRUPTIBLE);
if (!tx->completed) {
LOG("Failed to send message!");
ret = kIOReturnTimeout;
}
remqueue(&tx->entry);
delete[] tx->data;
delete tx;
}
}
idle_timeout->setTimeoutMS(MEI_DEVICE_IDLE_TIMEOUT * 1000);
return ret;
}
IOReturn SurfaceManagementEngineDriver::sendStartRequest() {
MEIBusMessageHeader header;
MEIBusHostVersionRequest req;
setupMessageHeader(&header, sizeof(req));
memset(&req, 0, sizeof(req));
req.cmd = MEI_HOST_START_REQ_CMD;
req.host_version_major = MEI_HBM_MAJOR_VERSION;
req.host_version_minor = MEI_HBM_MINOR_VERSION;
return writeHostMessage(&header, MEI_TO_MSG(&req));
}
IOReturn SurfaceManagementEngineDriver::sendPowerGatingCommand(bool enter) {
if (!device.pg_supported)
return kIOReturnNotPermitted;
UInt8 cmd;
if (enter)
cmd = MEI_PG_ISOLATION_ENTRY_REQ_CMD;
else
cmd = MEI_PG_ISOLATION_EXIT_REQ_CMD;
MEIBusMessageHeader header;
MEIBusPowerGatingRequest req;
setupMessageHeader(&header, sizeof(req));
memset(&req, 0, sizeof(req));
req.cmd = cmd;
return writeHostMessage(&header, MEI_TO_MSG(&req));
}
IOReturn SurfaceManagementEngineDriver::sendStopRequest() {
MEIBusMessageHeader header;
MEIBusHostStopRequest req;
setupMessageHeader(&header, sizeof(req));
memset(&req, 0, sizeof(req));
req.cmd = MEI_HOST_STOP_REQ_CMD;
req.reason = DriverStopRequest;
return writeHostMessage(&header, MEI_TO_MSG(&req));
}
IOReturn SurfaceManagementEngineDriver::sendCapabilityRequest() {
MEIBusMessageHeader header;
MEIBusCapabilityRequest req;
setupMessageHeader(&header, sizeof(req));
memset(&req, 0, sizeof(req));
req.cmd = MEI_CAPABILITIES_REQ_CMD;
if (device.vt_supported)
req.capability_requested[0] |= MEI_HBM_CAP_VTAG;
if (device.cd_supported)
req.capability_requested[0] |= MEI_HBM_CAP_CLIENT_DMA;
IOReturn ret = writeHostMessage(&header, MEI_TO_MSG(&req));
if (ret != kIOReturnSuccess)
return ret;
bus.state = MEIBusSetupCap;
init_timeout->setTimeoutMS(MEI_CLIENTS_INIT_TIMEOUT * 1000);
return kIOReturnSuccess;
}
IOReturn SurfaceManagementEngineDriver::sendClientEnumerationRequest() {
MEIBusMessageHeader header;
MEIBusHostEnumerationRequest req;
setupMessageHeader(&header, sizeof(req));
memset(&req, 0, sizeof(req));
req.cmd = MEI_HOST_ENUM_REQ_CMD;
req.flags |= device.dc_supported ? MEI_HBM_ENUM_ALLOW_ADD_FLAG : 0;
req.flags |= device.ie_supported ? MEI_HBM_ENUM_IMMEDIATE_FLAG : 0;
IOReturn ret = writeHostMessage(&header, MEI_TO_MSG(&req));
if (ret != kIOReturnSuccess)
return ret;
bus.state = MEIBusEnumerateClients;
init_timeout->setTimeoutMS(MEI_CLIENTS_INIT_TIMEOUT * 1000);
return kIOReturnSuccess;
}
IOReturn SurfaceManagementEngineDriver::sendClientPropertyRequest(UInt start_idx) {
UInt addr = bitmap_find_next_bit(me_client_map, MEI_MAX_CLIENT_NUM, start_idx);
// We got all client properties
if (addr == MEI_MAX_CLIENT_NUM) {
bus.state = MEIBusStarted;
device.state = MEIDeviceEnabled;
device.reset_cnt = 0;
rescan_work->interruptOccurred(nullptr, this, 0);
// Enable idle (d0i3 mode)
idle_timeout->setTimeoutMS(MEI_DEVICE_IDLE_TIMEOUT * 1000);
return kIOReturnSuccess;
}
MEIBusMessageHeader header;
MEIBusClientPropertyRequest req;
setupMessageHeader(&header, sizeof(req));
memset(&req, 0, sizeof(req));
req.cmd = MEI_HOST_CLIENT_PROP_REQ_CMD;
req.me_addr = addr;
IOReturn ret = writeHostMessage(&header, MEI_TO_MSG(&req));
if (ret != kIOReturnSuccess)
return ret;
init_timeout->setTimeoutMS(MEI_CLIENTS_INIT_TIMEOUT * 1000);
return kIOReturnSuccess;
}
IOReturn SurfaceManagementEngineDriver::sendAddClientResponse(UInt8 me_addr, MEIHostBusMessageReturnType status) {
MEIBusMessageHeader header;
MEIBusAddClientResponse res;
setupMessageHeader(&header, sizeof(res));
memset(&res, 0, sizeof(res));
res.cmd = MEI_ADD_CLIENT_RES_CMD;
res.me_addr = me_addr;
res.status = status;
return writeHostMessage(&header, MEI_TO_MSG(&res));
}
void SurfaceManagementEngineDriver::scheduleReset(IOInterruptEventSource *sender, int count) {
clearInterrupts();
IOReturn ret = resetDevice();
if (device.state == MEIDeviceDisabled) {
LOG("Error! Device disabled");
return;
}
// retry in case of failure
if (ret != kIOReturnSuccess)
reset_work->interruptOccurred(nullptr, this, 0);
}
void SurfaceManagementEngineDriver::scheduleRescan(IOInterruptEventSource *sender, int count) {
if (!ipts_client->active) {
LOG("Seems the client has been removed by hardware");
ipts_client->stop(this);
ipts_client->detach(this);
OSSafeReleaseNULL(ipts_client);
} else if (!ipts_client->initial) {
// Disabled due to bus reset
LOG("Reconnecting client...");
ipts_client->hostRequestReconnect();
return;
} else {
LOG("Starting client...");
if (!ipts_client->attach(this) || !ipts_client->start(this)) {
LOG("Failed to start client");
ipts_client->detach(this);
OSSafeReleaseNULL(ipts_client);
}
}
}
void SurfaceManagementEngineDriver::scheduleResume(IOInterruptEventSource *sender, int count) {
if (exitPowerGatingSync() != kIOReturnSuccess) {
LOG("Warning! Exit d0i3 failed. Resetting...");
reset_work->interruptOccurred(nullptr, this, 0);
}
}
bool SurfaceManagementEngineDriver::filterInterrupt(IOFilterInterruptEventSource *sender) {
UInt32 hcsr = readRegister(MEI_H_CSR);
return (hcsr & MEI_H_CSR_INT_STA_MASK) != 0;
}
void SurfaceManagementEngineDriver::handleInterrupt(IOInterruptEventSource *sender, int count) {
UInt8 rx_slots = 0;
disableInterrupts();
UInt32 hcsr = readRegister(MEI_H_CSR);
clearInterrupts();
/* check if ME wants a reset */
if (!isHardwareReady() && device.state != MEIDeviceResetting) {
LOG("Hardware not ready! Resetting...");
reset_work->interruptOccurred(nullptr, this, 0);
goto end;
}
if (readRegister(MEI_ME_CSR) & MEI_ME_CSR_RESET)
setHostInterrupt();
handlePowerGatingInterrupt(hcsr & MEI_H_CSR_INT_STA_MASK);
// Check if we need to start the device
if (!isHostReady()) {
if (isHardwareReady()) {
LOG("We need to start the device");
command_gate->commandWakeup(&wait_hw_ready);
} else {
LOG("Spurious Interrupt");
}
goto end;
}
// Check slots available for reading
if (countRxSlots(&rx_slots) == kIOReturnSuccess) {
while (rx_slots > 0) {
IOReturn ret = handleRead(&rx_slots);
/* There is a race between ME write and interrupt delivery:
* Not all data is always available immediately after the
* interrupt, so try to read again on the next interrupt.
*/
if (ret == kIOReturnNotReadable)
break;
if (ret != kIOReturnSuccess &&
(device.state != MEIDeviceResetting && device.state != MEIDevicePowerDown)) {
LOG("Read message failed! Resetting...");
reset_work->interruptOccurred(nullptr, this, 0);
goto end;
}
}
}
bus.tx_buf_ready = calcFilledSlots() == 0;
/*
* During PG handshake only allowed write is the replay to the
* PG exit message, so block calling write function
* if the pg event is in PG handshake
*/
if (device.pg_event != MEIPowerGatingEventWait && device.pg_event != MEIPowerGatingEventReceived) {
handleWrite();
bus.tx_buf_ready = calcFilledSlots() == 0;
}
end:
enableInterrupts();
}
void SurfaceManagementEngineDriver::handlePowerGatingInterrupt(UInt32 source) {
if (device.pg_event == MEIPowerGatingInterruptWait && source & MEI_H_CSR_D0I3C_INT_STA) {
device.pg_event = MEIPowerGatingInterruptReceived;
if (device.pg_state == MEIPowerGatingOn) {
device.pg_state = MEIPowerGatingOff;
if (bus.state != MEIBusIdle) {
// Force MEI_H_CSR_READY because it could be wiped off during PG
LOG("d0i3 set host ready");
enableDevice();
}
} else
device.pg_state = MEIPowerGatingOn;
command_gate->commandWakeup(&wait_power_gating);
}
if (device.pg_state == MEIPowerGatingOn && (source & MEI_H_CSR_INT_STA)) {
/*
* HW sent some data and we are in D0i3,
* so we got here because of HW initiated exit from D0i3.
*/
LOG("Resuming from d0i3");
resume_work->interruptOccurred(nullptr, this, 0);
}
}
IOReturn SurfaceManagementEngineDriver::handleRead(UInt8 *filled_slots) {
MEIBusMessageHeader *msg_hdr;
MEIBusExtendedMetaHeader *meta_hdr = nullptr;
IOReturn ret = kIOReturnSuccess;
if (!bus.rx_msg_hdr[0]) {
bus.rx_msg_hdr[0] = readRegister(MEI_ME_CB_RW);
bus.rx_msg_hdr_len = 1;
(*filled_slots)--;
UInt16 expected_len = 0;
msg_hdr = reinterpret_cast(bus.rx_msg_hdr);
if (msg_hdr->dma_ring)
expected_len += MEI_SLOT_SIZE;
if (msg_hdr->extended)
expected_len += MEI_SLOT_SIZE;
if (!bus.rx_msg_hdr[0] || msg_hdr->reserved || msg_hdr->length < expected_len) {
LOG("Error! Corrupted message header 0x%08X", bus.rx_msg_hdr[0]);
return kIOReturnInvalid;
}
}
msg_hdr = reinterpret_cast(bus.rx_msg_hdr);
if (MEI_SLOTS_TO_DATA(*filled_slots) < msg_hdr->length) {
LOG("Error! Less data available than length=%08x.", *filled_slots);
/* we can't read the message right now */
return kIOReturnNotReadable;
}
int ext_hdr_len = 1;
UInt16 hdr_size_left = msg_hdr->length;
if (msg_hdr->extended) {
LOG("Got extended header");
if (!bus.rx_msg_hdr[1]) {
bus.rx_msg_hdr[1] = readRegister(MEI_ME_CB_RW);
bus.rx_msg_hdr_len++;
(*filled_slots)--;
}
meta_hdr = reinterpret_cast(&bus.rx_msg_hdr[1]);
UInt16 hdr_size_ext = sizeof(MEIBusExtendedMetaHeader) + MEI_SLOTS_TO_DATA(meta_hdr->size);
if (hdr_size_left < hdr_size_ext) {
LOG("Error! Corrupted message header len %d", msg_hdr->length);
return kIOReturnInvalid;
}
hdr_size_left -= hdr_size_ext;
ext_hdr_len = meta_hdr->size + 2; // 2 = MEIBusMessageHeader + MEIBusExtendedMetaHeader
for (int i = bus.rx_msg_hdr_len; i < ext_hdr_len; i++) {
bus.rx_msg_hdr[i] = readRegister(MEI_ME_CB_RW);
bus.rx_msg_hdr_len++;
(*filled_slots)--;
}
}
if (msg_hdr->dma_ring) {
LOG("Got dma ring set");
if (hdr_size_left != MEI_SLOT_SIZE) {
LOG("Error! Corrupted message header len %d", msg_hdr->length);
return kIOReturnInvalid;
}
bus.rx_msg_hdr[ext_hdr_len] = readRegister(MEI_ME_CB_RW);
bus.rx_msg_hdr_len++;
(*filled_slots)--;
msg_hdr->length -= MEI_SLOT_SIZE;
}
if (msg_hdr->host_addr == 0 && msg_hdr->me_addr == 0) {
// Host message
ret = handleHostMessage(msg_hdr);
if (ret != kIOReturnSuccess) {
LOG("Handle message failed!");
return ret;
}
} else {
// Client message
if (!ipts_client || !ipts_client->active || msg_hdr->me_addr != ipts_client->addr) {
/*
* A message for not connected fixed address clients should be silently discarded
* On power down client may be force cleaned, silently discard such messages
*/
if ((msg_hdr->host_addr == 0 && msg_hdr->me_addr != 0) || device.state == MEIDevicePowerDown) {
discardMessage(msg_hdr, msg_hdr->length);
ret = kIOReturnSuccess;
} else {
LOG("No destination client found 0x%08X", bus.rx_msg_hdr[0]);
return kIOReturnInvalid;
}
} else
ret = handleClientMessage(ipts_client, msg_hdr, meta_hdr);
}
// Reset the number of slots and header
memset(bus.rx_msg_hdr, 0, sizeof(bus.rx_msg_hdr));
bus.rx_msg_hdr_len = 0;
if (countRxSlots(filled_slots) != kIOReturnSuccess) {
LOG("Resetting due to slots overflow");
return kIOReturnOverrun;
}
return ret;
}
IOReturn SurfaceManagementEngineDriver::handleHostMessage(MEIBusMessageHeader *header) {
MEIBusHostVersionResponse *version_res;
MEIBusClientPropertyResponse *props_res;
MEIBusHostEnumerationResponse *enum_res;
MEIBusAddClientRequest *add_client_req;
MEIBusCapabilityResponse *cap_res;
MEIHostBusMessageReturnType status;
IOReturn ret;
// read the message to our buffer
if (header->length >= sizeof(bus.rx_msg_buf)) {
LOG("WTF? Message length larger than rx_msg_buf");
return kIOReturnError;
}
readMessage(bus.rx_msg_buf, header->length);
MEIBusMessage *mei_msg = reinterpret_cast(bus.rx_msg_buf);
// MEIBusClientCommand *cl_cmd = reinterpret_cast(mei_msg);
/*
* ignore spurious message and prevent reset nesting
* bus is put to idle during system reset
*/
if (bus.state == MEIBusIdle) {
LOG("Bus state is idle, ignore spurious messages");
return kIOReturnSuccess;
}
switch (mei_msg->cmd) {
case MEI_HOST_START_RES_CMD:
LOG("Start response message received");
init_timeout->cancelTimeout();
version_res = reinterpret_cast(mei_msg);
// LOG("MEI Bus Version: DRIVER=%02d:%02d DEVICE=%02d:%02d", MEI_HBM_MAJOR_VERSION, MEI_HBM_MINOR_VERSION,
// version_res->me_max_version_major, version_res->me_max_version_minor);
if (version_res->host_version_supported) {
device.version_major = MEI_HBM_MAJOR_VERSION;
device.version_minor = MEI_HBM_MINOR_VERSION;
} else {
device.version_major = version_res->me_max_version_major;
device.version_minor = version_res->me_max_version_minor;
}
if (!isBusMessageVersionSupported()) {
LOG("Warning, start version mismatch - stopping the driver");
bus.state = MEIBusStopped;
if (sendStopRequest() != kIOReturnSuccess) {
LOG("Error! Failed to send stop request");
return kIOReturnIOError;
}
break;
}
configDeviceFeatures();
if (device.state != MEIDeviceInitClients || bus.state != MEIBusStarting) {
if (device.state == MEIDevicePowerDown) {
LOG("Start on shutdown, ignoring");
return kIOReturnSuccess;
}
LOG("Error! Start state mismatch, [%d, %d]", device.state, bus.state);
return kIOReturnError;
}
if (device.cap_supported) {
if (sendCapabilityRequest() != kIOReturnSuccess) {
LOG("Capabilities request failed");
return kIOReturnIOError;
}
command_gate->commandWakeup(&wait_bus_start);
break;
}
if (sendClientEnumerationRequest() != kIOReturnSuccess) {
LOG("Enumeration request failed");
return kIOReturnIOError;
}
command_gate->commandWakeup(&wait_bus_start);
break;
case MEI_CAPABILITIES_RES_CMD:
LOG("Capabilities response message received");
init_timeout->cancelTimeout();
if (device.state != MEIDeviceInitClients || bus.state != MEIBusSetupCap) {
if (device.state == MEIDevicePowerDown) {
LOG("Capabilities response on shutdown, ignoring");
return kIOReturnSuccess;
}
LOG("Error! Capabilities response state mismatch, [%d, %d]", device.state, bus.state);
return kIOReturnError;
}
cap_res = reinterpret_cast(mei_msg);
if (!(cap_res->capability_granted[0] & MEI_HBM_CAP_VTAG))
device.vt_supported = false;
if (!(cap_res->capability_granted[0] & MEI_HBM_CAP_CLIENT_DMA))
device.cd_supported = false;
if (sendClientEnumerationRequest() != kIOReturnSuccess) {
LOG("Enumeration request failed");
return kIOReturnIOError;
}
break;
case MEI_HOST_ENUM_RES_CMD:
LOG("Enumeration response message received");
init_timeout->cancelTimeout();
enum_res = reinterpret_cast(mei_msg);
memcpy(me_client_map, enum_res->valid_addresses, sizeof(enum_res->valid_addresses));
if (device.state != MEIDeviceInitClients || bus.state != MEIBusEnumerateClients) {
if (device.state == MEIDevicePowerDown) {
LOG("enumeration response on shutdown, ignoring");
return kIOReturnSuccess;
}
LOG("Error! Enumeration response state mismatch, [%d, %d]", device.state, bus.state);
return kIOReturnError;
}
bus.state = MEIBusRequestingClientProps;
// First client property request
if (sendClientPropertyRequest(0) != kIOReturnSuccess) {
LOG("Error! Properties request failed");
return kIOReturnIOError;
}
break;
case MEI_HOST_CLIENT_PROP_RES_CMD:
LOG("Property response message received");
init_timeout->cancelTimeout();
if (device.state != MEIDeviceInitClients || bus.state != MEIBusRequestingClientProps) {
if (device.state == MEIDevicePowerDown) {
LOG("Properties response on shutdown, ignoring");
return kIOReturnSuccess;
}
LOG("Error! Properties response state mismatch, [%d, %d]", device.state, bus.state);
return kIOReturnError;
}
props_res = reinterpret_cast(mei_msg);
if (props_res->status == MEIHostBusMessageReturnClientNotFound) {
LOG("Warning, client %d not found", props_res->me_addr);
} else if (props_res->status != MEIHostBusMessageReturnSuccess) {
LOG("Error! Properties response wrong status = %d", props_res->status);
return kIOReturnError;
} else {
if (addClient(&props_res->client_properties, props_res->me_addr) == kIOReturnInvalid) {
uuid_t swapped_uuid;
uuid_string_t uuid_str;
uuid_copy(swapped_uuid, props_res->client_properties.uuid);
*(reinterpret_cast(swapped_uuid)) = OSSwapInt32(*(reinterpret_cast(swapped_uuid)));
*(reinterpret_cast(swapped_uuid) + 2) = OSSwapInt16(*(reinterpret_cast(swapped_uuid) + 2));
*(reinterpret_cast(swapped_uuid) + 3) = OSSwapInt16(*(reinterpret_cast(swapped_uuid) + 3));
uuid_unparse_lower(swapped_uuid, uuid_str);
LOG("Unknown MEI client with uuid %s", uuid_str);
LOG("Ignore non IPTS client, continue to request client properties");
}
}
// Request property for next client
if (sendClientPropertyRequest(props_res->me_addr + 1) != kIOReturnSuccess) {
LOG("Error! Properties request failed");
return kIOReturnIOError;
}
break;
case MEI_PG_ISOLATION_ENTRY_RES_CMD:
LOG("Power gating isolation entry response received");
if (device.pg_state != MEIPowerGatingOff || device.pg_event != MEIPowerGatingEventWait) {
LOG("Power gating entry response, state mismatch [%d, %d]", device.pg_state, device.pg_event);
return kIOReturnError;
}
device.pg_event = MEIPowerGatingEventReceived;
command_gate->commandWakeup(&wait_power_gating);
break;
case MEI_PG_ISOLATION_EXIT_REQ_CMD:
LOG("Power gating isolation exit request received");
if (device.pg_state != MEIPowerGatingOn ||
(device.pg_event != MEIPowerGatingEventWait && device.pg_event != MEIPowerGatingEventIdle)) {
LOG("Power gating exit response state mismatch [%d, %d]", device.pg_state, device.pg_event);
return kIOReturnError;
}
switch (device.pg_event) {
case MEIPowerGatingEventWait:
device.pg_event = MEIPowerGatingEventReceived;
command_gate->commandWakeup(&wait_power_gating);
break;
case MEIPowerGatingEventIdle:
/*
* If the driver is not waiting on this then
* this is HW initiated exit from PG.
*/
device.pg_event = MEIPowerGatingEventReceived;
resume_work->interruptOccurred(nullptr, this, 0);
break;
default:
return kIOReturnError;
}
break;
case MEI_HOST_STOP_RES_CMD:
LOG("Stop response message received");
init_timeout->cancelTimeout();
if (bus.state != MEIBusStopped) {
LOG("Error! Stop response state mismatch, [%d, %d]", device.state, bus.state);
return kIOReturnError;
}
device.state = MEIDevicePowerDown;
// force the reset
return kIOReturnError;
case MEI_ME_STOP_REQ_CMD:
LOG("Stop request message received");
bus.state = MEIBusStopped;
if (sendStopRequest() != kIOReturnSuccess) {
LOG("Error! Stop request failed");
return kIOReturnIOError;
}
break;
case MEI_ADD_CLIENT_REQ_CMD:
LOG("Add client request received");
// After the host receives the enum resp message clients may be added or removed
if (bus.state <= MEIBusEnumerateClients || bus.state >= MEIBusStopped) {
LOG("Error! Add client state mismatch, [%d, %d]", device.state, bus.state);
return kIOReturnError;
}
add_client_req = reinterpret_cast(mei_msg);
status = MEIHostBusMessageReturnSuccess;
ret = addClient(&add_client_req->client_properties, add_client_req->me_addr);
if (ret == kIOReturnInvalid)
status = MEIHostBusMessageReturnRejected;
else if (ret != kIOReturnSuccess)
status = MEIHostBusMessageReturnClientNotFound;
if (device.state == MEIDeviceEnabled)
rescan_work->interruptOccurred(nullptr, this, 0);
if (sendAddClientResponse(add_client_req->me_addr, status) != kIOReturnSuccess) {
LOG("Error! Failed to send add client response");
return kIOReturnIOError;
}
break;
default:
LOG("WTF? Unknown command %X", mei_msg->cmd);
return kIOReturnError;
}
return kIOReturnSuccess;
}
IOReturn SurfaceManagementEngineDriver::handleClientMessage(SurfaceManagementEngineClient *client, MEIBusMessageHeader *mei_hdr, MEIBusExtendedMetaHeader *meta) {
UInt16 data_len;
UInt16 length = mei_hdr->length;
if (mei_hdr->extended || mei_hdr->dma_ring)
goto discard;
data_len = length + client->rx_cache_pos;
if (client->properties.max_msg_length < data_len) {
LOG("Warning, message overflow. client max msg size %d, rx msg size %d", client->properties.max_msg_length, data_len);
goto discard;
}
readMessage(client->rx_cache + client->rx_cache_pos, length);
client->rx_cache_pos += length;
if (mei_hdr->msg_complete)
client->messageComplete();
idle_timeout->setTimeoutMS(MEI_DEVICE_IDLE_TIMEOUT * 1000);
return kIOReturnSuccess;
discard:
discardMessage(mei_hdr, length);
return kIOReturnSuccess;
}
void SurfaceManagementEngineDriver::discardMessage(MEIBusMessageHeader *hdr, UInt16 discard_len) {
readMessage(bus.rx_msg_buf, discard_len);
}
IOReturn SurfaceManagementEngineDriver::handleWrite() {
if (!acquireWriteBuffer())
return kIOReturnAborted;
MEIClientTransaction *tx;
qe_foreach_element_safe(tx, &bus.tx_queue, entry) {
if (submitTransaction(tx))
completeTransaction(tx);
}
return kIOReturnSuccess;
}
void SurfaceManagementEngineDriver::completeTransaction(MEIClientTransaction *tx) {
if (tx->blocking)
command_gate->commandWakeup(&tx->wait);
else {
remqueue(&tx->entry);
delete[] tx->data;
delete tx;
}
}
bool SurfaceManagementEngineDriver::submitTransaction(MEIClientTransaction *tx) {
MEIBusMessageHeader msg_hdr;
msg_hdr.host_addr = 0;
msg_hdr.me_addr = tx->client->addr;
msg_hdr.internal = false;
msg_hdr.extended = false;
msg_hdr.length = 0;
UInt16 hdr_len = sizeof(MEIBusMessageHeader) + msg_hdr.length;
UInt16 data_len;
UInt8 empty_slots;
if (findEmptySlots(&empty_slots) != kIOReturnSuccess) {
LOG("Write buffer overflow detected");
return false;
}
UInt16 empty_len = MEI_SLOTS_TO_DATA(empty_slots) & MEI_MSG_MAX_LEN_MASK;
/**
* Split the message only if we can write the whole host buffer
* otherwise wait for next time the host buffer is empty.
*/
if (hdr_len + tx->data_len <= empty_len) {
data_len = tx->data_len;
msg_hdr.msg_complete = 1;
} else if (empty_slots == device.tx_buf_depth) {
data_len = empty_len - hdr_len;
msg_hdr.msg_complete = 0;
} else
return false;
msg_hdr.length += data_len;
if (writeMessage(reinterpret_cast(&msg_hdr), hdr_len, tx->data, data_len) != kIOReturnSuccess)
return true; // delete this transaction in case of error but leave tx->completed=false
if (msg_hdr.msg_complete) {
tx->completed = true;
return true;
} else {
tx->data += data_len;
tx->data_len -= data_len;
return false;
}
}
void SurfaceManagementEngineDriver::enterIdle(IOTimerEventSource *timer) {
IOReturn ret;
if (isWriteQueueEmpty())
ret = enterPowerGatingSync();
else
ret = kIOReturnBusy;
if (ret != kIOReturnSuccess && ret != kIOReturnBusy) {
LOG("Warning! Enter d0i3 failed. Resetting...");
reset_work->interruptOccurred(nullptr, this, 0);
} else if (ret == kIOReturnBusy)
idle_timeout->setTimeoutMS(MEI_DEVICE_IDLE_TIMEOUT * 1000);
}
void SurfaceManagementEngineDriver::initialiseTimeout(IOTimerEventSource *timer) {
if (device.state == MEIDeviceInitClients && bus.state != MEIBusIdle) {
LOG("Init clients timeout");
resetDevice();
}
}
IOReturn SurfaceManagementEngineDriver::addClient(MEIClientProperty *client_props, UInt8 addr) {
if (uuid_compare(SURFACE_IPTS_CLIENT_UUID, client_props->uuid) != 0)
return kIOReturnInvalid;
if (!ipts_client) {
ipts_client = OSTypeAlloc(SurfaceManagementEngineClient);
if (!ipts_client || !ipts_client->init()) {
LOG("Failed to create ipts client");
OSSafeReleaseNULL(ipts_client);
return kIOReturnError;
}
}
ipts_client->resetProperties(client_props, addr);
return kIOReturnSuccess;
}
================================================
FILE: BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineDriver.hpp
================================================
//
// SurfaceManagementEngineDriver.hpp
// SurfaceTouchScreen
//
// Created by Xavier on 2022/05/28.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#ifndef SurfaceManagementEngineDriver_hpp
#define SurfaceManagementEngineDriver_hpp
#include
#include
#include
#include
#include
#include
#include "MEIProtocol.h"
#define kIOPMPowerOff 0
#define kIOPMNumberPowerStates 2
static IOPMPowerState MyIOPMPowerStates[kIOPMNumberPowerStates] = {
{1, kIOPMPowerOff, kIOPMPowerOff, kIOPMPowerOff, 0, 0, 0, 0, 0, 0, 0, 0},
{1, kIOPMPowerOn, kIOPMPowerOn, kIOPMPowerOn, 0, 0, 0, 0, 0, 0, 0, 0}
};
enum MEIDeviceState {
MEIDeviceInitializing = 0,
MEIDeviceInitClients,
MEIDeviceEnabled,
MEIDeviceResetting,
MEIDeviceDisabled,
MEIDevicePowerDown,
MEIDevicePowerUp,
};
/**
* enum MEIBusState - host bus message protocol state
*
* @MEIBusIdle : protocol not started
* @MEIBusStarting : start request message was sent
* @MEIBusSetupCap : capabilities request message was sent
* @MEIBusSetupDMARing : dma ring setup request message was sent
* @MEIBusEnumerateClients : enumeration request was sent
* @MEIBusRequestingClientProps : acquiring clients properties
* @MEIBusStarted : enumeration was completed
* @MEIBusStopped : stopping exchange
*/
enum MEIBusState {
MEIBusIdle = 0,
MEIBusStarting,
MEIBusSetupCap,
MEIBusSetupDMARing,
MEIBusEnumerateClients,
MEIBusRequestingClientProps,
MEIBusStarted,
MEIBusStopped,
};
/**
* enum MEIPowerGatingEvent - power gating transition events
*
* @MEIPowerGatingEventIdle : the driver is not in power gating transition
* @MEIPowerGatingEventWait : the driver is waiting for a pg event to complete
* @MEIPowerGatingEventReceived : the driver received pg event
* @MEIPowerGatingInterruptWait : the driver is waiting for a pg event interrupt
* @MEIPowerGatingInterruptReceived : the driver received pg event interrupt
*/
enum MEIPowerGatingEvent {
MEIPowerGatingEventIdle,
MEIPowerGatingEventWait,
MEIPowerGatingEventReceived,
MEIPowerGatingInterruptWait,
MEIPowerGatingInterruptReceived,
};
/**
* enum MEIPowerGatingState - device internal power gating state
*
* @MEIPowerGatingOff : device is not power gated - it is active
* @MEIPowerGatingOn : device is power gated - it is in lower power state
*/
enum MEIPowerGatingState {
MEIPowerGatingOff = 0,
MEIPowerGatingOn = 1,
};
struct MEIPhysicalDevice {
IOPCIDevice* pci_dev;
IOMemoryMap* mmap;
MEIDeviceState state;
MEIPowerGatingEvent pg_event;
MEIPowerGatingState pg_state;
queue_head_t write_q;
queue_head_t write_waiting_q;
queue_head_t write_ctrl_q;
queue_head_t read_ctrl_q;
int reset_cnt;
UInt8 tx_buf_depth;
UInt8 version_minor;
UInt8 version_major;
bool pg_supported; // power gating isolation
bool dc_supported; // dynamic clients
bool dot_supported; // disconnect on timeout
bool ev_supported; // event notification
bool fa_supported; // fixed address client
bool ie_supported; // immediate reply to enum request
bool os_supported; // support OS ver message
bool dr_supported; // dma ring
bool vt_supported; // vtag
bool cap_supported; // capabilities message
bool cd_supported; // client dma
};
class SurfaceManagementEngineClient;
struct MEIClientTransaction {
queue_entry entry;
SurfaceManagementEngineClient *client;
UInt8* data;
UInt16 data_len;
bool completed;
bool blocking;
bool wait;
};
struct MEIBus {
MEIBusState state;
UInt8 rx_msg_buf[MEI_RX_MSG_BUF_SIZE];
MEI_SLOT_TYPE rx_msg_hdr[MEI_RX_MSG_BUF_SIZE];
int rx_msg_hdr_len;
bool tx_buf_ready;
UInt8 tx_queue_limit;
queue_head_t tx_queue;
};
UUID_DEFINE(SURFACE_IPTS_CLIENT_UUID, 0x70, 0x08, 0x8d, 0x3e, 0x1a, 0x27, 0x08, 0x42, 0x8e, 0xb5, 0x9a, 0xcb, 0x94, 0x02, 0xae, 0x04);
/*
* Implements a MEI based IPTS driver
* fixed_addr=12 vt_supported=0
*/
class EXPORT SurfaceManagementEngineDriver : public IOService {
OSDeclareDefaultStructors(SurfaceManagementEngineDriver);
public:
bool init(OSDictionary* properties) override;
IOService* probe(IOService* provider, SInt32* score) override;
bool start(IOService* provider) override;
void stop(IOService* provider) override;
void free() override;
IOReturn setPowerState(unsigned long whichState, IOService *whatDevice) override;
IOReturn sendClientMessage(SurfaceManagementEngineClient *client, UInt8 *buffer, UInt16 buffer_len, bool blocking);
protected:
IOReturn mapMemory();
void unmapMemory();
private:
IOWorkLoop* work_loop {nullptr};
IOCommandGate* command_gate {nullptr};
IOFilterInterruptEventSource* interrupt_source {nullptr};
IOInterruptEventSource* reset_work {nullptr};
IOInterruptEventSource* rescan_work {nullptr};
IOInterruptEventSource* resume_work {nullptr};
IOTimerEventSource* init_timeout {nullptr};
IOTimerEventSource* idle_timeout {nullptr};
SurfaceManagementEngineClient* ipts_client {nullptr};
IOCommandGate::Action client_msg_action {nullptr};
MEIPhysicalDevice device;
MEIBus bus;
UInt8 me_client_map[MEI_MAX_CLIENT_NUM/8];
bool awake {true};
bool wait_hw_ready {false};
bool wait_bus_start {false};
bool wait_power_gating {false};
void releaseResources();
IOReturn startDeviceGated();
void stopDeviceGated();
IOReturn restartDeviceGated();
inline UInt32 readRegister(int offset);
inline void writeRegister(UInt32 value, int offset);
UInt8 calcFilledSlots();
IOReturn findEmptySlots(UInt8 *empty_slots);
IOReturn countRxSlots(UInt8 *filled_slots);
bool acquireWriteBuffer();
bool isHardwareReady();
bool isHostReady();
bool isBusMessageVersionSupported();
bool isWriteQueueEmpty();
inline void setHostCSR(UInt32 hcsr);
IOReturn initDevice();
void configDevice();
IOReturn resetDevice();
void deresetDevice();
void enableDevice();
IOReturn waitDeviceReady();
void configDeviceFeatures();
void resetBus();
void clearInterrupts();
void enableInterrupts();
void disableInterrupts();
void setHostInterrupt();
IOReturn enterPowerGating();
IOReturn enterPowerGatingSync();
IOReturn exitPowerGatingSync();
void readMessage(UInt8 *buffer, UInt16 buffer_len);
IOReturn writeMessage(UInt8 *header, UInt16 header_len, UInt8 *data, UInt16 data_len);
inline void setupMessageHeader(MEIBusMessageHeader *header, UInt16 length);
IOReturn writeHostMessage(MEIBusMessageHeader *header, MEIBusMessage *msg);
IOReturn sendClientMessageGated(SurfaceManagementEngineClient *client, UInt8 *buffer, UInt16 *buffer_len, bool *blocking);
IOReturn sendStartRequest();
IOReturn sendStopRequest();
IOReturn sendPowerGatingCommand(bool enter);
IOReturn sendCapabilityRequest();
IOReturn sendClientEnumerationRequest();
IOReturn sendClientPropertyRequest(UInt client_idx);
IOReturn sendAddClientResponse(UInt8 me_addr, MEIHostBusMessageReturnType status);
void scheduleReset(IOInterruptEventSource *sender, int count);
void scheduleRescan(IOInterruptEventSource *sender, int count);
void scheduleResume(IOInterruptEventSource *sender, int count);
bool filterInterrupt(IOFilterInterruptEventSource *sender);
void handleInterrupt(IOInterruptEventSource *sender, int count);
void handlePowerGatingInterrupt(UInt32 source);
IOReturn handleRead(UInt8 *filled_slots);
IOReturn handleHostMessage(MEIBusMessageHeader *hdr);
IOReturn handleClientMessage(SurfaceManagementEngineClient *client, MEIBusMessageHeader *mei_hdr, MEIBusExtendedMetaHeader *meta);
void discardMessage(MEIBusMessageHeader *hdr, UInt16 discard_len);
IOReturn handleWrite();
void completeTransaction(MEIClientTransaction *tx);
bool submitTransaction(MEIClientTransaction *tx);
void enterIdle(IOTimerEventSource *timer);
void initialiseTimeout(IOTimerEventSource *timer);
IOReturn addClient(MEIClientProperty *client_props, UInt8 addr);
};
#endif /* SurfaceManagementEngineDriver_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceSerialHub/SerialProtocol.h
================================================
//
// SerialProtocol.h
// SurfaceSerialHub
//
// Created by Xavier on 2021/10/29.
// Copyright © 2021 Xia Shangning. All rights reserved.
//
#ifndef SerialProtocol_h
#define SerialProtocol_h
#include "../helpers.hpp"
/* SSH Protocol Config see https://github.com/linux-surface/surface-aggregator-module/blob/master/doc/requests.txt for reference*/
#define SSH_TC_SAM 0x01 /* Generic system functionality, real-time clock. */
#define SSH_TC_BAT 0x02 /* Battery/power subsystem. */
#define SSH_TC_TMP 0x03 /* Thermal subsystem. */
#define SSH_TC_PMC 0x04
#define SSH_TC_FAN 0x05
#define SSH_TC_PoM 0x06
#define SSH_TC_DBG 0x07
#define SSH_TC_KBD 0x08 /* Legacy keyboard (Laptop 1/2). */
#define SSH_TC_FWU 0x09
#define SSH_TC_UNI 0x0a
#define SSH_TC_LPC 0x0b
#define SSH_TC_TCL 0x0c /* Telemetry, Crashdumps, and Logs? */
#define SSH_TC_SFL 0x0d
#define SSH_TC_KIP 0x0e /* Keyboard and Integrated Peripherals. (hotplug stuff) */
#define SSH_TC_EXT 0x0f
#define SSH_TC_BLD 0x10
#define SSH_TC_BAS 0x11 /* Detachment system (Surface Book 2/3). */
#define SSH_TC_SEN 0x12
#define SSH_TC_SRQ 0x13
#define SSH_TC_MCU 0x14
#define SSH_TC_HID 0x15 /* User Input/HID subsystem (Keyboard + Touchpad). */
#define SSH_TC_TCH 0x16
#define SSH_TC_BKL 0x17
#define SSH_TC_TAM 0x18
#define SSH_TC_ACC0 0x19
#define SSH_TC_UFI 0x1a
#define SSH_TC_USC 0x1b
#define SSH_TC_PEN 0x1c
#define SSH_TC_VID 0x1d
#define SSH_TC_AUD 0x1e
#define SSH_TC_SMC 0x1f
#define SSH_TC_KPD 0x20
#define SSH_TC_REG 0x21 /* Event/notifier registry. */
#define SSH_TC_SPT 0x22
#define SSH_TC_SYS 0x23
#define SSH_TC_ACC1 0x24
#define SSH_TC_SHB 0x25
#define SSH_TC_POS 0x26 /* Laptop Studio screen position. */
#define SSH_TC_COUNT 0x26
#define SSH_TID_PRIMARY 0x01
#define SSH_TID_SECONDARY 0x02
/* TC=0x01 */
#define SSH_CID_SAM_ENABLE_EVENT 0x0B
#define SSH_CID_SAM_DISABLE_EVENT 0x0C
#define SSH_CID_SAM_VERSION 0x13
#define SSH_CID_SAM_DISPLAY_OFF 0x15
#define SSH_CID_SAM_DISPLAY_ON 0x16
#define SSH_CID_SAM_D0_EXIT 0x33
#define SSH_CID_SAM_D0_ENTRY 0x34
/* TC=0x02 */
#define SSH_CID_BAT_STA 0x01
#define SSH_CID_BAT_BIX 0x02
#define SSH_CID_BAT_BST 0x03
#define SSH_CID_BAT_PMAX 0x0B
#define SSH_CID_BAT_PSOC 0x0C
#define SSH_CID_BAT_PSR 0x0D
#define SSH_EVENT_CID_BAT_BIX 0x15
#define SSH_EVENT_CID_BAT_BST 0x16
#define SSH_EVENT_CID_BAT_PSR 0x17
/* TC=0x03 */
#define SSH_CID_TMP_SENSOR 0x01
#define SSH_CID_TMP_GET_PERF 0x02
#define SSH_CID_TMP_SET_PERF 0x03
#define SSH_TEMP_SENSOR_MB1 0x01
#define SSH_TEMP_SENSOR_MB2 0x02
#define SSH_TEMP_SENSOR_MB3 0x03
#define SSH_TEMP_SENSOR_MB4 0x04
#define SSH_TEMP_SENSOR_BAT 0x05
#define SSH_TEMP_SENSOR_GPU 0x06
#define SSH_TEMP_SENSOR_SSD 0x07
#define SSH_TEMP_SENSOR_SOC 0x08
/* TC=0x08 */
#define SSH_CID_KBD_GET_DESCRIPTOR 0x00
#define SSH_CID_KBD_SET_CAPS_LED 0x01
#define SSH_CID_KBD_GET_FEAT_REPORT 0x0B
#define SSH_EVENT_CID_KBD_INPUT_GENERIC 0x03
#define SSH_EVENT_CID_KBD_INPUT_HOTKEYS 0x04
/* TC=0x0e */
#define SSH_CID_KIP_ENABLE_EVENT 0x27
#define SSH_CID_KIP_DISABLE_EVENT 0x28
/* TC=0x15 */
#define SSH_CID_HID_OUT_REPORT 0x01
#define SSH_CID_HID_GET_FEAT_REPORT 0x02
#define SSH_CID_HID_SET_FEAT_REPORT 0x03
#define SSH_CID_HID_GET_DESCRIPTOR 0x04
#define SSH_EVENT_CID_HID_INPUT 0x00
/* TC=0x21 */
#define SSH_CID_REG_ENABLE_EVENT 0x01
#define SSH_CID_REG_DISABLE_EVENT 0x02
#define SSH_EVENT_FLAG_SEQUENCED BIT(0)
#define SSH_SYN_BYTE_1 0xAA
#define SSH_SYN_BYTE_2 0x55
#define SSH_SYN_BYTES 0x55AA /* Together as a 16-bit integer*/
#define SSH_FRAME_TYPE_NAK 0x04 /* Sent on error in previously received message. */
#define SSH_FRAME_TYPE_ACK 0x40 /* Sent to acknowledge receival of DATA frame. */
#define SSH_FRAME_TYPE_DATA_SEQ 0x80 /* Sent to transfer data. Sequenced. */
#define SSH_FRAME_TYPE_DATA_NSQ 0x00 /* Same as DATA_SEQ, but does not need to be ACKed. */
#define SSH_PAYLOAD_TYPE_COMMAND 0x80
/*
* -- SYN FRAME CRC(F) PAYLOAD CRC(P) --
* CMD+DATA
*/
#define SSH_PAYLOAD_OFFSET sizeof(SurfaceSerialMessage)
#ifndef PACKED
#define PACKED __attribute__((packed))
#endif
struct PACKED SurfaceSerialFrame {
UInt8 type;
UInt16 length;
UInt8 seq_id;
};
struct PACKED SurfaceSerialPayload {
UInt8 type;
UInt8 data[];
};
struct PACKED SurfaceSerialCommand {
UInt8 type; /* command type payload = 0x80 */
UInt8 target_category;
UInt8 target_id_out; /* to SAM (request) */
UInt8 target_id_in; /* from SAM (response) */
UInt8 instance_id;
UInt16 request_id; /* request<->response, events->reserved id set by command `enable event source`*/
UInt8 command_id;
UInt8 data[];
};
struct PACKED SurfaceSerialMessage {
UInt16 syn;
SurfaceSerialFrame frame;
UInt16 frame_crc;
UInt8 payload[];
};
struct PACKED SurfaceSerialEventData {
UInt8 target_category;
UInt8 flags;
UInt16 request_id; /* the request id used for the event*/
UInt8 instance_id;
};
#define CRC_INITIAL 0xFFFF
UInt16 const crc_ccitt_false_table[256] = {
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
};
static inline UInt16 crc_ccitt_false_byte(UInt16 crc, const UInt8 c)
{
return (crc << 8) ^ crc_ccitt_false_table[(crc >> 8) ^ c];
}
inline UInt16 crc_ccitt_false(UInt16 crc, UInt8 const* buffer, size_t len)
{
while (len--)
crc = crc_ccitt_false_byte(crc, *buffer++);
return crc;
}
#endif /* SerialProtocol_h */
================================================
FILE: BigSurface/BigSurface/SurfaceSerialHub/SurfaceSerialHubDriver.cpp
================================================
//
// SurfaceSerialHubDriver.cpp
// SurfaceSerialHub
//
// Created by Xavier on 2021/10/29.
// Copyright © 2021 Xia Shangning. All rights reserved.
//
#include "SurfaceSerialHubDriver.hpp"
#include "../../../Dependencies/VoodooSerial/VoodooSerial/ACPIParser/VoodooACPIResourcesParser.hpp"
#include "../SurfaceSerialHubDevices/SurfaceBatteryNub.hpp"
#include "../SurfaceSerialHubDevices/SurfaceHIDNub.hpp"
struct SurfaceSerialEventRegistryConfig {
UInt8 target_category;
UInt8 target_id;
UInt8 cid_enable;
UInt8 cid_disable;
};
static const SurfaceSerialEventRegistryConfig event_conf[] = {
{SSH_TC_SAM, SSH_TID_PRIMARY, SSH_CID_SAM_ENABLE_EVENT, SSH_CID_SAM_DISABLE_EVENT},
{SSH_TC_REG, SSH_TID_SECONDARY, SSH_CID_REG_ENABLE_EVENT, SSH_CID_REG_DISABLE_EVENT},
{SSH_TC_KIP, SSH_TID_SECONDARY, SSH_CID_KIP_ENABLE_EVENT, SSH_CID_KIP_DISABLE_EVENT},
};
OSDefineMetaClassAndAbstractStructors(SurfaceSerialHubClient, IOService);
#define super IOService
OSDefineMetaClassAndStructors(SurfaceSerialHubDriver, IOService);
void err_dump(const char *name, const char *str, UInt8 *buffer, UInt16 len) {
IOLog("%s::%s\n", name, str);
if (len == 0)
return;
IOLog("%s::msg dump: length: %d\n", name, len);
int row = (len-1)/16 + 1;
for (int r=0; r= 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)
return false;
// minimum length required for data transfer is 0x08=sizeof(SurfaceSerialFrame)
if (len >= 4 && buffer[1]==SSH_FRAME_TYPE_DATA_NSQ && buffer[2]interruptOccurred(nullptr, this, 0);
}
void SurfaceSerialHubDriver::processReceivedBuffer(IOInterruptEventSource *sender, int count) {
while (ring_buffer[current].filled_len) {
_process(ring_buffer[current].buffer, ring_buffer[current].filled_len);
ring_buffer[current].filled_len = 0;
current = SSH_RING_BUFFER_NEXT(current);
}
}
void SurfaceSerialHubDriver::_process(UInt8 *buffer, UInt16 length) {
if (length == 0)
return;
if (rx_msg.partial_syn) {
if (judge_sync(buffer, length)) {
processMessage();
rx_msg.pos = 1;
rx_msg.cache[0] = SSH_SYN_BYTE_1;
} else {
rx_msg.cache[rx_msg.pos++] = SSH_SYN_BYTE_1;
}
rx_msg.partial_syn = false;
}
int end = find_sync_bytes(buffer, length);
if (end != -1) { // found sync bytes
if (end > 0) {
memcpy(rx_msg.cache+rx_msg.pos, buffer, end);
rx_msg.pos += end;
}
if (rx_msg.pos > 0) { // a message is completed
processMessage();
buffer += end;
length -= end;
}
rx_msg.pos = 2;
rx_msg.cache[0] = SSH_SYN_BYTE_1;
rx_msg.cache[1] = SSH_SYN_BYTE_2;
_process(buffer+2, length-2);
} else {
if (buffer[length-1] == SSH_SYN_BYTE_1) {
memcpy(rx_msg.cache+rx_msg.pos, buffer, length-1);
rx_msg.pos += length-1;
rx_msg.partial_syn = true;
} else {
memcpy(rx_msg.cache+rx_msg.pos, buffer, length);
rx_msg.pos += length;
}
if (rx_msg.pos >= 5 && rx_msg.len == SSH_MSG_LENGTH_UNKNOWN)
rx_msg.len = reinterpret_cast(rx_msg.cache)->frame.length+10;
if (rx_msg.pos == rx_msg.len) { // a message is completed
processMessage();
if (rx_msg.partial_syn) { // certainly another message
rx_msg.pos = 1;
rx_msg.cache[0] = SSH_SYN_BYTE_1;
rx_msg.partial_syn = false;
}
}
}
}
#define ERR_DUMP_MSG(str) err_dump(getName(), str, rx_msg.cache, rx_msg.pos)
IOReturn SurfaceSerialHubDriver::processMessage() {
if (rx_msg.pos < 10) {
sendNAK();
ERR_DUMP_MSG("Message received incomplete! Protential data loss!");
return kIOReturnError;
}
SurfaceSerialMessage *message = reinterpret_cast(rx_msg.cache);
SurfaceSerialCommand *command;
UInt8 *rx_data;
UInt16 calc_crc, crc, rx_data_len;
WaitingRequest *req;
PendingCommand *cmd;
bool found = false;
if (message->syn != SSH_SYN_BYTES) {
sendNAK();
ERR_DUMP_MSG("syn btyes error!");
return kIOReturnError;
}
if (message->frame_crc != crc_ccitt_false(CRC_INITIAL, rx_msg.cache+2, sizeof(SurfaceSerialFrame))) {
sendNAK();
ERR_DUMP_MSG("frame crc error!");
return kIOReturnError;
}
if (rx_msg.pos != message->frame.length+10) {
sendNAK();
ERR_DUMP_MSG("data length error!");
return kIOReturnError;
}
switch (message->frame.type) {
case SSH_FRAME_TYPE_ACK:
if (rx_msg.cache[SSH_PAYLOAD_OFFSET]!=0xFF || rx_msg.cache[SSH_PAYLOAD_OFFSET+1]!=0xFF) {
sendNAK();
ERR_DUMP_MSG("payload crc for ACK should be 0xFFFF!");
return kIOReturnError;
}
qe_foreach_element_safe(cmd, &pending_list, entry) {
SurfaceSerialMessage *pending_msg = reinterpret_cast(cmd->buffer);
if (pending_msg->frame.seq_id == message->frame.seq_id) {
found = true;
remqueue(&cmd->entry);
cmd->timer->cancelTimeout();
cmd->timer->disable();
work_loop->removeEventSource(cmd->timer);
OSSafeReleaseNULL(cmd->timer);
delete[] cmd->buffer;
delete cmd;
break;
}
}
if (!found)
DBG_LOG("Warning, no pending command found for seq_id %d", message->frame.seq_id);
break;
case SSH_FRAME_TYPE_NAK:
LOG("Warning, NAK received! Resending all pending messages!");
qe_foreach_element(cmd, &pending_list, entry) {
if (cmd->trial_count) { // not a NSQ command
cmd->trial_count = 1;
cmd->timer->cancelTimeout();
cmd->timer->setTimeoutUS(1);
}
}
break;
case SSH_FRAME_TYPE_DATA_SEQ:
sendACK(message->frame.seq_id);
case SSH_FRAME_TYPE_DATA_NSQ:
command = reinterpret_cast(rx_msg.cache+SSH_PAYLOAD_OFFSET);
rx_data = command->data;
rx_data_len = message->frame.length - sizeof(SurfaceSerialCommand);
calc_crc = crc_ccitt_false(CRC_INITIAL, rx_msg.cache+SSH_PAYLOAD_OFFSET, message->frame.length);
crc = *(reinterpret_cast(rx_data+rx_data_len));
if (crc != calc_crc) {
sendNAK();
ERR_DUMP_MSG("payload crc error!");
return kIOReturnError;
}
if (command->request_id >= SSH_REQID_MIN) { // a message
qe_foreach_element_safe(req, &waiting_list, entry) {
if (req->req_id == command->request_id) {
found = true;
if (rx_data_len) {
req->data = new UInt8[rx_data_len];
req->data_len = rx_data_len;
memcpy(req->data, rx_data, rx_data_len);
}
command_gate->commandWakeup(&req->waiting);
remqueue(&req->entry);
break;
}
}
if (!found)
DBG_LOG("Warning, received data with unknown tc %x, cid %x", command->target_category, command->command_id);
} else { // an event
if (!queue_empty(&event_handler_lists[command->request_id]) || !queue_empty(&event_handler_lists[0])) {
EventHandler *h;
bool handled = false;
qe_foreach_element(h, &event_handler_lists[0], entry) {
if (h->target_iid == 0 || h->target_iid == command->instance_id) {
h->client->eventReceived(command->target_category, command->target_id_in, command->instance_id, command->command_id, rx_data, rx_data_len);
handled = true;
}
}
qe_foreach_element(h, &event_handler_lists[command->request_id], entry) {
if (h->target_iid == 0 || h->target_iid == command->instance_id) {
h->client->eventReceived(command->target_category, command->target_id_in, command->instance_id, command->command_id, rx_data, rx_data_len);
handled = true;
}
}
if (!handled)
DBG_LOG("Warning, registered event unhandled with unknown iid %x (tc %x, cid %x)", command->instance_id, command->target_category, command->command_id);
} else
ERR_DUMP_MSG("Event unregistered!");
}
break;
default:
sendNAK();
ERR_DUMP_MSG("Unknown message type!");
return kIOReturnError;
}
rx_msg.pos = 0;
rx_msg.len = SSH_MSG_LENGTH_UNKNOWN;
return kIOReturnSuccess;
}
IOReturn SurfaceSerialHubDriver::sendACK(UInt8 seq_id) {
UInt8 buffer[SSH_PAYLOAD_OFFSET+2];
SurfaceSerialMessage *msg = reinterpret_cast(buffer);
msg->syn = SSH_SYN_BYTES;
msg->frame.type = SSH_FRAME_TYPE_ACK;
msg->frame.length = 0;
msg->frame.seq_id = seq_id;
msg->frame_crc = crc_ccitt_false(CRC_INITIAL, buffer+2, sizeof(SurfaceSerialFrame));
buffer[SSH_PAYLOAD_OFFSET] = 0xFF;
buffer[SSH_PAYLOAD_OFFSET+1] = 0xFF;
return uart_controller->transmitData(buffer, SSH_PAYLOAD_OFFSET+2);
}
IOReturn SurfaceSerialHubDriver::sendNAK() {
UInt8 buffer[SSH_PAYLOAD_OFFSET+2];
SurfaceSerialMessage *msg = reinterpret_cast(buffer);
msg->syn = SSH_SYN_BYTES;
msg->frame.type = SSH_FRAME_TYPE_NAK;
msg->frame.length = 0;
msg->frame.seq_id = 0;
msg->frame_crc = crc_ccitt_false(CRC_INITIAL, buffer+2, sizeof(SurfaceSerialFrame));
buffer[SSH_PAYLOAD_OFFSET] = 0xFF;
buffer[SSH_PAYLOAD_OFFSET+1] = 0xFF;
return uart_controller->transmitData(buffer, SSH_PAYLOAD_OFFSET+2);
}
UInt16 SurfaceSerialHubDriver::sendCommand(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *payload, UInt16 payload_len, bool seq) {
if (!awake)
return 0;
UInt16 len = sizeof(SurfaceSerialMessage)+sizeof(SurfaceSerialCommand)+payload_len+2;
UInt8 *buffer = new UInt8[len];
SurfaceSerialMessage *msg = reinterpret_cast(buffer);
msg->syn = SSH_SYN_BYTES;
msg->frame.type = seq ? SSH_FRAME_TYPE_DATA_SEQ : SSH_FRAME_TYPE_DATA_NSQ;
msg->frame.length = payload_len + 8;
msg->frame.seq_id = seq_counter.getID();
msg->frame_crc = crc_ccitt_false(CRC_INITIAL, buffer+2, sizeof(SurfaceSerialFrame));
SurfaceSerialCommand *cmd = reinterpret_cast(msg->payload);
cmd->type = SSH_PAYLOAD_TYPE_COMMAND;
cmd->target_category = tc;
cmd->target_id_out = tid;
cmd->target_id_in = 0x00;
cmd->instance_id = iid;
cmd->request_id = req_counter.getID();
cmd->command_id = cid;
if (payload_len > 0)
memcpy(cmd->data, payload, payload_len);
*(reinterpret_cast(cmd->data+payload_len)) = crc_ccitt_false(CRC_INITIAL, msg->payload, sizeof(SurfaceSerialCommand)+payload_len);
if (command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceSerialHubDriver::sendCommandGated), buffer, &len, &seq) != kIOReturnSuccess) {
LOG("Sending command failed!");
delete[] buffer;
return 0;
}
return cmd->request_id;
}
IOReturn SurfaceSerialHubDriver::sendCommandGated(UInt8 *tx_buffer, UInt16 *len, bool *seq) {
PendingCommand *cmd = new PendingCommand;
cmd->buffer = tx_buffer;
cmd->len = *len;
cmd->trial_count = *seq ? 1 : 0; // if no ACK is needed, count is set to 0
cmd->timer = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceSerialHubDriver::commandTimeout));
if (!cmd->timer) {
LOG("Could not create timer for sending command!");
delete cmd;
return kIOReturnError;
}
enqueue(&pending_list, &cmd->entry);
work_loop->addEventSource(cmd->timer);
cmd->timer->enable();
cmd->timer->setTimeoutUS(1);
return kIOReturnSuccess;
}
void SurfaceSerialHubDriver::commandTimeout(IOTimerEventSource* timer) {
PendingCommand *cmd;
bool found = false;
qe_foreach_element_safe(cmd, &pending_list, entry) {
if (cmd->timer == timer) {
found = true;
SurfaceSerialCommand *cmd_data = reinterpret_cast(cmd->buffer+sizeof(SurfaceSerialMessage));
if (cmd->trial_count == 0) {
if (uart_controller->transmitData(cmd->buffer, cmd->len) != kIOReturnSuccess)
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);
} else if (cmd->trial_count > SSH_CMD_TRAIL_CNT) {
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);
} else {
if (cmd->trial_count > 1)
DBG_LOG("Timeout, trial count: %d", cmd->trial_count);
if (uart_controller->transmitData(cmd->buffer, cmd->len) != kIOReturnSuccess)
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);
cmd->trial_count++;
cmd->timer->setTimeoutMS(SSH_ACK_TIMEOUT);
break;
}
remqueue(&cmd->entry);
cmd->timer->disable();
work_loop->removeEventSource(cmd->timer);
OSSafeReleaseNULL(cmd->timer);
delete[] cmd->buffer;
delete cmd;
break;
}
}
if (!found)
DBG_LOG("Warning, timeout occurred but find no timer");
}
IOReturn SurfaceSerialHubDriver::getResponse(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *payload, UInt16 payload_len, bool seq, UInt8 *buffer, UInt16 buffer_len) {
UInt16 req_id = sendCommand(tc, tid, iid, cid, payload, payload_len, seq);
if (req_id != 0)
return command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceSerialHubDriver::waitResponse), &req_id, buffer, &buffer_len);
return kIOReturnError;
}
IOReturn SurfaceSerialHubDriver::waitResponse(UInt16 *req_id, UInt8 *buffer, UInt16 *buffer_len) {
AbsoluteTime abstime, deadline;
IOReturn sleep;
WaitingRequest *w = new WaitingRequest;
w->waiting = false;
w->req_id = *req_id;
w->data = nullptr;
w->data_len = 0;
enqueue(&waiting_list, &w->entry);
nanoseconds_to_absolutetime(SSH_WAIT_TIMEOUT * 1000000, &abstime);
clock_absolutetime_interval_to_deadline(abstime, &deadline);
sleep = command_gate->commandSleep(&w->waiting, deadline, THREAD_INTERRUPTIBLE);
if (sleep == THREAD_TIMED_OUT) {
LOG("Timeout waiting for response");
remqueue(&w->entry);
delete w;
return kIOReturnTimeout;
}
if (*buffer_len != w->data_len)
DBG_LOG("Warning, given buffer_len(%d) and received data_len(%d) mismatched!", *buffer_len, w->data_len);
if (w->data_len) {
if (*buffer_len < w->data_len)
w->data_len = *buffer_len;
memcpy(buffer, w->data, w->data_len);
delete[] w->data;
}
delete w;
return kIOReturnSuccess;
}
IOReturn SurfaceSerialHubDriver::registerEvent(SurfaceSerialHubClient *client, SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid) {
if (type >= SurfaceSerialEventTypeCount)
return kIOReturnInvalid;
if (client) {
EventHandler *h;
if (tc == 0) { // debug event handler for all events
if (!queue_empty(&event_handler_lists[0])) {
LOG("Already has a debug handler!");
return kIOReturnNoResources;
}
} else {
qe_foreach_element(h, &event_handler_lists[tc], entry) {
if (h->client == client && (h->target_iid == iid || h->target_iid == 0 || iid == 0)) {
LOG("Event already registered!");
return kIOReturnAborted;
}
}
IOReturn ret = sendEventCommand(type, tc, iid, true);
if (ret != kIOReturnSuccess)
return ret;
}
h = new EventHandler;
h->target_iid = iid;
h->client = client;
enqueue(&event_handler_lists[tc], &h->entry);
return kIOReturnSuccess;
} else { // client = nullptr means only enabling the event
if (tc == 0)
return kIOReturnInvalid;
return sendEventCommand(type, tc, iid, true);
}
}
void SurfaceSerialHubDriver::unregisterEvent(SurfaceSerialHubClient *client, SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid) {
if (type >= SurfaceSerialEventTypeCount)
return;
if (client) {
EventHandler *h;
qe_foreach_element_safe(h, &event_handler_lists[tc], entry) {
if (h->client == client && (h->target_iid == iid || iid == 0)) {
if (tc != 0)
sendEventCommand(type, tc, iid, false);
remqueue(&h->entry);
delete h;
break;
}
}
} else if (tc != 0) {
sendEventCommand(type, tc, iid, false);
}
}
IOReturn SurfaceSerialHubDriver::sendEventCommand(SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid, bool enable) {
SurfaceSerialEventData payload;
payload.target_category = tc;
payload.instance_id = iid;
payload.request_id = tc;
payload.flags = SSH_EVENT_FLAG_SEQUENCED;
UInt8 ret;
UInt8 cid = enable ? event_conf[type].cid_enable : event_conf[type].cid_disable;
if (getResponse(event_conf[type].target_category, event_conf[type].target_id, 0, cid, reinterpret_cast(&payload), sizeof(SurfaceSerialEventData), true, &ret, 1) != kIOReturnSuccess || ret != 0) {
LOG("Unexpected response from event-%sable request", enable ? "en" : "dis");
return kIOReturnError;
}
return kIOReturnSuccess;
}
bool SurfaceSerialHubDriver::init(OSDictionary *properties) {
if (!super::init(properties))
return false;
memset(ring_buffer, 0, sizeof(ring_buffer));
memset(rx_msg.cache, 0, SSH_MSG_CACHE_SIZE);
rx_msg.pos = 0;
rx_msg.len = SSH_MSG_LENGTH_UNKNOWN;
rx_msg.partial_syn = false;
queue_head_init(pending_list);
queue_head_init(waiting_list);
for (int i=0; i < SSH_REQID_MIN; i++)
queue_head_init(event_handler_lists[i]);
return true;
}
IOService* SurfaceSerialHubDriver::probe(IOService *provider, SInt32 *score) {
if (!super::probe(provider, score))
return nullptr;
acpi_device = OSDynamicCast(IOACPIPlatformDevice, provider);
if (!acpi_device)
return nullptr;
if (getDeviceResources() != kIOReturnSuccess) {
LOG("Could not parse ACPI resources!");
return nullptr;
}
gpio_controller = getGPIOController();
if (!gpio_controller) {
LOG("Could not find GPIO controller, exiting");
return nullptr;
}
uart_controller = getUARTController();
if (!uart_controller) {
LOG("Could not find UART controller, exiting");
return nullptr;
}
// Give the UART controller some time to load
IOSleep(100);
// Allocate a ring buffer with size SSH_BUFFER_SIZE to store buffer from UART
for (int i=0; i < SSH_RING_BUFFER_SIZE; i++)
ring_buffer[i].buffer = new UInt8[fifo_size];
LOG("Surface Serial Hub found!");
return this;
}
bool SurfaceSerialHubDriver::start(IOService *provider) {
UInt32 version;
UInt8 ret;
if (!super::start(provider))
return false;
work_loop = IOWorkLoop::workLoop();
if (!work_loop) {
LOG("Could not get work loop");
goto exit;
}
command_gate = IOCommandGate::commandGate(this);
if (!command_gate) {
LOG("Could not open command gate");
goto exit;
}
work_loop->addEventSource(command_gate);
publish_timer = IOTimerEventSource::timerEventSource(this, OSMemberFunctionCast(IOTimerEventSource::Action, this, &SurfaceSerialHubDriver::delayedPublishingNubs));
if (!publish_timer) {
LOG("Could not create timer for publishing nubs!");
goto exit;
}
work_loop->addEventSource(publish_timer);
// publishing nubs after 20s
publish_timer->setTimeoutMS(20000);
uart_interrupt = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceSerialHubDriver::processReceivedBuffer));
if (!uart_interrupt) {
LOG("Could not create uart interrupt!");
goto exit;
}
work_loop->addEventSource(uart_interrupt);
uart_interrupt->enable();
gpio_interrupt = IOInterruptEventSource::interruptEventSource(this, OSMemberFunctionCast(IOInterruptEventAction, this, &SurfaceSerialHubDriver::gpioWakeUp), this, 0);
if (!gpio_interrupt) {
LOG("Could not create gpio interrupt!");
goto exit;
}
work_loop->addEventSource(gpio_interrupt);
gpio_interrupt->enable();
if (uart_controller->requestConnect(this, OSMemberFunctionCast(VoodooUARTController::MessageHandler, this, &SurfaceSerialHubDriver::bufferReceived), baudrate, data_bits, stop_bits, parity, flow_control) != kIOReturnSuccess) {
LOG("Failed to connect to UART controller!");
goto exit;
}
if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_VERSION, nullptr, 0, true, reinterpret_cast(&version), 4) != kIOReturnSuccess) {
LOG("Failed to get SAM version! UART probably misconfigured!");
goto exit_connected;
}
LOG("SAM version %u.%u.%u", (version >> 24) & 0xff, (version >> 8) & 0xffff, version & 0xff);
if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_D0_ENTRY, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)
DBG_LOG("Unexpected response from D0-entry notification, ret=%x", ret);
if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_DISPLAY_ON, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)
DBG_LOG("Unexpected response from display-on notification, ret=%x", ret);
PMinit();
uart_controller->joinPMtree(this);
registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);
registerService();
return true;
exit_connected:
uart_controller->requestDisconnect(this);
exit:
releaseResources();
return false;
}
void SurfaceSerialHubDriver::stop(IOService *provider) {
UInt8 ret;
getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_DISPLAY_OFF, nullptr, 0, true, &ret, 1);
getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_D0_EXIT, nullptr, 0, true, &ret, 1);
uart_controller->requestDisconnect(this);
PMstop();
releaseResources();
super::stop(provider);
}
void SurfaceSerialHubDriver::free() {
super::free();
}
IOReturn SurfaceSerialHubDriver::flushCacheGated() {
// Clear pending commands, rx_buffer and msg cache
PendingCommand *cmd;
if (!queue_empty(&pending_list)) {
DBG_LOG("There are still pending commands!");
qe_foreach_element_safe(cmd, &pending_list, entry) {
remqueue(&cmd->entry);
cmd->timer->cancelTimeout();
cmd->timer->disable();
work_loop->removeEventSource(cmd->timer);
OSSafeReleaseNULL(cmd->timer);
delete[] cmd->buffer;
delete cmd;
}
}
if (ring_buffer[current].filled_len) {
DBG_LOG("There are still raw data unprocessed!");
while (ring_buffer[current].filled_len) {
ring_buffer[current].filled_len = 0;
current = (current + 1) % SSH_RING_BUFFER_SIZE;
}
}
rx_msg.pos = 0;
rx_msg.len = SSH_MSG_LENGTH_UNKNOWN;
rx_msg.partial_syn = false;
return kIOReturnSuccess;
}
IOReturn SurfaceSerialHubDriver::setPowerState(unsigned long whichState, IOService *whatDevice) {
if (whatDevice != this)
return kIOReturnInvalid;
if (whichState == 0) {
if (awake) {
UInt8 ret;
if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_DISPLAY_OFF, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)
DBG_LOG("Unexpected response from display-off notification");
if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_D0_EXIT, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)
DBG_LOG("Unexpected response from d0-exit notification");
uart_interrupt->disable();
awake = false;
command_gate->runAction(OSMemberFunctionCast(IOCommandGate::Action, this, &SurfaceSerialHubDriver::flushCacheGated));
DBG_LOG("Going to sleep");
}
} else {
if (!awake) {
uart_interrupt->enable();
awake = true;
UInt8 ret;
if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_D0_ENTRY, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)
DBG_LOG("Unexpected response from D0-entry notification, ret=%x", ret);
if (getResponse(SSH_TC_SAM, SSH_TID_PRIMARY, 0, SSH_CID_SAM_DISPLAY_ON, nullptr, 0, true, &ret, 1) != kIOReturnSuccess || ret != 0)
DBG_LOG("Unexpected response from display-on notification, ret=%x", ret);
DBG_LOG("Woke up");
}
}
return kIOPMAckImplied;
}
void SurfaceSerialHubDriver::releaseResources() {
if (battery_nub) {
battery_nub->stop(this);
battery_nub->detach(this);
OSSafeReleaseNULL(battery_nub);
}
if (hid_nub) {
hid_nub->stop(this);
hid_nub->detach(this);
OSSafeReleaseNULL(hid_nub);
}
EventHandler *h;
for (int i=0; i < SSH_REQID_MIN; i++) {
qe_foreach_element_safe(h, &event_handler_lists[i], entry) {
remqueue(&h->entry);
delete h;
}
}
WaitingRequest *req;
qe_foreach_element_safe(req, &waiting_list, entry) {
remqueue(&req->entry);
if (req->data_len)
delete[] req->data;
delete req;
}
PendingCommand *cmd;
qe_foreach_element_safe(cmd, &pending_list, entry) {
remqueue(&cmd->entry);
cmd->timer->cancelTimeout();
cmd->timer->disable();
work_loop->removeEventSource(cmd->timer);
OSSafeReleaseNULL(cmd->timer);
delete[] cmd->buffer;
delete cmd;
}
for (int i=0; i < SSH_RING_BUFFER_SIZE; i++) {
delete[] ring_buffer[i].buffer;
}
if (uart_interrupt) {
uart_interrupt->disable();
work_loop->removeEventSource(uart_interrupt);
OSSafeReleaseNULL(uart_interrupt);
}
if (gpio_interrupt) {
gpio_interrupt->disable();
work_loop->removeEventSource(gpio_interrupt);
OSSafeReleaseNULL(gpio_interrupt);
}
if (publish_timer) {
publish_timer->cancelTimeout();
publish_timer->disable();
work_loop->removeEventSource(publish_timer);
OSSafeReleaseNULL(publish_timer);
}
if (command_gate) {
work_loop->removeEventSource(command_gate);
OSSafeReleaseNULL(command_gate);
}
OSSafeReleaseNULL(work_loop);
}
VoodooGPIO* SurfaceSerialHubDriver::getGPIOController() {
VoodooGPIO* gpio_controller = nullptr;
// Wait for GPIO controller, up to 1 second
OSDictionary* name_match = serviceMatching("VoodooGPIO");
IOService* matched = waitForMatchingService(name_match, 1000000000);
gpio_controller = OSDynamicCast(VoodooGPIO, matched);
if (gpio_controller != NULL)
DBG_LOG("Got GPIO Controller! %s", gpio_controller->getName());
OSSafeReleaseNULL(name_match);
OSSafeReleaseNULL(matched);
return gpio_controller;
}
VoodooUARTController* SurfaceSerialHubDriver::getUARTController() {
// Wait for UART controller, up to 1 second, try for 5 times
// Sometimes it takes really a long time for UART to load
for (int i=0; i < 5; i++) {
OSDictionary* name_match = serviceMatching("VoodooUARTController");
IOService* matched = waitForMatchingService(name_match, 1000000000);
VoodooUARTController* uart = OSDynamicCast(VoodooUARTController, matched);
OSSafeReleaseNULL(name_match);
OSSafeReleaseNULL(matched);
if (uart) {
DBG_LOG("Got UART Controller! %s", uart->getName());
return uart;
}
IOSleep(1000);
}
return nullptr;
}
IOReturn SurfaceSerialHubDriver::getDeviceResources() {
VoodooACPIResourcesParser parser;
OSObject *result = nullptr;
OSData *data = nullptr;
if (acpi_device->evaluateObject("_CRS", &result) != kIOReturnSuccess ||
!(data = OSDynamicCast(OSData, result))) {
LOG("Could not find or evaluate _CRS method");
OSSafeReleaseNULL(result);
return kIOReturnNotFound;
}
UInt8 const* crs = reinterpret_cast(data->getBytesNoCopy());
UInt32 length = data->getLength();
parser.parseACPIResources(crs, 0, length);
OSSafeReleaseNULL(data);
if (!parser.found_uart || !parser.found_gpio_interrupts)
return kIOReturnNoResources;
DBG_LOG("Found valid UART bus and GPIO interrupt!");
// LOG("resource_consumer %d", parser.uart_info.resource_consumer);
// LOG("device_initiated %d", parser.uart_info.device_initiated);
// LOG("flow_control %d", parser.uart_info.flow_control);
// LOG("stop_bits %d", parser.uart_info.stop_bits);
// LOG("data_bits %d", parser.uart_info.data_bits);
// LOG("big_endian %d", parser.uart_info.big_endian);
// LOG("baudrate %u", parser.uart_info.baudrate);
// LOG("rx_fifo %d", parser.uart_info.rx_fifo);
// LOG("tx_fifo %d", parser.uart_info.tx_fifo);
// LOG("parity %d", parser.uart_info.parity);
// LOG("dtd_enabled %d", parser.uart_info.dtd_enabled);
// LOG("ri_enabled %d", parser.uart_info.ri_enabled);
// LOG("dsr_enabled %d", parser.uart_info.dsr_enabled);
// LOG("dtr_enabled %d", parser.uart_info.dtr_enabled);
// LOG("cts_enabled %d", parser.uart_info.cts_enabled);
// LOG("rts_enabled %d", parser.uart_info.rts_enabled);
baudrate = parser.uart_info.baudrate;
data_bits = parser.uart_info.data_bits;
stop_bits = parser.uart_info.stop_bits;
parity = parser.uart_info.parity;
flow_control = parser.uart_info.flow_control != 0;
// For SP6, UART bus reports a rx_fifo of size 32 yet the UART device reports itself with a fifo size 64
fifo_size = 64; //parser.uart_info.rx_fifo;
gpio_pin = parser.gpio_interrupts.pin_number;
gpio_irq = 0x00000001; // Set irq type to edge rising
return kIOReturnSuccess;
}
void SurfaceSerialHubDriver::delayedPublishingNubs(IOTimerEventSource *sender) {
battery_nub = OSTypeAlloc(SurfaceBatteryNub);
if (!battery_nub || !battery_nub->init() || !battery_nub->attach(this)) {
LOG("Failed to init Surface Battery nub!");
OSSafeReleaseNULL(battery_nub);
} else {
if (!battery_nub->start(this)) {
LOG("Failed to attach Surface Battery nub!");
battery_nub->detach(this);
OSSafeReleaseNULL(battery_nub);
} else
DBG_LOG("Surface Battery nub published!");
}
hid_nub = OSTypeAlloc(SurfaceHIDNub);
if (!hid_nub || !hid_nub->init() || !hid_nub->attach(this)) {
LOG("Failed to init Surface HID nub!");
OSSafeReleaseNULL(hid_nub);
} else {
if (!hid_nub->start(this)) {
LOG("Failed to attach Surface HID nub! Ignore this if you don't need HID nub");
hid_nub->detach(this);
OSSafeReleaseNULL(hid_nub);
} else
DBG_LOG("Surface HID nub published!");
}
}
void SurfaceSerialHubDriver::gpioWakeUp(IOInterruptEventSource *sender, int count) {
LOG("GPIO wake up event happened!");
}
IOReturn SurfaceSerialHubDriver::enableInterrupt(int source) {
return gpio_controller->enableInterrupt(gpio_pin);
}
IOReturn SurfaceSerialHubDriver::disableInterrupt(int source) {
return gpio_controller->disableInterrupt(gpio_pin);
}
IOReturn SurfaceSerialHubDriver::getInterruptType(int source, int* interrupt_type) {
return gpio_controller->getInterruptType(gpio_pin, interrupt_type);
}
IOReturn SurfaceSerialHubDriver::registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refcon) {
gpio_controller->setInterruptTypeForPin(gpio_pin, gpio_irq);
return gpio_controller->registerInterrupt(gpio_pin, target, handler, refcon);
}
IOReturn SurfaceSerialHubDriver::unregisterInterrupt(int source) {
return gpio_controller->unregisterInterrupt(gpio_pin);
}
================================================
FILE: BigSurface/BigSurface/SurfaceSerialHub/SurfaceSerialHubDriver.hpp
================================================
//
// SurfaceSerialHubDriver.hpp
// SurfaceSerialHub
//
// Created by Xavier on 2021/10/29.
// Copyright © 2021 Xia Shangning. All rights reserved.
//
#ifndef SurfaceSerialHubDriver_hpp
#define SurfaceSerialHubDriver_hpp
#include
#include "../../../Dependencies/VoodooGPIO/VoodooGPIO/VoodooGPIO.hpp"
#include "../../../Dependencies/VoodooSerial/VoodooSerial/VoodooUART/VoodooUARTController.hpp"
#include "SerialProtocol.h"
enum SurfaceSerialEventRegistryType {
SurfaceSerialEventHostManagedV1 = 0,
SurfaceSerialEventHostManagedV2,
SurfaceSerialEventHubManaged,
SurfaceSerialEventTypeCount
};
#define SSH_REQID_MIN SSH_TC_COUNT+1
#define SSH_MSG_CACHE_SIZE 256 // max length for a single message
#define SSH_MSG_LENGTH_UNKNOWN (SSH_MSG_CACHE_SIZE+1)
#define SSH_RING_BUFFER_SIZE 10
#define SSH_RING_BUFFER_NEXT(pos) ((pos) + 1) % SSH_RING_BUFFER_SIZE
#define SSH_ACK_TIMEOUT 50
#define SSH_CMD_TRAIL_CNT 3
#define SSH_WAIT_TIMEOUT (SSH_ACK_TIMEOUT * SSH_CMD_TRAIL_CNT)
class EXPORT SurfaceSerialHubClient : public IOService {
OSDeclareAbstractStructors(SurfaceSerialHubClient);
public:
/*
* This method is called when SSH receives corresponding registered events
* it should NOT block the thread
* the ACTUAL event handling codes should be done in device driver's own workloop thread
*/
virtual void eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) = 0;
};
class SurfaceBatteryNub;
class SurfaceHIDNub;
class EXPORT SurfaceSerialHubDriver : public IOService {
OSDeclareDefaultStructors(SurfaceSerialHubDriver);
public:
UInt16 sendCommand(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *payload, UInt16 payload_len, bool seq);
IOReturn getResponse(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *payload, UInt16 payload_len, bool seq, UInt8 *buffer, UInt16 buffer_len);
IOReturn registerEvent(SurfaceSerialHubClient *client, SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid);
void unregisterEvent(SurfaceSerialHubClient *client, SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid);
bool init(OSDictionary* properties) override;
IOService* probe(IOService* provider, SInt32* score) override;
bool start(IOService* provider) override;
void stop(IOService* provider) override;
void free() override;
IOReturn setPowerState(unsigned long whichState, IOService *whatDevice) override;
IOReturn enableInterrupt(int source) override;
IOReturn disableInterrupt(int source) override;
IOReturn getInterruptType(int source, int *interruptType) override;
IOReturn registerInterrupt(int source, OSObject *target, IOInterruptAction handler, void *refcon) override;
IOReturn unregisterInterrupt(int source) override;
private:
class CircleIDCounter {
private:
UInt16 min;
UInt16 max;
UInt16 id;
public:
CircleIDCounter(UInt16 _min, UInt16 _max){
min = _min;
max = _max;
id = min-1;
}
UInt16 getID() {
UInt16 ret = ++id;
if (id == max)
id = min-1;
return ret;
}
};
struct WaitingRequest {
queue_entry entry;
bool waiting;
UInt16 req_id;
UInt8* data;
UInt16 data_len;
};
struct PendingCommand {
queue_entry entry;
UInt8* buffer {nullptr};
UInt16 len {0};
UInt8 trial_count {0};
IOTimerEventSource* timer {nullptr};
};
struct MessageCache {
UInt8 cache[SSH_MSG_CACHE_SIZE];
UInt16 len;
UInt16 pos;
bool partial_syn;
};
struct RingBuffer {
UInt8* buffer;
UInt16 filled_len;
};
struct EventHandler {
queue_entry entry;
UInt8 target_iid;
SurfaceSerialHubClient *client;
};
IOWorkLoop* work_loop {nullptr};
IOCommandGate* command_gate {nullptr};
IOTimerEventSource* publish_timer {nullptr};
IOInterruptEventSource* uart_interrupt {nullptr};
IOInterruptEventSource* gpio_interrupt {nullptr};
IOACPIPlatformDevice* acpi_device {nullptr};
VoodooUARTController* uart_controller {nullptr};
VoodooGPIO* gpio_controller {nullptr};
SurfaceBatteryNub* battery_nub {nullptr};
SurfaceHIDNub* hid_nub {nullptr};
bool awake {true};
RingBuffer ring_buffer[SSH_RING_BUFFER_SIZE];
int current {0};
int last {SSH_RING_BUFFER_SIZE-1};
MessageCache rx_msg;
queue_head_t pending_list;
queue_head_t waiting_list;
queue_head_t event_handler_lists[SSH_REQID_MIN];
CircleIDCounter seq_counter {CircleIDCounter(0x00, 0xff)};
CircleIDCounter req_counter {CircleIDCounter(SSH_REQID_MIN, 0xffff)};
UInt32 baudrate {0};
UInt8 data_bits {0};
UInt8 stop_bits {0};
UInt8 parity {0};
bool flow_control {false};
UInt16 fifo_size {0};
UInt16 gpio_pin {0};
UInt16 gpio_irq {0};
void bufferReceived(VoodooUARTController *sender, UInt8 *buffer, UInt16 length);
IOReturn sendACK(UInt8 seq_id);
IOReturn sendNAK();
IOReturn processMessage();
void processReceivedBuffer(IOInterruptEventSource *sender, int count);
void delayedPublishingNubs(IOTimerEventSource *sender);
void gpioWakeUp(IOInterruptEventSource *sender, int count);
void _process(UInt8* buffer, UInt16 length);
IOReturn sendCommandGated(UInt8 *tx_buffer, UInt16 *len, bool *seq);
void commandTimeout(IOTimerEventSource* timer);
IOReturn waitResponse(UInt16 *req_id, UInt8 *buffer, UInt16 *buffer_len);
IOReturn sendEventCommand(SurfaceSerialEventRegistryType type, UInt8 tc, UInt8 iid, bool enable);
IOReturn getDeviceResources();
VoodooUARTController* getUARTController();
VoodooGPIO* getGPIOController();
IOReturn flushCacheGated();
void releaseResources();
};
#endif /* SurfaceSerialHubDriver_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceBatteryNub.cpp
================================================
//
// SurfaceBatteryNub.cpp
// SurfaceSerialHubDevices
//
// Created by Xavier on 2022/5/19.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#include "SurfaceBatteryNub.hpp"
#define super SurfaceSerialHubClient
OSDefineMetaClassAndStructors(SurfaceBatteryNub, SurfaceSerialHubClient)
bool SurfaceBatteryNub::attach(IOService* provider) {
if (!super::attach(provider))
return false;
ssh = OSDynamicCast(SurfaceSerialHubDriver, provider);
if (!ssh)
return false;
return true;
}
void SurfaceBatteryNub::detach(IOService* provider) {
ssh = nullptr;
super::detach(provider);
}
bool SurfaceBatteryNub::start(IOService *provider) {
if (!super::start(provider))
return false;
PMinit();
ssh->joinPMtree(this);
registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);
registerService();
return true;
}
void SurfaceBatteryNub::stop(IOService *provider) {
unregisterBatteryEvent(target);
super::stop(provider);
}
IOReturn SurfaceBatteryNub::setPowerState(unsigned long whichState, IOService *device) {
if (device != this)
return kIOReturnInvalid;
return kIOPMAckImplied;
}
IOReturn SurfaceBatteryNub::registerBatteryEvent(OSObject* owner, EventHandler _handler) {
if (!owner || !_handler)
return kIOReturnError;
if (target) {
LOG("Battery event already registered for a handler!");
return kIOReturnNoResources;
}
IOReturn ret = ssh->registerEvent(this, SurfaceSerialEventHostManagedV1, SSH_TC_BAT, 0x00);
if (ret != kIOReturnSuccess)
return ret;
target = owner;
handler = _handler;
return kIOReturnSuccess;
}
void SurfaceBatteryNub::unregisterBatteryEvent(OSObject* owner) {
if (target) {
if (target == owner) {
ssh->unregisterEvent(this, SurfaceSerialEventHostManagedV1, SSH_TC_BAT, 0x00);
target = nullptr;
handler = nullptr;
} else
LOG("Battery event not registered for this handler!");
}
}
void SurfaceBatteryNub::eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) {
// iid corresponds to battery/adaptor index, starts with 1
SurfaceBatteryEventType type;
switch (cid) {
case SSH_EVENT_CID_BAT_BIX:
type = SurfaceBatteryInformationChanged;
break;
case SSH_EVENT_CID_BAT_BST:
type = SurfaceBatteryStatusChanged;
break;
case SSH_EVENT_CID_BAT_PSR:
type = SurfaceAdaptorStatusChanged;
break;
default:
DBG_LOG("Unknown battery event! tid: %d, iid: %d, cid: %x, data_len: %d", tid, iid, cid, length);
return;
}
if (handler)
handler(target, this, type);
}
IOReturn SurfaceBatteryNub::getBatteryConnection(UInt8 index, bool *connected) {
UInt32 sta = 0x00;
if (ssh->getResponse(SSH_TC_BAT, index, 0x01, SSH_CID_BAT_STA, nullptr, 0, true, reinterpret_cast(&sta), 4) != kIOReturnSuccess)
return kIOReturnError;
*connected = (sta & 0x10) ? true : false;
return kIOReturnSuccess;
}
IOReturn SurfaceBatteryNub::getBatteryInformation(UInt8 index, OSArray **bix) {
UInt8 buffer[BIX_LENGTH];
if (ssh->getResponse(SSH_TC_BAT, index, 0x01, SSH_CID_BAT_BIX, nullptr, 0, true, buffer, BIX_LENGTH) != kIOReturnSuccess)
return kIOReturnError;
UInt32 *temp = reinterpret_cast(buffer+1);
const char *str = reinterpret_cast(buffer);
OSNumber *revision = OSNumber::withNumber(*buffer, 8);
OSNumber *power_unit = OSNumber::withNumber(temp[0], 32);
OSNumber *design_cap = OSNumber::withNumber(temp[1], 32);
OSNumber *last_full_cap = OSNumber::withNumber(temp[2], 32);
OSNumber *bat_tech = OSNumber::withNumber(temp[3], 32);
OSNumber *design_volt = OSNumber::withNumber(temp[4], 32);
OSNumber *design_cap_warn = OSNumber::withNumber(temp[5], 32);
OSNumber *design_cap_low = OSNumber::withNumber(temp[6], 32);
OSNumber *cycle_cnt = OSNumber::withNumber(temp[7], 32);
OSNumber *mesure_acc = OSNumber::withNumber(temp[8], 32);
OSNumber *max_sample_t = OSNumber::withNumber(temp[9], 32);
OSNumber *min_sample_t = OSNumber::withNumber(temp[10], 32);
OSNumber *max_avg_interval = OSNumber::withNumber(temp[11], 32);
OSNumber *min_avg_interval = OSNumber::withNumber(temp[12], 32);
OSNumber *bat_cap_gra_1 = OSNumber::withNumber(temp[13], 32);
OSNumber *bat_cap_gra_2 = OSNumber::withNumber(temp[14], 32);
OSString *model_number = OSString::withCString(str+0x3D);
OSString *serial_number = OSString::withCString(str+0x52);
OSString *bat_type = OSString::withCString(str+0x5D);
OSString *oem_info = OSString::withCString(str+0x62);
const OSObject *arr[] = {revision, power_unit, design_cap, last_full_cap, bat_tech,
design_volt, design_cap_warn, design_cap_low, cycle_cnt,
mesure_acc, max_sample_t, min_sample_t, max_avg_interval,
min_avg_interval, bat_cap_gra_1, bat_cap_gra_2, model_number,
serial_number, bat_type, oem_info};
*bix = OSArray::withObjects(arr, 20);
if (!(*bix)) {
LOG("Could not create a 20 sized array!");
for (int i=0; i<20; i++)
OSSafeReleaseNULL(arr[i]);
return kIOReturnError;
}
return kIOReturnSuccess;
}
IOReturn SurfaceBatteryNub::getBatteryStatus(UInt8 index, UInt32 *bst, UInt16 *temp) {
if (ssh->getResponse(SSH_TC_BAT, index, 0x01, SSH_CID_BAT_BST, nullptr, 0, true, reinterpret_cast(bst), BST_LENGTH) != kIOReturnSuccess)
return kIOReturnError;
if (ssh->getResponse(SSH_TC_TMP, SSH_TID_PRIMARY, SSH_TEMP_SENSOR_BAT, SSH_CID_TMP_SENSOR, nullptr, 0, true, reinterpret_cast(temp), 2) != kIOReturnSuccess)
LOG("Failed to get battery temperature!");
return kIOReturnSuccess;
}
IOReturn SurfaceBatteryNub::getAdaptorStatus(UInt32 *psr) {
return ssh->getResponse(SSH_TC_BAT, SSH_TID_PRIMARY, 0x01, SSH_CID_BAT_PSR, nullptr, 0, true, reinterpret_cast(psr), 4);
}
IOReturn SurfaceBatteryNub::setPerformanceMode(UInt32 mode) {
if (!ssh->sendCommand(SSH_TC_TMP, SSH_TID_PRIMARY, 0, SSH_CID_TMP_SET_PERF, reinterpret_cast(&mode), 4, true))
return kIOReturnError;
else
return kIOReturnSuccess;
}
================================================
FILE: BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceBatteryNub.hpp
================================================
//
// SurfaceBatteryNub.hpp
// SurfaceSerialHubDevices
//
// Created by Xavier on 2022/5/19.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#ifndef SurfaceBatteryNub_hpp
#define SurfaceBatteryNub_hpp
#include "../SurfaceSerialHub/SurfaceSerialHubDriver.hpp"
#define BIX_LENGTH 119
#define BST_LENGTH 16
enum SurfaceBatteryEventType {
SurfaceBatteryInformationChanged = 0,
SurfaceBatteryStatusChanged,
SurfaceAdaptorStatusChanged,
};
class EXPORT SurfaceBatteryNub : public SurfaceSerialHubClient {
OSDeclareDefaultStructors(SurfaceBatteryNub);
public:
typedef void (*EventHandler)(OSObject *owner, SurfaceBatteryNub *sender, SurfaceBatteryEventType type);
bool attach(IOService* provider) override;
void detach(IOService* provider) override;
bool start(IOService* provider) override;
void stop(IOService* provider) override;
IOReturn setPowerState(unsigned long whichState, IOService *device) override;
IOReturn registerBatteryEvent(OSObject* owner, EventHandler _handler);
void unregisterBatteryEvent(OSObject* owner);
void eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) override;
/*
* index: The index of battery, start with 1
*/
IOReturn getBatteryConnection(UInt8 index, bool *connected);
/*
* index: The index of battery, start with 1
* Returned OSArray bix need to be released by the caller!
*/
IOReturn getBatteryInformation(UInt8 index, OSArray **bix);
/*
* index: The index of battery, start with 1
*/
IOReturn getBatteryStatus(UInt8 index, UInt32 *bst, UInt16 *temp);
IOReturn getAdaptorStatus(UInt32 *psr);
IOReturn setPerformanceMode(UInt32 mode);
private:
SurfaceSerialHubDriver* ssh {nullptr};
OSObject* target {nullptr};
EventHandler handler {nullptr};
};
#endif /* SurfaceBatteryNub_hpp */
================================================
FILE: BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceHIDNub.cpp
================================================
//
// SurfaceHIDNub.cpp
// SurfaceSerialHubDevices
//
// Created by Xavier on 2022/5/20.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#include
#include
#include "SurfaceHIDNub.hpp"
#define super SurfaceSerialHubClient
OSDefineMetaClassAndStructors(SurfaceHIDNub, SurfaceSerialHubClient)
bool SurfaceHIDNub::attach(IOService* provider) {
if (!super::attach(provider))
return false;
ssh = OSDynamicCast(SurfaceSerialHubDriver, provider);
if (!ssh)
return false;
return true;
}
void SurfaceHIDNub::detach(IOService* provider) {
ssh = nullptr;
super::detach(provider);
}
bool SurfaceHIDNub::start(IOService *provider) {
if (!super::start(provider))
return false;
SurfaceHIDDescriptor desc;
if (getHIDDescriptor(SurfaceLegacyKeyboardDevice, &desc) != kIOReturnSuccess) {
legacy = false;
if (getHIDDescriptor(SurfaceKeyboardDevice, &desc) != kIOReturnSuccess)
return false;
}
LOG("HID version %d", !legacy+1);
setProperty(SURFACE_LEGACY_HID_STRING, legacy);
PMinit();
ssh->joinPMtree(this);
registerPowerDriver(this, myIOPMPowerStates, kIOPMNumberPowerStates);
registerService();
return true;
}
void SurfaceHIDNub::stop(IOService *provider) {
unregisterHIDEvent(target);
super::stop(provider);
}
IOReturn SurfaceHIDNub::setPowerState(unsigned long whichState, IOService *device) {
if (device != this)
return kIOReturnInvalid;
return kIOPMAckImplied;
}
IOReturn SurfaceHIDNub::registerHIDEvent(OSObject* owner, EventHandler _handler) {
if (!owner || !_handler)
return kIOReturnError;
if (target) {
LOG("HID event already registered for a handler!");
return kIOReturnNoResources;
}
IOReturn ret;
if (legacy)
ret = ssh->registerEvent(this, SurfaceSerialEventHostManagedV1, SSH_TC_KBD, SurfaceLegacyKeyboardDevice);
else {
ret = ssh->registerEvent(this, SurfaceSerialEventHostManagedV2, SSH_TC_HID, SurfaceKeyboardDevice);
if (ret == kIOReturnSuccess)
ret = ssh->registerEvent(this, SurfaceSerialEventHostManagedV2, SSH_TC_HID, SurfaceTouchpadDevice);
}
if (ret != kIOReturnSuccess)
return ret;
target = owner;
handler = _handler;
return kIOReturnSuccess;
}
void SurfaceHIDNub::unregisterHIDEvent(OSObject* owner) {
if (!target)
return;
if (target == owner) {
if (legacy)
ssh->unregisterEvent(this, SurfaceSerialEventHostManagedV1, SSH_TC_KBD, SurfaceLegacyKeyboardDevice);
else {
ssh->unregisterEvent(this, SurfaceSerialEventHostManagedV2, SSH_TC_HID, SurfaceKeyboardDevice);
ssh->unregisterEvent(this, SurfaceSerialEventHostManagedV2, SSH_TC_HID, SurfaceTouchpadDevice);
}
target = nullptr;
handler = nullptr;
} else
LOG("HID event not registered for this handler!");
}
void SurfaceHIDNub::eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) {
SurfaceHIDDeviceType device;
if (legacy) {
if ((cid != SSH_EVENT_CID_KBD_INPUT_GENERIC && cid != SSH_EVENT_CID_KBD_INPUT_HOTKEYS)
|| tid != SSH_TID_SECONDARY
|| iid != SurfaceLegacyKeyboardDevice)
goto error;
device = SurfaceLegacyKeyboardDevice;
} else {
if (cid != SSH_EVENT_CID_HID_INPUT || tid != SSH_TID_SECONDARY)
goto error;
switch (iid) {
case SurfaceKeyboardDevice:
device = SurfaceKeyboardDevice;
break;
case SurfaceTouchpadDevice:
device = SurfaceTouchpadDevice;
break;
default:
goto error;
}
}
if (handler)
handler(target, this, device, data_buffer, length);
return;
error:
DBG_LOG("Unknown HID event with tid: %d, iid: %d, cid: %d, data_len: %d", tid, iid, cid, length);
}
IOReturn SurfaceHIDNub::getHIDDescriptor(SurfaceHIDDeviceType device, SurfaceHIDDescriptor *desc) {
return getDescriptorData(device, SurfaceHIDDescriptorEntry, reinterpret_cast(desc), sizeof(SurfaceHIDDescriptor));
}
IOReturn SurfaceHIDNub::getHIDAttributes(SurfaceHIDDeviceType device, SurfaceHIDAttributes *attr) {
return getDescriptorData(device, SurfaceHIDAttributesEntry, reinterpret_cast(attr), sizeof(SurfaceHIDAttributes));
}
IOReturn SurfaceHIDNub::getReportDescriptor(SurfaceHIDDeviceType device, UInt8 *buffer, UInt16 len) {
return getDescriptorData(device, SurfaceReportDescriptorEntry, buffer, len);
}
IOReturn SurfaceHIDNub::getDescriptorData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len) {
if (legacy)
return getLegacyData(device, entry, buffer, buffer_len);
else
return getData(device, entry, buffer, buffer_len);
}
IOReturn SurfaceHIDNub::getLegacyData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len) {
return ssh->getResponse(SSH_TC_KBD, SSH_TID_SECONDARY, device, SSH_CID_KBD_GET_DESCRIPTOR, reinterpret_cast(&entry), 1, true, buffer, buffer_len);
}
IOReturn SurfaceHIDNub::getData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len) {
UInt8 cache[SURFACE_HID_DESC_HEADER_SIZE + 0x76]; // 0x76 is used by windows driver
SurfaceHIDDescriptorBufferHeader *cache_as_buf = reinterpret_cast(cache);
UInt16 rx_data_len = sizeof(cache) - SURFACE_HID_DESC_HEADER_SIZE;
UInt16 offset = 0;
UInt16 length = rx_data_len;
UInt16 remain_len = buffer_len;
UInt16 response_len;
cache_as_buf->entry = entry;
cache_as_buf->finished = false;
while (!cache_as_buf->finished && offset < buffer_len) {
response_len = rx_data_len > remain_len ? SURFACE_HID_DESC_HEADER_SIZE + remain_len : sizeof(cache);
cache_as_buf->offset = offset;
cache_as_buf->length = length;
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) {
LOG("Failed to get data from SSH!");
return kIOReturnError;
}
offset = cache_as_buf->offset;
length = cache_as_buf->length;
// Don't mess stuff up in case we receive garbage.
if (length > rx_data_len || offset > buffer_len) {
LOG("Received bogus data!");
return kIOReturnError;
}
if (offset + length > buffer_len) {
LOG("Not enough space for buffer, need at least %d", offset+length);
length = buffer_len - offset;
}
memcpy(buffer + offset, &cache_as_buf->data[0], length);
offset += length;
remain_len -= length;
length = rx_data_len;
}
if (offset != buffer_len) {
LOG("Unexpected descriptor length: got %u, expected %u", offset, buffer_len);
return kIOReturnError;
}
return kIOReturnSuccess;
}
IOReturn SurfaceHIDNub::getHIDRawReport(SurfaceHIDDeviceType device, UInt8 report_id, UInt8 *buffer, UInt16 len) {
if (legacy) {
UInt8 payload = 0;
UInt8 report[SURFACE_LEGACY_FEAT_REPORT_SIZE];
if (len < SURFACE_LEGACY_FEAT_REPORT_SIZE)
return kIOReturnNoSpace;
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);
if (ret != kIOReturnSuccess)
return ret;
if (report[0] != report_id)
return kIOReturnUnsupported;
memcpy(buffer, report, SURFACE_LEGACY_FEAT_REPORT_SIZE);
return kIOReturnSuccess;
} else
return ssh->getResponse(SSH_TC_HID, SSH_TID_SECONDARY, device, SSH_CID_HID_GET_FEAT_REPORT, &report_id, 1, true, buffer, len);
}
void SurfaceHIDNub::setHIDRawReport(SurfaceHIDDeviceType device, UInt8 report_id, bool feature, UInt8 *buffer, UInt16 len) {
if (!legacy) {
UInt8 cid = feature ? SSH_CID_HID_SET_FEAT_REPORT : SSH_CID_HID_OUT_REPORT;
buffer[0] = report_id;
ssh->sendCommand(SSH_TC_HID, SSH_TID_SECONDARY, device, cid, buffer, len, true);
}
}
================================================
FILE: BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceHIDNub.hpp
================================================
//
// SurfaceHIDNub.hpp
// SurfaceSerialHubDevices
//
// Created by Xavier on 2022/5/20.
// Copyright © 2022 Xia Shangning. All rights reserved.
//
#ifndef SurfaceHIDNub_hpp
#define SurfaceHIDNub_hpp
#include "../SurfaceSerialHub/SurfaceSerialHubDriver.hpp"
enum SurfaceHIDDescriptorEntryType : UInt8 {
SurfaceHIDDescriptorEntry = 0,
SurfaceHIDAttributesEntry = 2,
SurfaceReportDescriptorEntry = 1,
};
enum SurfaceHIDDeviceType {
SurfaceLegacyKeyboardDevice = 0x00,
SurfaceKeyboardDevice = 0x01,
SurfaceTouchpadDevice = 0x03,
};
struct PACKED SurfaceHIDDescriptorBufferHeader {
UInt8 entry;
UInt32 offset;
UInt32 length;
UInt8 finished;
UInt8 data[];
};
struct PACKED SurfaceHIDDescriptor {
UInt8 desc_len; /* = 9 */
UInt8 desc_type; /* = HID_DT_HID */
UInt16 hid_version;
UInt8 country_code;
UInt8 num_descriptors; /* = 1 */
UInt8 report_desc_type; /* = HID_DT_REPORT */
UInt16 report_desc_len;
};
struct PACKED SurfaceHIDAttributes {
UInt32 length;
UInt16 vendor;
UInt16 product;
UInt16 version;
UInt8 _unknown[22];
};
#define SURFACE_LEGACY_HID_STRING "SurfaceLegacyHID"
#define SURFACE_LEGACY_FEAT_REPORT_SIZE 7
#define SURFACE_HID_DESC_HEADER_SIZE sizeof(SurfaceHIDDescriptorBufferHeader)
class EXPORT SurfaceHIDNub : public SurfaceSerialHubClient {
OSDeclareDefaultStructors(SurfaceHIDNub)
public:
typedef void (*EventHandler)(OSObject *owner, SurfaceHIDNub *sender, SurfaceHIDDeviceType device, UInt8 *buffer, UInt16 len);
bool attach(IOService* provider) override;
void detach(IOService* provider) override;
bool start(IOService* provider) override;
void stop(IOService* provider) override;
IOReturn setPowerState(unsigned long whichState, IOService *device) override;
IOReturn registerHIDEvent(OSObject* owner, EventHandler _handler);
void unregisterHIDEvent(OSObject* owner);
void eventReceived(UInt8 tc, UInt8 tid, UInt8 iid, UInt8 cid, UInt8 *data_buffer, UInt16 length) override;
IOReturn getHIDDescriptor(SurfaceHIDDeviceType device, SurfaceHIDDescriptor *desc);
IOReturn getHIDAttributes(SurfaceHIDDeviceType device, SurfaceHIDAttributes *attr);
IOReturn getReportDescriptor(SurfaceHIDDeviceType device, UInt8 *buffer, UInt16 len);
IOReturn getHIDRawReport(SurfaceHIDDeviceType device, UInt8 report_id, UInt8 *buffer, UInt16 len);
void setHIDRawReport(SurfaceHIDDeviceType device, UInt8 report_id, bool feature, UInt8 *buffer, UInt16 len);
private:
SurfaceSerialHubDriver* ssh {nullptr};
OSObject* target {nullptr};
EventHandler handler {nullptr};
bool legacy {true};
IOReturn getDescriptorData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len);
IOReturn getLegacyData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len);
IOReturn getData(SurfaceHIDDeviceType device, SurfaceHIDDescriptorEntryType entry, UInt8 *buffer, UInt16 buffer_len);
};
#endif /* SurfaceHIDNub_hpp */
================================================
FILE: BigSurface/BigSurface/helpers.hpp
================================================
//
// helpers.hpp
// BigSurface
//
// Created by Xavier on 2023/2/7.
// Copyright © 2023 Xia Shangning. All rights reserved.
//
#ifndef helpers_hpp
#define helpers_hpp
#include
#include
#ifndef EXPORT
#define EXPORT __attribute__((visibility("default")))
#endif
#define kIOPMPowerOff 0
#define kIOPMNumberPowerStates 2
#define BIT(nr) (1UL << (nr))
#ifndef GENMASK
#define GENMASK(h, l) (((~0UL) << (l)) & (~0UL >> (64 - 1 - (h))))
#endif
static IOPMPowerState myIOPMPowerStates[kIOPMNumberPowerStates] = {
{1, kIOPMPowerOff, kIOPMPowerOff, kIOPMPowerOff, 0, 0, 0, 0, 0, 0, 0, 0},
{1, kIOPMPowerOn, kIOPMPowerOn, kIOPMPowerOn, 0, 0, 0, 0, 0, 0, 0, 0}
};
#define LOG(str, ...) IOLog("%s::" str "\n", getName(), ##__VA_ARGS__)
#ifdef DEBUG
#define DBG_LOG(str, ...) LOG("dbg-" str, ##__VA_ARGS__)
#else
#define DBG_LOG(str, ...) ;
#endif
#endif /* helpers_hpp */
================================================
FILE: BigSurface/BigSurface.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
2518A2F62734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 2518A2F32734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp */; };
2518A2F72734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2518A2F42734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp */; };
2518A2F82734F6AA00B0D631 /* APDS9960Constants.h in Headers */ = {isa = PBXBuildFile; fileRef = 2518A2F52734F6AA00B0D631 /* APDS9960Constants.h */; };
2524C0A626F3233A00CAAF12 /* SurfaceButtonDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2524C0A426F3233A00CAAF12 /* SurfaceButtonDriver.cpp */; };
2524C0A726F3233A00CAAF12 /* SurfaceButtonDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 2524C0A526F3233A00CAAF12 /* SurfaceButtonDriver.hpp */; };
25506BAA29929D7A007F59BF /* helpers.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25506BA929929D7A007F59BF /* helpers.hpp */; };
259040E926FC065400D605D0 /* SurfaceButtonDevice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259040E726FC065400D605D0 /* SurfaceButtonDevice.cpp */; };
259040EA26FC065400D605D0 /* SurfaceButtonDevice.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259040E826FC065400D605D0 /* SurfaceButtonDevice.hpp */; };
259040EC26FC0BB200D605D0 /* HIDReport.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259040EB26FC0BB200D605D0 /* HIDReport.hpp */; };
2597317D2738B01F00A7F7C1 /* KeyImplementations.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731702738B01F00A7F7C1 /* KeyImplementations.hpp */; };
2597317E2738B01F00A7F7C1 /* SurfaceACAdapter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259731712738B01F00A7F7C1 /* SurfaceACAdapter.cpp */; };
2597317F2738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731722738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp */; };
259731812738B01F00A7F7C1 /* BatteryManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259731742738B01F00A7F7C1 /* BatteryManager.cpp */; };
259731822738B01F00A7F7C1 /* SurfaceBattery.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259731752738B01F00A7F7C1 /* SurfaceBattery.cpp */; };
259731832738B01F00A7F7C1 /* SurfaceBattery.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731762738B01F00A7F7C1 /* SurfaceBattery.hpp */; };
259731842738B01F00A7F7C1 /* BatteryManagerState.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731772738B01F00A7F7C1 /* BatteryManagerState.hpp */; };
259731852738B01F00A7F7C1 /* KeyImplementations.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 259731782738B01F00A7F7C1 /* KeyImplementations.cpp */; };
259731862738B01F00A7F7C1 /* SurfaceACAdapter.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 259731792738B01F00A7F7C1 /* SurfaceACAdapter.hpp */; };
259731882738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2597317B2738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp */; };
259731892738B01F00A7F7C1 /* BatteryManager.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 2597317C2738B01F00A7F7C1 /* BatteryManager.hpp */; };
2597318C2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 2597318A2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp */; };
2597318D2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2597318B2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp */; };
25B97D89260B950E00657C76 /* libkmod.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7BE66D8F258AC5DC003CA4AD /* libkmod.a */; };
25C8D7EB27359FCD00F58956 /* SerialProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 25C8D7E827359FCD00F58956 /* SerialProtocol.h */; };
25C8D7EC27359FCD00F58956 /* SurfaceSerialHubDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25C8D7E927359FCD00F58956 /* SurfaceSerialHubDriver.cpp */; };
25C8D7ED27359FCD00F58956 /* SurfaceSerialHubDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25C8D7EA27359FCD00F58956 /* SurfaceSerialHubDriver.hpp */; };
25D907292736E2B2006D799F /* AmbientLightValue.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25D907272736E2B2006D799F /* AmbientLightValue.hpp */; };
25D9072A2736E2B2006D799F /* AmbientLightValue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25D907282736E2B2006D799F /* AmbientLightValue.cpp */; };
25DBA9742836A77700459629 /* SurfaceHIDNub.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25DBA9722836A77700459629 /* SurfaceHIDNub.cpp */; };
25DBA9752836A77700459629 /* SurfaceHIDNub.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25DBA9732836A77700459629 /* SurfaceHIDNub.hpp */; };
25E5B4CB2991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25E5B4C62991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp */; };
25E5B4CC2991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25E5B4C72991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp */; };
25E5B4CD2991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25E5B4C82991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp */; };
25E5B4CE2991ACE7007F21D4 /* MEIProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 25E5B4C92991ACE7007F21D4 /* MEIProtocol.h */; };
25E5B4CF2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25E5B4CA2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp */; };
25EA2A7E2836412B00525325 /* SurfaceBatteryNub.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25EA2A7C2836412B00525325 /* SurfaceBatteryNub.cpp */; };
25EA2A7F2836412B00525325 /* SurfaceBatteryNub.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 25EA2A7D2836412B00525325 /* SurfaceBatteryNub.hpp */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
25CBB35F2733D4C1009B568B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F1F172C51F42263A00AD98FA;
remoteInfo = VoodooGPIO;
};
25CBB3642733D4C9009B568B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 25813607272D6A2800EED5C9;
remoteInfo = VoodooSerial;
};
25CBB36A2733D50A009B568B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 25B97D6F260B950E00657C76;
remoteInfo = VoodooSerial;
};
25CDE61D285F291D003FB4C4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 7BBAB1F922E3A2F800B2941A;
remoteInfo = VoodooInput;
};
25CDE625285F2972003FB4C4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 7BBAB1F822E3A2F800B2941A;
remoteInfo = VoodooInput;
};
25D49D8E2854EE92008CAAA5 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = F1F172C41F42263A00AD98FA;
remoteInfo = VoodooGPIO;
};
25E5B47929919DCC007F21D4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 25E5B46829919DCB007F21D4;
remoteInfo = BigSurfaceHIDDriver;
};
25E5B47E29919F2C007F21D4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 25E5B46729919DCB007F21D4;
remoteInfo = BigSurfaceHIDDriver;
};
AC94C83C2119E50400D26081 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = AC94C8382119E50400D26081 /* VoodooI2CSynaptics.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = ACD148A21FF17DE00008EA7B;
remoteInfo = VoodooI2CSynaptics;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
2518A2F32734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceAmbientLightSensorDriver.hpp; sourceTree = ""; };
2518A2F42734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceAmbientLightSensorDriver.cpp; sourceTree = ""; };
2518A2F52734F6AA00B0D631 /* APDS9960Constants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APDS9960Constants.h; sourceTree = ""; };
2524C0A426F3233A00CAAF12 /* SurfaceButtonDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceButtonDriver.cpp; sourceTree = ""; };
2524C0A526F3233A00CAAF12 /* SurfaceButtonDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceButtonDriver.hpp; sourceTree = ""; };
25506BA929929D7A007F59BF /* helpers.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; path = helpers.hpp; sourceTree = ""; };
25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = VoodooSerial.xcodeproj; path = VoodooSerial/VoodooSerial.xcodeproj; sourceTree = ""; };
259040E726FC065400D605D0 /* SurfaceButtonDevice.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceButtonDevice.cpp; sourceTree = ""; };
259040E826FC065400D605D0 /* SurfaceButtonDevice.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceButtonDevice.hpp; sourceTree = ""; };
259040EB26FC0BB200D605D0 /* HIDReport.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = HIDReport.hpp; sourceTree = ""; };
259731702738B01F00A7F7C1 /* KeyImplementations.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = KeyImplementations.hpp; sourceTree = ""; };
259731712738B01F00A7F7C1 /* SurfaceACAdapter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceACAdapter.cpp; sourceTree = ""; };
259731722738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceBatteryDriver.hpp; sourceTree = ""; };
259731742738B01F00A7F7C1 /* BatteryManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BatteryManager.cpp; sourceTree = ""; };
259731752738B01F00A7F7C1 /* SurfaceBattery.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceBattery.cpp; sourceTree = ""; };
259731762738B01F00A7F7C1 /* SurfaceBattery.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceBattery.hpp; sourceTree = ""; };
259731772738B01F00A7F7C1 /* BatteryManagerState.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = BatteryManagerState.hpp; sourceTree = ""; };
259731782738B01F00A7F7C1 /* KeyImplementations.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = KeyImplementations.cpp; sourceTree = ""; };
259731792738B01F00A7F7C1 /* SurfaceACAdapter.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceACAdapter.hpp; sourceTree = ""; };
2597317B2738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceBatteryDriver.cpp; sourceTree = ""; };
2597317C2738B01F00A7F7C1 /* BatteryManager.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = BatteryManager.hpp; sourceTree = ""; };
2597318A2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceSMBusController.hpp; sourceTree = ""; };
2597318B2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceSMBusController.cpp; sourceTree = ""; };
25B97DA5260B950E00657C76 /* BigSurface.kext */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = BigSurface.kext; sourceTree = BUILT_PRODUCTS_DIR; };
25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = VoodooGPIO.xcodeproj; path = VoodooGPIO/VoodooGPIO.xcodeproj; sourceTree = ""; };
25B97E43260BA33B00657C76 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
25C8D7E827359FCD00F58956 /* SerialProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SerialProtocol.h; sourceTree = ""; };
25C8D7E927359FCD00F58956 /* SurfaceSerialHubDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceSerialHubDriver.cpp; sourceTree = ""; };
25C8D7EA27359FCD00F58956 /* SurfaceSerialHubDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceSerialHubDriver.hpp; sourceTree = ""; };
25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = VoodooInput.xcodeproj; path = VoodooInput/VoodooInput.xcodeproj; sourceTree = ""; };
25D9064A2736DB7F006D799F /* kern_smcinfo.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = kern_smcinfo.hpp; sourceTree = ""; };
25D9064B2736DB7F006D799F /* kern_vsmcapi.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = kern_vsmcapi.hpp; sourceTree = ""; };
25D9064C2736DB7F006D799F /* AppleSmc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppleSmc.h; sourceTree = ""; };
25D9064D2736DB7F006D799F /* kern_keyvalue.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = kern_keyvalue.hpp; sourceTree = ""; };
25D9064E2736DB7F006D799F /* kern_value.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = kern_value.hpp; sourceTree = ""; };
25D9064F2736DB7F006D799F /* AppleSmcBridge.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = AppleSmcBridge.hpp; sourceTree = ""; };
25D906F92736E125006D799F /* kern_config.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_config.hpp; sourceTree = ""; };
25D906FA2736E125006D799F /* hde64.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = hde64.h; sourceTree = ""; };
25D906FB2736E125006D799F /* kern_time.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_time.hpp; sourceTree = ""; };
25D906FC2736E125006D799F /* kern_nvram.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_nvram.hpp; sourceTree = ""; };
25D906FD2736E125006D799F /* kern_cpu.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_cpu.hpp; sourceTree = ""; };
25D906FE2736E125006D799F /* kern_devinfo.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_devinfo.hpp; sourceTree = ""; };
25D906FF2736E125006D799F /* kern_efi.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_efi.hpp; sourceTree = ""; };
25D907002736E125006D799F /* kern_policy.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_policy.hpp; sourceTree = ""; };
25D907012736E125006D799F /* kern_user.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_user.hpp; sourceTree = ""; };
25D907022736E125006D799F /* plugin_start.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = plugin_start.hpp; sourceTree = ""; };
25D907032736E125006D799F /* kern_iokit.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_iokit.hpp; sourceTree = ""; };
25D907042736E125006D799F /* kern_crypto.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_crypto.hpp; sourceTree = ""; };
25D907052736E125006D799F /* kern_mach.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_mach.hpp; sourceTree = ""; };
25D907062736E125006D799F /* kern_version.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_version.hpp; sourceTree = ""; };
25D907072736E125006D799F /* kern_compression.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_compression.hpp; sourceTree = ""; };
25D907082736E125006D799F /* kern_file.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_file.hpp; sourceTree = ""; };
25D907092736E125006D799F /* kern_rtc.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_rtc.hpp; sourceTree = ""; };
25D9070A2736E125006D799F /* kern_disasm.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_disasm.hpp; sourceTree = ""; };
25D9070C2736E125006D799F /* capstone.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = capstone.h; sourceTree = ""; };
25D9070D2736E125006D799F /* mips.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = mips.h; sourceTree = ""; };
25D9070E2736E125006D799F /* sparc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = sparc.h; sourceTree = ""; };
25D9070F2736E125006D799F /* systemz.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = systemz.h; sourceTree = ""; };
25D907102736E125006D799F /* arm.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = arm.h; sourceTree = ""; };
25D907112736E125006D799F /* x86.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = x86.h; sourceTree = ""; };
25D907122736E125006D799F /* ppc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ppc.h; sourceTree = ""; };
25D907132736E125006D799F /* arm64.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = arm64.h; sourceTree = ""; };
25D907142736E125006D799F /* xcore.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = xcore.h; sourceTree = ""; };
25D907152736E125006D799F /* platform.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = platform.h; sourceTree = ""; };
25D907162736E125006D799F /* kern_patcher.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_patcher.hpp; sourceTree = ""; };
25D907172736E125006D799F /* hde32.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = hde32.h; sourceTree = ""; };
25D907182736E125006D799F /* kern_compat.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_compat.hpp; sourceTree = ""; };
25D907192736E125006D799F /* kern_api.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_api.hpp; sourceTree = ""; };
25D9071A2736E125006D799F /* kern_util.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = kern_util.hpp; sourceTree = ""; };
25D9071D2736E125006D799F /* entry64.S */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.asm; path = entry64.S; sourceTree = ""; };
25D9071E2736E125006D799F /* build.tool */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = build.tool; sourceTree = ""; };
25D9071F2736E125006D799F /* entry32.S */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.asm; path = entry32.S; sourceTree = ""; };
25D907202736E125006D799F /* wrappers.inc */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.pascal; path = wrappers.inc; sourceTree = ""; };
25D907212736E125006D799F /* plugin_start.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = plugin_start.cpp; sourceTree = ""; };
25D907272736E2B2006D799F /* AmbientLightValue.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = AmbientLightValue.hpp; sourceTree = ""; };
25D907282736E2B2006D799F /* AmbientLightValue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AmbientLightValue.cpp; sourceTree = ""; };
25DBA9722836A77700459629 /* SurfaceHIDNub.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceHIDNub.cpp; sourceTree = ""; };
25DBA9732836A77700459629 /* SurfaceHIDNub.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = SurfaceHIDNub.hpp; sourceTree = ""; };
25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = BigSurfaceHIDDriver.xcodeproj; path = BigSurfaceHIDDriver/BigSurfaceHIDDriver.xcodeproj; sourceTree = ""; };
25E5B4C62991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceManagementEngineClient.hpp; sourceTree = ""; };
25E5B4C72991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceManagementEngineDriver.cpp; sourceTree = ""; };
25E5B4C82991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = SurfaceManagementEngineDriver.hpp; sourceTree = ""; };
25E5B4C92991ACE7007F21D4 /* MEIProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MEIProtocol.h; sourceTree = ""; };
25E5B4CA2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceManagementEngineClient.cpp; sourceTree = ""; };
25EA2A7C2836412B00525325 /* SurfaceBatteryNub.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SurfaceBatteryNub.cpp; sourceTree = ""; };
25EA2A7D2836412B00525325 /* SurfaceBatteryNub.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = SurfaceBatteryNub.hpp; sourceTree = ""; };
7BE66D8F258AC5DC003CA4AD /* libkmod.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libkmod.a; path = ../MacKernelSDK/Library/x86_64/libkmod.a; sourceTree = ""; };
AC94C8382119E50400D26081 /* VoodooI2CSynaptics.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = VoodooI2CSynaptics.xcodeproj; path = "../../VoodooI2C Satellites/VoodooI2CSynaptics/VoodooI2CSynaptics.xcodeproj"; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
25B97D88260B950E00657C76 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
25B97D89260B950E00657C76 /* libkmod.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
2518A2F22734F6AA00B0D631 /* SurfaceAmbientLightSensor */ = {
isa = PBXGroup;
children = (
2518A2F52734F6AA00B0D631 /* APDS9960Constants.h */,
2518A2F42734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp */,
2518A2F32734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp */,
25D907282736E2B2006D799F /* AmbientLightValue.cpp */,
25D907272736E2B2006D799F /* AmbientLightValue.hpp */,
);
path = SurfaceAmbientLightSensor;
sourceTree = "";
};
2524C0A326F3233A00CAAF12 /* SurfaceButton */ = {
isa = PBXGroup;
children = (
259040EB26FC0BB200D605D0 /* HIDReport.hpp */,
259040E726FC065400D605D0 /* SurfaceButtonDevice.cpp */,
259040E826FC065400D605D0 /* SurfaceButtonDevice.hpp */,
2524C0A426F3233A00CAAF12 /* SurfaceButtonDriver.cpp */,
2524C0A526F3233A00CAAF12 /* SurfaceButtonDriver.hpp */,
);
path = SurfaceButton;
sourceTree = "";
};
2597316F2738B01F00A7F7C1 /* SurfaceBattery */ = {
isa = PBXGroup;
children = (
259731712738B01F00A7F7C1 /* SurfaceACAdapter.cpp */,
259731792738B01F00A7F7C1 /* SurfaceACAdapter.hpp */,
259731752738B01F00A7F7C1 /* SurfaceBattery.cpp */,
259731762738B01F00A7F7C1 /* SurfaceBattery.hpp */,
259731742738B01F00A7F7C1 /* BatteryManager.cpp */,
2597317C2738B01F00A7F7C1 /* BatteryManager.hpp */,
259731772738B01F00A7F7C1 /* BatteryManagerState.hpp */,
259731782738B01F00A7F7C1 /* KeyImplementations.cpp */,
259731702738B01F00A7F7C1 /* KeyImplementations.hpp */,
2597317B2738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp */,
259731722738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp */,
2597318B2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp */,
2597318A2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp */,
);
path = SurfaceBattery;
sourceTree = "";
};
25B97D6E260B943E00657C76 /* BigSurface */ = {
isa = PBXGroup;
children = (
AC0955711F4ED49E0052E343 /* Dependencies */,
2524C0A326F3233A00CAAF12 /* SurfaceButton */,
2518A2F22734F6AA00B0D631 /* SurfaceAmbientLightSensor */,
25C8D7E727359FCD00F58956 /* SurfaceSerialHub */,
25DBA9762836A78900459629 /* SurfaceSerialHubDevices */,
2597316F2738B01F00A7F7C1 /* SurfaceBattery */,
25E5B4C52991ACE7007F21D4 /* SurfaceManagementEngine */,
25506BA929929D7A007F59BF /* helpers.hpp */,
25B97E43260BA33B00657C76 /* Info.plist */,
);
path = BigSurface;
sourceTree = "";
};
25C8D7E727359FCD00F58956 /* SurfaceSerialHub */ = {
isa = PBXGroup;
children = (
25C8D7E827359FCD00F58956 /* SerialProtocol.h */,
25C8D7E927359FCD00F58956 /* SurfaceSerialHubDriver.cpp */,
25C8D7EA27359FCD00F58956 /* SurfaceSerialHubDriver.hpp */,
);
path = SurfaceSerialHub;
sourceTree = "";
};
25CBB35C2733D4C1009B568B /* Products */ = {
isa = PBXGroup;
children = (
25CBB3602733D4C1009B568B /* VoodooGPIO.kext */,
);
name = Products;
sourceTree = "";
};
25CBB3612733D4C9009B568B /* Products */ = {
isa = PBXGroup;
children = (
25CBB3652733D4C9009B568B /* VoodooSerial.kext */,
);
name = Products;
sourceTree = "";
};
25CDE61A285F291D003FB4C4 /* Products */ = {
isa = PBXGroup;
children = (
25CDE61E285F291D003FB4C4 /* VoodooInput.kext */,
);
name = Products;
sourceTree = "";
};
25D906492736DB7F006D799F /* VirtualSMCSDK */ = {
isa = PBXGroup;
children = (
25D9064A2736DB7F006D799F /* kern_smcinfo.hpp */,
25D9064B2736DB7F006D799F /* kern_vsmcapi.hpp */,
25D9064C2736DB7F006D799F /* AppleSmc.h */,
25D9064D2736DB7F006D799F /* kern_keyvalue.hpp */,
25D9064E2736DB7F006D799F /* kern_value.hpp */,
25D9064F2736DB7F006D799F /* AppleSmcBridge.hpp */,
);
name = VirtualSMCSDK;
path = VirtualSMC.kext/Contents/Resources/VirtualSMCSDK;
sourceTree = "";
};
25D906A72736DC1A006D799F /* LiluSDK */ = {
isa = PBXGroup;
children = (
25D906F82736E125006D799F /* Headers */,
25D9071B2736E125006D799F /* Library */,
);
name = LiluSDK;
sourceTree = "";
};
25D906F82736E125006D799F /* Headers */ = {
isa = PBXGroup;
children = (
25D906F92736E125006D799F /* kern_config.hpp */,
25D906FA2736E125006D799F /* hde64.h */,
25D906FB2736E125006D799F /* kern_time.hpp */,
25D906FC2736E125006D799F /* kern_nvram.hpp */,
25D906FD2736E125006D799F /* kern_cpu.hpp */,
25D906FE2736E125006D799F /* kern_devinfo.hpp */,
25D906FF2736E125006D799F /* kern_efi.hpp */,
25D907002736E125006D799F /* kern_policy.hpp */,
25D907012736E125006D799F /* kern_user.hpp */,
25D907022736E125006D799F /* plugin_start.hpp */,
25D907032736E125006D799F /* kern_iokit.hpp */,
25D907042736E125006D799F /* kern_crypto.hpp */,
25D907052736E125006D799F /* kern_mach.hpp */,
25D907062736E125006D799F /* kern_version.hpp */,
25D907072736E125006D799F /* kern_compression.hpp */,
25D907082736E125006D799F /* kern_file.hpp */,
25D907092736E125006D799F /* kern_rtc.hpp */,
25D9070A2736E125006D799F /* kern_disasm.hpp */,
25D9070B2736E125006D799F /* capstone */,
25D907162736E125006D799F /* kern_patcher.hpp */,
25D907172736E125006D799F /* hde32.h */,
25D907182736E125006D799F /* kern_compat.hpp */,
25D907192736E125006D799F /* kern_api.hpp */,
25D9071A2736E125006D799F /* kern_util.hpp */,
);
name = Headers;
path = Lilu.kext/Contents/Resources/Headers;
sourceTree = "";
};
25D9070B2736E125006D799F /* capstone */ = {
isa = PBXGroup;
children = (
25D9070C2736E125006D799F /* capstone.h */,
25D9070D2736E125006D799F /* mips.h */,
25D9070E2736E125006D799F /* sparc.h */,
25D9070F2736E125006D799F /* systemz.h */,
25D907102736E125006D799F /* arm.h */,
25D907112736E125006D799F /* x86.h */,
25D907122736E125006D799F /* ppc.h */,
25D907132736E125006D799F /* arm64.h */,
25D907142736E125006D799F /* xcore.h */,
25D907152736E125006D799F /* platform.h */,
);
path = capstone;
sourceTree = "";
};
25D9071B2736E125006D799F /* Library */ = {
isa = PBXGroup;
children = (
25D9071C2736E125006D799F /* wrappers */,
25D907212736E125006D799F /* plugin_start.cpp */,
);
name = Library;
path = Lilu.kext/Contents/Resources/Library;
sourceTree = "";
};
25D9071C2736E125006D799F /* wrappers */ = {
isa = PBXGroup;
children = (
25D9071D2736E125006D799F /* entry64.S */,
25D9071E2736E125006D799F /* build.tool */,
25D9071F2736E125006D799F /* entry32.S */,
25D907202736E125006D799F /* wrappers.inc */,
);
path = wrappers;
sourceTree = "";
};
25DBA9762836A78900459629 /* SurfaceSerialHubDevices */ = {
isa = PBXGroup;
children = (
25EA2A7C2836412B00525325 /* SurfaceBatteryNub.cpp */,
25EA2A7D2836412B00525325 /* SurfaceBatteryNub.hpp */,
25DBA9722836A77700459629 /* SurfaceHIDNub.cpp */,
25DBA9732836A77700459629 /* SurfaceHIDNub.hpp */,
);
path = SurfaceSerialHubDevices;
sourceTree = "";
};
25E5B47629919DCB007F21D4 /* Products */ = {
isa = PBXGroup;
children = (
25E5B47A29919DCC007F21D4 /* BigSurfaceHIDDriver.kext */,
);
name = Products;
sourceTree = "";
};
25E5B4C52991ACE7007F21D4 /* SurfaceManagementEngine */ = {
isa = PBXGroup;
children = (
25E5B4C92991ACE7007F21D4 /* MEIProtocol.h */,
25E5B4CA2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp */,
25E5B4C62991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp */,
25E5B4C72991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp */,
25E5B4C82991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp */,
);
path = SurfaceManagementEngine;
sourceTree = "";
};
7BE66D8E258AC5DC003CA4AD /* Frameworks */ = {
isa = PBXGroup;
children = (
7BE66D8F258AC5DC003CA4AD /* libkmod.a */,
);
name = Frameworks;
sourceTree = "";
};
AC0955711F4ED49E0052E343 /* Dependencies */ = {
isa = PBXGroup;
children = (
25D906A72736DC1A006D799F /* LiluSDK */,
25D906492736DB7F006D799F /* VirtualSMCSDK */,
25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */,
25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */,
25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */,
25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */,
);
name = Dependencies;
path = ../../Dependencies;
sourceTree = "";
};
AC2603A61F2F294000CF238F = {
isa = PBXGroup;
children = (
25B97D6E260B943E00657C76 /* BigSurface */,
AC2603B11F2F294000CF238F /* Products */,
7BE66D8E258AC5DC003CA4AD /* Frameworks */,
);
sourceTree = "";
};
AC2603B11F2F294000CF238F /* Products */ = {
isa = PBXGroup;
children = (
25B97DA5260B950E00657C76 /* BigSurface.kext */,
);
name = Products;
sourceTree = "";
};
AC94C8392119E50400D26081 /* Products */ = {
isa = PBXGroup;
children = (
AC94C83D2119E50400D26081 /* VoodooI2CSynaptics.kext */,
);
name = Products;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
25B97D8A260B950E00657C76 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
259731842738B01F00A7F7C1 /* BatteryManagerState.hpp in Headers */,
2518A2F62734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.hpp in Headers */,
259731892738B01F00A7F7C1 /* BatteryManager.hpp in Headers */,
2597317F2738B01F00A7F7C1 /* SurfaceBatteryDriver.hpp in Headers */,
259731832738B01F00A7F7C1 /* SurfaceBattery.hpp in Headers */,
25EA2A7F2836412B00525325 /* SurfaceBatteryNub.hpp in Headers */,
25D907292736E2B2006D799F /* AmbientLightValue.hpp in Headers */,
2597318C2738B2BA00A7F7C1 /* SurfaceSMBusController.hpp in Headers */,
2518A2F82734F6AA00B0D631 /* APDS9960Constants.h in Headers */,
25506BAA29929D7A007F59BF /* helpers.hpp in Headers */,
2524C0A726F3233A00CAAF12 /* SurfaceButtonDriver.hpp in Headers */,
259731862738B01F00A7F7C1 /* SurfaceACAdapter.hpp in Headers */,
2597317D2738B01F00A7F7C1 /* KeyImplementations.hpp in Headers */,
25C8D7EB27359FCD00F58956 /* SerialProtocol.h in Headers */,
25E5B4CE2991ACE7007F21D4 /* MEIProtocol.h in Headers */,
25C8D7ED27359FCD00F58956 /* SurfaceSerialHubDriver.hpp in Headers */,
25DBA9752836A77700459629 /* SurfaceHIDNub.hpp in Headers */,
259040EC26FC0BB200D605D0 /* HIDReport.hpp in Headers */,
25E5B4CB2991ACE7007F21D4 /* SurfaceManagementEngineClient.hpp in Headers */,
259040EA26FC065400D605D0 /* SurfaceButtonDevice.hpp in Headers */,
25E5B4CD2991ACE7007F21D4 /* SurfaceManagementEngineDriver.hpp in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
25B97D6F260B950E00657C76 /* BigSurface */ = {
isa = PBXNativeTarget;
buildConfigurationList = 25B97DA2260B950E00657C76 /* Build configuration list for PBXNativeTarget "BigSurface" */;
buildPhases = (
25B97D8A260B950E00657C76 /* Headers */,
25B97D74260B950E00657C76 /* Sources */,
25B97D88260B950E00657C76 /* Frameworks */,
25B97DA0260B950E00657C76 /* Resources */,
25B97DA1260B950E00657C76 /* Add Plugins */,
);
buildRules = (
);
dependencies = (
25D49D8F2854EE92008CAAA5 /* PBXTargetDependency */,
25CBB36B2733D50A009B568B /* PBXTargetDependency */,
25CDE626285F2972003FB4C4 /* PBXTargetDependency */,
25E5B47F29919F2C007F21D4 /* PBXTargetDependency */,
);
name = BigSurface;
productName = VoodooI2C;
productReference = 25B97DA5260B950E00657C76 /* BigSurface.kext */;
productType = "com.apple.product-type.kernel-extension";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
AC2603A71F2F294000CF238F /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1410;
ORGANIZATIONNAME = "Xia Shangning";
TargetAttributes = {
25B97D6F260B950E00657C76 = {
DevelopmentTeam = K8RXBXZGN4;
ProvisioningStyle = Manual;
};
};
};
buildConfigurationList = AC2603AA1F2F294000CF238F /* Build configuration list for PBXProject "BigSurface" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = AC2603A61F2F294000CF238F;
productRefGroup = AC2603B11F2F294000CF238F /* Products */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 25E5B47629919DCB007F21D4 /* Products */;
ProjectRef = 25E5B47529919DCB007F21D4 /* BigSurfaceHIDDriver.xcodeproj */;
},
{
ProductGroup = 25CBB35C2733D4C1009B568B /* Products */;
ProjectRef = 25B97DB8260B971000657C76 /* VoodooGPIO.xcodeproj */;
},
{
ProductGroup = AC94C8392119E50400D26081 /* Products */;
ProjectRef = AC94C8382119E50400D26081 /* VoodooI2CSynaptics.xcodeproj */;
},
{
ProductGroup = 25CDE61A285F291D003FB4C4 /* Products */;
ProjectRef = 25CDE619285F291D003FB4C4 /* VoodooInput.xcodeproj */;
},
{
ProductGroup = 25CBB3612733D4C9009B568B /* Products */;
ProjectRef = 25813612272D6A2800EED5C9 /* VoodooSerial.xcodeproj */;
},
);
projectRoot = "";
targets = (
25B97D6F260B950E00657C76 /* BigSurface */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
25CBB3602733D4C1009B568B /* VoodooGPIO.kext */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = VoodooGPIO.kext;
remoteRef = 25CBB35F2733D4C1009B568B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
25CBB3652733D4C9009B568B /* VoodooSerial.kext */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = VoodooSerial.kext;
remoteRef = 25CBB3642733D4C9009B568B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
25CDE61E285F291D003FB4C4 /* VoodooInput.kext */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = VoodooInput.kext;
remoteRef = 25CDE61D285F291D003FB4C4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
25E5B47A29919DCC007F21D4 /* BigSurfaceHIDDriver.kext */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = BigSurfaceHIDDriver.kext;
remoteRef = 25E5B47929919DCC007F21D4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
AC94C83D2119E50400D26081 /* VoodooI2CSynaptics.kext */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = VoodooI2CSynaptics.kext;
remoteRef = AC94C83C2119E50400D26081 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
25B97DA0260B950E00657C76 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
25B97DA1260B950E00657C76 /* Add Plugins */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Add Plugins";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "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";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
25B97D74260B950E00657C76 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
25DBA9742836A77700459629 /* SurfaceHIDNub.cpp in Sources */,
259731812738B01F00A7F7C1 /* BatteryManager.cpp in Sources */,
25C8D7EC27359FCD00F58956 /* SurfaceSerialHubDriver.cpp in Sources */,
25D9072A2736E2B2006D799F /* AmbientLightValue.cpp in Sources */,
259040E926FC065400D605D0 /* SurfaceButtonDevice.cpp in Sources */,
2518A2F72734F6AA00B0D631 /* SurfaceAmbientLightSensorDriver.cpp in Sources */,
259731822738B01F00A7F7C1 /* SurfaceBattery.cpp in Sources */,
25E5B4CC2991ACE7007F21D4 /* SurfaceManagementEngineDriver.cpp in Sources */,
259731882738B01F00A7F7C1 /* SurfaceBatteryDriver.cpp in Sources */,
25EA2A7E2836412B00525325 /* SurfaceBatteryNub.cpp in Sources */,
259731852738B01F00A7F7C1 /* KeyImplementations.cpp in Sources */,
2597318D2738B2BA00A7F7C1 /* SurfaceSMBusController.cpp in Sources */,
25E5B4CF2991ACE7007F21D4 /* SurfaceManagementEngineClient.cpp in Sources */,
2597317E2738B01F00A7F7C1 /* SurfaceACAdapter.cpp in Sources */,
2524C0A626F3233A00CAAF12 /* SurfaceButtonDriver.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
25CBB36B2733D50A009B568B /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = VoodooSerial;
targetProxy = 25CBB36A2733D50A009B568B /* PBXContainerItemProxy */;
};
25CDE626285F2972003FB4C4 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = VoodooInput;
targetProxy = 25CDE625285F2972003FB4C4 /* PBXContainerItemProxy */;
};
25D49D8F2854EE92008CAAA5 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = VoodooGPIO;
targetProxy = 25D49D8E2854EE92008CAAA5 /* PBXContainerItemProxy */;
};
25E5B47F29919F2C007F21D4 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = BigSurfaceHIDDriver;
targetProxy = 25E5B47E29919F2C007F21D4 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
25B97DA3260B950E00657C76 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_DEADCODE_DEADSTORES = YES;
CLANG_ANALYZER_DIVIDE_BY_ZERO = NO;
CLANG_ANALYZER_NULL_DEREFERENCE = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_WARN_DOCUMENTATION_COMMENTS = NO;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO;
CODE_SIGN_IDENTITY = "-";
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
CODE_SIGN_INJECT_BASE_ENTITLEMENTS = YES;
CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1.2.0;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = K8RXBXZGN4;
GCC_OPTIMIZATION_LEVEL = 3;
HEADER_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/../Dependencies/VoodooInput/Debug/VoodooInput.kext/Contents/Resources",
"$(PROJECT_DIR)/../Dependencies/VirtualSMC.kext/Contents/Resources/",
"$(PROJECT_DIR)/../Dependencies/Lilu.kext/Contents/Resources/",
);
INFOPLIST_FILE = BigSurface/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2021 Xia Shangning. All rights reserved.";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/../MacKernelSDK/Library/x86_64",
);
MACOSX_DEPLOYMENT_TARGET = 10.12;
MARKETING_VERSION = 1.2.0;
MODULE_NAME = com.xavier.BigSurface;
MODULE_VERSION = 1.0.6;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
PRODUCT_BUNDLE_IDENTIFIER = com.xavier.BigSurface;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
RUN_CLANG_STATIC_ANALYZER = YES;
WARNING_CFLAGS = "";
WRAPPER_EXTENSION = kext;
};
name = Debug;
};
25B97DA4260B950E00657C76 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_DEADCODE_DEADSTORES = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_WARN_DOCUMENTATION_COMMENTS = NO;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO;
CODE_SIGN_IDENTITY = "-";
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
CODE_SIGN_INJECT_BASE_ENTITLEMENTS = YES;
CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1.2.0;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = K8RXBXZGN4;
GCC_INLINES_ARE_PRIVATE_EXTERN = YES;
GCC_OPTIMIZATION_LEVEL = fast;
HEADER_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/../Dependencies/VoodooInput/Debug/VoodooInput.kext/Contents/Resources",
"$(PROJECT_DIR)/../Dependencies/VirtualSMC.kext/Contents/Resources/",
"$(PROJECT_DIR)/../Dependencies/Lilu.kext/Contents/Resources/",
);
INFOPLIST_FILE = BigSurface/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2021 Xia Shangning. All rights reserved.";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/../MacKernelSDK/Library/x86_64",
);
MACOSX_DEPLOYMENT_TARGET = 10.12;
MARKETING_VERSION = 1.2.0;
MODULE_NAME = com.xavier.BigSurface;
MODULE_VERSION = 1.0.6;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.xavier.BigSurface;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
WARNING_CFLAGS = "";
WRAPPER_EXTENSION = kext;
};
name = Release;
};
AC2603B81F2F294000CF238F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = x86_64;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 3;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
KERNEL_EXTENSION_HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/../MacKernelSDK/Headers";
KERNEL_FRAMEWORK_HEADERS = "$(PROJECT_DIR)/../MacKernelSDK/Headers";
MACOSX_DEPLOYMENT_TARGET = 10.12;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
WARNING_CFLAGS = "";
};
name = Debug;
};
AC2603B91F2F294000CF238F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = x86_64;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = fast;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
KERNEL_EXTENSION_HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/../MacKernelSDK/Headers";
KERNEL_FRAMEWORK_HEADERS = "$(PROJECT_DIR)/../MacKernelSDK/Headers";
MACOSX_DEPLOYMENT_TARGET = 10.12;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
WARNING_CFLAGS = "";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
25B97DA2260B950E00657C76 /* Build configuration list for PBXNativeTarget "BigSurface" */ = {
isa = XCConfigurationList;
buildConfigurations = (
25B97DA3260B950E00657C76 /* Debug */,
25B97DA4260B950E00657C76 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
AC2603AA1F2F294000CF238F /* Build configuration list for PBXProject "BigSurface" */ = {
isa = XCConfigurationList;
buildConfigurations = (
AC2603B81F2F294000CF238F /* Debug */,
AC2603B91F2F294000CF238F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = AC2603A71F2F294000CF238F /* Project object */;
}
================================================
FILE: BigSurface/BigSurface.xcodeproj/project.pbxproj.orig
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
4E67867E1FACB2A80000D307 /* VoodooI2CUPDDData.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E6786791FACB2A80000D307 /* VoodooI2CUPDDData.h */; };
4E67867F1FACB2A80000D307 /* VoodooI2CUPDDEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4E67867A1FACB2A80000D307 /* VoodooI2CUPDDEngine.cpp */; };
4E6786801FACB2A80000D307 /* VoodooI2CUPDDEngine.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 4E67867B1FACB2A80000D307 /* VoodooI2CUPDDEngine.hpp */; };
4E6786811FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4E67867C1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.cpp */; };
4E6786821FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.hpp in Headers */ = {isa = PBXBuildFile; fileRef = 4E67867D1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.hpp */; };
AC015C471F32345500516383 /* VoodooI2CACPIController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC015C451F32345500516383 /* VoodooI2CACPIController.cpp */; };
AC015C481F32345500516383 /* VoodooI2CACPIController.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC015C461F32345500516383 /* VoodooI2CACPIController.hpp */; };
AC0955751F4ED4C50052E343 /* helpers.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0955731F4ED4C50052E343 /* helpers.cpp */; };
AC0955761F4ED4C50052E343 /* helpers.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0955741F4ED4C50052E343 /* helpers.hpp */; };
AC09557A1F4ED4F60052E343 /* linuxirq.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0955771F4ED4F60052E343 /* linuxirq.hpp */; };
AC09557B1F4ED4F60052E343 /* VoodooI2CACPICRSParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0955781F4ED4F60052E343 /* VoodooI2CACPICRSParser.cpp */; };
AC09557C1F4ED4F60052E343 /* VoodooI2CACPICRSParser.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0955791F4ED4F60052E343 /* VoodooI2CACPICRSParser.hpp */; };
AC0AD4581F3842800070A642 /* VoodooI2CDeviceNub.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0AD4561F3842800070A642 /* VoodooI2CDeviceNub.cpp */; };
AC0AD4591F3842800070A642 /* VoodooI2CDeviceNub.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0AD4571F3842800070A642 /* VoodooI2CDeviceNub.hpp */; };
AC0E75761F69997B002268D0 /* VoodooI2CDigitiserTransducer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0E75741F69997B002268D0 /* VoodooI2CDigitiserTransducer.cpp */; };
AC0E75771F69997B002268D0 /* VoodooI2CDigitiserTransducer.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0E75751F69997B002268D0 /* VoodooI2CDigitiserTransducer.hpp */; };
AC0E757A1F69ACEE002268D0 /* VoodooI2CDigitiserStylus.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC0E75781F69ACEE002268D0 /* VoodooI2CDigitiserStylus.cpp */; };
AC0E757B1F69ACEE002268D0 /* VoodooI2CDigitiserStylus.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC0E75791F69ACEE002268D0 /* VoodooI2CDigitiserStylus.hpp */; };
AC4954511F31E91D0040E11F /* VoodooI2CPCIController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC49544F1F31E91D0040E11F /* VoodooI2CPCIController.cpp */; };
AC4954521F31E91D0040E11F /* VoodooI2CPCIController.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC4954501F31E91D0040E11F /* VoodooI2CPCIController.hpp */; };
AC6268941F2F6CF1000CBF2D /* VoodooI2CController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AC6268921F2F6CF1000CBF2D /* VoodooI2CController.cpp */; };
AC6268951F2F6CF1000CBF2D /* VoodooI2CController.hpp in Headers */ = {isa = PBXBuildFile; fileRef = AC6268931F2F6CF1000CBF2D /* VoodooI2CController.hpp */; };
AC7400B91F3B6F1000937DD5 /* Introduction.md in Sources */ = {isa = PBXBuildFile; fileRef = AC7400B81F3B6F1000937DD5 /* Introduction.md */; };
ACD09F031F756B7800E9829A /* VoodooI2CMultitouchInterface.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACD09F011F756B7800E9829A /* VoodooI2CMultitouchInterface.cpp */; };
ACD09F041F756B7800E9829A /* VoodooI2CMultitouchInterface.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACD09F021F756B7800E9829A /* VoodooI2CMultitouchInterface.hpp */; };
ACF6CF111F7587E5001CAAEE /* VoodooI2CMultitouchEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6CF0F1F7587E5001CAAEE /* VoodooI2CMultitouchEngine.cpp */; };
ACF6CF121F7587E5001CAAEE /* VoodooI2CMultitouchEngine.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACF6CF101F7587E5001CAAEE /* VoodooI2CMultitouchEngine.hpp */; };
ACF6E5871F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6E5851F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.cpp */; };
ACF6E5881F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E5861F759B5D00A0CD61 /* VoodooI2CCSGestureEngine.hpp */; };
ACF6E5901F759EA000A0CD61 /* csgesture-softc.h in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E5891F759EA000A0CD61 /* csgesture-softc.h */; };
ACF6E5911F759EA000A0CD61 /* csgesturescroll.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6E58A1F759EA000A0CD61 /* csgesturescroll.cpp */; };
ACF6E5921F759EA000A0CD61 /* csgesturescroll.h in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E58B1F759EA000A0CD61 /* csgesturescroll.h */; };
ACF6E5931F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6E58C1F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.cpp */; };
ACF6E5941F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E58D1F759EA000A0CD61 /* VoodooCSGestureHIDWrapper.h */; };
ACF6E5951F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF6E58E1F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.cpp */; };
ACF6E5961F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACF6E58F1F759EA000A0CD61 /* VoodooCSGestureHIPointingWrapper.hpp */; };
ACF810E81F3304720031A6F5 /* VoodooI2CControllerNub.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACF810E61F3304720031A6F5 /* VoodooI2CControllerNub.cpp */; };
ACF810E91F3304720031A6F5 /* VoodooI2CControllerNub.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACF810E71F3304720031A6F5 /* VoodooI2CControllerNub.hpp */; };
ACFCBA901F33644D00F9B59C /* VoodooI2CControllerDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ACFCBA8E1F33644D00F9B59C /* VoodooI2CControllerDriver.cpp */; };
ACFCBA911F33644D00F9B59C /* VoodooI2CControllerDriver.hpp in Headers */ = {isa = PBXBuildFile; fileRef = ACFCBA8F1F33644D00F9B59C /* VoodooI2CControllerDriver.hpp */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
7B30D69B1F91141300190488 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 7B30D6971F91141300190488 /* VoodooI2CELAN.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 7B30D6871F910BAB00190488;
remoteInfo = VoodooI2CELAN;
};
7B30D69D1F91166900190488 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 7B30D6971F91141300190488 /* VoodooI2CELAN.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 7B30D6861F910BAB00190488;
remoteInfo = VoodooI2CELAN;
};
ACBE3FED1FEDF49B0027F52E /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = AC09558A1F4EE10C0052E343 /* VoodooGPIO.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = F1F172C41F42263A00AD98FA;
remoteInfo = VoodooGPIO;
};
ACBE3FF41FEDF4FA0027F52E /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = ACBE3FF01FEDF4FA0027F52E /* VoodooI2CUPDDEngine.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 4E0A28F01FAD1AD200D377B0;
remoteInfo = VoodooI2CUPDDEngine;
};
ACBE3FF61FEDF4FE0027F52E /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = ACBE3FF01FEDF4FA0027F52E /* VoodooI2CUPDDEngine.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 4E0A28EF1FAD1AD200D377B0;
remoteInfo = VoodooI2CUPDDEngine;
};
AC0387581F5422FB00ECEDF9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = AC0387541F5422FB00ECEDF9 /* VoodooI2CHID.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AC0DE5DF1F4FFB4B006149C8;
remoteInfo = VoodooI2CHID;
};
AC09558E1F4EE10C0052E343 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = AC09558A1F4EE10C0052E343 /* VoodooGPIO.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F1F172C51F42263A00AD98FA;
remoteInfo = VoodooGPIO;
};
AC2DC7351F7F0E5B0071CDCA /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = AC2DC7311F7F0E5B0071CDCA /* VoodooI2CServices.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AC2DC71C1F7F0D450071CDCA;
remoteInfo = VoodooI2CServices;
};
AC2DC7371F7F0E670071CDCA /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = AC2DC7311F7F0E5B0071CDCA /* VoodooI2CServices.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = AC2DC71B1F7F0D450071CDCA;
remoteInfo = VoodooI2CServices;
};
ACFB95CB1F54294F00867E18 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = AC0387541F5422FB00ECEDF9 /* VoodooI2CHID.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = AC0DE5DE1F4FFB4B006149C8;
remoteInfo = VoodooI2CHID;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
<<<<<<< HEAD
7B30D6971F91141300190488 /* VoodooI2CELAN.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = VoodooI2CELAN.xcodeproj; path = "../../VoodooI2C Satellites/VoodooI2CELAN/VoodooI2CELAN.xcodeproj"; sourceTree = ""; };
4E6786791FACB2A80000D307 /* updd_data.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = updd_data.h; path = "../../Multitouch Support/UPDD/updd_data.h"; sourceTree = ""; };
=======
4E6786791FACB2A80000D307 /* VoodooI2CUPDDData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = VoodooI2CUPDDData.h; path = "../../Multitouch Support/UPDD/VoodooI2CUPDDData.h"; sourceTree = ""; };
>>>>>>> a29c41f... Changes to comply with VoodooI2C design guidelines.
4E67867A1FACB2A80000D307 /* VoodooI2CUPDDEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CUPDDEngine.cpp; path = "../../Multitouch Support/UPDD/VoodooI2CUPDDEngine.cpp"; sourceTree = ""; };
4E67867B1FACB2A80000D307 /* VoodooI2CUPDDEngine.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CUPDDEngine.hpp; path = "../../Multitouch Support/UPDD/VoodooI2CUPDDEngine.hpp"; sourceTree = ""; };
4E67867C1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CUPDDGestureSocket.cpp; path = "../../Multitouch Support/UPDD/VoodooI2CUPDDGestureSocket.cpp"; sourceTree = ""; };
4E67867D1FACB2A80000D307 /* VoodooI2CUPDDGestureSocket.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CUPDDGestureSocket.hpp; path = "../../Multitouch Support/UPDD/VoodooI2CUPDDGestureSocket.hpp"; sourceTree = ""; };
AC015C451F32345500516383 /* VoodooI2CACPIController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VoodooI2CACPIController.cpp; path = VoodooI2CController/VoodooI2CACPIController.cpp; sourceTree = ""; };
AC015C461F32345500516383 /* VoodooI2CACPIController.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = VoodooI2CACPIController.hpp; path = VoodooI2CController/VoodooI2CACPIController.hpp; sourceTree = ""; };
AC0387541F5422FB00ECEDF9 /* VoodooI2CHID.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = VoodooI2CHID.xcodeproj; path = "../../VoodooI2C Satellites/VoodooI2CHID/VoodooI2CHID.xcodeproj"; sourceTree = ""; };
AC0955731F4ED4C50052E343 /* helpers.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = helpers.cpp; path = ../../Dependencies/helpers.cpp; sourceTree = "