xref: /netbsd-src/sys/dev/usb/udl.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /*	$NetBSD: udl.c,v 1.12 2014/12/12 05:19:33 msaitoh Exp $	*/
2 
3 /*-
4  * Copyright (c) 2009 FUKAUMI Naoki.
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, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 /*
29  * Copyright (c) 2009 Marcus Glocker <mglocker@openbsd.org>
30  *
31  * Permission to use, copy, modify, and distribute this software for any
32  * purpose with or without fee is hereby granted, provided that the above
33  * copyright notice and this permission notice appear in all copies.
34  *
35  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
36  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
37  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
38  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
39  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
40  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
41  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
42  */
43 
44 /*
45  * Driver for the ``DisplayLink DL-1x0 / DL-1x5'' graphic chips based
46  * on the reversed engineered specifications of Florian Echtler
47  * <floe at butterbrot dot org>:
48  *
49  * 	http://floe.butterbrot.org/displaylink/doku.php
50  *
51  * This driver was written by Marcus Glocker for OpenBSD and ported to
52  * NetBSD by FUKAUMI Naoki with many modification.
53  */
54 
55 #include <sys/cdefs.h>
56 __KERNEL_RCSID(0, "$NetBSD: udl.c,v 1.12 2014/12/12 05:19:33 msaitoh Exp $");
57 
58 #include <sys/param.h>
59 #include <sys/device.h>
60 #include <sys/kernel.h>
61 #include <sys/proc.h>
62 #include <sys/systm.h>
63 #include <sys/kmem.h>
64 #include <uvm/uvm.h>
65 
66 #include <sys/bus.h>
67 #include <sys/endian.h>
68 
69 #include <dev/usb/usb.h>
70 #include <dev/usb/usbdi.h>
71 #include <dev/usb/usbdivar.h>
72 #include <dev/usb/usbdi_util.h>
73 #include <dev/usb/usb_mem.h>
74 #include <dev/usb/usbdevs.h>
75 
76 #include <dev/firmload.h>
77 
78 #include <dev/videomode/videomode.h>
79 #include <dev/videomode/edidvar.h>
80 
81 #include <dev/wscons/wsconsio.h>
82 #include <dev/wscons/wsdisplayvar.h>
83 #include <dev/rasops/rasops.h>
84 
85 #include <dev/usb/udl.h>
86 #ifdef notyet
87 #include <dev/usb/udlio.h>
88 #endif
89 
90 /*
91  * Defines.
92  */
93 #ifdef UDL_DEBUG
94 #define DPRINTF(x)	do { if (udl_debug) printf x; } while (0)
95 #define DPRINTFN(n, x)	do { if (udl_debug >= (n)) printf x; } while (0)
96 int udl_debug = 1;
97 #else
98 #define DPRINTF(x)	do {} while (0)
99 #define DPRINTFN(n, x)	do {} while (0)
100 #endif
101 
102 /*
103  * Prototypes.
104  */
105 static int		udl_match(device_t, cfdata_t, void *);
106 static void		udl_attach(device_t, device_t, void *);
107 static int		udl_detach(device_t, int);
108 
109 static int		udl_ioctl(void *, void *, u_long, void *, int,
110 			    struct lwp *);
111 static paddr_t		udl_mmap(void *, void *, off_t, int);
112 static int		udl_alloc_screen(void *, const struct wsscreen_descr *,
113 			    void **, int *, int *, long *);
114 static void		udl_free_screen(void *, void *);
115 static int		udl_show_screen(void *, void *, int,
116 			    void (*)(void *, int, int), void *);
117 
118 static void		udl_comp_load(struct udl_softc *);
119 static void		udl_comp_unload(struct udl_softc *);
120 static int		udl_fbmem_alloc(struct udl_softc *);
121 static void		udl_fbmem_free(struct udl_softc *);
122 static int		udl_cmdq_alloc(struct udl_softc *);
123 static void		udl_cmdq_free(struct udl_softc *);
124 static struct udl_cmdq *udl_cmdq_get(struct udl_softc *sc);
125 static void		udl_cmdq_put(struct udl_softc *sc,
126 			    struct udl_cmdq *cmdq);
127 static void		udl_cmdq_flush(struct udl_softc *);
128 
129 static void		udl_cursor(void *, int, int, int);
130 static void		udl_putchar(void *, int, int, u_int, long);
131 static void		udl_copycols(void *, int, int, int, int);
132 static void		udl_erasecols(void *, int, int, int, long);
133 static void		udl_copyrows(void *, int, int, int);
134 static void		udl_eraserows(void *, int, int, long);
135 
136 static void		udl_restore_char(struct rasops_info *);
137 static void		udl_draw_char(struct rasops_info *, uint16_t *, u_int,
138 			    int, int);
139 static void		udl_copy_rect(struct udl_softc *, int, int, int, int,
140 			    int, int);
141 static void		udl_fill_rect(struct udl_softc *, uint16_t, int, int,
142 			    int, int);
143 #ifdef notyet
144 static void		udl_draw_rect(struct udl_softc *,
145 			    struct udl_ioctl_damage *);
146 static void		udl_draw_rect_comp(struct udl_softc *,
147 			    struct udl_ioctl_damage *);
148 #endif
149 
150 static inline void	udl_copy_line(struct udl_softc *, int, int, int);
151 static inline void	udl_fill_line(struct udl_softc *, uint16_t, int, int);
152 static inline void	udl_draw_line(struct udl_softc *, uint16_t *, int,
153 			    int);
154 #ifdef notyet
155 static inline void	udl_draw_line_comp(struct udl_softc *, uint16_t *, int,
156 			    int);
157 #endif
158 
159 static int		udl_cmd_send(struct udl_softc *);
160 static void		udl_cmd_send_async(struct udl_softc *);
161 static void		udl_cmd_send_async_cb(usbd_xfer_handle,
162 			    usbd_private_handle, usbd_status);
163 
164 static int		udl_ctrl_msg(struct udl_softc *, uint8_t, uint8_t,
165 			    uint16_t, uint16_t, uint8_t *, uint16_t);
166 static int		udl_init(struct udl_softc *);
167 static void		udl_read_edid(struct udl_softc *);
168 static void		udl_set_address(struct udl_softc *, int, int, int,
169 			    int);
170 static void		udl_blank(struct udl_softc *, int);
171 static uint16_t		udl_lfsr(uint16_t);
172 static int		udl_set_resolution(struct udl_softc *,
173 			    const struct videomode *);
174 static const struct videomode *udl_videomode_lookup(const char *);
175 
176 static inline void
177 udl_cmd_add_1(struct udl_softc *sc, uint8_t val)
178 {
179 
180 	*sc->sc_cmd_buf++ = val;
181 }
182 
183 static inline void
184 udl_cmd_add_2(struct udl_softc *sc, uint16_t val)
185 {
186 
187 	be16enc(sc->sc_cmd_buf, val);
188 	sc->sc_cmd_buf += 2;
189 }
190 
191 static inline void
192 udl_cmd_add_3(struct udl_softc *sc, uint32_t val)
193 {
194 
195 	udl_cmd_add_2(sc, val >> 8);
196 	udl_cmd_add_1(sc, val);
197 }
198 
199 static inline void
200 udl_cmd_add_4(struct udl_softc *sc, uint32_t val)
201 {
202 
203 	be32enc(sc->sc_cmd_buf, val);
204 	sc->sc_cmd_buf += 4;
205 }
206 
207 static inline void
208 udl_cmd_add_buf(struct udl_softc *sc, uint16_t *buf, int width)
209 {
210 #if BYTE_ORDER == BIG_ENDIAN
211 	memcpy(sc->sc_cmd_buf, buf, width * 2);
212 	sc->sc_cmd_buf += width * 2;
213 #else
214 	uint16_t *endp;
215 
216 	endp = buf + width;
217 
218 	if (((uintptr_t)sc->sc_cmd_buf & 1) == 0) {
219 		while (buf < endp) {
220 			*(uint16_t *)sc->sc_cmd_buf = htobe16(*buf++);
221 			sc->sc_cmd_buf += 2;
222 		}
223 	} else {
224 		while (buf < endp) {
225 			be16enc(sc->sc_cmd_buf, *buf++);
226 			sc->sc_cmd_buf += 2;
227 		}
228 	}
229 #endif
230 }
231 
232 static inline void
233 udl_reg_write_1(struct udl_softc *sc, uint8_t reg, uint8_t val)
234 {
235 
236 	udl_cmd_add_4(sc, (UDL_BULK_SOC << 24) |
237 	    (UDL_BULK_CMD_REG_WRITE_1 << 16) | (reg << 8) | val);
238 }
239 
240 static inline void
241 udl_reg_write_2(struct udl_softc *sc, uint8_t reg, uint16_t val)
242 {
243 
244 	udl_reg_write_1(sc, reg++, val >> 8);
245 	udl_reg_write_1(sc, reg, val);
246 }
247 
248 static inline void
249 udl_reg_write_3(struct udl_softc *sc, uint8_t reg, uint32_t val)
250 {
251 
252 	udl_reg_write_1(sc, reg++, val >> 16);
253 	udl_reg_write_1(sc, reg++, val >> 8);
254 	udl_reg_write_1(sc, reg, val);
255 }
256 
257 /* XXX */
258 static int
259 firmware_load(const char *dname, const char *iname, uint8_t **ucodep,
260     size_t *sizep)
261 {
262 	firmware_handle_t fh;
263 	int error;
264 
265 	if ((error = firmware_open(dname, iname, &fh)) != 0)
266 		return error;
267 	*sizep = firmware_get_size(fh);
268 	if ((*ucodep = firmware_malloc(*sizep)) == NULL) {
269 		firmware_close(fh);
270 		return ENOMEM;
271 	}
272 	if ((error = firmware_read(fh, 0, *ucodep, *sizep)) != 0)
273 		firmware_free(*ucodep, *sizep);
274 	firmware_close(fh);
275 
276 	return error;
277 }
278 
279 /*
280  * Driver glue.
281  */
282 CFATTACH_DECL_NEW(udl, sizeof(struct udl_softc),
283 	udl_match, udl_attach, udl_detach, NULL);
284 
285 /*
286  * wsdisplay glue.
287  */
288 static struct wsdisplay_accessops udl_accessops = {
289 	udl_ioctl,
290 	udl_mmap,
291 	udl_alloc_screen,
292 	udl_free_screen,
293 	udl_show_screen,
294 	NULL,
295 	NULL,
296 	NULL,
297 };
298 
299 /*
300  * Matching devices.
301  */
302 static const struct usb_devno udl_devs[] = {
303 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_GUC2020 },
304 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LD220 },
305 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LD190 },
306 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_U70 },
307 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_VCUD60 },
308 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_CONV },
309 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_DLDVI },
310 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_USBRGB },
311 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LCDUSB7X },
312 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LCDUSB10X },
313 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_VGA10 },
314 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_WSDVI },
315 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_EC008 },
316 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_GXDVIU2 },
317 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_GXDVIU2B },
318 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LCD4300U },
319 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LCD8000U },
320 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_HPDOCK },
321 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_NL571 },
322 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_M01061 },
323 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_NBDOCK },
324 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_SWDVI },
325 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LUM70 },
326 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LCD8000UD_DVI },
327 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LDEWX015U },
328 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_LT1421WIDE },
329 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_SD_U2VDH },
330 	{ USB_VENDOR_DISPLAYLINK, USB_PRODUCT_DISPLAYLINK_UM7X0 }
331 };
332 
333 static int
334 udl_match(device_t parent, cfdata_t match, void *aux)
335 {
336 	struct usb_attach_arg *uaa = aux;
337 
338 	if (usb_lookup(udl_devs, uaa->vendor, uaa->product) != NULL)
339 		return UMATCH_VENDOR_PRODUCT;
340 
341 	return UMATCH_NONE;
342 }
343 
344 static void
345 udl_attach(device_t parent, device_t self, void *aux)
346 {
347 	struct udl_softc *sc = device_private(self);
348 	struct usb_attach_arg *uaa = aux;
349 	struct wsemuldisplaydev_attach_args aa;
350 	const struct videomode *vmp;
351 	usbd_status error;
352 	char *devinfop;
353 
354 	aprint_naive("\n");
355 	aprint_normal("\n");
356 
357 	sc->sc_dev = self;
358 	sc->sc_udev = uaa->device;
359 
360 	devinfop = usbd_devinfo_alloc(sc->sc_udev, 0);
361 	aprint_normal_dev(sc->sc_dev, "%s\n", devinfop);
362 	usbd_devinfo_free(devinfop);
363 
364 	/*
365 	 * Set device configuration descriptor number.
366 	 */
367 	error = usbd_set_config_no(sc->sc_udev, 1, 0);
368 	if (error != USBD_NORMAL_COMPLETION) {
369 		aprint_error_dev(self, "failed to set configuration"
370 		    ", err=%s\n", usbd_errstr(error));
371 		return;
372 	}
373 
374 	/*
375 	 * Create device handle to interface descriptor.
376 	 */
377 	error = usbd_device2interface_handle(sc->sc_udev, 0, &sc->sc_iface);
378 	if (error != USBD_NORMAL_COMPLETION)
379 		return;
380 
381 	/*
382 	 * Open bulk TX pipe.
383 	 */
384 	error = usbd_open_pipe(sc->sc_iface, 1, USBD_EXCLUSIVE_USE,
385 	    &sc->sc_tx_pipeh);
386 	if (error != USBD_NORMAL_COMPLETION)
387 		return;
388 
389 	/*
390 	 * Allocate bulk command queue.
391 	 */
392 #ifdef UDL_EVENT_COUNTERS
393 	evcnt_attach_dynamic(&sc->sc_ev_cmdq_get, EVCNT_TYPE_MISC, NULL,
394 	    device_xname(sc->sc_dev), "udl_cmdq_get");
395 	evcnt_attach_dynamic(&sc->sc_ev_cmdq_put, EVCNT_TYPE_MISC, NULL,
396 	    device_xname(sc->sc_dev), "udl_cmdq_put");
397 	evcnt_attach_dynamic(&sc->sc_ev_cmdq_wait, EVCNT_TYPE_MISC, NULL,
398 	    device_xname(sc->sc_dev), "udl_cmdq_wait");
399 	evcnt_attach_dynamic(&sc->sc_ev_cmdq_timeout, EVCNT_TYPE_MISC, NULL,
400 	    device_xname(sc->sc_dev), "udl_cmdq_timeout");
401 #endif
402 
403 	if (udl_cmdq_alloc(sc) != 0)
404 		return;
405 
406 	cv_init(&sc->sc_cv, device_xname(sc->sc_dev));
407 	mutex_init(&sc->sc_mtx, MUTEX_DEFAULT, IPL_TTY); /* XXX for tty_lock */
408 
409 	if ((sc->sc_cmd_cur = udl_cmdq_get(sc)) == NULL)
410 		return;
411 	UDL_CMD_BUFINIT(sc);
412 
413 	/*
414 	 * Initialize chip.
415 	 */
416 	if (udl_init(sc) != 0)
417 		return;
418 
419 	udl_read_edid(sc);
420 
421 	/*
422 	 * Initialize resolution.
423 	 */
424 #ifndef UDL_VIDEOMODE
425 	if (sc->sc_ei.edid_nmodes != 0 &&
426 	    sc->sc_ei.edid_preferred_mode != NULL)
427 		vmp = sc->sc_ei.edid_preferred_mode;
428 	else
429 #define UDL_VIDEOMODE	"640x480x60"
430 #endif
431 		vmp = udl_videomode_lookup(UDL_VIDEOMODE);
432 
433 	if (vmp == NULL)
434 		return;
435 
436 	sc->sc_width = vmp->hdisplay;
437 	sc->sc_height = vmp->vdisplay;
438 	sc->sc_offscreen = sc->sc_height * 3 / 2;
439 	sc->sc_depth = 16;
440 
441 	if (udl_set_resolution(sc, vmp) != 0)
442 		return;
443 
444 	sc->sc_defaultscreen.name = "default";
445 	sc->sc_screens[0] = &sc->sc_defaultscreen;
446 	sc->sc_screenlist.nscreens = 1;
447 	sc->sc_screenlist.screens = sc->sc_screens;
448 
449 	/*
450 	 * Set initial wsdisplay emulation mode.
451 	 */
452 	sc->sc_mode = WSDISPLAYIO_MODE_EMUL;
453 
454 	/*
455 	 * Attach wsdisplay.
456 	 */
457 	aa.console = 0;
458 	aa.scrdata = &sc->sc_screenlist;
459 	aa.accessops = &udl_accessops;
460 	aa.accesscookie = sc;
461 
462 	sc->sc_wsdisplay =
463 	    config_found(sc->sc_dev, &aa, wsemuldisplaydevprint);
464 
465 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
466 }
467 
468 static int
469 udl_detach(device_t self, int flags)
470 {
471 	struct udl_softc *sc = device_private(self);
472 
473 	/*
474 	 * Close bulk TX pipe.
475 	 */
476 	if (sc->sc_tx_pipeh != NULL) {
477 		usbd_abort_pipe(sc->sc_tx_pipeh);
478 		usbd_close_pipe(sc->sc_tx_pipeh);
479 	}
480 
481 	/*
482 	 * Free command xfer buffers.
483 	 */
484 	udl_cmdq_flush(sc);
485 	udl_cmdq_free(sc);
486 
487 	cv_destroy(&sc->sc_cv);
488 	mutex_destroy(&sc->sc_mtx);
489 
490 	/*
491 	 * Free Huffman table.
492 	 */
493 	udl_comp_unload(sc);
494 
495 	/*
496 	 * Free framebuffer memory.
497 	 */
498 	udl_fbmem_free(sc);
499 
500 	/*
501 	 * Detach wsdisplay.
502 	 */
503 	if (sc->sc_wsdisplay != NULL)
504 		config_detach(sc->sc_wsdisplay, DETACH_FORCE);
505 
506 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
507 
508 #ifdef UDL_EVENT_COUNTERS
509 	evcnt_detach(&sc->sc_ev_cmdq_get);
510 	evcnt_detach(&sc->sc_ev_cmdq_put);
511 	evcnt_detach(&sc->sc_ev_cmdq_wait);
512 	evcnt_detach(&sc->sc_ev_cmdq_timeout);
513 #endif
514 
515 	return 0;
516 }
517 
518 static int
519 udl_ioctl(void *v, void *vs, u_long cmd, void *data, int flag, struct lwp *l)
520 {
521 	struct udl_softc *sc = v;
522 #ifdef notyet
523 	struct udl_ioctl_damage *d;
524 #endif
525 	struct wsdisplay_fbinfo *wdf;
526 	u_int mode;
527 
528 	switch (cmd) {
529 	case WSDISPLAYIO_GTYPE:
530 		*(u_int *)data = WSDISPLAY_TYPE_DL;
531 		return 0;
532 
533 	case WSDISPLAYIO_GINFO:
534 		wdf = (struct wsdisplay_fbinfo *)data;
535 		wdf->height = sc->sc_height;
536 		wdf->width = sc->sc_width;
537 		wdf->depth = sc->sc_depth;
538 		wdf->cmsize = 0;
539 		return 0;
540 
541 	case WSDISPLAYIO_GVIDEO:
542 		*(u_int *)data = sc->sc_blank;
543 		return 0;
544 
545 	case WSDISPLAYIO_SVIDEO:
546 		mode = *(u_int *)data;
547 		if (mode == sc->sc_blank)
548 			return 0;
549 		switch (mode) {
550 		case WSDISPLAYIO_VIDEO_OFF:
551 			udl_blank(sc, 1);
552 			break;
553 		case WSDISPLAYIO_VIDEO_ON:
554 			udl_blank(sc, 0);
555 			break;
556 		default:
557 			return EINVAL;
558 		}
559 		udl_cmd_send_async(sc);
560 		udl_cmdq_flush(sc);
561 		sc->sc_blank = mode;
562 		return 0;
563 
564 	case WSDISPLAYIO_SMODE:
565 		mode = *(u_int *)data;
566 		if (mode == sc->sc_mode)
567 			return 0;
568 		switch (mode) {
569 		case WSDISPLAYIO_MODE_EMUL:
570 			/* clear screen */
571 			udl_fill_rect(sc, 0, 0, 0, sc->sc_width,
572 			    sc->sc_height);
573 			udl_cmd_send_async(sc);
574 			udl_cmdq_flush(sc);
575 			udl_comp_unload(sc);
576 			break;
577 		case WSDISPLAYIO_MODE_DUMBFB:
578 			if (UDL_CMD_BUFSIZE(sc) > 0)
579 				udl_cmd_send_async(sc);
580 			udl_cmdq_flush(sc);
581 			udl_comp_load(sc);
582 			break;
583 		default:
584 			return EINVAL;
585 		}
586 		sc->sc_mode = mode;
587 		return 0;
588 
589 	case WSDISPLAYIO_LINEBYTES:
590 		*(u_int *)data = sc->sc_width * (sc->sc_depth / 8);
591 		return 0;
592 
593 #ifdef notyet
594 	/*
595 	 * XXX
596 	 * OpenBSD allows device specific ioctl()s and use this
597 	 * UDLIO_DAMAGE for the damage extension ops of X servers.
598 	 * Before blindly pulling such interfaces, probably we should
599 	 * discuss how such devices should be handled which have
600 	 * in-direct framebuffer memories that should be transfered
601 	 * per updated rectangle regions via MI wscons APIs.
602 	 */
603 	case UDLIO_DAMAGE:
604 		d = (struct udl_ioctl_damage *)data;
605 		d->status = UDLIO_STATUS_OK;
606 		if (sc->sc_flags & UDL_COMPRDY)
607 			udl_draw_rect_comp(sc, d);
608 		else
609 			udl_draw_rect(sc, d);
610 		return 0;
611 #endif
612 	}
613 
614 	return EPASSTHROUGH;
615 }
616 
617 static paddr_t
618 udl_mmap(void *v, void *vs, off_t off, int prot)
619 {
620 	struct udl_softc *sc = v;
621 	vaddr_t vaddr;
622 	paddr_t paddr;
623 	bool rv __diagused;
624 
625 	if (off < 0 || off > roundup2(UDL_FBMEM_SIZE(sc), PAGE_SIZE))
626 		return -1;
627 
628 	/* allocate framebuffer memory */
629 	if (udl_fbmem_alloc(sc) != 0)
630 		return -1;
631 
632 	vaddr = (vaddr_t)sc->sc_fbmem + off;
633 	rv = pmap_extract(pmap_kernel(), vaddr, &paddr);
634 	KASSERT(rv);
635 	paddr += vaddr & PGOFSET;
636 
637 	/* XXX we need MI paddr_t -> mmap cookie API */
638 #if defined(__alpha__)
639 #define PTOMMAP(paddr)	alpha_btop((char *)paddr)
640 #elif defined(__arm__)
641 #define PTOMMAP(paddr)	arm_btop((u_long)paddr)
642 #elif defined(__hppa__)
643 #define PTOMMAP(paddr)	btop((u_long)paddr)
644 #elif defined(__i386__) || defined(__x86_64__)
645 #define PTOMMAP(paddr)	x86_btop(paddr)
646 #elif defined(__m68k__)
647 #define PTOMMAP(paddr)	m68k_btop((char *)paddr)
648 #elif defined(__mips__)
649 #define PTOMMAP(paddr)	mips_btop(paddr)
650 #elif defined(__powerpc__)
651 #define PTOMMAP(paddr)	(paddr)
652 #elif defined(__sh__)
653 #define PTOMMAP(paddr)	sh3_btop(paddr)
654 #elif defined(__sparc__)
655 #define PTOMMAP(paddr)	(paddr)
656 #elif defined(__sparc64__)
657 #define PTOMMAP(paddr)	atop(paddr)
658 #elif defined(__vax__)
659 #define PTOMMAP(paddr)	btop((u_int)paddr)
660 #endif
661 
662 	return PTOMMAP(paddr);
663 }
664 
665 static int
666 udl_alloc_screen(void *v, const struct wsscreen_descr *type,
667     void **cookiep, int *curxp, int *curyp, long *attrp)
668 {
669 	struct udl_softc *sc = v;
670 
671 	if (sc->sc_nscreens > 0)
672 		return ENOMEM;
673 
674 	/*
675 	 * Initialize rasops.
676 	 */
677 	sc->sc_ri.ri_depth = sc->sc_depth;
678 	sc->sc_ri.ri_bits = NULL;
679 	sc->sc_ri.ri_width = sc->sc_width;
680 	sc->sc_ri.ri_height = sc->sc_height;
681 	sc->sc_ri.ri_stride = sc->sc_width * (sc->sc_depth / 8);
682 	sc->sc_ri.ri_hw = sc;
683 	sc->sc_ri.ri_flg = 0;
684 
685 	if (sc->sc_depth == 16) {
686 		sc->sc_ri.ri_rnum = 5;
687 		sc->sc_ri.ri_gnum = 6;
688 		sc->sc_ri.ri_bnum = 5;
689 		sc->sc_ri.ri_rpos = 11;
690 		sc->sc_ri.ri_gpos = 5;
691 		sc->sc_ri.ri_bpos = 0;
692 	}
693 
694 	rasops_init(&sc->sc_ri, sc->sc_height / 8, sc->sc_width / 8);
695 
696 	sc->sc_ri.ri_ops.cursor = udl_cursor;
697 	sc->sc_ri.ri_ops.putchar = udl_putchar;
698 	sc->sc_ri.ri_ops.copycols = udl_copycols;
699 	sc->sc_ri.ri_ops.erasecols = udl_erasecols;
700 	sc->sc_ri.ri_ops.copyrows = udl_copyrows;
701 	sc->sc_ri.ri_ops.eraserows = udl_eraserows;
702 
703 	sc->sc_ri.ri_ops.allocattr(&sc->sc_ri, 0, 0, 0, attrp);
704 
705 	sc->sc_defaultscreen.ncols = sc->sc_ri.ri_cols;
706 	sc->sc_defaultscreen.nrows = sc->sc_ri.ri_rows;
707 	sc->sc_defaultscreen.textops = &sc->sc_ri.ri_ops;
708 	sc->sc_defaultscreen.fontwidth = sc->sc_ri.ri_font->fontwidth;
709 	sc->sc_defaultscreen.fontheight = sc->sc_ri.ri_font->fontheight;
710 	sc->sc_defaultscreen.capabilities = sc->sc_ri.ri_caps;
711 
712 	*cookiep = &sc->sc_ri;
713 	*curxp = 0;
714 	*curyp = 0;
715 
716 	sc->sc_nscreens++;
717 
718 	return 0;
719 }
720 
721 static void
722 udl_free_screen(void *v, void *cookie)
723 {
724 	struct udl_softc *sc = v;
725 
726 	sc->sc_nscreens--;
727 }
728 
729 static int
730 udl_show_screen(void *v, void *cookie, int waitok,
731     void (*cb)(void *, int, int), void *cbarg)
732 {
733 
734 	return 0;
735 }
736 
737 static inline void
738 udl_cmd_add_decomptable(struct udl_softc *sc, uint8_t *buf, int len)
739 {
740 
741 	udl_cmd_add_2(sc, (UDL_BULK_SOC << 8) | UDL_BULK_CMD_DECOMP);
742 	udl_cmd_add_4(sc, 0x263871cd);	/* magic number */
743 	udl_cmd_add_4(sc, 0x00000200);	/* 512 byte chunks */
744 	memcpy(sc->sc_cmd_buf, buf, len);
745 	sc->sc_cmd_buf += len;
746 }
747 
748 static void
749 udl_comp_load(struct udl_softc *sc)
750 {
751 	struct udl_huffman *h;
752 	uint8_t *decomp;
753 	size_t decomp_size;
754 	int error, i;
755 
756 	if (!(sc->sc_flags & UDL_DECOMPRDY)) {
757 		error = firmware_load("udl", "udl-decomp", &decomp,
758 		    &decomp_size);
759 		if (error != 0) {
760 			aprint_error_dev(sc->sc_dev,
761 			    "error %d, could not read decomp table %s!\n",
762 			    error, "udl-decomp");
763 			return;
764 		}
765 		udl_cmd_add_decomptable(sc, decomp, decomp_size);
766 		firmware_free(decomp, decomp_size);
767 		if (udl_cmd_send(sc) != 0)
768 			return;
769 		sc->sc_flags |= UDL_DECOMPRDY;
770 	}
771 
772 	if (!(sc->sc_flags & UDL_COMPRDY)) {
773 		error = firmware_load("udl", "udl-comp", &sc->sc_huffman,
774 		    &sc->sc_huffman_size);
775 		if (error != 0) {
776 			aprint_error_dev(sc->sc_dev,
777 			    "error %d, could not read huffman table %s!\n",
778 			    error, "udl-comp");
779 			return;
780 		}
781 		h = (struct udl_huffman *)sc->sc_huffman;
782 		for (i = 0; i < UDL_HUFFMAN_RECORDS; i++)
783 			h[i].bit_pattern = be32toh(h[i].bit_pattern);
784 		sc->sc_huffman_base = sc->sc_huffman + UDL_HUFFMAN_BASE;
785 		sc->sc_flags |= UDL_COMPRDY;
786 	}
787 }
788 
789 static void
790 udl_comp_unload(struct udl_softc *sc)
791 {
792 
793 	if (sc->sc_flags & UDL_COMPRDY) {
794 		firmware_free(sc->sc_huffman, sc->sc_huffman_size);
795 		sc->sc_huffman = NULL;
796 		sc->sc_huffman_size = 0;
797 		sc->sc_flags &= ~UDL_COMPRDY;
798 	}
799 }
800 
801 static int
802 udl_fbmem_alloc(struct udl_softc *sc)
803 {
804 
805 	if (sc->sc_fbmem == NULL) {
806 		sc->sc_fbmem = kmem_alloc(UDL_FBMEM_SIZE(sc), KM_SLEEP);
807 		if (sc->sc_fbmem == NULL)
808 			return -1;
809 	}
810 
811 	return 0;
812 }
813 
814 static void
815 udl_fbmem_free(struct udl_softc *sc)
816 {
817 
818 	if (sc->sc_fbmem != NULL) {
819 		kmem_free(sc->sc_fbmem, UDL_FBMEM_SIZE(sc));
820 		sc->sc_fbmem = NULL;
821 	}
822 }
823 
824 static int
825 udl_cmdq_alloc(struct udl_softc *sc)
826 {
827 	struct udl_cmdq *cmdq;
828 	int i;
829 
830 	TAILQ_INIT(&sc->sc_freecmd);
831 	TAILQ_INIT(&sc->sc_xfercmd);
832 
833 	for (i = 0; i < UDL_NCMDQ; i++) {
834 		cmdq = &sc->sc_cmdq[i];
835 
836 		cmdq->cq_sc = sc;
837 
838 		cmdq->cq_xfer = usbd_alloc_xfer(sc->sc_udev);
839 		if (cmdq->cq_xfer == NULL) {
840 			aprint_error_dev(sc->sc_dev,
841 			    "%s: can't allocate xfer handle!\n", __func__);
842 			goto error;
843 		}
844 
845 		cmdq->cq_buf =
846 		    usbd_alloc_buffer(cmdq->cq_xfer, UDL_CMD_BUFFER_SIZE);
847 		if (cmdq->cq_buf == NULL) {
848 			aprint_error_dev(sc->sc_dev,
849 			    "%s: can't allocate xfer buffer!\n", __func__);
850 			goto error;
851 		}
852 
853 		TAILQ_INSERT_TAIL(&sc->sc_freecmd, cmdq, cq_chain);
854 	}
855 
856 	return 0;
857 
858  error:
859 	udl_cmdq_free(sc);
860 	return -1;
861 }
862 
863 static void
864 udl_cmdq_free(struct udl_softc *sc)
865 {
866 	struct udl_cmdq *cmdq;
867 	int i;
868 
869 	for (i = 0; i < UDL_NCMDQ; i++) {
870 		cmdq = &sc->sc_cmdq[i];
871 
872 		if (cmdq->cq_xfer != NULL) {
873 			usbd_free_xfer(cmdq->cq_xfer);
874 			cmdq->cq_xfer = NULL;
875 			cmdq->cq_buf = NULL;
876 		}
877 	}
878 }
879 
880 static struct udl_cmdq *
881 udl_cmdq_get(struct udl_softc *sc)
882 {
883 	struct udl_cmdq *cmdq;
884 
885 	cmdq = TAILQ_FIRST(&sc->sc_freecmd);
886 	if (cmdq != NULL) {
887 		TAILQ_REMOVE(&sc->sc_freecmd, cmdq, cq_chain);
888 		UDL_EVCNT_INCR(&sc->sc_ev_cmdq_get);
889 	}
890 
891 	return cmdq;
892 }
893 
894 static void
895 udl_cmdq_put(struct udl_softc *sc, struct udl_cmdq *cmdq)
896 {
897 
898 	TAILQ_INSERT_TAIL(&sc->sc_freecmd, cmdq, cq_chain);
899 	UDL_EVCNT_INCR(&sc->sc_ev_cmdq_put);
900 }
901 
902 static void
903 udl_cmdq_flush(struct udl_softc *sc)
904 {
905 
906 	mutex_enter(&sc->sc_mtx);
907 	while (TAILQ_FIRST(&sc->sc_xfercmd) != NULL)
908 		cv_wait(&sc->sc_cv, &sc->sc_mtx);
909 	mutex_exit(&sc->sc_mtx);
910 }
911 
912 static void
913 udl_cursor(void *cookie, int on, int row, int col)
914 {
915 	struct rasops_info *ri = cookie;
916 	struct udl_softc *sc = ri->ri_hw;
917 	int x, y, width, height;
918 
919 	if (ri->ri_flg & RI_CURSOR)
920 		udl_restore_char(ri);
921 
922 	ri->ri_crow = row;
923 	ri->ri_ccol = col;
924 
925 	if (on != 0) {
926 		ri->ri_flg |= RI_CURSOR;
927 
928 		x = col * ri->ri_font->fontwidth;
929 		y = row * ri->ri_font->fontheight;
930 		width = ri->ri_font->fontwidth;
931 		height = ri->ri_font->fontheight;
932 
933 		/* save the last character block to off-screen */
934 		udl_copy_rect(sc, x, y, 0, sc->sc_offscreen, width, height);
935 
936 		/* draw cursor */
937 		udl_fill_rect(sc, 0xffff, x, y, width, 1);
938 		udl_fill_rect(sc, 0xffff, x, y + 1, 1, height - 2);
939 		udl_fill_rect(sc, 0xffff, x + width - 1, y + 1, 1, height - 2);
940 		udl_fill_rect(sc, 0xffff, x, y + height - 1, width, 1);
941 
942 		udl_cmd_send_async(sc);
943 	} else
944 		ri->ri_flg &= ~RI_CURSOR;
945 }
946 
947 static void
948 udl_putchar(void *cookie, int row, int col, u_int uc, long attr)
949 {
950 	struct rasops_info *ri = cookie;
951 	struct udl_softc *sc = ri->ri_hw;
952 	uint16_t rgb16[2];
953 	int fg, bg, underline, x, y, width, height;
954 
955 	rasops_unpack_attr(attr, &fg, &bg, &underline);
956 	rgb16[1] = (uint16_t)ri->ri_devcmap[fg];
957 	rgb16[0] = (uint16_t)ri->ri_devcmap[bg];
958 
959 	x = col * ri->ri_font->fontwidth;
960 	y = row * ri->ri_font->fontheight;
961 	width = ri->ri_font->fontwidth;
962 	height = ri->ri_font->fontheight;
963 
964 	if (uc == ' ') {
965 		/*
966 		 * Writting a block for the space character instead rendering
967 		 * it from font bits is more slim.
968 		 */
969 		udl_fill_rect(sc, rgb16[0], x, y, width, height);
970 	} else {
971 		/* render a character from font bits */
972 		udl_draw_char(ri, rgb16, uc, x, y);
973 	}
974 
975 	if (underline != 0)
976 		udl_fill_rect(sc, rgb16[1], x, y + height - 1, width, 1);
977 
978 #if 0
979 	udl_cmd_send_async(sc);
980 #endif
981 }
982 
983 static void
984 udl_copycols(void *cookie, int row, int src, int dst, int num)
985 {
986 	struct rasops_info *ri = cookie;
987 	struct udl_softc *sc = ri->ri_hw;
988 	int sx, dx, y, width, height;
989 
990 	sx = src * ri->ri_font->fontwidth;
991 	dx = dst * ri->ri_font->fontwidth;
992 	y = row * ri->ri_font->fontheight;
993 	width = num * ri->ri_font->fontwidth;
994 	height = ri->ri_font->fontheight;
995 
996 	/* copy row block to off-screen first to fix overlay-copy problem */
997 	udl_copy_rect(sc, sx, y, 0, sc->sc_offscreen, width, height);
998 
999 	/* copy row block back from off-screen now */
1000 	udl_copy_rect(sc, 0, sc->sc_offscreen, dx, y, width, height);
1001 #if 0
1002 	udl_cmd_send_async(sc);
1003 #endif
1004 }
1005 
1006 static void
1007 udl_erasecols(void *cookie, int row, int col, int num, long attr)
1008 {
1009 	struct rasops_info *ri = cookie;
1010 	struct udl_softc *sc = ri->ri_hw;
1011 	uint16_t rgb16;
1012 	int fg, bg, x, y, width, height;
1013 
1014 	rasops_unpack_attr(attr, &fg, &bg, NULL);
1015 	rgb16 = (uint16_t)ri->ri_devcmap[bg];
1016 
1017 	x = col * ri->ri_font->fontwidth;
1018 	y = row * ri->ri_font->fontheight;
1019 	width = num * ri->ri_font->fontwidth;
1020 	height = ri->ri_font->fontheight;
1021 
1022 	udl_fill_rect(sc, rgb16, x, y, width, height);
1023 #if 0
1024 	udl_cmd_send_async(sc);
1025 #endif
1026 }
1027 
1028 static void
1029 udl_copyrows(void *cookie, int src, int dst, int num)
1030 {
1031 	struct rasops_info *ri = cookie;
1032 	struct udl_softc *sc = ri->ri_hw;
1033 	int sy, ey, dy, width, height;
1034 
1035 	width = ri->ri_emuwidth;
1036 	height = ri->ri_font->fontheight;
1037 
1038 	if (dst < src) {
1039 		sy = src * height;
1040 		ey = (src + num) * height;
1041 		dy = dst * height;
1042 
1043 		while (sy < ey) {
1044 			udl_copy_rect(sc, 0, sy, 0, dy, width, height);
1045 			sy += height;
1046 			dy += height;
1047 		}
1048 	} else {
1049 		sy = (src + num) * height;
1050 		ey = src * height;
1051 		dy = (dst + num) * height;
1052 
1053 		while (sy > ey) {
1054 			sy -= height;
1055 			dy -= height;
1056 			udl_copy_rect(sc, 0, sy, 0, dy, width, height);
1057 		}
1058 	}
1059 #if 0
1060 	udl_cmd_send_async(sc);
1061 #endif
1062 }
1063 
1064 static void
1065 udl_eraserows(void *cookie, int row, int num, long attr)
1066 {
1067 	struct rasops_info *ri = cookie;
1068 	struct udl_softc *sc = ri->ri_hw;
1069 	uint16_t rgb16;
1070 	int fg, bg, y, width, height;
1071 
1072 	rasops_unpack_attr(attr, &fg, &bg, NULL);
1073 	rgb16 = (uint16_t)ri->ri_devcmap[bg];
1074 
1075 	y = row * ri->ri_font->fontheight;
1076 	width = ri->ri_emuwidth;
1077 	height = num * ri->ri_font->fontheight;
1078 
1079 	udl_fill_rect(sc, rgb16, 0, y, width, height);
1080 #if 0
1081 	udl_cmd_send_async(sc);
1082 #endif
1083 }
1084 
1085 static void
1086 udl_restore_char(struct rasops_info *ri)
1087 {
1088 	struct udl_softc *sc = ri->ri_hw;
1089 	int x, y, width, height;
1090 
1091 	x = ri->ri_ccol * ri->ri_font->fontwidth;
1092 	y = ri->ri_crow * ri->ri_font->fontheight;
1093 	width = ri->ri_font->fontwidth;
1094 	height = ri->ri_font->fontheight;
1095 
1096 	/* restore the last saved character from off-screen */
1097 	udl_copy_rect(sc, 0, sc->sc_offscreen, x, y, width, height);
1098 }
1099 
1100 static void
1101 udl_draw_char(struct rasops_info *ri, uint16_t *rgb16, u_int uc, int x, int y)
1102 {
1103 	struct udl_softc *sc = ri->ri_hw;
1104 	struct wsdisplay_font *font = ri->ri_font;
1105 	uint32_t fontbits;
1106 	uint16_t pixels[32];
1107 	uint8_t *fontbase;
1108 	int i, soff, eoff;
1109 
1110 	soff = y * sc->sc_width + x;
1111 	eoff = (y + font->fontheight) * sc->sc_width + x;
1112 	fontbase = (uint8_t *)font->data + (uc - font->firstchar) *
1113 	    ri->ri_fontscale;
1114 
1115 	while (soff < eoff) {
1116 		fontbits = 0;
1117 		switch (font->stride) {
1118 		case 4:
1119 			fontbits |= fontbase[3];
1120 			/* FALLTHROUGH */
1121 		case 3:
1122 			fontbits |= fontbase[2] << 8;
1123 			/* FALLTHROUGH */
1124 		case 2:
1125 			fontbits |= fontbase[1] << 16;
1126 			/* FALLTHROUGH */
1127 		case 1:
1128 			fontbits |= fontbase[0] << 24;
1129 		}
1130 		fontbase += font->stride;
1131 
1132 		for (i = 0; i < font->fontwidth; i++) {
1133 			pixels[i] = rgb16[(fontbits >> 31) & 1];
1134 			fontbits <<= 1;
1135 		}
1136 
1137 		udl_draw_line(sc, pixels, soff, font->fontwidth);
1138 		soff += sc->sc_width;
1139 	}
1140 }
1141 
1142 static void
1143 udl_copy_rect(struct udl_softc *sc, int sx, int sy, int dx, int dy, int width,
1144     int height)
1145 {
1146 	int sbase, soff, ebase, eoff, dbase, doff, width_cur;
1147 
1148 	sbase = sy * sc->sc_width;
1149 	ebase = (sy + height) * sc->sc_width;
1150 	dbase = dy * sc->sc_width;
1151 
1152 	while (width > 0) {
1153 		soff = sbase + sx;
1154 		eoff = ebase + sx;
1155 		doff = dbase + dx;
1156 
1157 		if (width >= UDL_CMD_WIDTH_MAX)
1158 			width_cur = UDL_CMD_WIDTH_MAX;
1159 		else
1160 			width_cur = width;
1161 
1162 		while (soff < eoff) {
1163 			udl_copy_line(sc, soff, doff, width_cur);
1164 			soff += sc->sc_width;
1165 			doff += sc->sc_width;
1166 		}
1167 
1168 		sx += width_cur;
1169 		dx += width_cur;
1170 		width -= width_cur;
1171 	}
1172 }
1173 
1174 static void
1175 udl_fill_rect(struct udl_softc *sc, uint16_t rgb16, int x, int y, int width,
1176     int height)
1177 {
1178 	int sbase, soff, ebase, eoff, width_cur;
1179 
1180 	sbase = y * sc->sc_width;
1181 	ebase = (y + height) * sc->sc_width;
1182 
1183 	while (width > 0) {
1184 		soff = sbase + x;
1185 		eoff = ebase + x;
1186 
1187 		if (width >= UDL_CMD_WIDTH_MAX)
1188 			width_cur = UDL_CMD_WIDTH_MAX;
1189 		else
1190 			width_cur = width;
1191 
1192 		while (soff < eoff) {
1193 			udl_fill_line(sc, rgb16, soff, width_cur);
1194 			soff += sc->sc_width;
1195 		}
1196 
1197 		x += width_cur;
1198 		width -= width_cur;
1199 	}
1200 }
1201 
1202 #ifdef notyet
1203 static void
1204 udl_draw_rect(struct udl_softc *sc, struct udl_ioctl_damage *d)
1205 {
1206 	int sbase, soff, ebase, eoff, x, y, width, width_cur, height;
1207 
1208 	x = d->x1;
1209 	y = d->y1;
1210 	width = d->x2 - d->x1;
1211 	height = d->y2 - d->y1;
1212 	sbase = y * sc->sc_width;
1213 	ebase = (y + height) * sc->sc_width;
1214 
1215 	while (width > 0) {
1216 		soff = sbase + x;
1217 		eoff = ebase + x;
1218 
1219 		if (width >= UDL_CMD_WIDTH_MAX)
1220 			width_cur = UDL_CMD_WIDTH_MAX;
1221 		else
1222 			width_cur = width;
1223 
1224 		while (soff < eoff) {
1225 			udl_draw_line(sc, (uint16_t *)sc->sc_fbmem + soff,
1226 			    soff, width_cur);
1227 			soff += sc->sc_width;
1228 		}
1229 
1230 		x += width_cur;
1231 		width -= width_cur;
1232 	}
1233 
1234 	udl_cmd_send_async(sc);
1235 }
1236 
1237 static void
1238 udl_draw_rect_comp(struct udl_softc *sc, struct udl_ioctl_damage *d)
1239 {
1240 	int soff, eoff, x, y, width, height;
1241 
1242 	x = d->x1;
1243 	y = d->y1;
1244 	width = d->x2 - d->x1;
1245 	height = d->y2 - d->y1;
1246 	soff = y * sc->sc_width + x;
1247 	eoff = (y + height) * sc->sc_width + x;
1248 
1249 	udl_reg_write_1(sc, UDL_REG_SYNC, 0xff);
1250 	sc->sc_cmd_cblen = 4;
1251 
1252 	while (soff < eoff) {
1253 		udl_draw_line_comp(sc, (uint16_t *)sc->sc_fbmem + soff, soff,
1254 		    width);
1255 		soff += sc->sc_width;
1256 	}
1257 
1258 	udl_cmd_send_async(sc);
1259 }
1260 #endif
1261 
1262 static inline void
1263 udl_copy_line(struct udl_softc *sc, int soff, int doff, int width)
1264 {
1265 
1266 	if (__predict_false((UDL_CMD_BUFSIZE(sc) + UDL_CMD_COPY_SIZE + 2) >
1267 	    UDL_CMD_BUFFER_SIZE))
1268 		udl_cmd_send_async(sc);
1269 
1270 	udl_cmd_add_2(sc, (UDL_BULK_SOC << 8) | UDL_BULK_CMD_FB_COPY16);
1271 	udl_cmd_add_4(sc, ((doff * 2) << 8) | (width & 0xff));
1272 
1273 	udl_cmd_add_3(sc, soff * 2);
1274 }
1275 
1276 static inline void
1277 udl_fill_line(struct udl_softc *sc, uint16_t rgb16, int off, int width)
1278 {
1279 
1280 	if (__predict_false((UDL_CMD_BUFSIZE(sc) + UDL_CMD_FILL_SIZE + 2) >
1281 	    UDL_CMD_BUFFER_SIZE))
1282 		udl_cmd_send_async(sc);
1283 
1284 	udl_cmd_add_2(sc, (UDL_BULK_SOC << 8) | UDL_BULK_CMD_FB_RLE16);
1285 	udl_cmd_add_4(sc, ((off * 2) << 8) | (width & 0xff));
1286 
1287 	udl_cmd_add_1(sc, width);
1288 	udl_cmd_add_2(sc, rgb16);
1289 }
1290 
1291 static inline void
1292 udl_draw_line(struct udl_softc *sc, uint16_t *buf, int off, int width)
1293 {
1294 
1295 	if (__predict_false(
1296 	    (UDL_CMD_BUFSIZE(sc) + UDL_CMD_DRAW_SIZE(width) + 2) >
1297 	    UDL_CMD_BUFFER_SIZE))
1298 		udl_cmd_send_async(sc);
1299 
1300 	udl_cmd_add_2(sc, (UDL_BULK_SOC << 8) | UDL_BULK_CMD_FB_WRITE16);
1301 	udl_cmd_add_4(sc, ((off * 2) << 8) | (width & 0xff));
1302 
1303 	udl_cmd_add_buf(sc, buf, width);
1304 }
1305 
1306 #ifdef notyet
1307 static inline int
1308 udl_cmd_add_buf_comp(struct udl_softc *sc, uint16_t *buf, int width)
1309 {
1310 	struct udl_huffman *h;
1311 	uint16_t *startp, *endp;
1312 	uint32_t bit_pattern;
1313 	uint16_t prev;
1314 	int16_t diff;
1315 	uint8_t bit_count, bit_pos, bit_rem, curlen;
1316 
1317 	startp = buf;
1318 	if (width >= UDL_CMD_WIDTH_MAX)
1319 		endp = buf + UDL_CMD_WIDTH_MAX;
1320 	else
1321 		endp = buf + width;
1322 
1323 	prev = bit_pos = *sc->sc_cmd_buf = 0;
1324 	bit_rem = 8;
1325 
1326 	/*
1327 	 * Generate a sub-block with maximal 256 pixels compressed data.
1328 	 */
1329 	while (buf < endp) {
1330 		/* get difference between current and previous pixel */
1331 		diff = *buf - prev;
1332 
1333 		/* get the huffman difference bit sequence */
1334 		h = (struct udl_huffman *)sc->sc_huffman_base + diff;
1335 		bit_count = h->bit_count;
1336 		bit_pattern = h->bit_pattern;
1337 
1338 		curlen = (bit_pos + bit_count + 7) / 8;
1339 		if (__predict_false((sc->sc_cmd_cblen + curlen + 1) >
1340 		    UDL_CMD_COMP_BLOCK_SIZE))
1341 			break;
1342 
1343 		/* generate one pixel compressed data */
1344 		while (bit_count >= bit_rem) {
1345 			*sc->sc_cmd_buf++ |=
1346 			    (bit_pattern & ((1 << bit_rem) - 1)) << bit_pos;
1347 			*sc->sc_cmd_buf = 0;
1348 			sc->sc_cmd_cblen++;
1349 			bit_count -= bit_rem;
1350 			bit_pattern >>= bit_rem;
1351 			bit_pos = 0;
1352 			bit_rem = 8;
1353 		}
1354 
1355 		if (bit_count > 0) {
1356 			*sc->sc_cmd_buf |=
1357 			    (bit_pattern & ((1 << bit_count) - 1)) << bit_pos;
1358 			bit_pos += bit_count;
1359 			bit_rem -= bit_count;
1360 		}
1361 
1362 		prev = *buf++;
1363 	}
1364 
1365 	/*
1366  	 * If we have bits left in our last byte, round up to the next
1367  	 * byte, so we don't overwrite them.
1368  	 */
1369 	if (bit_pos > 0) {
1370 		sc->sc_cmd_buf++;
1371 		sc->sc_cmd_cblen++;
1372 	}
1373 
1374 	/* return how many pixels we have compressed */
1375 	return buf - startp;
1376 }
1377 
1378 static inline void
1379 udl_draw_line_comp(struct udl_softc *sc, uint16_t *buf, int off, int width)
1380 {
1381 	uint8_t *widthp;
1382 	int width_cur;
1383 
1384 	while (width > 0) {
1385 		if (__predict_false(
1386 		    (sc->sc_cmd_cblen + UDL_CMD_COMP_MIN_SIZE + 1) >
1387 		    UDL_CMD_COMP_BLOCK_SIZE)) {
1388 			if (UDL_CMD_BUFSIZE(sc) < UDL_CMD_COMP_THRESHOLD) {
1389 				while (sc->sc_cmd_cblen <
1390 				    UDL_CMD_COMP_BLOCK_SIZE) {
1391 					*sc->sc_cmd_buf++ = 0;
1392 					sc->sc_cmd_cblen++;
1393 				}
1394 			} else
1395 				udl_cmd_send_async(sc);
1396 			udl_reg_write_1(sc, UDL_REG_SYNC, 0xff);
1397 			sc->sc_cmd_cblen = 4;
1398 		}
1399 
1400 		udl_cmd_add_2(sc, (UDL_BULK_SOC << 8) |
1401 		    (UDL_BULK_CMD_FB_WRITE16 | UDL_BULK_CMD_FB_COMP));
1402 		udl_cmd_add_4(sc, (off * 2) << 8);
1403 
1404 		widthp = sc->sc_cmd_buf - 1;
1405 
1406 		sc->sc_cmd_cblen += UDL_CMD_HEADER_SIZE;
1407 
1408 		width_cur = udl_cmd_add_buf_comp(sc, buf, width);
1409 
1410 		*widthp = width_cur;
1411 		buf += width_cur;
1412 		off += width_cur;
1413 		width -= width_cur;
1414 	}
1415 }
1416 #endif
1417 
1418 static int
1419 udl_cmd_send(struct udl_softc *sc)
1420 {
1421 	struct udl_cmdq *cmdq;
1422 	usbd_status error;
1423 	uint32_t len;
1424 
1425 	cmdq = sc->sc_cmd_cur;
1426 
1427 	/* mark end of command stack */
1428 	udl_cmd_add_2(sc, (UDL_BULK_SOC << 8) | UDL_BULK_CMD_EOC);
1429 
1430 	len = UDL_CMD_BUFSIZE(sc);
1431 
1432 	/* do xfer */
1433 	error = usbd_bulk_transfer(cmdq->cq_xfer, sc->sc_tx_pipeh,
1434 	    USBD_NO_COPY, USBD_NO_TIMEOUT, cmdq->cq_buf, &len, "udlcmds");
1435 
1436 	UDL_CMD_BUFINIT(sc);
1437 
1438 	if (error != USBD_NORMAL_COMPLETION) {
1439 		aprint_error_dev(sc->sc_dev, "%s: %s!\n", __func__,
1440 		    usbd_errstr(error));
1441 		return -1;
1442 	}
1443 
1444 	return 0;
1445 }
1446 
1447 static void
1448 udl_cmd_send_async(struct udl_softc *sc)
1449 {
1450 	struct udl_cmdq *cmdq;
1451 	usbd_status error;
1452 	uint32_t len;
1453 
1454 #if 1
1455 	/*
1456 	 * XXX
1457 	 * All tty ops for wsemul are called with tty_lock spin mutex held,
1458 	 * so we can't call cv_wait(9) here to acquire a free buffer.
1459 	 * For now, all commands and data for wsemul ops are discarded
1460 	 * if there is no free command buffer, and then screen text might
1461 	 * be corrupted on large scroll ops etc.
1462 	 *
1463 	 * Probably we have to reorganize the giant tty_lock mutex, or
1464 	 * change wsdisplay APIs (especially wsdisplaystart()) to return
1465 	 * a number of actually handled characters as OpenBSD does, but
1466 	 * the latter one requires whole API changes around rasops(9) etc.
1467 	 */
1468 	if (sc->sc_mode == WSDISPLAYIO_MODE_EMUL) {
1469 		if (TAILQ_FIRST(&sc->sc_freecmd) == NULL) {
1470 			UDL_CMD_BUFINIT(sc);
1471 			return;
1472 		}
1473 	}
1474 #endif
1475 
1476 	cmdq = sc->sc_cmd_cur;
1477 
1478 	/* mark end of command stack */
1479 	udl_cmd_add_2(sc, (UDL_BULK_SOC << 8) | UDL_BULK_CMD_EOC);
1480 
1481 	len = UDL_CMD_BUFSIZE(sc);
1482 
1483 	/* do xfer */
1484 	mutex_enter(&sc->sc_mtx);
1485 	usbd_setup_xfer(cmdq->cq_xfer, sc->sc_tx_pipeh, cmdq, cmdq->cq_buf,
1486 	    len, USBD_NO_COPY, USBD_NO_TIMEOUT, udl_cmd_send_async_cb);
1487 	error = usbd_transfer(cmdq->cq_xfer);
1488 	if (error != USBD_NORMAL_COMPLETION && error != USBD_IN_PROGRESS) {
1489 		aprint_error_dev(sc->sc_dev, "%s: %s!\n", __func__,
1490 		    usbd_errstr(error));
1491 		mutex_exit(&sc->sc_mtx);
1492 		goto end;
1493 	}
1494 
1495 	TAILQ_INSERT_TAIL(&sc->sc_xfercmd, cmdq, cq_chain);
1496 	cmdq = udl_cmdq_get(sc);
1497 	mutex_exit(&sc->sc_mtx);
1498 	while (cmdq == NULL) {
1499 		int err;
1500 		UDL_EVCNT_INCR(&sc->sc_ev_cmdq_wait);
1501 		mutex_enter(&sc->sc_mtx);
1502 		err = cv_timedwait(&sc->sc_cv, &sc->sc_mtx,
1503 		    mstohz(100) /* XXX is this needed? */);
1504 		if (err != 0) {
1505 			DPRINTF(("%s: %s: cv timeout (error = %d)\n",
1506 			    device_xname(sc->sc_dev), __func__, err));
1507 			UDL_EVCNT_INCR(&sc->sc_ev_cmdq_timeout);
1508 		}
1509 		cmdq = udl_cmdq_get(sc);
1510 		mutex_exit(&sc->sc_mtx);
1511 	}
1512 	sc->sc_cmd_cur = cmdq;
1513  end:
1514 	UDL_CMD_BUFINIT(sc);
1515 }
1516 
1517 static void
1518 udl_cmd_send_async_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
1519     usbd_status status)
1520 {
1521 	struct udl_cmdq *cmdq = priv;
1522 	struct udl_softc *sc = cmdq->cq_sc;
1523 
1524 	if (status != USBD_NORMAL_COMPLETION) {
1525 		aprint_error_dev(sc->sc_dev, "%s: %s!\n", __func__,
1526 		    usbd_errstr(status));
1527 
1528 		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
1529 			return;
1530 		if (status == USBD_STALLED)
1531 			usbd_clear_endpoint_stall_async(sc->sc_tx_pipeh);
1532 	}
1533 
1534 	mutex_enter(&sc->sc_mtx);
1535 	TAILQ_REMOVE(&sc->sc_xfercmd, cmdq, cq_chain);
1536 	udl_cmdq_put(sc, cmdq);
1537 
1538 	/* signal xfer op that sleeps for a free xfer buffer */
1539 	cv_signal(&sc->sc_cv);
1540 	mutex_exit(&sc->sc_mtx);
1541 }
1542 
1543 static int
1544 udl_ctrl_msg(struct udl_softc *sc, uint8_t rt, uint8_t r, uint16_t index,
1545     uint16_t value, uint8_t *buf, uint16_t len)
1546 {
1547 	usb_device_request_t req;
1548 	usbd_status error;
1549 
1550 	req.bmRequestType = rt;
1551 	req.bRequest = r;
1552 	USETW(req.wIndex, index);
1553 	USETW(req.wValue, value);
1554 	USETW(req.wLength, len);
1555 
1556 	error = usbd_do_request(sc->sc_udev, &req, buf);
1557 	if (error != USBD_NORMAL_COMPLETION) {
1558 		aprint_error_dev(sc->sc_dev, "%s: %s!\n", __func__,
1559 		    usbd_errstr(error));
1560 		return -1;
1561 	}
1562 
1563 	return 0;
1564 }
1565 
1566 static int
1567 udl_init(struct udl_softc *sc)
1568 {
1569 	static uint8_t key[16] = {
1570 	    0x57, 0xcd, 0xdc, 0xa7, 0x1c, 0x88, 0x5e, 0x15,
1571 	    0x60, 0xfe, 0xc6, 0x97, 0x16, 0x3d, 0x47, 0xf2
1572 	};
1573 	uint8_t status[4], val;
1574 
1575 	if (udl_ctrl_msg(sc, UT_READ_VENDOR_DEVICE, UDL_CTRL_CMD_READ_STATUS,
1576 	    0x0000, 0x0000, status, sizeof(status)) != 0)
1577 		return -1;
1578 
1579 	if (udl_ctrl_msg(sc, UT_READ_VENDOR_DEVICE, UDL_CTRL_CMD_READ_1,
1580 	    0xc484, 0x0000, &val, 1) != 0)
1581 		return -1;
1582 
1583 	val = 1;
1584 	if (udl_ctrl_msg(sc, UT_WRITE_VENDOR_DEVICE, UDL_CTRL_CMD_WRITE_1,
1585 	    0xc41f, 0x0000, &val, 1) != 0)
1586 		return -1;
1587 
1588 	if (udl_ctrl_msg(sc, UT_WRITE_VENDOR_DEVICE, UDL_CTRL_CMD_SET_KEY,
1589 	    0x0000, 0x0000, key, sizeof(key)) != 0)
1590 		return -1;
1591 
1592 	val = 0;
1593 	if (udl_ctrl_msg(sc, UT_WRITE_VENDOR_DEVICE, UDL_CTRL_CMD_WRITE_1,
1594 	    0xc40b, 0x0000, &val, 1) != 0)
1595 		return -1;
1596 
1597 	return 0;
1598 }
1599 
1600 static void
1601 udl_read_edid(struct udl_softc *sc)
1602 {
1603 	uint8_t buf[64], edid[128];
1604 	int offset;
1605 
1606 	memset(&sc->sc_ei, 0, sizeof(struct edid_info));
1607 
1608 	offset = 0;
1609 	if (udl_ctrl_msg(sc, UT_READ_VENDOR_DEVICE, UDL_CTRL_CMD_READ_EDID,
1610 	    0x00a1, (offset << 8), buf, 64) != 0)
1611 		return;
1612 	if (buf[0] != 0)
1613 		return;
1614 	memcpy(&edid[offset], &buf[1], 63);
1615 	offset += 63;
1616 
1617 	if (udl_ctrl_msg(sc, UT_READ_VENDOR_DEVICE, UDL_CTRL_CMD_READ_EDID,
1618 	    0x00a1, (offset << 8), buf, 64) != 0)
1619 		return;
1620 	if (buf[0] != 0)
1621 		return;
1622 	memcpy(&edid[offset], &buf[1], 63);
1623 	offset += 63;
1624 
1625 	if (udl_ctrl_msg(sc, UT_READ_VENDOR_DEVICE, UDL_CTRL_CMD_READ_EDID,
1626 	    0x00a1, (offset << 8), buf, 3) != 0)
1627 		return;
1628 	if (buf[0] != 0)
1629 		return;
1630 	memcpy(&edid[offset], &buf[1], 2);
1631 
1632 	if (edid_parse(edid, &sc->sc_ei) == 0) {
1633 #ifdef UDL_DEBUG
1634 		edid_print(&sc->sc_ei);
1635 #endif
1636 	}
1637 }
1638 
1639 static void
1640 udl_set_address(struct udl_softc *sc, int start16, int stride16, int start8,
1641     int stride8)
1642 {
1643 	udl_reg_write_1(sc, UDL_REG_SYNC, 0x00);
1644 	udl_reg_write_3(sc, UDL_REG_ADDR_START16, start16);
1645 	udl_reg_write_3(sc, UDL_REG_ADDR_STRIDE16, stride16);
1646 	udl_reg_write_3(sc, UDL_REG_ADDR_START8, start8);
1647 	udl_reg_write_3(sc, UDL_REG_ADDR_STRIDE8, stride8);
1648 	udl_reg_write_1(sc, UDL_REG_SYNC, 0xff);
1649 }
1650 
1651 static void
1652 udl_blank(struct udl_softc *sc, int blank)
1653 {
1654 
1655 	if (blank != 0)
1656 		udl_reg_write_1(sc, UDL_REG_BLANK, UDL_REG_BLANK_ON);
1657 	else
1658 		udl_reg_write_1(sc, UDL_REG_BLANK, UDL_REG_BLANK_OFF);
1659 	udl_reg_write_1(sc, UDL_REG_SYNC, 0xff);
1660 }
1661 
1662 static uint16_t
1663 udl_lfsr(uint16_t count)
1664 {
1665 	uint16_t val = 0xffff;
1666 
1667 	while (count > 0) {
1668 		val = (uint16_t)(val << 1) | ((uint16_t)(
1669 		    (uint16_t)(val << 0) ^
1670 		    (uint16_t)(val << 11) ^
1671 		    (uint16_t)(val << 13) ^
1672 		    (uint16_t)(val << 14)
1673 		    ) >> 15);
1674 		count--;
1675 	}
1676 
1677 	return val;
1678 }
1679 
1680 static int
1681 udl_set_resolution(struct udl_softc *sc, const struct videomode *vmp)
1682 {
1683 	uint16_t val;
1684 	int start16, stride16, start8, stride8;
1685 
1686 	/* set video memory offsets */
1687 	start16 = 0;
1688 	stride16 = sc->sc_width * 2;
1689 	start8 = stride16 * sc->sc_height;
1690 	stride8 = sc->sc_width;
1691 	udl_set_address(sc, start16, stride16, start8, stride8);
1692 
1693 	/* write resolution values */
1694 	udl_reg_write_1(sc, UDL_REG_SYNC, 0x00);
1695 	udl_reg_write_1(sc, UDL_REG_COLORDEPTH, UDL_REG_COLORDEPTH_16);
1696 	val = vmp->htotal - vmp->hsync_start;
1697 	udl_reg_write_2(sc, UDL_REG_XDISPLAYSTART, udl_lfsr(val));
1698 	val += vmp->hdisplay;
1699 	udl_reg_write_2(sc, UDL_REG_XDISPLAYEND, udl_lfsr(val));
1700 	val = vmp->vtotal - vmp->vsync_start;
1701 	udl_reg_write_2(sc, UDL_REG_YDISPLAYSTART, udl_lfsr(val));
1702 	val += vmp->vdisplay;
1703 	udl_reg_write_2(sc, UDL_REG_YDISPLAYEND, udl_lfsr(val));
1704 	val = vmp->htotal - 1;
1705 	udl_reg_write_2(sc, UDL_REG_XENDCOUNT, udl_lfsr(val));
1706 	val = vmp->hsync_end - vmp->hsync_start + 1;
1707 	if (vmp->flags & VID_PHSYNC) {
1708 		udl_reg_write_2(sc, UDL_REG_HSYNCSTART, udl_lfsr(1));
1709 		udl_reg_write_2(sc, UDL_REG_HSYNCEND, udl_lfsr(val));
1710 	} else {
1711 		udl_reg_write_2(sc, UDL_REG_HSYNCSTART, udl_lfsr(val));
1712 		udl_reg_write_2(sc, UDL_REG_HSYNCEND, udl_lfsr(1));
1713 	}
1714 	val = vmp->hdisplay;
1715 	udl_reg_write_2(sc, UDL_REG_HPIXELS, val);
1716 	val = vmp->vtotal;
1717 	udl_reg_write_2(sc, UDL_REG_YENDCOUNT, udl_lfsr(val));
1718 	val = vmp->vsync_end - vmp->vsync_start;
1719 	if (vmp->flags & VID_PVSYNC) {
1720 		udl_reg_write_2(sc, UDL_REG_VSYNCSTART, udl_lfsr(0));
1721 		udl_reg_write_2(sc, UDL_REG_VSYNCEND, udl_lfsr(val));
1722 	} else {
1723 		udl_reg_write_2(sc, UDL_REG_VSYNCSTART, udl_lfsr(val));
1724 		udl_reg_write_2(sc, UDL_REG_VSYNCEND, udl_lfsr(0));
1725 	}
1726 	val = vmp->vdisplay;
1727 	udl_reg_write_2(sc, UDL_REG_VPIXELS, val);
1728 	val = vmp->dot_clock / 5;
1729 	udl_reg_write_2(sc, UDL_REG_PIXELCLOCK5KHZ, bswap16(val));
1730 	udl_reg_write_1(sc, UDL_REG_SYNC, 0xff);
1731 
1732 	if (udl_cmd_send(sc) != 0)
1733 		return -1;
1734 
1735 	/* clear screen */
1736 	udl_fill_rect(sc, 0, 0, 0, sc->sc_width, sc->sc_height);
1737 
1738 	if (udl_cmd_send(sc) != 0)
1739 		return -1;
1740 
1741 	/* show framebuffer content */
1742 	udl_blank(sc, 0);
1743 
1744 	if (udl_cmd_send(sc) != 0)
1745 		return -1;
1746 
1747 	sc->sc_blank = WSDISPLAYIO_VIDEO_ON;
1748 
1749 	return 0;
1750 }
1751 
1752 static const struct videomode *
1753 udl_videomode_lookup(const char *name)
1754 {
1755 	int i;
1756 
1757 	for (i = 0; i < videomode_count; i++)
1758 		if (strcmp(name, videomode_list[i].name) == 0)
1759 			return &videomode_list[i];
1760 
1761 	return NULL;
1762 }
1763