summaryrefslogtreecommitdiff
path: root/board/servo_v4/usb_pd_policy.c
blob: 3c49eefeda5dd5e18d9dfc12d35f733bfeb2c9ea (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
/* Copyright 2017 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.
 */

#include "atomic.h"
#include "charge_manager.h"
#include "common.h"
#include "console.h"
#include "gpio.h"
#include "hooks.h"
#include "host_command.h"
#include "i2c.h"
#include "registers.h"
#include "system.h"
#include "task.h"
#include "tcpm.h"
#include "timer.h"
#include "util.h"
#include "usb_mux.h"
#include "usb_pd.h"
#include "usb_pd_config.h"
#include "usb_pd_tcpm.h"

#define CPRINTF(format, args...) cprintf(CC_USBPD, format, ## args)
#define CPRINTS(format, args...) cprints(CC_USBPD, format, ## args)

#define DUT_PDO_FIXED_FLAGS (PDO_FIXED_DUAL_ROLE | PDO_FIXED_DATA_SWAP |\
			     PDO_FIXED_COMM_CAP)

#define CHG_PDO_FIXED_FLAGS (PDO_FIXED_DATA_SWAP)

#define VBUS_UNCHANGED(curr, pend, new) (curr == new && pend == new)

/* Macros to config the PD role */
#define CONFIG_SET_CLEAR(c, set, clear) ((c | (set)) & ~(clear))
#define CONFIG_SRC(c) CONFIG_SET_CLEAR(c, \
				CC_DISABLE_DTS | CC_ALLOW_SRC, \
				CC_ENABLE_DRP | CC_SNK_WITH_PD)
#define CONFIG_SNK(c) CONFIG_SET_CLEAR(c, \
				CC_DISABLE_DTS, \
				CC_ALLOW_SRC | CC_ENABLE_DRP | CC_SNK_WITH_PD)
#define CONFIG_PDSNK(c) CONFIG_SET_CLEAR(c, \
				CC_DISABLE_DTS | CC_SNK_WITH_PD, \
				CC_ALLOW_SRC | CC_ENABLE_DRP)
#define CONFIG_DRP(c) CONFIG_SET_CLEAR(c, \
				CC_DISABLE_DTS | CC_ALLOW_SRC | CC_ENABLE_DRP, \
				CC_SNK_WITH_PD)
#define CONFIG_SRCDTS(c) CONFIG_SET_CLEAR(c, \
				CC_ALLOW_SRC, \
				CC_ENABLE_DRP | CC_DISABLE_DTS | CC_SNK_WITH_PD)
#define CONFIG_SNKDTS(c) CONFIG_SET_CLEAR(c, \
				0, \
				CC_ALLOW_SRC | CC_ENABLE_DRP | \
				CC_DISABLE_DTS | CC_SNK_WITH_PD)
#define CONFIG_PDSNKDTS(c) CONFIG_SET_CLEAR(c, \
				CC_SNK_WITH_PD, \
				CC_ALLOW_SRC | CC_ENABLE_DRP | CC_DISABLE_DTS)
#define CONFIG_DRPDTS(c) CONFIG_SET_CLEAR(c, \
				CC_ALLOW_SRC | CC_ENABLE_DRP, \
				CC_DISABLE_DTS | CC_SNK_WITH_PD)

/* Macros to apply Rd/Rp to CC lines */
#define DUT_ACTIVE_CC_SET(r, flags) \
	gpio_set_flags(cc_config & CC_POLARITY ? \
				CONCAT2(GPIO_USB_DUT_CC2_, r) : \
				CONCAT2(GPIO_USB_DUT_CC1_, r), \
		       flags)
#define DUT_INACTIVE_CC_SET(r, flags) \
	gpio_set_flags(cc_config & CC_POLARITY ? \
				CONCAT2(GPIO_USB_DUT_CC1_, r) : \
				CONCAT2(GPIO_USB_DUT_CC2_, r), \
		       flags)
#define DUT_BOTH_CC_SET(r, flags) \
	do { \
		gpio_set_flags(CONCAT2(GPIO_USB_DUT_CC1_, r), flags); \
		gpio_set_flags(CONCAT2(GPIO_USB_DUT_CC2_, r), flags); \
	} while (0)

#define DUT_ACTIVE_CC_PU(r) DUT_ACTIVE_CC_SET(r, GPIO_OUT_HIGH)
#define DUT_INACTIVE_CC_PU(r) DUT_INACTIVE_CC_SET(r, GPIO_OUT_HIGH)
#define DUT_ACTIVE_CC_PD(r) DUT_ACTIVE_CC_SET(r, GPIO_OUT_LOW)
#define DUT_BOTH_CC_PD(r) DUT_BOTH_CC_SET(r, GPIO_OUT_LOW)
#define DUT_BOTH_CC_OPEN(r) DUT_BOTH_CC_SET(r, GPIO_INPUT)

