aboutsummaryrefslogtreecommitdiff
path: root/u300-ril.c
blob: e14fbd2d81fea5037521ed3a91cd0e06de5fa9c5 (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
/*
 * ST-Ericsson U300 RIL
 *
 * Copyright (C) ST-Ericsson AB 2008-2011
 * Copyright 2006, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Based on reference-ril by The Android Open Source Project.
 *
 * Heavily modified for ST-Ericsson modems.
 * Author: Christian Bejram <christian.bejram@stericsson.com>
 * Author: Sverre Vegge <sverre.vegge@stericsson.com>
 */

#include <cutils/properties.h>
#include <telephony/ril.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <alloca.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <cutils/sockets.h>
#include <termios.h>
#include <stdbool.h>
#ifndef CAIF_SOCKET_SUPPORT_DISABLED
#include <linux/errno.h>
#include <linux/caif/caif_socket.h>
#include <linux/rtnetlink.h>
#endif

#include "atchannel.h"
#include "at_tok.h"
#include "misc.h"

#include "u300-ril.h"
#include "u300-ril-callhandling.h"
#include "u300-ril-messaging.h"
#include "u300-ril-network.h"
#include "u300-ril-pdp.h"
#include "u300-ril-services.h"
#include "u300-ril-sim.h"
#include "u300-ril-stk.h"
#include "u300-ril-oem.h"
#include "u300-ril-requestdatahandler.h"
#include "u300-ril-audio.h"
#include "u300-ril-information.h"

#define LOG_TAG "RILV"
#include <utils/Log.h>

#define RIL_VERSION_STRING  "ST-Ericsson u300-ril Gingerbread"

#define timespec_cmp(a, b, op)   \
    ((a).tv_sec == (b).tv_sec    \
     ? (a).tv_nsec op(b).tv_nsec \
     : (a).tv_sec op(b).tv_sec)

/*** MUTEX declarations ***/
/* Mutex used to synchronize startup of RIL queueRunners from RIL manager */
bool g_managerRelease = false;
pthread_mutex_t ril_manager_queue_startup_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ril_manager_queue_startup_cond = PTHREAD_COND_INITIALIZER;

/* Mutex used to synchronize exit of RIL queueRunners to RIL manager */
pthread_mutex_t ril_manager_queue_exit_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ril_manager_queue_exit_cond = PTHREAD_COND_INITIALIZER;

/* Mutex used to synchronize startup between multiple RIL queueRunners. */
bool defaultQueueReady = false;
static pthread_mutex_t ril_queue_synch_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t ril_queue_synch_cond = PTHREAD_COND_INITIALIZER;

/* Mutex used to synchronize RIL state varilable changes */
static pthread_mutex_t s_state_mutex = PTHREAD_MUTEX_INITIALIZER;

/* Mutex used to synchronize screen state variable changes */
static pthread_mutex_t s_screen_state_mutex = PTHREAD_MUTEX_INITIALIZER;

/* Mutex used to synchronize system shutdown with Dbus 'OFF' message */
bool g_offSignalReceived = false;
pthread_mutex_t ril_system_shutdown_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ril_system_shutdown_cond = PTHREAD_COND_INITIALIZER;

/*** Declarations ***/
static void onRequest(int request, void *data, size_t datalen,
                      RIL_Token t);
static int supports(int requestCode);
static void onCancel(RIL_Token t);
static const char *getVersion(void);
static int isRadioOn(void);
static void signalManager(void);
extern const char *requestToString(int request);

static RIL_RadioState onStateRequest(void);

/*** Static Variables ***/
const RIL_RadioFunctions g_callbacks = {
    RIL_VERSION,
    onRequest,
    onStateRequest,
    supports,
    onCancel,
    getVersion
};

char ril_iface[MAX_IFNAME_LEN] = "";
const struct RIL_Env *s_rilenv;

static RIL_RadioState s_state = RADIO_STATE_OFF; /* Static allowed */
static int s_queueRuns = 0; /* Static allowed */

/*****************************************************/
/* Controlled static state variables - section start */
/*****************************************************/
#define __s_restrictedState RIL_RESTRICTED_STATE_NONE
static int s_restrictedState = __s_restrictedState;
/*****************************************************/
/* Controlled static state variables - section end   */
/*****************************************************/

static RequestQueue s_requestQueueDefault = {
    .queueMutex = PTHREAD_MUTEX_INITIALIZER,
    .cond = PTHREAD_COND_INITIALIZER,
    .requestList = NULL,
    .eventList = NULL,
    .enabled = 0,
    .closed = 1
};

static RequestQueue s_requestQueueAuxiliary = {
    .queueMutex = PTHREAD_MUTEX_INITIALIZER,
    .cond = PTHREAD_COND_INITIALIZER,
    .requestList = NULL,
    .eventList = NULL,
    .enabled = 0,
    .closed = 1
};

static RequestQueue *s_requestQueues[] = {
    &s_requestQueueDefault,
    &s_requestQueueAuxiliary
};

#define RIL_REQUEST_LAST_ELEMENT 0xFFFF

/*
 * Groups of requests that will go on a dedicated queue
 * instead of the auxiliary queue.
 */

static int defaultRequests[] = {
    RIL_REQUEST_SCREEN_STATE,
    RIL_REQUEST_SMS_ACKNOWLEDGE,
    RIL_REQUEST_GSM_SMS_BROADCAST_ACTIVATION,
    RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING,
    RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND,
    RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE,
    RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM,
    RIL_REQUEST_LAST_ELEMENT
};

static RILRequestGroup RILRequestGroups[] = {
    {CMD_QUEUE_DEFAULT, "DEFAULT", defaultRequests, &s_requestQueueDefault},
    {CMD_QUEUE_AUXILIARY, "AUXILIARY", NULL, &s_requestQueueAuxiliary}
};

/**
 * Call to signal ril_queue_synch_cond to waiting threads
 */
static void signalDefaultQueueReady(void)
{
    int err;

    if ((err = pthread_mutex_lock(&ril_queue_synch_mutex)) != 0) {
        LOGE("%s() failed to take defaultQueueReady mutex: %s!",
             __func__, strerror(err));
        assert(0);
    }

    defaultQueueReady = true;
    if ((err = pthread_cond_broadcast(&ril_queue_synch_cond)) != 0) {
        LOGE("%s() failed to broadcast defaultQueueReady cond: %s!",
            __func__, strerror(err));
        assert(0);
    }

    if ((err = pthread_mutex_unlock(&ril_queue_synch_mutex)) != 0) {
        LOGE("%s() failed to release defaultQueueReady mutex: %s!",
            __func__, strerror(err));
        assert(0);
    }
}

/**
 * Call to waits for ril_queue_synch_cond
 */
static void waitDefaultQueueReady(void)
{
    int err;

    if ((err = pthread_mutex_lock(&ril_queue_synch_mutex)) != 0) {
        LOGE("%s() failed to take defaultQueueReady mutex: %s!",
             __func__, strerror(err));
        assert(0);
    }

    while (!defaultQueueReady) {
        if ((err = pthread_cond_wait(&ril_queue_synch_cond,
                                     &ril_queue_synch_mutex)) != 0) {
            LOGE("%s() failed to broadcast defaultQueueReady cond: %s!",
                 __func__, strerror(err));
            assert(0);
        }
    }

    if ((err = pthread_mutex_unlock(&ril_queue_synch_mutex)) != 0) {
        LOGE("%s() failed to release defaultQueueReady mutex: %s!",
            __func__, strerror(err));
        assert(0);
    }
}

/**
 * This is a reference implementation of reset of modem state information.
 * All files/categories must implement a version of this to handle reset
 * notificaitons.
 */
static void onResetModemStateRil(int resetState)
{
    /* NOTE: Function is called in DEFAULT queueRunner context! */

    switch (resetState) {
    case RESET_START:
        /*
         * Issued prior to AT channels are recreated and shall therefore NOT
         * initiate modem communication!
         * -> Reset any internal static state variables and report to Android if
         *    nessasary.
         */
        /** s_restrictedState */
        /* Reset and reported to Android */
        s_restrictedState = __s_restrictedState;
        RIL_onUnsolicitedResponse(RIL_UNSOL_RESTRICTED_STATE_CHANGED,
                                  &s_restrictedState, sizeof(int *));
        break;
    case RESET_AT_INITIALIZED:
        /*
         * Issued when AT channels are available and before SIM is booted and
         * available.
         * -> Re-setup modem and Android with internal static state variables
         *    which cannot be reset after modem restart.
         */
        /** s_restrictedState */
        /* No impact */
        break;
    case RESET_SIM_READY:
        /*
         * Issued after SIM is unlocked.
         * -> Re-setup modem with internal static state variables which
         *    cannot be reset before SIM is unlocked.
         */
        /** s_restrictedState */
        /* No impact */
        break;
    default:
        LOGE("%s() received unknown resetState. Fatal error!", __func__);
        assert(0);
    }
}

static void resetModemState(int resetState)
{
    LOGI("%s() starting with resetState (%d)", __func__, resetState);
    onResetModemStateRil(resetState);
    onResetModemStateAudio(resetState);
    onResetModemStateCallHandling(resetState);
    onResetModemStateInformation(resetState);
    onResetModemStateMessaging(resetState);
    onResetModemStateNetwork(resetState);
    onResetModemStatePdp(resetState);
    onResetModemStateServices(resetState);
    onResetModemStateSim(resetState);
    onResetModemStateStk(resetState);
}

static void shutdownSystem(RIL_Token t)
{
    int err;
    if ((err = pthread_mutex_lock(&ril_system_shutdown_mutex)) != 0) {
        LOGE("%s() failed to take system shutdown mutex: %s!", __func__,
                strerror(err));
        assert(0);
    }

    /**
     * If Dbus is disabled, there will be no indication when the modem
     * is shut down and thus no signal to the condition.
     * To allow system maximum time to shut down the modem, the request
     * will wait here until the timeout in Android expires.
     */
    while (!g_offSignalReceived) {
        if ((err = pthread_cond_wait(&ril_system_shutdown_cond,
                                &ril_system_shutdown_mutex)) != 0) {
            LOGE("%s(): pthread_cond_wait Failed. err: %s", __func__,
                strerror(err));
        }
    }

    if ((err = pthread_mutex_unlock(&ril_system_shutdown_mutex)) != 0) {
        LOGE("%s() failed to release system shutdown mutex: %s!", __func__,
                strerror(err));
    }

    RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
}

void enqueueRILEventOnList(RequestQueue* q, RILEvent* e)
{
    int err;

    if ((err = pthread_mutex_lock(&q->queueMutex)) != 0) {
        LOGE("%s() failed to take queue mutex: %s!", __func__, strerror(err));
        assert(0);
    }
    if (q->eventList == NULL)
        q->eventList = e;
    else {
        if (timespec_cmp(q->eventList->abstime, e->abstime, >)) {
            e->next = q->eventList;
            q->eventList->prev = e;
            q->eventList = e;
        } else {
            RILEvent *tmp = q->eventList;
            do {
                if (timespec_cmp(tmp->abstime, e->abstime, >)) {
                    tmp->prev->next = e;
                    e->prev = tmp->prev;
                    tmp->prev = e;
                    e->next = tmp;
                    break;
                } else if (tmp->next == NULL) {
                    tmp->next = e;
                    e->prev = tmp;
                    break;
                }
                tmp = tmp->next;
            } while (tmp);
        }
    }

    if ((err = pthread_cond_broadcast(&q->cond)) != 0)
        LOGE("%s() failed to take broadcast queue update: %s!",
            __func__, strerror(err));

    if ((err = pthread_mutex_unlock(&q->queueMutex)) != 0)
        LOGE("%s() failed to release queue mutex: %s!",
            __func__, strerror(err));
}

/*
 * Enqueue a RIL event on an event queue.
 * Each QueueRunner thread has one request and one event queue.
 *
 * When DEFAULT and AUXILIARY groups are enabled the DEFAULT AT channel
 * shall not be blocked by slow AT commnds. Events posted on the DEFAULT
 * queue must execute AT commands that gives immediate response.
 * Non-prioritized events are typically put on the AUXILIARY queue,
 * which may be temporarily blocked by "slow" AT commands.
 */
void enqueueRILEvent(int eventQueue, void (*callback)(void *param),
                     void *param, const struct timeval *relativeTime)
{
    struct timeval tv;

    RILEvent *e = malloc(sizeof(RILEvent));

    e->eventCallback = callback;
    e->param = param;
    memset(&(e->abstime), 0, sizeof(e->abstime));
    e->next = NULL;
    e->prev = NULL;

    if (relativeTime == NULL) {
        relativeTime = alloca(sizeof(struct timeval));
        memset((struct timeval *) relativeTime, 0, sizeof(struct timeval));
    }

    gettimeofday(&tv, NULL);

    e->abstime.tv_sec = tv.tv_sec + relativeTime->tv_sec;
    e->abstime.tv_nsec = (tv.tv_usec + relativeTime->tv_usec) * 1000;

    if (e->abstime.tv_nsec > 1000000000) {
        e->abstime.tv_sec++;
        e->abstime.tv_nsec -= 1000000000;
    }

    switch(eventQueue) {
    case CMD_QUEUE_DEFAULT:
        /* DEFAULT group is always enabled */
        enqueueRILEventOnList(&s_requestQueueDefault, e);
        break;
    case CMD_QUEUE_AUXILIARY:
        if (!RILRequestGroups[CMD_QUEUE_AUXILIARY].requestQueue->enabled) {
            LOGW("%s(): AUXILIARY group is not enabled! "
                "Posting event on DEFAULT queue", __func__);
            enqueueRILEventOnList(&s_requestQueueDefault, e);
        } else
            enqueueRILEventOnList(&s_requestQueueAuxiliary, e);
        break;
    default:
        LOGW("%s(): Unknown event queue!"
            " Posting event on DEFAULT queue.", __func__);
        enqueueRILEventOnList(&s_requestQueueDefault, e);
    }

    return;
}

static void setPreferredMessageStorage()
{
    ATResponse *atresponse = NULL;
    char *tok = NULL;
    int used1, total1;
    int err = -1;

    err = at_send_command_singleline("AT+CPMS=\"SM\",\"SM\"","+CPMS: ",
                                     &atresponse);
    if (err < 0 || atresponse->success == 0)
        goto error;

    /*
     * Depending on the host boot time the indication that message storage
     * on SIM is full (+CIEV: 10,1) may be sent before the RIL is started.
     * The RIL will explicitly check status of SIM messages storage using
     * +CPMS intermediate response and inform Android if storage is full.
     * +CPMS: <used1>,<total1>,<used2>,<total2>,<used3>,<total3>
     */
    tok = atresponse->p_intermediates->line;

    err = at_tok_start(&tok);
    if (err < 0)
        goto error;

    err = at_tok_nextint(&tok, &used1);
    if (err < 0)
        goto error;

    err = at_tok_nextint(&tok, &total1);
    if (err < 0)
        goto error;

    if (used1 >= total1)
        RIL_onUnsolicitedResponse(RIL_UNSOL_SIM_SMS_STORAGE_FULL,NULL, 0);

    goto exit;

error:
    LOGE("%s() failed during AT+CPMS sending/handling!", __func__);

exit:
    at_response_free(atresponse);
    return;
}

/** Do post- SIM ready initialization. */
static void onSIMReady()
{
    LOGI("%s()", __func__);

    /*
     * Configure preferred message storage
     *  mem1 = SM, mem2 = SM
     */
    setPreferredMessageStorage();

    /* Select message service */
    if (at_send_command("AT+CSMS=0", NULL) < 0)
        LOGW("%s(): Failed to send AT+CSMS", __func__);

    /*
     * Configure new messages indication
     *  mode = 2 - Buffer unsolicited result code in TA when TA-TE link is
     *             reserved(e.g. in on.line data mode) and flush them to the
     *             TE after reservation. Otherwise forward them directly to
     *             the TE.
     *  mt   = 2 - SMS-DELIVERs (except class 2 messages and messages in the
     *             message waiting indication group (store message)) are
     *             routed directly to TE using unsolicited result code:
     *             +CMT: [<alpha>],<length><CR><LF><pdu> (PDU mode)
     *             Class 2 messages are handled as if <mt> = 1
     *  bm   = 0 - No CBM indications are routed to the TE.
     *  ds   = 1 - SMS-STATUS-REPORTs are routed to the TE using unsolicited
     *             result code: +CDS: <length><CR><LF><pdu> (PDU mode)
     *  bfr  = 0 - TA buffer of unsolicited result codes defined within this
     *             command is flushed to the TE when <mode> 1...3 is entered
     *             (OK response is given before flushing the codes).
     */
    if (at_send_command("AT+CNMI=2,2,0,1,0", NULL) < 0)
        LOGW("%s(): Failed to send AT+CNMI", __func__);

    /* Configure ST-Ericsson current PS bearer Reporting. */
    if (at_send_command("AT*EPSB=1", NULL) < 0)
        LOGW("%s(): Failed to send AT+EPSB", __func__);

#ifdef LTE_COMMAND_SET_ENABLED
    /*
     * Subscribe to network registration events.
     *  n = 2 - Enable network registration and location information
     *          unsolicited result code +CREG: <stat>[,<lac>,<ci>]
     */
    if (at_send_command("AT+CREG=2", NULL) < 0)
        LOGW("%s(): Failed to send AT+CREG", __func__);

    if (at_send_command("AT+CEREG=2", NULL) < 0)
        LOGW("%s(): Failed to send AT+CEREG", __func__);
#else
    /* Subscribe to network registration events.
     *  n = 2 - Enable network registration and location information
     *          unsolicited result code *EREG: <stat>[,<lac>,<ci>]
     */
    if (at_send_command("AT*EREG=2", NULL) < 0)
        LOGW("%s(): Failed to send AT*EREG", __func__);
#endif

    /*
     * Subsctibe to Call Waiting Notifications.
     *  n = 1 - Enable call waiting notifications
     */
    if (at_send_command("AT+CCWA=1", NULL) < 0)
        LOGW("%s(): Failed to send AT+CCWA", __func__);

    /*
     * Subscribe to Supplementary Services Notification
     *  n = 1 - Enable the +CSSI result code presentation status.
     *          Intermediaate result codes. When enabled and a supplementary
     *          service notification is received after a mobile originated
     *          call setup.
     *  m = 1 - Enable the +CSSU result code presentation status.
     *          Unsolicited result code. When a supplementary service
     *          notification is received during a mobile terminated call
     *          setup or during a call, or when a forward check supplementary
     *          service notification is received.
     */
    if (at_send_command("AT+CSSN=1,1", NULL) < 0)
        LOGW("%s(): Failed to send AT+CSSN", __func__);

    /*
     * Subscribe to Unstuctured Supplementary Service Data (USSD) notifications.
     *  n = 1 - Enable result code presentation in the TA.
     */
    if (at_send_command("AT+CUSD=1", NULL) < 0)
        LOGW("%s(): Failed to send AT+CUSD", __func__);

    /*
     * Subscribe to Packet Domain Event Reporting.
     *  mode = 1 - Discard unsolicited result codes when ME-TE link is reserved
     *             (e.g. in on-line data mode); otherwise forward them directly
     *             to the TE.
     *   bfr = 0 - MT buffer of unsolicited result codes defined within this
     *             command is cleared when <mode> 1 is entered.
     */
    if (at_send_command("AT+CGEREP=1,0", NULL) < 0)
        LOGW("%s(): Failed to send AT+CGEREP", __func__);

    /*
     * Configure Short Message (SMS) Format
     *  mode = 0 - PDU mode.
     */
    if (at_send_command("AT+CMGF=0", NULL) < 0)
        LOGW("%s(): Failed to send AT+CMGF", __func__);

#ifndef USE_EARLY_NITZ_TIME_SUBSCRIPTION
    /* Subscribe to ST-Ericsson time zone/NITZ reporting */
    if (at_send_command("AT*ETZR=3", NULL) < 0)
        LOGW("%s(): Failed to send AT+ETZR", __func__);
#endif

    /*
     * Configure Mobile Equipment Event Reporting.
     *  mode = 3 - Forward unsolicited result codes directly to the TE;
     *             There is no inband technique used to embed result codes
     *             and data when TA is in on-line data mode.
     */
    if (at_send_command("AT+CMER=3,0,0,1", NULL) < 0)
        LOGW("%s(): Failed to send AT+CMER", __func__);

    /*
     * EACE should be sent to modem after SIM ready state.
     * Support notifications for comfort tone to Android.
     */
    if (at_send_command("AT*EACE=1", NULL) < 0)
        LOGW("%s(): Failed to enable comfort tone notifications", __func__);

    /*
     * Configure Minimum Interval Between RSSI Reports.
     *  gsm_interval   = 2 - Set reporting interval for GSM RAT RSSI change
     *  wcdma_interval = 2 - Set reporting interval for WCDMA RAT RSSI change
     */
    if (at_send_command("AT*EMIBRR=2,2", NULL) < 0)
        LOGW("%s(): Failed to send AT*EMIBRR", __func__);

    /* In case of modem restart do a reset on internal RIL state */
    /* TODO: more protection for not running mulitple times if reenter? */
    if (s_queueRuns > 1)
        resetModemState(RESET_SIM_READY);

    /*
     * To prevent Gsm/Cdma-ServiceStateTracker.java from polling RIL
     * with numerous RIL_REQUEST_SIGNAL_STRENGTH after power on
     * we get current signal strength using AT+CIND and and send
     * RIL_UNSOL_SIGNAL_STRENGTH up to stops further requests.
     */
    pollAndDispatchSignalStrength(NULL);
}

/**
 * Will LOCK THE MUTEX! MAKE SURE TO RELEASE IT!
 */
void getScreenStateLock(void)
{
    int err;

    /* Making sure we're not changing anything with regards to screen state. */
    if ((err = pthread_mutex_lock(&s_screen_state_mutex)) != 0)
        LOGE("%s() failed to take screen state mutex: %s!",
            __func__, strerror(err));
}

void releaseScreenStateLock(void)
{
    int err;

    /* Changing screen state is safe again */
    if ((err = pthread_mutex_unlock(&s_screen_state_mutex)) != 0)
        LOGW("%s() failed to release screen state mutex: %s",
            __func__,  strerror(err));
}

static RequestQueue *getRequestQueue(int request)
{
    size_t i, j;

    /* We are using only one RIL command group/AT channel. */
    if (!RILRequestGroups[CMD_QUEUE_AUXILIARY].requestQueue->enabled)
        return RILRequestGroups[CMD_QUEUE_DEFAULT].requestQueue;

    for (i = 0; i < RIL_MAX_NR_OF_CHANNELS; i++) {
        if (RILRequestGroups[i].requestQueue->enabled)
        {
            if (RILRequestGroups[i].group == CMD_QUEUE_AUXILIARY)
                continue;

            if (RILRequestGroups[i].requests == NULL)
                continue;

            for (j = 0;
                 RILRequestGroups[i].requests[j] != RIL_REQUEST_LAST_ELEMENT;
                 j++) {
                if (request == RILRequestGroups[i].requests[j])
                    return RILRequestGroups[i].requestQueue;
            }
        }
    }

    /*
     * If the request is not mapped to any particular
     * group it shall be put on the AUXILIARY queue.
     */
    return RILRequestGroups[CMD_QUEUE_AUXILIARY].requestQueue;
}

static bool requestStateFilter(int request, void *data,
                               size_t datalen, RIL_Token t)
{
    /*
     * These commands will not accept RADIO_NOT_AVAILABLE and cannot be executed
     * before we are in SIM_STATE_READY so we just return GENERIC_FAILURE if
     * not in SIM_STATE_READY.
     */
    if (s_state != RADIO_STATE_SIM_READY
        && (request == RIL_REQUEST_WRITE_SMS_TO_SIM ||
            request == RIL_REQUEST_DELETE_SMS_ON_SIM)) {
        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
        return true;
    }

    /* Special handling of ALL requsts while in radio_state_unavailable */
    if (s_state == RADIO_STATE_UNAVAILABLE) {
        /*
         * NOTE: The following command(s) must never fail. Return static state
         * for these command(s) while in RADIO_STATE_UNAVAILABLE.
         */
        if (request == RIL_REQUEST_GET_SIM_STATUS) {
            requestGetSimStatus_ModemUnavailable(data, datalen, t);
        }
        /*
         * NOTE: The following command(s) must always be handled! Return success
         * and store state for later execution while in RADIO_STATE_UNAVAILABLE.
         */
        else if (request == RIL_REQUEST_SCREEN_STATE) {
            requestScreenState_ModemUnavailable(data, datalen, t);
        }
        /* NOTE: Ignore all other requests when RADIO_STATE_UNAVAILABLE */
        else {
            RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
        }
        return true;
    }

    /*
     * Ignore all non-power requests when RADIO_STATE_OFF
     * (except RIL_REQUEST_RADIO_POWER and
     * RIL_REQUEST_GET_SIM_STATUS and a few more).
     * This is according to reference RIL implementation.
     * Note that returning RIL_E_RADIO_NOT_AVAILABLE for all ignored requests
     * causes Android Telephony to enter state RADIO_NOT_AVAILABLE and block
     * all communication with the RIL.
     */
    if (s_state == RADIO_STATE_OFF
        && !(request == RIL_REQUEST_RADIO_POWER ||
             request == RIL_REQUEST_STK_GET_PROFILE ||
             request == RIL_REQUEST_STK_SET_PROFILE ||
             request == RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING ||
             request == RIL_REQUEST_GET_SIM_STATUS ||
             request == RIL_REQUEST_GET_IMEISV ||
             request == RIL_REQUEST_GET_IMEI ||
             request == RIL_REQUEST_DEVICE_IDENTITY ||
             request == RIL_REQUEST_BASEBAND_VERSION ||
             request == RIL_REQUEST_SCREEN_STATE)) {
        RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
        return true;
    }

    /*
     * Ignore all non-power requests when RADIO_STATE_OFF
     * and RADIO_STATE_SIM_NOT_READY (except RIL_REQUEST_RADIO_POWER
     * and a few more).
     */
    if ((s_state == RADIO_STATE_OFF || s_state == RADIO_STATE_SIM_NOT_READY)
        && !(request == RIL_REQUEST_RADIO_POWER ||
             request == RIL_REQUEST_GET_SIM_STATUS ||
             request == RIL_REQUEST_GET_IMEISV ||
             request == RIL_REQUEST_GET_IMEI ||
             request == RIL_REQUEST_DEVICE_IDENTITY ||
             request == RIL_REQUEST_BASEBAND_VERSION ||
             request == RIL_REQUEST_SCREEN_STATE ||
             request == RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING ||
             request == RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE ||
             request == RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND ||
             request == RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM)) {
        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
        return true;
    }

    /*
     * Don't allow radio operations when sim is absent or locked!
     * DIAL, GET_CURRENT_CALLS, HANGUP and LAST_CALL_FAIL_CAUSE are
     * required to handle emergency calls.
     */
    if (s_state == RADIO_STATE_SIM_LOCKED_OR_ABSENT
        && !(request == RIL_REQUEST_ENTER_SIM_PIN ||
             request == RIL_REQUEST_ENTER_SIM_PUK ||
             request == RIL_REQUEST_ENTER_SIM_PIN2 ||
             request == RIL_REQUEST_ENTER_SIM_PUK2 ||
             request == RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION ||
             request == RIL_REQUEST_GET_SIM_STATUS ||
             request == RIL_REQUEST_RADIO_POWER ||
             request == RIL_REQUEST_GET_IMEISV ||
             request == RIL_REQUEST_GET_IMEI ||
             request == RIL_REQUEST_BASEBAND_VERSION ||
             request == RIL_REQUEST_DIAL ||
             request == RIL_REQUEST_GET_CURRENT_CALLS ||
             request == RIL_REQUEST_HANGUP ||
             request == RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND ||
             request == RIL_REQUEST_SET_TTY_MODE ||
             request == RIL_REQUEST_QUERY_TTY_MODE ||
             request == RIL_REQUEST_DTMF ||
             request == RIL_REQUEST_DTMF_START ||
             request == RIL_REQUEST_DTMF_STOP ||
             request == RIL_REQUEST_LAST_CALL_FAIL_CAUSE ||
             request == RIL_REQUEST_SCREEN_STATE ||
             request == RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING ||
             request == RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE ||
             request == RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND ||
             request == RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM)) {
        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
        return true;
    }

    return false;
}

static void processRequest(int request, void *data, size_t datalen,
                           RIL_Token t)
{
    LOGI("processRequest: %s", requestToString(request));

    if (requestStateFilter(request, data, datalen, t))
        goto finally;

    switch (request) {

    /* Basic Voice Call */
    case RIL_REQUEST_LAST_CALL_FAIL_CAUSE:
        requestLastCallFailCause(data, datalen, t);
        break;
    case RIL_REQUEST_GET_CURRENT_CALLS:
        requestGetCurrentCalls(data, datalen, t);
        break;
    case RIL_REQUEST_DIAL:
        requestDial(data, datalen, t);
        break;
    case RIL_REQUEST_HANGUP:
        requestHangup(data, datalen, t);
        break;
    case RIL_REQUEST_ANSWER:
        requestAnswer(data, datalen, t);
        break;

    /* Advanced Voice Call */
    case RIL_REQUEST_GET_CLIR:
        requestGetCLIR(data, datalen, t);
        break;
    case RIL_REQUEST_SET_CLIR:
        requestSetCLIR(data, datalen, t);
        break;
    case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS:
        requestQueryCallForwardStatus(data, datalen, t);
        break;
    case RIL_REQUEST_SET_CALL_FORWARD:
        requestSetCallForward(data, datalen, t);
        break;
    case RIL_REQUEST_QUERY_CALL_WAITING:
        requestQueryCallWaiting(data, datalen, t);
        break;
    case RIL_REQUEST_SET_CALL_WAITING:
        requestSetCallWaiting(data, datalen, t);
        break;
    case RIL_REQUEST_UDUB:
        requestUDUB(data, datalen, t);
        break;
    case RIL_REQUEST_GET_MUTE:
        requestGetMute(data, datalen, t);
        break;
    case RIL_REQUEST_SET_MUTE:
        requestSetMute(data, datalen, t);
        break;
    case RIL_REQUEST_SCREEN_STATE:
        requestScreenState(data, datalen, t);
        break;
    case RIL_REQUEST_QUERY_CLIP:
        requestQueryClip(data, datalen, t);
        break;
    case RIL_REQUEST_DTMF:
        requestDTMF(data, datalen, t);
        break;
    case RIL_REQUEST_DTMF_START:
        requestDTMFStart(data, datalen, t);
        break;
    case RIL_REQUEST_DTMF_STOP:
        requestDTMFStop(data, datalen, t);
        break;

    /* Multiparty Voice Call */
    case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND:
        requestHangupWaitingOrBackground(data, datalen, t);
        break;
    case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND:
        requestHangupForegroundResumeBackground(data, datalen, t);
        break;
    case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE:
        requestSwitchWaitingOrHoldingAndActive(data, datalen, t);
        break;
    case RIL_REQUEST_CONFERENCE:
        requestConference(data, datalen, t);
        break;
    case RIL_REQUEST_SEPARATE_CONNECTION:
        requestSeparateConnection(data, datalen, t);
        break;
    case RIL_REQUEST_EXPLICIT_CALL_TRANSFER:
        requestExplicitCallTransfer(data, datalen, t);
        break;

    /* Data Call Requests */
    case RIL_REQUEST_SETUP_DATA_CALL:
        requestSetupDataCall(data, datalen, t);
        break;
    case RIL_REQUEST_DEACTIVATE_DATA_CALL:
        requestDeactivateDataCall(data, datalen, t);
        break;
    case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE:
        requestLastPDPFailCause(data, datalen, t);
        break;
    case RIL_REQUEST_DATA_CALL_LIST:
        requestPDPContextList(data, datalen, t);
        break;

    /* SMS Requests */
    case RIL_REQUEST_SEND_SMS:
        requestSendSMS(data, datalen, t);
        break;
    case RIL_REQUEST_SEND_SMS_EXPECT_MORE:
        requestSendSMSExpectMore(data, datalen, t);
        break;
    case RIL_REQUEST_WRITE_SMS_TO_SIM:
        requestWriteSmsToSim(data, datalen, t);
        break;
    case RIL_REQUEST_DELETE_SMS_ON_SIM:
        requestDeleteSmsOnSim(data, datalen, t);
        break;
    case RIL_REQUEST_GET_SMSC_ADDRESS:
        requestGetSMSCAddress(data, datalen, t);
        break;
    case RIL_REQUEST_SET_SMSC_ADDRESS:
        requestSetSMSCAddress(data, datalen, t);
        break;
    case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS:
        requestSmsStorageFull(data, datalen, t);
        break;
    case RIL_REQUEST_SMS_ACKNOWLEDGE:
        requestSMSAcknowledge(data, datalen, t);
        break;
    case RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG:
        requestGSMGetBroadcastSMSConfig(data, datalen, t);
        break;
    case RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG:
        requestGSMSetBroadcastSMSConfig(data, datalen, t);
        break;
    case RIL_REQUEST_GSM_SMS_BROADCAST_ACTIVATION:
        requestGSMSMSBroadcastActivation(data, datalen, t);
        break;

    /* SIM Handling Requests */
    case RIL_REQUEST_SIM_IO:
        requestSIM_IO(data, datalen, t);
        break;
    case RIL_REQUEST_GET_SIM_STATUS:
        requestGetSimStatus(data, datalen, t);
        break;
    case RIL_REQUEST_ENTER_SIM_PIN:
    case RIL_REQUEST_ENTER_SIM_PUK:
    case RIL_REQUEST_ENTER_SIM_PIN2:
    case RIL_REQUEST_ENTER_SIM_PUK2:
        requestEnterSimPin(data, datalen, t, request);
        break;
    case RIL_REQUEST_CHANGE_SIM_PIN:
        requestChangeSimPin(data, datalen, t, request);
        break;
    case RIL_REQUEST_CHANGE_SIM_PIN2:
        requestChangeSimPin2(data, datalen, t, request);
        break;
    case RIL_REQUEST_CHANGE_BARRING_PASSWORD:
        requestChangeBarringPassword(data, datalen, t, request);
        break;
    case RIL_REQUEST_QUERY_FACILITY_LOCK:
        requestQueryFacilityLock(data, datalen, t);
        break;
    case RIL_REQUEST_SET_FACILITY_LOCK:
        requestSetFacilityLock(data, datalen, t);
        break;

    /* USSD Requests */
    case RIL_REQUEST_SEND_USSD:
        requestSendUSSD(data, datalen, t);
        break;
    case RIL_REQUEST_CANCEL_USSD:
        requestCancelUSSD(data, datalen, t);
        break;

    /* Network Selection */
    case RIL_REQUEST_SET_BAND_MODE:
        requestSetBandMode(data, datalen, t);
        break;
    case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE:
        requestQueryAvailableBandMode(data, datalen, t);
        break;
    case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION:
        requestEnterNetworkDepersonalization(data, datalen, t);
        break;
    case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
        requestQueryNetworkSelectionMode(data, datalen, t);
        break;
    case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC:
        requestSetNetworkSelectionAutomatic(data, datalen, t);
        break;
    case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL:
        requestSetNetworkSelectionManual(data, datalen, t);
        break;
    case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS:
        requestQueryAvailableNetworks(data, datalen, t);
        break;
    case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
        requestSetPreferredNetworkType(data, datalen, t);
        break;
    case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
        requestGetPreferredNetworkType(data, datalen, t);
        break;
    case RIL_REQUEST_REGISTRATION_STATE:
        requestRegistrationState(data, datalen, t);
        break;
    case RIL_REQUEST_GPRS_REGISTRATION_STATE:
        requestGprsRegistrationState(data, datalen, t);
        break;
    case RIL_REQUEST_SET_LOCATION_UPDATES:
        requestSetLocationUpdates(data, datalen, t);
        break;

    /* OEM */
    case RIL_REQUEST_OEM_HOOK_RAW:
        requestOEMHookRaw(data, datalen, t);
        break;
    case RIL_REQUEST_OEM_HOOK_STRINGS:
        requestOEMHookStrings(data, datalen, t);
        break;

    /* Misc */
    case RIL_REQUEST_SIGNAL_STRENGTH:
        requestSignalStrength(data, datalen, t);
        break;
    case RIL_REQUEST_OPERATOR:
        requestOperator(data, datalen, t);
        break;
    case RIL_REQUEST_RADIO_POWER:
        requestRadioPower(data, datalen, t);
        break;
    case RIL_REQUEST_GET_IMSI:
        requestGetIMSI(data, datalen, t);
        break;
    case RIL_REQUEST_GET_IMEI: /* Deprecated */
        requestGetIMEI(data, datalen, t);
        break;
    case RIL_REQUEST_GET_IMEISV:   /* Deprecated */
        requestGetIMEISV(data, datalen, t);
        break;
    case RIL_REQUEST_DEVICE_IDENTITY:
        requestDeviceIdentity(data, datalen, t);
        break;
    case RIL_REQUEST_BASEBAND_VERSION:
        requestBasebandVersion(data, datalen, t);
        break;
    case RIL_REQUEST_SET_SUPP_SVC_NOTIFICATION:
        requestSetSuppSvcNotification(data, datalen, t);
        break;

    /* SIM Application Toolkit */
    case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE:
        requestStkSendTerminalResponse(data, datalen, t);
        break;
    case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND:
        requestStkSendEnvelopeCommand(data, datalen, t);
        break;
    case RIL_REQUEST_STK_GET_PROFILE:
        requestStkGetProfile(data, datalen, t);
        break;
    case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING:
        requestReportStkServiceIsRunning(data, datalen, t);
        break;
    case RIL_REQUEST_STK_SET_PROFILE:
        requestStkSetProfile(data, datalen, t);
        break;
    case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM:
        requestStkHandleCallSetupRequestedFromSIM(data, datalen, t);
        break;

    /* Network neighbors */
    case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS:
        requestNeighboringCellIDs(data, datalen, t);
        break;

    /* TTY mode */
    case RIL_REQUEST_SET_TTY_MODE:
        requestSetTtyMode(data, datalen, t);
        break;
    case RIL_REQUEST_QUERY_TTY_MODE:
        requestQueryTtyMode(data, datalen, t);
        break;

    default:
        LOGW("%s(): FIXME: Unsupported request logged: %s!",
             __func__, requestToString(request));
        RIL_onRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
        break;
    }

finally:
    return;
}

/**
 * Call from RIL to us to make a RIL_REQUEST.
 *
 * Must be completed with a call to RIL_onRequestComplete().
 */
static void onRequest(int request, void *data, size_t datalen, RIL_Token t)
{
    RILRequest *r;
    RequestQueue *q = &s_requestQueueDefault;
    int err;

    const char *property = "sys.shutdown.requested";
    char systemShutdown[PROPERTY_VALUE_MAX + 1];
    int getRet = -1;

    /*
     * Check if this is a 'RADIO_POWER' request, and if Android system
     * property for shutdown is set.
     * Note: If property is set a shutdown is taking place, regardless
     * of value.
     */
    if (request == RIL_REQUEST_RADIO_POWER && ((int *) data)[0] == 0) {
        getRet = property_get(property, systemShutdown, NULL);
        if (getRet > 0) {
            shutdownSystem(t);
            goto finally;
        }
    }

    /* In radio state unavailable no requests are to enter the queues */
    if (s_state == RADIO_STATE_UNAVAILABLE) {
        (void)requestStateFilter(request, data, datalen, t);
        goto finally;
    }

    q = getRequestQueue(request);

    r = calloc(1, sizeof(RILRequest));
    assert(r != NULL);

    /* Formulate a RILRequest and put it in the queue. */
    r->request = request;
    r->data = dupRequestData(request, data, datalen);
    r->datalen = datalen;
    r->token = t;
    r->next = NULL;

    if ((err = pthread_mutex_lock(&q->queueMutex)) != 0) {
        LOGE("%s() failed to take queue mutex: %s!", __func__, strerror(err));
        assert(0);
    }

    /* Queue empty, just throw r on top. */
    if (q->requestList == NULL)
        q->requestList = r;
    else {
        RILRequest *l = q->requestList;
        while (l->next != NULL)
            l = l->next;

        l->next = r;
    }

    if ((err = pthread_cond_broadcast(&q->cond)) != 0)
        LOGE("%s() failed to broadcast queue update: %s!",
            __func__, strerror(err));

    if ((err = pthread_mutex_unlock(&q->queueMutex)) != 0)
        LOGE("%s() failed to release queue mutex: %s!",
            __func__, strerror(err));

finally:
    return;
}

int getRestrictedState(void)
{
    return s_restrictedState;
}

/**
 * Returns current RIL radio state.
 */
RIL_RadioState getCurrentState(void)
{
    return s_state;
}

/**
 * Synchronous call from the RIL to us to return current radio state.
 * RADIO_STATE_UNAVAILABLE should be the initial state.
 */
static RIL_RadioState onStateRequest(void)
{
    return getCurrentState();
}

/**
 * Call from RIL to us to find out whether a specific request code
 * is supported by this implementation.
 *
 * Return 1 for "supported" and 0 for "unsupported".
 *
 * Currently just stubbed with the default value of one. This is currently
 * not used by android, and therefore not implemented here. We return
 * RIL_E_REQUEST_NOT_SUPPORTED when we encounter unsupported requests.
 */
static int supports(int requestCode)
{
    LOGW("Unimplemented function \"%s\" called!", __func__);

    return 1;
}

/**
 * onCancel() is currently stubbed, because android doesn't use it and
 * our implementation will depend on how a cancellation is handled in
 * the upper layers.
 */
static void onCancel(RIL_Token t)
{
    LOGW("Unimplemented function \"%s\" called!", __func__);
}

static const char *getVersion(void)
{
    return RIL_VERSION_STRING;
}

const char *radioStateToString(RIL_RadioState radioState)
{
    const char *state;

    switch (radioState) {
    case RADIO_STATE_OFF:
        state = "RADIO_STATE_OFF";
        break;
    case RADIO_STATE_UNAVAILABLE:
        state = "RADIO_STATE_UNAVAILABLE";
        break;
    case RADIO_STATE_SIM_NOT_READY:
        state = "RADIO_STATE_SIM_NOT_READY";
        break;
    case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
        state = "RADIO_STATE_SIM_LOCKED_OR_ABSENT";
        break;
    case RADIO_STATE_SIM_READY:
        state = "RADIO_STATE_SIM_READY";
        break;
    case RADIO_STATE_RUIM_NOT_READY:
        state = "RADIO_STATE_RUIM_NOT_READY";
        break;
    case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
        state = "RADIO_STATE_RUIM_READY";
        break;
    case RADIO_STATE_NV_NOT_READY:
        state = "RADIO_STATE_NV_NOT_READY";
        break;
    case RADIO_STATE_NV_READY:
        state = "RADIO_STATE_NV_READY";
        break;
    default:
        state = "RADIO_STATE_<> Unknown!";
        break;
    }

    return state;
}

void setRadioState(RIL_RadioState newState)
{
    RIL_RadioState oldState;
    int err;

    if ((err = pthread_mutex_lock(&s_state_mutex)) != 0) {
        LOGE("%s() failed to take state mutex: %s!", __func__, strerror(err));
        assert(0);
    }

    oldState = s_state;

    LOGI("setRadioState: oldState=%s newState=%s", radioStateToString(oldState),
         radioStateToString(newState));

    if (s_state != newState)
        s_state = newState;

    if ((err = pthread_mutex_unlock(&s_state_mutex)) != 0)
        LOGW("%s(): Failed to release state mutex: %s", __func__,
             strerror(err));

    /* Do these outside of the mutex. */
    if (s_state != oldState || s_state == RADIO_STATE_SIM_LOCKED_OR_ABSENT) {
        /*
         * Fetch emergency call code list from EF_ECC
         * and store it into PROP_EMERGENCY_LIST_RW (ril.ecclist)
         * property. This is done here in addition to in initializeDefault() to
         * ensure RIL is able to access the SIM.
         */
        if (s_state == RADIO_STATE_SIM_READY) {
            setupECCList(0);
        }

        RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
                                  NULL, 0);

        if (s_state == RADIO_STATE_SIM_READY)
            enqueueRILEvent(CMD_QUEUE_DEFAULT, onSIMReady, NULL, NULL);
        else if (s_state == RADIO_STATE_SIM_NOT_READY)
            enqueueRILEvent(CMD_QUEUE_DEFAULT, pollSIMState, NULL,
                            NULL);
    }
}

