diff mbox series

RFC: dma-buf: Add an API for importing and exporting sync files

Message ID 20200225235856.975366-1-jason@jlekstrand.net (mailing list archive)
State New, archived
Headers show
Series RFC: dma-buf: Add an API for importing and exporting sync files | expand

Commit Message

Jason Ekstrand Feb. 25, 2020, 11:58 p.m. UTC
Explicit synchronization is the future.  At least, that seems to be what
most userspace APIs are agreeing on at this point.  However, most of our
Linux APIs (both userspace and kernel UAPI) are currently built around
implicit synchronization with dma-buf.  While work is ongoing to change
many of the userspace APIs and protocols to an explicit synchronization
model, switching over piecemeal is difficult due to the number of
potential components involved.  On the kernel side, many drivers use
dma-buf including GPU (3D/compute), display, v4l, and others.  In
userspace, we have X11, several Wayland compositors, 3D drivers, compute
drivers (OpenCL etc.), media encode/decode, and the list goes on.

This patch provides a path forward by allowing userspace to manually
manage the fences attached to a dma-buf.  Alternatively, one can think
of this as making dma-buf's implicit synchronization simply a carrier
for an explicit fence.  This is accomplished by adding two IOCTLs to
dma-buf for importing and exporting a sync file to/from the dma-buf.
This way a userspace component which is uses explicit synchronization,
such as a Vulkan driver, can manually set the write fence on a buffer
before handing it off to an implicitly synchronized component such as a
Wayland compositor or video encoder.  In this way, each of the different
components can be upgraded to an explicit synchronization model one at a
time as long as the userspace pieces connecting them are aware of it and
import/export fences at the right times.

There is a potential race condition with this API if userspace is not
careful.  A typical use case for implicit synchronization is to wait for
the dma-buf to be ready, use it, and then signal it for some other
component.  Because a sync_file cannot be created until it is guaranteed
to complete in finite time, userspace can only signal the dma-buf after
it has already submitted the work which uses it to the kernel and has
received a sync_file back.  There is no way to atomically submit a
wait-use-signal operation.  This is not, however, really a problem with
this API so much as it is a problem with explicit synchronization
itself.  The way this is typically handled is to have very explicit
ownership transfer points in the API or protocol which ensure that only
one component is using it at any given time.  Both X11 (via the PRESENT
extension) and Wayland provide such ownership transfer points via
explicit present and idle messages.

The decision was intentionally made in this patch to make the import and
export operations IOCTLs on the dma-buf itself rather than as a DRM
IOCTL.  This makes it the import/export operation universal across all
components which use dma-buf including GPU, display, v4l, and others.
It also means that a userspace component can do the import/export
without access to the DRM fd which may be tricky to get in cases where
the client communicates with DRM via a userspace API such as OpenGL or
Vulkan.  At a future date we may choose to add direct import/export APIs
to components such as drm_syncobj to avoid allocating a file descriptor
and going through two ioctls.  However, that seems to be something of a
micro-optimization as import/export operations are likely to happen at a
rate of a few per frame of rendered or decoded video.

Signed-off-by: Jason Ekstrand <jason@jlekstrand.net>
---

This is marked as an RFC because I intend it to start a discussion about
how to solve a problem.  The current patch compiles but that's it for now.
I'll be writing IGT tests and Vulkan driver patches which exercise it over
the next couple of days.  In the mean time, feel free to tell me why you
think this is a great and/or terrible idea. :-)

--Jason


 drivers/dma-buf/dma-buf.c    | 115 +++++++++++++++++++++++++++++++++++
 include/uapi/linux/dma-buf.h |  13 +++-
 2 files changed, 126 insertions(+), 2 deletions(-)

Comments

Christian König Feb. 26, 2020, 9:16 a.m. UTC | #1
Hi Jason,

Am 26.02.20 um 00:58 schrieb Jason Ekstrand:
> Explicit synchronization is the future.  At least, that seems to be what
> most userspace APIs are agreeing on at this point.  However, most of our
> Linux APIs (both userspace and kernel UAPI) are currently built around
> implicit synchronization with dma-buf.  While work is ongoing to change
> many of the userspace APIs and protocols to an explicit synchronization
> model, switching over piecemeal is difficult due to the number of
> potential components involved.  On the kernel side, many drivers use
> dma-buf including GPU (3D/compute), display, v4l, and others.  In
> userspace, we have X11, several Wayland compositors, 3D drivers, compute
> drivers (OpenCL etc.), media encode/decode, and the list goes on.
>
> This patch provides a path forward by allowing userspace to manually
> manage the fences attached to a dma-buf.  Alternatively, one can think
> of this as making dma-buf's implicit synchronization simply a carrier
> for an explicit fence.  This is accomplished by adding two IOCTLs to
> dma-buf for importing and exporting a sync file to/from the dma-buf.
> This way a userspace component which is uses explicit synchronization,
> such as a Vulkan driver, can manually set the write fence on a buffer
> before handing it off to an implicitly synchronized component such as a
> Wayland compositor or video encoder.  In this way, each of the different
> components can be upgraded to an explicit synchronization model one at a
> time as long as the userspace pieces connecting them are aware of it and
> import/export fences at the right times.
>
> There is a potential race condition with this API if userspace is not
> careful.  A typical use case for implicit synchronization is to wait for
> the dma-buf to be ready, use it, and then signal it for some other
> component.  Because a sync_file cannot be created until it is guaranteed
> to complete in finite time, userspace can only signal the dma-buf after
> it has already submitted the work which uses it to the kernel and has
> received a sync_file back.  There is no way to atomically submit a
> wait-use-signal operation.  This is not, however, really a problem with
> this API so much as it is a problem with explicit synchronization
> itself.  The way this is typically handled is to have very explicit
> ownership transfer points in the API or protocol which ensure that only
> one component is using it at any given time.  Both X11 (via the PRESENT
> extension) and Wayland provide such ownership transfer points via
> explicit present and idle messages.
>
> The decision was intentionally made in this patch to make the import and
> export operations IOCTLs on the dma-buf itself rather than as a DRM
> IOCTL.  This makes it the import/export operation universal across all
> components which use dma-buf including GPU, display, v4l, and others.
> It also means that a userspace component can do the import/export
> without access to the DRM fd which may be tricky to get in cases where
> the client communicates with DRM via a userspace API such as OpenGL or
> Vulkan.  At a future date we may choose to add direct import/export APIs
> to components such as drm_syncobj to avoid allocating a file descriptor
> and going through two ioctls.  However, that seems to be something of a
> micro-optimization as import/export operations are likely to happen at a
> rate of a few per frame of rendered or decoded video.
>
> Signed-off-by: Jason Ekstrand <jason@jlekstrand.net>
> ---
>
> This is marked as an RFC because I intend it to start a discussion about
> how to solve a problem.  The current patch compiles but that's it for now.
> I'll be writing IGT tests and Vulkan driver patches which exercise it over
> the next couple of days.  In the mean time, feel free to tell me why you
> think this is a great and/or terrible idea. :-)

For the exporting part I think it is an absolutely great idea because it 
simplifies compatibility with explicit sync quite a bit.

But for the importing part it is a clear NAK at the moment. See we can't 
allow userspace to mess with DMA-buf fences in that way because it rips 
open a security hole you can push an elephant through.

Just imagine that you access some DMA-buf with a shader and that 
operation is presented as a fence on the DMA-bufs reservation object. 
And now you can go ahead and replace that fence and free up the memory.

Tricking the Linux kernel into allocating page tables in that freed 
memory is trivial and that's basically it you can overwrite page tables 
with your shader and gain access to all of system memory :)

