VirtualBox

source: vbox/trunk/src/VBox/Devices/PC/DrvACPI.cpp@ 27316

Last change on this file since 27316 was 27316, checked in by vboxsync, 15 years ago

Devices/ACPI: fixes for r58659

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 34.4 KB
Line 
1/* $Id: DrvACPI.cpp 27316 2010-03-12 09:49:51Z vboxsync $ */
2/** @file
3 * DrvACPI - ACPI Host Driver.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22/*******************************************************************************
23* Header Files *
24*******************************************************************************/
25#define LOG_GROUP LOG_GROUP_DRV_ACPI
26
27#ifdef RT_OS_WINDOWS
28# include <windows.h>
29#endif
30
31#include <VBox/pdmdrv.h>
32#include <VBox/log.h>
33#include <iprt/assert.h>
34#include <iprt/string.h>
35#include <iprt/uuid.h>
36
37#ifdef RT_OS_LINUX
38# include <iprt/critsect.h>
39# include <iprt/dir.h>
40# include <iprt/semaphore.h>
41# include <iprt/stream.h>
42#endif
43
44#ifdef RT_OS_DARWIN
45# include <Carbon/Carbon.h>
46# include <IOKit/ps/IOPowerSources.h>
47# include <IOKit/ps/IOPSKeys.h>
48#endif
49
50#ifdef RT_OS_FREEBSD
51# include <sys/ioctl.h>
52# include <dev/acpica/acpiio.h>
53# include <sys/types.h>
54# include <sys/sysctl.h>
55# include <stdio.h>
56# include <errno.h>
57# include <fcntl.h>
58# include <unistd.h>
59#endif
60
61#include "Builtins.h"
62
63
64/*******************************************************************************
65* Structures and Typedefs *
66*******************************************************************************/
67/**
68 * ACPI driver instance data.
69 *
70 * @implements PDMIACPICONNECTOR
71 */
72typedef struct DRVACPI
73{
74 /** The ACPI interface. */
75 PDMIACPICONNECTOR IACPIConnector;
76 /** The ACPI port interface. */
77 PPDMIACPIPORT pPort;
78 /** Pointer to the driver instance. */
79 PPDMDRVINS pDrvIns;
80
81#ifdef RT_OS_LINUX
82 /** The current power source. */
83 PDMACPIPOWERSOURCE enmPowerSource;
84 /** true = one or more batteries preset, false = no battery present. */
85 bool fBatteryPresent;
86 /** Remaining battery capacity. */
87 PDMACPIBATCAPACITY enmBatteryRemainingCapacity;
88 /** Battery state. */
89 PDMACPIBATSTATE enmBatteryState;
90 /** Preset battery charging/discharging rate. */
91 uint32_t u32BatteryPresentRate;
92 /** The poller thread. */
93 PPDMTHREAD pPollerThread;
94 /** Synchronize access to the above fields.
95 * XXX A spinlock is probaly cheaper ... */
96 RTCRITSECT CritSect;
97 /** Event semaphore the poller thread is sleeping on. */
98 RTSEMEVENT hPollerSleepEvent;
99#endif
100
101} DRVACPI, *PDRVACPI;
102
103
104/**
105 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
106 */
107static DECLCALLBACK(void *) drvACPIQueryInterface(PPDMIBASE pInterface, const char *pszIID)
108{
109 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
110 PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);
111
112 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
113 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIACPICONNECTOR, &pThis->IACPIConnector);
114 return NULL;
115}
116
117/**
118 * Get the current power source of the host system.
119 *
120 * @returns status code
121 * @param pInterface Pointer to the interface structure containing the called function pointer.
122 * @param pPowerSource Pointer to the power source result variable.
123 */
124static DECLCALLBACK(int) drvACPIQueryPowerSource(PPDMIACPICONNECTOR pInterface,
125 PDMACPIPOWERSOURCE *pPowerSource)
126{
127#if defined(RT_OS_WINDOWS)
128 SYSTEM_POWER_STATUS powerStatus;
129 if (GetSystemPowerStatus(&powerStatus))
130 {
131 /* running on battery? */
132 if ( powerStatus.ACLineStatus == 0 /* Offline */
133 || powerStatus.ACLineStatus == 255 /* Unknown */
134 && (powerStatus.BatteryFlag & 15) /* high | low | critical | charging */
135 ) /** @todo why is 'charging' included in the flag test? Add parenthesis around the right bits so the code is clearer. */
136 {
137 *pPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
138 }
139 /* running on AC link? */
140 else if (powerStatus.ACLineStatus == 1)
141 {
142 *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
143 }
144 else
145 /* what the hell we're running on? */
146 {
147 *pPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
148 }
149 }
150 else
151 {
152 AssertMsgFailed(("Could not determine system power status, error: 0x%x\n",
153 GetLastError()));
154 *pPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
155 }
156
157#elif defined (RT_OS_LINUX)
158 PDRVACPI pThis = RT_FROM_MEMBER(pInterface, DRVACPI, IACPIConnector);
159 RTCritSectEnter(&pThis->CritSect);
160 *pPowerSource = pThis->enmPowerSource;
161 RTCritSectLeave(&pThis->CritSect);
162
163#elif defined (RT_OS_DARWIN)
164 *pPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
165
166 CFTypeRef pBlob = IOPSCopyPowerSourcesInfo();
167 CFArrayRef pSources = IOPSCopyPowerSourcesList(pBlob);
168
169 CFDictionaryRef pSource = NULL;
170 const void *psValue;
171 bool fResult;
172
173 if (CFArrayGetCount(pSources) > 0)
174 {
175 for (int i = 0; i < CFArrayGetCount(pSources); ++i)
176 {
177 pSource = IOPSGetPowerSourceDescription(pBlob, CFArrayGetValueAtIndex(pSources, i));
178 /* If the source is empty skip over to the next one. */
179 if(!pSource)
180 continue;
181 /* Skip all power sources which are currently not present like a
182 * second battery. */
183 if (CFDictionaryGetValue(pSource, CFSTR(kIOPSIsPresentKey)) == kCFBooleanFalse)
184 continue;
185 /* Only internal power types are of interest. */
186 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTransportTypeKey), &psValue);
187 if ( fResult
188 && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSInternalType), 0) == kCFCompareEqualTo)
189 {
190 /* Check which power source we are connect on. */
191 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSPowerSourceStateKey), &psValue);
192 if ( fResult
193 && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSACPowerValue), 0) == kCFCompareEqualTo)
194 *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
195 else if ( fResult
196 && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSBatteryPowerValue), 0) == kCFCompareEqualTo)
197 *pPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
198 }
199 }
200 }
201 CFRelease(pBlob);
202 CFRelease(pSources);
203
204#elif defined(RT_OS_FREEBSD)
205 int fAcLine = 0;
206 size_t cbParameter = sizeof(fAcLine);
207
208 int rc = sysctlbyname("hw.acpi.acline", &fAcLine, &cbParameter, NULL, NULL);
209
210 if (!rc)
211 {
212 if (fAcLine == 1)
213 *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
214 else if (fAcLine == 0)
215 *pPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
216 else
217 *pPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
218 }
219 else
220 {
221 AssertMsg(errno == ENOENT, ("rc=%d (%s)\n", rc, strerror(errno)));
222 *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
223 }
224#else /* !RT_OS_FREEBSD either - what could this be? */
225 *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
226
227#endif /* !RT_OS_FREEBSD */
228 return VINF_SUCCESS;
229}
230
231/**
232 * @copydoc PDMIACPICONNECTOR::pfnQueryBatteryStatus
233 */
234static DECLCALLBACK(int) drvACPIQueryBatteryStatus(PPDMIACPICONNECTOR pInterface, bool *pfPresent,
235 PPDMACPIBATCAPACITY penmRemainingCapacity,
236 PPDMACPIBATSTATE penmBatteryState,
237 uint32_t *pu32PresentRate)
238{
239 /* default return values for all architectures */
240 *pfPresent = false; /* no battery present */
241 *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGED;
242 *penmRemainingCapacity = PDM_ACPI_BAT_CAPACITY_UNKNOWN;
243 *pu32PresentRate = ~0; /* present rate is unknown */
244
245#if defined(RT_OS_WINDOWS)
246 SYSTEM_POWER_STATUS powerStatus;
247 if (GetSystemPowerStatus(&powerStatus))
248 {
249 /* 128 means no battery present */
250 *pfPresent = !(powerStatus.BatteryFlag & 128);
251 /* just forward the value directly */
252 *penmRemainingCapacity = (PDMACPIBATCAPACITY)powerStatus.BatteryLifePercent;
253 /* we assume that we are discharging the battery if we are not on-line and
254 * not charge the battery */
255 uint32_t uBs = PDM_ACPI_BAT_STATE_CHARGED;
256 if (powerStatus.BatteryFlag & 8)
257 uBs = PDM_ACPI_BAT_STATE_CHARGING;
258 else if (powerStatus.ACLineStatus == 0 || powerStatus.ACLineStatus == 255)
259 uBs = PDM_ACPI_BAT_STATE_DISCHARGING;
260 if (powerStatus.BatteryFlag & 4)
261 uBs |= PDM_ACPI_BAT_STATE_CRITICAL;
262 *penmBatteryState = (PDMACPIBATSTATE)uBs;
263 /* on Windows it is difficult to request the present charging/discharging rate */
264 }
265 else
266 {
267 AssertMsgFailed(("Could not determine system power status, error: 0x%x\n",
268 GetLastError()));
269 }
270
271#elif defined(RT_OS_LINUX)
272 PDRVACPI pThis = RT_FROM_MEMBER(pInterface, DRVACPI, IACPIConnector);
273 RTCritSectEnter(&pThis->CritSect);
274 *pfPresent = pThis->fBatteryPresent;
275 *penmRemainingCapacity = pThis->enmBatteryRemainingCapacity;
276 *penmBatteryState = pThis->enmBatteryState;
277 *pu32PresentRate = pThis->u32BatteryPresentRate;
278 RTCritSectLeave(&pThis->CritSect);
279
280#elif defined(RT_OS_DARWIN)
281 CFTypeRef pBlob = IOPSCopyPowerSourcesInfo();
282 CFArrayRef pSources = IOPSCopyPowerSourcesList(pBlob);
283
284 CFDictionaryRef pSource = NULL;
285 const void *psValue;
286 bool fResult;
287
288 if (CFArrayGetCount(pSources) > 0)
289 {
290 for (int i = 0; i < CFArrayGetCount(pSources); ++i)
291 {
292 pSource = IOPSGetPowerSourceDescription(pBlob, CFArrayGetValueAtIndex(pSources, i));
293 /* If the source is empty skip over to the next one. */
294 if(!pSource)
295 continue;
296 /* Skip all power sources which are currently not present like a
297 * second battery. */
298 if (CFDictionaryGetValue(pSource, CFSTR(kIOPSIsPresentKey)) == kCFBooleanFalse)
299 continue;
300 /* Only internal power types are of interest. */
301 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTransportTypeKey), &psValue);
302 if ( fResult
303 && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSInternalType), 0) == kCFCompareEqualTo)
304 {
305 PDMACPIPOWERSOURCE powerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
306 /* First check which power source we are connect on. */
307 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSPowerSourceStateKey), &psValue);
308 if ( fResult
309 && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSACPowerValue), 0) == kCFCompareEqualTo)
310 powerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
311 else if ( fResult
312 && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSBatteryPowerValue), 0) == kCFCompareEqualTo)
313 powerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
314
315 /* At this point the power source is present. */
316 *pfPresent = true;
317 *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGED;
318
319 int curCapacity = 0;
320 int maxCapacity = 1;
321 float remCapacity = 0.0f;
322
323 /* Fetch the current capacity value of the power source */
324 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSCurrentCapacityKey), &psValue);
325 if (fResult)
326 CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
327 /* Fetch the maximum capacity value of the power source */
328 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSMaxCapacityKey), &psValue);
329 if (fResult)
330 CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
331
332 /* Calculate the remaining capacity in percent */
333 remCapacity = ((float)curCapacity/(float)maxCapacity * PDM_ACPI_BAT_CAPACITY_MAX);
334 *penmRemainingCapacity = (PDMACPIBATCAPACITY)remCapacity;
335
336 if (powerSource == PDM_ACPI_POWER_SOURCE_BATTERY)
337 {
338 /* If we are on battery power we are discharging in every
339 * case */
340 *penmBatteryState = PDM_ACPI_BAT_STATE_DISCHARGING;
341 int timeToEmpty = -1;
342 /* Get the time till the battery source will be empty */
343 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTimeToEmptyKey), &psValue);
344 if (fResult)
345 CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &timeToEmpty);
346 if (timeToEmpty != -1)
347 /* 0...1000 */
348 *pu32PresentRate = (uint32_t)roundf((remCapacity / ((float)timeToEmpty/60.0)) * 10.0);
349 }
350
351 if ( powerSource == PDM_ACPI_POWER_SOURCE_OUTLET
352 && CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSIsChargingKey), &psValue))
353 {
354 /* We are running on an AC power source, but we also have a
355 * battery power source present. */
356 if (CFBooleanGetValue((CFBooleanRef)psValue) > 0)
357 {
358 /* This means charging. */
359 *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGING;
360 int timeToFull = -1;
361 /* Get the time till the battery source will be charged */
362 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTimeToFullChargeKey), &psValue);
363 if (fResult)
364 CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &timeToFull);
365 if (timeToFull != -1)
366 /* 0...1000 */
367 *pu32PresentRate = (uint32_t)roundf((100.0-(float)remCapacity) / ((float)timeToFull/60.0)) * 10.0;
368 }
369 }
370
371 /* Check for critical */
372 int criticalValue = 20;
373 fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSDeadWarnLevelKey), &psValue);
374 if (fResult)
375 CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &criticalValue);
376 if (remCapacity < criticalValue)
377 *penmBatteryState = (PDMACPIBATSTATE)(*penmBatteryState | PDM_ACPI_BAT_STATE_CRITICAL);
378 }
379 }
380 }
381 CFRelease(pBlob);
382 CFRelease(pSources);
383
384#elif defined(RT_OS_FREEBSD)
385 /* We try to use /dev/acpi first and if that fails use the sysctls. */
386 bool fSuccess = true;
387 int FileAcpi = 0;
388 int rc = 0;
389
390 FileAcpi = open("/dev/acpi", O_RDONLY);
391 if (FileAcpi != -1)
392 {
393 bool fMilliWatt;
394 union acpi_battery_ioctl_arg BatteryIo;
395
396 memset(&BatteryIo, 0, sizeof(BatteryIo));
397 BatteryIo.unit = 0; /* Always use the first battery. */
398
399 /* Determine the power units first. */
400 if (ioctl(FileAcpi, ACPIIO_BATT_GET_BIF, &BatteryIo) == -1)
401 fSuccess = false;
402 else
403 {
404 if (BatteryIo.bif.units == ACPI_BIF_UNITS_MW)
405 fMilliWatt = true;
406 else
407 fMilliWatt = false; /* mA */
408
409 BatteryIo.unit = 0;
410 if (ioctl(FileAcpi, ACPIIO_BATT_GET_BATTINFO, &BatteryIo) == -1)
411 fSuccess = false;
412 else
413 {
414 if ((BatteryIo.battinfo.state & ACPI_BATT_STAT_NOT_PRESENT) == ACPI_BATT_STAT_NOT_PRESENT)
415 *pfPresent = false;
416 else
417 {
418 *pfPresent = true;
419
420 if (BatteryIo.battinfo.state & ACPI_BATT_STAT_DISCHARG)
421 *penmBatteryState = PDM_ACPI_BAT_STATE_DISCHARGING;
422 else if (BatteryIo.battinfo.state & ACPI_BATT_STAT_CHARGING)
423 *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGING;
424 else
425 *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGED;
426
427 if (BatteryIo.battinfo.state & ACPI_BATT_STAT_CRITICAL)
428 *penmBatteryState = (PDMACPIBATSTATE)(*penmBatteryState | PDM_ACPI_BAT_STATE_CRITICAL);
429 }
430
431 if (BatteryIo.battinfo.cap != -1)
432 *penmRemainingCapacity = (PDMACPIBATCAPACITY)BatteryIo.battinfo.cap;
433
434 BatteryIo.unit = 0;
435 if (ioctl(FileAcpi, ACPIIO_BATT_GET_BST, &BatteryIo) == 0)
436 {
437 /* The rate can be either mW or mA but the ACPI device wants mW. */
438 if (BatteryIo.bst.rate != 0xffffffff)
439 {
440 if (fMilliWatt)
441 *pu32PresentRate = BatteryIo.bst.rate;
442 else if (BatteryIo.bst.volt != 0xffffffff)
443 {
444 /*
445 * The rate is in mA so we have to convert it.
446 * The current power rate can be calculated with P = U * I
447 */
448 *pu32PresentRate = (uint32_t)( ( ((float)BatteryIo.bst.volt/1000.0)
449 * ((float)BatteryIo.bst.rate/1000.0))
450 * 1000.0);
451 }
452 }
453 }
454 }
455 }
456
457 close(FileAcpi);
458 }
459 else
460 fSuccess = false;
461
462 if (!fSuccess)
463 {
464 int fBatteryState = 0;
465 size_t cbParameter = sizeof(fBatteryState);
466
467 rc = sysctlbyname("hw.acpi.battery.state", &fBatteryState, &cbParameter, NULL, NULL);
468 if (!rc)
469 {
470 if ((fBatteryState & ACPI_BATT_STAT_NOT_PRESENT) == ACPI_BATT_STAT_NOT_PRESENT)
471 *pfPresent = false;
472 else
473 {
474 *pfPresent = true;
475
476 if (fBatteryState & ACPI_BATT_STAT_DISCHARG)
477 *penmBatteryState = PDM_ACPI_BAT_STATE_DISCHARGING;
478 else if (fBatteryState & ACPI_BATT_STAT_CHARGING)
479 *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGING;
480 else
481 *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGED;
482
483 if (fBatteryState & ACPI_BATT_STAT_CRITICAL)
484 *penmBatteryState = (PDMACPIBATSTATE)(*penmBatteryState | PDM_ACPI_BAT_STATE_CRITICAL);
485
486 /* Get battery level. */
487 int curCapacity = 0;
488 cbParameter = sizeof(curCapacity);
489 rc = sysctlbyname("hw.acpi.battery.life", &curCapacity, &cbParameter, NULL, NULL);
490 if (!rc && curCapacity >= 0)
491 *penmRemainingCapacity = (PDMACPIBATCAPACITY)curCapacity;
492
493 /* The rate can't be determined with sysctls. */
494 }
495 }
496 }
497
498#endif /* RT_OS_FREEBSD */
499
500 return VINF_SUCCESS;
501}
502
503#ifdef RT_OS_LINUX
504/**
505 * Poller thread for /proc/acpi status files.
506 *
507 * Reading these files takes ages (several seconds) on some hosts, therefore
508 * start this thread. The termination of this thread may take some seconds
509 * on such a hosts!
510 *
511 * @param pDrvIns The driver instance data.
512 * @param pThread The thread.
513 */
514static DECLCALLBACK(int) drvACPIPoller(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
515{
516 PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);
517
518 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
519 return VINF_SUCCESS;
520
521 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
522 {
523 /*
524 * Read the status of the powerline-adapter.
525 */
526
527 PDMACPIPOWERSOURCE enmPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
528 PRTSTREAM pStrmStatus;
529 PRTDIR pDir = NULL;
530 RTDIRENTRY DirEntry;
531 char szLine[1024];
532 int rc = RTDirOpen(&pDir, "/proc/acpi/ac_adapter/");
533 if (RT_SUCCESS(rc))
534 {
535 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
536 {
537 rc = RTDirRead(pDir, &DirEntry, NULL);
538 if (RT_FAILURE(rc))
539 break;
540 if ( strcmp(DirEntry.szName, ".") == 0
541 || strcmp(DirEntry.szName, "..") == 0)
542 continue;
543 rc = RTStrmOpenF("r", &pStrmStatus,
544 "/proc/acpi/ac_adapter/%s/status", DirEntry.szName);
545 if (RT_FAILURE(rc))
546 rc = RTStrmOpenF("r", &pStrmStatus,
547 "/proc/acpi/ac_adapter/%s/state", DirEntry.szName);
548 if (RT_SUCCESS(rc))
549 {
550 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
551 {
552 rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
553 if (RT_FAILURE(rc))
554 break;
555 if ( strstr(szLine, "Status:") != NULL
556 || strstr(szLine, "state:") != NULL)
557 {
558 if (strstr(szLine, "on-line") != NULL)
559 enmPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
560 else
561 enmPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
562 break;
563 }
564 }
565 RTStrmClose(pStrmStatus);
566 break;
567 }
568 }
569 RTDirClose(pDir);
570 }
571
572 /*
573 * Read the status of all batteries and collect it into one.
574 */
575
576 int32_t maxCapacityTotal = INT32_MIN; /* the summed up maximum capacity */
577 int32_t currentCapacityTotal = INT32_MIN; /* the summed up total capacity */
578 int32_t presentRate = 0;
579 int32_t presentRateTotal = 0;
580 bool fBatteryPresent = false;
581 bool fCharging = false;
582 bool fDischarging = false;
583 bool fCritical = false;
584
585 rc = RTDirOpen(&pDir, "/proc/acpi/battery/");
586 if (RT_SUCCESS(rc))
587 {
588 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
589 {
590 rc = RTDirRead(pDir, &DirEntry, NULL);
591 if (RT_FAILURE(rc))
592 break;
593 if ( strcmp(DirEntry.szName, ".") == 0
594 || strcmp(DirEntry.szName, "..") == 0)
595 continue;
596
597 pStrmStatus;
598 rc = RTStrmOpenF("r", &pStrmStatus,
599 "/proc/acpi/battery/%s/status", DirEntry.szName);
600 /* there is a 2nd variant of that file */
601 if (RT_FAILURE(rc))
602 {
603 rc = RTStrmOpenF("r", &pStrmStatus,
604 "/proc/acpi/battery/%s/state", DirEntry.szName);
605 }
606 if (RT_FAILURE(rc))
607 continue;
608
609 PRTSTREAM pStrmInfo;
610 rc = RTStrmOpenF("r", &pStrmInfo,
611 "/proc/acpi/battery/%s/info", DirEntry.szName);
612 if (RT_FAILURE(rc))
613 {
614 RTStrmClose(pStrmStatus);
615 continue;
616 }
617
618 /* get 'present' status from the info file */
619 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
620 {
621 rc = RTStrmGetLine(pStrmInfo, szLine, sizeof(szLine));
622 if (RT_FAILURE(rc))
623 break;
624 if (strstr(szLine, "present:") != NULL)
625 {
626 if (strstr(szLine, "yes") != NULL)
627 {
628 fBatteryPresent = true;
629 break;
630 }
631 }
632 }
633
634 RTStrmRewind(pStrmInfo);
635 if (fBatteryPresent)
636 {
637 /* get the maximum capacity from the info file */
638 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
639 {
640 int32_t maxCapacity = INT32_MIN;
641 rc = RTStrmGetLine(pStrmInfo, szLine, sizeof(szLine));
642 if (RT_FAILURE(rc))
643 break;
644 if (strstr(szLine, "last full capacity:") != NULL)
645 {
646 char *psz;
647 rc = RTStrToInt32Ex(RTStrStripL(&szLine[19]), &psz, 0, &maxCapacity);
648 if (RT_FAILURE(rc))
649 maxCapacity = INT32_MIN;
650
651 /* did we get a valid capacity and it's the first value we got? */
652 if (maxCapacityTotal < 0 && maxCapacity > 0)
653 {
654 /* take this as the maximum capacity */
655 maxCapacityTotal = maxCapacity;
656 }
657 else
658 {
659 /* sum up the maximum capacity */
660 if (maxCapacityTotal > 0 && maxCapacity > 0)
661 maxCapacityTotal += maxCapacity;
662 }
663 /* we got all we need */
664 break;
665 }
666 }
667
668 /* get the current capacity/state from the status file */
669 bool fGotRemainingCapacity = false;
670 bool fGotBatteryState = false;
671 bool fGotCapacityState = false;
672 bool fGotPresentRate = false;
673 while ( ( !fGotRemainingCapacity
674 || !fGotBatteryState
675 || !fGotCapacityState
676 || !fGotPresentRate)
677 && pThread->enmState == PDMTHREADSTATE_RUNNING)
678 {
679 int32_t currentCapacity = INT32_MIN;
680 rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
681 if (RT_FAILURE(rc))
682 break;
683 if (strstr(szLine, "remaining capacity:") != NULL)
684 {
685 char *psz;
686 rc = RTStrToInt32Ex(RTStrStripL(&szLine[19]), &psz, 0, &currentCapacity);
687 if (RT_FAILURE(rc))
688 currentCapacity = INT32_MIN;
689
690 /* is this the first valid value we see? If so, take it! */
691 if (currentCapacityTotal < 0 && currentCapacity >= 0)
692 {
693 currentCapacityTotal = currentCapacity;
694 }
695 else
696 {
697 /* just sum up the current value */
698 if (currentCapacityTotal > 0 && currentCapacity > 0)
699 currentCapacityTotal += currentCapacity;
700 }
701 fGotRemainingCapacity = true;
702 }
703 else if (strstr(szLine, "charging state:") != NULL)
704 {
705 if (strstr(szLine + 15, "discharging") != NULL)
706 fDischarging = true;
707 else if (strstr(szLine + 15, "charging") != NULL)
708 fCharging = true;
709 fGotBatteryState = true;
710 }
711 else if (strstr(szLine, "capacity state:") != NULL)
712 {
713 if (strstr(szLine + 15, "critical") != NULL)
714 fCritical = true;
715 fGotCapacityState = true;
716 }
717 if (strstr(szLine, "present rate:") != NULL)
718 {
719 char *psz;
720 rc = RTStrToInt32Ex(RTStrStripL(&szLine[13]), &psz, 0, &presentRate);
721 if (RT_FAILURE(rc))
722 presentRate = 0;
723 fGotPresentRate = true;
724 }
725 }
726 }
727
728 if (presentRate)
729 {
730 if (fDischarging)
731 presentRateTotal -= presentRate;
732 else
733 presentRateTotal += presentRate;
734 }
735
736 RTStrmClose(pStrmStatus);
737 RTStrmClose(pStrmInfo);
738 }
739 RTDirClose(pDir);
740 }
741
742 /* atomic update of the state */
743 RTCritSectEnter(&pThis->CritSect);
744 pThis->enmPowerSource = enmPowerSource;
745 pThis->fBatteryPresent = fBatteryPresent;
746
747 /* charging/discharging bits are mutual exclusive */
748 uint32_t uBs = PDM_ACPI_BAT_STATE_CHARGED;
749 if (fDischarging)
750 uBs = PDM_ACPI_BAT_STATE_DISCHARGING;
751 else if (fCharging)
752 uBs = PDM_ACPI_BAT_STATE_CHARGING;
753 if (fCritical)
754 uBs |= PDM_ACPI_BAT_STATE_CRITICAL;
755 pThis->enmBatteryState = (PDMACPIBATSTATE)uBs;
756
757 if (maxCapacityTotal > 0 && currentCapacityTotal > 0)
758 {
759 if (presentRateTotal < 0)
760 presentRateTotal = -presentRateTotal;
761
762 /* calculate the percentage */
763 pThis->enmBatteryRemainingCapacity =
764 (PDMACPIBATCAPACITY)( ( (float)currentCapacityTotal
765 / (float)maxCapacityTotal)
766 * PDM_ACPI_BAT_CAPACITY_MAX);
767 pThis->u32BatteryPresentRate =
768 (uint32_t)(( (float)presentRateTotal
769 / (float)maxCapacityTotal) * 1000);
770 }
771 RTCritSectLeave(&pThis->CritSect);
772
773 /* wait a bit (e.g. Ubuntu/GNOME polls every 30 seconds) */
774 rc = RTSemEventWait(pThis->hPollerSleepEvent, 20000);
775 }
776
777 return VINF_SUCCESS;
778}
779
780static DECLCALLBACK(int) drvACPIPollerWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
781{
782 PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);
783
784 RTSemEventSignal(pThis->hPollerSleepEvent);
785 RTThreadPoke(pThread->Thread);
786 return VINF_SUCCESS;
787}
788#endif /* RT_OS_LINUX */
789
790
791/**
792 * Destruct a driver instance.
793 *
794 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
795 * resources can be freed correctly.
796 *
797 * @param pDrvIns The driver instance data.
798 */
799static DECLCALLBACK(void) drvACPIDestruct(PPDMDRVINS pDrvIns)
800{
801 PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);
802
803 LogFlow(("drvACPIDestruct\n"));
804 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
805
806#ifdef RT_OS_LINUX
807 RTSemEventDestroy(pThis->hPollerSleepEvent);
808 pThis->hPollerSleepEvent = NIL_RTSEMEVENT;
809 RTCritSectDelete(&pThis->CritSect);
810#endif
811}
812
813/**
814 * Construct an ACPI driver instance.
815 *
816 * @copydoc FNPDMDRVCONSTRUCT
817 */
818static DECLCALLBACK(int) drvACPIConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
819{
820 PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);
821 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
822 int rc = VINF_SUCCESS;
823
824 /*
825 * Init the static parts.
826 */
827 pThis->pDrvIns = pDrvIns;
828 /* IBase */
829 pDrvIns->IBase.pfnQueryInterface = drvACPIQueryInterface;
830 /* IACPIConnector */
831 pThis->IACPIConnector.pfnQueryPowerSource = drvACPIQueryPowerSource;
832 pThis->IACPIConnector.pfnQueryBatteryStatus = drvACPIQueryBatteryStatus;
833
834 /*
835 * Validate the config.
836 */
837 if (!CFGMR3AreValuesValid(pCfg, "\0"))
838 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
839
840 /*
841 * Check that no-one is attached to us.
842 */
843 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
844 ("Configuration error: Not possible to attach anything to this driver!\n"),
845 VERR_PDM_DRVINS_NO_ATTACH);
846
847 /*
848 * Query the ACPI port interface.
849 */
850 pThis->pPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIACPIPORT);
851 if (!pThis->pPort)
852 {
853 AssertMsgFailed(("Configuration error: the above device/driver didn't export the ACPI port interface!\n"));
854 return VERR_PDM_MISSING_INTERFACE_ABOVE;
855 }
856
857#ifdef RT_OS_LINUX
858 /*
859 * Start the poller thread.
860 */
861 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pThis->pPollerThread, pThis, drvACPIPoller,
862 drvACPIPollerWakeup, 0, RTTHREADTYPE_INFREQUENT_POLLER, "ACPI Poller");
863 if (RT_FAILURE(rc))
864 return rc;
865
866 rc = RTCritSectInit(&pThis->CritSect);
867 if (RT_FAILURE(rc))
868 return rc;
869
870 rc = RTSemEventCreate(&pThis->hPollerSleepEvent);
871#endif
872
873 return rc;
874}
875
876
877/**
878 * ACPI driver registration record.
879 */
880const PDMDRVREG g_DrvACPI =
881{
882 /* u32Version */
883 PDM_DRVREG_VERSION,
884 /* szName */
885 "ACPIHost",
886 /* szRCMod */
887 "",
888 /* szR0Mod */
889 "",
890 /* pszDescription */
891 "ACPI Host Driver",
892 /* fFlags */
893 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
894 /* fClass. */
895 PDM_DRVREG_CLASS_ACPI,
896 /* cMaxInstances */
897 ~0,
898 /* cbInstance */
899 sizeof(DRVACPI),
900 /* pfnConstruct */
901 drvACPIConstruct,
902 /* pfnDestruct */
903 drvACPIDestruct,
904 /* pfnRelocate */
905 NULL,
906 /* pfnIOCtl */
907 NULL,
908 /* pfnPowerOn */
909 NULL,
910 /* pfnReset */
911 NULL,
912 /* pfnSuspend */
913 NULL,
914 /* pfnResume */
915 NULL,
916 /* pfnAttach */
917 NULL,
918 /* pfnDetach */
919 NULL,
920 /* pfnPowerOff */
921 NULL,
922 /* pfnSoftReset */
923 NULL,
924 /* u32EndVersion */
925 PDM_DRVREG_VERSION
926};
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette