Что такое xorg в linux
Перейти к содержимому

Что такое xorg в linux

  • автор:

DESCRIPTION¶

This work was derived by the X.Org Foundation from the XFree86 Project's XFree86 4.4rc2 release. The XFree86 release was originally derived from X386 1.2 by Thomas Roell which was contributed to X11R5 by Snitily Graphics Consulting Service.

PLATFORMS¶

NETWORK CONNECTIONS¶

OPTIONS¶

In addition to the normal server options described in the Xserver(1) manual page, Xorg accepts the following command line switches:

vtXX XX specifies the Virtual Terminal device number which Xorg will use. Without this option, Xorg will pick the first available Virtual Terminal that it can locate. This option applies only to platforms that have virtual terminal support, such as Linux, BSD, OpenSolaris, SVR3, and SVR4. -allowMouseOpenFail Allow the server to start up even if the mouse device can't be opened or initialised. This is equivalent to the AllowMouseOpenFail xorg.conf(5) file option. -allowNonLocalXvidtune Make the VidMode extension available to remote clients. This allows the xvidtune client to connect from another host. This is equivalent to the AllowNonLocalXvidtune xorg.conf(5) file option. By default non-local connections are not allowed. -bgamma value Set the blue gamma correction. value must be between 0.1 and 10. The default is 1.0. Not all drivers support this. See also the -gamma, -rgamma, and -ggamma options. -bpp n No longer supported. Use -depth to set the color depth, and use -fbbpp if you really need to force a non-default framebuffer (hardware) pixel format. -config file Read the server configuration from file. This option will work for any file when the server is run as root (i.e, with real-uid 0), or for files relative to a directory in the config search path for all other users. -configdir directory Read the server configuration files from directory. This option will work for any directory when the server is run as root (i.e, with real-uid 0), or for directories relative to a directory in the config directory search path for all other users. -configure When this option is specified, the Xorg server loads all video driver modules, probes for available hardware, and writes out an initial xorg.conf(5) file based on what was detected. This option currently has some problems on some platforms, but in most cases it is a good way to bootstrap the configuration process. This option is only available when the server is run as root (i.e, with real-uid 0). -crt /dev/ttyXX SCO only. This is the same as the vt option, and is provided for compatibility with the native SCO X server. -depth n Sets the default color depth. Legal values are 1, 4, 8, 15, 16, and 24. Not all drivers support all values. -disableVidMode Disable the parts of the VidMode extension (used by the xvidtune client) that can be used to change the video modes. This is equivalent to the DisableVidModeExtension xorg.conf(5) file option. -fbbpp n Sets the number of framebuffer bits per pixel. You should only set this if you're sure it's necessary; normally the server can deduce the correct value from -depth above. Useful if you want to run a depth 24 configuration with a 24 bpp framebuffer rather than the (possibly default) 32 bpp framebuffer (or vice versa). Legal values are 1, 8, 16, 24, 32. Not all drivers support all values. -flipPixels Swap the default values for the black and white pixels. -gamma value Set the gamma correction. value must be between 0.1 and 10. The default is 1.0. This value is applied equally to the R, G and B values. Those values can be set independently with the -rgamma, -bgamma, and -ggamma options. Not all drivers support this. -ggamma value Set the green gamma correction. value must be between 0.1 and 10. The default is 1.0. Not all drivers support this. See also the -gamma, -rgamma, and -bgamma options. -ignoreABI The Xorg server checks the ABI revision levels of each module that it loads. It will normally refuse to load modules with ABI revisions that are newer than the server's. This is because such modules might use interfaces that the server does not have. When this option is specified, mismatches like this are downgraded from fatal errors to warnings. This option should be used with care. -isolateDevice bus-id Restrict device resets to the device at bus-id. The bus-id string has the form bustype:bus:device:function (e.g., ‘PCI:1:0:0’). At present, only isolation of PCI devices is supported; i.e., this option is ignored if bustype is anything other than ‘PCI’. -keeptty Prevent the server from detaching its initial controlling terminal. If you want to use systemd-logind integration you must specify this option. Not all platforms support (or can use) this option. -keyboard keyboard-name Use the xorg.conf(5) file InputDevice section called keyboard-name as the core keyboard. This option is ignored when the Layout section specifies a core keyboard. In the absence of both a Layout section and this option, the first relevant InputDevice section is used for the core keyboard. -layout layout-name Use the xorg.conf(5) file Layout section called layout-name. By default the first Layout section is used. -logfile filename Use the file called filename as the Xorg server log file. The default log file when running as root is /var/log/Xorg.n.log and for non root it is $XDG_DATA_HOME/xorg/Xorg.n.log where n is the display number of the Xorg server. The default may be in a different directory on some platforms. This option is only available when the server is run as root (i.e, with real-uid 0). -logverbose [n] Sets the verbosity level for information printed to the Xorg server log file. If the n value isn't supplied, each occurrence of this option increments the log file verbosity level. When the n value is supplied, the log file verbosity level is set to that value. The default log file verbosity level is 3. -modulepath searchpath Set the module search path to searchpath. searchpath is a comma separated list of directories to search for Xorg server modules. This option is only available when the server is run as root (i.e, with real-uid 0). -nosilk Disable Silken Mouse support. -novtswitch Disable the automatic switching on X server reset and shutdown to the VT that was active when the server started, if supported by the OS. -pointer pointer-name Use the xorg.conf(5) file InputDevice section called pointer-name as the core pointer. This option is ignored when the Layout section specifies a core pointer. In the absence of both a Layout section and this option, the first relevant InputDevice section is used for the core pointer. -quiet Suppress most informational messages at startup. The verbosity level is set to zero. -rgamma value Set the red gamma correction. value must be between 0.1 and 10. The default is 1.0. Not all drivers support this. See also the -gamma, -bgamma, and -ggamma options. -sharevts Share virtual terminals with another X server, if supported by the OS. -screen screen-name Use the xorg.conf(5) file Screen section called screen-name. By default the screens referenced by the default Layout section are used, or the first Screen section when there are no Layout sections. -showconfig This is the same as the -version option, and is included for compatibility reasons. It may be removed in a future release, so the -version option should be used instead. -showDefaultModulePath Print out the default module path the server was compiled with. -showDefaultLibPath Print out the path libraries should be installed to. -showopts For each driver module installed, print out the list of options and their argument types. -weight nnn Set RGB weighting at 16 bpp. The default is 565. This applies only to those drivers which support 16 bpp. -verbose [n] Sets the verbosity level for information printed on stderr. If the n value isn't supplied, each occurrence of this option increments the verbosity level. When the n value is supplied, the verbosity level is set to that value. The default verbosity level is 0. -version Print out the server version, patchlevel, release date, the operating system/platform it was built on, and whether it includes module loader support.