What we could do is to always make sure that the added fences will 
complete later than the already existing ones, but that is also rather 
tricky to get right. I wouldn't do that if we don't have a rather big 
use case for this.

Regards,
Christian.

>
> --Jason
[SNIP]
Daniel Vetter Feb. 26, 2020, 10:05 a.m. UTC | #2
On Wed, Feb 26, 2020 at 10:16:05AM +0100, Christian König wrote:
> Hi Jason,
> 
> Am 26.02.20 um 00:58 schrieb Jason Ekstrand:
> > Explicit synchronization is the future.  At least, that seems to be what
> > most userspace APIs are agreeing on at this point.  However, most of our
> > Linux APIs (both userspace and kernel UAPI) are currently built around
> > implicit synchronization with dma-buf.  While work is ongoing to change
> > many of the userspace APIs and protocols to an explicit synchronization
> > model, switching over piecemeal is difficult due to the number of
> > potential components involved.  On the kernel side, many drivers use
> > dma-buf including GPU (3D/compute), display, v4l, and others.  In
> > userspace, we have X11, several Wayland compositors, 3D drivers, compute
> > drivers (OpenCL etc.), media encode/decode, and the list goes on.
> > 
> > This patch provides a path forward by allowing userspace to manually
> > manage the fences attached to a dma-buf.  Alternatively, one can think
> > of this as making dma-buf's implicit synchronization simply a carrier
> > for an explicit fence.  This is accomplished by adding two IOCTLs to
> > dma-buf for importing and exporting a sync file to/from the dma-buf.
> > This way a userspace component which is uses explicit synchronization,
> > such as a Vulkan driver, can manually set the write fence on a buffer
> > before handing it off to an implicitly synchronized component such as a
> > Wayland compositor or video encoder.  In this way, each of the different
> > components can be upgraded to an explicit synchronization model one at a
> > time as long as the userspace pieces connecting them are aware of it and
> > import/export fences at the right times.
> > 
> > There is a potential race condition with this API if userspace is not
> > careful.  A typical use case for implicit synchronization is to wait for
> > the dma-buf to be ready, use it, and then signal it for some other
> > component.  Because a sync_file cannot be created until it is guaranteed
> > to complete in finite time, userspace can only signal the dma-buf after
> > it has already submitted the work which uses it to the kernel and has
> > received a sync_file back.  There is no way to atomically submit a
> > wait-use-signal operation.  This is not, however, really a problem with
> > this API so much as it is a problem with explicit synchronization
> > itself.  The way this is typically handled is to have very explicit
> > ownership transfer points in the API or protocol which ensure that only
> > one component is using it at any given time.  Both X11 (via the PRESENT
> > extension) and Wayland provide such ownership transfer points via
> > explicit present and idle messages.
> > 
> > The decision was intentionally made in this patch to make the import and
> > export operations IOCTLs on the dma-buf itself rather than as a DRM
> > IOCTL.  This makes it the import/export operation universal across all
> > components which use dma-buf including GPU, display, v4l, and others.
> > It also means that a userspace component can do the import/export
> > without access to the DRM fd which may be tricky to get in cases where
> > the client communicates with DRM via a userspace API such as OpenGL or
> > Vulkan.  At a future date we may choose to add direct import/export APIs
> > to components such as drm_syncobj to avoid allocating a file descriptor
> > and going through two ioctls.  However, that seems to be something of a
> > micro-optimization as import/export operations are likely to happen at a
> > rate of a few per frame of rendered or decoded video.
> > 
> > Signed-off-by: Jason Ekstrand <jason@jlekstrand.net>
> > ---
> > 
> > This is marked as an RFC because I intend it to start a discussion about
> > how to solve a problem.  The current patch compiles but that's it for now.
> > I'll be writing IGT tests and Vulkan driver patches which exercise it over
> > the next couple of days.  In the mean time, feel free to tell me why you
> > think this is a great and/or terrible idea. :-)
> 
> For the exporting part I think it is an absolutely great idea because it
> simplifies compatibility with explicit sync quite a bit.
> 
> But for the importing part it is a clear NAK at the moment. See we can't
> allow userspace to mess with DMA-buf fences in that way because it rips open
> a security hole you can push an elephant through.
> 
> Just imagine that you access some DMA-buf with a shader and that operation
> is presented as a fence on the DMA-bufs reservation object. And now you can
> go ahead and replace that fence and free up the memory.
> 
> Tricking the Linux kernel into allocating page tables in that freed memory
> is trivial and that's basically it you can overwrite page tables with your
> shader and gain access to all of system memory :)
> 
> What we could do is to always make sure that the added fences will complete
> later than the already existing ones, but that is also rather tricky to get
> right. I wouldn't do that if we don't have a rather big use case for this.

I think the main use-case for adding a fence is adding a write fence for
vk winsys buffers, which run without any sync at all. So essentially what
we'd do is promote one of the read fences which are already attached to be
the write fence.

But yeah making sure we don't break any of the dma_resv guarantees about
how these fences works is going to be somewhat tricky. Probably can reuse
a big chunk of the fence container work we've done for syncobj timelines,
since they have some of the same issues of having to chain fences to not
break the world.
-Daniel

> 
> Regards,
> Christian.
> 
> > 
> > --Jason
> [SNIP]
Jason Ekstrand Feb. 26, 2020, 3:28 p.m. UTC | #3
On Wed, Feb 26, 2020 at 4:05 AM Daniel Vetter <daniel@ffwll.ch> wrote:
>
> On Wed, Feb 26, 2020 at 10:16:05AM +0100, Christian König wrote:
> > Hi Jason,
> >
> > Am 26.02.20 um 00:58 schrieb Jason Ekstrand:
> > > Explicit synchronization is the future.  At least, that seems to be what
> > > most userspace APIs are agreeing on at this point.  However, most of our
> > > Linux APIs (both userspace and kernel UAPI) are currently built around
> > > implicit synchronization with dma-buf.  While work is ongoing to change
> > > many of the userspace APIs and protocols to an explicit synchronization
> > > model, switching over piecemeal is difficult due to the number of
> > > potential components involved.  On the kernel side, many drivers use
> > > dma-buf including GPU (3D/compute), display, v4l, and others.  In
> > > userspace, we have X11, several Wayland compositors, 3D drivers, compute
> > > drivers (OpenCL etc.), media encode/decode, and the list goes on.
> > >
> > > This patch provides a path forward by allowing userspace to manually
> > > manage the fences attached to a dma-buf.  Alternatively, one can think
> > > of this as making dma-buf's implicit synchronization simply a carrier
> > > for an explicit fence.  This is accomplished by adding two IOCTLs to
> > > dma-buf for importing and exporting a sync file to/from the dma-buf.
> > > This way a userspace component which is uses explicit synchronization,
> > > such as a Vulkan driver, can manually set the write fence on a buffer
> > > before handing it off to an implicitly synchronized component such as a
> > > Wayland compositor or video encoder.  In this way, each of the different
> > > components can be upgraded to an explicit synchronization model one at a
> > > time as long as the userspace pieces connecting them are aware of it and
> > > import/export fences at the right times.
> > >
> > > There is a potential race condition with this API if userspace is not
> > > careful.  A typical use case for implicit synchronization is to wait for
> > > the dma-buf to be ready, use it, and then signal it for some other
> > > component.  Because a sync_file cannot be created until it is guaranteed
> > > to complete in finite time, userspace can only signal the dma-buf after
> > > it has already submitted the work which uses it to the kernel and has
> > > received a sync_file back.  There is no way to atomically submit a
> > > wait-use-signal operation.  This is not, however, really a problem with
> > > this API so much as it is a problem with explicit synchronization
> > > itself.  The way this is typically handled is to have very explicit
> > > ownership transfer points in the API or protocol which ensure that only
> > > one component is using it at any given time.  Both X11 (via the PRESENT
> > > extension) and Wayland provide such ownership transfer points via
> > > explicit present and idle messages.
> > >
> > > The decision was intentionally made in this patch to make the import and
> > > export operations IOCTLs on the dma-buf itself rather than as a DRM
> > > IOCTL.  This makes it the import/export operation universal across all
> > > components which use dma-buf including GPU, display, v4l, and others.
> > > It also means that a userspace component can do the import/export
> > > without access to the DRM fd which may be tricky to get in cases where
> > > the client communicates with DRM via a userspace API such as OpenGL or
> > > Vulkan.  At a future date we may choose to add direct import/export APIs
> > > to components such as drm_syncobj to avoid allocating a file descriptor
> > > and going through two ioctls.  However, that seems to be something of a
> > > micro-optimization as import/export operations are likely to happen at a
> > > rate of a few per frame of rendered or decoded video.
> > >
> > > Signed-off-by: Jason Ekstrand <jason@jlekstrand.net>
> > > ---
> > >
> > > This is marked as an RFC because I intend it to start a discussion about
> > > how to solve a problem.  The current patch compiles but that's it for now.
> > > I'll be writing IGT tests and Vulkan driver patches which exercise it over
> > > the next couple of days.  In the mean time, feel free to tell me why you
> > > think this is a great and/or terrible idea. :-)
> >
> > For the exporting part I think it is an absolutely great idea because it
> > simplifies compatibility with explicit sync quite a bit.

