fel.c 58.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
 * Copyright (C) 2012  Henrik Nordstrom <henrik@henriknordstrom.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

18
19
20
21
#include "common.h"
#include "portable_endian.h"
#include "progress.h"

22
23
#include <libusb.h>
#include <stdint.h>
24
#include <stdbool.h>
25
26
27
28
29
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
30
#include <stdarg.h>
31
#include <errno.h>
32
#include <unistd.h>
33
#include <sys/stat.h>
34

35
36
37
static const uint16_t AW_USB_VENDOR_ID  = 0x1F3A;
static const uint16_t AW_USB_PRODUCT_ID = 0xEFE8;

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* a helper function to report libusb errors */
void usb_error(int rc, const char *caption, int exitcode)
{
	if (caption)
		fprintf(stderr, "%s ", caption);

#if defined(LIBUSBX_API_VERSION) && (LIBUSBX_API_VERSION >= 0x01000102)
	fprintf(stderr, "ERROR %d: %s\n", rc, libusb_strerror(rc));
#else
	/* assume that libusb_strerror() is missing in the libusb API */
	fprintf(stderr, "ERROR %d\n", rc);
#endif

	if (exitcode != 0)
		exit(exitcode);
}

55
56
57
58
59
60
61
62
63
struct  aw_usb_request {
	char signature[8];
	uint32_t length;
	uint32_t unknown1;	/* 0x0c000000 */
	uint16_t request;
	uint32_t length2;	/* Same as length */
	char	pad[10];
}  __attribute__((packed));

64
65
66
67
68
69
70
71
72
73
74
struct aw_fel_version {
	char signature[8];
	uint32_t soc_id;	/* 0x00162300 */
	uint32_t unknown_0a;	/* 1 */
	uint16_t protocol;	/* 1 */
	uint8_t  unknown_12;	/* 0x44 */
	uint8_t  unknown_13;	/* 0x08 */
	uint32_t scratchpad;	/* 0x7e00 */
	uint32_t pad[2];	/* unused */
} __attribute__((packed));

75
76
77
static const int AW_USB_READ = 0x11;
static const int AW_USB_WRITE = 0x12;

78
79
static int AW_USB_FEL_BULK_EP_OUT;
static int AW_USB_FEL_BULK_EP_IN;
80
81
static int timeout = 10000; /* 10 seconds */

82
static bool verbose = false; /* If set, makes the 'fel' tool more talkative */
83
84
static uint32_t uboot_entry = 0; /* entry point (address) of U-Boot */
static uint32_t uboot_size  = 0; /* size of U-Boot binary */
85
86
87
88
89
90
91
92
93
94

static void pr_info(const char *fmt, ...)
{
	va_list arglist;
	if (verbose) {
		va_start(arglist, fmt);
		vprintf(fmt, arglist);
		va_end(arglist);
	}
}
95

96
97
98
99
100
101
102
103
104
105
/*
 * AW_USB_MAX_BULK_SEND and the timeout constant are related.
 * Both need to be selected in a way that transferring the maximum chunk size
 * with (SoC-specific) slow transfer speed won't time out.
 *
 * The 512 KiB here are chosen based on the assumption that we want a 10 seconds
 * timeout, and "slow" transfers take place at approx. 64 KiB/sec - so we can
 * expect the maximum chunk being transmitted within 8 seconds or less.
 */
static const int AW_USB_MAX_BULK_SEND = 512 * 1024; /* 512 KiB per bulk request */
106

107
108
void usb_bulk_send(libusb_device_handle *usb, int ep, const void *data,
		   size_t length, bool progress)
109
{
110
111
112
113
	/*
	 * With no progress notifications, we'll use the maximum chunk size.
	 * Otherwise, it's useful to lower the size (have more chunks) to get
	 * more frequent status updates. 128 KiB per request seem suitable.
114
	 * (Worst case of "slow" transfers -> one update every two seconds.)
115
116
	 */
	size_t max_chunk = progress ? 128 * 1024 : AW_USB_MAX_BULK_SEND;
117
118

	size_t chunk;
119
120
	int rc, sent;
	while (length > 0) {
121
122
		chunk = length < max_chunk ? length : max_chunk;
		rc = libusb_bulk_transfer(usb, ep, (void *)data, chunk, &sent, timeout);
123
124
		if (rc != 0)
			usb_error(rc, "usb_bulk_send()", 2);
125
126
		length -= sent;
		data += sent;
127
128

		if (progress)
Bernhard Nortmann's avatar
Bernhard Nortmann committed
129
			progress_update(sent); /* notification after each chunk */
130
131
132
133
134
135
136
	}
}

void usb_bulk_recv(libusb_device_handle *usb, int ep, void *data, int length)
{
	int rc, recv;
	while (length > 0) {
137
		rc = libusb_bulk_transfer(usb, ep, data, length, &recv, timeout);
138
139
		if (rc != 0)
			usb_error(rc, "usb_bulk_recv()", 2);
140
141
142
143
144
		length -= recv;
		data += recv;
	}
}

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
/* Constants taken from ${U-BOOT}/include/image.h */
#define IH_MAGIC	0x27051956	/* Image Magic Number	*/
#define IH_ARCH_ARM		2	/* ARM			*/
#define IH_TYPE_INVALID		0	/* Invalid Image	*/
#define IH_TYPE_FIRMWARE	5	/* Firmware Image	*/
#define IH_TYPE_SCRIPT		6	/* Script file		*/
#define IH_NMLEN		32	/* Image Name Length	*/

/* Additional error codes, newly introduced for get_image_type() */
#define IH_TYPE_ARCH_MISMATCH	-1

#define HEADER_NAME_OFFSET	32	/* offset of name field	*/
#define HEADER_SIZE		(HEADER_NAME_OFFSET + IH_NMLEN)

/*
 * Utility function to determine the image type from a mkimage-compatible
 * header at given buffer (address).
 *
 * For invalid headers (insufficient size or 'magic' mismatch) the function
 * will return IH_TYPE_INVALID. Negative return values might indicate
 * special error conditions, e.g. IH_TYPE_ARCH_MISMATCH signals that the
 * image doesn't match the expected (ARM) architecture.
 * Otherwise the function will return the "ih_type" field for valid headers.
 */
int get_image_type(const uint8_t *buf, size_t len)
{
	uint32_t *buf32 = (uint32_t *)buf;

	if (len <= HEADER_SIZE) /* insufficient length/size */
		return IH_TYPE_INVALID;
	if (be32toh(buf32[0]) != IH_MAGIC) /* signature mismatch */
		return IH_TYPE_INVALID;
	/* For sunxi, we always expect ARM architecture here */
	if (buf[29] != IH_ARCH_ARM)
		return IH_TYPE_ARCH_MISMATCH;

	/* assume a valid header, and return ih_type */
	return buf[30];
}

185
186
void aw_send_usb_request(libusb_device_handle *usb, int type, int length)
{
187
188
189
190
191
192
193
	struct aw_usb_request req = {
		.signature = "AWUC",
		.request = htole16(type),
		.length = htole32(length),
		.unknown1 = htole32(0x0c000000)
	};
	req.length2 = req.length;
194
	usb_bulk_send(usb, AW_USB_FEL_BULK_EP_OUT, &req, sizeof(req), false);
195
196
197
198
199
200
201
202
203
}

void aw_read_usb_response(libusb_device_handle *usb)
{
	char buf[13];
	usb_bulk_recv(usb, AW_USB_FEL_BULK_EP_IN, &buf, sizeof(buf));
	assert(strcmp(buf, "AWUS") == 0);
}

204
205
void aw_usb_write(libusb_device_handle *usb, const void *data, size_t len,
		  bool progress)
206
207
{
	aw_send_usb_request(usb, AW_USB_WRITE, len);
208
	usb_bulk_send(usb, AW_USB_FEL_BULK_EP_OUT, data, len, progress);
209
210
211
212
213
214
	aw_read_usb_response(usb);
}

void aw_usb_read(libusb_device_handle *usb, const void *data, size_t len)
{
	aw_send_usb_request(usb, AW_USB_READ, len);
215
	usb_bulk_send(usb, AW_USB_FEL_BULK_EP_IN, data, len, false);
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
	aw_read_usb_response(usb);
}

struct aw_fel_request {
	uint32_t request;
	uint32_t address;
	uint32_t length;
	uint32_t pad;
};

static const int AW_FEL_VERSION = 0x001;
static const int AW_FEL_1_WRITE = 0x101;
static const int AW_FEL_1_EXEC  = 0x102;
static const int AW_FEL_1_READ  = 0x103;

void aw_send_fel_request(libusb_device_handle *usb, int type, uint32_t addr, uint32_t length)
{
233
234
235
236
237
	struct aw_fel_request req = {
		.request = htole32(type),
		.address = htole32(addr),
		.length = htole32(length)
	};
238
	aw_usb_write(usb, &req, sizeof(req), false);
239
240
241
242
243
244
245
246
}

void aw_read_fel_status(libusb_device_handle *usb)
{
	char buf[8];
	aw_usb_read(usb, &buf, sizeof(buf));
}

247
void aw_fel_get_version(libusb_device_handle *usb, struct aw_fel_version *buf)
248
249
{
	aw_send_fel_request(usb, AW_FEL_VERSION, 0, 0);
250
	aw_usb_read(usb, buf, sizeof(*buf));
251
252
	aw_read_fel_status(usb);

253
254
255
256
257
258
259
260
261
262
263
264
	buf->soc_id = (le32toh(buf->soc_id) >> 8) & 0xFFFF;
	buf->unknown_0a = le32toh(buf->unknown_0a);
	buf->protocol = le32toh(buf->protocol);
	buf->scratchpad = le16toh(buf->scratchpad);
	buf->pad[0] = le32toh(buf->pad[0]);
	buf->pad[1] = le32toh(buf->pad[1]);
}

