forked from ValveSoftware/steamos-compositor
/
drm.cpp
2838 lines (2303 loc) · 77.7 KB
/
drm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// DRM output stuff
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <poll.h>
extern "C" {
#include <wlr/types/wlr_buffer.h>
}
#include "drm.hpp"
#include "main.hpp"
#include "modegen.hpp"
#include "vblankmanager.hpp"
#include "wlserver.hpp"
#include "log.hpp"
#include "gpuvis_trace_utils.h"
#include "steamcompmgr.hpp"
#include <algorithm>
#include <thread>
#include <unordered_set>
extern "C" {
#include "libdisplay-info/info.h"
#include "libdisplay-info/edid.h"
#include "libdisplay-info/cta.h"
}
struct drm_t g_DRM = {};
uint32_t g_nDRMFormat = DRM_FORMAT_INVALID;
uint32_t g_nDRMFormatHDR = DRM_FORMAT_INVALID;
bool g_bRotated = false;
bool g_bUseLayers = true;
bool g_bDebugLayers = false;
const char *g_sOutputName = nullptr;
#ifndef DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP
#define DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP 0x15
#endif
bool g_bSupportsAsyncFlips = false;
enum drm_mode_generation g_drmModeGeneration = DRM_MODE_GENERATE_CVT;
enum g_panel_orientation g_drmModeOrientation = PANEL_ORIENTATION_AUTO;
std::atomic<uint64_t> g_drmEffectiveOrientation(DRM_MODE_ROTATE_0);
static LogScope drm_log("drm");
static LogScope drm_verbose_log("drm", LOG_SILENT);
static std::map< std::string, std::string > pnps = {};
drm_screen_type drm_get_connector_type(drmModeConnector *connector);
static struct fb& get_fb( struct drm_t& drm, uint32_t id )
{
std::lock_guard<std::mutex> m( drm.fb_map_mutex );
return drm.fb_map[ id ];
}
static struct crtc *find_crtc_for_connector(struct drm_t *drm, const struct connector *connector) {
for (size_t i = 0; i < drm->crtcs.size(); i++) {
uint32_t crtc_mask = 1 << i;
if (connector->possible_crtcs & crtc_mask)
return &drm->crtcs[i];
}
return nullptr;
}
static bool get_plane_formats(struct drm_t *drm, struct plane *plane, struct wlr_drm_format_set *formats) {
for (uint32_t k = 0; k < plane->plane->count_formats; k++) {
uint32_t fmt = plane->plane->formats[k];
wlr_drm_format_set_add(formats, fmt, DRM_FORMAT_MOD_INVALID);
}
if (plane->props.count("IN_FORMATS") > 0) {
uint64_t blob_id = plane->initial_prop_values["IN_FORMATS"];
drmModePropertyBlobRes *blob = drmModeGetPropertyBlob(drm->fd, blob_id);
if (!blob) {
drm_log.errorf_errno("drmModeGetPropertyBlob(IN_FORMATS) failed");
return false;
}
struct drm_format_modifier_blob *data =
(struct drm_format_modifier_blob *)blob->data;
uint32_t *fmts = (uint32_t *)((char *)data + data->formats_offset);
struct drm_format_modifier *mods = (struct drm_format_modifier *)
((char *)data + data->modifiers_offset);
for (uint32_t i = 0; i < data->count_modifiers; ++i) {
for (int j = 0; j < 64; ++j) {
if (mods[i].formats & ((uint64_t)1 << j)) {
wlr_drm_format_set_add(formats,
fmts[j + mods[i].offset], mods[i].modifier);
}
}
}
drmModeFreePropertyBlob(blob);
}
return true;
}
static const char *get_enum_name(const drmModePropertyRes *prop, uint64_t value)
{
for (int i = 0; i < prop->count_enums; i++) {
if (prop->enums[i].value == value)
return prop->enums[i].name;
}
return nullptr;
}
static uint32_t pick_plane_format( const struct wlr_drm_format_set *formats, uint32_t Xformat, uint32_t Aformat )
{
uint32_t result = DRM_FORMAT_INVALID;
for ( size_t i = 0; i < formats->len; i++ ) {
uint32_t fmt = formats->formats[i]->format;
if ( fmt == Xformat ) {
// Prefer formats without alpha channel for main plane
result = fmt;
} else if ( result == DRM_FORMAT_INVALID && fmt == Aformat ) {
result = fmt;
}
}
return result;
}
/* Pick a primary plane that can be connected to the chosen CRTC. */
static struct plane *find_primary_plane(struct drm_t *drm)
{
struct plane *primary = nullptr;
for (size_t i = 0; i < drm->planes.size(); i++) {
struct plane *plane = &drm->planes[i];
if (!(plane->plane->possible_crtcs & (1 << drm->crtc_index)))
continue;
uint64_t plane_type = drm->planes[i].initial_prop_values["type"];
if (plane_type == DRM_PLANE_TYPE_PRIMARY) {
primary = plane;
break;
}
}
if (primary == nullptr)
return nullptr;
return primary;
}
static void drm_unlock_fb_internal( struct drm_t *drm, struct fb *fb );
std::atomic<uint64_t> g_nCompletedPageFlipCount = { 0u };
static void page_flip_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, unsigned int crtc_id, void *data)
{
uint64_t flipcount = (uint64_t)data;
g_nCompletedPageFlipCount = flipcount;
if ( g_DRM.crtc->id != crtc_id )
return;
// This is the last vblank time
uint64_t vblanktime = sec * 1'000'000'000lu + usec * 1'000lu;
vblank_mark_possible_vblank(vblanktime);
// TODO: get the fbids_queued instance from data if we ever have more than one in flight
drm_verbose_log.debugf("page_flip_handler %" PRIu64, flipcount);
gpuvis_trace_printf("page_flip_handler %" PRIu64, flipcount);
for ( uint32_t i = 0; i < g_DRM.fbids_on_screen.size(); i++ )
{
uint32_t previous_fbid = g_DRM.fbids_on_screen[ i ];
assert( previous_fbid != 0 );
struct fb &previous_fb = get_fb( g_DRM, previous_fbid );
if ( --previous_fb.n_refs == 0 )
{
// we flipped away from this previous fbid, now safe to delete
std::lock_guard<std::mutex> lock( g_DRM.free_queue_lock );
for ( uint32_t i = 0; i < g_DRM.fbid_unlock_queue.size(); i++ )
{
if ( g_DRM.fbid_unlock_queue[ i ] == previous_fbid )
{
drm_verbose_log.debugf("deferred unlock %u", previous_fbid);
drm_unlock_fb_internal( &g_DRM, &get_fb( g_DRM, previous_fbid ) );
g_DRM.fbid_unlock_queue.erase( g_DRM.fbid_unlock_queue.begin() + i );
break;
}
}
for ( uint32_t i = 0; i < g_DRM.fbid_free_queue.size(); i++ )
{
if ( g_DRM.fbid_free_queue[ i ] == previous_fbid )
{
drm_verbose_log.debugf( "deferred free %u", previous_fbid );
drm_drop_fbid( &g_DRM, previous_fbid );
g_DRM.fbid_free_queue.erase( g_DRM.fbid_free_queue.begin() + i );
break;
}
}
}
}
g_DRM.fbids_on_screen = g_DRM.fbids_queued;
g_DRM.fbids_queued.clear();
g_DRM.flip_lock.unlock();
}
void flip_handler_thread_run(void)
{
pthread_setname_np( pthread_self(), "gamescope-kms" );
struct pollfd pollfd = {
.fd = g_DRM.fd,
.events = POLLIN,
};
while ( true )
{
int ret = poll( &pollfd, 1, -1 );
if ( ret < 0 ) {
drm_log.errorf_errno( "polling for DRM events failed" );
break;
}
drmEventContext evctx = {
.version = 3,
.page_flip_handler2 = page_flip_handler,
};
drmHandleEvent(g_DRM.fd, &evctx);
}
}
static const drmModePropertyRes *get_prop(struct drm_t *drm, uint32_t prop_id)
{
if (drm->props.count(prop_id) > 0) {
return drm->props[prop_id];
}
drmModePropertyRes *prop = drmModeGetProperty(drm->fd, prop_id);
if (!prop) {
drm_log.errorf_errno("drmModeGetProperty failed");
return nullptr;
}
drm->props[prop_id] = prop;
return prop;
}
static bool get_object_properties(struct drm_t *drm, uint32_t obj_id, uint32_t obj_type, std::map<std::string, const drmModePropertyRes *> &map, std::map<std::string, uint64_t> &values)
{
drmModeObjectProperties *props = drmModeObjectGetProperties(drm->fd, obj_id, obj_type);
if (!props) {
drm_log.errorf_errno("drmModeObjectGetProperties failed");
return false;
}
map = {};
values = {};
for (uint32_t i = 0; i < props->count_props; i++) {
const drmModePropertyRes *prop = get_prop(drm, props->props[i]);
if (!prop) {
return false;
}
map[prop->name] = prop;
values[prop->name] = props->prop_values[i];
}
drmModeFreeObjectProperties(props);
return true;
}
static bool compare_modes( drmModeModeInfo mode1, drmModeModeInfo mode2 )
{
bool goodRefresh1 = mode1.vrefresh >= 60;
bool goodRefresh2 = mode2.vrefresh >= 60;
if (goodRefresh1 != goodRefresh2)
return goodRefresh1;
bool preferred1 = mode1.type & DRM_MODE_TYPE_PREFERRED;
bool preferred2 = mode2.type & DRM_MODE_TYPE_PREFERRED;
if (preferred1 != preferred2)
return preferred1;
int area1 = mode1.hdisplay * mode1.vdisplay;
int area2 = mode2.hdisplay * mode2.vdisplay;
if (area1 != area2)
return area1 > area2;
return mode1.vrefresh > mode2.vrefresh;
}
static void
drm_hdr_parse_edid(drm_t *drm, struct connector *connector, const struct di_edid *edid)
{
struct connector_metadata_t *metadata = &connector->metadata;
const struct di_edid_chromaticity_coords* chroma = di_edid_get_chromaticity_coords(edid);
const struct di_cta_hdr_static_metadata_block* hdr_static_metadata = NULL;
const struct di_cta_colorimetry_block* colorimetry = NULL;
const struct di_edid_cta* cta = NULL;
const struct di_edid_ext* const* exts = di_edid_get_extensions(edid);
for (; *exts != NULL; exts++) {
if ((cta = di_edid_ext_get_cta(*exts)))
break;
}
if (cta) {
const struct di_cta_data_block* const* blocks = di_edid_cta_get_data_blocks(cta);
for (; *blocks != NULL; blocks++) {
if (!hdr_static_metadata && (hdr_static_metadata = di_cta_data_block_get_hdr_static_metadata(*blocks)))
continue;
if (!colorimetry && (colorimetry = di_cta_data_block_get_colorimetry(*blocks)))
continue;
}
}
struct hdr_metadata_infoframe *infoframe = &metadata->defaultHdrMetadata.hdmi_metadata_type1;
if (chroma) {
infoframe->display_primaries[0].x = color_xy_to_u16(chroma->red_x);
infoframe->display_primaries[0].y = color_xy_to_u16(chroma->red_y);
infoframe->display_primaries[1].x = color_xy_to_u16(chroma->green_x);
infoframe->display_primaries[1].y = color_xy_to_u16(chroma->green_y);
infoframe->display_primaries[2].x = color_xy_to_u16(chroma->blue_x);
infoframe->display_primaries[2].y = color_xy_to_u16(chroma->blue_y);
infoframe->white_point.x = color_xy_to_u16(chroma->white_x);
infoframe->white_point.y = color_xy_to_u16(chroma->white_y);
}
if (hdr_static_metadata) {
infoframe->max_display_mastering_luminance = nits_to_u16(hdr_static_metadata->desired_content_max_luminance);
infoframe->min_display_mastering_luminance = nits_to_u16_dark(hdr_static_metadata->desired_content_min_luminance);
/* To be filled in by the app based on the scene, default to desired_content_max_luminance. */
infoframe->max_cll = nits_to_u16(hdr_static_metadata->desired_content_max_luminance);
infoframe->max_fall = nits_to_u16(hdr_static_metadata->desired_content_max_frame_avg_luminance);
}
metadata->supportsST2084 =
chroma &&
colorimetry && colorimetry->bt2020_rgb &&
hdr_static_metadata && hdr_static_metadata->eotfs && hdr_static_metadata->eotfs->pq;
if (metadata->supportsST2084) {
metadata->defaultHdrMetadata.metadata_type = 0;
infoframe->metadata_type = 0;
infoframe->eotf = HDMI_EOTF_ST2084;
metadata->hdr10_metadata_blob = drm_create_hdr_metadata_blob(drm, &metadata->defaultHdrMetadata);
if (metadata->hdr10_metadata_blob == nullptr) {
fprintf(stderr, "Failed to create blob for HDR_OUTPUT_METADATA. Falling back to null blob.\n");
}
}
}
static void parse_edid( drm_t *drm, struct connector *conn)
{
memset(conn->make_pnp, 0, sizeof(conn->make_pnp));
free(conn->make);
conn->make = NULL;
free(conn->model);
conn->model = NULL;
if (conn->props.count("EDID") == 0) {
return;
}
uint64_t blob_id = conn->initial_prop_values["EDID"];
if (blob_id == 0) {
return;
}
drmModePropertyBlobRes *blob = drmModeGetPropertyBlob(drm->fd, blob_id);
if (!blob) {
drm_log.errorf_errno("drmModeGetPropertyBlob(EDID) failed");
return;
}
struct di_info *info = di_info_parse_edid(blob->data, blob->length);
if (!info) {
drm_log.errorf("Failed to parse edid");
return;
}
drmModeFreePropertyBlob(blob);
const struct di_edid *edid = di_info_get_edid(info);
const struct di_edid_vendor_product *vendor_product = di_edid_get_vendor_product(edid);
char pnp_id[] = {
vendor_product->manufacturer[0],
vendor_product->manufacturer[1],
vendor_product->manufacturer[2],
'\0',
};
memcpy(conn->make_pnp, pnp_id, sizeof(pnp_id));
if (pnps.count(pnp_id) > 0) {
conn->make = strdup(pnps[pnp_id].c_str());
}
else {
// Some vendors like AOC, don't have a PNP id listed,
// but their name is literally just "AOC", so just
// use the PNP name directly.
conn->make = strdup(pnp_id);
}
const struct di_edid_display_descriptor *const *descriptors = di_edid_get_display_descriptors(edid);
for (size_t i = 0; descriptors[i] != NULL; i++) {
const struct di_edid_display_descriptor *desc = descriptors[i];
if (di_edid_display_descriptor_get_tag(desc) == DI_EDID_DISPLAY_DESCRIPTOR_PRODUCT_NAME) {
conn->model = strdup(di_edid_display_descriptor_get_string(desc));
}
}
drm_hdr_parse_edid(drm, conn, edid);
di_info_destroy(info);
}
static bool refresh_state( drm_t *drm )
{
drmModeRes *resources = drmModeGetResources(drm->fd);
if (resources == nullptr) {
drm_log.errorf_errno("drmModeGetResources failed");
return false;
}
// Add connectors which appeared
for (int i = 0; i < resources->count_connectors; i++) {
uint32_t conn_id = resources->connectors[i];
if (drm->connectors.count(conn_id) == 0) {
struct connector conn = { .id = conn_id };
drm->connectors[conn_id] = conn;
}
}
// Remove connectors which disappeared
auto it = drm->connectors.begin();
while (it != drm->connectors.end()) {
struct connector *conn = &it->second;
bool found = false;
for (int j = 0; j < resources->count_connectors; j++) {
if (resources->connectors[j] == conn->id) {
found = true;
break;
}
}
if (!found) {
drm_log.debugf("connector '%s' disappeared", conn->name);
if (drm->connector == conn) {
drm_log.infof("current connector '%s' disappeared", conn->name);
drm->connector = nullptr;
}
free(conn->name);
conn->name = nullptr;
conn->metadata.hdr10_metadata_blob = nullptr;
drmModeFreeConnector(conn->connector);
it = drm->connectors.erase(it);
} else {
it++;
}
}
drmModeFreeResources(resources);
// Re-probe connectors props and status
for (auto &kv : drm->connectors) {
struct connector *conn = &kv.second;
if (conn->connector != nullptr) {
conn->metadata.hdr10_metadata_blob = nullptr;
drmModeFreeConnector(conn->connector);
}
conn->connector = drmModeGetConnector(drm->fd, conn->id);
if (conn->connector == nullptr) {
drm_log.errorf_errno("drmModeGetConnector failed");
return false;
}
if (!get_object_properties(drm, conn->id, DRM_MODE_OBJECT_CONNECTOR, conn->props, conn->initial_prop_values)) {
return false;
}
/* sort modes by preference: preferred flag, then highest area, then
* highest refresh rate */
std::stable_sort(conn->connector->modes, conn->connector->modes + conn->connector->count_modes, compare_modes);
parse_edid(drm, conn);
if ( conn->name != nullptr )
continue;
const char *type_str = drmModeGetConnectorTypeName(conn->connector->connector_type);
if (!type_str)
type_str = "Unknown";
char name[128] = {};
snprintf(name, sizeof(name), "%s-%d", type_str, conn->connector->connector_type_id);
conn->name = strdup(name);
conn->possible_crtcs = drmModeConnectorGetPossibleCrtcs(drm->fd, conn->connector);
if (!conn->possible_crtcs)
drm_log.errorf_errno("drmModeConnectorGetPossibleCrtcs failed");
conn->has_colorspace = conn->props.contains( "Colorspace" );
conn->has_hdr_output_metadata = conn->props.contains( "HDR_OUTPUT_METADATA" );
conn->has_content_type = conn->props.contains( "content type" );
conn->current.crtc_id = conn->initial_prop_values["CRTC_ID"];
if (conn->has_colorspace)
conn->current.colorspace = conn->initial_prop_values["Colorspace"];
if (conn->has_hdr_output_metadata)
conn->current.hdr_output_metadata = std::make_shared<wlserver_hdr_metadata>(conn->initial_prop_values["HDR_OUTPUT_METADATA"], false);
if (conn->has_content_type)
conn->current.content_type = conn->initial_prop_values["content type"];
conn->target_refresh = 0;
conn->vrr_capable = !!conn->initial_prop_values["vrr_capable"];
drm_log.debugf("found new connector '%s'", conn->name);
}
for (size_t i = 0; i < drm->crtcs.size(); i++) {
struct crtc *crtc = &drm->crtcs[i];
if (!get_object_properties(drm, crtc->id, DRM_MODE_OBJECT_CRTC, crtc->props, crtc->initial_prop_values)) {
return false;
}
crtc->has_gamma_lut = crtc->props.contains( "GAMMA_LUT" );
if (!crtc->has_gamma_lut)
drm_log.infof("CRTC %" PRIu32 " has no gamma LUT support", crtc->id);
crtc->has_degamma_lut = crtc->props.contains( "DEGAMMA_LUT" );
if (!crtc->has_degamma_lut)
drm_log.infof("CRTC %" PRIu32 " has no degamma LUT support", crtc->id);
crtc->has_ctm = crtc->props.contains( "CTM" );
if (!crtc->has_ctm)
drm_log.infof("CRTC %" PRIu32 " has no CTM support", crtc->id);
crtc->has_vrr_enabled = crtc->props.contains( "VRR_ENABLED" );
if (!crtc->has_vrr_enabled)
drm_log.infof("CRTC %" PRIu32 " has no VRR_ENABLED support", crtc->id);
crtc->lut3d_size = crtc->props.contains( "VALVE1_LUT3D_SIZE" ) ? uint32_t(crtc->initial_prop_values["VALVE1_LUT3D_SIZE"]) : 0;
crtc->shaperlut_size = crtc->props.contains( "VALVE1_SHAPER_LUT_SIZE" ) ? uint32_t(crtc->initial_prop_values["VALVE1_SHAPER_LUT_SIZE"]) : 0;
crtc->current.active = crtc->initial_prop_values["ACTIVE"];
if (crtc->has_vrr_enabled)
drm->current.vrr_enabled = crtc->initial_prop_values["VRR_ENABLED"];
}
for (size_t i = 0; i < drm->planes.size(); i++) {
struct plane *plane = &drm->planes[i];
if (!get_object_properties(drm, plane->id, DRM_MODE_OBJECT_PLANE, plane->props, plane->initial_prop_values)) {
return false;
}
}
return true;
}
static bool get_resources(struct drm_t *drm)
{
drmModeRes *resources = drmModeGetResources(drm->fd);
if (resources == nullptr) {
drm_log.errorf_errno("drmModeGetResources failed");
return false;
}
for (int i = 0; i < resources->count_crtcs; i++) {
struct crtc crtc = { .id = resources->crtcs[i] };
crtc.crtc = drmModeGetCrtc(drm->fd, crtc.id);
if (crtc.crtc == nullptr) {
drm_log.errorf_errno("drmModeGetCrtc failed");
return false;
}
drm->crtcs.push_back(crtc);
}
drmModeFreeResources(resources);
drmModePlaneRes *plane_resources = drmModeGetPlaneResources(drm->fd);
if (!plane_resources) {
drm_log.errorf_errno("drmModeGetPlaneResources failed");
return false;
}
for (uint32_t i = 0; i < plane_resources->count_planes; i++) {
struct plane plane = { .id = plane_resources->planes[i] };
plane.plane = drmModeGetPlane(drm->fd, plane.id);
if (plane.plane == nullptr) {
drm_log.errorf_errno("drmModeGetPlane failed");
return false;
}
drm->planes.push_back(plane);
}
drmModeFreePlaneResources(plane_resources);
if (!refresh_state(drm))
return false;
for (size_t i = 0; i < drm->crtcs.size(); i++) {
struct crtc *crtc = &drm->crtcs[i];
crtc->pending = crtc->current;
}
return true;
}
struct mode_blocklist_entry
{
uint32_t width, height, refresh;
};
// Filter out reporting some modes that are required for
// certain certifications, but are completely useless,
// and probably don't fit the display pixel size.
static mode_blocklist_entry g_badModes[] =
{
{ 4096, 2160, 0 },
};
static const drmModeModeInfo *find_mode( const drmModeConnector *connector, int hdisplay, int vdisplay, uint32_t vrefresh )
{
for (int i = 0; i < connector->count_modes; i++) {
const drmModeModeInfo *mode = &connector->modes[i];
bool bad = false;
for (const auto& badMode : g_badModes) {
bad |= (badMode.width == 0 || mode->hdisplay == badMode.width)
&& (badMode.height == 0 || mode->vdisplay == badMode.height)
&& (badMode.refresh == 0 || mode->vrefresh == badMode.refresh);
}
if (bad)
continue;
if (hdisplay != 0 && hdisplay != mode->hdisplay)
continue;
if (vdisplay != 0 && vdisplay != mode->vdisplay)
continue;
if (vrefresh != 0 && vrefresh != mode->vrefresh)
continue;
return mode;
}
return NULL;
}
static std::unordered_map<std::string, int> parse_connector_priorities(const char *str)
{
std::unordered_map<std::string, int> priorities{};
if (!str) {
return priorities;
}
int i = 0;
char *buf = strdup(str);
char *name = strtok(buf, ",");
while (name) {
priorities[name] = i;
i++;
name = strtok(nullptr, ",");
}
free(buf);
return priorities;
}
static int get_connector_priority(struct drm_t *drm, const char *name)
{
if (drm->connector_priorities.count(name) > 0) {
return drm->connector_priorities[name];
}
if (drm->connector_priorities.count("*") > 0) {
return drm->connector_priorities["*"];
}
return drm->connector_priorities.size();
}
static bool get_saved_mode(const char *description, saved_mode &mode_info)
{
const char *mode_file = getenv("GAMESCOPE_MODE_SAVE_FILE");
if (!mode_file || !*mode_file)
return false;
FILE *file = fopen(mode_file, "r");
if (!file)
return false;
char line[256];
while (fgets(line, sizeof(line), file))
{
char saved_description[256];
bool valid = sscanf(line, "%255[^:]:%dx%d@%d", saved_description, &mode_info.width, &mode_info.height, &mode_info.refresh) == 4;
if (valid && !strcmp(saved_description, description))
{
fclose(file);
return true;
}
}
fclose(file);
return false;
}
static bool setup_best_connector(struct drm_t *drm, bool force)
{
if (drm->connector && drm->connector->connector->connection != DRM_MODE_CONNECTED) {
drm_log.infof("current connector '%s' disconnected", drm->connector->name);
drm->connector = nullptr;
}
struct connector *best = nullptr;
int best_priority = INT_MAX;
for (auto &kv : drm->connectors) {
struct connector *conn = &kv.second;
if (conn->connector->connection != DRM_MODE_CONNECTED)
continue;
if (drm->force_internal && drm_get_connector_type(conn->connector) == DRM_SCREEN_TYPE_EXTERNAL)
continue;
int priority = get_connector_priority(drm, conn->name);
if (priority < best_priority) {
best = conn;
best_priority = priority;
}
}
if (!force) {
if ((!best && drm->connector) || (best && best == drm->connector)) {
// Let's keep our current connector
return true;
}
}
if ( best == nullptr ) {
/* we could be fancy and listen for hotplug events and wait for
* a connector.. */
drm_log.errorf("cannot find any connector!");
return false;
}
if (!drm_set_connector(drm, best)) {
return false;
}
char description[256];
if (drm_get_connector_type(best->connector) == DRM_SCREEN_TYPE_INTERNAL) {
snprintf(description, sizeof(description), "Internal screen");
} else if (best->make && best->model) {
snprintf(description, sizeof(description), "%s %s", best->make, best->model);
} else if (best->model) {
snprintf(description, sizeof(description), "%s", best->model);
} else {
snprintf(description, sizeof(description), "External screen");
}
const drmModeModeInfo *mode = nullptr;
if ( drm->preferred_width != 0 || drm->preferred_height != 0 || drm->preferred_refresh != 0 )
{
mode = find_mode(best->connector, drm->preferred_width, drm->preferred_height, drm->preferred_refresh);
}
if (!mode && drm_get_connector_type(best->connector) == DRM_SCREEN_TYPE_EXTERNAL) {
saved_mode mode_info;
if (get_saved_mode(description, mode_info))
mode = find_mode(best->connector, mode_info.width, mode_info.height, mode_info.refresh);
}
if (!mode) {
mode = find_mode(best->connector, 0, 0, 0);
}
if (!mode) {
drm_log.errorf("could not find mode!");
return false;
}
best->target_refresh = mode->vrefresh;
if (!drm_set_mode(drm, mode)) {
return false;
}
const struct wlserver_output_info wlserver_output_info = {
.description = description,
.phys_width = (int) best->connector->mmWidth,
.phys_height = (int) best->connector->mmHeight,
};
wlserver_set_output_info(&wlserver_output_info);
return true;
}
void load_pnps(void)
{
const char *filename = HWDATA_PNP_IDS;
FILE *f = fopen(filename, "r");
if (!f) {
drm_log.infof("failed to open PNP IDs file at '%s'", filename);
return;
}
char *line = NULL;
size_t line_size = 0;
while (getline(&line, &line_size, f) >= 0) {
char *nl = strchr(line, '\n');
if (nl) {
*nl = '\0';
}
char *sep = strchr(line, '\t');
if (!sep) {
continue;
}
*sep = '\0';
std::string id(line);
std::string name(sep + 1);
pnps[id] = name;
}
free(line);
fclose(f);
}
bool init_drm(struct drm_t *drm, int width, int height, int refresh, bool wants_adaptive_sync)
{
load_pnps();
drm->wants_vrr_enabled = wants_adaptive_sync;
drm->preferred_width = width;
drm->preferred_height = height;
drm->preferred_refresh = refresh;
drm->device_name = nullptr;
dev_t dev_id = 0;
if (vulkan_primary_dev_id(&dev_id)) {
drmDevice *drm_dev = nullptr;
if (drmGetDeviceFromDevId(dev_id, 0, &drm_dev) != 0) {
drm_log.errorf("Failed to find DRM device with device ID %" PRIu64, (uint64_t)dev_id);
return false;
}
assert(drm_dev->available_nodes & (1 << DRM_NODE_PRIMARY));
drm->device_name = strdup(drm_dev->nodes[DRM_NODE_PRIMARY]);
drm_log.infof("opening DRM node '%s'", drm->device_name);
}
else
{
drm_log.infof("warning: picking an arbitrary DRM device");
}
drm->fd = wlsession_open_kms( drm->device_name );
if ( drm->fd < 0 )
{
drm_log.errorf("Could not open KMS device");
return false;
}
if (drmSetClientCap(drm->fd, DRM_CLIENT_CAP_ATOMIC, 1) != 0) {
drm_log.errorf("drmSetClientCap(ATOMIC) failed");
return false;
}
if (drmGetCap(drm->fd, DRM_CAP_CURSOR_WIDTH, &drm->cursor_width) != 0) {
drm->cursor_width = 64;
}
if (drmGetCap(drm->fd, DRM_CAP_CURSOR_HEIGHT, &drm->cursor_height) != 0) {
drm->cursor_height = 64;
}
uint64_t cap;
if (drmGetCap(drm->fd, DRM_CAP_ADDFB2_MODIFIERS, &cap) == 0 && cap != 0) {
drm->allow_modifiers = true;
}
g_bSupportsAsyncFlips = drmGetCap(drm->fd, DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP, &cap) == 0 && cap != 0;
if (!g_bSupportsAsyncFlips)
drm_log.errorf("Immediate flips are not supported by the KMS driver");
if (!get_resources(drm)) {
return false;
}
drm->lo_device = liftoff_device_create( drm->fd );
if ( drm->lo_device == nullptr )
return false;
if ( liftoff_device_register_all_planes( drm->lo_device ) < 0 )
return false;
drm_log.infof("Connectors:");
for (const auto &kv : drm->connectors) {
const struct connector *conn = &kv.second;
const char *status_str = "disconnected";
if ( conn->connector->connection == DRM_MODE_CONNECTED )
status_str = "connected";
drm_log.infof(" %s (%s)", conn->name, status_str);
}
drm->connector_priorities = parse_connector_priorities( g_sOutputName );
if (!setup_best_connector(drm, false)) {
return false;
}
// Fetch formats which can be scanned out
for (size_t i = 0; i < drm->planes.size(); i++) {
struct plane *plane = &drm->planes[i];
if (!get_plane_formats(drm, plane, &drm->formats))
return false;
}
if (!get_plane_formats(drm, drm->primary, &drm->primary_formats)) {
return false;
}
g_nDRMFormat = pick_plane_format(&drm->primary_formats, DRM_FORMAT_XRGB8888, DRM_FORMAT_ARGB8888);
if ( g_nDRMFormat == DRM_FORMAT_INVALID ) {
drm_log.errorf("Primary plane doesn't support XRGB8888 nor ARGB8888");
return false;
}
g_nDRMFormatHDR = pick_plane_format(&drm->primary_formats, DRM_FORMAT_XRGB2101010, DRM_FORMAT_ARGB2101010);
if ( g_nDRMFormatHDR == DRM_FORMAT_INVALID ) {
g_nDRMFormatHDR = pick_plane_format(&drm->primary_formats, DRM_FORMAT_XBGR2101010, DRM_FORMAT_ABGR2101010);
if ( g_nDRMFormatHDR == DRM_FORMAT_INVALID ) {
drm_log.errorf("Primary plane doesn't support any 10 bit formats. No HDR.");
}
}
drm->kms_in_fence_fd = -1;
std::thread flip_handler_thread( flip_handler_thread_run );
flip_handler_thread.detach();
if (g_bUseLayers) {
liftoff_log_set_priority(g_bDebugLayers ? LIFTOFF_DEBUG : LIFTOFF_ERROR);
}
hdr_output_metadata sdr_metadata;
memset(&sdr_metadata, 0, sizeof(sdr_metadata));
drm->sdr_static_metadata = drm_create_hdr_metadata_blob(drm, &sdr_metadata);
drm->flipcount = 0;
drm->needs_modeset = true;
return true;
}
static int add_property(drmModeAtomicReq *req, uint32_t obj_id, std::map<std::string, const drmModePropertyRes *> &props, const char *name, uint64_t value)
{
if ( props.count( name ) == 0 )
{
drm_log.errorf("no property %s on object %u", name, obj_id);
return -ENOENT;
}
const drmModePropertyRes *prop = props[ name ];