Unfortunately, it only helps half of explicit sync and not the half
that's hard to deal with from Vulkan. :-/

> > But for the importing part it is a clear NAK at the moment. See we can't
> > allow userspace to mess with DMA-buf fences in that way because it rips open
> > a security hole you can push an elephant through.

Oh, sure, I'm 100% sure I did that part wrong.  Why else would I send
the patch but to have someone who actually knows what they're doing
tell me how to do it correctly? :-P

> > Just imagine that you access some DMA-buf with a shader and that operation
> > is presented as a fence on the DMA-bufs reservation object. And now you can
> > go ahead and replace that fence and free up the memory.
> >
> > Tricking the Linux kernel into allocating page tables in that freed memory
> > is trivial and that's basically it you can overwrite page tables with your
> > shader and gain access to all of system memory :)
> >
> > What we could do is to always make sure that the added fences will complete
> > later than the already existing ones, but that is also rather tricky to get
> > right. I wouldn't do that if we don't have a rather big use case for this.

Right.  I thought about that but I'm still learning how dma_resv
works.  It'd be easy enough to make a fence array that contains both
the old fence and the new fence and replace the old fence with that.
What I don't know is the proper way to replace the exclusive fence
safely.  Some sort of atomic_cpxchg loop, perhaps?  I presume there's
some way of doing it properly because DRM drivers are doing it all the
time.

> I think the main use-case for adding a fence is adding a write fence for
> vk winsys buffers, which run without any sync at all. So essentially what
> we'd do is promote one of the read fences which are already attached to be
> the write fence.

Correct.  We're effectively doing an import in ANV today but we're
doing it with a dummy execbuf which claims to write the BO and has a
batch that's just MI_BATCH_BUFFER_END.

> But yeah making sure we don't break any of the dma_resv guarantees about
> how these fences works is going to be somewhat tricky. Probably can reuse
> a big chunk of the fence container work we've done for syncobj timelines,
> since they have some of the same issues of having to chain fences to not
> break the world.

Happy to not break the world.  I just don't know how yet. :-)

--Jason
Bas Nieuwenhuizen Feb. 26, 2020, 4:46 p.m. UTC | #4
On Wed, Feb 26, 2020 at 4:29 PM Jason Ekstrand <jason@jlekstrand.net> wrote:
>
> On Wed, Feb 26, 2020 at 4:05 AM Daniel Vetter <daniel@ffwll.ch> wrote:
> >
> > On Wed, Feb 26, 2020 at 10:16:05AM +0100, Christian König wrote:
> > > Hi Jason,
> > >
> > > Am 26.02.20 um 00:58 schrieb Jason Ekstrand:
> > > > Explicit synchronization is the future.  At least, that seems to be what
> > > > most userspace APIs are agreeing on at this point.  However, most of our
> > > > Linux APIs (both userspace and kernel UAPI) are currently built around
> > > > implicit synchronization with dma-buf.  While work is ongoing to change
> > > > many of the userspace APIs and protocols to an explicit synchronization
> > > > model, switching over piecemeal is difficult due to the number of
> > > > potential components involved.  On the kernel side, many drivers use
> > > > dma-buf including GPU (3D/compute), display, v4l, and others.  In
> > > > userspace, we have X11, several Wayland compositors, 3D drivers, compute
> > > > drivers (OpenCL etc.), media encode/decode, and the list goes on.
> > > >
> > > > This patch provides a path forward by allowing userspace to manually
> > > > manage the fences attached to a dma-buf.  Alternatively, one can think
> > > > of this as making dma-buf's implicit synchronization simply a carrier
> > > > for an explicit fence.  This is accomplished by adding two IOCTLs to
> > > > dma-buf for importing and exporting a sync file to/from the dma-buf.
> > > > This way a userspace component which is uses explicit synchronization,
> > > > such as a Vulkan driver, can manually set the write fence on a buffer
> > > > before handing it off to an implicitly synchronized component such as a
> > > > Wayland compositor or video encoder.  In this way, each of the different
> > > > components can be upgraded to an explicit synchronization model one at a
> > > > time as long as the userspace pieces connecting them are aware of it and
> > > > import/export fences at the right times.
> > > >
> > > > There is a potential race condition with this API if userspace is not
> > > > careful.  A typical use case for implicit synchronization is to wait for
> > > > the dma-buf to be ready, use it, and then signal it for some other
> > > > component.  Because a sync_file cannot be created until it is guaranteed
> > > > to complete in finite time, userspace can only signal the dma-buf after
> > > > it has already submitted the work which uses it to the kernel and has
> > > > received a sync_file back.  There is no way to atomically submit a
> > > > wait-use-signal operation.  This is not, however, really a problem with
> > > > this API so much as it is a problem with explicit synchronization
> > > > itself.  The way this is typically handled is to have very explicit
> > > > ownership transfer points in the API or protocol which ensure that only
> > > > one component is using it at any given time.  Both X11 (via the PRESENT
> > > > extension) and Wayland provide such ownership transfer points via
> > > > explicit present and idle messages.
> > > >
> > > > The decision was intentionally made in this patch to make the import and
> > > > export operations IOCTLs on the dma-buf itself rather than as a DRM
> > > > IOCTL.  This makes it the import/export operation universal across all
> > > > components which use dma-buf including GPU, display, v4l, and others.
> > > > It also means that a userspace component can do the import/export
> > > > without access to the DRM fd which may be tricky to get in cases where
> > > > the client communicates with DRM via a userspace API such as OpenGL or
> > > > Vulkan.  At a future date we may choose to add direct import/export APIs
> > > > to components such as drm_syncobj to avoid allocating a file descriptor
> > > > and going through two ioctls.  However, that seems to be something of a
> > > > micro-optimization as import/export operations are likely to happen at a
> > > > rate of a few per frame of rendered or decoded video.
> > > >
> > > > Signed-off-by: Jason Ekstrand <jason@jlekstrand.net>
> > > > ---
> > > >
> > > > This is marked as an RFC because I intend it to start a discussion about
> > > > how to solve a problem.  The current patch compiles but that's it for now.
> > > > I'll be writing IGT tests and Vulkan driver patches which exercise it over
> > > > the next couple of days.  In the mean time, feel free to tell me why you
> > > > think this is a great and/or terrible idea. :-)
> > >
> > > For the exporting part I think it is an absolutely great idea because it
> > > simplifies compatibility with explicit sync quite a bit.
>
> Unfortunately, it only helps half of explicit sync and not the half
> that's hard to deal with from Vulkan. :-/
>
> > > But for the importing part it is a clear NAK at the moment. See we can't
> > > allow userspace to mess with DMA-buf fences in that way because it rips open
> > > a security hole you can push an elephant through.
>
> Oh, sure, I'm 100% sure I did that part wrong.  Why else would I send
> the patch but to have someone who actually knows what they're doing
> tell me how to do it correctly? :-P
>
> > > Just imagine that you access some DMA-buf with a shader and that operation
> > > is presented as a fence on the DMA-bufs reservation object. And now you can
> > > go ahead and replace that fence and free up the memory.
> > >
> > > Tricking the Linux kernel into allocating page tables in that freed memory
> > > is trivial and that's basically it you can overwrite page tables with your
> > > shader and gain access to all of system memory :)
> > >
> > > What we could do is to always make sure that the added fences will complete
> > > later than the already existing ones, but that is also rather tricky to get
> > > right. I wouldn't do that if we don't have a rather big use case for this.
>
> Right.  I thought about that but I'm still learning how dma_resv
> works.  It'd be easy enough to make a fence array that contains both
> the old fence and the new fence and replace the old fence with that.
> What I don't know is the proper way to replace the exclusive fence
> safely.  Some sort of atomic_cpxchg loop, perhaps?  I presume there's
> some way of doing it properly because DRM drivers are doing it all the
> time.