void aw_fel_print_version(libusb_device_handle *usb)
{
	struct aw_fel_version buf;
	aw_fel_get_version(usb, &buf);
265

Henrik Nordstrom's avatar
Henrik Nordstrom committed
266
	const char *soc_name="unknown";
267
	switch (buf.soc_id) {
Bernhard Nortmann's avatar
Bernhard Nortmann committed
268
269
270
271
272
	case 0x1623: soc_name="A10"; break;
	case 0x1625: soc_name="A13"; break;
	case 0x1633: soc_name="A31"; break;
	case 0x1651: soc_name="A20"; break;
	case 0x1650: soc_name="A23"; break;
273
	case 0x1689: soc_name="A64"; break;
Bernhard Nortmann's avatar
Bernhard Nortmann committed
274
275
276
277
	case 0x1639: soc_name="A80"; break;
	case 0x1667: soc_name="A33"; break;
	case 0x1673: soc_name="A83T"; break;
	case 0x1680: soc_name="H3"; break;
278
	case 0x1718: soc_name="H5"; break;
Henrik Nordstrom's avatar
Henrik Nordstrom committed
279
280
	}

281
282
283
284
	printf("%.8s soc=%08x(%s) %08x ver=%04x %02x %02x scratchpad=%08x %08x %08x\n",
		buf.signature, buf.soc_id, soc_name, buf.unknown_0a,
		buf.protocol, buf.unknown_12, buf.unknown_13,
		buf.scratchpad, buf.pad[0], buf.pad[1]);
285
286
287
288
289
290
291
292
293
294
295
296
}

void aw_fel_read(libusb_device_handle *usb, uint32_t offset, void *buf, size_t len)
{
	aw_send_fel_request(usb, AW_FEL_1_READ, offset, len);
	aw_usb_read(usb, buf, len);
	aw_read_fel_status(usb);
}

void aw_fel_write(libusb_device_handle *usb, void *buf, uint32_t offset, size_t len)
{
	aw_send_fel_request(usb, AW_FEL_1_WRITE, offset, len);
297
	aw_usb_write(usb, buf, len, false);
298
299
300
301
302
303
304
305
306
	aw_read_fel_status(usb);
}

void aw_fel_execute(libusb_device_handle *usb, uint32_t offset)
{
	aw_send_fel_request(usb, AW_FEL_1_EXEC, offset, 0);
	aw_read_fel_status(usb);
}

307
308
309
310
311
312
313
314
/*
 * This function is a higher-level wrapper for the FEL write functionality.
 * Unlike aw_fel_write() above - which is reserved for internal use - this
 * routine is meant to be called from "user" code, and supports (= allows)
 * progress callbacks.
 * The return value represents elapsed time in seconds (needed for execution).
 */
double aw_write_buffer(libusb_device_handle *usb, void *buf, uint32_t offset,
315
		       size_t len, bool progress)
316
317
318
319
320
321
322
{
	/* safeguard against overwriting an already loaded U-Boot binary */
	if (uboot_size > 0 && offset <= uboot_entry + uboot_size
			   && offset + len >= uboot_entry)
	{
		fprintf(stderr, "ERROR: Attempt to overwrite U-Boot! "
			"Request 0x%08X-0x%08X overlaps 0x%08X-0x%08X.\n",
323
			offset, (uint32_t)(offset + len),
324
325
326
327
328
			uboot_entry, uboot_entry + uboot_size);
		exit(1);
	}
	double start = gettime();
	aw_send_fel_request(usb, AW_FEL_1_WRITE, offset, len);
329
	aw_usb_write(usb, buf, len, progress);
330
331
332
333
	aw_read_fel_status(usb);
	return gettime() - start;
}

334
335
336
337
338
339
void hexdump(void *data, uint32_t offset, size_t size)
{
	size_t j;
	unsigned char *buf = data;
	for (j = 0; j < size; j+=16) {
		size_t i;
340
		printf("%08zx: ", offset + j);
341
		for (i = 0; i < 16; i++) {
342
			if (j + i < size)
343
				printf("%02x ", buf[j+i]);
344
			else
345
346
				printf("__ ");
		}
347
		putchar(' ');
348
		for (i = 0; i < 16; i++) {
349
350
351
352
			if (j + i >= size)
				putchar('.');
			else
				putchar(isprint(buf[j+i]) ? buf[j+i] : '.');
353
		}
354
		putchar('\n');
355
356
	}
}
357

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
unsigned int file_size(const char *filename)
{
	struct stat st;
	if (stat(filename, &st) != 0) {
		fprintf(stderr, "stat() error on file \"%s\": %s\n", filename,
			strerror(errno));
		exit(1);
	}
	if (!S_ISREG(st.st_mode)) {
		fprintf(stderr, "error: \"%s\" is not a regular file\n", filename);
		exit(1);
	}
	return st.st_size;
}

373
374
375
376
int save_file(const char *name, void *data, size_t size)
{
	FILE *out = fopen(name, "wb");
	int rc;
377
	if (!out) {
378
		perror("Failed to open output file");
379
380
		exit(1);
	}
381
382
383
384
385
	rc = fwrite(data, size, 1, out);
	fclose(out);
	return rc;
}

386
387
388
389
390
391
392
393
394
395
void *load_file(const char *name, size_t *size)
{
	size_t bufsize = 8192;
	size_t offset = 0;
	char *buf = malloc(bufsize);
	FILE *in;
	if (strcmp(name, "-") == 0)
		in = stdin;
	else
		in = fopen(name, "rb");
396
	if (!in) {
397
		perror("Failed to open input file");
398
399
		exit(1);
	}
400
	
Bernhard Nortmann's avatar
Bernhard Nortmann committed
401
	while (true) {
402
403
		ssize_t len = bufsize - offset;
		ssize_t n = fread(buf+offset, 1, len, in);
404
		offset += n;
405
		if (n < len)
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
			break;
		bufsize <<= 1;
		buf = realloc(buf, bufsize);
	}
	if (size) 
		*size = offset;
	if (in != stdin)
		fclose(in);
	return buf;
}

void aw_fel_hexdump(libusb_device_handle *usb, uint32_t offset, size_t size)
{
	unsigned char buf[size];
	aw_fel_read(usb, offset, buf, size);
	hexdump(buf, offset, size);
}

void aw_fel_dump(libusb_device_handle *usb, uint32_t offset, size_t size)
{
	unsigned char buf[size];
	aw_fel_read(usb, offset, buf, size);
	fwrite(buf, size, 1, stdout);
}
Henrik Nordstrom's avatar
Henrik Nordstrom committed
430
void aw_fel_fill(libusb_device_handle *usb, uint32_t offset, size_t size, unsigned char value)
431
432
{
	unsigned char buf[size];
Henrik Nordstrom's avatar
Henrik Nordstrom committed
433
	memset(buf, value, size);
434
	aw_write_buffer(usb, buf, offset, size, false);
435
436
}

437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
 * The 'sram_swap_buffers' structure is used to describe information about
 * two buffers in SRAM, the content of which needs to be exchanged before
 * calling the U-Boot SPL code and then exchanged again before returning
 * control back to the FEL code from the BROM.
 */

typedef struct {
	uint32_t buf1; /* BROM buffer */
	uint32_t buf2; /* backup storage location */
	uint32_t size; /* buffer size */
} sram_swap_buffers;

/*
 * Each SoC variant may have its own list of memory buffers to be exchanged
 * and the information about the placement of the thunk code, which handles
 * the transition of execution from the BROM FEL code to the U-Boot SPL and
 * back.
 *
 * Note: the entries in the 'swap_buffers' tables need to be sorted by 'buf1'
 * addresses. And the 'buf1' addresses are the BROM data buffers, while 'buf2'
 * addresses are the intended backup locations.
459
460
461
462
463
464
465
466
467
468
469
470
 *
 * Also for performance reasons, we optionally want to have MMU enabled with
 * optimal section attributes configured (the code from the BROM should use
 * I-cache, writing data to the DRAM area should use write combining). The
 * reason is that the BROM FEL protocol implementation moves data using the
 * CPU somewhere on the performance critical path when transferring data over
 * USB. The older SoC variants (A10/A13/A20/A31/A23) already have MMU enabled
 * and we only need to adjust section attributes. The BROM in newer SoC variants
 * (A33/A83T/H3) doesn't enable MMU anymore, so we need to find some 16K of
 * spare space in SRAM to place the translation table there and specify it as
 * the 'mmu_tt_addr' field in the 'soc_sram_info' structure. The 'mmu_tt_addr'
 * address must be 16K aligned.
471
472
 */
typedef struct {
473
	uint32_t           soc_id;       /* ID of the SoC */
474
	uint32_t           spl_addr;     /* SPL load address */
475
476
477
	uint32_t           scratch_addr; /* A safe place to upload & run code */
	uint32_t           thunk_addr;   /* Address of the thunk code */
	uint32_t           thunk_size;   /* Maximal size of the thunk code */
478
	bool               needs_l2en;   /* Set the L2EN bit */
479
	uint32_t           mmu_tt_addr;  /* MMU translation table address */
480
	uint32_t           sid_addr;     /* base address for SID_KEY[0-3] registers */
481
	uint32_t           rvbar_reg;    /* MMIO address of RVBARADDR0_L register */
482
483
484
485
486
487
488
489
	sram_swap_buffers *swap_buffers;
} soc_sram_info;

/*
 * The FEL code from BROM in A10/A13/A20 sets up two stacks for itself. One
 * at 0x2000 (and growing down) for the IRQ handler. And another one at 0x7000
 * (and also growing down) for the regular code. In order to use the whole
 * 32 KiB in the A1/A2 sections of SRAM, we need to temporarily move these
490
491
492
 * stacks elsewhere. And the addresses 0x7D00-0x7FFF contain something
 * importantant too (overwriting them kills FEL). On A10/A13/A20 we can use
 * the SRAM sections A3/A4 (0x8000-0xBFFF) for this purpose.
493
494
 */
sram_swap_buffers a10_a13_a20_sram_swap_buffers[] = {
495
496
497
498
499
500
	/* 0x1C00-0x1FFF (IRQ stack) */
	{ .buf1 = 0x01C00, .buf2 = 0xA400, .size = 0x0400 },
	/* 0x5C00-0x6FFF (Stack) */
	{ .buf1 = 0x05C00, .buf2 = 0xA800, .size = 0x1400 },
	/* 0x7C00-0x7FFF (Something important) */
	{ .buf1 = 0x07C00, .buf2 = 0xBC00, .size = 0x0400 },
501
	{ .size = 0 }  /* End of the table */
502
503
};

