summaryrefslogtreecommitdiffstats
path: root/gps/libloc_api_50001/loc_eng.cpp
blob: e092f0a561fd03df5e67b67c605ad3daf6efe0f5 (plain)
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
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
/* Copyright (c) 2009-2012, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of The Linux Foundation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#define LOG_NDDEBUG 0
#define LOG_TAG "LocSvc_eng"

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <math.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <netinet/in.h>         /* struct sockaddr_in */
#include <sys/socket.h>
#include <sys/time.h>
#include <netdb.h>
#include <time.h>

#include "LocApiAdapter.h"

#include <cutils/sched_policy.h>
#include <utils/SystemClock.h>
#include <utils/Log.h>
#include <string.h>

#include <loc_eng.h>
#include <loc_eng_ni.h>
#include <loc_eng_dmn_conn.h>
#include <loc_eng_dmn_conn_handler.h>
#include <loc_eng_msg.h>
#include <loc_eng_msg_id.h>
#include <loc_eng_nmea.h>
#include <msg_q.h>
#include <loc.h>

#include "log_util.h"
#include "loc_eng_log.h"

#define SUCCESS TRUE
#define FAILURE FALSE

static void loc_eng_deferred_action_thread(void* context);
static void* loc_eng_create_msg_q();
static void loc_eng_free_msg(void* msg);

pthread_mutex_t LocEngContext::lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t LocEngContext::cond = PTHREAD_COND_INITIALIZER;
LocEngContext* LocEngContext::me = NULL;
boolean gpsConfigAlreadyRead = false;

loc_gps_cfg_s_type gps_conf;

/* Parameter spec table */
static loc_param_s_type loc_parameter_table[] =
{
  {"INTERMEDIATE_POS",               &gps_conf.INTERMEDIATE_POS,               NULL, 'n'},
  {"ACCURACY_THRES",                 &gps_conf.ACCURACY_THRES,                 NULL, 'n'},
  {"ENABLE_WIPER",                   &gps_conf.ENABLE_WIPER,                   NULL, 'n'},
  {"NMEA_PROVIDER",                  &gps_conf.NMEA_PROVIDER,                  NULL, 'n'},
  {"SUPL_VER",                       &gps_conf.SUPL_VER,                       NULL, 'n'},
  {"CAPABILITIES",                   &gps_conf.CAPABILITIES,                   NULL, 'n'},
  {"GYRO_BIAS_RANDOM_WALK",          &gps_conf.GYRO_BIAS_RANDOM_WALK,          &gps_conf.GYRO_BIAS_RANDOM_WALK_VALID, 'f'},
  {"ACCEL_RANDOM_WALK_SPECTRAL_DENSITY",     &gps_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY,    &gps_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
  {"ANGLE_RANDOM_WALK_SPECTRAL_DENSITY",     &gps_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY,    &gps_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
  {"RATE_RANDOM_WALK_SPECTRAL_DENSITY",      &gps_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY,     &gps_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
  {"VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY",  &gps_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY, &gps_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
  {"SENSOR_ACCEL_BATCHES_PER_SEC",   &gps_conf.SENSOR_ACCEL_BATCHES_PER_SEC,   NULL, 'n'},
  {"SENSOR_ACCEL_SAMPLES_PER_BATCH", &gps_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH, NULL, 'n'},
  {"SENSOR_GYRO_BATCHES_PER_SEC",    &gps_conf.SENSOR_GYRO_BATCHES_PER_SEC,    NULL, 'n'},
  {"SENSOR_GYRO_SAMPLES_PER_BATCH",  &gps_conf.SENSOR_GYRO_SAMPLES_PER_BATCH,  NULL, 'n'},
  {"SENSOR_ACCEL_BATCHES_PER_SEC_HIGH",   &gps_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH,   NULL, 'n'},
  {"SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH", &gps_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH, NULL, 'n'},
  {"SENSOR_GYRO_BATCHES_PER_SEC_HIGH",    &gps_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH,    NULL, 'n'},
  {"SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH",  &gps_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH,  NULL, 'n'},
  {"SENSOR_CONTROL_MODE",            &gps_conf.SENSOR_CONTROL_MODE,            NULL, 'n'},
  {"SENSOR_USAGE",                   &gps_conf.SENSOR_USAGE,                   NULL, 'n'},
  {"SENSOR_ALGORITHM_CONFIG_MASK",   &gps_conf.SENSOR_ALGORITHM_CONFIG_MASK,   NULL, 'n'},
  {"QUIPC_ENABLED",                  &gps_conf.QUIPC_ENABLED,                  NULL, 'n'},
  {"LPP_PROFILE",                    &gps_conf.LPP_PROFILE,                    NULL, 'n'},
};

static void loc_default_parameters(void)
{
   /* defaults */
   gps_conf.INTERMEDIATE_POS = 0;
   gps_conf.ACCURACY_THRES = 0;
   gps_conf.ENABLE_WIPER = 0;
   gps_conf.NMEA_PROVIDER = 0;
   gps_conf.SUPL_VER = 0x10000;
   gps_conf.CAPABILITIES = 0x7;

   gps_conf.GYRO_BIAS_RANDOM_WALK = 0;
   gps_conf.SENSOR_ACCEL_BATCHES_PER_SEC = 2;
   gps_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH = 5;
   gps_conf.SENSOR_GYRO_BATCHES_PER_SEC = 2;
   gps_conf.SENSOR_GYRO_SAMPLES_PER_BATCH = 5;
   gps_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH = 4;
   gps_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH = 25;
   gps_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH = 4;
   gps_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH = 25;
   gps_conf.SENSOR_CONTROL_MODE = 0; /* AUTO */
   gps_conf.SENSOR_USAGE = 0; /* Enabled */
   gps_conf.SENSOR_ALGORITHM_CONFIG_MASK = 0; /* INS Disabled = FALSE*/

   /* Values MUST be set by OEMs in configuration for sensor-assisted
      navigation to work. There are NO default values */
   gps_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY = 0;
   gps_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY = 0;
   gps_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY = 0;
   gps_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY = 0;

   gps_conf.GYRO_BIAS_RANDOM_WALK_VALID = 0;
   gps_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
   gps_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
   gps_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
   gps_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;

      /* LTE Positioning Profile configuration is disable by default*/
   gps_conf.LPP_PROFILE = 0;
}

LocEngContext::LocEngContext(gps_create_thread threadCreator) :
    deferred_q((const void*)loc_eng_create_msg_q()),
    //TODO: should we conditionally create ulp msg q?
    ulp_q((const void*)loc_eng_create_msg_q()),
    deferred_action_thread(threadCreator("loc_eng",loc_eng_deferred_action_thread, this)),
    counter(0)
{
    LOC_LOGV("LocEngContext %d : %d pthread_id %ld\n",
             getpid(), gettid(),
             deferred_action_thread);
}

LocEngContext* LocEngContext::get(gps_create_thread threadCreator)
{
    pthread_mutex_lock(&lock);
    // gonna need mutex protection here...
    if (NULL == me) {
        me = new LocEngContext(threadCreator);
    }
    me->counter++;

    pthread_mutex_unlock(&lock);
    return me;
}

void LocEngContext::drop()
{
    if (deferred_action_thread != pthread_self()) {
        pthread_mutex_lock(&lock);
        counter--;
        if (counter == 0) {
            loc_eng_msg *msg(new loc_eng_msg(this, LOC_ENG_MSG_QUIT));
            msg_q_snd((void*)deferred_q, msg, loc_eng_free_msg);

            // I am not sure if this is going to be hazardous. The calling thread
            // might be blocked for a while, if the q is loaded.  I am wondering
            // if we should just dump all the msgs in the q upon QUIT.
            pthread_cond_wait(&cond, &lock);

            msg_q_destroy((void**)&deferred_q);
            msg_q_destroy((void**)&ulp_q);
            delete me;
            me = NULL;
        }
        pthread_mutex_unlock(&lock);
    } else {
        LOC_LOGE("The HAL thread cannot free itself");
    }
}

// 2nd half of init(), singled out for
// modem restart to use.
static int loc_eng_reinit(loc_eng_data_s_type &loc_eng_data);
static void loc_eng_agps_reinit(loc_eng_data_s_type &loc_eng_data);

static int loc_eng_set_server(loc_eng_data_s_type &loc_eng_data,
                              LocServerType type, const char *hostname, int port);
// Internal functions
static void loc_inform_gps_status(loc_eng_data_s_type &loc_eng_data,
                                  GpsStatusValue status);
static void loc_eng_report_status(loc_eng_data_s_type &loc_eng_data,
                                  GpsStatusValue status);
static void loc_eng_process_conn_request(loc_eng_data_s_type &loc_eng_data,
                                         int connHandle, AGpsType agps_type);
static void loc_eng_agps_close_status(loc_eng_data_s_type &loc_eng_data, int is_succ);
static void loc_eng_handle_engine_down(loc_eng_data_s_type &loc_eng_data) ;
static void loc_eng_handle_engine_up(loc_eng_data_s_type &loc_eng_data) ;
static int loc_eng_set_privacy(loc_eng_data_s_type &loc_eng_data,
                               int8_t privacy_setting);

static char extra_data[100];
/*********************************************************************
 * Initialization checking macros
 *********************************************************************/
#define STATE_CHECK(ctx, x, ret) \
    if (!(ctx))                  \
  {                              \
      /* Not intialized, abort */\
      LOC_LOGE("%s: log_eng state error: %s", __func__, x); \
      EXIT_LOG(%s, x);                                            \
      ret;                                                        \
  }
#define INIT_CHECK(ctx, ret) STATE_CHECK(ctx, "instance not initialized", ret)

void loc_eng_msg_sender(void* loc_eng_data_p, void* msg)
{
    LocEngContext* loc_eng_context = (LocEngContext*)((loc_eng_data_s_type*)loc_eng_data_p)->context;
    msg_q_snd((void*)loc_eng_context->deferred_q, msg, loc_eng_free_msg);
}

static void* loc_eng_create_msg_q()
{
    void* q = NULL;
    if (eMSG_Q_SUCCESS != msg_q_init(&q)) {
        LOC_LOGE("loc_eng_create_msg_q Q init failed.");
        q = NULL;
    }
    return q;
}

static void loc_eng_free_msg(void* msg)
{
    delete (loc_eng_msg*)msg;
}

/*===========================================================================
FUNCTION    loc_eng_init

DESCRIPTION
   Initialize the location engine, this include setting up global datas
   and registers location engien with loc api service.

DEPENDENCIES
   None

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_init(loc_eng_data_s_type &loc_eng_data, LocCallbacks* callbacks,
                 LOC_API_ADAPTER_EVENT_MASK_T event,
                  void (*loc_external_msg_sender) (void*, void*))

{
    int ret_val =-1;

    ENTRY_LOG_CALLFLOW();
    if (NULL == callbacks || 0 == event) {
        LOC_LOGE("loc_eng_init: bad parameters cb %p eMask %d", callbacks, event);
        EXIT_LOG(%d, ret_val);
        return ret_val;
    }

    if (NULL != loc_eng_data.context) {
        // Current loc_eng_cleanup keeps context initialized, so must enable
        // here too.
        loc_eng_set_privacy(loc_eng_data, 1);
    }

    STATE_CHECK((NULL == loc_eng_data.context),
                "instance already initialized", return 0);

    memset(&loc_eng_data, 0, sizeof (loc_eng_data));

    // Create context (msg q + thread) (if not yet created)
    // This will also parse gps.conf, if not done.
    loc_eng_data.context = (void*)LocEngContext::get(callbacks->create_thread_cb);
    if (NULL != callbacks->set_capabilities_cb) {
        callbacks->set_capabilities_cb(gps_conf.CAPABILITIES);
    }

    // Save callbacks
    loc_eng_data.location_cb  = callbacks->location_cb;
    loc_eng_data.sv_status_cb = callbacks->sv_status_cb;
    loc_eng_data.status_cb    = callbacks->status_cb;
    loc_eng_data.nmea_cb      = callbacks->nmea_cb;
    loc_eng_data.acquire_wakelock_cb = callbacks->acquire_wakelock_cb;
    loc_eng_data.release_wakelock_cb = callbacks->release_wakelock_cb;
    loc_eng_data.request_utc_time_cb = callbacks->request_utc_time_cb;
    loc_eng_data.intermediateFix = gps_conf.INTERMEDIATE_POS;

    // initial states taken care of by the memset above
    // loc_eng_data.engine_status -- GPS_STATUS_NONE;
    // loc_eng_data.fix_session_status -- GPS_STATUS_NONE;
    // loc_eng_data.mute_session_state -- LOC_MUTE_SESS_NONE;

    if ((event & LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT) && (gps_conf.NMEA_PROVIDER == NMEA_PROVIDER_AP))
    {
        event = event ^ LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT; // unregister for modem NMEA report
        loc_eng_data.generateNmea = true;
    }
    else
    {
        loc_eng_data.generateNmea = false;
    }

    LocEng locEngHandle(&loc_eng_data, event, loc_eng_data.acquire_wakelock_cb,
                        loc_eng_data.release_wakelock_cb, loc_eng_msg_sender, loc_external_msg_sender,
                        callbacks->location_ext_parser, callbacks->sv_ext_parser);
    loc_eng_data.client_handle = LocApiAdapter::getLocApiAdapter(locEngHandle);

    if (NULL == loc_eng_data.client_handle) {
        // drop the context and declare failure
        ((LocEngContext*)(loc_eng_data.context))->drop();
        loc_eng_data.context = NULL;
    } else {
        LOC_LOGD("loc_eng_init created client, id = %p\n", loc_eng_data.client_handle);

        // call reinit to send initialization messages
       int tries = 30;
       while (tries > 0 &&
              LOC_API_ADAPTER_ERR_SUCCESS != (ret_val = loc_eng_reinit(loc_eng_data))) {
           tries--;
           LOC_LOGD("loc_eng_init client open failed, %d more tries", tries);
           sleep(1);
       }

        if (LOC_API_ADAPTER_ERR_SUCCESS == ret_val) {
            loc_eng_set_privacy(loc_eng_data, 1);
        }
    }

    EXIT_LOG(%d, ret_val);
    return ret_val;
}

static int loc_eng_reinit(loc_eng_data_s_type &loc_eng_data)
{
    ENTRY_LOG();
    int ret_val = loc_eng_data.client_handle->reinit();

    if (LOC_API_ADAPTER_ERR_SUCCESS == ret_val) {
        LOC_LOGD("loc_eng_reinit reinit() successful");

        loc_eng_msg_suple_version *supl_msg(new loc_eng_msg_suple_version(&loc_eng_data,
                                                                          gps_conf.SUPL_VER));
        msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                  supl_msg, loc_eng_free_msg);

        loc_eng_msg_lpp_config *lpp_msg(new loc_eng_msg_lpp_config(&loc_eng_data,
                                                                          gps_conf.LPP_PROFILE));
        msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                  lpp_msg, loc_eng_free_msg);

        loc_eng_msg_sensor_control_config *sensor_control_config_msg(
            new loc_eng_msg_sensor_control_config(&loc_eng_data, gps_conf.SENSOR_USAGE));
        msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                  sensor_control_config_msg, loc_eng_free_msg);

        /* Make sure at least one of the sensor property is specified by the user in the gps.conf file. */
        if( gps_conf.GYRO_BIAS_RANDOM_WALK_VALID ||
            gps_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
            gps_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
            gps_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
            gps_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID )
        {
            loc_eng_msg_sensor_properties *sensor_properties_msg(
                new loc_eng_msg_sensor_properties(&loc_eng_data,
                                                   gps_conf.GYRO_BIAS_RANDOM_WALK_VALID,
                                                   gps_conf.GYRO_BIAS_RANDOM_WALK,
                                                   gps_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
                                                   gps_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY,
                                                   gps_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
                                                   gps_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY,
                                                   gps_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
                                                   gps_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY,
                                                   gps_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
                                                   gps_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY));
            msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                      sensor_properties_msg, loc_eng_free_msg);
        }

        loc_eng_msg_sensor_perf_control_config *sensor_perf_control_conf_msg(
            new loc_eng_msg_sensor_perf_control_config(&loc_eng_data,
                                                       gps_conf.SENSOR_CONTROL_MODE,
                                                       gps_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH,
                                                       gps_conf.SENSOR_ACCEL_BATCHES_PER_SEC,
                                                       gps_conf.SENSOR_GYRO_SAMPLES_PER_BATCH,
                                                       gps_conf.SENSOR_GYRO_BATCHES_PER_SEC,
                                                       gps_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH,
                                                       gps_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH,
                                                       gps_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH,
                                                       gps_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH,
                                                       gps_conf.SENSOR_ALGORITHM_CONFIG_MASK));
        msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                  sensor_perf_control_conf_msg, loc_eng_free_msg);
    }

    EXIT_LOG(%d, ret_val);
    return ret_val;
}

