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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
/*
 * PROJECT:         ReactOS ACPI-Compliant Control Method Battery
 * LICENSE:         BSD - See COPYING.ARM in the top level directory
 * FILE:            boot/drivers/bus/acpi/cmbatt/cmbatt.c
 * PURPOSE:         Main Initialization Code and IRP Handling
 * PROGRAMMERS:     ReactOS Portable Systems Group
 */

/* INCLUDES *******************************************************************/

#include "cmbatt.h"

#include <debug.h>

/* GLOBALS ********************************************************************/

ULONG CmBattDebug;
PCALLBACK_OBJECT CmBattPowerCallBackObject;
PVOID CmBattPowerCallBackRegistration;
UNICODE_STRING GlobalRegistryPath;
KTIMER CmBattWakeDpcTimerObject;
KDPC CmBattWakeDpcObject;
PDEVICE_OBJECT AcAdapterPdo;
LARGE_INTEGER CmBattWakeDpcDelay;
 
/* FUNCTIONS ******************************************************************/

VOID
NTAPI
CmBattPowerCallBack(IN PCMBATT_DEVICE_EXTENSION DeviceExtension,
                    IN ULONG Action,
                    IN ULONG Value)
{
    BOOLEAN Cancelled;
    PDEVICE_OBJECT DeviceObject;
    if (CmBattDebug & 0x10)
        DbgPrint("CmBattPowerCallBack: action: %d, value: %d \n", Action, Value);
    
    /* Check if a transition is going to happen */
    if (Action == PO_CB_SYSTEM_STATE_LOCK)
    {
        /* We have just re-entered S0: call the wake DPC in 10 seconds */
        if (Value == 1)
        {
            if (CmBattDebug & 0x10)
                DbgPrint("CmBattPowerCallBack: Calling CmBattWakeDpc after 10 seconds.\n");
            Cancelled = KeSetTimer(&CmBattWakeDpcTimerObject, CmBattWakeDpcDelay, &CmBattWakeDpcObject);
            if (CmBattDebug & 0x10)
                DbgPrint("CmBattPowerCallBack: timerCanceled = %d.\n", Cancelled);
        }
        else if (Value == 0)
        {
            /* We are exiting the S0 state: loop all devices to set the delay flag */
            if (CmBattDebug & 0x10)
                DbgPrint("CmBattPowerCallBack: Delaying Notifications\n");
            for (DeviceObject = DeviceExtension->DeviceObject;
                 DeviceObject;
                 DeviceObject = DeviceObject->NextDevice)
            {
                /* Set the delay flag */
                DeviceExtension = DeviceObject->DeviceExtension;
                DeviceExtension->DelayNotification = TRUE;
            }
        }
        else if (CmBattDebug & 0x10)
        {
            /* Unknown value */
            DbgPrint("CmBattPowerCallBack: unknown argument2 = %08x\n");
        }
    }
}

VOID
NTAPI
CmBattWakeDpc(IN PKDPC Dpc,
              IN PCMBATT_DEVICE_EXTENSION FdoExtension,
              IN PVOID SystemArgument1,
              IN PVOID SystemArgument2)
{
    PDEVICE_OBJECT CurrentObject;
    BOOLEAN AcNotify = FALSE;
    PCMBATT_DEVICE_EXTENSION DeviceExtension;
    ULONG ArFlag;
    if (CmBattDebug & 2) DbgPrint("CmBattWakeDpc: Entered.\n");
    
    /* Loop all device objects */
    for (CurrentObject = FdoExtension->DeviceObject;
         CurrentObject;
         CurrentObject = CurrentObject->NextDevice)
    {
        /* Turn delay flag off, we're back in S0 */
        DeviceExtension = CurrentObject->DeviceExtension;
        DeviceExtension->DelayNotification = 0;
        
        /* Check if this is an AC adapter */
        if (DeviceExtension->FdoType == CmBattAcAdapter)
        {
            /* Was there a pending notify? */
            if (DeviceExtension->ArFlag & CMBATT_AR_NOTIFY)
            {
                /* We'll send a notify on the next pass */
                AcNotify = TRUE;
                DeviceExtension->ArFlag = 0;
                if (CmBattDebug & 0x20)
                    DbgPrint("CmBattWakeDpc: AC adapter notified\n");
            }
        }
    }

    /* Loop the device objects again */
    for (CurrentObject = FdoExtension->DeviceObject;
         CurrentObject;
         CurrentObject = CurrentObject->NextDevice)
    {
        /* Check if this is a battery */
        DeviceExtension = CurrentObject->DeviceExtension;
        if (DeviceExtension->FdoType == CmBattBattery)
        {
            /* Check what ARs are pending */
            ArFlag = DeviceExtension->ArFlag;
            if (CmBattDebug & 0x20)
                DbgPrint("CmBattWakeDpc: Performing delayed ARs: %01x\n", ArFlag);

            /* Insert notification, clear the lock value */
            if (ArFlag & CMBATT_AR_INSERT) InterlockedExchange(&DeviceExtension->ArLockValue, 0);

            /* Removal, clear the battery tag */
            if (ArFlag & CMBATT_AR_REMOVE) DeviceExtension->Tag = 0;

            /* Notification (or AC/DC adapter change from first pass above) */
            if ((ArFlag & CMBATT_AR_NOTIFY) || (AcNotify))
            {
                /* Notify the class driver */
                BatteryClassStatusNotify(DeviceExtension->ClassData);
            }
        }
    }
}

