aboutsummaryrefslogtreecommitdiff
path: root/rmi4update/rmi4update.cpp
blob: 19eadb5846ad48b2fc22f5b020c2d2b4504bed1b (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
/*
 * Copyright (C) 2014 Andrew Duggan
 * Copyright (C) 2014 Synaptics Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <alloca.h>
#include <time.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include "rmi4update.h"

#define RMI_F34_QUERY_SIZE		7
#define RMI_F34_HAS_NEW_REG_MAP		(1 << 0)
#define RMI_F34_IS_UNLOCKED		(1 << 1)
#define RMI_F34_HAS_CONFIG_ID		(1 << 2)
#define RMI_F34_BLOCK_SIZE_OFFSET	1
#define RMI_F34_FW_BLOCKS_OFFSET	3
#define RMI_F34_CONFIG_BLOCKS_OFFSET	5

#define RMI_F34_BLOCK_SIZE_V1_OFFSET	0
#define RMI_F34_FW_BLOCKS_V1_OFFSET	0
#define RMI_F34_CONFIG_BLOCKS_V1_OFFSET	2

#define RMI_F34_BLOCK_DATA_OFFSET	2
#define RMI_F34_BLOCK_DATA_V1_OFFSET	1

#define RMI_F34_COMMAND_MASK		0x0F
#define RMI_F34_STATUS_MASK		0x07
#define RMI_F34_STATUS_SHIFT		4
#define RMI_F34_ENABLED_MASK		0x80

#define RMI_F34_COMMAND_V1_MASK		0x3F
#define RMI_F34_STATUS_V1_MASK		0x3F
#define RMI_F34_ENABLED_V1_MASK		0x80

#define RMI_F34_WRITE_FW_BLOCK        0x02
#define RMI_F34_ERASE_ALL             0x03
#define RMI_F34_WRITE_LOCKDOWN_BLOCK  0x04
#define RMI_F34_WRITE_CONFIG_BLOCK    0x06
#define RMI_F34_ENABLE_FLASH_PROG     0x0f

#define RMI_F34_ENABLE_WAIT_MS 300
#define RMI_F34_ERASE_WAIT_MS (5 * 1000)
#define RMI_F34_ERASE_V8_WAIT_MS (10000)
#define RMI_F34_IDLE_WAIT_MS 500

/* Most recent device status event */
#define RMI_F01_STATUS_CODE(status)		((status) & 0x0f)
/* Indicates that flash programming is enabled (bootloader mode). */
#define RMI_F01_STATUS_BOOTLOADER(status)	(!!((status) & 0x40))
/* The device has lost its configuration for some reason. */
#define RMI_F01_STATUS_UNCONFIGURED(status)	(!!((status) & 0x80))

/* Indicates that flash programming is enabled V7(bootloader mode). */
#define RMI_F01_STATUS_BOOTLOADER_v7(status) (!!((status) & 0x80))

/*
 * Sleep mode controls power management on the device and affects all
 * functions of the device.
 */
#define RMI_F01_CTRL0_SLEEP_MODE_MASK	0x03

#define RMI_SLEEP_MODE_NORMAL		0x00
#define RMI_SLEEP_MODE_SENSOR_SLEEP	0x01
#define RMI_SLEEP_MODE_RESERVED0	0x02
#define RMI_SLEEP_MODE_RESERVED1	0x03

/*
 * This bit disables whatever sleep mode may be selected by the sleep_mode
 * field and forces the device to run at full power without sleeping.
 */
#define RMI_F01_CRTL0_NOSLEEP_BIT	(1 << 2)

int RMI4Update::UpdateFirmware(bool force, bool performLockdown)
{
	struct timespec start;
	struct timespec end;
	long long int duration_us = 0;
	int rc;
	const unsigned char eraseAll = RMI_F34_ERASE_ALL;
	rc = FindUpdateFunctions();
	if (rc != UPDATE_SUCCESS)
		return rc;

	rc = m_device.QueryBasicProperties();
	if (rc < 0)
		return UPDATE_FAIL_QUERY_BASIC_PROPERTIES;

	if (!force && m_firmwareImage.HasIO()) {
		if (m_firmwareImage.GetFirmwareID() <= m_device.GetFirmwareID()) {
			fprintf(stderr, "Firmware image (%ld) is not newer then the firmware on the device (%ld)\n",
				m_firmwareImage.GetFirmwareID(), m_device.GetFirmwareID());
			rc = UPDATE_FAIL_FIRMWARE_IMAGE_IS_OLDER;
			return rc;
		}
	}

	fprintf(stdout, "Device Properties:\n");
	m_device.PrintProperties();

	rc = DisableNonessentialInterupts();
	if (rc != UPDATE_SUCCESS)
		return rc;

	rc = ReadF34Queries();
	if (rc != UPDATE_SUCCESS)
		return rc;
	rc = m_firmwareImage.VerifyImageMatchesDevice(GetFirmwareSize(), GetConfigSize());
	if (rc != UPDATE_SUCCESS)
		return rc;

	if (m_f34.GetFunctionVersion() == 0x02) {
		fprintf(stdout, "Enable Flash V7+...\n");
		rc = EnterFlashProgrammingV7();
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			goto reset;
		}
		fprintf(stdout, "Enable Flash done V7+...\n");

		if (!m_IsErased){
			fprintf(stdout, "Erasing FW V7+...\n");
			rc = EraseFirmwareV7();
			if (rc != UPDATE_SUCCESS) {
				fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
				goto reset;
			}
			fprintf(stdout, "Erasing FW done V7+...\n");
		}
		if(m_bootloaderID[1] == 8){
			if (m_firmwareImage.GetFlashConfigData()) {
				fprintf(stdout, "Writing flash configuration V8...\n");
				rc = WriteFlashConfigV7();
				if (rc != UPDATE_SUCCESS) {
					fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
					goto reset;
				}
				fprintf(stdout, "Writing flash config done V8...\n");
			}
		}
		if (m_firmwareImage.GetFirmwareData()) {
			fprintf(stdout, "Writing firmware V7+...\n");
			rc = WriteFirmwareV7();
			if (rc != UPDATE_SUCCESS) {
				fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
				goto reset;
			}
			fprintf(stdout, "Writing firmware done V7+...\n");
		}
		if (m_firmwareImage.GetConfigData()) {
			fprintf(stdout, "Writing core configuration V7+...\n");
			rc = WriteCoreConfigV7();
			if (rc != UPDATE_SUCCESS) {
				fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
				goto reset;
			}
			fprintf(stdout, "Writing core config done V7+...\n");
			goto reset;
		}
		
	} else {
		rc = EnterFlashProgramming();
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			goto reset;
		}
	}

	if (performLockdown && m_unlocked) {
		if (m_firmwareImage.GetLockdownData()) {
			fprintf(stdout, "Writing lockdown...\n");
			clock_gettime(CLOCK_MONOTONIC, &start);
			rc = WriteBlocks(m_firmwareImage.GetLockdownData(),
					m_firmwareImage.GetLockdownSize() / 0x10,
					RMI_F34_WRITE_LOCKDOWN_BLOCK);
			if (rc != UPDATE_SUCCESS) {
				fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
				goto reset;
			}
			clock_gettime(CLOCK_MONOTONIC, &end);
			duration_us = diff_time(&start, &end);
			fprintf(stdout, "Done writing lockdown, time: %lld us.\n", duration_us);
		}

		rc = EnterFlashProgramming();
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			goto reset;
		}
	}

	rc = WriteBootloaderID();
	if (rc != UPDATE_SUCCESS) {
		fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
		goto reset;
	}

	fprintf(stdout, "Erasing FW...\n");
	clock_gettime(CLOCK_MONOTONIC, &start);
	rc = m_device.Write(m_f34StatusAddr, &eraseAll, 1);
	if (rc != 1) {
		fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(UPDATE_FAIL_ERASE_ALL));
		rc = UPDATE_FAIL_ERASE_ALL;
		goto reset;
	}

	rc = WaitForIdle(RMI_F34_ERASE_WAIT_MS);
	if (rc != UPDATE_SUCCESS) {
		fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
		goto reset;
	}
	clock_gettime(CLOCK_MONOTONIC, &end);
	duration_us = diff_time(&start, &end);
	fprintf(stdout, "Erase complete, time: %lld us.\n", duration_us);

	if (m_firmwareImage.GetFirmwareData()) {
		fprintf(stdout, "Writing firmware...\n");
		clock_gettime(CLOCK_MONOTONIC, &start);
		rc = WriteBlocks(m_firmwareImage.GetFirmwareData(), m_fwBlockCount,
						RMI_F34_WRITE_FW_BLOCK);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			goto reset;
		}
		clock_gettime(CLOCK_MONOTONIC, &end);
		duration_us = diff_time(&start, &end);
		fprintf(stdout, "Done writing FW, time: %lld us.\n", duration_us);
	}

	if (m_firmwareImage.GetConfigData()) {
		fprintf(stdout, "Writing configuration...\n");
		clock_gettime(CLOCK_MONOTONIC, &start);
		rc = WriteBlocks(m_firmwareImage.GetConfigData(), m_configBlockCount,
				RMI_F34_WRITE_CONFIG_BLOCK);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			goto reset;
		}
		clock_gettime(CLOCK_MONOTONIC, &end);
		duration_us = diff_time(&start, &end);
		fprintf(stdout, "Done writing config, time: %lld us.\n", duration_us);
	}