/*===========================================================================
FUNCTION    loc_eng_cleanup

DESCRIPTION
   Cleans location engine. The location client handle will be released.

DEPENDENCIES
   None

RETURN VALUE
   None

SIDE EFFECTS
   N/A

===========================================================================*/
void loc_eng_cleanup(loc_eng_data_s_type &loc_eng_data)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return);

    // XTRA has no state, so we are fine with it.

    // we need to check and clear NI
#if 0
    // we need to check and clear ATL
    if (NULL != loc_eng_data.agnss_nif) {
        delete loc_eng_data.agnss_nif;
        loc_eng_data.agnss_nif = NULL;
    }
    if (NULL != loc_eng_data.internet_nif) {
        delete loc_eng_data.internet_nif;
        loc_eng_data.internet_nif = NULL;
    }
#endif
    if (loc_eng_data.client_handle->isInSession())
    {
        LOC_LOGD("loc_eng_cleanup: fix not stopped. stop it now.");
        loc_eng_stop(loc_eng_data);
    }

    loc_eng_set_privacy(loc_eng_data, 0);

#if 0 // can't afford to actually clean up, for many reason.

    ((LocEngContext*)(loc_eng_data.context))->drop();
    loc_eng_data.context = NULL;

    // De-initialize ulp
    if (locEngUlpInf != NULL)
    {
        locEngUlpInf = NULL;
        msg_q_destroy( &loc_eng_data.ulp_q);
    }

    if (loc_eng_data.client_handle != NULL)
    {
        LOC_LOGD("loc_eng_init: client opened. close it now.");
        delete loc_eng_data.client_handle;
        loc_eng_data.client_handle = NULL;
    }