504
505
506
507
508
509
510
511
512
513
514
515
516
/*
 * A31 is very similar to A10/A13/A20, except that it has no SRAM at 0x8000.
 * So we use the SRAM section B at 0x20000-0x2FFFF instead. In the FEL mode,
 * the MMU translation table is allocated by the BROM at 0x20000. But we can
 * also safely use it as the backup storage because the MMU is temporarily
 * disabled during the time of the SPL execution.
 */
sram_swap_buffers a31_sram_swap_buffers[] = {
	{ .buf1 = 0x01800, .buf2 = 0x20000, .size = 0x800 },
	{ .buf1 = 0x05C00, .buf2 = 0x20800, .size = 0x8000 - 0x5C00 },
	{ .size = 0 }  /* End of the table */
};

517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*
 * A64 has 32KiB of SRAM A at 0x10000 and a large SRAM C at 0x18000. SRAM A
 * and SRAM C reside in the address space back-to-back without any gaps, thus
 * representing a singe large contiguous area. Everything is the same as on
 * A10/A13/A20, but just shifted by 0x10000.
 */
sram_swap_buffers a64_sram_swap_buffers[] = {
	/* 0x11C00-0x11FFF (IRQ stack) */
	{ .buf1 = 0x11C00, .buf2 = 0x1A400, .size = 0x0400 },
	/* 0x15C00-0x16FFF (Stack) */
	{ .buf1 = 0x15C00, .buf2 = 0x1A800, .size = 0x1400 },
	/* 0x17C00-0x17FFF (Something important) */
	{ .buf1 = 0x17C00, .buf2 = 0x1BC00, .size = 0x0400 },
	{ .size = 0 }  /* End of the table */
};

533
/*
534
535
536
 * Use the SRAM section at 0x44000 as the backup storage. This is the memory,
 * which is normally shared with the OpenRISC core (should we do an extra check
 * to ensure that this core is powered off and can't interfere?).
537
 */
538
sram_swap_buffers ar100_abusing_sram_swap_buffers[] = {
539
540
	{ .buf1 = 0x01800, .buf2 = 0x44000, .size = 0x800 },
	{ .buf1 = 0x05C00, .buf2 = 0x44800, .size = 0x8000 - 0x5C00 },
541
	{ .size = 0 }  /* End of the table */
542
543
};

544
545
546
547
548
549
550
/*
 * A80 has 40KiB SRAM A1 at 0x10000 where the SPL has to be loaded to. The
 * secure SRAM B at 0x20000 is used as backup area for FEL stacks and data.
 */
sram_swap_buffers a80_sram_swap_buffers[] = {
	{ .buf1 = 0x11800, .buf2 = 0x20000, .size = 0x800 },
	{ .buf1 = 0x15400, .buf2 = 0x20800, .size = 0x18000 - 0x15400 },
551
	{ .size = 0 }  /* End of the table */
552
553
};

554
555
556
soc_sram_info soc_sram_info_table[] = {
	{
		.soc_id       = 0x1623, /* Allwinner A10 */
557
		.scratch_addr = 0x1000,
558
		.thunk_addr   = 0xA200, .thunk_size = 0x200,
559
		.swap_buffers = a10_a13_a20_sram_swap_buffers,
560
		.needs_l2en   = true,
561
		.sid_addr     = 0x01C23800,
562
563
564
	},
	{
		.soc_id       = 0x1625, /* Allwinner A13 */
565
		.scratch_addr = 0x1000,
566
		.thunk_addr   = 0xA200, .thunk_size = 0x200,
567
		.swap_buffers = a10_a13_a20_sram_swap_buffers,
568
		.needs_l2en   = true,
569
		.sid_addr     = 0x01C23800,
570
571
572
	},
	{
		.soc_id       = 0x1651, /* Allwinner A20 */
573
		.scratch_addr = 0x1000,
574
		.thunk_addr   = 0xA200, .thunk_size = 0x200,
575
		.swap_buffers = a10_a13_a20_sram_swap_buffers,
576
		.sid_addr     = 0x01C23800,
577
	},
Hans de Goede's avatar
Hans de Goede committed
578
579
	{
		.soc_id       = 0x1650, /* Allwinner A23 */
580
		.scratch_addr = 0x1000,
Hans de Goede's avatar
Hans de Goede committed
581
		.thunk_addr   = 0x46E00, .thunk_size = 0x200,
582
		.swap_buffers = ar100_abusing_sram_swap_buffers,
583
		.sid_addr     = 0x01C23800,
Hans de Goede's avatar
Hans de Goede committed
584
	},
585
586
	{
		.soc_id       = 0x1633, /* Allwinner A31 */
587
		.scratch_addr = 0x1000,
588
589
		.thunk_addr   = 0x22E00, .thunk_size = 0x200,
		.swap_buffers = a31_sram_swap_buffers,
590
	},
591
592
	{
		.soc_id       = 0x1667, /* Allwinner A33 */
593
		.scratch_addr = 0x1000,
594
		.thunk_addr   = 0x46E00, .thunk_size = 0x200,
595
		.swap_buffers = ar100_abusing_sram_swap_buffers,
596
		.sid_addr     = 0x01C23800,
597
	},
598
599
600
601
602
603
604
	{
		.soc_id       = 0x1689, /* Allwinner A64 */
		.spl_addr     = 0x10000,
		.scratch_addr = 0x11000,
		.thunk_addr   = 0x1A200, .thunk_size = 0x200,
		.swap_buffers = a64_sram_swap_buffers,
		.sid_addr     = 0x01C14200,
605
		.rvbar_reg    = 0x017000A0,
606
	},
607
608
	{
		.soc_id       = 0x1673, /* Allwinner A83T */
609
		.scratch_addr = 0x1000,
610
		.thunk_addr   = 0x46E00, .thunk_size = 0x200,
611
		.swap_buffers = ar100_abusing_sram_swap_buffers,
612
		.sid_addr     = 0x01C14200,
613
	},
614
615
	{
		.soc_id       = 0x1680, /* Allwinner H3 */
616
		.scratch_addr = 0x1000,
617
618
619
		.mmu_tt_addr  = 0x8000,
		.thunk_addr   = 0xA200, .thunk_size = 0x200,
		.swap_buffers = a10_a13_a20_sram_swap_buffers,
620
		.sid_addr     = 0x01C14200,
621
	},
622
623
624
625
626
627
628
629
630
	{
		.soc_id       = 0x1718, /* Allwinner H5 */
		.spl_addr     = 0x10000,
		.scratch_addr = 0x11000,
		.thunk_addr   = 0x1A200, .thunk_size = 0x200,
		.swap_buffers = a64_sram_swap_buffers,
		.sid_addr     = 0x01C14200,
		.rvbar_reg    = 0x017000A0,
	},
631
632
633
	{
		.soc_id       = 0x1639, /* Allwinner A80 */
		.spl_addr     = 0x10000,
634
		.scratch_addr = 0x11000,
635
636
637
		.thunk_addr   = 0x23400, .thunk_size = 0x200,
		.swap_buffers = a80_sram_swap_buffers,
	},
638
	{ .swap_buffers = NULL } /* End of the table */
639
640
641
642
643
644
645
646
647
648
649
650
651
652
};

/*
 * This generic record assumes BROM with similar properties to A10/A13/A20/A31,
 * but no extra SRAM sections beyond 0x8000. It also assumes that the IRQ
 * handler stack usage never exceeds 0x400 bytes.
 *
 * The users may or may not hope that the 0x7000-0x8000 area is also unused
 * by the BROM and re-purpose it for the SPL stack.
 *
 * The size limit for the ".text + .data" sections is ~21 KiB.
 */
sram_swap_buffers generic_sram_swap_buffers[] = {
	{ .buf1 = 0x01C00, .buf2 = 0x5800, .size = 0x400 },
653
	{ .size = 0 }  /* End of the table */
654
655
656
};

soc_sram_info generic_sram_info = {
657
	.scratch_addr = 0x1000,
658
659
660
661
662
663
	.thunk_addr   = 0x5680, .thunk_size = 0x180,
	.swap_buffers = generic_sram_swap_buffers,
};

soc_sram_info *aw_fel_get_sram_info(libusb_device_handle *usb)
{
664
665
666
667
668
669
670
671
672
673
674
675
676
	/* persistent sram_info, retrieves result pointer once and caches it */
	static soc_sram_info *result = NULL;
	if (result == NULL) {
		int i;

		struct aw_fel_version buf;
		aw_fel_get_version(usb, &buf);

		for (i = 0; soc_sram_info_table[i].swap_buffers; i++)
			if (soc_sram_info_table[i].soc_id == buf.soc_id) {
				result = &soc_sram_info_table[i];
				break;
			}
677

678
679
680
681
682
683
684
		if (!result) {
			printf("Warning: no 'soc_sram_info' data for your SoC (id=%04X)\n",
			       buf.soc_id);
			result = &generic_sram_info;
		}
	}
	return result;
685
686
687
688
689
690
}

static uint32_t fel_to_spl_thunk[] = {
	#include "fel-to-spl-thunk.h"
};

691
692
693
#define	DRAM_BASE		0x40000000
#define	DRAM_SIZE		0x80000000

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
uint32_t aw_read_arm_cp_reg(libusb_device_handle *usb, soc_sram_info *sram_info,
			    uint32_t coproc, uint32_t opc1, uint32_t crn,
			    uint32_t crm, uint32_t opc2)
{
	uint32_t val = 0;
	uint32_t opcode = 0xEE000000 | (1 << 20) | (1 << 4) |
			  ((opc1 & 7) << 21)    |
			  ((crn & 15) << 16)    |
			  ((coproc & 15) << 8)  |
			  ((opc2 & 7) << 5)     |
			  (crm & 15);
	uint32_t arm_code[] = {
		htole32(opcode),     /* mrc  coproc, opc1, r0, crn, crm, opc2 */
		htole32(0xe58f0000), /* str  r0, [pc]                         */
		htole32(0xe12fff1e), /* bx   lr                               */
	};
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	aw_fel_execute(usb, sram_info->scratch_addr);
	aw_fel_read(usb, sram_info->scratch_addr + 12, &val, sizeof(val));
	return le32toh(val);
}

