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