reset:
	m_device.Reset();
rebind:
	m_device.RebindDriver();
	if(!m_device.CheckABSEvent())
	{
		goto rebind;
	}

	// In order to print out new PR
	rc = FindUpdateFunctions();
	if (rc != UPDATE_SUCCESS)
		return rc;

	rc = m_device.QueryBasicProperties();
	if (rc < 0)
		return UPDATE_FAIL_QUERY_BASIC_PROPERTIES;
	fprintf(stdout, "Device Properties:\n");
	m_device.PrintProperties();

	return rc;

}

int RMI4Update::DisableNonessentialInterupts()
{
	int rc;
	unsigned char interruptEnabeMask = m_f34.GetInterruptMask() | m_f01.GetInterruptMask();

	rc = m_device.Write(m_f01.GetControlBase() + 1, &interruptEnabeMask, 1);
	if (rc != 1)
		return rc;

	return UPDATE_SUCCESS;
}

int RMI4Update::FindUpdateFunctions()
{
	if (0 > m_device.ScanPDT())
		return UPDATE_FAIL_SCAN_PDT;

	if (!m_device.GetFunction(m_f01, 0x01))
		return UPDATE_FAIL_NO_FUNCTION_01;

	if (!m_device.GetFunction(m_f34, 0x34))
		return UPDATE_FAIL_NO_FUNCTION_34;

	return UPDATE_SUCCESS;
}

int RMI4Update::rmi4update_poll()
{
	unsigned char f34_status;
	unsigned short dataAddr = m_f34.GetDataBase();
	int rc;

	rc = m_device.Read(dataAddr, &f34_status, sizeof(unsigned char));
	if (rc != sizeof(unsigned char))
		return UPDATE_FAIL_WRITE_FLASH_COMMAND;

	m_flashStatus = f34_status & 0x1F;
	m_inBLmode = f34_status & 0x80;
	if(!m_flashStatus)
		rc = m_device.Read(dataAddr + 4, &m_flashCmd, sizeof(unsigned char));

	return 0;
}