#ifdef FEATURE_GNSS_BIT_API
    {
        char baseband[PROPERTY_VALUE_MAX];
        property_get("ro.baseband", baseband, "msm");
        if ((strcmp(baseband,"svlte2a") == 0))
        {
            loc_eng_dmn_conn_loc_api_server_unblock();
            loc_eng_dmn_conn_loc_api_server_join();
        }
    }
#endif /* FEATURE_GNSS_BIT_API */

#endif

    EXIT_LOG(%s, VOID_RET);
}


/*===========================================================================
FUNCTION    loc_eng_start

DESCRIPTION
   Starts the tracking session

DEPENDENCIES
   None

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_start(loc_eng_data_s_type &loc_eng_data)
{
   ENTRY_LOG_CALLFLOW();
   INIT_CHECK(loc_eng_data.context, return -1);

   if((loc_eng_data.ulp_initialized == true) && (gps_conf.CAPABILITIES & ULP_CAPABILITY))
   {
       //Pass the start messgage to ULP if present & activated
       loc_eng_msg *msg(new loc_eng_msg(&loc_eng_data, ULP_MSG_START_FIX));
       msg_q_snd( (void*)((LocEngContext*)(loc_eng_data.context))->ulp_q,
                  msg, loc_eng_free_msg);
   }else
   {
       loc_eng_msg *msg(new loc_eng_msg(&loc_eng_data, LOC_ENG_MSG_START_FIX));
       msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                 msg, loc_eng_free_msg);
   }
   EXIT_LOG(%d, 0);
   return 0;
}

static int loc_eng_start_handler(loc_eng_data_s_type &loc_eng_data)
{
   ENTRY_LOG();
   int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;

   if (!loc_eng_data.client_handle->isInSession()) {
       ret_val = loc_eng_data.client_handle->startFix();

       if (ret_val == LOC_API_ADAPTER_ERR_SUCCESS ||
           ret_val == LOC_API_ADAPTER_ERR_ENGINE_DOWN)
       {
           loc_eng_data.client_handle->setInSession(TRUE);
           loc_inform_gps_status(loc_eng_data, GPS_STATUS_SESSION_BEGIN);
       }
   }

   EXIT_LOG(%d, ret_val);
   return ret_val;
}

/*===========================================================================
FUNCTION    loc_eng_stop_wrapper

DESCRIPTION
   Stops the tracking session

DEPENDENCIES
   None

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_stop(loc_eng_data_s_type &loc_eng_data)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return -1);

    if((loc_eng_data.ulp_initialized == true) && (gps_conf.CAPABILITIES & ULP_CAPABILITY))
    {
        //Pass the start messgage to ULP if present & activated
        loc_eng_msg *msg(new loc_eng_msg(&loc_eng_data, ULP_MSG_STOP_FIX));
        msg_q_snd( (void*)((LocEngContext*)(loc_eng_data.context))->ulp_q,
                   msg, loc_eng_free_msg);
    }else
    {
        loc_eng_msg *msg(new loc_eng_msg(&loc_eng_data, LOC_ENG_MSG_STOP_FIX));
        msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                  msg, loc_eng_free_msg);
    }

    EXIT_LOG(%d, 0);
    return 0;
}

static int loc_eng_stop_handler(loc_eng_data_s_type &loc_eng_data)
{
   ENTRY_LOG();
   int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;

   if (loc_eng_data.client_handle->isInSession()) {

       ret_val = loc_eng_data.client_handle->stopFix();
       if (ret_val == LOC_API_ADAPTER_ERR_SUCCESS)
       {
           loc_inform_gps_status(loc_eng_data, GPS_STATUS_SESSION_END);
       }

       loc_eng_data.client_handle->setInSession(FALSE);
   }

    EXIT_LOG(%d, ret_val);
    return ret_val;
}

/*===========================================================================
FUNCTION    loc_eng_mute_one_session

DESCRIPTION
   Mutes one session

DEPENDENCIES
   None

RETURN VALUE
   0: Success

SIDE EFFECTS
   N/A

===========================================================================*/
void loc_eng_mute_one_session(loc_eng_data_s_type &loc_eng_data)
{
    ENTRY_LOG();
    loc_eng_data.mute_session_state = LOC_MUTE_SESS_WAIT;
    EXIT_LOG(%s, VOID_RET);
}

/*===========================================================================
FUNCTION    loc_eng_set_position_mode

DESCRIPTION
   Sets the mode and fix frequency for the tracking session.

DEPENDENCIES
   None

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_set_position_mode(loc_eng_data_s_type &loc_eng_data,
                              LocPosMode &params)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return -1);
    loc_eng_msg_position_mode *msg(
        new loc_eng_msg_position_mode(&loc_eng_data, params));
    msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
              msg, loc_eng_free_msg);

    EXIT_LOG(%d, 0);
    return 0;
}

/*===========================================================================
FUNCTION    loc_eng_inject_time

DESCRIPTION
   This is used by Java native function to do time injection.

DEPENDENCIES
   None

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_inject_time(loc_eng_data_s_type &loc_eng_data, GpsUtcTime time,
                        int64_t timeReference, int uncertainty)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return -1);
    loc_eng_msg_set_time *msg(
        new loc_eng_msg_set_time(&loc_eng_data,
                                 time,
                                 timeReference,
                                 uncertainty));
    msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
              msg, loc_eng_free_msg);
    EXIT_LOG(%d, 0);
    return 0;
}


/*===========================================================================
FUNCTION    loc_eng_inject_location

DESCRIPTION
   This is used by Java native function to do location injection.

DEPENDENCIES
   None

RETURN VALUE
   0          : Successful
   error code : Failure

SIDE EFFECTS
   N/A
===========================================================================*/
int loc_eng_inject_location(loc_eng_data_s_type &loc_eng_data, double latitude,
                            double longitude, float accuracy)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return -1);
    loc_eng_msg_inject_location *msg(
        new loc_eng_msg_inject_location(&loc_eng_data,
                                        latitude,
                                        longitude,
                                        accuracy));
    msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
              msg, loc_eng_free_msg);

    EXIT_LOG(%d, 0);
    return 0;
}


/*===========================================================================
FUNCTION    loc_eng_delete_aiding_data

DESCRIPTION
   This is used by Java native function to delete the aiding data. The function
   updates the global variable for the aiding data to be deleted. If the GPS
   engine is off, the aiding data will be deleted. Otherwise, the actual action
   will happen when gps engine is turned off.

DEPENDENCIES
   Assumes the aiding data type specified in GpsAidingData matches with
   LOC API specification.

RETURN VALUE
   None

SIDE EFFECTS
   N/A

===========================================================================*/
void loc_eng_delete_aiding_data(loc_eng_data_s_type &loc_eng_data, GpsAidingData f)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return);

    loc_eng_msg_delete_aiding_data *msg(
        new loc_eng_msg_delete_aiding_data(&loc_eng_data,
                                           f));
    msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
              msg, loc_eng_free_msg);

    EXIT_LOG(%s, VOID_RET);
}

/*===========================================================================

FUNCTION    loc_inform_gps_state

DESCRIPTION
   Informs the GPS Provider about the GPS status

DEPENDENCIES
   None

RETURN VALUE
   None

SIDE EFFECTS
   N/A

===========================================================================*/
static void loc_inform_gps_status(loc_eng_data_s_type &loc_eng_data, GpsStatusValue status)
{
    ENTRY_LOG();

    static GpsStatusValue last_status = GPS_STATUS_NONE;

    GpsStatus gs = { sizeof(gs),status };


    if (loc_eng_data.status_cb)
    {
        CALLBACK_LOG_CALLFLOW("status_cb", %s, loc_get_gps_status_name(gs.status));
        loc_eng_data.status_cb(&gs);
    }

    last_status = status;

    EXIT_LOG(%s, VOID_RET);
}