KEYBOARD¶

The following key combinations are commonly part of the default XKEYBOARD keymap.

Ctrl+Alt+Backspace Immediately kills the server — no questions asked. It can be disabled by setting the DontZap xorg.conf(5) file option to a TRUE value.

CONFIGURATION¶

Xorg has a mechanism for automatically generating a built-in configuration at run-time when no xorg.conf file or xorg.conf.d files are present. The current version of this automatic configuration mechanism works in two ways.

The first is via enhancements that have made many components of the xorg.conf file optional. This means that information that can be probed or reasonably deduced doesn't need to be specified explicitly, greatly reducing the amount of built-in configuration information that needs to be generated at run-time.

The second is to have "safe" fallbacks for most configuration information. This maximises the likelihood that the Xorg server will start up in some usable configuration even when information about the specific hardware is not available.

The automatic configuration support for Xorg is work in progress. It is currently aimed at the most popular hardware and software platforms supported by Xorg. Enhancements are planned for future releases.

FILES¶

SEE ALSO¶

AUTHORS¶

Xorg was originally based on XFree86 4.4rc2. That was originally based on X386 1.2 by Thomas Roell, which was contributed to the then X Consortium's X11R5 distribution by SGCS.

Xorg is released by the X.Org Foundation.

The project that became XFree86 was originally founded in 1992 by David Dawes, Glenn Lai, Jim Tsillas and David Wexelblat.