void aw_write_arm_cp_reg(libusb_device_handle *usb, soc_sram_info *sram_info,
			 uint32_t coproc, uint32_t opc1, uint32_t crn,
			 uint32_t crm, uint32_t opc2, uint32_t val)
{
	uint32_t opcode = 0xEE000000 | (0 << 20) | (1 << 4) |
			  ((opc1 & 7) << 21)                |
			  ((crn & 15) << 16)                |
			  ((coproc & 15) << 8)              |
			  ((opc2 & 7) << 5)                 |
			  (crm & 15);
	uint32_t arm_code[] = {
		htole32(0xe59f000c), /* ldr  r0, [pc, #12]                    */
		htole32(opcode),     /* mcr  coproc, opc1, r0, crn, crm, opc2 */
		htole32(0xf57ff04f), /* dsb  sy                               */
		htole32(0xf57ff06f), /* isb  sy                               */
		htole32(0xe12fff1e), /* bx   lr                               */
		htole32(val)
	};
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	aw_fel_execute(usb, sram_info->scratch_addr);
}

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
/* multiple "readl" from sequential addresses to a destination buffer */
void aw_fel_readl_n(libusb_device_handle *usb, uint32_t addr,
		    uint32_t *dst, size_t count)
{
	soc_sram_info *sram_info = aw_fel_get_sram_info(usb);
	uint32_t val;
	uint32_t arm_code[] = {
		htole32(0xe59f0010), /* ldr        r0, [pc, #16]            */
		htole32(0xe5901000), /* ldr        r1, [r0]                 */
		htole32(0xe58f100c), /* str        r1, [pc, #12]            */
		htole32(0xe2800004), /* add        r0, r0, #4               */
		htole32(0xe58f0000), /* str        r0, [pc]                 */
		htole32(0xe12fff1e), /* bx         lr                       */
		htole32(addr),
		/* value goes here */
	};
	/* scratch buffer setup: transfers ARM code and also sets the addr */
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	while (count-- > 0) {
		/*
		 * Since the scratch code auto-increments addr, we can simply
		 * execute it repeatedly for sequential "readl"s; retrieving
		 * one uint32_t each time.
		 */
		aw_fel_execute(usb, sram_info->scratch_addr);
		aw_fel_read(usb, sram_info->scratch_addr + 28, &val, sizeof(val));
		*dst++ = le32toh(val);
	}
}

/* "readl" of a single value */
uint32_t aw_fel_readl(libusb_device_handle *usb, uint32_t addr)
{
	uint32_t val;
	aw_fel_readl_n(usb, addr, &val, 1);
	return val;
}

/* multiple "writel" from a source buffer to sequential addresses */
void aw_fel_writel_n(libusb_device_handle *usb, uint32_t addr,
		     uint32_t *src, size_t count)
{
	if (count == 0) return; /* on zero count, do not access *src at all */

	soc_sram_info *sram_info = aw_fel_get_sram_info(usb);
	uint32_t arm_code[] = {
		htole32(0xe59f0010), /* ldr        r0, [pc, #16]            */
		htole32(0xe59f1010), /* ldr        r1, [pc, #16]            */
		htole32(0xe5801000), /* str        r1, [r0]                 */
		htole32(0xe2800004), /* add        r0, r0, #4               */
		htole32(0xe58f0000), /* str        r0, [pc]                 */
		htole32(0xe12fff1e), /* bx         lr                       */
		htole32(addr),
		htole32(*src++)
	};
	/* scratch buffer setup: transfers ARM code, addr and first value */
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	aw_fel_execute(usb, sram_info->scratch_addr); /* stores first value */
	while (--count > 0) {
		/*
		 * Subsequent transfers only need to set up the next value
		 * to store (since the scratch code auto-increments addr).
		 */
801
802
		uint32_t val = htole32(*src++);
		aw_fel_write(usb, &val, sram_info->scratch_addr + 28, sizeof(val));
803
804
805
806
807
808
809
810
811
812
		aw_fel_execute(usb, sram_info->scratch_addr);
	}
}

/* "writel" of a single value */
void aw_fel_writel(libusb_device_handle *usb, uint32_t addr, uint32_t val)
{
	aw_fel_writel_n(usb, addr, &val, 1);
}

813
814
815
816
817
818
819
820
821
822
void aw_fel_print_sid(libusb_device_handle *usb)
{
	soc_sram_info *soc_info = aw_fel_get_sram_info(usb);
	if (soc_info->sid_addr) {
		pr_info("SID key (e-fuses) at 0x%08X\n", soc_info->sid_addr);

		uint32_t key[4];
		aw_fel_readl_n(usb, soc_info->sid_addr, key, 4);

		unsigned int i;
Bernhard Nortmann's avatar
Bernhard Nortmann committed
823
		/* output SID in "xxxxxxxx:xxxxxxxx:xxxxxxxx:xxxxxxxx" format */
824
		for (i = 0; i <= 3; i++)
Bernhard Nortmann's avatar
Bernhard Nortmann committed
825
			printf("%08x%c", key[i], i < 3 ? ':' : '\n');
826
827
828
829
830
831
	} else {
		printf("SID registers for your SoC (id=%04X) are unknown or inaccessible.\n",
			soc_info->soc_id);
	}
}

832
void aw_enable_l2_cache(libusb_device_handle *usb, soc_sram_info *sram_info)
833
834
835
836
837
838
839
840
{
	uint32_t arm_code[] = {
		htole32(0xee112f30), /* mrc        15, 0, r2, cr1, cr0, {1}  */
		htole32(0xe3822002), /* orr        r2, r2, #2                */
		htole32(0xee012f30), /* mcr        15, 0, r2, cr1, cr0, {1}  */
		htole32(0xe12fff1e), /* bx         lr                        */
	};

841
842
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	aw_fel_execute(usb, sram_info->scratch_addr);
843
844
}

845
846
void aw_get_stackinfo(libusb_device_handle *usb, soc_sram_info *sram_info,
                      uint32_t *sp_irq, uint32_t *sp)
847
848
849
850
851
852
853
854
855
856
857
{
	uint32_t results[2] = { 0 };
#if 0
	/* Does not work on Cortex-A8 (needs Virtualization Extensions) */
	uint32_t arm_code[] = {
		htole32(0xe1010300), /* mrs        r0, SP_irq                */
		htole32(0xe58f0004), /* str        r0, [pc, #4]              */
		htole32(0xe58fd004), /* str        sp, [pc, #4]              */
		htole32(0xe12fff1e), /* bx         lr                        */
	};

858
859
860
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	aw_fel_execute(usb, sram_info->scratch_addr);
	aw_fel_read(usb, sram_info->scratch_addr + 0x10, results, 8);
861
862
863
864
865
866
867
868
869
870
871
872
873
874
#else
	/* Works everywhere */
	uint32_t arm_code[] = {
		htole32(0xe10f0000), /* mrs        r0, CPSR                  */
		htole32(0xe3c0101f), /* bic        r1, r0, #31               */
		htole32(0xe3811012), /* orr        r1, r1, #18               */
		htole32(0xe121f001), /* msr        CPSR_c, r1                */
		htole32(0xe1a0100d), /* mov        r1, sp                    */
		htole32(0xe121f000), /* msr        CPSR_c, r0                */
		htole32(0xe58f1004), /* str        r1, [pc, #4]              */
		htole32(0xe58fd004), /* str        sp, [pc, #4]              */
		htole32(0xe12fff1e), /* bx         lr                        */
	};

875
876
877
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	aw_fel_execute(usb, sram_info->scratch_addr);
	aw_fel_read(usb, sram_info->scratch_addr + 0x24, results, 8);
878
879
880
881
882
#endif
	*sp_irq = le32toh(results[0]);
	*sp     = le32toh(results[1]);
}

883
uint32_t aw_get_ttbr0(libusb_device_handle *usb, soc_sram_info *sram_info)
884
{
885
	return aw_read_arm_cp_reg(usb, sram_info, 15, 0, 2, 0, 0);
886
887
}

888
889
890
891
892
893
894
895
896
897
uint32_t aw_get_ttbcr(libusb_device_handle *usb, soc_sram_info *sram_info)
{
	return aw_read_arm_cp_reg(usb, sram_info, 15, 0, 2, 0, 2);
}

uint32_t aw_get_dacr(libusb_device_handle *usb, soc_sram_info *sram_info)
{
	return aw_read_arm_cp_reg(usb, sram_info, 15, 0, 3, 0, 0);
}