/** Returns 1 if on, 0 if off, and -1 on error. */
static int isRadioOn(void)
{
    ATResponse *atresponse = NULL;
    int err;
    char *line;
    int ret;

    err = at_send_command_singleline("AT+CFUN?", "+CFUN:", &atresponse);
    if (err < 0 || atresponse->success == 0)
        goto error;

    line = atresponse->p_intermediates->line;

    err = at_tok_start(&line);
    if (err < 0)
        goto error;

    err = at_tok_nextint(&line, &ret);
    if (err < 0)
        goto error;

    switch (ret) {
    case 1:                    /* Full functionality (switched on) */
    case 5:                    /* GSM only */
    case 6:                    /* WCDMA only */
        ret = 1;
        break;

    default:
        ret = 0;
    }

    at_response_free(atresponse);

    return ret;

error:
    at_response_free(atresponse);
    return -1;
}

static bool supportsECAM(int* version)
{
    ATResponse *atresponse = NULL;
    char *line = NULL;
    char *found = NULL;
    int ecamHiRange;

    if (at_send_command_singleline("AT*ECAM=?", "*ECAM:", &atresponse) < 0)
        goto error;   /* AT send error */

    if (atresponse->success == 0)
        return false; /* Likely no support */

    /* Find substring and decode number into version */
    line = atresponse->p_intermediates->line;
    found = strstr(line, "(0-");
    if (found == NULL)
        goto error;   /* Parsing error */

    ecamHiRange = atoi(found+3);
    if (ecamHiRange == 0)
        goto error;   /* Invalid range */

    *version = ecamHiRange;
    return true;

error:
    LOGE("%s() failed to check support for AT*ECAM, "
        "assuming no support!", __func__);
    return false;
}

