summaryrefslogtreecommitdiffstats
path: root/src/VBox/Additions/x11/VBoxClient/display-svga-x11.cpp
blob: 90005ab117f25fdf05ae917503bb5142344d1018 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
/* $Id: display-svga-x11.cpp $ */
/** @file
 * X11 guest client - VMSVGA emulation resize event pass-through to X.Org
 * guest driver.
 */

/*
 * Copyright (C) 2017-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

/*
 * Known things to test when changing this code.  All assume a guest with VMSVGA
 * active and controlled by X11 or Wayland, and Guest Additions installed and
 * running, unless otherwise stated.
 *  - On Linux 4.6 and later guests, VBoxClient --vmsvga should be running as
 *    root and not as the logged-in user.  Dynamic resizing should work for all
 *    screens in any environment which handles kernel resize notifications,
 *    including at log-in screens.  Test GNOME Shell Wayland and GNOME Shell
 *    under X.Org or Unity or KDE at the log-in screen and after log-in.
 *  - Linux 4.10 changed the user-kernel-ABI introduced in 4.6: test both.
 *  - On other guests (than Linux 4.6 or later) running X.Org Server 1.3 or
 *    later, VBoxClient --vmsvga should never be running as root, and should run
 *    (and dynamic resizing and screen enable/disable should work for all
 *    screens) whenever a user is logged in to a supported desktop environment.
 *  - On guests running X.Org Server 1.2 or older, VBoxClient --vmsvga should
 *    never run as root and should run whenever a user is logged in to a
 *    supported desktop environment.  Dynamic resizing should work for the first
 *    screen, and enabling others should not be possible.
 *  - When VMSVGA is not enabled, VBoxClient --vmsvga should never stay running.
 *  - The following assumptions are done and should be taken into account when reading/chaning the code:
 *    # The order of the outputs (monitors) is assumed to be the same in RANDROUTPUT array and
 *    XRRScreenResources.outputs array.
 *  - This code does 2 related but separate things: 1- It resizes and enables/disables monitors upon host's
 *    requests (see the infinite loop in run()). 2- it listens to RandR events (caused by this or any other X11 client)
 *    on a different thread and notifies host about the new monitor positions. See sendMonitorPositions(...). This is
 *    mainly a work around since we have realized that vmsvga does not convey correct monitor positions thru FIFO.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include <stdio.h>
#include <dlfcn.h>
/** For sleep(..) */
#include <unistd.h>
#include "VBoxClient.h"

#include <VBox/VBoxGuestLib.h>

#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/file.h>
#include <iprt/mem.h>
#include <iprt/path.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include <iprt/env.h>

#include <X11/Xlibint.h>
#include <X11/extensions/Xrandr.h>
#include <X11/extensions/panoramiXproto.h>

#include "display-svga-xf86cvt.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
#define MILLIS_PER_INCH (25.4)
#define DEFAULT_DPI (96.0)

/* Time in milliseconds to relax if no X11 events available. */
#define VBOX_SVGA_X11_RELAX_TIME_MS  (500)
/* Time in milliseconds to wait for host events. */
#define VBOX_SVGA_HOST_EVENT_RX_TIMEOUT_MS  (500)

/** Maximum number of supported screens.  DRM and X11 both limit this to 32. */
/** @todo if this ever changes, dynamically allocate resizeable arrays in the
 *  context structure. */
#define VMW_MAX_HEADS 32