I think for an exclusive fence you may need to create a fence array
that includes the existing exclusive and shared fences in the dma_resv
combined with the added fence.

However, I'm not sure what the best way is to do garbage collection on
that so that we don't get an impossibly list of fence arrays. (Note
the dma_resv has a lock that needs to be taken before adding an
exclusive fence, might be useful). Some code that does a thing like
this is __dma_resv_make_exclusive in
drivers/gpu/drm/amd/amdgpu/amdgpu_dma_buf.c

The other piece of the puzzle is that on the submit path this would
need something to ignore implicit fences. And there semantically the
question comes up whether it is safe for a driver to ignore exclusive
fences from another driver. (and then we have amdgpu which has its own
rules on exclusiveness of its shared fences based on the context. e.g.
the current option to ignore implicit fences for a buffer still syncs
on exclusive fences on the buffer).









>
> > I think the main use-case for adding a fence is adding a write fence for
> > vk winsys buffers, which run without any sync at all. So essentially what
> > we'd do is promote one of the read fences which are already attached to be
> > the write fence.
>
> Correct.  We're effectively doing an import in ANV today but we're
> doing it with a dummy execbuf which claims to write the BO and has a
> batch that's just MI_BATCH_BUFFER_END.
>
> > But yeah making sure we don't break any of the dma_resv guarantees about
> > how these fences works is going to be somewhat tricky. Probably can reuse
> > a big chunk of the fence container work we've done for syncobj timelines,
> > since they have some of the same issues of having to chain fences to not
> > break the world.
>
> Happy to not break the world.  I just don't know how yet. :-)
>
> --Jason
Christian König Feb. 27, 2020, 8:28 a.m. UTC | #5
Am 26.02.20 um 17:46 schrieb Bas Nieuwenhuizen:
> On Wed, Feb 26, 2020 at 4:29 PM Jason Ekstrand <jason@jlekstrand.net> wrote:
>> On Wed, Feb 26, 2020 at 4:05 AM Daniel Vetter <daniel@ffwll.ch> wrote:
>>> On Wed, Feb 26, 2020 at 10:16:05AM +0100, Christian König wrote:
>>> [SNIP]
>>>> Just imagine that you access some DMA-buf with a shader and that operation
>>>> is presented as a fence on the DMA-bufs reservation object. And now you can
>>>> go ahead and replace that fence and free up the memory.
>>>>
>>>> Tricking the Linux kernel into allocating page tables in that freed memory
>>>> is trivial and that's basically it you can overwrite page tables with your
>>>> shader and gain access to all of system memory :)
>>>>
>>>> What we could do is to always make sure that the added fences will complete
>>>> later than the already existing ones, but that is also rather tricky to get
>>>> right. I wouldn't do that if we don't have a rather big use case for this.
>> Right.  I thought about that but I'm still learning how dma_resv
>> works.  It'd be easy enough to make a fence array that contains both
>> the old fence and the new fence and replace the old fence with that.
>> What I don't know is the proper way to replace the exclusive fence
>> safely.  Some sort of atomic_cpxchg loop, perhaps?  I presume there's
>> some way of doing it properly because DRM drivers are doing it all the
>> time.

First of all you need to grab the lock of the dma_resv object or you 
can't replace the exclusive nor the shared ones.

This way you don't need to do a atomic_cmpxchg or anything else and 
still guarantee correct ordering.

> I think for an exclusive fence you may need to create a fence array
> that includes the existing exclusive and shared fences in the dma_resv
> combined with the added fence.

Yes, that at least gives us the correct synchronization.

> However, I'm not sure what the best way is to do garbage collection on
> that so that we don't get an impossibly list of fence arrays.

Exactly yes. That's also the reason why the dma_fence_chain container I 
came up with for the sync timeline stuff has such a rather sophisticated 
garbage collection.

When some of the included fences signal you need to free up the 
array/chain and make sure that the memory for the container can be reused.

>   (Note
> the dma_resv has a lock that needs to be taken before adding an
> exclusive fence, might be useful). Some code that does a thing like
> this is __dma_resv_make_exclusive in
> drivers/gpu/drm/amd/amdgpu/amdgpu_dma_buf.c 

Wanted to move that into dma_resv.c for quite a while since there are 
quite a few other cases where we need this.

Regards,
Christian.

> The other piece of the puzzle is that on the submit path this would
> need something to ignore implicit fences. And there semantically the
> question comes up whether it is safe for a driver to ignore exclusive
> fences from another driver. (and then we have amdgpu which has its own
> rules on exclusiveness of its shared fences based on the context. e.g.
> the current option to ignore implicit fences for a buffer still syncs
> on exclusive fences on the buffer).
Jason Ekstrand March 3, 2020, 7:10 p.m. UTC | #6
On Thu, Feb 27, 2020 at 2:28 AM Christian König
<christian.koenig@amd.com> wrote:
>
> Am 26.02.20 um 17:46 schrieb Bas Nieuwenhuizen:
> > On Wed, Feb 26, 2020 at 4:29 PM Jason Ekstrand <jason@jlekstrand.net> wrote:
> >> On Wed, Feb 26, 2020 at 4:05 AM Daniel Vetter <daniel@ffwll.ch> wrote:
> >>> On Wed, Feb 26, 2020 at 10:16:05AM +0100, Christian König wrote:
> >>> [SNIP]
> >>>> Just imagine that you access some DMA-buf with a shader and that operation
> >>>> is presented as a fence on the DMA-bufs reservation object. And now you can
> >>>> go ahead and replace that fence and free up the memory.
> >>>>
> >>>> Tricking the Linux kernel into allocating page tables in that freed memory
> >>>> is trivial and that's basically it you can overwrite page tables with your
> >>>> shader and gain access to all of system memory :)
> >>>>
> >>>> What we could do is to always make sure that the added fences will complete
> >>>> later than the already existing ones, but that is also rather tricky to get
> >>>> right. I wouldn't do that if we don't have a rather big use case for this.
> >> Right.  I thought about that but I'm still learning how dma_resv
> >> works.  It'd be easy enough to make a fence array that contains both
> >> the old fence and the new fence and replace the old fence with that.
> >> What I don't know is the proper way to replace the exclusive fence
> >> safely.  Some sort of atomic_cpxchg loop, perhaps?  I presume there's
> >> some way of doing it properly because DRM drivers are doing it all the
> >> time.
>
> First of all you need to grab the lock of the dma_resv object or you
> can't replace the exclusive nor the shared ones.
>
> This way you don't need to do a atomic_cmpxchg or anything else and
> still guarantee correct ordering.