VOID
NTAPI
CmBattNotifyHandler(IN PCMBATT_DEVICE_EXTENSION DeviceExtension,
                    IN ULONG NotifyValue)
{
    ULONG ArFlag;
    PCMBATT_DEVICE_EXTENSION FdoExtension;
    PDEVICE_OBJECT DeviceObject;
    
    if (CmBattDebug & (CMBATT_ACPI_ASSERT | CMBATT_PNP_INFO))
        DbgPrint("CmBattNotifyHandler: CmBatt 0x%08x Type %d Number %d Notify Value: %x\n",
                 DeviceExtension,
                 DeviceExtension->FdoType,
                 DeviceExtension->DeviceId,
                 NotifyValue);
    
    /* Check what kind of notification was received */
    switch (NotifyValue)
    {
        /* ACPI Specification says is sends a "Bus Check" when power source changes */
        case ACPI_BUS_CHECK:
        
            /* We treat it as possible physical change */
            DeviceExtension->ArFlag |= (CMBATT_AR_NOTIFY | CMBATT_AR_INSERT);
            if ((DeviceExtension->Tag) &&
                (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_WARNING)))
                DbgPrint("CmBattNotifyHandler: Received battery #%x insertion, but tag was not invalid.\n",
                         DeviceExtension->DeviceId);
            break;
        
        /* Status of the battery has changed */
        case ACPI_BATT_NOTIFY_STATUS:
        
            /* All we'll do is notify the class driver */
            DeviceExtension->ArFlag |= CMBATT_AR_NOTIFY;
            break;
        
        /* Information on the battery has changed, such as physical presence */
        case ACPI_DEVICE_CHECK:
        case ACPI_BATT_NOTIFY_INFO:
        
            /* Reset all state and let the class driver re-evaluate it all */
            DeviceExtension->ArFlag |= (CMBATT_AR_NOTIFY |
                                        CMBATT_AR_INSERT |
                                        CMBATT_AR_REMOVE);
            break;
            
        default:
        
            if (CmBattDebug & CMBATT_PNP_INFO)
                DbgPrint("CmBattNotifyHandler: Unknown Notify Value: %x\n", NotifyValue);
    }

    /* Check if we're supposed to delay the notification till later */
    if (DeviceExtension->DelayNotification)
    {
        /* We'll handle this when we get a status query later on */
        if (CmBattDebug & CMBATT_PNP_INFO)
            DbgPrint("CmBattNotifyHandler: Notification delayed: ARs = %01x\n",
                      DeviceExtension->ArFlag);
        return;
    }

    /* We're going to handle this now */
    if (CmBattDebug & CMBATT_PNP_INFO) 
        DbgPrint("CmBattNotifyHandler: Performing ARs: %01x\n", DeviceExtension->ArFlag);

    /* Check if this is a battery or AC adapter notification */
    if (DeviceExtension->FdoType == CmBattBattery)
    {
        /* Reset the current trip point */
        DeviceExtension->TripPointValue = BATTERY_UNKNOWN_CAPACITY;
        
        /* Check what ARs have to be done */
        ArFlag = DeviceExtension->ArFlag;
        
        /* New battery inserted, reset lock value */
        if (ArFlag & CMBATT_AR_INSERT) InterlockedExchange(&DeviceExtension->ArLockValue, 0);

        /* Check if the battery may have been removed */
        if (ArFlag & CMBATT_AR_REMOVE) DeviceExtension->Tag = 0;
        
        /* Check if there's been any sort of change to the battery */
        if (ArFlag & CMBATT_AR_NOTIFY)
        {
            /* We'll probably end up re-evaluating _BIF and _BST */
            DeviceExtension->NotifySent = TRUE;
            BatteryClassStatusNotify(DeviceExtension->ClassData);
        }
    }
    else if (DeviceExtension->ArFlag & CMBATT_AR_NOTIFY)
    {
        /* The only known notification is AC/DC change. Loop device objects. */
        for (DeviceObject = DeviceExtension->FdoDeviceObject->DriverObject->DeviceObject;
             DeviceObject;
             DeviceObject = DeviceObject->NextDevice)
        {
            /* Is this a battery? */
            FdoExtension = DeviceObject->DeviceExtension;
            if (FdoExtension->FdoType == CmBattBattery)
            {
                /* Send a notification to the class driver */
                FdoExtension->NotifySent = TRUE;
                BatteryClassStatusNotify(FdoExtension->ClassData);
            }
        }
    }
    
    /* ARs have been processed */
    DeviceExtension->ArFlag = 0;
}

VOID
NTAPI
CmBattUnload(IN PDRIVER_OBJECT DriverObject)
{
    if (CmBattDebug & CMBATT_GENERIC_INFO) DPRINT("CmBattUnload: \n");
    
    /* Check if we have a registered power callback */
    if (CmBattPowerCallBackObject)
    {
        /* Get rid of it */
        ExUnregisterCallback(CmBattPowerCallBackRegistration);
        ObDereferenceObject(CmBattPowerCallBackObject);
    }
    
    /* Free the registry buffer if it exists */
    if (GlobalRegistryPath.Buffer) ExFreePool(GlobalRegistryPath.Buffer);

    /* Make sure we don't still have references to the DO */
    if ((DriverObject->DeviceObject) && (CmBattDebug & CMBATT_GENERIC_WARNING))
    {
        DbgPrint("Unload called before all devices removed.\n");
    }
}

NTSTATUS
NTAPI
CmBattVerifyStaticInfo(PCMBATT_DEVICE_EXTENSION DeviceExtension,
                       ULONG BatteryTag)
{
    UNIMPLEMENTED;
    return STATUS_NOT_IMPLEMENTED;   
}

NTSTATUS
NTAPI
CmBattOpenClose(IN PDEVICE_OBJECT DeviceObject,
                IN PIRP Irp)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PIO_STACK_LOCATION IoStackLocation;
    UCHAR Major;
    ULONG Count;
    PCMBATT_DEVICE_EXTENSION DeviceExtension;
    PAGED_CODE();
    if (CmBattDebug & CMBATT_GENERIC_INFO) DPRINT("CmBattOpenClose\n");

    /* Grab the device extension and lock it */
    DeviceExtension = DeviceObject->DeviceExtension;
    ExAcquireFastMutex(&DeviceExtension->FastMutex);
    
    /* Check if someone is trying to open a device that doesn't exist yet */
    Count = DeviceExtension->HandleCount;
    if (Count == 0xFFFFFFFF)
    {
        /* Fail the request */
        Status = STATUS_NO_SUCH_DEVICE;
        if (CmBattDebug & CMBATT_PNP_INFO)
        {
            DbgPrint("CmBattOpenClose: Failed (UID = %x)(device being removed).\n",
                     DeviceExtension->Tag);
        }
        goto Complete;
    }
    
    /* Check if this is an open or close */
    IoStackLocation = IoGetCurrentIrpStackLocation(Irp);
    Major = IoStackLocation->MajorFunction;
    if (Major == IRP_MJ_CREATE)
    {
        /* Increment the open count */
        DeviceExtension->HandleCount = Count + 1;  
        if (CmBattDebug & CMBATT_PNP_INFO)
        {
            DbgPrint("CmBattOpenClose: Open (DeviceNumber = %x)(count = %x).\n",
                     DeviceExtension->DeviceId, Count + 1);
        }
    }
    else if (Major == IRP_MJ_CLOSE)
    {
        /* Decrement the open count */
        DeviceExtension->HandleCount = Count - 1;
        if (CmBattDebug & CMBATT_PNP_INFO)
        {
            DbgPrint("CmBattOpenClose: Close (DeviceNumber = %x)(count = %x).\n",
                     DeviceExtension->DeviceId, Count + 1);
        }
    }

Complete:
    /* Release lock and complete request */
    ExReleaseFastMutex(&DeviceExtension->FastMutex);
    Irp->IoStatus.Status = Status;
    IoCompleteRequest(Irp, IO_NO_INCREMENT);
    return Status;  
}