int RMI4Update::ReadFlashConfig()
{
	int rc;
	int transaction_count, remain_block;
	unsigned char *flash_cfg;
	int transfer_leng = 0;
	int read_leng = 0;
	int offset = 0;
	unsigned char trans_leng_buf[2];
	unsigned char cmd_buf[1];
	unsigned char off[2] = {0, 0};
	unsigned char partition_id = FLASH_CONFIG_PARTITION;
	unsigned short dataAddr = m_f34.GetDataBase();
	int i;
	int retry = 0;
	unsigned char *data_temp;
	struct partition_tbl *partition_temp;

	flash_cfg = (unsigned char *)malloc(m_blockSize * m_flashConfigLength);
	memset(flash_cfg, 0, m_blockSize * m_flashConfigLength);
	partition_temp = (partition_tbl *)malloc(sizeof(struct partition_tbl));
	memset(partition_temp, 0, sizeof(struct partition_tbl));
	/* calculate the count */
	remain_block = (m_flashConfigLength % m_payloadLength);
	transaction_count = (m_flashConfigLength / m_payloadLength);

	if (remain_block > 0)
		transaction_count++;

	/* set partition id for bootloader 7 */
	rc = m_device.Write(dataAddr + 1, &partition_id, sizeof(partition_id));
	if (rc != sizeof(partition_id))
		return UPDATE_FAIL_WRITE_FLASH_COMMAND;
	rc = m_device.Write(dataAddr + 2, off, sizeof(off));
	if (rc != sizeof(off))
		return UPDATE_FAIL_WRITE_INITIAL_ZEROS;

	for (i = 0; i < transaction_count; i++)
	{
		if ((i == (transaction_count -1)) && (remain_block > 0))
			transfer_leng = remain_block;
		else
			transfer_leng = m_payloadLength;

		// Set Transfer Length
		trans_leng_buf[0] = (unsigned char)(transfer_leng & 0xFF);
		trans_leng_buf[1] = (unsigned char)((transfer_leng & 0xFF00) >> 8);
		rc = m_device.Write(dataAddr + 3, trans_leng_buf, sizeof(trans_leng_buf));
		if (rc != sizeof(trans_leng_buf))
			return UPDATE_FAIL_WRITE_FLASH_COMMAND;

		// Set Command to Read
		cmd_buf[0] = (unsigned char)CMD_V7_READ;
		rc = m_device.Write(dataAddr + 4, cmd_buf, sizeof(cmd_buf));
		if (rc != sizeof(cmd_buf))
			return UPDATE_FAIL_WRITE_FLASH_COMMAND;

		//Wait for completion
		do {
			Sleep(20);
			rmi4update_poll();
			if (m_flashStatus == SUCCESS){
				break;
			}
			retry++;
		} while(retry < 20);

		read_leng = transfer_leng * m_blockSize;
		data_temp = (unsigned char *) malloc(sizeof(char) * read_leng);
		rc = m_device.Read(dataAddr + 5, data_temp, sizeof(char) * read_leng);
		if (rc != ((ssize_t)sizeof(char) * read_leng))
			return UPDATE_FAIL_READ_F34_QUERIES;

		memcpy(flash_cfg + offset, data_temp, sizeof(char) * read_leng);
		offset += read_leng;
		free(data_temp);
	}

	// Initialize as NULL here to avoid segmentation fault.
	m_partitionConfig = NULL;
	m_partitionCore = NULL;
	m_partitionGuest = NULL;

	/* parse the config length */
	for (i = 2; i < m_blockSize * m_flashConfigLength; i = i + 8)
	{
		memcpy(partition_temp->data ,flash_cfg + i, sizeof(struct partition_tbl));
		if (partition_temp->partition_id == CORE_CONFIG_PARTITION)
		{
			m_partitionConfig = (partition_tbl *) malloc(sizeof(struct partition_tbl));
			memcpy(m_partitionConfig ,partition_temp, sizeof(struct partition_tbl));
			memset(partition_temp, 0, sizeof(struct partition_tbl));
			fprintf(stdout, "CORE_CONFIG_PARTITION is found\n");
		}
		else if (partition_temp->partition_id == CORE_CODE_PARTITION)
		{
			m_partitionCore = (partition_tbl *) malloc(sizeof(struct partition_tbl));
			memcpy(m_partitionCore ,partition_temp, sizeof(struct partition_tbl));
			memset(partition_temp, 0, sizeof(struct partition_tbl));
			fprintf(stdout, "CORE_CODE_PARTITION is found\n");
		}
		else if (partition_temp->partition_id == GUEST_CODE_PARTITION)
		{
			m_partitionGuest = (partition_tbl *) malloc(sizeof(struct partition_tbl));
			memcpy(m_partitionGuest ,partition_temp, sizeof(struct partition_tbl));
			memset(partition_temp, 0, sizeof(struct partition_tbl));
			fprintf(stdout, "GUEST_CODE_PARTITION is found\n");
		}
		else if (partition_temp->partition_id == NONE_PARTITION)
			break;
	}

	if (flash_cfg)
		free(flash_cfg);

	if (partition_temp)
		free(partition_temp);

	m_fwBlockCount = m_partitionCore ? m_partitionCore->partition_len : 0;
	m_configBlockCount = m_partitionConfig ? m_partitionConfig->partition_len : 0;
	m_guestBlockCount = m_partitionGuest ? m_partitionGuest->partition_len : 0;
	fprintf(stdout, "F34 fw blocks:     %d\n", m_fwBlockCount);
	fprintf(stdout, "F34 config blocks: %d\n", m_configBlockCount);
	fprintf(stdout, "F34 guest blocks:     %d\n", m_guestBlockCount);
	fprintf(stdout, "\n");

	m_guestData = (unsigned char *) malloc(m_guestBlockCount * m_blockSize);
	memset(m_guestData, 0, m_guestBlockCount * m_blockSize);
	memset(m_guestData + m_guestBlockCount * m_blockSize -4, 0, 4);
	return UPDATE_SUCCESS;
}

int RMI4Update::ReadF34QueriesV7()
{
	int rc;
	struct f34_v7_query_0 query_0;
	struct f34_v7_query_1_7 query_1_7;
	unsigned char idStr[3];
	unsigned short queryAddr = m_f34.GetQueryBase();
	unsigned char offset;

	rc = m_device.Read(queryAddr, query_0.data, sizeof(query_0.data));
	if (rc != sizeof(query_0.data))
		return UPDATE_FAIL_READ_BOOTLOADER_ID;

	offset = query_0.subpacket_1_size + 1;
	rc = m_device.Read(queryAddr + offset, query_1_7.data, sizeof(query_1_7.data));
	if (rc != sizeof(query_1_7.data))
		return UPDATE_FAIL_READ_BOOTLOADER_ID;

	m_bootloaderID[0] = query_1_7.bl_minor_revision;
	m_bootloaderID[1] = query_1_7.bl_major_revision;
	m_hasConfigID = query_0.has_config_id;
	m_blockSize = query_1_7.block_size_15_8 << 8 |
			query_1_7.block_size_7_0;
	m_flashConfigLength = query_1_7.flash_config_length_15_8 << 8 |
				query_1_7.flash_config_length_7_0;
	m_payloadLength = query_1_7.payload_length_15_8 << 8 |
			query_1_7.payload_length_7_0;
	m_buildID = query_1_7.bl_fw_id_7_0 |
			query_1_7.bl_fw_id_15_8 << 8 |
			query_1_7.bl_fw_id_23_16 << 16 |
			query_1_7.bl_fw_id_31_24 << 24;

	idStr[0] = m_bootloaderID[0];
	idStr[1] = m_bootloaderID[1];
	idStr[2] = 0;

	fprintf(stdout, "F34 bootloader id: %s (%#04x %#04x)\n", idStr, m_bootloaderID[0],
		m_bootloaderID[1]);
	fprintf(stdout, "F34 has config id: %d\n", m_hasConfigID);
	fprintf(stdout, "F34 unlocked:      %d\n", m_unlocked);
	fprintf(stdout, "F34 block size:    %d\n", m_blockSize);
	fprintf(stdout, "F34 flash cfg leng:%d\n", m_flashConfigLength);
	fprintf(stdout, "F34 payload length:%d\n", m_payloadLength);
	fprintf(stdout, "F34 build id:      %lu\n", m_buildID);

	return ReadFlashConfig();
}

