1package drm
2
3import (
4 "context"
5 "os"
6 "sync"
7 "sync/atomic"
8 "testing"
9 "testing/synctest"
10 "time"
11
12 portsmocks "github.com/bnema/neferwl/internal/mocks/ports"
13 "github.com/bnema/neferwl/internal/ports"
14 "github.com/stretchr/testify/mock"
15 "golang.org/x/sys/unix"
16)
17
18// runStuck runs an output whose commits return errs (after the start
19// modeset test and modeset) and whose CRTC never sends an event. It
20// returns the recorded commits once n were made, failing after 2s.
21func runStuck(t *testing.T, n int, errs ...error) []commitRec {
22 t.Helper()
23 h := startStuck(t, nil, errs...)
24 h.scenes <- ports.Scene{Seq: 1}
25 waitFor(t, func() bool { return h.count() >= n })
26 return h.stop()
27}
28
29// stuckRun is an output run by startStuck.
30type stuckRun struct {
31 t *testing.T
32 scenes chan ports.Scene
33 contents *contentFeed
34 active chan bool
35 presented chan ports.OutputPresented
36 sink ports.PresentationSink
37 count func() int
38 stop func() []commitRec
39}
40
41// startStuck runs an output whose commits return errs (after the start
42// modeset test and modeset) and whose CRTC never sends an event. render
43// makes each frame's fence once the output started (nil: none).
44func startStuck(t *testing.T, render func() *os.File, errs ...error) *stuckRun {
45 t.Helper()
46 o, k, commits, commitMu := testOutputMu(t, append([]error{nil, nil}, errs...)...)
47 o.cursor, o.tearing, o.fbs = nil, false, [2]uint32{}
48 o.frame.stuckAfter = 200 * time.Millisecond
49 o.flipped = make(chan flipEvent) // no event ever
50 r := portsmocks.NewMockRenderer(t)
51 buf := func() ports.DMABuf {
52 f, w, _ := os.Pipe()
53 w.Close()
54 return ports.DMABuf{Planes: []ports.DMABufPlane{{File: f}}}
55 }
56 r.EXPECT().SetHDR(float64(0)).Return().Maybe()
57 r.EXPECT().ExportTargets(2, mock.Anything, false).Return([]ports.DMABuf{buf(), buf()}, nil).Once()
58 r.EXPECT().UseTarget(mock.Anything).Return()
59 var started atomic.Bool
60 r.EXPECT().Render(mock.Anything, mock.Anything).RunAndReturn(func(ports.Scene, map[ports.WindowID]ports.SurfaceContent) (*os.File, error) {
61 if render == nil || !started.Load() {
62 return nil, nil
63 }
64 return render(), nil
65 })
66 r.EXPECT().Close().Return().Once()
67 k.EXPECT().addFB(mock.Anything, uint32(fourccXRGB)).Return(70, nil).Twice()
68 k.EXPECT().createBlob(mock.Anything).Return(99, nil)
69 k.EXPECT().destroyBlob(mock.Anything).Return(nil)
70 k.EXPECT().rmFB(mock.Anything).Return(nil).Maybe()
71 h := &stuckRun{t: t, scenes: make(chan ports.Scene, 1), contents: newContentFeed(t, 1), active: make(chan bool, 1), presented: nil}
72 h.sink, h.presented = presentedSink(t, 64)
73 ctx, cancel := context.WithCancel(context.Background())
74 done := make(chan error, 1)
75 go func() {
76 done <- o.Run(ctx, func(int, int) (ports.Renderer, error) { return r, nil }, nil, h.active, h.scenes, h.contents.in(), h.contents.ret, nil, h.sink, nil, nil)
77 }()
78 h.count = func() int {
79 commitMu.Lock()
80 defer commitMu.Unlock()
81 return len(*commits)
82 }
83 h.stop = func() []commitRec {
84 cancel()
85 if err := <-done; err != nil {
86 t.Fatal(err)
87 }
88 commitMu.Lock()
89 defer commitMu.Unlock()
90 return append([]commitRec(nil), (*commits)...)
91 }
92 waitFor(t, func() bool { return h.count() == 2 })
93 started.Store(true)
94 return h
95}
96
97// A commit whose event never comes must not stop the output: it is
98// abandoned with a modeset, then the scene is committed again.
99func TestMissingEventRecoversWithModeset(t *testing.T) {
100 c := runStuck(t, 5)
101 if c[2].user&3 != userFrame {
102 t.Fatalf("commit 2 is not a frame: %+v", c[2])
103 }
104 if c[3].flags&atomicAllowModes == 0 {
105 t.Fatalf("no recovery modeset after the missing event: flags %#x", c[3].flags)
106 }
107 if c[4].user&3 != userFrame || c[4].user>>userKindBits <= c[2].user>>userKindBits {
108 t.Fatalf("scene not committed again after the modeset: %+v", c[4])
109 }
110}
111
112// EBUSY with no commit of ours in flight gets no event: the commit is
113// retried without one.
114func TestBusyWithoutEventRetries(t *testing.T) {
115 c := runStuck(t, 4, unix.EBUSY)
116 if c[2].user&3 != userFrame || c[3].user&3 != userFrame || c[3].flags&atomicAllowModes != 0 {
117 t.Fatalf("busy frame not retried: %+v", c[2:])
118 }
119}
120
121// EBUSY that lasts past the limit ends in a modeset, and a modeset
122// refused as busy is retried too.
123func TestLastingBusyModesets(t *testing.T) {
124 errs := make([]error, 8)
125 for i := range errs {
126 errs[i] = unix.EBUSY
127 }
128 c := runStuck(t, 2+len(errs)+1, errs...)
129 found := false
130 for _, r := range c[2:] {
131 if r.flags&atomicAllowModes != 0 {
132 found = true
133 }
134 }
135 if !found {
136 t.Fatal("no modeset while EBUSY lasted")
137 }
138}
139
140// fencePipe is a fence that signals when its write end is written.
141func fencePipe(t *testing.T) (fence, signal *os.File) {
142 t.Helper()
143 r, w, err := os.Pipe()
144 if err != nil {
145 t.Fatal(err)
146 }
147 t.Cleanup(func() { r.Close(); w.Close() })
148 return r, w
149}
150
151// A frame whose GPU fence has not signalled is slow, not lost: it keeps
152// waiting past the limit; once the fence signalled and still no event
153// came, the output modesets.
154func TestUnsignalledFenceDelaysRecovery(t *testing.T) {
155 synctest.Test(t, unsignalledFenceDelaysRecovery)
156}
157
158func unsignalledFenceDelaysRecovery(t *testing.T) {
159 var mu sync.Mutex
160 var signals []*os.File
161 h := startStuck(t, func() *os.File {
162 f, w := fencePipe(t)
163 mu.Lock()
164 signals = append(signals, w)
165 mu.Unlock()
166 return f
167 })
168 h.scenes <- ports.Scene{Seq: 1}
169 waitFor(t, func() bool { return h.count() == 3 })
170 time.Sleep(3 * 200 * time.Millisecond)
171 synctest.Wait()
172 if n := h.count(); n != 3 {
173 t.Fatalf("%d commits while the frame's fence is unsignalled", n)
174 }
175 mu.Lock()
176 _, _ = signals[0].Write([]byte{1})
177 mu.Unlock()
178 waitFor(t, func() bool { return h.count() >= 4 })
179 if c := h.stop(); c[3].flags&atomicAllowModes == 0 {
180 t.Fatalf("no modeset once the fence signalled: %#x", c[3].flags)
181 }
182}
183
184// A frame refused with EBUSY may still be read by the GPU: what was seen
185// is reported only once its fence signalled.
186func TestSeenWaitsForRefusedFrameFence(t *testing.T) {
187 var mu sync.Mutex
188 var signals []*os.File
189 h := startStuck(t, func() *os.File {
190 f, w := fencePipe(t)
191 mu.Lock()
192 signals = append(signals, w)
193 mu.Unlock()
194 return f
195 }, unix.EBUSY, unix.EACCES)
196 h.scenes <- ports.Scene{Seq: 1}
197 // EBUSY, then the retry loses DRM master: nothing is pending.
198 waitFor(t, func() bool { return h.count() == 4 })
199 h.contents.send(ports.SurfaceContent{ID: 1, Seq: 7})
200 select {
201 case p := <-h.presented:
202 t.Fatalf("seen reported while refused frames may be read: %+v", p)
203 case <-time.After(50 * time.Millisecond):
204 }
205 mu.Lock()
206 for _, w := range signals {
207 _, _ = w.Write([]byte{1})
208 }
209 mu.Unlock()
210 select {
211 case p := <-h.presented:
212 if p.Seen[1] != 7 {
213 t.Fatalf("report %+v", p)
214 }
215 case <-time.After(2 * time.Second):
216 t.Fatal("seen not reported once the fences signalled")
217 }
218 h.stop()
219}
220
221// An EBUSY run ends when commits stop being refused: a later EBUSY is
222// retried, not taken as the same run lasting past the limit.
223func TestLaterBusyStartsNewRun(t *testing.T) { synctest.Test(t, laterBusyStartsNewRun) }
224
225func laterBusyStartsNewRun(t *testing.T) {
226 o, _, _ := testOutput(t, unix.EBUSY, unix.EBUSY)
227 o.frame.stuckAfter = 100 * time.Millisecond
228 enabled := true
229 o.commitFailed(o.commitFrame(70, nil, false, false, pendingFrame{}), &enabled)
230 time.Sleep(busyRetry)
231 if o.expire() {
232 t.Fatal("first EBUSY retry modesets")
233 }
234 time.Sleep(2 * o.frame.stuckAfter)
235 o.commitFailed(o.commitFrame(70, nil, false, false, pendingFrame{}), &enabled)
236 time.Sleep(busyRetry)
237 if o.expire() {
238 t.Fatal("a new EBUSY taken as the old run: modeset")
239 }
240}
241
242// A modeset that fails keeps what is on screen: buffers still shown are
243// not released under the plane.
244func TestFailedModesetKeepsShown(t *testing.T) {
245 o, k, _ := testOutput(t, unix.EACCES)
246 k.EXPECT().createBlob(mock.Anything).Return(99, nil)
247 k.EXPECT().destroyBlob(mock.Anything).Return(nil)
248 o.shown, o.queued = 5, 6
249 if err := o.modeset(); err == nil {
250 t.Fatal("modeset succeeded")
251 }
252 if o.shown != 5 || o.queued != 6 {
253 t.Fatalf("shown %d queued %d after a failed modeset", o.shown, o.queued)
254 }
255}