-
Notifications
You must be signed in to change notification settings - Fork 1
/
wtptp.c
1307 lines (1082 loc) · 28.3 KB
/
wtptp.c
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
// SPDX-License-Identifier: Beerware
/*
* 2018 by Marek Behun <[email protected]>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <asm/termbits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>
#include <math.h>
#include <endian.h>
#include <pthread.h>
#include "tim.h"
#include "utils.h"
#include "wtptp.h"
#include "mox-imager.h"
/* Some architectures don't have termios2 */
#ifndef TCGETS2
#define TCGETS2 TCGETS
#define TCSETS2 TCSETS
#define TCSETSW2 TCSETSW
#define TCSETSF2 TCSETSF
#define termios2 termios
#endif
#define EXIT_STATUS_TOO_MANY_RESTARTS 5
static int wtpfd = -1;
static u32 last_image_sent;
static int sent_timh_was_trusted;
static const char *xread_timed_out_msg;
static const char *nack_msg;
static const char *unk_resp_sts_msg;
static inline void xtcdrain(int fd)
{
if (ioctl(fd, TCSBRK, 1) < 0)
die("Cannot tcdrain: %m");
}
static inline void xtcflush(int fd, int q)
{
if (ioctl(fd, TCFLSH, q) < 0)
die("Cannot tcflush: %m");
}
static inline void xtcgetattr2(int fd, struct termios2 *t)
{
if (ioctl(fd, TCGETS2, t) < 0)
die("Failed getting tty attrs: %m");
}
static inline void xtcsetattr2(int fd, const struct termios2 *t)
{
if (ioctl(fd, TCSETS2, t) < 0)
die("Failed setting tty attrs: %m");
}
static void cfmakeraw2(struct termios2 *t)
{
t->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR |
ICRNL | IXON);
t->c_oflag &= ~OPOST;
t->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
t->c_cflag &= ~(CSIZE | PARENB);
t->c_cflag |= CS8;
}
static void xread(void *buf, size_t size)
{
ssize_t res;
size_t rd;
struct pollfd pfd;
pfd.fd = wtpfd;
pfd.events = POLLIN;
rd = 0;
while (rd < size) {
pfd.revents = 0;
res = poll(&pfd, 1, 2 * 1000);
if (res == 0)
throw_or_die(xread_timed_out_msg,
"Timed out while waiting for response!%s",
xread_timed_out_msg ?: "");
else if (res < 0)
die("Cannot poll: %m");
if (pfd.revents & POLLERR)
die("File descriptor error!");
res = read(wtpfd, buf + rd, size - rd);
if (res <= 0)
die("Cannot read %zu bytes: %m", size);
rd += res;
}
}
static void xwrite(const void *buf, size_t size)
{
ssize_t res;
res = write(wtpfd, buf, size);
if (res < 0)
die("Cannot write %zu bytes: %m", size);
else if ((size_t)res < size)
die("Cannot write %zu bytes: written only %zi", size, res);
}
static enum escape_state {
STATE_ESCAPE,
STATE_SEQ_ESCAPE,
STATE_WRITE_CLEAR,
STATE_WRITE_WTP,
} state;
#define state_store(i) __atomic_store_n(&state, (i), __ATOMIC_RELEASE)
#define state_load() __atomic_load_n(&state, __ATOMIC_ACQUIRE)
static void seq_write(const void *seq, size_t len)
{
const useconds_t one_cycle = 1000 * 1000 * 10 / 115200;
usleep(one_cycle);
xwrite(seq, len);
xtcdrain(wtpfd);
}
static void *seq_write_handler(void *ptr __attribute__((unused)))
{
const u8 esc_seq[] = { 0xbb, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 };
const u8 clr_seq[] = { 0x0d, 0x0d, 0x0d, 0x0d };
const u8 wtp_seq[] = { 0x03, 'w', 't', 'p', '\r' };
enum escape_state prev_state = state_load();
while (1) {
enum escape_state new_state = state_load();
if (new_state != STATE_ESCAPE && prev_state == STATE_ESCAPE) {
xtcflush(wtpfd, TCOFLUSH);
xtcdrain(wtpfd);
}
switch (new_state) {
case STATE_ESCAPE:
xwrite(esc_seq, sizeof(esc_seq));
break;
case STATE_SEQ_ESCAPE:
seq_write(esc_seq, sizeof(esc_seq));
break;
case STATE_WRITE_CLEAR:
seq_write(clr_seq, sizeof(clr_seq));
return NULL;
case STATE_WRITE_WTP:
seq_write(wtp_seq, sizeof(wtp_seq));
return NULL;
default:
__builtin_unreachable();
}
prev_state = new_state;
}
}
static void seq_write_thread_start(pthread_t *write_thread)
{
int ret;
ret = pthread_create(write_thread, NULL, seq_write_handler, NULL);
if (ret) {
errno = ret;
die("pthread_create failed: %m");
}
}
static void seq_write_thread_join(pthread_t write_thread)
{
int ret;
ret = pthread_join(write_thread, NULL);
if (ret) {
errno = ret;
die("pthread_join failed: %m");
}
}
static int is_all_zeros(const u8 *buf, int len)
{
int i;
for (i = 0; i < len; ++i)
if (buf[i])
return 0;
return 1;
}
static void initwtp_fail(pthread_t *write_thread)
{
error("Invalid reply too many times, aborting!\n\n");
if (write_thread) {
state_store(STATE_WRITE_CLEAR);
seq_write_thread_join(*write_thread);
}
exit(EXIT_STATUS_TOO_MANY_RESTARTS);
}
/*
* This works when escape sequence is needed to force UART mode but also when
* BootROM console is enabled and "wtp" command is needed.
*/
void initwtp(int escape_seq, int max_restarts)
{
const u8 bootrom_prompt_reply[] = {
'>', '>', 0x22, 0x33, 0x44, 0x55, 0x66, 0x77
};
pthread_t write_thread;
struct termios2 opts;
struct pollfd pfd;
tcflag_t iflag;
int ack_count;
u8 buf[8192];
int restarts;
int len, i;
int done;
int ret;
if (!escape_seq) {
/* only send wtp command */
xwrite("\x03wtp\r", 5);
xread(buf, 8);
if (memcmp(buf, "!\r\nwtp\r\n", 8))
die("Invalid reply for command wtp, try again");
notice("Initialized WTP download mode\n\n");
return;
}
if (!isatty(wtpfd))
die("Cannot send escape sequence on non-tty file descriptor");
/* set PARMRK to distinguish between zero byte and break condition */
xtcgetattr2(wtpfd, &opts);
iflag = opts.c_iflag;
opts.c_iflag |= PARMRK;
xtcsetattr2(wtpfd, &opts);
notice("Sending escape sequence, please power up the device\n");
seq_write_thread_start(&write_thread);
pfd.fd = wtpfd;
pfd.events = POLLIN;
len = 0;
ack_count = 0;
done = 0;
restarts = 0;
while (!done) {
if (state == STATE_WRITE_CLEAR || state == STATE_WRITE_WTP) {
pfd.revents = 0;
ret = poll(&pfd, 1, 300);
if (ret < 0)
die("poll failed: %m");
else if (!ret && state == STATE_WRITE_CLEAR)
break;
}
ret = read(wtpfd, buf + len, sizeof(buf) - len);
if (ret <= 0)
die("read failed: %m");
len += ret;
switch (state) {
case STATE_ESCAPE:
if (buf[len - 1] == 0x3e) {
state_store(STATE_SEQ_ESCAPE);
printf("\e[0KReceived sync reply\n");
printf("Sending escape sequence with delay\n");
}
__attribute__((__fallthrough__));
case STATE_SEQ_ESCAPE:
for (i = 8; i > 0; i--)
if (len >= i && !memcmp(buf + len - i, bootrom_prompt_reply, i))
break;
if (i > 0) {
if (i == 8 || (len - i >= 8 && !memcmp(buf + len - i - 8, bootrom_prompt_reply, 8))) {
state_store(STATE_WRITE_WTP);
printf("\e[0KDetected BootROM command prompt\n");
printf("Sending wtp sequence\n");
seq_write_thread_join(write_thread);
len = 0;
/* it is required to wait at least 0.5s */
usleep(500000);
} else {
memmove(buf, buf + len - i, i);
len = i;
}
} else {
if (len >= 16) {
if (is_all_zeros(buf + len - 16, 16)) {
state_store(STATE_WRITE_CLEAR);
printf("\e[0KReceived ack reply\n");
printf("Sending clearbuf sequence\n");
seq_write_thread_join(write_thread);
ack_count = 0;
restarts++;
} else if (buf[len - 1] != 0x3e) {
if (max_restarts >= 0 && restarts > max_restarts) {
initwtp_fail(&write_thread);
} else {
state_store(STATE_ESCAPE);
notice("\e[0KInvalid reply 0x%02x, try restarting again\r", buf[len - 1]);
fflush(stdout);
}
}
len = 0;
}
}
break;
case STATE_WRITE_CLEAR:
if (is_all_zeros(buf, len)) {
/*
* if we received too much ack replies after
* first read (ack_count is non-zero), send
* clearbuf sequence again
*/
if (ack_count && ack_count + len > 1000) {
seq_write_thread_start(&write_thread);
seq_write_thread_join(write_thread);
ack_count = 0;
} else {
ack_count += len;
}
len = 0;
} else {
if (max_restarts >= 0 && restarts > max_restarts) {
initwtp_fail(NULL);
} else {
state_store(STATE_ESCAPE);
seq_write_thread_start(&write_thread);
notice("\e[0KInvalid reply, try restarting again\r");
fflush(stdout);
}
}
break;
case STATE_WRITE_WTP:
/* 4095 bytes is size of kernel tty buffer, drop data from beginning of buffer and read remaining data */
if (len >= 4095) {
memmove(buf, buf + len - 7, 7);
len = 7;
} else if (len >= 8) {
if (!memcmp(buf + len - 8, "!\r\nwtp\r\n", 8)) {
done = 1;
} else {
if (max_restarts >= 0 && restarts > max_restarts) {
initwtp_fail(NULL);
} else {
state_store(STATE_ESCAPE);
seq_write_thread_start(&write_thread);
notice("\e[0KInvalid reply 0x%02x, try restarting again\r", buf[len - 1]);
fflush(stdout);
}
}
}
break;
default:
__builtin_unreachable();
}
}
info("\e[0KInitialized UART download mode\n\n");
/* restore previous iflag */
xtcgetattr2(wtpfd, &opts);
opts.c_iflag = iflag;
xtcsetattr2(wtpfd, &opts);
}
void setwtpfd(const char *fdstr)
{
char *end;
int flags;
wtpfd = strtol(fdstr, &end, 10);
if (*end || wtpfd < 0)
die("Wrong file descriptor %s", fdstr);
flags = fcntl(wtpfd, F_GETFL);
if (flags < 0 && errno == EBADF)
die("Wrong file descriptor %s", fdstr);
if (flags < 0)
die("Could not get file descriptor flags: %m");
if (flags & O_NONBLOCK) {
/* set to blocking mode */
if (fcntl(wtpfd, F_SETFL, flags & ~O_NONBLOCK))
die("Unsetting O_NONBLOCK failed: %m");
}
}
void openwtp(const char *path)
{
struct termios2 opts;
int flags;
/* O_NONBLOCK is required to avoid hangs when CLOCAL is not set */
wtpfd = open(path, O_RDWR | O_NONBLOCK | O_NOCTTY);
if (wtpfd < 0)
die("Cannot open %s: %m", path);
memset(&opts, 0, sizeof(opts));
xtcgetattr2(wtpfd, &opts);
cfmakeraw2(&opts);
opts.c_cflag |= CREAD | CLOCAL;
opts.c_cflag &= ~(CSTOPB | HUPCL | CRTSCTS);
opts.c_cflag &= ~CBAUD;
opts.c_cflag |= B115200;
#ifdef IBSHIFT
opts.c_cflag &= ~(CBAUD << IBSHIFT);
opts.c_cflag |= B0 << IBSHIFT;
#endif
opts.c_cc[VMIN] = 1;
opts.c_cc[VTIME] = 0;
xtcsetattr2(wtpfd, &opts);
xtcgetattr2(wtpfd, &opts);
if ((opts.c_cflag & CBAUD) != B115200)
die("Baudrate 115200 not supported");
#ifdef IBSHIFT
if (((opts.c_cflag >> IBSHIFT) & CBAUD) != B0)
die("Baudrate 115200 not supported");
#endif
xtcflush(wtpfd, TCIFLUSH);
flags = fcntl(wtpfd, F_GETFL);
if (flags < 0)
die("Failure getting file descriptor flags: %m");
/* unset O_NONBLOCK */
if (fcntl(wtpfd, F_SETFL, flags & ~O_NONBLOCK))
die("Unsetting O_NONBLOCK failed: %m");
last_image_sent = 0;
sent_timh_was_trusted = 0;
xread_timed_out_msg = NULL;
nack_msg = NULL;
unk_resp_sts_msg = NULL;
}
void closewtp(void)
{
if (wtpfd != -1)
close(wtpfd);
wtpfd = -1;
}
/*
* Some images may print additional characters on UART when loaded. We must
* ignore this characters in WTPTP protocol.
*
* Try to receive the until character sequence in first up to max bytes, and
* if stdout is a TTY, print anything that was sent before this sequence to
* in yellow.
*/
static int read_until(const u8 *until, size_t ulen, size_t max)
{
int printed = 0;
size_t i, j, pos;
u8 buf[ulen], last;
int istty;
istty = isatty(STDOUT_FILENO);
pos = 0;
for (i = 0; i < max; ++i) {
xread(&buf[pos], 1);
if (buf[pos] == until[pos]) {
++pos;
} else {
if (istty) {
if (printed) {
printf("%.*s", (int)pos + 1,
(char *)buf);
} else {
for (j = 0; j < pos + 1; j++)
if (buf[j] != '\r' &&
buf[j] != '\n')
break;
if (j < pos + 1) {
printf("\n\033[33;1m%.*s",
(int)(pos + 1 - j),
(char *)buf + j);
printed = 1;
}
}
last = buf[pos];
}
pos = 0;
}
if (pos == ulen)
break;
}
if (printed) {
if (last != '\n')
putchar('\n');
printf("\n\033[0m");
fflush(stdout);
}
return pos == ulen;
}
static int compute_tbg_freq(int xtal, int fbdiv, int refdiv, int vcodiv_sel)
{
if (!refdiv)
refdiv = 1;
return 1000000 * (u64)xtal * (fbdiv << 2) / (refdiv * (1 << vcodiv_sel));
}
static int compute_best_uart_params(u32 clk, u32 desired_baud, u32 *div, u32 *m)
{
u8 m1, m2, m3, m4, best_m1 = 0, best_m2 = 0, best_m3 = 0, best_m4 = 0;
u64 ticks, ratio, err, best_err = -1ULL;
u32 d, d_max, best_d;
_Bool eq, best_eq = 0;
/*
* We are using fixed-point arithmetic to compute best possible
* parameters. We need to know the maximum possible parameter value for
* the integral part of the fixed-point number so that we know how many
* bits we must shift.
*/
const u64 fp_max_param =
/* max ticks * max desired baud */
(u64)((3 * (63 + 63) + 2 * (63 + 63)) * 1023) * 6000000;
const int fp_shift = __builtin_clzll(fp_max_param) - 1;
const u64 fp_1 = 1ULL << fp_shift;
d_max = clk / (desired_baud * 16);
if (d_max > 1023)
d_max = 1023;
for (d = 2; d <= d_max; ++d) {
u8 lo, hi;
m1 = clk / (desired_baud * d);
if (m1 < 2 || m1 > 63)
continue;
lo = m1 == 2 ? 2 : m1 - 1;
hi = m1 == 63 ? 63 : m1 + 1;
for (m2 = lo; m2 <= hi; ++m2) {
for (m3 = lo; m3 <= hi; ++m3) {
if (abs((int)m2 - m3) > 1)
continue;
for (m4 = lo; m4 <= hi; ++m4) {
if (abs((int)m3 - m4) > 1)
continue;
ticks = (3 * ((u32)m1 + m2) + 2 * ((u32)m3 + m4)) * d;
ratio = ((ticks * desired_baud) << fp_shift) / (10ULL * clk);
/* distance from 1 */
if (ratio > fp_1)
err = ratio - fp_1;
else
err = fp_1 - ratio;
eq = (m1 == m2 && m2 == m3 && m3 == m4);
if (err < best_err || (err == best_err && eq && !best_eq)) {
best_err = err;
best_d = d;
best_m1 = m1;
best_m2 = m2;
best_m3 = m3;
best_m4 = m4;
best_eq = eq;
}
}
}
}
}
if (best_err == -1ULL)
return -1;
*div = best_d;
*m = (best_m4 << 24) | (best_m3 << 16) | (best_m2 << 8) | best_m1;
return 0;
}
static tcflag_t baudrate_to_cflag(unsigned int baudrate)
{
#define B(b) { B ## b, b }
static const struct {
tcflag_t cflag;
unsigned int baudrate;
} map[] = {
B(50), B(75), B(110), B(134), B(150), B(200), B(300), B(600),
B(1200), B(1800), B(2400), B(4800), B(9600), B(19200), B(38400),
B(57600), B(115200), B(230400), B(460800), B(500000), B(576000),
B(921600), B(1000000), B(1152000), B(1500000), B(2000000),
#ifdef B2500000
/* non-SPARC architectures support these Bnnn constants */
B(2500000), B(3000000), B(3500000), B(4000000)
#else
/* SPARC architecture supports these Bnnn constants */
B(76800), B(153600), B(307200), B(614400)
#endif
};
#undef B
size_t i;
if (!baudrate)
die("Baudrate 0 not valid");
for (i = 0; i < sizeof(map)/sizeof(*map); i++)
if (map[i].baudrate == baudrate)
return map[i].cflag;
#ifdef BOTHER
return BOTHER;
#else
die("Baudrate %u not supported", baudrate);
#endif
}
static int
is_within_tolerance(unsigned int value, unsigned int reference,
unsigned int tolerance)
{
return 100 * value >= reference * (100 - tolerance) &&
100 * value <= reference * (100 + tolerance);
}
void change_baudrate(unsigned int baudrate)
{
struct termios2 opts = {};
tcflag_t cflag_speed = baudrate_to_cflag(baudrate);
xtcgetattr2(wtpfd, &opts);
opts.c_cflag &= ~CBAUD;
opts.c_cflag |= cflag_speed;
#ifdef IBSHIFT
opts.c_cflag &= ~(CBAUD << IBSHIFT);
opts.c_cflag |= B0 << IBSHIFT;
#endif
#ifdef BOTHER
opts.c_ispeed = opts.c_ospeed = baudrate;
#endif
xtcsetattr2(wtpfd, &opts);
xtcgetattr2(wtpfd, &opts);
#ifndef BOTHER
if ((opts.c_cflag & CBAUD) != cflag_speed)
die("Baudrate %u not supported", baudrate);
# ifdef IBSHIFT
if (((opts.c_cflag >> IBSHIFT) & CBAUD) != B0)
die("Baudrate %u not supported", baudrate);
# endif
#else
/* Check that set baudrate is in 3% tolerance */
if (!is_within_tolerance(opts.c_ospeed, baudrate, 3) ||
!is_within_tolerance(opts.c_ispeed, baudrate, 3))
die("Baudrate %u not supported", baudrate);
#endif
usleep(10000);
xtcflush(wtpfd, TCIFLUSH);
}
void try_change_baudrate(unsigned int baudrate)
{
u8 buf[6] = "baud";
int tbg_freq;
u32 div, m;
notice("Requesting baudrate change to %u baud\n", baudrate);
if (!isatty(wtpfd))
die("File descriptor is not tty and does not support baudrate change");
/*
* Wait 100ms to make sure we send the "baud" command only after BootROM
* verified the TIM and is in execution of the GPP program.
*/
usleep(100000);
xwrite(buf, 4);
if (!read_until(buf, 4, 256))
die("Did not receive \"baud\" command reply!");
xread(buf, 5);
tbg_freq = compute_tbg_freq(buf[0], buf[1],
((buf[3] & 1) << 8) | buf[2], buf[4]);
if (compute_best_uart_params(tbg_freq, baudrate, &div, &m))
die("Failed computing A3720 UART parameters for baudrate %i!",
baudrate);
*(u16 *)&buf[0] = htole16(div);
*(u32 *)&buf[2] = htole32(m);
xwrite(buf, 6);
usleep(300000);
change_baudrate(baudrate);
}
static void readresp(u8 cmd, u8 seq, u8 cid, resp_t *resp)
{
const u8 chk[3] = { cmd, seq, cid };
if (!read_until(chk, sizeof(chk), 256))
die("Failed cmd[%02x %02x %02x]", cmd, seq, cid);
memcpy(resp, chk, 3);
xread(((void *) resp) + 3, 2);
if (resp->status > 0x2)
throw_or_die(unk_resp_sts_msg, "Unknown response status code 0x%x%s",
resp->status, unk_resp_sts_msg ?: "");
xread(((void *) resp) + 5, 1);
if (resp->len > 0)
xread(((void *) resp) + 6, resp->len);
}
static u8 *_sendcmd_buf(u32 len)
{
static u32 allocated_len;
static u8 *buf;
if (!allocated_len) {
allocated_len = 4096;
buf = xmalloc(allocated_len);
}
if (len > allocated_len) {
buf = xrealloc(buf, len);
allocated_len = len;
}
return buf;
}
static void _sendcmd(u8 cmd, u8 seq, u8 cid, u8 flags, u32 len,
const void *data, resp_t *resp)
{
u8 *buf;
buf = _sendcmd_buf(8 + len);
buf[0] = cmd;
buf[1] = seq;
buf[2] = cid;
buf[3] = flags;
*(u32 *) &buf[4] = htole32(len);
if (len)
memcpy(buf + 8, data, len);
xwrite(buf, 8 + len);
if (resp)
readresp(cmd, seq, cid, resp);
}
static void checkresp(resp_t *resp)
{
if (resp->status == 0x2)
die("Sequence error on command %02x", resp->cmd);
else if (resp->status == 0x1)
throw_or_die(nack_msg, "NACK on command %02x%s", resp->cmd, nack_msg ?: "");
}
static void sendcmd(u8 cmd, u8 seq, u8 cid, u8 flags, u32 len, const void *data,
resp_t *resp)
{
int ismsg;
resp_t msgresp;
_sendcmd(cmd, seq, cid, flags, len, data, resp);
if (!resp)
return;
for (ismsg = resp->flags & 3; ismsg & 1; ismsg = msgresp.flags & 3) {
_sendcmd(0x2b, 0, cid, 0, 0, NULL, &msgresp);
if (ismsg & 2)
printf("Message from target: 0x%08x\n",
*(u32 *) msgresp.data);
else
printf("Message from target: \"%.*s\"\n",
(int) msgresp.len, msgresp.data);
}
checkresp(resp);
}
static void preamble(void)
{
static const u8 chk[4] = { 0x00, 0xd3, 0x02, 0x2b };
xwrite("\x00\xd3\x02\x2b", 4);
if (!read_until(chk, sizeof(chk), 256))
die("Wrong reply to preamble");
}
static void getversion(void)
{
static int printed;
resp_t resp;
sendcmd(0x20, 0, 0, 0, 0, NULL, &resp);
if (resp.len != 12)
die("GetVersion response length = %i != 12", resp.len);
if (!printed) {
u32 date;
date = le32toh(*(u32 *)&resp.data[4]);
printf("GetVersion response: version %c.%c.%c%c, "
"date %04x-%02x-%02x, CPU %s\n",
resp.data[3], resp.data[2], resp.data[1], resp.data[0],
date & 0xffff, (date >> 24) & 0xff, (date >> 16) & 0xff,
id2name(*(u32 *)&resp.data[8]));
printed = 1;
}
}
u32 selectimage(void)
{
resp_t resp;
preamble();
getversion();
if (last_image_sent == TIMH_ID)
xread_timed_out_msg = nack_msg = unk_resp_sts_msg = NULL;
sendcmd(0x26, 0, 0, 0, 0, NULL, &resp);
if (resp.len != 4)
die("SelectImage response length = %i != 4", resp.len);
return *(u32 *) resp.data;
}
void sendimage(image_t *img, int fast, const args_t *args)
{
static int seq = 1;
resp_t resp;
u8 buf[4];
u32 sent, tosend = 0;
double start;
int diff;
int istty = isatty(STDOUT_FILENO);
buf[0] = 0;
sendcmd(0x27, 0, 0, 0, 1, buf, &resp);
start = now();
sent = 0;
while (sent < img->size) {
int eta;
if ((fast && !sent) || !fast) {
*(u32 *) buf = htole32(img->size - sent);
sendcmd(0x2a, seq, 0, fast ? 4 : 0, 4, buf, &resp);
if (resp.len != 4)
die("DataHeader response length = %i != 4",
resp.len);
if (fast && !(resp.flags & 4))
die("Fast mode not supported");
tosend = le32toh(*(u32 *) resp.data);
}
if (img->size - sent < tosend)
tosend = img->size - sent;
if (fast)
xwrite(img->data + sent, tosend);
else
sendcmd(0x22, seq, 0, 0, tosend, img->data + sent,
&resp);
sent += tosend;
if (istty) {
eta = lrint((now() - start) * (img->size - sent) /
sent);
printf("\r%u%% sent, ETA %02i:%02i",
100 * sent / img->size, eta / 60, eta % 60);
fflush(stdout);
} else {
int pprev, p;
pprev = 100 * (sent - tosend) / img->size;
p = 100 * sent / img->size;
if (p != pprev) {
printf(".");
fflush(stdout);
}
}
}
if (istty) {
diff = lrint(now() - start);
printf("\r100%% sent in %02i:%02i \n", diff / 60, diff % 60);
} else {
printf("\n");
}
if (fast) {
readresp(0x22, seq, 0, &resp);
checkresp(&resp);
}
sendcmd(0x30, 0, 0, 0, 0, NULL, &resp);
last_image_sent = img->id;
if (img->id == TIMH_ID) {
sent_timh_was_trusted = tim_is_trusted(img);
if (args->deploy) {
nack_msg = xread_timed_out_msg =
"\n\nProbable reason:\n"
" Deploying failed becuase the board is already deployed (EFUSEs are already burned).";
} else if (args->otp_read) {
if (sent_timh_was_trusted) {
nack_msg = "\n\nProbable reason:\n"
" OTP reading may have failed because you specified a wrong board vendor\n"
" with the -R / --otp-read option.";
unk_resp_sts_msg = "\n\nProbable reason:\n"
" OTP reading may have failed because you specified a board vendor with\n"
" the -RVENDOR / --otp-read=VENDOR option, but the board is not trusted.\n"
" Try the option without specifying a vendor (just -R / --otp-read).";
} else {
xread_timed_out_msg = "\n\nProbable reason:\n"
" OTP reading may have failed because the board is trusted and you did\n"
" not specify board vendor (see the -R / --otp-read option in --help).";
}
} else {
if (sent_timh_was_trusted)
nack_msg = "\n\nProbable reason:\n"
" The image may have been rejected because it is cryptographically\n"
" signed with a different private key than the board requires, or the\n"
" signature was somehow corrupted.";
else
xread_timed_out_msg = "\n\nProbable reason:\n"
" The image may have been rejected because it is not a trusted image\n"
" and the board is trusted (EFUSEs are burned so that it will only\n"
" boot a cryptographically signed image).";
}
}
}
static void eccread(void *_buf, size_t size)
{
static const u8 ecc[128] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,
0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,
0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,