forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGonkHal.cpp
2016 lines (1690 loc) · 56 KB
/
GonkHal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et ft=cpp : */
/* Copyright 2012 Mozilla Foundation and Mozilla contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/android_alarm.h>
#include <math.h>
#include <regex.h>
#include <sched.h>
#include <stdio.h>
#include <sys/klog.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/resource.h>
#include <time.h>
#include <unistd.h>
#include "mozilla/DebugOnly.h"
#include "android/log.h"
#include "cutils/properties.h"
#include "hardware/hardware.h"
#include "hardware/lights.h"
#include "hardware_legacy/uevent.h"
#include "hardware_legacy/vibrator.h"
#include "hardware_legacy/power.h"
#include "libdisplay/GonkDisplay.h"
#include "utils/threads.h"
#include "base/message_loop.h"
#include "Hal.h"
#include "HalImpl.h"
#include "HalLog.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/dom/battery/Constants.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/FileUtils.h"
#include "mozilla/Monitor.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/Preferences.h"
#include "nsAlgorithm.h"
#include "nsPrintfCString.h"
#include "nsIObserver.h"
#include "nsIObserverService.h"
#include "nsIRecoveryService.h"
#include "nsIRunnable.h"
#include "nsScreenManagerGonk.h"
#include "nsThreadUtils.h"
#include "nsThreadUtils.h"
#include "nsIThread.h"
#include "nsXULAppAPI.h"
#include "OrientationObserver.h"
#include "UeventPoller.h"
#include "nsIWritablePropertyBag2.h"
#include <algorithm>
#define NsecPerMsec 1000000LL
#define NsecPerSec 1000000000
// The header linux/oom.h is not available in bionic libc. We
// redefine some of its constants here.
#ifndef OOM_DISABLE
#define OOM_DISABLE (-17)
#endif
#ifndef OOM_ADJUST_MIN
#define OOM_ADJUST_MIN (-16)
#endif
#ifndef OOM_ADJUST_MAX
#define OOM_ADJUST_MAX 15
#endif
#ifndef OOM_SCORE_ADJ_MIN
#define OOM_SCORE_ADJ_MIN (-1000)
#endif
#ifndef OOM_SCORE_ADJ_MAX
#define OOM_SCORE_ADJ_MAX 1000
#endif
#ifndef BATTERY_CHARGING_ARGB
#define BATTERY_CHARGING_ARGB 0x00FF0000
#endif
#ifndef BATTERY_FULL_ARGB
#define BATTERY_FULL_ARGB 0x0000FF00
#endif
using namespace mozilla;
using namespace mozilla::hal;
using namespace mozilla::dom;
namespace mozilla {
namespace hal_impl {
/**
* These are defined by libhardware, specifically, hardware/libhardware/include/hardware/lights.h
* in the gonk subsystem.
* If these change and are exposed to JS, make sure nsIHal.idl is updated as well.
*/
enum LightType {
eHalLightID_Backlight = 0,
eHalLightID_Keyboard = 1,
eHalLightID_Buttons = 2,
eHalLightID_Battery = 3,
eHalLightID_Notifications = 4,
eHalLightID_Attention = 5,
eHalLightID_Bluetooth = 6,
eHalLightID_Wifi = 7,
eHalLightID_Count // This should stay at the end
};
enum LightMode {
eHalLightMode_User = 0, // brightness is managed by user setting
eHalLightMode_Sensor = 1, // brightness is managed by a light sensor
eHalLightMode_Count
};
enum FlashMode {
eHalLightFlash_None = 0,
eHalLightFlash_Timed = 1, // timed flashing. Use flashOnMS and flashOffMS for timing
eHalLightFlash_Hardware = 2, // hardware assisted flashing
eHalLightFlash_Count
};
struct LightConfiguration {
LightType light;
LightMode mode;
FlashMode flash;
uint32_t flashOnMS;
uint32_t flashOffMS;
uint32_t color;
};
static light_device_t* sLights[eHalLightID_Count]; // will be initialized to nullptr
static light_device_t*
GetDevice(hw_module_t* module, char const* name)
{
int err;
hw_device_t* device;
err = module->methods->open(module, name, &device);
if (err == 0) {
return (light_device_t*)device;
} else {
return nullptr;
}
}
static void
InitLights()
{
// assume that if backlight is nullptr, nothing has been set yet
// if this is not true, the initialization will occur everytime a light is read or set!
if (!sLights[eHalLightID_Backlight]) {
int err;
hw_module_t* module;
err = hw_get_module(LIGHTS_HARDWARE_MODULE_ID, (hw_module_t const**)&module);
if (err == 0) {
sLights[eHalLightID_Backlight]
= GetDevice(module, LIGHT_ID_BACKLIGHT);
sLights[eHalLightID_Keyboard]
= GetDevice(module, LIGHT_ID_KEYBOARD);
sLights[eHalLightID_Buttons]
= GetDevice(module, LIGHT_ID_BUTTONS);
sLights[eHalLightID_Battery]
= GetDevice(module, LIGHT_ID_BATTERY);
sLights[eHalLightID_Notifications]
= GetDevice(module, LIGHT_ID_NOTIFICATIONS);
sLights[eHalLightID_Attention]
= GetDevice(module, LIGHT_ID_ATTENTION);
sLights[eHalLightID_Bluetooth]
= GetDevice(module, LIGHT_ID_BLUETOOTH);
sLights[eHalLightID_Wifi]
= GetDevice(module, LIGHT_ID_WIFI);
}
}
}
/**
* The state last set for the lights until liblights supports
* getting the light state.
*/
static light_state_t sStoredLightState[eHalLightID_Count];
/**
* Set the value of a light to a particular color, with a specific flash pattern.
* light specifices which light. See Hal.idl for the list of constants
* mode specifies user set or based on ambient light sensor
* flash specifies whether or how to flash the light
* flashOnMS and flashOffMS specify the pattern for XXX flash mode
* color specifies the color. If the light doesn't support color, the given color is
* transformed into a brightness, or just an on/off if that is all the light is capable of.
* returns true if successful and false if failed.
*/
static bool
SetLight(LightType light, const LightConfiguration& aConfig)
{
light_state_t state;
InitLights();
if (light < 0 || light >= eHalLightID_Count ||
sLights[light] == nullptr) {
return false;
}
memset(&state, 0, sizeof(light_state_t));
state.color = aConfig.color;
state.flashMode = aConfig.flash;
state.flashOnMS = aConfig.flashOnMS;
state.flashOffMS = aConfig.flashOffMS;
state.brightnessMode = aConfig.mode;
sLights[light]->set_light(sLights[light], &state);
sStoredLightState[light] = state;
return true;
}
/**
* GET the value of a light returning a particular color, with a specific flash pattern.
* returns true if successful and false if failed.
*/
static bool
GetLight(LightType light, LightConfiguration* aConfig)
{
light_state_t state;
if (light < 0 || light >= eHalLightID_Count ||
sLights[light] == nullptr) {
return false;
}
memset(&state, 0, sizeof(light_state_t));
state = sStoredLightState[light];
aConfig->light = light;
aConfig->color = state.color;
aConfig->flash = FlashMode(state.flashMode);
aConfig->flashOnMS = state.flashOnMS;
aConfig->flashOffMS = state.flashOffMS;
aConfig->mode = LightMode(state.brightnessMode);
return true;
}
namespace {
/**
* This runnable runs for the lifetime of the program, once started. It's
* responsible for "playing" vibration patterns.
*/
class VibratorRunnable final
: public nsIRunnable
, public nsIObserver
{
public:
VibratorRunnable()
: mMonitor("VibratorRunnable")
, mIndex(0)
{
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
if (!os) {
NS_WARNING("Could not get observer service!");
return;
}
os->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
}
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIRUNNABLE
NS_DECL_NSIOBSERVER
// Run on the main thread, not the vibrator thread.
void Vibrate(const nsTArray<uint32_t> &pattern);
void CancelVibrate();
static bool ShuttingDown() { return sShuttingDown; }
protected:
~VibratorRunnable() {}
private:
Monitor mMonitor;
// The currently-playing pattern.
nsTArray<uint32_t> mPattern;
// The index we're at in the currently-playing pattern. If mIndex >=
// mPattern.Length(), then we're not currently playing anything.
uint32_t mIndex;
// Set to true in our shutdown observer. When this is true, we kill the
// vibrator thread.
static bool sShuttingDown;
};
NS_IMPL_ISUPPORTS(VibratorRunnable, nsIRunnable, nsIObserver);
bool VibratorRunnable::sShuttingDown = false;
static StaticRefPtr<VibratorRunnable> sVibratorRunnable;
NS_IMETHODIMP
VibratorRunnable::Run()
{
MonitorAutoLock lock(mMonitor);
// We currently assume that mMonitor.Wait(X) waits for X milliseconds. But in
// reality, the kernel might not switch to this thread for some time after the
// wait expires. So there's potential for some inaccuracy here.
//
// This doesn't worry me too much. Note that we don't even start vibrating
// immediately when VibratorRunnable::Vibrate is called -- we go through a
// condvar onto another thread. Better just to be chill about small errors in
// the timing here.
while (!sShuttingDown) {
if (mIndex < mPattern.Length()) {
uint32_t duration = mPattern[mIndex];
if (mIndex % 2 == 0) {
vibrator_on(duration);
}
mIndex++;
mMonitor.Wait(PR_MillisecondsToInterval(duration));
}
else {
mMonitor.Wait();
}
}
sVibratorRunnable = nullptr;
return NS_OK;
}
NS_IMETHODIMP
VibratorRunnable::Observe(nsISupports *subject, const char *topic,
const char16_t *data)
{
MOZ_ASSERT(strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0);
MonitorAutoLock lock(mMonitor);
sShuttingDown = true;
mMonitor.Notify();
return NS_OK;
}
void
VibratorRunnable::Vibrate(const nsTArray<uint32_t> &pattern)
{
MonitorAutoLock lock(mMonitor);
mPattern = pattern;
mIndex = 0;
mMonitor.Notify();
}
void
VibratorRunnable::CancelVibrate()
{
MonitorAutoLock lock(mMonitor);
mPattern.Clear();
mPattern.AppendElement(0);
mIndex = 0;
mMonitor.Notify();
}
void
EnsureVibratorThreadInitialized()
{
if (sVibratorRunnable) {
return;
}
sVibratorRunnable = new VibratorRunnable();
nsCOMPtr<nsIThread> thread;
NS_NewThread(getter_AddRefs(thread), sVibratorRunnable);
}
} // anonymous namespace
void
Vibrate(const nsTArray<uint32_t> &pattern, const hal::WindowIdentifier &)
{
MOZ_ASSERT(NS_IsMainThread());
if (VibratorRunnable::ShuttingDown()) {
return;
}
EnsureVibratorThreadInitialized();
sVibratorRunnable->Vibrate(pattern);
}
void
CancelVibrate(const hal::WindowIdentifier &)
{
MOZ_ASSERT(NS_IsMainThread());
if (VibratorRunnable::ShuttingDown()) {
return;
}
EnsureVibratorThreadInitialized();
sVibratorRunnable->CancelVibrate();
}
namespace {
class BatteryUpdater : public nsRunnable {
public:
NS_IMETHOD Run()
{
hal::BatteryInformation info;
hal_impl::GetCurrentBatteryInformation(&info);
// Control the battery indicator (led light) here using BatteryInformation
// we just retrieved.
uint32_t color = 0; // Format: 0x00rrggbb.
if (info.charging() && (info.level() == 1)) {
// Charging and battery full.
color = BATTERY_FULL_ARGB;
} else if (info.charging() && (info.level() < 1)) {
// Charging but not full.
color = BATTERY_CHARGING_ARGB;
} // else turn off battery indicator.
LightConfiguration aConfig;
aConfig.light = eHalLightID_Battery;
aConfig.mode = eHalLightMode_User;
aConfig.flash = eHalLightFlash_None;
aConfig.flashOnMS = aConfig.flashOffMS = 0;
aConfig.color = color;
SetLight(eHalLightID_Battery, aConfig);
hal::NotifyBatteryChange(info);
{
// bug 975667
// Gecko gonk hal is required to emit battery charging/level notification via nsIObserverService.
// This is useful for XPCOM components that are not statically linked to Gecko and cannot call
// hal::EnableBatteryNotifications
nsCOMPtr<nsIObserverService> obsService = mozilla::services::GetObserverService();
nsCOMPtr<nsIWritablePropertyBag2> propbag =
do_CreateInstance("@mozilla.org/hash-property-bag;1");
if (obsService && propbag) {
propbag->SetPropertyAsBool(NS_LITERAL_STRING("charging"),
info.charging());
propbag->SetPropertyAsDouble(NS_LITERAL_STRING("level"),
info.level());
obsService->NotifyObservers(propbag, "gonkhal-battery-notifier", nullptr);
}
}
return NS_OK;
}
};
} // anonymous namespace
class BatteryObserver final : public IUeventObserver
{
public:
NS_INLINE_DECL_REFCOUNTING(BatteryObserver)
BatteryObserver()
:mUpdater(new BatteryUpdater())
{
}
virtual void Notify(const NetlinkEvent &aEvent)
{
// this will run on IO thread
NetlinkEvent *event = const_cast<NetlinkEvent*>(&aEvent);
const char *subsystem = event->getSubsystem();
// e.g. DEVPATH=/devices/platform/sec-battery/power_supply/battery
const char *devpath = event->findParam("DEVPATH");
if (strcmp(subsystem, "power_supply") == 0 &&
strstr(devpath, "battery")) {
// aEvent will be valid only in this method.
NS_DispatchToMainThread(mUpdater);
}
}
protected:
~BatteryObserver() {}
private:
nsRefPtr<BatteryUpdater> mUpdater;
};
// sBatteryObserver is owned by the IO thread. Only the IO thread may
// create or destroy it.
static StaticRefPtr<BatteryObserver> sBatteryObserver;
static void
RegisterBatteryObserverIOThread()
{
MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
MOZ_ASSERT(!sBatteryObserver);
sBatteryObserver = new BatteryObserver();
RegisterUeventListener(sBatteryObserver);
}
void
EnableBatteryNotifications()
{
XRE_GetIOMessageLoop()->PostTask(
FROM_HERE,
NewRunnableFunction(RegisterBatteryObserverIOThread));
}
static void
UnregisterBatteryObserverIOThread()
{
MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
MOZ_ASSERT(sBatteryObserver);
UnregisterUeventListener(sBatteryObserver);
sBatteryObserver = nullptr;
}
void
DisableBatteryNotifications()
{
XRE_GetIOMessageLoop()->PostTask(
FROM_HERE,
NewRunnableFunction(UnregisterBatteryObserverIOThread));
}
static bool
GetCurrentBatteryCharge(int* aCharge)
{
bool success = ReadSysFile("/sys/class/power_supply/battery/capacity",
aCharge);
if (!success) {
return false;
}
#ifdef DEBUG
if ((*aCharge < 0) || (*aCharge > 100)) {
HAL_LOG("charge level contains unknown value: %d", *aCharge);
}
#endif
return (*aCharge >= 0) && (*aCharge <= 100);
}
static bool
GetCurrentBatteryCharging(int* aCharging)
{
static const DebugOnly<int> BATTERY_NOT_CHARGING = 0;
static const int BATTERY_CHARGING_USB = 1;
static const int BATTERY_CHARGING_AC = 2;
// Generic device support
int chargingSrc;
bool success =
ReadSysFile("/sys/class/power_supply/battery/charging_source", &chargingSrc);
if (success) {
#ifdef DEBUG
if (chargingSrc != BATTERY_NOT_CHARGING &&
chargingSrc != BATTERY_CHARGING_USB &&
chargingSrc != BATTERY_CHARGING_AC) {
HAL_LOG("charging_source contained unknown value: %d", chargingSrc);
}
#endif
*aCharging = (chargingSrc == BATTERY_CHARGING_USB ||
chargingSrc == BATTERY_CHARGING_AC);
return true;
}
// Otoro device support
char chargingSrcString[16];
success = ReadSysFile("/sys/class/power_supply/battery/status",
chargingSrcString, sizeof(chargingSrcString));
if (success) {
*aCharging = strcmp(chargingSrcString, "Charging") == 0 ||
strcmp(chargingSrcString, "Full") == 0;
return true;
}
return false;
}
void
GetCurrentBatteryInformation(hal::BatteryInformation* aBatteryInfo)
{
int charge;
static bool previousCharging = false;
static double previousLevel = 0.0, remainingTime = 0.0;
static struct timespec lastLevelChange;
struct timespec now;
double dtime, dlevel;
if (GetCurrentBatteryCharge(&charge)) {
aBatteryInfo->level() = (double)charge / 100.0;
} else {
aBatteryInfo->level() = dom::battery::kDefaultLevel;
}
int charging;
if (GetCurrentBatteryCharging(&charging)) {
aBatteryInfo->charging() = charging;
} else {
aBatteryInfo->charging() = true;
}
if (aBatteryInfo->charging() != previousCharging){
aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
memset(&lastLevelChange, 0, sizeof(struct timespec));
}
if (aBatteryInfo->charging()) {
if (aBatteryInfo->level() == 1.0) {
aBatteryInfo->remainingTime() = dom::battery::kDefaultRemainingTime;
} else if (aBatteryInfo->level() != previousLevel){
if (lastLevelChange.tv_sec != 0) {
clock_gettime(CLOCK_MONOTONIC, &now);
dtime = now.tv_sec - lastLevelChange.tv_sec;
dlevel = aBatteryInfo->level() - previousLevel;
if (dlevel <= 0.0) {
aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
} else {
remainingTime = (double) round(dtime / dlevel * (1.0 - aBatteryInfo->level()));
aBatteryInfo->remainingTime() = remainingTime;
}
lastLevelChange = now;
} else { // lastLevelChange.tv_sec == 0
clock_gettime(CLOCK_MONOTONIC, &lastLevelChange);
aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
}
} else {
clock_gettime(CLOCK_MONOTONIC, &now);
dtime = now.tv_sec - lastLevelChange.tv_sec;
if (dtime < remainingTime) {
aBatteryInfo->remainingTime() = round(remainingTime - dtime);
} else {
aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
}
}
} else {
aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
}
previousCharging = aBatteryInfo->charging();
previousLevel = aBatteryInfo->level();
}
namespace {
/**
* RAII class to help us remember to close file descriptors.
*/
bool WriteToFile(const char *filename, const char *toWrite)
{
int fd = open(filename, O_WRONLY);
ScopedClose autoClose(fd);
if (fd < 0) {
HAL_LOG("Unable to open file %s.", filename);
return false;
}
if (write(fd, toWrite, strlen(toWrite)) < 0) {
HAL_LOG("Unable to write to file %s.", filename);
return false;
}
return true;
}
// We can write to screenEnabledFilename to enable/disable the screen, but when
// we read, we always get "mem"! So we have to keep track ourselves whether
// the screen is on or not.
bool sScreenEnabled = true;
// We can read wakeLockFilename to find out whether the cpu wake lock
// is already acquired, but reading and parsing it is a lot more work
// than tracking it ourselves, and it won't be accurate anyway (kernel
// internal wake locks aren't counted here.)
bool sCpuSleepAllowed = true;
// Some CPU wake locks may be acquired internally in HAL. We use a counter to
// keep track of these needs. Note we have to hold |sInternalLockCpuMonitor|
// when reading or writing this variable to ensure thread-safe.
int32_t sInternalLockCpuCount = 0;
} // anonymous namespace
bool
GetScreenEnabled()
{
return sScreenEnabled;
}
void
SetScreenEnabled(bool aEnabled)
{
GetGonkDisplay()->SetEnabled(aEnabled);
sScreenEnabled = aEnabled;
}
bool
GetKeyLightEnabled()
{
LightConfiguration config;
GetLight(eHalLightID_Buttons, &config);
return (config.color != 0x00000000);
}
void
SetKeyLightEnabled(bool aEnabled)
{
LightConfiguration config;
config.mode = eHalLightMode_User;
config.flash = eHalLightFlash_None;
config.flashOnMS = config.flashOffMS = 0;
config.color = 0x00000000;
if (aEnabled) {
// Convert the value in [0, 1] to an int between 0 and 255 and then convert
// it to a color. Note that the high byte is FF, corresponding to the alpha
// channel.
double brightness = GetScreenBrightness();
uint32_t val = static_cast<int>(round(brightness * 255.0));
uint32_t color = (0xff<<24) + (val<<16) + (val<<8) + val;
config.color = color;
}
SetLight(eHalLightID_Buttons, config);
SetLight(eHalLightID_Keyboard, config);
}
double
GetScreenBrightness()
{
LightConfiguration config;
LightType light = eHalLightID_Backlight;
GetLight(light, &config);
// backlight is brightness only, so using one of the RGB elements as value.
int brightness = config.color & 0xFF;
return brightness / 255.0;
}
void
SetScreenBrightness(double brightness)
{
// Don't use De Morgan's law to push the ! into this expression; we want to
// catch NaN too.
if (!(0 <= brightness && brightness <= 1)) {
HAL_LOG("SetScreenBrightness: Dropping illegal brightness %f.", brightness);
return;
}
// Convert the value in [0, 1] to an int between 0 and 255 and convert to a color
// note that the high byte is FF, corresponding to the alpha channel.
uint32_t val = static_cast<int>(round(brightness * 255.0));
uint32_t color = (0xff<<24) + (val<<16) + (val<<8) + val;
LightConfiguration config;
config.mode = eHalLightMode_User;
config.flash = eHalLightFlash_None;
config.flashOnMS = config.flashOffMS = 0;
config.color = color;
SetLight(eHalLightID_Backlight, config);
if (GetKeyLightEnabled()) {
SetLight(eHalLightID_Buttons, config);
SetLight(eHalLightID_Keyboard, config);
}
}
static Monitor* sInternalLockCpuMonitor = nullptr;
static void
UpdateCpuSleepState()
{
const char *wakeLockFilename = "/sys/power/wake_lock";
const char *wakeUnlockFilename = "/sys/power/wake_unlock";
sInternalLockCpuMonitor->AssertCurrentThreadOwns();
bool allowed = sCpuSleepAllowed && !sInternalLockCpuCount;
WriteToFile(allowed ? wakeUnlockFilename : wakeLockFilename, "gecko");
}
static void
InternalLockCpu() {
MonitorAutoLock monitor(*sInternalLockCpuMonitor);
++sInternalLockCpuCount;
UpdateCpuSleepState();
}
static void
InternalUnlockCpu() {
MonitorAutoLock monitor(*sInternalLockCpuMonitor);
--sInternalLockCpuCount;
UpdateCpuSleepState();
}
bool
GetCpuSleepAllowed()
{
return sCpuSleepAllowed;
}
void
SetCpuSleepAllowed(bool aAllowed)
{
MonitorAutoLock monitor(*sInternalLockCpuMonitor);
sCpuSleepAllowed = aAllowed;
UpdateCpuSleepState();
}
void
AdjustSystemClock(int64_t aDeltaMilliseconds)
{
int fd;
struct timespec now;
if (aDeltaMilliseconds == 0) {
return;
}
// Preventing context switch before setting system clock
sched_yield();
clock_gettime(CLOCK_REALTIME, &now);
now.tv_sec += (time_t)(aDeltaMilliseconds / 1000LL);
now.tv_nsec += (long)((aDeltaMilliseconds % 1000LL) * NsecPerMsec);
if (now.tv_nsec >= NsecPerSec) {
now.tv_sec += 1;
now.tv_nsec -= NsecPerSec;
}
if (now.tv_nsec < 0) {
now.tv_nsec += NsecPerSec;
now.tv_sec -= 1;
}
do {
fd = open("/dev/alarm", O_RDWR);
} while (fd == -1 && errno == EINTR);
ScopedClose autoClose(fd);
if (fd < 0) {
HAL_LOG("Failed to open /dev/alarm: %s", strerror(errno));
return;
}
if (ioctl(fd, ANDROID_ALARM_SET_RTC, &now) < 0) {
HAL_LOG("ANDROID_ALARM_SET_RTC failed: %s", strerror(errno));
}
hal::NotifySystemClockChange(aDeltaMilliseconds);
}
int32_t
GetTimezoneOffset()
{
PRExplodedTime prTime;
PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &prTime);
// Daylight saving time (DST) will be taken into account.
int32_t offset = prTime.tm_params.tp_gmt_offset;
offset += prTime.tm_params.tp_dst_offset;
// Returns the timezone offset relative to UTC in minutes.
return -(offset / 60);
}
static int32_t sKernelTimezoneOffset = 0;
static void
UpdateKernelTimezone(int32_t timezoneOffset)
{
if (sKernelTimezoneOffset == timezoneOffset) {
return;
}
// Tell the kernel about the new time zone as well, so that FAT filesystems
// will get local timestamps rather than UTC timestamps.
//
// We assume that /init.rc has a sysclktz entry so that settimeofday has
// already been called once before we call it (there is a side-effect in
// the kernel the very first time settimeofday is called where it does some
// special processing if you only set the timezone).
struct timezone tz;
memset(&tz, 0, sizeof(tz));
tz.tz_minuteswest = timezoneOffset;
settimeofday(nullptr, &tz);
sKernelTimezoneOffset = timezoneOffset;
}
void
SetTimezone(const nsCString& aTimezoneSpec)
{
if (aTimezoneSpec.Equals(GetTimezone())) {
// Even though the timezone hasn't changed, we still need to tell the
// kernel what the current timezone is. The timezone is persisted in
// a property and doesn't change across reboots, but the kernel still
// needs to be updated on every boot.
UpdateKernelTimezone(GetTimezoneOffset());
return;
}
int32_t oldTimezoneOffsetMinutes = GetTimezoneOffset();
property_set("persist.sys.timezone", aTimezoneSpec.get());
// This function is automatically called by the other time conversion
// functions that depend on the timezone. To be safe, we call it manually.
tzset();
int32_t newTimezoneOffsetMinutes = GetTimezoneOffset();
UpdateKernelTimezone(newTimezoneOffsetMinutes);
hal::NotifySystemTimezoneChange(
hal::SystemTimezoneChangeInformation(
oldTimezoneOffsetMinutes, newTimezoneOffsetMinutes));
}
nsCString
GetTimezone()
{
char timezone[32];
property_get("persist.sys.timezone", timezone, "");
return nsCString(timezone);
}
void
EnableSystemClockChangeNotifications()
{
}
void
DisableSystemClockChangeNotifications()
{
}
void
EnableSystemTimezoneChangeNotifications()
{
}
void
DisableSystemTimezoneChangeNotifications()
{
}
// Nothing to do here. Gonk widgetry always listens for screen
// orientation changes.
void
EnableScreenConfigurationNotifications()
{
}
void
DisableScreenConfigurationNotifications()
{
}
void
GetCurrentScreenConfiguration(hal::ScreenConfiguration* aScreenConfiguration)
{
*aScreenConfiguration = nsScreenGonk::GetConfiguration();
}
bool
LockScreenOrientation(const dom::ScreenOrientation& aOrientation)
{
return OrientationObserver::GetInstance()->LockScreenOrientation(aOrientation);
}
void
UnlockScreenOrientation()
{