static bool initializeCommon(void)
{
    int err = 0;

    LOGI("%s()", __func__);

    if (at_handshake() < 0) {
        LOG_FATAL("Handshake failed!");
        goto error;
    }

    /* Configure/set
     *   command echo (E), result code suppression (Q), DCE response format (V)
     *
     *  E0 = DCE does not echo characters during command state and online
     *       command state
     *  Q0 = DCE transmits result codes
     *  V1 = Display verbose result codes
     */
    err = at_send_command("ATE0Q0V1", NULL);
    if (err < 0)
        goto error;

    /* Set default character set. */
    err = at_send_command("AT+CSCS=\"UTF-8\"", NULL);
    if (err < 0)
        goto error;

    /* Disable automatic answer. */
    err = at_send_command("ATS0=0", NULL);
    if (err < 0)
        goto error;

    /* Enable +CME ERROR: <err> result code and use numeric <err> values. */
    err = at_send_command("AT+CMEE=1", NULL);
    if (err < 0)
        goto error;

    /* Enable Connected Line Identification Presentation. */
    err = at_send_command("AT+COLP=0", NULL);
    if (err < 0)
        goto error;

    /* Disable Service Reporting. */
    err = at_send_command("AT+CR=0", NULL);
    if (err < 0)
        goto error;

    /* Configure carrier detect signal - 1 = DCD follows the connection. */
    err = at_send_command("AT&C=1", NULL);
    if (err < 0)
        goto error;

    /* Configure DCE response to Data Termnal Ready signal - 0 = ignore. */
    err = at_send_command("AT&D=0", NULL);
    if (err < 0)
        goto error;

    /* Configure Cellular Result Codes - 0 = Disables extended format. */
    err = at_send_command("AT+CRC=0", NULL);
    if (err < 0)
        goto error;

    return true;
error:
    return false;
}

