summaryrefslogtreecommitdiff
path: root/arch/arm/mach-stm32mp/cmd_stm32prog/stm32prog_serial.c
blob: 70940f01f3216a6718054206477c003eef4e5218 (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
// SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause
/*
 * Copyright (C) 2020, STMicroelectronics - All Rights Reserved
 */

#include <common.h>
#include <console.h>
#include <dfu.h>
#include <malloc.h>
#include <serial.h>
#include <watchdog.h>
#include <dm/lists.h>
#include <dm/device-internal.h>
#include <linux/delay.h>
#include "stm32prog.h"

/* - configuration part -----------------------------*/
#define USART_BL_VERSION	0x40	/* USART bootloader version V4.0*/
#define UBOOT_BL_VERSION	0x03	/* bootloader version V0.3*/
#define DEVICE_ID_BYTE1		0x05	/* MSB byte of device ID*/
#define DEVICE_ID_BYTE2		0x00	/* LSB byte of device ID*/
#define USART_RAM_BUFFER_SIZE	256	/* Size of USART_RAM_Buf buffer*/

/* - Commands -----------------------------*/
#define GET_CMD_COMMAND		0x00	/* Get CMD command*/
#define GET_VER_COMMAND		0x01	/* Get Version command*/
#define GET_ID_COMMAND		0x02	/* Get ID command*/
#define GET_PHASE_COMMAND	0x03	/* Get Phase command*/
#define RM_COMMAND		0x11	/* Read Memory command*/
#define READ_PART_COMMAND	0x12	/* Read Partition command*/
#define START_COMMAND		0x21	/* START command (Go)*/
#define DOWNLOAD_COMMAND	0x31	/* Download command*/
/* existing command for other STM32 but not used */
/* ERASE			0x43 */
/* EXTENDED_ERASE		0x44 */
/* WRITE_UNPROTECTED		0x73 */
/* READOUT_PROTECT		0x82 */
/* READOUT_UNPROTECT		0x92 */

/* - miscellaneous defines ----------------------------------------*/
#define INIT_BYTE		0x7F	/*Init Byte ID*/
#define ACK_BYTE		0x79	/*Acknowlede Byte ID*/
#define NACK_BYTE		0x1F	/*No Acknowlede Byte ID*/
#define ABORT_BYTE		0x5F	/*ABORT*/

struct udevice *down_serial_dev;

const u8 cmd_id[] = {
	GET_CMD_COMMAND,
	GET_VER_COMMAND,
	GET_ID_COMMAND,
	GET_PHASE_COMMAND,
	RM_COMMAND,
	READ_PART_COMMAND,
	START_COMMAND,
	DOWNLOAD_COMMAND
};

#define NB_CMD sizeof(cmd_id)

/* DFU support for serial *********************************************/
static struct dfu_entity *stm32prog_get_entity(struct stm32prog_data *data)
{
	int alt_id;

	if (!data->cur_part)
		if (data->phase == PHASE_FLASHLAYOUT)
			alt_id = 0;
		else
			return NULL;
	else
		alt_id = data->cur_part->alt_id;

	return dfu_get_entity(alt_id);
}

static int stm32prog_write(struct stm32prog_data *data, u8 *buffer,
			   u32 buffer_size)
{
	struct dfu_entity *dfu_entity;
	u8 ret = 0;

	dfu_entity = stm32prog_get_entity(data);
	if (!dfu_entity)
		return -ENODEV;

	ret = dfu_write(dfu_entity,
			buffer,
			buffer_size,
			data->dfu_seq);

	if (ret) {
		stm32prog_err("DFU write failed [%d] cnt: %d",
			      ret, data->dfu_seq);
	}
	data->dfu_seq++;
	/* handle rollover as in driver/dfu/dfu.c */
	data->dfu_seq &= 0xffff;
	if (buffer_size == 0)
		data->dfu_seq = 0; /* flush done */

	return ret;
}

static int stm32prog_read(struct stm32prog_data *data, u8 phase, u32 offset,
			  u8 *buffer, u32 buffer_size)
{
	struct dfu_entity *dfu_entity;
	struct stm32prog_part_t *part;
	u32 size;
	int ret, i;

	if (data->dfu_seq) {
		stm32prog_err("DFU write pending for phase %d, seq %d",
			      data->phase, data->dfu_seq);
		return -EINVAL;
	}
	if (phase == PHASE_FLASHLAYOUT || phase > PHASE_LAST_USER) {
		stm32prog_err("read failed : phase %d is invalid", phase);
		return -EINVAL;
	}
	if (data->read_phase <= PHASE_LAST_USER &&
	    phase != data->read_phase) {
		/* clear previous read session */
		dfu_entity = dfu_get_entity(data->read_phase - 1);
		if (dfu_entity)
			dfu_transaction_cleanup(dfu_entity);
	}

	dfu_entity = NULL;
	/* found partition for the expected phase */
	for (i = 0; i < data->part_nb; i++) {
		part = &data->part_array[i];
		if (part->id == phase)
			dfu_entity = dfu_get_entity(part->alt_id);
	}
	if (!dfu_entity) {
		stm32prog_err("read failed : phase %d is unknown", phase);
		return -ENODEV;
	}

	/* clear pending read before to force offset */
	if (dfu_entity->inited &&
	    (data->read_phase != phase || data->offset != offset))
		dfu_transaction_cleanup(dfu_entity);

	/* initiate before to force offset */
	if (!dfu_entity->inited) {
		ret = dfu_transaction_initiate(dfu_entity, true);
			if (ret < 0) {
				stm32prog_err("DFU read init failed [%d] phase = %d offset = 0x%08x",
					      ret, phase, offset);
			return ret;
		}
	}
	/* force new offset */
	if (dfu_entity->offset != offset)
		dfu_entity->offset = offset;
	data->offset = offset;
	data->read_phase = phase;
	pr_debug("\nSTM32 download read %s offset=0x%x\n",
		 dfu_entity->name, offset);
	ret = dfu_read(dfu_entity, buffer, buffer_size,
		       dfu_entity->i_blk_seq_num);
	if (ret < 0) {
		stm32prog_err("DFU read failed [%d] phase = %d offset = 0x%08x",
			      ret, phase, offset);
		return ret;
	}

	size = ret;

	if (size < buffer_size) {
		data->offset = 0;
		data->read_phase = PHASE_END;
		memset(buffer + size, 0, buffer_size - size);
	} else {
		data->offset += size;
	}

	return ret;
}

/* UART access ***************************************************/
int stm32prog_serial_init(struct stm32prog_data *data, int link_dev)
{
	struct udevice *dev = NULL;
	int node;
	char alias[10];
	const char *path;
	struct dm_serial_ops *ops;
	/* no parity, 8 bits, 1 stop */
	u32 serial_config = SERIAL_DEFAULT_CONFIG;

	down_serial_dev = NULL;

	sprintf(alias, "serial%d", link_dev);
	path = fdt_get_alias(gd->fdt_blob, alias);
	if (!path) {
		pr_err("%s alias not found", alias);
		return -ENODEV;
	}
	node = fdt_path_offset(gd->fdt_blob, path);
	if (!uclass_get_device_by_of_offset(UCLASS_SERIAL, node,
					    &dev)) {
		down_serial_dev = dev;
	} else if (node > 0 &&
		   !lists_bind_fdt(gd->dm_root, offset_to_ofnode(node),
				   &dev, false)) {
		if (!device_probe(dev))
			down_serial_dev = dev;
	}
	if (!down_serial_dev) {
		pr_err("%s = %s device not found", alias, path);
		return -ENODEV;
	}

	/* force silent console on uart only when used */
	if (gd->cur_serial_dev == down_serial_dev)
		gd->flags |= GD_FLG_DISABLE_CONSOLE | GD_FLG_SILENT;
	else
		gd->flags &= ~(GD_FLG_DISABLE_CONSOLE | GD_FLG_SILENT);

	ops = serial_get_ops(down_serial_dev);

	if (!ops) {
		pr_err("%s = %s missing ops", alias, path);
		return -ENODEV;
	}
	if (!ops->setconfig) {
		pr_err("%s = %s missing setconfig", alias, path);
		return -ENODEV;
	}

	clrsetbits_le32(&serial_config, SERIAL_PAR_MASK, SERIAL_PAR_EVEN);

	data->buffer = memalign(CONFIG_SYS_CACHELINE_SIZE,
				USART_RAM_BUFFER_SIZE);

	return ops->setconfig(down_serial_dev, serial_config);
}

static void stm32prog_serial_flush(void)
{
	struct dm_serial_ops *ops = serial_get_ops(down_serial_dev);
	int err;

	do {
		err = ops->getc(down_serial_dev);
	} while (err != -EAGAIN);
}

static int stm32prog_serial_getc_err(void)
{
	struct dm_serial_ops *ops = serial_get_ops(down_serial_dev);
	int err;

	do {
		err = ops->getc(down_serial_dev);
		if (err == -EAGAIN) {
			ctrlc();
			WATCHDOG_RESET();
		}
	} while ((err == -EAGAIN) && (!had_ctrlc()));

	return err;
}

static u8 stm32prog_serial_getc(void)
{
	int err;

	err = stm32prog_serial_getc_err();

	return err >= 0 ? err : 0;
}

static bool stm32prog_serial_get_buffer(u8 *buffer, u32 *count)
{
	struct dm_serial_ops *ops = serial_get_ops(down_serial_dev);
	int err;

	do {
		err = ops->getc(down_serial_dev);
		if (err >= 0) {
			*buffer++ = err;
			*count -= 1;
		} else if (err == -EAGAIN) {
			ctrlc();
			WATCHDOG_RESET();
		} else {
			break;
		}
	} while (*count && !had_ctrlc());

	return !!(err < 0);
}

static void stm32prog_serial_putc(u8 w_byte)
{
	struct dm_serial_ops *ops = serial_get_ops(down_serial_dev);
	int err;

	do {
		err = ops->putc(down_serial_dev, w_byte);
	} while (err == -EAGAIN);
}

/* Helper function ************************************************/

static u8 stm32prog_header(struct stm32prog_data *data)
{
	u8 ret;
	u8 boot = 0;
	struct dfu_entity *dfu_entity;
	u64 size = 0;

	dfu_entity = stm32prog_get_entity(data);
	if (!dfu_entity)
		return -ENODEV;

	printf("\nSTM32 download write %s\n", dfu_entity->name);

	/* force cleanup to avoid issue with previous read */
	dfu_transaction_cleanup(dfu_entity);

	ret = stm32prog_header_check(data->header_data,
				     &data->header);

	/* no header : max size is partition size */
	if (ret) {
		dfu_entity->get_medium_size(dfu_entity, &size);
		data->header.image_length = size;
	}

	/**** Flash the header if necessary for boot partition */
	if (data->phase < PHASE_FIRST_USER)
		boot = 1;

	/* write header if boot partition */
	if (boot) {
		if (ret) {
			stm32prog_err("invalid header (error %d)", ret);
		} else {
			ret = stm32prog_write(data,
					      (u8 *)data->header_data,
					      BL_HEADER_SIZE);
		}
	} else {
		if (ret)
			printf("  partition without checksum\n");
		ret = 0;
	}

	free(data->header_data);
	data->header_data = NULL;

	return ret;
}

static u8 stm32prog_start(struct stm32prog_data *data, u32 address)
{
	u8 ret = 0;
	struct dfu_entity *dfu_entity;

	if (address < 0x100) {
		if (address == PHASE_OTP)
			return stm32prog_otp_start(data);

		if (address == PHASE_PMIC)
			return stm32prog_pmic_start(data);

		if (address == PHASE_RESET || address == PHASE_END) {
			data->cur_part = NULL;
			data->dfu_seq = 0;
			data->phase = address;
			return 0;
		}
		if (address != data->phase) {
			stm32prog_err("invalid received phase id %d, current phase is %d",
				      (u8)address, (u8)data->phase);
			return -EINVAL;
		}
	}
	/* check the last loaded partition */
	if (address == DEFAULT_ADDRESS || address == data->phase) {
		switch (data->phase) {
		case PHASE_END:
		case PHASE_RESET:
		case PHASE_DO_RESET:
			data->cur_part = NULL;
			data->phase = PHASE_DO_RESET;
			return 0;
		}
		dfu_entity = stm32prog_get_entity(data);
		if (!dfu_entity)
			return -ENODEV;

		if (data->dfu_seq) {
			ret = dfu_flush(dfu_entity, NULL, 0, data->dfu_seq);
			data->dfu_seq = 0;
			if (ret) {
				stm32prog_err("DFU flush failed [%d]", ret);
				return ret;
			}
		}
		printf("\n  received length = 0x%x\n", data->cursor);
		if (data->header.present) {
			if (data->cursor !=
			    (data->header.image_length + BL_HEADER_SIZE)) {
				stm32prog_err("transmission interrupted (length=0x%x expected=0x%x)",
					      data->cursor,
					      data->header.image_length +
					      BL_HEADER_SIZE);
				return -EIO;
			}
			if (data->header.image_checksum != data->checksum) {
				stm32prog_err("invalid checksum received (0x%x expected 0x%x)",
					      data->checksum,
					      data->header.image_checksum);
				return -EIO;
			}
			printf("\n  checksum OK (0x%x)\n", data->checksum);
		}

		/* update DFU with received flashlayout */
		if (data->phase == PHASE_FLASHLAYOUT)
			stm32prog_dfu_init(data);
	} else {
		void (*entry)(void) = (void *)address;

		printf("## Starting application at 0x%x ...\n", address);
		(*entry)();
		printf("## Application terminated\n");
		ret = -ENOEXEC;
	}

	return ret;
}

/**
 * get_address() - Get address if it is valid
 *
 * @tmp_xor:		Current xor value to update
 * @return The address area
 */
static u32 get_address(u8 *tmp_xor)
{
	u32 address = 0x0;
	u8 data;

	data = stm32prog_serial_getc();
	*tmp_xor ^= data;
	address |= ((u32)data) << 24;

	data = stm32prog_serial_getc();
	address |= ((u32)data) << 16;
	*tmp_xor ^= data;

	data = stm32prog_serial_getc();
	address |= ((u32)data) << 8;
	*tmp_xor ^= data;

	data = stm32prog_serial_getc();
	address |= ((u32)data);
	*tmp_xor ^= data;

	return address;
}

static void stm32prog_serial_result(u8 result)
{
	/* always flush fifo before to send result */
	stm32prog_serial_flush();
	stm32prog_serial_putc(result);
}

/* Command -----------------------------------------------*/
/**
 * get_cmd_command() - Respond to Get command
 *
 * @data:		Current command context
 */
static void get_cmd_command(struct stm32prog_data *data)
{
	u32 counter = 0x0;

	stm32prog_serial_putc(NB_CMD);
	stm32prog_serial_putc(USART_BL_VERSION);

	for (counter = 0; counter < NB_CMD; counter++)
		stm32prog_serial_putc(cmd_id[counter]);

	stm32prog_serial_result(ACK_BYTE);
}

/**
 * get_version_command() - Respond to Get Version command
 *
 * @data:		Current command context
 */
static void get_version_command(struct stm32prog_data *data)
{
	stm32prog_serial_putc(UBOOT_BL_VERSION);
	stm32prog_serial_result(ACK_BYTE);
}

/**
 * get_id_command() - Respond to Get ID command
 *
 * @data:		Current command context
 */
static void get_id_command(struct stm32prog_data *data)
{
	/* Send Device IDCode */
	stm32prog_serial_putc(0x1);
	stm32prog_serial_putc(DEVICE_ID_BYTE1);
	stm32prog_serial_putc(DEVICE_ID_BYTE2);
	stm32prog_serial_result(ACK_BYTE);
}

/**
 * get_phase_command() - Respond to Get phase
 *
 * @data:		Current command context
 */
static void get_phase_command(struct stm32prog_data *data)
{
	char *err_msg = NULL;
	u8 i, length = 0;
	u32 destination = DEFAULT_ADDRESS; /* destination address */
	int phase = data->phase;

	if (phase == PHASE_RESET || phase == PHASE_DO_RESET) {
		err_msg = stm32prog_get_error(data);
		length = strlen(err_msg);
	}
	if (phase == PHASE_FLASHLAYOUT)
		destination = STM32_DDR_BASE;

	stm32prog_serial_putc(length + 5);           /* Total length */
	stm32prog_serial_putc(phase & 0xFF);         /* partition ID */
	stm32prog_serial_putc(destination);          /* byte 1 of address */
	stm32prog_serial_putc(destination >> 8);     /* byte 2 of address */
	stm32prog_serial_putc(destination >> 16);    /* byte 3 of address */
	stm32prog_serial_putc(destination >> 24);    /* byte 4 of address */

	stm32prog_serial_putc(length);               /* Information length */
	for (i = 0; i < length; i++)
		stm32prog_serial_putc(err_msg[i]);
	stm32prog_serial_result(ACK_BYTE);

	if (phase == PHASE_RESET)
		stm32prog_do_reset(data);
}

/**
 * read_memory_command() - Read data from memory
 *
 * @data:		Current command context
 */
static void read_memory_command(struct stm32prog_data *data)
{
	u32 address = 0x0;
	u8 rcv_data = 0x0, tmp_xor = 0x0;
	u32 counter = 0x0;

	/* Read memory address */
	address = get_address(&tmp_xor);

	/* If address memory is not received correctly */
	rcv_data = stm32prog_serial_getc();
	if (rcv_data != tmp_xor) {
		stm32prog_serial_result(NACK_BYTE);
		return;
	}

	stm32prog_serial_result(ACK_BYTE);

	/* Read the number of bytes to be received:
	 * Max NbrOfData = Data + 1 = 256
	 */
	rcv_data = stm32prog_serial_getc();
	tmp_xor = ~rcv_data;
	if (stm32prog_serial_getc() != tmp_xor) {
		stm32prog_serial_result(NACK_BYTE);
		return;
	}

	/* If checksum is correct send ACK */
	stm32prog_serial_result(ACK_BYTE);

	/* Send data to the host:
	 * Number of data to read = data + 1
	 */
	for (counter = (rcv_data + 1); counter != 0; counter--)
		stm32prog_serial_putc(*(u8 *)(address++));
}

/**
 * start_command() - Respond to start command
 *
 * Jump to user application in RAM or partition check
 *
 * @data:		Current command context
 */
static void start_command(struct stm32prog_data *data)
{
	u32 address = 0;
	u8 tmp_xor = 0x0;
	u8 ret, rcv_data;

	/* Read memory address */
	address = get_address(&tmp_xor);

	/* If address memory is not received correctly */
	rcv_data = stm32prog_serial_getc();
	if (rcv_data != tmp_xor) {
		stm32prog_serial_result(NACK_BYTE);
		return;
	}
	/* validate partition */
	ret = stm32prog_start(data,
			      address);

	if (ret)
		stm32prog_serial_result(ABORT_BYTE);
	else
		stm32prog_serial_result(ACK_BYTE);
}

/**
 * download_command() - Respond to download command
 *
 * Write data to not volatile memory, Flash
 *
 * @data:		Current command context
 */
static void download_command(struct stm32prog_data *data)
{
	u32 address = 0x0;
	u8 my_xor = 0x0;
	u8 rcv_xor;
	u32 counter = 0x0, codesize = 0x0;
	u8 *ramaddress = 0;
	u8 rcv_data = 0x0;
	struct image_header_s *image_header = &data->header;
	u32 cursor = data->cursor;
	long size = 0;
	u8 operation;
	u32 packet_number;
	u32 result = ACK_BYTE;
	u8 ret;
	unsigned int i;
	bool error;
	int rcv;

	address = get_address(&my_xor);

	/* If address memory is not received correctly */
	rcv_xor = stm32prog_serial_getc();
	if (rcv_xor != my_xor) {
		result = NACK_BYTE;
		goto end;
	}

	/* If address valid send ACK */
	stm32prog_serial_result(ACK_BYTE);

	/* get packet number and operation type */
	operation = (u8)((u32)address >> 24);
	packet_number = ((u32)(((u32)address << 8))) >> 8;

	switch (operation) {
	/* supported operation */
	case PHASE_FLASHLAYOUT:
	case PHASE_OTP:
	case PHASE_PMIC:
		break;
	default:
		result = NACK_BYTE;
		goto end;
	}
	/* check the packet number */
	if (packet_number == 0) {
		/* erase: re-initialize the image_header struct */
		data->packet_number = 0;
		if (data->header_data)
			memset(data->header_data, 0, BL_HEADER_SIZE);
		else
			data->header_data = calloc(1, BL_HEADER_SIZE);
		cursor = 0;
		data->cursor = 0;
		data->checksum = 0;
		/*idx = cursor;*/
	} else {
		data->packet_number++;
	}

	/* Check with the number of current packet if the device receive
	 * the true packet
	 */
	if (packet_number != data->packet_number) {
		data->packet_number--;
		result = NACK_BYTE;
		goto end;
	}

	/*-- Read number of bytes to be written and data -----------*/

	/* Read the number of bytes to be written:
	 * Max NbrOfData = data + 1 <= 256
	 */
	rcv_data = stm32prog_serial_getc();

	/* NbrOfData to write = data + 1 */
	codesize = rcv_data + 0x01;

	if (codesize > USART_RAM_BUFFER_SIZE) {
		result = NACK_BYTE;
		goto end;
	}

	/* Checksum Initialization */
	my_xor = rcv_data;

	/* UART receive data and send to Buffer */
	counter = codesize;
	error = stm32prog_serial_get_buffer(data->buffer, &counter);

	/* read checksum */
	if (!error) {
		rcv = stm32prog_serial_getc_err();
		error = !!(rcv < 0);
		rcv_xor = rcv;
	}

	if (error) {
		printf("transmission error on packet %d, byte %d\n",
		       packet_number, codesize - counter);
		/* waiting end of packet before flush & NACK */
		mdelay(30);
		data->packet_number--;
		result = NACK_BYTE;
		goto end;
	}

	/* Compute Checksum */
	ramaddress = data->buffer;
	for (counter = codesize; counter != 0; counter--)
		my_xor ^= *(ramaddress++);

	/* If Checksum is incorrect */
	if (rcv_xor != my_xor) {
		printf("checksum error on packet %d\n",
		       packet_number);
		/* wait to be sure that all data are received
		 * in the FIFO before flush
		 */
		mdelay(30);
		data->packet_number--;
		result = NACK_BYTE;
		goto end;
	}

	/* Update current position in buffer */
	data->cursor += codesize;

	if (operation == PHASE_OTP) {
		size = data->cursor - cursor;
		/* no header for OTP */
		if (stm32prog_otp_write(data, cursor,
					data->buffer, &size))
			result = ABORT_BYTE;
		goto end;
	}

	if (operation == PHASE_PMIC) {
		size = data->cursor - cursor;
		/* no header for PMIC */
		if (stm32prog_pmic_write(data, cursor,
					 data->buffer, &size))
			result = ABORT_BYTE;
		goto end;
	}

	if (cursor < BL_HEADER_SIZE) {
		/* size = portion of header in this chunck */
		if (data->cursor >= BL_HEADER_SIZE)
			size = BL_HEADER_SIZE - cursor;
		else
			size = data->cursor - cursor;
		memcpy((void *)((u32)(data->header_data) + cursor),
		       data->buffer, size);
		cursor += size;

		if (cursor == BL_HEADER_SIZE) {
			/* Check and Write the header */
			if (stm32prog_header(data)) {
				result = ABORT_BYTE;
				goto end;
			}
		} else {
			goto end;
		}
	}

	if (image_header->present) {
		if (data->cursor <= BL_HEADER_SIZE)
			goto end;
		/* compute checksum on payload */
		for (i = (unsigned long)size; i < codesize; i++)
			data->checksum += data->buffer[i];

		if (data->cursor >
		    image_header->image_length + BL_HEADER_SIZE) {
			pr_err("expected size exceeded\n");
			result = ABORT_BYTE;
			goto end;
		}

		/* write data (payload) */
		ret = stm32prog_write(data,
				      &data->buffer[size],
				      codesize - size);
	} else {
		/* write all */
		ret = stm32prog_write(data,
				      data->buffer,
				      codesize);
	}
	if (ret)
		result = ABORT_BYTE;

end:
	stm32prog_serial_result(result);
}

/**
 * read_partition() - Respond to read command
 *
 * Read data from not volatile memory, Flash
 *
 * @data:		Current command context
 */
static void read_partition_command(struct stm32prog_data *data)
{
	u32 i, part_id, codesize, offset = 0, rcv_data;
	long size;
	u8 tmp_xor;
	int res;
	u8 buffer[256];

	part_id = stm32prog_serial_getc();
	tmp_xor = part_id;

	offset = get_address(&tmp_xor);

	rcv_data = stm32prog_serial_getc();
	if (rcv_data != tmp_xor) {
		pr_debug("1st checksum received = %x, computed %x\n",
			 rcv_data, tmp_xor);
		goto error;
	}
	stm32prog_serial_putc(ACK_BYTE);

	/* NbrOfData to read = data + 1 */
	rcv_data = stm32prog_serial_getc();
	codesize = rcv_data + 0x01;
	tmp_xor = rcv_data;

	rcv_data = stm32prog_serial_getc();
	if ((rcv_data ^ tmp_xor) != 0xFF) {
		pr_debug("2nd checksum received = %x, computed %x\n",
			 rcv_data, tmp_xor);
		goto error;
	}

	pr_debug("%s : %x\n", __func__, part_id);
	rcv_data = 0;
	switch (part_id) {
	case PHASE_OTP:
		size = codesize;
		if (!stm32prog_otp_read(data, offset, buffer, &size))
			rcv_data = size;
		break;
	case PHASE_PMIC:
		size = codesize;
		if (!stm32prog_pmic_read(data, offset, buffer, &size))
			rcv_data = size;
		break;
	default:
		res = stm32prog_read(data, part_id, offset,
				     buffer, codesize);
		if (res > 0)
			rcv_data = res;
		break;
	}
	if (rcv_data > 0) {
		stm32prog_serial_putc(ACK_BYTE);
		/*----------- Send data to the host -----------*/
		for (i = 0; i < rcv_data; i++)
			stm32prog_serial_putc(buffer[i]);
		/*----------- Send filler to the host -----------*/
		for (; i < codesize; i++)
			stm32prog_serial_putc(0x0);
		return;
	}
	stm32prog_serial_result(ABORT_BYTE);
	return;

error:
	stm32prog_serial_result(NACK_BYTE);
}

/* MAIN function = SERIAL LOOP ***********************************************/

/**
 * stm32prog_serial_loop() - USART bootloader Loop routine
 *
 * @data:		Current command context
 * @return true if reset is needed after loop
 */
bool stm32prog_serial_loop(struct stm32prog_data *data)
{
	u32 counter = 0x0;
	u8 command = 0x0;
	u8 found;
	int phase = data->phase;

	/* element of cmd_func need to aligned with cmd_id[]*/
	void (*cmd_func[NB_CMD])(struct stm32prog_data *) = {
		/* GET_CMD_COMMAND */	get_cmd_command,
		/* GET_VER_COMMAND */	get_version_command,
		/* GET_ID_COMMAND */	get_id_command,
		/* GET_PHASE_COMMAND */	get_phase_command,
		/* RM_COMMAND */	read_memory_command,
		/* READ_PART_COMMAND */	read_partition_command,
		/* START_COMMAND */	start_command,
		/* DOWNLOAD_COMMAND */	download_command
	};

	/* flush and NACK pending command received during u-boot init
	 * request command reemit
	 */
	stm32prog_serial_result(NACK_BYTE);

	clear_ctrlc(); /* forget any previous Control C */
	while (!had_ctrlc()) {
		phase = data->phase;

		if (phase == PHASE_DO_RESET)
			return true;

		/* Get the user command: read first byte */
		command = stm32prog_serial_getc();

		if (command == INIT_BYTE) {
			puts("\nConnected\n");
			stm32prog_serial_result(ACK_BYTE);
			continue;
		}

		found = 0;
		for (counter = 0; counter < NB_CMD; counter++)
			if (cmd_id[counter] == command) {
				found = 1;
				break;
			}
		if (found)
			if ((command ^ stm32prog_serial_getc()) != 0xFF)
				found = 0;
		if (!found) {
			/* wait to be sure that all data are received
			 * in the FIFO before flush (CMD and XOR)
			 */
			mdelay(3);
			stm32prog_serial_result(NACK_BYTE);
		} else {
			stm32prog_serial_result(ACK_BYTE);
			cmd_func[counter](data);
		}
		WATCHDOG_RESET();
	}

	/* clean device */
	if (gd->cur_serial_dev == down_serial_dev) {
		/* restore console on uart */
		gd->flags &= ~(GD_FLG_DISABLE_CONSOLE | GD_FLG_SILENT);
	}
	down_serial_dev = NULL;

	return false; /* no reset after ctrlc */
}