int RMI4Update::ReadF34Queries()
{
	int rc;
	unsigned char idStr[3];
	unsigned char buf[8];
	unsigned short queryAddr = m_f34.GetQueryBase();
	unsigned short f34Version = m_f34.GetFunctionVersion();
	unsigned short querySize;

	if (f34Version == 0x2)
		return ReadF34QueriesV7();
	else if (f34Version == 0x1)
		querySize = 8;
	else
		querySize = 2;

	rc = m_device.Read(queryAddr, m_bootloaderID, RMI_BOOTLOADER_ID_SIZE);
	if (rc != RMI_BOOTLOADER_ID_SIZE)
		return UPDATE_FAIL_READ_BOOTLOADER_ID;

	if (f34Version == 0x1)
		++queryAddr;
	else
		queryAddr += querySize;

	if (f34Version == 0x1) {
		rc = m_device.Read(queryAddr, buf, 1);
		if (rc != 1)
			return UPDATE_FAIL_READ_F34_QUERIES;

		m_hasNewRegmap = buf[0] & RMI_F34_HAS_NEW_REG_MAP;
		m_unlocked = buf[0] & RMI_F34_IS_UNLOCKED;;
		m_hasConfigID = buf[0] & RMI_F34_HAS_CONFIG_ID;

		++queryAddr;

		rc = m_device.Read(queryAddr, buf, 2);
		if (rc != 2)
			return UPDATE_FAIL_READ_F34_QUERIES;

		m_blockSize = extract_short(buf + RMI_F34_BLOCK_SIZE_V1_OFFSET);

		++queryAddr;

		rc = m_device.Read(queryAddr, buf, 8);
		if (rc != 8)
			return UPDATE_FAIL_READ_F34_QUERIES;

		m_fwBlockCount = extract_short(buf + RMI_F34_FW_BLOCKS_V1_OFFSET);
		m_configBlockCount = extract_short(buf + RMI_F34_CONFIG_BLOCKS_V1_OFFSET);
	} else {
		rc = m_device.Read(queryAddr, buf, RMI_F34_QUERY_SIZE);
		if (rc != RMI_F34_QUERY_SIZE)
			return UPDATE_FAIL_READ_F34_QUERIES;

		m_hasNewRegmap = buf[0] & RMI_F34_HAS_NEW_REG_MAP;
		m_unlocked = buf[0] & RMI_F34_IS_UNLOCKED;;
		m_hasConfigID = buf[0] & RMI_F34_HAS_CONFIG_ID;
		m_blockSize = extract_short(buf + RMI_F34_BLOCK_SIZE_OFFSET);
		m_fwBlockCount = extract_short(buf + RMI_F34_FW_BLOCKS_OFFSET);
		m_configBlockCount = extract_short(buf + RMI_F34_CONFIG_BLOCKS_OFFSET);
	}

	idStr[0] = m_bootloaderID[0];
	idStr[1] = m_bootloaderID[1];
	idStr[2] = 0;

	fprintf(stdout, "F34 bootloader id: %s (%#04x %#04x)\n", idStr, m_bootloaderID[0],
		m_bootloaderID[1]);
	fprintf(stdout, "F34 has config id: %d\n", m_hasConfigID);
	fprintf(stdout, "F34 unlocked:      %d\n", m_unlocked);
	fprintf(stdout, "F34 new reg map:   %d\n", m_hasNewRegmap);
	fprintf(stdout, "F34 block size:    %d\n", m_blockSize);
	fprintf(stdout, "F34 fw blocks:     %d\n", m_fwBlockCount);
	fprintf(stdout, "F34 config blocks: %d\n", m_configBlockCount);
	fprintf(stdout, "\n");

	if (f34Version == 0x1)
		m_f34StatusAddr = m_f34.GetDataBase() + 2;
	else
		m_f34StatusAddr = m_f34.GetDataBase() + RMI_F34_BLOCK_DATA_OFFSET + m_blockSize;

	return UPDATE_SUCCESS;
}

int RMI4Update::ReadF34Controls()
{
	int rc;
	unsigned char buf[2];

	if (m_f34.GetFunctionVersion() == 0x1) {
		rc = m_device.Read(m_f34StatusAddr, buf, 2);
		if (rc != 2)
			return UPDATE_FAIL_READ_F34_CONTROLS;

		m_f34Command = buf[0] & RMI_F34_COMMAND_V1_MASK;
		m_f34Status = buf[1] & RMI_F34_STATUS_V1_MASK;
		m_programEnabled = !!(buf[1] & RMI_F34_ENABLED_MASK);

	} else {
		rc = m_device.Read(m_f34StatusAddr, buf, 1);
		if (rc != 1)
			return UPDATE_FAIL_READ_F34_CONTROLS;

		m_f34Command = buf[0] & RMI_F34_COMMAND_MASK;
		m_f34Status = (buf[0] >> RMI_F34_STATUS_SHIFT) & RMI_F34_STATUS_MASK;
		m_programEnabled = !!(buf[0] & RMI_F34_ENABLED_MASK);
	}
	
	return UPDATE_SUCCESS;
}

int RMI4Update::WriteBootloaderID()
{
	int rc;
	int blockDataOffset = RMI_F34_BLOCK_DATA_OFFSET;

	if (m_f34.GetFunctionVersion() == 0x1)
		blockDataOffset = RMI_F34_BLOCK_DATA_V1_OFFSET;

	rc = m_device.Write(m_f34.GetDataBase() + blockDataOffset,
				m_bootloaderID, RMI_BOOTLOADER_ID_SIZE);
	if (rc != RMI_BOOTLOADER_ID_SIZE)
		return UPDATE_FAIL_WRITE_BOOTLOADER_ID;

	return UPDATE_SUCCESS;
}

