1/* $NetBSD: fdtbus.c,v 1.46 2022/03/04 08:19:06 skrll Exp $ */
2
3/*-
4 * Copyright (c) 2015 Jared D. McNeill <jmcneill@invisible.ca>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__KERNEL_RCSID(0, "$NetBSD: fdtbus.c,v 1.46 2022/03/04 08:19:06 skrll Exp $");
31
32#include <sys/param.h>
33#include <sys/systm.h>
34#include <sys/device.h>
35#include <sys/kmem.h>
36#include <sys/cpu.h>
37
38#include <sys/bus.h>
39
40#include <dev/ofw/openfirm.h>
41
42#include <dev/fdt/fdtvar.h>
43
44#include <libfdt.h>
45
46#include "locators.h"
47
48#define	FDT_MAX_PATH	256
49
50struct fdt_node {
51	device_t	n_bus;
52	device_t	n_dev;
53	int		n_phandle;
54	const char	*n_name;
55	struct fdt_attach_args n_faa;
56
57	int		n_cfpass;
58	cfdata_t	n_cf;
59
60	u_int		n_order;
61
62	bool		n_pinctrl_init;
63
64	TAILQ_ENTRY(fdt_node) n_nodes;
65};
66
67static TAILQ_HEAD(, fdt_node) fdt_nodes =
68    TAILQ_HEAD_INITIALIZER(fdt_nodes);
69static bool fdt_need_rescan = false;
70
71struct fdt_softc {
72	device_t	sc_dev;
73	int		sc_phandle;
74	struct fdt_attach_args sc_faa;
75};
76
77static int	fdt_match(device_t, cfdata_t, void *);
78static void	fdt_attach(device_t, device_t, void *);
79static int	fdt_rescan(device_t, const char *, const int *);
80static void	fdt_childdet(device_t, device_t);
81
82static int	fdt_scan_submatch(device_t, cfdata_t, const int *, void *);
83static void	fdt_scan_best(struct fdt_softc *, struct fdt_node *);
84static void	fdt_scan(struct fdt_softc *, int);
85static void	fdt_add_node(struct fdt_node *);
86static u_int	fdt_get_order(int);
87static void	fdt_pre_attach(struct fdt_node *);
88static void	fdt_post_attach(struct fdt_node *);
89
90static const struct device_compatible_entry compat_data[] = {
91	{ .compat = "simple-bus" },
92	{ .compat = "simple-pm-bus" },
93	DEVICE_COMPAT_EOL
94};
95
96CFATTACH_DECL2_NEW(simplebus, sizeof(struct fdt_softc),
97    fdt_match, fdt_attach, NULL, NULL, fdt_rescan, fdt_childdet);
98
99static int
100fdt_match(device_t parent, cfdata_t cf, void *aux)
101{
102	const struct fdt_attach_args *faa = aux;
103	const int phandle = faa->faa_phandle;
104	int match;
105
106	/* Check compatible string */
107	match = of_compatible_match(phandle, compat_data);
108	if (match)
109		return match;
110
111	/* Some nodes have no compatible string */
112	if (!of_hasprop(phandle, "compatible")) {
113		if (OF_finddevice("/clocks") == phandle)
114			return 1;
115		if (OF_finddevice("/chosen") == phandle)
116			return 1;
117	}
118
119	/* Always match the root node */
120	return OF_finddevice("/") == phandle;
121}
122
123static void
124fdt_attach(device_t parent, device_t self, void *aux)
125{
126	struct fdt_softc *sc = device_private(self);
127	const struct fdt_attach_args *faa = aux;
128	const int phandle = faa->faa_phandle;
129	const char *descr, *model;
130
131	sc->sc_dev = self;
132	sc->sc_phandle = phandle;
133	sc->sc_faa = *faa;
134
135	aprint_naive("\n");
136
137	descr = fdtbus_get_string(phandle, "model");
138	if (descr)
139		aprint_normal(": %s\n", descr);
140	else
141		aprint_normal("\n");
142
143	/* Find all child nodes */
144	fdt_add_bus(self, phandle, &sc->sc_faa);
145
146	/* Only the root bus should scan for devices */
147	if (OF_finddevice("/") != faa->faa_phandle)
148		return;
149
150	/* Set hw.model if available */
151	model = fdtbus_get_string(phandle, "compatible");
152	if (model)
153		cpu_setmodel("%s", model);
154	else if (descr)
155		cpu_setmodel("%s", descr);
156
157	/* Scan devices */
158	fdt_rescan(self, NULL, NULL);
159}
160
161static int
162fdt_rescan(device_t self, const char *ifattr, const int *locs)
163{
164	struct fdt_softc *sc = device_private(self);
165	struct fdt_node *node;
166	int pass;
167
168	TAILQ_FOREACH(node, &fdt_nodes, n_nodes)
169		fdt_scan_best(sc, node);
170
171	pass = 0;
172	fdt_need_rescan = false;
173	do {
174		fdt_scan(sc, pass);
175		if (fdt_need_rescan == true) {
176			pass = 0;
177			TAILQ_FOREACH(node, &fdt_nodes, n_nodes) {
178				if (node->n_cfpass == -1)
179					fdt_scan_best(sc, node);
180			}
181			fdt_need_rescan = false;
182		} else {
183			pass++;
184		}
185	} while (pass <= FDTCF_PASS_DEFAULT);
186
187	return 0;
188}
189
190static void
191fdt_childdet(device_t parent, device_t child)
192{
193	struct fdt_node *node;
194
195	TAILQ_FOREACH(node, &fdt_nodes, n_nodes)
196		if (node->n_dev == child) {
197			node->n_dev = NULL;
198			break;
199		}
200}
201
202static void
203fdt_init_attach_args(const struct fdt_attach_args *faa_tmpl, struct fdt_node *node,
204    bool quiet, struct fdt_attach_args *faa)
205{
206	*faa = *faa_tmpl;
207	faa->faa_phandle = node->n_phandle;
208	faa->faa_name = node->n_name;
209	faa->faa_quiet = quiet;
210	faa->faa_bst = node->n_faa.faa_bst;
211	faa->faa_dmat = fdtbus_iommu_map(node->n_phandle, 0,
212	   node->n_faa.faa_dmat);
213}
214
215static bool
216fdt_add_bus_stdmatch(void *arg, int child)
217{
218	return fdtbus_status_okay(child);
219}
220
221void
222fdt_add_bus(device_t bus, const int phandle, struct fdt_attach_args *faa)
223{
224	fdt_add_bus_match(bus, phandle, faa, fdt_add_bus_stdmatch, NULL);
225}
226
227void
228fdt_add_bus_match(device_t bus, const int phandle, struct fdt_attach_args *faa,
229    bool (*fn)(void *, int), void *fnarg)
230{
231	int child;
232
233	for (child = OF_child(phandle); child; child = OF_peer(child)) {
234		if (fn && !fn(fnarg, child))
235			continue;
236
237		fdt_add_child(bus, child, faa, fdt_get_order(child));
238	}
239}
240
241static int
242fdt_dma_translate(int phandle, struct fdt_dma_range **ranges, u_int *nranges)
243{
244	const uint8_t *data;
245	int len, n;
246
247	const int parent = OF_parent(phandle);
248	if (parent == -1)
249		return 1;	/* done searching */
250
251	data = fdtbus_get_prop(phandle, "dma-ranges", &len);
252	if (data == NULL)
253		return 1;	/* no dma-ranges property, stop searching */
254
255	if (len == 0)
256		return 0;	/* dma-ranges property is empty, keep going */
257
258	const int addr_cells = fdtbus_get_addr_cells(phandle);
259	const int size_cells = fdtbus_get_size_cells(phandle);
260	const int paddr_cells = fdtbus_get_addr_cells(parent);
261	if (addr_cells == -1 || size_cells == -1 || paddr_cells == -1)
262		return 1;
263
264	const int entry_size = (addr_cells + paddr_cells + size_cells) * 4;
265
266	*nranges = len / entry_size;
267	*ranges = kmem_alloc(sizeof(struct fdt_dma_range) * *nranges, KM_SLEEP);
268	for (n = 0; len >= entry_size; n++, len -= entry_size) {
269		const uint64_t cba = fdtbus_get_cells(data, addr_cells);
270		data += addr_cells * 4;
271		const uint64_t pba = fdtbus_get_cells(data, paddr_cells);
272		data += paddr_cells * 4;
273		const uint64_t cl = fdtbus_get_cells(data, size_cells);
274		data += size_cells * 4;
275
276		(*ranges)[n].dr_sysbase = pba;
277		(*ranges)[n].dr_busbase = cba;
278		(*ranges)[n].dr_len = cl;
279	}
280
281	return 1;
282}
283
284static bus_dma_tag_t
285fdt_get_dma_tag(struct fdt_node *node)
286{
287	struct fdt_dma_range *ranges = NULL;
288	u_int nranges = 0;
289	int parent;
290
291	parent = OF_parent(node->n_phandle);
292	while (parent != -1) {
293		if (fdt_dma_translate(parent, &ranges, &nranges) != 0)
294			break;
295		parent = OF_parent(parent);
296	}
297
298	return fdtbus_dma_tag_create(node->n_phandle, ranges, nranges);
299}
300
301static uint32_t
302fdt_bus_flags(int phandle, uint32_t *flags)
303{
304	if (of_hasprop(phandle, "nonposted-mmio")) {
305		*flags |= FDT_BUS_SPACE_FLAG_NONPOSTED_MMIO;
306		return 1;
307	}
308
309	return 0;
310}
311
312static bus_space_tag_t
313fdt_get_bus_tag(struct fdt_node *node)
314{
315	uint32_t flags = 0;
316	int parent;
317
318	parent = OF_parent(node->n_phandle);
319	while (parent != -1) {
320		if (fdt_bus_flags(parent, &flags) != 0) {
321			break;
322		}
323		parent = OF_parent(parent);
324	}
325
326	return fdtbus_bus_tag_create(node->n_phandle, flags);
327}
328
329void
330fdt_add_child(device_t bus, const int child, struct fdt_attach_args *faa,
331    u_int order)
332{
333	struct fdt_node *node;
334
335	/* Add the node to our device list */
336	node = kmem_zalloc(sizeof(*node), KM_SLEEP);
337	node->n_bus = bus;
338	node->n_dev = NULL;
339	node->n_phandle = child;
340	node->n_name = fdtbus_get_string(child, "name");
341	node->n_cfpass = -1;
342	node->n_cf = NULL;
343	node->n_order = order;
344	node->n_faa = *faa;
345	node->n_faa.faa_phandle = child;
346	node->n_faa.faa_name = node->n_name;
347	node->n_faa.faa_bst = fdt_get_bus_tag(node);
348	node->n_faa.faa_dmat = fdt_get_dma_tag(node);
349
350	fdt_add_node(node);
351	fdt_need_rescan = true;
352}
353
354static int
355fdt_scan_submatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
356{
357	if (locs[FDTCF_PASS] != FDTCF_PASS_DEFAULT &&
358	    locs[FDTCF_PASS] != cf->cf_loc[FDTCF_PASS])
359		return 0;
360
361	return config_stdsubmatch(parent, cf, locs, aux);
362}
363
364static void
365fdt_scan_best(struct fdt_softc *sc, struct fdt_node *node)
366{
367	struct fdt_attach_args faa;
368	cfdata_t cf, best_cf;
369	int match, best_match, best_pass;
370
371	best_cf = NULL;
372	best_match = 0;
373	best_pass = FDTCF_PASS_DEFAULT;
374
375	for (int pass = 0; pass <= FDTCF_PASS_DEFAULT; pass++) {
376		const int locs[FDTCF_NLOCS] = {
377			[FDTCF_PASS] = pass
378		};
379		fdt_init_attach_args(&sc->sc_faa, node, true, &faa);
380		cf = config_search(node->n_bus, &faa,
381		    CFARGS(.submatch = fdt_scan_submatch,
382			   .iattr = "fdt",
383			   .locators = locs));
384		if (cf == NULL)
385			continue;
386		match = config_match(node->n_bus, cf, &faa);
387		if (match > best_match) {
388			best_match = match;
389			best_cf = cf;
390			best_pass = pass;
391		}
392	}
393
394	node->n_cf = best_cf;
395	node->n_cfpass = best_pass;
396}
397
398static void
399fdt_scan(struct fdt_softc *sc, int pass)
400{
401	struct fdt_node *node;
402	struct fdt_attach_args faa;
403	const int locs[FDTCF_NLOCS] = {
404		[FDTCF_PASS] = pass
405	};
406	bool quiet = pass != FDTCF_PASS_DEFAULT;
407
408	TAILQ_FOREACH(node, &fdt_nodes, n_nodes) {
409		if (node->n_cfpass != pass || node->n_dev != NULL)
410			continue;
411
412		fdt_init_attach_args(&sc->sc_faa, node, quiet, &faa);
413
414		if (quiet && node->n_cf == NULL) {
415			/*
416			 * No match for this device, skip it.
417			 */
418			continue;
419		}
420
421		/*
422		 * Attach the device.
423		 */
424		fdt_pre_attach(node);
425
426		devhandle_t nodeh = device_handle(node->n_bus);
427
428		if (quiet) {
429			node->n_dev = config_attach(node->n_bus, node->n_cf,
430			    &faa, fdtbus_print,
431			    CFARGS(.locators = locs,
432				   .devhandle =
433				       devhandle_from_of(nodeh,
434							 node->n_phandle)));
435		} else {
436			/*
437			 * Default pass.
438			 */
439			node->n_dev = config_found(node->n_bus, &faa,
440			    fdtbus_print,
441			    CFARGS(.submatch = fdt_scan_submatch,
442				   .iattr = "fdt",
443				   .locators = locs,
444				   .devhandle =
445				       devhandle_from_of(nodeh,
446							 node->n_phandle)));
447		}
448
449		if (node->n_dev != NULL)
450			fdt_post_attach(node);
451	}
452}
453
454static void
455fdt_pre_attach(struct fdt_node *node)
456{
457	const char *cfgname;
458	int error;
459
460	node->n_pinctrl_init = fdtbus_pinctrl_has_config(node->n_phandle, "init");
461
462	cfgname = node->n_pinctrl_init ? "init" : "default";
463
464	aprint_debug_dev(node->n_bus, "set %s config for %s\n", cfgname, node->n_name);
465
466	error = fdtbus_pinctrl_set_config(node->n_phandle, cfgname);
467	if (error != 0 && error != ENOENT)
468		aprint_debug_dev(node->n_bus,
469		    "failed to set %s config on %s: %d\n",
470		    cfgname, node->n_name, error);
471
472	fdtbus_powerdomain_enable(node->n_phandle);
473}
474
475static void
476fdt_post_attach(struct fdt_node *node)
477{
478	char buf[FDT_MAX_PATH];
479	prop_dictionary_t dict;
480	int error;
481
482	dict = device_properties(node->n_dev);
483	if (fdtbus_get_path(node->n_phandle, buf, sizeof(buf)))
484		prop_dictionary_set_string(dict, "fdt-path", buf);
485
486	if (node->n_pinctrl_init) {
487		aprint_debug_dev(node->n_bus, "set default config for %s\n", node->n_name);
488		error = fdtbus_pinctrl_set_config(node->n_phandle, "default");
489		if (error != 0 && error != ENOENT)
490			aprint_debug_dev(node->n_bus,
491			    "failed to set default config on %s: %d\n",
492			    node->n_name, error);
493	}
494}
495
496static void
497fdt_add_node(struct fdt_node *new_node)
498{
499	struct fdt_node *node;
500
501	TAILQ_FOREACH(node, &fdt_nodes, n_nodes)
502		if (node->n_order > new_node->n_order) {
503			TAILQ_INSERT_BEFORE(node, new_node, n_nodes);
504			return;
505		}
506	TAILQ_INSERT_TAIL(&fdt_nodes, new_node, n_nodes);
507}
508
509void
510fdt_remove_byhandle(int phandle)
511{
512	struct fdt_node *node;
513
514	TAILQ_FOREACH(node, &fdt_nodes, n_nodes) {
515		if (node->n_phandle == phandle) {
516			TAILQ_REMOVE(&fdt_nodes, node, n_nodes);
517			return;
518		}
519	}
520}
521
522void
523fdt_remove_bycompat(const char *compatible[])
524{
525	struct fdt_node *node, *next;
526
527	TAILQ_FOREACH_SAFE(node, &fdt_nodes, n_nodes, next) {
528		if (of_compatible(node->n_phandle, compatible)) {
529			TAILQ_REMOVE(&fdt_nodes, node, n_nodes);
530		}
531	}
532}
533
534int
535fdt_find_with_property(const char *prop, int *pindex)
536{
537	struct fdt_node *node;
538	int index = 0;
539
540	TAILQ_FOREACH(node, &fdt_nodes, n_nodes) {
541		if (index++ < *pindex)
542			continue;
543		if (of_hasprop(node->n_phandle, prop)) {
544			*pindex = index;
545			return node->n_phandle;
546		}
547	}
548
549	return -1;
550}
551
552static u_int
553fdt_get_order(int phandle)
554{
555	u_int val = UINT_MAX;
556	int child;
557
558	of_getprop_uint32(phandle, "phandle", &val);
559
560	for (child = OF_child(phandle); child; child = OF_peer(child)) {
561		u_int child_val = fdt_get_order(child);
562		if (child_val < val)
563			val = child_val;
564	}
565
566	return val;
567}
568
569int
570fdtbus_print(void *aux, const char *pnp)
571{
572	const struct fdt_attach_args * const faa = aux;
573	char buf[FDT_MAX_PATH];
574	const char *name = buf;
575	int len;
576
577	if (pnp && faa->faa_quiet)
578		return QUIET;
579
580	/* Skip "not configured" for nodes w/o compatible property */
581	if (pnp && OF_getproplen(faa->faa_phandle, "compatible") <= 0)
582		return QUIET;
583
584	if (!fdtbus_get_path(faa->faa_phandle, buf, sizeof(buf)))
585		name = faa->faa_name;
586
587	if (pnp) {
588		aprint_normal("%s at %s", name, pnp);
589		const char *compat = fdt_getprop(fdtbus_get_data(),
590		    fdtbus_phandle2offset(faa->faa_phandle), "compatible",
591		    &len);
592		while (len > 0) {
593			aprint_debug(" <%s>", compat);
594			len -= (strlen(compat) + 1);
595			compat += (strlen(compat) + 1);
596		}
597	} else
598		aprint_debug(" (%s)", name);
599
600	return UNCONF;
601}
602