summaryrefslogtreecommitdiff
path: root/util/flash_ec
blob: 07ee541a9628c3e65a32b0a232ad0397403635e7 (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
#!/bin/bash

# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

SCRIPT="$(readlink -f "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT")"

EC_DIR="$(readlink -f "${SCRIPT_DIR}/..")"
if [[ "$(basename "${EC_DIR}")" != "ec" ]]; then
	EC_DIR=
fi
TEMP_DIR=""

# Loads script libraries.
. "/usr/share/misc/shflags" || exit 1

# Redirects tput to stderr, and drop any error messages.
tput2() {
	tput "$@" 1>&2 2>/dev/null || true
}

error() {
	tput2 bold && tput2 setaf 1
	echo "ERROR: $*" >&2
	tput2 sgr0
}


info() {
	tput2 bold && tput2 setaf 2
	echo "INFO: $*" >&2
	tput2 sgr0
}

warn() {
	tput2 bold && tput2 setaf 3
	echo "WARNING: $*" >&2
	tput2 sgr0
}

die() {
	[ -z "$*" ] || error "$@"
	exit 1
}


# Include a board name to the BOARDS_${EC_CHIP} array below ONLY IF servod is
# not aware of its 'ec_chip'. If servod becomes able to answer 'ec_chip'
# for the board, remove it from BOARDS_XXXX array below.
BOARDS_IT83XX=(
	glkrvp_ite
	it83xx_evb
	reef_it8320
)

BOARDS_STM32=(
	chell_pd
	coffeecake
	chocodile_bec
	chocodile_vpdmcu
	glados_pd
	jerry
	minimuffin
	nami_fp
	nocturne_fp
	oak_pd
	pit
	plankton
	rainier
	samus_pd
	staff
	strago_pd
	wand
	whiskers
	zinger
)
BOARDS_STM32_PROG_EN=(
	plankton
)

BOARDS_STM32_DFU=(
	dingdong
	hoho
	twinkie
	discovery
	servo_v4
	servo_micro
	sweetberry
	polyberry
	stm32f446e-eval
	tigertail
)

BOARDS_NPCX_5M5G_JTAG=(
	npcx_evb
	npcx_evb_arm
)

BOARDS_NPCX_5M6G_JTAG=(
)

BOARDS_NPCX_7M6X_JTAG=(
)

BOARDS_NPCX_7M7X_JTAG=(
	npcx7_evb
)

BOARDS_NPCX_SPI=(
	glkrvp
)

BOARDS_SPI_1800MV=(
	coral
	reef
)

BOARDS_RAIDEN=(
	coral
	eve
	fizz
	flapjack
	kukui
	nami
	nautilus
	poppy
	rammus
	reef
	scarlet
	soraka
)

DEFAULT_PORT="${SERVOD_PORT:-9999}"
BITBANG_RATE="9600"  # Could be overwritten by a command line option.

# Flags
DEFINE_integer bitbang_rate "${BITBANG_RATE}" \
	"UART baud rate to use when bit bang programming, "\
"standard UART rates from 9600 to 57600 are supported."
DEFINE_string board "${DEFAULT_BOARD}" \
	"The board to run debugger on."
DEFINE_string chip "" \
	"The chip to run debugger on."
DEFINE_string image "" \
	"Full pathname of the EC firmware image to flash."
DEFINE_string logfile "" \
	"Stm32 only: pathname of the file to store communications log."
DEFINE_string offset "0" \
	"Offset where to program the image from."
DEFINE_integer port "${DEFAULT_PORT}" \
	"Port to communicate to servo on."
DEFINE_boolean raiden "${FLAGS_FALSE}" \
	"Use raiden_debug_spi programmer"
DEFINE_string read "" "Stm32, it83xx and npcx_(|int_)spi only:"\
" pathname of the file to store EC firmware image."
DEFINE_boolean ro "${FLAGS_FALSE}" \
	"Write only the read-only partition"
DEFINE_integer timeout 600 \
	"Timeout for flashing the EC, measured in seconds."
DEFINE_boolean verbose "${FLAGS_FALSE}" \
	"Verbose hw control logging"
DEFINE_boolean verify "${FLAGS_FALSE}" "Stm32, it83xx and npcx_(int_)spi only:"\
" verify EC firmware image after programming."

# Parse command line
FLAGS_HELP="usage: $0 [flags]"
FLAGS "$@" || exit 1
eval set -- "${FLAGS_ARGV}"
if [[ $# -gt 0 ]]; then
	die "invalid arguments: \"$*\""
fi

set -e

DUT_CONTROL_CMD="dut-control --port=${FLAGS_port}"

function dut_control() {
	if [ "${FLAGS_verbose}" = ${FLAGS_TRUE} ]; then
		echo "$DUT_CONTROL_CMD $@" 1>&2
	fi

	$DUT_CONTROL_CMD "$@" >/dev/null
}

function dut_control_or_die {
	dut_control "$@" || die "dut-control $* exited $? (non-zero)"
}

function dut_control_get() {
	local DUT_GETVAL=
	if dut_control "$1" ; then
		DUT_GETVAL=$(${DUT_CONTROL_CMD} $1)
	fi
	# Remove the shortest prefix ending ':'
	echo "${DUT_GETVAL#*:}"
 }

function get_servo_type() {
	if dut_control "servo_type" ; then
		$DUT_CONTROL_CMD servo_type | sed -e s/servo_type://
	fi
}

SERVO_EC_CHIP="$(($DUT_CONTROL_CMD ec_chip) | sed -e s/ec_chip://)"
SERVO_EC_CHIP="${SERVO_EC_CHIP,,}"
if [[ "${SERVO_EC_CHIP}" =~ "unknown" ]]; then
	SERVO_EC_CHIP=""
fi

if [[ -z "${FLAGS_board}" && -z "${FLAGS_chip}" && \
      -z "${SERVO_EC_CHIP}" ]]; then
	die "Please check that servod is running or," \
	"manually specify either --board or --chip."
fi

BOARD=${FLAGS_board}

in_array() {
	local n=$#
	local value=${!n}

	for (( i=1; i<$#; i++ )) do
		if [ "${!i}" == "${value}" ]; then
			return 0
		fi
	done
	return 1
}

declare -a SUPPORTED_CHIPS

if $(in_array "${BOARDS_STM32[@]}" "${BOARD}"); then
	SUPPORTED_CHIPS+=("stm32")
fi

if $(in_array "${BOARDS_STM32_DFU[@]}" "${BOARD}"); then
	SUPPORTED_CHIPS+=("stm32_dfu")
fi

if $(in_array "${BOARDS_NPCX_5M5G_JTAG[@]}" "${BOARD}"); then
	SUPPORTED_CHIPS+=("npcx_5m5g_jtag")
fi

if $(in_array "${BOARDS_NPCX_5M6G_JTAG[@]}" "${BOARD}"); then
	SUPPORTED_CHIPS+=("npcx_5m6g_jtag")
fi

if $(in_array "${BOARDS_NPCX_7M6X_JTAG[@]}" "${BOARD}"); then
	SUPPORTED_CHIPS+=("npcx_7m6x_jtag")
fi

if $(in_array "${BOARDS_NPCX_7M7X_JTAG[@]}" "${BOARD}"); then
	SUPPORTED_CHIPS+=("npcx_7m7x_jtag")
fi

if $(in_array "${BOARDS_NPCX_SPI[@]}" "${BOARD}"); then
	SUPPORTED_CHIPS+=("npcx_spi")
fi

if $(in_array "${BOARDS_IT83XX[@]}" "${BOARD}"); then
	SUPPORTED_CHIPS+=("it83xx")
fi

if [[ ${#SUPPORTED_CHIPS[@]} -eq 0 && -n "${FLAGS_chip}" ]]; then
	SUPPORTED_CHIPS+="${FLAGS_chip}"
fi

if [[ ${#SUPPORTED_CHIPS[@]} -eq 0 && -n "${SERVO_EC_CHIP}" ]]; then
	SUPPORTED_CHIPS+=("${SERVO_EC_CHIP}")
fi

SERVO_TYPE="$(get_servo_type)"

if [[ ${#SUPPORTED_CHIPS[@]} -eq 0 ]]; then
	# This happens if ${FLAGS_board} is not known in this flash_ec yet,
	# ${FLAGS_chip} is not given, and servod doesn't know ec_chip.
	# In this case, '--chip' should be specified in the command line.
	die "board '${BOARD}' not supported." \
	    "Please check that servod is running, or manually specify --chip."
elif [[ ${#SUPPORTED_CHIPS[@]} -eq 1 ]]; then
	CHIP="${SUPPORTED_CHIPS[0]}"
elif [ -n "${FLAGS_chip}" ]; then
	if $(in_array "${SUPPORTED_CHIPS[@]}" "${FLAGS_chip}"); then
		CHIP="${FLAGS_chip}"
	else
		die "board ${BOARD} only supports (${SUPPORTED_CHIPS[@]})," \
			"not ${FLAGS_chip}."
	fi
else
	# Ideally, ec_chip per servo_type should be specified in servo overlay
	# file, instead of having multiple board-to-chip mapping info in this
	# script. Please refer to crrev.com/c/1496460 for example.
	die "board ${BOARD} supports multiple chips" \
	"(${FILTERED_CHIPS[@]}). Use --chip= to choose one."
fi

if [ -n "${FLAGS_chip}" -a "${CHIP}" != "${FLAGS_chip}" ]; then
	die "board ${BOARD} doesn't use chip ${FLAGS_chip}"
fi

if [[ "${CHIP}" = "stm32_dfu" ]]; then
	NEED_SERVO="no"
fi

case "${CHIP}" in
	"stm32"|"npcx_spi"|"npcx_int_spi"|"it83xx") ;;
	*)
		if [[ -n "${FLAGS_read}" ]]; then
			die "The flag is not yet supported on ${CHIP}."
		fi

		# If verification is not supported, then show a warning message.
		# Keep it running however.
		if [[ "${FLAGS_verify}" == ${FLAGS_TRUE} ]]; then
			warn "Ignoring '--verify'" \
			"since read is not supported on ${CHIP}."
		fi
		;;
esac

servo_has_warm_reset() {
	dut_control -i warm_reset >/dev/null 2>&1
}

servo_has_cold_reset() {
	dut_control -i cold_reset >/dev/null 2>&1
}

servo_has_dut_i2c_mux() {
	dut_control -i dut_i2c_mux >/dev/null 2>&1
}

# reset the EC
toad_ec_hard_reset() {
	if dut_control cold_reset 2>/dev/null ; then
		dut_control cold_reset:on
		dut_control cold_reset:off
	else
		info "you probably need to hard-reset your EC manually"
	fi
}

servo_ec_hard_reset_or_die() {
	dut_control_or_die cold_reset:on
	dut_control_or_die cold_reset:off
}

servo_ec_hard_reset() {
	dut_control cold_reset:on
	dut_control cold_reset:off
}

servo_usbpd_hard_reset() {
	dut_control usbpd_reset:on sleep:0.5 usbpd_reset:off
}

servo_sh_hard_reset() {
	dut_control sh_reset:on
	dut_control sh_reset:off
}

ccd_cr50_ec_hard_reset() {
	servo_ec_hard_reset
}

ec_reset() {
	stype=${SERVO_TYPE}
	if [[ "${SERVO_TYPE}" =~ "servo" ]] ; then
		stype=servo
	fi

	if [[ -n "${stype}" ]]; then
		eval ${stype}_${MCU}_hard_reset
	fi
}

# force the EC to boot in serial monitor mode
toad_ec_boot0() {
	dut_control boot_mode:$1
}

ccd_ec_boot0() {
	info "Using CCD $2."
	dut_control ccd_ec_boot_mode_$2:$1
}

servo_ec_boot0() {
	dut_control ec_boot_mode:$1
}

servo_usbpd_boot0() {
	dut_control usbpd_boot_mode:$1
}

servo_sh_boot0() {
	dut_control sh_boot_mode:$1
}

ec_switch_boot0() {
	on_value=$1
	# Enable programming GPIOs
	if $(in_array "${BOARDS_STM32_PROG_EN[@]}" "${BOARD}"); then
		dut_control prog_en:yes
	fi
	if [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]] ; then
		stype=ccd
	elif [[ "${SERVO_TYPE}" =~ "servo" ]] ; then
		stype=servo
	else
		stype=${SERVO_TYPE}
		if [[ "${SERVO_TYPE}" =~ "toad" ]] ; then
			if [[ "${on_value}" == "on" ]] ; then
				on_value="yes"
			else
				on_value="no"
			fi
		fi
	fi
	eval ${stype}_${MCU}_boot0 "${on_value}" $2
}

ec_enable_boot0() {
	ec_switch_boot0 "on" $1
}

ec_disable_boot0() {
	ec_switch_boot0 "off" $1
}

# Returns 0 on success (if on beaglebone)
on_servov3() {
	grep -qs '^CHROMEOS_RELEASE_BOARD=beaglebone_servo' /etc/lsb-release
}

# Returns 0 on success (if raiden should be used instead of servo)
error_reported=  # Avoid double printing the error message.
on_raiden() {
	if [[ "${SERVO_TYPE}" =~ "servo_v4" ]] || \
	   [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]] || \
	   [[ "${SERVO_TYPE}" =~ "servo_micro" ]]; then
		return 0
	fi
	if [ -z "${BOARD}" ]; then
		[ "${FLAGS_raiden}" = ${FLAGS_TRUE} ] && return 0 || return 1
	fi
	if [ "${FLAGS_raiden}" = ${FLAGS_TRUE} ]; then
		if in_array "${BOARDS_RAIDEN[@]}" "${BOARD}"; then
			return 0
		fi
		if [ -z "${error_reported}" ]; then
			error_reported="y"
			die "raiden mode not supported on ${BOARD}" >&2
		fi
	fi
	return 1
}

# Put back the servo and the system in a clean state at exit
FROZEN_PIDS=""
cleanup() {
	for pid in ${FROZEN_PIDS}; do
		info "Sending SIGCONT to process ${pid}!"
		kill -CONT "${pid}"
	done

	# If $TEMP_DIR exists, then delete it.
	if [[ -d "${TEMP_DIR}" ]]; then
		rm -rf "${TEMP_DIR}" > /dev/null 2>&1
	fi

	if [ "${CHIP}" = "it83xx" ]; then
		if [ "${SERVO_TYPE}" = "servo_v2" ]; then
			info "Reinitializing ftdi_i2c interface"
			# Ask servod to close its FTDI I2C interface because it
			# could be open or closed at this point.  Using
			# ftdii2c_cmd:close when it's already closed is okay,
			# however ftdii2c_cmd:open when it's already open
			# triggers an error.
			#
			# If there is a simple, reliable way to detect whether
			# servod FTDI I2C interface is open or closed, it would
			# be preferable to check and only re-initialize if it's
			# closed.  Patches welcome.
			dut_control ftdii2c_cmd:close
			dut_control ftdii2c_cmd:init
			dut_control ftdii2c_cmd:open
			dut_control ftdii2c_cmd:setclock
		fi

		# Reset the dut mux if it exists
		if servo_has_dut_i2c_mux; then
			# Turn off dut i2c mux
			dut_control dut_i2c_mux:none
		fi

		# Let the AP boot back up.
		if servo_has_warm_reset; then
			dut_control warm_reset:off
		fi
	fi

	if [ -n "${save}" ]; then
		info "Restoring servo settings..."
		servo_restore "$save"
	fi

	if [ "${CHIP}" = "stm32" -o "${CHIP}" = "npcx_uut" ]; then
		# Reconnect the EC-3PO interpreter to the UART.
		dut_control "${MCU}"_ec3po_interp_connect:on || \
		    warn "hdctools cannot reconnect the EC-3PO interpreter to" \
		    "the UART."
		dut_control "${MCU}"_boot_mode:off
	fi

	if [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]]; then
		dut_control ccd_ec_boot_mode_uut:off
		dut_control ccd_ec_boot_mode_bitbang:off
		dut_control "${MCU}"_uart_bitbang_en:off
	fi

	if ! on_raiden || servo_has_cold_reset; then
		ec_reset
	fi
}
trap cleanup EXIT

# Possible default EC images
if [ "${FLAGS_ro}" = ${FLAGS_TRUE} ] ; then
	EC_FILE=ec.RO.flat
else
	EC_FILE=ec.bin
fi


LOCAL_BUILD=
if [[ -n "${EC_DIR}" ]]; then
	if [ "${FLAGS_ro}" = ${FLAGS_TRUE} ] ; then
		LOCAL_BUILD="${EC_DIR}/build/${BOARD}/RO/${EC_FILE}"
	else
		LOCAL_BUILD="${EC_DIR}/build/${BOARD}/${EC_FILE}"
	fi
fi

# Get baseboard from build system if present
BASEBOARD=

# We do not want to exit script if make call fails; we turn -e back on after
# setting BASEBOARD
set +e
if [[ -n "${EC_DIR}" ]]; then
	BASEBOARD=$(make --quiet -C ${EC_DIR} BOARD=${BOARD} print-baseboard \
		2>/dev/null)
elif [[ -d "${HOME}/trunk/src/platform/ec" ]]; then
	BASEBOARD=$(make --quiet -C ${HOME}/trunk/src/platform/ec \
		BOARD=${BOARD} print-baseboard 2>/dev/null)
else
	info "Could not find ec build folder to calculate baseboard."
fi
if [ $? -ne 0 ]; then
	info "EC build system didn't recognize ${BOARD}. Assuming no baseboard."
fi
set -e

if [[ -n "${BASEBOARD}" ]]; then
	EMERGE_BUILD=/build/${BASEBOARD}/firmware/${BOARD}/${EC_FILE}
else
	EMERGE_BUILD=/build/${BOARD}/firmware/${EC_FILE}
fi

# Find the EC image to use
function ec_image() {
	# No image specified on the command line, try default ones
	if [[ -n "${FLAGS_image}" ]] ; then
		if [ -f "${FLAGS_image}" ] || \
		   [ "${FLAGS_image}" == "-" ]; then
			echo "${FLAGS_image}"
			return
		fi
		die "Invalid image path : ${FLAGS_image}"
	else
		if [ -f "${LOCAL_BUILD}" ]; then
			echo "${LOCAL_BUILD}"
			return
		fi
		if [ -f "${EMERGE_BUILD}" ]; then
			echo "${EMERGE_BUILD}"
			return
		fi
	fi
	die "no EC image found : build one or specify one."
}

# Find the EC UART provided by servo.
function servo_ec_uart() {
	SERVOD_FAIL="Cannot communicate with servod. Is servod running?"
	PTY=$(($DUT_CONTROL_CMD raw_${MCU}_uart_pty ||
	       $DUT_CONTROL_CMD ${MCU}_uart_pty) | cut -d: -f2)
	if [[ -z "${PTY}" ]]; then
	    die "${SERVOD_FAIL}"
	fi
	echo $PTY
}

# Servo variables management
case "${BOARD}" in
        chocodile_bec ) MCU="usbpd" ;;
	oak_pd|samus_pd|strago_pd ) MCU="usbpd" ;;
	chell_pd|glados_pd ) MCU="usbpd" ;;
	nami_fp|nocturne_fp ) MCU="usbpd" ;;
	dingdong|hoho|twinkie ) DUT_CONTROL_CMD="true" ; MCU="ec" ;;
	*) MCU="ec" ;;
esac

# Not every control is supported on every servo type.  Therefore, define which
# controls are supported by each servo type.
servo_v2_VARS="jtag_buf_on_flex_en jtag_buf_en cold_reset spi1_vref"
servo_micro_VARS="cold_reset spi1_vref"
servo_v4_with_ccd_cr50_VARS="cold_reset"
# Flashing an STM32 over the UART requires modifying the UART properties along
# with the boot mode pin.
if [ "${CHIP}" = "stm32" ] ; then
	common_stm32_VARS=" ${MCU}_uart_parity"
	common_stm32_VARS+=" ${MCU}_uart_baudrate"
	servo_v2_VARS+=$common_stm32_VARS
	servo_v2_VARS+=" ${MCU}_uart_en"
	servo_micro_VARS+=$common_stm32_VARS
	servo_micro_VARS+=" ${MCU}_uart_en"
	servo_v4_with_ccd_cr50_VARS+=$common_stm32_VARS
fi
if $(in_array "${BOARDS_STM32_PROG_EN[@]}" "${BOARD}"); then
	servo_v2_VARS+=" prog_en"
fi
if [ "${CHIP}" = "npcx_uut" ] ; then
	servo_v4_with_ccd_cr50_VARS+=" ccd_keepalive_en"
fi
toad_VARS="${MCU}_uart_parity ${MCU}_uart_baudrate boot_mode"

if [[ "${CHIP}" == "npcx_int_spi" ]]; then
	servo_v2_VARS+=" fw_up"
	servo_micro_VARS+=" fw_up"
fi
# Some servo boards use the same controls.
servo_v3_VARS="${servo_v2_VARS}"
servo_v4_with_servo_micro_VARS="${servo_micro_VARS}"

function servo_save() {
	if [[ "${SERVO_TYPE}" == "servo_v2" ]]; then
		dut_control i2c_mux_en:on
		dut_control i2c_mux:remote_adc
	fi

	SERVO_VARS_NAME=${SERVO_TYPE}_VARS
	if [[ -n "${!SERVO_VARS_NAME}" ]]; then
		$DUT_CONTROL_CMD ${!SERVO_VARS_NAME}
	fi
}

function servo_restore() {
	echo "$1" | while read line
	do
		dut_control "$line"
	done

	if [[ "${SERVO_TYPE}" == "servo_v2" ]]; then
		dut_control i2c_mux_en:off
	fi
}

function claim_pty() {
	if grep -q cros_sdk /proc/1/cmdline; then
		die "You must run this tool in a chroot that was entered with" \
		    "'cros_sdk --no-ns-pid' (see crbug.com/444931 for details)"
	fi

	if [[ -z "$1" ]]; then
		warn "No parameter passed to claim_pty()"
		return
	fi

	# Disconnect the EC-3PO interpreter from the UART since it will
	# interfere with flashing.
	dut_control ${MCU}_ec3po_interp_connect:off || \
	    warn "hdctools cannot disconnect the EC-3PO interpreter from" \
	    "the UART."

	pids=$(lsof -FR 2>/dev/null -- $1 | tr -d 'pR')
	FROZEN_PIDS=""

	# reverse order to SIGSTOP parents before children
	for pid in $(echo ${pids} | tac -s " "); do
		if ps -o cmd= "${pid}" | grep -qE "(servod|/sbin/init)"; then
			info "Skip stopping servod or init: process ${pid}."
		else
			info "Sending SIGSTOP to process ${pid}!"
			FROZEN_PIDS+=" ${pid}"
			sleep 0.02
			kill -STOP ${pid}
		fi
	done
}

function get_serial() {
	if [[ "${SERVO_TYPE}" =~ "servo_v4_with_servo_micro" ]]; then
		if [[ -z "${BOARD}" ]]; then
			sn_ctl="servo_micro_"
		else
			sn_ctl="servo_micro_for_${BOARD}_"
		fi
	elif [[ "${SERVO_TYPE}" =~ "_with_ccd" ]] ; then
		sn_ctl="ccd_"
	else
		# If it's none of the above, the main serialname will do.
		sn_ctl=""
	fi

	SERIALNAME=$(${DUT_CONTROL_CMD} "${sn_ctl}serialname" | cut -d: -f2)
	echo $SERIALNAME
}

# Board specific flashing scripts

# helper function for using servo v2/3 with openocd
function flash_openocd() {
	OCD_CFG="servo.cfg"
	if [[ -z "${EC_DIR}" ]]; then
		# check if we're on beaglebone
		if [[ -e "/usr/share/ec-devutils" ]]; then
			OCD_PATH="/usr/share/ec-devutils"
		else
			die "Cannot locate openocd configs"
		fi
	else
		OCD_PATH="${EC_DIR}/util/openocd"
	fi

	dut_control jtag_buf_on_flex_en:on
	dut_control jtag_buf_en:on

	sudo timeout -k 10 -s 9 "${FLAGS_timeout}" \
		openocd -s "${OCD_PATH}" -f "${OCD_CFG}" -f "${OCD_CHIP_CFG}" \
		-c "${OCD_CMDS}" || \
	die "Failed to program ${IMG}"
}

# helper function for using servo with flashrom
function flash_flashrom() {
	TOOL_PATH="${EC_DIR}/build/${BOARD}/util:/usr/sbin/:$PATH"
	FLASHROM=$(PATH="${TOOL_PATH}" which flashrom)

	if on_servov3; then
		FLASHROM_ARGS="-p linux_spi"
	elif on_raiden; then
	    if [[ "${SERVO_TYPE}" =~ "servo_micro" ]]; then
		# Servo micro doesn't use the "target" parameter.
		FLASHROM_ARGS="-p raiden_debug_spi:"
	    else
		FLASHROM_ARGS="-p raiden_debug_spi:target=EC,"
	    fi
	else
		FLASHROM_ARGS="-p ft2232_spi:type=servo-v2,port=B,"
	fi

	if [ ! -x "$FLASHROM" ]; then
		die "no flashrom util found."
	fi

	if ! on_servov3; then
		SERIALNAME=$(get_serial)
		if [[ "$SERIALNAME" != "" ]] ; then
			FLASHROM_ARGS+="serial=${SERIALNAME}"
		fi
	fi

	if ! on_raiden || [[ "${SERVO_TYPE}" =~ "servo_micro" ]] ; then
		if $(in_array "${BOARDS_SPI_1800MV[@]}" "${BOARD}"); then
			SPI_VOLTAGE="pp1800"
		else
			SPI_VOLTAGE="pp3300"
		fi

		dut_control cold_reset:on

		# If spi flash is in npcx's ec, enable gang programer mode
		if [[ "${CHIP}" == "npcx_int_spi" ]]; then
			# Set GP_SEL# as low then start ec
			dut_control fw_up:on
			sleep 0.1
			dut_control cold_reset:off
		fi

		# Turn on SPI1 interface on servo for SPI Flash Chip
		dut_control spi1_vref:${SPI_VOLTAGE} spi1_buf_en:on
		if [[ ! "${SERVO_TYPE}" =~ "servo_micro" ]]; then
			# Servo micro doesn't support this control.
			dut_control spi1_buf_on_flex_en:on
		fi
	else
		if [[ "${CHIP}" == "npcx_int_spi" ]]; then
			# Set GP_SEL# as low then start ec
			dut_control cold_reset:on
			dut_control fw_up:on
			# sleep 0.1
			dut_control cold_reset:off
		else
			# Assert EC reset.
			dut_control cold_reset:on
		fi

		# Temp layout
		L=/tmp/flash_spi_layout_$$

		[[ -z "${FLAGS_read}" ]] && dump_fmap -F "${IMG}" > "${L}"

		FLASHROM_OPTIONS="-i EC_RW -i WP_RO -l "${L}" --ignore-fmap"
		FLASHROM_OPTIONS+=" --fast-verify"
	fi

	# Generate the correct flashrom command base.
	FLASHROM_CMDLINE="${FLASHROM} ${FLASHROM_ARGS}"
	if [[ -z "${FLAGS_read}" ]]; then
		# Program EC image.
		# flashrom should report the image size at the end of the output.
		local FLASHROM_GETSIZE="sudo ${FLASHROM_CMDLINE} --get-size"
		if [[ "${FLAGS_verbose}" == ${FLAGS_TRUE} ]]; then
			info "Running flashrom:" 1>&2
			echo " ${FLASHROM_GETSIZE}" 1>&2
		fi
		SPI_SIZE=$(${FLASHROM_GETSIZE} 2>/dev/null |\
			       grep -oe '[0-9]\+$') || \
			die "Failed to determine chip size!"
		[[ ${SPI_SIZE} -eq 0 ]] && die "Chip size is 0!"

		IMG_SIZE=$(stat -c%s "${IMG}")
		PATCH_SIZE=$((${SPI_SIZE} - ${IMG_SIZE}))

		# Temp image
		T=/tmp/flash_spi_$$

		if [[ "${CHIP}" =~ ^npcx(|_int)_spi$ ]] ; then
		{	# Patch temp image up to SPI_SIZE
			cat $IMG
			if [[ ${IMG_SIZE} -lt ${SPI_SIZE} ]] ; then
				dd if=/dev/zero bs=${PATCH_SIZE} count=1 | \
					tr '\0' '\377'
			fi
		} > $T
		else
		{	# Patch temp image up to SPI_SIZE
			if [[ ${IMG_SIZE} -lt ${SPI_SIZE} ]] ; then
				dd if=/dev/zero bs=${PATCH_SIZE} count=1 | \
					tr '\0' '\377'
			fi
			cat $IMG
		} > $T
		fi

		info "Programming EC firmware image."
		local FLASHROM_WRITE="${FLASHROM_CMDLINE} ${FLASHROM_OPTIONS}"
		if [[ "${FLAGS_verbose}" == ${FLAGS_TRUE} ]]; then
			info "Running flashrom:" 1>&2
			echo " ${FLASHROM_WRITE} -w ${T}" 1>&2
		fi
		sudo timeout -k 10 -s 9 "${FLAGS_timeout}" \
			${FLASHROM_WRITE} -w "${T}"
	else
		# Read EC image.
		info "Reading EC firmware image."
		if [[ "${FLAGS_verbose}" == ${FLAGS_TRUE} ]]; then
			info "Running flashrom:" 1>&2
			echo " ${FLASHROM_CMDLINE} -r ${FLAGS_read}" 1>&2
		fi
		sudo timeout -k 10 -s 9 "${FLAGS_timeout}" \
			${FLASHROM_CMDLINE} -r "${FLAGS_read}"
	fi
	if [[ -z "${FLAGS_read}" && "${FLAGS_verify}" == ${FLAGS_TRUE} ]]; then
		# Verify EC image.
		info "Verifying EC firmware image."
		if [[ "${FLAGS_verbose}" == ${FLAGS_TRUE} ]]; then
			info "Running flashrom:" 1>&2
			echo " ${FLASHROM_CMDLINE} -v ${T}" 1>&2
		fi
		sudo timeout -k 10 -s 9 "${FLAGS_timeout}" \
			${FLASHROM_CMDLINE} -v "${T}"
	fi
	[[ -f "${T}" ]] && rm "${T}"

	# Set GP_SEL# as default to disable GP mode when ec reboots
	if [[ "${CHIP}" == "npcx_int_spi" ]]; then
		dut_control fw_up:off
	fi

	if  ! on_raiden || [[ "${SERVO_TYPE}" =~ "servo_micro" ]] ; then
		# Turn off SPI1 interface on servo
		dut_control spi1_vref:off spi1_buf_en:off
		if [[ ! "${SERVO_TYPE}" =~ "servo_micro" ]] ; then
			dut_control spi1_buf_on_flex_en:off
		fi

	else
		[[ -f "${L}" ]] && rm "${L}"
	fi

	# Do not save/restore servo settings
	save=
}

function flash_stm32() {
	local STM32MON
	local STM32MON_OPT

	if ! servo_has_cold_reset; then
		die "Cold reset must be available for STM32 programming"
	fi

	TOOL_PATH="${EC_DIR}/build/${BOARD}/util:$PATH"
	STM32MON=$(PATH="${TOOL_PATH}" which stm32mon)
	EC_UART="$(servo_ec_uart)"
	if [ ! -x "$STM32MON" ]; then
		die "no stm32mon util found."
	fi

	info "Using serial flasher : ${STM32MON}"
	info "${MCU} UART pty : ${EC_UART}"
	claim_pty ${EC_UART}
	STM32MON_OPT="-d ${EC_UART}"

	# Make sure EC reboots in serial monitor mode.
	ec_enable_boot0 "bitbang"

	# Pulse EC reset.
	ec_reset

	if ! on_raiden && [[ "${SERVO_TYPE}" =~ "servo" ]] ; then
		dut_control ${MCU}_uart_en:on
	fi
	dut_control ${MCU}_uart_parity:even

	if [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]] ; then
		case "${FLAGS_bitbang_rate}" in
			(9600|19200|38400|57600) : ;;
			(*)
			    die "${FLAGS_bitbang_rate} is not a valid" \
			    "bit bang rate"
			    ;;
		esac
		info "Programming at ${FLAGS_bitbang_rate} baud"
		dut_control ${MCU}_uart_baudrate:"${FLAGS_bitbang_rate}"
		dut_control ${MCU}_uart_bitbang_en:on
	else
		dut_control ${MCU}_uart_baudrate:115200
	fi

	# Add a delay long enough for cr50 to update the ccdstate. Cr50 updates
	# ccdstate once a second, so a 2 second delay should be safe.
	if [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]] ; then
		sleep 2
		STM32MON_OPT+=" -c"
	fi

	if [ -n "${FLAGS_logfile}" ]; then
		info "Saving log in ${FLAGS_logfile}"
		STM32MON_OPT+=" -L ${FLAGS_logfile}"
	fi

	local IMG_READ="${FLAGS_read}"
	# Program EC image.
	if [[ -z "${IMG_READ}" ]]; then
		info "Programming EC firmware image."
		# Unprotect flash, erase, and write
		local STM32MON_COMMAND="${STM32MON} ${STM32MON_OPT} -u -e -w"
		if [[ "${FLAGS_verbose}" == ${FLAGS_TRUE} ]]; then
			echo "${STM32MON_COMMAND} ${IMG}"
		fi
		timeout -k 10 -s 9 "${FLAGS_timeout}" \
			${STM32MON_COMMAND} "${IMG}"

		# If it is a program-verify request, then make a temporary
		# directory to store the image
		if [[ "${FLAGS_verify}" == ${FLAGS_TRUE} ]]; then
			local TEMP_SUFFIX=".$(basename ${SCRIPT}).${CHIP}"
			TEMP_DIR="$(mktemp -d --suffix="${TEMP_SUFFIX}")"
			IMG_READ="${TEMP_DIR}/ec.read.bin"
		fi
	fi

	# Read EC image.
	if [[ -n "${IMG_READ}" ]]; then
		info "Reading EC firmware image."
		local STM32MON_READ_CMD="${STM32MON} ${STM32MON_OPT} -U -r"
		if [[ "${FLAGS_verbose}" == ${FLAGS_TRUE} ]]; then
			echo "${STM32MON_READ_CMD} ${IMG_READ}"
		fi
		timeout -k 10 -s 9 "${FLAGS_timeout}" \
			${STM32MON_READ_CMD} "${IMG_READ}"
	fi

	# Verify the flash by comparing the source image to the read image,
	# only if it was a flash write request.
	if [[ -z "${FLAGS_read}" && "${FLAGS_verify}" == ${FLAGS_TRUE} ]]; then
		info "Verifying EC firmware image."
		if [[ "${FLAGS_verbose}" == ${FLAGS_TRUE} ]]; then
			echo "diff ${IMG} ${IMG_READ}"
		fi
		diff "${IMG}" "${IMG_READ}" > /dev/null 2>&1
		[[ $? != 0 ]] && die "Failed to verify EC firmware image."
	fi

	# Remove the Application processor reset
	# TODO(crosbug.com/p/30738): we cannot rely on servo_VARS to restore it
	if servo_has_warm_reset; then
		dut_control warm_reset:off
	fi
}

function flash_stm32_dfu() {
	DFU_DEVICE=0483:df11
	ADDR=0x08000000
	DFU_UTIL='dfu-util'
	which $DFU_UTIL &> /dev/null || die \
		"no dfu-util util found.  Did you 'sudo emerge dfu-util'"

	info "Using dfu flasher : ${DFU_UTIL}"

	dev_cnt=$(lsusb -d $DFU_DEVICE | wc -l)
	if [ $dev_cnt -eq 0 ] ; then
		die "unable to locate dfu device at $DFU_DEVICE"
	elif [ $dev_cnt -ne 1 ] ; then
		die "too many dfu devices (${dev_cnt}). Disconnect all but one."
	fi

	SIZE=$(wc -c ${IMG} | cut -d' ' -f1)
	# Remove read protection
	sudo timeout -k 10 -s 9 "${FLAGS_timeout}" \
		$DFU_UTIL -a 0 -s ${ADDR}:${SIZE}:force:unprotect -D "${IMG}"
	# Wait for mass-erase and reboot after unprotection
	sleep 1
	# Actual image flashing
	sudo timeout -k 10 -s 9 "${FLAGS_timeout}" \
		$DFU_UTIL -a 0 -s ${ADDR}:${SIZE} -D "${IMG}"
}

function dut_i2c_dev() {
	# TODO(b/79684405): Drop support for $DUT_I2C_DEV env var override
	# as soon as dut-control dut_i2c_dev command is implemented.
	if [ -n "$DUT_I2C_DEV" ]; then
		[ -e "$DUT_I2C_DEV" ] ||
			die "\$DUT_I2C_DEV is a non-existent path: $DUT_I2C_DEV"
		echo "$DUT_I2C_DEV"
		return
	fi

	# TODO(b/79684405): Drop this hack as soon as dut-control dut_i2c_dev
	# command is implemented.
	if (
		set -e
		cd /sys/class/i2c-dev
		# Sorting in reverse numerical order generally picks the correct
		# servod I2C bus when there are multiple servos in line to the
		# DUT, e.g. servo_v4->servo_micro, or servo_v4->CR50 (CCD).
		for dev in $(ls | grep ^i2c- | sort -s -t- -n -k2,2 -r); do
			if grep -q servod "$dev"/name; then
				echo /dev/"$dev"
				exit
			fi
		done
		false
	); then
		return
	fi

	# TODO(b/79684405): This should just work once a dut-control dut_i2c_dev
	# command is implemented.
	local dut_i2c_dev="$($DUT_CONTROL_CMD dut_i2c_dev)" ||
		die "dut-control dut_i2c_dev exited $? (non-zero)"
	dut_i2c_dev="$(echo "$dut_i2c_dev" | sed -e 's/^dut_i2c_dev://')"
	[ -e "$dut_i2c_dev" ] ||
		die "dut-control dut_i2c_dev returned non-existent path: "\
"$dut_i2c_dev"
	echo "$dut_i2c_dev"
}

function flash_it83xx() {
	local TOOL_PATH="${EC_DIR}/build/${BOARD}/util:$PATH"
	local ITEFLASH_BIN=$(PATH="${TOOL_PATH}" which iteflash)

	if [[ ! -x "$ITEFLASH_BIN" ]]; then
		die "no iteflash util found."
	fi

	# Now the we have enabled the I2C mux on the servo to talk to the dut,
	# we need to switch the I2C mux on the dut to allow ec programing (if
	# there is a mux on the dut)
	if servo_has_dut_i2c_mux; then
		info "Switching DUT I2C Mux to ${CHIP}"
		# TODO(b/126189871): Investigate about the timeout in CCD mode,
		# and remove with this retry logic along with the fix.
		local num_attempts=1
		if [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]]; then
			num_attempts=3
		fi
		while :; do
			if dut_control dut_i2c_mux:ec_prog; then
				break;
			fi
			if (( --num_attempts <= 0 )); then
				die "dut_i2c_mux failed."
			fi
			sleep 5
		done
	fi

	# Ensure that the AP is off while we are flashing the EC via:
	# - warm_reset:on
	# - cold_reset:on
	# - cold_reset:off
	# ...reflash EC...
	# - warm_reset:off
	if servo_has_warm_reset; then
		dut_control_or_die warm_reset:on
	fi
	if servo_has_cold_reset; then
		servo_ec_hard_reset_or_die
	fi

	# Send the special waveform to the ITE EC.
	if [[ "${SERVO_TYPE}" =~ "servo_micro" ]]; then
		info "Asking Servo Micro to send the dbgr special waveform to "\
"${CHIP}"
		dut_control_or_die enable_ite_dfu
	elif [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]]; then
		local CCD_I2C_CAP="$(dut_control_get ccd_i2c_en)"
		if [[ "${CCD_I2C_CAP,,}" != "always" ]]; then
			die "CCD I2C capability is not set as 'Always'" \
				": ${CCD_I2C_CAP}"
		fi

		info "Asking CR50 to send the dbgr special waveform to ${CHIP}"
		sleep 2
		dut_control_or_die cr50_i2c_ctrl:ite_debugger_mode
		sleep 3
	elif [[ "${SERVO_TYPE}" == "servo_v2" ]]; then
		info "Closing servod connection to ftdi_i2c interface"
		dut_control_or_die ftdii2c_cmd:close
	else
		die "This servo type is not yet supported: ${SERVO_TYPE}"
	fi

	# Build the iteflash command line.
	local ITEFLASH_ARGS=( "${ITEFLASH_BIN}" )

	if [[ "${SERVO_TYPE}" == "servo_v2" ]]; then
		ITEFLASH_ARGS+=( "--send-waveform=1" "--i2c-interface=ftdi" )
	else
		ITEFLASH_ARGS+=( "--send-waveform=0" )
		if [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]]; then
			ITEFLASH_ARGS+=( "--i2c-interface=ccd" )
		else
			ITEFLASH_ARGS=( "sudo" "--" "${ITEFLASH_ARGS[@]}" \
				"--i2c-interface=linux" \
				"--i2c-dev-path=$(dut_i2c_dev)" )
		fi
	fi

	if [[ -n "${FLAGS_read}" ]]; then
		ITEFLASH_ARGS+=( "--read=${FLAGS_read}" )
		info "Reading EC firmware image using iteflash..."
	else
		ITEFLASH_ARGS+=( "--erase" "--write=${IMG}" )
		info "Programming EC firmware image using iteflash..."
	fi

	if [[ "${FLAGS_verbose}" == ${FLAGS_TRUE} ]]; then
		ITEFLASH_ARGS+=( "--debug" )
		echo "${ITEFLASH_ARGS[@]}"
	fi

	"${ITEFLASH_ARGS[@]}"
}

function flash_lm4() {
	OCD_CHIP_CFG="lm4_chip.cfg"
	OCD_CMDS="init; flash_lm4 ${IMG} ${FLAGS_offset}; shutdown;"

	flash_openocd

}

function flash_nrf51() {
	OCD_CHIP_CFG="nrf51_chip.cfg"
	OCD_CMDS="init; flash_nrf51 ${IMG} ${FLAGS_offset}; exit_debug_mode_nrf51; shutdown;"

	flash_openocd

	# waiting 100us for the reset pulse is not necessary, it takes ~2.5ms
	dut_control swd_reset:on swd_reset:off
}

function flash_npcx_jtag() {
	IMG_PATH="${EC_DIR}/build/${BOARD}"
	OCD_CHIP_CFG="npcx_chip.cfg"
	if [ "${FLAGS_ro}" = ${FLAGS_TRUE} ] ; then
		# Program RO region only
		OCD_CMDS="init; flash_npcx_ro ${CHIP} ${IMG_PATH} ${FLAGS_offset}; shutdown;"
	else
		# Program all EC regions
		OCD_CMDS="init; flash_npcx_all ${CHIP} ${IMG_PATH} ${FLAGS_offset}; shutdown;"
	fi

	# Reset the EC
	ec_reset

	flash_openocd
}

function flash_npcx_uut() {
	TOOL_PATH="${EC_DIR}/build/${BOARD}/util:$PATH"
	NPCX_UUT=$(PATH="${TOOL_PATH}" which uartupdatetool)
	EC_UART="$(servo_ec_uart)"

	BUILD_PATH="${EC_DIR}/build/${BOARD}"
	MONITOR_PATH="${BUILD_PATH}/chip/npcx/spiflashfw"
	MON="${MONITOR_PATH}/npcx_monitor.bin"

	if [[ ! -f "$MON" ]]; then
		MON="$(dirname "$IMG")/npcx_monitor.bin"
	fi

	if [[ ! -f "$MON" ]]; then
		echo "Failed to find npcx_monitor.bin"
		exit 1
	fi

	# The start address to restore monitor firmware binary
	MON_ADDR="0x200C3020"

	if [ ! -x "$NPCX_UUT" ]; then
		die "no NPCX UART Update Tool found."
	fi

	info "Using: NPCX UART Update Tool"
	info "${MCU} UART pty : ${EC_UART}"
	claim_pty ${EC_UART}

	if [[ "${SERVO_TYPE}" =~ "ccd_cr50" ]] ; then
		dut_control ccd_keepalive_en:on
	fi

	# Force the EC to boot in UART update mode
	ec_enable_boot0 "uut"
	ec_reset

	# Have to wait a bit for EC boot-up
	sleep 0.1

	# For CCD, disable the trigger pin for normal UART operation
	ec_disable_boot0 "uut"
	sleep 0.1

	# Remove the prefix "/dev/" because uartupdatetool will add it.
	EC_UART=${EC_UART#/dev/}
	UUT_ARGS="--port ${EC_UART} --baudrate 115200"

	# Load monitor binary to address 0x200C3020
	if [[ "${FLAGS_verbose}" = ${FLAGS_TRUE} ]]; then
		echo ${NPCX_UUT} ${UUT_ARGS} --opr wr --addr ${MON_ADDR} \
			--file ${MON}
	fi
	${NPCX_UUT} ${UUT_ARGS} --opr wr --addr "${MON_ADDR}" \
		--file "${MON}" || die "Failed to load monitor binary."

	if [[ "${FLAGS_verbose}" = ${FLAGS_TRUE} ]]; then
		echo ${NPCX_UUT} ${UUT_ARGS} --auto --offset ${FLAGS_offset} \
			--file ${IMG}
	fi
	${NPCX_UUT} ${UUT_ARGS} --auto --offset "${FLAGS_offset}" \
		--file "${IMG}" || die "Failed to flash EC."
}

function flash_npcx_5m5g_jtag() {
	flash_npcx_jtag
}

function flash_npcx_5m6g_jtag() {
	flash_npcx_jtag
}

function flash_npcx_7m6x_jtag() {
	flash_npcx_jtag
}

function flash_npcx_7m7x_jtag() {
	flash_npcx_jtag
}

function flash_npcx_spi() {
	flash_flashrom
}

function flash_npcx_int_spi() {
	flash_flashrom
}

function flash_mec1322() {
	flash_flashrom
}

if dut_control boot_mode 2>/dev/null ; then
	if [[ "${MCU}" != "ec" ]] ; then
		die "Toad cable can't support non-ec UARTs"
	fi
	SERVO_TYPE=toad
	info "Using a dedicated debug cable"
fi
info "Using ${SERVO_TYPE}."

# Only if it is a flash program request, call ec_image.
if [[ -z "${FLAGS_read}" ]]; then
	IMG="$(ec_image)"
	info "Using ${MCU} image : ${IMG}"
fi

if [ "${NEED_SERVO}" != "no" ] ; then
	save="$(servo_save)"
fi

info "Flashing chip ${CHIP}."
flash_${CHIP}
info "Flashing done."