898
uint32_t aw_get_sctlr(libusb_device_handle *usb, soc_sram_info *sram_info)
899
{
900
	return aw_read_arm_cp_reg(usb, sram_info, 15, 0, 1, 0, 0);
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
void aw_set_ttbr0(libusb_device_handle *usb, soc_sram_info *sram_info,
		  uint32_t ttbr0)
{
	return aw_write_arm_cp_reg(usb, sram_info, 15, 0, 2, 0, 0, ttbr0);
}

void aw_set_ttbcr(libusb_device_handle *usb, soc_sram_info *sram_info,
		  uint32_t ttbcr)
{
	return aw_write_arm_cp_reg(usb, sram_info, 15, 0, 2, 0, 2, ttbcr);
}

void aw_set_dacr(libusb_device_handle *usb, soc_sram_info *sram_info,
		 uint32_t dacr)
{
	aw_write_arm_cp_reg(usb, sram_info, 15, 0, 3, 0, 0, dacr);
}

void aw_set_sctlr(libusb_device_handle *usb, soc_sram_info *sram_info,
		  uint32_t sctlr)
{
	aw_write_arm_cp_reg(usb, sram_info, 15, 0, 1, 0, 0, sctlr);
}

/*
 * Reconstruct the same MMU translation table as used by the A20 BROM.
 * We are basically reverting the changes, introduced in newer SoC
 * variants. This works fine for the SoC variants with the memory
 * layout similar to A20 (the SRAM is in the first megabyte of the
 * address space and the BROM is in the last megabyte of the address
 * space).
 */
uint32_t *aw_generate_mmu_translation_table(void)
{
	uint32_t *tt = malloc(4096 * sizeof(uint32_t));
	uint32_t i;

	/*
	 * Direct mapping using 1MB sections with TEXCB=00000 (Strongly
	 * ordered) for all memory except the first and the last sections,
	 * which have TEXCB=00100 (Normal). Domain bits are set to 1111
	 * and AP bits are set to 11, but this is mostly irrelevant.
	 */
	for (i = 0; i < 4096; i++)
		tt[i] = 0x00000DE2 | (i << 20);
	tt[0x000] |= 0x1000;
	tt[0xFFF] |= 0x1000;

	return tt;
}

954
955
uint32_t *aw_backup_and_disable_mmu(libusb_device_handle *usb,
                                    soc_sram_info *sram_info)
956
{
957
	uint32_t *tt = NULL;
958
	uint32_t sctlr, ttbr0, ttbcr, dacr;
959
960
961
	uint32_t i;

	uint32_t arm_code[] = {
962
		/* Disable I-cache, MMU and branch prediction */
963
964
		htole32(0xee110f10), /* mrc        15, 0, r0, cr1, cr0, {0}  */
		htole32(0xe3c00001), /* bic        r0, r0, #1                */
965
966
		htole32(0xe3c00a01), /* bic        r0, r0, #4096             */
		htole32(0xe3c00b02), /* bic        r0, r0, #2048             */
967
968
969
970
971
		htole32(0xee010f10), /* mcr        15, 0, r0, cr1, cr0, {0}  */
		/* Return back to FEL */
		htole32(0xe12fff1e), /* bx         lr                        */
	};

972
973
974
975
976
977
978
979
980
981
982
	/*
	 * Below are some checks for the register values, which are known
	 * to be initialized in this particular way by the existing BROM
	 * implementations. We don't strictly need them to exactly match,
	 * but still have these safety guards in place in order to detect
	 * and review any potential configuration changes in future SoC
	 * variants (if one of these checks fails, then it is not a serious
	 * problem but more likely just an indication that one of these
	 * checks needs to be relaxed).
	 */

983
	/* Basically, ignore M/Z/I/V/UNK bits and expect no TEX remap */
984
	sctlr = aw_get_sctlr(usb, sram_info);
985
	if ((sctlr & ~((0x7 << 11) | (1 << 6) | 1)) != 0x00C50038) {
986
987
988
989
		fprintf(stderr, "Unexpected SCTLR (%08X)\n", sctlr);
		exit(1);
	}

990
	if (!(sctlr & 1)) {
991
992
		pr_info("MMU is not enabled by BROM\n");
		return NULL;
993
994
	}

995
	dacr = aw_get_dacr(usb, sram_info);
996
997
998
999
1000
	if (dacr != 0x55555555) {
		fprintf(stderr, "Unexpected DACR (%08X)\n", dacr);
		exit(1);
	}

1001
	ttbcr = aw_get_ttbcr(usb, sram_info);
1002
1003
	if (ttbcr != 0x00000000) {
		fprintf(stderr, "Unexpected TTBCR (%08X)\n", ttbcr);
1004
1005
1006
		exit(1);
	}

1007
	ttbr0 = aw_get_ttbr0(usb, sram_info);
1008
1009
1010
1011
1012
	if (ttbr0 & 0x3FFF) {
		fprintf(stderr, "Unexpected TTBR0 (%08X)\n", ttbr0);
		exit(1);
	}

1013
	tt = malloc(16 * 1024);
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
	pr_info("Reading the MMU translation table from 0x%08X\n", ttbr0);
	aw_fel_read(usb, ttbr0, tt, 16 * 1024);
	for (i = 0; i < 4096; i++)
		tt[i] = le32toh(tt[i]);

	/* Basic sanity checks to be sure that this is a valid table */
	for (i = 0; i < 4096; i++) {
		if (((tt[i] >> 1) & 1) != 1 || ((tt[i] >> 18) & 1) != 0) {
			fprintf(stderr, "MMU: not a section descriptor\n");
			exit(1);
		}
		if ((tt[i] >> 20) != i) {
			fprintf(stderr, "MMU: not a direct mapping\n");
			exit(1);
		}
	}

1031
	pr_info("Disabling I-cache, MMU and branch prediction...");
1032
1033
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	aw_fel_execute(usb, sram_info->scratch_addr);
1034
1035
1036
1037
1038
	pr_info(" done.\n");

	return tt;
}

1039
1040
1041
void aw_restore_and_enable_mmu(libusb_device_handle *usb,
                               soc_sram_info *sram_info,
                               uint32_t *tt)
1042
1043
{
	uint32_t i;
1044
	uint32_t ttbr0 = aw_get_ttbr0(usb, sram_info);
1045
1046

	uint32_t arm_code[] = {
1047
1048
1049
1050
1051
1052
1053
1054
		/* Invalidate I-cache, TLB and BTB */
		htole32(0xe3a00000), /* mov        r0, #0                    */
		htole32(0xee080f17), /* mcr        15, 0, r0, cr8, cr7, {0}  */
		htole32(0xee070f15), /* mcr        15, 0, r0, cr7, cr5, {0}  */
		htole32(0xee070fd5), /* mcr        15, 0, r0, cr7, cr5, {6}  */
		htole32(0xf57ff04f), /* dsb        sy                        */
		htole32(0xf57ff06f), /* isb        sy                        */
		/* Enable I-cache, MMU and branch prediction */
1055
1056
		htole32(0xee110f10), /* mrc        15, 0, r0, cr1, cr0, {0}  */
		htole32(0xe3800001), /* orr        r0, r0, #1                */
1057
1058
		htole32(0xe3800a01), /* orr        r0, r0, #4096             */
		htole32(0xe3800b02), /* orr        r0, r0, #2048             */
1059
1060
1061
1062
1063
		htole32(0xee010f10), /* mcr        15, 0, r0, cr1, cr0, {0}  */
		/* Return back to FEL */
		htole32(0xe12fff1e), /* bx         lr                        */
	};

1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
	pr_info("Setting write-combine mapping for DRAM.\n");
	for (i = (DRAM_BASE >> 20); i < ((DRAM_BASE + DRAM_SIZE) >> 20); i++) {
		/* Clear TEXCB bits */
		tt[i] &= ~((7 << 12) | (1 << 3) | (1 << 2));
		/* Set TEXCB to 00100 (Normal uncached mapping) */
		tt[i] |= (1 << 12);
	}

	pr_info("Setting cached mapping for BROM.\n");
	/* Clear TEXCB bits first */
	tt[0xFFF] &= ~((7 << 12) | (1 << 3) | (1 << 2));
	/* Set TEXCB to 00111 (Normal write-back cached mapping) */
	tt[0xFFF] |= (1 << 12) | /* TEX */
		     (1 << 3)  | /* C */
		     (1 << 2);   /* B */

1080
1081
1082
1083
1084
	pr_info("Writing back the MMU translation table.\n");
	for (i = 0; i < 4096; i++)
		tt[i] = htole32(tt[i]);
	aw_fel_write(usb, tt, ttbr0, 16 * 1024);

1085
	pr_info("Enabling I-cache, MMU and branch prediction...");
1086
1087
	aw_fel_write(usb, arm_code, sram_info->scratch_addr, sizeof(arm_code));
	aw_fel_execute(usb, sram_info->scratch_addr);
1088
1089
1090
1091
1092
	pr_info(" done.\n");

	free(tt);
}

1093
1094
1095
1096
/*
 * Maximum size of SPL, at the same time this is the start offset
 * of the main U-Boot image within u-boot-sunxi-with-spl.bin
 */
1097
#define SPL_LEN_LIMIT 0x8000
1098

1099
1100
1101
1102
1103
1104
1105
1106
void aw_fel_write_and_execute_spl(libusb_device_handle *usb,
				  uint8_t *buf, size_t len)
{
	soc_sram_info *sram_info = aw_fel_get_sram_info(usb);
	sram_swap_buffers *swap_buffers;
	char header_signature[9] = { 0 };
	size_t i, thunk_size;
	uint32_t *thunk_buf;
1107
	uint32_t sp, sp_irq;
1108
	uint32_t spl_checksum, spl_len, spl_len_limit = SPL_LEN_LIMIT;
1109
	uint32_t *buf32 = (uint32_t *)buf;
1110
	uint32_t cur_addr = sram_info->spl_addr;
1111
	uint32_t *tt = NULL;
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

	if (!sram_info || !sram_info->swap_buffers) {
		fprintf(stderr, "SPL: Unsupported SoC type\n");
		exit(1);
	}

	if (len < 32 || memcmp(buf + 4, "eGON.BT0", 8) != 0) {
		fprintf(stderr, "SPL: eGON header is not found\n");
		exit(1);
	}

	spl_checksum = 2 * le32toh(buf32[3]) - 0x5F0A6C39;
	spl_len = le32toh(buf32[4]);

	if (spl_len > len || (spl_len % 4) != 0) {
		fprintf(stderr, "SPL: bad length in the eGON header\n");
		exit(1);
	}

	len = spl_len;
	for (i = 0; i < len / 4; i++)
		spl_checksum -= le32toh(buf32[i]);

	if (spl_checksum != 0) {
		fprintf(stderr, "SPL: checksum check failed\n");
		exit(1);
	}

1140
1141
	if (sram_info->needs_l2en) {
		pr_info("Enabling the L2 cache\n");
1142
		aw_enable_l2_cache(usb, sram_info);
1143
1144
	}

1145
	aw_get_stackinfo(usb, sram_info, &sp_irq, &sp);
1146
1147
	pr_info("Stack pointers: sp_irq=0x%08X, sp=0x%08X\n", sp_irq, sp);

1148
	tt = aw_backup_and_disable_mmu(usb, sram_info);
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
	if (!tt && sram_info->mmu_tt_addr) {
		if (sram_info->mmu_tt_addr & 0x3FFF) {
			fprintf(stderr, "SPL: 'mmu_tt_addr' must be 16K aligned\n");
			exit(1);
		}
		pr_info("Generating the new MMU translation table at 0x%08X\n",
		        sram_info->mmu_tt_addr);
		/*
		 * These settings are used by the BROM in A10/A13/A20 and
		 * we replicate them here when enabling the MMU. The DACR
		 * value 0x55555555 means that accesses are checked against
		 * the permission bits in the translation tables for all
		 * domains. The TTBCR value 0x00000000 means that the short
		 * descriptor translation table format is used, TTBR0 is used
		 * for all the possible virtual addresses (N=0) and that the
		 * translation table must be aligned at a 16K boundary.
		 */
		aw_set_dacr(usb, sram_info, 0x55555555);
		aw_set_ttbcr(usb, sram_info, 0x00000000);
		aw_set_ttbr0(usb, sram_info, sram_info->mmu_tt_addr);
		tt = aw_generate_mmu_translation_table();
	}
1171

1172
1173
	swap_buffers = sram_info->swap_buffers;
	for (i = 0; swap_buffers[i].size; i++) {
1174
1175
1176
1177
1178
		if ((swap_buffers[i].buf2 >= sram_info->spl_addr) &&
		    (swap_buffers[i].buf2 < sram_info->spl_addr + spl_len_limit))
			spl_len_limit = swap_buffers[i].buf2 - sram_info->spl_addr;
		if (len > 0 && cur_addr < swap_buffers[i].buf1) {
			uint32_t tmp = swap_buffers[i].buf1 - cur_addr;
1179
1180
			if (tmp > len)
				tmp = len;
1181
1182
			aw_fel_write(usb, buf, cur_addr, tmp);
			cur_addr += tmp;
1183
1184
1185
			buf += tmp;
			len -= tmp;
		}
1186
		if (len > 0 && cur_addr == swap_buffers[i].buf1) {
1187
1188
1189
1190
			uint32_t tmp = swap_buffers[i].size;
			if (tmp > len)
				tmp = len;
			aw_fel_write(usb, buf, swap_buffers[i].buf2, tmp);
1191
			cur_addr += tmp;
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
			buf += tmp;
			len -= tmp;
		}
	}

	/* Clarify the SPL size limitations, and bail out if they are not met */
	if (sram_info->thunk_addr < spl_len_limit)
		spl_len_limit = sram_info->thunk_addr;

	if (spl_len > spl_len_limit) {
		fprintf(stderr, "SPL: too large (need %d, have %d)\n",
			(int)spl_len, (int)spl_len_limit);
		exit(1);
	}

	/* Write the remaining part of the SPL */
	if (len > 0)
1209
		aw_fel_write(usb, buf, cur_addr, len);
1210

1211
1212
	thunk_size = sizeof(fel_to_spl_thunk) + sizeof(sram_info->spl_addr) +
		     (i + 1) * sizeof(*swap_buffers);
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222

	if (thunk_size > sram_info->thunk_size) {
		fprintf(stderr, "SPL: bad thunk size (need %d, have %d)\n",
			(int)sizeof(fel_to_spl_thunk), sram_info->thunk_size);
		exit(1);
	}

	thunk_buf = malloc(thunk_size);
	memcpy(thunk_buf, fel_to_spl_thunk, sizeof(fel_to_spl_thunk));
	memcpy(thunk_buf + sizeof(fel_to_spl_thunk) / sizeof(uint32_t),
1223
1224
	       &sram_info->spl_addr, sizeof(sram_info->spl_addr));
	memcpy(thunk_buf + sizeof(fel_to_spl_thunk) / sizeof(uint32_t) + 1,
1225
1226
1227
1228
1229
	       swap_buffers, (i + 1) * sizeof(*swap_buffers));

	for (i = 0; i < thunk_size / sizeof(uint32_t); i++)
		thunk_buf[i] = htole32(thunk_buf[i]);

1230
	pr_info("=> Executing the SPL...");
1231
1232
	aw_fel_write(usb, thunk_buf, sram_info->thunk_addr, thunk_size);
	aw_fel_execute(usb, sram_info->thunk_addr);
1233
	pr_info(" done.\n");
1234
1235
1236
1237
1238
1239
1240

	free(thunk_buf);

	/* TODO: Try to find and fix the bug, which needs this workaround */
	usleep(250000);

	/* Read back the result and check if everything was fine */
1241
	aw_fel_read(usb, sram_info->spl_addr + 4, header_signature, 8);
1242
1243
1244
1245
1246
	if (strcmp(header_signature, "eGON.FEL") != 0) {
		fprintf(stderr, "SPL: failure code '%s'\n",
			header_signature);
		exit(1);
	}
1247

1248
	/* re-enable the MMU if it was enabled by BROM */
Bernhard Nortmann's avatar
Bernhard Nortmann committed
1249
	if (tt != NULL)
1250
		aw_restore_and_enable_mmu(usb, sram_info, tt);
1251
1252
}

1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
/*
 * This function tests a given buffer address and length for a valid U-Boot
 * image. Upon success, the image data gets transferred to the default memory
 * address stored within the image header; and the function preserves the
 * U-Boot entry point (offset) and size values.
 */
void aw_fel_write_uboot_image(libusb_device_handle *usb,
		uint8_t *buf, size_t len)
{
	if (len <= HEADER_SIZE)
		return; /* Insufficient size (no actual data), just bail out */

	uint32_t *buf32 = (uint32_t *)buf;

1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
	/* Check for a valid mkimage header */
	int image_type = get_image_type(buf, len);
	if (image_type <= IH_TYPE_INVALID) {
		switch (image_type) {
		case IH_TYPE_INVALID:
			fprintf(stderr, "Invalid U-Boot image: bad size or signature\n");
			break;
		case IH_TYPE_ARCH_MISMATCH:
			fprintf(stderr, "Invalid U-Boot image: wrong architecture\n");
			break;
		default:
			fprintf(stderr, "Invalid U-Boot image: error code %d\n",
				image_type);
		}
1281
1282
		exit(1);
	}
1283
1284
1285
	if (image_type != IH_TYPE_FIRMWARE) {
		fprintf(stderr, "U-Boot image type mismatch: "
			"expected IH_TYPE_FIRMWARE, got %02X\n", image_type);
1286
1287
1288
1289
		exit(1);
	}
	uint32_t data_size = be32toh(buf32[3]); /* Image Data Size */
	uint32_t load_addr = be32toh(buf32[4]); /* Data Load Address */
1290
	if (data_size != len - HEADER_SIZE) {
1291
		fprintf(stderr, "U-Boot image data size mismatch: "
1292
			"expected %zu, got %u\n", len - HEADER_SIZE, data_size);
1293
1294
1295
1296
1297
1298
		exit(1);
	}
	/* TODO: Verify image data integrity using the checksum field ih_dcrc,
	 * available from be32toh(buf32[6])
	 *
	 * However, this requires CRC routines that mimic their U-Boot
Bernhard Nortmann's avatar
Bernhard Nortmann committed
1299
	 * counterparts, namely image_check_dcrc() in ${U-BOOT}/common/image.c
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
	 * and crc_wd() in ${U-BOOT}/lib/crc32.c
	 *
	 * It should be investigated if existing CRC routines in sunxi-tools
	 * could be factored out and reused for this purpose - e.g. calc_crc32()
	 * from nand-part-main.c
	 */

	/* If we get here, we're "good to go" (i.e. actually write the data) */
	pr_info("Writing image \"%.*s\", %u bytes @ 0x%08X.\n",
		IH_NMLEN, buf + HEADER_NAME_OFFSET, data_size, load_addr);

1311
	aw_write_buffer(usb, buf + HEADER_SIZE, load_addr, data_size, false);
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329

	/* keep track of U-Boot memory region in global vars */
	uboot_entry = load_addr;
	uboot_size = data_size;
}

/*
 * This function handles the common part of both "spl" and "uboot" commands.
 */
void aw_fel_process_spl_and_uboot(libusb_device_handle *usb,
		const char *filename)
{
	/* load file into memory buffer */
	size_t size;
	uint8_t *buf = load_file(filename, &size);
	/* write and execute the SPL from the buffer */
	aw_fel_write_and_execute_spl(usb, buf, size);
	/* check for optional main U-Boot binary (and transfer it, if applicable) */
1330
1331
	if (size > SPL_LEN_LIMIT)
		aw_fel_write_uboot_image(usb, buf + SPL_LEN_LIMIT, size - SPL_LEN_LIMIT);
1332
	free(buf);
1333
1334
}

1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
/*
 * Test the SPL header for our "sunxi" variant. We want to make sure that
 * we can safely use specific header fields to pass information to U-Boot.
 * In case of a missing signature (e.g. Allwinner boot0) or header version
 * mismatch, this function will return "false". If all seems fine,
 * the result is "true".
 */
#define SPL_SIGNATURE			"SPL" /* marks "sunxi" header */
#define SPL_MIN_VERSION			1 /* minimum required version */
#define SPL_MAX_VERSION			1 /* maximum supported version */
1345
bool have_sunxi_spl(libusb_device_handle *usb, uint32_t spl_addr)
1346
1347
1348
1349
1350
1351
1352
{
	uint8_t spl_signature[4];

	aw_fel_read(usb, spl_addr + 0x14,
		&spl_signature, sizeof(spl_signature));

	if (memcmp(spl_signature, SPL_SIGNATURE, 3) != 0)
1353
		return false; /* signature mismatch, no "sunxi" SPL */
1354
1355
1356
1357
1358
1359

	if (spl_signature[3] < SPL_MIN_VERSION) {
		fprintf(stderr, "sunxi SPL version mismatch: "
			"found 0x%02X < required minimum 0x%02X\n",
			spl_signature[3], SPL_MIN_VERSION);
		fprintf(stderr, "You need to update your U-Boot (mksunxiboot) to a more recent version.\n");
1360
		return false;
1361
1362
1363
1364
1365
1366
	}
	if (spl_signature[3] > SPL_MAX_VERSION) {
		fprintf(stderr, "sunxi SPL version mismatch: "
			"found 0x%02X > maximum supported 0x%02X\n",
			spl_signature[3], SPL_MAX_VERSION);
		fprintf(stderr, "You need a more recent version of this (sunxi-tools) fel utility.\n");
1367
		return false;
1368
	}
1369
	return true; /* sunxi SPL and suitable version */
1370
1371
1372
1373
}

/*
 * Pass information to U-Boot via specialized fields in the SPL header
1374
1375
 * (see "boot_file_head" in ${U-BOOT}/arch/arm/include/asm/arch-sunxi/spl.h),
 * providing the boot script address (DRAM location of boot.scr).
1376
 */
1377
1378
void pass_fel_information(libusb_device_handle *usb,
			  uint32_t script_address, uint32_t uEnv_length)
1379
1380
1381
1382
1383
{
	soc_sram_info *sram_info = aw_fel_get_sram_info(usb);

	/* write something _only_ if we have a suitable SPL header */
	if (have_sunxi_spl(usb, sram_info->spl_addr)) {
1384
1385
1386
1387
1388
1389
1390
1391
1392
		pr_info("Passing boot info via sunxi SPL: "
			"script address = 0x%08X, uEnv length = %u\n",
			script_address, uEnv_length);
		uint32_t transfer[] = {
			htole32(script_address),
			htole32(uEnv_length)
		};
		aw_fel_write(usb, transfer,
			sram_info->spl_addr + 0x18, sizeof(transfer));
1393
1394
1395
	}
}

1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
static int aw_fel_get_endpoint(libusb_device_handle *usb)
{
	struct libusb_device *dev = libusb_get_device(usb);
	struct libusb_config_descriptor *config;
	int if_idx, set_idx, ep_idx, ret;

	ret = libusb_get_active_config_descriptor(dev, &config);
	if (ret)
		return ret;

	for (if_idx = 0; if_idx < config->bNumInterfaces; if_idx++) {
		const struct libusb_interface *iface = config->interface + if_idx;

		for (set_idx = 0; set_idx < iface->num_altsetting; set_idx++) {
			const struct libusb_interface_descriptor *setting =
				iface->altsetting + set_idx;

			for (ep_idx = 0; ep_idx < setting->bNumEndpoints; ep_idx++) {
				const struct libusb_endpoint_descriptor *ep =
					setting->endpoint + ep_idx;

Bernhard Nortmann's avatar
Bernhard Nortmann committed
1417
				/* Test for bulk transfer endpoint */
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
				if ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) !=
						LIBUSB_TRANSFER_TYPE_BULK)
					continue;

				if ((ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) ==
						LIBUSB_ENDPOINT_IN)
					AW_USB_FEL_BULK_EP_IN = ep->bEndpointAddress;
				else
					AW_USB_FEL_BULK_EP_OUT = ep->bEndpointAddress;
			}
		}
	}

	libusb_free_config_descriptor(config);

	return 0;
}