/*
 * Dynamic PDO that reflects capabilities present on the CHG port. Allow for
 * multiple entries so that we can offer greater than 5V charging. The 1st
 * entry will be fixed 5V, but its current value may change based on the CHG
 * port vbus info. Subsequent entries are used for when offering vbus greater
 * than 5V.
 */
static const uint16_t pd_src_voltages_mv[] = {
		5000, 9000, 12000, 15000, 20000,
};
static uint32_t pd_src_chg_pdo[ARRAY_SIZE(pd_src_voltages_mv)];
static uint8_t chg_pdo_cnt;

const uint32_t pd_snk_pdo[] = {
		PDO_FIXED(5000, 500, CHG_PDO_FIXED_FLAGS),
		PDO_BATT(4750, 21000, 15000),
		PDO_VAR(4750, 21000, 3000),
};
const int pd_snk_pdo_cnt = ARRAY_SIZE(pd_snk_pdo);

struct vbus_prop {
	int mv;
	int ma;
};
static struct vbus_prop vbus[CONFIG_USB_PD_PORT_COUNT];
static int active_charge_port = CHARGE_PORT_NONE;
static enum charge_supplier active_charge_supplier;
static uint8_t vbus_rp = TYPEC_RP_RESERVED;

static int cc_config = CC_ALLOW_SRC;

/* Voltage thresholds for no connect in DTS mode */
static int pd_src_vnc_dts[TYPEC_RP_RESERVED][2] = {
	{PD_SRC_3_0_VNC_MV, PD_SRC_1_5_VNC_MV},
	{PD_SRC_1_5_VNC_MV, PD_SRC_DEF_VNC_MV},
	{PD_SRC_3_0_VNC_MV, PD_SRC_DEF_VNC_MV},
};
/* Voltage thresholds for Ra attach in DTS mode */
static int pd_src_rd_threshold_dts[TYPEC_RP_RESERVED][2] = {
	{PD_SRC_3_0_RD_THRESH_MV, PD_SRC_1_5_RD_THRESH_MV},
	{PD_SRC_1_5_RD_THRESH_MV, PD_SRC_DEF_RD_THRESH_MV},
	{PD_SRC_3_0_RD_THRESH_MV, PD_SRC_DEF_RD_THRESH_MV},
};
/* Voltage thresholds for no connect in normal SRC mode */
static int pd_src_vnc[TYPEC_RP_RESERVED] = {
	PD_SRC_DEF_VNC_MV,
	PD_SRC_1_5_VNC_MV,
	PD_SRC_3_0_VNC_MV,
};
/* Voltage thresholds for Ra attach in normal SRC mode */
static int pd_src_rd_threshold[TYPEC_RP_RESERVED] = {
	PD_SRC_DEF_RD_THRESH_MV,
	PD_SRC_1_5_RD_THRESH_MV,
	PD_SRC_3_0_RD_THRESH_MV,
};

/* Saved value for the duration of faking PD disconnect */
static int fake_pd_disconnect_duration_us;

/* Shadow what would be in TCPC register state. */
static int rp_value_stored = TYPEC_RP_USB;
static int cc_pull_stored = TYPEC_CC_RD;

/*
 * Set the USB PD max voltage to value appropriate for the board version.
 * The red/blue versions of servo_v4 have an ESD between VBUS and CC1/CC2
 * that has a breakdown voltage of 11V.
 */
#define MAX_MV_RED_BLUE 9000

static int user_limited_max_mv = 20000;

static uint32_t max_supported_voltage(void)
{
	int board_max_mv = board_get_version() >= BOARD_VERSION_BLACK ?
		PD_MAX_VOLTAGE_MV : MAX_MV_RED_BLUE;

	return board_max_mv < user_limited_max_mv ? board_max_mv :
						    user_limited_max_mv;
}

static int charge_port_is_active(void)
{
	return active_charge_port == CHG && vbus[CHG].mv > 0;
}

static int is_charge_through_allowed(void)
{
	return charge_port_is_active() && cc_config & CC_ALLOW_SRC;
}

static int get_dual_role_of_src(void)
{
	return cc_config & CC_ENABLE_DRP ? PD_DRP_TOGGLE_ON :
					   PD_DRP_FORCE_SOURCE;
}