/*===========================================================================
FUNCTION    loc_eng_agps_reinit

DESCRIPTION
   2nd half of loc_eng_agps_init(), singled out for modem restart to use.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
static void loc_eng_agps_reinit(loc_eng_data_s_type &loc_eng_data)
{
    ENTRY_LOG();

    // Set server addresses which came before init
    if (loc_eng_data.supl_host_set)
    {
        loc_eng_set_server(loc_eng_data, LOC_AGPS_SUPL_SERVER,
                           loc_eng_data.supl_host_buf,
                           loc_eng_data.supl_port_buf);
    }

    if (loc_eng_data.c2k_host_set)
    {
        loc_eng_set_server(loc_eng_data, LOC_AGPS_CDMA_PDE_SERVER,
                           loc_eng_data.c2k_host_buf,
                           loc_eng_data.c2k_port_buf);
    }
    EXIT_LOG(%s, VOID_RET);
}
/*===========================================================================
FUNCTION    loc_eng_agps_init

DESCRIPTION
   Initialize the AGps interface.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
void loc_eng_agps_init(loc_eng_data_s_type &loc_eng_data, AGpsCallbacks* callbacks)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return);
    STATE_CHECK((NULL == loc_eng_data.agps_status_cb),
                "agps instance already initialized",
                return);
    if(callbacks == NULL) {
        LOC_LOGE("loc_eng_agps_init: bad parameters cb %p", callbacks);
        EXIT_LOG(%s, VOID_RET);
        return;
    }
    loc_eng_data.agps_status_cb = callbacks->status_cb;

    loc_eng_data.agnss_nif = new AgpsStateMachine(loc_eng_data.agps_status_cb,
                                                  AGPS_TYPE_SUPL,
                                                  false);
    loc_eng_data.internet_nif = new AgpsStateMachine(loc_eng_data.agps_status_cb,
                                                     AGPS_TYPE_WWAN_ANY,
                                                     false);
    loc_eng_data.wifi_nif = new AgpsStateMachine(loc_eng_data.agps_status_cb,
                                                 AGPS_TYPE_WIFI,
                                                 true);

#ifdef FEATURE_GNSS_BIT_API
    {
        char baseband[PROPERTY_VALUE_MAX];
        property_get("ro.baseband", baseband, "msm");
        if ((strcmp(baseband,"svlte2a") == 0) ||
            (strcmp(baseband,"sglte") == 0) ||
            (strcmp(baseband,"msm") == 0))
        {
            loc_eng_dmn_conn_loc_api_server_launch(callbacks->create_thread_cb,
                                                   NULL, NULL, &loc_eng_data);
        } else {
            LOC_LOGD("%s:%d] loc_eng_dmn_conn_loc_api_server was not initialized.baseband = %s\n",
            __func__, __LINE__, baseband);
        }
    }
#endif /* FEATURE_GNSS_BIT_API */

    loc_eng_agps_reinit(loc_eng_data);
    EXIT_LOG(%s, VOID_RET);
}

/*===========================================================================
FUNCTION    loc_eng_agps_open

DESCRIPTION
   This function is called when on-demand data connection opening is successful.
It should inform engine about the data open result.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_agps_open(loc_eng_data_s_type &loc_eng_data, AGpsType agpsType,
                     const char* apn, AGpsBearerType bearerType)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context && loc_eng_data.agps_status_cb,
               return -1);

    if (apn == NULL)
    {
        LOC_LOGE("APN Name NULL\n");
        return 0;
    }

    LOC_LOGD("loc_eng_agps_open APN name = [%s]", apn);

    int apn_len = smaller_of(strlen (apn), MAX_APN_LEN);
    loc_eng_msg_atl_open_success *msg(
        new loc_eng_msg_atl_open_success(&loc_eng_data, agpsType, apn,
                                        apn_len, bearerType));
    msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
              msg, loc_eng_free_msg);

    EXIT_LOG(%d, 0);
    return 0;
}

/*===========================================================================
FUNCTION    loc_eng_agps_closed

DESCRIPTION
   This function is called when on-demand data connection closing is done.
It should inform engine about the data close result.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_agps_closed(loc_eng_data_s_type &loc_eng_data, AGpsType agpsType)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context && loc_eng_data.agps_status_cb,
               return -1);

    loc_eng_msg_atl_closed *msg(new loc_eng_msg_atl_closed(&loc_eng_data, agpsType));
    msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
              msg, loc_eng_free_msg);

    EXIT_LOG(%d, 0);
    return 0;
}

/*===========================================================================
FUNCTION    loc_eng_agps_open_failed

DESCRIPTION
   This function is called when on-demand data connection opening has failed.
It should inform engine about the data open result.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_agps_open_failed(loc_eng_data_s_type &loc_eng_data, AGpsType agpsType)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context && loc_eng_data.agps_status_cb,
               return -1);

    loc_eng_msg_atl_open_failed *msg(new loc_eng_msg_atl_open_failed(&loc_eng_data, agpsType));
    msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
              msg, loc_eng_free_msg);

    EXIT_LOG(%d, 0);
    return 0;
}

/*===========================================================================

FUNCTION resolve_in_addr

DESCRIPTION
   Translates a hostname to in_addr struct

DEPENDENCIES
   n/a

RETURN VALUE
   TRUE if successful

SIDE EFFECTS
   n/a

===========================================================================*/
static boolean resolve_in_addr(const char *host_addr, struct in_addr *in_addr_ptr)
{
    ENTRY_LOG();
    boolean ret_val = TRUE;

    struct hostent             *hp;
    hp = gethostbyname(host_addr);
    if (hp != NULL) /* DNS OK */
    {
        memcpy(in_addr_ptr, hp->h_addr_list[0], hp->h_length);
    }
    else
    {
        /* Try IP representation */
        if (inet_aton(host_addr, in_addr_ptr) == 0)
        {
            /* IP not valid */
            LOC_LOGE("DNS query on '%s' failed\n", host_addr);
            ret_val = FALSE;
        }
    }

    EXIT_LOG(%s, loc_logger_boolStr[ret_val!=0]);
    return ret_val;
}

/*===========================================================================
FUNCTION    loc_eng_set_server

DESCRIPTION
   This is used to set the default AGPS server. Server address is obtained
   from gps.conf.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
static int loc_eng_set_server(loc_eng_data_s_type &loc_eng_data,
                              LocServerType type, const char* hostname, int port)
{
    ENTRY_LOG();
    int ret = 0;

    if (LOC_AGPS_SUPL_SERVER == type) {
        char url[MAX_URL_LEN];
        unsigned int len = snprintf(url, sizeof(url), "%s:%u", hostname, (unsigned) port);

        if (sizeof(url) > len) {
            loc_eng_msg_set_server_url *msg(new loc_eng_msg_set_server_url(&loc_eng_data,
                                                                           url, len));
            msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                      msg, loc_eng_free_msg);
        }
    } else if (LOC_AGPS_CDMA_PDE_SERVER == type ||
               LOC_AGPS_CUSTOM_PDE_SERVER == type ||
               LOC_AGPS_MPC_SERVER == type) {
        struct in_addr addr;
        if (!resolve_in_addr(hostname, &addr))
        {
            LOC_LOGE("loc_eng_set_server, hostname %s cannot be resolved.\n", hostname);
            ret = -2;
        } else {
            unsigned int ip = htonl(addr.s_addr);
            loc_eng_msg_set_server_ipv4 *msg(new loc_eng_msg_set_server_ipv4(&loc_eng_data,
                                                                             ip,
                                                                             port,
                                                                             type));
            msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                      msg, loc_eng_free_msg);
        }
    } else {
        LOC_LOGE("loc_eng_set_server, type %d cannot be resolved.\n", type);
    }

    EXIT_LOG(%d, ret);
    return ret;
}

/*===========================================================================
FUNCTION    loc_eng_set_server_proxy

DESCRIPTION
   If loc_eng_set_server is called before loc_eng_init, it doesn't work. This
   proxy buffers server settings and calls loc_eng_set_server when the client is
   open.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_set_server_proxy(loc_eng_data_s_type &loc_eng_data,
                             LocServerType type,
                             const char* hostname, int port)
{
    ENTRY_LOG_CALLFLOW();
    int ret_val = 0;

    if (NULL != loc_eng_data.context)
    {
        ret_val = loc_eng_set_server(loc_eng_data, type, hostname, port);
    } else {
        LOC_LOGW("set_server called before init. save the address, type: %d, hostname: %s, port: %d",
                 (int) type, hostname, port);
        switch (type)
        {
        case LOC_AGPS_SUPL_SERVER:
            strlcpy(loc_eng_data.supl_host_buf, hostname,
                    sizeof(loc_eng_data.supl_host_buf));
            loc_eng_data.supl_port_buf = port;
            loc_eng_data.supl_host_set = 1;
            break;
        case LOC_AGPS_CDMA_PDE_SERVER:
            strlcpy(loc_eng_data.c2k_host_buf, hostname,
                    sizeof(loc_eng_data.c2k_host_buf));
            loc_eng_data.c2k_port_buf = port;
            loc_eng_data.c2k_host_set = 1;
            break;
        default:
            LOC_LOGE("loc_eng_set_server_proxy, unknown server type = %d", (int) type);
        }
    }

    EXIT_LOG(%d, ret_val);
    return ret_val;
}

/*===========================================================================
FUNCTION    loc_eng_agps_ril_update_network_availability

DESCRIPTION
   Sets data call allow vs disallow flag to modem
   This is the only member of sLocEngAGpsRilInterface implemented.

DEPENDENCIES
   None

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
void loc_eng_agps_ril_update_network_availability(loc_eng_data_s_type &loc_eng_data,
                                                  int available, const char* apn)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return);
    if (apn != NULL)
    {
        LOC_LOGD("loc_eng_agps_ril_update_network_availability: APN Name = [%s]\n", apn);
        int apn_len = smaller_of(strlen (apn), MAX_APN_LEN);
        loc_eng_msg_set_data_enable *msg(new loc_eng_msg_set_data_enable(&loc_eng_data, apn,
                                                                         apn_len, available));
        msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
                  msg, loc_eng_free_msg);
    }
    EXIT_LOG(%s, VOID_RET);
}

/*===========================================================================
FUNCTION    loc_eng_report_status

DESCRIPTION
   Reports GPS engine state to Java layer.

DEPENDENCIES
   N/A

RETURN VALUE
   N/A

SIDE EFFECTS
   N/A

===========================================================================*/
static void loc_eng_report_status (loc_eng_data_s_type &loc_eng_data, GpsStatusValue status)
{
    ENTRY_LOG();
    // Switch from WAIT to MUTE, for "engine on" or "session begin" event
    if (status == GPS_STATUS_SESSION_BEGIN || status == GPS_STATUS_ENGINE_ON)
    {
        if (loc_eng_data.mute_session_state == LOC_MUTE_SESS_WAIT)
        {
            LOC_LOGD("loc_eng_report_status: mute_session_state changed from WAIT to IN SESSION");
            loc_eng_data.mute_session_state = LOC_MUTE_SESS_IN_SESSION;
        }
    }

    // Switch off MUTE session
    if (loc_eng_data.mute_session_state == LOC_MUTE_SESS_IN_SESSION &&
        (status == GPS_STATUS_SESSION_END || status == GPS_STATUS_ENGINE_OFF))
    {
        LOC_LOGD("loc_eng_report_status: mute_session_state changed from IN SESSION to NONE");
        loc_eng_data.mute_session_state = LOC_MUTE_SESS_NONE;
    }

    // Session End is not reported during Android navigating state
    boolean navigating = loc_eng_data.client_handle->isInSession();
    if (status != GPS_STATUS_NONE &&
        !(status == GPS_STATUS_SESSION_END && navigating) &&
        !(status == GPS_STATUS_SESSION_BEGIN && !navigating))
    {
        if (loc_eng_data.mute_session_state != LOC_MUTE_SESS_IN_SESSION)
        {
            // Inform GpsLocationProvider about mNavigating status
            loc_inform_gps_status(loc_eng_data, status);
        }
        else {
            LOC_LOGD("loc_eng_report_status: muting the status report.");
        }
    }

    // Only keeps ENGINE ON/OFF in engine_status
    if (status == GPS_STATUS_ENGINE_ON || status == GPS_STATUS_ENGINE_OFF)
    {
        loc_eng_data.engine_status = status;
    }

    // Only keeps SESSION BEGIN/END in fix_session_status
    if (status == GPS_STATUS_SESSION_BEGIN || status == GPS_STATUS_SESSION_END)
    {
        loc_eng_data.fix_session_status = status;
    }
    EXIT_LOG(%s, VOID_RET);
}