/**
 * Initialize everything that can be configured while we're still in
 * AT+CFUN=0.
 */
static bool initializeDefault()
{
    int err;
    int support = 0;

    LOGI("%s()", __func__);

    /* Record how many times queueRunners have been started */
    s_queueRuns++;

    /* Change radio state to RADIO_STATE_OFF since modem is now available. */
    setRadioState(RADIO_STATE_OFF);

    /*
     * Initial state in the RIL when booting for first time is RADIO_STATE_OFF.
     * If initial boot we must explicitly send RADIO_STATE_OFF.
     */
    RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED, NULL, 0);

    /*
     * Set phone functionality.
     * 4 = Disable the phone's transmit and receive RF circuits.
     */
    if (at_send_command("AT+CFUN=4", NULL) < 0)
        goto error;

    /*
     * SIM Application Toolkit Configuration
     *  n = 0 - Disable SAT unsolicited result codes
     *  stkPrfl = - SIM application toolkit profile in hexadecimal format
     *              starting with first byte of the profile.
     *              See 3GPP TS 11.14[1] for details.
     *
     * Terminal profile is currently empty because stkPrfl is currently
     * overriden by the default profile stored in the modem.
     */
#ifdef USE_LEGACY_SAT_AT_CMDS
    if (at_send_command("AT*STKC=0,\"000000000000000000\"", NULL) < 0)
        LOGW("%s(): Failed to initialize STK", __func__);