static void dut_allow_charge(void)
{
	/*
	 * Update to charge enable if charger still present and not
	 * already charging.
	 */
	if (is_charge_through_allowed() &&
	    pd_get_dual_role(DUT) != PD_DRP_FORCE_SOURCE &&
	    pd_get_dual_role(DUT) != PD_DRP_TOGGLE_ON) {
		CPRINTS("Enable DUT charge through");
		pd_set_dual_role(DUT, get_dual_role_of_src());
		/*
		 * If DRP role, don't set any CC pull resistor, the PD
		 * state machine will toggle and set the pull resistors
		 * when needed.
		 */
		if (!(cc_config & CC_ENABLE_DRP))
			pd_set_host_mode(DUT, 1);

		/*
		 * Enable PD comm. The PD comm may be disabled during
		 * the power charge-through was detached.
		 */
		pd_comm_enable(DUT, 1);

		pd_update_contract(DUT);
	}
}
DECLARE_DEFERRED(dut_allow_charge);

static void board_manage_dut_port(void)
{
	enum pd_dual_role_states allowed_role;
	enum pd_dual_role_states current_role;

	/*
	 * This function is called by the CHG port whenever there has been a
	 * change in its vbus voltage or current. That change may necessitate
	 * that the DUT port present a different Rp value or renogiate its PD
	 * contract if it is connected.
	 */

	/* Assume the default value of Rd */
	allowed_role = PD_DRP_FORCE_SINK;

	/* If VBUS charge through is available, mark as such. */
	if (is_charge_through_allowed())
		allowed_role = get_dual_role_of_src();

	current_role = pd_get_dual_role(DUT);
	if (current_role != allowed_role) {
		/* Update role. */
		if (allowed_role == PD_DRP_FORCE_SINK) {
			/* We've lost charge through. Disable VBUS. */
			gpio_set_level(GPIO_DUT_CHG_EN, 0);

			/* Mark as SNK only. */
			pd_set_dual_role(DUT, PD_DRP_FORCE_SINK);
			pd_set_host_mode(DUT, 0);

			/*
			 * Disable PD comm. It matches the user expectation that
			 * unplugging the power charge-through makes servo v4 as
			 * a passive hub, without any PD support.
			 *
			 * There is an exception that servo v4 is explicitly set
			 * to have PD, like the "pnsnk" mode.
			 */
			pd_comm_enable(DUT, cc_config & CC_SNK_WITH_PD ? 1 : 0);
		} else {
			/* Allow charge through after PD negotiate. */
			hook_call_deferred(&dut_allow_charge_data, 2000 * MSEC);
		}
	}

	/*
	 * Update PD contract to reflect new available CHG
	 * voltage/current values.
	 */
	pd_update_contract(DUT);
}

static void update_ports(void)
{
	int pdo_index, src_index, snk_index, i;
	uint32_t pdo, max_ma, max_mv;

	/*
	 * CHG Vbus has changed states, update PDO that reflects CHG port
	 * state
	 */
	if (!charge_port_is_active()) {
		/* CHG Vbus has dropped, so become SNK. */
		chg_pdo_cnt = 0;
	} else {
		/* Advertise the 'best' PDOs at various discrete voltages */
		if (active_charge_supplier == CHARGE_SUPPLIER_PD) {
			src_index = 0;
			snk_index = -1;

			for (i = 0; i < ARRAY_SIZE(pd_src_voltages_mv); ++i) {
				/* Adhere to board voltage limits */
				if (pd_src_voltages_mv[i] >
				    max_supported_voltage())
					break;

				/* Find the 'best' PDO <= voltage */
				pdo_index = pd_find_pdo_index(
					CHG, pd_src_voltages_mv[i], &pdo);
				/* Don't duplicate PDOs */
				if (pdo_index == snk_index)
					continue;
				/* Skip battery / variable PDOs */
				if ((pdo & PDO_TYPE_MASK) != PDO_TYPE_FIXED)
					continue;

				snk_index = pdo_index;
				pd_extract_pdo_power(pdo, &max_ma, &max_mv);
				pd_src_chg_pdo[src_index++] =
					PDO_FIXED_VOLT(max_mv) |
					PDO_FIXED_CURR(max_ma) |
					DUT_PDO_FIXED_FLAGS |
					PDO_FIXED_EXTERNAL;
			}
			chg_pdo_cnt = src_index;
		} else {
			/* 5V PDO */
			pd_src_chg_pdo[0] = PDO_FIXED_VOLT(PD_MIN_MV) |
				PDO_FIXED_CURR(vbus[CHG].ma) |
				DUT_PDO_FIXED_FLAGS |
				PDO_FIXED_EXTERNAL;

			chg_pdo_cnt = 1;
		}
	}

	/* Call DUT port manager to update Rp and possible PD contract */
	board_manage_dut_port();
}