1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
/*
 * This function stores a given entry point to the RVBAR address for CPU0,
 * and then writes the Reset Management Register to request a warm boot.
 * It is useful with some AArch64 transitions, e.g. when passing control to
 * ARM Trusted Firmware (ATF) during the boot process of Pine64.
 *
 * The code was inspired by
 * https://github.com/apritzel/u-boot/commit/fda6bd1bf285c44f30ea15c7e6231bf53c31d4a8
 */
void aw_rmr_request(libusb_device_handle *usb, uint32_t entry_point, bool aarch64)
{
	soc_sram_info *soc_info = aw_fel_get_sram_info(usb);
	if (!soc_info->rvbar_reg) {
		fprintf(stderr, "ERROR: Can't issue RMR request!\n"
			"RVBAR is not supported or unknown for your SoC (id=%04X).\n",
			soc_info->soc_id);
		return;
	}

	uint32_t rmr_mode = (1 << 1) | (aarch64 ? 1 : 0); /* RR, AA64 flag */
	uint32_t arm_code[] = {
		htole32(0xe59f0028), /* ldr        r0, [rvbar_reg]          */
		htole32(0xe59f1028), /* ldr        r1, [entry_point]        */
		htole32(0xe5801000), /* str        r1, [r0]                 */
		htole32(0xf57ff04f), /* dsb        sy                       */
		htole32(0xf57ff06f), /* isb        sy                       */

		htole32(0xe59f101c), /* ldr        r1, [rmr_mode]           */
		htole32(0xee1c0f50), /* mrc        15, 0, r0, cr12, cr0, {2}*/
		htole32(0xe1800001), /* orr        r0, r0, r1               */
		htole32(0xee0c0f50), /* mcr        15, 0, r0, cr12, cr0, {2}*/
		htole32(0xf57ff06f), /* isb        sy                       */

		htole32(0xe320f003), /* loop:      wfi                      */
		htole32(0xeafffffd), /* b          <loop>                   */

		htole32(soc_info->rvbar_reg),
		htole32(entry_point),
		htole32(rmr_mode)
	};
	/* scratch buffer setup: transfers ARM code and parameter values */
	aw_fel_write(usb, arm_code, soc_info->scratch_addr, sizeof(arm_code));
	/* execute the thunk code (triggering a warm reset on the SoC) */
	pr_info("Store entry point 0x%08X to RVBAR 0x%08X, "
		"and request warm reset with RMR mode %u...",
		entry_point, soc_info->rvbar_reg, rmr_mode);
	aw_fel_execute(usb, soc_info->scratch_addr);
	pr_info(" done.\n");
}

