Showing preview only (440K chars total). Download the full file or copy to clipboard to get everything.
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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>IOKitPersonalities</key>
<dict>
<key>Surface Ambient Light Sensor</key>
<dict>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>IOClass</key>
<string>SurfaceAmbientLightSensorDriver</string>
<key>IOProbeScore</key>
<integer>400</integer>
<key>IOPropertyMatch</key>
<dict>
<key>name</key>
<string>MSHW0184</string>
</dict>
<key>IOProviderClass</key>
<string>VoodooI2CDeviceNub</string>
</dict>
<key>Surface Battery</key>
<dict>
<key>BatteryCount</key>
<integer>1</integer>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>IOClass</key>
<string>SurfaceBatteryDriver</string>
<key>IOProviderClass</key>
<string>SurfaceBatteryNub</string>
<key>PerformanceMode</key>
<integer>1</integer>
</dict>
<key>Surface Battery SMBus Controller</key>
<dict>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>IOClass</key>
<string>SurfaceSMBusController</string>
<key>IOProviderClass</key>
<string>SurfaceBatteryDriver</string>
</dict>
<key>Surface Button</key>
<dict>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>IOClass</key>
<string>SurfaceButtonDriver</string>
<key>IONameMatch</key>
<string>MSHW0040</string>
<key>IOProbeScore</key>
<integer>400</integer>
<key>IOProviderClass</key>
<string>IOACPIPlatformDevice</string>
</dict>
<key>Surface Management Engine</key>
<dict>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>IOClass</key>
<string>SurfaceManagementEngineDriver</string>
<key>IOPCIMatch</key>
<string>0x34e48086 0x9d3e8086</string>
<key>IOProbeScore</key>
<integer>400</integer>
<key>IOProviderClass</key>
<string>IOPCIDevice</string>
</dict>
<key>Surface Serial Hub</key>
<dict>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>IOClass</key>
<string>SurfaceSerialHubDriver</string>
<key>IONameMatch</key>
<string>MSHW0084</string>
<key>IOProbeScore</key>
<integer>600</integer>
<key>IOProviderClass</key>
<string>IOACPIPlatformDevice</string>
</dict>
</dict>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2021 Xia Shangning. All rights reserved.</string>
<key>OSBundleCompatibleVersion</key>
<string>1.0.0</string>
<key>OSBundleLibraries</key>
<dict>
<key>as.vit9696.Lilu</key>
<string>1.2.0</string>
<key>as.vit9696.VirtualSMC</key>
<string>1.2.0</string>
<key>com.apple.iokit.IOACPIFamily</key>
<string>1.4</string>
<key>com.apple.iokit.IOHIDFamily</key>
<string>2.0</string>
<key>com.apple.iokit.IOPCIFamily</key>
<string>2.9</string>
<key>com.apple.iokit.IOSMBusFamily</key>
<string>1.0.0</string>
<key>com.apple.kpi.bsd</key>
<string>16.7</string>
<key>com.apple.kpi.iokit</key>
<string>16.7</string>
<key>com.apple.kpi.libkern</key>
<string>16.7</string>
<key>com.apple.kpi.mach</key>
<string>16.7</string>
<key>com.xavier.VoodooSerial</key>
<string>1.2</string>
<key>org.coolstar.VoodooGPIO</key>
<string>1.2</string>
</dict>
<key>OSBundleRequired</key>
<string>Root</string>
</dict>
</plist>
================================================
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<Value *>(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 <libkern/libkern.h>
#include <VirtualSMCSDK/kern_vsmcapi.hpp>
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 <Headers/kern_util.hpp>
#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<const SMC_DATA *>(&sensor), sizeof(sensor), SmcKeyTypeAli, nullptr, SMC_KEY_ATTRIBUTE_CONST | SMC_KEY_ATTRIBUTE_READ));
VirtualSMCAPI::addKey(KeyALI1, vsmcPlugin.data, VirtualSMCAPI::valueWithData(
reinterpret_cast<const SMC_DATA *>(&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<const SMC_DATA *>(&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<const SMC_DATA *>(&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<SurfaceAmbientLightSensorDriver *>(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<UInt8 *>(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 <IOKit/IOTimerEventSource.h>
#include <IOKit/acpi/IOACPIPlatformDevice.h>
#include "../../../Dependencies/VoodooGPIO/VoodooGPIO/VoodooGPIO.hpp"
#include "../../../Dependencies/VoodooSerial/VoodooSerial/ACPIParser/VoodooACPIResourcesParser.hpp"
#include "./../../Dependencies/VoodooSerial/VoodooSerial/VoodooI2C/VoodooI2CDevice/VoodooI2CDeviceNub.hpp"
#include <VirtualSMCSDK/kern_vsmcapi.hpp>
#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; i<bat_cnt; i++)
instance->batteries[i] = SurfaceBattery(OSDynamicCast(IOACPIPlatformDevice, deviceIterator->getNextObject()), i, instance->stateLock, &instance->state.btInfo[i]);
deviceIterator->release();
} else {
for (UInt8 i=0; i<bat_cnt; i++)
instance->batteries[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; i<adp_cnt; i++)
instance->adapters[i] = SurfaceACAdapter(OSDynamicCast(IOACPIPlatformDevice, deviceIterator->getNextObject()), i, instance->stateLock, &instance->state.acInfo[i]);
deviceIterator->release();
} else {
for (UInt8 i=0; i<adp_cnt; i++)
instance->adapters[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 <IOKit/pwr_mgt/RootDomain.h>
#include <Headers/kern_util.hpp>
#include <stdatomic.h>
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<bool *>(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<SInt16 *>(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<UInt16 *>(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<UInt16 *>(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<UInt16 *>(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<UInt16 *>(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<UInt16 *>(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<UInt16 *>(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<bool *>(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<bool *>(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<bool *>(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<UInt16 *>(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<UInt16 *>(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<UInt16 *>(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<UInt16 *>(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 <libkern/libkern.h>
#include <VirtualSMCSDK/kern_vsmcapi.hpp>
#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 <IOKit/acpi/IOACPIPlatformDevice.h>
#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 <IOKit/battery/AppleSmartBatteryCommands.h>
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 <IOKit/acpi/IOACPIPlatformDevice.h>
#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 <VirtualSMCSDK/kern_vsmcapi.hpp>
#include <Headers/kern_util.hpp>
#include "SurfaceBatteryDriver.hpp"
#include "KeyImplementations.hpp"
#include <IOKit/battery/AppleSmartBatteryCommands.h>
#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<UInt32 *>(buffer+1);
const char *str = reinterpret_cast<const char *>(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<VirtualSMCKeyValue *>(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<SurfaceBatteryDriver *>(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 <stdatomic.h>
#include <libkern/c++/OSContainers.h>
#include <IOKit/IOCatalogue.h>
#include <IOKit/IOTimerEventSource.h>
#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<UInt16*>(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<char *>(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<char *>(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<char *>(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<char *>(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<char *>(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<UInt16 *>(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<SurfaceSMBusController *>(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 <IOKit/IOSMBusController.h>
#include <IOKit/IOInterruptEventSource.h>
#include <IOKit/battery/AppleSmartBatteryCommands.h>
#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 <IOKit/hid/IOHIDDevice.h>
#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<UInt8 const*>(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 <IOKit/acpi/IOACPIPlatformDevice.h>
#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<MEIBusExtendedHeader *>(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<UInt8 *>(hdr) >= reinterpret_cast<UInt8 *>(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<MEIBusMessage *>(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<UInt32 *>(swapped_uuid)) = OSSwapInt32(*(reinterpret_cast<UInt32 *>(swapped_uuid)));
*(reinterpret_cast<UInt16 *>(swapped_uuid) + 2) = OSSwapInt16(*(reinterpret_cast<UInt16 *>(swapped_uuid) + 2));
*(reinterpret_cast<UInt16 *>(swapped_uuid) + 3) = OSSwapInt16(*(reinterpret_cast<UInt16 *>(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<UInt32 *>(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<MEI_SLOT_TYPE *>(header);
for (int i = 0; i < header_len / MEI_SLOT_SIZE; i++)
writeRegister(buf[i], MEI_H_CB_WW);
buf = reinterpret_cast<MEI_SLOT_TYPE *>(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<UInt8 *>(header), sizeof(MEIBusMessageHeader), reinterpret_cast<UInt8 *>(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<MEIBusMessageHeader *>(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<MEIBusMessageHeader *>(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<MEIBusExtendedMetaHeader *>(&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<MEIBusMessage *>(bus.rx_msg_buf);
// MEIBusClientCommand *cl_cmd = reinterpret_cast<MEIBusClientCommand *>(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<MEIBusHostVersionResponse *>(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() != kIOReturnSucc
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
SYMBOL INDEX (268 symbols across 33 files)
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/AmbientLightValue.cpp
function SMC_RESULT (line 10) | SMC_RESULT SMCAmbientLightValue::readAccess() {
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/AmbientLightValue.hpp
class ALSForceBits (line 14) | class ALSForceBits : public VirtualSMCValue {
method UInt8 (line 37) | UInt8 bits() { return data[0]; }
class SMCAmbientLightValue (line 40) | class SMCAmbientLightValue : public VirtualSMCValue {
type PACKED (line 50) | struct PACKED
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/SurfaceAmbientLightSensorDriver.cpp
function IOService (line 16) | IOService* SurfaceAmbientLightSensorDriver::probe(IOService *provider, S...
function IOReturn (line 122) | IOReturn SurfaceAmbientLightSensorDriver::initDevice() {
function IOReturn (line 145) | inline IOReturn SurfaceAmbientLightSensorDriver::readRegister(UInt8 reg,...
function IOReturn (line 149) | inline IOReturn SurfaceAmbientLightSensorDriver::writeRegister(UInt8 reg...
function IOReturn (line 157) | IOReturn SurfaceAmbientLightSensorDriver::configDevice(UInt8 func, bool ...
function IOReturn (line 198) | IOReturn SurfaceAmbientLightSensorDriver::setPowerState(unsigned long wh...
FILE: BigSurface/BigSurface/SurfaceAmbientLightSensor/SurfaceAmbientLightSensorDriver.hpp
function SurfaceAmbientLightSensorDriver (line 25) | class EXPORT SurfaceAmbientLightSensorDriver : public IOService {
FILE: BigSurface/BigSurface/SurfaceBattery/BatteryManager.cpp
function UInt16 (line 179) | UInt16 BatteryManager::calculateBatteryStatus(UInt8 index) {
FILE: BigSurface/BigSurface/SurfaceBattery/BatteryManager.hpp
function BatteryManager (line 21) | class EXPORT BatteryManager : public OSObject {
FILE: BigSurface/BigSurface/SurfaceBattery/BatteryManagerState.hpp
type BatteryInfo (line 14) | struct BatteryInfo {
type State (line 38) | struct State {
type BatteryManufacturerData (line 77) | struct BatteryManufacturerData {
type ACAdapterInfo (line 112) | struct ACAdapterInfo {
type BatteryManagerState (line 119) | struct BatteryManagerState {
FILE: BigSurface/BigSurface/SurfaceBattery/KeyImplementations.cpp
function SMC_RESULT (line 11) | SMC_RESULT ACID::readAccess() {
function SMC_RESULT (line 32) | SMC_RESULT ACIN::readAccess() {
function SMC_RESULT (line 40) | SMC_RESULT AC_N::readAccess() {
function SMC_RESULT (line 45) | SMC_RESULT B0AC::readAccess() {
function SMC_RESULT (line 53) | SMC_RESULT B0AV::readAccess() {
function SMC_RESULT (line 61) | SMC_RESULT B0BI::readAccess() {
function SMC_RESULT (line 68) | SMC_RESULT B0CT::readAccess() {
function SMC_RESULT (line 77) | SMC_RESULT B0FC::readAccess() {
function SMC_RESULT (line 85) | SMC_RESULT B0PS::readAccess() {
function SMC_RESULT (line 91) | SMC_RESULT B0RM::readAccess() {
function SMC_RESULT (line 99) | SMC_RESULT B0St::readAccess() {
function SMC_RESULT (line 107) | SMC_RESULT B0TF::readAccess() {
function SMC_RESULT (line 119) | SMC_RESULT BATP::readAccess() {
function SMC_RESULT (line 127) | SMC_RESULT BBAD::readAccess() {
function SMC_RESULT (line 136) | SMC_RESULT BBIN::readAccess() {
function SMC_RESULT (line 144) | SMC_RESULT BFCL::readAccess() {
function SMC_RESULT (line 150) | SMC_RESULT BNum::readAccess() {
function SMC_RESULT (line 155) | SMC_RESULT BSIn::readAccess() {
function SMC_RESULT (line 178) | SMC_RESULT BRSC::readAccess() {
function SMC_RESULT (line 197) | SMC_RESULT CHBI::readAccess() {
function SMC_RESULT (line 205) | SMC_RESULT CHBV::readAccess() {
function SMC_RESULT (line 213) | SMC_RESULT CHLC::readAccess() {
function SMC_RESULT (line 232) | SMC_RESULT TB0T::readAccess() {
function SMC_RESULT (line 240) | SMC_RESULT BC1V::readAccess() {
FILE: BigSurface/BigSurface/SurfaceBattery/KeyImplementations.hpp
class BatKey (line 16) | class BatKey : public VirtualSMCValue { }
class BatIdxKey (line 18) | class BatIdxKey : public VirtualSMCValue {
method BatIdxKey (line 22) | BatIdxKey(size_t index) : index(index) {}
class AC_N (line 25) | class AC_N : public BatKey { protected: SMC_RESULT readAccess() override; }
class ACID (line 26) | class ACID : public BatKey { protected: SMC_RESULT readAccess() override; }
class ACIN (line 27) | class ACIN : public BatKey { protected: SMC_RESULT readAccess() override; }
class B0AC (line 29) | class B0AC : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class B0AV (line 30) | class B0AV : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class B0BI (line 31) | class B0BI : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class B0CT (line 32) | class B0CT : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class B0FC (line 33) | class B0FC : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class B0PS (line 34) | class B0PS : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class B0RM (line 35) | class B0RM : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class B0St (line 36) | class B0St : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class B0TF (line 37) | class B0TF : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class TB0T (line 38) | class TB0T : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
class BATP (line 40) | class BATP : public BatKey { protected: SMC_RESULT readAccess() override; }
class BBAD (line 41) | class BBAD : public BatKey { protected: SMC_RESULT readAccess() override; }
class BBIN (line 42) | class BBIN : public BatKey { protected: SMC_RESULT readAccess() override; }
class BFCL (line 43) | class BFCL : public BatKey { protected: SMC_RESULT readAccess() override; }
class BNum (line 44) | class BNum : public BatKey { protected: SMC_RESULT readAccess() override; }
class BSIn (line 45) | class BSIn : public BatKey { protected: SMC_RESULT readAccess() override; }
class BRSC (line 46) | class BRSC : public BatKey { protected: SMC_RESULT readAccess() override; }
class CHBI (line 47) | class CHBI : public BatKey { protected: SMC_RESULT readAccess() override; }
class CHBV (line 48) | class CHBV : public BatKey { protected: SMC_RESULT readAccess() override; }
class CHLC (line 49) | class CHLC : public BatKey { protected: SMC_RESULT readAccess() override; }
class BC1V (line 51) | class BC1V : public BatIdxKey { using BatIdxKey::BatIdxKey; protected: S...
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceACAdapter.hpp
class SurfaceACAdapter (line 14) | class SurfaceACAdapter {
method SurfaceACAdapter (line 16) | SurfaceACAdapter() {}
method SurfaceACAdapter (line 20) | SurfaceACAdapter(IOACPIPlatformDevice *device, SInt32 id, IOSimpleLock...
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceBattery.cpp
function UInt32 (line 11) | UInt32 SurfaceBattery::getNumberFromArray(OSArray *array, UInt32 index) {
function UInt16 (line 184) | UInt16 SurfaceBattery::calculateBatteryStatus() {
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceBattery.hpp
class SurfaceBattery (line 14) | class SurfaceBattery {
method SurfaceBattery (line 52) | SurfaceBattery() {}
method SurfaceBattery (line 57) | SurfaceBattery(IOACPIPlatformDevice *device, SInt32 id, IOSimpleLock *...
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceBatteryDriver.cpp
function IOService (line 199) | IOService *SurfaceBatteryDriver::probe(IOService *provider, SInt32 *scor...
function IOReturn (line 368) | IOReturn SurfaceBatteryDriver::setProperties(OSObject *props) {
function IOReturn (line 391) | IOReturn SurfaceBatteryDriver::setPowerState(unsigned long whichState, I...
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceBatteryDriver.hpp
function SurfaceBatteryDriver (line 18) | class EXPORT SurfaceBatteryDriver : public IOService {
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceSMBusController.cpp
function IOSMBusStatus (line 63) | IOSMBusStatus SurfaceSMBusController::startRequest(IOSMBusRequest *reque...
function IOReturn (line 330) | IOReturn SurfaceSMBusController::handleACPINotification(void *target) {
FILE: BigSurface/BigSurface/SurfaceBattery/SurfaceSMBusController.hpp
function SurfaceSMBusController (line 17) | class EXPORT SurfaceSMBusController : public IOSMBusController {
FILE: BigSurface/BigSurface/SurfaceButton/HIDReport.hpp
class keys (line 8) | class __attribute__((packed)) keys final {
method keys (line 10) | keys(void) : keys_{} {}
method UInt8 (line 12) | const UInt8(&get_raw_value(void) const)[32] {
method empty (line 16) | bool empty(void) const {
method clear (line 25) | void clear(void) {
method insert (line 29) | void insert(UInt8 key) {
method erase (line 40) | void erase(UInt8 key) {
method exists (line 48) | bool exists(UInt8 key) const {
method count (line 57) | size_t count(void) const {
class consumer_input (line 74) | class __attribute__((packed)) consumer_input final {
method consumer_input (line 76) | consumer_input(void) : report_id_(2) {}
FILE: BigSurface/BigSurface/SurfaceButton/SurfaceButtonDevice.cpp
function IOReturn (line 29) | IOReturn SurfaceButtonDevice::simulateKeyboardEvent(UInt32 usagePage, UI...
function IOReturn (line 59) | IOReturn SurfaceButtonDevice::newReportDescriptor(IOMemoryDescriptor **d...
function OSString (line 64) | OSString *SurfaceButtonDevice::newManufacturerString() const {
function OSString (line 68) | OSString *SurfaceButtonDevice::newProductString() const {
function OSNumber (line 72) | OSNumber *SurfaceButtonDevice::newVendorIDNumber() const {
function OSNumber (line 76) | OSNumber *SurfaceButtonDevice::newProductIDNumber() const {
function OSNumber (line 80) | OSNumber *SurfaceButtonDevice::newLocationIDNumber() const {
function OSNumber (line 84) | OSNumber *SurfaceButtonDevice::newCountryCodeNumber() const {
function OSNumber (line 88) | OSNumber *SurfaceButtonDevice::newVersionNumber() const {
function OSNumber (line 92) | OSNumber *SurfaceButtonDevice::newPrimaryUsagePageNumber() const {
function OSNumber (line 96) | OSNumber *SurfaceButtonDevice::newPrimaryUsageNumber() const {
FILE: BigSurface/BigSurface/SurfaceButton/SurfaceButtonDevice.hpp
class SurfaceButtonDevice (line 12) | class SurfaceButtonDevice final : public IOHIDDevice {
FILE: BigSurface/BigSurface/SurfaceButton/SurfaceButtonDriver.cpp
function VoodooGPIO (line 14) | VoodooGPIO* SurfaceButtonDriver::getGPIOController() {
function IOReturn (line 29) | IOReturn SurfaceButtonDriver::parseButtonResources(VoodooACPIResourcesPa...
function IOReturn (line 51) | IOReturn SurfaceButtonDriver::getDeviceResources() {
function IOService (line 121) | IOService *SurfaceButtonDriver::probe(IOService *provider, SInt32 *score){
function IOReturn (line 189) | IOReturn SurfaceButtonDriver::setPowerState(unsigned long whichState, IO...
function IOReturn (line 213) | IOReturn SurfaceButtonDriver::enableInterrupt(int source) {
function IOReturn (line 217) | IOReturn SurfaceButtonDriver::disableInterrupt(int source) {
function IOReturn (line 221) | IOReturn SurfaceButtonDriver::getInterruptType(int source, int* interrup...
function IOReturn (line 225) | IOReturn SurfaceButtonDriver::registerInterrupt(int source, OSObject *ta...
function IOReturn (line 230) | IOReturn SurfaceButtonDriver::unregisterInterrupt(int source) {
FILE: BigSurface/BigSurface/SurfaceButton/SurfaceButtonDriver.hpp
function SurfaceButtonDriver (line 29) | class EXPORT SurfaceButtonDriver : public IOService {
FILE: BigSurface/BigSurface/SurfaceManagementEngine/MEIProtocol.h
type MEIHostBusMessageReturnType (line 207) | enum MEIHostBusMessageReturnType
type MEIExtendedHeaderType (line 219) | enum MEIExtendedHeaderType : UInt8 {
function MEIBusExtendedHeader (line 230) | struct PACKED MEIBusExtendedHeader {
function MEIBusExtendedMetaHeader (line 245) | struct PACKED MEIBusExtendedMetaHeader {
function MEIBusExtendedHeader (line 255) | static inline MEIBusExtendedHeader *mei_ext_begin(MEIBusExtendedMetaHead...
function mei_ext_last (line 268) | static inline bool mei_ext_last(MEIBusExtendedMetaHeader *meta, MEIBusEx...
function MEIBusMessageHeader (line 286) | struct PACKED MEIBusMessageHeader {
function MEIBusMessage (line 307) | struct PACKED MEIBusMessage {
function MEIBusGenericMessage (line 314) | struct PACKED MEIBusGenericMessage {
type MEIBusGenericMessage (line 319) | typedef MEIBusGenericMessage MEIBusPowerGatingRequest;
type MEIBusGenericMessage (line 320) | typedef MEIBusGenericMessage MEIBusPowerGatingResponse;
function MEIBusHostVersionRequest (line 322) | struct PACKED MEIBusHostVersionRequest {
function MEIBusHostVersionResponse (line 329) | struct PACKED MEIBusHostVersionResponse {
type MEIStopReason (line 336) | enum MEIStopReason
function MEIBusHostStopRequest (line 348) | struct PACKED MEIBusHostStopRequest {
function MEIBusHostStopResponse (line 354) | struct PACKED MEIBusHostStopResponse {
function MEIBusMEStopRequest (line 359) | struct PACKED MEIBusMEStopRequest {
function MEIBusHostEnumerationRequest (line 372) | struct PACKED MEIBusHostEnumerationRequest {
function MEIBusHostEnumerationResponse (line 378) | struct PACKED MEIBusHostEnumerationResponse {
function MEIClientProperty (line 396) | struct PACKED MEIClientProperty {
function MEIBusClientPropertyRequest (line 407) | struct PACKED MEIBusClientPropertyRequest {
function MEIBusClientPropertyResponse (line 413) | struct PACKED MEIBusClientPropertyResponse {
function MEIBusAddClientRequest (line 430) | struct PACKED MEIBusAddClientRequest {
function MEIBusAddClientResponse (line 446) | struct PACKED MEIBusAddClientResponse {
function MEIBusClientCommand (line 462) | struct PACKED MEIBusClientCommand {
type MEIBusClientCommand (line 469) | typedef MEIBusClientCommand MEIBusClientConnectionRequest;
type MEIClientConnectionStatus (line 471) | enum MEIClientConnectionStatus
function MEIBusClientConnectionResponse (line 488) | struct PACKED MEIBusClientConnectionResponse {
function MEIBusFlowControl (line 497) | struct PACKED MEIBusFlowControl {
function MEIBusNotificationRequest (line 514) | struct PACKED MEIBusNotificationRequest {
function MEIBusNotificationResponse (line 535) | struct PACKED MEIBusNotificationResponse {
function MEIBusDMAInfo (line 551) | struct PACKED MEIBusDMAInfo {
type MEIDMADescriptor (line 564) | enum MEIDMADescriptor {
function MEIBusDMASetupRequest (line 578) | struct PACKED MEIBusDMASetupRequest {
function MEIBusDMASetupResponse (line 591) | struct PACKED MEIBusDMASetupResponse {
function MEIBusDMARingControl (line 609) | struct PACKED MEIBusDMARingControl {
function MEIBusCapabilityRequest (line 631) | struct PACKED MEIBusCapabilityRequest {
function MEIBusCapabilityResponse (line 642) | struct PACKED MEIBusCapabilityResponse {
function MEIBusClientDMAMapRequest (line 657) | struct PACKED MEIBusClientDMAMapRequest {
function MEIBusClientDMAUnmapRequest (line 674) | struct PACKED MEIBusClientDMAUnmapRequest {
function MEIBusClientDMAResponse (line 687) | struct PACKED MEIBusClientDMAResponse {
FILE: BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineClient.cpp
function IOReturn (line 85) | IOReturn SurfaceManagementEngineClient::setPowerState(unsigned long whic...
function IOReturn (line 111) | IOReturn SurfaceManagementEngineClient::registerMessageHandler(OSObject ...
function IOReturn (line 131) | IOReturn SurfaceManagementEngineClient::sendMessage(UInt8 *data, UInt16 ...
FILE: BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineClient.hpp
type MEIClientMessage (line 14) | struct MEIClientMessage {
function SurfaceManagementEngineClient (line 20) | class EXPORT SurfaceManagementEngineClient : public IOService {
FILE: BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineDriver.cpp
function bitmap_set_bit (line 15) | void bitmap_set_bit(UInt8 *map, UInt addr, bool set) {
function bitmap_get_bit (line 24) | bool bitmap_get_bit(UInt8 *map, UInt addr) {
function UInt (line 30) | UInt bitmap_find_next_bit(UInt8 *map, UInt map_size, UInt start_addr) {
function IOService (line 48) | IOService* SurfaceManagementEngineDriver::probe(IOService* provider, SIn...
function IOReturn (line 144) | IOReturn SurfaceManagementEngineDriver::setPowerState(unsigned long whic...
function IOReturn (line 221) | IOReturn SurfaceManagementEngineDriver::startDeviceGated() {
function IOReturn (line 282) | IOReturn SurfaceManagementEngineDriver::restartDeviceGated() {
function IOReturn (line 298) | IOReturn SurfaceManagementEngineDriver::mapMemory() {
function UInt32 (line 312) | inline UInt32 SurfaceManagementEngineDriver::readRegister(int offset) {
function UInt8 (line 329) | UInt8 SurfaceManagementEngineDriver::calcFilledSlots() {
function IOReturn (line 337) | IOReturn SurfaceManagementEngineDriver::findEmptySlots(UInt8 *empty_slot...
function IOReturn (line 346) | IOReturn SurfaceManagementEngineDriver::countRxSlots(UInt8 *filled_slots) {
function IOReturn (line 428) | IOReturn SurfaceManagementEngineDriver::initDevice() {
function IOReturn (line 453) | IOReturn SurfaceManagementEngineDriver::resetDevice() {
function IOReturn (line 580) | IOReturn SurfaceManagementEngineDriver::waitDeviceReady() {
function IOReturn (line 676) | IOReturn SurfaceManagementEngineDriver::enterPowerGating() {
function IOReturn (line 689) | IOReturn SurfaceManagementEngineDriver::enterPowerGatingSync() {
function IOReturn (line 746) | IOReturn SurfaceManagementEngineDriver::exitPowerGatingSync() {
function IOReturn (line 794) | IOReturn SurfaceManagementEngineDriver::writeMessage(UInt8 *header, UInt...
function IOReturn (line 841) | IOReturn SurfaceManagementEngineDriver::writeHostMessage(MEIBusMessageHe...
function IOReturn (line 845) | IOReturn SurfaceManagementEngineDriver::sendClientMessage(SurfaceManagem...
function IOReturn (line 849) | IOReturn SurfaceManagementEngineDriver::sendClientMessageGated(SurfaceMa...
function IOReturn (line 892) | IOReturn SurfaceManagementEngineDriver::sendStartRequest() {
function IOReturn (line 904) | IOReturn SurfaceManagementEngineDriver::sendPowerGatingCommand(bool ente...
function IOReturn (line 923) | IOReturn SurfaceManagementEngineDriver::sendStopRequest() {
function IOReturn (line 934) | IOReturn SurfaceManagementEngineDriver::sendCapabilityRequest() {
function IOReturn (line 953) | IOReturn SurfaceManagementEngineDriver::sendClientEnumerationRequest() {
function IOReturn (line 970) | IOReturn SurfaceManagementEngineDriver::sendClientPropertyRequest(UInt s...
function IOReturn (line 997) | IOReturn SurfaceManagementEngineDriver::sendAddClientResponse(UInt8 me_a...
function IOReturn (line 1147) | IOReturn SurfaceManagementEngineDriver::handleRead(UInt8 *filled_slots) {
function IOReturn (line 1247) | IOReturn SurfaceManagementEngineDriver::handleHostMessage(MEIBusMessageH...
function IOReturn (line 1502) | IOReturn SurfaceManagementEngineDriver::handleClientMessage(SurfaceManag...
function IOReturn (line 1533) | IOReturn SurfaceManagementEngineDriver::handleWrite() {
function IOReturn (line 1621) | IOReturn SurfaceManagementEngineDriver::addClient(MEIClientProperty *cli...
FILE: BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineDriver.hpp
type MEIDeviceState (line 29) | enum MEIDeviceState {
type MEIBusState (line 51) | enum MEIBusState {
type MEIPowerGatingEvent (line 71) | enum MEIPowerGatingEvent {
type MEIPowerGatingState (line 85) | enum MEIPowerGatingState {
type MEIPhysicalDevice (line 90) | struct MEIPhysicalDevice {
class SurfaceManagementEngineClient (line 117) | class SurfaceManagementEngineClient
type MEIClientTransaction (line 119) | struct MEIClientTransaction {
type MEIBus (line 129) | struct MEIBus {
function SurfaceManagementEngineDriver (line 145) | class EXPORT SurfaceManagementEngineDriver : public IOService {
FILE: BigSurface/BigSurface/SurfaceSerialHub/SerialProtocol.h
function SurfaceSerialFrame (line 131) | struct PACKED SurfaceSerialFrame {
function SurfaceSerialPayload (line 137) | struct PACKED SurfaceSerialPayload {
function SurfaceSerialCommand (line 142) | struct PACKED SurfaceSerialCommand {
function SurfaceSerialMessage (line 153) | struct PACKED SurfaceSerialMessage {
function SurfaceSerialEventData (line 160) | struct PACKED SurfaceSerialEventData {
function UInt16 (line 204) | static inline UInt16 crc_ccitt_false_byte(UInt16 crc, const UInt8 c)
function UInt16 (line 209) | inline UInt16 crc_ccitt_false(UInt16 crc, UInt8 const* buffer, size_t len)
FILE: BigSurface/BigSurface/SurfaceSerialHub/SurfaceSerialHubDriver.cpp
type SurfaceSerialEventRegistryConfig (line 14) | struct SurfaceSerialEventRegistryConfig {
function err_dump (line 32) | void err_dump(const char *name, const char *str, UInt8 *buffer, UInt16 l...
function judge_sync (line 48) | bool judge_sync(UInt8 *buffer, UInt16 len) {
function find_sync_bytes (line 60) | int find_sync_bytes(UInt8 *buffer, UInt16 len) {
function IOReturn (line 142) | IOReturn SurfaceSerialHubDriver::processMessage() {
function IOReturn (line 267) | IOReturn SurfaceSerialHubDriver::sendACK(UInt8 seq_id) {
function IOReturn (line 280) | IOReturn SurfaceSerialHubDriver::sendNAK() {
function UInt16 (line 293) | UInt16 SurfaceSerialHubDriver::sendCommand(UInt8 tc, UInt8 tid, UInt8 ii...
function IOReturn (line 330) | IOReturn SurfaceSerialHubDriver::sendCommandGated(UInt8 *tx_buffer, UInt...
function IOReturn (line 383) | IOReturn SurfaceSerialHubDriver::getResponse(UInt8 tc, UInt8 tid, UInt8 ...
function IOReturn (line 391) | IOReturn SurfaceSerialHubDriver::waitResponse(UInt16 *req_id, UInt8 *buf...
function IOReturn (line 424) | IOReturn SurfaceSerialHubDriver::registerEvent(SurfaceSerialHubClient *c...
function IOReturn (line 481) | IOReturn SurfaceSerialHubDriver::sendEventCommand(SurfaceSerialEventRegi...
function IOService (line 515) | IOService* SurfaceSerialHubDriver::probe(IOService *provider, SInt32 *sc...
function IOReturn (line 637) | IOReturn SurfaceSerialHubDriver::flushCacheGated() {
function IOReturn (line 666) | IOReturn SurfaceSerialHubDriver::setPowerState(unsigned long whichState,...
function VoodooGPIO (line 757) | VoodooGPIO* SurfaceSerialHubDriver::getGPIOController() {
function VoodooUARTController (line 773) | VoodooUARTController* SurfaceSerialHubDriver::getUARTController() {
function IOReturn (line 792) | IOReturn SurfaceSerialHubDriver::getDeviceResources() {
function IOReturn (line 875) | IOReturn SurfaceSerialHubDriver::enableInterrupt(int source) {
function IOReturn (line 879) | IOReturn SurfaceSerialHubDriver::disableInterrupt(int source) {
function IOReturn (line 883) | IOReturn SurfaceSerialHubDriver::getInterruptType(int source, int* inter...
function IOReturn (line 887) | IOReturn SurfaceSerialHubDriver::registerInterrupt(int source, OSObject ...
function IOReturn (line 892) | IOReturn SurfaceSerialHubDriver::unregisterInterrupt(int source) {
FILE: BigSurface/BigSurface/SurfaceSerialHub/SurfaceSerialHubDriver.hpp
type SurfaceSerialEventRegistryType (line 18) | enum SurfaceSerialEventRegistryType {
function SurfaceSerialHubClient (line 35) | class EXPORT SurfaceSerialHubClient : public IOService {
class SurfaceBatteryNub (line 47) | class SurfaceBatteryNub
class SurfaceHIDNub (line 48) | class SurfaceHIDNub
function SurfaceSerialHubDriver (line 50) | class EXPORT SurfaceSerialHubDriver : public IOService {
FILE: BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceBatteryNub.cpp
function IOReturn (line 47) | IOReturn SurfaceBatteryNub::setPowerState(unsigned long whichState, IOSe...
function IOReturn (line 53) | IOReturn SurfaceBatteryNub::registerBatteryEvent(OSObject* owner, EventH...
function IOReturn (line 102) | IOReturn SurfaceBatteryNub::getBatteryConnection(UInt8 index, bool *conn...
function IOReturn (line 112) | IOReturn SurfaceBatteryNub::getBatteryInformation(UInt8 index, OSArray *...
function IOReturn (line 158) | IOReturn SurfaceBatteryNub::getBatteryStatus(UInt8 index, UInt32 *bst, U...
function IOReturn (line 169) | IOReturn SurfaceBatteryNub::getAdaptorStatus(UInt32 *psr) {
function IOReturn (line 173) | IOReturn SurfaceBatteryNub::setPerformanceMode(UInt32 mode) {
FILE: BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceBatteryNub.hpp
type SurfaceBatteryEventType (line 17) | enum SurfaceBatteryEventType {
function SurfaceSerialHubClient (line 23) | class EXPORT SurfaceBatteryNub : public SurfaceSerialHubClient {
FILE: BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceHIDNub.cpp
function IOReturn (line 58) | IOReturn SurfaceHIDNub::setPowerState(unsigned long whichState, IOServic...
function IOReturn (line 64) | IOReturn SurfaceHIDNub::registerHIDEvent(OSObject* owner, EventHandler _...
function IOReturn (line 137) | IOReturn SurfaceHIDNub::getHIDDescriptor(SurfaceHIDDeviceType device, Su...
function IOReturn (line 141) | IOReturn SurfaceHIDNub::getHIDAttributes(SurfaceHIDDeviceType device, Su...
function IOReturn (line 145) | IOReturn SurfaceHIDNub::getReportDescriptor(SurfaceHIDDeviceType device,...
function IOReturn (line 149) | IOReturn SurfaceHIDNub::getDescriptorData(SurfaceHIDDeviceType device, S...
function IOReturn (line 156) | IOReturn SurfaceHIDNub::getLegacyData(SurfaceHIDDeviceType device, Surfa...
function IOReturn (line 160) | IOReturn SurfaceHIDNub::getData(SurfaceHIDDeviceType device, SurfaceHIDD...
function IOReturn (line 212) | IOReturn SurfaceHIDNub::getHIDRawReport(SurfaceHIDDeviceType device, UIn...
FILE: BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceHIDNub.hpp
type SurfaceHIDDescriptorEntryType (line 14) | enum SurfaceHIDDescriptorEntryType : UInt8 {
type SurfaceHIDDeviceType (line 20) | enum SurfaceHIDDeviceType {
function SurfaceHIDDescriptorBufferHeader (line 26) | struct PACKED SurfaceHIDDescriptorBufferHeader {
function SurfaceHIDDescriptor (line 34) | struct PACKED SurfaceHIDDescriptor {
function SurfaceHIDAttributes (line 44) | struct PACKED SurfaceHIDAttributes {
function SurfaceSerialHubClient (line 57) | class EXPORT SurfaceHIDNub : public SurfaceSerialHubClient {
Condensed preview — 49 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (453K chars).
[
{
"path": ".gitignore",
"chars": 404,
"preview": "# Xcode\n#\n# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore\n\n"
},
{
"path": ".gitmodules",
"chars": 631,
"preview": "[submodule \"MacKernelSDK\"]\n\tpath = MacKernelSDK\n\turl = https://github.com/acidanthera/MacKernelSDK\n[submodule \"Dependenc"
},
{
"path": "BigSurface/BigSurface/Info.plist",
"chars": 4038,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/APDS9960Constants.h",
"chars": 4288,
"preview": "//\n// APDS9960Constants.h\n// SurfaceAmbientLightSensor\n//\n// Created by Xavier on 2021/10/27.\n// Copyright © 2021 Xi"
},
{
"path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/AmbientLightValue.cpp",
"chars": 711,
"preview": "//\n// AmbientLightValue.cpp\n// SMCLightSensor\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"Ambi"
},
{
"path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/AmbientLightValue.hpp",
"chars": 2061,
"preview": "//\n// AmbientLightValue.hpp\n// SMCLightSensor\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef Ambien"
},
{
"path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/SurfaceAmbientLightSensorDriver.cpp",
"chars": 8260,
"preview": "//\n// SurfaceAmbientLightSensorDriver.cpp\n// SurfaceAmbientLightSensor\n//\n// Created by Xia on 2021/10/27.\n// Copyri"
},
{
"path": "BigSurface/BigSurface/SurfaceAmbientLightSensor/SurfaceAmbientLightSensorDriver.hpp",
"chars": 3221,
"preview": "//\n// SurfaceAmbientLightSensorDriver.hpp\n// SurfaceAmbientLightSensor\n//\n// Created by Xia on 2021/10/27.\n// Copyri"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/BatteryManager.cpp",
"chars": 7920,
"preview": "//\n// BatteryManager.cpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"Battery"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/BatteryManager.hpp",
"chars": 2943,
"preview": "//\n// BatteryManager.hpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n// Portions copyr"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/BatteryManagerState.hpp",
"chars": 3002,
"preview": "//\n// BatteryManagerState.h\n// SurfaceBattery\n//\n// Copyright © 2018 usersse2. All rights reserved.\n//\n\n#ifndef Batte"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/KeyImplementations.cpp",
"chars": 9150,
"preview": "//\n// KeyImplementations.cpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"Key"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/KeyImplementations.hpp",
"chars": 3103,
"preview": "//\n// KeyImplementations.hpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef KeyIm"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/SurfaceACAdapter.cpp",
"chars": 603,
"preview": "//\n// SurfaceACAdapter.cpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"Surfa"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/SurfaceACAdapter.hpp",
"chars": 1017,
"preview": "//\n// SurfaceACAdapter.hpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef Surface"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/SurfaceBattery.cpp",
"chars": 7489,
"preview": "//\n// SurfaceBattery.cpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include \"Surface"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/SurfaceBattery.hpp",
"chars": 3431,
"preview": "//\n// SurfaceBattery.hpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef SurfaceBa"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/SurfaceBatteryDriver.cpp",
"chars": 18519,
"preview": "//\n// SurfaceBatteryDriver.cpp\n// SurfaceBattery\n//\n// Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#incl"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/SurfaceBatteryDriver.hpp",
"chars": 4892,
"preview": "//\n// SurfaceBatteryDriver.hpp\n// SurfaceBattery\n//\n// Copyright © 2022 Xia Shangning. All rights reserved.\n//\n\n#ifnd"
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/SurfaceSMBusController.cpp",
"chars": 14214,
"preview": "//\n// SurfaceSMBusController.cpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#include "
},
{
"path": "BigSurface/BigSurface/SurfaceBattery/SurfaceSMBusController.hpp",
"chars": 3098,
"preview": "//\n// SurfaceSMBusController.hpp\n// SurfaceBattery\n//\n// Copyright © 2018 usrsse2. All rights reserved.\n//\n\n#ifndef S"
},
{
"path": "BigSurface/BigSurface/SurfaceButton/HIDReport.hpp",
"chars": 1858,
"preview": "//\n// HIDReport.hpp\n// SurfaceButtonDriver\n//\n// Copyright © 2019 Le Bao Hiep. All rights reserved.\n//\n\nclass __attri"
},
{
"path": "BigSurface/BigSurface/SurfaceButton/SurfaceButtonDevice.cpp",
"chars": 3176,
"preview": "//\n// SurfaceButtonDevice.cpp\n// SurfaceButton\n//\n// Copyright © 2018-2020 Le Bao Hiep. All rights reserved.\n//\n\n#inc"
},
{
"path": "BigSurface/BigSurface/SurfaceButton/SurfaceButtonDevice.hpp",
"chars": 1029,
"preview": "//\n// SurfaceButtonDevice.hpp\n// SurfaceButton\n//\n// Copyright © 2018-2020 Le Bao Hiep. All rights reserved.\n//\n\n#inc"
},
{
"path": "BigSurface/BigSurface/SurfaceButton/SurfaceButtonDriver.cpp",
"chars": 10168,
"preview": "//\n// SurfaceButtonDriver.hpp\n// SurfaceButton\n//\n// Created by Xavier on 22/03/2021.\n// Copyright © 2021 Xia Shangn"
},
{
"path": "BigSurface/BigSurface/SurfaceButton/SurfaceButtonDriver.hpp",
"chars": 2877,
"preview": "//\n// SurfaceButtonDriver.hpp\n// SurfaceButton\n//\n// Created by Xavier on 22/03/2021.\n// Copyright © 2021 Xia Shangn"
},
{
"path": "BigSurface/BigSurface/SurfaceManagementEngine/MEIProtocol.h",
"chars": 20372,
"preview": "//\n// MEIProtocol.h\n// SurfaceTouchScreen\n//\n// Created by Xavier on 2022/5/29.\n// Copyright © 2022 Xia Shangning. A"
},
{
"path": "BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineClient.cpp",
"chars": 5463,
"preview": "//\n// SurfaceManagementEngineClient.cpp\n// SurfaceTouchScreen\n//\n// Created by Xavier on 2022/6/1.\n// Copyright © 20"
},
{
"path": "BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineClient.hpp",
"chars": 2167,
"preview": "//\n// SurfaceManagementEngineClient.hpp\n// SurfaceTouchScreen\n//\n// Created by Xavier on 2022/6/1.\n// Copyright © 20"
},
{
"path": "BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineDriver.cpp",
"chars": 58752,
"preview": "//\n// SurfaceManagementEngineDriver.cpp\n// SurfaceTouchScreen\n//\n// Created by Xavier on 2022/05/28.\n// Copyright © "
},
{
"path": "BigSurface/BigSurface/SurfaceManagementEngine/SurfaceManagementEngineDriver.hpp",
"chars": 8958,
"preview": "//\n// SurfaceManagementEngineDriver.hpp\n// SurfaceTouchScreen\n//\n// Created by Xavier on 2022/05/28.\n// Copyright © "
},
{
"path": "BigSurface/BigSurface/SurfaceSerialHub/SerialProtocol.h",
"chars": 8400,
"preview": "//\n// SerialProtocol.h\n// SurfaceSerialHub\n//\n// Created by Xavier on 2021/10/29.\n// Copyright © 2021 Xia Shangning."
},
{
"path": "BigSurface/BigSurface/SurfaceSerialHub/SurfaceSerialHubDriver.cpp",
"chars": 35280,
"preview": "//\n// SurfaceSerialHubDriver.cpp\n// SurfaceSerialHub\n//\n// Created by Xavier on 2021/10/29.\n// Copyright © 2021 Xia "
},
{
"path": "BigSurface/BigSurface/SurfaceSerialHub/SurfaceSerialHubDriver.hpp",
"chars": 6321,
"preview": "//\n// SurfaceSerialHubDriver.hpp\n// SurfaceSerialHub\n//\n// Created by Xavier on 2021/10/29.\n// Copyright © 2021 Xia "
},
{
"path": "BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceBatteryNub.cpp",
"chars": 6511,
"preview": "//\n// SurfaceBatteryNub.cpp\n// SurfaceSerialHubDevices\n//\n// Created by Xavier on 2022/5/19.\n// Copyright © 2022 Xia"
},
{
"path": "BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceBatteryNub.hpp",
"chars": 2022,
"preview": "//\n// SurfaceBatteryNub.hpp\n// SurfaceSerialHubDevices\n//\n// Created by Xavier on 2022/5/19.\n// Copyright © 2022 Xia"
},
{
"path": "BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceHIDNub.cpp",
"chars": 8541,
"preview": "//\n// SurfaceHIDNub.cpp\n// SurfaceSerialHubDevices\n//\n// Created by Xavier on 2022/5/20.\n// Copyright © 2022 Xia Sha"
},
{
"path": "BigSurface/BigSurface/SurfaceSerialHubDevices/SurfaceHIDNub.hpp",
"chars": 3258,
"preview": "//\n// SurfaceHIDNub.hpp\n// SurfaceSerialHubDevices\n//\n// Created by Xavier on 2022/5/20.\n// Copyright © 2022 Xia Sha"
},
{
"path": "BigSurface/BigSurface/helpers.hpp",
"chars": 961,
"preview": "//\n// helpers.hpp\n// BigSurface\n//\n// Created by Xavier on 2023/2/7.\n// Copyright © 2023 Xia Shangning. All rights r"
},
{
"path": "BigSurface/BigSurface.xcodeproj/project.pbxproj",
"chars": 52011,
"preview": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 54;\n\tobjects = {\n\n/* Begin PBXBuildFile section *"
},
{
"path": "BigSurface/BigSurface.xcodeproj/project.pbxproj.orig",
"chars": 47888,
"preview": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 46;\n\tobjects = {\n\n/* Begin PBXBuildFile section *"
},
{
"path": "BigSurface/BigSurface.xcodeproj/project.xcworkspace/contents.xcworkspacedata",
"chars": 135,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n version = \"1.0\">\n <FileRef\n location = \"self:\">\n </FileRef"
},
{
"path": "BigSurface/BigSurface.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
"chars": 238,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "BigSurface/BigSurface.xcodeproj/xcshareddata/xcschemes/BigSurface.xcscheme",
"chars": 2389,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n LastUpgradeVersion = \"1420\"\n version = \"1.3\">\n <BuildAction\n "
},
{
"path": "BigSurface.xcworkspace/contents.xcworkspacedata",
"chars": 167,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n version = \"1.0\">\n <FileRef\n location = \"group:BigSurface/Big"
},
{
"path": "BigSurface.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
"chars": 238,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "BigSurface.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings",
"chars": 181,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "LICENSE.txt",
"chars": 32393,
"preview": "AL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <ht"
},
{
"path": "README.md",
"chars": 3594,
"preview": "# BigSurface\nThe name comes from macOS Big Sur.\nBig Sur + Surface -> Big Surface (LOL)\n\nPS : If you have a better name, "
}
]
About this extraction
This page contains the full source code of the Xiashangning/BigSurface GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 49 files (418.3 KB), approximately 121.8k tokens, and a symbol index with 268 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.