int board_set_active_charge_port(int charge_port)
{
	if (charge_port == DUT)
		return -1;

	active_charge_port = charge_port;
	update_ports();

	if (!charge_port_is_active())
		/* Don't negotiate > 5V, except in lockstep with DUT */
		pd_set_external_voltage_limit(CHG, PD_MIN_MV);

	return 0;
}

void board_set_charge_limit(int port, int supplier, int charge_ma,
			    int max_ma, int charge_mv)
{
	if (port != CHG)
		return;

	active_charge_supplier = supplier;

	/* Update the voltage/current values for CHG port */
	vbus[CHG].ma = charge_ma;
	vbus[CHG].mv = charge_mv;
	update_ports();
}

int pd_tcpc_cc_nc(int port, int cc_volt, int cc_sel)
{
	int rp_index;
	int nc;

	/* Can never be called from CHG port as it's sink only */
	if (port == CHG)
		return 0;

	rp_index = vbus_rp;
	/*
	 * If rp_index > 2, then always return not connected. This case should
	 * only happen when all Rp GPIO controls are tri-stated.
	 */
	if (rp_index >= TYPEC_RP_RESERVED)
		return 1;

	/* Select the correct voltage threshold for current Rp and DTS mode */
	if (cc_config & CC_DISABLE_DTS)
		nc = cc_volt >= pd_src_vnc[rp_index];
	else
		nc = cc_volt >= pd_src_vnc_dts[rp_index][cc_sel];

	return nc;
}

int pd_tcpc_cc_ra(int port, int cc_volt, int cc_sel)
{
	int rp_index;
	int ra;

	/* Can never be called from CHG port as it's sink only */
	if (port == CHG)
		return 0;

	rp_index = vbus_rp;
	/*
	 * If rp_index > 2, then can't be Ra. This case should
	 * only happen when all Rp GPIO controls are tri-stated.
	 */
	if (rp_index >= TYPEC_RP_RESERVED)
		return 0;

	/* Select the correct voltage threshold for current Rp and DTS mode */
	if (cc_config & CC_DISABLE_DTS)
		ra = cc_volt < pd_src_rd_threshold[rp_index];
	else
		ra = cc_volt < pd_src_rd_threshold_dts[rp_index][cc_sel];

	return ra;
}

int pd_adc_read(int port, int cc)
{
	int mv;

	if (port == 0)
		mv = adc_read_channel(cc ? ADC_CHG_CC2_PD : ADC_CHG_CC1_PD);
	else if (!(cc_config & CC_DETACH)) {
		/*
		 * In servo v4 hardware logic, both CC lines are wired directly
		 * to DUT. When servo v4 as a snk, DUT may source Vconn to CC2
		 * (CC1 if polarity flip) and make the voltage high as vRd-3.0,
		 * which makes the PD state mess up. As the PD state machine
		 * doesn't handle this case. It assumes that CC2 (CC1 if
		 * polarity flip) is separated by a Type-C cable, resulting a
		 * voltage lower than the max of vRa.
		 *
		 * It fakes the voltage within vRa.
		 */
		if ((cc_config & CC_DISABLE_DTS) &&
		    cc_pull_stored == TYPEC_CC_RD && port == DUT &&
		    cc == (cc_config & CC_POLARITY ? 0 : 1))
			mv = 0;
		else
			mv = adc_read_channel(cc ? ADC_DUT_CC2_PD :
						   ADC_DUT_CC1_PD);
	} else {
		/*
		 * When emulating detach, fake the voltage on CC to 0 to avoid
		 * triggering some debounce logic.
		 *
		 * The servo v4 makes Rd/Rp open but the DUT may present Rd/Rp
		 * alternatively that makes the voltage on CC falls into some
		 * unexpected range and triggers the PD state machine switching
		 * between SNK_DISCONNECTED and SNK_DISCONNECTED_DEBOUNCE.
		 */
		mv = 0;
	}

	return mv;
}