/*===========================================================================
FUNCTION loc_eng_handle_engine_down
         loc_eng_handle_engine_up

DESCRIPTION
   Calls this function when it is detected that modem restart is happening.
   Either we detected the modem is down or received modem up event.
   This must be called from the deferred thread to avoid race condition.

DEPENDENCIES
   None

RETURN VALUE
   None

SIDE EFFECTS
   N/A

===========================================================================*/
void loc_eng_handle_engine_down(loc_eng_data_s_type &loc_eng_data)
{
    ENTRY_LOG();
    loc_eng_ni_reset_on_engine_restart(loc_eng_data);
    loc_eng_report_status(loc_eng_data, GPS_STATUS_ENGINE_OFF);
    EXIT_LOG(%s, VOID_RET);
}

void loc_eng_handle_engine_up(loc_eng_data_s_type &loc_eng_data)
{
    ENTRY_LOG();
    loc_eng_reinit(loc_eng_data);

    if (loc_eng_data.agps_status_cb != NULL) {
        loc_eng_data.agnss_nif->dropAllSubscribers();
        loc_eng_data.internet_nif->dropAllSubscribers();

        loc_eng_agps_reinit(loc_eng_data);
    }

    loc_eng_report_status(loc_eng_data, GPS_STATUS_ENGINE_ON);

    // modem is back up.  If we crashed in the middle of navigating, we restart.
    if (loc_eng_data.client_handle->isInSession()) {
        // This sets the copy in adapter to modem
        loc_eng_data.client_handle->setPositionMode(NULL);
        loc_eng_data.client_handle->setInSession(false);
        loc_eng_start_handler(loc_eng_data);
    }
    EXIT_LOG(%s, VOID_RET);
}

