/** * \file drm_ioc32.c * * 32-bit ioctl compatibility routines for the DRM. * * \author Paul Mackerras * * Copyright (C) Paul Mackerras 2005. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include #include #include "drmP.h" #include "drm_core.h" #define DRM_IOCTL_VERSION32 DRM_IOWR(0x00, drm_version32_t) #define DRM_IOCTL_GET_UNIQUE32 DRM_IOWR(0x01, drm_unique32_t) #define DRM_IOCTL_GET_MAP32 DRM_IOWR(0x04, drm_map32_t) #define DRM_IOCTL_GET_CLIENT32 DRM_IOWR(0x05, drm_client32_t) #define DRM_IOCTL_GET_STATS32 DRM_IOR( 0x06, drm_stats32_t) #define DRM_IOCTL_SET_UNIQUE32 DRM_IOW( 0x10, drm_unique32_t) #define DRM_IOCTL_ADD_MAP32 DRM_IOWR(0x15, drm_map32_t) #define DRM_IOCTL_ADD_BUFS32 DRM_IOWR(0x16, drm_buf_desc32_t) #define DRM_IOCTL_MARK_BUFS32 DRM_IOW( 0x17, drm_buf_desc32_t) #define DRM_IOCTL_INFO_BUFS32 DRM_IOWR(0x18, drm_buf_info32_t) #define DRM_IOCTL_MAP_BUFS32 DRM_IOWR(0x19, drm_buf_map32_t) #define DRM_IOCTL_FREE_BUFS32 DRM_IOW( 0x1a, drm_buf_free32_t) #define DRM_IOCTL_RM_MAP32 DRM_IOW( 0x1b, drm_map32_t) #define DRM_IOCTL_SET_SAREA_CTX32 DRM_IOW( 0x1c, drm_ctx_priv_map32_t) #define DRM_IOCTL_GET_SAREA_CTX32 DRM_IOWR(0x1d, drm_ctx_priv_map32_t) #define DRM_IOCTL_RES_CTX32 DRM_IOWR(0x26, drm_ctx_res32_t) #define DRM_IOCTL_DMA32 DRM_IOWR(0x29, drm_dma32_t) #define DRM_IOCTL_AGP_ENABLE32 DRM_IOW( 0x32, drm_agp_mode32_t) #define DRM_IOCTL_AGP_INFO32 DRM_IOR( 0x33, drm_agp_info32_t) #define DRM_IOCTL_AGP_ALLOC32 DRM_IOWR(0x34, drm_agp_buffer32_t) #define DRM_IOCTL_AGP_FREE32 DRM_IOW( 0x35, drm_agp_buffer32_t) #define DRM_IOCTL_AGP_BIND32 DRM_IOW( 0x36, drm_agp_binding32_t) #define DRM_IOCTL_AGP_UNBIND32 DRM_IOW( 0x37, drm_agp_binding32_t) #define DRM_IOCTL_SG_ALLOC32 DRM_IOW( 0x38, drm_scatter_gather32_t) #define DRM_IOCTL_SG_FREE32 DRM_IOW( 0x39, drm_scatter_gather32_t) #define DRM_IOCTL_WAIT_VBLANK32 DRM_IOWR(0x3a, drm_wait_vblank32_t) typedef struct drm_version_32 { int version_major; /**< Major version */ int version_minor; /**< Minor version */ int version_patchlevel; /**< Patch level */ u32 name_len; /**< Length of name buffer */ u32 name; /**< Name of driver */ u32 date_len; /**< Length of date buffer */ u32 date; /**< User-space buffer to hold date */ u32 desc_len; /**< Length of desc buffer */ u32 desc; /**< User-space buffer to hold desc */ } drm_version32_t; static int compat_drm_version(struct file *file, unsigned int cmd, unsigned long arg) { drm_version32_t v32; drm_version_t __user *version; int err; if (copy_from_user(&v32, (void __user *)arg, sizeof(v32))) return -EFAULT; version = compat_alloc_user_space(sizeof(*version)); if (!access_ok(VERIFY_WRITE, version, sizeof(*version))) return -EFAULT; if (__put_user(v32.name_len, &version->name_len) || __put_user((void __user *)(unsigned long)v32.name, &version->name) || __put_user(v32.date_len, &version->date_len) || __put_user((void __user *)(unsigned long)v32.date, &version->date) || __put_user(v32.desc_len, &version->desc_len) || __put_user((void __user *)(unsigned long)v32.desc, &version->desc)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_VERSION, (unsigned long)version); if (err) return err; if (__get_user(v32.version_major, &version->version_major) || __get_user(v32.version_minor, &version->version_minor) || __get_user(v32.version_patchlevel, &version->version_patchlevel) || __get_user(v32.name_len, &version->name_len) || __get_user(v32.date_len, &version->date_len) || __get_user(v32.desc_len, &version->desc_len)) return -EFAULT; if (copy_to_user((void __user *)arg, &v32, sizeof(v32))) return -EFAULT; return 0; } typedef struct drm_unique32 { u32 unique_len; /**< Length of unique */ u32 unique; /**< Unique name for driver instantiation */ } drm_unique32_t; static int compat_drm_getunique(struct file *file, unsigned int cmd, unsigned long arg) { drm_unique32_t uq32; drm_unique_t __user *u; int err; if (copy_from_user(&uq32, (void __user *)arg, sizeof(uq32))) return -EFAULT; u = compat_alloc_user_space(sizeof(*u)); if (!access_ok(VERIFY_WRITE, u, sizeof(*u))) return -EFAULT; if (__put_user(uq32.unique_len, &u->unique_len) || __put_user((void __user *)(unsigned long)uq32.unique, &u->unique)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_GET_UNIQUE, (unsigned long)u); if (err) return err; if (__get_user(uq32.unique_len, &u->unique_len)) return -EFAULT; if (copy_to_user((void __user *)arg, &uq32, sizeof(uq32))) return -EFAULT; return 0; } static int compat_drm_setunique(struct file *file, unsigned int cmd, unsigned long arg) { drm_unique32_t uq32; drm_unique_t __user *u; if (copy_from_user(&uq32, (void __user *)arg, sizeof(uq32))) return -EFAULT; u = compat_alloc_user_space(sizeof(*u)); if (!access_ok(VERIFY_WRITE, u, sizeof(*u))) return -EFAULT; if (__put_user(uq32.unique_len, &u->unique_len) || __put_user((void __user *)(unsigned long)uq32.unique, &u->unique)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_SET_UNIQUE, (unsigned long)u); } typedef struct drm_map32 { u32 offset; /**< Requested physical address (0 for SAREA)*/ u32 size; /**< Requested physical size (bytes) */ drm_map_type_t type; /**< Type of memory to map */ drm_map_flags_t flags; /**< Flags */ u32 handle; /**< User-space: "Handle" to pass to mmap() */ int mtrr; /**< MTRR slot used */ } drm_map32_t; static int compat_drm_getmap(struct file *file, unsigned int cmd, unsigned long arg) { drm_map32_t __user *argp = (void __user *)arg; drm_map32_t m32; drm_map_t __user *map; int idx, err; void *handle; if (get_user(idx, &argp->offset)) return -EFAULT; map = compat_alloc_user_space(sizeof(*map)); if (!access_ok(VERIFY_WRITE, map, sizeof(*map))) return -EFAULT; if (__put_user(idx, &map->offset)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_GET_MAP, (unsigned long)map); if (err) return err; if (__get_user(m32.offset, &map->offset) || __get_user(m32.size, &map->size) || __get_user(m32.type, &map->type) || __get_user(m32.flags, &map->flags) || __get_user(handle, &map->handle) || __get_user(m32.mtrr, &map->mtrr)) return -EFAULT; m32.handle = (unsigned long)handle; if (copy_to_user(argp, &m32, sizeof(m32))) return -EFAULT; return 0; } static int compat_drm_addmap(struct file *file, unsigned int cmd, unsigned long arg) { drm_map32_t __user *argp = (void __user *)arg; drm_map32_t m32; drm_map_t __user *map; int err; void *handle; if (copy_from_user(&m32, argp, sizeof(m32))) return -EFAULT; map = compat_alloc_user_space(sizeof(*map)); if (!access_ok(VERIFY_WRITE, map, sizeof(*map))) return -EFAULT; if (__put_user(m32.offset, &map->offset) || __put_user(m32.size, &map->size) || __put_user(m32.type, &map->type) || __put_user(m32.flags, &map->flags)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_ADD_MAP, (unsigned long)map); if (err) return err; if (__get_user(m32.offset, &map->offset) || __get_user(m32.mtrr, &map->mtrr) || __get_user(handle, &map->handle)) return -EFAULT; m32.handle = (unsigned long)handle; if (m32.handle != (unsigned long)handle && printk_ratelimit()) printk(KERN_ERR "compat_drm_addmap truncated handle" " %p for type %d offset %x\n", handle, m32.type, m32.offset); if (copy_to_user(argp, &m32, sizeof(m32))) return -EFAULT; return 0; } static int compat_drm_rmmap(struct file *file, unsigned int cmd, unsigned long arg) { drm_map32_t __user *argp = (void __user *)arg; drm_map_t __user *map; u32 handle; if (get_user(handle, &argp->handle)) return -EFAULT; map = compat_alloc_user_space(sizeof(*map)); if (!access_ok(VERIFY_WRITE, map, sizeof(*map))) return -EFAULT; if (__put_user((void *)(unsigned long)handle, &map->handle)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_RM_MAP, (unsigned long)map); } typedef struct drm_client32 { int idx; /**< Which client desired? */ int auth; /**< Is client authenticated? */ u32 pid; /**< Process ID */ u32 uid; /**< User ID */ u32 magic; /**< Magic */ u32 iocs; /**< Ioctl count */ } drm_client32_t; static int compat_drm_getclient(struct file *file, unsigned int cmd, unsigned long arg) { drm_client32_t c32; drm_client32_t __user *argp = (void __user *)arg; drm_client_t __user *client; int idx, err; if (get_user(idx, &argp->idx)) return -EFAULT; client = compat_alloc_user_space(sizeof(*client)); if (!access_ok(VERIFY_WRITE, client, sizeof(*client))) return -EFAULT; if (__put_user(idx, &client->idx)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_GET_CLIENT, (unsigned long)client); if (err) return err; if (__get_user(c32.auth, &client->auth) || __get_user(c32.pid, &client->pid) || __get_user(c32.uid, &client->uid) || __get_user(c32.magic, &client->magic) || __get_user(c32.iocs, &client->iocs)) return -EFAULT; if (copy_to_user(argp, &c32, sizeof(c32))) return -EFAULT; return 0; } typedef struct drm_stats32 { u32 count; struct { u32 value; drm_stat_type_t type; } data[15]; } drm_stats32_t; static int compat_drm_getstats(struct file *file, unsigned int cmd, unsigned long arg) { drm_stats32_t s32; drm_stats32_t __user *argp = (void __user *)arg; drm_stats_t __user *stats; int i, err; stats = compat_alloc_user_space(sizeof(*stats)); if (!access_ok(VERIFY_WRITE, stats, sizeof(*stats))) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_GET_STATS, (unsigned long)stats); if (err) return err; if (__get_user(s32.count, &stats->count)) return -EFAULT; for (i = 0; i < 15; ++i) if (__get_user(s32.data[i].value, &stats->data[i].value) || __get_user(s32.data[i].type, &stats->data[i].type)) return -EFAULT; if (copy_to_user(argp, &s32, sizeof(s32))) return -EFAULT; return 0; } typedef struct drm_buf_desc32 { int count; /**< Number of buffers of this size */ int size; /**< Size in bytes */ int low_mark; /**< Low water mark */ int high_mark; /**< High water mark */ int flags; u32 agp_start; /**< Start address in the AGP aperture */ } drm_buf_desc32_t; static int compat_drm_addbufs(struct file *file, unsigned int cmd, unsigned long arg) { drm_buf_desc32_t __user *argp = (void __user *)arg; drm_buf_desc_t __user *buf; int err; unsigned long agp_start; buf = compat_alloc_user_space(sizeof(*buf)); if (!access_ok(VERIFY_WRITE, buf, sizeof(*buf)) || !access_ok(VERIFY_WRITE, argp, sizeof(*argp))) return -EFAULT; if (__copy_in_user(buf, argp, offsetof(drm_buf_desc32_t, agp_start)) || __get_user(agp_start, &argp->agp_start) || __put_user(agp_start, &buf->agp_start)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_ADD_BUFS, (unsigned long)buf); if (err) return err; if (__copy_in_user(argp, buf, offsetof(drm_buf_desc32_t, agp_start)) || __get_user(agp_start, &buf->agp_start) || __put_user(agp_start, &argp->agp_start)) return -EFAULT; return 0; } static int compat_drm_markbufs(struct file *file, unsigned int cmd, unsigned long arg) { drm_buf_desc32_t b32; drm_buf_desc32_t __user *argp = (void __user *)arg; drm_buf_desc_t __user *buf; if (copy_from_user(&b32, argp, sizeof(b32))) return -EFAULT; buf = compat_alloc_user_space(sizeof(*buf)); if (!access_ok(VERIFY_WRITE, buf, sizeof(*buf))) return -EFAULT; if (__put_user(b32.size, &buf->size) || __put_user(b32.low_mark, &buf->low_mark) || __put_user(b32.high_mark, &buf->high_mark)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_MARK_BUFS, (unsigned long)buf); } typedef struct drm_buf_info32 { int count; /**< Entries in list */ u32 list; } drm_buf_info32_t; static int compat_drm_infobufs(struct file *file, unsigned int cmd, unsigned long arg) { drm_buf_info32_t req32; drm_buf_info32_t __user *argp = (void __user *)arg; drm_buf_desc32_t __user *to; drm_buf_info_t __user *request; drm_buf_desc_t __user *list; size_t nbytes; int i, err; int count, actual; if (copy_from_user(&req32, argp, sizeof(req32))) return -EFAULT; count = req32.count; to = (drm_buf_desc32_t __user *)(unsigned long)req32.list; if (count < 0) count = 0; if (count > 0 && !access_ok(VERIFY_WRITE, to, count * sizeof(drm_buf_desc32_t))) return -EFAULT; nbytes = sizeof(*request) + count * sizeof(drm_buf_desc_t); request = compat_alloc_user_space(nbytes); if (!access_ok(VERIFY_WRITE, request, nbytes)) return -EFAULT; list = (drm_buf_desc_t *) (request + 1); if (__put_user(count, &request->count) || __put_user(list, &request->list)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_INFO_BUFS, (unsigned long)request); if (err) return err; if (__get_user(actual, &request->count)) return -EFAULT; if (count >= actual) for (i = 0; i < actual; ++i) if (__copy_in_user(&to[i], &list[i], offsetof(drm_buf_desc_t, flags))) return -EFAULT; if (__put_user(actual, &argp->count)) return -EFAULT; return 0; } typedef struct drm_buf_pub32 { int idx; /**< Index into the master buffer list */ int total; /**< Buffer size */ int used; /**< Amount of buffer in use (for DMA) */ u32 address; /**< Address of buffer */ } drm_buf_pub32_t; typedef struct drm_buf_map32 { int count; /**< Length of the buffer list */ u32 virtual; /**< Mmap'd area in user-virtual */ u32 list; /**< Buffer information */ } drm_buf_map32_t; static int compat_drm_mapbufs(struct file *file, unsigned int cmd, unsigned long arg) { drm_buf_map32_t __user *argp = (void __user *)arg; drm_buf_map32_t req32; drm_buf_pub32_t __user *list32; drm_buf_map_t __user *request; drm_buf_pub_t __user *list; int i, err; int count, actual; size_t nbytes; void __user *addr; if (copy_from_user(&req32, argp, sizeof(req32))) return -EFAULT; count = req32.count; list32 = (void __user *)(unsigned long)req32.list; if (count < 0) return -EINVAL; nbytes = sizeof(*request) + count * sizeof(drm_buf_pub_t); request = compat_alloc_user_space(nbytes); if (!access_ok(VERIFY_WRITE, request, nbytes)) return -EFAULT; list = (drm_buf_pub_t *) (request + 1); if (__put_user(count, &request->count) || __put_user(list, &request->list)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_MAP_BUFS, (unsigned long)request); if (err) return err; if (__get_user(actual, &request->count)) return -EFAULT; if (count >= actual) for (i = 0; i < actual; ++i) if (__copy_in_user(&list32[i], &list[i], offsetof(drm_buf_pub_t, address)) || __get_user(addr, &list[i].address) || __put_user((unsigned long)addr, &list32[i].address)) return -EFAULT; if (__put_user(actual, &argp->count) || __get_user(addr, &request->virtual) || __put_user((unsigned long)addr, &argp->virtual)) return -EFAULT; return 0; } typedef struct drm_buf_free32 { int count; u32 list; } drm_buf_free32_t; static int compat_drm_freebufs(struct file *file, unsigned int cmd, unsigned long arg) { drm_buf_free32_t req32; drm_buf_free_t __user *request; drm_buf_free32_t __user *argp = (void __user *)arg; if (copy_from_user(&req32, argp, sizeof(req32))) return -EFAULT; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request))) return -EFAULT; if (__put_user(req32.count, &request->count) || __put_user((int __user *)(unsigned long)req32.list, &request->list)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_FREE_BUFS, (unsigned long)request); } typedef struct drm_ctx_priv_map32 { unsigned int ctx_id; /**< Context requesting private mapping */ u32 handle; /**< Handle of map */ } drm_ctx_priv_map32_t; static int compat_drm_setsareactx(struct file *file, unsigned int cmd, unsigned long arg) { drm_ctx_priv_map32_t req32; drm_ctx_priv_map_t __user *request; drm_ctx_priv_map32_t __user *argp = (void __user *)arg; if (copy_from_user(&req32, argp, sizeof(req32))) return -EFAULT; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request))) return -EFAULT; if (__put_user(req32.ctx_id, &request->ctx_id) || __put_user((void *)(unsigned long)req32.handle, &request->handle)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_SET_SAREA_CTX, (unsigned long)request); } static int compat_drm_getsareactx(struct file *file, unsigned int cmd, unsigned long arg) { drm_ctx_priv_map_t __user *request; drm_ctx_priv_map32_t __user *argp = (void __user *)arg; int err; unsigned int ctx_id; void *handle; if (!access_ok(VERIFY_WRITE, argp, sizeof(*argp)) || __get_user(ctx_id, &argp->ctx_id)) return -EFAULT; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request))) return -EFAULT; if (__put_user(ctx_id, &request->ctx_id)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_GET_SAREA_CTX, (unsigned long)request); if (err) return err; if (__get_user(handle, &request->handle) || __put_user((unsigned long)handle, &argp->handle)) return -EFAULT; return 0; } typedef struct drm_ctx_res32 { int count; u32 contexts; } drm_ctx_res32_t; static int compat_drm_resctx(struct file *file, unsigned int cmd, unsigned long arg) { drm_ctx_res32_t __user *argp = (void __user *)arg; drm_ctx_res32_t res32; drm_ctx_res_t __user *res; int err; if (copy_from_user(&res32, argp, sizeof(res32))) return -EFAULT; res = compat_alloc_user_space(sizeof(*res)); if (!access_ok(VERIFY_WRITE, res, sizeof(*res))) return -EFAULT; if (__put_user(res32.count, &res->count) || __put_user((drm_ctx_t __user *)(unsigned long)res32.contexts, &res->contexts)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_RES_CTX, (unsigned long)res); if (err) return err; if (__get_user(res32.count, &res->count) || __put_user(res32.count, &argp->count)) return -EFAULT; return 0; } typedef struct drm_dma32 { int context; /**< Context handle */ int send_count; /**< Number of buffers to send */ u32 send_indices; /**< List of handles to buffers */ u32 send_sizes; /**< Lengths of data to send */ drm_dma_flags_t flags; /**< Flags */ int request_count; /**< Number of buffers requested */ int request_size; /**< Desired size for buffers */ u32 request_indices; /**< Buffer information */ u32 request_sizes; int granted_count; /**< Number of buffers granted */ } drm_dma32_t; static int compat_drm_dma(struct file *file, unsigned int cmd, unsigned long arg) { drm_dma32_t d32; drm_dma32_t __user *argp = (void __user *)arg; drm_dma_t __user *d; int err; if (copy_from_user(&d32, argp, sizeof(d32))) return -EFAULT; d = compat_alloc_user_space(sizeof(*d)); if (!access_ok(VERIFY_WRITE, d, sizeof(*d))) return -EFAULT; if (__put_user(d32.context, &d->context) || __put_user(d32.send_count, &d->send_count) || __put_user((int __user *)(unsigned long)d32.send_indices, &d->send_indices) || __put_user((int __user *)(unsigned long)d32.send_sizes, &d->send_sizes) || __put_user(d32.flags, &d->flags) || __put_user(d32.request_count, &d->request_count) || __put_user((int __user *)(unsigned long)d32.request_indices, &d->request_indices) || __put_user((int __user *)(unsigned long)d32.request_sizes, &d->request_sizes)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_DMA, (unsigned long)d); if (err) return err; if (__get_user(d32.request_size, &d->request_size) || __get_user(d32.granted_count, &d->granted_count) || __put_user(d32.request_size, &argp->request_size) || __put_user(d32.granted_count, &argp->granted_count)) return -EFAULT; return 0; } #if __OS_HAS_AGP typedef struct drm_agp_mode32 { u32 mode; /**< AGP mode */ } drm_agp_mode32_t; static int compat_drm_agp_enable(struct file *file, unsigned int cmd, unsigned long arg) { drm_agp_mode32_t __user *argp = (void __user *)arg; drm_agp_mode32_t m32; drm_agp_mode_t __user *mode; if (get_user(m32.mode, &argp->mode)) return -EFAULT; mode = compat_alloc_user_space(sizeof(*mode)); if (put_user(m32.mode, &mode->mode)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_AGP_ENABLE, (unsigned long)mode); } typedef struct drm_agp_info32 { int agp_version_major; int agp_version_minor; u32 mode; u32 aperture_base; /* physical address */ u32 aperture_size; /* bytes */ u32 memory_allowed; /* bytes */ u32 memory_used; /* PCI information */ unsigned short id_vendor; unsigned short id_device; } drm_agp_info32_t; static int compat_drm_agp_info(struct file *file, unsigned int cmd, unsigned long arg) { drm_agp_info32_t __user *argp = (void __user *)arg; drm_agp_info32_t i32; drm_agp_info_t __user *info; int err; info = compat_alloc_user_space(sizeof(*info)); if (!access_ok(VERIFY_WRITE, info, sizeof(*info))) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_AGP_INFO, (unsigned long)info); if (err) return err; if (__get_user(i32.agp_version_major, &info->agp_version_major) || __get_user(i32.agp_version_minor, &info->agp_version_minor) || __get_user(i32.mode, &info->mode) || __get_user(i32.aperture_base, &info->aperture_base) || __get_user(i32.aperture_size, &info->aperture_size) || __get_user(i32.memory_allowed, &info->memory_allowed) || __get_user(i32.memory_used, &info->memory_used) || __get_user(i32.id_vendor, &info->id_vendor) || __get_user(i32.id_device, &info->id_device)) return -EFAULT; if (copy_to_user(argp, &i32, sizeof(i32))) return -EFAULT; return 0; } typedef struct drm_agp_buffer32 { u32 size; /**< In bytes -- will round to page boundary */ u32 handle; /**< Used for binding / unbinding */ u32 type; /**< Type of memory to allocate */ u32 physical; /**< Physical used by i810 */ } drm_agp_buffer32_t; static int compat_drm_agp_alloc(struct file *file, unsigned int cmd, unsigned long arg) { drm_agp_buffer32_t __user *argp = (void __user *)arg; drm_agp_buffer32_t req32; drm_agp_buffer_t __user *request; int err; if (copy_from_user(&req32, argp, sizeof(req32))) return -EFAULT; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request)) || __put_user(req32.size, &request->size) || __put_user(req32.type, &request->type)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_AGP_ALLOC, (unsigned long)request); if (err) return err; if (__get_user(req32.handle, &request->handle) || __get_user(req32.physical, &request->physical) || copy_to_user(argp, &req32, sizeof(req32))) { drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_AGP_FREE, (unsigned long)request); return -EFAULT; } return 0; } static int compat_drm_agp_free(struct file *file, unsigned int cmd, unsigned long arg) { drm_agp_buffer32_t __user *argp = (void __user *)arg; drm_agp_buffer_t __user *request; u32 handle; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request)) || get_user(handle, &argp->handle) || __put_user(handle, &request->handle)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_AGP_FREE, (unsigned long)request); } typedef struct drm_agp_binding32 { u32 handle; /**< From drm_agp_buffer */ u32 offset; /**< In bytes -- will round to page boundary */ } drm_agp_binding32_t; static int compat_drm_agp_bind(struct file *file, unsigned int cmd, unsigned long arg) { drm_agp_binding32_t __user *argp = (void __user *)arg; drm_agp_binding32_t req32; drm_agp_binding_t __user *request; if (copy_from_user(&req32, argp, sizeof(req32))) return -EFAULT; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request)) || __put_user(req32.handle, &request->handle) || __put_user(req32.offset, &request->offset)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_AGP_BIND, (unsigned long)request); } static int compat_drm_agp_unbind(struct file *file, unsigned int cmd, unsigned long arg) { drm_agp_binding32_t __user *argp = (void __user *)arg; drm_agp_binding_t __user *request; u32 handle; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request)) || get_user(handle, &argp->handle) || __put_user(handle, &request->handle)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_AGP_UNBIND, (unsigned long)request); } #endif /* __OS_HAS_AGP */ typedef struct drm_scatter_gather32 { u32 size; /**< In bytes -- will round to page boundary */ u32 handle; /**< Used for mapping / unmapping */ } drm_scatter_gather32_t; static int compat_drm_sg_alloc(struct file *file, unsigned int cmd, unsigned long arg) { drm_scatter_gather32_t __user *argp = (void __user *)arg; drm_scatter_gather_t __user *request; int err; unsigned long x; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request)) || !access_ok(VERIFY_WRITE, argp, sizeof(*argp)) || __get_user(x, &argp->size) || __put_user(x, &request->size)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_SG_ALLOC, (unsigned long)request); if (err) return err; /* XXX not sure about the handle conversion here... */ if (__get_user(x, &request->handle) || __put_user(x >> PAGE_SHIFT, &argp->handle)) return -EFAULT; return 0; } static int compat_drm_sg_free(struct file *file, unsigned int cmd, unsigned long arg) { drm_scatter_gather32_t __user *argp = (void __user *)arg; drm_scatter_gather_t __user *request; unsigned long x; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request)) || !access_ok(VERIFY_WRITE, argp, sizeof(*argp)) || __get_user(x, &argp->handle) || __put_user(x << PAGE_SHIFT, &request->handle)) return -EFAULT; return drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_SG_FREE, (unsigned long)request); } struct drm_wait_vblank_request32 { drm_vblank_seq_type_t type; unsigned int sequence; u32 signal; }; struct drm_wait_vblank_reply32 { drm_vblank_seq_type_t type; unsigned int sequence; s32 tval_sec; s32 tval_usec; }; typedef union drm_wait_vblank32 { struct drm_wait_vblank_request32 request; struct drm_wait_vblank_reply32 reply; } drm_wait_vblank32_t; static int compat_drm_wait_vblank(struct file *file, unsigned int cmd, unsigned long arg) { drm_wait_vblank32_t __user *argp = (void __user *)arg; drm_wait_vblank32_t req32; drm_wait_vblank_t __user *request; int err; if (copy_from_user(&req32, argp, sizeof(req32))) return -EFAULT; request = compat_alloc_user_space(sizeof(*request)); if (!access_ok(VERIFY_WRITE, request, sizeof(*request)) || __put_user(req32.request.type, &request->request.type) || __put_user(req32.request.sequence, &request->request.sequence) || __put_user(req32.request.signal, &request->request.signal)) return -EFAULT; err = drm_ioctl(file->f_dentry->d_inode, file, DRM_IOCTL_WAIT_VBLANK, (unsigned long)request); if (err) return err; if (__get_user(req32.reply.type, &request->reply.type) || __get_user(req32.reply.sequence, &request->reply.sequence) || __get_user(req32.reply.tval_sec, &request->reply.tval_sec) || __get_user(req32.reply.tval_usec, &request->reply.tval_usec)) return -EFAULT; if (copy_to_user(argp, &req32, sizeof(req32))) return -EFAULT; return 0; } drm_ioctl_compat_t *drm_compat_ioctls[] = { [DRM_IOCTL_NR(DRM_IOCTL_VERSION32)] = compat_drm_version, [DRM_IOCTL_NR(DRM_IOCTL_GET_UNIQUE32)] = compat_drm_getunique, [DRM_IOCTL_NR(DRM_IOCTL_GET_MAP32)] = compat_drm_getmap, [DRM_IOCTL_NR(DRM_IOCTL_GET_CLIENT32)] = compat_drm_getclient, [DRM_IOCTL_NR(DRM_IOCTL_GET_STATS32)] = compat_drm_getstats, [DRM_IOCTL_NR(DRM_IOCTL_SET_UNIQUE32)] = compat_drm_setunique, [DRM_IOCTL_NR(DRM_IOCTL_ADD_MAP32)] = compat_drm_addmap, [DRM_IOCTL_NR(DRM_IOCTL_ADD_BUFS32)] = compat_drm_addbufs, [DRM_IOCTL_NR(DRM_IOCTL_MARK_BUFS32)] = compat_drm_markbufs, [DRM_IOCTL_NR(DRM_IOCTL_INFO_BUFS32)] = compat_drm_infobufs, [DRM_IOCTL_NR(DRM_IOCTL_MAP_BUFS32)] = compat_drm_mapbufs, [DRM_IOCTL_NR(DRM_IOCTL_FREE_BUFS32)] = compat_drm_freebufs, [DRM_IOCTL_NR(DRM_IOCTL_RM_MAP32)] = compat_drm_rmmap, [DRM_IOCTL_NR(DRM_IOCTL_SET_SAREA_CTX32)] = compat_drm_setsareactx, [DRM_IOCTL_NR(DRM_IOCTL_GET_SAREA_CTX32)] = compat_drm_getsareactx, [DRM_IOCTL_NR(DRM_IOCTL_RES_CTX32)] = compat_drm_resctx, [DRM_IOCTL_NR(DRM_IOCTL_DMA32)] = compat_drm_dma, #if __OS_HAS_AGP [DRM_IOCTL_NR(DRM_IOCTL_AGP_ENABLE32)] = compat_drm_agp_enable, [DRM_IOCTL_NR(DRM_IOCTL_AGP_INFO32)] = compat_drm_agp_info, [DRM_IOCTL_NR(DRM_IOCTL_AGP_ALLOC32)] = compat_drm_agp_alloc, [DRM_IOCTL_NR(DRM_IOCTL_AGP_FREE32)] = compat_drm_agp_free, [DRM_IOCTL_NR(DRM_IOCTL_AGP_BIND32)] = compat_drm_agp_bind, [DRM_IOCTL_NR(DRM_IOCTL_AGP_UNBIND32)] = compat_drm_agp_unbind, #endif [DRM_IOCTL_NR(DRM_IOCTL_SG_ALLOC32)] = compat_drm_sg_alloc, [DRM_IOCTL_NR(DRM_IOCTL_SG_FREE32)] = compat_drm_sg_free, [DRM_IOCTL_NR(DRM_IOCTL_WAIT_VBLANK32)] = compat_drm_wait_vblank, }; /** * Called whenever a 32-bit process running under a 64-bit kernel * performs an ioctl on /dev/drm. * * \param filp file pointer. * \param cmd command. * \param arg user argument. * \return zero on success or negative number on failure. */ long drm_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { unsigned int nr = DRM_IOCTL_NR(cmd); drm_ioctl_compat_t *fn; int ret; if (nr >= DRM_ARRAY_SIZE(drm_compat_ioctls)) return -ENOTTY; fn = drm_compat_ioctls[nr]; lock_kernel(); /* XXX for now */ if (fn != NULL) ret = (*fn)(filp, cmd, arg); else ret = drm_ioctl(filp->f_dentry->d_inode, filp, cmd, arg); unlock_kernel(); return ret; } EXPORT_SYMBOL(drm_compat_ioctl); 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
/*
 * DRM based mode setting test program
 * Copyright 2008 Tungsten Graphics
 *   Jakob Bornecrantz <jakob@tungstengraphics.com>
 * Copyright 2008 Intel Corporation
 *   Jesse Barnes <jesse.barnes@intel.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/*
 * This fairly simple test program dumps output in a similar format to the
 * "xrandr" tool everyone knows & loves.  It's necessarily slightly different
 * since the kernel separates outputs into encoder and connector structures,
 * each with their own unique ID.  The program also allows test testing of the
 * memory management and mode setting APIs by allowing the user to specify a
 * connector and mode to use for mode setting.  If all works as expected, a
 * blue background should be painted on the monitor attached to the specified
 * connector after the selected mode is set.
 *
 * TODO: use cairo to write the mode info on the selected output once
 *       the mode has been programmed, along with possible test patterns.
 */