XFree86 was later integrated in the then X Consortium's X11R6 release by a group of dedicated XFree86 developers, including the following:

Xorg source is available from the FTP server <ftp://ftp.x.org/>, and from the X.Org server <http://gitweb.freedesktop.org/>. Documentation and other information can be found from the X.Org web site <http://www.x.org/>.

LEGAL¶

XFree86(TM) is a trademark of The XFree86 Project, Inc.

X11(TM) and X Window System(TM) are trademarks of The Open Group.

Что такое xorg в linux

Xorg is an open source implementation of the X Window System (frequenty abbreviated to X or X11).

Xorg provides an interface between hardware and the graphical software which you want to run.

2 Nomenclature

  1. X session The combination of an X server and connecting X clients.
  2. Display Managers Provide X users with a graphical login prompt

3 X Client Server Architecture

X uses a client server model. A given X server runs on one user’s local machine, whilst the client programs which communicate with the server may run on different remote machines. This is the reverse of the common configuration of client-server systems, where the client runs on the user’s computer and the server runs on a remote computer.

For example I can run emacs on my local machine, and connect via ssh to a remote CS server at uni to run say libreoffice, which would be running on the remote server so I can access my school files, but the libre office window would be rendered on my local machine, and it would also process my keyboard input (assuming of course the SSH session is configured correctly).

4 Starting an X Session

An X session is usually started by either the startx command or a daemon X display manager daemon program started by systemd based on the dependency of graphical.target.

  1. Running startx basically runs xinit (startx is a user-friendly wrapper).
  2. startx first looks for

See this stackexchange post for more details.

4.1 Summary

tl;dr: .xinitrc is run from xinit (and thus its wrapper startx), .xsession is run when custom is selected on display manager login or if .xinitrc is not found (have tested), and .xsessionrc is always run.

Что такое 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 successor, see Wayland.

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:

  • If it cannot find the specific driver installed for the hardware (listed below), it first searches for fbdev ( xf86-video-fbdev ), which does not include any 2D or 3D acceleration.
  • If that is not found, it searches for vesa ( xf86-video-vesa ), the generic driver, which handles a large number of chipsets but does not include any 2D or 3D acceleration.
  • If vesa is not found, Xorg will fall back to kernel mode setting, which includes GLAMOR acceleration (see modesetting(4) ).

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:

alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />This article or section needs expansion. alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />

  1. For Intel graphics on 4th generation and above, see Intel graphics#Installation for available drivers.
  2. Classic OpenGL (non-Gallium3D) drivers for older hardware (Mesa 22.0 and higher have dropped support for i915 classic driver)
  3. For NVIDIA Optimus enabled laptop which uses an integrated video card combined with a dedicated GPU, see NVIDIA Optimus.

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#Features overview.

  1. 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

Xorg uses a configuration file called xorg.conf and files ending in the suffix .conf for its initial setup: the complete list of the folders where these files are searched can be found in xorg.conf(5) , together with a detailed explanation of all the available options.

Using .conf files

The /etc/X11/xorg.conf.d/ directory stores host-specific configuration. You are free to add configuration files there, but they must have a .conf suffix: the files are read in ASCII order, and by convention their names start with XX— (two digits and a hyphen, so that for example 10 is read before 20). These files are parsed by the X server upon startup and are treated like part of the traditional xorg.conf configuration file. Note that on conflicting configuration, the file read last will be processed. For this reason, the most generic configuration files should be ordered first by name. The configuration entries in the xorg.conf file are processed at the end.

Using xorg.conf

Xorg can also be configured via /etc/X11/xorg.conf or /etc/xorg.conf . You can also generate a skeleton for xorg.conf with:

This should create a xorg.conf.new file in /root/ that you can copy over to /etc/X11/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

  • Newer versions of Xorg are auto-configuring, so manual configuration should not be needed.
  • If Xorg is unable to detect any monitor or to avoid auto-configuring, a configuration file can be used. A common case where this is necessary is a headless system, which boots without a monitor and starts Xorg automatically, either from a virtual console at login, or from a display manager.

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.

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