static int board_set_rp(int rp)
{
	if (cc_config & CC_DISABLE_DTS) {
		/*
		 * DTS mode is disabled, so only present the requested Rp value
		 * on CC1 (active) and leave all Rp/Rd resistors on CC2
		 * (inactive) disconnected.
		 */
		switch (rp) {
		case TYPEC_RP_USB:
			DUT_ACTIVE_CC_PU(RPUSB);
			break;
		case TYPEC_RP_1A5:
			DUT_ACTIVE_CC_PU(RP1A5);
			break;
		case TYPEC_RP_3A0:
			DUT_ACTIVE_CC_PU(RP3A0);
			break;
		case TYPEC_RP_RESERVED:
			/*
			 * This case can be used to force a detach event since
			 * all values are set to inputs above. Nothing else to
			 * set.
			 */
			break;
		default:
			return EC_ERROR_INVAL;
		}
	} else {
		/* DTS mode is enabled. The rp parameter is used to select the
		 * Type C current limit to advertise. The combinations of Rp on
		 * each CC line is shown in the table below.
		 *
		 * CC values for Debug sources (DTS)
		 *
		 * Source type  Mode of Operation   CC1    CC2
		 * ---------------------------------------------
		 * DTS          Default USB Power   Rp3A0  Rp1A5
		 * DTS          USB-C @ 1.5 A       Rp1A5  RpUSB
		 * DTS          USB-C @ 3 A         Rp3A0  RpUSB
		 */
		switch (rp) {
		case TYPEC_RP_USB:
			DUT_ACTIVE_CC_PU(RP3A0);
			DUT_INACTIVE_CC_PU(RP1A5);
			break;
		case TYPEC_RP_1A5:
			DUT_ACTIVE_CC_PU(RP1A5);
			DUT_INACTIVE_CC_PU(RPUSB);
			break;
		case TYPEC_RP_3A0:
			DUT_ACTIVE_CC_PU(RP3A0);
			DUT_INACTIVE_CC_PU(RPUSB);
			break;
		case TYPEC_RP_RESERVED:
			/*
			 * This case can be used to force a detach event since
			 * all values are set to inputs above. Nothing else to
			 * set.
			 */
			break;
		default:
			return EC_ERROR_INVAL;
		}
	}
	/* Save new Rp value for DUT port */
	vbus_rp = rp;

	return EC_SUCCESS;
}

int pd_set_rp_rd(int port, int cc_pull, int rp_value)
{
	int rv = EC_SUCCESS;

	if (port != 1)
		return EC_ERROR_UNIMPLEMENTED;

	/* CC is disabled for emulating detach. Don't change Rd/Rp. */
	if (cc_config & CC_DETACH)
		return EC_SUCCESS;

	/* By default disconnect all Rp/Rd resistors from both CC lines */
	/* Set Rd for CC1/CC2 to High-Z. */
	DUT_BOTH_CC_OPEN(RD);
	/* Set Rp for CC1/CC2 to High-Z. */
	DUT_BOTH_CC_OPEN(RP3A0);
	DUT_BOTH_CC_OPEN(RP1A5);
	DUT_BOTH_CC_OPEN(RPUSB);
	/* Set TX Hi-Z */
	DUT_BOTH_CC_OPEN(TX_DATA);

	if (cc_pull == TYPEC_CC_RP) {
		rv = board_set_rp(rp_value);
	} else if (cc_pull == TYPEC_CC_RD) {
		/*
		 * The DUT port uses a captive cable. It can present Rd on both
		 * CC1 and CC2. If DTS mode is enabled, then present Rd on both
		 * CC lines. However, if DTS mode is disabled only present Rd on
		 * CC1 (active).
		 */
		if (cc_config & CC_DISABLE_DTS)
			DUT_ACTIVE_CC_PD(RD);
		else
			DUT_BOTH_CC_PD(RD);

	}

	rp_value_stored = rp_value;
	cc_pull_stored = cc_pull;

	return rv;
}

int board_select_rp_value(int port, int rp)
{
	if (port != 1)
		return EC_ERROR_UNIMPLEMENTED;

	/*
	 * Update Rp value to indicate non-pd power available.
	 * Do not change pull direction though.
	 */
	if ((rp != rp_value_stored) && (cc_pull_stored == TYPEC_CC_RP)) {
		rp_value_stored = rp;
		return pd_set_rp_rd(port, TYPEC_CC_RP, rp);
	}

	return EC_SUCCESS;
}

int charge_manager_get_source_pdo(const uint32_t **src_pdo, const int port)
{
	int pdo_cnt = 0;

	/*
	 * If CHG is providing VBUS, then advertise what's available on the CHG
	 * port, otherwise we provide no power.
	 */
	if (charge_port_is_active()) {
		*src_pdo =  pd_src_chg_pdo;
		pdo_cnt = chg_pdo_cnt;
	}

	return pdo_cnt;
}

int pd_is_valid_input_voltage(int mv)
{
	/* Any voltage less than the max is allowed */
	return 1;
}