#endif

    /*
     * Configure Packet Domain Network Registration Status events
     *    2 = Enable network registration and location information
     *        unsolicited result code
     */
    if (at_send_command("AT+CGREG=2", NULL) < 0)
        goto error;

    /* Subscribe to ST-Ericsson Pin code event.
     *   The command requests the MS to report when the PIN code has been
     *   inserted and accepted.
     *      1 = Request for report on inserted PIN code is activated (on)
     */
    if (at_send_command("AT*EPEE=1", NULL) < 0)
        goto error;

    /* Subscribe to ST-Ericsson SIM State Reporting.
     *   Enable SIM state reporting on the format *ESIMSR: <sim_state>
     */
    if (at_send_command("AT*ESIMSR=1", NULL) < 0)
        goto error;

    /* Subscribe to ST-Ericsson Call monitoring events.
     * Done here to handle during emergency calls without SIM.
     *  onoff = 1 - Call monitoring is on and supports <ccstatus> 0-7
     *  onoff = 2 - Call monitoring is on and supports <ccstatus> 0-8
     *
     * Check modem support before setting best support.
     */
    (void) supportsECAM(&support);
    if (at_send_command(support > 1?"AT*ECAM=2":"AT*ECAM=1", NULL) < 0)
        LOGW("%s(): Failed to subscribe to ST-Ericsson "
            "Call monitoring events", __func__);

    /* Enable barred status reporting used for reporting restricted state. */
    if (at_send_command("AT*EBSR=1", NULL) < 0)
        LOGW("%s(): Failed to enable barred status reporting", __func__);

