+/**
+ * Start using the specified surface for this buffer resource.
+ */
+void
+svga_buffer_bind_host_surface(struct svga_context *svga,
+ struct svga_buffer *sbuf,
+ struct svga_buffer_surface *bufsurf)
+{
+ /* Update the to-bind surface */
+ assert(bufsurf->handle);
+ assert(sbuf->handle);
+
+ /* If we are switching from stream output to other buffer,
+ * make sure to copy the buffer content.
+ */
+ if (sbuf->bind_flags & PIPE_BIND_STREAM_OUTPUT) {
+ SVGA_RETRY(svga, SVGA3D_vgpu10_BufferCopy(svga->swc, sbuf->handle,
+ bufsurf->handle,
+ 0, 0, sbuf->b.b.width0));
+ }
+
+ /* Set this surface as the current one */
+ sbuf->handle = bufsurf->handle;
+ sbuf->key = bufsurf->key;
+ sbuf->bind_flags = bufsurf->bind_flags;
+}
+
+
+/**
+ * Prepare a host surface that can be used as indicated in the
+ * tobind_flags. If the existing host surface is not created
+ * with the necessary binding flags and if the new bind flags can be
+ * combined with the existing bind flags, then we will recreate a
+ * new surface with the combined bind flags. Otherwise, we will create
+ * a surface for that incompatible bind flags.
+ * For example, if a stream output buffer is reused as a constant buffer,
+ * since constant buffer surface cannot be bound as a stream output surface,
+ * two surfaces will be created, one for stream output,
+ * and another one for constant buffer.
+ */
+enum pipe_error
+svga_buffer_validate_host_surface(struct svga_context *svga,
+ struct svga_buffer *sbuf,
+ unsigned tobind_flags)
+{
+ struct svga_buffer_surface *bufsurf;
+ enum pipe_error ret = PIPE_OK;
+
+ /* Flush any pending upload first */
+ svga_buffer_upload_flush(svga, sbuf);
+
+ /* First check from the cached buffer surface list to see if there is
+ * already a buffer surface that has the requested bind flags, or
+ * surface with compatible bind flags that can be promoted.
+ */
+ bufsurf = svga_buffer_get_host_surface(sbuf, tobind_flags);
+
+ if (bufsurf) {
+ if ((bufsurf->bind_flags & tobind_flags) == tobind_flags) {
+ /* there is a surface with the requested bind flags */
+ svga_buffer_bind_host_surface(svga, sbuf, bufsurf);
+ } else {
+
+ /* Recreate a host surface with the combined bind flags */
+ ret = svga_buffer_recreate_host_surface(svga, sbuf,
+ bufsurf->bind_flags |
+ tobind_flags);
+
+ /* Destroy the old surface */
+ svga_screen_surface_destroy(svga_screen(sbuf->b.b.screen),
+ &bufsurf->key, &bufsurf->handle);
+
+ list_del(&bufsurf->list);
+ FREE(bufsurf);
+ }
+ } else {
+ /* Need to create a new surface if the bind flags are incompatible,
+ * such as constant buffer surface & stream output surface.
+ */
+ ret = svga_buffer_recreate_host_surface(svga, sbuf,
+ tobind_flags);
+ }
+ return ret;
+}
+
+