/*===========================================================================
FUNCTION loc_eng_deferred_action_thread

DESCRIPTION
   Main routine for the thread to execute loc_eng commands.

DEPENDENCIES
   None

RETURN VALUE
   None

SIDE EFFECTS
   N/A

===========================================================================*/
static void loc_eng_deferred_action_thread(void* arg)
{
    ENTRY_LOG();
    loc_eng_msg *msg;
    static int cnt = 0;
    LocEngContext* context = (LocEngContext*)arg;

    // make sure we do not run in background scheduling group
    set_sched_policy(gettid(), SP_FOREGROUND);

    while (1)
    {
        LOC_LOGD("%s:%d] %d listening ...\n", __func__, __LINE__, cnt++);

        // we are only sending / receiving msg pointers
        msq_q_err_type result = msg_q_rcv((void*)context->deferred_q, (void **) &msg);
        if (eMSG_Q_SUCCESS != result) {
            LOC_LOGE("%s:%d] fail receiving msg: %s\n", __func__, __LINE__,
                     loc_get_msg_q_status(result));
            return;
        }

        loc_eng_data_s_type* loc_eng_data_p = (loc_eng_data_s_type*)msg->owner;

        LOC_LOGD("%s:%d] received msg_id = %s context = %p\n",
                 __func__, __LINE__, loc_get_msg_name(msg->msgid), loc_eng_data_p->context);

        // need to ensure the instance data is valid
        STATE_CHECK(NULL != loc_eng_data_p->context,
                    "instance cleanup happened",
                    delete msg; return);

        switch(msg->msgid) {
        case LOC_ENG_MSG_QUIT:
        {
            LocEngContext* context = (LocEngContext*)loc_eng_data_p->context;
            pthread_mutex_lock(&(context->lock));
            pthread_cond_signal(&(context->cond));
            pthread_mutex_unlock(&(context->lock));
            EXIT_LOG(%s, "LOC_ENG_MSG_QUIT, signal the main thread and return");
        }
        return;

        case LOC_ENG_MSG_REQUEST_NI:
        {
            loc_eng_msg_request_ni *niMsg = (loc_eng_msg_request_ni*)msg;
            loc_eng_ni_request_handler(*loc_eng_data_p, &niMsg->notify, niMsg->passThroughData);
        }
        break;

        case LOC_ENG_MSG_INFORM_NI_RESPONSE:
        {
            loc_eng_msg_inform_ni_response *nrMsg = (loc_eng_msg_inform_ni_response*)msg;
            loc_eng_data_p->client_handle->informNiResponse(nrMsg->response,
                                                            nrMsg->passThroughData);
        }
        break;

        case LOC_ENG_MSG_START_FIX:
            loc_eng_start_handler(*loc_eng_data_p);
            break;

        case LOC_ENG_MSG_STOP_FIX:
            if (loc_eng_data_p->agps_request_pending)
            {
                loc_eng_data_p->stop_request_pending = true;
                LOC_LOGD("loc_eng_stop - deferring stop until AGPS data call is finished\n");
            } else {
                loc_eng_stop_handler(*loc_eng_data_p);
            }
            break;

        case LOC_ENG_MSG_SET_POSITION_MODE:
        {
            loc_eng_msg_position_mode *pmMsg = (loc_eng_msg_position_mode*)msg;
            loc_eng_data_p->client_handle->setPositionMode(&(pmMsg->pMode));
        }
        break;

        case LOC_ENG_MSG_SET_TIME:
        {
            loc_eng_msg_set_time *tMsg = (loc_eng_msg_set_time*)msg;
            loc_eng_data_p->client_handle->setTime(tMsg->time, tMsg->timeReference,
                                                   tMsg->uncertainty);
        }
        break;

        case LOC_ENG_MSG_INJECT_LOCATION:
        {
            loc_eng_msg_inject_location *ilMsg = (loc_eng_msg_inject_location*) msg;
            loc_eng_data_p->client_handle->injectPosition(ilMsg->latitude, ilMsg->longitude,
                                                          ilMsg->accuracy);
        }
        break;

        case LOC_ENG_MSG_SET_SERVER_IPV4:
        {
            loc_eng_msg_set_server_ipv4 *ssiMsg = (loc_eng_msg_set_server_ipv4*)msg;
            loc_eng_data_p->client_handle->setServer(ssiMsg->nl_addr,
                                                     ssiMsg->port,
                                                     ssiMsg->serverType);
        }
        break;

        case LOC_ENG_MSG_SET_SERVER_URL:
        {
            loc_eng_msg_set_server_url *ssuMsg = (loc_eng_msg_set_server_url*)msg;
            loc_eng_data_p->client_handle->setServer(ssuMsg->url, ssuMsg->len);
        }
        break;

        case LOC_ENG_MSG_SUPL_VERSION:
        {
            loc_eng_msg_suple_version *svMsg = (loc_eng_msg_suple_version*)msg;
            loc_eng_data_p->client_handle->setSUPLVersion(svMsg->supl_version);
        }
        break;

        case LOC_ENG_MSG_LPP_CONFIG:
        {
            loc_eng_msg_lpp_config *svMsg = (loc_eng_msg_lpp_config*)msg;
            loc_eng_data_p->client_handle->setLPPConfig(svMsg->lpp_config);
        }
        break;

        case LOC_ENG_MSG_SET_SENSOR_CONTROL_CONFIG:
        {
            loc_eng_msg_sensor_control_config *sccMsg = (loc_eng_msg_sensor_control_config*)msg;
            loc_eng_data_p->client_handle->setSensorControlConfig(sccMsg->sensorsDisabled);
        }
        break;

        case LOC_ENG_MSG_SET_SENSOR_PROPERTIES:
        {
            loc_eng_msg_sensor_properties *spMsg = (loc_eng_msg_sensor_properties*)msg;
            loc_eng_data_p->client_handle->setSensorProperties(spMsg->gyroBiasVarianceRandomWalk_valid,
                                                               spMsg->gyroBiasVarianceRandomWalk,
                                                               spMsg->accelRandomWalk_valid,
                                                               spMsg->accelRandomWalk,
                                                               spMsg->angleRandomWalk_valid,
                                                               spMsg->angleRandomWalk,
                                                               spMsg->rateRandomWalk_valid,
                                                               spMsg->rateRandomWalk,
                                                               spMsg->velocityRandomWalk_valid,
                                                               spMsg->velocityRandomWalk);
        }
        break;

        case LOC_ENG_MSG_SET_SENSOR_PERF_CONTROL_CONFIG:
        {
            loc_eng_msg_sensor_perf_control_config *spccMsg = (loc_eng_msg_sensor_perf_control_config*)msg;
            loc_eng_data_p->client_handle->setSensorPerfControlConfig(spccMsg->controlMode, spccMsg->accelSamplesPerBatch, spccMsg->accelBatchesPerSec,
                                                                      spccMsg->gyroSamplesPerBatch, spccMsg->gyroBatchesPerSec,
                                                                      spccMsg->accelSamplesPerBatchHigh, spccMsg->accelBatchesPerSecHigh,
                                                                      spccMsg->gyroSamplesPerBatchHigh, spccMsg->gyroBatchesPerSecHigh,
                                                                      spccMsg->algorithmConfig);
        }
        break;

        case LOC_ENG_MSG_EXT_POWER_CONFIG:
        {
            loc_eng_msg_ext_power_config *pwrMsg = (loc_eng_msg_ext_power_config*)msg;
            loc_eng_data_p->client_handle->setExtPowerConfig(pwrMsg->isBatteryCharging);
        }
        break;

        case LOC_ENG_MSG_REPORT_POSITION:
            if (loc_eng_data_p->mute_session_state != LOC_MUTE_SESS_IN_SESSION)
            {
                bool reported = false;
                loc_eng_msg_report_position *rpMsg = (loc_eng_msg_report_position*)msg;
                if (loc_eng_data_p->location_cb != NULL) {
                    if (LOC_SESS_FAILURE == rpMsg->status) {
                        // in case we want to handle the failure case
                        loc_eng_data_p->location_cb(NULL, NULL);
                        reported = true;
                    }
                    // what's in the else if is... (line by line)
                    // 1. this is a good fix; or
                    //   1.1 there is source info; or
                    //   1.1.1 this is from hybrid provider;
                    //   1.2 it is a Satellite fix; or
                    //   1.2.1 it is a sensor fix
                    // 2. (must be intermediate fix... implicit)
                    //   2.1 we accepte intermediate; and
                    //   2.2 it is NOT the case that
                    //   2.2.1 there is inaccuracy; and
                    //   2.2.2 we care about inaccuracy; and
                    //   2.2.3 the inaccuracy exceeds our tolerance
                    else if ((LOC_SESS_SUCCESS == rpMsg->status &&
                              (((LOCATION_HAS_SOURCE_INFO & rpMsg->location.flags) &&
                                ULP_LOCATION_IS_FROM_HYBRID == rpMsg->location.position_source) ||
                               ((LOC_POS_TECH_MASK_SATELLITE & rpMsg->technology_mask) ||
                                (LOC_POS_TECH_MASK_SENSORS & rpMsg->technology_mask)))) ||
                             (LOC_SESS_INTERMEDIATE == loc_eng_data_p->intermediateFix &&
                              !((rpMsg->location.flags & GPS_LOCATION_HAS_ACCURACY) &&
                                (gps_conf.ACCURACY_THRES != 0) &&
                                (rpMsg->location.accuracy > gps_conf.ACCURACY_THRES)))) {
                        loc_eng_data_p->location_cb((GpsLocation*)&(rpMsg->location),
                                                    (void*)rpMsg->locationExt);
                        reported = true;
                    }
                }

                // if we have reported this fix
                if (reported &&
                    // and if this is a singleshot
                    GPS_POSITION_RECURRENCE_SINGLE ==
                    loc_eng_data_p->client_handle->getPositionMode().recurrence) {
                    if (LOC_SESS_INTERMEDIATE == rpMsg->status) {
                        // modem could be still working for a final fix,
                        // although we no longer need it.  So stopFix().
                        loc_eng_data_p->client_handle->stopFix();
                    }
                    // turn off the session flag.
                    loc_eng_data_p->client_handle->setInSession(false);
                }

                if (loc_eng_data_p->generateNmea && rpMsg->location.position_source == ULP_LOCATION_IS_FROM_GNSS)
                {
                    loc_eng_nmea_generate_pos(loc_eng_data_p, rpMsg->location, rpMsg->locationExtended);
                }

                // Free the allocated memory for rawData
                GpsLocation* gp = (GpsLocation*)&(rpMsg->location);
                if (gp != NULL && gp->rawData != NULL)
                {
                    delete (char*)gp->rawData;
                    gp->rawData = NULL;
                    gp->rawDataSize = 0;
                }
            }

            break;

        case LOC_ENG_MSG_REPORT_SV:
            if (loc_eng_data_p->mute_session_state != LOC_MUTE_SESS_IN_SESSION)
            {
                loc_eng_msg_report_sv *rsMsg = (loc_eng_msg_report_sv*)msg;
                if (loc_eng_data_p->sv_status_cb != NULL) {
                    loc_eng_data_p->sv_status_cb((GpsSvStatus*)&(rsMsg->svStatus),
                                                 (void*)rsMsg->svExt);
                }

                if (loc_eng_data_p->generateNmea)
                {
                    loc_eng_nmea_generate_sv(loc_eng_data_p, rsMsg->svStatus, rsMsg->locationExtended);
                }

            }
            break;

        case LOC_ENG_MSG_REPORT_STATUS:
            loc_eng_report_status(*loc_eng_data_p, ((loc_eng_msg_report_status*)msg)->status);
            break;

        case LOC_ENG_MSG_REPORT_NMEA:
            if (NULL != loc_eng_data_p->nmea_cb) {
                loc_eng_msg_report_nmea* nmMsg = (loc_eng_msg_report_nmea*)msg;
                struct timeval tv;
                gettimeofday(&tv, (struct timezone *) NULL);
                int64_t now = tv.tv_sec * 1000LL + tv.tv_usec / 1000;
                CALLBACK_LOG_CALLFLOW("nmea_cb", %p, nmMsg->nmea);
                loc_eng_data_p->nmea_cb(now, nmMsg->nmea, nmMsg->length);
            }
            break;

        case LOC_ENG_MSG_REQUEST_BIT:
        {
            AgpsStateMachine* stateMachine;
            loc_eng_msg_request_bit* brqMsg = (loc_eng_msg_request_bit*)msg;
            if (brqMsg->ifType == LOC_ENG_IF_REQUEST_TYPE_SUPL) {
                stateMachine = loc_eng_data_p->agnss_nif;
            } else if (brqMsg->ifType == LOC_ENG_IF_REQUEST_TYPE_ANY) {
                stateMachine = loc_eng_data_p->internet_nif;
            } else {
                LOC_LOGD("%s]%d: unknown I/F request type = 0x%x\n", __func__, __LINE__, brqMsg->ifType);
                break;
            }
            BITSubscriber subscriber(stateMachine, brqMsg->ipv4Addr, brqMsg->ipv6Addr);

            stateMachine->subscribeRsrc((Subscriber*)&subscriber);
        }
        break;

        case LOC_ENG_MSG_RELEASE_BIT:
        {
            AgpsStateMachine* stateMachine;
            loc_eng_msg_release_bit* brlMsg = (loc_eng_msg_release_bit*)msg;
            if (brlMsg->ifType == LOC_ENG_IF_REQUEST_TYPE_SUPL) {
                stateMachine = loc_eng_data_p->agnss_nif;
            } else if (brlMsg->ifType == LOC_ENG_IF_REQUEST_TYPE_ANY) {
                stateMachine = loc_eng_data_p->internet_nif;
            } else {
                LOC_LOGD("%s]%d: unknown I/F request type = 0x%x\n", __func__, __LINE__, brlMsg->ifType);
                break;
            }
            BITSubscriber subscriber(stateMachine, brlMsg->ipv4Addr, brlMsg->ipv6Addr);

            stateMachine->unsubscribeRsrc((Subscriber*)&subscriber);
        }
        break;

        case LOC_ENG_MSG_REQUEST_ATL:
        {
            loc_eng_msg_request_atl* arqMsg = (loc_eng_msg_request_atl*)msg;
            boolean backwardCompatibleMode = AGPS_TYPE_INVALID == arqMsg->type;
            AgpsStateMachine* stateMachine = (AGPS_TYPE_SUPL == arqMsg->type ||
                                              backwardCompatibleMode) ?
                                             loc_eng_data_p->agnss_nif :
                                             loc_eng_data_p->internet_nif;
            ATLSubscriber subscriber(arqMsg->handle,
                                     stateMachine,
                                     loc_eng_data_p->client_handle,
                                     backwardCompatibleMode);

            stateMachine->subscribeRsrc((Subscriber*)&subscriber);
        }
        break;

        case LOC_ENG_MSG_RELEASE_ATL:
        {
            loc_eng_msg_release_atl* arlMsg = (loc_eng_msg_release_atl*)msg;
            ATLSubscriber s1(arlMsg->handle,
                             loc_eng_data_p->agnss_nif,
                             loc_eng_data_p->client_handle,
                             false);
            // attempt to unsubscribe from agnss_nif first
            if (! loc_eng_data_p->agnss_nif->unsubscribeRsrc((Subscriber*)&s1)) {
                ATLSubscriber s2(arlMsg->handle,
                                 loc_eng_data_p->internet_nif,
                                 loc_eng_data_p->client_handle,
                                 false);
                // if unsuccessful, try internet_nif
                loc_eng_data_p->internet_nif->unsubscribeRsrc((Subscriber*)&s2);
            }
        }
        break;

        case LOC_ENG_MSG_REQUEST_WIFI:
        {
            loc_eng_msg_request_wifi *wrqMsg = (loc_eng_msg_request_wifi *)msg;
            if (wrqMsg->senderId == LOC_ENG_IF_REQUEST_SENDER_ID_QUIPC ||
                wrqMsg->senderId == LOC_ENG_IF_REQUEST_SENDER_ID_MSAPM ||
                wrqMsg->senderId == LOC_ENG_IF_REQUEST_SENDER_ID_MSAPU) {
              AgpsStateMachine* stateMachine = loc_eng_data_p->wifi_nif;
              WIFISubscriber subscriber(stateMachine, wrqMsg->ssid, wrqMsg->password, wrqMsg->senderId);
              stateMachine->subscribeRsrc((Subscriber*)&subscriber);
            } else {
              LOC_LOGE("%s]%d ERROR: unknown sender ID", __func__, __LINE__);
              break;
            }
        }
        break;

        case LOC_ENG_MSG_RELEASE_WIFI:
        {
            AgpsStateMachine* stateMachine = loc_eng_data_p->wifi_nif;
            loc_eng_msg_release_wifi* wrlMsg = (loc_eng_msg_release_wifi*)msg;
            WIFISubscriber subscriber(stateMachine, wrlMsg->ssid, wrlMsg->password, wrlMsg->senderId);
            stateMachine->unsubscribeRsrc((Subscriber*)&subscriber);
        }
        break;

        case LOC_ENG_MSG_REQUEST_XTRA_DATA:
            if (loc_eng_data_p->xtra_module_data.download_request_cb != NULL)
            {
                loc_eng_data_p->xtra_module_data.download_request_cb();
            }
            break;

        case LOC_ENG_MSG_REQUEST_TIME:
            if (loc_eng_data_p->request_utc_time_cb != NULL)
            {
                loc_eng_data_p->request_utc_time_cb();
            }
            else
            {
                LOC_LOGE("%s] ERROR: Callback function for request_time is NULL", __func__);
            }
            break;

        case LOC_ENG_MSG_REQUEST_POSITION:
            break;

        case LOC_ENG_MSG_DELETE_AIDING_DATA:
            loc_eng_data_p->aiding_data_for_deletion |= ((loc_eng_msg_delete_aiding_data*)msg)->type;
            break;

        case LOC_ENG_MSG_ENABLE_DATA:
        {
            loc_eng_msg_set_data_enable *unaMsg = (loc_eng_msg_set_data_enable*)msg;
            loc_eng_data_p->client_handle->enableData(unaMsg->enable);
            loc_eng_data_p->client_handle->setAPN(unaMsg->apn, unaMsg->length);
        }
        break;

        case LOC_ENG_MSG_INJECT_XTRA_DATA:
        {
            loc_eng_msg_inject_xtra_data *xdMsg = (loc_eng_msg_inject_xtra_data*)msg;
            loc_eng_data_p->client_handle->setXtraData(xdMsg->data, xdMsg->length);
        }
        break;

        case LOC_ENG_MSG_ATL_OPEN_SUCCESS:
        {
            loc_eng_msg_atl_open_success *aosMsg = (loc_eng_msg_atl_open_success*)msg;
            AgpsStateMachine* stateMachine;
            switch (aosMsg->agpsType) {
              case AGPS_TYPE_WIFI: {
                stateMachine = loc_eng_data_p->wifi_nif;
                break;
              }
              case AGPS_TYPE_SUPL: {
                stateMachine = loc_eng_data_p->agnss_nif;
                break;
              }
              default: {
                stateMachine  = loc_eng_data_p->internet_nif;
              }
            }

            stateMachine->setBearer(aosMsg->bearerType);
            stateMachine->setAPN(aosMsg->apn, aosMsg->length);
            stateMachine->onRsrcEvent(RSRC_GRANTED);
        }
        break;

        case LOC_ENG_MSG_ATL_CLOSED:
        {
            loc_eng_msg_atl_closed *acsMsg = (loc_eng_msg_atl_closed*)msg;
            AgpsStateMachine* stateMachine;
            switch (acsMsg->agpsType) {
              case AGPS_TYPE_WIFI: {
                stateMachine = loc_eng_data_p->wifi_nif;
                break;
              }
              case AGPS_TYPE_SUPL: {
                stateMachine = loc_eng_data_p->agnss_nif;
                break;
              }
              default: {
                stateMachine  = loc_eng_data_p->internet_nif;
              }
            }

            stateMachine->onRsrcEvent(RSRC_RELEASED);
        }
        break;

        case LOC_ENG_MSG_ATL_OPEN_FAILED:
        {
            loc_eng_msg_atl_open_failed *aofMsg = (loc_eng_msg_atl_open_failed*)msg;
            AgpsStateMachine* stateMachine;
            switch (aofMsg->agpsType) {
              case AGPS_TYPE_WIFI: {
                stateMachine = loc_eng_data_p->wifi_nif;
                break;
              }
              case AGPS_TYPE_SUPL: {
                stateMachine = loc_eng_data_p->agnss_nif;
                break;
              }
              default: {
                stateMachine  = loc_eng_data_p->internet_nif;
              }
            }

            stateMachine->onRsrcEvent(RSRC_DENIED);
        }
        break;

        case LOC_ENG_MSG_ENGINE_DOWN:
            loc_eng_handle_engine_down(*loc_eng_data_p);
            break;

        case LOC_ENG_MSG_ENGINE_UP:
            loc_eng_handle_engine_up(*loc_eng_data_p);
            break;

        case LOC_ENG_MSG_REQUEST_NETWORK_POSIITON:
        {
            loc_eng_msg_request_network_position *nlprequestmsg = (loc_eng_msg_request_network_position*)msg;
            //loc_eng_handle_request_network_position(nlprequestmsg );
            LOC_LOGD("Received n/w position request from ULP.Request type %d Periodicity: %d\n",
                     nlprequestmsg->networkPosRequest.request_type,
                      nlprequestmsg->networkPosRequest.interval_ms);
            if(loc_eng_data_p->ulp_network_callback != NULL)
            {
                loc_eng_data_p->ulp_network_callback((UlpNetworkRequestPos*)&(nlprequestmsg->networkPosRequest));
            }
            else
                LOC_LOGE("Ulp Network call back not initialized");
        }
        break;

        case LOC_ENG_MSG_REQUEST_PHONE_CONTEXT:
        {
            loc_eng_msg_request_phone_context *contextReqMsg = (loc_eng_msg_request_phone_context*)msg;
            LOC_LOGD("Received phone context request from ULP.context_type 0x%x,request_type 0x%x  ",
                     contextReqMsg->contextRequest.context_type,contextReqMsg->contextRequest.request_type)
            if(loc_eng_data_p->ulp_phone_context_req_cb != NULL)
            {
                loc_eng_data_p->ulp_phone_context_req_cb((UlpPhoneContextRequest*)&(contextReqMsg->contextRequest));
            }
            else
                LOC_LOGE("Ulp Phone context request call back not initialized");
            }
        break;

        case LOC_ENG_MSG_PRIVACY:
        {
            loc_eng_msg_privacy *privacyMsg = (loc_eng_msg_privacy*)msg;
#ifdef SET_PRIVACY
            loc_eng_data_p->client_handle->setPrivacy(privacyMsg->privacy_setting);
#else
            LOC_LOGE("Ignoring call to setPrivacy");
#endif
        }
        break;

        default:
            LOC_LOGE("unsupported msgid = %d\n", msg->msgid);
            break;
        }

        if ( (msg->msgid == LOC_ENG_MSG_ATL_OPEN_FAILED)  |
             (msg->msgid == LOC_ENG_MSG_ATL_CLOSED)  |
             (msg->msgid == LOC_ENG_MSG_ATL_OPEN_SUCCESS) )
        {
            loc_eng_data_p->agps_request_pending = false;
            if (loc_eng_data_p->stop_request_pending) {
                loc_eng_stop_handler(*loc_eng_data_p);
                loc_eng_data_p->stop_request_pending = false;
            }
        }
        loc_eng_data_p->stop_request_pending = false;

        if (loc_eng_data_p->engine_status != GPS_STATUS_ENGINE_ON &&
            loc_eng_data_p->aiding_data_for_deletion != 0)
        {
            loc_eng_data_p->client_handle->deleteAidingData(loc_eng_data_p->aiding_data_for_deletion);
            loc_eng_data_p->aiding_data_for_deletion = 0;
        }

        delete msg;
    }

    EXIT_LOG(%s, VOID_RET);
}