#define checkFunctionPtrReturn(pFunction) \
    do { \
        if (pFunction) { } \
        else \
        { \
            VBClLogFatalError("Could not find symbol address (%s)\n", #pFunction); \
            dlclose(x11Context.pRandLibraryHandle); \
            x11Context.pRandLibraryHandle = NULL; \
            return VERR_NOT_FOUND; \
        } \
    } while (0)

#define checkFunctionPtr(pFunction) \
    do { \
        if (pFunction) {} \
        else VBClLogError("Could not find symbol address (%s)\n", #pFunction);\
    } while (0)


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
#define X_VMwareCtrlSetRes  1

typedef struct
{
   CARD8    reqType;
   CARD8    VMwareCtrlReqType;
   CARD16   length B16;
   CARD32   screen B32;
   CARD32   x B32;
   CARD32   y B32;
} xVMwareCtrlSetResReq;
#define sz_xVMwareCtrlSetResReq 16

typedef struct
{
   BYTE     type;
   BYTE     pad1;
   CARD16   sequenceNumber B16;
   CARD32   length B32;
   CARD32   screen B32;
   CARD32   x B32;
   CARD32   y B32;
   CARD32   pad2 B32;
   CARD32   pad3 B32;
   CARD32   pad4 B32;
} xVMwareCtrlSetResReply;
#define sz_xVMwareCtrlSetResReply 32

typedef struct {
   CARD8  reqType;           /* always X_VMwareCtrlReqCode */
   CARD8  VMwareCtrlReqType; /* always X_VMwareCtrlSetTopology */
   CARD16 length B16;
   CARD32 screen B32;
   CARD32 number B32;
   CARD32 pad1   B32;
} xVMwareCtrlSetTopologyReq;
#define sz_xVMwareCtrlSetTopologyReq 16

#define X_VMwareCtrlSetTopology 2

typedef struct {
   BYTE   type; /* X_Reply */
   BYTE   pad1;
   CARD16 sequenceNumber B16;
   CARD32 length B32;
   CARD32 screen B32;
   CARD32 pad2   B32;
   CARD32 pad3   B32;
   CARD32 pad4   B32;
   CARD32 pad5   B32;
   CARD32 pad6   B32;
} xVMwareCtrlSetTopologyReply;
#define sz_xVMwareCtrlSetTopologyReply 32

struct X11VMWRECT
{
    int16_t x;
    int16_t y;
    uint16_t w;
    uint16_t h;
};
AssertCompileSize(struct X11VMWRECT, 8);

struct X11CONTEXT
{
    Display *pDisplay;
    /* We use a separate connection for randr event listening since sharing  a
       single display object with resizing (main) and event listening threads ends up having a deadlock.*/
    Display *pDisplayRandRMonitoring;
    Window rootWindow;
    int iDefaultScreen;
    XRRScreenResources *pScreenResources;
    int hRandRMajor;
    int hRandRMinor;
    int hRandREventBase;
    int hRandRErrorBase;
    int hEventMask;
    bool fMonitorInfoAvailable;
    /** The number of outputs (monitors, including disconnect ones) xrandr reports. */
    int hOutputCount;
    void *pRandLibraryHandle;
    bool fWmwareCtrlExtention;
    int hVMWCtrlMajorOpCode;
    /** Function pointers we used if we dlopen libXrandr instead of linking. */
    void (*pXRRSelectInput) (Display *, Window, int);
    Bool (*pXRRQueryExtension) (Display *, int *, int *);
    Status (*pXRRQueryVersion) (Display *, int *, int*);
    XRRMonitorInfo* (*pXRRGetMonitors)(Display *, Window, Bool, int *);
    XRRScreenResources* (*pXRRGetScreenResources)(Display *, Window);
    Status (*pXRRSetCrtcConfig)(Display *, XRRScreenResources *, RRCrtc,
                                Time, int, int, RRMode, Rotation, RROutput *, int);
    void (*pXRRFreeMonitors)(XRRMonitorInfo *);
    void (*pXRRFreeScreenResources)(XRRScreenResources *);
    void (*pXRRFreeModeInfo)(XRRModeInfo *);
    void (*pXRRFreeOutputInfo)(XRROutputInfo *);
    void (*pXRRSetScreenSize)(Display *, Window, int, int, int, int);
    int (*pXRRUpdateConfiguration)(XEvent *event);
    XRRModeInfo* (*pXRRAllocModeInfo)(_Xconst char *, int);
    RRMode (*pXRRCreateMode) (Display *, Window, XRRModeInfo *);
    XRROutputInfo* (*pXRRGetOutputInfo) (Display *, XRRScreenResources *, RROutput);
    XRRCrtcInfo* (*pXRRGetCrtcInfo) (Display *, XRRScreenResources *, RRCrtc crtc);
    void (*pXRRFreeCrtcInfo)(XRRCrtcInfo *);
    void (*pXRRAddOutputMode)(Display *, RROutput, RRMode);
    void (*pXRRDeleteOutputMode)(Display *, RROutput, RRMode);
    void (*pXRRDestroyMode)(Display *, RRMode);
    void (*pXRRSetOutputPrimary)(Display *, Window, RROutput);
};

static X11CONTEXT x11Context;

struct RANDROUTPUT
{
    int32_t x;
    int32_t y;
    uint32_t width;
    uint32_t height;
    bool fEnabled;
    bool fPrimary;
};


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static void x11Connect();
static int determineOutputCount();


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** Monitor positions array. Allocated here and deallocated in the class descructor. */
RTPOINT *mpMonitorPositions;
/** Thread to listen to some of the X server events. */
RTTHREAD mX11MonitorThread = NIL_RTTHREAD;
/** Shutdown indicator for the monitor thread. */
static bool g_fMonitorThreadShutdown = false;



#ifdef RT_OS_SOLARIS
static bool VMwareCtrlSetRes(
    Display *dpy, int hExtensionMajorOpcode, int screen, int x, int y)
{
    xVMwareCtrlSetResReply rep;
    xVMwareCtrlSetResReq *pReq;
    bool fResult = false;

    LockDisplay(dpy);

    GetReq(VMwareCtrlSetRes, pReq);
    AssertPtrReturn(pReq, false);

    pReq->reqType = hExtensionMajorOpcode;
    pReq->VMwareCtrlReqType = X_VMwareCtrlSetRes;
    pReq->screen = screen;
    pReq->x = x;
    pReq->y = y;

    fResult = !!_XReply(dpy, (xReply *)&rep, (SIZEOF(xVMwareCtrlSetResReply) - SIZEOF(xReply)) >> 2, xFalse);

    UnlockDisplay(dpy);

    return fResult;
}
#endif /* RT_OS_SOLARIS */

/** Makes a call to vmwarectrl extension. This updates the
 * connection information and possible resolutions (modes)
 * of each monitor on the driver. Also sets the preferred mode
 * of each output (monitor) to currently selected one. */
bool VMwareCtrlSetTopology(Display *dpy, int hExtensionMajorOpcode,
                            int screen, xXineramaScreenInfo extents[], int number)
{
    xVMwareCtrlSetTopologyReply rep;
    xVMwareCtrlSetTopologyReq *req;

    long len;

    LockDisplay(dpy);

    GetReq(VMwareCtrlSetTopology, req);
    req->reqType = hExtensionMajorOpcode;
    req->VMwareCtrlReqType = X_VMwareCtrlSetTopology;
    req->screen = screen;
    req->number = number;

    len = ((long) number) << 1;
    SetReqLen(req, len, len);
    len <<= 2;
    _XSend(dpy, (char *)extents, len);

    if (!_XReply(dpy, (xReply *)&rep,
                 (SIZEOF(xVMwareCtrlSetTopologyReply) - SIZEOF(xReply)) >> 2,
                 xFalse))
    {
        UnlockDisplay(dpy);
        SyncHandle();
        return false;
    }
    UnlockDisplay(dpy);
    SyncHandle();
    return true;
}

/** This function assumes monitors are named as from Virtual1 to VirtualX. */
static int getMonitorIdFromName(const char *sMonitorName)
{
    if (!sMonitorName)
        return -1;
#ifdef RT_OS_SOLARIS
    if (!strcmp(sMonitorName, "default"))
        return 1;
#endif
    int iLen = strlen(sMonitorName);
    if (iLen <= 0)
        return -1;
    int iBase = 10;
    int iResult = 0;
    for (int i = iLen - 1; i >= 0; --i)
    {
        /* Stop upon seeing the first non-numeric char. */
        if (sMonitorName[i] < 48 || sMonitorName[i] > 57)
            break;
        iResult += (sMonitorName[i] - 48) * iBase / 10;
        iBase *= 10;
    }
    return iResult;
}

static void sendMonitorPositions(RTPOINT *pPositions, size_t cPositions)
{
    if (cPositions && !pPositions)
    {
        VBClLogError(("Monitor position update called with NULL pointer!\n"));
        return;
    }
    int rc = VbglR3SeamlessSendMonitorPositions(cPositions, pPositions);
    if (RT_SUCCESS(rc))
        VBClLogInfo("Sending monitor positions (%u of them)  to the host: %Rrc\n", cPositions, rc);
    else
        VBClLogError("Error during sending monitor positions (%u of them)  to the host: %Rrc\n", cPositions, rc);
}

static void queryMonitorPositions()
{
    static const int iSentinelPosition = -1;
    if (mpMonitorPositions)
    {
        free(mpMonitorPositions);
        mpMonitorPositions = NULL;
    }

    int iMonitorCount = 0;
    XRRMonitorInfo *pMonitorInfo = NULL;
#ifdef WITH_DISTRO_XRAND_XINERAMA
    pMonitorInfo = XRRGetMonitors(x11Context.pDisplayRandRMonitoring,
                                  DefaultRootWindow(x11Context.pDisplayRandRMonitoring), true, &iMonitorCount);
#else
    if (x11Context.pXRRGetMonitors)
        pMonitorInfo = x11Context.pXRRGetMonitors(x11Context.pDisplayRandRMonitoring,
                                                  DefaultRootWindow(x11Context.pDisplayRandRMonitoring), true, &iMonitorCount);
#endif
    if (!pMonitorInfo)
        return;
    if (iMonitorCount == -1)
        VBClLogError("Could not get monitor info\n");
    else
    {
        mpMonitorPositions = (RTPOINT*)malloc(x11Context.hOutputCount * sizeof(RTPOINT));
        /** @todo memset? */
        for (int i = 0; i < x11Context.hOutputCount; ++i)
        {
            mpMonitorPositions[i].x = iSentinelPosition;
            mpMonitorPositions[i].y = iSentinelPosition;
        }
        for (int i = 0; i < iMonitorCount; ++i)
        {
            char *pszMonitorName = XGetAtomName(x11Context.pDisplayRandRMonitoring, pMonitorInfo[i].name);
            if (!pszMonitorName)
            {
                VBClLogError("queryMonitorPositions: skip monitor with unknown name %d\n", i);
                continue;
            }

            int iMonitorID = getMonitorIdFromName(pszMonitorName) - 1;
            XFree((void *)pszMonitorName);
            pszMonitorName = NULL;

            if (iMonitorID >= x11Context.hOutputCount || iMonitorID == -1)
            {
                VBClLogInfo("queryMonitorPositions: skip monitor %d (id %d) (w,h)=(%d,%d) (x,y)=(%d,%d)\n",
                            i, iMonitorID,
                            pMonitorInfo[i].width, pMonitorInfo[i].height,
                            pMonitorInfo[i].x, pMonitorInfo[i].y);
                continue;
            }
            VBClLogInfo("Monitor %d (w,h)=(%d,%d) (x,y)=(%d,%d)\n",
                        i,
                        pMonitorInfo[i].width, pMonitorInfo[i].height,
                        pMonitorInfo[i].x, pMonitorInfo[i].y);
            mpMonitorPositions[iMonitorID].x = pMonitorInfo[i].x;
            mpMonitorPositions[iMonitorID].y = pMonitorInfo[i].y;
        }
        if (iMonitorCount > 0)
            sendMonitorPositions(mpMonitorPositions, x11Context.hOutputCount);
    }
#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRFreeMonitors(pMonitorInfo);
#else
    if (x11Context.pXRRFreeMonitors)
        x11Context.pXRRFreeMonitors(pMonitorInfo);
#endif
}

static void monitorRandREvents()
{
    XEvent event;

    if (XPending(x11Context.pDisplayRandRMonitoring) > 0)
    {
        XNextEvent(x11Context.pDisplayRandRMonitoring, &event);
        int eventTypeOffset = event.type - x11Context.hRandREventBase;
        VBClLogInfo("received X11 event (%d)\n", event.type);
        switch (eventTypeOffset)
        {
            case RRScreenChangeNotify:
                VBClLogInfo("RRScreenChangeNotify event received\n");
                queryMonitorPositions();
                break;
            default:
                break;
        }
    } else
    {
        RTThreadSleep(VBOX_SVGA_X11_RELAX_TIME_MS);
    }
}

/**
 * @callback_method_impl{FNRTTHREAD}
 */
static DECLCALLBACK(int) x11MonitorThreadFunction(RTTHREAD ThreadSelf, void *pvUser)
{
    RT_NOREF(ThreadSelf, pvUser);
    while (!ASMAtomicReadBool(&g_fMonitorThreadShutdown))
    {
        monitorRandREvents();
    }

    VBClLogInfo("X11 thread gracefully terminated\n");

    return 0;
}

static int startX11MonitorThread()
{
    int rc;
    Assert(g_fMonitorThreadShutdown == false);
    if (mX11MonitorThread == NIL_RTTHREAD)
    {
        rc = RTThreadCreate(&mX11MonitorThread, x11MonitorThreadFunction, NULL /*pvUser*/, 0 /*cbStack*/,
                            RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE, "X11 events");
        if (RT_FAILURE(rc))
            VBClLogFatalError("Warning: failed to start X11 monitor thread (VBoxClient) rc=%Rrc!\n", rc);
    }
    else
        rc = VINF_ALREADY_INITIALIZED;
    return rc;
}

static int stopX11MonitorThread(void)
{
    int rc = VINF_SUCCESS;
    if (mX11MonitorThread != NIL_RTTHREAD)
    {
        ASMAtomicWriteBool(&g_fMonitorThreadShutdown, true);
        /** @todo  Send event to thread to get it out of XNextEvent. */
        //????????
        //mX11Monitor.interruptEventWait();
        rc = RTThreadWait(mX11MonitorThread, RT_MS_1SEC, NULL /*prc*/);
        if (RT_SUCCESS(rc))
        {
            mX11MonitorThread = NIL_RTTHREAD;
            g_fMonitorThreadShutdown = false;
        }
        else
            VBClLogError("Failed to stop X11 monitor thread, rc=%Rrc!\n", rc);
    }
    return rc;
}

static bool callVMWCTRL(struct RANDROUTPUT *paOutputs)
{
    int hHeight = 600;
    int hWidth = 800;
    bool fResult = false;
    int idxDefaultScreen = DefaultScreen(x11Context.pDisplay);

    AssertReturn(idxDefaultScreen >= 0, false);
    AssertReturn(idxDefaultScreen < x11Context.hOutputCount, false);

    xXineramaScreenInfo *extents = (xXineramaScreenInfo *)malloc(x11Context.hOutputCount * sizeof(xXineramaScreenInfo));
    if (!extents)
        return false;
    int hRunningOffset = 0;
    for (int i = 0; i < x11Context.hOutputCount; ++i)
    {
        if (paOutputs[i].fEnabled)
        {
            hHeight = paOutputs[i].height;
            hWidth = paOutputs[i].width;
        }
        else
        {
            hHeight = 0;
            hWidth = 0;
        }
        extents[i].x_org = hRunningOffset;
        extents[i].y_org = 0;
        extents[i].width = hWidth;
        extents[i].height = hHeight;
        hRunningOffset += hWidth;
    }
#ifdef RT_OS_SOLARIS
    fResult = VMwareCtrlSetRes(x11Context.pDisplay, x11Context.hVMWCtrlMajorOpCode,
                               idxDefaultScreen, extents[idxDefaultScreen].width,
                               extents[idxDefaultScreen].height);
#else
    fResult = VMwareCtrlSetTopology(x11Context.pDisplay, x11Context.hVMWCtrlMajorOpCode,
                                    idxDefaultScreen, extents, x11Context.hOutputCount);
#endif
    free(extents);
    return fResult;
}

/**
 * @interface_method_impl{VBCLSERVICE,pfnInit}
 */
static DECLCALLBACK(int) vbclSVGAInit(void)
{
    int rc;

    /* In 32-bit guests GAs build on our release machines causes an xserver hang.
     * So for 32-bit GAs we use our DRM client. */
#if ARCH_BITS == 32
    rc = VbglR3DrmClientStart();
    if (RT_FAILURE(rc))
        VBClLogError("Starting DRM resizing client (32-bit) failed with %Rrc\n", rc);
    return VERR_NOT_AVAILABLE; /** @todo r=andy Why ignoring rc here? */
#endif

    /* If DRM client is already running don't start this service. */
    if (VbglR3DrmClientIsRunning())
    {
        VBClLogInfo("DRM resizing is already running. Exiting this service\n");
        return VERR_NOT_AVAILABLE;
    }

    if (VBClHasWayland())
    {
        rc = VbglR3DrmClientStart();
        if (RT_SUCCESS(rc))
        {
            VBClLogInfo("VBoxDrmClient has been successfully started, exitting parent process\n");
            exit(0);
        }
        else
        {
            VBClLogError("Starting DRM resizing client failed with %Rrc\n", rc);
        }
        return rc;
    }

    x11Connect();

    if (x11Context.pDisplay == NULL)
        return VERR_NOT_AVAILABLE;

    /* don't start the monitoring thread if related randr functionality is not available. */
    if (x11Context.fMonitorInfoAvailable)
    {
        if (RT_FAILURE(startX11MonitorThread()))
            return VERR_NOT_AVAILABLE;
    }

    return VINF_SUCCESS;
}

/**
 * @interface_method_impl{VBCLSERVICE,pfnStop}
 */
static DECLCALLBACK(void) vbclSVGAStop(void)
{
    int rc;

    rc = stopX11MonitorThread();
    if (RT_FAILURE(rc))
    {
        VBClLogError("cannot stop X11 monitor thread (%Rrc)\n", rc);
        return;
    }

    if (mpMonitorPositions)
    {
        free(mpMonitorPositions);
        mpMonitorPositions = NULL;
    }

    if (x11Context.pDisplayRandRMonitoring)
    {
#ifdef WITH_DISTRO_XRAND_XINERAMA
        XRRSelectInput(x11Context.pDisplayRandRMonitoring, x11Context.rootWindow, 0);
#else
        if (x11Context.pXRRSelectInput)
            x11Context.pXRRSelectInput(x11Context.pDisplayRandRMonitoring, x11Context.rootWindow, 0);
#endif
    }

    if (x11Context.pDisplay)
    {
        XCloseDisplay(x11Context.pDisplay);
        x11Context.pDisplay = NULL;
    }

    if (x11Context.pDisplayRandRMonitoring)
    {
        XCloseDisplay(x11Context.pDisplayRandRMonitoring);
        x11Context.pDisplayRandRMonitoring = NULL;
    }

    if (x11Context.pRandLibraryHandle)
    {
        dlclose(x11Context.pRandLibraryHandle);
        x11Context.pRandLibraryHandle = NULL;
    }
}

#ifndef WITH_DISTRO_XRAND_XINERAMA
static int openLibRandR()
{
    x11Context.pRandLibraryHandle = dlopen("libXrandr.so", RTLD_LAZY /*| RTLD_LOCAL */);
    if (!x11Context.pRandLibraryHandle)
        x11Context.pRandLibraryHandle = dlopen("libXrandr.so.2", RTLD_LAZY /*| RTLD_LOCAL */);
    if (!x11Context.pRandLibraryHandle)
        x11Context.pRandLibraryHandle = dlopen("libXrandr.so.2.2.0", RTLD_LAZY /*| RTLD_LOCAL */);

    if (!x11Context.pRandLibraryHandle)
    {
        VBClLogFatalError("Could not locate libXrandr for dlopen\n");
        return VERR_NOT_FOUND;
    }

    *(void **)(&x11Context.pXRRSelectInput) = dlsym(x11Context.pRandLibraryHandle, "XRRSelectInput");
    checkFunctionPtrReturn(x11Context.pXRRSelectInput);

    *(void **)(&x11Context.pXRRQueryExtension) = dlsym(x11Context.pRandLibraryHandle, "XRRQueryExtension");
    checkFunctionPtrReturn(x11Context.pXRRQueryExtension);

    *(void **)(&x11Context.pXRRQueryVersion) = dlsym(x11Context.pRandLibraryHandle, "XRRQueryVersion");
    checkFunctionPtrReturn(x11Context.pXRRQueryVersion);

    /* Don't bail out when XRRGetMonitors XRRFreeMonitors are missing as in Oracle Solaris 10. It is not crucial esp. for single monitor. */
    *(void **)(&x11Context.pXRRGetMonitors) = dlsym(x11Context.pRandLibraryHandle, "XRRGetMonitors");
    checkFunctionPtr(x11Context.pXRRGetMonitors);

    *(void **)(&x11Context.pXRRFreeMonitors) = dlsym(x11Context.pRandLibraryHandle, "XRRFreeMonitors");
    checkFunctionPtr(x11Context.pXRRFreeMonitors);

    x11Context.fMonitorInfoAvailable = x11Context.pXRRGetMonitors && x11Context.pXRRFreeMonitors;

    *(void **)(&x11Context.pXRRGetScreenResources) = dlsym(x11Context.pRandLibraryHandle, "XRRGetScreenResources");
    checkFunctionPtr(x11Context.pXRRGetScreenResources);

    *(void **)(&x11Context.pXRRSetCrtcConfig) = dlsym(x11Context.pRandLibraryHandle, "XRRSetCrtcConfig");
    checkFunctionPtr(x11Context.pXRRSetCrtcConfig);

    *(void **)(&x11Context.pXRRFreeScreenResources) = dlsym(x11Context.pRandLibraryHandle, "XRRFreeScreenResources");
    checkFunctionPtr(x11Context.pXRRFreeScreenResources);

    *(void **)(&x11Context.pXRRFreeModeInfo) = dlsym(x11Context.pRandLibraryHandle, "XRRFreeModeInfo");
    checkFunctionPtr(x11Context.pXRRFreeModeInfo);

    *(void **)(&x11Context.pXRRFreeOutputInfo) = dlsym(x11Context.pRandLibraryHandle, "XRRFreeOutputInfo");
    checkFunctionPtr(x11Context.pXRRFreeOutputInfo);

    *(void **)(&x11Context.pXRRSetScreenSize) = dlsym(x11Context.pRandLibraryHandle, "XRRSetScreenSize");
    checkFunctionPtr(x11Context.pXRRSetScreenSize);

    *(void **)(&x11Context.pXRRUpdateConfiguration) = dlsym(x11Context.pRandLibraryHandle, "XRRUpdateConfiguration");
    checkFunctionPtr(x11Context.pXRRUpdateConfiguration);

    *(void **)(&x11Context.pXRRAllocModeInfo) = dlsym(x11Context.pRandLibraryHandle, "XRRAllocModeInfo");
    checkFunctionPtr(x11Context.pXRRAllocModeInfo);

    *(void **)(&x11Context.pXRRCreateMode) = dlsym(x11Context.pRandLibraryHandle, "XRRCreateMode");
    checkFunctionPtr(x11Context.pXRRCreateMode);

    *(void **)(&x11Context.pXRRGetOutputInfo) = dlsym(x11Context.pRandLibraryHandle, "XRRGetOutputInfo");
    checkFunctionPtr(x11Context.pXRRGetOutputInfo);

    *(void **)(&x11Context.pXRRGetCrtcInfo) = dlsym(x11Context.pRandLibraryHandle, "XRRGetCrtcInfo");
    checkFunctionPtr(x11Context.pXRRGetCrtcInfo);

    *(void **)(&x11Context.pXRRFreeCrtcInfo) = dlsym(x11Context.pRandLibraryHandle, "XRRFreeCrtcInfo");
    checkFunctionPtr(x11Context.pXRRFreeCrtcInfo);

    *(void **)(&x11Context.pXRRAddOutputMode) = dlsym(x11Context.pRandLibraryHandle, "XRRAddOutputMode");
    checkFunctionPtr(x11Context.pXRRAddOutputMode);

    *(void **)(&x11Context.pXRRDeleteOutputMode) = dlsym(x11Context.pRandLibraryHandle, "XRRDeleteOutputMode");
    checkFunctionPtr(x11Context.pXRRDeleteOutputMode);

    *(void **)(&x11Context.pXRRDestroyMode) = dlsym(x11Context.pRandLibraryHandle, "XRRDestroyMode");
    checkFunctionPtr(x11Context.pXRRDestroyMode);

    *(void **)(&x11Context.pXRRSetOutputPrimary) = dlsym(x11Context.pRandLibraryHandle, "XRRSetOutputPrimary");
    checkFunctionPtr(x11Context.pXRRSetOutputPrimary);

    return VINF_SUCCESS;
}
#endif

static void x11Connect()
{
    x11Context.pScreenResources = NULL;
    x11Context.pXRRSelectInput = NULL;
    x11Context.pRandLibraryHandle = NULL;
    x11Context.pXRRQueryExtension = NULL;
    x11Context.pXRRQueryVersion = NULL;
    x11Context.pXRRGetMonitors = NULL;
    x11Context.pXRRGetScreenResources = NULL;
    x11Context.pXRRSetCrtcConfig = NULL;
    x11Context.pXRRFreeMonitors = NULL;
    x11Context.pXRRFreeScreenResources = NULL;
    x11Context.pXRRFreeOutputInfo = NULL;
    x11Context.pXRRFreeModeInfo = NULL;
    x11Context.pXRRSetScreenSize = NULL;
    x11Context.pXRRUpdateConfiguration = NULL;
    x11Context.pXRRAllocModeInfo = NULL;
    x11Context.pXRRCreateMode = NULL;
    x11Context.pXRRGetOutputInfo = NULL;
    x11Context.pXRRGetCrtcInfo = NULL;
    x11Context.pXRRFreeCrtcInfo = NULL;
    x11Context.pXRRAddOutputMode = NULL;
    x11Context.pXRRDeleteOutputMode = NULL;
    x11Context.pXRRDestroyMode = NULL;
    x11Context.pXRRSetOutputPrimary = NULL;
    x11Context.fWmwareCtrlExtention = false;
    x11Context.fMonitorInfoAvailable = false;
    x11Context.hRandRMajor = 0;
    x11Context.hRandRMinor = 0;

    int dummy;
    if (x11Context.pDisplay != NULL)
        VBClLogFatalError("%s called with bad argument\n", __func__);
    x11Context.pDisplay = XOpenDisplay(NULL);
    x11Context.pDisplayRandRMonitoring = XOpenDisplay(NULL);
    if (x11Context.pDisplay == NULL)
        return;
#ifndef WITH_DISTRO_XRAND_XINERAMA
    if (openLibRandR() != VINF_SUCCESS)
    {
        XCloseDisplay(x11Context.pDisplay);
        XCloseDisplay(x11Context.pDisplayRandRMonitoring);
        x11Context.pDisplay = NULL;
        x11Context.pDisplayRandRMonitoring = NULL;
        return;
    }
#endif

    x11Context.fWmwareCtrlExtention = XQueryExtension(x11Context.pDisplay, "VMWARE_CTRL",
                                                      &x11Context.hVMWCtrlMajorOpCode, &dummy, &dummy);
    if (!x11Context.fWmwareCtrlExtention)
        VBClLogError("VMWARE's ctrl extension is not available! Multi monitor management is not possible\n");
    else
        VBClLogInfo("VMWARE's ctrl extension is available. Major Opcode is %d.\n", x11Context.hVMWCtrlMajorOpCode);

    /* Check Xrandr stuff. */
    bool fSuccess = false;
#ifdef WITH_DISTRO_XRAND_XINERAMA
    fSuccess = XRRQueryExtension(x11Context.pDisplay, &x11Context.hRandREventBase, &x11Context.hRandRErrorBase);
#else
    if (x11Context.pXRRQueryExtension)
        fSuccess = x11Context.pXRRQueryExtension(x11Context.pDisplay, &x11Context.hRandREventBase, &x11Context.hRandRErrorBase);
#endif
    if (fSuccess)
    {
        fSuccess = false;
#ifdef WITH_DISTRO_XRAND_XINERAMA
        fSuccess = XRRQueryVersion(x11Context.pDisplay, &x11Context.hRandRMajor, &x11Context.hRandRMinor);
#else
    if (x11Context.pXRRQueryVersion)
        fSuccess = x11Context.pXRRQueryVersion(x11Context.pDisplay, &x11Context.hRandRMajor, &x11Context.hRandRMinor);
#endif
        if (!fSuccess)
        {
            XCloseDisplay(x11Context.pDisplay);
            x11Context.pDisplay = NULL;
            return;
        }
        if (x11Context.hRandRMajor < 1 || x11Context.hRandRMinor <= 3)
        {
            VBClLogError("Resizing service requires libXrandr Version >= 1.4. Detected version is %d.%d\n", x11Context.hRandRMajor, x11Context.hRandRMinor);
            XCloseDisplay(x11Context.pDisplay);
            x11Context.pDisplay = NULL;

            int rc = VbglR3DrmLegacyX11AgentStart();
            VBClLogInfo("Attempt to start legacy X11 resize agent, rc=%Rrc\n", rc);

            return;
        }
    }
    x11Context.rootWindow = DefaultRootWindow(x11Context.pDisplay);
    x11Context.hEventMask = RRScreenChangeNotifyMask;

    /* Select the XEvent types we want to listen to. */
#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRSelectInput(x11Context.pDisplayRandRMonitoring, x11Context.rootWindow, x11Context.hEventMask);
#else
    if (x11Context.pXRRSelectInput)
        x11Context.pXRRSelectInput(x11Context.pDisplayRandRMonitoring, x11Context.rootWindow, x11Context.hEventMask);
#endif
    x11Context.iDefaultScreen = DefaultScreen(x11Context.pDisplay);

#ifdef WITH_DISTRO_XRAND_XINERAMA
    x11Context.pScreenResources = XRRGetScreenResources(x11Context.pDisplay, x11Context.rootWindow);
#else
    if (x11Context.pXRRGetScreenResources)
        x11Context.pScreenResources = x11Context.pXRRGetScreenResources(x11Context.pDisplay, x11Context.rootWindow);
#endif
    x11Context.hOutputCount = RT_VALID_PTR(x11Context.pScreenResources) ? determineOutputCount() : 0;
#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRFreeScreenResources(x11Context.pScreenResources);
#else
    if (x11Context.pXRRFreeScreenResources)
        x11Context.pXRRFreeScreenResources(x11Context.pScreenResources);
#endif
}

static int determineOutputCount()
{
    if (!x11Context.pScreenResources)
        return 0;
    return x11Context.pScreenResources->noutput;
}

static int findExistingModeIndex(unsigned iXRes, unsigned iYRes)
{
    if (!x11Context.pScreenResources)
        return -1;
    for (int i = 0; i < x11Context.pScreenResources->nmode; ++i)
    {
        if (x11Context.pScreenResources->modes[i].width == iXRes && x11Context.pScreenResources->modes[i].height == iYRes)
            return i;
    }
    return -1;
}

static bool disableCRTC(RRCrtc crtcID)
{
    XRRCrtcInfo *pCrctInfo = NULL;

#ifdef WITH_DISTRO_XRAND_XINERAMA
    pCrctInfo = XRRGetCrtcInfo(x11Context.pDisplay, x11Context.pScreenResources, crtcID);
#else
    if (x11Context.pXRRGetCrtcInfo)
        pCrctInfo = x11Context.pXRRGetCrtcInfo(x11Context.pDisplay, x11Context.pScreenResources, crtcID);
#endif

    if (!pCrctInfo)
        return false;

    Status ret = Success;
#ifdef WITH_DISTRO_XRAND_XINERAMA
    ret = XRRSetCrtcConfig(x11Context.pDisplay, x11Context.pScreenResources, crtcID,
                           CurrentTime, 0, 0, None, RR_Rotate_0, NULL, 0);
#else
    if (x11Context.pXRRSetCrtcConfig)
        ret = x11Context.pXRRSetCrtcConfig(x11Context.pDisplay, x11Context.pScreenResources, crtcID,
                                           CurrentTime, 0, 0, None, RR_Rotate_0, NULL, 0);
#endif

#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRFreeCrtcInfo(pCrctInfo);
#else
    if (x11Context.pXRRFreeCrtcInfo)
        x11Context.pXRRFreeCrtcInfo(pCrctInfo);
#endif

    /** @todo  In case of unsuccesful crtc config set  we have to revert frame buffer size and crtc sizes. */
    if (ret == Success)
        return true;
    else
        return false;
}

static XRRScreenSize currentSize()
{
    XRRScreenSize cSize;
    cSize.width = DisplayWidth(x11Context.pDisplay, x11Context.iDefaultScreen);
    cSize.mwidth = DisplayWidthMM(x11Context.pDisplay, x11Context.iDefaultScreen);
    cSize.height = DisplayHeight(x11Context.pDisplay, x11Context.iDefaultScreen);
    cSize.mheight = DisplayHeightMM(x11Context.pDisplay, x11Context.iDefaultScreen);
    return cSize;
}

static unsigned int computeDpi(unsigned int pixels, unsigned int mm)
{
   unsigned int dpi = 0;
   if (mm > 0)
      dpi = (unsigned int)((double)pixels * MILLIS_PER_INCH / (double)mm + 0.5);
   return dpi > 0 ? dpi : (unsigned int)DEFAULT_DPI;
}

static bool resizeFrameBuffer(struct RANDROUTPUT *paOutputs)
{
    unsigned int iXRes = 0;
    unsigned int iYRes = 0;
    /* Don't care about the output positions for now. */
    for (int i = 0; i < x11Context.hOutputCount; ++i)
    {
        if (!paOutputs[i].fEnabled)
            continue;
        iXRes += paOutputs[i].width;
        iYRes = iYRes < paOutputs[i].height ? paOutputs[i].height : iYRes;
    }
    XRRScreenSize cSize= currentSize();
    unsigned int xdpi = computeDpi(cSize.width, cSize.mwidth);
    unsigned int ydpi = computeDpi(cSize.height, cSize.mheight);
    unsigned int xmm;
    unsigned int ymm;
    xmm = (int)(MILLIS_PER_INCH * iXRes / ((double)xdpi) + 0.5);
    ymm = (int)(MILLIS_PER_INCH * iYRes / ((double)ydpi) + 0.5);
#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRSelectInput(x11Context.pDisplay, x11Context.rootWindow, RRScreenChangeNotifyMask);
    XRRSetScreenSize(x11Context.pDisplay, x11Context.rootWindow, iXRes, iYRes, xmm, ymm);
#else
    if (x11Context.pXRRSelectInput)
        x11Context.pXRRSelectInput(x11Context.pDisplay, x11Context.rootWindow, RRScreenChangeNotifyMask);
    if (x11Context.pXRRSetScreenSize)
        x11Context.pXRRSetScreenSize(x11Context.pDisplay, x11Context.rootWindow, iXRes, iYRes, xmm, ymm);
#endif
    XSync(x11Context.pDisplay, False);
    XEvent configEvent;
    bool event = false;
    while (XCheckTypedEvent(x11Context.pDisplay, RRScreenChangeNotify + x11Context.hRandREventBase, &configEvent))
    {
#ifdef WITH_DISTRO_XRAND_XINERAMA
        XRRUpdateConfiguration(&configEvent);
#else
        if (x11Context.pXRRUpdateConfiguration)
            x11Context.pXRRUpdateConfiguration(&configEvent);
#endif
        event = true;
    }
#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRSelectInput(x11Context.pDisplay, x11Context.rootWindow, 0);
#else
    if (x11Context.pXRRSelectInput)
        x11Context.pXRRSelectInput(x11Context.pDisplay, x11Context.rootWindow, 0);
#endif
    XRRScreenSize newSize = currentSize();

    /* On Solaris guest, new screen size is not reported properly despite
     * RRScreenChangeNotify event arrives. Hense, only check for event here.
     * Linux guests do report new size correctly. */
    if (   !event
#ifndef RT_OS_SOLARIS
        || newSize.width != (int)iXRes || newSize.height != (int)iYRes
#endif
       )
    {
        VBClLogError("Resizing frame buffer to %d %d has failed, current mode %d %d\n",
                     iXRes, iYRes, newSize.width, newSize.height);
        return false;
    }
    return true;
}

static XRRModeInfo *createMode(int iXRes, int iYRes)
{
    XRRModeInfo *pModeInfo = NULL;
    char sModeName[126];
    sprintf(sModeName, "%dx%d_vbox", iXRes, iYRes);
#ifdef WITH_DISTRO_XRAND_XINERAMA
    pModeInfo = XRRAllocModeInfo(sModeName, strlen(sModeName));
#else
    if (x11Context.pXRRAllocModeInfo)
        pModeInfo = x11Context.pXRRAllocModeInfo(sModeName, strlen(sModeName));
#endif
    pModeInfo->width = iXRes;
    pModeInfo->height = iYRes;

    DisplayModeR const mode = VBoxClient_xf86CVTMode(iXRes, iYRes, 60 /*VRefresh */, true /*Reduced */, false  /* Interlaced */);

    /* Convert kHz to Hz: f86CVTMode returns clock value in units of kHz,
     * XRRCreateMode will expect it in units of Hz. */
    pModeInfo->dotClock = mode.Clock * 1000;

    pModeInfo->hSyncStart = mode.HSyncStart;
    pModeInfo->hSyncEnd = mode.HSyncEnd;
    pModeInfo->hTotal = mode.HTotal;
    pModeInfo->hSkew = mode.HSkew;
    pModeInfo->vSyncStart = mode.VSyncStart;
    pModeInfo->vSyncEnd = mode.VSyncEnd;
    pModeInfo->vTotal = mode.VTotal;

    RRMode newMode = None;
#ifdef WITH_DISTRO_XRAND_XINERAMA
    newMode = XRRCreateMode(x11Context.pDisplay, x11Context.rootWindow, pModeInfo);
#else
    if (x11Context.pXRRCreateMode)
        newMode = x11Context.pXRRCreateMode(x11Context.pDisplay, x11Context.rootWindow, pModeInfo);
#endif
    if (newMode == None)
    {
#ifdef WITH_DISTRO_XRAND_XINERAMA
        XRRFreeModeInfo(pModeInfo);
#else
        if (x11Context.pXRRFreeModeInfo)
            x11Context.pXRRFreeModeInfo(pModeInfo);
#endif
        return NULL;
    }
    pModeInfo->id = newMode;
    return pModeInfo;
}

static bool configureOutput(int iOutputIndex, struct RANDROUTPUT *paOutputs)
{
    if (iOutputIndex >= x11Context.hOutputCount)
    {
        VBClLogError("Output index %d is greater than # of oputputs %d\n", iOutputIndex, x11Context.hOutputCount);
        return false;
    }

    AssertReturn(iOutputIndex >= 0, false);
    AssertReturn(iOutputIndex < VMW_MAX_HEADS, false);

    /* Remember the last instantiated display mode ID here. This mode will be replaced with the
     * new one on the next guest screen resize event. */
    static RRMode aPrevMode[VMW_MAX_HEADS];

    RROutput outputId = x11Context.pScreenResources->outputs[iOutputIndex];
    XRROutputInfo *pOutputInfo = NULL;
#ifdef WITH_DISTRO_XRAND_XINERAMA
    pOutputInfo = XRRGetOutputInfo(x11Context.pDisplay, x11Context.pScreenResources, outputId);
#else
    if (x11Context.pXRRGetOutputInfo)
        pOutputInfo = x11Context.pXRRGetOutputInfo(x11Context.pDisplay, x11Context.pScreenResources, outputId);
#endif
    if (!pOutputInfo)
        return false;
    XRRModeInfo *pModeInfo = NULL;
    bool fNewMode = false;
    /* Index of the mode within the XRRScreenResources.modes array. -1 if such a mode with required resolution does not exists*/
    int iModeIndex = findExistingModeIndex(paOutputs[iOutputIndex].width, paOutputs[iOutputIndex].height);
    if (iModeIndex != -1 && iModeIndex < x11Context.pScreenResources->nmode)
        pModeInfo = &(x11Context.pScreenResources->modes[iModeIndex]);
    else
    {
        /* A mode with required size was not found. Create a new one. */
        pModeInfo = createMode(paOutputs[iOutputIndex].width, paOutputs[iOutputIndex].height);
        VBClLogInfo("create mode %s (%u) on output %d\n", pModeInfo->name, pModeInfo->id, iOutputIndex);
        fNewMode = true;
    }
    if (!pModeInfo)
    {
        VBClLogError("Could not create mode for the resolution (%d, %d)\n",
                     paOutputs[iOutputIndex].width, paOutputs[iOutputIndex].height);
        return false;
    }

#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRAddOutputMode(x11Context.pDisplay, outputId, pModeInfo->id);
#else
    if (x11Context.pXRRAddOutputMode)
        x11Context.pXRRAddOutputMode(x11Context.pDisplay, outputId, pModeInfo->id);
#endif

    /* If mode has been newly created, destroy and forget mode created on previous guest screen resize event. */
    if (   aPrevMode[iOutputIndex] > 0
        && pModeInfo->id != aPrevMode[iOutputIndex]
        && fNewMode)
    {
        VBClLogInfo("removing unused mode %u from output %d\n", aPrevMode[iOutputIndex], iOutputIndex);
#ifdef WITH_DISTRO_XRAND_XINERAMA
        XRRDeleteOutputMode(x11Context.pDisplay, outputId, aPrevMode[iOutputIndex]);
        XRRDestroyMode(x11Context.pDisplay, aPrevMode[iOutputIndex]);
#else
        if (x11Context.pXRRDeleteOutputMode)
            x11Context.pXRRDeleteOutputMode(x11Context.pDisplay, outputId, aPrevMode[iOutputIndex]);
        if (x11Context.pXRRDestroyMode)
            x11Context.pXRRDestroyMode(x11Context.pDisplay, aPrevMode[iOutputIndex]);
#endif
        /* Forget destroyed mode. */
        aPrevMode[iOutputIndex] = 0;
    }

    /* Only cache modes created "by us". XRRDestroyMode will complain if provided mode
     * was not created by XRRCreateMode call. */
    if (fNewMode)
        aPrevMode[iOutputIndex] = pModeInfo->id;

    if (paOutputs[iOutputIndex].fPrimary)
    {
#ifdef WITH_DISTRO_XRAND_XINERAMA
        XRRSetOutputPrimary(x11Context.pDisplay, x11Context.rootWindow, outputId);
#else
        if (x11Context.pXRRSetOutputPrimary)
            x11Context.pXRRSetOutputPrimary(x11Context.pDisplay, x11Context.rootWindow, outputId);
#endif
    }

    /* Make sure outputs crtc is set. */
    pOutputInfo->crtc = pOutputInfo->crtcs[0];

    RRCrtc crtcId = pOutputInfo->crtcs[0];
    Status ret = Success;
#ifdef WITH_DISTRO_XRAND_XINERAMA
    ret = XRRSetCrtcConfig(x11Context.pDisplay, x11Context.pScreenResources, crtcId, CurrentTime,
                           paOutputs[iOutputIndex].x, paOutputs[iOutputIndex].y,
                           pModeInfo->id, RR_Rotate_0, &(outputId), 1 /*int noutputs*/);
#else
    if (x11Context.pXRRSetCrtcConfig)
        ret = x11Context.pXRRSetCrtcConfig(x11Context.pDisplay, x11Context.pScreenResources, crtcId, CurrentTime,
                                           paOutputs[iOutputIndex].x, paOutputs[iOutputIndex].y,
                                           pModeInfo->id, RR_Rotate_0, &(outputId), 1 /*int noutputs*/);
#endif
    if (ret != Success)
        VBClLogError("crtc set config failed for output %d\n", iOutputIndex);

#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRFreeOutputInfo(pOutputInfo);
#else
    if (x11Context.pXRRFreeOutputInfo)
        x11Context.pXRRFreeOutputInfo(pOutputInfo);
#endif

    if (fNewMode)
    {
#ifdef WITH_DISTRO_XRAND_XINERAMA
        XRRFreeModeInfo(pModeInfo);
#else
        if (x11Context.pXRRFreeModeInfo)
            x11Context.pXRRFreeModeInfo(pModeInfo);
#endif
    }
    return true;
}

/** Construct the xrandr command which sets the whole monitor topology each time. */
static void setXrandrTopology(struct RANDROUTPUT *paOutputs)
{
    if (!x11Context.pDisplay)
    {
        VBClLogInfo("not connected to X11\n");
        return;
    }

    XGrabServer(x11Context.pDisplay);
    if (x11Context.fWmwareCtrlExtention)
        callVMWCTRL(paOutputs);

#ifdef WITH_DISTRO_XRAND_XINERAMA
    x11Context.pScreenResources = XRRGetScreenResources(x11Context.pDisplay, x11Context.rootWindow);
#else
    if (x11Context.pXRRGetScreenResources)
        x11Context.pScreenResources = x11Context.pXRRGetScreenResources(x11Context.pDisplay, x11Context.rootWindow);
#endif

    x11Context.hOutputCount = RT_VALID_PTR(x11Context.pScreenResources) ? determineOutputCount() : 0;
    if (!x11Context.pScreenResources)
    {
        XUngrabServer(x11Context.pDisplay);
        XFlush(x11Context.pDisplay);
        return;
    }

    /* Disable crtcs. */
    for (int i = 0; i < x11Context.pScreenResources->noutput; ++i)
    {
        XRROutputInfo *pOutputInfo = NULL;
#ifdef WITH_DISTRO_XRAND_XINERAMA
        pOutputInfo = XRRGetOutputInfo(x11Context.pDisplay, x11Context.pScreenResources, x11Context.pScreenResources->outputs[i]);
#else
        if (x11Context.pXRRGetOutputInfo)
            pOutputInfo = x11Context.pXRRGetOutputInfo(x11Context.pDisplay, x11Context.pScreenResources, x11Context.pScreenResources->outputs[i]);
#endif
        if (!pOutputInfo)
            continue;
        if (pOutputInfo->crtc == None)
            continue;

        if (!disableCRTC(pOutputInfo->crtc))
        {
            VBClLogFatalError("Crtc disable failed %lu\n", pOutputInfo->crtc);
            XUngrabServer(x11Context.pDisplay);
            XSync(x11Context.pDisplay, False);
#ifdef WITH_DISTRO_XRAND_XINERAMA
            XRRFreeScreenResources(x11Context.pScreenResources);
#else
            if (x11Context.pXRRFreeScreenResources)
                x11Context.pXRRFreeScreenResources(x11Context.pScreenResources);
#endif
            XFlush(x11Context.pDisplay);
            return;
        }
#ifdef WITH_DISTRO_XRAND_XINERAMA
        XRRFreeOutputInfo(pOutputInfo);
#else
        if (x11Context.pXRRFreeOutputInfo)
            x11Context.pXRRFreeOutputInfo(pOutputInfo);
#endif
    }
    /* Resize the frame buffer. */
    if (!resizeFrameBuffer(paOutputs))
    {
        XUngrabServer(x11Context.pDisplay);
        XSync(x11Context.pDisplay, False);
#ifdef WITH_DISTRO_XRAND_XINERAMA
        XRRFreeScreenResources(x11Context.pScreenResources);
#else
        if (x11Context.pXRRFreeScreenResources)
            x11Context.pXRRFreeScreenResources(x11Context.pScreenResources);
#endif
        XFlush(x11Context.pDisplay);
        return;
    }

    /* Configure the outputs. */
    for (int i = 0; i < x11Context.hOutputCount; ++i)
    {
        /* be paranoid. */
        if (i >= x11Context.pScreenResources->noutput)
            break;
        if (!paOutputs[i].fEnabled)
            continue;
        if (configureOutput(i, paOutputs))
            VBClLogInfo("output[%d] successfully configured\n", i);
        else
            VBClLogError("failed to configure output[%d]\n", i);
    }
    XSync(x11Context.pDisplay, False);
#ifdef WITH_DISTRO_XRAND_XINERAMA
    XRRFreeScreenResources(x11Context.pScreenResources);
#else
    if (x11Context.pXRRFreeScreenResources)
        x11Context.pXRRFreeScreenResources(x11Context.pScreenResources);
#endif
    XUngrabServer(x11Context.pDisplay);
    XFlush(x11Context.pDisplay);
}

/**
 * @interface_method_impl{VBCLSERVICE,pfnWorker}
 */
static DECLCALLBACK(int) vbclSVGAWorker(bool volatile *pfShutdown)
{
    /* Do not acknowledge the first event we query for to pick up old events,
     * e.g. from before a guest reboot. */
    bool fAck = false;
    bool fFirstRun = true;
    static struct VMMDevDisplayDef aMonitors[VMW_MAX_HEADS];

    int rc = VbglR3CtlFilterMask(VMMDEV_EVENT_DISPLAY_CHANGE_REQUEST, 0);
    if (RT_FAILURE(rc))
        VBClLogFatalError("Failed to request display change events, rc=%Rrc\n", rc);
    rc = VbglR3AcquireGuestCaps(VMMDEV_GUEST_SUPPORTS_GRAPHICS, 0, false);
    if (RT_FAILURE(rc))
        VBClLogFatalError("Failed to register resizing support, rc=%Rrc\n", rc);
    if (rc == VERR_RESOURCE_BUSY)  /* Someone else has already acquired it. */
        return VERR_RESOURCE_BUSY;

    /* Let the main thread know that it can continue spawning services. */
    RTThreadUserSignal(RTThreadSelf());

    for (;;)
    {
        struct VMMDevDisplayDef aDisplays[VMW_MAX_HEADS];
        uint32_t cDisplaysOut;
        /* Query the first size without waiting.  This lets us e.g. pick up
         * the last event before a guest reboot when we start again after. */
        rc = VbglR3GetDisplayChangeRequestMulti(VMW_MAX_HEADS, &cDisplaysOut, aDisplays, fAck);
        fAck = true;
        if (RT_FAILURE(rc))
            VBClLogError("Failed to get display change request, rc=%Rrc\n", rc);
        if (cDisplaysOut > VMW_MAX_HEADS)
            VBClLogError("Display change request contained, rc=%Rrc\n", rc);
        if (cDisplaysOut > 0)
        {
            for (unsigned i = 0; i < cDisplaysOut && i < VMW_MAX_HEADS; ++i)
            {
                uint32_t idDisplay = aDisplays[i].idDisplay;
                if (idDisplay >= VMW_MAX_HEADS)
                    continue;
                aMonitors[idDisplay].fDisplayFlags = aDisplays[i].fDisplayFlags;
                if (!(aDisplays[i].fDisplayFlags & VMMDEV_DISPLAY_DISABLED))
                {
                    if (idDisplay == 0 || (aDisplays[i].fDisplayFlags & VMMDEV_DISPLAY_ORIGIN))
                    {
                        aMonitors[idDisplay].xOrigin = aDisplays[i].xOrigin;
                        aMonitors[idDisplay].yOrigin = aDisplays[i].yOrigin;
                    } else {
                        aMonitors[idDisplay].xOrigin = aMonitors[idDisplay - 1].xOrigin + aMonitors[idDisplay - 1].cx;
                        aMonitors[idDisplay].yOrigin = aMonitors[idDisplay - 1].yOrigin;
                    }
                    aMonitors[idDisplay].cx = aDisplays[i].cx;
                    aMonitors[idDisplay].cy = aDisplays[i].cy;
                }
            }
            /* Create a whole topology and send it to xrandr. */
            struct RANDROUTPUT aOutputs[VMW_MAX_HEADS];
            int iRunningX = 0;
            for (int j = 0; j < x11Context.hOutputCount; ++j)
            {
                aOutputs[j].x = iRunningX;
                aOutputs[j].y = aMonitors[j].yOrigin;
                aOutputs[j].width = aMonitors[j].cx;
                aOutputs[j].height = aMonitors[j].cy;
                aOutputs[j].fEnabled = !(aMonitors[j].fDisplayFlags & VMMDEV_DISPLAY_DISABLED);
                aOutputs[j].fPrimary = (aMonitors[j].fDisplayFlags & VMMDEV_DISPLAY_PRIMARY);
                if (aOutputs[j].fEnabled)
                    iRunningX += aOutputs[j].width;
            }
            /* In 32-bit guests GAs build on our release machines causes an xserver lock during vmware_ctrl extention
               if we do the call withing XGrab. We make the call the said extension only once (to connect the outputs)
               rather than at each resize iteration. */
#if ARCH_BITS == 32
            if (fFirstRun)
                callVMWCTRL(aOutputs);
#endif
            setXrandrTopology(aOutputs);
            /* Wait for some seconds and set toplogy again after the boot. In some desktop environments (cinnamon) where
               DE get into our resizing our first resize is reverted by the DE. Sleeping for some secs. helps. Setting
               topology a 2nd time resolves the black screen I get after resizing.*/
            if (fFirstRun)
            {
                sleep(4);
                setXrandrTopology(aOutputs);
                fFirstRun = false;
            }
        }
        uint32_t events;
        do
        {
            rc = VbglR3WaitEvent(VMMDEV_EVENT_DISPLAY_CHANGE_REQUEST, VBOX_SVGA_HOST_EVENT_RX_TIMEOUT_MS, &events);
        } while (rc == VERR_TIMEOUT && !ASMAtomicReadBool(pfShutdown));

        if (ASMAtomicReadBool(pfShutdown))
        {
            /* Shutdown requested. */
            break;
        }
        else if (RT_FAILURE(rc))
        {
            VBClLogFatalError("Failure waiting for event, rc=%Rrc\n", rc);
        }

    };

    return VINF_SUCCESS;
}

VBCLSERVICE g_SvcDisplaySVGA =
{
    "dp-svga-x11",                      /* szName */
    "SVGA X11 display",                 /* pszDescription */
    ".vboxclient-display-svga-x11",     /* pszPidFilePathTemplate */
    NULL,                               /* pszUsage */
    NULL,                               /* pszOptions */
    NULL,                               /* pfnOption */
    vbclSVGAInit,                       /* pfnInit */
    vbclSVGAWorker,                     /* pfnWorker */
    vbclSVGAStop,                       /* pfnStop*/
    NULL                                /* pfnTerm */
};