#ifdef USE_EARLY_NITZ_TIME_SUBSCRIPTION
    /* Subscribe to ST-Ericsson time zone/NITZ reporting */
    if (at_send_command("AT*ETZR=3", NULL) < 0)
        LOGW("%s(): Failed to send early AT*ETZR", __func__);
#endif

    /*
     * Emergency numbers from 3GPP TS 22.101, chapter 10.1.1.
     * 911 and 112 should always be set in the system property, but if SIM is
     * absent, these numbers also has to be added: 000, 08, 110, 999, 118
     * and 119.
     */
    err = property_set(PROP_EMERGENCY_LIST_RW,
                        "911,112,000,08,110,999,118,119");

    /*
     * We do not go to error in this case. Even though we cannot set emergency
     * numbers it is better to continue and at least be able to call some
     * numbers.
     */
    if (err < 0)
        LOGE("[ECC] Creating emergency list ril.ecclist"
            " in system properties failed!");
    else
        LOGD("[ECC] Set initial defaults to system property ril.ecclist");

    /*
     * Older versions of Android does not support ril.ecclist. For legacy
     * reasons ro.ril.ecclist is therefore set up with emergency numbers from
     * 3GPP TS 22.101, chapter 10.1.1.
     */
    err = property_set(PROP_EMERGENCY_LIST_RO,
                        "911,112,000,08,110,999,118,119");

    if (err < 0)
        LOGE("[ECC] Creating emergency list ro.ril.ecclist in "
            "system properties failed!");
    else
        LOGD("[ECC] Set initial defaults to system property ro.ril.ecclist");

    /*
     * Fetch emergency call code list from EF_ECC
     * and store it into PROP_EMERGENCY_LIST_RW (ril.ecclist)
     * property. Do not analyse attached network: ME is not
     * connected to a BSS yet.
     */
    if (!isSimAbsent())
        setupECCList(0);
    else
        LOGI("[ECC]: SIM is absent, keeping default ECCs");

    /* In case of modem restart do a reset on internal RIL state */
    if (s_queueRuns > 1)
        resetModemState(RESET_AT_INITIALIZED);

    return true;

error:
    return false;
}

/**
 * Called by atchannel when an unsolicited line appears.
 * This is called on atchannel's reader thread. AT commands may
 * not be issued here.
 */