NTSTATUS
NTAPI
CmBattIoctl(IN PDEVICE_OBJECT DeviceObject,
            IN PIRP Irp)
{
    PCMBATT_DEVICE_EXTENSION DeviceExtension = DeviceObject->DeviceExtension;
    NTSTATUS Status;
    PIO_STACK_LOCATION IoStackLocation;
    ULONG IoControlCode, OutputBufferLength, InputBufferLength;
    PAGED_CODE();
    if (CmBattDebug & 2) DbgPrint("CmBattIoctl\n");

    /* Acquire the remove lock */
    Status = IoAcquireRemoveLock(&DeviceExtension->RemoveLock, 0);
    if (!NT_SUCCESS(Status))
    {
        /* It's too late, fail */
        Irp->IoStatus.Status = STATUS_DEVICE_REMOVED;
        IoCompleteRequest(Irp, IO_NO_INCREMENT);
        return STATUS_DEVICE_REMOVED;
    }
    
    /* There's nothing to do for an AC adapter */
    if (DeviceExtension->FdoType == CmBattAcAdapter)
    {
        /* Pass it down, and release the remove lock */
        IoSkipCurrentIrpStackLocation(Irp);
        Status = IoCallDriver(DeviceExtension->AttachedDevice, Irp);
        IoReleaseRemoveLock(&DeviceExtension->RemoveLock, Irp);
        return Status;
    }
    
    /* Send to class driver */
    Status = BatteryClassIoctl(DeviceExtension->ClassData, Irp);
    if (Status == STATUS_NOT_SUPPORTED)
    {
        /* Read IOCTL information from IRP stack */
        IoStackLocation = IoGetCurrentIrpStackLocation(Irp);
        IoControlCode = IoStackLocation->Parameters.DeviceIoControl.IoControlCode;
        OutputBufferLength = IoStackLocation->Parameters.DeviceIoControl.OutputBufferLength;
        InputBufferLength = IoStackLocation->Parameters.DeviceIoControl.InputBufferLength;
        if (CmBattDebug & 4)
            DbgPrint("CmBattIoctl: Received  Direct Access IOCTL %x\n", IoControlCode);
    
        /* Handle internal IOCTLs */
        switch (IoControlCode)
        {
            case IOCTL_BATTERY_QUERY_UNIQUE_ID:
            
                /* Data is 4 bytes long */
                if (OutputBufferLength == sizeof(ULONG))
                {
                    /* Query it */
                    Status = CmBattGetUniqueId(DeviceExtension->PdoDeviceObject,
                                               Irp->AssociatedIrp.SystemBuffer);
                    if (NT_SUCCESS(Status)) Irp->IoStatus.Information = sizeof(ULONG);
                }
                else
                {
                    /* Buffer size invalid */
                    Status = STATUS_INVALID_BUFFER_SIZE;
                }
                break;
            
            case IOCTL_BATTERY_QUERY_STA:
            
                /* Data is 4 bytes long */
                if (OutputBufferLength == sizeof(ULONG))
                {
                    /* Query it */
                    Status = CmBattGetStaData(DeviceExtension->PdoDeviceObject,
                                              Irp->AssociatedIrp.SystemBuffer);
                    if (NT_SUCCESS(Status)) Irp->IoStatus.Information = sizeof(ULONG);
                }
                else
                {
                    /* Buffer size invalid */
                    Status = STATUS_INVALID_BUFFER_SIZE;
                }
                break;
            
            case IOCTL_BATTERY_QUERY_PSR:
            
                /* Data is 4 bytes long */
                if (OutputBufferLength == sizeof(ULONG))
                {
                    /* Do we have an AC adapter? */
                    if (AcAdapterPdo)
                    {
                        /* Query it */
                        Status = CmBattGetPsrData(AcAdapterPdo,
                                                  Irp->AssociatedIrp.SystemBuffer);
                        if (NT_SUCCESS(Status)) Irp->IoStatus.Information = sizeof(ULONG);
                    }
                    else
                    {
                        /* No adapter, just a battery, so fail */
                        Status = STATUS_NO_SUCH_DEVICE;
                    }
                }
                else
                {
                    /* Buffer size invalid */
                    Status = STATUS_INVALID_BUFFER_SIZE;
                }
                break;
                
            case IOCTL_BATTERY_SET_TRIP_POINT:
            
                /* Data is 4 bytes long */
                if (InputBufferLength == sizeof(ULONG))
                {
                    /* Query it */
                    Status = CmBattSetTripPpoint(DeviceExtension,
                                                 *(PULONG)Irp->AssociatedIrp.SystemBuffer);
                    Irp->IoStatus.Information = 0;
                }
                else
                {
                    /* Buffer size invalid */
                    Status = STATUS_INVALID_BUFFER_SIZE;
                }
                break;
    
            case IOCTL_BATTERY_QUERY_BIF:
            
                /* Data is 1060 bytes long */
                if (OutputBufferLength == sizeof(ACPI_BIF_DATA))
                {
                    /* Query it */
                    Status = CmBattGetBifData(DeviceExtension,
                                              Irp->AssociatedIrp.SystemBuffer);
                    if (NT_SUCCESS(Status)) Irp->IoStatus.Information = sizeof(ACPI_BIF_DATA);
                }
                else
                {
                    /* Buffer size invalid */
                    Status = STATUS_INVALID_BUFFER_SIZE;
                }
                break;
            
            case IOCTL_BATTERY_QUERY_BST:
            
                /* Data is 16 bytes long */
                if (OutputBufferLength == sizeof(ACPI_BST_DATA))
                {
                    /* Query it */
                    Status = CmBattGetBstData(DeviceExtension,
                                              Irp->AssociatedIrp.SystemBuffer);
                    if (NT_SUCCESS(Status)) Irp->IoStatus.Information = sizeof(ACPI_BST_DATA);
                }
                else
                {
                    /* Buffer size invalid */
                    Status = STATUS_INVALID_BUFFER_SIZE;
                }
                break;
            
            default:
            
                /* Unknown, let us pass it on to ACPI */
                if (CmBattDebug & 0xC)
                    DbgPrint("CmBattIoctl: Unknown IOCTL %x\n", IoControlCode);
                break;
        }
        
        /* Did someone pick it up? */
        if (Status != STATUS_NOT_SUPPORTED)
        {
            /* Complete the request */
            Irp->IoStatus.Status = Status;
            IoCompleteRequest(Irp, IO_NO_INCREMENT);
        }
        else
        {
            /* Still unsupported, try ACPI */
            IoSkipCurrentIrpStackLocation(Irp);
            Status = IoCallDriver(DeviceExtension->AttachedDevice, Irp);
        }
    }

    /* Release the remove lock and return status */
    IoReleaseRemoveLock(&DeviceExtension->RemoveLock, Irp);
    return Status;
}