int RMI4Update::WriteFirmwareV7()
{
	int transaction_count, remain_block;
	int transfer_leng = 0;
	int offset = 0;
	unsigned char trans_leng_buf[2];
	unsigned char cmd_buf[1];
	unsigned char off[2] = {0, 0};
	unsigned char partition_id;
	int i;
	int retry = 0;
	unsigned char *data_temp;
	int rc;
	unsigned short left_bytes;
	unsigned short write_size;
	unsigned short max_write_size;
	unsigned short dataAddr = m_f34.GetDataBase();

	/* calculate the count */
	partition_id = CORE_CODE_PARTITION;
	remain_block = (m_fwBlockCount % m_payloadLength);
	transaction_count = (m_fwBlockCount / m_payloadLength);
	if (remain_block > 0)
		transaction_count++;

	/* set partition id for bootloader 7 */
	rc = m_device.Write(dataAddr + 1, &partition_id, sizeof(partition_id));
	if (rc != sizeof(partition_id))
		return UPDATE_FAIL_WRITE_FLASH_COMMAND;

	rc = m_device.Write(dataAddr + 2, off, sizeof(off));
	if (rc != sizeof(off))
		return UPDATE_FAIL_WRITE_INITIAL_ZEROS;

	for (i = 0; i < transaction_count; i++)
	{
		if ((i == (transaction_count -1)) && (remain_block > 0))
			transfer_leng = remain_block;
		else
			transfer_leng = m_payloadLength;

		// Set Transfer Length
		trans_leng_buf[0] = (unsigned char)(transfer_leng & 0xFF);
		trans_leng_buf[1] = (unsigned char)((transfer_leng & 0xFF00) >> 8);

		rc = m_device.Write(dataAddr + 3, trans_leng_buf, sizeof(trans_leng_buf));
		if (rc != sizeof(trans_leng_buf))
			return UPDATE_FAIL_WRITE_FLASH_COMMAND;

		// Set Command to Write
		cmd_buf[0] = (unsigned char)CMD_V7_WRITE;
		rc = m_device.Write(dataAddr + 4, cmd_buf, sizeof(cmd_buf));
		if (rc != sizeof(cmd_buf))
			return UPDATE_FAIL_WRITE_FLASH_COMMAND;

		max_write_size = 16;
		if (max_write_size >= transfer_leng * m_blockSize)
			max_write_size = transfer_leng * m_blockSize;
		else if (max_write_size > m_blockSize)
			max_write_size -= max_write_size % m_blockSize;
		else
			max_write_size = m_blockSize;

		left_bytes = transfer_leng * m_blockSize;
		do {
			if (left_bytes / max_write_size)
				write_size = max_write_size;
			else
				write_size = left_bytes;

			data_temp = (unsigned char *) malloc(sizeof(unsigned char) * write_size);
			memcpy(data_temp, m_firmwareImage.GetFirmwareData() + offset, sizeof(char) * write_size);
			rc = m_device.Write(dataAddr + 5, data_temp, sizeof(char) * write_size);
			if (rc != ((ssize_t)sizeof(char) * write_size)) {
				fprintf(stdout, "err write_size = %d; rc = %d\n", write_size, rc);
				return UPDATE_FAIL_READ_F34_QUERIES;
			}

			offset += write_size;
			left_bytes -= write_size;
			free(data_temp);
		} while (left_bytes);

		// Sleep 100 ms and wait for attention.
		Sleep(100);
		rc = WaitForIdle(RMI_F34_IDLE_WAIT_MS, false);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			return UPDATE_FAIL_TIMEOUT_WAITING_FOR_ATTN;
		}

		//Wait for completion
		do {
			Sleep(20);
			rmi4update_poll();
			if (m_flashStatus == SUCCESS){
				break;

			}
			retry++;
		} while(retry < 20);

		if (m_flashStatus != SUCCESS) {
			fprintf(stdout, "err flash_status = %d\n", m_flashStatus);
			return UPDATE_FAIL_WRITE_F01_CONTROL_0;
		}

	}
	return UPDATE_SUCCESS;
}

int RMI4Update::WriteCoreConfigV7()
{
	int transaction_count, remain_block;
	int transfer_leng = 0;
	int offset = 0;
	unsigned char trans_leng_buf[2];
	unsigned char cmd_buf[1];
	unsigned char off[2] = {0, 0};
	unsigned char partition_id;
	unsigned short dataAddr = m_f34.GetDataBase();
	unsigned short left_bytes;
	unsigned short write_size;
	unsigned short max_write_size;
	int rc;
	int i;
	int retry = 0;
	unsigned char *data_temp;

	/* calculate the count */
	partition_id = CORE_CONFIG_PARTITION;
	remain_block = (m_configBlockCount % m_payloadLength);
	transaction_count = (m_configBlockCount / m_payloadLength);
	if (remain_block > 0)
		transaction_count++;

	/* set partition id for bootloader 7 */
	rc = m_device.Write(dataAddr + 1, &partition_id, sizeof(partition_id));
	if (rc != sizeof(partition_id))
		return UPDATE_FAIL_WRITE_FLASH_COMMAND;

	rc = m_device.Write(dataAddr + 2, off, sizeof(off));
	if (rc != sizeof(off))
		return UPDATE_FAIL_WRITE_INITIAL_ZEROS;

	for (i = 0; i < transaction_count; i++)
	{
		if ((i == (transaction_count -1)) && (remain_block > 0))
			transfer_leng = remain_block;
		else
			transfer_leng = m_payloadLength;

		// Set Transfer Length
		trans_leng_buf[0] = (unsigned char)(transfer_leng & 0xFF);
		trans_leng_buf[1] = (unsigned char)((transfer_leng & 0xFF00) >> 8);

		rc = m_device.Write(dataAddr + 3, trans_leng_buf, sizeof(trans_leng_buf));
		if (rc != sizeof(trans_leng_buf))
			return UPDATE_FAIL_WRITE_FLASH_COMMAND;

		// Set Command to Write
		cmd_buf[0] = (unsigned char)CMD_V7_WRITE;
		rc = m_device.Write(dataAddr + 4, cmd_buf, sizeof(cmd_buf));
		if (rc != sizeof(cmd_buf))
			return UPDATE_FAIL_WRITE_FLASH_COMMAND;

		max_write_size = 16;
		if (max_write_size >= transfer_leng * m_blockSize)
			max_write_size = transfer_leng * m_blockSize;
		else if (max_write_size > m_blockSize)
			max_write_size -= max_write_size % m_blockSize;
		else
			max_write_size = m_blockSize;

		left_bytes = transfer_leng * m_blockSize;

		do {
			if (left_bytes / max_write_size)
				write_size = max_write_size;
			else
				write_size = left_bytes;

			data_temp = (unsigned char *) malloc(sizeof(unsigned char) * write_size);
			memcpy(data_temp, m_firmwareImage.GetConfigData() + offset, sizeof(char) * write_size);
			rc = m_device.Write(dataAddr + 5, data_temp, sizeof(char) * write_size);
			if (rc != ((ssize_t)sizeof(char) * write_size)) {
				return UPDATE_FAIL_READ_F34_QUERIES;
			}

			offset += write_size;
			left_bytes -= write_size;
			free(data_temp);
		} while (left_bytes);

		// Wait for attention.
		rc = WaitForIdle(RMI_F34_IDLE_WAIT_MS, false);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			return UPDATE_FAIL_TIMEOUT_WAITING_FOR_ATTN;
		}

		//Wait for completion
		do {
			Sleep(20);
			rmi4update_poll();
			if (m_flashStatus == SUCCESS){
				break;
			}
			retry++;
		} while(retry < 20);

		if (m_flashStatus != SUCCESS) {
			fprintf(stdout, "err flash_status = %d\n", m_flashStatus);
			return UPDATE_FAIL_WRITE_F01_CONTROL_0;
		}

	}
	return UPDATE_SUCCESS;
}

