Что такое xorg в linux
Что такое xorg в linux
The X.Org project provides an open source implementation of the X Window System. The development work is being done in conjunction with the freedesktop.org community. The X.Org Foundation is the educational non-profit corporation whose Board serves this effort, and whose Members lead this work.
Xorg (commonly referred to as simply X) is the most popular display server among Linux users. Its ubiquity has led to making it an ever-present requisite for GUI applications, resulting in massive adoption from most distributions. See the Xorg Wikipedia article or visit the Xorg website for more details.
For the alternative and potential successor, see Wayland.
Contents
Installation
Xorg can be installed with the xorg-server package.
Additionally, some packages from the xorg-apps group are necessary for certain configuration tasks. They are pointed out in the relevant sections.
Finally, an xorg group is also available, which includes Xorg server packages, packages from the xorg-apps group and fonts.
Driver installation
The Linux kernel includes open-source video drivers and support for hardware accelerated framebuffers. However, userland support is required for OpenGL and 2D acceleration in X11.
First, identify the graphics card (the Subsystem output shows the specific model):
Then, install an appropriate driver. You can search the package database for a complete list of open-source video drivers:
Xorg searches for installed drivers automatically:
In order for video acceleration to work, and often to expose all the modes that the GPU can set, a proper video driver is required:
Brand | Type | Driver | OpenGL | OpenGL (multilib) | Documentation |
---|---|---|---|---|---|
AMD / ATI | Open source | xf86-video-amdgpu | mesa | lib32-mesa | AMDGPU |
xf86-video-ati | ATI | ||||
Proprietary | xf86-video-amdgpu | amdgpu-pro-libgl AUR | lib32-amdgpu-pro-libgl AUR | AMDGPU PRO | |
Intel | Open source | xf86-video-intel | mesa | lib32-mesa | Intel graphics |
NVIDIA | Open source | xf86-video-nouveau | mesa | lib32-mesa | Nouveau |
Proprietary | nvidia | nvidia-utils | lib32-nvidia-utils | NVIDIA | |
nvidia-470xx-dkms AUR | nvidia-470xx-utils AUR | lib32-nvidia-470xx-utils AUR | |||
nvidia-390xx AUR | nvidia-390xx-utils AUR | lib32-nvidia-390xx-utils AUR |
Other video drivers can be found in the xorg-drivers group.
Xorg should run smoothly without closed source drivers, which are typically needed only for advanced features such as fast 3D-accelerated rendering for games. The exceptions to this rule are recent GPUs (especially NVIDIA GPUs) not supported by open source drivers.
For a translation of model names (e.g. Radeon RX 6800) to GPU architectures (e.g. RDNA 2), see wikipedia:List of AMD graphics processing units.
GPU architecture | Open-source driver | Proprietary driver |
---|---|---|
RDNA, RDNA 2 | AMDGPU | AMDGPU PRO |
GCN 3, GCN 4, GCN 5 | ||
GCN 1, GCN 2 | AMDGPU* / ATI | not available |
TeraScale and older | ATI | not available |
*: Experimental
Running
The Xorg(1) command is usually not run directly. Instead, the X server is started with either a display manager or xinit.
Configuration
Using xorg.conf
Alternatively, your proprietary video card drivers may come with a tool to automatically configure Xorg: see the article of your video driver, NVIDIA or AMDGPU PRO, for more details.
Input devices
For input devices the X server defaults to the libinput driver ( xf86-input-libinput ), but xf86-input-evdev and related drivers are available as alternative.[1]
Udev, which is provided as a systemd dependency, will detect hardware and both drivers will act as hotplugging input driver for almost all devices, as defined in the default configuration files 10-quirks.conf and 40-libinput.conf in the /usr/share/X11/xorg.conf.d/ directory.
After starting X server, the log file will show which driver hotplugged for the individual devices (note the most recent log file name may vary):
If both do not support a particular device, install the needed driver from the xorg-drivers group. The same applies, if you want to use another driver.
To influence hotplugging, see #Configuration.
For specific instructions, see also the libinput article, the following pages below, or Fedora:Input device configuration for more examples.
Input identification
Mouse acceleration
Extra mouse buttons
Touchpad
Touchscreen
Keyboard settings
Monitor settings
Manual configuration
For a headless configuration, the xf86-video-dummy driver is necessary; install it and create a configuration file, such as the following:
Multiple monitors
See main article Multihead for general information.
See also GPU-specific instructions:
More than one graphics card
You must define the correct driver to use and put the bus ID of your graphic cards (in decimal notation).
To get your bus IDs (in hexadecimal):
The bus IDs here are 0:2:0 and 1:0:0.
Display size and DPI
The factual accuracy of this article or section is disputed.
The DPI of the X server is determined in the following manner:
In order to get correct dots per inch (DPI) set, the display size must be recognized or set. Having the correct DPI is especially necessary where fine detail is required (like font rendering). Previously, manufacturers tried to create a standard for 96 DPI (a 10.3″ diagonal monitor would be 800×600, a 13.2″ monitor 1024×768). These days, screen DPIs vary and may not be equal horizontally and vertically. For example, a 19″ widescreen LCD at 1440×900 may have a DPI of 89×87. To be able to set the DPI, the Xorg server attempts to auto-detect your monitor’s physical screen size through the graphic card with DDC. When the Xorg server knows the physical screen size, it will be able to set the correct DPI depending on resolution size.
To see if your display size and DPI are detected/calculated correctly:
Check that the dimensions match your display size. If the Xorg server is not able to correctly calculate the screen size, it will default to 75×75 DPI and you will have to calculate it yourself.
If you have specifications on the physical size of the screen, they can be entered in the Xorg configuration file so that the proper DPI is calculated (adjust identifier to your xrandr output) :
If you only want to enter the specification of your monitor without creating a full xorg.conf create a new config file. For example ( /etc/X11/xorg.conf.d/90-monitor.conf ):
If you do not have specifications for physical screen width and height (most specifications these days only list by diagonal size), you can use the monitor’s native resolution (or aspect ratio) and diagonal length to calculate the horizontal and vertical physical dimensions. Using the Pythagorean theorem on a 13.3″ diagonal length screen with a 1280×800 native resolution (or 16:10 aspect ratio):
This will give the pixel diagonal length and with this value you can discover the physical horizontal and vertical lengths (and convert them to millimeters):
Setting DPI manually
For RandR compliant drivers (for example the open source ATI driver), you can set it by:
Proprietary NVIDIA driver
You can manually set the DPI by adding the option under the Device or Screen section:
Manual DPI Setting Caveat
With GTK library versions since 3.16, when this variable is not otherwise explicitly set, GTK sets it to 96. To have GTK apps obey the server DPI you may need to explictly set Xft.dpi to the same value as the server. The Xft.dpi resource is the method by which some desktop environments optionally force DPI to a particular value in personal settings. Among these are KDE and TDE.
Display Power Management
DPMS (Display Power Management Signaling) is a technology that allows power saving behaviour of monitors when the computer is not in use. This will allow you to have your monitors automatically go into standby after a predefined period of time.
Composite
The Composite extension for X causes an entire sub-tree of the window hierarchy to be rendered to an off-screen buffer. Applications can then take the contents of that buffer and do whatever they like. The off-screen buffer can be automatically merged into the parent window, or merged by external programs called compositing managers. For more information, see Wikipedia:Compositing window manager.
Some window managers (e.g. Compiz, Enlightenment, KWin, Marco, Metacity, Muffin, Mutter, Xfwm) do compositing on their own. For other window managers, a standalone composite manager can be used.
List of composite managers
Tips and tricks
This article or section needs expansion.
Automation
This section lists utilities for automating keyboard / mouse input and window operations (like moving, resizing or raising).
Nested X session
This article or section needs expansion.
To run a nested session of another desktop environment:
This will launch a Window Maker session in a 1024 by 768 window within your current X session.
This needs the package xorg-server-xnest to be installed.
Starting GUI programs remotely
On-demand disabling and enabling of input sources
With the help of xinput you can temporarily disable or enable input sources. This might be useful, for example, on systems that have more than one mouse, such as the ThinkPads and you would rather use just one to avoid unwanted mouse clicks.
Find the name or ID of the device you want to disable:
For example in a Lenovo ThinkPad T500, the output looks like this:
To re-enable the device, just issue the opposite command:
Alternatively using the device name, the command to disable the touchpad would be:
Killing application with hotkey
Run script on hotkey:
Block TTY access
This article or section needs expansion.
To block tty access when in an X add the following to xorg.conf:
Prevent a user from killing X
To prevent a user from killing when it is running add the following to xorg.conf:
Rootless Xorg
Xorg may run with standard user privileges instead of root (so-called «rootless» Xorg). This is a significant security improvement over running as root. Note that most display managers do not support rootless Xorg.
Using xinitrc
To configure rootless Xorg using xinitrc:
Using GDM
GDM will run Xorg without root privileges by default when kernel mode setting is used.
Session log redirection
When Xorg is run in rootless mode, Xorg logs are saved to
Alternatively, copy /etc/X11/xinit/xserverrc to
Troubleshooting
General
If a problem occurs, view the log stored in either /var/log/ or, for the rootless X default since v1.16, in
Black screen, No protocol specified. Resource temporarily unavailable for all or some users
X creates configuration and temporary files in current user’s home directory. Make sure there is free disk space available on the partition your home directory resides in. Unfortunately, X server does not provide any more obvious information about lack of disk space in this case.
DRI with Matrox cards stopped working
If you use a Matrox card and DRI stopped working after upgrading to Xorg, try adding the line:
Frame-buffer mode problems
X fails to start with the following log messages:
Program requests «font ‘(null)'»
and use what is closer to the shown value.
Recovery: disabling Xorg before GUI login
If Xorg is set to boot up automatically and for some reason you need to prevent it from starting up before the login/display manager appears (if the system is wrongly configured and Xorg does not recognize your mouse or keyboard input, for instance), you can accomplish this task with two methods.
Depending on setup, you will need to do one or more of these steps:
/.xinitrc or comment out the exec line in it.
X clients started with «su» fail
If you are getting «Client is not authorized to connect to server», try adding the line:
X failed to start: Keyboard initialization failed
If the filesystem (specifically /tmp ) is full, startx will fail. /var/log/Xorg.0.log will end with:
Make some free space on the relevant filesystem and X will start.
A green screen whenever trying to watch a video
Your color depth is set wrong. It may need to be 24 instead of 16, for example.
SocketCreateListener error
Invalid MIT-MAGIC-COOKIE-1 key when trying to run a program as root
That error means that only the current user has access to the X server. The solution is to give access to root:
That line can also be used to give access to X to a different user than root.
Xorg-server Fatal server error: (EE) AddScreen/ScreenInit
If the Xorg server is not working randomly and in the Xorg log you see:
Then, this problem may be caused by systemd issue 13943. Set up early KMS start.
Ubuntu Wiki
Настройка Xorg
Сохраните ваш конфигурационный файл
Помните, что автоопределение устройств желательно проводить при незапущенном Xorg.
Остановите Xorg
Запустите процесс автонастройки Xorg
Запустите Gnome/KDE
Как отредактировать конфигурационный файл (xorg.conf) вручную
Запустите в терминале или консоли:
Вызов справки в nano: Ctrl+g (Ctrl+x выход)
Где находится файл журнала, как произвести отладку? File:
содержит массу бесценной отладочной информации о том, что происходит, когда запускается Xorg. Найдите строки, содержащие EE (errors) и WW (warnings).
How to edit or add HorizSync and VertRefresh lines Find your monitors manual (manufacturers website and Google are useful). Look for hozizontal sync and vertical refresh rates, also if bandwidth or maximum dot clock / pixel clock is mentioned, write it down.
Edit xorg.conf and put correct values to your xconf.org’s Monitor section. Something like this:
Be sure that Identifier is same as the Monitor line in Screen section.
Copy paste the new Modeline to Monitor section (for example):
Now you can select the default resolution and colordepth by tweaking the Screen section. It should look something like this:
Starting the X: startx OR sudo /etc/init.d/gdm start (in KDE it’s kdm)
If that doesn’t work, try fixing the xorg.conf or get back to your original by copying the backup over your changed one with:
When you’re back in X, you can cycle through different modes by pressing CTRL+ALT++ (plus sign on numpad), or go to System->Preferences->Screen Resolution.
How to adjust position of your screen? open terminal(Applications->Accessories->Terminal), run xvidtune (type: «xvidtune»), adjust the screen and hit Show-button. You’ll see a line with something like this on the terminal screen:
In Monitor section, add the above line with a prefix «Modeline», like this:
That should do it. There should be no need to restart X if you did make the change (hit Apply in xvidtune), but you should test that this new change works. Hit ctrl+alt+backspace to restart X. If it doesn’t work, you can copy back the old configuration file using:
and restart X using:
Problems? Things to try:
Miscellaneous resources (may contain outdated information)
Laptop with Intel graphics and widescreen http://ubuntuforums.org/showthread.php?t=351647
Xorg (Русский)
Проект X.Org представляет свободную реализацию оконной системы X с открытым исходным кодом. Разработка осуществляется X.Org Foundation, которая является образовательной некоммерческой организацией, совместно с сообществом freedesktop.org.
Xorg (обычно называемый просто X) очень популярен среди пользователей Linux, что привело к тому, что большинство приложений с графическим интерфейсом используют X11, из-за этого Xorg доступен в большинстве дистрибутивов. Для более подробной информации смотрите статью Xorg в Википедии или посетите веб-сайт Xorg.
Contents
Установка
В дополнение к нему, могут понадобиться пакеты из группы xorg-apps для некоторых способов настроек. О них рассказано в соответствующих разделах.
Установка драйвера
Ядро Linux включает в себя видеодрайверы с открытым исходным кодом и поддержку аппаратного ускорения буфера кадров. Однако, для работы OpenGL и двухмерного ускорения в X11 требуется поддержка пользовательского ПО.
Сперва определите вашу видеокарту:
Затем установите соответствующий драйвер. Вы можете поискать в базе данных пакетов полный список видеодрайверов с открытым исходным кодом:
Xorg автоматически ищет установленные драйверы:
Для того, чтобы ускорение видео работало, и часто для того, чтобы разблокировать все режимы, в которых может работать GPU, требуется правильный видеодрайвер:
Бренд | Тип | Драйвер | OpenGL | OpenGL (multilib) | Документация |
---|---|---|---|---|---|
AMD / ATI | Свободный | xf86-video-amdgpu | mesa | lib32-mesa | AMDGPU (Русский) |
xf86-video-ati | ATI (Русский) | ||||
Intel | Свободный | xf86-video-intel | mesa | lib32-mesa | Intel graphics (Русский) |
NVIDIA | Свободный | xf86-video-nouveau | mesa | lib32-mesa | Nouveau (Русский) |
Проприетарный | nvidia | nvidia-utils | lib32-nvidia-utils | NVIDIA (Русский) | |
nvidia-390xx AUR | nvidia-390xx-utils AUR | lib32-nvidia-390xx-utils AUR |
Во избежание проблем X следует запускать без драйверов с закрытым исходным кодом, которые обычно требуются только для расширенных возможностей, таких, как быстрый 3D рендеринг в играх. Исключением из этого правила являются недавние графические процессоры (особенно видеокарты NVIDIA), которые не поддерживаются драйверами с открытым исходным кодом.
Запуск
Команду Xorg(1) обычно не используют для запуска. Вместо этого оконный сервер X запускают с помощью экранного менеджера или xinit.
Настройка
Смотрите примеры настройки на вики Fedora.
Через файл xorg.conf
Кроме того, ваш проприетарный видеодрайвер может поставляться с инструментом для автоматической настройки Xorg: смотрите статьи NVIDIA (Русский) или AMDGPU (Русский) для подробностей.
Устройства ввода
Для устройств ввода в X по умолчанию используют драйвер libinput ( xf86-input-libinput ), но также можно использовать драйвер xf86-input-evdev и другие соответствующие драйверы.[1]
После запуска оконной системы X, в лог-файле будет записываться информация об используемом драйвере для каждого подключенного устройства (обратите внимание, что имя последнего лог-файла может отличаться):
Чтобы изменить поведение горячего подключения (hotplugging), смотрите статью #Настройка.
Для получения конкретных инструкций, смотрите статью libinput, следующие страницы ниже, или записи в википедии Fedora.
Идентификация ввода
Для получения дополнительной информации смотрите Keyboard input#Identifying keycodes in Xorg.
Ускорение мыши
Дополнительные кнопки мыши
Тачпад
Тачскрин
Настройка клавиатуры
Настройка монитора
Ручная настройка
Несколько мониторов
Смотрите главную статью Multihead для получения общей информации.
Также смотрите специфичные инструкции для GPU:
Более одной видеокарты
Вы должны определить нужный драйвер для использования и ввести ID шины (bus ID) нужной видеокарты.
Чтобы узнать ID шины:
Размер дисплея/DPI
The factual accuracy of this article or section is disputed.
DPI оконной системы X устанавливается следующими способами:
Чтобы убедиться, что разрешение вашего дисплея и DPI обнаружены/правильно рассчитаны:
Убедитесь, что выведенное разрешение соответствует настоящему разрешению вашего монитора. Если Xorg не может правильно рассчитать разрешение экрана, он по умолчанию установит значение 75×75 DPI. Поэтому вам придется самому рассчитать его.
Если у вас есть в спецификации физическое разрешение экрана, его можно ввести в конфигурационный файл Xorg так, чтобы был рассчитан правильный DPI (регулируете идентификатор для вашего вывода xrandr):
Если вы только хотите ввести спецификацию вашего монитора без создания полного xorg.conf, тогда создайте новый конфигурационный файл. Например, ( /etc/X11/xorg.conf.d/90-monitor.conf ):
Если у вас нет в спецификации ширины и высоты монитора (сейчас в большинстве спецификаций указывается только размер диагонали), вы можете использовать родное разрешение монитора (или соотношение сторон) и размер диагонали для вычисления горизонтальных и вертикальных размеров. Используя теорему Пифагора для монитора с диагональю 13,3″ и с родным разрешением 1280×800 (или соотношением сторон 16:10):
Вы получите размер диагонали в пикселях. С помощью него можно узнать ширину и высоту монитора в дюймах (а затем перевести их в миллиметры):
Настройка DPI вручную
Для RandR-совместимых драйверов (например, драйвер ATI с открытым исходным кодом) вы можете установить dpi так:
Чтобы сделать его постоянным, посмотрите запуск команд после запуска X.
Проприетарный драйвер NVIDIA
DPI можно установить вручную, если планируется использование только одного разрешения экрана (калькулятор DPI):
Вы можете установить DPI вручную, добавив параметры ниже в /etc/X11/xorg.conf.d/20-nvidia.conf (внутри раздела Device):
Предостережение о ручной настройке DPI
Начиная с версии GTK 3.16, если эта переменная явно не задана, GTK задаёт ей значение 96. Чтобы приложения GTK работали с DPI сервера, потребуется явно задать Xft.dpi то же значение, что и у сервера. Также некоторые среды рабочего стола опционально приводят DPI к определенному значению в своих настройках с помощью файла ресурсов Xft.dpi. Среди них KDE (Русский) и TDE.
Управление питанием дисплея
DPMS (Display Power Management Signaling (англ), сигналы управления энергопотреблением дисплеев) — технология, позволяющая настроить энергосбережение монитора, когда компьютер не используется. Она позволит вам автоматически переключить монитор в режим ожидания через определенное время простоя.
Композит
Композитное расширение для X приводит к вынесению всего поддерева иерархии окон в буфер вне экрана. Затем приложения могут загружать содержимое этого буфера и делать все, что им нравится. Закадровый буфер может автоматически объединяться в родительское окно или объединяться внешними программами, называемыми композитными менеджерами. Для получения дополнительной информации смотрите следующую статью: w:ru:Композитный менеджер окон
Некоторые оконные менеджеры (например, Compiz, Enlightenment, KWin, Marco, Metacity, Muffin, Mutter, Xfwm) имеют встроенный композит. Для других оконных менеджеров можно использовать отдельные композитные менеджеры.
Список композитных менеджеров
Советы и рекомендации
This article or section needs expansion.
Автоматизация
В этом разделе перечислены утилиты для автоматизации операций с окнами (например, перемещение, изменение размера или фокусировка), ввода/вывода клавиатуры и мыши.
Вложенная X-сессия
This article or section needs expansion.
Для запуска вложенного сеанса другой среды рабочего стола:
Это запустит сеанс Window Maker в окне 1024 на 768 в рамках текущей X-сессии.
Запуск программ с GUI удаленно
Отключение и включение при необходимости устройств ввода
С помощью xinput вы можете временно отключить или включить устройства ввода. Это полезно, например, на системах, имеющих несколько мышек, таких как ThinkPads и, если вам хотелось бы использовать только одну, чтобы избежать нежелательные нажатия.
Найдите имя или ID устройства, которое вы хотите отключить:
Например для ноутбука Lenovo ThinkPad T500 вывод выглядит следующим образом:
Чтобы снова включить устройство, просто выполните противоположную команду:
Так выглядит команда для выключения устройства (здесь тачпада) через его имя:
Закрытие приложения с помощью горячей клавиши
Привяжите скрипт к горячей клавише:
Блокирование доступа к TTY
This article or section needs expansion.
Чтобы запретить доступ к tty в X, добавьте следующее в файл xorg.conf:
Запрет пользователю закрывать, перезапускать X
Чтобы запретить пользователю закрывать, перезапускать запущенный Xorg, добавьте следующее в файл xorg.conf:
Использование Xorg без прав суперпользователя
Если вам не удовлетворяют эти требования, повторно включите права суперпользователя в /etc/X11/Xwrapper.config :
Также GDM запускает Xorg без привилегий суперпользователя по умолчанию, когда используется KMS.
Неработающее перенаправление
Пока журналы пользователя Xorg хранятся в
Или скопируйте /etc/X11/xinit/xserverrc в
Решение проблем
Общее
Если произошла какая-то проблема с X, посмотрите лог (журнал), хранящийся в /var/log/ или для пользователей без рут-доступа в
/.local/share/xorg/ (по умолчанию с версии 1.16). Пользователям GDM следует проверить журнал systemd. [6]
Черный экран, протокол не указан. Ресурс временно недоступен для всех или некоторых пользователей
X создает конфигурационные и временные файлы в текущем домашнем каталоге пользователя. Убедитесь в наличии свободного места на разделе, в котором находится домашний каталог. К сожаления, X сервер в этом случае не представляет очевидную информацию о недостатке места.
DRI с картами Matrox перестает работать
Если вы используете карту Matrox и DRI перестал работать после обновления Xorg, попробуйте добавить строку:
Проблемы с режимом Фреймбуфер
Если X не запускается со следующим сообщением в журнале,
Программа требует «font ‘(null)'»
и используйте тот шрифт, у которого dpi ближе к показанному значению.
Восстановление: отключение Xorg перед входом в GUI
Если Xorg настроен на автозапуск и по какой-то причине вам нужно предотвратить его запуск до менеджера входа/экранного менеджера (например, если ваша система неправильно настроена и Xorg не распознает ввод с помощью мыши или клавиатуры), вы можете решить эту задачу двумя способами.
В зависимости от настройки, вам необходимо выполнить один или более шагов:
/.xinitrc или закомментируйте линии с exec в нем.
Клиент X запускается с ошибкой «su»
Если вы получаете сообщение «Client is not authorized to connect to server» (Клиент не авторизован для подключения к серверу), попробуйте добавить строку:
Не удалось запустить X: Ошибка инициализация клавиатуры
Если файловая система (в частности /tmp ) заполнена, startx не запустится. В конце журнала /var/log/Xorg.0.log будет:
Освободите место на соответствующей файловой системе, и X сервер запустится.
Зеленый экран при попытке просмотра видео
У вас неправильно установлена цветовая глубина. Например, требуется 24 вместо 16.
Ошибка SocketCreateListener
Неверный ключ MIT-MAGIC-COOKIE-1 при попытке запустить программу от суперпользователя
Эта ошибка означает, что только текущий пользователь имеет доступ к X-серверу. Решение состоит в том, чтобы предоставить доступ для суперпользователя:
Эта строка также может быть использована для предоставления доступа к X другому пользователю, нежели root.
Фатальная ошибка сервера: (EE) AddScreen/ScreenInit
Если Xorg-server не работает случайным образом и в логе Xorg вы видите:
Тогда, эта пробелема может быть вызвано проблемой systemd #134943. настройте Ранний запуск KMS.