NTSTATUS
NTAPI
CmBattQueryTag(IN PCMBATT_DEVICE_EXTENSION DeviceExtension,
               OUT PULONG Tag)
{
    PDEVICE_OBJECT PdoDevice;
    ULONG StaData;
    ULONG NewTag;
    NTSTATUS Status;
    PAGED_CODE();
    if (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_INFO))
      DbgPrint("CmBattQueryTag - Tag (%d), Battery %x, Device %d\n",
                *Tag, DeviceExtension, DeviceExtension->DeviceId);
    
    /* Get PDO and clear notification flag */  
    PdoDevice = DeviceExtension->PdoDeviceObject;
    DeviceExtension->NotifySent = 0;
    
    /* Get _STA from PDO (we need the machine status, not the battery status) */
    Status = CmBattGetStaData(PdoDevice, &StaData);
    if (NT_SUCCESS(Status))
    {
        /* Is a battery present? */
        if (StaData & ACPI_STA_BATTERY_PRESENT)
        {
            /* Do we not have a tag yet? */
            if (!DeviceExtension->Tag)
            {
                /* Set the new tag value, reset tags if we reached the maximum */
                NewTag = DeviceExtension->TagData;
                if (DeviceExtension->TagData++ == 0xFFFFFFFF) NewTag = 1;
                DeviceExtension->Tag = NewTag;
                if (CmBattDebug & CMBATT_GENERIC_INFO)
                    DbgPrint("CmBattQueryTag - New Tag: (%d)\n", DeviceExtension->Tag);
                
                /* Reset trip point data */
                DeviceExtension->TripPointOld = 0;
                DeviceExtension->TripPointValue = BATTERY_UNKNOWN_CAPACITY;
                                
                /* Clear AR lock and set new interrupt time */
                InterlockedExchange(&DeviceExtension->ArLockValue, 0);
                DeviceExtension->InterruptTime = KeQueryInterruptTime();
            }
        }
        else
        {
            /* No battery, so no tag */
            DeviceExtension->Tag = 0;
            Status = STATUS_NO_SUCH_DEVICE;
        }
    }
    
    /* Return the tag and status result */
    *Tag = DeviceExtension->Tag;
    if (CmBattDebug & CMBATT_ACPI_WARNING)
      DbgPrint("CmBattQueryTag: Returning Tag: 0x%x, status 0x%x\n", *Tag, Status);
    return Status;
}

NTSTATUS
NTAPI
CmBattDisableStatusNotify(IN PCMBATT_DEVICE_EXTENSION DeviceExtension)
{
    NTSTATUS Status;
    PAGED_CODE();
    if (CmBattDebug & 0xA) DbgPrint("CmBattDisableStatusNotify\n");

    /* Do we have a trip point */
    if (DeviceExtension->TripPointSet)
    {
        /* Is there a current value set? */
        if (DeviceExtension->TripPointValue)
        {
            /* Reset it back to 0 */
            DeviceExtension->TripPointValue = 0;
            Status = CmBattSetTripPpoint(DeviceExtension, 0);
            if (!NT_SUCCESS(Status))
            {
                /* If it failed, set unknown/invalid value */
                DeviceExtension->TripPointValue = BATTERY_UNKNOWN_CAPACITY;
                if (CmBattDebug & 8)
                    DbgPrint("CmBattDisableStatusNotify: SetTripPoint failed - %x\n", Status);
            }
        }
        else
        {
            /* No trip point set, so this is a successful no-op */
            Status = STATUS_SUCCESS;
        }
    }
    else
    {
        /* Nothing we can do */
        Status = STATUS_OBJECT_NAME_NOT_FOUND;
    }
    
    /* Return status */
    return Status;
}