/*===========================================================================
FUNCTION loc_eng_ulp_init

DESCRIPTION
   This function dynamically loads the libulp.so and calls
   its init function to start up the ulp module

DEPENDENCIES
   None

RETURN VALUE
   0: no error
   -1: errors

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_ulp_init(loc_eng_data_s_type &loc_eng_data, const ulpInterface * loc_eng_ulpInf)
{
    ENTRY_LOG();
    int ret_val=-1;
    if((loc_eng_ulpInf != NULL) && (((ulpInterface *)loc_eng_ulpInf)->init != NULL))
    {
        // Initialize the ULP interface
        ((ulpInterface *)loc_eng_ulpInf)->init(loc_eng_data);
        loc_eng_data.ulp_initialized = TRUE;
        ret_val = 0;
    }
    else
        LOC_LOGE("ulp not initialized. NULL parameter");
    EXIT_LOG(%d, ret_val);
    return ret_val;
}

/*===========================================================================
FUNCTION    loc_eng_inject_raw_command

DESCRIPTION
   This is used to send special test modem commands from the applications
   down into the HAL
DEPENDENCIES
   N/A

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
bool loc_eng_inject_raw_command(loc_eng_data_s_type &loc_eng_data,
                                char* command, int length)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return -1);
    boolean ret_val;
    LOC_LOGD("loc_eng_send_extra_command: %s\n", command);
    ret_val = TRUE;

    if((loc_eng_data.ulp_initialized == true) && (gps_conf.CAPABILITIES & ULP_CAPABILITY))
    {
        ulp_msg_inject_raw_command *msg(
            new ulp_msg_inject_raw_command(&loc_eng_data,command, length));
        msg_q_snd( (void*)((LocEngContext*)(loc_eng_data.context))->ulp_q
                   , msg, loc_eng_free_msg);
        ret_val = 0;
    }else
    {
        ret_val = -1;
    }


    EXIT_LOG(%s, loc_logger_boolStr[ret_val!=0]);
    return ret_val;
}
/*===========================================================================
FUNCTION    loc_eng_update_criteria

DESCRIPTION
   This is used to inform the ULP module of new unique criteria that are passed
   in by the applications
DEPENDENCIES
   N/A

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_update_criteria(loc_eng_data_s_type &loc_eng_data,
                            UlpLocationCriteria criteria)
{
    ENTRY_LOG_CALLFLOW();
    INIT_CHECK(loc_eng_data.context, return -1);
    int ret_val;

    if((loc_eng_data.ulp_initialized == true) && (gps_conf.CAPABILITIES & ULP_CAPABILITY))
    {
       LOC_LOGD("SJ:loc_eng_update_criteria: valid 0x%x action:%d, minTime:%ld, minDistance:%f, singleShot:%d, horizontalAccuracy:%d, powerRequirement:%d \n",
         criteria.valid_mask, criteria.action, criteria.min_interval, criteria.min_distance,  criteria.recurrence_type,  criteria.preferred_horizontal_accuracy,
              criteria.preferred_power_consumption );
     ulp_msg_update_criteria *msg(
         new ulp_msg_update_criteria(&loc_eng_data,criteria));
     msg_q_snd( (void*)((LocEngContext*)(loc_eng_data.context))->ulp_q
                , msg, loc_eng_free_msg);
     ret_val = 0;
    }else
    {
        ret_val = -1;
    }
    EXIT_LOG(%d, ret_val);
    return ret_val;
}

/*===========================================================================
FUNCTION    loc_eng_ulp_phone_context_settings_update

DESCRIPTION
   This is used to inform the ULP module of phone settings changes carried out
   by the users
DEPENDENCIES
   N/A

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/

int loc_eng_ulp_phone_context_settings_update(loc_eng_data_s_type &loc_eng_data,
                                              UlpPhoneContextSettings *settings)
{
    ENTRY_LOG();
    int ret_val = -1;

    LOC_LOGD("loc_eng_ulp_phone_context_settings: context_type - 0x%x is_agps_enabled - %d "
             "is_battery_charging %d ,is_gps_enabled %d, is_network_position_available %d,"
             "is_wifi_setting_enabled %d, is_agps_setting_enabled %d, is_enh_location_services_enabled %d\n",
             settings->context_type ,settings->is_agps_enabled,settings->is_battery_charging,
             settings->is_gps_enabled, settings->is_network_position_available,
             settings->is_wifi_setting_enabled, settings->is_agps_enabled,
             settings->is_enh_location_services_enabled );

    if((loc_eng_data.ulp_initialized == true) && (gps_conf.CAPABILITIES & ULP_CAPABILITY))
    {
        ulp_msg_inject_phone_context_settings *msg
         (new ulp_msg_inject_phone_context_settings(&loc_eng_data, *settings));
        msg_q_snd( (void*)((LocEngContext*)(loc_eng_data.context))->ulp_q, msg, loc_eng_free_msg);
        ret_val = 0;
    }

    // Send battery information to modem for processing.
    if(settings->context_type & ULP_PHONE_CONTEXT_BATTERY_CHARGING_STATE)
    {
        loc_eng_msg_ext_power_config *msg(new loc_eng_msg_ext_power_config(&loc_eng_data, settings->is_battery_charging));
        msg_q_snd( (void*)((LocEngContext*)(loc_eng_data.context))->deferred_q, msg, loc_eng_free_msg);
    }

    EXIT_LOG(%d, ret_val);
    return ret_val;
}
/*===========================================================================
FUNCTION    loc_eng_ulp_network_init

DESCRIPTION
   Initialize the ULP network interface.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_ulp_phone_context_init(loc_eng_data_s_type &loc_eng_data,UlpPhoneContextCallbacks *callback)
{
    int ret_val = -1;
    ENTRY_LOG();
    if(callback != NULL) {
        loc_eng_data.ulp_phone_context_req_cb = callback->ulp_request_phone_context_cb ;
        ret_val = 0;
    }
    else
        LOC_LOGE("loc_eng_ulp_phone_context_init: bad parameters cb %p", callback);
    EXIT_LOG(%d, ret_val);
    return ret_val;
}

/*===========================================================================
FUNCTION    loc_eng_ulp_network_init

DESCRIPTION
   Initialize the ULP network interface.

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_ulp_network_init(loc_eng_data_s_type &loc_eng_data,
                             UlpNetworkLocationCallbacks *callbacks)
{
    int ret_val = -1;
    ENTRY_LOG_CALLFLOW();
    if(callbacks != NULL) {
        loc_eng_data.ulp_network_callback = callbacks->ulp_network_location_request_cb;
        ret_val = 0;
    }
    else
        LOC_LOGE("loc_eng_ulp_network_init: bad parameters cb %p", callbacks);
    EXIT_LOG(%d, ret_val);
    return ret_val;
}


/*===========================================================================
FUNCTION    loc_eng_ulp_send_network_position

DESCRIPTION
   Ulp send data

DEPENDENCIES
   NONE

RETURN VALUE
   0

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_ulp_send_network_position(loc_eng_data_s_type &loc_eng_data,
                                             UlpNetworkPositionReport *position_report)
{
    ENTRY_LOG();
    int ret_val = 0;
    if((loc_eng_data.ulp_initialized == true) && (gps_conf.CAPABILITIES & ULP_CAPABILITY))
    {
     ulp_msg_inject_network_position *msg
         (new ulp_msg_inject_network_position(&loc_eng_data, *position_report));
     msg_q_snd( (void*)((LocEngContext*)(loc_eng_data.context))->ulp_q
                , msg, loc_eng_free_msg);
     ret_val = 0;
    }else
    {
        ret_val = -1;
    }
    EXIT_LOG(%d, ret_val);
    return ret_val;
}
/*===========================================================================
FUNCTION    loc_eng_read_config

DESCRIPTION
   Initiates the reading of the gps config file stored in /etc dir

DEPENDENCIES
   None

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
int loc_eng_read_config(void)
{
    ENTRY_LOG_CALLFLOW();
    if(gpsConfigAlreadyRead == false)
    {
      // Initialize our defaults before reading of configuration file overwrites them.
      loc_default_parameters();
      // Ee only want to parse the conf file once. This is a good place to ensure that.
      // In fact one day the conf file should go into context.
      UTIL_READ_CONF(GPS_CONF_FILE, loc_parameter_table);
      gpsConfigAlreadyRead = true;
    } else {
      LOC_LOGV("GPS Config file has already been read\n");
    }

    EXIT_LOG(%d, 0);
    return 0;
}

/*===========================================================================
FUNCTION    loc_eng_set_privacy

DESCRIPTION
   Sets the privacy lock setting (1. GPS on, 0. GPS off).

DEPENDENCIES
   None

RETURN VALUE
   0: success

SIDE EFFECTS
   N/A

===========================================================================*/
static int loc_eng_set_privacy(loc_eng_data_s_type &loc_eng_data,
                               int8_t privacy_setting)
{
    ENTRY_LOG();
    INIT_CHECK(loc_eng_data.context, return -1);
#ifdef SET_PRIVACY
    loc_eng_msg_privacy *msg(
        new loc_eng_msg_privacy(&loc_eng_data, privacy_setting));
    msg_q_snd((void*)((LocEngContext*)(loc_eng_data.context))->deferred_q,
              msg, loc_eng_free_msg);
#endif
    EXIT_LOG(%d, 0);
    return 0;
}