1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (c) 2011 Nathan Whitehorn
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 AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, 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__FBSDID("$FreeBSD$");
31
32#include <sys/param.h>
33#include <sys/kernel.h>
34#include <sys/systm.h>
35#include <sys/fbio.h>
36
37#include <dev/vt/vt.h>
38#include <dev/vt/hw/fb/vt_fb.h>
39#include <dev/vt/colors/vt_termcolors.h>
40
41#include <vm/vm.h>
42#include <vm/pmap.h>
43
44#include <machine/bus.h>
45#include <machine/cpu.h>
46
47#include <dev/ofw/openfirm.h>
48#include <dev/ofw/ofw_bus.h>
49#include <dev/ofw/ofw_pci.h>
50
51struct ofwfb_softc {
52	struct fb_info	fb;
53
54	phandle_t	sc_node;
55	ihandle_t	sc_handle;
56	bus_space_tag_t	sc_memt;
57	int		iso_palette;
58};
59
60static void ofwfb_initialize(struct vt_device *vd);
61static vd_probe_t	ofwfb_probe;
62static vd_init_t	ofwfb_init;
63static vd_bitblt_text_t	ofwfb_bitblt_text;
64static vd_bitblt_bmp_t	ofwfb_bitblt_bitmap;
65
66static const struct vt_driver vt_ofwfb_driver = {
67	.vd_name	= "ofwfb",
68	.vd_probe	= ofwfb_probe,
69	.vd_init	= ofwfb_init,
70	.vd_blank	= vt_fb_blank,
71	.vd_bitblt_text	= ofwfb_bitblt_text,
72	.vd_bitblt_bmp	= ofwfb_bitblt_bitmap,
73	.vd_fb_ioctl	= vt_fb_ioctl,
74	.vd_fb_mmap	= vt_fb_mmap,
75	.vd_priority	= VD_PRIORITY_GENERIC+1,
76};
77
78static unsigned char ofw_colors[16] = {
79	/* See "16-color Text Extension" Open Firmware document, page 4 */
80	0, 4, 2, 6, 1, 5, 3, 7,
81	8, 12, 10, 14, 9, 13, 11, 15
82};
83
84static struct ofwfb_softc ofwfb_conssoftc;
85VT_DRIVER_DECLARE(vt_ofwfb, vt_ofwfb_driver);
86
87static int
88ofwfb_probe(struct vt_device *vd)
89{
90	int disabled;
91	phandle_t chosen, node;
92	ihandle_t stdout;
93	char buf[64];
94
95	disabled = 0;
96	TUNABLE_INT_FETCH("hw.ofwfb.disable", &disabled);
97	if (disabled)
98		return (CN_DEAD);
99
100	chosen = OF_finddevice("/chosen");
101	if (chosen == -1)
102		return (CN_DEAD);
103
104	node = -1;
105	if (OF_getprop(chosen, "stdout", &stdout, sizeof(stdout)) ==
106	    sizeof(stdout))
107		node = OF_instance_to_package(stdout);
108	if (node == -1)
109		if (OF_getprop(chosen, "stdout-path", buf, sizeof(buf)) > 0)
110			node = OF_finddevice(buf);
111	if (node == -1) {
112		/*
113		 * The "/chosen/stdout" does not exist try
114		 * using "screen" directly.
115		 */
116		node = OF_finddevice("screen");
117	}
118	OF_getprop(node, "device_type", buf, sizeof(buf));
119	if (strcmp(buf, "display") != 0)
120		return (CN_DEAD);
121
122	/* Looks OK... */
123	return (CN_INTERNAL);
124}
125
126static void
127ofwfb_bitblt_bitmap(struct vt_device *vd, const struct vt_window *vw,
128    const uint8_t *pattern, const uint8_t *mask,
129    unsigned int width, unsigned int height,
130    unsigned int x, unsigned int y, term_color_t fg, term_color_t bg)
131{
132	struct fb_info *sc = vd->vd_softc;
133	u_long line;
134	uint32_t fgc, bgc;
135	int c, l;
136	uint8_t b, m;
137	union {
138		uint32_t l;
139		uint8_t	 c[4];
140	} ch1, ch2;
141
142#ifdef __powerpc__
143	/* Deal with unmapped framebuffers */
144	if (sc->fb_flags & FB_FLAG_NOWRITE) {
145		if (pmap_bootstrapped) {
146			sc->fb_flags &= ~FB_FLAG_NOWRITE;
147			ofwfb_initialize(vd);
148			vd->vd_driver->vd_blank(vd, TC_BLACK);
149		} else {
150			return;
151		}
152	}
153#endif
154
155	fgc = sc->fb_cmap[fg];
156	bgc = sc->fb_cmap[bg];
157	b = m = 0;
158
159	if (((struct ofwfb_softc *)vd->vd_softc)->iso_palette) {
160		fg = ofw_colors[fg];
161		bg = ofw_colors[bg];
162	}
163
164	line = (sc->fb_stride * y) + x * sc->fb_bpp/8;
165	if (mask == NULL && sc->fb_bpp == 8 && (width % 8 == 0)) {
166		/* Don't try to put off screen pixels */
167		if (((x + width) > vd->vd_width) || ((y + height) >
168		    vd->vd_height))
169			return;
170
171		for (; height > 0; height--) {
172			for (c = 0; c < width; c += 8) {
173				b = *pattern++;
174
175				/*
176				 * Assume that there is more background than
177				 * foreground in characters and init accordingly
178				 */
179				ch1.l = ch2.l = (bg << 24) | (bg << 16) |
180				    (bg << 8) | bg;
181
182				/*
183				 * Calculate 2 x 4-chars at a time, and then
184				 * write these out.
185				 */
186				if (b & 0x80) ch1.c[0] = fg;
187				if (b & 0x40) ch1.c[1] = fg;
188				if (b & 0x20) ch1.c[2] = fg;
189				if (b & 0x10) ch1.c[3] = fg;
190
191				if (b & 0x08) ch2.c[0] = fg;
192				if (b & 0x04) ch2.c[1] = fg;
193				if (b & 0x02) ch2.c[2] = fg;
194				if (b & 0x01) ch2.c[3] = fg;
195
196				*(uint32_t *)(sc->fb_vbase + line + c) = ch1.l;
197				*(uint32_t *)(sc->fb_vbase + line + c + 4) =
198				    ch2.l;
199			}
200			line += sc->fb_stride;
201		}
202	} else {
203		for (l = 0;
204		    l < height && y + l < vw->vw_draw_area.tr_end.tp_row;
205		    l++) {
206			for (c = 0;
207			    c < width && x + c < vw->vw_draw_area.tr_end.tp_col;
208			    c++) {
209				if (c % 8 == 0)
210					b = *pattern++;
211				else
212					b <<= 1;
213				if (mask != NULL) {
214					if (c % 8 == 0)
215						m = *mask++;
216					else
217						m <<= 1;
218					/* Skip pixel write, if mask not set. */
219					if ((m & 0x80) == 0)
220						continue;
221				}
222				switch(sc->fb_bpp) {
223				case 8:
224					*(uint8_t *)(sc->fb_vbase + line + c) =
225					    b & 0x80 ? fg : bg;
226					break;
227				case 32:
228					*(uint32_t *)(sc->fb_vbase + line + 4*c)
229					    = (b & 0x80) ? fgc : bgc;
230					break;
231				default:
232					/* panic? */
233					break;
234				}
235			}
236			line += sc->fb_stride;
237		}
238	}
239}
240
241void
242ofwfb_bitblt_text(struct vt_device *vd, const struct vt_window *vw,
243    const term_rect_t *area)
244{
245	unsigned int col, row, x, y;
246	struct vt_font *vf;
247	term_char_t c;
248	term_color_t fg, bg;
249	const uint8_t *pattern;
250
251	vf = vw->vw_font;
252
253	for (row = area->tr_begin.tp_row; row < area->tr_end.tp_row; ++row) {
254		for (col = area->tr_begin.tp_col; col < area->tr_end.tp_col;
255		    ++col) {
256			x = col * vf->vf_width +
257			    vw->vw_draw_area.tr_begin.tp_col;
258			y = row * vf->vf_height +
259			    vw->vw_draw_area.tr_begin.tp_row;
260
261			c = VTBUF_GET_FIELD(&vw->vw_buf, row, col);
262			pattern = vtfont_lookup(vf, c);
263			vt_determine_colors(c,
264			    VTBUF_ISCURSOR(&vw->vw_buf, row, col), &fg, &bg);
265
266			ofwfb_bitblt_bitmap(vd, vw,
267			    pattern, NULL, vf->vf_width, vf->vf_height,
268			    x, y, fg, bg);
269		}
270	}
271
272#ifndef SC_NO_CUTPASTE
273	if (!vd->vd_mshown)
274		return;
275
276	term_rect_t drawn_area;
277
278	drawn_area.tr_begin.tp_col = area->tr_begin.tp_col * vf->vf_width;
279	drawn_area.tr_begin.tp_row = area->tr_begin.tp_row * vf->vf_height;
280	drawn_area.tr_end.tp_col = area->tr_end.tp_col * vf->vf_width;
281	drawn_area.tr_end.tp_row = area->tr_end.tp_row * vf->vf_height;
282
283	if (vt_is_cursor_in_area(vd, &drawn_area)) {
284		ofwfb_bitblt_bitmap(vd, vw,
285		    vd->vd_mcursor->map, vd->vd_mcursor->mask,
286		    vd->vd_mcursor->width, vd->vd_mcursor->height,
287		    vd->vd_mx_drawn + vw->vw_draw_area.tr_begin.tp_col,
288		    vd->vd_my_drawn + vw->vw_draw_area.tr_begin.tp_row,
289		    vd->vd_mcursor_fg, vd->vd_mcursor_bg);
290	}
291#endif
292}
293
294static void
295ofwfb_initialize(struct vt_device *vd)
296{
297	struct ofwfb_softc *sc = vd->vd_softc;
298	int i, err;
299	cell_t retval;
300	uint32_t oldpix;
301
302	sc->fb.fb_cmsize = 16;
303
304	if (sc->fb.fb_flags & FB_FLAG_NOWRITE)
305		return;
306
307	/*
308	 * Set up the color map
309	 */
310
311	sc->iso_palette = 0;
312	switch (sc->fb.fb_bpp) {
313	case 8:
314		vt_generate_cons_palette(sc->fb.fb_cmap, COLOR_FORMAT_RGB, 255,
315		    16, 255, 8, 255, 0);
316
317		for (i = 0; i < 16; i++) {
318			err = OF_call_method("color!", sc->sc_handle, 4, 1,
319			    (cell_t)((sc->fb.fb_cmap[i] >> 16) & 0xff),
320			    (cell_t)((sc->fb.fb_cmap[i] >> 8) & 0xff),
321			    (cell_t)((sc->fb.fb_cmap[i] >> 0) & 0xff),
322			    (cell_t)i, &retval);
323			if (err)
324				break;
325		}
326		if (i != 16)
327			sc->iso_palette = 1;
328
329		break;
330
331	case 32:
332		/*
333		 * We bypass the usual bus_space_() accessors here, mostly
334		 * for performance reasons. In particular, we don't want
335		 * any barrier operations that may be performed and handle
336		 * endianness slightly different. Figure out the host-view
337		 * endianness of the frame buffer.
338		 */
339		oldpix = bus_space_read_4(sc->sc_memt, sc->fb.fb_vbase, 0);
340		bus_space_write_4(sc->sc_memt, sc->fb.fb_vbase, 0, 0xff000000);
341		if (*(uint8_t *)(sc->fb.fb_vbase) == 0xff)
342			vt_generate_cons_palette(sc->fb.fb_cmap,
343			    COLOR_FORMAT_RGB, 255, 0, 255, 8, 255, 16);
344		else
345			vt_generate_cons_palette(sc->fb.fb_cmap,
346			    COLOR_FORMAT_RGB, 255, 16, 255, 8, 255, 0);
347		bus_space_write_4(sc->sc_memt, sc->fb.fb_vbase, 0, oldpix);
348		break;
349
350	default:
351		panic("Unknown color space depth %d", sc->fb.fb_bpp);
352		break;
353        }
354}
355
356static int
357ofwfb_init(struct vt_device *vd)
358{
359	struct ofwfb_softc *sc;
360	char buf[64];
361	phandle_t chosen;
362	phandle_t node;
363	uint32_t depth, height, width, stride;
364	uint32_t fb_phys;
365	int i, len;
366
367	/* Initialize softc */
368	vd->vd_softc = sc = &ofwfb_conssoftc;
369
370	node = -1;
371	chosen = OF_finddevice("/chosen");
372	if (OF_getprop(chosen, "stdout", &sc->sc_handle,
373	    sizeof(ihandle_t)) == sizeof(ihandle_t))
374		node = OF_instance_to_package(sc->sc_handle);
375	if (node == -1)
376		/* Try "/chosen/stdout-path" now */
377		if (OF_getprop(chosen, "stdout-path", buf, sizeof(buf)) > 0) {
378			node = OF_finddevice(buf);
379			if (node != -1)
380				sc->sc_handle = OF_open(buf);
381		}
382	if (node == -1) {
383		/*
384		 * The "/chosen/stdout" does not exist try
385		 * using "screen" directly.
386		 */
387		node = OF_finddevice("screen");
388		sc->sc_handle = OF_open("screen");
389	}
390	OF_getprop(node, "device_type", buf, sizeof(buf));
391	if (strcmp(buf, "display") != 0)
392		return (CN_DEAD);
393
394	/* Keep track of the OF node */
395	sc->sc_node = node;
396
397	/*
398	 * Try to use a 32-bit framebuffer if possible. This may be
399	 * unimplemented and fail. That's fine -- it just means we are
400	 * stuck with the defaults.
401	 */
402	OF_call_method("set-depth", sc->sc_handle, 1, 1, (cell_t)32, &i);
403
404	/* Make sure we have needed properties */
405	if (OF_getproplen(node, "height") != sizeof(height) ||
406	    OF_getproplen(node, "width") != sizeof(width) ||
407	    OF_getproplen(node, "depth") != sizeof(depth))
408		return (CN_DEAD);
409
410	/* Only support 8 and 32-bit framebuffers */
411	OF_getprop(node, "depth", &depth, sizeof(depth));
412	if (depth != 8 && depth != 32)
413		return (CN_DEAD);
414	sc->fb.fb_bpp = sc->fb.fb_depth = depth;
415
416	OF_getprop(node, "height", &height, sizeof(height));
417	OF_getprop(node, "width", &width, sizeof(width));
418	if (OF_getprop(node, "linebytes", &stride, sizeof(stride)) !=
419	    sizeof(stride))
420		stride = width*depth/8;
421
422	sc->fb.fb_height = height;
423	sc->fb.fb_width = width;
424	sc->fb.fb_stride = stride;
425	sc->fb.fb_size = sc->fb.fb_height * sc->fb.fb_stride;
426
427	/*
428	 * Grab the physical address of the framebuffer, and then map it
429	 * into our memory space. If the MMU is not yet up, it will be
430	 * remapped for us when relocation turns on.
431	 */
432	if (OF_getproplen(node, "address") == sizeof(fb_phys)) {
433		/* XXX We assume #address-cells is 1 at this point. */
434		OF_getprop(node, "address", &fb_phys, sizeof(fb_phys));
435
436	#if defined(__powerpc__)
437		sc->sc_memt = &bs_be_tag;
438		bus_space_map(sc->sc_memt, fb_phys, sc->fb.fb_size,
439		    BUS_SPACE_MAP_PREFETCHABLE, &sc->fb.fb_vbase);
440	#elif defined(__arm__)
441		sc->sc_memt = fdtbus_bs_tag;
442		bus_space_map(sc->sc_memt, sc->fb.fb_pbase, sc->fb.fb_size,
443		    BUS_SPACE_MAP_PREFETCHABLE,
444		    (bus_space_handle_t *)&sc->fb.fb_vbase);
445	#else
446		#error Unsupported platform!
447	#endif
448
449		sc->fb.fb_pbase = fb_phys;
450	} else {
451		/*
452		 * Some IBM systems don't have an address property. Try to
453		 * guess the framebuffer region from the assigned addresses.
454		 * This is ugly, but there doesn't seem to be an alternative.
455		 * Linux does the same thing.
456		 */
457
458		struct ofw_pci_register pciaddrs[8];
459		int num_pciaddrs = 0;
460
461		/*
462		 * Get the PCI addresses of the adapter, if present. The node
463		 * may be the child of the PCI device: in that case, try the
464		 * parent for the assigned-addresses property.
465		 */
466		len = OF_getprop(node, "assigned-addresses", pciaddrs,
467		    sizeof(pciaddrs));
468		if (len == -1) {
469			len = OF_getprop(OF_parent(node), "assigned-addresses",
470			    pciaddrs, sizeof(pciaddrs));
471		}
472		if (len == -1)
473			len = 0;
474		num_pciaddrs = len / sizeof(struct ofw_pci_register);
475
476		fb_phys = num_pciaddrs;
477		for (i = 0; i < num_pciaddrs; i++) {
478			/* If it is too small, not the framebuffer */
479			if (pciaddrs[i].size_lo < sc->fb.fb_stride * height)
480				continue;
481			/* If it is not memory, it isn't either */
482			if (!(pciaddrs[i].phys_hi &
483			    OFW_PCI_PHYS_HI_SPACE_MEM32))
484				continue;
485
486			/* This could be the framebuffer */
487			fb_phys = i;
488
489			/* If it is prefetchable, it certainly is */
490			if (pciaddrs[i].phys_hi & OFW_PCI_PHYS_HI_PREFETCHABLE)
491				break;
492		}
493
494		if (fb_phys == num_pciaddrs) /* No candidates found */
495			return (CN_DEAD);
496
497	#if defined(__powerpc__)
498		OF_decode_addr(node, fb_phys, &sc->sc_memt, &sc->fb.fb_vbase,
499		    NULL);
500		sc->fb.fb_pbase = sc->fb.fb_vbase & ~DMAP_BASE_ADDRESS;
501	#else
502		/* No ability to interpret assigned-addresses otherwise */
503		return (CN_DEAD);
504	#endif
505        }
506
507
508	#if defined(__powerpc__)
509	/*
510	 * If we are running on PowerPC in real mode (supported only on AIM
511	 * CPUs), the frame buffer may be inaccessible (real mode does not
512	 * necessarily cover all RAM) and may also be mapped with the wrong
513	 * cache properties (all real mode accesses are assumed cacheable).
514	 * Just don't write to it for the time being.
515	 */
516	if (!(cpu_features & PPC_FEATURE_BOOKE) && !(mfmsr() & PSL_DR))
517		sc->fb.fb_flags |= FB_FLAG_NOWRITE;
518	#endif
519	ofwfb_initialize(vd);
520	vt_fb_init(vd);
521
522	return (CN_INTERNAL);
523}
524
525