NTSTATUS
NTAPI
CmBattSetStatusNotify(IN PCMBATT_DEVICE_EXTENSION DeviceExtension,
                      IN ULONG BatteryTag,
                      IN PBATTERY_NOTIFY BatteryNotify)
{
    NTSTATUS Status;
    ACPI_BST_DATA BstData;
    ULONG Capacity, NewTripPoint, TripPoint, DesignVoltage;
    BOOLEAN Charging;
    PAGED_CODE();
    if (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_INFO))
        DbgPrint("CmBattSetStatusNotify: Tag (%d) Target(0x%x)\n",
                 BatteryTag, BatteryNotify->LowCapacity);
    
    /* Update any ACPI evaluations */    
    Status = CmBattVerifyStaticInfo(DeviceExtension, BatteryTag);
    if (!NT_SUCCESS(Status)) return Status;
    
    /* Trip point not supported, fail */
    if (!DeviceExtension->TripPointSet) return STATUS_OBJECT_NAME_NOT_FOUND;
    
    /* Are both capacities known? */
    if ((BatteryNotify->HighCapacity == BATTERY_UNKNOWN_CAPACITY) ||
        (BatteryNotify->LowCapacity == BATTERY_UNKNOWN_CAPACITY))
    {
        /* We can't set trip points without these */
        if (CmBattDebug & CMBATT_GENERIC_WARNING)
            DbgPrint("CmBattSetStatusNotify: Failing request because of BATTERY_UNKNOWN_CAPACITY.\n");
        return STATUS_NOT_SUPPORTED;
    }
    
    /* Is the battery charging? */
    Charging = DeviceExtension->BstData.State & ACPI_BATT_STAT_CHARGING;
    if (Charging)
    {
        /* Then the trip point is when we hit the cap */
        Capacity = BatteryNotify->HighCapacity;
        NewTripPoint = BatteryNotify->HighCapacity;
    }
    else
    {
        /* Otherwise it's when we discharge to the bottom */
        Capacity = BatteryNotify->LowCapacity;
        NewTripPoint = BatteryNotify->LowCapacity;
    }

    /* Do we have data in Amps or Watts? */
    if (DeviceExtension->BifData.PowerUnit == ACPI_BATT_POWER_UNIT_AMPS)
    {
        /* We need the voltage to do the conversion */
        DesignVoltage = DeviceExtension->BifData.DesignVoltage;
        if ((DesignVoltage != BATTERY_UNKNOWN_VOLTAGE) && (DesignVoltage))
        {
            /* Convert from mAh into Ah */
            TripPoint = 1000 * NewTripPoint;
            if (Charging)
            {
                /* Scale the high trip point */
                NewTripPoint = (TripPoint + 500) / DesignVoltage + ((TripPoint + 500) % DesignVoltage != 0);
            }
            else
            {
                /* Scale the low trip point */
                NewTripPoint = (TripPoint - 500) / DesignVoltage - ((TripPoint - 500) % DesignVoltage == 0);
            }
        }
        else
        {
            /* Without knowing the voltage, Amps are not enough data on consumption */
            Status = STATUS_NOT_SUPPORTED;<--- Status is assigned
            if (CmBattDebug & CMBATT_ACPI_WARNING)
                DbgPrint("CmBattSetStatusNotify: Can't calculate BTP, DesignVoltage = 0x%08x\n",
                        DesignVoltage);  
        }
    }
    else if (Charging)
    {
        /* Make it trip just one past the charge cap */
        ++NewTripPoint;
    }
    else if (NewTripPoint > 0)
    {
        /* Make it trip just one below the drain cap */
        --NewTripPoint;
    }

    /* Do we actually have a new trip point? */
    if (NewTripPoint == DeviceExtension->TripPointValue)
    {
        /* No, so there is no work to be done */
        if (CmBattDebug & CMBATT_GENERIC_STATUS)
            DbgPrint("CmBattSetStatusNotify: Keeping original setting: %X\n", DeviceExtension->TripPointValue);
        return STATUS_SUCCESS;
    }
    
    /* Set the trip point with ACPI and check for success */
    DeviceExtension->TripPointValue = NewTripPoint;
    Status = CmBattSetTripPpoint(DeviceExtension, NewTripPoint);<--- Status is overwritten
    if (!(NewTripPoint) && (Capacity)) Status = STATUS_NOT_SUPPORTED;
    if (!NT_SUCCESS(Status))
    {
        /* We failed to set the trip point, or there wasn't one settable */
        DeviceExtension->TripPointValue = BATTERY_UNKNOWN_CAPACITY;
        if (CmBattDebug & (CMBATT_GENERIC_WARNING | CMBATT_ACPI_WARNING))
            DbgPrint("CmBattSetStatusNotify: SetTripPoint failed - %x\n", Status);
        return Status;
    }
    
    /* Read the new BST data to see the latest state */
    Status = CmBattGetBstData(DeviceExtension, &BstData);
    if (!NT_SUCCESS(Status))
    {
        /* We'll return failure to the caller */
        if (CmBattDebug & (CMBATT_GENERIC_WARNING | CMBATT_ACPI_WARNING))
            DbgPrint("CmBattSetStatusNotify: GetBstData - %x\n", Status);
    }
    else if ((Charging) && (BstData.RemainingCapacity >= NewTripPoint))
    {
        /* We are charging and our capacity is past the trip point, so trip now */
        if (CmBattDebug & CMBATT_GENERIC_WARNING)
            DbgPrint("CmBattSetStatusNotify: Trip point already crossed (1): TP = %08x, remaining capacity = %08x\n",
                     NewTripPoint, BstData.RemainingCapacity);
        CmBattNotifyHandler(DeviceExtension, ACPI_BATT_NOTIFY_STATUS);
    }
    else if ((BstData.RemainingCapacity) && (Capacity))
    {
        /* We are discharging, and our capacity is below the trip point, trip now */
        if (CmBattDebug & CMBATT_GENERIC_WARNING)
            DbgPrint("CmBattSetStatusNotify: Trip point already crossed (1): TP = %08x, remaining capacity = %08x\n",
                     NewTripPoint, BstData.RemainingCapacity);
        CmBattNotifyHandler(DeviceExtension, ACPI_BATT_NOTIFY_STATUS);        
    }

    /* All should've went well if we got here, unless BST failed... return! */
    if (CmBattDebug & CMBATT_GENERIC_STATUS)
          DbgPrint("CmBattSetStatusNotify: Want %X CurrentCap %X\n",
                    Capacity, DeviceExtension->RemainingCapacity);
    if (CmBattDebug & CMBATT_ACPI_WARNING)
          DbgPrint("CmBattSetStatusNotify: Set to: [%#08lx][%#08lx][%#08lx] Status %x\n",
                    BatteryNotify->PowerState,
                    BatteryNotify->LowCapacity,
                    BatteryNotify->HighCapacity);
    return Status;
}