1486
1487
1488
1489
1490
1491
1492
1493
/* check buffer for magic "#=uEnv", indicating uEnv.txt compatible format */
static bool is_uEnv(void *buffer, size_t size)
{
	if (size <= 6)
		return false; /* insufficient size */
	return memcmp(buffer, "#=uEnv", 6) == 0;
}

1494
1495
/* private helper function, gets used for "write*" and "multi*" transfers */
static unsigned int file_upload(libusb_device_handle *handle, size_t count,
1496
				size_t argc, char **argv, progress_cb_t callback)
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
{
	if (argc < count * 2) {
		fprintf(stderr, "error: too few arguments for uploading %zu files\n",
			count);
		exit(1);
	}

	/* get all file sizes, keeping track of total bytes */
	size_t size = 0;
	unsigned int i;
	for (i = 0; i < count; i++)
		size += file_size(argv[i * 2 + 1]);

1510
	progress_start(callback, size); /* set total size and progress callback */
1511
1512
1513
1514
1515
1516

	/* now transfer each file in turn */
	for (i = 0; i < count; i++) {
		void *buf = load_file(argv[i * 2 + 1], &size);
		if (size > 0) {
			uint32_t offset = strtoul(argv[i * 2], NULL, 0);
1517
			aw_write_buffer(handle, buf, offset, size, callback != NULL);
1518

Bernhard Nortmann's avatar
Bernhard Nortmann committed
1519
			/* If we transferred a script, try to inform U-Boot about its address. */
1520
			if (get_image_type(buf, size) == IH_TYPE_SCRIPT)
1521
1522
1523
				pass_fel_information(handle, offset, 0);
			if (is_uEnv(buf, size)) /* uEnv-style data */
				pass_fel_information(handle, offset, size);
1524
1525
1526
1527
		}
		free(buf);
	}

Bernhard Nortmann's avatar
Bernhard Nortmann committed
1528
	return i; /* return number of files that were processed */
1529
1530
}

1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
/* open libusb handle to desired FEL device */
static libusb_device_handle *open_fel_device(int busnum, int devnum,
		uint16_t vendor_id, uint16_t product_id)
{
	libusb_device_handle *result = NULL;

	if (busnum < 0 || devnum < 0) {
		/* With the default values (busnum -1, devnum -1) we don't care
		 * for a specific USB device; so let libusb open the first
		 * device that matches VID/PID.
		 */
		result = libusb_open_device_with_vid_pid(NULL, vendor_id, product_id);
		if (!result) {
			switch (errno) {
			case EACCES:
				fprintf(stderr, "ERROR: You don't have permission to access Allwinner USB FEL device\n");
				break;
			default:
				fprintf(stderr, "ERROR: Allwinner USB FEL device not found!\n");
				break;
			}
			exit(1);
		}
		return result;
	}

	/* look for specific bus and device number */
	pr_info("Selecting USB Bus %03d Device %03d\n", busnum, devnum);
	bool found = false;
	ssize_t rc, i;
	libusb_device **list;

	rc = libusb_get_device_list(NULL, &list);
1564
1565
	if (rc < 0)
		usb_error(rc, "libusb_get_device_list()", 1);
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
	for (i = 0; i < rc; i++) {
		if (libusb_get_bus_number(list[i]) == busnum
		    && libusb_get_device_address(list[i]) == devnum) {
			found = true; /* bus:devnum matched */
			struct libusb_device_descriptor desc;
			libusb_get_device_descriptor(list[i], &desc);
			if (desc.idVendor != vendor_id
			    || desc.idProduct != product_id) {
				fprintf(stderr, "ERROR: Bus %03d Device %03d not a FEL device "
					"(expected %04x:%04x, got %04x:%04x)\n", busnum, devnum,
					vendor_id, product_id, desc.idVendor, desc.idProduct);
				exit(1);
			}
			/* open handle to this specific device (incrementing its refcount) */
			rc = libusb_open(list[i], &result);
1581
1582
			if (rc != 0)
				usb_error(rc, "libusb_open()", 1);
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
			break;
		}
	}
	libusb_free_device_list(list, true);

	if (!found) {
		fprintf(stderr, "ERROR: Bus %03d Device %03d not found in libusb device list\n",
			busnum, devnum);
		exit(1);
	}
	return result;
}