int RMI4Update::WriteFlashConfigV7()
{
	int transaction_count, remain_block;
	int transfer_leng = 0;
	int offset = 0;
	unsigned char trans_leng_buf[2];
	unsigned char cmd_buf[1];
	unsigned char off[2] = {0, 0};
	unsigned char partition_id;
	unsigned short dataAddr = m_f34.GetDataBase();
	unsigned short left_bytes;
	unsigned short write_size;
	unsigned short max_write_size;
	int rc;
	int i;
	int retry = 0;
	unsigned char *data_temp;
	unsigned short FlashConfigBlockCount;

	/* calculate the count */
	partition_id = FLASH_CONFIG_PARTITION;

	FlashConfigBlockCount = m_firmwareImage.GetFlashConfigSize() / m_blockSize;

	remain_block = (FlashConfigBlockCount % m_payloadLength);
	transaction_count = (FlashConfigBlockCount / m_payloadLength);
	if (remain_block > 0)
		transaction_count++;

	/* set partition id for bootloader 7 */
	rc = m_device.Write(dataAddr + 1, &partition_id, sizeof(partition_id));
	if (rc != sizeof(partition_id))
		return UPDATE_FAIL_WRITE_FLASH_COMMAND;

	rc = m_device.Write(dataAddr + 2, off, sizeof(off));
	if (rc != sizeof(off))
		return UPDATE_FAIL_WRITE_INITIAL_ZEROS;

	for (i = 0; i < transaction_count; i++)
	{
		if ((i == (transaction_count -1)) && (remain_block > 0))
			transfer_leng = remain_block;
		else
			transfer_leng = m_payloadLength;

		// Set Transfer Length
		trans_leng_buf[0] = (unsigned char)(transfer_leng & 0xFF);
		trans_leng_buf[1] = (unsigned char)((transfer_leng & 0xFF00) >> 8);

		rc = m_device.Write(dataAddr + 3, trans_leng_buf, sizeof(trans_leng_buf));
		if (rc != sizeof(trans_leng_buf))
			return UPDATE_FAIL_WRITE_FLASH_COMMAND;

		// Set Command to Write
		cmd_buf[0] = (unsigned char)CMD_V7_WRITE;
		rc = m_device.Write(dataAddr + 4, cmd_buf, sizeof(cmd_buf));
		if (rc != sizeof(cmd_buf))
			return UPDATE_FAIL_WRITE_FLASH_COMMAND;

		max_write_size = 16;
		if (max_write_size >= transfer_leng * m_blockSize)
			max_write_size = transfer_leng * m_blockSize;
		else if (max_write_size > m_blockSize)
			max_write_size -= max_write_size % m_blockSize;
		else
			max_write_size = m_blockSize;

		left_bytes = transfer_leng * m_blockSize;

		do {
			if (left_bytes / max_write_size)
				write_size = max_write_size;
			else
				write_size = left_bytes;

			data_temp = (unsigned char *) malloc(sizeof(unsigned char) * write_size);
			memcpy(data_temp, m_firmwareImage.GetFlashConfigData() + offset, sizeof(char) * write_size);
			rc = m_device.Write(dataAddr + 5, data_temp, sizeof(char) * write_size);
			if (rc != ((ssize_t)sizeof(char) * write_size)) {
				fprintf(stdout, "err write_size = %d; rc = %d\n", write_size, rc);
				return UPDATE_FAIL_READ_F34_QUERIES;
			}

			offset += write_size;
			left_bytes -= write_size;
			free(data_temp);
		} while (left_bytes);

		// Wair for attention.
		rc = WaitForIdle(RMI_F34_IDLE_WAIT_MS, false);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			return UPDATE_FAIL_TIMEOUT_WAITING_FOR_ATTN;
		}

		//Wait for completion
		do {
			Sleep(20);
			rmi4update_poll();
			if (m_flashStatus == SUCCESS){
				break;
			}
			retry++;
		} while(retry < 20);

		if (m_flashStatus != SUCCESS) {
			fprintf(stdout, "err flash_status = %d\n", m_flashStatus);
			return UPDATE_FAIL_WRITE_F01_CONTROL_0;
		}

	}
	return UPDATE_SUCCESS;
}