NTSTATUS
NTAPI
CmBattGetBatteryStatus(IN PCMBATT_DEVICE_EXTENSION DeviceExtension,
                       IN ULONG Tag)
{
    ULONG PsrData = 0;
    NTSTATUS Status;
    ULONG BstState;
    ULONG DesignVoltage, PresentRate, RemainingCapacity;
    PAGED_CODE();
    if (CmBattDebug & CMBATT_GENERIC_INFO)
        DbgPrint("CmBattGetBatteryStatus - CmBatt (%08x) Tag (%d)\n", DeviceExtension, Tag);
    
    /* Validate ACPI data */    
    Status = CmBattVerifyStaticInfo(DeviceExtension, Tag);
    if (!NT_SUCCESS(Status)) return Status;

    /* Check for delayed status notifications */
    if (DeviceExtension->DelayNotification)
    {
        /* Process them now and don't do any other work */
        CmBattNotifyHandler(DeviceExtension, ACPI_BATT_NOTIFY_STATUS);
        return Status;
    }

    /* Get _BST from ACPI */
    Status = CmBattGetBstData(DeviceExtension, &DeviceExtension->BstData);
    if (!NT_SUCCESS(Status))
    {
        /* Fail */
        InterlockedExchange(&DeviceExtension->ArLockValue, 0);
        return Status;
    }
    
    /* Clear current BST information */ 
    DeviceExtension->State = 0;
    DeviceExtension->RemainingCapacity = 0;
    DeviceExtension->PresentVoltage = 0;
    DeviceExtension->Rate = 0;

    /* Get battery state */
    BstState = DeviceExtension->BstData.State;
    
    /* Is the battery both charging and discharging? */
    if ((BstState & ACPI_BATT_STAT_DISCHARG) && (BstState & ACPI_BATT_STAT_CHARGING) &&
        (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_WARNING)))
            DbgPrint("************************ ACPI BIOS BUG ********************\n* "
                     "CmBattGetBatteryStatus: Invalid state: _BST method returned 0x%08x for Battery State.\n"
                     "* One battery cannot be charging and discharging at the same time.\n",
                     BstState);
    
    /* Is the battery discharging? */   
    if (BstState & ACPI_BATT_STAT_DISCHARG)
    {
        /* Set power state and check if it just started discharging now */
        DeviceExtension->State |= BATTERY_DISCHARGING;
        if (!(DeviceExtension->State & ACPI_BATT_STAT_DISCHARG))
        {
            /* Remember the time when the state changed */
            DeviceExtension->InterruptTime = KeQueryInterruptTime();
        }
    }
    else if (BstState & ACPI_BATT_STAT_CHARGING)
    {
        /* Battery is charging, update power state */
        DeviceExtension->State |= (BATTERY_CHARGING | BATTERY_POWER_ON_LINE);
    }
    
    /* Is the battery in a critical state? */
    if (BstState & ACPI_BATT_STAT_CRITICAL) DeviceExtension->State |= BATTERY_CRITICAL;
    
    /* Read the voltage data */  
    DeviceExtension->PresentVoltage = DeviceExtension->BstData.PresentVoltage;
    
    /* Check if we have an A/C adapter */
    if (AcAdapterPdo)
    {
        /* Query information on it */
        CmBattGetPsrData(AcAdapterPdo, &PsrData);
    }
    else
    {
        /* Otherwise, check if the battery is charging */
        if (BstState & ACPI_BATT_STAT_CHARGING)
        {
            /* Then we'll assume there's a charger */
            PsrData = 1;
        }
        else
        {
            /* Assume no charger */
            PsrData = 0;        
        }
    }
    
    /* Is there a charger? */
    if (PsrData)
    {
        /* Set the power state flag to reflect this */
        DeviceExtension->State |= BATTERY_POWER_ON_LINE;
        if (CmBattDebug & (CMBATT_GENERIC_INFO | CMBATT_GENERIC_STATUS))
            DbgPrint("CmBattGetBatteryStatus: AC adapter is connected\n");
    }
    else if (CmBattDebug & (CMBATT_GENERIC_INFO | CMBATT_GENERIC_STATUS))
    {
        DbgPrint("CmBattGetBatteryStatus: AC adapter is NOT connected\n");        
    }
    
    /* Get some data we'll need */
    DesignVoltage = DeviceExtension->BifData.DesignVoltage;
    PresentRate = DeviceExtension->BstData.PresentRate;
    RemainingCapacity = DeviceExtension->BstData.RemainingCapacity;
    
    /* Check if we have battery data in Watts instead of Amps */
    if (DeviceExtension->BifData.PowerUnit == ACPI_BATT_POWER_UNIT_WATTS)
    {
        /* Get the data from the BST */
        DeviceExtension->RemainingCapacity = RemainingCapacity;
        DeviceExtension->Rate = PresentRate;
        
        /* Check if the rate is invalid */
        if (PresentRate > CM_MAX_VALUE)
        {
            /* Set an unknown rate and don't touch the old value */
            DeviceExtension->Rate = BATTERY_UNKNOWN_RATE;
            if ((PresentRate != CM_UNKNOWN_VALUE) && (CmBattDebug & CMBATT_ACPI_WARNING))
            {
                DbgPrint("CmBattGetBatteryStatus - Rate is greater than CM_MAX_VALUE\n");
                DbgPrint("----------------------   PresentRate = 0x%08x\n", PresentRate);
            }
        }
    }
    else if ((DesignVoltage != CM_UNKNOWN_VALUE) && (DesignVoltage))
    {
        /* We have voltage data, what about capacity? */
        if (RemainingCapacity == CM_UNKNOWN_VALUE)
        {
            /* Unable to calculate it */
            DeviceExtension->RemainingCapacity = BATTERY_UNKNOWN_CAPACITY;
            if (CmBattDebug & CMBATT_ACPI_WARNING)
            {
                DbgPrint("CmBattGetBatteryStatus - Can't calculate RemainingCapacity \n");
                DbgPrint("----------------------   RemainingCapacity = CM_UNKNOWN_VALUE\n");
            }
        }
        else
        {
            /* Compute the capacity with the information we have */
            DeviceExtension->RemainingCapacity = (DesignVoltage * RemainingCapacity + 500) / 1000;
        }
        
        /* Check if we have a rate */
        if (PresentRate != CM_UNKNOWN_VALUE)
        {
            /* Make sure the rate isn't too large */
            if (PresentRate > (-500 / DesignVoltage))
            {
                /* It is, so set unknown state */
                DeviceExtension->Rate = BATTERY_UNKNOWN_RATE;
                if (CmBattDebug & CMBATT_ACPI_WARNING)
                {
                    DbgPrint("CmBattGetBatteryStatus - Can't calculate Rate \n");
                    DbgPrint("----------------------   Overflow: PresentRate = 0x%08x\n", PresentRate);
                }
            }
            
            /* Compute the rate */
            DeviceExtension->Rate = (PresentRate * DesignVoltage + 500) / 1000;
        }
        else
        {
            /* We don't have a rate, so set unknown value */
            DeviceExtension->Rate = BATTERY_UNKNOWN_RATE;        
            if (CmBattDebug & CMBATT_ACPI_WARNING)
            {
                DbgPrint("CmBattGetBatteryStatus - Can't calculate Rate \n");
                DbgPrint("----------------------   Present Rate = CM_UNKNOWN_VALUE\n");
            }
        }
    }
    else
    {
        /* We have no rate, and no capacity, set unknown values */
        DeviceExtension->Rate = BATTERY_UNKNOWN_RATE;
        DeviceExtension->RemainingCapacity = BATTERY_UNKNOWN_CAPACITY;
        if (CmBattDebug & CMBATT_ACPI_WARNING)
        {
            DbgPrint("CmBattGetBatteryStatus - Can't calculate RemainingCapacity and Rate \n");
            DbgPrint("----------------------   DesignVoltage = 0x%08x\n", DesignVoltage);
        }
    }
    
    /* Check if we have an unknown rate */
    if (DeviceExtension->Rate == BATTERY_UNKNOWN_RATE)
    {
        /* The battery is discharging but we don't know by how much... this is bad! */
        if ((BstState & ACPI_BATT_STAT_DISCHARG) &&
            (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_WARNING)))
            DbgPrint("CmBattGetBatteryStatus: battery rate is unknown when battery is not charging!\n");
    }
    else if (DeviceExtension->State & BATTERY_DISCHARGING)
    {
        /* The battery is discharging, so treat the rate as a negative rate */
        DeviceExtension->Rate = -(LONG)DeviceExtension->Rate;
    }
    else if (!(DeviceExtension->State & BATTERY_CHARGING) && (DeviceExtension->Rate))
    {
        /* We are not charging, not discharging, but have a rate? Ignore it! */
        if (CmBattDebug & CMBATT_GENERIC_WARNING)
            DbgPrint("CmBattGetBatteryStatus: battery is not charging or discharging, but rate = %x\n",
                     DeviceExtension->Rate);
        DeviceExtension->Rate = 0;
    }
     
    /* Done */
    return STATUS_SUCCESS;
}

