fdt_loader_cmd.c revision 248934
1116742Ssam/*-
2116904Ssam * Copyright (c) 2009-2010 The FreeBSD Foundation
3186904Ssam * All rights reserved.
4116742Ssam *
5116742Ssam * This software was developed by Semihalf under sponsorship from
6116742Ssam * the FreeBSD Foundation.
7116742Ssam *
8116742Ssam * Redistribution and use in source and binary forms, with or without
9116742Ssam * modification, are permitted provided that the following conditions
10116742Ssam * are met:
11116742Ssam * 1. Redistributions of source code must retain the above copyright
12116742Ssam *    notice, this list of conditions and the following disclaimer.
13116742Ssam * 2. Redistributions in binary form must reproduce the above copyright
14116742Ssam *    notice, this list of conditions and the following disclaimer in the
15116904Ssam *    documentation and/or other materials provided with the distribution.
16116904Ssam *
17116904Ssam * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18116904Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19116904Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20116904Ssam * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21116904Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22116904Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23116904Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24116904Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25116904Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26116742Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27116742Ssam * SUCH DAMAGE.
28116742Ssam */
29116742Ssam
30116742Ssam#include <sys/cdefs.h>
31116742Ssam__FBSDID("$FreeBSD: head/sys/boot/fdt/fdt_loader_cmd.c 248934 2013-03-30 16:33:16Z kientzle $");
32116742Ssam
33116742Ssam#include <stand.h>
34116742Ssam#include <fdt.h>
35116742Ssam#include <libfdt.h>
36116742Ssam#include <sys/param.h>
37116742Ssam#include <sys/linker.h>
38116742Ssam#include <machine/elf.h>
39191756Ssam
40191756Ssam#include "bootstrap.h"
41116742Ssam#include "glue.h"
42116742Ssam
43170530Ssam#ifdef DEBUG
44170530Ssam#define debugf(fmt, args...) do { printf("%s(): ", __func__);	\
45170530Ssam    printf(fmt,##args); } while (0)
46170530Ssam#else
47170530Ssam#define debugf(fmt, args...)
48138568Ssam#endif
49116742Ssam
50127903Ssam#define FDT_CWD_LEN	256
51127903Ssam#define FDT_MAX_DEPTH	6
52178952Ssam
53178952Ssam#define FDT_PROP_SEP	" = "
54178952Ssam
55178952Ssam#define STR(number) #number
56178952Ssam#define STRINGIFY(number) STR(number)
57127903Ssam
58116742Ssam#define COPYOUT(s,d,l)	archsw.arch_copyout(s, d, l)
59116742Ssam#define COPYIN(s,d,l)	archsw.arch_copyin(s, d, l)
60116742Ssam
61116742Ssam#define FDT_STATIC_DTB_SYMBOL	"fdt_static_dtb"
62170530Ssam
63170530Ssam#define	CMD_REQUIRES_BLOB	0x01
64170530Ssam
65170530Ssam/* Location of FDT yet to be loaded. */
66170530Ssam/* This may be in read-only memory, so can't be manipulated directly. */
67170530Ssamstatic struct fdt_header *fdt_to_load = NULL;
68116742Ssam/* Location of FDT on heap. */
69116742Ssam/* This is the copy we actually manipulate. */
70138568Ssamstatic struct fdt_header *fdtp = NULL;
71116742Ssam/* Size of FDT blob */
72127903Ssamstatic size_t fdtp_size = 0;
73170530Ssam/* Location of FDT in kernel or module. */
74170530Ssam/* This won't be set if FDT is loaded from disk or memory. */
75170530Ssam/* If it is set, we'll update it when fdt_copy() gets called. */
76170530Ssamstatic vm_offset_t fdtp_va = 0;
77170530Ssam
78170530Ssamstatic int fdt_load_dtb(vm_offset_t va);
79170530Ssam
80127903Ssamstatic int fdt_cmd_nyi(int argc, char *argv[]);
81127903Ssam
82138568Ssamstatic int fdt_cmd_addr(int argc, char *argv[]);
83127903Ssamstatic int fdt_cmd_mkprop(int argc, char *argv[]);
84127903Ssamstatic int fdt_cmd_cd(int argc, char *argv[]);
85170530Ssamstatic int fdt_cmd_hdr(int argc, char *argv[]);
86127903Ssamstatic int fdt_cmd_ls(int argc, char *argv[]);
87127903Ssamstatic int fdt_cmd_prop(int argc, char *argv[]);
88116742Ssamstatic int fdt_cmd_pwd(int argc, char *argv[]);
89170530Ssamstatic int fdt_cmd_rm(int argc, char *argv[]);
90170530Ssamstatic int fdt_cmd_mknode(int argc, char *argv[]);
91170530Ssamstatic int fdt_cmd_mres(int argc, char *argv[]);
92170530Ssam
93170530Ssamtypedef int cmdf_t(int, char *[]);
94170530Ssam
95170530Ssamstruct cmdtab {
96138568Ssam	char	*name;
97116742Ssam	cmdf_t	*handler;
98127903Ssam	int	flags;
99127903Ssam};
100170530Ssam
101170530Ssamstatic const struct cmdtab commands[] = {
102170530Ssam	{ "addr", &fdt_cmd_addr,	0 },
103170530Ssam	{ "alias", &fdt_cmd_nyi,	0 },
104170530Ssam	{ "cd", &fdt_cmd_cd,		CMD_REQUIRES_BLOB },
105170530Ssam	{ "header", &fdt_cmd_hdr,	CMD_REQUIRES_BLOB },
106170530Ssam	{ "ls", &fdt_cmd_ls,		CMD_REQUIRES_BLOB },
107170530Ssam	{ "mknode", &fdt_cmd_mknode,	CMD_REQUIRES_BLOB },
108138568Ssam	{ "mkprop", &fdt_cmd_mkprop,	CMD_REQUIRES_BLOB },
109127903Ssam	{ "mres", &fdt_cmd_mres,	CMD_REQUIRES_BLOB },
110116742Ssam	{ "prop", &fdt_cmd_prop,	CMD_REQUIRES_BLOB },
111116742Ssam	{ "pwd", &fdt_cmd_pwd,		CMD_REQUIRES_BLOB },
112116742Ssam	{ "rm", &fdt_cmd_rm,		CMD_REQUIRES_BLOB },
113116742Ssam	{ NULL, NULL }
114116742Ssam};
115116742Ssam
116116742Ssamstatic char cwd[FDT_CWD_LEN] = "/";
117116742Ssam
118116742Ssamstatic vm_offset_t
119116742Ssamfdt_find_static_dtb()
120116742Ssam{
121116742Ssam	Elf_Ehdr *ehdr;
122116742Ssam	Elf_Shdr *shdr;
123116742Ssam	Elf_Sym sym;
124116742Ssam	vm_offset_t strtab, symtab, fdt_start;
125116742Ssam	uint64_t offs;
126116742Ssam	struct preloaded_file *kfp;
127116742Ssam	struct file_metadata *md;
128116742Ssam	char *strp;
129116742Ssam	int i, sym_count;
130116742Ssam
131116742Ssam	sym_count = symtab = strtab = 0;
132116742Ssam	strp = NULL;
133170530Ssam
134218927Sbschmidt	offs = __elfN(relocation_offset);
135116742Ssam
136170530Ssam	kfp = file_findfile(NULL, NULL);
137192328Ssam	if (kfp == NULL)
138116742Ssam		return (0);
139116742Ssam
140116742Ssam	/* Locate the dynamic symbols and strtab. */
141116742Ssam	md = file_findmetadata(kfp, MODINFOMD_ELFHDR);
142116742Ssam	if (md == NULL)
143116742Ssam		return (0);
144116742Ssam	ehdr = (Elf_Ehdr *)md->md_data;
145116742Ssam
146116742Ssam	md = file_findmetadata(kfp, MODINFOMD_SHDR);
147116742Ssam	if (md == NULL)
148116742Ssam		return (0);
149116742Ssam	shdr = (Elf_Shdr *)md->md_data;
150116742Ssam
151116742Ssam	for (i = 0; i < ehdr->e_shnum; ++i) {
152116742Ssam		if (shdr[i].sh_type == SHT_DYNSYM && symtab == 0) {
153127903Ssam			symtab = shdr[i].sh_addr + offs;
154138568Ssam			sym_count = shdr[i].sh_size / sizeof(Elf_Sym);
155116742Ssam		} else if (shdr[i].sh_type == SHT_STRTAB && strtab == 0) {
156116742Ssam			strtab = shdr[i].sh_addr + offs;
157116742Ssam		}
158116742Ssam	}
159116742Ssam
160116742Ssam	/*
161116742Ssam	 * The most efficent way to find a symbol would be to calculate a
162193840Ssam	 * hash, find proper bucket and chain, and thus find a symbol.
163193840Ssam	 * However, that would involve code duplication (e.g. for hash
164193840Ssam	 * function). So we're using simpler and a bit slower way: we're
165116742Ssam	 * iterating through symbols, searching for the one which name is
166116742Ssam	 * 'equal' to 'fdt_static_dtb'. To speed up the process a little bit,
167116742Ssam	 * we are eliminating symbols type of which is not STT_NOTYPE, or(and)
168116742Ssam	 * those which binding attribute is not STB_GLOBAL.
169262007Skevlo	 */
170116742Ssam	fdt_start = 0;
171116742Ssam	while (sym_count > 0 && fdt_start == 0) {
172116742Ssam		COPYOUT(symtab, &sym, sizeof(sym));
173116742Ssam		symtab += sizeof(sym);
174116742Ssam		--sym_count;
175116742Ssam		if (ELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
176170530Ssam		    ELF_ST_TYPE(sym.st_info) != STT_NOTYPE)
177116742Ssam			continue;
178170530Ssam		strp = strdupout(strtab + sym.st_name);
179170530Ssam		if (strcmp(strp, FDT_STATIC_DTB_SYMBOL) == 0)
180170530Ssam			fdt_start = (vm_offset_t)sym.st_value + offs;
181170530Ssam		free(strp);
182170530Ssam	}
183170530Ssam	return (fdt_start);
184173273Ssam}
185173273Ssam
186173273Ssamstatic int
187173273Ssamfdt_load_dtb(vm_offset_t va)
188116742Ssam{
189195618Srpaulo	struct fdt_header header;
190116742Ssam	int err;
191127903Ssam
192127903Ssam	COPYOUT(va, &header, sizeof(header));
193170530Ssam	err = fdt_check_header(&header);
194170530Ssam	if (err < 0) {
195138568Ssam		if (err == -FDT_ERR_BADVERSION)
196138568Ssam			sprintf(command_errbuf,
197170530Ssam			    "incompatible blob version: %d, should be: %d",
198170530Ssam			    fdt_version(fdtp), FDT_LAST_SUPPORTED_VERSION);
199183243Ssam
200183243Ssam		else
201138568Ssam			sprintf(command_errbuf, "error validating blob: %s",
202232480Sadrian			    fdt_strerror(err));
203246807Smonthadar		return (1);
204232480Sadrian	}
205246807Smonthadar
206232480Sadrian	/*
207246807Smonthadar	 * Release previous blob
208232480Sadrian	 */
209127903Ssam	if (fdtp)
210138568Ssam		free(fdtp);
211138568Ssam
212138568Ssam	fdtp_size = fdt_totalsize(&header);
213138568Ssam	fdtp = malloc(fdtp_size);
214138568Ssam
215138568Ssam	if (fdtp == NULL) {
216116742Ssam		command_errmsg = "can't allocate memory for device tree copy";
217138568Ssam		return (1);
218138568Ssam	}
219138568Ssam
220170530Ssam	fdtp_va = va;
221170530Ssam	COPYOUT(va, fdtp, fdtp_size);
222170530Ssam	debugf("DTB blob found at 0x%jx, size: 0x%jx\n", (uintmax_t)va, (uintmax_t)fdtp_size);
223170530Ssam
224170530Ssam	return (0);
225170530Ssam}
226170530Ssam
227138568Ssamstatic int
228138568Ssamfdt_load_dtb_addr(struct fdt_header *header)
229138568Ssam{
230138568Ssam
231138568Ssam	// TODO: Verify that there really is an FDT at
232138568Ssam	// the specified location.
233170530Ssam	fdtp_size = fdt_totalsize(header);
234170530Ssam	free(fdtp);
235170530Ssam	if ((fdtp = malloc(fdtp_size)) == NULL) {
236170530Ssam		command_errmsg = "can't allocate memory for device tree copy";
237170530Ssam		return (1);
238170530Ssam	}
239170530Ssam
240170530Ssam	fdtp_va = 0; // Don't write this back into module or kernel.
241170530Ssam	bcopy(header, fdtp, fdtp_size);
242170530Ssam	return (0);
243170530Ssam}
244170530Ssam
245170530Ssamstatic int
246170530Ssamfdt_setup_fdtp()
247170530Ssam{
248170530Ssam  struct preloaded_file *bfp;
249170530Ssam  struct fdt_header *hdr;
250170530Ssam  const char *s;
251170530Ssam  char *p;
252170530Ssam  vm_offset_t va;
253170530Ssam
254170530Ssam  if ((bfp = file_findfile(NULL, "dtb")) != NULL) {
255138568Ssam	  printf("Using DTB from loaded file.\n");
256138568Ssam	  return fdt_load_dtb(bfp->f_addr);
257138568Ssam  }
258138568Ssam
259138568Ssam  if (fdt_to_load != NULL) {
260138568Ssam	  printf("Using DTB from memory address 0x%08X.\n",
261170530Ssam		 (unsigned int)fdt_to_load);
262170530Ssam	  return fdt_load_dtb_addr(fdt_to_load);
263170530Ssam  }
264138568Ssam
265138568Ssam  s = ub_env_get("fdtaddr");
266138568Ssam  if (s != NULL && *s != '\0') {
267170530Ssam	  hdr = (struct fdt_header *)strtoul(s, &p, 16);
268138568Ssam	  if (*p == '\0') {
269138568Ssam		  printf("Using DTB provided by U-Boot.\n");
270138568Ssam		  return fdt_load_dtb_addr(hdr);
271138568Ssam	  }
272138568Ssam  }
273138568Ssam
274138568Ssam  if ((va = fdt_find_static_dtb()) != 0) {
275138568Ssam	  printf("Using DTB compiled into kernel.\n");
276138568Ssam	  return (fdt_load_dtb(va));
277138568Ssam  }
278138568Ssam
279138568Ssam  command_errmsg = "no device tree blob found!";
280138568Ssam  return (1);
281138568Ssam}
282138568Ssam
283138568Ssam#define fdt_strtovect(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
284138568Ssam    (cellbuf), (lim), (cellsize), 0);
285138568Ssam
286138568Ssam/* Force using base 16 */
287173863Ssam#define fdt_strtovectx(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
288138568Ssam    (cellbuf), (lim), (cellsize), 16);
289138568Ssam
290138568Ssamstatic int
291138568Ssam_fdt_strtovect(char *str, void *cellbuf, int lim, unsigned char cellsize,
292138568Ssam    uint8_t base)
293138568Ssam{
294138568Ssam	char *buf = str;
295138568Ssam	char *end = str + strlen(str) - 2;
296170530Ssam	uint32_t *u32buf = NULL;
297170530Ssam	uint8_t *u8buf = NULL;
298170530Ssam	int cnt = 0;
299170530Ssam
300172055Ssam	if (cellsize == sizeof(uint32_t))
301170530Ssam		u32buf = (uint32_t *)cellbuf;
302170530Ssam	else
303138568Ssam		u8buf = (uint8_t *)cellbuf;
304170530Ssam
305138568Ssam	if (lim == 0)
306138568Ssam		return (0);
307138568Ssam
308138568Ssam	while (buf < end) {
309138568Ssam
310138568Ssam		/* Skip white whitespace(s)/separators */
311138568Ssam		while (!isxdigit(*buf) && buf < end)
312170530Ssam			buf++;
313170530Ssam
314170530Ssam		if (u32buf != NULL)
315170530Ssam			u32buf[cnt] =
316138568Ssam			    cpu_to_fdt32((uint32_t)strtol(buf, NULL, base));
317138568Ssam
318138568Ssam		else
319138568Ssam			u8buf[cnt] = (uint8_t)strtol(buf, NULL, base);
320138568Ssam
321170530Ssam		if (cnt + 1 <= lim - 1)
322170530Ssam			cnt++;
323170530Ssam		else
324170530Ssam			break;
325170530Ssam		buf++;
326170530Ssam		/* Find another number */
327170530Ssam		while ((isxdigit(*buf) || *buf == 'x') && buf < end)
328170530Ssam			buf++;
329170530Ssam	}
330193542Ssam	return (cnt);
331193542Ssam}
332193542Ssam
333170530Ssam#define	TMP_MAX_ETH	8
334172055Ssam
335232479Sadrianstatic void
336234874Smonthadarfixup_ethernet(const char *env, char *ethstr, int *eth_no, int len)
337234874Smonthadar{
338193542Ssam	char *end, *str;
339170530Ssam	uint8_t tmp_addr[6];
340170530Ssam	int i, n;
341170530Ssam
342170530Ssam	/* Extract interface number */
343170530Ssam	i = strtol(env + 3, &end, 10);
344170530Ssam	if (end == (env + 3))
345170530Ssam		/* 'ethaddr' means interface 0 address */
346170530Ssam		n = 0;
347170530Ssam	else
348170530Ssam		n = i;
349170530Ssam
350170530Ssam	if (n > TMP_MAX_ETH)
351170530Ssam		return;
352172055Ssam
353170530Ssam	str = ub_env_get(env);
354170530Ssam
355173618Ssam	/* Convert macaddr string into a vector of uints */
356170530Ssam	fdt_strtovectx(str, &tmp_addr, 6, sizeof(uint8_t));
357170530Ssam	if (n != 0) {
358173618Ssam		i = strlen(env) - 7;
359173618Ssam		strncpy(ethstr + 8, env + 3, i);
360173618Ssam	}
361173618Ssam	/* Set actual property to a value from vect */
362173618Ssam	fdt_setprop(fdtp, fdt_path_offset(fdtp, ethstr),
363173618Ssam	    "local-mac-address", &tmp_addr, 6 * sizeof(uint8_t));
364173618Ssam
365170530Ssam	/* Clear ethernet..XXXX.. string */
366170530Ssam	bzero(ethstr + 8, len - 8);
367170530Ssam
368170530Ssam	if (n + 1 > *eth_no)
369170530Ssam		*eth_no = n + 1;
370170530Ssam}
371170530Ssam
372170530Ssamstatic void
373170530Ssamfixup_cpubusfreqs(unsigned long cpufreq, unsigned long busfreq)
374170530Ssam{
375170530Ssam	int lo, o = 0, o2, maxo = 0, depth;
376170530Ssam	const uint32_t zero = 0;
377170530Ssam
378170530Ssam	/* We want to modify every subnode of /cpus */
379170530Ssam	o = fdt_path_offset(fdtp, "/cpus");
380170530Ssam	if (o < 0)
381170530Ssam		return;
382170530Ssam
383170530Ssam	/* maxo should contain offset of node next to /cpus */
384170530Ssam	depth = 0;
385170530Ssam	maxo = o;
386170530Ssam	while (depth != -1)
387170530Ssam		maxo = fdt_next_node(fdtp, maxo, &depth);
388170530Ssam
389170530Ssam	/* Find CPU frequency properties */
390170530Ssam	o = fdt_node_offset_by_prop_value(fdtp, o, "clock-frequency",
391170530Ssam	    &zero, sizeof(uint32_t));
392170530Ssam
393170530Ssam	o2 = fdt_node_offset_by_prop_value(fdtp, o, "bus-frequency", &zero,
394170530Ssam	    sizeof(uint32_t));
395170530Ssam
396170530Ssam	lo = MIN(o, o2);
397170530Ssam
398170530Ssam	while (o != -FDT_ERR_NOTFOUND && o2 != -FDT_ERR_NOTFOUND) {
399170530Ssam
400170530Ssam		o = fdt_node_offset_by_prop_value(fdtp, lo,
401170530Ssam		    "clock-frequency", &zero, sizeof(uint32_t));
402170530Ssam
403170530Ssam		o2 = fdt_node_offset_by_prop_value(fdtp, lo, "bus-frequency",
404170530Ssam		    &zero, sizeof(uint32_t));
405170530Ssam
406170530Ssam		/* We're only interested in /cpus subnode(s) */
407170530Ssam		if (lo > maxo)
408170530Ssam			break;
409170530Ssam
410170530Ssam		fdt_setprop_inplace_cell(fdtp, lo, "clock-frequency",
411170530Ssam		    (uint32_t)cpufreq);
412170530Ssam
413170530Ssam		fdt_setprop_inplace_cell(fdtp, lo, "bus-frequency",
414170530Ssam		    (uint32_t)busfreq);
415170530Ssam
416170530Ssam		lo = MIN(o, o2);
417170530Ssam	}
418170530Ssam}
419170530Ssam
420170530Ssamstatic int
421182820Ssamfdt_reg_valid(uint32_t *reg, int len, int addr_cells, int size_cells)
422182820Ssam{
423182820Ssam	int cells_in_tuple, i, tuples, tuple_size;
424170530Ssam	uint32_t cur_start, cur_size;
425182820Ssam
426182820Ssam	cells_in_tuple = (addr_cells + size_cells);
427182820Ssam	tuple_size = cells_in_tuple * sizeof(uint32_t);
428182820Ssam	tuples = len / tuple_size;
429170530Ssam	if (tuples == 0)
430170530Ssam		return (EINVAL);
431170530Ssam
432170530Ssam	for (i = 0; i < tuples; i++) {
433170530Ssam		if (addr_cells == 2)
434138568Ssam			cur_start = fdt64_to_cpu(reg[i * cells_in_tuple]);
435120098Ssam		else
436120098Ssam			cur_start = fdt32_to_cpu(reg[i * cells_in_tuple]);
437120098Ssam
438170530Ssam		if (size_cells == 2)
439170530Ssam			cur_size = fdt64_to_cpu(reg[i * cells_in_tuple + 2]);
440170530Ssam		else
441170530Ssam			cur_size = fdt32_to_cpu(reg[i * cells_in_tuple + 1]);
442120098Ssam
443138568Ssam		if (cur_size == 0)
444120098Ssam			return (EINVAL);
445120098Ssam
446170530Ssam		debugf(" reg#%d (start: 0x%0x size: 0x%0x) valid!\n",
447170530Ssam		    i, cur_start, cur_size);
448170530Ssam	}
449170530Ssam	return (0);
450120098Ssam}
451138568Ssam
452120098Ssamstatic void
453120098Ssamfixup_memory(struct sys_info *si)
454170530Ssam{
455170530Ssam	struct mem_region *curmr;
456170530Ssam	uint32_t addr_cells, size_cells;
457120098Ssam	uint32_t *addr_cellsp, *reg,  *size_cellsp;
458138568Ssam	int err, i, len, memory, realmrno, root;
459120098Ssam	uint8_t *buf, *sb;
460120098Ssam	uint64_t rstart, rsize;
461170530Ssam	int reserved;
462170530Ssam
463170530Ssam	root = fdt_path_offset(fdtp, "/");
464120098Ssam	if (root < 0) {
465138568Ssam		sprintf(command_errbuf, "Could not find root node !");
466120098Ssam		return;
467120098Ssam	}
468170530Ssam
469170530Ssam	memory = fdt_path_offset(fdtp, "/memory");
470170530Ssam	if (memory <= 0) {
471170530Ssam		/* Create proper '/memory' node. */
472120098Ssam		memory = fdt_add_subnode(fdtp, root, "memory");
473138568Ssam		if (memory <= 0) {
474120098Ssam			sprintf(command_errbuf, "Could not fixup '/memory' "
475120098Ssam			    "node, error code : %d!\n", memory);
476170530Ssam			return;
477170530Ssam		}
478170530Ssam
479170530Ssam		err = fdt_setprop(fdtp, memory, "device_type", "memory",
480120098Ssam		    sizeof("memory"));
481138568Ssam
482120098Ssam		if (err < 0)
483170530Ssam			return;
484170530Ssam	}
485170530Ssam
486170530Ssam	addr_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#address-cells",
487170530Ssam	    NULL);
488170530Ssam	size_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#size-cells", NULL);
489170530Ssam
490170530Ssam	if (addr_cellsp == NULL || size_cellsp == NULL) {
491170530Ssam		sprintf(command_errbuf, "Could not fixup '/memory' node : "
492170530Ssam		    "%s %s property not found in root node!\n",
493120098Ssam		    (!addr_cellsp) ? "#address-cells" : "",
494116742Ssam		    (!size_cellsp) ? "#size-cells" : "");
495116742Ssam		return;
496116742Ssam	}
497116742Ssam
498116742Ssam	addr_cells = fdt32_to_cpu(*addr_cellsp);
499116742Ssam	size_cells = fdt32_to_cpu(*size_cellsp);
500116742Ssam
501116742Ssam	/*
502116742Ssam	 * Convert memreserve data to memreserve property
503116742Ssam	 * Check if property already exists
504116742Ssam	 */
505116742Ssam	reserved = fdt_num_mem_rsv(fdtp);
506116742Ssam	if (reserved &&
507116742Ssam	    (fdt_getprop(fdtp, root, "memreserve", NULL) == NULL)) {
508116742Ssam		len = (addr_cells + size_cells) * reserved * sizeof(uint32_t);
509116742Ssam		sb = buf = (uint8_t *)malloc(len);
510116742Ssam		if (!buf)
511116742Ssam			return;
512116742Ssam
513116742Ssam		bzero(buf, len);
514116742Ssam
515116742Ssam		for (i = 0; i < reserved; i++) {
516116742Ssam			curmr = &si->mr[i];
517116742Ssam			if (fdt_get_mem_rsv(fdtp, i, &rstart, &rsize))
518172055Ssam				break;
519172055Ssam			if (rsize) {
520116742Ssam				/* Ensure endianess, and put cells into a buffer */
521127903Ssam				if (addr_cells == 2)
522127903Ssam					*(uint64_t *)buf =
523116742Ssam					    cpu_to_fdt64(rstart);
524116742Ssam				else
525116742Ssam					*(uint32_t *)buf =
526187797Ssam					    cpu_to_fdt32(rstart);
527187797Ssam
528187797Ssam				buf += sizeof(uint32_t) * addr_cells;
529187797Ssam				if (size_cells == 2)
530187797Ssam					*(uint64_t *)buf =
531116742Ssam					    cpu_to_fdt64(rsize);
532127903Ssam				else
533127903Ssam					*(uint32_t *)buf =
534127903Ssam					    cpu_to_fdt32(rsize);
535170530Ssam
536170530Ssam				buf += sizeof(uint32_t) * size_cells;
537170530Ssam			}
538170530Ssam		}
539170530Ssam
540170530Ssam		/* Set property */
541170530Ssam		if ((err = fdt_setprop(fdtp, root, "memreserve", sb, len)) < 0)
542170530Ssam			printf("Could not fixup 'memreserve' property.\n");
543170530Ssam
544170530Ssam		free(sb);
545170530Ssam	}
546170530Ssam
547170530Ssam	/* Count valid memory regions entries in sysinfo. */
548138568Ssam	realmrno = si->mr_no;
549127903Ssam	for (i = 0; i < si->mr_no; i++)
550127903Ssam		if (si->mr[i].start == 0 && si->mr[i].size == 0)
551170530Ssam			realmrno--;
552170530Ssam
553170530Ssam	if (realmrno == 0) {
554170530Ssam		sprintf(command_errbuf, "Could not fixup '/memory' node : "
555170530Ssam		    "sysinfo doesn't contain valid memory regions info!\n");
556170530Ssam		return;
557170530Ssam	}
558170530Ssam
559170530Ssam	if ((reg = (uint32_t *)fdt_getprop(fdtp, memory, "reg",
560170530Ssam	    &len)) != NULL) {
561170530Ssam
562170530Ssam		if (fdt_reg_valid(reg, len, addr_cells, size_cells) == 0)
563170530Ssam			/*
564170530Ssam			 * Do not apply fixup if existing 'reg' property
565170530Ssam			 * seems to be valid.
566170530Ssam			 */
567170530Ssam			return;
568170530Ssam	}
569183243Ssam
570170530Ssam	len = (addr_cells + size_cells) * realmrno * sizeof(uint32_t);
571170530Ssam	sb = buf = (uint8_t *)malloc(len);
572183243Ssam	if (!buf)
573170530Ssam		return;
574170530Ssam
575170530Ssam	bzero(buf, len);
576170530Ssam
577170530Ssam	for (i = 0; i < si->mr_no; i++) {
578170530Ssam		curmr = &si->mr[i];
579170530Ssam		if (curmr->size != 0) {
580170530Ssam			/* Ensure endianess, and put cells into a buffer */
581170530Ssam			if (addr_cells == 2)
582170530Ssam				*(uint64_t *)buf =
583170530Ssam				    cpu_to_fdt64(curmr->start);
584170530Ssam			else
585170530Ssam				*(uint32_t *)buf =
586170530Ssam				    cpu_to_fdt32(curmr->start);
587170530Ssam
588170530Ssam			buf += sizeof(uint32_t) * addr_cells;
589170530Ssam			if (size_cells == 2)
590170530Ssam				*(uint64_t *)buf =
591187797Ssam				    cpu_to_fdt64(curmr->size);
592187797Ssam			else
593187797Ssam				*(uint32_t *)buf =
594187797Ssam				    cpu_to_fdt32(curmr->size);
595187797Ssam
596170530Ssam			buf += sizeof(uint32_t) * size_cells;
597170530Ssam		}
598170530Ssam	}
599173273Ssam
600173273Ssam	/* Set property */
601173273Ssam	if ((err = fdt_setprop(fdtp, memory, "reg", sb, len)) < 0)
602173273Ssam		sprintf(command_errbuf, "Could not fixup '/memory' node.\n");
603170530Ssam
604170530Ssam	free(sb);
605173273Ssam}
606173273Ssam
607173273Ssamstatic void
608173273Ssamfixup_stdout(const char *env)
609173273Ssam{
610173273Ssam	const char *str;
611173273Ssam	char *ptr;
612173273Ssam	int serialno;
613170530Ssam	int len, no, sero;
614170530Ssam	const struct fdt_property *prop;
615170530Ssam	char *tmp[10];
616170530Ssam
617170530Ssam	str = ub_env_get(env);
618170530Ssam	ptr = (char *)str + strlen(str) - 1;
619170530Ssam	while (ptr > str && isdigit(*(str - 1)))
620170530Ssam		str--;
621170530Ssam
622170530Ssam	if (ptr == str)
623170530Ssam		return;
624170530Ssam
625170530Ssam	serialno = (int)strtol(ptr, NULL, 0);
626170530Ssam	no = fdt_path_offset(fdtp, "/chosen");
627170530Ssam	if (no < 0)
628170530Ssam		return;
629170530Ssam
630170530Ssam	prop = fdt_get_property(fdtp, no, "stdout", &len);
631170530Ssam
632170530Ssam	/* If /chosen/stdout does not extist, create it */
633170530Ssam	if (prop == NULL || (prop != NULL && len == 0)) {
634170530Ssam
635170530Ssam		bzero(tmp, 10 * sizeof(char));
636170530Ssam		strcpy((char *)&tmp, "serial");
637170530Ssam		if (strlen(ptr) > 3)
638170530Ssam			/* Serial number too long */
639172055Ssam			return;
640172055Ssam
641170530Ssam		strncpy((char *)tmp + 6, ptr, 3);
642172055Ssam		sero = fdt_path_offset(fdtp, (const char *)tmp);
643170530Ssam		if (sero < 0)
644170530Ssam			/*
645170530Ssam			 * If serial device we're trying to assign
646170530Ssam			 * stdout to doesn't exist in DT -- return.
647170530Ssam			 */
648170530Ssam			return;
649170530Ssam
650170530Ssam		fdt_setprop(fdtp, no, "stdout", &tmp,
651170530Ssam		    strlen((char *)&tmp) + 1);
652170530Ssam		fdt_setprop(fdtp, no, "stdin", &tmp,
653170530Ssam		    strlen((char *)&tmp) + 1);
654170530Ssam	}
655170530Ssam}
656170530Ssam
657170530Ssam/*
658170530Ssam * Locate the blob, fix it up and return its location.
659170530Ssam */
660170530Ssamstatic int
661170530Ssamfdt_fixup(void)
662170530Ssam{
663170530Ssam	const char *env;
664170530Ssam	char *ethstr;
665170530Ssam	int chosen, err, eth_no, len;
666170530Ssam	struct sys_info *si;
667170530Ssam
668172055Ssam	env = NULL;
669172055Ssam	eth_no = 0;
670172055Ssam	ethstr = NULL;
671170530Ssam	len = 0;
672170530Ssam
673170530Ssam	if (fdtp == NULL) {
674170530Ssam		err = fdt_setup_fdtp();
675170530Ssam		if (err) {
676170530Ssam			sprintf(command_errbuf, "No valid device tree blob found!");
677170530Ssam			return (0);
678170530Ssam		}
679170530Ssam	}
680170530Ssam
681170530Ssam	/* Create /chosen node (if not exists) */
682170530Ssam	if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
683170530Ssam	    -FDT_ERR_NOTFOUND)
684170530Ssam		chosen = fdt_add_subnode(fdtp, 0, "chosen");
685170530Ssam
686170530Ssam	/* Value assigned to fixup-applied does not matter. */
687170530Ssam	if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
688138568Ssam		return (1);
689116742Ssam
690116742Ssam	/* Acquire sys_info */
691116742Ssam	si = ub_get_sys_info();
692138568Ssam
693138568Ssam	while ((env = ub_env_enum(env)) != NULL) {
694138568Ssam		if (strncmp(env, "eth", 3) == 0 &&
695138568Ssam		    strncmp(env + (strlen(env) - 4), "addr", 4) == 0) {
696138568Ssam			/*
697138568Ssam			 * Handle Ethernet addrs: parse uboot env eth%daddr
698138568Ssam			 */
699138568Ssam
700138568Ssam			if (!eth_no) {
701127903Ssam				/*
702170530Ssam				 * Check how many chars we will need to store
703170530Ssam				 * maximal eth iface number.
704170530Ssam				 */
705170530Ssam				len = strlen(STRINGIFY(TMP_MAX_ETH)) +
706170530Ssam				    strlen("ethernet");
707193439Ssam
708170530Ssam				/*
709170530Ssam				 * Reserve mem for string "ethernet" and len
710170530Ssam				 * chars for iface no.
711170530Ssam				 */
712138568Ssam				ethstr = (char *)malloc(len * sizeof(char));
713170530Ssam				bzero(ethstr, len * sizeof(char));
714253639Srpaulo				strcpy(ethstr, "ethernet0");
715138568Ssam			}
716138568Ssam
717170530Ssam			/* Modify blob */
718138568Ssam			fixup_ethernet(env, ethstr, &eth_no, len);
719138568Ssam
720138568Ssam		} else if (strcmp(env, "consoledev") == 0)
721195618Srpaulo			fixup_stdout(env);
722195618Srpaulo	}
723231187Sadrian
724231187Sadrian	/* Modify cpu(s) and bus clock frequenties in /cpus node [Hz] */
725231187Sadrian	fixup_cpubusfreqs(si->clk_cpu, si->clk_bus);
726231187Sadrian
727195618Srpaulo	/* Fixup memory regions */
728231187Sadrian	fixup_memory(si);
729231187Sadrian
730231187Sadrian	fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
731231187Sadrian	return (1);
732231187Sadrian}
733231187Sadrian
734231187Sadrian/*
735231187Sadrian * Copy DTB blob to specified location and return size
736231187Sadrian */
737231187Sadrianint
738234892Smonthadarfdt_copy(vm_offset_t va)
739231187Sadrian{
740231187Sadrian	int err;
741231187Sadrian
742231187Sadrian	if (fdtp == NULL) {
743231187Sadrian		err = fdt_setup_fdtp();
744231187Sadrian		if (err) {
745231187Sadrian			printf("No valid device tree blob found!");
746231187Sadrian			return (0);
747231187Sadrian		}
748231187Sadrian	}
749116742Ssam
750116742Ssam	if (fdt_fixup() == 0)
751138568Ssam		return (0);
752170530Ssam
753170530Ssam	if (fdtp_va != 0) {
754170530Ssam		/* Overwrite the FDT with the fixed version. */
755170530Ssam		/* XXX Is this really appropriate? */
756170530Ssam		COPYIN(fdtp, fdtp_va, fdtp_size);
757170530Ssam	}
758138568Ssam	COPYIN(fdtp, va, fdtp_size);
759127903Ssam	return (fdtp_size);
760138568Ssam}
761170530Ssam
762170530Ssam
763170530Ssam
764138568Ssamint
765170530Ssamcommand_fdt_internal(int argc, char *argv[])
766170530Ssam{
767170530Ssam	cmdf_t *cmdh;
768178354Ssam	int flags;
769138568Ssam	char *cmd;
770116742Ssam	int i, err;
771178354Ssam
772178354Ssam	if (argc < 2) {
773178354Ssam		command_errmsg = "usage is 'fdt <command> [<args>]";
774178354Ssam		return (CMD_ERROR);
775170530Ssam	}
776239142Sadrian
777172055Ssam	/*
778227331Sadrian	 * Validate fdt <command>.
779227331Sadrian	 */
780227331Sadrian	cmd = strdup(argv[1]);
781227331Sadrian	i = 0;
782227331Sadrian	cmdh = NULL;
783227331Sadrian	while (!(commands[i].name == NULL)) {
784227331Sadrian		if (strcmp(cmd, commands[i].name) == 0) {
785227331Sadrian			/* found it */
786227331Sadrian			cmdh = commands[i].handler;
787227331Sadrian			flags = commands[i].flags;
788227331Sadrian			break;
789227331Sadrian		}
790172055Ssam		i++;
791172055Ssam	}
792172055Ssam	if (cmdh == NULL) {
793172055Ssam		command_errmsg = "unknown command";
794172055Ssam		return (CMD_ERROR);
795172055Ssam	}
796172055Ssam
797172055Ssam	if (flags & CMD_REQUIRES_BLOB) {
798193439Ssam		/*
799193439Ssam		 * Check if uboot env vars were parsed already. If not, do it now.
800193439Ssam		 */
801193439Ssam		if (fdt_fixup() == 0)
802193439Ssam			return (CMD_ERROR);
803193439Ssam	}
804193439Ssam
805193439Ssam	/*
806172055Ssam	 * Call command handler.
807138568Ssam	 */
808138568Ssam	err = (*cmdh)(argc, argv);
809138568Ssam
810116742Ssam	return (err);
811138568Ssam}
812138568Ssam
813138568Ssamstatic int
814116742Ssamfdt_cmd_addr(int argc, char *argv[])
815187797Ssam{
816187797Ssam	struct preloaded_file *fp;
817187797Ssam	struct fdt_header *hdr;
818170530Ssam	const char *addr;
819190455Ssam	char *cp;
820127903Ssam
821190455Ssam	fdt_to_load = NULL;
822190455Ssam
823190455Ssam	if (argc > 2)
824190455Ssam		addr = argv[2];
825170530Ssam	else {
826170530Ssam		sprintf(command_errbuf, "no address specified");
827170530Ssam		return (CMD_ERROR);
828170530Ssam	}
829127903Ssam
830127903Ssam	hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
831138568Ssam	if (cp == addr) {
832127903Ssam		sprintf(command_errbuf, "Invalid address: %s", addr);
833127903Ssam		return (CMD_ERROR);
834127903Ssam	}
835127903Ssam
836127903Ssam	while ((fp = file_findfile(NULL, "dtb")) != NULL) {
837127903Ssam		file_discard(fp);
838127903Ssam	}
839127903Ssam
840127903Ssam	fdt_to_load = hdr;
841127903Ssam	return (CMD_OK);
842127903Ssam}
843181347Ssam
844181347Ssamstatic int
845138568Ssamfdt_cmd_cd(int argc, char *argv[])
846138568Ssam{
847138568Ssam	char *path;
848138568Ssam	char tmp[FDT_CWD_LEN];
849138568Ssam	int len, o;
850138568Ssam
851138568Ssam	path = (argc > 2) ? argv[2] : "/";
852138568Ssam
853138568Ssam	if (path[0] == '/') {
854138568Ssam		len = strlen(path);
855138568Ssam		if (len >= FDT_CWD_LEN)
856138568Ssam			goto fail;
857138568Ssam	} else {
858138568Ssam		/* Handle path specification relative to cwd */
859138568Ssam		len = strlen(cwd) + strlen(path) + 1;
860138568Ssam		if (len >= FDT_CWD_LEN)
861138568Ssam			goto fail;
862138568Ssam
863138568Ssam		strcpy(tmp, cwd);
864138568Ssam		strcat(tmp, "/");
865138568Ssam		strcat(tmp, path);
866138568Ssam		path = tmp;
867138568Ssam	}
868138568Ssam
869138568Ssam	o = fdt_path_offset(fdtp, path);
870138568Ssam	if (o < 0) {
871138568Ssam		sprintf(command_errbuf, "could not find node: '%s'", path);
872138568Ssam		return (CMD_ERROR);
873116742Ssam	}
874116742Ssam
875116742Ssam	strcpy(cwd, path);
876116742Ssam	return (CMD_OK);
877116742Ssam
878116742Ssamfail:
879116742Ssam	sprintf(command_errbuf, "path too long: %d, max allowed: %d",
880116742Ssam	    len, FDT_CWD_LEN - 1);
881172055Ssam	return (CMD_ERROR);
882116742Ssam}
883116742Ssam
884172055Ssamstatic int
885172055Ssamfdt_cmd_hdr(int argc __unused, char *argv[] __unused)
886116742Ssam{
887138568Ssam	char line[80];
888138568Ssam	int ver;
889138568Ssam
890116742Ssam	if (fdtp == NULL) {
891116742Ssam		command_errmsg = "no device tree blob pointer?!";
892116742Ssam		return (CMD_ERROR);
893116742Ssam	}
894116742Ssam
895116742Ssam	ver = fdt_version(fdtp);
896116742Ssam	pager_open();
897116742Ssam	sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
898116742Ssam	pager_output(line);
899116742Ssam	sprintf(line, " magic                   = 0x%08x\n", fdt_magic(fdtp));
900116742Ssam	pager_output(line);
901116742Ssam	sprintf(line, " size                    = %d\n", fdt_totalsize(fdtp));
902116742Ssam	pager_output(line);
903116742Ssam	sprintf(line, " off_dt_struct           = 0x%08x\n",
904172055Ssam	    fdt_off_dt_struct(fdtp));
905116742Ssam	pager_output(line);
906172055Ssam	sprintf(line, " off_dt_strings          = 0x%08x\n",
907172055Ssam	    fdt_off_dt_strings(fdtp));
908172055Ssam	pager_output(line);
909172055Ssam	sprintf(line, " off_mem_rsvmap          = 0x%08x\n",
910116742Ssam	    fdt_off_mem_rsvmap(fdtp));
911116742Ssam	pager_output(line);
912116742Ssam	sprintf(line, " version                 = %d\n", ver);
913116742Ssam	pager_output(line);
914116742Ssam	sprintf(line, " last compatible version = %d\n",
915116742Ssam	    fdt_last_comp_version(fdtp));
916116742Ssam	pager_output(line);
917116742Ssam	if (ver >= 2) {
918116742Ssam		sprintf(line, " boot_cpuid              = %d\n",
919116742Ssam		    fdt_boot_cpuid_phys(fdtp));
920116742Ssam		pager_output(line);
921116742Ssam	}
922116742Ssam	if (ver >= 3) {
923172055Ssam		sprintf(line, " size_dt_strings         = %d\n",
924172055Ssam		    fdt_size_dt_strings(fdtp));
925172055Ssam		pager_output(line);
926172055Ssam	}
927172055Ssam	if (ver >= 17) {
928172055Ssam		sprintf(line, " size_dt_struct          = %d\n",
929172055Ssam		    fdt_size_dt_struct(fdtp));
930172055Ssam		pager_output(line);
931172055Ssam	}
932172055Ssam	pager_close();
933172055Ssam
934172055Ssam	return (CMD_OK);
935172055Ssam}
936172055Ssam
937182820Ssamstatic int
938182820Ssamfdt_cmd_ls(int argc, char *argv[])
939182820Ssam{
940182820Ssam	const char *prevname[FDT_MAX_DEPTH] = { NULL };
941182820Ssam	const char *name;
942182820Ssam	char *path;
943182820Ssam	int i, o, depth, len;
944182820Ssam
945116742Ssam	path = (argc > 2) ? argv[2] : NULL;
946231058Sadrian	if (path == NULL)
947231058Sadrian		path = cwd;
948231058Sadrian
949231058Sadrian	o = fdt_path_offset(fdtp, path);
950231058Sadrian	if (o < 0) {
951231058Sadrian		sprintf(command_errbuf, "could not find node: '%s'", path);
952231058Sadrian		return (CMD_ERROR);
953231058Sadrian	}
954231058Sadrian
955231058Sadrian	for (depth = 0;
956231058Sadrian	    (o >= 0) && (depth >= 0);
957231058Sadrian	    o = fdt_next_node(fdtp, o, &depth)) {
958231058Sadrian
959231058Sadrian		name = fdt_get_name(fdtp, o, &len);
960231058Sadrian
961195618Srpaulo		if (depth > FDT_MAX_DEPTH) {
962116742Ssam			printf("max depth exceeded: %d\n", depth);
963116742Ssam			continue;
964116742Ssam		}
965116742Ssam
966116742Ssam		prevname[depth] = name;
967116742Ssam
968116742Ssam		/* Skip root (i = 1) when printing devices */
969116742Ssam		for (i = 1; i <= depth; i++) {
970116742Ssam			if (prevname[i] == NULL)
971116742Ssam				break;
972116742Ssam
973172055Ssam			if (strcmp(cwd, "/") == 0)
974172055Ssam				printf("/");
975172055Ssam			printf("%s", prevname[i]);
976172055Ssam		}
977172055Ssam		printf("\n");
978172055Ssam	}
979172055Ssam
980172055Ssam	return (CMD_OK);
981193542Ssam}
982172055Ssam
983172055Ssamstatic __inline int
984172055Ssamisprint(int c)
985172055Ssam{
986172055Ssam
987172055Ssam	return (c >= ' ' && c <= 0x7e);
988172055Ssam}
989116742Ssam
990116742Ssamstatic int
991138568Ssamfdt_isprint(const void *data, int len, int *count)
992138568Ssam{
993138568Ssam	const char *d;
994138568Ssam	char ch;
995178354Ssam	int yesno, i;
996178354Ssam
997178354Ssam	if (len == 0)
998138568Ssam		return (0);
999116742Ssam
1000138568Ssam	d = (const char *)data;
1001138568Ssam	if (d[len - 1] != '\0')
1002138568Ssam		return (0);
1003138568Ssam
1004138568Ssam	*count = 0;
1005138568Ssam	yesno = 1;
1006138568Ssam	for (i = 0; i < len; i++) {
1007138568Ssam		ch = *(d + i);
1008138568Ssam		if (isprint(ch) || (ch == '\0' && i > 0)) {
1009138568Ssam			/* Count strings */
1010116742Ssam			if (ch == '\0')
1011138568Ssam				(*count)++;
1012138568Ssam			continue;
1013124457Ssam		}
1014124457Ssam
1015124457Ssam		yesno = 0;
1016124457Ssam		break;
1017124457Ssam	}
1018124457Ssam
1019124457Ssam	return (yesno);
1020138568Ssam}
1021138568Ssam
1022124457Ssamstatic int
1023138568Ssamfdt_data_str(const void *data, int len, int count, char **buf)
1024116742Ssam{
1025138568Ssam	char *b, *tmp;
1026138568Ssam	const char *d;
1027120098Ssam	int buf_len, i, l;
1028120098Ssam
1029116742Ssam	/*
1030138568Ssam	 * Calculate the length for the string and allocate memory.
1031138568Ssam	 *
1032138568Ssam	 * Note that 'len' already includes at least one terminator.
1033178354Ssam	 */
1034178354Ssam	buf_len = len;
1035178354Ssam	if (count > 1) {
1036178354Ssam		/*
1037138568Ssam		 * Each token had already a terminator buried in 'len', but we
1038138568Ssam		 * only need one eventually, don't count space for these.
1039138568Ssam		 */
1040138568Ssam		buf_len -= count - 1;
1041138568Ssam
1042116742Ssam		/* Each consecutive token requires a ", " separator. */
1043116742Ssam		buf_len += count * 2;
1044148291Ssam	}
1045148291Ssam
1046148291Ssam	/* Add some space for surrounding double quotes. */
1047116742Ssam	buf_len += count * 2;
1048138568Ssam
1049148291Ssam	/* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1050116742Ssam	b = (char *)malloc(buf_len);
1051148291Ssam	tmp = (char *)malloc(buf_len);
1052148291Ssam	if (b == NULL)
1053148291Ssam		goto error;
1054148291Ssam
1055148291Ssam	if (tmp == NULL) {
1056148291Ssam		free(b);
1057148291Ssam		goto error;
1058160685Ssam	}
1059160685Ssam
1060160685Ssam	b[0] = '\0';
1061160685Ssam
1062160685Ssam	/*
1063160685Ssam	 * Now that we have space, format the string.
1064160685Ssam	 */
1065160685Ssam	i = 0;
1066160685Ssam	do {
1067160685Ssam		d = (const char *)data + i;
1068160685Ssam		l = strlen(d) + 1;
1069160685Ssam
1070160685Ssam		sprintf(tmp, "\"%s\"%s", d,
1071160685Ssam		    (i + l) < len ?  ", " : "");
1072160685Ssam		strcat(b, tmp);
1073160685Ssam
1074160685Ssam		i += l;
1075160685Ssam
1076160685Ssam	} while (i < len);
1077160685Ssam	*buf = b;
1078160685Ssam
1079160685Ssam	free(tmp);
1080160685Ssam
1081160685Ssam	return (0);
1082170530Ssamerror:
1083170530Ssam	return (1);
1084170530Ssam}
1085170530Ssam
1086170530Ssamstatic int
1087170530Ssamfdt_data_cell(const void *data, int len, char **buf)
1088170530Ssam{
1089170530Ssam	char *b, *tmp;
1090170530Ssam	const uint32_t *c;
1091170530Ssam	int count, i, l;
1092170530Ssam
1093170530Ssam	/* Number of cells */
1094170530Ssam	count = len / 4;
1095170530Ssam
1096170530Ssam	/*
1097170530Ssam	 * Calculate the length for the string and allocate memory.
1098170530Ssam	 */
1099170530Ssam
1100170530Ssam	/* Each byte translates to 2 output characters */
1101170530Ssam	l = len * 2;
1102170530Ssam	if (count > 1) {
1103170530Ssam		/* Each consecutive cell requires a " " separator. */
1104170530Ssam		l += (count - 1) * 1;
1105170530Ssam	}
1106170530Ssam	/* Each cell will have a "0x" prefix */
1107170530Ssam	l += count * 2;
1108170530Ssam	/* Space for surrounding <> and terminator */
1109170530Ssam	l += 3;
1110170530Ssam
1111170530Ssam	b = (char *)malloc(l);
1112170530Ssam	tmp = (char *)malloc(l);
1113170530Ssam	if (b == NULL)
1114170530Ssam		goto error;
1115170530Ssam
1116170530Ssam	if (tmp == NULL) {
1117170530Ssam		free(b);
1118116742Ssam		goto error;
1119	}
1120
1121	b[0] = '\0';
1122	strcat(b, "<");
1123
1124	for (i = 0; i < len; i += 4) {
1125		c = (const uint32_t *)((const uint8_t *)data + i);
1126		sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1127		    i < (len - 4) ? " " : "");
1128		strcat(b, tmp);
1129	}
1130	strcat(b, ">");
1131	*buf = b;
1132
1133	free(tmp);
1134
1135	return (0);
1136error:
1137	return (1);
1138}
1139
1140static int
1141fdt_data_bytes(const void *data, int len, char **buf)
1142{
1143	char *b, *tmp;
1144	const char *d;
1145	int i, l;
1146
1147	/*
1148	 * Calculate the length for the string and allocate memory.
1149	 */
1150
1151	/* Each byte translates to 2 output characters */
1152	l = len * 2;
1153	if (len > 1)
1154		/* Each consecutive byte requires a " " separator. */
1155		l += (len - 1) * 1;
1156	/* Each byte will have a "0x" prefix */
1157	l += len * 2;
1158	/* Space for surrounding [] and terminator. */
1159	l += 3;
1160
1161	b = (char *)malloc(l);
1162	tmp = (char *)malloc(l);
1163	if (b == NULL)
1164		goto error;
1165
1166	if (tmp == NULL) {
1167		free(b);
1168		goto error;
1169	}
1170
1171	b[0] = '\0';
1172	strcat(b, "[");
1173
1174	for (i = 0, d = data; i < len; i++) {
1175		sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1176		strcat(b, tmp);
1177	}
1178	strcat(b, "]");
1179	*buf = b;
1180
1181	free(tmp);
1182
1183	return (0);
1184error:
1185	return (1);
1186}
1187
1188static int
1189fdt_data_fmt(const void *data, int len, char **buf)
1190{
1191	int count;
1192
1193	if (len == 0) {
1194		*buf = NULL;
1195		return (1);
1196	}
1197
1198	if (fdt_isprint(data, len, &count))
1199		return (fdt_data_str(data, len, count, buf));
1200
1201	else if ((len % 4) == 0)
1202		return (fdt_data_cell(data, len, buf));
1203
1204	else
1205		return (fdt_data_bytes(data, len, buf));
1206}
1207
1208static int
1209fdt_prop(int offset)
1210{
1211	char *line, *buf;
1212	const struct fdt_property *prop;
1213	const char *name;
1214	const void *data;
1215	int len, rv;
1216
1217	line = NULL;
1218	prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1219	if (prop == NULL)
1220		return (1);
1221
1222	name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1223	len = fdt32_to_cpu(prop->len);
1224
1225	rv = 0;
1226	buf = NULL;
1227	if (len == 0) {
1228		/* Property without value */
1229		line = (char *)malloc(strlen(name) + 2);
1230		if (line == NULL) {
1231			rv = 2;
1232			goto out2;
1233		}
1234		sprintf(line, "%s\n", name);
1235		goto out1;
1236	}
1237
1238	/*
1239	 * Process property with value
1240	 */
1241	data = prop->data;
1242
1243	if (fdt_data_fmt(data, len, &buf) != 0) {
1244		rv = 3;
1245		goto out2;
1246	}
1247
1248	line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1249	    strlen(buf) + 2);
1250	if (line == NULL) {
1251		sprintf(command_errbuf, "could not allocate space for string");
1252		rv = 4;
1253		goto out2;
1254	}
1255
1256	sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1257
1258out1:
1259	pager_open();
1260	pager_output(line);
1261	pager_close();
1262
1263out2:
1264	if (buf)
1265		free(buf);
1266
1267	if (line)
1268		free(line);
1269
1270	return (rv);
1271}
1272
1273static int
1274fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1275{
1276	uint32_t cells[100];
1277	char *buf;
1278	int len, rv;
1279	const struct fdt_property *p;
1280
1281	p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1282
1283	if (p != NULL) {
1284		if (mode == 1) {
1285			 /* Adding inexistant value in mode 1 is forbidden */
1286			sprintf(command_errbuf, "property already exists!");
1287			return (CMD_ERROR);
1288		}
1289	} else if (mode == 0) {
1290		sprintf(command_errbuf, "property does not exist!");
1291		return (CMD_ERROR);
1292	}
1293	len = strlen(value);
1294	rv = 0;
1295	buf = (char *)value;
1296
1297	switch (*buf) {
1298	case '&':
1299		/* phandles */
1300		break;
1301	case '<':
1302		/* Data cells */
1303		len = fdt_strtovect(buf, (void *)&cells, 100,
1304		    sizeof(uint32_t));
1305
1306		rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1307		    len * sizeof(uint32_t));
1308		break;
1309	case '[':
1310		/* Data bytes */
1311		len = fdt_strtovect(buf, (void *)&cells, 100,
1312		    sizeof(uint8_t));
1313
1314		rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1315		    len * sizeof(uint8_t));
1316		break;
1317	case '"':
1318	default:
1319		/* Default -- string */
1320		rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1321		break;
1322	}
1323
1324	if (rv != 0) {
1325		if (rv == -FDT_ERR_NOSPACE)
1326			sprintf(command_errbuf,
1327			    "Device tree blob is too small!\n");
1328		else
1329			sprintf(command_errbuf,
1330			    "Could not add/modify property!\n");
1331	}
1332	return (rv);
1333}
1334
1335/* Merge strings from argv into a single string */
1336static int
1337fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1338{
1339	char *buf;
1340	int i, idx, sz;
1341
1342	*buffer = NULL;
1343	sz = 0;
1344
1345	for (i = start; i < argc; i++)
1346		sz += strlen(argv[i]);
1347
1348	/* Additional bytes for whitespaces between args */
1349	sz += argc - start;
1350
1351	buf = (char *)malloc(sizeof(char) * sz);
1352	bzero(buf, sizeof(char) * sz);
1353
1354	if (buf == NULL) {
1355		sprintf(command_errbuf, "could not allocate space "
1356		    "for string");
1357		return (1);
1358	}
1359
1360	idx = 0;
1361	for (i = start, idx = 0; i < argc; i++) {
1362		strcpy(buf + idx, argv[i]);
1363		idx += strlen(argv[i]);
1364		buf[idx] = ' ';
1365		idx++;
1366	}
1367	buf[sz - 1] = '\0';
1368	*buffer = buf;
1369	return (0);
1370}
1371
1372/* Extract offset and name of node/property from a given path */
1373static int
1374fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1375{
1376	int o;
1377	char *path = *pathp, *name = NULL, *subpath = NULL;
1378
1379	subpath = strrchr(path, '/');
1380	if (subpath == NULL) {
1381		o = fdt_path_offset(fdtp, cwd);
1382		name = path;
1383		path = (char *)&cwd;
1384	} else {
1385		*subpath = '\0';
1386		if (strlen(path) == 0)
1387			path = cwd;
1388
1389		name = subpath + 1;
1390		o = fdt_path_offset(fdtp, path);
1391	}
1392
1393	if (strlen(name) == 0) {
1394		sprintf(command_errbuf, "name not specified");
1395		return (1);
1396	}
1397	if (o < 0) {
1398		sprintf(command_errbuf, "could not find node: '%s'", path);
1399		return (1);
1400	}
1401	*namep = name;
1402	*nodeoff = o;
1403	*pathp = path;
1404	return (0);
1405}
1406
1407static int
1408fdt_cmd_prop(int argc, char *argv[])
1409{
1410	char *path, *propname, *value;
1411	int o, next, depth, rv;
1412	uint32_t tag;
1413
1414	path = (argc > 2) ? argv[2] : NULL;
1415
1416	value = NULL;
1417
1418	if (argc > 3) {
1419		/* Merge property value strings into one */
1420		if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1421			return (CMD_ERROR);
1422	} else
1423		value = NULL;
1424
1425	if (path == NULL)
1426		path = cwd;
1427
1428	rv = CMD_OK;
1429
1430	if (value) {
1431		/* If value is specified -- try to modify prop. */
1432		if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1433			return (CMD_ERROR);
1434
1435		rv = fdt_modprop(o, propname, value, 0);
1436		if (rv)
1437			return (CMD_ERROR);
1438		return (CMD_OK);
1439
1440	}
1441	/* User wants to display properties */
1442	o = fdt_path_offset(fdtp, path);
1443
1444	if (o < 0) {
1445		sprintf(command_errbuf, "could not find node: '%s'", path);
1446		rv = CMD_ERROR;
1447		goto out;
1448	}
1449
1450	depth = 0;
1451	while (depth >= 0) {
1452		tag = fdt_next_tag(fdtp, o, &next);
1453		switch (tag) {
1454		case FDT_NOP:
1455			break;
1456		case FDT_PROP:
1457			if (depth > 1)
1458				/* Don't process properties of nested nodes */
1459				break;
1460
1461			if (fdt_prop(o) != 0) {
1462				sprintf(command_errbuf, "could not process "
1463				    "property");
1464				rv = CMD_ERROR;
1465				goto out;
1466			}
1467			break;
1468		case FDT_BEGIN_NODE:
1469			depth++;
1470			if (depth > FDT_MAX_DEPTH) {
1471				printf("warning: nesting too deep: %d\n",
1472				    depth);
1473				goto out;
1474			}
1475			break;
1476		case FDT_END_NODE:
1477			depth--;
1478			if (depth == 0)
1479				/*
1480				 * This is the end of our starting node, force
1481				 * the loop finish.
1482				 */
1483				depth--;
1484			break;
1485		}
1486		o = next;
1487	}
1488out:
1489	return (rv);
1490}
1491
1492static int
1493fdt_cmd_mkprop(int argc, char *argv[])
1494{
1495	int o;
1496	char *path, *propname, *value;
1497
1498	path = (argc > 2) ? argv[2] : NULL;
1499
1500	value = NULL;
1501
1502	if (argc > 3) {
1503		/* Merge property value strings into one */
1504		if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1505			return (CMD_ERROR);
1506	} else
1507		value = NULL;
1508
1509	if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1510		return (CMD_ERROR);
1511
1512	if (fdt_modprop(o, propname, value, 1))
1513		return (CMD_ERROR);
1514
1515	return (CMD_OK);
1516}
1517
1518static int
1519fdt_cmd_rm(int argc, char *argv[])
1520{
1521	int o, rv;
1522	char *path = NULL, *propname;
1523
1524	if (argc > 2)
1525		path = argv[2];
1526	else {
1527		sprintf(command_errbuf, "no node/property name specified");
1528		return (CMD_ERROR);
1529	}
1530
1531	o = fdt_path_offset(fdtp, path);
1532	if (o < 0) {
1533		/* If node not found -- try to find & delete property */
1534		if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1535			return (CMD_ERROR);
1536
1537		if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1538			sprintf(command_errbuf, "could not delete"
1539			    "%s\n", (rv == -FDT_ERR_NOTFOUND) ?
1540			    "(property/node does not exist)" : "");
1541			return (CMD_ERROR);
1542
1543		} else
1544			return (CMD_OK);
1545	}
1546	/* If node exists -- remove node */
1547	rv = fdt_del_node(fdtp, o);
1548	if (rv) {
1549		sprintf(command_errbuf, "could not delete node");
1550		return (CMD_ERROR);
1551	}
1552	return (CMD_OK);
1553}
1554
1555static int
1556fdt_cmd_mknode(int argc, char *argv[])
1557{
1558	int o, rv;
1559	char *path = NULL, *nodename = NULL;
1560
1561	if (argc > 2)
1562		path = argv[2];
1563	else {
1564		sprintf(command_errbuf, "no node name specified");
1565		return (CMD_ERROR);
1566	}
1567
1568	if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1569		return (CMD_ERROR);
1570
1571	rv = fdt_add_subnode(fdtp, o, nodename);
1572
1573	if (rv < 0) {
1574		if (rv == -FDT_ERR_NOSPACE)
1575			sprintf(command_errbuf,
1576			    "Device tree blob is too small!\n");
1577		else
1578			sprintf(command_errbuf,
1579			    "Could not add node!\n");
1580		return (CMD_ERROR);
1581	}
1582	return (CMD_OK);
1583}
1584
1585static int
1586fdt_cmd_pwd(int argc, char *argv[])
1587{
1588	char line[FDT_CWD_LEN];
1589
1590	pager_open();
1591	sprintf(line, "%s\n", cwd);
1592	pager_output(line);
1593	pager_close();
1594	return (CMD_OK);
1595}
1596
1597static int
1598fdt_cmd_mres(int argc, char *argv[])
1599{
1600	uint64_t start, size;
1601	int i, total;
1602	char line[80];
1603
1604	pager_open();
1605	total = fdt_num_mem_rsv(fdtp);
1606	if (total > 0) {
1607		pager_output("Reserved memory regions:\n");
1608		for (i = 0; i < total; i++) {
1609			fdt_get_mem_rsv(fdtp, i, &start, &size);
1610			sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1611			    i, start, size);
1612			pager_output(line);
1613		}
1614	} else
1615		pager_output("No reserved memory regions\n");
1616	pager_close();
1617
1618	return (CMD_OK);
1619}
1620
1621static int
1622fdt_cmd_nyi(int argc, char *argv[])
1623{
1624
1625	printf("command not yet implemented\n");
1626	return (CMD_ERROR);
1627}
1628