int RMI4Update::EraseFirmwareV7()
{
	unsigned char erase_cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};
	int retry = 0;
	int rc;

	/* set partition id for bootloader 7 */
	erase_cmd[0] = CORE_CODE_PARTITION;
	/* write bootloader id */
	erase_cmd[6] = m_bootloaderID[0];
	erase_cmd[7] = m_bootloaderID[1];
	if(m_bootloaderID[1] == 8){
		/* Set Command to Erase AP for BL8*/
		erase_cmd[5] = (unsigned char)CMD_V7_ERASE_AP;
	} else {
		/* Set Command to Erase AP for BL7*/
		erase_cmd[5] = (unsigned char)CMD_V7_ERASE;
	}
	
	fprintf(stdout, "Erase command : ");
	for(int i = 0 ;i<8;i++){
		fprintf(stdout, "%d ", erase_cmd[i]);
	}
	fprintf(stdout, "\n");

	rmi4update_poll();
	if (!m_inBLmode)
		return UPDATE_FAIL_DEVICE_NOT_IN_BOOTLOADER;
	if(m_bootloaderID[1] == 8){
		// For BL8 device, we need hold 1 seconds after querying
		// F34 status to avoid not get attention by following giving 
		// erase command.
		Sleep(1000);
	}

	rc = m_device.Write(m_f34.GetDataBase() + 1, erase_cmd, sizeof(erase_cmd));
	if (rc != sizeof(erase_cmd))
		return UPDATE_FAIL_WRITE_F01_CONTROL_0;

	Sleep(100);

	//Wait from ATTN
	if(m_bootloaderID[1] == 8){
		// Wait for attention for BL8 device.
		rc = WaitForIdle(RMI_F34_ERASE_V8_WAIT_MS, false);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			return UPDATE_FAIL_TIMEOUT_WAITING_FOR_ATTN;
		}
	}
	do {
		Sleep(20);
		rmi4update_poll();
		if (m_flashStatus == SUCCESS){
			break;
		}
		retry++;
	} while(retry < 20);

	if (m_flashStatus != SUCCESS) {
		fprintf(stdout, "err flash_status = %d\n", m_flashStatus);
		return UPDATE_FAIL_WRITE_F01_CONTROL_0;
	}
 
	if(m_bootloaderID[1] == 7){
		// For BL7, we need erase config partition.
		fprintf(stdout, "Start to erase config\n");
		erase_cmd[0] = CORE_CONFIG_PARTITION;
		erase_cmd[6] = m_bootloaderID[0];
		erase_cmd[7] = m_bootloaderID[1];
		erase_cmd[5] = (unsigned char)CMD_V7_ERASE;

		Sleep(100);
		rmi4update_poll();
		if (!m_inBLmode)
		  return UPDATE_FAIL_DEVICE_NOT_IN_BOOTLOADER;

		rc = m_device.Write(m_f34.GetDataBase() + 1, erase_cmd, sizeof(erase_cmd));
		if (rc != sizeof(erase_cmd))
			return UPDATE_FAIL_WRITE_F01_CONTROL_0;

		//Wait from ATTN
		Sleep(100);

		rc = WaitForIdle(RMI_F34_ERASE_WAIT_MS, true);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			return UPDATE_FAIL_TIMEOUT_WAITING_FOR_ATTN;
		}


		do {
			Sleep(20);
			rmi4update_poll();
			if (m_flashStatus == SUCCESS){
				break;
			}
			retry++;
		} while(retry < 20);

		if (m_flashStatus != SUCCESS) {
			fprintf(stdout, "err flash_status = %d\n", m_flashStatus);
			return UPDATE_FAIL_WRITE_F01_CONTROL_0;
		}
	}

	return UPDATE_SUCCESS;
}

int RMI4Update::EnterFlashProgrammingV7()
{
	int rc;
	unsigned char f34_status;
	rc = m_device.Read(m_f34.GetDataBase(), &f34_status, sizeof(unsigned char));
	m_inBLmode = f34_status & 0x80;
	if(!m_inBLmode){
		fprintf(stdout, "Not in BL mode, going to BL mode...\n");
		unsigned char EnterCmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};
		int retry = 0;

		/* set partition id for bootloader 7 */
		EnterCmd[0] = BOOTLOADER_PARTITION;

		/* write bootloader id */
		EnterCmd[6] = m_bootloaderID[0];
		EnterCmd[7] = m_bootloaderID[1];

		// Set Command to EnterBL
		EnterCmd[5] = (unsigned char)CMD_V7_ENTER_BL;

		rc = m_device.Write(m_f34.GetDataBase() + 1, EnterCmd, sizeof(EnterCmd));
		if (rc != sizeof(EnterCmd))
			return UPDATE_FAIL_WRITE_F01_CONTROL_0;

		rc = WaitForIdle(RMI_F34_ENABLE_WAIT_MS, false);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			return UPDATE_FAIL_TIMEOUT_WAITING_FOR_ATTN;
		}

		//Wait from ATTN
		do {
			Sleep(20);
			rmi4update_poll();
			if (m_flashStatus == SUCCESS){
				break;
			}
			retry++;
		} while(retry < 20);

		if (m_flashStatus != SUCCESS) {
			fprintf(stdout, "err flash_status = %d\n", m_flashStatus);
			return UPDATE_FAIL_WRITE_F01_CONTROL_0;
		}

		Sleep(RMI_F34_ENABLE_WAIT_MS);

		fprintf(stdout, "%s\n", __func__);
		rmi4update_poll();
		if (!m_inBLmode)
			return UPDATE_FAIL_DEVICE_NOT_IN_BOOTLOADER;

	} else
		fprintf(stdout, "Already in BL mode, skip...\n");

	if(m_device.GetDeviceType() != RMI_DEVICE_TYPE_TOUCHPAD) {
		// workaround for touchscreen only
		fprintf(stdout, "Erase in BL mode\n");
		rc = EraseFirmwareV7();
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
			return UPDATE_FAIL_ERASE_ALL;
		}
		fprintf(stdout, "Erase in BL mode end\n");
		m_device.RebindDriver();
	}

	Sleep(RMI_F34_ENABLE_WAIT_MS);

	rc = FindUpdateFunctions();
	if (rc != UPDATE_SUCCESS)
		return rc;

	rc = ReadF34Queries();
	if (rc != UPDATE_SUCCESS)
		return rc;

	return UPDATE_SUCCESS;
}