NTSTATUS
NTAPI
CmBattQueryInformation(IN PCMBATT_DEVICE_EXTENSION FdoExtension,
                       IN ULONG Tag,
                       IN BATTERY_QUERY_INFORMATION_LEVEL InfoLevel,
                       IN OPTIONAL LONG AtRate,
                       IN PVOID Buffer,
                       IN ULONG BufferLength,
                       OUT PULONG ReturnedLength)
{
    NTSTATUS Status;
    PVOID QueryData = NULL;
    ULONG QueryLength = 0;
    ULONG RemainingTime = 0;
    ANSI_STRING TempString;
    UNICODE_STRING TempString2;
    WCHAR InfoBuffer[256];
    WCHAR TempBuffer[256];
    UNICODE_STRING InfoString;
    ULONG RemainingCapacity;
    BATTERY_REPORTING_SCALE BatteryReportingScale[2];
    LONG Rate;
    PAGED_CODE();
    if (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_INFO))
        DbgPrint("CmBattQueryInformation - Tag (%d) Device %d, Informationlevel %d\n",
                 Tag,
                 FdoExtension->DeviceId,
                 InfoLevel);

    /* Check ACPI Data */
    Status = CmBattVerifyStaticInfo(FdoExtension, Tag);
    if (!NT_SUCCESS(Status)) return Status;

    /* Check what caller wants */
    switch (InfoLevel)
    {
        case BatteryInformation:
            /* Just return our static information */
            QueryData = &FdoExtension->BatteryInformation;
            QueryLength = sizeof(BATTERY_INFORMATION);
            break;
        
        case BatteryGranularityInformation:
        
            /* Return our static information, we have two scales */
            BatteryReportingScale[0].Granularity = FdoExtension->BatteryCapacityGranularity1;
            BatteryReportingScale[0].Capacity = FdoExtension->BatteryInformation.DefaultAlert1;
            BatteryReportingScale[1].Granularity = FdoExtension->BatteryCapacityGranularity2;
            BatteryReportingScale[1].Capacity = FdoExtension->BatteryInformation.DesignedCapacity;
            QueryData = BatteryReportingScale;
            QueryLength = sizeof(BATTERY_REPORTING_SCALE) * 2;
            break;
            
        case BatteryEstimatedTime:
        
            /* Check if it's been more than 2 1/2 minutes since the last change */
            if ((KeQueryInterruptTime() - 150000000) > (FdoExtension->InterruptTime))
            {
                /* Get new battery status */
                CmBattGetBatteryStatus(FdoExtension, FdoExtension->Tag);
                
                /* If the caller didn't specify a rate, use our static one */
                Rate = AtRate;
                if (!Rate) Rate = FdoExtension->Rate;
                
                /* If we don't have a valid negative rate, use unknown value */
                if (Rate >= 0) Rate = BATTERY_UNKNOWN_RATE;
                
                /* Grab the remaining capacity */
                RemainingCapacity = FdoExtension->RemainingCapacity;
                
                /* See if we don't know one or the other */
                if ((Rate == BATTERY_UNKNOWN_RATE) ||
                    (RemainingCapacity == BATTERY_UNKNOWN_CAPACITY))
                {
                    /* If the battery is discharging, we can't give out a time */
                    if ((FdoExtension->BstData.State & ACPI_BATT_STAT_DISCHARG) &&
                        (CmBattDebug & CMBATT_GENERIC_WARNING))
                            DbgPrint("CmBattQueryInformation: Can't calculate EstimatedTime.\n");
                    
                    /* Check if we don't have a rate and capacity is going down */
                    if ((FdoExtension->Rate == BATTERY_UNKNOWN_RATE) &&
                        (FdoExtension->BstData.State & ACPI_BATT_STAT_DISCHARG))
                    {
                        /* We have to fail, since we lack data */
                        Status = STATUS_INVALID_DEVICE_REQUEST;
                        if (CmBattDebug & CMBATT_GENERIC_WARNING)
                            DbgPrint("----------------------   PresentRate = BATTERY_UNKNOWN_RATE\n");
                    }
                    
                    /* If we don't have capacity, the rate is useless */
                    if (RemainingCapacity == BATTERY_UNKNOWN_CAPACITY)
                    {
                        /* We have to fail the request */
                        Status = STATUS_INVALID_DEVICE_REQUEST;
                        if (CmBattDebug & CMBATT_GENERIC_WARNING)
                            DbgPrint("----------------------   RemainingCapacity = BATTERY_UNKNOWN_CAPACITY\n");
                    }
                }
                else
                {
                    /* We have data, but is it valid? */
                    if (RemainingCapacity > 0x123456)
                    {
                        /* The capacity seems bogus, so don't use it */
                        if (CmBattDebug & CMBATT_ACPI_WARNING)
                            DbgPrint("CmBattQueryInformation: Data Overflow in calculating Remaining Capacity.\n");
                    }
                    else
                    {
                        /* Compute the remaining time in seconds, based on rate */
                        RemainingTime = (RemainingCapacity * 3600) / -Rate;
                    }
                }
            }
            
            /* Return the remaining time */
            QueryData = &RemainingTime;
            QueryLength = sizeof(ULONG);
            break;
            
        case BatteryDeviceName:
        
            /* Build the model number string */
            RtlInitAnsiString(&TempString, FdoExtension->ModelNumber);

            /* Convert it to Unicode */
            InfoString.Buffer = InfoBuffer;
            InfoString.MaximumLength = sizeof(InfoBuffer);            
            Status = RtlAnsiStringToUnicodeString(&InfoString, &TempString, 0);
            
            /* Return the unicode buffer */
            QueryData = InfoString.Buffer;
            QueryLength = InfoString.Length;
            break;
            
        case BatteryTemperature:
        case BatteryManufactureDate:
        
            /* We don't support these */
            Status = STATUS_INVALID_DEVICE_REQUEST;
            break;
            
        case BatteryManufactureName:
            
            /* Build the OEM info string */
            RtlInitAnsiString(&TempString, FdoExtension->OemInfo);
            
            /* Convert it to Unicode */
            InfoString.Buffer = InfoBuffer;
            InfoString.MaximumLength = sizeof(InfoBuffer);
            Status = RtlAnsiStringToUnicodeString(&InfoString, &TempString, 0);
            
            /* Return the unicode buffer */
            QueryData = InfoString.Buffer;
            QueryLength = InfoString.Length;
            break;
            
        case BatteryUniqueID:

            /* Build the serial number string */
            RtlInitAnsiString(&TempString, FdoExtension->SerialNumber);

            /* Convert it to Unicode */
            InfoString.Buffer = InfoBuffer;
            InfoString.MaximumLength = sizeof(InfoBuffer);
            RtlAnsiStringToUnicodeString(&InfoString, &TempString, 0);

            /* Setup a temporary string for concatenation */
            TempString2.Buffer = TempBuffer;
            TempString2.MaximumLength = sizeof(TempBuffer);
            
            /* Check if there's an OEM string */
            if (FdoExtension->OemInfo[0])
            {
                /* Build the OEM info string */
                RtlInitAnsiString(&TempString, FdoExtension->OemInfo);
              
                /* Convert it to Unicode and append it */
                RtlAnsiStringToUnicodeString(&TempString2, &TempString, 0);
                RtlAppendUnicodeStringToString(&InfoString, &TempString2);
            }
            
            /* Build the model number string */
            RtlInitAnsiString(&TempString, FdoExtension->ModelNumber);
            
            /* Convert it to Unicode and append it */
            RtlAnsiStringToUnicodeString(&TempString2, &TempString, 0);
            RtlAppendUnicodeStringToString(&InfoString, &TempString2);
            
            /* Return the final appended string */
            QueryData = InfoString.Buffer;
            QueryLength = InfoString.Length;
            break;
            
        default:
        
            /* Everything else is unknown */
            Status = STATUS_INVALID_PARAMETER;
            break;
    }

    /* Return the required length and check if the caller supplied enough */
    *ReturnedLength = QueryLength;
    if (BufferLength < QueryLength) Status = STATUS_BUFFER_TOO_SMALL;

    /* Copy the data if there's enough space and it exists */
    if ((NT_SUCCESS(Status)) && (QueryData)) RtlCopyMemory(Buffer, QueryData, QueryLength);
      
    /* Return function result */
    return Status;
}