1596
1597
int main(int argc, char **argv)
{
1598
	bool uboot_autostart = false; /* flag for "uboot" command = U-Boot autostart */
1599
	bool pflag_active = false; /* -p switch, causing "write" to output progress */
1600
1601
	libusb_device_handle *handle;
	int busnum = -1, devnum = -1;
1602
#if defined(__linux__)
1603
	int iface_detached = -1;
1604
#endif
1605
1606

	if (argc <= 1) {
1607
		puts("sunxi-fel " VERSION "\n");
1608
1609
		printf("Usage: %s [options] command arguments... [command...]\n"
			"	-v, --verbose			Verbose logging\n"
1610
			"	-p, --progress			\"write\" transfers show a progress bar\n"
1611
			"	-d, --dev bus:devnum		Use specific USB bus and device number\n"
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
			"\n"
			"	spl file			Load and execute U-Boot SPL\n"
			"		If file additionally contains a main U-Boot binary\n"
			"		(u-boot-sunxi-with-spl.bin), this command also transfers that\n"
			"		to memory (default address from image), but won't execute it.\n"
			"\n"
			"	uboot file-with-spl		like \"spl\", but actually starts U-Boot\n"
			"		U-Boot execution will take place when the fel utility exits.\n"
			"		This allows combining \"uboot\" with further \"write\" commands\n"
			"		(to transfer other files needed for the boot).\n"
			"\n"
1623
1624
1625
			"	hex[dump] address length	Dumps memory region in hex\n"
			"	dump address length		Binary memory dump\n"
			"	exe[cute] address		Call function address\n"
1626
			"	reset64 address			RMR request for AArch64 warm boot\n"
1627
1628
			"	readl address			Read 32-bit value from device memory\n"
			"	writel address value		Write 32-bit value to device memory\n"
1629
			"	read address length file	Write memory contents into file\n"
1630
			"	write address file		Store file contents into memory\n"
1631
			"	write-with-progress addr file	\"write\" with progress bar\n"
1632
1633
			"	write-with-gauge addr file	Output progress for \"dialog --gauge\"\n"
			"	write-with-xgauge addr file	Extended gauge output (updates prompt)\n"
1634
1635
			"	multi[write] # addr file ...	\"write-with-progress\" multiple files,\n"
			"					sharing a common progress status\n"
1636
1637
1638
			"	multi[write]-with-gauge ...	like their \"write-with-*\" counterpart,\n"
			"	multi[write]-with-xgauge ...	  but following the 'multi' syntax:\n"
			"					  <#> addr file [addr file [...]]\n"
1639
			"	echo-gauge \"some text\"		Update prompt/caption for gauge output\n"
1640
			"	ver[sion]			Show BROM version\n"
1641
			"	sid				Retrieve and output 128-bit SID key\n"
1642
			"	clear address length		Clear memory\n"
Henrik Nordstrom's avatar
Henrik Nordstrom committed
1643
			"	fill address length value	Fill memory\n"
1644
1645
			, argv[0]
		);
1646
		exit(0);
1647
1648
	}

1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
	/* process all "prefix"-type arguments first */
	while (argc > 1) {
		if (strcmp(argv[1], "--verbose") == 0 || strcmp(argv[1], "-v") == 0)
			verbose = true;
		else if (strcmp(argv[1], "--progress") == 0 || strcmp(argv[1], "-p") == 0)
			pflag_active = true;
		else if (strncmp(argv[1], "--dev", 5) == 0 || strncmp(argv[1], "-d", 2) == 0) {
			char *dev_arg = argv[1];
			dev_arg += strspn(dev_arg, "-dev="); /* skip option chars, ignore '=' */
			if (*dev_arg == 0 && argc > 2) { /* at end of argument, use the next one instead */
				dev_arg = argv[2];
				argc -= 1;
				argv += 1;
			}
			if (sscanf(dev_arg, "%d:%d", &busnum, &devnum) != 2
			    || busnum <= 0 || devnum <= 0) {
				fprintf(stderr, "ERROR: Expected 'bus:devnum', got '%s'.\n", dev_arg);
				exit(1);
			}
		} else
			break; /* no valid (prefix) option detected, exit loop */
		argc -= 1;
		argv += 1;
1672
	}
1673

1674
1675
	int rc = libusb_init(NULL);
	assert(rc == 0);
1676
1677
	handle = open_fel_device(busnum, devnum, AW_USB_VENDOR_ID, AW_USB_PRODUCT_ID);
	assert(handle != NULL);
1678
	rc = libusb_claim_interface(handle, 0);
1679
1680
1681
1682
1683
1684
1685
#if defined(__linux__)
	if (rc != LIBUSB_SUCCESS) {
		libusb_detach_kernel_driver(handle, 0);
		iface_detached = 0;
		rc = libusb_claim_interface(handle, 0);
	}
#endif
1686
1687
	assert(rc == 0);

1688
1689
1690
1691
1692
	if (aw_fel_get_endpoint(handle)) {
		fprintf(stderr, "ERROR: Failed to get FEL mode endpoint addresses!\n");
		exit(1);
	}

1693
1694
	while (argc > 1 ) {
		int skip = 1;
1695

1696
		if (strncmp(argv[1], "hex", 3) == 0 && argc > 3) {
1697
1698
1699
1700
1701
			aw_fel_hexdump(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0));
			skip = 3;
		} else if (strncmp(argv[1], "dump", 4) == 0 && argc > 3) {
			aw_fel_dump(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0));
			skip = 3;
1702
1703
1704
1705
1706
1707
		} else if (strcmp(argv[1], "readl") == 0 && argc > 2) {
			printf("0x%08x\n", aw_fel_readl(handle, strtoul(argv[2], NULL, 0)));
			skip = 2;
		} else if (strcmp(argv[1], "writel") == 0 && argc > 3) {
			aw_fel_writel(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0));
			skip = 3;
1708
		} else if (strncmp(argv[1], "exe", 3) == 0 && argc > 2) {
1709
1710
			aw_fel_execute(handle, strtoul(argv[2], NULL, 0));
			skip=3;
1711
1712
1713
1714
1715
		} else if (strcmp(argv[1], "reset64") == 0 && argc > 2) {
			aw_rmr_request(handle, strtoul(argv[2], NULL, 0), true);
			/* Cancel U-Boot autostart, and stop processing args */
			uboot_autostart = false;
			break;
1716
		} else if (strncmp(argv[1], "ver", 3) == 0) {
1717
			aw_fel_print_version(handle);
1718
1719
		} else if (strcmp(argv[1], "sid") == 0) {
			aw_fel_print_sid(handle);
1720
		} else if (strcmp(argv[1], "write") == 0 && argc > 3) {
1721
1722
			skip += 2 * file_upload(handle, 1, argc - 2, argv + 2,
					pflag_active ? progress_bar : NULL);
1723
1724
1725
		} else if (strcmp(argv[1], "write-with-progress") == 0 && argc > 3) {
			skip += 2 * file_upload(handle, 1, argc - 2, argv + 2,
						progress_bar);
1726
1727
1728
1729
1730
1731
		} else if (strcmp(argv[1], "write-with-gauge") == 0 && argc > 3) {
			skip += 2 * file_upload(handle, 1, argc - 2, argv + 2,
						progress_gauge);
		} else if (strcmp(argv[1], "write-with-xgauge") == 0 && argc > 3) {
			skip += 2 * file_upload(handle, 1, argc - 2, argv + 2,
						progress_gauge_xxx);
1732
1733
1734
1735
1736
		} else if ((strcmp(argv[1], "multiwrite") == 0 ||
			    strcmp(argv[1], "multi") == 0) && argc > 4) {
			size_t count = strtoul(argv[2], NULL, 0); /* file count */
			skip = 2 + 2 * file_upload(handle, count, argc - 3,
						   argv + 3, progress_bar);
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
		} else if ((strcmp(argv[1], "multiwrite-with-gauge") == 0 ||
			    strcmp(argv[1], "multi-with-gauge") == 0) && argc > 4) {
			size_t count = strtoul(argv[2], NULL, 0); /* file count */
			skip = 2 + 2 * file_upload(handle, count, argc - 3,
						   argv + 3, progress_gauge);
		} else if ((strcmp(argv[1], "multiwrite-with-xgauge") == 0 ||
			    strcmp(argv[1], "multi-with-xgauge") == 0) && argc > 4) {
			size_t count = strtoul(argv[2], NULL, 0); /* file count */
			skip = 2 + 2 * file_upload(handle, count, argc - 3,
						   argv + 3, progress_gauge_xxx);
1747
1748
1749
1750
		} else if ((strcmp(argv[1], "echo-gauge") == 0) && argc > 2) {
			skip = 2;
			printf("XXX\n0\n%s\nXXX\n", argv[2]);
			fflush(stdout);
1751
1752
1753
1754
1755
1756
1757
		} else if (strcmp(argv[1], "read") == 0 && argc > 4) {
			size_t size = strtoul(argv[3], NULL, 0);
			void *buf = malloc(size);
			aw_fel_read(handle, strtoul(argv[2], NULL, 0), buf, size);
			save_file(argv[4], buf, size);
			free(buf);
			skip=4;
1758
		} else if (strcmp(argv[1], "clear") == 0 && argc > 2) {
Henrik Nordstrom's avatar
Henrik Nordstrom committed
1759
			aw_fel_fill(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0), 0);
1760
			skip=3;
Henrik Nordstrom's avatar
Henrik Nordstrom committed
1761
1762
1763
		} else if (strcmp(argv[1], "fill") == 0 && argc > 3) {
			aw_fel_fill(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0), (unsigned char)strtoul(argv[4], NULL, 0));
			skip=4;
1764
		} else if (strcmp(argv[1], "spl") == 0 && argc > 2) {
1765
1766
1767
1768
			aw_fel_process_spl_and_uboot(handle, argv[2]);
			skip=2;
		} else if (strcmp(argv[1], "uboot") == 0 && argc > 2) {
			aw_fel_process_spl_and_uboot(handle, argv[2]);
1769
1770
			uboot_autostart = (uboot_entry > 0 && uboot_size > 0);
			if (!uboot_autostart)
1771
				printf("Warning: \"uboot\" command failed to detect image! Can't execute U-Boot.\n");
1772
			skip=2;
1773
1774
1775
1776
1777
1778
1779
1780
		} else {
			fprintf(stderr,"Invalid command %s\n", argv[1]);
			exit(1);
		}
		argc-=skip;
		argv+=skip;
	}

Bernhard Nortmann's avatar
Bernhard Nortmann committed
1781
	/* auto-start U-Boot if requested (by the "uboot" command) */
1782
	if (uboot_autostart) {
1783
1784
1785
1786
		pr_info("Starting U-Boot (0x%08X).\n", uboot_entry);
		aw_fel_execute(handle, uboot_entry);
	}

1787
	libusb_release_interface(handle, 0);
1788
1789
1790
1791
#if defined(__linux__)
	if (iface_detached >= 0)
		libusb_attach_kernel_driver(handle, iface_detached);
#endif
1792
1793
	libusb_close(handle);
	libusb_exit(NULL);
1794

1795
1796
	return 0;
}