void pd_transition_voltage(int idx)
{
	timestamp_t deadline;
	uint32_t ma, mv;

	pd_extract_pdo_power(pd_src_chg_pdo[idx - 1], &ma, &mv);
	/* Is this a transition to a new voltage? */
	if (charge_port_is_active() && vbus[CHG].mv != mv) {
		/*
		 * Alter voltage limit on charge port, this should cause
		 * the port to select the desired PDO.
		 */
		pd_set_external_voltage_limit(CHG, mv);

		/* Wait for CHG transition */
		deadline.val = get_time().val + PD_T_PS_TRANSITION;
		CPRINTS("Waiting for CHG port transition");
		while (charge_port_is_active() &&
		       vbus[CHG].mv != mv &&
		       get_time().val < deadline.val)
			msleep(10);

		if (vbus[CHG].mv != mv) {
			CPRINTS("Missed CHG transition, resetting DUT");
			pd_power_supply_reset(DUT);
			return;
		}

		CPRINTS("CHG transitioned");
	}

	vbus[DUT].mv = vbus[CHG].mv;
	vbus[DUT].ma = vbus[CHG].ma;
}

int pd_set_power_supply_ready(int port)
{
	/* Port 0 can never provide vbus. */
	if (port == CHG)
		return EC_ERROR_INVAL;

	if (charge_port_is_active()) {
		/* Enable VBUS */
		gpio_set_level(GPIO_DUT_CHG_EN, 1);

		if (vbus[CHG].mv != PD_MIN_MV)
			CPRINTS("ERROR, CHG port voltage %d != PD_MIN_MV",
				vbus[CHG].mv);

		vbus[DUT].mv = vbus[CHG].mv;
		vbus[DUT].ma = vbus[CHG].mv;
		pd_set_dual_role(DUT, get_dual_role_of_src());
	} else {
		vbus[DUT].mv = 0;
		vbus[DUT].ma = 0;
		gpio_set_level(GPIO_DUT_CHG_EN, 0);
		pd_set_dual_role(DUT, PD_DRP_FORCE_SINK);
		return EC_ERROR_NOT_POWERED;
	}

	/* Enable CCD, if debuggable TS attached */
	if (pd_ts_dts_plugged(DUT))
		ccd_enable(1);

	return EC_SUCCESS; /* we are ready */
}

void pd_power_supply_reset(int port)
{
	/* Port 0 can never provide vbus. */
	if (port == CHG)
		return;

	ccd_enable(0);

	/* Disable VBUS */
	gpio_set_level(GPIO_DUT_CHG_EN, 0);

	/* DUT is lost, back to 5V limit on CHG */
	pd_set_external_voltage_limit(CHG, PD_MIN_MV);
}

int pd_snk_is_vbus_provided(int port)
{

	return gpio_get_level(port ? GPIO_USB_DET_PP_DUT :
				     GPIO_USB_DET_PP_CHG);
}

int pd_board_checks(void)
{
	return EC_SUCCESS;
}

int pd_check_power_swap(int port)
{
	/*
	 * When only host VBUS is available, then servo_v4 is not setting
	 * PDO_FIXED_EXTERNAL in the src_pdo sent to the DUT. When this bit is
	 * not set, the DUT will always attempt to swap its power role to
	 * SRC. Let servo_v4 have more control over its power role by always
	 * rejecting power swap requests from the DUT.
	 */

	/* Port 0 can never provide vbus. */
	if (port == CHG)
		return 0;

	if (pd_snk_is_vbus_provided(CHG))
		return 1;

	return 0;
}

int pd_check_data_swap(int port, int data_role)
{
	/*
	 * Servo should allow data role swaps to let DUT see the USB hub, but
	 * doing it on CHG port is a waste as its data lines is unconnected.
	 */
	if (port == CHG)
		return 0;

	return 1;
}

void pd_execute_data_swap(int port, int data_role)
{
	/*
	 * TODO(b/137887386): Turn on the fastboot/DFU path when data swap to
	 * DFP?
	 */
}

void pd_check_pr_role(int port, int pr_role, int flags)
{
	/*
	 * Don't define any policy to initiate power role swap.
	 *
	 * CHG port is SNK only. DUT port requires a user to switch its
	 * role by commands. So don't do anything implicitly.
	 */
}

void pd_check_dr_role(int port, int dr_role, int flags)
{
	if (port == CHG)
		return;

	/* If DFP, try to switch to UFP, to let DUT see the USB hub. */
	if ((flags & PD_FLAGS_PARTNER_DR_DATA) && dr_role == PD_ROLE_DFP)
		pd_request_data_swap(port);
}