Fixed in v3.

> > I think for an exclusive fence you may need to create a fence array
> > that includes the existing exclusive and shared fences in the dma_resv
> > combined with the added fence.
>
> Yes, that at least gives us the correct synchronization.

Fixed in v2

> > However, I'm not sure what the best way is to do garbage collection on
> > that so that we don't get an impossibly list of fence arrays.
>
> Exactly yes. That's also the reason why the dma_fence_chain container I
> came up with for the sync timeline stuff has such a rather sophisticated
> garbage collection.
>
> When some of the included fences signal you need to free up the
> array/chain and make sure that the memory for the container can be reused.

Currently (as of v2), I'm using dma_fence_array and being careful to
not bother constructing one if there's only one fence in play.  Is
this insufficient?  If so, maybe we should consider improving
dma_fence_array.

> >   (Note
> > the dma_resv has a lock that needs to be taken before adding an
> > exclusive fence, might be useful). Some code that does a thing like
> > this is __dma_resv_make_exclusive in
> > drivers/gpu/drm/amd/amdgpu/amdgpu_dma_buf.c
>
> Wanted to move that into dma_resv.c for quite a while since there are
> quite a few other cases where we need this.

I've roughly done that.  The primary difference is that my version
takes an optional additional fence to add to the array.  This makes it
a bit more complicated but I think I got it mostly right.

I've also written userspace code which exercises this and it seems to
work.  Hopefully, that will give a better idea of what I'm trying to
accomplish.

https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/4037

--Jason
Christian König March 4, 2020, 8:34 a.m. UTC | #7
Am 03.03.20 um 20:10 schrieb Jason Ekstrand:
> On Thu, Feb 27, 2020 at 2:28 AM Christian König
> <christian.koenig@amd.com> wrote:
>> [SNIP]
>>> However, I'm not sure what the best way is to do garbage collection on
>>> that so that we don't get an impossibly list of fence arrays.
>> Exactly yes. That's also the reason why the dma_fence_chain container I
>> came up with for the sync timeline stuff has such a rather sophisticated
>> garbage collection.
>>
>> When some of the included fences signal you need to free up the
>> array/chain and make sure that the memory for the container can be reused.
> Currently (as of v2), I'm using dma_fence_array and being careful to
> not bother constructing one if there's only one fence in play.  Is
> this insufficient?  If so, maybe we should consider improving
> dma_fence_array.

That still won't work correctly in all cases. See the problem is not 
only optimization, but also avoiding situations where userspace can 
abuse the interface to do nasty things.

For example if userspace just calls that function in a loop you can 
create a long chain of dma_fence_array objects.

If that chain is then suddenly released the recursive dropping of 
references can overwrite the kernel stack.