int RMI4Update::EnterFlashProgramming()
{
	int rc;
	unsigned char f01Control_0;
	const unsigned char enableProg = RMI_F34_ENABLE_FLASH_PROG;

	rc = WriteBootloaderID();
	if (rc != UPDATE_SUCCESS)
		return rc;

	fprintf(stdout, "Enabling flash programming.\n");
	rc = m_device.Write(m_f34StatusAddr, &enableProg, 1);
	if (rc != 1)
		return UPDATE_FAIL_ENABLE_FLASH_PROGRAMMING;

	Sleep(RMI_F34_ENABLE_WAIT_MS);
	if(m_device.GetDeviceType() != RMI_DEVICE_TYPE_TOUCHPAD) {
		fprintf(stdout, "not TouchPad, rebind driver here\n");
		m_device.RebindDriver();
	}
	rc = WaitForIdle(0);
	if (rc != UPDATE_SUCCESS)
		return UPDATE_FAIL_NOT_IN_IDLE_STATE;

	if (!m_programEnabled)
		return UPDATE_FAIL_PROGRAMMING_NOT_ENABLED;

	fprintf(stdout, "Programming is enabled.\n");
	rc = FindUpdateFunctions();
	if (rc != UPDATE_SUCCESS)
		return rc;

	rc = m_device.Read(m_f01.GetDataBase(), &m_deviceStatus, 1);
	if (rc != 1)
		return UPDATE_FAIL_READ_DEVICE_STATUS;

	if(m_f34.GetFunctionVersion() > 0x1){
		if (!RMI_F01_STATUS_BOOTLOADER_v7(m_deviceStatus))
			return UPDATE_FAIL_DEVICE_NOT_IN_BOOTLOADER;
		fprintf(stdout, "Already in BL mode V7\n");
	} else {
		if (!RMI_F01_STATUS_BOOTLOADER(m_deviceStatus))
			return UPDATE_FAIL_DEVICE_NOT_IN_BOOTLOADER;
		fprintf(stdout, "Already in BL mode\n");
	}

	rc = ReadF34Queries();
	if (rc != UPDATE_SUCCESS)
		return rc;

	rc = m_device.Read(m_f01.GetControlBase(), &f01Control_0, 1);
	if (rc != 1)
		return UPDATE_FAIL_READ_F01_CONTROL_0;

	f01Control_0 |= RMI_F01_CRTL0_NOSLEEP_BIT;
	f01Control_0 = (f01Control_0 & ~RMI_F01_CTRL0_SLEEP_MODE_MASK) | RMI_SLEEP_MODE_NORMAL;

	rc = m_device.Write(m_f01.GetControlBase(), &f01Control_0, 1);
	if (rc != 1)
		return UPDATE_FAIL_WRITE_F01_CONTROL_0;

	return UPDATE_SUCCESS;
}

int RMI4Update::WriteBlocks(unsigned char *block, unsigned short count, unsigned char cmd)
{
	int blockNum;
	unsigned char zeros[] = { 0, 0 };
	int rc;
	unsigned short addr;
	unsigned char *blockWithCmd = (unsigned char *)alloca(m_blockSize + 1);

	if (m_f34.GetFunctionVersion() == 0x1)
		addr = m_f34.GetDataBase() + RMI_F34_BLOCK_DATA_V1_OFFSET;
	else
		addr = m_f34.GetDataBase() + RMI_F34_BLOCK_DATA_OFFSET;

	rc = m_device.Write(m_f34.GetDataBase(), zeros, 2);
	if (rc != 2)
		return UPDATE_FAIL_WRITE_INITIAL_ZEROS;

	for (blockNum = 0; blockNum < count; ++blockNum) {
		if (m_writeBlockWithCmd) {
			memcpy(blockWithCmd, block, m_blockSize);
			blockWithCmd[m_blockSize] = cmd;

			rc = m_device.Write(addr, blockWithCmd, m_blockSize + 1);
			if (rc != m_blockSize + 1) {
				fprintf(stderr, "failed to write block %d\n", blockNum);
				return UPDATE_FAIL_WRITE_BLOCK;
			}
		} else {
			rc = m_device.Write(addr, block, m_blockSize);
			if (rc != m_blockSize) {
				fprintf(stderr, "failed to write block %d\n", blockNum);
				return UPDATE_FAIL_WRITE_BLOCK;
			}

			rc = m_device.Write(m_f34StatusAddr, &cmd, 1);
			if (rc != 1) {
				fprintf(stderr, "failed to write command for block %d\n", blockNum);
				return UPDATE_FAIL_WRITE_FLASH_COMMAND;
			}
		}

		rc = WaitForIdle(RMI_F34_IDLE_WAIT_MS, !m_writeBlockWithCmd);
		if (rc != UPDATE_SUCCESS) {
			fprintf(stderr, "failed to go into idle after writing block %d\n", blockNum);
			return UPDATE_FAIL_NOT_IN_IDLE_STATE;
		}

		block += m_blockSize;
	}

	return UPDATE_SUCCESS;
}

/*
 * This is a limited implementation of WaitForIdle which assumes WaitForAttention is supported
 * this will be true for HID, but other protocols will need to revert polling. Polling
 * is not implemented yet.
 */
int RMI4Update::WaitForIdle(int timeout_ms, bool readF34OnSucess)
{
	int rc = 0;
	struct timeval tv;

	if (timeout_ms > 0) {
		tv.tv_sec = timeout_ms / 1000;
		tv.tv_usec = (timeout_ms % 1000) * 1000;

		rc = m_device.WaitForAttention(&tv, m_f34.GetInterruptMask());
		if (rc == -ETIMEDOUT){
			/*
			 * If for some reason we are not getting attention reports for HID devices
			 * then we can still continue after the timeout and read F34 status
			 * but if we have to wait for the timeout to ellapse everytime then this
			 * will be slow. If this message shows up a lot then something is wrong
			 * with receiving attention reports and that should be fixed.
			 */
			fprintf(stderr, "RMI4Update::WaitForIdle Timed out waiting for attn report\n");
		}
	}

	if (rc <= 0 || readF34OnSucess) {
		rc = ReadF34Controls();
		if (rc != UPDATE_SUCCESS)
			return rc;

		if (!m_f34Status && !m_f34Command) {
			if (!m_programEnabled) {
				fprintf(stderr, "RMI4Update::WaitForIdle Bootloader is idle but program_enabled bit isn't set.\n");
				return UPDATE_FAIL_PROGRAMMING_NOT_ENABLED;
			} else {
				return UPDATE_SUCCESS;
			}
		}
		fprintf(stderr, "RMI4Update::WaitForIdle\n");
		fprintf(stderr, "  ERROR: Waiting for idle status.\n");
		fprintf(stderr, "  Command: %#04x\n", m_f34Command);
		fprintf(stderr, "  Status:  %#04x\n", m_f34Status);
		fprintf(stderr, "  Enabled: %d\n", m_programEnabled);
		fprintf(stderr, "  Idle:    %d\n", !m_f34Command && !m_f34Status);

		return UPDATE_FAIL_NOT_IN_IDLE_STATE;
	}

	return UPDATE_SUCCESS;
}