static void onUnsolicited(const char *s, const char *sms_pdu)
{
    LOGI("onUnsolicited: %s", s);

    /* Ignore unsolicited responses until we're initialized.
     * This is OK because the RIL library will poll for initial state.
     */
    if (s_state == RADIO_STATE_UNAVAILABLE)
        return;

    if (strStartsWith(s, "*ETZV:")) {
        /* If we're in screen state, we have disabled CREG, but the ETZV
         * will catch those few cases. So we send network state changed as
         * well on NITZ.
         */
        RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_NETWORK_STATE_CHANGED,
                                  NULL, 0);

        onNetworkTimeReceived(s);
    } else if (strStartsWith(s, "*EPEV"))
        /* Pin event, poll SIM State! */
        enqueueRILEvent(CMD_QUEUE_DEFAULT, pollSIMState, NULL, NULL);
    else if (strStartsWith(s, "*ESIMSR"))
        onSimStateChanged(s);
    else if (strStartsWith(s, "+CRING:")
             || strStartsWith(s, "RING"))
        RIL_onUnsolicitedResponse(RIL_UNSOL_CALL_RING, NULL, 0);
    else if (strStartsWith(s, "+CCWA"))
        RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED,
                                  NULL, 0);
    else if (strStartsWith(s, "*EREG:")
             || strStartsWith(s, "+CGREG:")
             || strStartsWith(s, "+CREG:"))
        onNetworkStateChanged(s);
    else if (strStartsWith(s, "+CMT:"))
        RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_NEW_SMS, sms_pdu,
                                  strlen(sms_pdu));
    else if (strStartsWith(s, "+CBM:"))
        onNewBroadcastSms(sms_pdu);
    else if (strStartsWith(s, "+CMTI:"))
        onNewSmsOnSIM(s);
    else if (strStartsWith(s, "+CDS:"))
        onNewStatusReport(sms_pdu);
    else if (strStartsWith(s, "+CGEV:")) {
        /* Really, we can ignore NW CLASS and ME CLASS events here,
         * but right now we don't since extranous
         * RIL_UNSOL_PDP_CONTEXT_LIST_CHANGED calls are tolerated.
         */
        enqueueRILEvent(CMD_QUEUE_AUXILIARY, onPDPContextListChanged,
                        NULL, NULL);
    } else if (strStartsWith(s, "+CIEV: 2"))
        unsolSignalStrength(s);
    else if (strStartsWith(s, "+CIEV: 10"))
        unsolSimSmsFull(s);
    else if (strStartsWith(s, "*EBSRU:"))
        onRestrictedStateChanged(s, &s_restrictedState);
    else if (strStartsWith(s, "+CSSI:"))
        onSuppServiceNotification(s, 0);
    else if (strStartsWith(s, "+CSSU:"))
        onSuppServiceNotification(s, 1);
    else if (strStartsWith(s, "+CUSD:"))
        onUSSDReceived(s);
    else if (strStartsWith(s, "*ECAV:"))
        onECAVReceived(s);
#ifndef USE_LEGACY_SAT_AT_CMDS
    else if (strStartsWith(s, "+CUSATEND"))
        RIL_onUnsolicitedResponse(RIL_UNSOL_STK_SESSION_END, NULL, 0);
#else
    else if (strStartsWith(s, "*STKEND"))
        RIL_onUnsolicitedResponse(RIL_UNSOL_STK_SESSION_END, NULL, 0);
#endif
#ifndef USE_LEGACY_SAT_AT_CMDS
    else if (strStartsWith(s, "+CUSATP:"))
        onStkProactiveCommand(s);
#else
    else if (strStartsWith(s, "*STKI:"))
        onStkProactiveCommand(s);
#endif
#ifndef USE_LEGACY_SAT_AT_CMDS
    else if (strStartsWith(s, "*ESHLREF:"))
        onStkSimRefresh(s);
#else
    else if (strStartsWith(s, "*ESIMRF:"))
        onStkSimRefresh(s);
#endif
    else if (strStartsWith(s, "*STKN:"))
        onStkEventNotify(s);
    else if (strStartsWith(s, "*ESHLVOCU:"))
        onStkEventNotify(s);
    else if (strStartsWith(s, "*ESHLSSU:"))
        onStkEventNotify(s);
    else if (strStartsWith(s, "*ESHLUSSU:"))
        onStkEventNotify(s);
    else if (strStartsWith(s, "*ESHLDTMFU:"))
        onStkEventNotify(s);
    else if (strStartsWith(s, "*ESHLSMSU:"))
        onStkEventNotify(s);
    else if (strStartsWith(s, "*EACE:"))
        onAudioCallEventNotify(s);
    else if (strStartsWith(s, "*EPSB:")) {
        onNetworkStateChanged(s);
        onEPSBReceived(s);
    } else
        onOemUnsolHook(s);
}

void signalCloseQueues(void)
{
    unsigned int i;
    setRadioState(RADIO_STATE_UNAVAILABLE);

    for (i = 0; i < NUM_ELEMS(s_requestQueues); i++) {
        int err;
        RequestQueue *q = s_requestQueues[i];
        if ((err = pthread_mutex_lock(&q->queueMutex)) != 0)
            LOGW("%s() failed to take queue mutex: %s",
                __func__, strerror(err));

        q->closed = 1;
        if ((err = pthread_cond_signal(&q->cond)) != 0)
            LOGW("%s() failed to broadcast queue update: %s",
                __func__, strerror(err));

        if ((err = pthread_mutex_unlock(&q->queueMutex)) != 0)
            LOGW("%s() failed to take queue mutex: %s", __func__,
                 strerror(err));
    }
}

static void signalManager(void)
{
    int err;

    if ((err = pthread_mutex_lock(&ril_manager_queue_exit_mutex)) != 0)
        LOG_FATAL("%s() failed to take RIL Manager AT fail mutex: %s",
                  __func__, strerror(err));

    if ((err = pthread_cond_signal(&ril_manager_queue_exit_cond)) != 0)
        LOGW("%s() failed to signal RIL Manager: %s",
             __func__, strerror(err));

    if ((err = pthread_mutex_unlock(&ril_manager_queue_exit_mutex)) != 0)
        LOG_FATAL("%s() failed to take RIL Manager AT Fail mutex: %s",
                  __func__, strerror(err));
}

/* Called on command or reader thread. */
static void onATReaderClosed()
{
    LOGI("AT channel closed, closing queues!");
    signalCloseQueues();
}

/* Callback from AT Channel. Called on command thread. */
static void onATTimeout()
{
    LOGI("AT channel timeout. Trying to abort command and check channel.");

    /* Throw escape on the channel and check sanity with handshake */
    at_send_escape();

    if (at_handshake() >= 0) {
        LOGI("AT channel sanity check successful. Continuing...");
    }
    else {
        LOG_FATAL("%s() Channel sanity check failed!", __func__);
        signalCloseQueues();

        /* Prevent further command execution */
        at_close();
    }
}

int parseGroups(char* groups, RILRequestGroup **parsedGroups)
{
    int n = 0;

    if (parsedGroups == NULL)
        return -1;

    /* DEFAULT group is mandatory */
    RILRequestGroups[CMD_QUEUE_DEFAULT].requestQueue->enabled = 1;
    parsedGroups[n] = &RILRequestGroups[CMD_QUEUE_DEFAULT];
    n++;

    /*
     * If only the DEFAULT group is specified on the command line
     * this is considered as a special case used for test purposes
     * and the AUXILIARY group will not be added.
     */
    if (strcasestr(groups, RILRequestGroups[CMD_QUEUE_DEFAULT].name) &&
        !strcasestr(groups, RILRequestGroups[CMD_QUEUE_AUXILIARY].name)) {
        LOGW("Only DEFAULT group is enabled!"
            " Using one group/AT channel is only for testing purposes.");
        goto exit;
    }

    /* AUXILIARY group is mandatory */
    RILRequestGroups[CMD_QUEUE_AUXILIARY].requestQueue->enabled = 1;
    parsedGroups[n] = &RILRequestGroups[CMD_QUEUE_AUXILIARY];
    n++;

exit:
    return n;
}

void initializeStateVariables()
{
    defaultQueueReady = false; /* Mutexes not required. Only called while queues
                                * are halted! */
    resetModemState(RESET_START);
}