For reference see what dance is necessary in the dma_fence_chain_release 
function to avoid that:
>         /* Manually unlink the chain as much as possible to avoid 
> recursion
>          * and potential stack overflow.
>          */
>         while ((prev = rcu_dereference_protected(chain->prev, true))) {
....

It took me quite a while to figure out how to do this without causing 
issues. But I don't see how this would be possible for dma_fence_array.

As far as I can see the only real option to implement this would be to 
change the dma_resv object container so that you can add fences without 
overriding existing ones.

For shared fences that can be done relative easily, but I absolutely 
don't see how to do this for exclusive ones without a larger rework.

>>>    (Note
>>> the dma_resv has a lock that needs to be taken before adding an
>>> exclusive fence, might be useful). Some code that does a thing like
>>> this is __dma_resv_make_exclusive in
>>> drivers/gpu/drm/amd/amdgpu/amdgpu_dma_buf.c
>> Wanted to move that into dma_resv.c for quite a while since there are
>> quite a few other cases where we need this.
> I've roughly done that.  The primary difference is that my version
> takes an optional additional fence to add to the array.  This makes it
> a bit more complicated but I think I got it mostly right.
>
> I've also written userspace code which exercises this and it seems to
> work.  Hopefully, that will give a better idea of what I'm trying to
> accomplish.

Yes, that is indeed a really nice to have feature.

Regards,
Christian.
Jason Ekstrand March 4, 2020, 4:27 p.m. UTC | #8
On Wed, Mar 4, 2020 at 2:34 AM Christian König <christian.koenig@amd.com> wrote:
>
> Am 03.03.20 um 20:10 schrieb Jason Ekstrand:
> > On Thu, Feb 27, 2020 at 2:28 AM Christian König
> > <christian.koenig@amd.com> wrote:
> >> [SNIP]
> >>> However, I'm not sure what the best way is to do garbage collection on
> >>> that so that we don't get an impossibly list of fence arrays.
> >> Exactly yes. That's also the reason why the dma_fence_chain container I
> >> came up with for the sync timeline stuff has such a rather sophisticated
> >> garbage collection.
> >>
> >> When some of the included fences signal you need to free up the
> >> array/chain and make sure that the memory for the container can be reused.
> > Currently (as of v2), I'm using dma_fence_array and being careful to
> > not bother constructing one if there's only one fence in play.  Is
> > this insufficient?  If so, maybe we should consider improving
> > dma_fence_array.
>
> That still won't work correctly in all cases. See the problem is not
> only optimization, but also avoiding situations where userspace can
> abuse the interface to do nasty things.
>
> For example if userspace just calls that function in a loop you can
> create a long chain of dma_fence_array objects.
>
> If that chain is then suddenly released the recursive dropping of
> references can overwrite the kernel stack.
>
> For reference see what dance is necessary in the dma_fence_chain_release
> function to avoid that:
> >         /* Manually unlink the chain as much as possible to avoid
> > recursion
> >          * and potential stack overflow.
> >          */
> >         while ((prev = rcu_dereference_protected(chain->prev, true))) {
> ....
>
> It took me quite a while to figure out how to do this without causing
> issues. But I don't see how this would be possible for dma_fence_array.

Ah, I see the issue now!  It hadn't even occurred to me that userspace
could use this to build up an infinite recursion chain.  That's nasty!
 I'll give this some more thought and see if can come up with
something clever.

Here's one thought:  We could make dma_fence_array automatically
collapse any arrays it references and instead directly reference their
fences.  This way, no matter how much the client chains things, they
will never get more than one dma_fence_array.  Of course, the
difficulty here (answering my own question) comes if they ping-pong
back-and-forth between something which constructs a dma_fence_array
and something which constructs a dma_fence_chain to get
array-of-chain-of-array-of-chain-of-...  More thought needed.

> As far as I can see the only real option to implement this would be to
> change the dma_resv object container so that you can add fences without
> overriding existing ones.
>
> For shared fences that can be done relative easily, but I absolutely
> don't see how to do this for exclusive ones without a larger rework.

Fair enough.  Thanks for taking the time to explain the issue.  I'll
give this some more thought.

--Jason


> >>>    (Note
> >>> the dma_resv has a lock that needs to be taken before adding an
> >>> exclusive fence, might be useful). Some code that does a thing like
> >>> this is __dma_resv_make_exclusive in
> >>> drivers/gpu/drm/amd/amdgpu/amdgpu_dma_buf.c
> >> Wanted to move that into dma_resv.c for quite a while since there are
> >> quite a few other cases where we need this.
> > I've roughly done that.  The primary difference is that my version
> > takes an optional additional fence to add to the array.  This makes it
> > a bit more complicated but I think I got it mostly right.
> >
> > I've also written userspace code which exercises this and it seems to
> > work.  Hopefully, that will give a better idea of what I'm trying to
> > accomplish.
>
> Yes, that is indeed a really nice to have feature.
>
> Regards,
> Christian.
Jason Ekstrand March 4, 2020, 4:41 p.m. UTC | #9
On Wed, Mar 4, 2020 at 10:27 AM Jason Ekstrand <jason@jlekstrand.net> wrote:
>
> On Wed, Mar 4, 2020 at 2:34 AM Christian König <christian.koenig@amd.com> wrote:
> >
> > Am 03.03.20 um 20:10 schrieb Jason Ekstrand:
> > > On Thu, Feb 27, 2020 at 2:28 AM Christian König
> > > <christian.koenig@amd.com> wrote:
> > >> [SNIP]
> > >>> However, I'm not sure what the best way is to do garbage collection on
> > >>> that so that we don't get an impossibly list of fence arrays.
> > >> Exactly yes. That's also the reason why the dma_fence_chain container I
> > >> came up with for the sync timeline stuff has such a rather sophisticated
> > >> garbage collection.
> > >>
> > >> When some of the included fences signal you need to free up the
> > >> array/chain and make sure that the memory for the container can be reused.
> > > Currently (as of v2), I'm using dma_fence_array and being careful to
> > > not bother constructing one if there's only one fence in play.  Is
> > > this insufficient?  If so, maybe we should consider improving
> > > dma_fence_array.
> >
> > That still won't work correctly in all cases. See the problem is not
> > only optimization, but also avoiding situations where userspace can
> > abuse the interface to do nasty things.
> >
> > For example if userspace just calls that function in a loop you can
> > create a long chain of dma_fence_array objects.
> >
> > If that chain is then suddenly released the recursive dropping of
> > references can overwrite the kernel stack.
> >
> > For reference see what dance is necessary in the dma_fence_chain_release
> > function to avoid that:
> > >         /* Manually unlink the chain as much as possible to avoid
> > > recursion
> > >          * and potential stack overflow.
> > >          */
> > >         while ((prev = rcu_dereference_protected(chain->prev, true))) {
> > ....
> >
> > It took me quite a while to figure out how to do this without causing
> > issues. But I don't see how this would be possible for dma_fence_array.
>
> Ah, I see the issue now!  It hadn't even occurred to me that userspace
> could use this to build up an infinite recursion chain.  That's nasty!
>  I'll give this some more thought and see if can come up with
> something clever.
>
> Here's one thought:  We could make dma_fence_array automatically
> collapse any arrays it references and instead directly reference their
> fences.  This way, no matter how much the client chains things, they
> will never get more than one dma_fence_array.  Of course, the
> difficulty here (answering my own question) comes if they ping-pong
> back-and-forth between something which constructs a dma_fence_array
> and something which constructs a dma_fence_chain to get
> array-of-chain-of-array-of-chain-of-...  More thought needed.

Answering my own questions again...  I think the
array-of-chain-of-array case is also solvable.

For array-of-chain, we can simply add all unsignaled dma_fences in the
chain to the array.  The array won't signal until all of them have
which is exactly the same behavior as if we'd added the chain itself.

For chain-of-array, we can add all unsignaled dma_fences in the array
to the same point in the chain.  There may be some fiddling with the
chain numbering required here but I think we can get it so the chain
won't signal until everything in the array has signaled and we get the
same behavior as if we'd added the dma_fence_array to the chain.

In both cases, we end up with either a single array or a single and
destruction doesn't require recursion.  Thoughts?

--Jason
Christian König March 5, 2020, 1:06 p.m. UTC | #10
Am 04.03.20 um 17:41 schrieb Jason Ekstrand:
> On Wed, Mar 4, 2020 at 10:27 AM Jason Ekstrand <jason@jlekstrand.net> wrote:
>> On Wed, Mar 4, 2020 at 2:34 AM Christian König <christian.koenig@amd.com> wrote:
>>> Am 03.03.20 um 20:10 schrieb Jason Ekstrand:
>>>> On Thu, Feb 27, 2020 at 2:28 AM Christian König
>>>> <christian.koenig@amd.com> wrote:
>>>> [SNIP]
>>> For reference see what dance is necessary in the dma_fence_chain_release
>>> function to avoid that:
>>>>          /* Manually unlink the chain as much as possible to avoid
>>>> recursion
>>>>           * and potential stack overflow.
>>>>           */
>>>>          while ((prev = rcu_dereference_protected(chain->prev, true))) {
>>> ....
>>>
>>> It took me quite a while to figure out how to do this without causing
>>> issues. But I don't see how this would be possible for dma_fence_array.
>> Ah, I see the issue now!  It hadn't even occurred to me that userspace
>> could use this to build up an infinite recursion chain.  That's nasty!

Yeah, when I first stumbled over it it was like why the heck is my code 
crashing in an interrupt handler?

Realizing that this is stack corruption because of the long chain we 
constructed was quite an enlightenment.

And then it took me even longer to fix it :)

>>   I'll give this some more thought and see if can come up with
>> something clever.
>>
>> Here's one thought:  We could make dma_fence_array automatically
>> collapse any arrays it references and instead directly reference their
>> fences.  This way, no matter how much the client chains things, they
>> will never get more than one dma_fence_array.  Of course, the
>> difficulty here (answering my own question) comes if they ping-pong
>> back-and-forth between something which constructs a dma_fence_array
>> and something which constructs a dma_fence_chain to get
>> array-of-chain-of-array-of-chain-of-...  More thought needed.

Condensing the fences into a larger array can certainly work, yes.

> Answering my own questions again...  I think the
> array-of-chain-of-array case is also solvable.
>
> For array-of-chain, we can simply add all unsignaled dma_fences in the
> chain to the array.  The array won't signal until all of them have
> which is exactly the same behavior as if we'd added the chain itself.

Yeah, that should work. Probably best to implement something like a 
cursor to walk all fences in the data structure.

> For chain-of-array, we can add all unsignaled dma_fences in the array
> to the same point in the chain.  There may be some fiddling with the
> chain numbering required here but I think we can get it so the chain
> won't signal until everything in the array has signaled and we get the
> same behavior as if we'd added the dma_fence_array to the chain.

Well as far as I can see this won't work because it would break the 
semantics of the timeline sync.

But I think I know a different way which should work: A dma_fence_chain 
can still contain a dma_fence_array, only the other way around is 
forbidden. Then we create the cursor functionality in such a way that it 
allows us to deep dive into the data structure and return all containing 
fences one by one.

I can prototype that if you want, shouldn't be more than a few hours of 
hacking anyway.

Regards,
Christian.

>
> In both cases, we end up with either a single array or a single and
> destruction doesn't require recursion.  Thoughts?
>
> --Jason
Jason Ekstrand March 5, 2020, 3:54 p.m. UTC | #11
On Thu, Mar 5, 2020 at 7:06 AM Christian König <christian.koenig@amd.com> wrote:
>
> Am 04.03.20 um 17:41 schrieb Jason Ekstrand:
> > On Wed, Mar 4, 2020 at 10:27 AM Jason Ekstrand <jason@jlekstrand.net> wrote:
> >> On Wed, Mar 4, 2020 at 2:34 AM Christian König <christian.koenig@amd.com> wrote:
> >>> Am 03.03.20 um 20:10 schrieb Jason Ekstrand:
> >>>> On Thu, Feb 27, 2020 at 2:28 AM Christian König
> >>>> <christian.koenig@amd.com> wrote:
> >>>> [SNIP]
> >>> For reference see what dance is necessary in the dma_fence_chain_release
> >>> function to avoid that:
> >>>>          /* Manually unlink the chain as much as possible to avoid
> >>>> recursion
> >>>>           * and potential stack overflow.
> >>>>           */
> >>>>          while ((prev = rcu_dereference_protected(chain->prev, true))) {
> >>> ....
> >>>
> >>> It took me quite a while to figure out how to do this without causing
> >>> issues. But I don't see how this would be possible for dma_fence_array.
> >> Ah, I see the issue now!  It hadn't even occurred to me that userspace
> >> could use this to build up an infinite recursion chain.  That's nasty!
>
> Yeah, when I first stumbled over it it was like why the heck is my code
> crashing in an interrupt handler?
>
> Realizing that this is stack corruption because of the long chain we
> constructed was quite an enlightenment.
>
> And then it took me even longer to fix it :)

Fun....

> >>   I'll give this some more thought and see if can come up with
> >> something clever.
> >>
> >> Here's one thought:  We could make dma_fence_array automatically
> >> collapse any arrays it references and instead directly reference their
> >> fences.  This way, no matter how much the client chains things, they
> >> will never get more than one dma_fence_array.  Of course, the
> >> difficulty here (answering my own question) comes if they ping-pong
> >> back-and-forth between something which constructs a dma_fence_array
> >> and something which constructs a dma_fence_chain to get
> >> array-of-chain-of-array-of-chain-of-...  More thought needed.
>
> Condensing the fences into a larger array can certainly work, yes.
>
> > Answering my own questions again...  I think the
> > array-of-chain-of-array case is also solvable.
> >
> > For array-of-chain, we can simply add all unsignaled dma_fences in the
> > chain to the array.  The array won't signal until all of them have
> > which is exactly the same behavior as if we'd added the chain itself.
>
> Yeah, that should work. Probably best to implement something like a
> cursor to walk all fences in the data structure.
>
> > For chain-of-array, we can add all unsignaled dma_fences in the array
> > to the same point in the chain.  There may be some fiddling with the
> > chain numbering required here but I think we can get it so the chain
> > won't signal until everything in the array has signaled and we get the
> > same behavior as if we'd added the dma_fence_array to the chain.
>
> Well as far as I can see this won't work because it would break the
> semantics of the timeline sync.

I'm not 100% convinced it has to.  We already have support for the
seqno regressing and we ensure that we still wait for all the fences.
I thought maybe we could use that but I haven't spent enough time
looking at the details to be sure.  I may be missing something.

> But I think I know a different way which should work: A dma_fence_chain
> can still contain a dma_fence_array, only the other way around is
> forbidden. Then we create the cursor functionality in such a way that it
> allows us to deep dive into the data structure and return all containing
> fences one by one.

Agreed.  As long as one container is able to consume the other, it's fine.

> I can prototype that if you want, shouldn't be more than a few hours of
> hacking anyway.

If you'd like to, go for it.  I'd be happy to give it a go as well but
if you already know what you want, it may be easier for you to just
write the patch for the cursor.

Two more questions:

 1. Do you want this collapsing to happen every time we create a
dma_fence_array or should it be a special entrypoint?  Collapsing all
the time likely means doing extra array calculations instead of the
dma_fence_array taking ownership of the array that's passed in.  My
gut says that cost is ok; but my gut doesn't spend much time in kernel
space.

 2. When we do the collapsing, should we call dma_fence_is_signaled()
to avoid adding signaled fences to the array?  It seems like avoiding
adding references to fences that are already signaled would let the
kernel clean them up faster and reduce the likelihood that a fence
will hang around forever because it keeps getting added to arrays with
other unsignaled fences.

--Jason
Christian König March 9, 2020, 4:21 p.m. UTC | #12
Am 05.03.20 um 16:54 schrieb Jason Ekstrand:
> On Thu, Mar 5, 2020 at 7:06 AM Christian König <christian.koenig@amd.com> wrote:
>> [SNIP]
>> Well as far as I can see this won't work because it would break the
>> semantics of the timeline sync.
> I'm not 100% convinced it has to.  We already have support for the
> seqno regressing and we ensure that we still wait for all the fences.
> I thought maybe we could use that but I haven't spent enough time
> looking at the details to be sure.  I may be missing something.

That won't work. The seqno regression works by punishing userspace for 
doing something stupid and undefined.

Be we can't do that under normal circumstances.

>> I can prototype that if you want, shouldn't be more than a few hours of
>> hacking anyway.
> If you'd like to, go for it.  I'd be happy to give it a go as well but
> if you already know what you want, it may be easier for you to just
> write the patch for the cursor.

Send you two patches for that a few minutes ago. But keep in mind that 
those are completely untested.

> Two more questions:
>
>   1. Do you want this collapsing to happen every time we create a
> dma_fence_array or should it be a special entrypoint?  Collapsing all
> the time likely means doing extra array calculations instead of the
> dma_fence_array taking ownership of the array that's passed in.  My
> gut says that cost is ok; but my gut doesn't spend much time in kernel
> space.

In my prototype implementation that is a dma_resv function you call and 
get either a single fence or a dma_fence_array with the collapsed fences 
in return.

But I wouldn't add that to the general dma_fence_array_init function 
since this is still a rather special case. Well see the patches, they 
should be pretty self explaining.

>   2. When we do the collapsing, should we call dma_fence_is_signaled()
> to avoid adding signaled fences to the array?  It seems like avoiding
> adding references to fences that are already signaled would let the
> kernel clean them up faster and reduce the likelihood that a fence
> will hang around forever because it keeps getting added to arrays with
> other unsignaled fences.

I think so. Can't think of a good reason why we would want to add 
already signaled fences to the array.

Christian.

>
> --Jason
Jason Ekstrand March 11, 2020, 3:43 a.m. UTC | #13
On Mon, Mar 9, 2020 at 11:21 AM Christian König
<christian.koenig@amd.com> wrote:
>
> Am 05.03.20 um 16:54 schrieb Jason Ekstrand:
> > On Thu, Mar 5, 2020 at 7:06 AM Christian König <christian.koenig@amd.com> wrote:
> >> [SNIP]
> >> Well as far as I can see this won't work because it would break the
> >> semantics of the timeline sync.
> > I'm not 100% convinced it has to.  We already have support for the
> > seqno regressing and we ensure that we still wait for all the fences.
> > I thought maybe we could use that but I haven't spent enough time
> > looking at the details to be sure.  I may be missing something.
>
> That won't work. The seqno regression works by punishing userspace for
> doing something stupid and undefined.
>
> Be we can't do that under normal circumstances.
>
> >> I can prototype that if you want, shouldn't be more than a few hours of
> >> hacking anyway.
> > If you'd like to, go for it.  I'd be happy to give it a go as well but
> > if you already know what you want, it may be easier for you to just
> > write the patch for the cursor.
>
> Send you two patches for that a few minutes ago. But keep in mind that
> those are completely untested.

No worries.  They were full of bugs but I think I've got them sorted
out now.  The v2's I'm about to send seem to work.  I'm going to leave
a Vulkan demo running all night long just to make sure I'm not leaking
memory like mad.

--Jason

> > Two more questions:
> >
> >   1. Do you want this collapsing to happen every time we create a
> > dma_fence_array or should it be a special entrypoint?  Collapsing all
> > the time likely means doing extra array calculations instead of the
> > dma_fence_array taking ownership of the array that's passed in.  My
> > gut says that cost is ok; but my gut doesn't spend much time in kernel
> > space.
>
> In my prototype implementation that is a dma_resv function you call and
> get either a single fence or a dma_fence_array with the collapsed fences
> in return.
>
> But I wouldn't add that to the general dma_fence_array_init function
> since this is still a rather special case. Well see the patches, they
> should be pretty self explaining.
>
> >   2. When we do the collapsing, should we call dma_fence_is_signaled()
> > to avoid adding signaled fences to the array?  It seems like avoiding
> > adding references to fences that are already signaled would let the
> > kernel clean them up faster and reduce the likelihood that a fence
> > will hang around forever because it keeps getting added to arrays with
> > other unsignaled fences.
>
> I think so. Can't think of a good reason why we would want to add
> already signaled fences to the array.
>
> Christian.
>
> >
> > --Jason
>
diff mbox series

Patch

diff --git a/drivers/dma-buf/dma-buf.c b/drivers/dma-buf/dma-buf.c
index d4097856c86b..3845b87e209e 100644
--- a/drivers/dma-buf/dma-buf.c
+++ b/drivers/dma-buf/dma-buf.c
@@ -20,6 +20,7 @@ 
 #include <linux/debugfs.h>
 #include <linux/module.h>
 #include <linux/seq_file.h>
+#include <linux/sync_file.h>
 #include <linux/poll.h>
 #include <linux/dma-resv.h>
 #include <linux/mm.h>
@@ -348,6 +349,114 @@  static long dma_buf_set_name(struct dma_buf *dmabuf, const char __user *buf)
 	return ret;
 }
 
+static long dma_buf_wait_sync_file(struct dma_buf *dmabuf,
+				   const void __user *user_data)
+{
+	struct dma_buf_sync_file arg;
+	struct dma_fence *fence;
+
+	if (copy_from_user(&arg, user_data, sizeof(arg)))
+		return -EFAULT;
+
+	if (arg.flags != 0 && arg.flags != DMA_BUF_SYNC_FILE_SYNC_WRITE)
+		return -EINVAL;
+
+	fence = sync_file_get_fence(arg.fd);
+	if (!fence)
+		return -EINVAL;
+
+	if (arg.flags & DMA_BUF_SYNC_FILE_SYNC_WRITE) {
+		dma_resv_add_excl_fence(dmabuf->resv, fence);
+	} else {
+		dma_resv_add_shared_fence(dmabuf->resv, fence);
+	}
+
+	return 0;
+}
+
+static long dma_buf_signal_sync_file(struct dma_buf *dmabuf,
+				     void __user *user_data)
+{
+	struct dma_buf_sync_file arg;
+	struct dma_fence *fence = NULL;
+	struct sync_file *sync_file;
+	int fd, ret;
+
+	if (copy_from_user(&arg, user_data, sizeof(arg)))
+		return -EFAULT;
+
+	if (arg.flags != 0 && arg.flags != DMA_BUF_SYNC_FILE_SYNC_WRITE)
+		return -EINVAL;
+
+	fd = get_unused_fd_flags(O_CLOEXEC);
+	if (fd < 0)
+		return fd;
+
+	if (arg.flags & DMA_BUF_SYNC_FILE_SYNC_WRITE) {
+		/* We need to include both the exclusive fence and all of
+		 * the shared fences in our fence.
+		 */
+		struct dma_fence **fences = NULL;
+		unsigned i, num_fences = 0;
+
+		ret = dma_resv_get_fences_rcu(dmabuf->resv, NULL,
+					      &num_fences, &fences);
+		if (ret)
+			goto err_put_fd;
+
+		if (num_fences == 0) {
+			fence = dma_fence_get_stub();
+		} else if (num_fences == 1) {
+			fence = fences[0];
+			kfree(fences);
+		} else {
+			struct dma_fence_array *fence_arr;
+
+			fence_arr = dma_fence_array_create(num_fences, fences,
+							   dma_fence_context_alloc(1),
+							   1, false);
+			if (!fence_arr) {
+				for (i = 0; i < num_fences; i++)
+					dma_fence_put(fences[i]);
+				kfree(fences);
+				ret = -ENOMEM;
+				goto err_put_fd;
+			}
+
+			/* The fence array now owns fences_arr and our
+			 * references to each of the individual fences.  We
+			 * only own a reference to the one array fence.
+			 */
+			fence = &fence_arr->base;
+		}
+	} else {
+		fence = dma_resv_get_excl_rcu(dmabuf->resv);
+		if (!fence)
+			fence = dma_fence_get_stub();
+	}
+
+	sync_file = sync_file_create(fence);
+
+	dma_fence_put(fence);
+
+	if (!sync_file) {
+		ret = -EINVAL;
+		goto err_put_fd;
+	}
+
+	fd_install(fd, sync_file->file);
+
+	arg.fd = fd;
+	if (copy_to_user(user_data, &arg, sizeof(arg)))
+		return -EFAULT;
+
+	return 0;
+
+err_put_fd:
+	put_unused_fd(fd);
+	return ret;
+}
+
 static long dma_buf_ioctl(struct file *file,
 			  unsigned int cmd, unsigned long arg)
 {
@@ -390,6 +499,12 @@  static long dma_buf_ioctl(struct file *file,
 	case DMA_BUF_SET_NAME:
 		return dma_buf_set_name(dmabuf, (const char __user *)arg);
 
+	case DMA_BUF_IOCTL_WAIT_SYNC_FILE:
+		return dma_buf_wait_sync_file(dmabuf, (const void __user *)arg);
+
+	case DMA_BUF_IOCTL_SIGNAL_SYNC_FILE:
+		return dma_buf_signal_sync_file(dmabuf, (void __user *)arg);
+
 	default:
 		return -ENOTTY;
 	}
diff --git a/include/uapi/linux/dma-buf.h b/include/uapi/linux/dma-buf.h
index dbc7092e04b5..825b9a913c89 100644
--- a/include/uapi/linux/dma-buf.h
+++ b/include/uapi/linux/dma-buf.h
@@ -37,8 +37,17 @@  struct dma_buf_sync {
 
 #define DMA_BUF_NAME_LEN	32
 
+struct dma_buf_sync_file {
+	__u32 flags;
+	__s32 fd;
+};
+
+#define DMA_BUF_SYNC_FILE_SYNC_WRITE	(1 << 0)
+
 #define DMA_BUF_BASE		'b'
-#define DMA_BUF_IOCTL_SYNC	_IOW(DMA_BUF_BASE, 0, struct dma_buf_sync)
-#define DMA_BUF_SET_NAME	_IOW(DMA_BUF_BASE, 1, const char *)
+#define DMA_BUF_IOCTL_SYNC	    _IOW(DMA_BUF_BASE, 0, struct dma_buf_sync)
+#define DMA_BUF_SET_NAME	    _IOW(DMA_BUF_BASE, 1, const char *)
+#define DMA_BUF_IOCTL_WAIT_SYNC_FILE	_IOW(DMA_BUF_BASE, 2, struct dma_buf_sync)
+#define DMA_BUF_IOCTL_SIGNAL_SYNC_FILE	_IOW(DMA_BUF_BASE, 3, struct dma_buf_sync)
 
 #endif