#include "config.h"

#include <assert.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/poll.h>
#include <sys/time.h>

#include "xf86drm.h"
#include "xf86drmMode.h"
#include "drm_fourcc.h"
#include "libkms.h"

#include "buffers.h"

struct crtc {
	drmModeCrtc *crtc;
	drmModeObjectProperties *props;
	drmModePropertyRes **props_info;
	drmModeModeInfo *mode;
};

struct encoder {
	drmModeEncoder *encoder;
};

struct connector {
	drmModeConnector *connector;
	drmModeObjectProperties *props;
	drmModePropertyRes **props_info;
};

struct fb {
	drmModeFB *fb;
};

struct plane {
	drmModePlane *plane;
	drmModeObjectProperties *props;
	drmModePropertyRes **props_info;
};

struct source {
	drmModeSource *source;
};

struct resources {
	drmModeRes *res;
	drmModePlaneRes *plane_res;
	drmModeSourceRes *source_res;

	struct crtc *crtcs;
	struct encoder *encoders;
	struct connector *connectors;
	struct fb *fbs;
	struct plane *planes;
	struct source *sources;
};

struct device {
	int fd;

	struct resources *resources;
	struct kms_driver *kms;

	struct {
		unsigned int width;
		unsigned int height;

		unsigned int fb_id;
		struct kms_bo *bo;
	} mode;
};

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