/* ----------------- Vendor Defined Messages ------------------ */
const struct svdm_response svdm_rsp = {
	.identity = NULL,
	.svids = NULL,
	.modes = NULL,
};

int pd_custom_vdm(int port, int cnt, uint32_t *payload,
		  uint32_t **rpayload)
{
	int cmd = PD_VDO_CMD(payload[0]);

	/* make sure we have some payload */
	if (cnt == 0)
		return 0;

	switch (cmd) {
	case VDO_CMD_VERSION:
		/* guarantee last byte of payload is null character */
		*(payload + cnt - 1) = 0;
		CPRINTF("ver: %s\n", (char *)(payload+1));
		break;
	case VDO_CMD_CURRENT:
		CPRINTF("Current: %dmA\n", payload[1]);
		break;
	}

	return 0;
}



const struct svdm_amode_fx supported_modes[] = {};
const int supported_modes_cnt = ARRAY_SIZE(supported_modes);


static void print_cc_mode(void)
{
	/* Get current CCD status */
	ccprintf("cc: %s\n", cc_config & CC_DETACH ? "off" : "on");
	ccprintf("dts mode: %s\n", cc_config & CC_DISABLE_DTS ? "off" : "on");
	ccprintf("chg mode: %s\n",
		 gpio_get_level(GPIO_DUT_CHG_EN) ? "on" : "off");
	ccprintf("chg allowed: %s\n", cc_config & CC_ALLOW_SRC ? "on" : "off");
	ccprintf("drp enabled: %s\n", cc_config & CC_ENABLE_DRP ? "on" : "off");
	ccprintf("cc polarity: %s\n", cc_config & CC_POLARITY ? "cc2" :
								"cc1");
}


static void do_cc(int cc_config_new)
{
	int chargeable;
	int dualrole;

	if (cc_config_new != cc_config) {
		if (!(cc_config & CC_DETACH)) {
			/* Force detach */
			pd_power_supply_reset(DUT);
			/* Always set to 0 here so both CC lines are changed */
			cc_config &= ~(CC_DISABLE_DTS & CC_ALLOW_SRC);

			/* Remove Rp/Rd on both CC lines */
			pd_comm_enable(DUT, 0);
			pd_set_rp_rd(DUT, TYPEC_CC_RP, TYPEC_RP_RESERVED);

			/*
			 * If just changing mode (cc keeps enabled), give some
			 * time for DUT to detach, use tErrorRecovery.
			 */
			if (!(cc_config_new & CC_DETACH))
				usleep(PD_T_ERROR_RECOVERY);
		}

		/* Accept new cc_config value */
		cc_config = cc_config_new;

		if (!(cc_config & CC_DETACH)) {
			/* Can we source? */
			chargeable = is_charge_through_allowed();
			dualrole = chargeable ? get_dual_role_of_src() :
						PD_DRP_FORCE_SINK;
			pd_set_dual_role(DUT, dualrole);
			/*
			 * If force_source or force_sink role, explicitly set
			 * the Rp or Rd resistors on CC lines.
			 *
			 * If DRP role, don't set any CC pull resistor, the PD
			 * state machine will toggle and set the pull resistors
			 * when needed.
			 */
			if (dualrole != PD_DRP_TOGGLE_ON)
				pd_set_host_mode(DUT, chargeable);

			/*
			 * For the normal lab use, emulating a sink has no PD
			 * comm, like a passive hub. For the PD FAFT use, we
			 * need to validate some PD behavior, so a flag
			 * CC_SNK_WITH_PD to force enabling PD comm.
			 */
			if (cc_config & CC_SNK_WITH_PD)
				pd_comm_enable(DUT, 1);
			else
				pd_comm_enable(DUT, chargeable);
		}
	}
}