void *queueRunner(void *param)
{
    int fd;
    int ret;
    struct queueArgs *queueArgs = (struct queueArgs *) param;
    struct RequestQueue *q = NULL;

    LOGI("%s() thread index %d waiting for Manager release flag", __func__,
         queueArgs->index);

    ret = pthread_mutex_lock(&ril_manager_queue_startup_mutex);
    if (ret != 0)
        LOGE("%s(): Failed to get mutex lock. err: %s", __func__,
                strerror(-ret));

    while (!g_managerRelease) {
        ret = pthread_cond_wait(&ril_manager_queue_startup_cond,
                                &ril_manager_queue_startup_mutex);
        if (ret != 0)
            LOGE("%s(): pthread_cond_wait Failed. err: %s", __func__,
                strerror(-ret));
    }

    ret = pthread_mutex_unlock(&ril_manager_queue_startup_mutex);
    if (ret != 0)
        LOGE("%s(): Failed to unlock mutex. err: %s", __func__,
                strerror(-ret));

    LOGI("%s() index %d setting up AT socket channel", __func__,
         queueArgs->index);
    fd = -1;
    while (fd < 0) {
        if (queueArgs->type == NULL) {
            LOGE("%s(): Unsupported channel type. Bailing out!", __func__);
            goto error;
        }

        if (!strncmp(queueArgs->type, "CAIF", 4)) {
#ifndef CAIF_SOCKET_SUPPORT_DISABLED
            int cf_prio = CAIF_PRIO_HIGH;

            struct sockaddr_caif addr = {
                .family = AF_CAIF,
                .u.at.type = CAIF_ATTYPE_PLAIN
            };

            fd = socket(AF_CAIF, SOCK_SEQPACKET, CAIFPROTO_AT);
            if (fd < 0) {
                LOGE("%s(): failed to create socket. errno: %d(%s).",
                    __func__, errno, strerror(-errno));
            }

            if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &cf_prio,
                sizeof(cf_prio)) != 0)
                LOGE("%s(): Not able to set socket priority. Errno:%d(%s).",
                     __func__, errno, strerror(-errno));

            ret = connect(fd, (struct sockaddr *) &addr, sizeof(addr));
            if (ret != 0) {
                LOGE("%s(): Failed to connect. errno: %d(%s).", __func__,
                    errno, strerror(-errno));
                goto error;
            }
#else
            LOGE("%s(): Unsupported channel type CAIF. Bailing out!",
                __func__);
            goto error;
#endif
        } else if (!strncmp(queueArgs->type, "UNIX", 4)) {
            struct sockaddr_un addr;
            int len;
            if (queueArgs->arg == NULL) {
                LOGE("%s(): No path specified for UNIX socket!"
                    " Bailing out!", __func__);
                goto error;
            }
            bzero((char *) &addr, sizeof(addr));
            addr.sun_family = AF_UNIX;

            strncpy(addr.sun_path, queueArgs->arg,
                    sizeof(addr.sun_path));
            len = strlen(addr.sun_path) + sizeof(addr.sun_family);
            fd = socket(AF_UNIX, SOCK_STREAM, 0);
            ret = connect(fd, (struct sockaddr *) &addr, len);
            if (ret != 0) {
                LOGE("%s(): Failed to connect. errno: %d(%s).", __func__,
                    errno, strerror(-errno));
                goto error;
            }
        } else if (!strncmp(queueArgs->type, "IP", 2)) {
            int port;
            if (!queueArgs->arg) {
                LOGE("%s(): No port specified for IP socket! "
                    "Bailing out!", __func__);
                goto error;
            }
            port = atoi(queueArgs->arg);
            if (queueArgs->xarg) {
                char *host = queueArgs->xarg;
                fd = socket_network_client(host, port, SOCK_STREAM);
            } else
                fd = socket_loopback_client(port, SOCK_STREAM);
        } else if (!strncmp(queueArgs->type, "TTY", 3)) {
            struct termios ios;
            fd = open(queueArgs->arg, O_RDWR);

            /* Disable echo on serial ports. */
            tcgetattr(fd, &ios);
            cfmakeraw(&ios);
            cfsetospeed(&ios, B115200);
            cfsetispeed(&ios, B115200);
            ios.c_cflag |= CREAD | CLOCAL;
            tcflush(fd, TCIOFLUSH);
            tcsetattr(fd, TCSANOW, &ios);
        } else if (!strncmp(queueArgs->type, "CHAR", 4))
            fd = open(queueArgs->arg, O_RDWR);

        if (fd < 0) {
            LOGE("%s() failed to open AT channel type:%s %s %s err:%s. "
                 "retrying in 10 s!",__func__,  queueArgs->type,
                 queueArgs->arg ? queueArgs->arg : "",
                 queueArgs->xarg ? queueArgs->xarg : "",
                 strerror(errno));
            sleep(10);
        }
    }
    ret = at_open(fd, onUnsolicited);

    if (ret < 0) {
        LOGE("%s(): AT error %d on at_open!", __func__, ret);
        goto error;
    }

    at_set_on_reader_closed(onATReaderClosed);
    at_set_on_timeout(onATTimeout);
    at_set_timeout_msec(3 * 60 * 1000);

    if (!initializeCommon()) {
        LOGE("%s(): initializeCommon() failed!", __func__);
        goto error;
    }

    q = queueArgs->group->requestQueue;
    q->closed = 0;

    if (queueArgs->group->group == CMD_QUEUE_DEFAULT) {
        if (!initializeDefault()) {
            LOGE("%s() failed to initialize default AT channel!",
                __func__);
            goto error;
        }
        at_make_default_channel();

        /*
         * Defaultqueue must be allowed to finish initialization before other
         * threads starts executing Android requests. Signalling other threads.
         */
        signalDefaultQueueReady();
    } else {
        waitDefaultQueueReady();
    }

    RILRequest *r = NULL;
    RILEvent   *e = NULL;

    LOGI("Looping the requestQueue for index %d!", queueArgs->index);
    for (;;) {
        struct timeval tv;
        struct timespec ts;
        int err;

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

        if ((err = pthread_mutex_lock(&q->queueMutex)) != 0) {
            LOGE("%s() failed to take queue mutex: %s!",
                __func__, strerror(err));
            /* Need to restart all threads and restart modem.*/
            goto error;
        }

        if (q->closed != 0) {
            LOGW("%s() index %d queue close indication, ending current thread!",
                __func__, queueArgs->index);
            if ((err = pthread_mutex_unlock(&q->queueMutex)) != 0)
                LOGE("Failed to release queue mutex: %s!", strerror(err));
            break;
        }

        while (q->closed == 0 && q->requestList == NULL &&
               q->eventList == NULL) {
            if ((err = pthread_cond_wait(&q->cond, &q->queueMutex)) != 0)
                LOGE("%s() failed to broadcast queue update: %s!",
                    __func__, strerror(err));
        }

        /* eventList is prioritized, smallest abstime first. */
        if (q->closed == 0 && q->requestList == NULL && q->eventList) {
            err = pthread_cond_timedwait(&q->cond, &q->queueMutex,
                                         &q->eventList->abstime);
            if (err && err != ETIMEDOUT)
                LOGE("%s(): Timedwait returned unexpected error: %s!",
                     __func__, strerror(err));
        }

        if (q->closed != 0) {
            if ((err = pthread_mutex_unlock(&q->queueMutex)) != 0)
                LOGW("%s(): Failed to release queue mutex: %s!",
                    __func__, strerror(err));
            break;
        }

        e = NULL;
        r = NULL;

        gettimeofday(&tv, NULL);

        ts.tv_sec = tv.tv_sec;
        ts.tv_nsec = tv.tv_usec * 1000;

        if (q->eventList != NULL &&
            timespec_cmp(q->eventList->abstime, ts, <)) {
            e = q->eventList;
            q->eventList = e->next;
        }

        if (q->requestList != NULL) {
            r = q->requestList;
            q->requestList = r->next;
        }

        if ((err = pthread_mutex_unlock(&q->queueMutex)) != 0)
            LOGW("%s(): Failed to release queue mutex: %s!",
                __func__, strerror(err));

        if (e) {
            e->eventCallback(e->param);
            free(e);
        }

        if (r) {
            processRequest(r->request, r->data, r->datalen, r->token);
            freeRequestData(r->request, r->data, r->datalen);
            free(r);
        }
    }

    goto exit;

error:
    signalCloseQueues();
    if (queueArgs != NULL &&
        queueArgs->group->group == CMD_QUEUE_DEFAULT) {
        signalDefaultQueueReady();
    }

exit:
    /* Final cleanup of queues. Radio state must be unavailable at this point */
    assert(s_state == RADIO_STATE_UNAVAILABLE);

    LOGI("%s() index %d start flushing all remaining requests and events!",
         __func__, queueArgs->index);
    /*
     * NOTE: There cannot be events that will generate response to earlier
     * requests. If so we have to let all events trigger immediatly and refuse
     * further events to be put on the queue.
     */
    /* Request queue cleanup */
    while (q != NULL && q->requestList != NULL) {
        r = q->requestList;
        q->requestList = r->next;
        if(!requestStateFilter(r->request, r->data, r->datalen, r->token)) {
            LOGE("%s() tried to send immidiate response to request but it was "
                 "not stopped by filter. Undefined behavior expected! Error!",
                 __func__);
        }
        freeRequestData(r->request, r->data, r->datalen);
        free(r);
    }
    /* Event queue cleanup */
    while (q != NULL && q->eventList != NULL) {
        e = q->eventList;
        q->eventList = e->next;
        free(e);
    }
    LOGI("%s() index %d finished flushing, queues emptied", __func__,
         queueArgs->index);

    /* Make sure AT channel is closed in case queueRunner triggered the exit */
    at_close();
    /*
     * Finally signal RIL Manager that this queueRunner and
     * AT channel is closed.
     */
    signalManager();

    LOGD("%s() thread with index %d ending", __func__, queueArgs->index);
    free(queueArgs);
    return NULL;
}