struct type_name {
	int type;
	const char *name;
};

#define type_name_fn(res) \
const char * res##_str(int type) {			\
	unsigned int i;					\
	for (i = 0; i < ARRAY_SIZE(res##_names); i++) { \
		if (res##_names[i].type == type)	\
			return res##_names[i].name;	\
	}						\
	return "(invalid)";				\
}

struct type_name encoder_type_names[] = {
	{ DRM_MODE_ENCODER_NONE, "none" },
	{ DRM_MODE_ENCODER_DAC, "DAC" },
	{ DRM_MODE_ENCODER_TMDS, "TMDS" },
	{ DRM_MODE_ENCODER_LVDS, "LVDS" },
	{ DRM_MODE_ENCODER_TVDAC, "TVDAC" },
};

static type_name_fn(encoder_type)

struct type_name connector_status_names[] = {
	{ DRM_MODE_CONNECTED, "connected" },
	{ DRM_MODE_DISCONNECTED, "disconnected" },
	{ DRM_MODE_UNKNOWNCONNECTION, "unknown" },
};

static type_name_fn(connector_status)

struct type_name connector_type_names[] = {
	{ DRM_MODE_CONNECTOR_Unknown, "unknown" },
	{ DRM_MODE_CONNECTOR_VGA, "VGA" },
	{ DRM_MODE_CONNECTOR_DVII, "DVI-I" },
	{ DRM_MODE_CONNECTOR_DVID, "DVI-D" },
	{ DRM_MODE_CONNECTOR_DVIA, "DVI-A" },
	{ DRM_MODE_CONNECTOR_Composite, "composite" },
	{ DRM_MODE_CONNECTOR_SVIDEO, "s-video" },
	{ DRM_MODE_CONNECTOR_LVDS, "LVDS" },
	{ DRM_MODE_CONNECTOR_Component, "component" },
	{ DRM_MODE_CONNECTOR_9PinDIN, "9-pin DIN" },
	{ DRM_MODE_CONNECTOR_DisplayPort, "DP" },
	{ DRM_MODE_CONNECTOR_HDMIA, "HDMI-A" },
	{ DRM_MODE_CONNECTOR_HDMIB, "HDMI-B" },
	{ DRM_MODE_CONNECTOR_TV, "TV" },
	{ DRM_MODE_CONNECTOR_eDP, "eDP" },
};

static type_name_fn(connector_type)

#define bit_name_fn(res)					\
const char * res##_str(int type) {				\
	unsigned int i;						\
	const char *sep = "";					\
	for (i = 0; i < ARRAY_SIZE(res##_names); i++) {		\
		if (type & (1 << i)) {				\
			printf("%s%s", sep, res##_names[i]);	\
			sep = ", ";				\
		}						\
	}							\
	return NULL;						\
}

static const char *mode_type_names[] = {
	"builtin",
	"clock_c",
	"crtc_c",
	"preferred",
	"default",
	"userdef",
	"driver",
};

static bit_name_fn(mode_type)

static const char *mode_flag_names[] = {
	"phsync",
	"nhsync",
	"pvsync",
	"nvsync",
	"interlace",
	"dblscan",
	"csync",
	"pcsync",
	"ncsync",
	"hskew",
	"bcast",
	"pixmux",
	"dblclk",
	"clkdiv2"
};

static bit_name_fn(mode_flag)

static void dump_encoders(struct device *dev)
{
	drmModeEncoder *encoder;
	int i;

	printf("Encoders:\n");
	printf("id\tcrtc\ttype\tpossible crtcs\tpossible clones\t\n");
	for (i = 0; i < dev->resources->res->count_encoders; i++) {
		encoder = dev->resources->encoders[i].encoder;
		if (!encoder)
			continue;

		printf("%d\t%d\t%s\t0x%08x\t0x%08x\n",
		       encoder->encoder_id,
		       encoder->crtc_id,
		       encoder_type_str(encoder->encoder_type),
		       encoder->possible_crtcs,
		       encoder->possible_clones);
	}
	printf("\n");
}

static void dump_mode(drmModeModeInfo *mode)
{
	printf("  %s %d %d %d %d %d %d %d %d %d",
	       mode->name,
	       mode->vrefresh,
	       mode->hdisplay,
	       mode->hsync_start,
	       mode->hsync_end,
	       mode->htotal,
	       mode->vdisplay,
	       mode->vsync_start,
	       mode->vsync_end,
	       mode->vtotal);

	printf(" flags: ");
	mode_flag_str(mode->flags);
	printf("; type: ");
	mode_type_str(mode->type);
	printf("\n");
}

static void dump_blob(struct device *dev, uint32_t blob_id)
{
	uint32_t i;
	unsigned char *blob_data;
	drmModePropertyBlobPtr blob;

	blob = drmModeGetPropertyBlob(dev->fd, blob_id);
	if (!blob)
		return;

	blob_data = blob->data;

	for (i = 0; i < blob->length; i++) {
		if (i % 16 == 0)
			printf("\n\t\t\t");
		printf("%.2hhx", blob_data[i]);
	}
	printf("\n");

	drmModeFreePropertyBlob(blob);
}

static void dump_prop(struct device *dev, drmModePropertyPtr prop,
		      uint32_t prop_id, uint64_t value)
{
	int i;
	printf("\t%d", prop_id);
	if (!prop) {
		printf("\n");
		return;
	}

	printf(" %s:\n", prop->name);

	printf("\t\tflags:");
	if (prop->flags & DRM_MODE_PROP_PENDING)
		printf(" pending");
	if (prop->flags & DRM_MODE_PROP_RANGE)
		printf(" range");
	if (prop->flags & DRM_MODE_PROP_IMMUTABLE)
		printf(" immutable");
	if (prop->flags & DRM_MODE_PROP_ENUM)
		printf(" enum");
	if (prop->flags & DRM_MODE_PROP_BITMASK)
		printf(" bitmask");
	if (prop->flags & DRM_MODE_PROP_BLOB)
		printf(" blob");
	printf("\n");

	if (prop->flags & DRM_MODE_PROP_RANGE) {
		printf("\t\tvalues:");
		for (i = 0; i < prop->count_values; i++)
			printf(" %"PRIu64, prop->values[i]);
		printf("\n");
	}

	if (prop->flags & DRM_MODE_PROP_ENUM) {
		printf("\t\tenums:");
		for (i = 0; i < prop->count_enums; i++)
			printf(" %s=%llu", prop->enums[i].name,
			       prop->enums[i].value);
		printf("\n");
	} else if (prop->flags & DRM_MODE_PROP_BITMASK) {
		printf("\t\tvalues:");
		for (i = 0; i < prop->count_enums; i++)
			printf(" %s=0x%llx", prop->enums[i].name,
			       (1LL << prop->enums[i].value));
		printf("\n");
	} else {
		assert(prop->count_enums == 0);
	}

	if (prop->flags & DRM_MODE_PROP_BLOB) {
		printf("\t\tblobs:\n");
		for (i = 0; i < prop->count_blobs; i++)
			dump_blob(dev, prop->blob_ids[i]);
		printf("\n");
	} else {
		assert(prop->count_blobs == 0);
	}

	printf("\t\tvalue:");
	if (prop->flags & DRM_MODE_PROP_BLOB)
		dump_blob(dev, value);
	else
		printf(" %"PRIu64"\n", value);
}

static void dump_connectors(struct device *dev)
{
	int i, j;

	printf("Connectors:\n");
	printf("id\tencoder\tstatus\t\ttype\tsize (mm)\tmodes\tencoders\n");
	for (i = 0; i < dev->resources->res->count_connectors; i++) {
		struct connector *_connector = &dev->resources->connectors[i];
		drmModeConnector *connector = _connector->connector;
		if (!connector)
			continue;

		printf("%d\t%d\t%s\t%s\t%dx%d\t\t%d\t",
		       connector->connector_id,
		       connector->encoder_id,
		       connector_status_str(connector->connection),
		       connector_type_str(connector->connector_type),
		       connector->mmWidth, connector->mmHeight,
		       connector->count_modes);

		for (j = 0; j < connector->count_encoders; j++)
			printf("%s%d", j > 0 ? ", " : "", connector->encoders[j]);
		printf("\n");

		if (connector->count_modes) {
			printf("  modes:\n");
			printf("\tname refresh (Hz) hdisp hss hse htot vdisp "
			       "vss vse vtot)\n");
			for (j = 0; j < connector->count_modes; j++)
				dump_mode(&connector->modes[j]);
		}

		if (_connector->props) {
			printf("  props:\n");
			for (j = 0; j < (int)_connector->props->count_props; j++)
				dump_prop(dev, _connector->props_info[j],
					  _connector->props->props[j],
					  _connector->props->prop_values[j]);
		}
	}
	printf("\n");
}

static void dump_crtcs(struct device *dev)
{
	int i;
	uint32_t j;

	printf("CRTCs:\n");
	printf("id\tfb\tpos\tsize\n");
	for (i = 0; i < dev->resources->res->count_crtcs; i++) {
		struct crtc *_crtc = &dev->resources->crtcs[i];
		drmModeCrtc *crtc = _crtc->crtc;
		if (!crtc)
			continue;

		printf("%d\t%d\t(%d,%d)\t(%dx%d)\n",
		       crtc->crtc_id,
		       crtc->buffer_id,
		       crtc->x, crtc->y,
		       crtc->width, crtc->height);
		dump_mode(&crtc->mode);

		if (_crtc->props) {
			printf("  props:\n");
			for (j = 0; j < _crtc->props->count_props; j++)
				dump_prop(dev, _crtc->props_info[j],
					  _crtc->props->props[j],
					  _crtc->props->prop_values[j]);
		} else {
			printf("  no properties found\n");
		}
	}
	printf("\n");
}

static void dump_framebuffers(struct device *dev)
{
	drmModeFB *fb;
	int i;

	printf("Frame buffers:\n");
	printf("id\tsize\tpitch\n");
	for (i = 0; i < dev->resources->res->count_fbs; i++) {
		fb = dev->resources->fbs[i].fb;
		if (!fb)
			continue;

		printf("%u\t(%ux%u)\t%u\n",
		       fb->fb_id,
		       fb->width, fb->height,
		       fb->pitch);
	}
	printf("\n");
}

static void dump_planes(struct device *dev)
{
	unsigned int i, j;

	printf("Planes:\n");
	printf("id\tcrtc\tfb\tCRTC x,y\tx,y\tgamma size\tpossible crtcs\n");

	if (!dev->resources->plane_res)
		return;

	for (i = 0; i < dev->resources->plane_res->count_planes; i++) {
		struct plane *plane = &dev->resources->planes[i];
		drmModePlane *ovr = plane->plane;
		if (!ovr)
			continue;

		printf("%d\t%d\t%d\t%d,%d\t\t%d,%d\t%-8d\t0x%08x\n",
		       ovr->plane_id, ovr->crtc_id, ovr->fb_id,
		       ovr->crtc_x, ovr->crtc_y, ovr->x, ovr->y,
		       ovr->gamma_size, ovr->possible_crtcs);

		if (!ovr->count_formats)
			continue;

		printf("  formats:");
		for (j = 0; j < ovr->count_formats; j++)
			printf(" %4.4s", (char *)&ovr->formats[j]);
		printf("\n");

		if (plane->props) {
			printf("  props:\n");
			for (j = 0; j < plane->props->count_props; j++)
				dump_prop(dev, plane->props_info[j],
					  plane->props->props[j],
					  plane->props->prop_values[j]);
		} else {
			printf("  no properties found\n");
		}
	}
	printf("\n");

	return;
}

static void dump_sources(struct device *dev)
{
	unsigned int i, j;

	printf("Sources:\n");
	printf("id\tplane\twidth\theight\tformat\tpossible planes\tname\n");

	if (!dev->resources->source_res)
		return;

	for (i = 0; i < dev->resources->source_res->count_sources; i++) {
		struct source *source = &dev->resources->sources[i];
		drmModeSource *src = source->source;
		if (!src)
			continue;

		printf("%d\t%d\t%d\t%d\t%4.4s\t0x%08x\t%s\n",
		       src->source_id, src->plane_id,
		       src->width, src->height, (char *)&src->pixel_format,
		       src->possible_planes, src->name);

		if (!src->count_formats)
			continue;

		printf("  formats:");
		for (j = 0; j < src->count_formats; j++)
			printf(" %4.4s", (char *)&src->formats[j]);
		printf("\n");
	}
	printf("\n");

	return;
}

static void free_resources(struct resources *res)
{
	if (!res)
		return;

#define free_resource(_res, __res, type, Type)					\
	do {									\
		int i;								\
		if (!(_res)->type##s)						\
			break;							\
		for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {	\
			if (!(_res)->type##s[i].type)				\
				break;						\
			drmModeFree##Type((_res)->type##s[i].type);		\
		}								\
		free((_res)->type##s);						\
	} while (0)

#define free_properties(_res, __res, type)					\
	do {									\
		int i;								\
		for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {	\
			drmModeFreeObjectProperties(res->type##s[i].props);	\
			free(res->type##s[i].props_info);			\
		}								\
	} while (0)

	if (res->res) {
		free_properties(res, res, crtc);

		free_resource(res, res, crtc, Crtc);
		free_resource(res, res, encoder, Encoder);
		free_resource(res, res, connector, Connector);
		free_resource(res, res, fb, FB);

		drmModeFreeResources(res->res);
	}

	if (res->plane_res) {
		free_properties(res, plane_res, plane);

		free_resource(res, plane_res, plane, Plane);

		drmModeFreePlaneResources(res->plane_res);
	}

	if (res->source_res) {
		free_resource(res, source_res, source, Source);

		drmModeFreeSourceResources(res->source_res);
	}

	free(res);
}

static struct resources *get_resources(struct device *dev)
{
	struct resources *res;
	int i;

	res = malloc(sizeof *res);
	if (res == 0)
		return NULL;

	memset(res, 0, sizeof *res);

	res->res = drmModeGetResources(dev->fd);
	if (!res->res) {
		fprintf(stderr, "drmModeGetResources failed: %s\n",
			strerror(errno));
		goto error;
	}

	res->crtcs = malloc(res->res->count_crtcs * sizeof *res->crtcs);
	res->encoders = malloc(res->res->count_encoders * sizeof *res->encoders);
	res->connectors = malloc(res->res->count_connectors * sizeof *res->connectors);
	res->fbs = malloc(res->res->count_fbs * sizeof *res->fbs);

	if (!res->crtcs || !res->encoders || !res->connectors || !res->fbs)
		goto error;

	memset(res->crtcs , 0, res->res->count_crtcs * sizeof *res->crtcs);
	memset(res->encoders, 0, res->res->count_encoders * sizeof *res->encoders);
	memset(res->connectors, 0, res->res->count_connectors * sizeof *res->connectors);
	memset(res->fbs, 0, res->res->count_fbs * sizeof *res->fbs);

#define get_resource(_res, __res, type, Type)					\
	do {									\
		int i;								\
		for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {	\
			(_res)->type##s[i].type =				\
				drmModeGet##Type(dev->fd, (_res)->__res->type##s[i]); \
			if (!(_res)->type##s[i].type)				\
				fprintf(stderr, "could not get %s %i: %s\n",	\
					#type, (_res)->__res->type##s[i],	\
					strerror(errno));			\
		}								\
	} while (0)

	get_resource(res, res, crtc, Crtc);
	get_resource(res, res, encoder, Encoder);
	get_resource(res, res, connector, Connector);
	get_resource(res, res, fb, FB);

#define get_properties(_res, __res, type, Type)					\
	do {									\
		int i;								\
		for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {	\
			struct type *obj = &res->type##s[i];			\
			unsigned int j;						\
			obj->props =						\
				drmModeObjectGetProperties(dev->fd, obj->type->type##_id, \
							   DRM_MODE_OBJECT_##Type); \
			if (!obj->props) {					\
				fprintf(stderr,					\
					"could not get %s %i properties: %s\n", \
					#type, obj->type->type##_id,		\
					strerror(errno));			\
				continue;					\
			}							\
			obj->props_info = malloc(obj->props->count_props *	\
						 sizeof *obj->props_info);	\
			if (!obj->props_info)					\
				continue;					\
			for (j = 0; j < obj->props->count_props; ++j)		\
				obj->props_info[j] =				\
					drmModeGetProperty(dev->fd, obj->props->props[j]); \
		}								\
	} while (0)

	get_properties(res, res, crtc, CRTC);
	get_properties(res, res, connector, CONNECTOR);

	for (i = 0; i < res->res->count_crtcs; ++i)
		res->crtcs[i].mode = &res->crtcs[i].crtc->mode;

	/* Planes */
	res->plane_res = drmModeGetPlaneResources(dev->fd);
	if (!res->plane_res) {
		fprintf(stderr, "drmModeGetPlaneResources failed: %s\n",
			strerror(errno));
		return res;
	}

	res->planes = malloc(res->plane_res->count_planes * sizeof *res->planes);
	if (!res->planes)
		goto error;

	memset(res->planes, 0, res->plane_res->count_planes * sizeof *res->planes);

	get_resource(res, plane_res, plane, Plane);
	get_properties(res, plane_res, plane, PLANE);

	/* Live sources */
	res->source_res = drmModeGetSourceResources(dev->fd);
	if (!res->source_res)	/* Live sources are optional */
		return res;

	res->sources = malloc(res->source_res->count_sources * sizeof *res->sources);
	if (!res->sources)
		goto error;

	memset(res->sources, 0, res->source_res->count_sources * sizeof *res->sources);

	get_resource(res, source_res, source, Source);

	return res;

error:
	free_resources(res);
	return NULL;
}

static int get_crtc_index(struct device *dev, uint32_t id)
{
	int i;

	for (i = 0; i < dev->resources->res->count_crtcs; ++i) {
		drmModeCrtc *crtc = dev->resources->crtcs[i].crtc;
		if (crtc && crtc->crtc_id == id)
			return i;
	}

	return -1;
}

static drmModeConnector *get_connector_by_id(struct device *dev, uint32_t id)
{
	drmModeConnector *connector;
	int i;

	for (i = 0; i < dev->resources->res->count_connectors; i++) {
		connector = dev->resources->connectors[i].connector;
		if (connector && connector->connector_id == id)
			return connector;
	}

	return NULL;
}

static drmModeEncoder *get_encoder_by_id(struct device *dev, uint32_t id)
{
	drmModeEncoder *encoder;
	int i;

	for (i = 0; i < dev->resources->res->count_encoders; i++) {
		encoder = dev->resources->encoders[i].encoder;
		if (encoder && encoder->encoder_id == id)
			return encoder;
	}

	return NULL;
}

/* -----------------------------------------------------------------------------
 * Pipes and planes
 */

/*
 * Mode setting with the kernel interfaces is a bit of a chore.
 * First you have to find the connector in question and make sure the
 * requested mode is available.
 * Then you need to find the encoder attached to that connector so you
 * can bind it with a free crtc.
 */
struct pipe_arg {
	uint32_t *con_ids;
	unsigned int num_cons;
	uint32_t crtc_id;
	char mode_str[64];
	char format_str[5];
	unsigned int fourcc;
	drmModeModeInfo *mode;
	struct crtc *crtc;
	unsigned int fb_id[2], current_fb_id;
	struct timeval start;

	int swap_count;
};

struct plane_arg {
	uint32_t crtc_id;  /* the id of CRTC to bind to */
	uint32_t source_id;
	bool has_position;
	int32_t x, y;
	uint32_t w, h;
	unsigned int fb_id;
	char format_str[5]; /* need to leave room for terminating \0 */
	unsigned int fourcc;
};

static drmModeModeInfo *
connector_find_mode(struct device *dev, uint32_t con_id, const char *mode_str)
{
	drmModeConnector *connector;
	drmModeModeInfo *mode;
	int i;

	connector = get_connector_by_id(dev, con_id);
	if (!connector || !connector->count_modes)
		return NULL;

	for (i = 0; i < connector->count_modes; i++) {
		mode = &connector->modes[i];
		if (!strcmp(mode->name, mode_str))
			return mode;
	}

	return NULL;
}

static struct crtc *pipe_find_crtc(struct device *dev, struct pipe_arg *pipe)
{
	uint32_t possible_crtcs = ~0;
	uint32_t active_crtcs = 0;
	unsigned int crtc_idx;
	unsigned int i;
	int j;

	for (i = 0; i < pipe->num_cons; ++i) {
		uint32_t crtcs_for_connector = 0;
		drmModeConnector *connector;
		drmModeEncoder *encoder;
		int idx;

		connector = get_connector_by_id(dev, pipe->con_ids[i]);
		if (!connector)
			return NULL;

		for (j = 0; j < connector->count_encoders; ++j) {
			encoder = get_encoder_by_id(dev, connector->encoders[j]);
			if (!encoder)
				continue;

			crtcs_for_connector |= encoder->possible_crtcs;

			idx = get_crtc_index(dev, encoder->crtc_id);
			if (idx >= 0)
				active_crtcs |= 1 << idx;
		}

		possible_crtcs &= crtcs_for_connector;
	}

	if (!possible_crtcs)
		return NULL;

	/* Return the first possible and active CRTC if one exists, or the first
	 * possible CRTC otherwise.
	 */
	if (possible_crtcs & active_crtcs)
		crtc_idx = ffs(possible_crtcs & active_crtcs);
	else
		crtc_idx = ffs(possible_crtcs);

	return &dev->resources->crtcs[crtc_idx - 1];
}

static int pipe_find_crtc_and_mode(struct device *dev, struct pipe_arg *pipe)
{
	drmModeModeInfo *mode;
	int i;

	pipe->mode = NULL;

	for (i = 0; i < (int)pipe->num_cons; i++) {
		mode = connector_find_mode(dev, pipe->con_ids[i],
					   pipe->mode_str);
		if (mode == NULL) {
			fprintf(stderr,
				"failed to find mode \"%s\" for connector %u\n",
				pipe->mode_str, pipe->con_ids[i]);
			return -EINVAL;
		}
	}

	/* If the CRTC ID was specified, get the corresponding CRTC. Otherwise
	 * locate a CRTC that can be attached to all the connectors.
	 */
	if (pipe->crtc_id != (uint32_t)-1) {
		for (i = 0; i < dev->resources->res->count_crtcs; i++) {
			struct crtc *crtc = &dev->resources->crtcs[i];

			if (pipe->crtc_id == crtc->crtc->crtc_id) {
				pipe->crtc = crtc;
				break;
			}
		}
	} else {
		pipe->crtc = pipe_find_crtc(dev, pipe);
	}

	if (!pipe->crtc) {
		fprintf(stderr, "failed to find CRTC for pipe\n");
		return -EINVAL;
	}

	pipe->mode = mode;
	pipe->crtc->mode = mode;

	return 0;
}

/* -----------------------------------------------------------------------------
 * Properties
 */

struct property_arg {
	uint32_t obj_id;
	uint32_t obj_type;
	char name[DRM_PROP_NAME_LEN+1];
	uint32_t prop_id;
	uint64_t value;
};

static void set_property(struct device *dev, struct property_arg *p)
{
	drmModeObjectProperties *props;
	drmModePropertyRes **props_info;
	const char *obj_type;
	int ret;
	int i;

	p->obj_type = 0;
	p->prop_id = 0;

#define find_object(_res, __res, type, Type)					\
	do {									\
		for (i = 0; i < (int)(_res)->__res->count_##type##s; ++i) {	\
			struct type *obj = &(_res)->type##s[i];			\
			if (obj->type->type##_id != p->obj_id)			\
				continue;					\
			p->obj_type = DRM_MODE_OBJECT_##Type;			\
			obj_type = #Type;					\
			props = obj->props;					\
			props_info = obj->props_info;				\
		}								\
	} while(0)								\

	find_object(dev->resources, res, crtc, CRTC);
	if (p->obj_type == 0)
		find_object(dev->resources, res, connector, CONNECTOR);
	if (p->obj_type == 0)
		find_object(dev->resources, plane_res, plane, PLANE);
	if (p->obj_type == 0) {
		fprintf(stderr, "Object %i not found, can't set property\n",
			p->obj_id);
			return;
	}

	if (!props) {
		fprintf(stderr, "%s %i has no properties\n",
			obj_type, p->obj_id);
		return;
	}

	for (i = 0; i < (int)props->count_props; ++i) {
		if (!props_info[i])
			continue;
		if (strcmp(props_info[i]->name, p->name) == 0)
			break;
	}

	if (i == (int)props->count_props) {
		fprintf(stderr, "%s %i has no %s property\n",
			obj_type, p->obj_id, p->name);
		return;
	}

	p->prop_id = props->props[i];

	ret = drmModeObjectSetProperty(dev->fd, p->obj_id, p->obj_type,
				       p->prop_id, p->value);
	if (ret < 0)
		fprintf(stderr, "failed to set %s %i property %s to %" PRIu64 ": %s\n",
			obj_type, p->obj_id, p->name, p->value, strerror(errno));
}

/* -------------------------------------------------------------------------- */

static void
page_flip_handler(int fd, unsigned int frame,
		  unsigned int sec, unsigned int usec, void *data)
{
	struct pipe_arg *pipe;
	unsigned int new_fb_id;
	struct timeval end;
	double t;

	pipe = data;
	if (pipe->current_fb_id == pipe->fb_id[0])
		new_fb_id = pipe->fb_id[1];
	else
		new_fb_id = pipe->fb_id[0];

	drmModePageFlip(fd, pipe->crtc->crtc->crtc_id, new_fb_id,
			DRM_MODE_PAGE_FLIP_EVENT, pipe);
	pipe->current_fb_id = new_fb_id;
	pipe->swap_count++;
	if (pipe->swap_count == 60) {
		gettimeofday(&end, NULL);
		t = end.tv_sec + end.tv_usec * 1e-6 -
			(pipe->start.tv_sec + pipe->start.tv_usec * 1e-6);
		fprintf(stderr, "freq: %.02fHz\n", pipe->swap_count / t);
		pipe->swap_count = 0;
		pipe->start = end;
	}
}

static int set_plane(struct device *dev, struct plane_arg *p)
{
	drmModePlane *ovr;
	uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
	uint32_t plane_id = 0;
	struct kms_bo *plane_bo;
	uint32_t plane_flags = 0;
	int crtc_x, crtc_y, crtc_w, crtc_h;
	struct crtc *crtc = NULL;
	unsigned int pipe;
	unsigned int i;

	/* Find an unused plane which can be connected to our CRTC. Find the
	 * CRTC index first, then iterate over available planes.
	 */
	for (i = 0; i < (unsigned int)dev->resources->res->count_crtcs; i++) {
		if (p->crtc_id == dev->resources->res->crtcs[i]) {
			crtc = &dev->resources->crtcs[i];
			pipe = i;
			break;
		}
	}

	if (!crtc) {
		fprintf(stderr, "CRTC %u not found\n", p->crtc_id);
		return -1;
	}

	for (i = 0; i < dev->resources->plane_res->count_planes && !plane_id; i++) {
		ovr = dev->resources->planes[i].plane;
		if (!ovr)
			continue;

		if ((ovr->possible_crtcs & (1 << pipe)) && !ovr->crtc_id)
			plane_id = ovr->plane_id;
	}

	if (!plane_id) {
		fprintf(stderr, "no unused plane available for CRTC %u\n",
			crtc->crtc->crtc_id);
		return -1;
	}

	fprintf(stderr, "testing %dx%d@%s overlay plane %u\n",
		p->w, p->h, p->format_str, plane_id);

	plane_bo = create_test_buffer(dev->kms, p->fourcc, p->w, p->h, handles,
				      pitches, offsets, PATTERN_TILES);
	if (plane_bo == NULL)
		return -1;

	/* just use single plane format for now.. */
	if (drmModeAddFB2(dev->fd, p->w, p->h, p->fourcc,
			handles, pitches, offsets, &p->fb_id, plane_flags)) {
		fprintf(stderr, "failed to add fb: %s\n", strerror(errno));
		return -1;
	}

	if (!p->has_position) {
		/* Default to the middle of the screen */
		crtc_x = (crtc->mode->hdisplay - p->w) / 2;
		crtc_y = (crtc->mode->vdisplay - p->h) / 2;
	} else {
		crtc_x = p->x;
		crtc_y = p->y;
	}
	crtc_w = p->w;
	crtc_h = p->h;

	/* note src coords (last 4 args) are in Q16 format */
	if (drmModeSetPlane(dev->fd, plane_id, crtc->crtc->crtc_id, p->fb_id,
			    plane_flags, crtc_x, crtc_y, crtc_w, crtc_h,
			    0, 0, p->w << 16, p->h << 16)) {
		fprintf(stderr, "failed to enable plane: %s\n",
			strerror(errno));
		return -1;
	}

	ovr->crtc_id = crtc->crtc->crtc_id;

	return 0;
}

static void set_mode(struct device *dev, struct pipe_arg *pipes, unsigned int count)
{
	uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
	unsigned int fb_id;
	struct kms_bo *bo;
	unsigned int i;
	unsigned int j;
	int ret, x;

	dev->mode.width = 0;
	dev->mode.height = 0;

	for (i = 0; i < count; i++) {
		struct pipe_arg *pipe = &pipes[i];

		ret = pipe_find_crtc_and_mode(dev, pipe);
		if (ret < 0)
			continue;

		dev->mode.width += pipe->mode->hdisplay;
		if (dev->mode.height < pipe->mode->vdisplay)
			dev->mode.height = pipe->mode->vdisplay;
	}

	bo = create_test_buffer(dev->kms, pipes[0].fourcc,
				dev->mode.width, dev->mode.height,
				handles, pitches, offsets, PATTERN_SMPTE);
	if (bo == NULL)
		return;

	ret = drmModeAddFB2(dev->fd, dev->mode.width, dev->mode.height,
			    pipes[0].fourcc, handles, pitches, offsets, &fb_id, 0);
	if (ret) {
		fprintf(stderr, "failed to add fb (%ux%u): %s\n",
			dev->mode.width, dev->mode.height, strerror(errno));
		return;
	}

	x = 0;
	for (i = 0; i < count; i++) {
		struct pipe_arg *pipe = &pipes[i];

		if (pipe->mode == NULL)
			continue;

		printf("setting mode %s@%s on connectors ",
		       pipe->mode_str, pipe->format_str);
		for (j = 0; j < pipe->num_cons; ++j)
			printf("%u, ", pipe->con_ids[j]);
		printf("crtc %d\n", pipe->crtc->crtc->crtc_id);

		ret = drmModeSetCrtc(dev->fd, pipe->crtc->crtc->crtc_id, fb_id,
				     x, 0, pipe->con_ids, pipe->num_cons,
				     pipe->mode);

		/* XXX: Actually check if this is needed */
		drmModeDirtyFB(dev->fd, fb_id, NULL, 0);

		x += pipe->mode->hdisplay;

		if (ret) {
			fprintf(stderr, "failed to set mode: %s\n", strerror(errno));
			return;
		}
	}

	dev->mode.bo = bo;
	dev->mode.fb_id = fb_id;
}

static void set_planes(struct device *dev, struct plane_arg *p, unsigned int count)
{
	unsigned int i;

	/* set up planes/overlays */
	for (i = 0; i < count; i++)
		if (set_plane(dev, &p[i]))
			return;
}

static void test_page_flip(struct device *dev, struct pipe_arg *pipes, unsigned int count)
{
	uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
	unsigned int other_fb_id;
	struct kms_bo *other_bo;
	drmEventContext evctx;
	unsigned int i;
	int ret;

	other_bo = create_test_buffer(dev->kms, pipes[0].fourcc,
				      dev->mode.width, dev->mode.height,
				      handles, pitches, offsets, PATTERN_PLAIN);
	if (other_bo == NULL)
		return;

	ret = drmModeAddFB2(dev->fd, dev->mode.width, dev->mode.height,
			    pipes[0].fourcc, handles, pitches, offsets,
			    &other_fb_id, 0);
	if (ret) {
		fprintf(stderr, "failed to add fb: %s\n", strerror(errno));
		return;
	}

	for (i = 0; i < count; i++) {
		struct pipe_arg *pipe = &pipes[i];

		if (pipe->mode == NULL)
			continue;

		ret = drmModePageFlip(dev->fd, pipe->crtc->crtc->crtc_id,
				      other_fb_id, DRM_MODE_PAGE_FLIP_EVENT,
				      pipe);
		if (ret) {
			fprintf(stderr, "failed to page flip: %s\n", strerror(errno));
			return;
		}
		gettimeofday(&pipe->start, NULL);
		pipe->swap_count = 0;
		pipe->fb_id[0] = dev->mode.fb_id;
		pipe->fb_id[1] = other_fb_id;
		pipe->current_fb_id = other_fb_id;
	}

	memset(&evctx, 0, sizeof evctx);
	evctx.version = DRM_EVENT_CONTEXT_VERSION;
	evctx.vblank_handler = NULL;
	evctx.page_flip_handler = page_flip_handler;
	
	while (1) {
#if 0
		struct pollfd pfd[2];

		pfd[0].fd = 0;
		pfd[0].events = POLLIN;
		pfd[1].fd = fd;
		pfd[1].events = POLLIN;

		if (poll(pfd, 2, -1) < 0) {
			fprintf(stderr, "poll error\n");
			break;
		}

		if (pfd[0].revents)
			break;
#else
		struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };
		fd_set fds;
		int ret;

		FD_ZERO(&fds);
		FD_SET(0, &fds);
		FD_SET(dev->fd, &fds);
		ret = select(dev->fd + 1, &fds, NULL, NULL, &timeout);

		if (ret <= 0) {
			fprintf(stderr, "select timed out or error (ret %d)\n",
				ret);
			continue;
		} else if (FD_ISSET(0, &fds)) {
			break;
		}
#endif

		drmHandleEvent(dev->fd, &evctx);
	}

	kms_bo_destroy(&other_bo);
}

#define min(a, b)	((a) < (b) ? (a) : (b))

static int parse_connector(struct pipe_arg *pipe, const char *arg)
{
	unsigned int len;
	unsigned int i;
	const char *p;
	char *endp;

	pipe->crtc_id = (uint32_t)-1;
	strcpy(pipe->format_str, "XR24");

	/* Count the number of connectors and allocate them. */
	pipe->num_cons = 1;
	for (p = arg; isdigit(*p) || *p == ','; ++p) {
		if (*p == ',')
			pipe->num_cons++;
	}

	pipe->con_ids = malloc(pipe->num_cons * sizeof *pipe->con_ids);
	if (pipe->con_ids == NULL)
		return -1;

	/* Parse the connectors. */
	for (i = 0, p = arg; i < pipe->num_cons; ++i, p = endp + 1) {
		pipe->con_ids[i] = strtoul(p, &endp, 10);
		if (*endp != ',')
			break;
	}

	if (i != pipe->num_cons - 1)
		return -1;

	/* Parse the remaining parameters. */
	if (*endp == '@') {
		arg = endp + 1;
		pipe->crtc_id = strtoul(arg, &endp, 10);
	}
	if (*endp != ':')
		return -1;

	arg = endp + 1;

	p = strchrnul(arg, '@');
	len = min(sizeof pipe->mode_str - 1, (unsigned int)(p - arg));
	strncpy(pipe->mode_str, arg, len);
	pipe->mode_str[len] = '\0';

	if (*p == '@') {
		strncpy(pipe->format_str, p + 1, 4);
		pipe->format_str[4] = '\0';
	}

	pipe->fourcc = format_fourcc(pipe->format_str);
	if (pipe->fourcc == 0)  {
		fprintf(stderr, "unknown format %s\n", pipe->format_str);
		return -1;
	}

	return 0;
}

static int parse_plane(struct plane_arg *plane, const char *p)
{
	char *end;

	memset(plane, 0, sizeof *plane);

	plane->crtc_id = strtoul(p, &end, 10);
	if (*end == '@') {
		p = end + 1;
		plane->source_id = strtoul(p, &end, 10);
	}
	if (*end != ':')
		return -EINVAL;

	p = end + 1;
	plane->w = strtoul(p, &end, 10);
	if (*end != 'x')
		return -EINVAL;

	p = end + 1;
	plane->h = strtoul(p, &end, 10);

	if (*end == '+' || *end == '-') {
		plane->x = strtol(end, &end, 10);
		if (*end != '+' && *end != '-')
			return -EINVAL;
		plane->y = strtol(end, &end, 10);

		plane->has_position = true;
	}

	if (*end == '@') {
		p = end + 1;
		if (strlen(p) != 4)
			return -EINVAL;

		strcpy(plane->format_str, p);
	} else {
		strcpy(plane->format_str, "XR24");
	}

	plane->fourcc = format_fourcc(plane->format_str);
	if (plane->fourcc == 0) {
		fprintf(stderr, "unknown format %s\n", plane->format_str);
		return -EINVAL;
	}

	return 0;
}

static int parse_property(struct property_arg *p, const char *arg)
{
	if (sscanf(arg, "%d:%32[^:]:%" SCNu64, &p->obj_id, p->name, &p->value) != 3)
		return -1;

	p->obj_type = 0;
	p->name[DRM_PROP_NAME_LEN] = '\0';

	return 0;
}

static void usage(char *name)
{
	fprintf(stderr, "usage: %s [-cdefMmPpsvw]\n", name);

	fprintf(stderr, "\n Query options:\n\n");
	fprintf(stderr, "\t-c\tlist connectors\n");
	fprintf(stderr, "\t-e\tlist encoders\n");
	fprintf(stderr, "\t-f\tlist framebuffers\n");
	fprintf(stderr, "\t-p\tlist CRTCs, planes and sources (pipes)\n");

	fprintf(stderr, "\n Test options:\n\n");
	fprintf(stderr, "\t-P <crtc_id>[@<source_id>]:<w>x<h>[+<x>+<y>][@<format>]\tset a plane\n");
	fprintf(stderr, "\t-s <connector_id>[,<connector_id>][@<crtc_id>]:<mode>[@<format>]\tset a mode\n");
	fprintf(stderr, "\t-v\ttest vsynced page flipping\n");
	fprintf(stderr, "\t-w <obj_id>:<prop_name>:<value>\tset property\n");

	fprintf(stderr, "\n Generic options:\n\n");
	fprintf(stderr, "\t-d\tdrop master after mode set\n");
	fprintf(stderr, "\t-M module\tuse the given driver\n");

	fprintf(stderr, "\n\tDefault is to dump all info.\n");
	exit(0);
}

static int page_flipping_supported(void)
{
	/*FIXME: generic ioctl needed? */
	return 1;
#if 0
	int ret, value;
	struct drm_i915_getparam gp;

	gp.param = I915_PARAM_HAS_PAGEFLIPPING;
	gp.value = &value;

	ret = drmCommandWriteRead(fd, DRM_I915_GETPARAM, &gp, sizeof(gp));
	if (ret) {
		fprintf(stderr, "drm_i915_getparam: %m\n");
		return 0;
	}

	return *gp.value;
#endif
}

static char optstr[] = "cdefM:P:ps:vw:";

int main(int argc, char **argv)
{
	struct device dev;

	int c;
	int encoders = 0, connectors = 0, framebuffers = 0;
	int crtcs = 0, planes = 0, sources = 0;
	int drop_master = 0;
	int test_vsync = 0;
	const char *modules[] = { "i915", "radeon", "nouveau", "vmwgfx", "omapdrm", "exynos" };
	char *module = NULL;
	unsigned int i;
	int count = 0, plane_count = 0;
	unsigned int prop_count = 0;
	struct pipe_arg *pipe_args = NULL;
	struct plane_arg *plane_args = NULL;
	struct property_arg *prop_args = NULL;
	unsigned int args = 0;
	int ret;

	memset(&dev, 0, sizeof dev);

	opterr = 0;
	while ((c = getopt(argc, argv, optstr)) != -1) {
		args++;

		switch (c) {
		case 'c':
			connectors = 1;
			break;
		case 'd':
			drop_master = 1;
			break;
		case 'e':
			encoders = 1;
			break;
		case 'f':
			framebuffers = 1;
			break;
		case 'M':
			module = optarg;
			/* Preserve the default behaviour of dumping all information. */
			args--;
			break;
		case 'P':
			plane_args = realloc(plane_args,
					     (plane_count + 1) * sizeof *plane_args);
			if (plane_args == NULL) {
				fprintf(stderr, "memory allocation failed\n");
				return 1;
			}

			if (parse_plane(&plane_args[plane_count], optarg) < 0)
				usage(argv[0]);

			plane_count++;
			break;
		case 'p':
			crtcs = 1;
			planes = 1;
			sources = 1;
			break;
		case 's':
			pipe_args = realloc(pipe_args,
					    (count + 1) * sizeof *pipe_args);
			if (pipe_args == NULL) {
				fprintf(stderr, "memory allocation failed\n");
				return 1;
			}

			if (parse_connector(&pipe_args[count], optarg) < 0)
				usage(argv[0]);

			count++;				      
			break;
		case 'v':
			test_vsync = 1;
			break;
		case 'w':
			prop_args = realloc(prop_args,
					   (prop_count + 1) * sizeof *prop_args);
			if (prop_args == NULL) {
				fprintf(stderr, "memory allocation failed\n");
				return 1;
			}

			if (parse_property(&prop_args[prop_count], optarg) < 0)
				usage(argv[0]);

			prop_count++;
			break;
		default:
			usage(argv[0]);
			break;
		}
	}

	if (!args) {
		encoders = connectors = framebuffers = 1;
		crtcs = planes = sources = 1;
	}

	if (module) {
		dev.fd = drmOpen(module, NULL);
		if (dev.fd < 0) {
			fprintf(stderr, "failed to open device '%s'.\n", module);
			return 1;
		}
	} else {
		for (i = 0; i < ARRAY_SIZE(modules); i++) {
			printf("trying to open device '%s'...", modules[i]);
			dev.fd = drmOpen(modules[i], NULL);
			if (dev.fd < 0) {
				printf("failed.\n");