By default, Xorg always sets DPI to 96 since 2009 (see [2]). A change was made with version 21.1 to provide proper DPI auto-detection, but reverted (see FS#72661).

The DPI of the X server can be set with the -dpi command line option.

Having the correct DPI is helpful 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 see if your display size and DPI are correct:

Check that the dimensions match your display size.

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 configuration 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

GTK very often overrides the server’s DPI via the optional Xresource Xft.dpi . To find out whether this is happening to you, check with:

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 explicitly 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 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

  • Picom — Compositor (a fork of Compton).
  • Xcompmgr — Composite window-effects manager.
  • steamos-compositor-plus — Valve’s compositor, with some added tweaks and fixes.

Tips and tricks

Automation

This section lists utilities for automating keyboard / mouse input and window operations (like moving, resizing or raising).

Tool Package Manual Keysym
input
Window
operations
Note
xautomation xautomation xte(1) Yes No Also contains screen scraping tools. Cannot simulate F13 and more.
xdo xdo xdo(1) No Yes Small X utility to perform elementary actions on windows.
xdotool xdotool xdotool(1) Yes Yes Very buggy and not in active development, e.g: has broken CLI parsing.[3][4]
xvkbd xvkbd AUR xvkbd(1) Yes No Virtual keyboard for Xorg, also has the -text option for sending characters.
AutoKey autokey-qt AUR autokey-gtk AUR documentation Yes Yes Higher-level, powerful macro and scripting utility, with both Qt and Gtk front-ends.

Nested X session

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.

A more modern way of doing a nested X session is with Xephyr.

Starting an application without a window manager

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:

Disable the device with xinput —disable device , where device is the device ID or name of the device you want to disable. In this example we will disable the Synaptics Touchpad, with the ID 10:

To re-enable the device, just issue the opposite command:

Alternatively using the device name, the command to disable the touchpad would be:

Persistently disable input source

You can disable a particular input source using a configuration snippet:

device is an arbitrary name, and driver_name is the name of the input driver, e.g. libinput . device_name is what is actually used to match the proper device. For alternate methods of targeting the correct device, such as libinput’s MatchIsTouchscreen , consult your input driver’s documentation. Though this example uses libinput, this is a driver-agnostic method which simply prevents the device from being propagated to the driver.

Killing application with hotkey

Run script on hotkey:

Block TTY access

To block tty access when in an X add the following to xorg.conf:

This can be used to help restrict command line access on a system accessible to non-trusted users.

Prevent a user from killing X

To prevent a user from killing X when it is running add the following to xorg.conf:

Killing an application visually

When an application is misbehaving or stuck, instead of using kill or killall from a terminal and having to find the process ID or name, xorg-xkill allows to click on said application to close its connection to the X server. Many existing applications do indeed abort when their connection to the X server is closed, but some can choose to continue.

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 some popular display managers do not support rootless Xorg (e.g. LightDM or XDM).

You can verify which user Xorg is running as with ps -o user= -C Xorg .

Using xinitrc

To configure rootless Xorg using xinitrc:

  • Run startx as a subprocess of the login shell; run startx directly and do not use exec startx .
  • Ensure that Xorg uses virtual terminal for which permissions were set, i.e. passed by logind in $XDG_VTNR via .xserverrc.
  • If using certain proprietary display drivers, kernel mode settingauto-detection will fail. In such cases, you must set needs_root_rights = no in /etc/X11/Xwrapper.config .
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

/.local/share/xorg/Xorg.log . However, the stdout and stderr output from the Xorg session is not redirected to this log. To re-enable redirection, start Xorg with the -keeptty flag and redirect the stdout and stderr output to a file:

Alternatively, copy /etc/X11/xinit/xserverrc to

/.xserverrc , and append -keeptty . See [5].

Xorg as Root

As explained above, there are circumstances in which rootless Xorg is defaulted to. If this is the case for your configuration, and you have a need to run Xorg as root, you can configure Xorg.wrap(1) to require root:

Troubleshooting

General

If a problem occurs, view the log stored in either /var/log/ or, for the rootless X default since v1.16, in

/.local/share/xorg/ . GDM users should check the systemd journal. [6]

The logfiles are of the form Xorg.n.log with n being the display number. For a single user machine with default configuration the applicable log is frequently Xorg.0.log , but otherwise it may vary. To make sure to pick the right file it may help to look at the timestamp of the X server session start and from which console it was started. For example:

  • In the logfile then be on the lookout for any lines beginning with (EE) , which represent errors, and also (WW) , which are warnings that could indicate other issues.
  • If there is an empty .xinitrc file in your $HOME , either delete or edit it in order for X to start properly. If you do not do this X will show a blank screen with what appears to be no errors in your Xorg.0.log . Simply deleting it will get it running with a default X environment.
  • If the screen goes black, you may still attempt to switch to a different virtual console (e.g. Ctrl+Alt+F6 ), and blindly log in as root. You can do this by typing root (press Enter after typing it) and entering the root password (again, press Enter after typing it).
  • Check specific pages in Category:Input devices if you have issues with keyboard, mouse, touchpad etc.
  • Search for common problems in AMDGPU, Intel and NVIDIA articles.

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:

to the Device section that references the video card in xorg.conf .

Frame-buffer mode problems

X fails to start with the following log messages:

Program requests «font ‘(null)'»

Error message: unable to load font `(null)’ .

Some programs only work with bitmap fonts. Two major packages with bitmap fonts are available, xorg-fonts-75dpi and xorg-fonts-100dpi . You do not need both; one should be enough. To find out which one would be better in your case, try xdpyinfo from xorg-xdpyinfo , like this:

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.

  • Change default target to rescue.target . See systemd#Change default target to boot into.
  • If you have not only a faulty system that makes Xorg unusable, but you have also set the GRUB menu wait time to zero, or cannot otherwise use GRUB to prevent Xorg from booting, you can use the Arch Linux live CD. Follow the installation guide about how to mount and chroot into the installed Arch Linux. Alternatively try to switch into another tty with Ctrl+Alt + function key (usually from F1 to F7 depending on which is not used by X), login as root and follow steps below.

Depending on setup, you will need to do one or more of these steps:

    the display manager.
  • Disable the automatic start of X.
  • Rename the

X clients started with «su» fail

If you are getting Client is not authorized to connect to server , try adding the line:

to /etc/pam.d/su and /etc/pam.d/su-l . pam_xauth will then properly set environment variables and handle xauth keys.

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

If X terminates with error message SocketCreateListener() failed , you may need to delete socket files in /tmp/.X11-unix . This may happen if you have previously run Xorg as root (e.g. to generate an xorg.conf ).

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.

Xorg/Руководство

Xorg — это сервер оконной системы X Window server, который позволяет пользователю организовать для себя графическую рабочую среду. Это руководство объясняет что такое Xorg, как его установить и за что отвечают различные параметры конфигурации.

Содержание

Что такое сервер оконной системы X Window?

Графический интерфейс против командной строки

Среднестатистический пользователь может быть встревожен мыслью о том, что ему придётся вводить команды. Почему бы ему не щёлкать мышью с той свободой, какую предоставляет Gentoo (и вообще Linux)? Конечно же, это возможно!

Linux предлагает широкий выбор бросающихся в глаза пользовательских интерфейсов, таких как оконные менеджеры и среды рабочего стола, которые можно установить поверх существующей установки.

Один из самых больших сюрпризов для новых пользователей Linux заключается в том, что графические интерфейсы — это ничего более, чем приложение (или иногда наборы приложений), запущенные на их системе. Это не часть ядра Linux или какой-либо внутренней части системы. Это мощное средство, раскрывающее графические возможности рабочей станции.

Стандарты важны, и стандарт для отрисовки и перемещения окон на экране, взаимодействующий с мышью, клавиатурой, и другим оборудованием, а также включающий иные важные аспекты, был создан и назван X Window System, обычно сокращенный до X11 или просто X. Он используется на Unix, Linux, и Unix-подобных операционных системах по всему миру.

Приложением, которое дает возможность пользователям Linux запускать графический интерфейс и использующее стандарт X11, является Xorg-X11, ответвление проекта XFree86. В XFree86 используется несовместимая с GPL лицензия; следовательно, рекомендуется использовать Xorg. Официальное дерево Portage больше не предоставляет пакеты XFree86.

Проект X.org

Проект X.org создан и поддерживается как свободно распространяемая реализация системы X11 с открытым исходным кодом. А также это основанная на X11 инфраструктура рабочего стола.

Xorg обеспечивает интерфейс между аппаратным обеспечением и графическим программным обеспечением. Помимо этого, Xorg умеет работать в сети, что позволяет запускать программу на одной системе, а смотреть на другой.

Установка

Перед установкой Xorg необходимо подготовить систему. Во-первых, настроим ядро для поддержки устройств ввода и видеокарт. Затем мы подготовим /etc/portage/make.conf так, чтобы были установлены нужные драйверы и пакеты Xorg.

Поддержка устройств ввода

Поддержку устройства событий (event interface) CONFIG_INPUT_EVDEV необходимо включить путем внесения изменений в конфигурацию ядра. Смотрите руководство по конфигурации ядра, если вы не знаете как настроить ваше ядро.

Установка режима в ядре

Современные видеодрайверы с открытым исходным кодом полагаются на поддержку Kernel Mode Setting (KMS). KMS предоставляет улучшенную графическую загрузку с меньшим мерцанием, более быстрым переключением пользователей, встроенной в кадровый буфер консолью, плавным переключением из консоли в Xorg, а также другие возможности.

Отключение устаревших кадровых буферов

Сначала подготовим ядро для KMS. На данном этапе не имеет значения, какой видеодрайвер Xorg будет использоваться.

Далее настройте ядро для использования подходящего драйвера KMS для видеокарты. Intel, NVIDIA и AMD/ATI являются распространенными видеокартами, поэтому смотрите соответствующие настройки ниже для каждой видеокарты.

Intel
NVIDIA

Для видеокарт NVIDIA доступно два варианта. Для систем с полностью открытым исходным кодом рекомендуется использовать открытый драйвер Nouveau. Вторым вариантом является использование пропиетарного драйвера NVIDIA, который официально поддерживается NVIDIA. В статье рекомендуется использовать драйвер Nouveau, однако следует помнить, что для определённых карт драйвер с открытым кодом не обеспечивает полную функциональность.

В дополнение к драйверу в ядре, некоторым картам требуется прошивка с закрытым кодом, встроенная в ядро Linux. В зависимости от выбранного драйвера, следует ознакомиться с соответствующей статьёй, чтобы узнать требуется ли для определённой карты прошивка (из sys-kernel/linux-firmware).

AMD/ATI

Для новых карт AMD/ATI (RadeonHD 2000 и выше) установите пакет sys-kernel/linux-firmware (пакет включает прошивки для драйверов radeon и amdgpu). Когда один из этих пакетов будет установлен, сделайте драйвер Radeon модулем ядра. Или, по желанию, настройте ядро как описано в разделе о прошивке из статьи о Radeon или, для более новых карт от AMD (GCN1.1+), в разделе о прошивке статьи AMDGPU.

Сейчас, когда KMS настроен, продолжите подготовку /etc/portage/make.conf в следующем разделе.

Когда ядро подготовлено, перед установкой Xorg необходимо установить несколько переменных в файле /etc/portage/make.conf .

make.conf

В Portage существует USE-флаг USE=X , включающий поддержку X в других пакетах (он включён по умолчанию в профилях desktop). Убедитесь, что этот USE-флаг добавлен в список включённых USE-флагов:

Первая переменная VIDEO_CARDS . Она используется для установки видеодрайвера, который планируется использовать и который обычно совпадает с используемой видеокартой. Наиболее распространённые значения — nouveau для карт NVIDIA и radeon для ATI. Оба варианта активно разрабатываются и являются хорошо поддерживаемыми драйверами с открытым исходным кодом. Для новых видеокарт AMD (Southern Islands и новее), можно попробовать новый драйвер с открытым исходным кодом amdgpu . Более подробная информация доступна в статье AMDGPU.

intel может быть использован для персональных и планшетных компьютеров с встроенными графическими чипами от Intel. См. Драйверы X для Intel для более детальной информации.

Вторая переменная — INPUT_DEVICES , которая используется для определения драйверов, необходимых для работы устройств ввода.

make.defaults по умолчанию использует Libinput в качестве драйвера для устройств ввода.

Чтобы проверить, что на данный момент установлено, запустите:

В случае необходимости использования других устройств ввода (например сенсорная панель Synaptics), добавьте их в переменную INPUT_DEVICES в файле /etc/portage/make.conf :

Если предложенные настройки не работают, то установите пакета x11-base/xorg-drivers (смотрите следующий пример). Проверьте все доступные варианты и выберите те, которые применимы к системе. Этот пример для системы с клавиатурой, мышью, Synaptics тачпадом и видеокартой Radeon.

USE-флаги имеют следующие значения:

USE flags for x11-base/xorg-server X.Org X servers

debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
elogind Use elogind to get control over framebuffer when running as regular user
minimal Install a very minimal build (disables, for example, plugins, fonts, most drivers, non-critical features)
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
suid Enable setuid root program(s)
systemd Enable use of systemd-specific libraries and features like socket activation or session tracking
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
udev Enable virtual/udev integration (device discovery, power and storage device support, etc)
unwind Enable libunwind usage for backtraces
xcsecurity Build Security extension
xephyr Build the Xephyr server
xnest Build the Xnest server
xorg Build the Xorg X server (HIGHLY RECOMMENDED)
xvfb Build the Xvfb server

Emerge

После настройки всех необходимых переменных и USE-флагов можно приступать к установке Xorg:

После завершения установки может потребоваться обновить некоторые переменные окружения перед тем, как продолжать. Используйте команду:

Конфигурация

X server разработан для работы «из коробки», поэтому нет необходимости вручную редактировать файлы настройки. Сервер сам должен определить и настроить устройства — мониторы, клавиатуры и мыши.

Попробуйте использовать startx без предварительного редактирования файлов настройки. Если Xorg не запустится, или будут другие проблемы, тогда необходима ручная настройка Xorg. Она приводится в следующем разделе.

Для запуска Xorg с правами непривилегированного пользователя или включите использование провайдера logind (см. Non root Xorg), или установите USE-флаг suid (см. замечание выше).

Каталог xorg.conf.d

Большинство конфигурационных файлов для Xorg находится в /etc/X11/xorg.conf.d/ . Если этого каталога не существует — создайте его. Каждый файл обладает уникальным именем и оканчивается на .conf . Имена файлов в этом каталоге читаются в буквенно-цифровом порядке. Например, 10-evdev.conf будет прочтен до b-synaptics.conf , и так далее. Файлы в этом каталоге не обязательно должны быть пронумерованы, это сделано для сохранения порядка. Порядок будет полезен при отладке неправильных файлов настройки.

Использование startx

Попробуйте startx для запуска X server. startx — это сценарий (устанавливается из пакета x11-apps/xinit), запускающий сеанс X; иными словами, он запускает X server и некоторые графические приложения вместе с ним. Он решает, какие приложения запустить, основываясь на следующей логике:

  • Если в домашнем каталоге существует файл с названием .xinitrc , будут выполнены команды из него.
  • В противном случае считывается значение переменной XSESSION из файла /etc/env.d/90xsession и выполняется соответствующий сеанс. Значения для XSESSION доступны в /etc/X11/Sessions/ . Для установки сеанса по умолчанию на уровне системы необходимо выполнить:

Если отсутствует оконный менеджер, появится чёрный экран. Так как это также может быть признаком того, что что-то пошло не так, для проверки X можно установить пакеты x11-wm/twm и x11-terms/xterm.

После установки программ снова запустите startx . Должно появиться несколько окон xterm , что является простой проверкой корректной работы сервера X. Удовлетворившись результатами, удалите x11-wm/twm и x11-terms/xterm. Они больше не понадобятся для установки необходимого окружения рабочего стола.

Сеанс также может быть передан в качестве аргумента для startx :

В дополнение к этому, параметры можно передать серверу X, прописав перед ними два дефиса:

Тонкая настройка X

Установка разрешения экрана

Если разрешение экрана установлено неправильно, необходимо проверить два раздела в конфигурации xorg.conf.d . Во-первых, есть раздел Screen со списком разрешений, с которыми может запуститься сервер X. Этот раздел вовсе может не содержать никаких записей о разрешениях. В этом случае Xorg рассчитает характеристики разрешений исходя из информации во втором разделе — Monitor.

Теперь давайте изменим разрешение. В следующем примере из /etc/X11/xorg.conf.d/40-monitor.conf мы добавим строку PreferredMode , так что наш сервер X запустится с разрешением 1440×900 по умолчанию. Пункт Option в разделе Device должен совпадать с именем монитора ( DVI-0 ), которое может быть получено через xrandr . Установите xrandr ( emerge xrandr ) просто для того, чтобы получить эту информацию. Аргумент после имени монитора (в Device ) должен совпадать с Identifier в разделе Monitor .

Запустите X ( startx ) для проверки желаемого разрешения.

Поддержка нескольких мониторов

Больше одного монитора можно установить в /etc/X11/xorg.conf.d/ . Определите для каждого монитора уникальный идентификатор, ориентируясь по его физическому расположению, например «RightOf» или «Above» относительно другого монитора. Следующий пример демонстрирует, как настроить DVI- и VGA-мониторы, когда VGA-монитор расположен по правую руку пользователя.

Настройка клавиатуры

См. статью Keyboard layout switching для определения методов переключения раскладки клавиатуры.

Для установки многоязычной клавиатуры X создайте подходящий файл в /etc/X11/xorg.conf.d/ . Пример для русской раскладки:

Команда «terminate» ( terminate:ctrl_alt_bksp ) дает возможность пользователю убить сеанс X используя комбинацию Ctrl + Alt + Backspace . Однако, это аварийно завершит работу X — следует этого избегать. Это может быть полезно, когда программы полностью «заморозили» экран, или при тонкой настройке окружения Xorg. Будьте осторожны, когда останавливаете рабочий стол этой комбинацией клавиш — большинству программ не нравится, когда их завершают подобным образом. Почти вся информация, не записанная на диск (хранящаяся в «открытых документах»), будет потеряна.

Ввиду того, что драйвер «evdev» может управлять несколькими устройствами (даже не являющимися клавиатурами), может понадобиться ввести ограничение раздела только на некоторые устройства, чтобы остальные работали корректно. Используйте директиву MatchProduct для сопоставления имени устройства, сверившись с man xorg.conf .

За дополнительной информацией о XkbModel и XkbOptions можно обратиться к /usr/share/X11/xkb/rules/base.lst и man xkeyboard-config .

Завершение

Запустите startx и порадуйтесь результату. Поздравляем, вы теперь (надеемся) обладаете рабочим Xorg! Следующим шагом является установка полезного оконного менеджера или окружения рабочего стола, например KDE, GNOME или Xfce. Информация об установке этих рабочих столов может быть найдена здесь на вики.

Смотрите также

    — describes how an unprivileged user can run Xorg without using suid. — a simpler and modern replacement for X display server. — статья Security Handbook о безопасности X сервера. — an open source implementation of the X server. — объясняет что такое Xorg, как его установить и за что отвечают различные параметры конфигурации. — X protocol extension and its CLI tool xrandr are used to manage screen resolutions, rotation and screens with multiply displays in X — the main component of the X Window system which abstracts the hardware and provides the foundation for most graphical user interfaces, like desktop environments or window managers, and their applications.

Внешние ресурсы

Создание и редактирование файлов настройки

man xorg.conf и man evdev содержат краткие, но исчерпывающие сведения о синтаксисе, используемом в их конфигурационных файлах. Удостоверьтесь, что они открыты в терминале, когда редактируете конфигурационные файлы Xorg!

Пример конфигураций можно найти в /usr/share/doc/xorg-server-*/xorg.conf.example.bz2 .

Есть ещё множество онлайн ресурсов о редактировании конфигурационных файлов в /etc/X11/ . Только немногие приведены здесь; используйте ваш любимый поисковик для того, чтобы найти больше.

Другие ресурсы

Больше информации об установке и настройке разных окружений рабочего стола и приложений можно найти в разделе Gentoo desktop resources нашей документации.

При обновлении xorg-server 1.9 или выше прочтите руководство по миграции.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *