Index: head/sys/dev/drm2/drm_gem.c =================================================================== --- head/sys/dev/drm2/drm_gem.c (revision 254879) +++ head/sys/dev/drm2/drm_gem.c (revision 254880) @@ -1,507 +1,507 @@ /*- * Copyright (c) 2011 The FreeBSD Foundation * All rights reserved. * * This software was developed by Konstantin Belousov under sponsorship from * the FreeBSD Foundation. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include "opt_vm.h" #include #include #include #include #include #include #include #include #include #include /* * We make up offsets for buffer objects so we can recognize them at * mmap time. */ /* pgoff in mmap is an unsigned long, so we need to make sure that * the faked up offset will fit */ #if ULONG_MAX == UINT64_MAX #define DRM_FILE_PAGE_OFFSET_START ((0xFFFFFFFFUL >> PAGE_SHIFT) + 1) #define DRM_FILE_PAGE_OFFSET_SIZE ((0xFFFFFFFFUL >> PAGE_SHIFT) * 16) #else #define DRM_FILE_PAGE_OFFSET_START ((0xFFFFFFFUL >> PAGE_SHIFT) + 1) #define DRM_FILE_PAGE_OFFSET_SIZE ((0xFFFFFFFUL >> PAGE_SHIFT) * 16) #endif int drm_gem_init(struct drm_device *dev) { struct drm_gem_mm *mm; drm_gem_names_init(&dev->object_names); mm = malloc(sizeof(*mm), DRM_MEM_DRIVER, M_WAITOK); dev->mm_private = mm; if (drm_ht_create(&mm->offset_hash, 19) != 0) { free(mm, DRM_MEM_DRIVER); return (ENOMEM); } mm->idxunr = new_unrhdr(0, DRM_GEM_MAX_IDX, NULL); return (0); } void drm_gem_destroy(struct drm_device *dev) { struct drm_gem_mm *mm; mm = dev->mm_private; dev->mm_private = NULL; drm_ht_remove(&mm->offset_hash); delete_unrhdr(mm->idxunr); free(mm, DRM_MEM_DRIVER); drm_gem_names_fini(&dev->object_names); } int drm_gem_object_init(struct drm_device *dev, struct drm_gem_object *obj, size_t size) { KASSERT((size & (PAGE_SIZE - 1)) == 0, ("Bad size %ju", (uintmax_t)size)); obj->dev = dev; obj->vm_obj = vm_pager_allocate(OBJT_DEFAULT, NULL, size, VM_PROT_READ | VM_PROT_WRITE, 0, curthread->td_ucred); obj->refcount = 1; obj->handle_count = 0; obj->size = size; return (0); } int drm_gem_private_object_init(struct drm_device *dev, struct drm_gem_object *obj, size_t size) { MPASS((size & (PAGE_SIZE - 1)) == 0); obj->dev = dev; obj->vm_obj = NULL; obj->refcount = 1; - atomic_set(&obj->handle_count, 0); + atomic_store_rel_int(&obj->handle_count, 0); obj->size = size; return (0); } struct drm_gem_object * drm_gem_object_alloc(struct drm_device *dev, size_t size) { struct drm_gem_object *obj; obj = malloc(sizeof(*obj), DRM_MEM_DRIVER, M_WAITOK | M_ZERO); if (drm_gem_object_init(dev, obj, size) != 0) goto free; if (dev->driver->gem_init_object != NULL && dev->driver->gem_init_object(obj) != 0) goto dealloc; return (obj); dealloc: vm_object_deallocate(obj->vm_obj); free: free(obj, DRM_MEM_DRIVER); return (NULL); } void drm_gem_object_free(struct drm_gem_object *obj) { struct drm_device *dev; dev = obj->dev; DRM_LOCK_ASSERT(dev); if (dev->driver->gem_free_object != NULL) dev->driver->gem_free_object(obj); } void drm_gem_object_reference(struct drm_gem_object *obj) { KASSERT(obj->refcount > 0, ("Dangling obj %p", obj)); refcount_acquire(&obj->refcount); } void drm_gem_object_unreference(struct drm_gem_object *obj) { if (obj == NULL) return; if (refcount_release(&obj->refcount)) drm_gem_object_free(obj); } void drm_gem_object_unreference_unlocked(struct drm_gem_object *obj) { struct drm_device *dev; if (obj == NULL) return; dev = obj->dev; DRM_LOCK(dev); drm_gem_object_unreference(obj); DRM_UNLOCK(dev); } void drm_gem_object_handle_reference(struct drm_gem_object *obj) { drm_gem_object_reference(obj); atomic_add_rel_int(&obj->handle_count, 1); } void drm_gem_object_handle_free(struct drm_gem_object *obj) { struct drm_device *dev; struct drm_gem_object *obj1; dev = obj->dev; if (obj->name != 0) { obj1 = drm_gem_names_remove(&dev->object_names, obj->name); obj->name = 0; drm_gem_object_unreference(obj1); } } void drm_gem_object_handle_unreference(struct drm_gem_object *obj) { if (obj == NULL || atomic_load_acq_int(&obj->handle_count) == 0) return; if (atomic_fetchadd_int(&obj->handle_count, -1) == 1) drm_gem_object_handle_free(obj); drm_gem_object_unreference(obj); } void drm_gem_object_handle_unreference_unlocked(struct drm_gem_object *obj) { if (obj == NULL || atomic_load_acq_int(&obj->handle_count) == 0) return; if (atomic_fetchadd_int(&obj->handle_count, -1) == 1) drm_gem_object_handle_free(obj); drm_gem_object_unreference_unlocked(obj); } int drm_gem_handle_create(struct drm_file *file_priv, struct drm_gem_object *obj, uint32_t *handle) { struct drm_device *dev = obj->dev; int ret; ret = drm_gem_name_create(&file_priv->object_names, obj, handle); if (ret != 0) return (ret); drm_gem_object_handle_reference(obj); if (dev->driver->gem_open_object) { ret = dev->driver->gem_open_object(obj, file_priv); if (ret) { drm_gem_handle_delete(file_priv, *handle); return ret; } } return (0); } int drm_gem_handle_delete(struct drm_file *file_priv, uint32_t handle) { struct drm_device *dev; struct drm_gem_object *obj; obj = drm_gem_names_remove(&file_priv->object_names, handle); if (obj == NULL) return (EINVAL); dev = obj->dev; if (dev->driver->gem_close_object) dev->driver->gem_close_object(obj, file_priv); drm_gem_object_handle_unreference_unlocked(obj); return (0); } void drm_gem_object_release(struct drm_gem_object *obj) { /* * obj->vm_obj can be NULL for private gem objects. */ vm_object_deallocate(obj->vm_obj); } int drm_gem_open_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_gem_open *args; struct drm_gem_object *obj; int ret; uint32_t handle; if (!drm_core_check_feature(dev, DRIVER_GEM)) return (ENODEV); args = data; obj = drm_gem_name_ref(&dev->object_names, args->name, (void (*)(void *))drm_gem_object_reference); if (obj == NULL) return (ENOENT); handle = 0; ret = drm_gem_handle_create(file_priv, obj, &handle); drm_gem_object_unreference_unlocked(obj); if (ret != 0) return (ret); args->handle = handle; args->size = obj->size; return (0); } void drm_gem_open(struct drm_device *dev, struct drm_file *file_priv) { drm_gem_names_init(&file_priv->object_names); } static int drm_gem_object_release_handle(uint32_t name, void *ptr, void *arg) { struct drm_file *file_priv; struct drm_gem_object *obj; struct drm_device *dev; file_priv = arg; obj = ptr; dev = obj->dev; if (dev->driver->gem_close_object) dev->driver->gem_close_object(obj, file_priv); drm_gem_object_handle_unreference(obj); return (0); } void drm_gem_release(struct drm_device *dev, struct drm_file *file_priv) { drm_gem_names_foreach(&file_priv->object_names, drm_gem_object_release_handle, file_priv); drm_gem_names_fini(&file_priv->object_names); } int drm_gem_close_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_gem_close *args; if (!drm_core_check_feature(dev, DRIVER_GEM)) return (ENODEV); args = data; return (drm_gem_handle_delete(file_priv, args->handle)); } int drm_gem_flink_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_gem_flink *args; struct drm_gem_object *obj; int error; if (!drm_core_check_feature(dev, DRIVER_GEM)) return (ENODEV); args = data; obj = drm_gem_name_ref(&file_priv->object_names, args->handle, (void (*)(void *))drm_gem_object_reference); if (obj == NULL) return (ENOENT); error = drm_gem_name_create(&dev->object_names, obj, &obj->name); if (error != 0) { if (error == EALREADY) error = 0; drm_gem_object_unreference_unlocked(obj); } if (error == 0) args->name = obj->name; return (error); } struct drm_gem_object * drm_gem_object_lookup(struct drm_device *dev, struct drm_file *file_priv, uint32_t handle) { struct drm_gem_object *obj; obj = drm_gem_name_ref(&file_priv->object_names, handle, (void (*)(void *))drm_gem_object_reference); return (obj); } static struct drm_gem_object * drm_gem_object_from_offset(struct drm_device *dev, vm_ooffset_t offset) { struct drm_gem_object *obj; struct drm_gem_mm *mm; struct drm_hash_item *map_list; if ((offset & DRM_GEM_MAPPING_MASK) != DRM_GEM_MAPPING_KEY) return (NULL); offset &= ~DRM_GEM_MAPPING_KEY; mm = dev->mm_private; if (drm_ht_find_item(&mm->offset_hash, DRM_GEM_MAPPING_IDX(offset), &map_list) != 0) { DRM_DEBUG("drm_gem_object_from_offset: offset 0x%jx obj not found\n", (uintmax_t)offset); return (NULL); } obj = __containerof(map_list, struct drm_gem_object, map_list); return (obj); } int drm_gem_create_mmap_offset(struct drm_gem_object *obj) { struct drm_device *dev; struct drm_gem_mm *mm; int ret; if (obj->on_map) return (0); dev = obj->dev; mm = dev->mm_private; ret = 0; obj->map_list.key = alloc_unr(mm->idxunr); ret = drm_ht_insert_item(&mm->offset_hash, &obj->map_list); if (ret != 0) { DRM_ERROR("failed to add to map hash\n"); free_unr(mm->idxunr, obj->map_list.key); return (ret); } obj->on_map = true; return (0); } void drm_gem_free_mmap_offset(struct drm_gem_object *obj) { struct drm_hash_item *list; struct drm_gem_mm *mm; if (!obj->on_map) return; mm = obj->dev->mm_private; list = &obj->map_list; drm_ht_remove_item(&mm->offset_hash, list); free_unr(mm->idxunr, list->key); obj->on_map = false; } int drm_gem_mmap_single(struct drm_device *dev, vm_ooffset_t *offset, vm_size_t size, struct vm_object **obj_res, int nprot) { struct drm_gem_object *gem_obj; struct vm_object *vm_obj; DRM_LOCK(dev); gem_obj = drm_gem_object_from_offset(dev, *offset); if (gem_obj == NULL) { DRM_UNLOCK(dev); return (ENODEV); } drm_gem_object_reference(gem_obj); DRM_UNLOCK(dev); vm_obj = cdev_pager_allocate(gem_obj, OBJT_MGTDEVICE, dev->driver->gem_pager_ops, size, nprot, DRM_GEM_MAPPING_MAPOFF(*offset), curthread->td_ucred); if (vm_obj == NULL) { drm_gem_object_unreference_unlocked(gem_obj); return (EINVAL); } *offset = DRM_GEM_MAPPING_MAPOFF(*offset); *obj_res = vm_obj; return (0); } void drm_gem_pager_dtr(void *handle) { struct drm_gem_object *obj; struct drm_device *dev; obj = handle; dev = obj->dev; DRM_LOCK(dev); drm_gem_free_mmap_offset(obj); drm_gem_object_unreference(obj); DRM_UNLOCK(dev); } Index: head/sys/dev/drm2/drm_irq.c =================================================================== --- head/sys/dev/drm2/drm_irq.c (revision 254879) +++ head/sys/dev/drm2/drm_irq.c (revision 254880) @@ -1,1253 +1,1253 @@ /*- * Copyright 2003 Eric Anholt * 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 * ERIC ANHOLT 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. * * Authors: * Eric Anholt * */ #include __FBSDID("$FreeBSD$"); /** @file drm_irq.c * Support code for handling setup/teardown of interrupt handlers and * handing interrupt handlers off to the drivers. */ #include #include MALLOC_DEFINE(DRM_MEM_VBLANK, "drm_vblank", "DRM VBLANK Handling Data"); /* Access macro for slots in vblank timestamp ringbuffer. */ #define vblanktimestamp(dev, crtc, count) ( \ (dev)->_vblank_time[(crtc) * DRM_VBLANKTIME_RBSIZE + \ ((count) % DRM_VBLANKTIME_RBSIZE)]) /* Retry timestamp calculation up to 3 times to satisfy * drm_timestamp_precision before giving up. */ #define DRM_TIMESTAMP_MAXRETRIES 3 /* Threshold in nanoseconds for detection of redundant * vblank irq in drm_handle_vblank(). 1 msec should be ok. */ #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000 int drm_irq_by_busid(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_irq_busid *irq = data; if ((irq->busnum >> 8) != dev->pci_domain || (irq->busnum & 0xff) != dev->pci_bus || irq->devnum != dev->pci_slot || irq->funcnum != dev->pci_func) return EINVAL; irq->irq = dev->irq; DRM_DEBUG("%d:%d:%d => IRQ %d\n", irq->busnum, irq->devnum, irq->funcnum, irq->irq); return 0; } static void drm_irq_handler_wrap(void *arg) { struct drm_device *dev = arg; mtx_lock(&dev->irq_lock); dev->driver->irq_handler(arg); mtx_unlock(&dev->irq_lock); } int drm_irq_install(struct drm_device *dev) { int retcode; if (dev->irq == 0 || dev->dev_private == NULL) return (EINVAL); DRM_DEBUG("irq=%d\n", dev->irq); DRM_LOCK(dev); if (dev->irq_enabled) { DRM_UNLOCK(dev); return EBUSY; } dev->irq_enabled = 1; dev->context_flag = 0; /* Before installing handler */ if (dev->driver->irq_preinstall) dev->driver->irq_preinstall(dev); DRM_UNLOCK(dev); /* Install handler */ retcode = bus_setup_intr(dev->device, dev->irqr, INTR_TYPE_TTY | INTR_MPSAFE, NULL, (dev->driver->driver_features & DRIVER_LOCKLESS_IRQ) != 0 ? drm_irq_handler_wrap : dev->driver->irq_handler, dev, &dev->irqh); if (retcode != 0) goto err; /* After installing handler */ DRM_LOCK(dev); if (dev->driver->irq_postinstall) dev->driver->irq_postinstall(dev); DRM_UNLOCK(dev); return (0); err: device_printf(dev->device, "Error setting interrupt: %d\n", retcode); dev->irq_enabled = 0; return (retcode); } int drm_irq_uninstall(struct drm_device *dev) { int i; if (!dev->irq_enabled) return EINVAL; dev->irq_enabled = 0; /* * Wake up any waiters so they don't hang. */ if (dev->num_crtcs) { mtx_lock(&dev->vbl_lock); for (i = 0; i < dev->num_crtcs; i++) { wakeup(&dev->_vblank_count[i]); dev->vblank_enabled[i] = 0; dev->last_vblank[i] = dev->driver->get_vblank_counter(dev, i); } mtx_unlock(&dev->vbl_lock); } DRM_DEBUG("irq=%d\n", dev->irq); if (dev->driver->irq_uninstall) dev->driver->irq_uninstall(dev); DRM_UNLOCK(dev); bus_teardown_intr(dev->device, dev->irqr, dev->irqh); DRM_LOCK(dev); return 0; } int drm_control(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_control *ctl = data; int err; switch (ctl->func) { case DRM_INST_HANDLER: /* Handle drivers whose DRM used to require IRQ setup but the * no longer does. */ if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ)) return 0; if (drm_core_check_feature(dev, DRIVER_MODESET)) return 0; if (dev->if_version < DRM_IF_VERSION(1, 2) && ctl->irq != dev->irq) return EINVAL; return drm_irq_install(dev); case DRM_UNINST_HANDLER: if (!drm_core_check_feature(dev, DRIVER_HAVE_IRQ)) return 0; if (drm_core_check_feature(dev, DRIVER_MODESET)) return 0; DRM_LOCK(dev); err = drm_irq_uninstall(dev); DRM_UNLOCK(dev); return err; default: return EINVAL; } } #define NSEC_PER_USEC 1000L #define NSEC_PER_SEC 1000000000L int64_t timeval_to_ns(const struct timeval *tv) { return ((int64_t)tv->tv_sec * NSEC_PER_SEC) + tv->tv_usec * NSEC_PER_USEC; } struct timeval ns_to_timeval(const int64_t nsec) { struct timeval tv; uint32_t rem; if (nsec == 0) { tv.tv_sec = 0; tv.tv_usec = 0; return (tv); } tv.tv_sec = nsec / NSEC_PER_SEC; rem = nsec % NSEC_PER_SEC; if (rem < 0) { tv.tv_sec--; rem += NSEC_PER_SEC; } tv.tv_usec = rem / 1000; return (tv); } /* * Clear vblank timestamp buffer for a crtc. */ static void clear_vblank_timestamps(struct drm_device *dev, int crtc) { memset(&dev->_vblank_time[crtc * DRM_VBLANKTIME_RBSIZE], 0, DRM_VBLANKTIME_RBSIZE * sizeof(struct timeval)); } static int64_t abs64(int64_t x) { return (x < 0 ? -x : x); } /* * Disable vblank irq's on crtc, make sure that last vblank count * of hardware and corresponding consistent software vblank counter * are preserved, even if there are any spurious vblank irq's after * disable. */ static void vblank_disable_and_save(struct drm_device *dev, int crtc) { u32 vblcount; int64_t diff_ns; int vblrc; struct timeval tvblank; /* Prevent vblank irq processing while disabling vblank irqs, * so no updates of timestamps or count can happen after we've * disabled. Needed to prevent races in case of delayed irq's. */ mtx_lock(&dev->vblank_time_lock); dev->driver->disable_vblank(dev, crtc); dev->vblank_enabled[crtc] = 0; /* No further vblank irq's will be processed after * this point. Get current hardware vblank count and * vblank timestamp, repeat until they are consistent. * * FIXME: There is still a race condition here and in * drm_update_vblank_count() which can cause off-by-one * reinitialization of software vblank counter. If gpu * vblank counter doesn't increment exactly at the leading * edge of a vblank interval, then we can lose 1 count if * we happen to execute between start of vblank and the * delayed gpu counter increment. */ do { dev->last_vblank[crtc] = dev->driver->get_vblank_counter(dev, crtc); vblrc = drm_get_last_vbltimestamp(dev, crtc, &tvblank, 0); } while (dev->last_vblank[crtc] != dev->driver->get_vblank_counter(dev, crtc)); /* Compute time difference to stored timestamp of last vblank * as updated by last invocation of drm_handle_vblank() in vblank irq. */ vblcount = atomic_read(&dev->_vblank_count[crtc]); diff_ns = timeval_to_ns(&tvblank) - timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount)); /* If there is at least 1 msec difference between the last stored * timestamp and tvblank, then we are currently executing our * disable inside a new vblank interval, the tvblank timestamp * corresponds to this new vblank interval and the irq handler * for this vblank didn't run yet and won't run due to our disable. * Therefore we need to do the job of drm_handle_vblank() and * increment the vblank counter by one to account for this vblank. * * Skip this step if there isn't any high precision timestamp * available. In that case we can't account for this and just * hope for the best. */ if ((vblrc > 0) && (abs64(diff_ns) > 1000000)) { atomic_inc(&dev->_vblank_count[crtc]); } /* Invalidate all timestamps while vblank irq's are off. */ clear_vblank_timestamps(dev, crtc); mtx_unlock(&dev->vblank_time_lock); } static void vblank_disable_fn(void * arg) { struct drm_device *dev = (struct drm_device *)arg; int i; if (!dev->vblank_disable_allowed) return; for (i = 0; i < dev->num_crtcs; i++) { mtx_lock(&dev->vbl_lock); if (atomic_read(&dev->vblank_refcount[i]) == 0 && dev->vblank_enabled[i]) { DRM_DEBUG("disabling vblank on crtc %d\n", i); vblank_disable_and_save(dev, i); } mtx_unlock(&dev->vbl_lock); } } void drm_vblank_cleanup(struct drm_device *dev) { /* Bail if the driver didn't call drm_vblank_init() */ if (dev->num_crtcs == 0) return; callout_stop(&dev->vblank_disable_callout); vblank_disable_fn(dev); free(dev->_vblank_count, DRM_MEM_VBLANK); free(dev->vblank_refcount, DRM_MEM_VBLANK); free(dev->vblank_enabled, DRM_MEM_VBLANK); free(dev->last_vblank, DRM_MEM_VBLANK); free(dev->last_vblank_wait, DRM_MEM_VBLANK); free(dev->vblank_inmodeset, DRM_MEM_VBLANK); free(dev->_vblank_time, DRM_MEM_VBLANK); dev->num_crtcs = 0; } int drm_vblank_init(struct drm_device *dev, int num_crtcs) { int i; callout_init(&dev->vblank_disable_callout, CALLOUT_MPSAFE); #if 0 mtx_init(&dev->vbl_lock, "drmvbl", NULL, MTX_DEF); #endif mtx_init(&dev->vblank_time_lock, "drmvtl", NULL, MTX_DEF); dev->num_crtcs = num_crtcs; dev->_vblank_count = malloc(sizeof(atomic_t) * num_crtcs, DRM_MEM_VBLANK, M_WAITOK); dev->vblank_refcount = malloc(sizeof(atomic_t) * num_crtcs, DRM_MEM_VBLANK, M_WAITOK); dev->vblank_enabled = malloc(num_crtcs * sizeof(int), DRM_MEM_VBLANK, M_WAITOK | M_ZERO); dev->last_vblank = malloc(num_crtcs * sizeof(u32), DRM_MEM_VBLANK, M_WAITOK | M_ZERO); dev->last_vblank_wait = malloc(num_crtcs * sizeof(u32), DRM_MEM_VBLANK, M_WAITOK | M_ZERO); dev->vblank_inmodeset = malloc(num_crtcs * sizeof(int), DRM_MEM_VBLANK, M_WAITOK | M_ZERO); dev->_vblank_time = malloc(num_crtcs * DRM_VBLANKTIME_RBSIZE * sizeof(struct timeval), DRM_MEM_VBLANK, M_WAITOK | M_ZERO); DRM_INFO("Supports vblank timestamp caching Rev 1 (10.10.2010).\n"); /* Driver specific high-precision vblank timestamping supported? */ if (dev->driver->get_vblank_timestamp) DRM_INFO("Driver supports precise vblank timestamp query.\n"); else DRM_INFO("No driver support for vblank timestamp query.\n"); /* Zero per-crtc vblank stuff */ for (i = 0; i < num_crtcs; i++) { atomic_set(&dev->_vblank_count[i], 0); atomic_set(&dev->vblank_refcount[i], 0); } dev->vblank_disable_allowed = 0; return 0; } void drm_calc_timestamping_constants(struct drm_crtc *crtc) { int64_t linedur_ns = 0, pixeldur_ns = 0, framedur_ns = 0; uint64_t dotclock; /* Dot clock in Hz: */ dotclock = (uint64_t) crtc->hwmode.clock * 1000; /* Fields of interlaced scanout modes are only halve a frame duration. * Double the dotclock to get halve the frame-/line-/pixelduration. */ if (crtc->hwmode.flags & DRM_MODE_FLAG_INTERLACE) dotclock *= 2; /* Valid dotclock? */ if (dotclock > 0) { /* Convert scanline length in pixels and video dot clock to * line duration, frame duration and pixel duration in * nanoseconds: */ pixeldur_ns = (int64_t)1000000000 / dotclock; linedur_ns = ((uint64_t)crtc->hwmode.crtc_htotal * 1000000000) / dotclock; framedur_ns = (int64_t)crtc->hwmode.crtc_vtotal * linedur_ns; } else DRM_ERROR("crtc %d: Can't calculate constants, dotclock = 0!\n", crtc->base.id); crtc->pixeldur_ns = pixeldur_ns; crtc->linedur_ns = linedur_ns; crtc->framedur_ns = framedur_ns; DRM_DEBUG("crtc %d: hwmode: htotal %d, vtotal %d, vdisplay %d\n", crtc->base.id, crtc->hwmode.crtc_htotal, crtc->hwmode.crtc_vtotal, crtc->hwmode.crtc_vdisplay); DRM_DEBUG("crtc %d: clock %d kHz framedur %d linedur %d, pixeldur %d\n", crtc->base.id, (int) dotclock/1000, (int) framedur_ns, (int) linedur_ns, (int) pixeldur_ns); } /** * drm_calc_vbltimestamp_from_scanoutpos - helper routine for kms * drivers. Implements calculation of exact vblank timestamps from * given drm_display_mode timings and current video scanout position * of a crtc. This can be called from within get_vblank_timestamp() * implementation of a kms driver to implement the actual timestamping. * * Should return timestamps conforming to the OML_sync_control OpenML * extension specification. The timestamp corresponds to the end of * the vblank interval, aka start of scanout of topmost-leftmost display * pixel in the following video frame. * * Requires support for optional dev->driver->get_scanout_position() * in kms driver, plus a bit of setup code to provide a drm_display_mode * that corresponds to the true scanout timing. * * The current implementation only handles standard video modes. It * returns as no operation if a doublescan or interlaced video mode is * active. Higher level code is expected to handle this. * * @dev: DRM device. * @crtc: Which crtc's vblank timestamp to retrieve. * @max_error: Desired maximum allowable error in timestamps (nanosecs). * On return contains true maximum error of timestamp. * @vblank_time: Pointer to struct timeval which should receive the timestamp. * @flags: Flags to pass to driver: * 0 = Default. * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler. * @refcrtc: drm_crtc* of crtc which defines scanout timing. * * Returns negative value on error, failure or if not supported in current * video mode: * * -EINVAL - Invalid crtc. * -EAGAIN - Temporary unavailable, e.g., called before initial modeset. * -ENOTSUPP - Function not supported in current display mode. * -EIO - Failed, e.g., due to failed scanout position query. * * Returns or'ed positive status flags on success: * * DRM_VBLANKTIME_SCANOUTPOS_METHOD - Signal this method used for timestamping. * DRM_VBLANKTIME_INVBL - Timestamp taken while scanout was in vblank interval. * */ int drm_calc_vbltimestamp_from_scanoutpos(struct drm_device *dev, int crtc, int *max_error, struct timeval *vblank_time, unsigned flags, struct drm_crtc *refcrtc) { struct timeval stime, raw_time; struct drm_display_mode *mode; int vbl_status, vtotal, vdisplay; int vpos, hpos, i; int64_t framedur_ns, linedur_ns, pixeldur_ns, delta_ns, duration_ns; bool invbl; if (crtc < 0 || crtc >= dev->num_crtcs) { DRM_ERROR("Invalid crtc %d\n", crtc); return -EINVAL; } /* Scanout position query not supported? Should not happen. */ if (!dev->driver->get_scanout_position) { DRM_ERROR("Called from driver w/o get_scanout_position()!?\n"); return -EIO; } mode = &refcrtc->hwmode; vtotal = mode->crtc_vtotal; vdisplay = mode->crtc_vdisplay; /* Durations of frames, lines, pixels in nanoseconds. */ framedur_ns = refcrtc->framedur_ns; linedur_ns = refcrtc->linedur_ns; pixeldur_ns = refcrtc->pixeldur_ns; /* If mode timing undefined, just return as no-op: * Happens during initial modesetting of a crtc. */ if (vtotal <= 0 || vdisplay <= 0 || framedur_ns == 0) { DRM_DEBUG("crtc %d: Noop due to uninitialized mode.\n", crtc); return -EAGAIN; } /* Get current scanout position with system timestamp. * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times * if single query takes longer than max_error nanoseconds. * * This guarantees a tight bound on maximum error if * code gets preempted or delayed for some reason. */ for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) { /* Disable preemption to make it very likely to * succeed in the first iteration. */ critical_enter(); /* Get system timestamp before query. */ getmicrouptime(&stime); /* Get vertical and horizontal scanout pos. vpos, hpos. */ vbl_status = dev->driver->get_scanout_position(dev, crtc, &vpos, &hpos); /* Get system timestamp after query. */ getmicrouptime(&raw_time); critical_exit(); /* Return as no-op if scanout query unsupported or failed. */ if (!(vbl_status & DRM_SCANOUTPOS_VALID)) { DRM_DEBUG("crtc %d : scanoutpos query failed [%d].\n", crtc, vbl_status); return -EIO; } duration_ns = timeval_to_ns(&raw_time) - timeval_to_ns(&stime); /* Accept result with < max_error nsecs timing uncertainty. */ if (duration_ns <= (int64_t) *max_error) break; } /* Noisy system timing? */ if (i == DRM_TIMESTAMP_MAXRETRIES) { DRM_DEBUG("crtc %d: Noisy timestamp %d us > %d us [%d reps].\n", crtc, (int) duration_ns/1000, *max_error/1000, i); } /* Return upper bound of timestamp precision error. */ *max_error = (int) duration_ns; /* Check if in vblank area: * vpos is >=0 in video scanout area, but negative * within vblank area, counting down the number of lines until * start of scanout. */ invbl = vbl_status & DRM_SCANOUTPOS_INVBL; /* Convert scanout position into elapsed time at raw_time query * since start of scanout at first display scanline. delta_ns * can be negative if start of scanout hasn't happened yet. */ delta_ns = (int64_t)vpos * linedur_ns + (int64_t)hpos * pixeldur_ns; /* Is vpos outside nominal vblank area, but less than * 1/100 of a frame height away from start of vblank? * If so, assume this isn't a massively delayed vblank * interrupt, but a vblank interrupt that fired a few * microseconds before true start of vblank. Compensate * by adding a full frame duration to the final timestamp. * Happens, e.g., on ATI R500, R600. * * We only do this if DRM_CALLED_FROM_VBLIRQ. */ if ((flags & DRM_CALLED_FROM_VBLIRQ) && !invbl && ((vdisplay - vpos) < vtotal / 100)) { delta_ns = delta_ns - framedur_ns; /* Signal this correction as "applied". */ vbl_status |= 0x8; } /* Subtract time delta from raw timestamp to get final * vblank_time timestamp for end of vblank. */ *vblank_time = ns_to_timeval(timeval_to_ns(&raw_time) - delta_ns); DRM_DEBUG("crtc %d : v %d p(%d,%d)@ %jd.%jd -> %jd.%jd [e %d us, %d rep]\n", crtc, (int)vbl_status, hpos, vpos, (uintmax_t)raw_time.tv_sec, (uintmax_t)raw_time.tv_usec, (uintmax_t)vblank_time->tv_sec, (uintmax_t)vblank_time->tv_usec, (int)duration_ns/1000, i); vbl_status = DRM_VBLANKTIME_SCANOUTPOS_METHOD; if (invbl) vbl_status |= DRM_VBLANKTIME_INVBL; return vbl_status; } /** * drm_get_last_vbltimestamp - retrieve raw timestamp for the most recent * vblank interval. * * @dev: DRM device * @crtc: which crtc's vblank timestamp to retrieve * @tvblank: Pointer to target struct timeval which should receive the timestamp * @flags: Flags to pass to driver: * 0 = Default. * DRM_CALLED_FROM_VBLIRQ = If function is called from vbl irq handler. * * Fetches the system timestamp corresponding to the time of the most recent * vblank interval on specified crtc. May call into kms-driver to * compute the timestamp with a high-precision GPU specific method. * * Returns zero if timestamp originates from uncorrected do_gettimeofday() * call, i.e., it isn't very precisely locked to the true vblank. * * Returns non-zero if timestamp is considered to be very precise. */ u32 drm_get_last_vbltimestamp(struct drm_device *dev, int crtc, struct timeval *tvblank, unsigned flags) { int ret = 0; /* Define requested maximum error on timestamps (nanoseconds). */ int max_error = (int) drm_timestamp_precision * 1000; /* Query driver if possible and precision timestamping enabled. */ if (dev->driver->get_vblank_timestamp && (max_error > 0)) { ret = dev->driver->get_vblank_timestamp(dev, crtc, &max_error, tvblank, flags); if (ret > 0) return (u32) ret; } /* GPU high precision timestamp query unsupported or failed. * Return gettimeofday timestamp as best estimate. */ microtime(tvblank); return 0; } /** * drm_vblank_count - retrieve "cooked" vblank counter value * @dev: DRM device * @crtc: which counter to retrieve * * Fetches the "cooked" vblank count value that represents the number of * vblank events since the system was booted, including lost events due to * modesetting activity. */ u32 drm_vblank_count(struct drm_device *dev, int crtc) { return atomic_read(&dev->_vblank_count[crtc]); } /** * drm_vblank_count_and_time - retrieve "cooked" vblank counter value * and the system timestamp corresponding to that vblank counter value. * * @dev: DRM device * @crtc: which counter to retrieve * @vblanktime: Pointer to struct timeval to receive the vblank timestamp. * * Fetches the "cooked" vblank count value that represents the number of * vblank events since the system was booted, including lost events due to * modesetting activity. Returns corresponding system timestamp of the time * of the vblank interval that corresponds to the current value vblank counter * value. */ u32 drm_vblank_count_and_time(struct drm_device *dev, int crtc, struct timeval *vblanktime) { u32 cur_vblank; /* Read timestamp from slot of _vblank_time ringbuffer * that corresponds to current vblank count. Retry if * count has incremented during readout. This works like * a seqlock. */ do { cur_vblank = atomic_read(&dev->_vblank_count[crtc]); *vblanktime = vblanktimestamp(dev, crtc, cur_vblank); rmb(); } while (cur_vblank != atomic_read(&dev->_vblank_count[crtc])); return cur_vblank; } /** * drm_update_vblank_count - update the master vblank counter * @dev: DRM device * @crtc: counter to update * * Call back into the driver to update the appropriate vblank counter * (specified by @crtc). Deal with wraparound, if it occurred, and * update the last read value so we can deal with wraparound on the next * call if necessary. * * Only necessary when going from off->on, to account for frames we * didn't get an interrupt for. * * Note: caller must hold dev->vbl_lock since this reads & writes * device vblank fields. */ static void drm_update_vblank_count(struct drm_device *dev, int crtc) { u32 cur_vblank, diff, tslot, rc; struct timeval t_vblank; /* * Interrupts were disabled prior to this call, so deal with counter * wrap if needed. * NOTE! It's possible we lost a full dev->max_vblank_count events * here if the register is small or we had vblank interrupts off for * a long time. * * We repeat the hardware vblank counter & timestamp query until * we get consistent results. This to prevent races between gpu * updating its hardware counter while we are retrieving the * corresponding vblank timestamp. */ do { cur_vblank = dev->driver->get_vblank_counter(dev, crtc); rc = drm_get_last_vbltimestamp(dev, crtc, &t_vblank, 0); } while (cur_vblank != dev->driver->get_vblank_counter(dev, crtc)); /* Deal with counter wrap */ diff = cur_vblank - dev->last_vblank[crtc]; if (cur_vblank < dev->last_vblank[crtc]) { diff += dev->max_vblank_count; DRM_DEBUG("last_vblank[%d]=0x%x, cur_vblank=0x%x => diff=0x%x\n", crtc, dev->last_vblank[crtc], cur_vblank, diff); } DRM_DEBUG("enabling vblank interrupts on crtc %d, missed %d\n", crtc, diff); /* Reinitialize corresponding vblank timestamp if high-precision query * available. Skip this step if query unsupported or failed. Will * reinitialize delayed at next vblank interrupt in that case. */ if (rc) { tslot = atomic_read(&dev->_vblank_count[crtc]) + diff; vblanktimestamp(dev, crtc, tslot) = t_vblank; } atomic_add(diff, &dev->_vblank_count[crtc]); } /** * drm_vblank_get - get a reference count on vblank events * @dev: DRM device * @crtc: which CRTC to own * * Acquire a reference count on vblank events to avoid having them disabled * while in use. * * RETURNS * Zero on success, nonzero on failure. */ int drm_vblank_get(struct drm_device *dev, int crtc) { int ret = 0; mtx_lock(&dev->vbl_lock); /* Going from 0->1 means we have to enable interrupts again */ - if (atomic_fetchadd_int(&dev->vblank_refcount[crtc], 1) == 0) { + if (atomic_add_return(1, &dev->vblank_refcount[crtc]) == 1) { mtx_lock(&dev->vblank_time_lock); if (!dev->vblank_enabled[crtc]) { /* Enable vblank irqs under vblank_time_lock protection. * All vblank count & timestamp updates are held off * until we are done reinitializing master counter and * timestamps. Filtercode in drm_handle_vblank() will * prevent double-accounting of same vblank interval. */ ret = -dev->driver->enable_vblank(dev, crtc); DRM_DEBUG("enabling vblank on crtc %d, ret: %d\n", crtc, ret); if (ret) atomic_dec(&dev->vblank_refcount[crtc]); else { dev->vblank_enabled[crtc] = 1; drm_update_vblank_count(dev, crtc); } } mtx_unlock(&dev->vblank_time_lock); } else { if (!dev->vblank_enabled[crtc]) { atomic_dec(&dev->vblank_refcount[crtc]); ret = EINVAL; } } mtx_unlock(&dev->vbl_lock); return ret; } /** * drm_vblank_put - give up ownership of vblank events * @dev: DRM device * @crtc: which counter to give up * * Release ownership of a given vblank counter, turning off interrupts * if possible. Disable interrupts after drm_vblank_offdelay milliseconds. */ void drm_vblank_put(struct drm_device *dev, int crtc) { KASSERT(atomic_read(&dev->vblank_refcount[crtc]) != 0, ("Too many drm_vblank_put for crtc %d", crtc)); /* Last user schedules interrupt disable */ - if (atomic_fetchadd_int(&dev->vblank_refcount[crtc], -1) == 1 && + if (atomic_dec_and_test(&dev->vblank_refcount[crtc]) && (drm_vblank_offdelay > 0)) callout_reset(&dev->vblank_disable_callout, (drm_vblank_offdelay * DRM_HZ) / 1000, vblank_disable_fn, dev); } void drm_vblank_off(struct drm_device *dev, int crtc) { struct drm_pending_vblank_event *e, *t; struct timeval now; unsigned int seq; mtx_lock(&dev->vbl_lock); vblank_disable_and_save(dev, crtc); mtx_lock(&dev->event_lock); wakeup(&dev->_vblank_count[crtc]); /* Send any queued vblank events, lest the natives grow disquiet */ seq = drm_vblank_count_and_time(dev, crtc, &now); list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) { if (e->pipe != crtc) continue; DRM_DEBUG("Sending premature vblank event on disable: \ wanted %d, current %d\n", e->event.sequence, seq); e->event.sequence = seq; e->event.tv_sec = now.tv_sec; e->event.tv_usec = now.tv_usec; drm_vblank_put(dev, e->pipe); list_move_tail(&e->base.link, &e->base.file_priv->event_list); drm_event_wakeup(&e->base); CTR3(KTR_DRM, "vblank_event_delivered %d %d %d", e->base.pid, e->pipe, e->event.sequence); } mtx_unlock(&dev->event_lock); mtx_unlock(&dev->vbl_lock); } /** * drm_vblank_pre_modeset - account for vblanks across mode sets * @dev: DRM device * @crtc: CRTC in question * @post: post or pre mode set? * * Account for vblank events across mode setting events, which will likely * reset the hardware frame counter. */ void drm_vblank_pre_modeset(struct drm_device *dev, int crtc) { /* vblank is not initialized (IRQ not installed ?) */ if (!dev->num_crtcs) return; /* * To avoid all the problems that might happen if interrupts * were enabled/disabled around or between these calls, we just * have the kernel take a reference on the CRTC (just once though * to avoid corrupting the count if multiple, mismatch calls occur), * so that interrupts remain enabled in the interim. */ if (!dev->vblank_inmodeset[crtc]) { dev->vblank_inmodeset[crtc] = 0x1; if (drm_vblank_get(dev, crtc) == 0) dev->vblank_inmodeset[crtc] |= 0x2; } } void drm_vblank_post_modeset(struct drm_device *dev, int crtc) { if (dev->vblank_inmodeset[crtc]) { mtx_lock(&dev->vbl_lock); dev->vblank_disable_allowed = 1; mtx_unlock(&dev->vbl_lock); if (dev->vblank_inmodeset[crtc] & 0x2) drm_vblank_put(dev, crtc); dev->vblank_inmodeset[crtc] = 0; } } /** * drm_modeset_ctl - handle vblank event counter changes across mode switch * @DRM_IOCTL_ARGS: standard ioctl arguments * * Applications should call the %_DRM_PRE_MODESET and %_DRM_POST_MODESET * ioctls around modesetting so that any lost vblank events are accounted for. * * Generally the counter will reset across mode sets. If interrupts are * enabled around this call, we don't have to do anything since the counter * will have already been incremented. */ int drm_modeset_ctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_modeset_ctl *modeset = data; int ret = 0; unsigned int crtc; /* If drm_vblank_init() hasn't been called yet, just no-op */ if (!dev->num_crtcs) goto out; crtc = modeset->crtc; if (crtc >= dev->num_crtcs) { ret = -EINVAL; goto out; } switch (modeset->cmd) { case _DRM_PRE_MODESET: drm_vblank_pre_modeset(dev, crtc); break; case _DRM_POST_MODESET: drm_vblank_post_modeset(dev, crtc); break; default: ret = -EINVAL; break; } out: return ret; } static void drm_vblank_event_destroy(struct drm_pending_event *e) { free(e, DRM_MEM_VBLANK); } static int drm_queue_vblank_event(struct drm_device *dev, int pipe, union drm_wait_vblank *vblwait, struct drm_file *file_priv) { struct drm_pending_vblank_event *e; struct timeval now; unsigned int seq; int ret; e = malloc(sizeof *e, DRM_MEM_VBLANK, M_WAITOK | M_ZERO); e->pipe = pipe; e->base.pid = curproc->p_pid; e->event.base.type = DRM_EVENT_VBLANK; e->event.base.length = sizeof e->event; e->event.user_data = vblwait->request.signal; e->base.event = &e->event.base; e->base.file_priv = file_priv; e->base.destroy = drm_vblank_event_destroy; mtx_lock(&dev->event_lock); if (file_priv->event_space < sizeof e->event) { ret = EBUSY; goto err_unlock; } file_priv->event_space -= sizeof e->event; seq = drm_vblank_count_and_time(dev, pipe, &now); if ((vblwait->request.type & _DRM_VBLANK_NEXTONMISS) && (seq - vblwait->request.sequence) <= (1 << 23)) { vblwait->request.sequence = seq + 1; vblwait->reply.sequence = vblwait->request.sequence; } DRM_DEBUG("event on vblank count %d, current %d, crtc %d\n", vblwait->request.sequence, seq, pipe); CTR4(KTR_DRM, "vblank_event_queued %d %d rt %x %d", curproc->p_pid, pipe, vblwait->request.type, vblwait->request.sequence); e->event.sequence = vblwait->request.sequence; if ((seq - vblwait->request.sequence) <= (1 << 23)) { e->event.sequence = seq; e->event.tv_sec = now.tv_sec; e->event.tv_usec = now.tv_usec; drm_vblank_put(dev, pipe); list_add_tail(&e->base.link, &e->base.file_priv->event_list); drm_event_wakeup(&e->base); vblwait->reply.sequence = seq; CTR3(KTR_DRM, "vblank_event_wakeup p1 %d %d %d", curproc->p_pid, pipe, vblwait->request.sequence); } else { /* drm_handle_vblank_events will call drm_vblank_put */ list_add_tail(&e->base.link, &dev->vblank_event_list); vblwait->reply.sequence = vblwait->request.sequence; } mtx_unlock(&dev->event_lock); return 0; err_unlock: mtx_unlock(&dev->event_lock); free(e, DRM_MEM_VBLANK); drm_vblank_put(dev, pipe); return ret; } /** * Wait for VBLANK. * * \param inode device inode. * \param file_priv DRM file private. * \param cmd command. * \param data user argument, pointing to a drm_wait_vblank structure. * \return zero on success or a negative number on failure. * * This function enables the vblank interrupt on the pipe requested, then * sleeps waiting for the requested sequence number to occur, and drops * the vblank interrupt refcount afterwards. (vblank irq disable follows that * after a timeout with no further vblank waits scheduled). */ int drm_wait_vblank(struct drm_device *dev, void *data, struct drm_file *file_priv) { union drm_wait_vblank *vblwait = data; int ret = 0; unsigned int flags, seq, crtc, high_crtc; if (/*(!drm_dev_to_irq(dev)) || */(!dev->irq_enabled)) return (EINVAL); if (vblwait->request.type & _DRM_VBLANK_SIGNAL) return (EINVAL); if (vblwait->request.type & ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK | _DRM_VBLANK_HIGH_CRTC_MASK)) { DRM_ERROR("Unsupported type value 0x%x, supported mask 0x%x\n", vblwait->request.type, (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK | _DRM_VBLANK_HIGH_CRTC_MASK)); return (EINVAL); } flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK; high_crtc = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK); if (high_crtc) crtc = high_crtc >> _DRM_VBLANK_HIGH_CRTC_SHIFT; else crtc = flags & _DRM_VBLANK_SECONDARY ? 1 : 0; if (crtc >= dev->num_crtcs) return (EINVAL); ret = drm_vblank_get(dev, crtc); if (ret) { DRM_DEBUG("failed to acquire vblank counter, %d\n", ret); return (ret); } seq = drm_vblank_count(dev, crtc); switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) { case _DRM_VBLANK_RELATIVE: vblwait->request.sequence += seq; vblwait->request.type &= ~_DRM_VBLANK_RELATIVE; case _DRM_VBLANK_ABSOLUTE: break; default: ret = (EINVAL); goto done; } if (flags & _DRM_VBLANK_EVENT) { /* must hold on to the vblank ref until the event fires * drm_vblank_put will be called asynchronously */ return drm_queue_vblank_event(dev, crtc, vblwait, file_priv); } if ((flags & _DRM_VBLANK_NEXTONMISS) && (seq - vblwait->request.sequence) <= (1<<23)) { vblwait->request.sequence = seq + 1; } dev->last_vblank_wait[crtc] = vblwait->request.sequence; mtx_lock(&dev->vblank_time_lock); while (((drm_vblank_count(dev, crtc) - vblwait->request.sequence) > (1 << 23)) && dev->irq_enabled) { /* * The wakeups from the drm_irq_uninstall() and * drm_vblank_off() may be lost there since vbl_lock * is not held. Then, the timeout will wake us; the 3 * seconds delay should not be a problem for * application when crtc is disabled or irq * uninstalled anyway. */ ret = msleep(&dev->_vblank_count[crtc], &dev->vblank_time_lock, PCATCH, "drmvbl", 3 * hz); if (ret != 0) break; } mtx_unlock(&dev->vblank_time_lock); if (ret != EINTR) { struct timeval now; long reply_seq; reply_seq = drm_vblank_count_and_time(dev, crtc, &now); CTR5(KTR_DRM, "wait_vblank %d %d rt %x success %d %d", curproc->p_pid, crtc, vblwait->request.type, vblwait->request.sequence, reply_seq); vblwait->reply.sequence = reply_seq; vblwait->reply.tval_sec = now.tv_sec; vblwait->reply.tval_usec = now.tv_usec; } else { CTR5(KTR_DRM, "wait_vblank %d %d rt %x error %d %d", curproc->p_pid, crtc, vblwait->request.type, ret, vblwait->request.sequence); } done: drm_vblank_put(dev, crtc); return ret; } void drm_handle_vblank_events(struct drm_device *dev, int crtc) { struct drm_pending_vblank_event *e, *t; struct timeval now; unsigned int seq; seq = drm_vblank_count_and_time(dev, crtc, &now); CTR2(KTR_DRM, "drm_handle_vblank_events %d %d", seq, crtc); mtx_lock(&dev->event_lock); list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) { if (e->pipe != crtc) continue; if ((seq - e->event.sequence) > (1<<23)) continue; e->event.sequence = seq; e->event.tv_sec = now.tv_sec; e->event.tv_usec = now.tv_usec; drm_vblank_put(dev, e->pipe); list_move_tail(&e->base.link, &e->base.file_priv->event_list); drm_event_wakeup(&e->base); CTR3(KTR_DRM, "vblank_event_wakeup p2 %d %d %d", e->base.pid, e->pipe, e->event.sequence); } mtx_unlock(&dev->event_lock); } /** * drm_handle_vblank - handle a vblank event * @dev: DRM device * @crtc: where this event occurred * * Drivers should call this routine in their vblank interrupt handlers to * update the vblank counter and send any signals that may be pending. */ bool drm_handle_vblank(struct drm_device *dev, int crtc) { u32 vblcount; int64_t diff_ns; struct timeval tvblank; if (!dev->num_crtcs) return false; /* Need timestamp lock to prevent concurrent execution with * vblank enable/disable, as this would cause inconsistent * or corrupted timestamps and vblank counts. */ mtx_lock(&dev->vblank_time_lock); /* Vblank irq handling disabled. Nothing to do. */ if (!dev->vblank_enabled[crtc]) { mtx_unlock(&dev->vblank_time_lock); return false; } /* Fetch corresponding timestamp for this vblank interval from * driver and store it in proper slot of timestamp ringbuffer. */ /* Get current timestamp and count. */ vblcount = atomic_read(&dev->_vblank_count[crtc]); drm_get_last_vbltimestamp(dev, crtc, &tvblank, DRM_CALLED_FROM_VBLIRQ); /* Compute time difference to timestamp of last vblank */ diff_ns = timeval_to_ns(&tvblank) - timeval_to_ns(&vblanktimestamp(dev, crtc, vblcount)); /* Update vblank timestamp and count if at least * DRM_REDUNDANT_VBLIRQ_THRESH_NS nanoseconds * difference between last stored timestamp and current * timestamp. A smaller difference means basically * identical timestamps. Happens if this vblank has * been already processed and this is a redundant call, * e.g., due to spurious vblank interrupts. We need to * ignore those for accounting. */ if (abs64(diff_ns) > DRM_REDUNDANT_VBLIRQ_THRESH_NS) { /* Store new timestamp in ringbuffer. */ vblanktimestamp(dev, crtc, vblcount + 1) = tvblank; /* Increment cooked vblank count. This also atomically commits * the timestamp computed above. */ atomic_inc(&dev->_vblank_count[crtc]); } else { DRM_DEBUG("crtc %d: Redundant vblirq ignored. diff_ns = %d\n", crtc, (int) diff_ns); } wakeup(&dev->_vblank_count[crtc]); drm_handle_vblank_events(dev, crtc); mtx_unlock(&dev->vblank_time_lock); return true; } Index: head/sys/dev/drm2/ttm/ttm_bo.c =================================================================== --- head/sys/dev/drm2/ttm/ttm_bo.c (revision 254879) +++ head/sys/dev/drm2/ttm/ttm_bo.c (revision 254880) @@ -1,1885 +1,1886 @@ /************************************************************************** * * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA * 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, sub license, 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 NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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. * **************************************************************************/ /* * Authors: Thomas Hellstrom */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #define TTM_ASSERT_LOCKED(param) #define TTM_DEBUG(fmt, arg...) #define TTM_BO_HASH_ORDER 13 static int ttm_bo_setup_vm(struct ttm_buffer_object *bo); static int ttm_bo_swapout(struct ttm_mem_shrink *shrink); static void ttm_bo_global_kobj_release(struct ttm_bo_global *glob); MALLOC_DEFINE(M_TTM_BO, "ttm_bo", "TTM Buffer Objects"); static inline int ttm_mem_type_from_flags(uint32_t flags, uint32_t *mem_type) { int i; for (i = 0; i <= TTM_PL_PRIV5; i++) if (flags & (1 << i)) { *mem_type = i; return 0; } return -EINVAL; } static void ttm_mem_type_debug(struct ttm_bo_device *bdev, int mem_type) { struct ttm_mem_type_manager *man = &bdev->man[mem_type]; printf(" has_type: %d\n", man->has_type); printf(" use_type: %d\n", man->use_type); printf(" flags: 0x%08X\n", man->flags); printf(" gpu_offset: 0x%08lX\n", man->gpu_offset); printf(" size: %ju\n", (uintmax_t)man->size); printf(" available_caching: 0x%08X\n", man->available_caching); printf(" default_caching: 0x%08X\n", man->default_caching); if (mem_type != TTM_PL_SYSTEM) (*man->func->debug)(man, TTM_PFX); } static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo, struct ttm_placement *placement) { int i, ret, mem_type; printf("No space for %p (%lu pages, %luK, %luM)\n", bo, bo->mem.num_pages, bo->mem.size >> 10, bo->mem.size >> 20); for (i = 0; i < placement->num_placement; i++) { ret = ttm_mem_type_from_flags(placement->placement[i], &mem_type); if (ret) return; printf(" placement[%d]=0x%08X (%d)\n", i, placement->placement[i], mem_type); ttm_mem_type_debug(bo->bdev, mem_type); } } #if 0 static ssize_t ttm_bo_global_show(struct ttm_bo_global *glob, char *buffer) { return snprintf(buffer, PAGE_SIZE, "%lu\n", (unsigned long) atomic_read(&glob->bo_count)); } #endif static inline uint32_t ttm_bo_type_flags(unsigned type) { return 1 << (type); } static void ttm_bo_release_list(struct ttm_buffer_object *bo) { struct ttm_bo_device *bdev = bo->bdev; size_t acc_size = bo->acc_size; MPASS(atomic_read(&bo->list_kref) == 0); MPASS(atomic_read(&bo->kref) == 0); MPASS(atomic_read(&bo->cpu_writers) == 0); MPASS(bo->sync_obj == NULL); MPASS(bo->mem.mm_node == NULL); MPASS(list_empty(&bo->lru)); MPASS(list_empty(&bo->ddestroy)); if (bo->ttm) ttm_tt_destroy(bo->ttm); atomic_dec(&bo->glob->bo_count); if (bo->destroy) bo->destroy(bo); else { free(bo, M_TTM_BO); } ttm_mem_global_free(bdev->glob->mem_glob, acc_size); } static int ttm_bo_wait_unreserved_locked(struct ttm_buffer_object *bo, bool interruptible) { const char *wmsg; int flags, ret; ret = 0; if (interruptible) { flags = PCATCH; wmsg = "ttbowi"; } else { flags = 0; wmsg = "ttbowu"; } while (ttm_bo_is_reserved(bo)) { ret = -msleep(bo, &bo->glob->lru_lock, flags, wmsg, 0); if (ret != 0) break; } return (ret); } void ttm_bo_add_to_lru(struct ttm_buffer_object *bo) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_mem_type_manager *man; MPASS(ttm_bo_is_reserved(bo)); if (!(bo->mem.placement & TTM_PL_FLAG_NO_EVICT)) { MPASS(list_empty(&bo->lru)); man = &bdev->man[bo->mem.mem_type]; list_add_tail(&bo->lru, &man->lru); refcount_acquire(&bo->list_kref); if (bo->ttm != NULL) { list_add_tail(&bo->swap, &bo->glob->swap_lru); refcount_acquire(&bo->list_kref); } } } int ttm_bo_del_from_lru(struct ttm_buffer_object *bo) { int put_count = 0; if (!list_empty(&bo->swap)) { list_del_init(&bo->swap); ++put_count; } if (!list_empty(&bo->lru)) { list_del_init(&bo->lru); ++put_count; } /* * TODO: Add a driver hook to delete from * driver-specific LRU's here. */ return put_count; } int ttm_bo_reserve_nolru(struct ttm_buffer_object *bo, bool interruptible, bool no_wait, bool use_sequence, uint32_t sequence) { int ret; while (unlikely(atomic_xchg(&bo->reserved, 1) != 0)) { /** * Deadlock avoidance for multi-bo reserving. */ if (use_sequence && bo->seq_valid) { /** * We've already reserved this one. */ if (unlikely(sequence == bo->val_seq)) return -EDEADLK; /** * Already reserved by a thread that will not back * off for us. We need to back off. */ if (unlikely(sequence - bo->val_seq < (1 << 31))) return -EAGAIN; } if (no_wait) return -EBUSY; ret = ttm_bo_wait_unreserved_locked(bo, interruptible); if (unlikely(ret)) return ret; } if (use_sequence) { bool wake_up = false; /** * Wake up waiters that may need to recheck for deadlock, * if we decreased the sequence number. */ if (unlikely((bo->val_seq - sequence < (1 << 31)) || !bo->seq_valid)) wake_up = true; /* * In the worst case with memory ordering these values can be * seen in the wrong order. However since we call wake_up_all * in that case, this will hopefully not pose a problem, * and the worst case would only cause someone to accidentally * hit -EAGAIN in ttm_bo_reserve when they see old value of * val_seq. However this would only happen if seq_valid was * written before val_seq was, and just means some slightly * increased cpu usage */ bo->val_seq = sequence; bo->seq_valid = true; if (wake_up) wakeup(bo); } else { bo->seq_valid = false; } return 0; } void ttm_bo_list_ref_sub(struct ttm_buffer_object *bo, int count, bool never_free) { u_int old; old = atomic_fetchadd_int(&bo->list_kref, -count); if (old <= count) { if (never_free) panic("ttm_bo_ref_buf"); ttm_bo_release_list(bo); } } int ttm_bo_reserve(struct ttm_buffer_object *bo, bool interruptible, bool no_wait, bool use_sequence, uint32_t sequence) { struct ttm_bo_global *glob = bo->glob; int put_count = 0; int ret; mtx_lock(&bo->glob->lru_lock); ret = ttm_bo_reserve_nolru(bo, interruptible, no_wait, use_sequence, sequence); if (likely(ret == 0)) { put_count = ttm_bo_del_from_lru(bo); mtx_unlock(&glob->lru_lock); ttm_bo_list_ref_sub(bo, put_count, true); } else mtx_unlock(&bo->glob->lru_lock); return ret; } int ttm_bo_reserve_slowpath_nolru(struct ttm_buffer_object *bo, bool interruptible, uint32_t sequence) { bool wake_up = false; int ret; while (unlikely(atomic_xchg(&bo->reserved, 1) != 0)) { if (bo->seq_valid && sequence == bo->val_seq) { DRM_ERROR( "%s: bo->seq_valid && sequence == bo->val_seq", __func__); } ret = ttm_bo_wait_unreserved_locked(bo, interruptible); if (unlikely(ret)) return ret; } if ((bo->val_seq - sequence < (1 << 31)) || !bo->seq_valid) wake_up = true; /** * Wake up waiters that may need to recheck for deadlock, * if we decreased the sequence number. */ bo->val_seq = sequence; bo->seq_valid = true; if (wake_up) wakeup(bo); return 0; } int ttm_bo_reserve_slowpath(struct ttm_buffer_object *bo, bool interruptible, uint32_t sequence) { struct ttm_bo_global *glob = bo->glob; int put_count, ret; mtx_lock(&glob->lru_lock); ret = ttm_bo_reserve_slowpath_nolru(bo, interruptible, sequence); if (likely(!ret)) { put_count = ttm_bo_del_from_lru(bo); mtx_unlock(&glob->lru_lock); ttm_bo_list_ref_sub(bo, put_count, true); } else mtx_unlock(&glob->lru_lock); return ret; } void ttm_bo_unreserve_locked(struct ttm_buffer_object *bo) { ttm_bo_add_to_lru(bo); atomic_set(&bo->reserved, 0); wakeup(bo); } void ttm_bo_unreserve(struct ttm_buffer_object *bo) { struct ttm_bo_global *glob = bo->glob; mtx_lock(&glob->lru_lock); ttm_bo_unreserve_locked(bo); mtx_unlock(&glob->lru_lock); } /* * Call bo->mutex locked. */ static int ttm_bo_add_ttm(struct ttm_buffer_object *bo, bool zero_alloc) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_bo_global *glob = bo->glob; int ret = 0; uint32_t page_flags = 0; TTM_ASSERT_LOCKED(&bo->mutex); bo->ttm = NULL; if (bdev->need_dma32) page_flags |= TTM_PAGE_FLAG_DMA32; switch (bo->type) { case ttm_bo_type_device: if (zero_alloc) page_flags |= TTM_PAGE_FLAG_ZERO_ALLOC; case ttm_bo_type_kernel: bo->ttm = bdev->driver->ttm_tt_create(bdev, bo->num_pages << PAGE_SHIFT, page_flags, glob->dummy_read_page); if (unlikely(bo->ttm == NULL)) ret = -ENOMEM; break; case ttm_bo_type_sg: bo->ttm = bdev->driver->ttm_tt_create(bdev, bo->num_pages << PAGE_SHIFT, page_flags | TTM_PAGE_FLAG_SG, glob->dummy_read_page); if (unlikely(bo->ttm == NULL)) { ret = -ENOMEM; break; } bo->ttm->sg = bo->sg; break; default: printf("[TTM] Illegal buffer object type\n"); ret = -EINVAL; break; } return ret; } static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem, bool evict, bool interruptible, bool no_wait_gpu) { struct ttm_bo_device *bdev = bo->bdev; bool old_is_pci = ttm_mem_reg_is_pci(bdev, &bo->mem); bool new_is_pci = ttm_mem_reg_is_pci(bdev, mem); struct ttm_mem_type_manager *old_man = &bdev->man[bo->mem.mem_type]; struct ttm_mem_type_manager *new_man = &bdev->man[mem->mem_type]; int ret = 0; if (old_is_pci || new_is_pci || ((mem->placement & bo->mem.placement & TTM_PL_MASK_CACHING) == 0)) { ret = ttm_mem_io_lock(old_man, true); if (unlikely(ret != 0)) goto out_err; ttm_bo_unmap_virtual_locked(bo); ttm_mem_io_unlock(old_man); } /* * Create and bind a ttm if required. */ if (!(new_man->flags & TTM_MEMTYPE_FLAG_FIXED)) { if (bo->ttm == NULL) { bool zero = !(old_man->flags & TTM_MEMTYPE_FLAG_FIXED); ret = ttm_bo_add_ttm(bo, zero); if (ret) goto out_err; } ret = ttm_tt_set_placement_caching(bo->ttm, mem->placement); if (ret) goto out_err; if (mem->mem_type != TTM_PL_SYSTEM) { ret = ttm_tt_bind(bo->ttm, mem); if (ret) goto out_err; } if (bo->mem.mem_type == TTM_PL_SYSTEM) { if (bdev->driver->move_notify) bdev->driver->move_notify(bo, mem); bo->mem = *mem; mem->mm_node = NULL; goto moved; } } if (bdev->driver->move_notify) bdev->driver->move_notify(bo, mem); if (!(old_man->flags & TTM_MEMTYPE_FLAG_FIXED) && !(new_man->flags & TTM_MEMTYPE_FLAG_FIXED)) ret = ttm_bo_move_ttm(bo, evict, no_wait_gpu, mem); else if (bdev->driver->move) ret = bdev->driver->move(bo, evict, interruptible, no_wait_gpu, mem); else ret = ttm_bo_move_memcpy(bo, evict, no_wait_gpu, mem); if (ret) { if (bdev->driver->move_notify) { struct ttm_mem_reg tmp_mem = *mem; *mem = bo->mem; bo->mem = tmp_mem; bdev->driver->move_notify(bo, mem); bo->mem = *mem; *mem = tmp_mem; } goto out_err; } moved: if (bo->evicted) { ret = bdev->driver->invalidate_caches(bdev, bo->mem.placement); if (ret) printf("[TTM] Can not flush read caches\n"); bo->evicted = false; } if (bo->mem.mm_node) { bo->offset = (bo->mem.start << PAGE_SHIFT) + bdev->man[bo->mem.mem_type].gpu_offset; bo->cur_placement = bo->mem.placement; } else bo->offset = 0; return 0; out_err: new_man = &bdev->man[bo->mem.mem_type]; if ((new_man->flags & TTM_MEMTYPE_FLAG_FIXED) && bo->ttm) { ttm_tt_unbind(bo->ttm); ttm_tt_destroy(bo->ttm); bo->ttm = NULL; } return ret; } /** * Call bo::reserved. * Will release GPU memory type usage on destruction. * This is the place to put in driver specific hooks to release * driver private resources. * Will release the bo::reserved lock. */ static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo) { if (bo->bdev->driver->move_notify) bo->bdev->driver->move_notify(bo, NULL); if (bo->ttm) { ttm_tt_unbind(bo->ttm); ttm_tt_destroy(bo->ttm); bo->ttm = NULL; } ttm_bo_mem_put(bo, &bo->mem); atomic_set(&bo->reserved, 0); wakeup(&bo); /* * Since the final reference to this bo may not be dropped by * the current task we have to put a memory barrier here to make * sure the changes done in this function are always visible. * * This function only needs protection against the final kref_put. */ mb(); } static void ttm_bo_cleanup_refs_or_queue(struct ttm_buffer_object *bo) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_bo_global *glob = bo->glob; struct ttm_bo_driver *driver = bdev->driver; void *sync_obj = NULL; int put_count; int ret; mtx_lock(&glob->lru_lock); ret = ttm_bo_reserve_nolru(bo, false, true, false, 0); mtx_lock(&bdev->fence_lock); (void) ttm_bo_wait(bo, false, false, true); if (!ret && !bo->sync_obj) { mtx_unlock(&bdev->fence_lock); put_count = ttm_bo_del_from_lru(bo); mtx_unlock(&glob->lru_lock); ttm_bo_cleanup_memtype_use(bo); ttm_bo_list_ref_sub(bo, put_count, true); return; } if (bo->sync_obj) sync_obj = driver->sync_obj_ref(bo->sync_obj); mtx_unlock(&bdev->fence_lock); if (!ret) { atomic_set(&bo->reserved, 0); wakeup(bo); } refcount_acquire(&bo->list_kref); list_add_tail(&bo->ddestroy, &bdev->ddestroy); mtx_unlock(&glob->lru_lock); if (sync_obj) { driver->sync_obj_flush(sync_obj); driver->sync_obj_unref(&sync_obj); } taskqueue_enqueue_timeout(taskqueue_thread, &bdev->wq, ((hz / 100) < 1) ? 1 : hz / 100); } /** * function ttm_bo_cleanup_refs_and_unlock * If bo idle, remove from delayed- and lru lists, and unref. * If not idle, do nothing. * * Must be called with lru_lock and reservation held, this function * will drop both before returning. * * @interruptible Any sleeps should occur interruptibly. * @no_wait_gpu Never wait for gpu. Return -EBUSY instead. */ static int ttm_bo_cleanup_refs_and_unlock(struct ttm_buffer_object *bo, bool interruptible, bool no_wait_gpu) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_bo_driver *driver = bdev->driver; struct ttm_bo_global *glob = bo->glob; int put_count; int ret; mtx_lock(&bdev->fence_lock); ret = ttm_bo_wait(bo, false, false, true); if (ret && !no_wait_gpu) { void *sync_obj; /* * Take a reference to the fence and unreserve, * at this point the buffer should be dead, so * no new sync objects can be attached. */ sync_obj = driver->sync_obj_ref(bo->sync_obj); mtx_unlock(&bdev->fence_lock); atomic_set(&bo->reserved, 0); wakeup(bo); mtx_unlock(&glob->lru_lock); ret = driver->sync_obj_wait(sync_obj, false, interruptible); driver->sync_obj_unref(&sync_obj); if (ret) return ret; /* * remove sync_obj with ttm_bo_wait, the wait should be * finished, and no new wait object should have been added. */ mtx_lock(&bdev->fence_lock); ret = ttm_bo_wait(bo, false, false, true); mtx_unlock(&bdev->fence_lock); if (ret) return ret; mtx_lock(&glob->lru_lock); ret = ttm_bo_reserve_nolru(bo, false, true, false, 0); /* * We raced, and lost, someone else holds the reservation now, * and is probably busy in ttm_bo_cleanup_memtype_use. * * Even if it's not the case, because we finished waiting any * delayed destruction would succeed, so just return success * here. */ if (ret) { mtx_unlock(&glob->lru_lock); return 0; } } else mtx_unlock(&bdev->fence_lock); if (ret || unlikely(list_empty(&bo->ddestroy))) { atomic_set(&bo->reserved, 0); wakeup(bo); mtx_unlock(&glob->lru_lock); return ret; } put_count = ttm_bo_del_from_lru(bo); list_del_init(&bo->ddestroy); ++put_count; mtx_unlock(&glob->lru_lock); ttm_bo_cleanup_memtype_use(bo); ttm_bo_list_ref_sub(bo, put_count, true); return 0; } /** * Traverse the delayed list, and call ttm_bo_cleanup_refs on all * encountered buffers. */ static int ttm_bo_delayed_delete(struct ttm_bo_device *bdev, bool remove_all) { struct ttm_bo_global *glob = bdev->glob; struct ttm_buffer_object *entry = NULL; int ret = 0; mtx_lock(&glob->lru_lock); if (list_empty(&bdev->ddestroy)) goto out_unlock; entry = list_first_entry(&bdev->ddestroy, struct ttm_buffer_object, ddestroy); refcount_acquire(&entry->list_kref); for (;;) { struct ttm_buffer_object *nentry = NULL; if (entry->ddestroy.next != &bdev->ddestroy) { nentry = list_first_entry(&entry->ddestroy, struct ttm_buffer_object, ddestroy); refcount_acquire(&nentry->list_kref); } ret = ttm_bo_reserve_nolru(entry, false, true, false, 0); if (remove_all && ret) { ret = ttm_bo_reserve_nolru(entry, false, false, false, 0); } if (!ret) ret = ttm_bo_cleanup_refs_and_unlock(entry, false, !remove_all); else mtx_unlock(&glob->lru_lock); if (refcount_release(&entry->list_kref)) ttm_bo_release_list(entry); entry = nentry; if (ret || !entry) goto out; mtx_lock(&glob->lru_lock); if (list_empty(&entry->ddestroy)) break; } out_unlock: mtx_unlock(&glob->lru_lock); out: if (entry && refcount_release(&entry->list_kref)) ttm_bo_release_list(entry); return ret; } static void ttm_bo_delayed_workqueue(void *arg, int pending __unused) { struct ttm_bo_device *bdev = arg; if (ttm_bo_delayed_delete(bdev, false)) { taskqueue_enqueue_timeout(taskqueue_thread, &bdev->wq, ((hz / 100) < 1) ? 1 : hz / 100); } } static void ttm_bo_release(struct ttm_buffer_object *bo) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type]; rw_wlock(&bdev->vm_lock); if (likely(bo->vm_node != NULL)) { RB_REMOVE(ttm_bo_device_buffer_objects, &bdev->addr_space_rb, bo); drm_mm_put_block(bo->vm_node); bo->vm_node = NULL; } rw_wunlock(&bdev->vm_lock); ttm_mem_io_lock(man, false); ttm_mem_io_free_vm(bo); ttm_mem_io_unlock(man); ttm_bo_cleanup_refs_or_queue(bo); if (refcount_release(&bo->list_kref)) ttm_bo_release_list(bo); } void ttm_bo_unref(struct ttm_buffer_object **p_bo) { struct ttm_buffer_object *bo = *p_bo; *p_bo = NULL; if (refcount_release(&bo->kref)) ttm_bo_release(bo); } int ttm_bo_lock_delayed_workqueue(struct ttm_bo_device *bdev) { int pending; taskqueue_cancel_timeout(taskqueue_thread, &bdev->wq, &pending); if (pending) taskqueue_drain_timeout(taskqueue_thread, &bdev->wq); return (pending); } void ttm_bo_unlock_delayed_workqueue(struct ttm_bo_device *bdev, int resched) { if (resched) { taskqueue_enqueue_timeout(taskqueue_thread, &bdev->wq, ((hz / 100) < 1) ? 1 : hz / 100); } } static int ttm_bo_evict(struct ttm_buffer_object *bo, bool interruptible, bool no_wait_gpu) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_mem_reg evict_mem; struct ttm_placement placement; int ret = 0; mtx_lock(&bdev->fence_lock); ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu); mtx_unlock(&bdev->fence_lock); if (unlikely(ret != 0)) { if (ret != -ERESTART) { printf("[TTM] Failed to expire sync object before buffer eviction\n"); } goto out; } MPASS(ttm_bo_is_reserved(bo)); evict_mem = bo->mem; evict_mem.mm_node = NULL; evict_mem.bus.io_reserved_vm = false; evict_mem.bus.io_reserved_count = 0; placement.fpfn = 0; placement.lpfn = 0; placement.num_placement = 0; placement.num_busy_placement = 0; bdev->driver->evict_flags(bo, &placement); ret = ttm_bo_mem_space(bo, &placement, &evict_mem, interruptible, no_wait_gpu); if (ret) { if (ret != -ERESTART) { printf("[TTM] Failed to find memory space for buffer 0x%p eviction\n", bo); ttm_bo_mem_space_debug(bo, &placement); } goto out; } ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, interruptible, no_wait_gpu); if (ret) { if (ret != -ERESTART) printf("[TTM] Buffer eviction failed\n"); ttm_bo_mem_put(bo, &evict_mem); goto out; } bo->evicted = true; out: return ret; } static int ttm_mem_evict_first(struct ttm_bo_device *bdev, uint32_t mem_type, bool interruptible, bool no_wait_gpu) { struct ttm_bo_global *glob = bdev->glob; struct ttm_mem_type_manager *man = &bdev->man[mem_type]; struct ttm_buffer_object *bo; int ret = -EBUSY, put_count; mtx_lock(&glob->lru_lock); list_for_each_entry(bo, &man->lru, lru) { ret = ttm_bo_reserve_nolru(bo, false, true, false, 0); if (!ret) break; } if (ret) { mtx_unlock(&glob->lru_lock); return ret; } refcount_acquire(&bo->list_kref); if (!list_empty(&bo->ddestroy)) { ret = ttm_bo_cleanup_refs_and_unlock(bo, interruptible, no_wait_gpu); if (refcount_release(&bo->list_kref)) ttm_bo_release_list(bo); return ret; } put_count = ttm_bo_del_from_lru(bo); mtx_unlock(&glob->lru_lock); MPASS(ret == 0); ttm_bo_list_ref_sub(bo, put_count, true); ret = ttm_bo_evict(bo, interruptible, no_wait_gpu); ttm_bo_unreserve(bo); if (refcount_release(&bo->list_kref)) ttm_bo_release_list(bo); return ret; } void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem) { struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type]; if (mem->mm_node) (*man->func->put_node)(man, mem); } /** * Repeatedly evict memory from the LRU for @mem_type until we create enough * space, or we've evicted everything and there isn't enough space. */ static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo, uint32_t mem_type, struct ttm_placement *placement, struct ttm_mem_reg *mem, bool interruptible, bool no_wait_gpu) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_mem_type_manager *man = &bdev->man[mem_type]; int ret; do { ret = (*man->func->get_node)(man, bo, placement, mem); if (unlikely(ret != 0)) return ret; if (mem->mm_node) break; ret = ttm_mem_evict_first(bdev, mem_type, interruptible, no_wait_gpu); if (unlikely(ret != 0)) return ret; } while (1); if (mem->mm_node == NULL) return -ENOMEM; mem->mem_type = mem_type; return 0; } static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man, uint32_t cur_placement, uint32_t proposed_placement) { uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING; uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING; /** * Keep current caching if possible. */ if ((cur_placement & caching) != 0) result |= (cur_placement & caching); else if ((man->default_caching & caching) != 0) result |= man->default_caching; else if ((TTM_PL_FLAG_CACHED & caching) != 0) result |= TTM_PL_FLAG_CACHED; else if ((TTM_PL_FLAG_WC & caching) != 0) result |= TTM_PL_FLAG_WC; else if ((TTM_PL_FLAG_UNCACHED & caching) != 0) result |= TTM_PL_FLAG_UNCACHED; return result; } static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man, uint32_t mem_type, uint32_t proposed_placement, uint32_t *masked_placement) { uint32_t cur_flags = ttm_bo_type_flags(mem_type); if ((cur_flags & proposed_placement & TTM_PL_MASK_MEM) == 0) return false; if ((proposed_placement & man->available_caching) == 0) return false; cur_flags |= (proposed_placement & man->available_caching); *masked_placement = cur_flags; return true; } /** * Creates space for memory region @mem according to its type. * * This function first searches for free space in compatible memory types in * the priority order defined by the driver. If free space isn't found, then * ttm_bo_mem_force_space is attempted in priority order to evict and find * space. */ int ttm_bo_mem_space(struct ttm_buffer_object *bo, struct ttm_placement *placement, struct ttm_mem_reg *mem, bool interruptible, bool no_wait_gpu) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_mem_type_manager *man; uint32_t mem_type = TTM_PL_SYSTEM; uint32_t cur_flags = 0; bool type_found = false; bool type_ok = false; bool has_erestartsys = false; int i, ret; mem->mm_node = NULL; for (i = 0; i < placement->num_placement; ++i) { ret = ttm_mem_type_from_flags(placement->placement[i], &mem_type); if (ret) return ret; man = &bdev->man[mem_type]; type_ok = ttm_bo_mt_compatible(man, mem_type, placement->placement[i], &cur_flags); if (!type_ok) continue; cur_flags = ttm_bo_select_caching(man, bo->mem.placement, cur_flags); /* * Use the access and other non-mapping-related flag bits from * the memory placement flags to the current flags */ ttm_flag_masked(&cur_flags, placement->placement[i], ~TTM_PL_MASK_MEMTYPE); if (mem_type == TTM_PL_SYSTEM) break; if (man->has_type && man->use_type) { type_found = true; ret = (*man->func->get_node)(man, bo, placement, mem); if (unlikely(ret)) return ret; } if (mem->mm_node) break; } if ((type_ok && (mem_type == TTM_PL_SYSTEM)) || mem->mm_node) { mem->mem_type = mem_type; mem->placement = cur_flags; return 0; } if (!type_found) return -EINVAL; for (i = 0; i < placement->num_busy_placement; ++i) { ret = ttm_mem_type_from_flags(placement->busy_placement[i], &mem_type); if (ret) return ret; man = &bdev->man[mem_type]; if (!man->has_type) continue; if (!ttm_bo_mt_compatible(man, mem_type, placement->busy_placement[i], &cur_flags)) continue; cur_flags = ttm_bo_select_caching(man, bo->mem.placement, cur_flags); /* * Use the access and other non-mapping-related flag bits from * the memory placement flags to the current flags */ ttm_flag_masked(&cur_flags, placement->busy_placement[i], ~TTM_PL_MASK_MEMTYPE); if (mem_type == TTM_PL_SYSTEM) { mem->mem_type = mem_type; mem->placement = cur_flags; mem->mm_node = NULL; return 0; } ret = ttm_bo_mem_force_space(bo, mem_type, placement, mem, interruptible, no_wait_gpu); if (ret == 0 && mem->mm_node) { mem->placement = cur_flags; return 0; } if (ret == -ERESTART) has_erestartsys = true; } ret = (has_erestartsys) ? -ERESTART : -ENOMEM; return ret; } static int ttm_bo_move_buffer(struct ttm_buffer_object *bo, struct ttm_placement *placement, bool interruptible, bool no_wait_gpu) { int ret = 0; struct ttm_mem_reg mem; struct ttm_bo_device *bdev = bo->bdev; MPASS(ttm_bo_is_reserved(bo)); /* * FIXME: It's possible to pipeline buffer moves. * Have the driver move function wait for idle when necessary, * instead of doing it here. */ mtx_lock(&bdev->fence_lock); ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu); mtx_unlock(&bdev->fence_lock); if (ret) return ret; mem.num_pages = bo->num_pages; mem.size = mem.num_pages << PAGE_SHIFT; mem.page_alignment = bo->mem.page_alignment; mem.bus.io_reserved_vm = false; mem.bus.io_reserved_count = 0; /* * Determine where to move the buffer. */ ret = ttm_bo_mem_space(bo, placement, &mem, interruptible, no_wait_gpu); if (ret) goto out_unlock; ret = ttm_bo_handle_move_mem(bo, &mem, false, interruptible, no_wait_gpu); out_unlock: if (ret && mem.mm_node) ttm_bo_mem_put(bo, &mem); return ret; } static int ttm_bo_mem_compat(struct ttm_placement *placement, struct ttm_mem_reg *mem) { int i; if (mem->mm_node && placement->lpfn != 0 && (mem->start < placement->fpfn || mem->start + mem->num_pages > placement->lpfn)) return -1; for (i = 0; i < placement->num_placement; i++) { if ((placement->placement[i] & mem->placement & TTM_PL_MASK_CACHING) && (placement->placement[i] & mem->placement & TTM_PL_MASK_MEM)) return i; } return -1; } int ttm_bo_validate(struct ttm_buffer_object *bo, struct ttm_placement *placement, bool interruptible, bool no_wait_gpu) { int ret; MPASS(ttm_bo_is_reserved(bo)); /* Check that range is valid */ if (placement->lpfn || placement->fpfn) if (placement->fpfn > placement->lpfn || (placement->lpfn - placement->fpfn) < bo->num_pages) return -EINVAL; /* * Check whether we need to move buffer. */ ret = ttm_bo_mem_compat(placement, &bo->mem); if (ret < 0) { ret = ttm_bo_move_buffer(bo, placement, interruptible, no_wait_gpu); if (ret) return ret; } else { /* * Use the access and other non-mapping-related flag bits from * the compatible memory placement flags to the active flags */ ttm_flag_masked(&bo->mem.placement, placement->placement[ret], ~TTM_PL_MASK_MEMTYPE); } /* * We might need to add a TTM. */ if (bo->mem.mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) { ret = ttm_bo_add_ttm(bo, true); if (ret) return ret; } return 0; } int ttm_bo_check_placement(struct ttm_buffer_object *bo, struct ttm_placement *placement) { MPASS(!((placement->fpfn || placement->lpfn) && (bo->mem.num_pages > (placement->lpfn - placement->fpfn)))); return 0; } int ttm_bo_init(struct ttm_bo_device *bdev, struct ttm_buffer_object *bo, unsigned long size, enum ttm_bo_type type, struct ttm_placement *placement, uint32_t page_alignment, bool interruptible, struct vm_object *persistent_swap_storage, size_t acc_size, struct sg_table *sg, void (*destroy) (struct ttm_buffer_object *)) { int ret = 0; unsigned long num_pages; struct ttm_mem_global *mem_glob = bdev->glob->mem_glob; ret = ttm_mem_global_alloc(mem_glob, acc_size, false, false); if (ret) { printf("[TTM] Out of kernel memory\n"); if (destroy) (*destroy)(bo); else free(bo, M_TTM_BO); return -ENOMEM; } num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT; if (num_pages == 0) { printf("[TTM] Illegal buffer object size\n"); if (destroy) (*destroy)(bo); else free(bo, M_TTM_BO); ttm_mem_global_free(mem_glob, acc_size); return -EINVAL; } bo->destroy = destroy; refcount_init(&bo->kref, 1); refcount_init(&bo->list_kref, 1); atomic_set(&bo->cpu_writers, 0); atomic_set(&bo->reserved, 1); INIT_LIST_HEAD(&bo->lru); INIT_LIST_HEAD(&bo->ddestroy); INIT_LIST_HEAD(&bo->swap); INIT_LIST_HEAD(&bo->io_reserve_lru); bo->bdev = bdev; bo->glob = bdev->glob; bo->type = type; bo->num_pages = num_pages; bo->mem.size = num_pages << PAGE_SHIFT; bo->mem.mem_type = TTM_PL_SYSTEM; bo->mem.num_pages = bo->num_pages; bo->mem.mm_node = NULL; bo->mem.page_alignment = page_alignment; bo->mem.bus.io_reserved_vm = false; bo->mem.bus.io_reserved_count = 0; bo->priv_flags = 0; bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED); bo->seq_valid = false; bo->persistent_swap_storage = persistent_swap_storage; bo->acc_size = acc_size; bo->sg = sg; atomic_inc(&bo->glob->bo_count); ret = ttm_bo_check_placement(bo, placement); if (unlikely(ret != 0)) goto out_err; /* * For ttm_bo_type_device buffers, allocate * address space from the device. */ if (bo->type == ttm_bo_type_device || bo->type == ttm_bo_type_sg) { ret = ttm_bo_setup_vm(bo); if (ret) goto out_err; } ret = ttm_bo_validate(bo, placement, interruptible, false); if (ret) goto out_err; ttm_bo_unreserve(bo); return 0; out_err: ttm_bo_unreserve(bo); ttm_bo_unref(&bo); return ret; } size_t ttm_bo_acc_size(struct ttm_bo_device *bdev, unsigned long bo_size, unsigned struct_size) { unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT; size_t size = 0; size += ttm_round_pot(struct_size); size += PAGE_ALIGN(npages * sizeof(void *)); size += ttm_round_pot(sizeof(struct ttm_tt)); return size; } size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev, unsigned long bo_size, unsigned struct_size) { unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT; size_t size = 0; size += ttm_round_pot(struct_size); size += PAGE_ALIGN(npages * sizeof(void *)); size += PAGE_ALIGN(npages * sizeof(dma_addr_t)); size += ttm_round_pot(sizeof(struct ttm_dma_tt)); return size; } int ttm_bo_create(struct ttm_bo_device *bdev, unsigned long size, enum ttm_bo_type type, struct ttm_placement *placement, uint32_t page_alignment, bool interruptible, struct vm_object *persistent_swap_storage, struct ttm_buffer_object **p_bo) { struct ttm_buffer_object *bo; size_t acc_size; int ret; bo = malloc(sizeof(*bo), M_TTM_BO, M_WAITOK | M_ZERO); acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object)); ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment, interruptible, persistent_swap_storage, acc_size, NULL, NULL); if (likely(ret == 0)) *p_bo = bo; return ret; } static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev, unsigned mem_type, bool allow_errors) { struct ttm_mem_type_manager *man = &bdev->man[mem_type]; struct ttm_bo_global *glob = bdev->glob; int ret; /* * Can't use standard list traversal since we're unlocking. */ mtx_lock(&glob->lru_lock); while (!list_empty(&man->lru)) { mtx_unlock(&glob->lru_lock); ret = ttm_mem_evict_first(bdev, mem_type, false, false); if (ret) { if (allow_errors) { return ret; } else { printf("[TTM] Cleanup eviction failed\n"); } } mtx_lock(&glob->lru_lock); } mtx_unlock(&glob->lru_lock); return 0; } int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type) { struct ttm_mem_type_manager *man; int ret = -EINVAL; if (mem_type >= TTM_NUM_MEM_TYPES) { printf("[TTM] Illegal memory type %d\n", mem_type); return ret; } man = &bdev->man[mem_type]; if (!man->has_type) { printf("[TTM] Trying to take down uninitialized memory manager type %u\n", mem_type); return ret; } man->use_type = false; man->has_type = false; ret = 0; if (mem_type > 0) { ttm_bo_force_list_clean(bdev, mem_type, false); ret = (*man->func->takedown)(man); } return ret; } int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type) { struct ttm_mem_type_manager *man = &bdev->man[mem_type]; if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) { printf("[TTM] Illegal memory manager memory type %u\n", mem_type); return -EINVAL; } if (!man->has_type) { printf("[TTM] Memory type %u has not been initialized\n", mem_type); return 0; } return ttm_bo_force_list_clean(bdev, mem_type, true); } int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type, unsigned long p_size) { int ret = -EINVAL; struct ttm_mem_type_manager *man; MPASS(type < TTM_NUM_MEM_TYPES); man = &bdev->man[type]; MPASS(!man->has_type); man->io_reserve_fastpath = true; man->use_io_reserve_lru = false; sx_init(&man->io_reserve_mutex, "ttmman"); INIT_LIST_HEAD(&man->io_reserve_lru); ret = bdev->driver->init_mem_type(bdev, type, man); if (ret) return ret; man->bdev = bdev; ret = 0; if (type != TTM_PL_SYSTEM) { ret = (*man->func->init)(man, p_size); if (ret) return ret; } man->has_type = true; man->use_type = true; man->size = p_size; INIT_LIST_HEAD(&man->lru); return 0; } static void ttm_bo_global_kobj_release(struct ttm_bo_global *glob) { ttm_mem_unregister_shrink(glob->mem_glob, &glob->shrink); vm_page_free(glob->dummy_read_page); } void ttm_bo_global_release(struct drm_global_reference *ref) { struct ttm_bo_global *glob = ref->object; if (refcount_release(&glob->kobj_ref)) ttm_bo_global_kobj_release(glob); } int ttm_bo_global_init(struct drm_global_reference *ref) { struct ttm_bo_global_ref *bo_ref = container_of(ref, struct ttm_bo_global_ref, ref); struct ttm_bo_global *glob = ref->object; int ret; sx_init(&glob->device_list_mutex, "ttmdlm"); mtx_init(&glob->lru_lock, "ttmlru", NULL, MTX_DEF); glob->mem_glob = bo_ref->mem_glob; glob->dummy_read_page = vm_page_alloc_contig(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ, 1, 0, VM_MAX_ADDRESS, PAGE_SIZE, 0, VM_MEMATTR_UNCACHEABLE); if (unlikely(glob->dummy_read_page == NULL)) { ret = -ENOMEM; goto out_no_drp; } INIT_LIST_HEAD(&glob->swap_lru); INIT_LIST_HEAD(&glob->device_list); ttm_mem_init_shrink(&glob->shrink, ttm_bo_swapout); ret = ttm_mem_register_shrink(glob->mem_glob, &glob->shrink); if (unlikely(ret != 0)) { printf("[TTM] Could not register buffer object swapout\n"); goto out_no_shrink; } atomic_set(&glob->bo_count, 0); refcount_init(&glob->kobj_ref, 1); return (0); out_no_shrink: vm_page_free(glob->dummy_read_page); out_no_drp: free(glob, M_DRM_GLOBAL); return ret; } int ttm_bo_device_release(struct ttm_bo_device *bdev) { int ret = 0; unsigned i = TTM_NUM_MEM_TYPES; struct ttm_mem_type_manager *man; struct ttm_bo_global *glob = bdev->glob; while (i--) { man = &bdev->man[i]; if (man->has_type) { man->use_type = false; if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) { ret = -EBUSY; printf("[TTM] DRM memory manager type %d is not clean\n", i); } man->has_type = false; } } sx_xlock(&glob->device_list_mutex); list_del(&bdev->device_list); sx_xunlock(&glob->device_list_mutex); if (taskqueue_cancel_timeout(taskqueue_thread, &bdev->wq, NULL)) taskqueue_drain_timeout(taskqueue_thread, &bdev->wq); while (ttm_bo_delayed_delete(bdev, true)) ; mtx_lock(&glob->lru_lock); if (list_empty(&bdev->ddestroy)) TTM_DEBUG("Delayed destroy list was clean\n"); if (list_empty(&bdev->man[0].lru)) TTM_DEBUG("Swap list was clean\n"); mtx_unlock(&glob->lru_lock); MPASS(drm_mm_clean(&bdev->addr_space_mm)); rw_wlock(&bdev->vm_lock); drm_mm_takedown(&bdev->addr_space_mm); rw_wunlock(&bdev->vm_lock); return ret; } int ttm_bo_device_init(struct ttm_bo_device *bdev, struct ttm_bo_global *glob, struct ttm_bo_driver *driver, uint64_t file_page_offset, bool need_dma32) { int ret = -EINVAL; rw_init(&bdev->vm_lock, "ttmvml"); bdev->driver = driver; memset(bdev->man, 0, sizeof(bdev->man)); /* * Initialize the system memory buffer type. * Other types need to be driver / IOCTL initialized. */ ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0); if (unlikely(ret != 0)) goto out_no_sys; RB_INIT(&bdev->addr_space_rb); ret = drm_mm_init(&bdev->addr_space_mm, file_page_offset, 0x10000000); if (unlikely(ret != 0)) goto out_no_addr_mm; TIMEOUT_TASK_INIT(taskqueue_thread, &bdev->wq, 0, ttm_bo_delayed_workqueue, bdev); INIT_LIST_HEAD(&bdev->ddestroy); bdev->dev_mapping = NULL; bdev->glob = glob; bdev->need_dma32 = need_dma32; bdev->val_seq = 0; mtx_init(&bdev->fence_lock, "ttmfence", NULL, MTX_DEF); sx_xlock(&glob->device_list_mutex); list_add_tail(&bdev->device_list, &glob->device_list); sx_xunlock(&glob->device_list_mutex); return 0; out_no_addr_mm: ttm_bo_clean_mm(bdev, 0); out_no_sys: return ret; } /* * buffer object vm functions. */ bool ttm_mem_reg_is_pci(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem) { struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type]; if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) { if (mem->mem_type == TTM_PL_SYSTEM) return false; if (man->flags & TTM_MEMTYPE_FLAG_CMA) return false; if (mem->placement & TTM_PL_FLAG_CACHED) return false; } return true; } void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo) { ttm_bo_release_mmap(bo); ttm_mem_io_free_vm(bo); } void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type]; ttm_mem_io_lock(man, false); ttm_bo_unmap_virtual_locked(bo); ttm_mem_io_unlock(man); } static void ttm_bo_vm_insert_rb(struct ttm_buffer_object *bo) { struct ttm_bo_device *bdev = bo->bdev; /* The caller acquired bdev->vm_lock. */ RB_INSERT(ttm_bo_device_buffer_objects, &bdev->addr_space_rb, bo); } /** * ttm_bo_setup_vm: * * @bo: the buffer to allocate address space for * * Allocate address space in the drm device so that applications * can mmap the buffer and access the contents. This only * applies to ttm_bo_type_device objects as others are not * placed in the drm device address space. */ static int ttm_bo_setup_vm(struct ttm_buffer_object *bo) { struct ttm_bo_device *bdev = bo->bdev; int ret; retry_pre_get: ret = drm_mm_pre_get(&bdev->addr_space_mm); if (unlikely(ret != 0)) return ret; rw_wlock(&bdev->vm_lock); bo->vm_node = drm_mm_search_free(&bdev->addr_space_mm, bo->mem.num_pages, 0, 0); if (unlikely(bo->vm_node == NULL)) { ret = -ENOMEM; goto out_unlock; } bo->vm_node = drm_mm_get_block_atomic(bo->vm_node, bo->mem.num_pages, 0); if (unlikely(bo->vm_node == NULL)) { rw_wunlock(&bdev->vm_lock); goto retry_pre_get; } ttm_bo_vm_insert_rb(bo); rw_wunlock(&bdev->vm_lock); bo->addr_space_offset = ((uint64_t) bo->vm_node->start) << PAGE_SHIFT; return 0; out_unlock: rw_wunlock(&bdev->vm_lock); return ret; } int ttm_bo_wait(struct ttm_buffer_object *bo, bool lazy, bool interruptible, bool no_wait) { struct ttm_bo_driver *driver = bo->bdev->driver; struct ttm_bo_device *bdev = bo->bdev; void *sync_obj; int ret = 0; if (likely(bo->sync_obj == NULL)) return 0; while (bo->sync_obj) { if (driver->sync_obj_signaled(bo->sync_obj)) { void *tmp_obj = bo->sync_obj; bo->sync_obj = NULL; - clear_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags); + atomic_clear_long(&bo->priv_flags, + 1UL << TTM_BO_PRIV_FLAG_MOVING); mtx_unlock(&bdev->fence_lock); driver->sync_obj_unref(&tmp_obj); mtx_lock(&bdev->fence_lock); continue; } if (no_wait) return -EBUSY; sync_obj = driver->sync_obj_ref(bo->sync_obj); mtx_unlock(&bdev->fence_lock); ret = driver->sync_obj_wait(sync_obj, lazy, interruptible); if (unlikely(ret != 0)) { driver->sync_obj_unref(&sync_obj); mtx_lock(&bdev->fence_lock); return ret; } mtx_lock(&bdev->fence_lock); if (likely(bo->sync_obj == sync_obj)) { void *tmp_obj = bo->sync_obj; bo->sync_obj = NULL; - clear_bit(TTM_BO_PRIV_FLAG_MOVING, - &bo->priv_flags); + atomic_clear_long(&bo->priv_flags, + 1UL << TTM_BO_PRIV_FLAG_MOVING); mtx_unlock(&bdev->fence_lock); driver->sync_obj_unref(&sync_obj); driver->sync_obj_unref(&tmp_obj); mtx_lock(&bdev->fence_lock); } else { mtx_unlock(&bdev->fence_lock); driver->sync_obj_unref(&sync_obj); mtx_lock(&bdev->fence_lock); } } return 0; } int ttm_bo_synccpu_write_grab(struct ttm_buffer_object *bo, bool no_wait) { struct ttm_bo_device *bdev = bo->bdev; int ret = 0; /* * Using ttm_bo_reserve makes sure the lru lists are updated. */ ret = ttm_bo_reserve(bo, true, no_wait, false, 0); if (unlikely(ret != 0)) return ret; mtx_lock(&bdev->fence_lock); ret = ttm_bo_wait(bo, false, true, no_wait); mtx_unlock(&bdev->fence_lock); if (likely(ret == 0)) atomic_inc(&bo->cpu_writers); ttm_bo_unreserve(bo); return ret; } void ttm_bo_synccpu_write_release(struct ttm_buffer_object *bo) { atomic_dec(&bo->cpu_writers); } /** * A buffer object shrink method that tries to swap out the first * buffer object on the bo_global::swap_lru list. */ static int ttm_bo_swapout(struct ttm_mem_shrink *shrink) { struct ttm_bo_global *glob = container_of(shrink, struct ttm_bo_global, shrink); struct ttm_buffer_object *bo; int ret = -EBUSY; int put_count; uint32_t swap_placement = (TTM_PL_FLAG_CACHED | TTM_PL_FLAG_SYSTEM); mtx_lock(&glob->lru_lock); list_for_each_entry(bo, &glob->swap_lru, swap) { ret = ttm_bo_reserve_nolru(bo, false, true, false, 0); if (!ret) break; } if (ret) { mtx_unlock(&glob->lru_lock); return ret; } refcount_acquire(&bo->list_kref); if (!list_empty(&bo->ddestroy)) { ret = ttm_bo_cleanup_refs_and_unlock(bo, false, false); if (refcount_release(&bo->list_kref)) ttm_bo_release_list(bo); return ret; } put_count = ttm_bo_del_from_lru(bo); mtx_unlock(&glob->lru_lock); ttm_bo_list_ref_sub(bo, put_count, true); /** * Wait for GPU, then move to system cached. */ mtx_lock(&bo->bdev->fence_lock); ret = ttm_bo_wait(bo, false, false, false); mtx_unlock(&bo->bdev->fence_lock); if (unlikely(ret != 0)) goto out; if ((bo->mem.placement & swap_placement) != swap_placement) { struct ttm_mem_reg evict_mem; evict_mem = bo->mem; evict_mem.mm_node = NULL; evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED; evict_mem.mem_type = TTM_PL_SYSTEM; ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, false, false); if (unlikely(ret != 0)) goto out; } ttm_bo_unmap_virtual(bo); /** * Swap out. Buffer will be swapped in again as soon as * anyone tries to access a ttm page. */ if (bo->bdev->driver->swap_notify) bo->bdev->driver->swap_notify(bo); ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage); out: /** * * Unreserve without putting on LRU to avoid swapping out an * already swapped buffer. */ atomic_set(&bo->reserved, 0); wakeup(bo); if (refcount_release(&bo->list_kref)) ttm_bo_release_list(bo); return ret; } void ttm_bo_swapout_all(struct ttm_bo_device *bdev) { while (ttm_bo_swapout(&bdev->glob->shrink) == 0) ; } Index: head/sys/dev/drm2/ttm/ttm_bo_util.c =================================================================== --- head/sys/dev/drm2/ttm/ttm_bo_util.c (revision 254879) +++ head/sys/dev/drm2/ttm/ttm_bo_util.c (revision 254880) @@ -1,668 +1,669 @@ /************************************************************************** * * Copyright (c) 2007-2009 VMware, Inc., Palo Alto, CA., USA * 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, sub license, 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 NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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. * **************************************************************************/ /* * Authors: Thomas Hellstrom */ #include __FBSDID("$FreeBSD$"); #include #include #include #include void ttm_bo_free_old_node(struct ttm_buffer_object *bo) { ttm_bo_mem_put(bo, &bo->mem); } int ttm_bo_move_ttm(struct ttm_buffer_object *bo, bool evict, bool no_wait_gpu, struct ttm_mem_reg *new_mem) { struct ttm_tt *ttm = bo->ttm; struct ttm_mem_reg *old_mem = &bo->mem; int ret; if (old_mem->mem_type != TTM_PL_SYSTEM) { ttm_tt_unbind(ttm); ttm_bo_free_old_node(bo); ttm_flag_masked(&old_mem->placement, TTM_PL_FLAG_SYSTEM, TTM_PL_MASK_MEM); old_mem->mem_type = TTM_PL_SYSTEM; } ret = ttm_tt_set_placement_caching(ttm, new_mem->placement); if (unlikely(ret != 0)) return ret; if (new_mem->mem_type != TTM_PL_SYSTEM) { ret = ttm_tt_bind(ttm, new_mem); if (unlikely(ret != 0)) return ret; } *old_mem = *new_mem; new_mem->mm_node = NULL; return 0; } int ttm_mem_io_lock(struct ttm_mem_type_manager *man, bool interruptible) { if (likely(man->io_reserve_fastpath)) return 0; if (interruptible) { if (sx_xlock_sig(&man->io_reserve_mutex)) return (-EINTR); else return (0); } sx_xlock(&man->io_reserve_mutex); return 0; } void ttm_mem_io_unlock(struct ttm_mem_type_manager *man) { if (likely(man->io_reserve_fastpath)) return; sx_xunlock(&man->io_reserve_mutex); } static int ttm_mem_io_evict(struct ttm_mem_type_manager *man) { struct ttm_buffer_object *bo; if (!man->use_io_reserve_lru || list_empty(&man->io_reserve_lru)) return -EAGAIN; bo = list_first_entry(&man->io_reserve_lru, struct ttm_buffer_object, io_reserve_lru); list_del_init(&bo->io_reserve_lru); ttm_bo_unmap_virtual_locked(bo); return 0; } static int ttm_mem_io_reserve(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem) { struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type]; int ret = 0; if (!bdev->driver->io_mem_reserve) return 0; if (likely(man->io_reserve_fastpath)) return bdev->driver->io_mem_reserve(bdev, mem); if (bdev->driver->io_mem_reserve && mem->bus.io_reserved_count++ == 0) { retry: ret = bdev->driver->io_mem_reserve(bdev, mem); if (ret == -EAGAIN) { ret = ttm_mem_io_evict(man); if (ret == 0) goto retry; } } return ret; } static void ttm_mem_io_free(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem) { struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type]; if (likely(man->io_reserve_fastpath)) return; if (bdev->driver->io_mem_reserve && --mem->bus.io_reserved_count == 0 && bdev->driver->io_mem_free) bdev->driver->io_mem_free(bdev, mem); } int ttm_mem_io_reserve_vm(struct ttm_buffer_object *bo) { struct ttm_mem_reg *mem = &bo->mem; int ret; if (!mem->bus.io_reserved_vm) { struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type]; ret = ttm_mem_io_reserve(bo->bdev, mem); if (unlikely(ret != 0)) return ret; mem->bus.io_reserved_vm = true; if (man->use_io_reserve_lru) list_add_tail(&bo->io_reserve_lru, &man->io_reserve_lru); } return 0; } void ttm_mem_io_free_vm(struct ttm_buffer_object *bo) { struct ttm_mem_reg *mem = &bo->mem; if (mem->bus.io_reserved_vm) { mem->bus.io_reserved_vm = false; list_del_init(&bo->io_reserve_lru); ttm_mem_io_free(bo->bdev, mem); } } static int ttm_mem_reg_ioremap(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem, void **virtual) { struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type]; int ret; void *addr; *virtual = NULL; (void) ttm_mem_io_lock(man, false); ret = ttm_mem_io_reserve(bdev, mem); ttm_mem_io_unlock(man); if (ret || !mem->bus.is_iomem) return ret; if (mem->bus.addr) { addr = mem->bus.addr; } else { addr = pmap_mapdev_attr(mem->bus.base + mem->bus.offset, mem->bus.size, (mem->placement & TTM_PL_FLAG_WC) ? VM_MEMATTR_WRITE_COMBINING : VM_MEMATTR_UNCACHEABLE); if (!addr) { (void) ttm_mem_io_lock(man, false); ttm_mem_io_free(bdev, mem); ttm_mem_io_unlock(man); return -ENOMEM; } } *virtual = addr; return 0; } static void ttm_mem_reg_iounmap(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem, void *virtual) { struct ttm_mem_type_manager *man; man = &bdev->man[mem->mem_type]; if (virtual && mem->bus.addr == NULL) pmap_unmapdev((vm_offset_t)virtual, mem->bus.size); (void) ttm_mem_io_lock(man, false); ttm_mem_io_free(bdev, mem); ttm_mem_io_unlock(man); } static int ttm_copy_io_page(void *dst, void *src, unsigned long page) { uint32_t *dstP = (uint32_t *) ((unsigned long)dst + (page << PAGE_SHIFT)); uint32_t *srcP = (uint32_t *) ((unsigned long)src + (page << PAGE_SHIFT)); int i; for (i = 0; i < PAGE_SIZE / sizeof(uint32_t); ++i) /* iowrite32(ioread32(srcP++), dstP++); */ *dstP++ = *srcP++; return 0; } static int ttm_copy_io_ttm_page(struct ttm_tt *ttm, void *src, unsigned long page, vm_memattr_t prot) { vm_page_t d = ttm->pages[page]; void *dst; if (!d) return -ENOMEM; src = (void *)((unsigned long)src + (page << PAGE_SHIFT)); /* XXXKIB can't sleep ? */ dst = pmap_mapdev_attr(VM_PAGE_TO_PHYS(d), PAGE_SIZE, prot); if (!dst) return -ENOMEM; memcpy(dst, src, PAGE_SIZE); pmap_unmapdev((vm_offset_t)dst, PAGE_SIZE); return 0; } static int ttm_copy_ttm_io_page(struct ttm_tt *ttm, void *dst, unsigned long page, vm_memattr_t prot) { vm_page_t s = ttm->pages[page]; void *src; if (!s) return -ENOMEM; dst = (void *)((unsigned long)dst + (page << PAGE_SHIFT)); src = pmap_mapdev_attr(VM_PAGE_TO_PHYS(s), PAGE_SIZE, prot); if (!src) return -ENOMEM; memcpy(dst, src, PAGE_SIZE); pmap_unmapdev((vm_offset_t)src, PAGE_SIZE); return 0; } int ttm_bo_move_memcpy(struct ttm_buffer_object *bo, bool evict, bool no_wait_gpu, struct ttm_mem_reg *new_mem) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_mem_type_manager *man = &bdev->man[new_mem->mem_type]; struct ttm_tt *ttm = bo->ttm; struct ttm_mem_reg *old_mem = &bo->mem; struct ttm_mem_reg old_copy = *old_mem; void *old_iomap; void *new_iomap; int ret; unsigned long i; unsigned long page; unsigned long add = 0; int dir; ret = ttm_mem_reg_ioremap(bdev, old_mem, &old_iomap); if (ret) return ret; ret = ttm_mem_reg_ioremap(bdev, new_mem, &new_iomap); if (ret) goto out; if (old_iomap == NULL && new_iomap == NULL) goto out2; if (old_iomap == NULL && ttm == NULL) goto out2; if (ttm->state == tt_unpopulated) { ret = ttm->bdev->driver->ttm_tt_populate(ttm); if (ret) { /* if we fail here don't nuke the mm node * as the bo still owns it */ old_copy.mm_node = NULL; goto out1; } } add = 0; dir = 1; if ((old_mem->mem_type == new_mem->mem_type) && (new_mem->start < old_mem->start + old_mem->size)) { dir = -1; add = new_mem->num_pages - 1; } for (i = 0; i < new_mem->num_pages; ++i) { page = i * dir + add; if (old_iomap == NULL) { vm_memattr_t prot = ttm_io_prot(old_mem->placement); ret = ttm_copy_ttm_io_page(ttm, new_iomap, page, prot); } else if (new_iomap == NULL) { vm_memattr_t prot = ttm_io_prot(new_mem->placement); ret = ttm_copy_io_ttm_page(ttm, old_iomap, page, prot); } else ret = ttm_copy_io_page(new_iomap, old_iomap, page); if (ret) { /* failing here, means keep old copy as-is */ old_copy.mm_node = NULL; goto out1; } } mb(); out2: old_copy = *old_mem; *old_mem = *new_mem; new_mem->mm_node = NULL; if ((man->flags & TTM_MEMTYPE_FLAG_FIXED) && (ttm != NULL)) { ttm_tt_unbind(ttm); ttm_tt_destroy(ttm); bo->ttm = NULL; } out1: ttm_mem_reg_iounmap(bdev, old_mem, new_iomap); out: ttm_mem_reg_iounmap(bdev, &old_copy, old_iomap); ttm_bo_mem_put(bo, &old_copy); return ret; } MALLOC_DEFINE(M_TTM_TRANSF_OBJ, "ttm_transf_obj", "TTM Transfer Objects"); static void ttm_transfered_destroy(struct ttm_buffer_object *bo) { free(bo, M_TTM_TRANSF_OBJ); } /** * ttm_buffer_object_transfer * * @bo: A pointer to a struct ttm_buffer_object. * @new_obj: A pointer to a pointer to a newly created ttm_buffer_object, * holding the data of @bo with the old placement. * * This is a utility function that may be called after an accelerated move * has been scheduled. A new buffer object is created as a placeholder for * the old data while it's being copied. When that buffer object is idle, * it can be destroyed, releasing the space of the old placement. * Returns: * !0: Failure. */ static int ttm_buffer_object_transfer(struct ttm_buffer_object *bo, struct ttm_buffer_object **new_obj) { struct ttm_buffer_object *fbo; struct ttm_bo_device *bdev = bo->bdev; struct ttm_bo_driver *driver = bdev->driver; fbo = malloc(sizeof(*fbo), M_TTM_TRANSF_OBJ, M_WAITOK); *fbo = *bo; /** * Fix up members that we shouldn't copy directly: * TODO: Explicit member copy would probably be better here. */ INIT_LIST_HEAD(&fbo->ddestroy); INIT_LIST_HEAD(&fbo->lru); INIT_LIST_HEAD(&fbo->swap); INIT_LIST_HEAD(&fbo->io_reserve_lru); fbo->vm_node = NULL; atomic_set(&fbo->cpu_writers, 0); mtx_lock(&bdev->fence_lock); if (bo->sync_obj) fbo->sync_obj = driver->sync_obj_ref(bo->sync_obj); else fbo->sync_obj = NULL; mtx_unlock(&bdev->fence_lock); refcount_init(&fbo->list_kref, 1); refcount_init(&fbo->kref, 1); fbo->destroy = &ttm_transfered_destroy; fbo->acc_size = 0; *new_obj = fbo; return 0; } vm_memattr_t ttm_io_prot(uint32_t caching_flags) { #if defined(__i386__) || defined(__amd64__) if (caching_flags & TTM_PL_FLAG_WC) return (VM_MEMATTR_WRITE_COMBINING); else /* * We do not support i386, look at the linux source * for the reason of the comment. */ return (VM_MEMATTR_UNCACHEABLE); #else #error Port me #endif } static int ttm_bo_ioremap(struct ttm_buffer_object *bo, unsigned long offset, unsigned long size, struct ttm_bo_kmap_obj *map) { struct ttm_mem_reg *mem = &bo->mem; if (bo->mem.bus.addr) { map->bo_kmap_type = ttm_bo_map_premapped; map->virtual = (void *)(((u8 *)bo->mem.bus.addr) + offset); } else { map->bo_kmap_type = ttm_bo_map_iomap; map->virtual = pmap_mapdev_attr(bo->mem.bus.base + bo->mem.bus.offset + offset, size, (mem->placement & TTM_PL_FLAG_WC) ? VM_MEMATTR_WRITE_COMBINING : VM_MEMATTR_UNCACHEABLE); map->size = size; } return (!map->virtual) ? -ENOMEM : 0; } static int ttm_bo_kmap_ttm(struct ttm_buffer_object *bo, unsigned long start_page, unsigned long num_pages, struct ttm_bo_kmap_obj *map) { struct ttm_mem_reg *mem = &bo->mem; vm_memattr_t prot; struct ttm_tt *ttm = bo->ttm; int i, ret; MPASS(ttm != NULL); if (ttm->state == tt_unpopulated) { ret = ttm->bdev->driver->ttm_tt_populate(ttm); if (ret) return ret; } if (num_pages == 1 && (mem->placement & TTM_PL_FLAG_CACHED)) { /* * We're mapping a single page, and the desired * page protection is consistent with the bo. */ map->bo_kmap_type = ttm_bo_map_kmap; map->page = ttm->pages[start_page]; map->sf = sf_buf_alloc(map->page, 0); map->virtual = (void *)sf_buf_kva(map->sf); } else { /* * We need to use vmap to get the desired page protection * or to make the buffer object look contiguous. */ prot = (mem->placement & TTM_PL_FLAG_CACHED) ? VM_MEMATTR_WRITE_COMBINING : ttm_io_prot(mem->placement); map->bo_kmap_type = ttm_bo_map_vmap; map->num_pages = num_pages; map->virtual = (void *)kva_alloc(num_pages * PAGE_SIZE); if (map->virtual != NULL) { for (i = 0; i < num_pages; i++) { /* XXXKIB hack */ pmap_page_set_memattr(ttm->pages[start_page + i], prot); } pmap_qenter((vm_offset_t)map->virtual, &ttm->pages[start_page], num_pages); } } return (!map->virtual) ? -ENOMEM : 0; } int ttm_bo_kmap(struct ttm_buffer_object *bo, unsigned long start_page, unsigned long num_pages, struct ttm_bo_kmap_obj *map) { struct ttm_mem_type_manager *man = &bo->bdev->man[bo->mem.mem_type]; unsigned long offset, size; int ret; MPASS(list_empty(&bo->swap)); map->virtual = NULL; map->bo = bo; if (num_pages > bo->num_pages) return -EINVAL; if (start_page > bo->num_pages) return -EINVAL; #if 0 if (num_pages > 1 && !DRM_SUSER(DRM_CURPROC)) return -EPERM; #endif (void) ttm_mem_io_lock(man, false); ret = ttm_mem_io_reserve(bo->bdev, &bo->mem); ttm_mem_io_unlock(man); if (ret) return ret; if (!bo->mem.bus.is_iomem) { return ttm_bo_kmap_ttm(bo, start_page, num_pages, map); } else { offset = start_page << PAGE_SHIFT; size = num_pages << PAGE_SHIFT; return ttm_bo_ioremap(bo, offset, size, map); } } void ttm_bo_kunmap(struct ttm_bo_kmap_obj *map) { struct ttm_buffer_object *bo = map->bo; struct ttm_mem_type_manager *man = &bo->bdev->man[bo->mem.mem_type]; if (!map->virtual) return; switch (map->bo_kmap_type) { case ttm_bo_map_iomap: pmap_unmapdev((vm_offset_t)map->virtual, map->size); break; case ttm_bo_map_vmap: pmap_qremove((vm_offset_t)(map->virtual), map->num_pages); kva_free((vm_offset_t)map->virtual, map->num_pages * PAGE_SIZE); break; case ttm_bo_map_kmap: sf_buf_free(map->sf); break; case ttm_bo_map_premapped: break; default: MPASS(0); } (void) ttm_mem_io_lock(man, false); ttm_mem_io_free(map->bo->bdev, &map->bo->mem); ttm_mem_io_unlock(man); map->virtual = NULL; map->page = NULL; map->sf = NULL; } int ttm_bo_move_accel_cleanup(struct ttm_buffer_object *bo, void *sync_obj, bool evict, bool no_wait_gpu, struct ttm_mem_reg *new_mem) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_bo_driver *driver = bdev->driver; struct ttm_mem_type_manager *man = &bdev->man[new_mem->mem_type]; struct ttm_mem_reg *old_mem = &bo->mem; int ret; struct ttm_buffer_object *ghost_obj; void *tmp_obj = NULL; mtx_lock(&bdev->fence_lock); if (bo->sync_obj) { tmp_obj = bo->sync_obj; bo->sync_obj = NULL; } bo->sync_obj = driver->sync_obj_ref(sync_obj); if (evict) { ret = ttm_bo_wait(bo, false, false, false); mtx_unlock(&bdev->fence_lock); if (tmp_obj) driver->sync_obj_unref(&tmp_obj); if (ret) return ret; if ((man->flags & TTM_MEMTYPE_FLAG_FIXED) && (bo->ttm != NULL)) { ttm_tt_unbind(bo->ttm); ttm_tt_destroy(bo->ttm); bo->ttm = NULL; } ttm_bo_free_old_node(bo); } else { /** * This should help pipeline ordinary buffer moves. * * Hang old buffer memory on a new buffer object, * and leave it to be released when the GPU * operation has completed. */ - set_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags); + atomic_set_long(&bo->priv_flags, + 1UL << TTM_BO_PRIV_FLAG_MOVING); mtx_unlock(&bdev->fence_lock); if (tmp_obj) driver->sync_obj_unref(&tmp_obj); ret = ttm_buffer_object_transfer(bo, &ghost_obj); if (ret) return ret; /** * If we're not moving to fixed memory, the TTM object * needs to stay alive. Otherwhise hang it on the ghost * bo to be unbound and destroyed. */ if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) ghost_obj->ttm = NULL; else bo->ttm = NULL; ttm_bo_unreserve(ghost_obj); ttm_bo_unref(&ghost_obj); } *old_mem = *new_mem; new_mem->mm_node = NULL; return 0; } Index: head/sys/dev/drm2/ttm/ttm_bo_vm.c =================================================================== --- head/sys/dev/drm2/ttm/ttm_bo_vm.c (revision 254879) +++ head/sys/dev/drm2/ttm/ttm_bo_vm.c (revision 254880) @@ -1,559 +1,560 @@ /************************************************************************** * * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA * 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, sub license, 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 NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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. * **************************************************************************/ /* * Authors: Thomas Hellstrom */ /* * Copyright (c) 2013 The FreeBSD Foundation * All rights reserved. * * Portions of this software were developed by Konstantin Belousov * under sponsorship from the FreeBSD Foundation. */ #include __FBSDID("$FreeBSD$"); #include "opt_vm.h" #include #include #include #include #include #include #include #define TTM_BO_VM_NUM_PREFAULT 16 RB_GENERATE(ttm_bo_device_buffer_objects, ttm_buffer_object, vm_rb, ttm_bo_cmp_rb_tree_items); int ttm_bo_cmp_rb_tree_items(struct ttm_buffer_object *a, struct ttm_buffer_object *b) { if (a->vm_node->start < b->vm_node->start) { return (-1); } else if (a->vm_node->start > b->vm_node->start) { return (1); } else { return (0); } } static struct ttm_buffer_object *ttm_bo_vm_lookup_rb(struct ttm_bo_device *bdev, unsigned long page_start, unsigned long num_pages) { unsigned long cur_offset; struct ttm_buffer_object *bo; struct ttm_buffer_object *best_bo = NULL; RB_FOREACH(bo, ttm_bo_device_buffer_objects, &bdev->addr_space_rb) { cur_offset = bo->vm_node->start; if (page_start >= cur_offset) { best_bo = bo; if (page_start == cur_offset) break; } } if (unlikely(best_bo == NULL)) return NULL; if (unlikely((best_bo->vm_node->start + best_bo->num_pages) < (page_start + num_pages))) return NULL; return best_bo; } static int ttm_bo_vm_fault(vm_object_t vm_obj, vm_ooffset_t offset, int prot, vm_page_t *mres) { struct ttm_buffer_object *bo = vm_obj->handle; struct ttm_bo_device *bdev = bo->bdev; struct ttm_tt *ttm = NULL; vm_page_t m, m1, oldm; int ret; int retval = VM_PAGER_OK; struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type]; vm_object_pip_add(vm_obj, 1); oldm = *mres; if (oldm != NULL) { vm_page_lock(oldm); vm_page_remove(oldm); vm_page_unlock(oldm); *mres = NULL; } else oldm = NULL; retry: VM_OBJECT_WUNLOCK(vm_obj); m = NULL; reserve: ret = ttm_bo_reserve(bo, false, false, false, 0); if (unlikely(ret != 0)) { if (ret == -EBUSY) { kern_yield(0); goto reserve; } } if (bdev->driver->fault_reserve_notify) { ret = bdev->driver->fault_reserve_notify(bo); switch (ret) { case 0: break; case -EBUSY: case -ERESTART: case -EINTR: kern_yield(0); goto reserve; default: retval = VM_PAGER_ERROR; goto out_unlock; } } /* * Wait for buffer data in transit, due to a pipelined * move. */ mtx_lock(&bdev->fence_lock); - if (test_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags)) { + if ((atomic_load_acq_long(&bo->priv_flags) & + (1UL << TTM_BO_PRIV_FLAG_MOVING)) != 0) { /* * Here, the behavior differs between Linux and FreeBSD. * * On Linux, the wait is interruptible (3rd argument to * ttm_bo_wait). There must be some mechanism to resume * page fault handling, once the signal is processed. * * On FreeBSD, the wait is uninteruptible. This is not a * problem as we can't end up with an unkillable process * here, because the wait will eventually time out. * * An example of this situation is the Xorg process * which uses SIGALRM internally. The signal could * interrupt the wait, causing the page fault to fail * and the process to receive SIGSEGV. */ ret = ttm_bo_wait(bo, false, false, false); mtx_unlock(&bdev->fence_lock); if (unlikely(ret != 0)) { retval = VM_PAGER_ERROR; goto out_unlock; } } else mtx_unlock(&bdev->fence_lock); ret = ttm_mem_io_lock(man, true); if (unlikely(ret != 0)) { retval = VM_PAGER_ERROR; goto out_unlock; } ret = ttm_mem_io_reserve_vm(bo); if (unlikely(ret != 0)) { retval = VM_PAGER_ERROR; goto out_io_unlock; } /* * Strictly, we're not allowed to modify vma->vm_page_prot here, * since the mmap_sem is only held in read mode. However, we * modify only the caching bits of vma->vm_page_prot and * consider those bits protected by * the bo->mutex, as we should be the only writers. * There shouldn't really be any readers of these bits except * within vm_insert_mixed()? fork? * * TODO: Add a list of vmas to the bo, and change the * vma->vm_page_prot when the object changes caching policy, with * the correct locks held. */ if (!bo->mem.bus.is_iomem) { /* Allocate all page at once, most common usage */ ttm = bo->ttm; if (ttm->bdev->driver->ttm_tt_populate(ttm)) { retval = VM_PAGER_ERROR; goto out_io_unlock; } } if (bo->mem.bus.is_iomem) { m = vm_phys_fictitious_to_vm_page(bo->mem.bus.base + bo->mem.bus.offset + offset); pmap_page_set_memattr(m, ttm_io_prot(bo->mem.placement)); } else { ttm = bo->ttm; m = ttm->pages[OFF_TO_IDX(offset)]; if (unlikely(!m)) { retval = VM_PAGER_ERROR; goto out_io_unlock; } pmap_page_set_memattr(m, (bo->mem.placement & TTM_PL_FLAG_CACHED) ? VM_MEMATTR_WRITE_BACK : ttm_io_prot(bo->mem.placement)); } VM_OBJECT_WLOCK(vm_obj); if (vm_page_busied(m)) { vm_page_lock(m); VM_OBJECT_WUNLOCK(vm_obj); vm_page_busy_sleep(m, "ttmpbs"); VM_OBJECT_WLOCK(vm_obj); ttm_mem_io_unlock(man); ttm_bo_unreserve(bo); goto retry; } m1 = vm_page_lookup(vm_obj, OFF_TO_IDX(offset)); if (m1 == NULL) { if (vm_page_insert(m, vm_obj, OFF_TO_IDX(offset))) { VM_OBJECT_WUNLOCK(vm_obj); VM_WAIT; VM_OBJECT_WLOCK(vm_obj); ttm_mem_io_unlock(man); ttm_bo_unreserve(bo); goto retry; } } else { KASSERT(m == m1, ("inconsistent insert bo %p m %p m1 %p offset %jx", bo, m, m1, (uintmax_t)offset)); } m->valid = VM_PAGE_BITS_ALL; *mres = m; vm_page_xbusy(m); if (oldm != NULL) { vm_page_lock(oldm); vm_page_free(oldm); vm_page_unlock(oldm); } out_io_unlock1: ttm_mem_io_unlock(man); out_unlock1: ttm_bo_unreserve(bo); vm_object_pip_wakeup(vm_obj); return (retval); out_io_unlock: VM_OBJECT_WLOCK(vm_obj); goto out_io_unlock1; out_unlock: VM_OBJECT_WLOCK(vm_obj); goto out_unlock1; } static int ttm_bo_vm_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot, vm_ooffset_t foff, struct ucred *cred, u_short *color) { /* * On Linux, a reference to the buffer object is acquired here. * The reason is that this function is not called when the * mmap() is initialized, but only when a process forks for * instance. Therefore on Linux, the reference on the bo is * acquired either in ttm_bo_mmap() or ttm_bo_vm_open(). It's * then released in ttm_bo_vm_close(). * * Here, this function is called during mmap() intialization. * Thus, the reference acquired in ttm_bo_mmap_single() is * sufficient. */ *color = 0; return (0); } static void ttm_bo_vm_dtor(void *handle) { struct ttm_buffer_object *bo = handle; ttm_bo_unref(&bo); } static struct cdev_pager_ops ttm_pager_ops = { .cdev_pg_fault = ttm_bo_vm_fault, .cdev_pg_ctor = ttm_bo_vm_ctor, .cdev_pg_dtor = ttm_bo_vm_dtor }; int ttm_bo_mmap_single(struct ttm_bo_device *bdev, vm_ooffset_t *offset, vm_size_t size, struct vm_object **obj_res, int nprot) { struct ttm_bo_driver *driver; struct ttm_buffer_object *bo; struct vm_object *vm_obj; int ret; rw_wlock(&bdev->vm_lock); bo = ttm_bo_vm_lookup_rb(bdev, OFF_TO_IDX(*offset), OFF_TO_IDX(size)); if (likely(bo != NULL)) refcount_acquire(&bo->kref); rw_wunlock(&bdev->vm_lock); if (unlikely(bo == NULL)) { printf("[TTM] Could not find buffer object to map\n"); return (EINVAL); } driver = bo->bdev->driver; if (unlikely(!driver->verify_access)) { ret = EPERM; goto out_unref; } ret = -driver->verify_access(bo); if (unlikely(ret != 0)) goto out_unref; vm_obj = cdev_pager_allocate(bo, OBJT_MGTDEVICE, &ttm_pager_ops, size, nprot, 0, curthread->td_ucred); if (vm_obj == NULL) { ret = EINVAL; goto out_unref; } /* * Note: We're transferring the bo reference to vm_obj->handle here. */ *offset = 0; *obj_res = vm_obj; return 0; out_unref: ttm_bo_unref(&bo); return ret; } void ttm_bo_release_mmap(struct ttm_buffer_object *bo) { vm_object_t vm_obj; vm_page_t m; int i; vm_obj = cdev_pager_lookup(bo); if (vm_obj == NULL) return; VM_OBJECT_WLOCK(vm_obj); retry: for (i = 0; i < bo->num_pages; i++) { m = vm_page_lookup(vm_obj, i); if (m == NULL) continue; if (vm_page_sleep_if_busy(m, "ttm_unm")) goto retry; cdev_pager_free_page(vm_obj, m); } VM_OBJECT_WUNLOCK(vm_obj); vm_object_deallocate(vm_obj); } #if 0 int ttm_fbdev_mmap(struct vm_area_struct *vma, struct ttm_buffer_object *bo) { if (vma->vm_pgoff != 0) return -EACCES; vma->vm_ops = &ttm_bo_vm_ops; vma->vm_private_data = ttm_bo_reference(bo); vma->vm_flags |= VM_IO | VM_MIXEDMAP | VM_DONTEXPAND; return 0; } ssize_t ttm_bo_io(struct ttm_bo_device *bdev, struct file *filp, const char __user *wbuf, char __user *rbuf, size_t count, loff_t *f_pos, bool write) { struct ttm_buffer_object *bo; struct ttm_bo_driver *driver; struct ttm_bo_kmap_obj map; unsigned long dev_offset = (*f_pos >> PAGE_SHIFT); unsigned long kmap_offset; unsigned long kmap_end; unsigned long kmap_num; size_t io_size; unsigned int page_offset; char *virtual; int ret; bool no_wait = false; bool dummy; read_lock(&bdev->vm_lock); bo = ttm_bo_vm_lookup_rb(bdev, dev_offset, 1); if (likely(bo != NULL)) ttm_bo_reference(bo); read_unlock(&bdev->vm_lock); if (unlikely(bo == NULL)) return -EFAULT; driver = bo->bdev->driver; if (unlikely(!driver->verify_access)) { ret = -EPERM; goto out_unref; } ret = driver->verify_access(bo, filp); if (unlikely(ret != 0)) goto out_unref; kmap_offset = dev_offset - bo->vm_node->start; if (unlikely(kmap_offset >= bo->num_pages)) { ret = -EFBIG; goto out_unref; } page_offset = *f_pos & ~PAGE_MASK; io_size = bo->num_pages - kmap_offset; io_size = (io_size << PAGE_SHIFT) - page_offset; if (count < io_size) io_size = count; kmap_end = (*f_pos + count - 1) >> PAGE_SHIFT; kmap_num = kmap_end - kmap_offset + 1; ret = ttm_bo_reserve(bo, true, no_wait, false, 0); switch (ret) { case 0: break; case -EBUSY: ret = -EAGAIN; goto out_unref; default: goto out_unref; } ret = ttm_bo_kmap(bo, kmap_offset, kmap_num, &map); if (unlikely(ret != 0)) { ttm_bo_unreserve(bo); goto out_unref; } virtual = ttm_kmap_obj_virtual(&map, &dummy); virtual += page_offset; if (write) ret = copy_from_user(virtual, wbuf, io_size); else ret = copy_to_user(rbuf, virtual, io_size); ttm_bo_kunmap(&map); ttm_bo_unreserve(bo); ttm_bo_unref(&bo); if (unlikely(ret != 0)) return -EFBIG; *f_pos += io_size; return io_size; out_unref: ttm_bo_unref(&bo); return ret; } ssize_t ttm_bo_fbdev_io(struct ttm_buffer_object *bo, const char __user *wbuf, char __user *rbuf, size_t count, loff_t *f_pos, bool write) { struct ttm_bo_kmap_obj map; unsigned long kmap_offset; unsigned long kmap_end; unsigned long kmap_num; size_t io_size; unsigned int page_offset; char *virtual; int ret; bool no_wait = false; bool dummy; kmap_offset = (*f_pos >> PAGE_SHIFT); if (unlikely(kmap_offset >= bo->num_pages)) return -EFBIG; page_offset = *f_pos & ~PAGE_MASK; io_size = bo->num_pages - kmap_offset; io_size = (io_size << PAGE_SHIFT) - page_offset; if (count < io_size) io_size = count; kmap_end = (*f_pos + count - 1) >> PAGE_SHIFT; kmap_num = kmap_end - kmap_offset + 1; ret = ttm_bo_reserve(bo, true, no_wait, false, 0); switch (ret) { case 0: break; case -EBUSY: return -EAGAIN; default: return ret; } ret = ttm_bo_kmap(bo, kmap_offset, kmap_num, &map); if (unlikely(ret != 0)) { ttm_bo_unreserve(bo); return ret; } virtual = ttm_kmap_obj_virtual(&map, &dummy); virtual += page_offset; if (write) ret = copy_from_user(virtual, wbuf, io_size); else ret = copy_to_user(rbuf, virtual, io_size); ttm_bo_kunmap(&map); ttm_bo_unreserve(bo); ttm_bo_unref(&bo); if (unlikely(ret != 0)) return ret; *f_pos += io_size; return io_size; } #endif