NTSTATUS
NTAPI
CmBattQueryStatus(IN PCMBATT_DEVICE_EXTENSION DeviceExtension,
                  IN ULONG Tag,
                  IN PBATTERY_STATUS BatteryStatus)
{
    NTSTATUS Status;
    PAGED_CODE();
    if (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_INFO))
        DbgPrint("CmBattQueryStatus - Tag (%d) Device %x\n", Tag, DeviceExtension->DeviceId);
    
    /* Query ACPI information */
    Status = CmBattGetBatteryStatus(DeviceExtension, Tag);
    if (NT_SUCCESS(Status))
    {
        BatteryStatus->PowerState = DeviceExtension->State;
        BatteryStatus->Capacity = DeviceExtension->RemainingCapacity;
        BatteryStatus->Voltage = DeviceExtension->PresentVoltage;
        BatteryStatus->Rate = DeviceExtension->Rate;
    }
    
    /* Return status */
    if (CmBattDebug & (CMBATT_GENERIC_INFO))
        DbgPrint("CmBattQueryStatus: Returning [%#08lx][%#08lx][%#08lx][%#08lx]\n",
                 BatteryStatus->PowerState,
                 BatteryStatus->Capacity,
                 BatteryStatus->Voltage,
                 BatteryStatus->Rate);
    return Status;
}

NTSTATUS
NTAPI
DriverEntry(IN PDRIVER_OBJECT DriverObject,
            IN PUNICODE_STRING RegistryPath)
{
    NTSTATUS Status;
    PDRIVER_EXTENSION DriverExtension;
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING CallbackName;

    /* Allocate registry path */
    GlobalRegistryPath.MaximumLength = RegistryPath->Length + sizeof(UNICODE_NULL);
    GlobalRegistryPath.Length = RegistryPath->Length;
    GlobalRegistryPath.Buffer = ExAllocatePoolWithTag(PagedPool,
                                                      GlobalRegistryPath.MaximumLength,
                                                      'MtaB');
    if (!GlobalRegistryPath.Buffer)
    {
        /* Fail if we're out of memory this early */
        if (CmBattDebug & CMBATT_GENERIC_WARNING)
            DbgPrint("CmBatt: Couldn't allocate pool for registry path.");
        return STATUS_INSUFFICIENT_RESOURCES;
    }
    
    /* Buffer allocated, copy the string */
    RtlCopyUnicodeString(&GlobalRegistryPath, RegistryPath);
    if (CmBattDebug & CMBATT_GENERIC_INFO)
        DbgPrint("CmBatt DriverEntry - Obj (%08x) Path \"%ws\"\n",
                 DriverObject,
                 RegistryPath->Buffer);
    
    /* Setup the major dispatchers */
    DriverObject->MajorFunction[IRP_MJ_CREATE] = CmBattOpenClose;
    DriverObject->MajorFunction[IRP_MJ_CLOSE] = CmBattOpenClose;
    DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = CmBattIoctl;
    DriverObject->MajorFunction[IRP_MJ_POWER] = CmBattPowerDispatch;
    DriverObject->MajorFunction[IRP_MJ_PNP] = CmBattPnpDispatch;
    DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = CmBattSystemControl;

    /* And the unload routine */
    DriverObject->DriverUnload = CmBattUnload;
    
    /* And the add device routine */
    DriverExtension = DriverObject->DriverExtension;
    DriverExtension->AddDevice = CmBattAddDevice;

    /* Create a power callback */    
    RtlInitUnicodeString(&CallbackName, L"\\Callback\\PowerState");
    InitializeObjectAttributes(&ObjectAttributes,
                               &CallbackName,
                               OBJ_KERNEL_HANDLE,
                               NULL,
                               NULL);
    Status = ExCreateCallback(&CmBattPowerCallBackObject, &ObjectAttributes, 0, TRUE);
    if (!NT_SUCCESS(Status))
    {
        /* No callback, fail */
        CmBattPowerCallBackObject = 0;
        if (CmBattDebug & CMBATT_GENERIC_WARNING)
            DbgPrint("CmBattRegisterPowerCallBack: failed status=0x%08x\n", Status);
    }
    else
    {
        /* Register the power callback now */
        CmBattPowerCallBackRegistration = ExRegisterCallback(CmBattPowerCallBackObject,
                                                             (PVOID)CmBattPowerCallBack,
                                                             DriverObject);
        if (CmBattPowerCallBackRegistration)
        {
            /* Last thing: setup our DPC and timer for battery wake */
            KeInitializeDpc(&CmBattWakeDpcObject, (PVOID)CmBattWakeDpc, DriverObject);
            KeInitializeTimer(&CmBattWakeDpcTimerObject);
        }
        else
        {
            ObDereferenceObject(CmBattPowerCallBackObject);
            if (CmBattDebug & CMBATT_GENERIC_WARNING)
                DbgPrint("CmBattRegisterPowerCallBack: ExRegisterCallback failed.\n");
        }
        
        /* All good */
        Status = STATUS_SUCCESS;
    }

    /* Return failure or success */
    return Status;
}

/* EOF */