static int command_cc(int argc, char **argv)
{
	int cc_config_new = cc_config;

	if (argc < 2) {
		print_cc_mode();
		return EC_SUCCESS;
	}

	if (!strcasecmp(argv[1], "off")) {
		cc_config_new |= CC_DETACH;
	} else if (!strcasecmp(argv[1], "on")) {
		cc_config_new &= ~CC_DETACH;
	} else {
		cc_config_new &= ~CC_DETACH;
		if (!strcasecmp(argv[1], "src"))
			cc_config_new = CONFIG_SRC(cc_config_new);
		else if (!strcasecmp(argv[1], "snk"))
			cc_config_new = CONFIG_SNK(cc_config_new);
		else if (!strcasecmp(argv[1], "pdsnk"))
			cc_config_new = CONFIG_PDSNK(cc_config_new);
		else if (!strcasecmp(argv[1], "drp"))
			cc_config_new = CONFIG_DRP(cc_config_new);
		else if (!strcasecmp(argv[1], "srcdts"))
			cc_config_new = CONFIG_SRCDTS(cc_config_new);
		else if (!strcasecmp(argv[1], "snkdts"))
			cc_config_new = CONFIG_SNKDTS(cc_config_new);
		else if (!strcasecmp(argv[1], "pdsnkdts"))
			cc_config_new = CONFIG_PDSNKDTS(cc_config_new);
		else if (!strcasecmp(argv[1], "drpdts"))
			cc_config_new = CONFIG_DRPDTS(cc_config_new);
		else
			return EC_ERROR_PARAM2;
	}

	if (!strcasecmp(argv[2], "cc1"))
		cc_config_new &= ~CC_POLARITY;
	else if (!strcasecmp(argv[2], "cc2"))
		cc_config_new |= CC_POLARITY;
	else if (argc >= 3)
		return EC_ERROR_PARAM3;

	do_cc(cc_config_new);
	print_cc_mode();

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(cc, command_cc,
			"[off|on|src|snk|pdsnk|drp|srcdts|snkdts|pdsnkdts|"
			"drpdts] [cc1|cc2]",
			"Servo_v4 DTS and CHG mode");

static void fake_disconnect_end(void)
{
	/* Reenable CC lines with previous dts and src modes */
	do_cc(cc_config & ~CC_DETACH);
}
DECLARE_DEFERRED(fake_disconnect_end);

static void fake_disconnect_start(void)
{
	/* Disable CC lines */
	do_cc(cc_config | CC_DETACH);

	hook_call_deferred(&fake_disconnect_end_data,
			   fake_pd_disconnect_duration_us);
}
DECLARE_DEFERRED(fake_disconnect_start);

static int cmd_fake_disconnect(int argc, char *argv[])
{
	int delay_ms, duration_ms;
	char *e;

	if (argc < 3)
		return EC_ERROR_PARAM_COUNT;

	delay_ms = strtoi(argv[1], &e, 0);
	if (*e || delay_ms < 0)
		return EC_ERROR_PARAM1;
	duration_ms = strtoi(argv[2], &e, 0);
	if (*e || duration_ms < 0)
		return EC_ERROR_PARAM2;

	/* Cancel any pending function calls */
	hook_call_deferred(&fake_disconnect_start_data, -1);
	hook_call_deferred(&fake_disconnect_end_data, -1);

	fake_pd_disconnect_duration_us = duration_ms * MSEC;
	hook_call_deferred(&fake_disconnect_start_data, delay_ms * MSEC);

	ccprintf("Fake disconnect for %d ms starting in %d ms.\n",
		duration_ms, delay_ms);

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(fakedisconnect, cmd_fake_disconnect,
			"<delay_ms> <duration_ms>", NULL);

static int cmd_usbc_action(int argc, char *argv[])
{
	if (argc != 2)
		return EC_ERROR_PARAM_COUNT;

	if (!strcasecmp(argv[1], "5v")) {
		do_cc(CONFIG_SRC(cc_config));
		user_limited_max_mv = 5000;
		update_ports();
	} else if (!strcasecmp(argv[1], "12v")) {
		do_cc(CONFIG_SRC(cc_config));
		user_limited_max_mv = 12000;
		update_ports();
	} else if (!strcasecmp(argv[1], "20v")) {
		do_cc(CONFIG_SRC(cc_config));
		user_limited_max_mv = 20000;
		update_ports();
	} else if (!strcasecmp(argv[1], "dev")) {
		/* Set the limit back to original */
		user_limited_max_mv = 20000;
		do_cc(CONFIG_PDSNK(cc_config));
	} else if (!strcasecmp(argv[1], "pol0")) {
		do_cc(cc_config & ~CC_POLARITY);
	} else if (!strcasecmp(argv[1], "pol1")) {
		do_cc(cc_config | CC_POLARITY);
	} else if (!strcasecmp(argv[1], "drp")) {
		/* Toggle the DRP state, compatible with Plankton. */
		do_cc(cc_config ^ CC_ENABLE_DRP);
		CPRINTF("DRP = %d, host_mode = %d\n",
			!!(cc_config & CC_ENABLE_DRP),
			!!(cc_config & CC_ALLOW_SRC));
	} else {
		return EC_ERROR_PARAM1;
	}

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(usbc_action, cmd_usbc_action,
			"5v|12v|20v|dev|pol0|pol1|drp",
			"Set Servo v4 type-C port state");