https://wiki.archlinux.org/api.php?action=feedcontributions&user=Arzeth&feedformat=atomArchWiki - User contributions [en]2024-03-28T19:09:37ZUser contributionsMediaWiki 1.41.0https://wiki.archlinux.org/index.php?title=Gamepad&diff=795022Gamepad2023-12-24T03:18:38Z<p>Arzeth: Add "Multi-mode wired gamepads" section. Zero info about them on the Internet, which caused me to spend 25 hours to get mine fully working after 1 year of using it.</p>
<hr />
<div>[[Category:Input devices]]<br />
[[Category:Gaming]]<br />
[[ja:ゲームパッド]]<br />
Many gamepads are working out-of-the-box nowadays, but there are still many potential problems and sources for errors since gamepad support in applications varies by a lot.<br />
<br />
{{Expansion|Need info about differences between API, how to switch between them.|section=Joystick API vibration support}}<br />
<br />
Linux has two different input systems for gamepads – the original Joystick interface and the newer evdev-based interface.<br />
<br />
{{ic|1=/dev/input/jsX}} maps to the Joystick API interface and {{ic|/dev/input/event*}} maps to the evdev ones (this also includes other input devices such as mice and keyboards). Symbolic links to those devices are also available in {{ic|/dev/input/by-id/}} and {{ic|/dev/input/by-path/}} where the legacy Joystick API has names ending with {{ic|-joystick}} while the evdev have names ending with {{ic|-event-joystick}}.<br />
<br />
Most new games will default to the evdev interface as it gives more detailed information about the buttons and axes available and also adds support for force feedback.<br />
<br />
While SDL1 defaults to evdev interface you can force it to use the old Joystick API by setting the environment variable {{ic|1=SDL_JOYSTICK_DEVICE=/dev/input/js0}}. This can help many games such as X3. SDL2 supports only the new evdev interface.<br />
<br />
== Installation ==<br />
<br />
Unless you are using very old joystick that uses [[Wikipedia:Game port|Gameport]] or a proprietary USB protocol, you will need just the generic USB Human Interface Device (HID) modules.<br />
<br />
For an extensive overview of all joystick related modules in Linux, you will need access to the Linux kernel sources — specifically the Documentation section. Unfortunately, official kernel packages do not include what we need. If you have the kernel sources downloaded, have a look at {{ic|Documentation/input/joydev/}}. You can browse the kernel source tree at [https://kernel.org/ kernel.org] by clicking the "browse" (cgit - the git frontend) link for the kernel that you are using, then clicking the "tree" link near the top. Alternatively, see [https://docs.kernel.org/input/joydev/joystick.html documentation from the latest kernel].<br />
<br />
Some joysticks need specific modules, such as the Microsoft Sidewinder controllers ({{ic|sidewinder}}), or the Logitech digital controllers ({{ic|adi}}). Many older joysticks will work with the simple {{ic|analog}} module. If your joystick is plugging in to a gameport provided by your soundcard, you will need your soundcard drivers loaded — however, some cards, like the Soundblaster Live, have a specific gameport driver ({{ic|emu10k1-gp}}). Older ISA soundcards may need the {{ic|ns558}} module, which is a standard gameport module.<br />
<br />
As you can see, there are many different modules related to getting your joystick working in Linux, so everything is not covered here. Please have a look at the documentation mentioned above for details.<br />
<br />
=== Loading the modules for analogue devices ===<br />
<br />
You need to load a module for your gameport ({{ic|ns558}}, {{ic|emu10k1-gp}}, {{ic|cs461x}}, etc...), a module for your joystick ({{ic|analog}}, {{ic|sidewinder}}, {{ic|adi}}, etc...), and finally the kernel joystick device driver ({{ic|joydev}}). You can [[load the module at boot]], or simply [[modprobe]] it. The {{ic|gameport}} module should load automatically, as this is a dependency of the other modules.<br />
<br />
=== USB gamepads ===<br />
<br />
You need to get USB working, and then modprobe your gamepad driver, which is {{ic|usbhid}}, as well as {{ic|joydev}}. <br />
If you use a usb mouse or keyboard, {{ic|usbhid}} will be loaded already and you just have to load the {{ic|joydev}} module.<br />
<br />
{{Note|If your Xbox 360 gamepad is connected with the Play&Charge USB cable it will show up in {{ic|lsusb}} but it will not show up as an input device in {{ic|/dev/input/js*}}, see [[#Xbox 360 controller]].}}<br />
<br />
== Configuration ==<br />
<br />
=== Testing ===<br />
<br />
Once the modules are loaded, you should be able to find a new device: {{ic|/dev/input/js0}} and a file ending with {{ic|-event-joystick}} in {{ic|/dev/input/by-id}} directory. You can simply {{ic|cat}} those devices to see if the joystick works — move the stick around, press all the buttons - you should see mojibake printed when you move the sticks or press buttons.<br />
<br />
If you get a permission error, see [[#Device permissions]].<br />
<br />
Both interfaces are also supported in [[Wine]] and reported as separate devices. You can test them (including vibration feedback) with {{ic|wine control joy.cpl}}.<br />
<br />
==== Joystick API ====<br />
<br />
There are a lot of applications that can test this old API, {{ic|jstest}} from the {{pkg|joyutils}} package is the simplest one. If the output is unreadable because the line printed is too long you can also use graphical tools. KDE Plasma has a built in one in ''System Settings > Input Devices > Game Controller''. There is {{AUR|jstest-gtk-git}} as an alternative.<br />
<br />
Use of {{ic|jstest}} is fairly simple, you just run {{ic|jstest /dev/input/js0}} and it will print a line with state of all the axes (normalised to {{ic|{-32767,32767}<nowiki/>}}) and buttons.<br />
<br />
After you start {{ic|jstest-gtk}}, it will just show you a list of joysticks available, you just need to select one and press Properties.<br />
<br />
==== evdev API ====<br />
<br />
The new 'evdev' API can be tested using the SDL2 joystick test application or using {{ic|evtest}} from {{Pkg|evtest}} or {{ic|evtest-qt}} from {{AUR|evtest-qt-git}}. Install {{AUR|sdl2-jstest-git}} and then run {{ic|sdl2-jstest --test 0}}. Use {{ic|sdl2-jstest --list}} to get IDs of other controllers if you have multiple ones connected.<br />
<br />
To test force feedback on the device, use {{ic|fftest}} from {{Pkg|linuxconsole}}:<br />
<br />
$ fftest /dev/input/by-id/usb-*event-joystick<br />
<br />
==== HTML5 Gamepad API ====<br />
<br />
Go to https://gamepad-tester.com/. Currently, testing vibration and producing a visual of the gamepad is supported in [[Chromium]] but not [[Firefox]]. Additionally, as of version 107.0.5304.121-1, Chromium can read Joystick devices but not evdev.<br />
<br />
=== Setting up deadzones and calibration ===<br />
<br />
{{Expansion|Describe calibration instructions for evdev|section=Unclear instructions on how to calibrate}}<br />
<br />
If you want to set up the deadzones (or remove them completely) of your analog input you have to do it separately for the xorg (for mouse and keyboard emulation), Joystick API and evdev API.<br />
<br />
==== Wine deadzones ====<br />
<br />
Add the following registry entry and set it to a string from {{ic|0}} to {{ic|10000}} (affects all axes):<br />
<br />
HKEY_CURRENT_USER\Software\Wine\DirectInput\DefaultDeadZone<br />
<br />
Source: [https://wiki.winehq.org/UsefulRegistryKeys UsefulRegistryKeys]<br />
<br />
==== Xorg deadzones ====<br />
<br />
Add a similar line to {{ic|/etc/X11/xorg.conf.d/51-joystick.conf}} (create if it does not exist):<br />
<br />
{{hc|1=/etc/X11/xorg.conf.d/51-joystick.conf|2=<br />
Section "InputClass"<br />
Option "MapAxis1" "deadzone=1000"<br />
EndSection<br />
}}<br />
<br />
{{ic|1000}} is the default value, but you can set anything between {{ic|0}} and {{{{ic|30000}}. To get the axis number see the "Testing Your Configuration" section of this article.<br />
If you already have an option with a specific axis just type in the {{ic|1=deadzone=value}} at the end of the parameter separated by a space.<br />
<br />
==== Joystick API deadzones and calibration ====<br />
<br />
The easiest way is using ''jstest-gtk'' from {{AUR|jstest-gtk-git}}. Select the joystick you want to edit, click the ''Properties'' button. On this new window, click the ''Calibration'' button ('''do not''' click ''Start Calibration'' after that). You can then set the {{ic|CenterMin}} and {{ic|CenterMax}} values, which control the center deadzone, and {{ic|RangeMin}} and {{ic|RangeMax}}, which control the end of throw deadzones. Note that the calibration settings are applied when the application opens the device, so you need to restart your game or test application to see updated calibration settings.<br />
<br />
After you set the deadzones, you also can create an [[udev]] rule to make all changes permanent:<br />
<br />
First, grab the vendor id of your joystick (replace {{ic|''X''}} with your joystick's number, it is usually {{ic|0}}):<br />
<br />
$ udevadm info -q property --property ID_VENDOR_ID --value /dev/input/js''X''<br />
<br />
Also grab the model id:<br />
<br />
$ udevadm info -q property --property ID_MODEL_ID --value /dev/input/js''X''<br />
<br />
If the commands above give you an empty output, it could be because your controller is connected via Bluetooth, making these unique attributes only visible on the parent device(s). To mitigate this, you could try finding other unique attributes by running:<br />
<br />
$ udevadm info -a /dev/input/js''X''<br />
<br />
This will list all available attributes from your device (and parent devices). So, for example, if the parent device of your joystick has the attribute {{ic|1=ATTRS{uniq}=="a0:b1:c2:d3:e4:f5"}}, or maybe both {{ic|1=ATTRS{idVendor}=="054c"}} and {{ic|1=ATTRS{idProduct}=="09cc"}}, then you can use these instead of {{ic|ENV{ID_VENDOR_ID} }} and {{ic|ENV{ID_MODEL_ID} }} in the ''udev'' rule below.<br />
<br />
You can also have both rules at the same time, just separate them with a new line.<br />
<br />
Anyway, now use ''jscal'' to dump the new calibration settings of your joystick:<br />
<br />
$ jscal -p /dev/input/js''X''<br />
<br />
Now, modify this ''udev'' rule with the values you got:<br />
<br />
{{hc|1=/etc/udev/rules.d/85-jscal-custom-calibration.rules|2=<br />
ACTION=="add", KERNEL=="js[0-9]*", ENV{ID_VENDOR_ID}=="054c", ENV{ID_MODEL_ID}=="09cc", RUN+="/usr/bin/jscal -s 1,1,1,1 /dev/input/js%n"<br />
}}<br />
<br />
This rule will automatically run {{ic|/usr/bin/jscal -s 1,1,1,1 /dev/input/js%n}} whenever you connect a joystick with vendor id {{ic|054c}} and model id {{ic|09cc}}. The {{ic|/dev/input/js%n}} part is required to automatically determine the correct joystick, so '''do not''' remove it.<br />
<br />
Finally, [[Udev#Loading new rules|load]] this new ''udev'' rule.<br />
<br />
==== evdev API deadzones and calibration ====<br />
<br />
The ''evdev-joystick'' tool from the {{pkg|linuxconsole}} package can be used to view and change deadzones and calibration for {{ic|evdev}} API devices.<br />
<br />
To view your device configuration:<br />
$ evdev-joystick --showcal /dev/input/by-id/usb-*-event-joystick<br />
<br />
To change the deadzone for a particular axis, use a command like:<br />
$ evdev-joystick --evdev /dev/input/by-id/usb-*-event-joystick --axis 0 --deadzone 0<br />
<br />
To set the same deadzone for all axes at once, omit the {{ic|--axis 0}} option.<br />
<br />
Use udev rules file to set them automatically when the controller is connected.<br />
<br />
Note that inside the kernel, the value is called {{ic|flatness}} and is set using the {{ic|EVIOCSABS}} {{ic|ioctl}}.<br />
<br />
Default configuration will look like similar to this:<br />
<br />
{{hc|$ evdev-joystick --showcal /dev/input/by-id/usb-Madcatz_Saitek_Pro_Flight_X-55_Rhino_Stick_G0000090-event-joystick|2= Supported Absolute axes:<br />
Absolute axis 0x00 (0) (X Axis) (min: 0, max: 65535, flatness: 4095 (=6.25%), fuzz: 255)<br />
Absolute axis 0x01 (1) (Y Axis) (min: 0, max: 65535, flatness: 4095 (=6.25%), fuzz: 255)<br />
Absolute axis 0x05 (5) (Z Rate Axis) (min: 0, max: 4095, flatness: 255 (=6.23%), fuzz: 15)<br />
Absolute axis 0x10 (16) (Hat zero, x axis) (min: -1, max: 1, flatness: 0 (=0.00%), fuzz: 0)<br />
Absolute axis 0x11 (17) (Hat zero, y axis) (min: -1, max: 1, flatness: 0 (=0.00%), fuzz: 0)<br />
}}<br />
<br />
While a more reasonable setting would be achieved with something like this (repeat for other axes):<br />
<br />
{{hc|$ evdev-joystick --evdev /dev/input/by-id/usb-Madcatz_Saitek_Pro_Flight_X-55_Rhino_Stick_G0000090-event-joystick --axis 0 --deadzone 512|2= Event device file: /dev/input/by-id/usb-Madcatz_Saitek_Pro_Flight_X-55_Rhino_Stick_G0000090-event-joystick<br />
Axis index to deal with: 0<br />
New dead zone value: 512<br />
Trying to set axis 0 deadzone to: 512<br />
Absolute axis 0x00 (0) (X Axis) Setting deadzone value to : 512<br />
(min: 0, max: 65535, flatness: 512 (=0.78%), fuzz: 255)<br />
}}<br />
<br />
==== Virtual xboxdrv gamepad deadzones and calibration ====<br />
<br />
It is possible to use ''xboxdrv'' to present your gamepad as a virtual xbox360 gamepad, while handling the axis calibration and deadzones.<br />
<br />
Imagine that you tested your gamepad with ''evtest-qt'', and find out that your left joystick cannot reach the maximum read value when you direct it to top most position. The side effect of this is that in some games (for example, HITMAN 2) the character cannot run.<br />
<br />
Run ''xboxdrv'' and determine how the problematic axis is called. In this case it is {{ic|Y1}}. Now try to direct it to top most position several times, and determine the lowest value that you saw. Imagine it is {{ic|29426}}. Now to be on a safe side, we take the value that is lower than that, like {{ic|29000}}. Run the command:<br />
# xboxdrv --detach-kernel-driver --calibration Y1=-32767:128:29000<br />
This will translate the values of your real gamepad from {{ic|128}} (center) to {{ic|29000}} (max readable value on top) of {{ic|Y1}} axis to the ideal values of virtual gamepad.<br />
<br />
Nice thing about ''xboxdrv'' is that it exports resulting device as both old Joystick API and new style evdev API so it should be compatible with basically any application. You can now see in jstest that the values of axis {{ic|1}} (corresponds to vertical axis of left joystick) is read from {{ic|0}} to {{ic|-32767}}, and in ''evtest-qt'' that you can reach the maximum value. And your character in game can run.<br />
<br />
===== Configuring curves and responsiveness =====<br />
<br />
In case your game requires just limited amount of buttons or has good support for multiple controllers, you may have good results with using ''xboxdrv'' to change response curves of the joystick.<br />
<br />
Below are example setups for Saitek X-55 HOTAS:<br />
<br />
$ xboxdrv --evdev /dev/input/by-id/usb-Madcatz_Saitek_Pro_Flight_X-55_Rhino_Throttle_G0000021-event-joystick \<br />
--evdev-no-grab --evdev-absmap 'ABS_#40=x1,ABS_#41=y1,ABS_X=x2,ABS_Y=y2' --device-name 'Hat and throttle' \<br />
--ui-axismap 'x2^cal:-32000:0:32000=,y2^cal:-32000:0:32000=' --silent<br />
<br />
this maps the {{ic|EV_ABS}} event with id of 40 and 41 (use ''xboxdrv'' with {{ic|--evdev-debug}} to see the events registered), which is the normally inaccessible "mouse pointer" on the throttle, to first gamepad joystick and throttles to second joystick, it also clamps the top and lower ranges as they not always register fully.<br />
<br />
A bit more interesting is the setup for the stick:<br />
<br />
$ xboxdrv --evdev /dev/input/by-id/usb-Madcatz_Saitek_Pro_Flight_X-55_Rhino_Stick_G0000090-event-joystick \<br />
--evdev-no-grab --evdev-absmap 'ABS_X=x1' --evdev-absmap 'ABS_Y=y1' --device-name 'Joystick' \<br />
--ui-axismap 'x1^cal:-32537:-455:32561=,x1^dead:-900:700:1=,x1^resp:-32768:-21845:-2000:0:2000:21485:32767=' \<br />
--ui-axismap 'y1^cal:-32539:-177:32532=,y1^dead:-700:2500:1=,y1^resp:-32768:-21845:-2000:0:2000:21485:32767=' \<br />
--evdev-absmap 'ABS_RZ=x2' --ui-axismap 'x2^cal:-32000:-100:32000,x2^dead:-1500:1000:1=,x2^resp:-32768:-21845:-2000:0:2000:21485:32767=' \<br />
--silent<br />
<br />
this maps the 3 joystick axes to gamepad axes and changes the calibration (min value, centre value, max value), dead zones (negative side, positive side, flag to turn smoothing) and finally change of response curve to a more flat one in the middle.<br />
<br />
You can also modify the responsiveness by setting the {{ic|sen}} (sensitivity) parameter. Setting it to value of {{ic|0}} will give you a linear sensitivity, value of {{ic|-1}} will give very insensitive axis while value of {{ic|1}} will give very sensitive axis. You can use intermediate values to make it less or more sensitive. Internally ''xboxdrv'' uses a quadratic formula to calculate the resulting value, so this setting gives a more smooth result than {{ic|resp}} shown above.<br />
<br />
=== Disable joystick from controlling mouse ===<br />
<br />
If you want to play games with your gamepad, you might want to disable its joystick control over mouse cursor. To do this, edit {{ic|/etc/X11/xorg.conf.d/51-joystick.conf}} (create if it does not exists) so that it looks like this:<br />
<br />
{{hc|/etc/X11/xorg.conf.d/51-joystick.conf |<br />
Section "InputClass"<br />
Identifier "joystick catchall"<br />
MatchIsJoystick "on"<br />
MatchDevicePath "/dev/input/event*"<br />
Driver "joystick"<br />
'''Option "StartKeysEnabled" "False"'''<br />
'''Option "StartMouseEnabled" "False"'''<br />
EndSection}}<br />
<br />
=== Using gamepad to send keystrokes ===<br />
<br />
A couple of programs exist to map gamepad buttons to keyboard keys, including:<br />
<br />
* {{AUR|qjoypad}}<br />
* {{AUR|antimicrox}}<br />
* {{AUR|sc-controller}}<br />
* {{Pkg|steam}} - see [[Steam#Steam Input]]<br />
<br />
All work well without the need for additional X.org configuration.<br />
<br />
==== Xorg configuration example ====<br />
<br />
This is a good solution for systems where restarting Xorg is a rare event because it is a static configuration loaded only on X startup. The example runs on a [[Kodi]] media PC, controlled with a Logitech Cordless RumblePad 2. Due to a problem with the d-pad (a.k.a. "hat") being recognized as another axis, [[Joy2key]] was used as a workaround. Since {{Pkg|kodi}} version 11.0 and {{AUR|joy2key}} 1.6.3-1, this setup no longer worked and the following was created for letting Xorg handle joystick events.<br />
<br />
First, [[install]] the {{AUR|xf86-input-joystick}} package. Then, create an X configuration file: <br />
<br />
{{hc|/etc/X11/xorg.conf.d/51-joystick.conf|2=<br />
Section "InputClass"<br />
Identifier "Joystick hat mapping"<br />
Option "StartKeysEnabled" "True"<br />
#MatchIsJoystick "on"<br />
Option "MapAxis5" "keylow=113 keyhigh=114"<br />
Option "MapAxis6" "keylow=111 keyhigh=116"<br />
EndSection<br />
}}<br />
<br />
{{Note|The {{ic|MatchIsJoystick "on"}} line does not seem to be required for the setup to work, but you may want to uncomment it.}}<br />
<br />
=== Remapping of gamepad buttons and more ===<br />
<br />
With some programs you can also configure your gamepad further, including the following potential features:<br />
<br />
* Remapping buttons and axes.<br />
** Assigning mapping profiles to different games.<br />
* Emulating a different type of gamepad. As noted in [[#Mimic Xbox 360 controller]], software can often behave better when seemingly given an Xbox 360 Controller, as this is a very common controller that many games have been tested with.<br />
* Additional functionality such as Macros, On-Screen-Displays etc.<br />
<br />
List of software:<br />
<br />
* {{App|SC Controller|Open-source software supporting button remapping and Xbox 360 Controller emulation.|https://github.com/Ryochan7/sc-controller|{{AUR|sc-controller}}}}<br />
* {{App|[[Steam]]|Proprietary storefront whose client supports rebinding gamepad inputs via [https://partner.steamgames.com/doc/features/steam_controller Steam Input]. When enabled, Steam exposes a Steam Controller to games that opt into the Steam Input API, as well as an emulated Xbox 360 Controller to games using traditional gamepad APIs. See [[Steam#Steam Input]] for further details.|https://store.steampowered.com/about/|{{Pkg|steam}}}}<br />
* {{App|[[xboxdrv]]|Xbox 360 controller driver which supports emulating the controller from a different input controller. Even if you don't have or need (in the sense of [[#Mimic Xbox 360 controller]]) a 360 controller, this is still flexible option for performing remapping.|https://xboxdrv.gitlab.io/|{{AUR|xboxdrv}}}}<br />
<br />
==== Remapping of gamepad on SDL2 applications ====<br />
<br />
Gamepads can be remapped for SDL2 applications using the {{ic|SDL_GAMECONTROLLERCONFIG}} environment variable. For each line, it includes the gamepad's GUID, a name, button / axis mappings and a platform. The controller's GUID can be retreived by installing {{AUR|sdl2-jstest-git}} and then running {{ic|sdl2-jstest --list}}.<br />
<br />
For example, to map Microsoft Xbox 360 controllers with different GUIDs:<br />
<br />
{{hc|~/.bashrc|2=export SDL_GAMECONTROLLERCONFIG="<br />
030000005e0400008e02000001000000,Microsoft Xbox 360,a:b0,b:b1,back:b6,dpdown:h0.1,dpleft:h0.2,dpright:h0.8,dpup:h0.4,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,<br />
030000005e0400008e02000004010000,Microsoft Xbox 360,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,<br />
"}}<br />
<br />
Some apps extract mapping information from a {{ic|gamecontrollerdb.txt}} file. It can be edited graphically with {{AUR|controllermap}}. An up to date database can be found on [https://github.com/gabomdq/SDL_GameControllerDB].<br />
<br />
== Specific devices ==<br />
<br />
While most gamepads, especially USB based ones should just work, some may require (or give better results) if you use alternative drivers. If it does not work the first time, do not give up, and read the following sections thoroughly!<br />
<br />
=== Dance pads ===<br />
<br />
Most dance pads should work. However some pads, especially those used from a video game console via an adapter, have a tendency to map the directional buttons as axis buttons. This prevents hitting left-right or up-down simultaneously. This behavior can be fixed for devices recognized by xpad via a module option:<br />
<br />
# modprobe -r xpad<br />
# modprobe xpad dpad_to_buttons=1<br />
<br />
If that did not work, you can try {{AUR|axisfix-git}} or patching the {{ic|joydev}} kernel module (https://github.com/adiel-mittmann/dancepad).<br />
<br />
=== Logitech Thunderpad Digital ===<br />
<br />
Logitech Thunderpad Digital will not show all the buttons if you use the {{ic|analog}} module. Use the device specific {{ic|adi}} module for this controller.<br />
<br />
=== Nintendo Gamecube Controller ===<br />
<br />
Dolphin Emulator has a [https://wiki.dolphin-emu.org/index.php?title=How_to_use_the_Official_GameCube_Controller_Adapter_for_Wii_U_in_Dolphin page on their wiki] that explains how to use the official Nintendo USB adapter with a Gamecube controller. This configuration also works with the Mayflash Controller Adapter if the switch is set to "Wii U".<br />
<br />
=== Nintendo Switch Pro Controller and Joy-Cons ===<br />
<br />
==== Using the kernel Nintendo HID driver ====<br />
<br />
The hid-nintendo kernel HID driver was mainlined in kernel 5.16. If you are using an earlier kernel, you will need to install the [[DKMS]] module named {{AUR|hid-nintendo-dkms}}. The driver provides support for rumble, battery level, and control of the player and home LEDs. It supports the Nintendo Switch Pro Controller over both USB and Bluetooth in addition to the Joy-Cons.<br />
<br />
An alternate DKMS module named {{AUR|hid-nintendo-nso-dkms}} patches in support for the Switch Online NES and SNES controllers.<br />
<br />
===== Using joycond userspace daemon =====<br />
<br />
The hid-nintendo kernel driver does not handle the combination of two Joy-Cons into one virtual input device. That functionality has been left up to userspace. {{AUR|joycond-git}} is a userspace daemon that combines two kernel Joy-Con evdev devices into one virtual input device using uinput. An application can use two Joy-Cons as if they are a single controller. When the daemon is active, Switch controllers will be placed in a pseudo pairing mode, and the LEDs will start flashing. Holding the triggers can be used to pair controllers and make them usable. To pair two Joy-Cons together, press one trigger on each Joy-Con.<br />
<br />
===== Mimic Xbox 360 controller =====<br />
<br />
Some games and emulators are hardcoded to work with an Xbox 360 controller, and will not work with other controllers. To get around this, you need to create a virtual Xbox 360 controller that emulates the expected interface, but is bound to your controller's inputs. This can be done with [[Steam#Steam Input|Steam Input]] or [[#Mimic Xbox 360 controller with other controllers|xboxdrv]].<br />
<br />
==== Use positional layout on SDL2 applications ====<br />
<br />
By default, SDL2 maps buttons on Nintendo controllers according to the gamepad's label instead of the button's position. This is enabled by the [https://github.com/libsdl-org/SDL/blob/b886f4c6c97f3d37d65f65afdb6bd68148fd4de6/include/SDL_hints.h#L508 SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS] setting, which defaults to {{ic|1}} for controllers known to use the Nintendo button layout,[https://github.com/libsdl-org/SDL/blob/7c05ea0a0ef075527fd745215d5d8a77f667bc21/src/joystick/SDL_gamecontrollerdb.h] and {{ic|0}} for other controllers.[https://github.com/libsdl-org/SDL/blob/ec58a817ef66efc23d7d6e964844317673b23ead/src/joystick/SDL_gamecontroller.c#L1575-L1582] This behavior can be overridden for all controllers by setting the {{ic|SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS}} [[environment variable]]. For example, if Nintendo's conception of A/B and X/Y is undesirable, set {{ic|1=SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS=0}}.<br />
<br />
=== iPEGA-9017s and other Bluetooth gamepads ===<br />
<br />
If you want to use one of the widely available Bluetooth gamepads, such as iPEGA-9017s designed mostly for Android and iOS devices you would need {{AUR|xboxdrv}}, {{Pkg|bluez}}, {{Pkg|bluez-plugins}}, and {{Pkg|bluez-utils}}. You should connect it in gamepad mode (if there are different modes, choose the gamepad one). Technically it is ready to be used, but in most cases games would not recognize it, and you would have to map it individually for all application. The best way to simplify it and make it work with all applications is to mimic Microsoft X360 controller with {{AUR|xboxdrv}}.<br />
Once connected you can create a udev rule to give it a persistent name, that would come in handy when setting it up.<br />
<br />
{{hc|/etc/udev/rules.d/99-btjoy.rules|2=<br />
#Create a symlink to appropriate /dev/input/eventX at /dev/btjoy<br />
ACTION=="add", SUBSYSTEM=="input", ATTRS{name}=="Bluetooth Gamepad", ATTRS{uniq}=="00:17:02:01:ae:2a", SYMLINK+="btjoy"<br />
}}<br />
<br />
Replace "Bluetooth Gamepad" with your device name and "00:17:02:01:ae:2a" with your device's address.<br />
<br />
Next, create a configuration for {{AUR|xboxdrv}} somewhere, for example:<br />
<br />
{{hc|~/.config/xboxdrv/ipega.conf|2=<br />
#iPEGA PG-9017S Config <br />
<br />
[xboxdrv]<br />
evdev-debug = true<br />
evdev-grab = true<br />
rumble = false<br />
mimic-xpad = true<br />
<br />
[evdev-absmap]<br />
ABS_HAT0X = dpad_x<br />
ABS_HAT0Y = dpad_y<br />
<br />
ABS_X = X1<br />
ABS_Y = Y1<br />
<br />
ABS_Z = X2<br />
ABS_RZ = Y2<br />
<br />
[axismap]<br />
-Y1 = Y1<br />
-Y2 = Y2<br />
<br />
[evdev-keymap]<br />
BTN_EAST=a<br />
BTN_C=b<br />
BTN_NORTH=y<br />
BTN_SOUTH=x<br />
BTN_TR2=start<br />
BTN_TL2=back<br />
BTN_Z=rt<br />
BTN_WEST=lt<br />
<br />
BTN_MODE = guide<br />
}}<br />
<br />
Refer to {{man|1|xboxdrv|url=https://xboxdrv.gitlab.io/xboxdrv.html}}{{Dead link|2023|11|25}} to see all the options.<br />
<br />
Now when you have the configuration and your device is connected you can start the {{AUR|xboxdrv}} like so:<br />
<br />
# xboxdrv --evdev /dev/btjoy --config .config/xboxdrv/ipega.conf<br />
<br />
Your games will now work with bluetooth gamepad as long as xboxdrv is running.<br />
<br />
==== iPEGA-9068 and 9087 ====<br />
<br />
For this model, use the same procedures as above, but with the configs:<br />
<br />
{{hc|~/.config/xboxdrv/ipega.conf|2=<br />
#iPEGA PG-9068 and PG-9087 Config <br />
<br />
[xboxdrv]<br />
evdev-debug = true<br />
evdev-grab = true<br />
rumble = false<br />
mimic-xpad = true<br />
<br />
[evdev-absmap]<br />
ABS_HAT0X = dpad_x<br />
ABS_HAT0Y = dpad_y<br />
<br />
ABS_X = X1<br />
ABS_Y = Y1<br />
<br />
ABS_Z = X2<br />
ABS_RZ = Y2<br />
<br />
[axismap]<br />
-Y1 = Y1<br />
-Y2 = Y2<br />
<br />
[evdev-keymap]<br />
BTN_A=a<br />
BTN_B=b<br />
BTN_Y=y<br />
BTN_X=x<br />
BTN_TR=rb<br />
BTN_TL=lb<br />
BTN_TR2=rt<br />
BTN_TL2=lt<br />
BTN_THUMBL=tl<br />
BTN_THUMBR=tr<br />
BTN_START=start<br />
BTN_SELECT=back<br />
<br />
BTN_MODE = guide<br />
}}<br />
<br />
==== Defender X7 ====<br />
<br />
For this model, use the same procedures as above, but with the configs:<br />
<br />
{{hc|~/.config/xboxdrv/defender.conf|2=<br />
#Defender x7 xboxdrv config<br />
<br />
[xboxdrv]<br />
evdev-debug = true<br />
evdev-grab = true<br />
rumble = false<br />
mimic-xpad = true<br />
<br />
[evdev-absmap]<br />
ABS_HAT0X = dpad_x<br />
ABS_HAT0Y = dpad_y<br />
<br />
ABS_X = X1<br />
ABS_Y = Y1<br />
<br />
ABS_Z = X2<br />
ABS_RZ = Y2<br />
<br />
[axismap]<br />
-Y1 = Y1<br />
-Y2 = Y2<br />
<br />
[evdev-keymap]<br />
BTN_EAST=b<br />
BTN_NORTH=x<br />
BTN_SOUTH=a<br />
BTN_WEST=y<br />
BTN_TR2=rt<br />
BTN_TL2=lt<br />
BTN_TR=rb<br />
BTN_TL=lb<br />
BTN_THUMBL=tl<br />
BTN_THUMBR=tr<br />
BTN_START=start<br />
BTN_SELECT=back<br />
<br />
BTN_MODE = guide<br />
}}<br />
<br />
Now when you have the configuration and your device is connected you can start the {{AUR|xboxdrv}} like so:<br />
<br />
# xboxdrv --evdev /dev/btjoy --config .config/xboxdrv/defender.conf<br />
<br />
=== Stadia Controller ===<br />
<br />
The Stadia controller can also be mapped with xboxdrv:<br />
<br />
{{hc<br />
|~/.config/xboxdrv/stadia.conf|2=<br />
# Stadia xboxdrv config<br />
<br />
[xboxdrv]<br />
mimic-xpad=true<br />
silent=true<br />
<br />
[evdev-absmap]<br />
ABS_X=x1<br />
ABS_Y=y1<br />
ABS_Z=x2<br />
ABS_RZ=y2<br />
ABS_GAS=rt<br />
ABS_BRAKE=lt<br />
ABS_HAT0X=dpad_x<br />
ABS_HAT0Y=dpad_y<br />
<br />
[axismap]<br />
-y1=y1<br />
-y2=y2<br />
<br />
[evdev-keymap]<br />
BTN_SOUTH=A<br />
BTN_EAST=B<br />
BTN_NORTH=X<br />
BTN_WEST=Y<br />
<br />
BTN_START=start<br />
BTN_SELECT=back<br />
BTN_MODE=guide<br />
<br />
BTN_THUMBL=tl<br />
BTN_THUMBR=tr<br />
BTN_TR=rb<br />
BTN_TL=lb<br />
}}<br />
<br />
=== Steam Controller ===<br />
<br />
{{Note|Kernel 4.18 [https://lore.kernel.org/lkml/20180416122703.22306-1-rodrigorivascosta@gmail.com/ provides a kernel driver] for wired/wireless use of the steam controller as a controller input device without [[Steam]].}}<br />
<br />
The [[Steam]] client will recognize the controller and provide keyboard/mouse/gamepad emulation while Steam is running. The in-game Steam overlay needs to be enabled and working in order for gamepad emulation to work. You may need to run {{ic|udevadm trigger}} with root privileges or plug the dongle out and in again, if the controller does not work immediately after installing and running Steam. If all else fails, try restarting the computer while the dongle is plugged in.<br />
<br />
If you are using the controller connected via Bluetooth LE, make sure the user is part of the {{ic|input}} group.<br />
<br />
If you cannot get the Steam Controller to work, see [[#Steam Controller not pairing]].<br />
<br />
Alternatively you can install {{AUR|python-steamcontroller-git}} to have controller and mouse emulation without Steam or {{AUR|sc-controller}} for a versatile graphical configuration tool simillar to what is provided by the Steam client.<br />
<br />
{{Note|If you do not use the [[Steam runtime]], you might actually need to disable the overlay for the controller to work in certain games (Rocket Wars, Rocket League, Binding of Isaac, etc.). Right click on a game in your library, select "Properties", and uncheck "Enable Steam Overlay".}}<br />
<br />
==== Wine ====<br />
<br />
{{AUR|python-steamcontroller-git}} can also be used to make the Steam Controller work for games running under Wine. You need to find and download the application {{ic|xbox360cemu.v.3.0}} (e.g. from [https://github.com/jacobmischka/ds4-in-wine/tree/master/xbox360cemu.v.3.0 here]). Then copy the files {{ic|dinput8.dll}}, {{ic|xbox360cemu.ini}}, {{ic|xinput1_3.dll}} and {{ic|xinput_9_1_0.dll}} to the directory that contains your game executable. Edit {{ic|xbox360cemu.ini}} and only change the following values under {{ic|[PAD1]}} to remap the Steam Controller correctly to a XBox controller.<br />
<br />
{{hc|xbox360cemu.ini|2= Right Analog X=4<br />
Right Analog Y=-5<br />
A=1<br />
B=2<br />
X=3<br />
Y=4<br />
Back=7<br />
Start=8<br />
Left Thumb=10<br />
Right Thumb=11<br />
Left Trigger=a3<br />
Right Trigger=a6}}<br />
<br />
Now start python-steamcontroller in Xbox360 mode ({{ic|sc-xbox.py start}}). You might also want to copy {{ic|XInputTest.exe}} from {{ic|xbox360cemu.v.3.0}} to the same directory and run it with Wine in order to test if the mappings work correctly. However neither mouse nor keyboard emulation work with this method.<br />
<br />
Alternatively you can use {{AUR|sc-controller}} for a similar graphical setup as Steam's own configurator. As of writing, it is a bit buggy here and there but offers an easy click and go way of configuring the controller.<br />
<br />
=== Xbox 360 controller ===<br />
<br />
Both the wired and wireless (with the ''Xbox 360 Wireless Receiver for Windows'') controllers are supported by the {{ic|xpad}} kernel module and should work without additional packages. Note that using a wireless Xbox360 controller with the Play&Charge USB cable will not work. The cable is for recharging only and does not transmit any input data over the wire.<br />
<br />
It has been reported that the default xpad driver has some issues with a few newer wired and wireless controllers, such as:<br />
* incorrect button mapping. ([https://github.com/ValveSoftware/steam-for-linux/issues/95#issuecomment-14009081 discussion in Steam bugtracker])<br />
* not-working sync. ([https://bbs.archlinux.org/viewtopic.php?id=156028 discussion in Arch Forum])<br />
* all four LEDs keep blinking, but controller works. TLP's USB autosuspend is one sure cause of this issue with wireless controllers. See below for fix.<br />
<br />
If you use the [[TLP]] power management tool, you may experience connection issues with your Microsoft wireless adapter (e.g. the indicator LED will go out after the adapter has been connected for a few seconds, and controller connection attempts fail, four LEDs keep blinking but controller works). This is due to TLP's USB autosuspend functionality, and the solution is to add the Microsoft wireless adapter's device ID to TLP blacklist<br />
(to check device ID to blacklist, run {{ic|tlp-stat -u}}; for original MS wireless dongle just add {{ic|1=USB_DENYLIST="045e:0719"}} to {{ic|/etc/tlp.conf}}),<br />
check [https://linrunner.de/en/tlp/docs/tlp-configuration.html#usb TLP configuration] for more details.<br />
<br />
If you experience such issues, you can use [[#xboxdrv]] as the default {{ic|xpad}} driver instead.<br />
<br />
If you wish to use the controller for controlling the mouse, or mapping buttons to keys, etc. you should use the {{AUR|xf86-input-joystick}} package (configuration help can be found using {{man|4|joystick|url=https://manpages.debian.org/latest/xserver-xorg-input-joystick/joystick.4.en.html}}). If the mouse locks itself in a corner, it might help changing the {{ic|MatchDevicePath}} in {{ic|/etc/X11/xorg.conf.d/50-joystick.conf}} from {{ic|/dev/input/event*}} to {{ic|/dev/input/js*}}.<br />
<br />
In order to connect via Bluetooth using KDE, add the following [[kernel parameter]] {{ic|1=bluetooth.disable_ertm=1}}.<br />
<br />
If you experience problems with the rumble feature not working in games, it may be necessary to set the environment variable {{ic|1=SDL_JOYSTICK_HIDAPI=0}}<br />
<br />
==== xboxdrv ====<br />
<br />
[https://gitlab.com/xboxdrv/xboxdrv xboxdrv] is an alternative to {{ic|xpad}} which provides more functionality and might work better with certain controllers. It works in userspace and can be launched as system service. <br />
<br />
Install it with the {{AUR|xboxdrv}} package. Then [[start]]/[[enable]] {{ic|xboxdrv.service}}.<br />
<br />
If you have issues with the controller being recognized but not working in steam games or working but with incorrect mappings, it may be required to modify you configuration as such:<br />
{{hc<br />
|/etc/default/xboxdrv|2=<br />
[xboxdrv]<br />
silent = true<br />
device-name = "Xbox 360 Wireless Receiver"<br />
mimic-xpad = true<br />
deadzone = 4000<br />
<br />
[xboxdrv-daemon]<br />
dbus = disabled<br />
}}<br />
<br />
Then [[restart]] {{ic|xboxdrv.service}}.<br />
<br />
===== Multiple controllers =====<br />
<br />
xboxdrv supports a multitude of controllers, but they need to be set up in {{ic|/etc/default/xboxdrv}}. For each extra controller, add an {{ic|1=next-controller = true}} line. For example, when using 4 controllers, add it 3 times:<br />
<br />
{{bc|1=<br />
[xboxdrv]<br />
silent = true<br />
next-controller = true<br />
next-controller = true<br />
next-controller = true<br />
[xboxdrv-daemon]<br />
dbus = disabled<br />
}}<br />
<br />
Then [[restart]] {{ic|xboxdrv.service}}.<br />
<br />
===== Mimic Xbox 360 controller with other controllers =====<br />
<br />
xboxdrv can be used to make any controller register as an Xbox 360 controller with the {{ic|--mimic-xpad}} switch. This may be desirable for games that support Xbox 360 controllers out of the box, but have trouble detecting or working with other gamepads.<br />
<br />
First, you need to find out what each button and axis on the controller is called. You can use {{Pkg|evtest}} for this. Run {{ic|evtest}} and select the device event ID number ({{ic|/dev/input/event*}}) that corresponds to your controller. Press the buttons on the controller and move the axes to read the names of each button and axis.<br />
<br />
Here is an example of the output:<br />
{{bc|<nowiki><br />
Event: time 1380985017.964843, type 4 (EV_MSC), code 4 (MSC_SCAN), value 90003<br />
Event: time 1380985017.964843, type 1 (EV_KEY), code 290 (BTN_THUMB2), value 1<br />
Event: time 1380985017.964843, -------------- SYN_REPORT ------------<br />
Event: time 1380985018.076843, type 4 (EV_MSC), code 4 (MSC_SCAN), value 90003<br />
Event: time 1380985018.076843, type 1 (EV_KEY), code 290 (BTN_THUMB2), value 0<br />
Event: time 1380985018.076843, -------------- SYN_REPORT ------------<br />
Event: time 1380985018.460841, type 4 (EV_MSC), code 4 (MSC_SCAN), value 90002<br />
Event: time 1380985018.460841, type 1 (EV_KEY), code 289 (BTN_THUMB), value 1<br />
Event: time 1380985018.460841, -------------- SYN_REPORT ------------<br />
Event: time 1380985018.572835, type 4 (EV_MSC), code 4 (MSC_SCAN), value 90002<br />
Event: time 1380985018.572835, type 1 (EV_KEY), code 289 (BTN_THUMB), value 0<br />
Event: time 1380985018.572835, -------------- SYN_REPORT ------------<br />
Event: time 1380985019.980824, type 4 (EV_MSC), code 4 (MSC_SCAN), value 90006<br />
Event: time 1380985019.980824, type 1 (EV_KEY), code 293 (BTN_PINKIE), value 1<br />
Event: time 1380985019.980824, -------------- SYN_REPORT ------------<br />
Event: time 1380985020.092835, type 4 (EV_MSC), code 4 (MSC_SCAN), value 90006<br />
Event: time 1380985020.092835, type 1 (EV_KEY), code 293 (BTN_PINKIE), value 0<br />
Event: time 1380985020.092835, -------------- SYN_REPORT ------------<br />
Event: time 1380985023.596806, type 3 (EV_ABS), code 3 (ABS_RX), value 18<br />
Event: time 1380985023.596806, -------------- SYN_REPORT ------------<br />
Event: time 1380985023.612811, type 3 (EV_ABS), code 3 (ABS_RX), value 0<br />
Event: time 1380985023.612811, -------------- SYN_REPORT ------------<br />
Event: time 1380985023.708768, type 3 (EV_ABS), code 3 (ABS_RX), value 14<br />
Event: time 1380985023.708768, -------------- SYN_REPORT ------------<br />
Event: time 1380985023.724772, type 3 (EV_ABS), code 3 (ABS_RX), value 128<br />
Event: time 1380985023.724772, -------------- SYN_REPORT ------------<br />
</nowiki>}}<br />
<br />
In this case, {{ic|BTN_THUMB}}, {{ic|BTN_THUMB2}} and {{ic|BTN_PINKIE}} are buttons and {{ic|ABS_RX}} is the X axis of the right analogue stick.<br />
You can now mimic an Xbox 360 controller with the following command:<br />
<br />
$ xboxdrv --evdev /dev/input/event* --evdev-absmap ABS_RX=X2 --evdev-keymap BTN_THUMB2=a,BTN_THUMB=b,BTN_PINKIE=rt --mimic-xpad<br />
<br />
The above example is incomplete. It only maps one axis and 3 buttons for demonstration purposes. Use {{ic|xboxdrv --help-button}} to see the names of the Xbox controller buttons and axes and bind them accordingly by expanding the command above. Axes mappings should go after {{ic|--evdev-absmap}} and button mappings follow {{ic|--evdev-keymap}} (comma separated list; no spaces).<br />
<br />
By default, xboxdrv outputs all events to the terminal. You can use this to test that the mappings are correct. Append the {{ic|--silent}} option to keep it quiet.<br />
<br />
==== Using generic/clone controllers ====<br />
<br />
Some clone gamepads might require a specific initialization sequence in order to work ([https://superuser.com/a/1380235 Super User answer]). For that you should run the following python script as the root user:<br />
<br />
{{bc|1=<br />
#!/usr/bin/env python3<br />
<br />
import usb.core<br />
<br />
dev = usb.core.find(idVendor=0x045e, idProduct=0x028e)<br />
<br />
if dev is None:<br />
raise ValueError('Device not found')<br />
else:<br />
dev.ctrl_transfer(0xc1, 0x01, 0x0100, 0x00, 0x14) <br />
}}<br />
<br />
=== Xbox Wireless Controller / Xbox One Wireless Controller ===<br />
<br />
==== Connect Xbox Wireless Controller with USB cable ====<br />
<br />
This is supported by the kernel and works any without additional packages.<br />
<br />
==== Connect Xbox Wireless Controller with Bluetooth ====<br />
<br />
===== Update controller firmware via Windows 10 =====<br />
<br />
The firmware of the Xbox Wireless Controller used to cause loops of connecting/disconnecting with Bluez. The best workaround is to plug the controller (via a USB cord) to a Windows 10 computer, download the [https://apps.microsoft.com/store/detail/xbox-accessories/9NBLGGH30XJ3?hl=en-us&gl=us Xbox Accessories] application through the Microsoft Store, and update the firmware of the controller.<br />
<br />
===== xpadneo =====<br />
<br />
A relatively new driver which does support the Xbox One S and Xbox Series X|S controller via Bluetooth is called [https://github.com/atar-axis/xpadneo/ xpadneo]. In addition to these two models, it has also basic support for the Xbox Elite Series 2 Wireless controller. In exchange for fully supporting just two controllers so far, it enables one to read out the correct battery level, supports rumble (even the one on the trigger buttons - L2/R2), corrects the (sometimes wrong) button mapping and more.<br />
<br />
Installation is done using DKMS: {{AUR|xpadneo-dkms-git}}.<br />
<br />
{{Note|Pairing a new Xbox One S controller for the first time may prove difficult, from not pairing at all to entering a connect/disconnect loop. These problems are described [https://github.com/atar-axis/xpadneo/issues/295 there]. The best way to reliably pair the controller is to first pair it in Windows 10. However, this needs be done using the same Bluetooth adapter. A solution is to install a free copy of Windows 10 Evaluation on a Virtual machine (using [[QEMU]] or [[VirtualBox]], taking care of the Bluetooth adapter passthrough requirements, ''e.g.'' as an USB device) using Arch Linux as your host, and pair in Windows 10 first, then do the same again under your Arch Linux system. Then pairing will succeed and there will be no need of further Windows 10 use.}}<br />
<br />
==== Connect Xbox Wireless Controller with Microsoft Xbox Wireless Adapter ====<br />
<br />
===== xone =====<br />
<br />
[https://github.com/medusalix/xone xone] is a Linux kernel driver for Xbox One and Xbox Series X|S accessories. It serves as a modern replacement for xpad, supersedes xow. Currently working via wired or with the wireless dongle. This driver is still in active development.<br />
<br />
Install {{AUR|xone-dkms-git}} and, if using the wireless dongle, {{AUR|xone-dongle-firmware}}. To retain the functionality of Xbox and Xbox 360 controllers install {{AUR|xpad-noone-dkms}}{{Broken package link|package not found}}. Reboot your system.<br />
<br />
{{Note|The headers corresponding to your kernel are required; see [[DKMS#Installation]].}}<br />
<br />
If the controller performs poorly (low polling rate) after being paired, you will need to [https://support.xbox.com/en-US/help/hardware-network/controller/update-xbox-wireless-controller update the controller's firmware] in Windows using the "Xbox Accessories" app from the Microsoft Store. Theoretically this should be possible with USB passthrough to a Windows virtual machine, but you may need to dual boot to an actual (baremetal) Windows installation for the Xbox Accessories application to see the controller and do the firmware update.<br />
<br />
Also, if you dual boot Windows, pairing the controller & adapter in Windows may cause the pairing to be lost in Linux. You will need to re-pair the controller & dongle when you reboot into Linux. This also happens in the other direction — when the controller & dongle are paired in Linux, they will need to be re-paired the next time you want to use them in Windows.<br />
<br />
===== xow =====<br />
<br />
[https://github.com/medusalix/xow xow] is a project that allows connection with a wireless dongle. It is currently in very early stages of development. It can be installed via {{AUR|xow-git}}{{Broken package link|package not found}}<br />
<br />
[[#xone|xone]] (made by the same developer) supersedes xow; using xone instead of xow is "highly recommended."<br />
<br />
=== Logitech Dual Action ===<br />
<br />
The Logitech Dual Action gamepad has a very similar mapping to the PS2 pad, but some buttons and triggers need to be swapped to mimic the Xbox controller.<br />
<br />
# xboxdrv --evdev /dev/input/event* \<br />
--evdev-absmap ABS_X=x1,ABS_Y=y1,ABS_RZ=x2,ABS_Z=y2,ABS_HAT0X=dpad_x,ABS_HAT0Y=dpad_y \<br />
--axismap -Y1=Y1,-Y2=Y2 \<br />
--evdev-keymap BTN_TRIGGER=x,BTN_TOP=y,BTN_THUMB=a,BTN_THUMB2=b,BTN_BASE3=back,BTN_BASE4=start,BTN_BASE=lt,BTN_BASE2=rt,BTN_TOP2=lb,BTN_PINKIE=rb,BTN_BASE5=tl,BTN_BASE6=tr \<br />
--mimic-xpad --silent<br />
<br />
=== PlayStation 2 controller via USB adapter ===<br />
<br />
To fix the button mapping of PS2 dual adapters and mimic the Xbox controller you can run the following command:<br />
<br />
# xboxdrv --evdev /dev/input/event* \<br />
--evdev-absmap ABS_X=x1,ABS_Y=y1,ABS_RZ=x2,ABS_Z=y2,ABS_HAT0X=dpad_x,ABS_HAT0Y=dpad_y \<br />
--axismap -Y1=Y1,-Y2=Y2 \<br />
--evdev-keymap BTN_TOP=x,BTN_TRIGGER=y,BTN_THUMB2=a,BTN_THUMB=b,BTN_BASE3=back,BTN_BASE4=start,BTN_BASE=lb,BTN_BASE2=rb,BTN_TOP2=lt,BTN_PINKIE=rt,BTN_BASE5=tl,BTN_BASE6=tr \<br />
--mimic-xpad --silent<br />
<br />
=== PlayStation 3 controller ===<br />
<br />
==== Pairing via USB ====<br />
<br />
If you own a PS3 controller and can connect with USB, plug it to your computer and press the PS button. The controller will power up and one of the four LEDs should light up indicating the controller's number.<br />
<br />
==== Pairing via Bluetooth ====<br />
<br />
Install {{Pkg|bluez}} {{Pkg|bluez-utils}} {{Pkg|bluez-plugins}}. Make sure bluetooth is working by following the first five steps of [[Bluetooth#Pairing]] and leave the bluetoothctl command running, then turn on the controller by pressing the middle 'PS' button(all 4 leds should be blinking quickly ~4 hz) and connect to your computer using usb. Lastly, type yes in the bluetoothctl prompt when asked '{{ic|Authorize service 00001124-0000-1000-8000-00805f9b34fb (yes/no)}}'.<br />
<br />
Alternative instructions:<br />
To connect your PS3 controller to your computer using Bluetooth, you first need to install {{Pkg|bluez}} and {{Pkg|bluez-plugins}} then connect your controller via USB. A pop-up should appear asking for pairing. Click on Trust & Authorize. You can now unplug your controller and press the PS button. The controller will connect and a LED will remain solid. You can now use it to play games. Connecting using the USB cable is only needed after the controller has been connected to another system.<br />
<br />
{{Tip|There are many complicated instructions on the internet on setting up a PS3 controller that require many steps such as compiling and installing qtsixa or sixpair and setting up the controller manually, or patching bluez with some specific patches. None of this is necessary on a modern Linux kernel and after installing bluez-plugins.}}<br />
<br />
=== PlayStation 3/4 controller ===<br />
<br />
The DualShock 3, DualShock 4 and Sixaxis controllers work out of the box when plugged in via USB (the PS button will need to be pushed to begin). They can also be used wirelessly via Bluetooth.<br />
<br />
Steam properly recognizes it as a PS3 pad and Big Picture can be launched with the PS button. Big Picture and some games may act as if it was a 360 controller. Gamepad control over mouse is on by default. You may want to turn it off before playing games, see [[#Joystick moving mouse]].<br />
<br />
==== Pairing via Bluetooth ====<br />
<br />
Install the {{Pkg|bluez}}, {{Pkg|bluez-plugins}}, and {{Pkg|bluez-utils}} packages, which includes the ''sixaxis'' plugin. Then [[start]] the [[bluetooth]] service and ensure bluetooth is powered on. If using ''bluetoothctl'' start it in a terminal and then plug the controller in via USB. You should be prompted to trust the controller in bluetoothctl. A graphical bluetooth front-end may program your PC's bluetooth address into the controller automatically. Hit the PlayStation button and check that the controller works while plugged in.<br />
<br />
You can now disconnect your controller. The next time you hit the PlayStation button it will connect without asking anything else.<br />
<br />
Alternatively, on a PS4 controller you can hold the share button and the PlayStation button simultaneously (for a few seconds) to put the gamepad in pairing mode, and pair as you would normally.<br />
<br />
GNOME's Settings also provides a graphical interface to pair sixaxis controllers when connected by wire.<br />
<br />
Remember to disconnect the controller when you are done as the controller will stay on when connected and drain the battery.<br />
<br />
{{Note|If the controller does not connect, make sure the bluetooth interface is turned on and the controllers have been trusted. (See [[Bluetooth]])}}<br />
<br />
==== Using generic/clone controllers ====<br />
<br />
Using generic/clone Dualshock controllers is possible, however there is an issue that may require to install a patched package. The default Bluetooth protocol stack does not detect some of the clone controllers. The {{AUR|bluez-ps3}} package is a version patched to be able to detect them.<br />
{{AUR|bluez-plugins-ps3}} is another package that only patch the bluez-plugins may work for some controllers.<br />
<br />
=== PlayStation 4 controller ===<br />
<br />
==== Pairing via USB ====<br />
<br />
Connect your controller via USB and press the {{ic|PS}} button.<br />
<br />
==== Pairing via Bluetooth ====<br />
<br />
If you want to use bluetooth mode, hold down the {{ic|PS}} button and {{ic|Share}} button together. The white LED of the controller should blink very quickly, and the wireless controller can be paired with your bluetooth manager (bluez, gnome-bluetooth).<br />
<br />
==== Disable touchpad acting as mouse ====<br />
<br />
This fixes conflicts with games that actually use touchpad as part of the gamepad, such as Rise of the Tomb Raider. This will work with both DualShock4 and DualSense controllers.<br />
<br />
===== libinput =====<br />
<br />
If using [[libinput]] with [[Xorg]], or if using [[Wayland]], then you can follow [[Libinput#Using environment variable]] to disable the touchpad device.<br />
<br />
Note that, since the touchpad is just one part of the controller, selecting the input device by vendor and product IDs will not suffice. Instead, consider selecting the device by name.<br />
<br />
For a full set of attributes you can use, consult {{ic|udevadm info --attribute-walk --name{{=}}''device_path''}}, where {{ic|''device_path''}} is the path to the device, such as {{ic|/dev/input/event''n''}} or {{ic|/dev/input/by-id/''identifier''}}.<br />
<br />
Example snippet:<br />
<br />
{{hc|/etc/udev/rules.d/72-ds4tm.rules |<br />
# Disable DS4 touchpad acting as mouse<br />
# USB<br />
ATTRS{name}{{=}}{{=}}"Sony Computer Entertainment Wireless Controller Touchpad", ENV{LIBINPUT_IGNORE_DEVICE}{{=}}"1"<br />
# Bluetooth<br />
ATTRS{name}{{=}}{{=}}"Wireless Controller Touchpad", ENV{LIBINPUT_IGNORE_DEVICE}{{=}}"1"}}<br />
<br />
Then, [[Udev#Loading new rules|reload udev rules]]. Reconnect the gamepad to apply changes.<br />
<br />
===== Xorg =====<br />
<br />
If using Xorg, you can follow [[Xorg#Persistently disable input source]] with {{ic|MatchProduct "Wireless Controller Touchpad"}} to disable the DualShock4/DualSense touchpad. See {{ic|xinput list}} for detected product names.<br />
<br />
=== PlayStation 5 (Dualsense) controller ===<br />
<br />
Bluetooth connection of Dualsense requires enabling userspace HID support, otherwise Dualsense refuses Bluetooth connection after pairing. If userspace HID is not already enabled, this can be done by editing or creating new file {{ic|/etc/bluetooth/input.conf}} with line {{ic|UserspaceHID{{=}}true}} and [[restart]]ing the {{ic|bluetooth.service}}.<br />
<br />
==== Configuration ====<br />
<br />
Button mapping (thanks to [https://github.com/yoyossef/ds360 yoyossef]):<br />
<br />
# xboxdrv \<br />
--evdev /dev/input/by-id/usb-Sony_Interactive_Entertainment_DualSense_Wireless_Controller-if03-event-joystick \<br />
--evdev-absmap ABS_HAT0X=dpad_x,ABS_HAT0Y=dpad_y,ABS_X=X1,ABS_Y=Y1,ABS_RX=X2,ABS_RY=Y2,ABS_Z=LT,ABS_RZ=RT \<br />
--evdev-keymap BTN_SOUTH=A,BTN_EAST=B,BTN_NORTH=Y,BTN_WEST=X,BTN_START=start,BTN_MODE=guide,BTN_SELECT=back \<br />
--evdev-keymap BTN_TL=LB,BTN_TR=RB,BTN_TL2=LT,BTN_TR2=RT,BTN_THUMBL=TL,BTN_THUMBR=TR \<br />
--axismap -y1=y1,-y2=y2 \<br />
--mimic-xpad \<br />
--silent<br />
<br />
Some applications, for example, Steam inside Geforce NOW inside web browser, may be confused with original joystick events, which shadow the newly created event source.<br />
Simply deleting {{ic|/dev/input/js0}} works this around.<br />
<br />
The PlayStation and mode buttons still do not work, however.<br />
<br />
==== dualsensectl ====<br />
<br />
[https://github.com/nowrep/dualsensectl dualsensectl] is a tool that can toggle the lightbar and microphone (and its LED), monitor the battery status, and power off the controller. To use it, [[install]] {{AUR|dualsensectl-git}}.<br />
<br />
== Multi-mode wired gamepads ==<br />
<br />
Some gamepads have 3 modes when wired: Switch, Xbox 360/Windows, Android.<br />
<br />
And they also don't have hotkeys to switch between them when connected ''wired''.<br />
<br />
When you connect such gamepad to Windows, it is in Xbox 360 Controller mode.<br />
<br />
But when you connect such gamepad to Linux, it enters the fallback mode (which happens to be the Android mode), which has a worse polling rate (100 Hz), the Home button acting as {{ic|XF86Home}}; doesn't expose vibration, gyroscope, and accelerometer; doesn't support {{AUR|xboxdrv}} without {{ic|--evdev}}; and identifies itself as e.g. "SHANWAN Android Gamepad" which is not liked by some games (though for SDL2 apps you can set a name in {{ic|SDL_GAMECONTROLLERCONFIG}}).<br />
<br />
When you connect the gamepad, it first tries to be a "Switch Pro Controller", but for some reason the Linux kernel considers the descriptors (sent by the gamepad) invalid, and therefore disconnects the gamepad. This causes the gamepad to reconnect in the aforementioned fallback mode.<br />
<br />
In {{ic|dmesg}} this looks like:<br />
<br />
{{bc|1=<br />
usb 1-5.3: new full-speed USB device number 37 using xhci_hcd<br />
usb 1-5.3: unable to read config index 0 '''descriptor'''/start: -32<br />
usb 1-5.3: chopping to 0 config(s)<br />
usb 1-5.3: can't read configurations, error '''-32'''<br />
usb 1-5.3: new full-speed USB device number 38 using xhci_hcd<br />
usb 1-5.3: New USB device found, idVendor=0079, idProduct=181c, bcdDevice= 1.00<br />
usb 1-5.3: New USB device strings: Mfr=1, Product=2, SerialNumber=0<br />
usb 1-5.3: Product: Android Gamepad<br />
usb 1-5.3: Manufacturer: SHANWAN<br />
}}<br />
<br />
Notice that the "USB Device number" gets increased after the failure. For some USB hubs the error code is {{ic|1=-32}} (EPIPE: broken pipe), for others it is {{ic|1=-71}} (EPROTO: protocol error).<br />
<br />
This error can be fixed by setting a quirk in {{ic|usbcore}} module (not {{ic|usbhid}}) for Switch controller's USB ID:<br />
<br />
# If you have already *manually* set quirks for other devices,<br />
# then don't forget to include them in the two commands below ↓<br />
echo -n "057e:2009:'''ik'''" | sudo tee /sys/module/usbcore/parameters/quirks<br />
<br />
# Optionally constant polling mode:<br />
sudo modprobe -r usbhid ; sleep 4 ; sudo modprobe -v usbhid "quirks=0x057e:0x2009:0x400"<br />
<br />
{{ic|ik}} are 2 flags ([https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/7.7_release_notes/kernel_parameters_changes List of all flags]).<br />
<br />
The flag {{ic|i}} means "allow bad descriptors".<br />
<br />
And the flag {{ic|k}} means "disable LPM" (link power management). It is specified in the command because it often helps devices of other types. This flag might do nothing because not all USB controllers even have LPM. You can try without {{ic|k}} aftewards.<br />
<br />
You could also try the flag {{ic|g}} ("200 ms pause after reading the descriptors") because it often helps devices of other types, but at least in the case of iPEGA PG-SW038C (a $10 gamepad) flag {{ic|g}} causes it infinitely reconnect.<br />
<br />
Note that once the gamepad downgrades to the fallback mode, it will never change its mode until you reconnect it. Even {{ic|echo 0 then 1 > %sysfsGamepadDir%/authorized}} doesn't work. And that's why passing the gamepad to a Windows VM would not help; {{ic|usbcore}} inits USB devices before passing them to a VM.<br />
<br />
<hr/><br />
<br />
Now reconnect the gamepad, it should be finally listed now as {{ic|ID 057e:2009 Nintendo Co., Ltd Switch Pro Controller}} when you run {{ic|lsusb}}. If that's true, then you can make this quirk permanent by add this option to GRUB:<br />
<br />
{{ic|1=usbcore.quirks="057e:2009:ik"}}<br />
<br />
along with (optionally) {{ic|1=usbhid.quirks="0x057e:0x2009:0x400"}} which stops the pointless blinking of LEDs when the gamepad is unused.<br />
<br />
Now that your gamepad is in Switch mode, you'll run into a problem of SDL2 deciding to become a user-space driver (for this it uses {{pkg|libusb}}, just like {{AUR|xboxdrv}}), which causes any SDL2 game to claim the whole gamepad (that is: {{ic|/dev/input/*}} and {{ic|/dev/hidraw*}} disappear, yet it's still possible to play this launched game with the gamepad), so you can't use the gamepad in multiple apps anymore.<br />
<br />
This can be fixed by adding<br />
<br />
SDL_HIDAPI_DISABLE_LIBUSB=1<br />
<br />
into {{ic|/etc/environment}}, and rebooting.<br />
<br />
If you have {{AUR|joycond}}, then delete it, because it is useless for such Switch-like gamepads, moreover {{ic|joycond}} has a {{ic|udev}} rule that disallows Steam to provide its own user-space driver.<br />
<br />
Unlike SDL2 (when it uses {{ic|/dev/hidraw*}} which is its preferred way in 2023), {{ic|xboxdrv}} and {{ic|/dev/input/*}} provide incorrect values for the right stick's X axis (it's always ≤0). Probably a bug in {{ic|hid-nintendo}} or something. For this reason {{ic|xboxdrv}} is unusable in most games when in Switch mode.<br />
<br />
You can test your gyroscope and accelerometer by launching {{AUR|antimicrox}}. They are not available in other gamepad modes when connected wired because their values are sent ''mixed'' with other event data (RX/RY/etc) in a special format that is not fully compatible with {{ic|xpad}} and {{ic|hid-generic}}.<br />
<br />
If you see in {{ic|dmesg}} that {{ic|hid-generic}} is used by your gamepad, then it's probably because you have built Linux kernel with your own config without {{ic|hid-nintendo}}. Unfortuately, Switch mode + {{ic|hid-generic}} is as useless as the fallback mode (even no vibration).<br />
<br />
=== Xbox 360 Controller mode ===<br />
After having completed everything above (i.e. 1-2 quirks, 1 envvar),<br />
<br />
add<br />
<br />
blacklist hid_nintendo<br />
<br />
into {{ic|1=/etc/modprobe.d/blacklist.conf}}<br />
<br />
then run {{ic|1=sudo mkinitcpio -P}} to rebuild {{ic|/boot/initramfs*}} (kernel reads {{ic|/etc/modprobe.d/}} only from its own initramfs, not your rootfs)<br />
<br />
Now create the following file: {{hc|1=/etc/udev/rules.d/10-disallow-generic-driver-for-switch.rules|2=<br />
# If<br />
# 1. a gamepad is multi-mode (Switch, X360, PC) and defaults to USB ID 057e:2009<br />
# AND at the same time<br />
# 2. `hid-nintendo` module can't be loaded (blacklisted or not compiled)<br />
# AND at the same time<br />
# 3. there's already a launched game that immediately grabs a gamepad,<br />
#<br />
# Then when you connect such gamepad, it will stay in "Switch Pro" mode,<br />
# but using the fallback `hid-generic` module<br />
# which would result in no vibration/etc<br />
# despite still being listed as a "Switch Pro Controller".<br />
<br />
# But by notifying the gamepad that we abandon to use it as an HID,<br />
# it automatically downgrades to "Xbox 360 Controller" mode,<br />
# which causes vibration and `xboxdrv` to work.<br />
SUBSYSTEM=="hid", DRIVER=="hid-generic", ATTRS{idVendor}=="057e", ATTRS{idProduct}=="2009", RUN="/bin/sh -c 'echo $id:1.0 > /sys/bus/usb/drivers/usbhid/unbind'"<br />
}}<br />
then run {{ic|sudo udevadm control --reload-rules && sudo udevadm trigger}}<br />
<br />
Since you probably don't want to reboot, run {{ic|sudo modprobe -r hid_nintendo}}<br />
<br />
From now on, to switch ("downgrade") from Switch mode to Xbox 360 mode, just run {{ic|sudo modprobe -r hid_nintendo}} (you don't even need to reconnect it). Within 2 seconds you'll have {{ic|045e:028e Microsoft Corp. Xbox360 Controller}} in {{ic|lsusb}}<br />
<br />
And if you want to switch vice versa:<br />
# {{ic|sudo modprobe hid_nintendo}} (even though it is blacklisted, this command still works because blacklisting just means "don't load this module ''automatically''").<br />
# Reconnect.<br />
<br />
==== Alternative rootless solution ====<br />
If you don't have root access, then:<br />
<br />
# Power off your PC (not just suspend)<br />
# Reconnect your gamepad.<br />
# Power the PC on.<br />
# UEFI (just like non-virtualized Windows) automatically and successfully initializes the gamepad (even if it's connected through a USB hub in your monitor) despite the invalid descriptors.<br />
# The gamepad receives info from UEFI (or maybe GRUB) that it's no longer needed as an HID, which causes it to switch ("downgrade") to Xbox 360 Controller mode. Switching between modes is done this way: the gamepad disconnects, then connects under a different USB ID.<br />
# You can even suspend (without turning off the monitor if that's what it's connected to) and then wake-up the PC, and it will still be in Xbox 360 Controller mode. But if you reconnect the gamepad, it will be in the fallback mode, so you'll have to follow the instruction again.<br />
<br />
=== USB debugging ===<br />
You'll probably not need to know this, but this USB ID (057e:2009) was discovered by USB debugging:<br />
<br />
# Allow debugging of the kernel:<br />
sudo ls /sys/kernel/debug/usb >/dev/null 2>&1 || sudo mount -t debugfs none_debugfs /sys/kernel/debug<br />
# Load the module that allows sniffing of the traffic of USB buses:<br />
sudo modprobe usbmon<br />
# We need only connection events, and in these events<br />
# we need only a USB ID which is in the pre-pre-last column:<br />
sudo /bin/grep --line-buffered -Po '(?<=0 0 18 = .{18}).{8}' /sys/kernel/debug/usb/usbmon/'''99999'''u | /bin/sed -E 's/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/\2\1:\4\3/'<br />
<br />
where {{ic|99999}} must be replaced with the USB Bus number that your gamepad uses, e.g. {{ic|1}} (without leading zeroes). It can be found by running {{ic|lsusb}}.<br />
<br />
If nothing helped and your gamepad still works in full capacity only in Windows, you can catch USB messages while in Windows, and then replay them while in Linux. See [https://github.com/JohnDMcMaster/usbrply usbrply]. For this, Windows must not be in VM because Linux kernel's {{ic|usbcore}} initializes a USB device before passing it to a VM. This could be avoided by buying a PCI-E USB controller and passing it through (External USB hubs can't be passed through). Or you can pass-through your motherboard's own USB controller if it is in a IOMMU group without devices important for you:<br />
<br />
{| role="presentation" class="wikitable mw-collapsible mw-collapsed"<br />
| <strong>Script which lists IOMMU groups</strong><br />
|-<br />
| {{hc|list-iommu-groups.sh|<nowiki><br />
#!/bin/bash<br />
shopt -s nullglob<br />
for g in $(find /sys/kernel/iommu_groups/* -maxdepth 0 -type d | sort -V); do<br />
echo "IOMMU Group ${g##*/}:"<br />
for d in $g/devices/*; do<br />
echo -e "\t$(lspci -nns ${d##*/})"<br />
done;<br />
done;</nowiki>}}<br />
|}<br />
<br />
== Tips and Tricks ==<br />
<br />
=== Gamepad over network ===<br />
<br />
If you want to use your gamepad with another computer over a network, you can use [[USB/IP]] or {{AUR|netstick-git}} to do this.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Device permissions ===<br />
<br />
Gamepad devices are affected by [[Udev#Allowing regular users to use devices|udev rules]]: unless they grant access to the device, it simply will not be readable by users. This section investigates the possibility of you already having a configuration file handling this.<br />
<br />
Any gamepad device, regardless of whether it is over USB or Bluetooth, is handled by the [https://docs.kernel.org/input/input_uapi.html "input" subsystem of the kernel], corresponding with {{ic|/dev/input}}. It's also common for udev rules to target the [https://docs.kernel.org/hid/hidraw.html "hidraw" kernel module]. Combining these, we can understand udev's handling of these devices by inspecting the configuration shipped by packages:<br />
<br />
$ grep --extended-regexp 'SUBSYSTEM=="input"|KERNEL=="hidraw' --recursive /usr/lib/udev/rules.d<br />
<br />
Some examples of applications which ship noteworthy rules:<br />
<br />
* [[systemd]]'s default rules set the group of all {{ic|input}} devices to {{ic|input}}, and the mode of joystick devices to {{ic|664}} [https://github.com/systemd/systemd/blob/edfb4a474e5cbef6578a70aae7f08a0f435c6c6a/rules.d/50-udev-default.rules.in#L33].<br />
* [[Steam]] ships udev rules allowing access to a variety of controllers. See [https://steamcommunity.com/app/353370/discussions/2/1735465524711324558/ this Steam discussion] for further info about the contents of the rules.<br />
* [[Dolphin emulator]] ships udev rules allowing access to controllers it supports.<br />
<br />
If your system does not already happen to have a udev rule for the device you want to use, you can either write one yourself or install the {{AUR|game-devices-udev}} package and restart your computer.<br />
<br />
{{Note|It is possible to add a user to the {{ic|input}} group in order to give them access to all devices. However, this is not recommended [https://github.com/systemd/systemd/issues/4288].}}<br />
<br />
=== Joystick moving mouse ===<br />
<br />
Sometimes USB gamepad can be recognized as HID mouse (only in X, it is still being installed as {{ic|/dev/input/js0}} as well). Known issue is cursor being moved by the joystick, or escaping to en edge of a screen right after plugin. If your application can detect gamepad by itself, you can remove the {{AUR|xf86-input-joystick}} package.<br />
<br />
A more gentle solution is described in [[#Disable joystick from controlling mouse]].<br />
<br />
=== Gamepad is not working in FNA/SDL based games ===<br />
<br />
If you are using a generic non-widely used gamepad you may encounter issues getting the gamepad recognized in games based on SDL. Since [https://github.com/flibitijibibo/FNA/commit/e55742cfe7e38b778a21ed8a12cb2f2081490d8d 14 May 2015], FNA supports dropping a {{ic|gamecontrollerdb.txt}} into the executable folder of the game, for example the [https://github.com/gabomdq/SDL_GameControllerDB SDL_GameControllerDB].<br />
<br />
As an alternative and for older versions of FNA or for SDL you can generate a mapping yourself by downloading the SDL source code via https://libsdl.org/, navigating to {{ic|/test/}}, compile the {{ic|controllermap.c}} program (alternatively install {{AUR|controllermap}}) and run the test. After completing the controllermap test, a GUID will be generated that you can put in the {{ic|SDL_GAMECONTROLLERCONFIG}} environment variable which will then be picked up by SDL/FNA games. For example:<br />
<br />
$ export SDL_GAMECONTROLLERCONFIG="030000008f0e00000300000010010000,GreenAsia Inc. USB Joystick ,platform:Linux,x:b3,a:b2,b:b1,y:b0,back:b8,start:b9,dpleft:h0.8,dpdown:h0.0,dpdown:h0.4,dpright:h0.0,dpright:h0.2,dpup:h0.0,dpup:h0.1,leftshoulder:h0.0,leftshoulder:b6,lefttrigger:b4,rightshoulder:b7,righttrigger:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a3,righty:a2,"<br />
<br />
=== Gamepad is not recognized by all programs ===<br />
<br />
Some software, Steam for example, will only recognize the first gamepad it encounters. Due to a bug in the driver for Microsoft wireless periphery devices this can in fact be the bluetooth dongle. If you find you have a {{ic|/dev/input/js*}} and {{ic|/dev/input/event*}} belonging to you keyboard's bluetooth transceiver you can get automatically get rid of it by creating according udev rules: <br />
<br />
{{hc|/etc/udev/rules.d/99-btcleanup.rules|2=<br />
ACTION=="add", KERNEL=="js[0-9]*", SUBSYSTEM=="input", KERNELS=="...", ATTRS{bInterfaceSubClass}=="00", ATTRS{bInterfaceProtocol}=="00", ATTRS{bInterfaceNumber}=="02", RUN+="/usr/bin/rm /dev/input/js%n"<br />
ACTION=="add", KERNEL=="event*", SUBSYSTEM=="input", KERNELS=="...", ATTRS{bInterfaceSubClass}=="00", ATTRS{bInterfaceProtocol}=="00", ATTRS{bInterfaceNumber}=="02", RUN+="/usr/bin/rm /dev/input/event%n"<br />
}}<br />
<br />
Correct the {{ic|1=KERNELS=="..."}} to match your device. The correct value can be found by running<br />
<br />
# udevadm info -an /dev/input/js0<br />
<br />
Assuming the device in question is {{ic|/dev/input/js0}}. After you placed the rule reload the rules with<br />
<br />
# udevadm control --reload<br />
<br />
Then replug the device making you trouble. The joystick and event devices should be gone, although their number will still be reserved. But the files are out of the way.<br />
<br />
=== Vibration does not work in certain Windows games ===<br />
<br />
Some Windows games look for an Xbox 360 controller in particular, causing vibration to not work even with otherwise functional XInput gamepads. One example of such game is [https://www.pcgamingwiki.com/wiki/Inside Inside].<br />
<br />
As a work-around for these games:<br />
<br />
* [[Kernel modules#Manual module handling|Unload]] the {{ic|xpad}} kernel module.<br />
* Launch {{ic|xboxdrv}}, including Xbox 360 mimicking gamepad and with vibration support:<br />
<br />
# xboxdrv --mimic-xpad --force-feedback<br />
<br />
=== Steam Controller ===<br />
<br />
==== Steam Controller not pairing ====<br />
<br />
There are some unknown cases where the packaged udev rule for the Steam controller does not work ({{bug|47330}}). The most reliable workaround is to make the controller world readable. Copy the rule {{ic|/usr/lib/udev/rules.d/70-steam-controller.rules}} to {{ic|/etc/udev/rules.d}} with a later prioritiy and change anything that says {{ic|1=MODE="0660"}} to {{ic|1=MODE="066'''6'''"}} e.g.<br />
<br />
{{hc|/etc/udev/rules.d/99-steam-controller-perms.rules|2=<br />
...<br />
SUBSYSTEM=="usb", ATTRS{idVendor}=="28de", MODE="0666"<br />
...<br />
}}<br />
<br />
You may have to reboot in order for the change to take effect.<br />
<br />
==== Steam Controller makes a game crash or not recognized ====<br />
<br />
If your Steam Controller is working well in Steam Big Picture mode, but not recognized by a game or the game starts crashing when you plug in the controller, this may be because of the native driver that has been added to the Linux kernel 4.18. Try to unload it, restart Steam and replug the controller.<br />
<br />
The module name of the driver is {{ic|hid_steam}}, so to unload it you may perform:<br />
<br />
# rmmod hid_steam<br />
<br />
=== Xbox One Wireless Gamepad detected but no inputs recognized ===<br />
<br />
This can occur when using a third party Xbox One controller with the {{ic|xpad}} or [[#xboxdrv]] drivers. Try switching to [[#xpadneo]].<br />
<br />
=== Playstation 4 controllers ===<br />
<br />
==== Controller not recognized when using Bluetooth ====<br />
<br />
[[Install]] the {{AUR|ds4drv}} package and run it with the hidraw ({{ic|ds4drv --hidraw}}) backend parameter.<br />
<br />
==== Button mapping ====<br />
<br />
To fix the button mapping of PS4 controller you can use the following command with xboxdrv (or try with the [https://github.com/chrippa/ds4drv ds4drv] program, {{AUR|ds4drv}}):<br />
<br />
# xboxdrv \<br />
--evdev /dev/input/by-id/usb-Sony_Computer_Entertainment_Wireless_Controller-event-joystick\<br />
--evdev-absmap ABS_X=x1,ABS_Y=y1 \<br />
--evdev-absmap ABS_Z=x2,ABS_RZ=y2 \<br />
--evdev-absmap ABS_HAT0X=dpad_x,ABS_HAT0Y=dpad_y \<br />
--evdev-keymap BTN_A=x,BTN_B=a \<br />
--evdev-keymap BTN_C=b,BTN_X=y \<br />
--evdev-keymap BTN_Y=lb,BTN_Z=rb \<br />
--evdev-keymap BTN_TL=lt,BTN_TR=rt \<br />
--evdev-keymap BTN_SELECT=tl,BTN_START=tr \<br />
--evdev-keymap BTN_TL2=back,BTN_TR2=start \<br />
--evdev-keymap BTN_MODE=guide \<br />
--axismap -y1=y1,-y2=y2 \<br />
--mimic-xpad \<br />
--silent<br />
<br />
==== Motion controls taking over joypad controls and/or causing unintended input with joypad controls ====<br />
<br />
{{Style|Could likely use the same solution as [[Gamepad#Disable touchpad acting as mouse]], which is already refactored into other pages where appropriate.}}<br />
<br />
With certain cloud gaming applications such as Parsec and Shadow, the Dualshock 4 V1 and V2 motion controls can conflict with the joypad controls resulting in the joypad not working, and with certain input sensitive games, especially racing games, the motion controls can cause unintentional drift during joypad control gameplay.<br />
<br />
This can be worked around by disabling the motion controls and the touchpad by adding the following udev rules:<br />
<br />
{{hc|1=/etc/udev/rules.d/51-disable-DS3-and-DS4-motion-controls.rules|2=<br />
SUBSYSTEM=="input", ATTRS{name}=="*Controller Motion Sensors", RUN+="/bin/rm %E{DEVNAME}", ENV{ID_INPUT_JOYSTICK}=""<br />
SUBSYSTEM=="input", ATTRS{name}=="*Controller Touchpad", RUN+="/bin/rm %E{DEVNAME}", ENV{ID_INPUT_JOYSTICK}=""<br />
}}<br />
<br />
Then [[udev#Loading new rules|reload the rules]] or reboot: these rules should work in both USB and Bluetooth mode.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_on_ZFS&diff=704334Install Arch Linux on ZFS2021-12-04T21:30:11Z<p>Arzeth: /* Permission denied */ more clarity</p>
<hr />
<div>[[Category:Installation process]]<br />
[[ja:ZFS に Arch Linux をインストール]]<br />
{{Related articles start}}<br />
{{Related|ZFS}}<br />
{{Related|Experimenting with ZFS}}<br />
{{Related articles end}}<br />
This article details the steps required to install Arch Linux onto a ZFS root filesystem.<br />
<br />
{{Warning| Blindly copying and pasting this wiki will not work. It is necessary to take the time to understand the boot process, and what is done when creating the pool and datasets. Here are some useful links:<br />
<br />
* [https://www.freebsd.org/doc/handbook/zfs.html FreeBSD ZFS Handbook]<br />
* [https://github.com/zfsonlinux/zfs/wiki ZFSOnLinux wiki]<br />
* [http://open-zfs.org/wiki/System_Administration OpenZFS wiki]<br />
* [https://pthree.org/2012/04/17/install-zfs-on-debian-gnulinux/ Aaron Toponce Install ZFS on Debian GNU/Linux]<br />
* [https://openzfs.github.io/openzfs-docs/Getting%20Started/Arch%20Linux/ OpenZFS documentation for Arch Linux]<br />
}}<br />
<br />
== Installation ==<br />
<br />
To install Archlinux on ZFS, you need to boot archiso system with ZFS module.<br />
<br />
=== Get ZFS module on archiso system ===<br />
<br />
A script to easily install and load the ZFS module on running archiso system. It should work on any archiso version.<br />
<br />
See [https://github.com/eoli3n/archiso-zfs eoli3n/archiso-zfs].<br />
<br />
=== Embedding ZFS module into custom archiso ===<br />
<br />
To build a custom archiso, see [[ZFS#Create an Archiso image with ZFS support|ZFS]] article.<br />
<br />
An unofficial weekly build is available [https://gitlab.com/m_zhou/archiso/ here].<br />
<br />
== Partition the destination drive ==<br />
<br />
Review [[Partitioning]] for information on determining the partition table type to use for ZFS. ZFS supports GPT and MBR partition tables.<br />
<br />
ZFS manages its own partitions, so only a basic partition table scheme is required. The partition that will contain the ZFS filesystem should be of the type {{ic|bf00}}, or "Solaris Root".<br />
<br />
Drives larger than 2TB require a GPT partition table. GRUB on BIOS/GPT configurations require a small (1~2MiB) BIOS boot partition to embed its image of boot code.<br />
<br />
Depending upon your machine's firmware or your choice of boot mode, booting may or may not require an EFI partition. On a BIOS machine (or a UEFI machine booting in legacy mode) EFI partition is not required. Consult [[Arch boot process#Boot loader]] for more information.<br />
<br />
=== Partition scheme ===<br />
<br />
Here is an example of a basic partition scheme that could be employed for your ZFS root install on a BIOS/MBR installation using GRUB:<br />
<br />
{{bc|<nowiki><br />
Part Size Type<br />
---- ---- -------------------------<br />
1 XXXG Solaris Root (bf00)<br />
</nowiki>}}<br />
<br />
Using GRUB on a BIOS (or UEFI machine in legacy boot mode) machine but using a GPT partition table:<br />
<br />
{{bc|<nowiki><br />
Part Size Type<br />
---- ---- -------------------------<br />
1 2M BIOS boot partition (ef02)<br />
2 XXXG Solaris Root (bf00)<br />
</nowiki>}}<br />
<br />
Another example, this time using a UEFI-specific bootloader (such as [[rEFInd]]) with an GPT partition table:<br />
<br />
{{bc|<nowiki><br />
Part Size Type<br />
---- ---- -------------------------<br />
1 100M EFI boot partition (ef00)<br />
2 XXXG Solaris Root (bf00)<br />
</nowiki>}}<br />
<br />
ZFS does not support swap files. If you require a swap partition, see [[ZFS#Swap volume]] for creating a swap ZVOL.<br />
<br />
{{Tip|Bootloaders with support for ZFS are described in [[#Install and configure the bootloader]].}}<br />
<br />
{{Warning|Several GRUB bugs ([https://savannah.gnu.org/bugs/?42861 bug #42861], [https://github.com/zfsonlinux/grub/issues/5 zfsonlinux/grub/issues/5]) complicate installing it on ZFS partitions, see [[#Install and configure the bootloader]] for a workaround}}<br />
<br />
=== Example parted commands ===<br />
<br />
Here are some example commands to partition a drive for the second scenario above ie using BIOS/legacy boot mode with a GPT partition table and a (slighty more than) 1MB BIOS boot partition for GRUB:<br />
<br />
# parted /dev/sdx<br />
(parted)mklabel gpt<br />
(parted)mkpart non-fs 0% 2<br />
(parted)mkpart primary 2 100%<br />
(parted)set 1 bios_grub on<br />
(parted)set 2 boot on<br />
(parted)quit<br />
<br />
You can achieve the above in a single command like so:<br />
<br />
# parted --script /dev/sdx mklabel gpt mkpart non-fs 0% 2 mkpart primary 2 100% set 1 bios_grub on set 2 boot on<br />
<br />
If you are creating an EFI partition then that should have the boot flag set instead of the root partition.<br />
<br />
== Format the destination disk ==<br />
<br />
If you have opted for a boot partition as well as any other non-ZFS system partitions then format them. Do not do anything to the Solaris partition nor to the BIOS boot partition. ZFS will manage the first, and your bootloader the second.<br />
<br />
== Setup the ZFS filesystem ==<br />
<br />
{{Warning|Do not use '-' in the names of your datasets. ([https://github.com/zfsonlinux/zfs/commit/c39b2786ac98ab87d6dda00aa83b399ed175055a see this "feature"])}}<br />
<br />
First, make sure the ZFS modules are loaded,<br />
<br />
# modprobe zfs<br />
<br />
=== Create the root zpool ===<br />
<br />
Create your pool and set all default dataset options. All dataset created on the zpool will inherit of each {{ic|-O}} set at the zpool creation. Default options are detailed in [https://openzfs.github.io/openzfs-docs/Getting%20Started/Debian/Debian%20Buster%20Root%20on%20ZFS.html#step-2-disk-formatting Debian Buster Root on ZFS. Step 2: Disk Formatting].<br />
<br />
{{Note|Use {{ic|1=-o ashift=9}} for disks with a 512 byte physical sector size or {{ic|1=-o ashift=12}} for disks with a 4096 byte physical sector size. See {{ic|lsblk -S -o NAME,PHY-SEC}} to get the physical sector size of each SCSI/SATA disk. Remove {{ic|-S}} if you want the same value from all devices.}}<br />
<br />
{{Warning|Keep in mind that most modern devices use a 4096 byte physical sector size, even though some report 512. This is especially true for SSDs. Selecting {{ic|1=ashift=9}} on a 4096 byte sector size (even if it reports 512) '''will''' incur a performance penalty. Selecting {{ic|1=ashift=12}} on a 512 byte sector size may incur in a capacity penalty, but no performance penalty. If in doubt, for a modern drive, err on the side of {{ic|1=ashift=12}}, or research your particular device for the appropriate value. Refer to [https://github.com/openzfs/zfs/issues/967 OpenZFS issue #967] for a related discussion, and [https://github.com/openzfs/zfs/issues/2497 OpenZFS issue #2497] for a consequence of a higher ashift value.<br />
}}<br />
<br />
# zpool create -f -o ashift=12 \<br />
-O acltype=posixacl \<br />
-O relatime=on \<br />
-O xattr=sa \<br />
-O dnodesize=legacy \<br />
-O normalization=formD \<br />
-O mountpoint=none \<br />
-O canmount=off \<br />
-O devices=off \<br />
-R /mnt \<br />
zroot /dev/disk/by-id/''id-to-partition-partx''<br />
<br />
==== Compression and native encryption ====<br />
<br />
This will enable compression and native encryption by default on all datasets:<br />
<br />
# zpool create -f -o ashift=12 \<br />
-O acltype=posixacl \<br />
-O relatime=on \<br />
-O xattr=sa \<br />
-O dnodesize=legacy \<br />
-O normalization=formD \<br />
-O mountpoint=none \<br />
-O canmount=off \<br />
-O devices=off \<br />
-R /mnt \<br />
-O compression=lz4 \<br />
-O encryption=aes-256-gcm \<br />
-O keyformat=passphrase \<br />
-O keylocation=prompt \<br />
zroot /dev/disk/by-id/''id-to-partition-partx''<br />
<br />
{{Warning|<br />
* Always use id names when working with ZFS, otherwise import errors will occur.<br />
* [[GRUB]] users should keep in mind that the ''zpool-create'' command normally enables all features, '''some of which may not be supported by GRUB'''. See: [[ZFS#GRUB-compatible pool creation]].<br />
}}<br />
<br />
=== Create your datasets ===<br />
<br />
Instead of using conventional disk partitions, ZFS has the concept of datasets to manage your storage. Unlike disk partitions, datasets have no fixed size and allow for different attributes, such as compression, to be applied per dataset. Normal ZFS datasets are mounted automatically by ZFS whilst legacy datasets are required to be mounted using fstab or with the traditional mount command.<br />
<br />
One of the most useful features of ZFS is boot environments. Boot environments allow you to create a bootable snapshot of your system that you can revert to at any time instantly by simply rebooting and booting from that boot environment. This can make doing system updates much safer and is also incredibly useful for developing and testing software. In order to be able to use a boot environment manager such as [https://github.com/b333z/beadm beadm], {{AUR|zectl}} (systemd-boot), or {{AUR|zedenv}} (GRUB) to manage boot environments, your datasets must be configured properly. Key to this are that you split your data directories (such as {{ic|/home}}) into datasets that are distinct from your system datasets and that you do not place data in the root of the pool as this cannot be moved afterwards.<br />
<br />
You should always create a dataset for at least your root filesystem and in nearly all cases you will also want {{ic|/home}} to be in a separate dataset. You may decide you want your logs to persist over boot environments. If you are a running any software that stores data outside of {{ic|/home}} (such as is the case for database servers) you should structure your datasets so that the data directories of the software you want to run are separated out from the root dataset.<br />
<br />
With these example commands, we will create a basic boot environment compatible configuration comprising of just root and {{ic|/home}} datasets. It inherits default options from [[#Create the root zpool|zpool creation.]]<br />
<br />
# zfs create -o mountpoint=none zroot/data<br />
# zfs create -o mountpoint=none zroot/ROOT<br />
# zfs create -o mountpoint=/ -o canmount=noauto zroot/ROOT/default<br />
# zfs create -o mountpoint=/home zroot/data/home<br />
<br />
You can also create your ROOT dataset without having to specify mountpoint to / since GRUB will mount it to / anyway. That gives you possibility to boot into some old versions of root just by cloning it and putting as menuentry of GRUB. In such, you can create ROOT with the following command:<br />
<br />
# zfs create -o mountpoint=/roots/default zroot/ROOT/default<br />
<br />
You can store {{ic|/root}} in your {{ic|zroot/data/home}} dataset.<br />
<br />
# zfs create -o mountpoint=/root zroot/data/home/root<br />
<br />
You will need to enable some options for datasets which hold specific directories:<br />
<br />
{| class="wikitable" style="text-align: left;"<br />
|+ Options required by specific directories<br />
! scope="col" | Directory<br />
! scope="col" | Dataset option<br />
! scope="col" | Details<br />
|-<br />
! /<br />
| canmount=noauto<br />
|<br />
|-<br />
|-<br />
! /var/log/journal<br />
| acltype=posixacl<br />
| [[Systemd#systemd-tmpfiles-setup.service fails to start at boot]]<br />
|-<br />
|}<br />
<br />
==== System datasets ====<br />
<br />
To create datasets for system directories, use {{ic|1=canmount=off}}.<br />
<br />
For some examples, please read [https://openzfs.github.io/openzfs-docs/Getting%20Started/Debian/Debian%20Buster%20Root%20on%20ZFS.html#step-3-system-installation Debian-Buster-Root-on-ZFS#step-3-system-installation]<br />
<br />
# zfs create -o mountpoint=/var -o canmount=off zroot/var<br />
# zfs create zroot/var/log<br />
# zfs create -o mountpoint=/var/lib -o canmount=off zroot/var/lib<br />
# zfs create zroot/var/lib/libvirt<br />
# zfs create zroot/var/lib/docker<br />
<br />
=== Export/Import your datasets ===<br />
<br />
To validate your configurations, export then reimport all your zpools.<br />
<br />
{{Warning|Do not skip this, otherwise you will be required to use {{ic|-f}} when importing your pools. This unloads the imported pool.}}<br />
<br />
{{Note|This might fail if you added a swap partition. You need to turn it off with the ''swapoff'' command.}}<br />
<br />
# zpool export zroot<br />
# zpool import -d /dev/disk/by-id -R /mnt zroot -N<br />
<br />
{{Note|{{ic|-d}} is not the actual device ID, but the {{ic|/dev/by-id}} directory containing the symbolic links.<br />
<br />
If this command fails and you are asked to import your pool via its numeric ID, run {{ic|zpool import}} to find out the ID of your pool then use a command such as:<br />
<br />
# zpool import 9876543212345678910 -R /mnt zroot<br />
}}<br />
<br />
If you used native encryption, load zfs key.<br />
<br />
# zfs load-key zroot<br />
<br />
Manually mount your rootfs dataset because it uses {{ic|1=canmount=noauto}}, then mount all others datasets.<br />
<br />
# zfs mount zroot/ROOT/default<br />
# zfs mount -a<br />
<br />
The ZFS filesystem is now ready to use.<br />
<br />
=== Configure the root filesystem ===<br />
<br />
If you used legacy datasets, it must be listed in {{ic|/etc/fstab}}.<br />
<br />
Set the bootfs property on the descendant root filesystem so the boot loader knows where to find the operating system.<br />
<br />
# zpool set bootfs=zroot/ROOT/default zroot<br />
<br />
Be sure to bring the {{ic|zpool.cache}} file into your new system. This is required later for the ZFS daemon to start.<br />
<br />
# cp /etc/zfs/zpool.cache /mnt/etc/zfs/zpool.cache<br />
<br />
if you do not have {{ic|/etc/zfs/zpool.cache}}, create it:<br />
<br />
# zpool set cachefile=/etc/zfs/zpool.cache zroot<br />
<br />
== Install and configure Arch Linux ==<br />
<br />
Follow the following steps using the [[Installation guide]]. It will be noted where special consideration must be taken for ZFSonLinux.<br />
<br />
* First mount any legacy or non-ZFS boot or system partitions using the mount command.<br />
<br />
* Install the base system.<br />
<br />
* The procedure described in [[Installation guide#Fstab]] is usually overkill for ZFS. ZFS usually auto mounts its own partitions, so we do not need ZFS partitions in {{ic|fstab}} file, unless the user made legacy datasets of system directories. To generate the {{ic|fstab}} for filesystems, use:<br />
<br />
# genfstab -U -p /mnt >> /mnt/etc/fstab<br />
<br />
* Change root into the new system, per [[Installation guide#Chroot]]:<br />
<br />
# arch-chroot /mnt<br />
<br />
* Edit the {{ic|/etc/fstab}}:<br />
<br />
{{Note|<br />
* If you chose to create legacy datasets for system directories, keep them in this {{ic|fstab}}!<br />
* Comment out all non-legacy datasets apart from the swap file and the boot/EFI partition. It is a convention to replace the swap's uuid with {{ic|/dev/zvol/zroot/swap}}.<br />
}}<br />
<br />
* You need to add the [[Unofficial_user_repositories#archzfs|Arch ZFS]] repository to {{ic|/etc/pacman.conf}}, [[Package_signing#Adding_unofficial_keys|sign its key]] and [[install]] '''zfs-linux''' (or '''zfs-linux-lts''' if you are running the LTS kernel) within the arch-chroot before you can update the ramdisk with ZFS support.<br />
<br />
* When creating the initial ramdisk, first edit {{ic|/etc/mkinitcpio.conf}} and add {{ic|zfs}} before filesystems. Also, move {{ic|keyboard}} hook before {{ic|zfs}} so you can type in console if something goes wrong. You may also remove fsck (if you are not using Ext3 or Ext4). Your {{ic|HOOKS}} line should look something like this:<br />
HOOKS=(base udev autodetect modconf block keyboard zfs filesystems)<br />
<br />
When using systemd in the initrd, you need to install {{AUR|mkinitcpio-sd-zfs}} and add the {{ic|sd-zfs}} hook after the {{ic|systemd}} hook instead of the {{ic|zfs}} hook. Keep in mind that this hook uses different kernel parameters than the default {{ic|zfs}} hook, more information can be found at the [https://github.com/dasJ/sd-zfs project page].<br />
{{Note|{{ic|sd-zfs}} does not support native encryption yet [https://github.com/dasJ/sd-zfs/issues/4 dasJ/sd-zfs/issues/4].}}<br />
<br />
{{Note|<br />
* If you are using a separate dataset for {{ic|/usr}} and have followed the instructions below, you must make sure you have the {{ic|usr}} hook enabled after {{ic|zfs}}, or your system will not boot.<br />
* When you generate the initramfs, the {{ic|zpool.cache}} is copied into the initrd. If you did not generate it before, or needed to regenerate it, remember to regenerate the initramfs again.<br />
* You can also use {{ic|legacy}} mountpoint to let fstab mount it<br />
}}<br />
<br />
* [[Regenerate the initramfs]].<br />
<br />
== Install and configure the bootloader ==<br />
<br />
=== Using GRUB for EFI/BIOS ===<br />
<br />
If you use GRUB, you can store your {{ic|/boot}} on a zpool. Please read [https://openzfs.github.io/openzfs-docs/Getting%20Started/Debian/Debian%20Buster%20Root%20on%20ZFS.html#step-3-system-installation Debian-Buster-Root-on-ZFS#step-3-system-installation].<br />
<br />
Install GRUB onto your disk as instructed here: [[GRUB#BIOS systems]] or [[GRUB#UEFI systems]]. The GRUB [https://www.gnu.org/software/grub/manual/grub.html#Configuration manual] provides detailed information on manually configuring the software which you can supplement with [[GRUB]] and [[GRUB/Tips and tricks]].<br />
<br />
==== bug: broken root pool detection ====<br />
<br />
Because of a known [https://github.com/zfsonlinux/grub/issues/22 bug], ''grub-mkconfig'' will fail to detect the root pool and omit in {{ic|/boot/grub/grub.cfg}}. Until this is fixed, there are two possible workarounds:<br />
<br />
* Workaround A: Modify code for rpool detection in {{ic|/etc/grub.d/10_linux}}. Replace<br />
:{{bc|1=rpool=`${grub_probe} --device ${GRUB_DEVICE} --target=fs_label 2>/dev/null {{!}}{{!}} true`}}<br />
:with<br />
:{{bc|1=rpool=`zdb -l \$\{GRUB_DEVICE\} {{!}} grep " name:" {{!}} cut -d\' -f2`}}<br />
:This will detect the correct root pool name and write working path to {{ic|/boot/grub/grub.cfg}} any time ''grub-mkconfig'' is used.<br />
* Workaround B: Hardcoded path to root dataset in the kernel command line via {{ic|/etc/default/grub}}:<br />
:{{bc|1=GRUB_CMDLINE_LINUX="root=ZFS=zroot/ROOT/default"}}<br />
:Because {{ic|GRUB_CMDLINE_LINUX}} is added at the end of the kernel command line, this path will overwrite the wrong, auto-generated one. Even though this is the less intrusive option to fix the issue, you will have to make sure the path is correct yourself.<br />
<br />
==== error: failed to get canonical path of ====<br />
<br />
''grub-mkconfig'' fails to properly generate entries for systems hosted on ZFS.<br />
<br />
# grub-mkconfig -o /boot/grub/grub.cfg<br />
/usr/bin/grub-probe: error: failed to get canonical path of `/dev/bus-Your_Disk_ID-part#'<br />
<br />
grub-install: error: failed to get canonical path of `/dev/bus-Your_Disk_ID-part#'<br />
<br />
To work around this you must set this environment variable: {{ic|1=ZPOOL_VDEV_NAME_PATH=1}}. For example:<br />
<br />
# ZPOOL_VDEV_NAME_PATH=1 grub-mkconfig -o /boot/grub/grub.cfg<br />
<br />
==== error: unknown filesystem ====<br />
<br />
GRUB tools like ''grub-probe'' or ''grub-install'' may fail with the error {{ic|1=unknown filesystem}} when filesystem detection fails. This may happen due to the filesystem not being supported by GRUB, or in the case of ZFS, unsupported features may be present (refer to [[ZFS#GRUB-compatible pool creation]] for appropriate features to include in a boot zpool.)<br />
<br />
In order to troubleshoot the error, understand which filesystem it is failing to identify (e.g. run ''grub-probe'' on the suspects, like {{ic|1=grub-probe /}} or {{ic|1=grub-probe /boot}}). An example interaction follows:<br />
<br />
# grub-probe /boot<br />
zfs<br />
<br />
# grub-probe /<br />
grub-probe: error: unknown filesystem.<br />
<br />
After identifying the problem filesystem, run {{ic|1=grub-probe -vvvv /}} and scan the output for the filesystem it was expected to identify. In this case, ZFS was expected, but the following output was generated:<br />
<br />
{{hc|1=grub-probe -vvvv /|2=<br />
(...)<br />
grub-core/kern/fs.c:56: Detecting zfs...<br />
grub-core/osdep/hostdisk.c:420: opening the device `/dev/sda4' in open_device()<br />
grub-core/fs/zfs/zfs.c:1199: label ok 0<br />
grub-core/osdep/hostdisk.c:399: reusing open device `/dev/sda4'<br />
grub-core/fs/zfs/zfs.c:1014: check 2 passed<br />
grub-core/fs/zfs/zfs.c:1025: check 3 passed<br />
grub-core/fs/zfs/zfs.c:1032: check 4 passed<br />
grub-core/fs/zfs/zfs.c:1042: check 6 passed<br />
grub-core/fs/zfs/zfs.c:1050: check 7 passed<br />
grub-core/fs/zfs/zfs.c:1061: check 8 passed<br />
grub-core/fs/zfs/zfs.c:1071: check 9 passed<br />
grub-core/fs/zfs/zfs.c:1093: check 11 passed<br />
grub-core/fs/zfs/zfs.c:1119: check 10 passed<br />
grub-core/fs/zfs/zfs.c:1135: str=com.delphix:hole_birth<br />
grub-core/fs/zfs/zfs.c:1135: str=com.delphix:embedded_data<br />
grub-core/fs/zfs/zfs.c:1144: check 12 passed (feature flags)<br />
grub-core/fs/zfs/zfs.c:1884: zio_read: E 0: size 4096/4096<br />
(...)<br />
grub-core/osdep/hostdisk.c:399: reusing open device `/dev/sda4'<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.delphix:extensible_dataset, value = 18, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.datto:bookmark_v2, value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.datto:encryption, value = c, cd = 0 # <------------------<br />
grub-core/kern/fs.c:78: zfs detection failed. # <----------------------------------------------------<br />
grub-core/kern/fs.c:56: Detecting xfs...<br />
grub-core/fs/xfs.c:931: Reading sb<br />
grub-core/fs/xfs.c:270: Validating superblock<br />
grub-core/kern/fs.c:78: xfs detection failed.<br />
grub-core/kern/fs.c:56: Detecting ufs2...<br />
(...)<br />
grub-core/kern/fs.c:56: Detecting affs...<br />
grub-core/kern/fs.c:78: affs detection failed.<br />
grub-probe: error: unknown filesystem.<br />
}}<br />
<br />
This shows that ZFS detection went well until the {{ic|com.datto:encryption}} feature was detected. Since ZFS Native Encryption is not supported by GRUB (as of August 2021), detection of ZFS failed. A second, GRUB-compatible zpool may be appropriate to boot into an encrypted system - as of August 2021, this is the recommended approach (refer to the [https://openzfs.github.io/openzfs-docs/Getting%20Started/Arch%20Linux/Root%20on%20ZFS/0-overview.html relevant OpenZFS project page]).<br />
<br />
A successful execution of {{ic|grub-probe}} on a GRUB-compatible zpool looks like this:<br />
{{hc|1=grub-probe -vvvv /boot|2=<br />
(...)<br />
grub-core/osdep/hostdisk.c:399: reusing open device `/dev/sda3'<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.delphix:extensible_dataset, value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.delphix:embedded_data, value = 1, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.delphix:hole_birth, value = 1, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = org.open-zfs:large_blocks, value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = org.illumos:lz4_compress, value = 1, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = , value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = , value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:3285: alive<br />
(...)<br />
grub-core/fs/zfs/zfs.c:1906: endian = 1<br />
grub-core/fs/zfs/zfs.c:597: dva=8, 20008<br />
grub-core/fs/zfs/zfs.c:2697: alive<br />
zfs<br />
}}<br />
<br />
==== Permission denied ====<br />
If you get this error while booting, then replace contents of {{ic|/usr/lib/initcpio/hooks/zfs}} with one that supports importing encrypted zpools:<br />
# wget -O /usr/lib/initcpio/hooks/zfs 'https://aur.archlinux.org/cgit/aur.git/plain/zfs-utils.initcpio.hook?h=zfs-utils-common'<br />
<br />
Then update {{ic|initramfs*.img}} in {{ic|/boot/}}:<br />
# mkinitcpio<br />
Now the {{ic|zfs}} hook will, just like LUKS's {{ic|encrypt}} hook, ask for a password instead of always saying "Permission denied". Note that this error was not because you, for example, enabled {{ic|1=-O encryption=aes-256-gcm}} and/or {{ic|1=-O compression=zstd-2}} with {{ic|1=-O recordsize=256k}}.<br />
<br />
At least, it works when a pool is created with {{ic|1=-O keyformat=passphrase -O keylocation=prompt}}<br />
<br />
Just in case, add {{ic|usr/lib/initcpio/hooks/zfs}} (yes, without a leading slash) to both {{ic|1=NoUpgrade=}} and {{ic|1=NoExtract=}} in {{ic|/etc/pacman.conf}}<br />
<br />
==== Booting your kernel and initrd from ZFS ====<br />
<br />
You may skip this section if you have your kernel and initrd on a separate {{ic|/boot}} partition using something like ext4 or vfat.<br />
<br />
Otherwise grub needs to load your kernel and initrd are from a ZFS dataset the kernel and initrd paths have to be in the following format:<br />
<br />
/dataset/@/actual/path<br />
<br />
Example with Arch installed on the root dataset:<br />
<br />
{{hc|/boot/grub/grub.cfg|2=<br />
set timeout=5<br />
set default=0<br />
<br />
menuentry "Arch Linux" {<br />
search -u UUID<br />
linux /@/boot/vmlinuz-linux zfs=zroot rw<br />
initrd /@/boot/initramfs-linux.img<br />
}<br />
}}<br />
<br />
Example with Arch installed on a nested dataset:<br />
<br />
{{hc|/boot/grub/grub.cfg|2=<br />
set timeout=5<br />
set default=0<br />
<br />
menuentry "Arch Linux" {<br />
search -u UUID<br />
linux /ROOT/default/@/boot/vmlinuz-linux zfs=zroot/ROOT/default rw<br />
initrd /ROOT/default/@/boot/initramfs-linux.img<br />
}<br />
}}<br />
<br />
Unlike with other filesystems, it is not necessary to specify {{ic|1=root=}} ({{ic|1=root=ZFS=zroot/ROOT/default}}), <br />
<br />
==== Booting your kernel and initrd from separate boot partition ====<br />
<br />
Example with a separate non-ZFS /boot partition and Arch installed on a nested dataset:<br />
<br />
{{hc|/boot/grub/grub.cfg|2=<br />
set timeout=5<br />
set default=0<br />
<br />
menuentry "Arch Linux" {<br />
search -u UUID<br />
linux /vmlinuz-linux zfs=zroot/ROOT/default rw<br />
initrd /initramfs-linux.img<br />
}<br />
}}<br />
<br />
=== Using systemd-boot for EFI only ===<br />
<br />
Systemd-boot cannot open ZFS zpools, you must store your {{ic|/boot}} on a separated VFAT or ext4 partition.<br />
<br />
{{Note|To be able to manage your Boot Environments with {{AUR|zectl}}, follow [https://github.com/johnramsden/zectl/blob/master/docs/plugins/systemdboot.md zectl/docs/plugins/systemdboot.md].}}<br />
<br />
Install bootloader on your {{ic|esp}}, following [[Systemd-boot#Installing the EFI boot manager]].<br />
<br />
Create a boot entry:<br />
<br />
{{hc|/efi/loader/entries/archlinux.conf|2=<br />
title Arch Linux<br />
linux vmlinuz-linux<br />
initrd intel-ucode.img<br />
initrd initramfs-linux.img<br />
options zfs=zroot/ROOT/default rw<br />
}}<br />
<br />
=== Using rEFInd for UEFI ===<br />
<br />
Use {{ic|EFISTUB}} and {{ic|rEFInd}} for the UEFI boot loader. The kernel parameters in {{ic|refind_linux.conf}} for ZFS should include {{ic|1=zfs=bootfs}} or {{ic|1=zfs=zroot}} so the system can boot from ZFS. The {{ic|root}} and {{ic|rootfstype}} parameters are not needed.<br />
<br />
== Configure systemd ZFS mounts ==<br />
<br />
For your system to be able to reboot without issues, you need to enable the {{ic|zfs.target}} to auto mount the pools and set the hostid.<br />
<br />
{{Note|The instructions in this section assume you are still in {{ic|arch-chroot}}}}<br />
<br />
For each pool you want automatically mounted execute:<br />
<br />
# zpool set cachefile=/etc/zfs/zpool.cache <pool><br />
<br />
Enable the target with [[systemd]]:<br />
<br />
# systemctl enable zfs.target<br />
<br />
In order to mount zfs pools automatically on boot you need to enable the following services and targets:<br />
<br />
# systemctl enable zfs-import-cache<br />
# systemctl enable zfs-mount<br />
# systemctl enable zfs-import.target<br />
<br />
When running ZFS on root, the machine's hostid will not be available at the time of mounting the root filesystem. There are two solutions to this. You can either place your spl hostid in the [[kernel parameters]] in your boot loader. For example, adding {{ic|1=spl.spl_hostid=0x00bab10c}}, to get your number use the {{ic|hostid}} command.<br />
<br />
The other, and suggested, solution is to make sure that there is a hostid in {{ic|/etc/hostid}}, and then regenerate the initramfs image which will copy the hostid into the initramfs image. To write the hostid file safely you need to use the {{ic|zgenhostid}} command.<br />
<br />
To use the libc-generated hostid (recommended):<br />
<br />
# zgenhostid $(hostid)<br />
<br />
To use a custom hostid (must be hexadecimal and 8 characters long):<br />
<br />
# zgenhostid deadbeef<br />
<br />
To let the tool generate a hostid:<br />
<br />
# zgenhostid<br />
<br />
Do not forget to regenerate your image using [[mkinitcpio]].<br />
<br />
== Unmount and restart ==<br />
<br />
We are almost done!<br />
<br />
# umount /mnt/boot (if you have a legacy boot partition)<br />
# zfs umount -a<br />
# zpool export zroot<br />
<br />
Now reboot.<br />
<br />
{{Warning|If you do not properly export the zpool, the pool will refuse to import in the ramdisk environment and you will be stuck at the busybox terminal.}}<br />
<br />
=== Loading password from USB-Stick ===<br />
<br />
It is possible to store password on usb-stick and load it when booting:<br />
<br />
Save password on first bytes of usb-stick:<br />
<br />
# dd if=your_password_file bs=32 count=1 of=/dev/disk/by-id/usb_stick<br />
<br />
To create partition zfs partition you can either use previous described method with password prompt or pipe with [[dd]]:<br />
<br />
# dd if=/dev/disk/by-id/usb_stick bs=32 count=1 | zfs create -o encryption=on -o keyformat=passphrase zroot/ROOT<br />
<br />
Next step is modyfing zfs hook. By default zfs prompts for password. You have to change it to have it piped with dd from your pendrive. In order to do so modify /usr/lib/initcpio/hooks/zfs and change line:<br />
<br />
# ! eval zfs load-key "${encryptionroot}"; do<br />
<br />
to:<br />
<br />
# ! eval dd if=/dev/disk/by-id/usb_stick bs=32 count=1 | zfs load-key "${encryptionroot}"; do<br />
<br />
You are modifying your zfs hook so do not forget to regenerate your image using [[mkinitcpio]]. Now zfs should load password from your usb-stick on boot.<br />
<br />
== Troubleshooting ==<br />
<br />
=== System fails to boot due to: cannot import zroot: no such pool available ===<br />
<br />
You can try the following steps and see if they can help.<br />
<br />
* Use the kernel modules from the [[Unofficial user repositories#archzfs|archzfs repo]] instead of the dkms version. You can go back to the dkms version after a sucessfull boot.<br />
* Remove the {{ic|/etc/zfs/zpool.cache}} and run:<br />
# zpool set cachefile=none zroot<br />
* Remove the {{ic|/etc/hostid}}.<br />
* Rebuild your initramfs.<br />
<br />
== See also ==<br />
<br />
* [https://github.com/dajhorn/pkg-zfs/wiki/HOWTO-install-Ubuntu-to-a-Native-ZFS-Root-Filesystem HOWTO install Ubuntu to a Native ZFS Root]<br />
* [https://lildude.co.uk/zfs-cheatsheet ZFS cheatsheet]<br />
* [[Funtoo:ZFS Install Guide]]<br />
* [https://kiljan.org/2018/09/23/a-reference-guide-to-zfs-on-arch-linux/ A reference guide to ZFS on Arch Linux]<br />
* [https://ramsdenj.com/2016/06/23/arch-linux-on-zfs-part-2-installation.html Arch Linux On Zfs ]<br />
* [https://www.youtube.com/watch?v=mLbtJQmfumI Youtube: Open-ZFS Bootcamp]</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_on_ZFS&diff=704333Install Arch Linux on ZFS2021-12-04T21:24:43Z<p>Arzeth: /* Install and configure the bootloader */ I had "Permission denied", so here's how to deal with it</p>
<hr />
<div>[[Category:Installation process]]<br />
[[ja:ZFS に Arch Linux をインストール]]<br />
{{Related articles start}}<br />
{{Related|ZFS}}<br />
{{Related|Experimenting with ZFS}}<br />
{{Related articles end}}<br />
This article details the steps required to install Arch Linux onto a ZFS root filesystem.<br />
<br />
{{Warning| Blindly copying and pasting this wiki will not work. It is necessary to take the time to understand the boot process, and what is done when creating the pool and datasets. Here are some useful links:<br />
<br />
* [https://www.freebsd.org/doc/handbook/zfs.html FreeBSD ZFS Handbook]<br />
* [https://github.com/zfsonlinux/zfs/wiki ZFSOnLinux wiki]<br />
* [http://open-zfs.org/wiki/System_Administration OpenZFS wiki]<br />
* [https://pthree.org/2012/04/17/install-zfs-on-debian-gnulinux/ Aaron Toponce Install ZFS on Debian GNU/Linux]<br />
* [https://openzfs.github.io/openzfs-docs/Getting%20Started/Arch%20Linux/ OpenZFS documentation for Arch Linux]<br />
}}<br />
<br />
== Installation ==<br />
<br />
To install Archlinux on ZFS, you need to boot archiso system with ZFS module.<br />
<br />
=== Get ZFS module on archiso system ===<br />
<br />
A script to easily install and load the ZFS module on running archiso system. It should work on any archiso version.<br />
<br />
See [https://github.com/eoli3n/archiso-zfs eoli3n/archiso-zfs].<br />
<br />
=== Embedding ZFS module into custom archiso ===<br />
<br />
To build a custom archiso, see [[ZFS#Create an Archiso image with ZFS support|ZFS]] article.<br />
<br />
An unofficial weekly build is available [https://gitlab.com/m_zhou/archiso/ here].<br />
<br />
== Partition the destination drive ==<br />
<br />
Review [[Partitioning]] for information on determining the partition table type to use for ZFS. ZFS supports GPT and MBR partition tables.<br />
<br />
ZFS manages its own partitions, so only a basic partition table scheme is required. The partition that will contain the ZFS filesystem should be of the type {{ic|bf00}}, or "Solaris Root".<br />
<br />
Drives larger than 2TB require a GPT partition table. GRUB on BIOS/GPT configurations require a small (1~2MiB) BIOS boot partition to embed its image of boot code.<br />
<br />
Depending upon your machine's firmware or your choice of boot mode, booting may or may not require an EFI partition. On a BIOS machine (or a UEFI machine booting in legacy mode) EFI partition is not required. Consult [[Arch boot process#Boot loader]] for more information.<br />
<br />
=== Partition scheme ===<br />
<br />
Here is an example of a basic partition scheme that could be employed for your ZFS root install on a BIOS/MBR installation using GRUB:<br />
<br />
{{bc|<nowiki><br />
Part Size Type<br />
---- ---- -------------------------<br />
1 XXXG Solaris Root (bf00)<br />
</nowiki>}}<br />
<br />
Using GRUB on a BIOS (or UEFI machine in legacy boot mode) machine but using a GPT partition table:<br />
<br />
{{bc|<nowiki><br />
Part Size Type<br />
---- ---- -------------------------<br />
1 2M BIOS boot partition (ef02)<br />
2 XXXG Solaris Root (bf00)<br />
</nowiki>}}<br />
<br />
Another example, this time using a UEFI-specific bootloader (such as [[rEFInd]]) with an GPT partition table:<br />
<br />
{{bc|<nowiki><br />
Part Size Type<br />
---- ---- -------------------------<br />
1 100M EFI boot partition (ef00)<br />
2 XXXG Solaris Root (bf00)<br />
</nowiki>}}<br />
<br />
ZFS does not support swap files. If you require a swap partition, see [[ZFS#Swap volume]] for creating a swap ZVOL.<br />
<br />
{{Tip|Bootloaders with support for ZFS are described in [[#Install and configure the bootloader]].}}<br />
<br />
{{Warning|Several GRUB bugs ([https://savannah.gnu.org/bugs/?42861 bug #42861], [https://github.com/zfsonlinux/grub/issues/5 zfsonlinux/grub/issues/5]) complicate installing it on ZFS partitions, see [[#Install and configure the bootloader]] for a workaround}}<br />
<br />
=== Example parted commands ===<br />
<br />
Here are some example commands to partition a drive for the second scenario above ie using BIOS/legacy boot mode with a GPT partition table and a (slighty more than) 1MB BIOS boot partition for GRUB:<br />
<br />
# parted /dev/sdx<br />
(parted)mklabel gpt<br />
(parted)mkpart non-fs 0% 2<br />
(parted)mkpart primary 2 100%<br />
(parted)set 1 bios_grub on<br />
(parted)set 2 boot on<br />
(parted)quit<br />
<br />
You can achieve the above in a single command like so:<br />
<br />
# parted --script /dev/sdx mklabel gpt mkpart non-fs 0% 2 mkpart primary 2 100% set 1 bios_grub on set 2 boot on<br />
<br />
If you are creating an EFI partition then that should have the boot flag set instead of the root partition.<br />
<br />
== Format the destination disk ==<br />
<br />
If you have opted for a boot partition as well as any other non-ZFS system partitions then format them. Do not do anything to the Solaris partition nor to the BIOS boot partition. ZFS will manage the first, and your bootloader the second.<br />
<br />
== Setup the ZFS filesystem ==<br />
<br />
{{Warning|Do not use '-' in the names of your datasets. ([https://github.com/zfsonlinux/zfs/commit/c39b2786ac98ab87d6dda00aa83b399ed175055a see this "feature"])}}<br />
<br />
First, make sure the ZFS modules are loaded,<br />
<br />
# modprobe zfs<br />
<br />
=== Create the root zpool ===<br />
<br />
Create your pool and set all default dataset options. All dataset created on the zpool will inherit of each {{ic|-O}} set at the zpool creation. Default options are detailed in [https://openzfs.github.io/openzfs-docs/Getting%20Started/Debian/Debian%20Buster%20Root%20on%20ZFS.html#step-2-disk-formatting Debian Buster Root on ZFS. Step 2: Disk Formatting].<br />
<br />
{{Note|Use {{ic|1=-o ashift=9}} for disks with a 512 byte physical sector size or {{ic|1=-o ashift=12}} for disks with a 4096 byte physical sector size. See {{ic|lsblk -S -o NAME,PHY-SEC}} to get the physical sector size of each SCSI/SATA disk. Remove {{ic|-S}} if you want the same value from all devices.}}<br />
<br />
{{Warning|Keep in mind that most modern devices use a 4096 byte physical sector size, even though some report 512. This is especially true for SSDs. Selecting {{ic|1=ashift=9}} on a 4096 byte sector size (even if it reports 512) '''will''' incur a performance penalty. Selecting {{ic|1=ashift=12}} on a 512 byte sector size may incur in a capacity penalty, but no performance penalty. If in doubt, for a modern drive, err on the side of {{ic|1=ashift=12}}, or research your particular device for the appropriate value. Refer to [https://github.com/openzfs/zfs/issues/967 OpenZFS issue #967] for a related discussion, and [https://github.com/openzfs/zfs/issues/2497 OpenZFS issue #2497] for a consequence of a higher ashift value.<br />
}}<br />
<br />
# zpool create -f -o ashift=12 \<br />
-O acltype=posixacl \<br />
-O relatime=on \<br />
-O xattr=sa \<br />
-O dnodesize=legacy \<br />
-O normalization=formD \<br />
-O mountpoint=none \<br />
-O canmount=off \<br />
-O devices=off \<br />
-R /mnt \<br />
zroot /dev/disk/by-id/''id-to-partition-partx''<br />
<br />
==== Compression and native encryption ====<br />
<br />
This will enable compression and native encryption by default on all datasets:<br />
<br />
# zpool create -f -o ashift=12 \<br />
-O acltype=posixacl \<br />
-O relatime=on \<br />
-O xattr=sa \<br />
-O dnodesize=legacy \<br />
-O normalization=formD \<br />
-O mountpoint=none \<br />
-O canmount=off \<br />
-O devices=off \<br />
-R /mnt \<br />
-O compression=lz4 \<br />
-O encryption=aes-256-gcm \<br />
-O keyformat=passphrase \<br />
-O keylocation=prompt \<br />
zroot /dev/disk/by-id/''id-to-partition-partx''<br />
<br />
{{Warning|<br />
* Always use id names when working with ZFS, otherwise import errors will occur.<br />
* [[GRUB]] users should keep in mind that the ''zpool-create'' command normally enables all features, '''some of which may not be supported by GRUB'''. See: [[ZFS#GRUB-compatible pool creation]].<br />
}}<br />
<br />
=== Create your datasets ===<br />
<br />
Instead of using conventional disk partitions, ZFS has the concept of datasets to manage your storage. Unlike disk partitions, datasets have no fixed size and allow for different attributes, such as compression, to be applied per dataset. Normal ZFS datasets are mounted automatically by ZFS whilst legacy datasets are required to be mounted using fstab or with the traditional mount command.<br />
<br />
One of the most useful features of ZFS is boot environments. Boot environments allow you to create a bootable snapshot of your system that you can revert to at any time instantly by simply rebooting and booting from that boot environment. This can make doing system updates much safer and is also incredibly useful for developing and testing software. In order to be able to use a boot environment manager such as [https://github.com/b333z/beadm beadm], {{AUR|zectl}} (systemd-boot), or {{AUR|zedenv}} (GRUB) to manage boot environments, your datasets must be configured properly. Key to this are that you split your data directories (such as {{ic|/home}}) into datasets that are distinct from your system datasets and that you do not place data in the root of the pool as this cannot be moved afterwards.<br />
<br />
You should always create a dataset for at least your root filesystem and in nearly all cases you will also want {{ic|/home}} to be in a separate dataset. You may decide you want your logs to persist over boot environments. If you are a running any software that stores data outside of {{ic|/home}} (such as is the case for database servers) you should structure your datasets so that the data directories of the software you want to run are separated out from the root dataset.<br />
<br />
With these example commands, we will create a basic boot environment compatible configuration comprising of just root and {{ic|/home}} datasets. It inherits default options from [[#Create the root zpool|zpool creation.]]<br />
<br />
# zfs create -o mountpoint=none zroot/data<br />
# zfs create -o mountpoint=none zroot/ROOT<br />
# zfs create -o mountpoint=/ -o canmount=noauto zroot/ROOT/default<br />
# zfs create -o mountpoint=/home zroot/data/home<br />
<br />
You can also create your ROOT dataset without having to specify mountpoint to / since GRUB will mount it to / anyway. That gives you possibility to boot into some old versions of root just by cloning it and putting as menuentry of GRUB. In such, you can create ROOT with the following command:<br />
<br />
# zfs create -o mountpoint=/roots/default zroot/ROOT/default<br />
<br />
You can store {{ic|/root}} in your {{ic|zroot/data/home}} dataset.<br />
<br />
# zfs create -o mountpoint=/root zroot/data/home/root<br />
<br />
You will need to enable some options for datasets which hold specific directories:<br />
<br />
{| class="wikitable" style="text-align: left;"<br />
|+ Options required by specific directories<br />
! scope="col" | Directory<br />
! scope="col" | Dataset option<br />
! scope="col" | Details<br />
|-<br />
! /<br />
| canmount=noauto<br />
|<br />
|-<br />
|-<br />
! /var/log/journal<br />
| acltype=posixacl<br />
| [[Systemd#systemd-tmpfiles-setup.service fails to start at boot]]<br />
|-<br />
|}<br />
<br />
==== System datasets ====<br />
<br />
To create datasets for system directories, use {{ic|1=canmount=off}}.<br />
<br />
For some examples, please read [https://openzfs.github.io/openzfs-docs/Getting%20Started/Debian/Debian%20Buster%20Root%20on%20ZFS.html#step-3-system-installation Debian-Buster-Root-on-ZFS#step-3-system-installation]<br />
<br />
# zfs create -o mountpoint=/var -o canmount=off zroot/var<br />
# zfs create zroot/var/log<br />
# zfs create -o mountpoint=/var/lib -o canmount=off zroot/var/lib<br />
# zfs create zroot/var/lib/libvirt<br />
# zfs create zroot/var/lib/docker<br />
<br />
=== Export/Import your datasets ===<br />
<br />
To validate your configurations, export then reimport all your zpools.<br />
<br />
{{Warning|Do not skip this, otherwise you will be required to use {{ic|-f}} when importing your pools. This unloads the imported pool.}}<br />
<br />
{{Note|This might fail if you added a swap partition. You need to turn it off with the ''swapoff'' command.}}<br />
<br />
# zpool export zroot<br />
# zpool import -d /dev/disk/by-id -R /mnt zroot -N<br />
<br />
{{Note|{{ic|-d}} is not the actual device ID, but the {{ic|/dev/by-id}} directory containing the symbolic links.<br />
<br />
If this command fails and you are asked to import your pool via its numeric ID, run {{ic|zpool import}} to find out the ID of your pool then use a command such as:<br />
<br />
# zpool import 9876543212345678910 -R /mnt zroot<br />
}}<br />
<br />
If you used native encryption, load zfs key.<br />
<br />
# zfs load-key zroot<br />
<br />
Manually mount your rootfs dataset because it uses {{ic|1=canmount=noauto}}, then mount all others datasets.<br />
<br />
# zfs mount zroot/ROOT/default<br />
# zfs mount -a<br />
<br />
The ZFS filesystem is now ready to use.<br />
<br />
=== Configure the root filesystem ===<br />
<br />
If you used legacy datasets, it must be listed in {{ic|/etc/fstab}}.<br />
<br />
Set the bootfs property on the descendant root filesystem so the boot loader knows where to find the operating system.<br />
<br />
# zpool set bootfs=zroot/ROOT/default zroot<br />
<br />
Be sure to bring the {{ic|zpool.cache}} file into your new system. This is required later for the ZFS daemon to start.<br />
<br />
# cp /etc/zfs/zpool.cache /mnt/etc/zfs/zpool.cache<br />
<br />
if you do not have {{ic|/etc/zfs/zpool.cache}}, create it:<br />
<br />
# zpool set cachefile=/etc/zfs/zpool.cache zroot<br />
<br />
== Install and configure Arch Linux ==<br />
<br />
Follow the following steps using the [[Installation guide]]. It will be noted where special consideration must be taken for ZFSonLinux.<br />
<br />
* First mount any legacy or non-ZFS boot or system partitions using the mount command.<br />
<br />
* Install the base system.<br />
<br />
* The procedure described in [[Installation guide#Fstab]] is usually overkill for ZFS. ZFS usually auto mounts its own partitions, so we do not need ZFS partitions in {{ic|fstab}} file, unless the user made legacy datasets of system directories. To generate the {{ic|fstab}} for filesystems, use:<br />
<br />
# genfstab -U -p /mnt >> /mnt/etc/fstab<br />
<br />
* Change root into the new system, per [[Installation guide#Chroot]]:<br />
<br />
# arch-chroot /mnt<br />
<br />
* Edit the {{ic|/etc/fstab}}:<br />
<br />
{{Note|<br />
* If you chose to create legacy datasets for system directories, keep them in this {{ic|fstab}}!<br />
* Comment out all non-legacy datasets apart from the swap file and the boot/EFI partition. It is a convention to replace the swap's uuid with {{ic|/dev/zvol/zroot/swap}}.<br />
}}<br />
<br />
* You need to add the [[Unofficial_user_repositories#archzfs|Arch ZFS]] repository to {{ic|/etc/pacman.conf}}, [[Package_signing#Adding_unofficial_keys|sign its key]] and [[install]] '''zfs-linux''' (or '''zfs-linux-lts''' if you are running the LTS kernel) within the arch-chroot before you can update the ramdisk with ZFS support.<br />
<br />
* When creating the initial ramdisk, first edit {{ic|/etc/mkinitcpio.conf}} and add {{ic|zfs}} before filesystems. Also, move {{ic|keyboard}} hook before {{ic|zfs}} so you can type in console if something goes wrong. You may also remove fsck (if you are not using Ext3 or Ext4). Your {{ic|HOOKS}} line should look something like this:<br />
HOOKS=(base udev autodetect modconf block keyboard zfs filesystems)<br />
<br />
When using systemd in the initrd, you need to install {{AUR|mkinitcpio-sd-zfs}} and add the {{ic|sd-zfs}} hook after the {{ic|systemd}} hook instead of the {{ic|zfs}} hook. Keep in mind that this hook uses different kernel parameters than the default {{ic|zfs}} hook, more information can be found at the [https://github.com/dasJ/sd-zfs project page].<br />
{{Note|{{ic|sd-zfs}} does not support native encryption yet [https://github.com/dasJ/sd-zfs/issues/4 dasJ/sd-zfs/issues/4].}}<br />
<br />
{{Note|<br />
* If you are using a separate dataset for {{ic|/usr}} and have followed the instructions below, you must make sure you have the {{ic|usr}} hook enabled after {{ic|zfs}}, or your system will not boot.<br />
* When you generate the initramfs, the {{ic|zpool.cache}} is copied into the initrd. If you did not generate it before, or needed to regenerate it, remember to regenerate the initramfs again.<br />
* You can also use {{ic|legacy}} mountpoint to let fstab mount it<br />
}}<br />
<br />
* [[Regenerate the initramfs]].<br />
<br />
== Install and configure the bootloader ==<br />
<br />
=== Using GRUB for EFI/BIOS ===<br />
<br />
If you use GRUB, you can store your {{ic|/boot}} on a zpool. Please read [https://openzfs.github.io/openzfs-docs/Getting%20Started/Debian/Debian%20Buster%20Root%20on%20ZFS.html#step-3-system-installation Debian-Buster-Root-on-ZFS#step-3-system-installation].<br />
<br />
Install GRUB onto your disk as instructed here: [[GRUB#BIOS systems]] or [[GRUB#UEFI systems]]. The GRUB [https://www.gnu.org/software/grub/manual/grub.html#Configuration manual] provides detailed information on manually configuring the software which you can supplement with [[GRUB]] and [[GRUB/Tips and tricks]].<br />
<br />
==== bug: broken root pool detection ====<br />
<br />
Because of a known [https://github.com/zfsonlinux/grub/issues/22 bug], ''grub-mkconfig'' will fail to detect the root pool and omit in {{ic|/boot/grub/grub.cfg}}. Until this is fixed, there are two possible workarounds:<br />
<br />
* Workaround A: Modify code for rpool detection in {{ic|/etc/grub.d/10_linux}}. Replace<br />
:{{bc|1=rpool=`${grub_probe} --device ${GRUB_DEVICE} --target=fs_label 2>/dev/null {{!}}{{!}} true`}}<br />
:with<br />
:{{bc|1=rpool=`zdb -l \$\{GRUB_DEVICE\} {{!}} grep " name:" {{!}} cut -d\' -f2`}}<br />
:This will detect the correct root pool name and write working path to {{ic|/boot/grub/grub.cfg}} any time ''grub-mkconfig'' is used.<br />
* Workaround B: Hardcoded path to root dataset in the kernel command line via {{ic|/etc/default/grub}}:<br />
:{{bc|1=GRUB_CMDLINE_LINUX="root=ZFS=zroot/ROOT/default"}}<br />
:Because {{ic|GRUB_CMDLINE_LINUX}} is added at the end of the kernel command line, this path will overwrite the wrong, auto-generated one. Even though this is the less intrusive option to fix the issue, you will have to make sure the path is correct yourself.<br />
<br />
==== error: failed to get canonical path of ====<br />
<br />
''grub-mkconfig'' fails to properly generate entries for systems hosted on ZFS.<br />
<br />
# grub-mkconfig -o /boot/grub/grub.cfg<br />
/usr/bin/grub-probe: error: failed to get canonical path of `/dev/bus-Your_Disk_ID-part#'<br />
<br />
grub-install: error: failed to get canonical path of `/dev/bus-Your_Disk_ID-part#'<br />
<br />
To work around this you must set this environment variable: {{ic|1=ZPOOL_VDEV_NAME_PATH=1}}. For example:<br />
<br />
# ZPOOL_VDEV_NAME_PATH=1 grub-mkconfig -o /boot/grub/grub.cfg<br />
<br />
==== error: unknown filesystem ====<br />
<br />
GRUB tools like ''grub-probe'' or ''grub-install'' may fail with the error {{ic|1=unknown filesystem}} when filesystem detection fails. This may happen due to the filesystem not being supported by GRUB, or in the case of ZFS, unsupported features may be present (refer to [[ZFS#GRUB-compatible pool creation]] for appropriate features to include in a boot zpool.)<br />
<br />
In order to troubleshoot the error, understand which filesystem it is failing to identify (e.g. run ''grub-probe'' on the suspects, like {{ic|1=grub-probe /}} or {{ic|1=grub-probe /boot}}). An example interaction follows:<br />
<br />
# grub-probe /boot<br />
zfs<br />
<br />
# grub-probe /<br />
grub-probe: error: unknown filesystem.<br />
<br />
After identifying the problem filesystem, run {{ic|1=grub-probe -vvvv /}} and scan the output for the filesystem it was expected to identify. In this case, ZFS was expected, but the following output was generated:<br />
<br />
{{hc|1=grub-probe -vvvv /|2=<br />
(...)<br />
grub-core/kern/fs.c:56: Detecting zfs...<br />
grub-core/osdep/hostdisk.c:420: opening the device `/dev/sda4' in open_device()<br />
grub-core/fs/zfs/zfs.c:1199: label ok 0<br />
grub-core/osdep/hostdisk.c:399: reusing open device `/dev/sda4'<br />
grub-core/fs/zfs/zfs.c:1014: check 2 passed<br />
grub-core/fs/zfs/zfs.c:1025: check 3 passed<br />
grub-core/fs/zfs/zfs.c:1032: check 4 passed<br />
grub-core/fs/zfs/zfs.c:1042: check 6 passed<br />
grub-core/fs/zfs/zfs.c:1050: check 7 passed<br />
grub-core/fs/zfs/zfs.c:1061: check 8 passed<br />
grub-core/fs/zfs/zfs.c:1071: check 9 passed<br />
grub-core/fs/zfs/zfs.c:1093: check 11 passed<br />
grub-core/fs/zfs/zfs.c:1119: check 10 passed<br />
grub-core/fs/zfs/zfs.c:1135: str=com.delphix:hole_birth<br />
grub-core/fs/zfs/zfs.c:1135: str=com.delphix:embedded_data<br />
grub-core/fs/zfs/zfs.c:1144: check 12 passed (feature flags)<br />
grub-core/fs/zfs/zfs.c:1884: zio_read: E 0: size 4096/4096<br />
(...)<br />
grub-core/osdep/hostdisk.c:399: reusing open device `/dev/sda4'<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.delphix:extensible_dataset, value = 18, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.datto:bookmark_v2, value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.datto:encryption, value = c, cd = 0 # <------------------<br />
grub-core/kern/fs.c:78: zfs detection failed. # <----------------------------------------------------<br />
grub-core/kern/fs.c:56: Detecting xfs...<br />
grub-core/fs/xfs.c:931: Reading sb<br />
grub-core/fs/xfs.c:270: Validating superblock<br />
grub-core/kern/fs.c:78: xfs detection failed.<br />
grub-core/kern/fs.c:56: Detecting ufs2...<br />
(...)<br />
grub-core/kern/fs.c:56: Detecting affs...<br />
grub-core/kern/fs.c:78: affs detection failed.<br />
grub-probe: error: unknown filesystem.<br />
}}<br />
<br />
This shows that ZFS detection went well until the {{ic|com.datto:encryption}} feature was detected. Since ZFS Native Encryption is not supported by GRUB (as of August 2021), detection of ZFS failed. A second, GRUB-compatible zpool may be appropriate to boot into an encrypted system - as of August 2021, this is the recommended approach (refer to the [https://openzfs.github.io/openzfs-docs/Getting%20Started/Arch%20Linux/Root%20on%20ZFS/0-overview.html relevant OpenZFS project page]).<br />
<br />
A successful execution of {{ic|grub-probe}} on a GRUB-compatible zpool looks like this:<br />
{{hc|1=grub-probe -vvvv /boot|2=<br />
(...)<br />
grub-core/osdep/hostdisk.c:399: reusing open device `/dev/sda3'<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.delphix:extensible_dataset, value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.delphix:embedded_data, value = 1, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = com.delphix:hole_birth, value = 1, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = org.open-zfs:large_blocks, value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = org.illumos:lz4_compress, value = 1, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = , value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:2117: zap: name = , value = 0, cd = 0<br />
grub-core/fs/zfs/zfs.c:3285: alive<br />
(...)<br />
grub-core/fs/zfs/zfs.c:1906: endian = 1<br />
grub-core/fs/zfs/zfs.c:597: dva=8, 20008<br />
grub-core/fs/zfs/zfs.c:2697: alive<br />
zfs<br />
}}<br />
<br />
==== Permission denied ====<br />
If you get this error while booting, then replace contents of {{ic|/usr/lib/initcpio/hooks/zfs}} with one that supports importing encrypted zpools:<br />
# wget -O /usr/lib/initcpio/hooks/zfs 'https://aur.archlinux.org/cgit/aur.git/plain/zfs-utils.initcpio.hook?h=zfs-utils-common'<br />
<br />
Then update {{ic|initramfs*.img}} in {{ic|/boot/}}:<br />
# mkinitcpio<br />
Now it will, just like LUKS, ask for a password instead of always saying "Permission denied". Note that this error was not because you, for example, enabled {{ic|1=-O encryption=aes-256-gcm}} and/or {{ic|1=-O compression=zstd-2}} with {{ic|1=-O recordsize=256k}}.<br />
<br />
At least, it works when a pool is created with {{ic|1=-O keyformat=passphrase -O keylocation=prompt}}<br />
<br />
Just in case, add {{ic|usr/lib/initcpio/hooks/zfs}} (yes, without a leading slash) to both {{ic|1=NoUpgrade=}} and {{ic|1=NoExtract=}} in {{ic|/etc/pacman.conf}}<br />
<br />
==== Booting your kernel and initrd from ZFS ====<br />
<br />
You may skip this section if you have your kernel and initrd on a separate {{ic|/boot}} partition using something like ext4 or vfat.<br />
<br />
Otherwise grub needs to load your kernel and initrd are from a ZFS dataset the kernel and initrd paths have to be in the following format:<br />
<br />
/dataset/@/actual/path<br />
<br />
Example with Arch installed on the root dataset:<br />
<br />
{{hc|/boot/grub/grub.cfg|2=<br />
set timeout=5<br />
set default=0<br />
<br />
menuentry "Arch Linux" {<br />
search -u UUID<br />
linux /@/boot/vmlinuz-linux zfs=zroot rw<br />
initrd /@/boot/initramfs-linux.img<br />
}<br />
}}<br />
<br />
Example with Arch installed on a nested dataset:<br />
<br />
{{hc|/boot/grub/grub.cfg|2=<br />
set timeout=5<br />
set default=0<br />
<br />
menuentry "Arch Linux" {<br />
search -u UUID<br />
linux /ROOT/default/@/boot/vmlinuz-linux zfs=zroot/ROOT/default rw<br />
initrd /ROOT/default/@/boot/initramfs-linux.img<br />
}<br />
}}<br />
<br />
Unlike with other filesystems, it is not necessary to specify {{ic|1=root=}} ({{ic|1=root=ZFS=zroot/ROOT/default}}), <br />
<br />
==== Booting your kernel and initrd from separate boot partition ====<br />
<br />
Example with a separate non-ZFS /boot partition and Arch installed on a nested dataset:<br />
<br />
{{hc|/boot/grub/grub.cfg|2=<br />
set timeout=5<br />
set default=0<br />
<br />
menuentry "Arch Linux" {<br />
search -u UUID<br />
linux /vmlinuz-linux zfs=zroot/ROOT/default rw<br />
initrd /initramfs-linux.img<br />
}<br />
}}<br />
<br />
=== Using systemd-boot for EFI only ===<br />
<br />
Systemd-boot cannot open ZFS zpools, you must store your {{ic|/boot}} on a separated VFAT or ext4 partition.<br />
<br />
{{Note|To be able to manage your Boot Environments with {{AUR|zectl}}, follow [https://github.com/johnramsden/zectl/blob/master/docs/plugins/systemdboot.md zectl/docs/plugins/systemdboot.md].}}<br />
<br />
Install bootloader on your {{ic|esp}}, following [[Systemd-boot#Installing the EFI boot manager]].<br />
<br />
Create a boot entry:<br />
<br />
{{hc|/efi/loader/entries/archlinux.conf|2=<br />
title Arch Linux<br />
linux vmlinuz-linux<br />
initrd intel-ucode.img<br />
initrd initramfs-linux.img<br />
options zfs=zroot/ROOT/default rw<br />
}}<br />
<br />
=== Using rEFInd for UEFI ===<br />
<br />
Use {{ic|EFISTUB}} and {{ic|rEFInd}} for the UEFI boot loader. The kernel parameters in {{ic|refind_linux.conf}} for ZFS should include {{ic|1=zfs=bootfs}} or {{ic|1=zfs=zroot}} so the system can boot from ZFS. The {{ic|root}} and {{ic|rootfstype}} parameters are not needed.<br />
<br />
== Configure systemd ZFS mounts ==<br />
<br />
For your system to be able to reboot without issues, you need to enable the {{ic|zfs.target}} to auto mount the pools and set the hostid.<br />
<br />
{{Note|The instructions in this section assume you are still in {{ic|arch-chroot}}}}<br />
<br />
For each pool you want automatically mounted execute:<br />
<br />
# zpool set cachefile=/etc/zfs/zpool.cache <pool><br />
<br />
Enable the target with [[systemd]]:<br />
<br />
# systemctl enable zfs.target<br />
<br />
In order to mount zfs pools automatically on boot you need to enable the following services and targets:<br />
<br />
# systemctl enable zfs-import-cache<br />
# systemctl enable zfs-mount<br />
# systemctl enable zfs-import.target<br />
<br />
When running ZFS on root, the machine's hostid will not be available at the time of mounting the root filesystem. There are two solutions to this. You can either place your spl hostid in the [[kernel parameters]] in your boot loader. For example, adding {{ic|1=spl.spl_hostid=0x00bab10c}}, to get your number use the {{ic|hostid}} command.<br />
<br />
The other, and suggested, solution is to make sure that there is a hostid in {{ic|/etc/hostid}}, and then regenerate the initramfs image which will copy the hostid into the initramfs image. To write the hostid file safely you need to use the {{ic|zgenhostid}} command.<br />
<br />
To use the libc-generated hostid (recommended):<br />
<br />
# zgenhostid $(hostid)<br />
<br />
To use a custom hostid (must be hexadecimal and 8 characters long):<br />
<br />
# zgenhostid deadbeef<br />
<br />
To let the tool generate a hostid:<br />
<br />
# zgenhostid<br />
<br />
Do not forget to regenerate your image using [[mkinitcpio]].<br />
<br />
== Unmount and restart ==<br />
<br />
We are almost done!<br />
<br />
# umount /mnt/boot (if you have a legacy boot partition)<br />
# zfs umount -a<br />
# zpool export zroot<br />
<br />
Now reboot.<br />
<br />
{{Warning|If you do not properly export the zpool, the pool will refuse to import in the ramdisk environment and you will be stuck at the busybox terminal.}}<br />
<br />
=== Loading password from USB-Stick ===<br />
<br />
It is possible to store password on usb-stick and load it when booting:<br />
<br />
Save password on first bytes of usb-stick:<br />
<br />
# dd if=your_password_file bs=32 count=1 of=/dev/disk/by-id/usb_stick<br />
<br />
To create partition zfs partition you can either use previous described method with password prompt or pipe with [[dd]]:<br />
<br />
# dd if=/dev/disk/by-id/usb_stick bs=32 count=1 | zfs create -o encryption=on -o keyformat=passphrase zroot/ROOT<br />
<br />
Next step is modyfing zfs hook. By default zfs prompts for password. You have to change it to have it piped with dd from your pendrive. In order to do so modify /usr/lib/initcpio/hooks/zfs and change line:<br />
<br />
# ! eval zfs load-key "${encryptionroot}"; do<br />
<br />
to:<br />
<br />
# ! eval dd if=/dev/disk/by-id/usb_stick bs=32 count=1 | zfs load-key "${encryptionroot}"; do<br />
<br />
You are modifying your zfs hook so do not forget to regenerate your image using [[mkinitcpio]]. Now zfs should load password from your usb-stick on boot.<br />
<br />
== Troubleshooting ==<br />
<br />
=== System fails to boot due to: cannot import zroot: no such pool available ===<br />
<br />
You can try the following steps and see if they can help.<br />
<br />
* Use the kernel modules from the [[Unofficial user repositories#archzfs|archzfs repo]] instead of the dkms version. You can go back to the dkms version after a sucessfull boot.<br />
* Remove the {{ic|/etc/zfs/zpool.cache}} and run:<br />
# zpool set cachefile=none zroot<br />
* Remove the {{ic|/etc/hostid}}.<br />
* Rebuild your initramfs.<br />
<br />
== See also ==<br />
<br />
* [https://github.com/dajhorn/pkg-zfs/wiki/HOWTO-install-Ubuntu-to-a-Native-ZFS-Root-Filesystem HOWTO install Ubuntu to a Native ZFS Root]<br />
* [https://lildude.co.uk/zfs-cheatsheet ZFS cheatsheet]<br />
* [[Funtoo:ZFS Install Guide]]<br />
* [https://kiljan.org/2018/09/23/a-reference-guide-to-zfs-on-arch-linux/ A reference guide to ZFS on Arch Linux]<br />
* [https://ramsdenj.com/2016/06/23/arch-linux-on-zfs-part-2-installation.html Arch Linux On Zfs ]<br />
* [https://www.youtube.com/watch?v=mLbtJQmfumI Youtube: Open-ZFS Bootcamp]</div>Arzethhttps://wiki.archlinux.org/index.php?title=OpenGL&diff=703933OpenGL2021-11-30T20:09:50Z<p>Arzeth: /* OpenGL over Vulkan (Zink) */ clarify my words</p>
<hr />
<div>[[Category:Graphics]]<br />
[[Category:Development]]<br />
From [[wikipedia:OpenGL]]:<br />
: OpenGL (Open Graphics Library) is a cross-language, cross-platform application programming interface (API) for rendering 2D and 3D vector graphics.<br />
<br />
Learn more at [https://www.khronos.org/opengl/ Khronos].<br />
<br />
== Installation ==<br />
<br />
To run any application that uses OpenGL you will need to [[install]] driver(s) for your hardware (either GPUs or CPUs)<br />
<br />
* {{Pkg|mesa}} is an open-source OpenGL implementation, continually updated to support the latest OpenGL specification. It has a collection of open-source drivers for [[Intel graphics]], [[ATI]], [[AMDGPU|AMD]], [[AMDGPU PRO|AMD PRO]], and [[NVIDIA]] GPUs and also provides software rasterizers, The included drivers in the package are<br />
** {{ic|i915}} : for GMA 916G as well as the i830, i845 and i865 integrated GPU series.<br />
** {{ic|i965}} : for Intel's Gen 4 hardware and later. It is officially supported by Intel.<br />
** {{ic|iris}} : for Intel's Gen 8 hardware and later. It is officially supported by Intel.<br />
** {{ic|r100}} : for AMD's Radeon R100 GPU series.<br />
** {{ic|r200}} : for AMD's Radeon R200 GPU series.<br />
** {{ic|r300}} : for AMD's Radeon R300, R400, and R500 GPU series.<br />
** {{ic|r600}} : for AMD's Radeon HD 2000 GPU series and later. It is officially supported by AMD.<br />
** {{ic|radeonsi}} : for AMD's Southern Island GPUs and later. It is officially supported by AMD.<br />
** {{ic|nouveau}} : [[Nouveau]] is the open-source driver for [[NVIDIA]] GPUs.<br />
** {{ic|virgl}} : is a virtual GPU driver for sharing a GPU with a host for virtual machines.<br />
** {{ic|svga}} : for VMware virtual GPUs.<br />
** {{ic|zink}} : is a Gallium driver, it can be used to run OpenGL on vulkan.<br />
** {{ic|swrast}} : Legacy software rasterizer.<br />
** {{ic|softpipe}} : Software rasterizer, a reference Gallium driver.<br />
** {{ic|llvmpipe}} : Software rasterizer, uses LLVM for x86 JIT code generation and is multi-threaded.<br />
** {{ic|swr}} : High performance software rasterizer that uses AVX and AVX2 CPU instructions, also known as [https://www.openswr.org/ OpenSWR].<br />
{{Note|The right driver for mesa should be selected automatically, you do not have to configure it, just install the package.}}<br />
<br />
* {{Pkg|nvidia-utils}} is proprietary driver for [[NVIDIA]] GPUs.<br />
<br />
* {{AUR|amdgpu-pro-libgl}} is proprietary driver for [[AMDGPU PRO|AMD PRO]] GPUs.<br />
<br />
{{Tip|<br />
* For AMD (and ATI) it is recommended to use the open-source driver unless you have a very strong reason to use proprietary one.<br />
* For NVIDIA installing the proprietary driver is mostly better for newer cards or better performance in general.}}<br />
<br />
== Verification ==<br />
<br />
To verify your OpenGL installation you can use {{Pkg|mesa-utils}} {{ic|glxinfo}} and you should get output like this :<br />
<br />
{{hc|1=$ glxinfo {{!}} grep OpenGL|2=<br />
OpenGL vendor string: X.Org<br />
OpenGL renderer string: AMD RV620 (DRM 2.50.0 / 5.10.12-arch1-1, LLVM 11.0.1)<br />
OpenGL core profile version string: 3.3 (Core Profile) Mesa 20.3.4<br />
OpenGL core profile shading language version string: 3.30<br />
OpenGL core profile context flags: (none)<br />
OpenGL core profile profile mask: core profile<br />
OpenGL core profile extensions:<br />
OpenGL version string: 3.0 Mesa 20.3.4<br />
OpenGL shading language version string: 1.30<br />
OpenGL context flags: (none)<br />
OpenGL extensions:<br />
OpenGL ES profile version string: OpenGL ES 3.0 Mesa 20.3.4<br />
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.00<br />
OpenGL ES profile extensions:<br />
}}<br />
(with different values depending on your setup of course)<br />
<br />
From the same package you can also try {{ic|glxgears}}, you should see 3 rotating gears.<br />
<br />
== Switching between drivers ==<br />
<br />
For [[Hybrid graphics]] you might want to see [[PRIME]].<br />
{{Note|According to a [https://www.reddit.com/r/linuxhardware/comments/he9nhe/amd_and_nvidia_gpus_in_the_same_machine_it_works/ reddit post] can have 2 GPUs from different vendors working concurrently just fine.}}<br />
<br />
=== Mesa ===<br />
<br />
You can override used driver using the following [[environment variable]]:<br />
<br />
MESA_LOADER_DRIVER_OVERRIDE=''driver''<br />
<br />
By default mesa searches for drivers in {{ic|/lib/dri/}} you can see the list of drivers by<br />
<br />
$ ls /lib/dri/<br />
<br />
{{ic|''driver''}} is the name of the driver without {{ic|_dri.so}}. If it failed it will fallback to llvmpipe.<br />
<br />
You can also use OpenGL software rasterizer drivers by setting the following [[environment variables]]:<br />
<br />
LIBGL_ALWAYS_SOFTWARE=true<br />
GALLIUM_DRIVER=''driver''<br />
<br />
{{ic|''driver''}} is one of {{ic|softpipe}}, {{ic|llvmpipe}}, or {{ic|swr}}.<br />
<br />
{{Tip|As of the time of writing this llvmpipe & swr are faster than softpipe.}}<br />
<br />
== OpenGL over Vulkan (Zink) ==<br />
If you experience some issues (a bug in radeonsi/Iris/etc.), you may try using Zink.<br />
<br />
On AMD RX 6700 XT the FPS is 58-105% depending on a game compared to radeonsi according to [https://www.phoronix.com/scan.php?page=article&item=zink-ends-2021&num=1].<br />
<br />
On NVIDIA at the moment (2021-11-30) many apps still don't work on NVIDIA GPUs when using the latest driver 495.44 and mesa-git's master branch. When paired with Copper DRI extension (not yet upstreamed), the average FPS in Tomb Raider is 20% higher on RTX 2070.<br />
<br />
$ env __GLX_VENDOR_LIBRARY_NAME=mesa MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink %app%<br />
<br />
== Development ==<br />
<br />
{{Note|This section is for developers who wants to use OpenGL. End users do not need any thing from this section.}}<br />
Using OpenGL in code requires functions loader, read more at [https://www.khronos.org/opengl/wiki/OpenGL_Loading_Library Khronos].<br />
<br />
{{Expansion|Put list of packages relevant to OpenGL and in Arch repo}}<br />
<br />
=== OpenGL Hardware Database ===<br />
<br />
[https://www.gpuinfo.org/ GPUInfo] provides user reported GPU/driver combinations, supported extensions, capabilities, etc.</div>Arzethhttps://wiki.archlinux.org/index.php?title=OpenGL&diff=703932OpenGL2021-11-30T20:07:35Z<p>Arzeth: /* OpenGL over Vulkan (Zink) */ fix</p>
<hr />
<div>[[Category:Graphics]]<br />
[[Category:Development]]<br />
From [[wikipedia:OpenGL]]:<br />
: OpenGL (Open Graphics Library) is a cross-language, cross-platform application programming interface (API) for rendering 2D and 3D vector graphics.<br />
<br />
Learn more at [https://www.khronos.org/opengl/ Khronos].<br />
<br />
== Installation ==<br />
<br />
To run any application that uses OpenGL you will need to [[install]] driver(s) for your hardware (either GPUs or CPUs)<br />
<br />
* {{Pkg|mesa}} is an open-source OpenGL implementation, continually updated to support the latest OpenGL specification. It has a collection of open-source drivers for [[Intel graphics]], [[ATI]], [[AMDGPU|AMD]], [[AMDGPU PRO|AMD PRO]], and [[NVIDIA]] GPUs and also provides software rasterizers, The included drivers in the package are<br />
** {{ic|i915}} : for GMA 916G as well as the i830, i845 and i865 integrated GPU series.<br />
** {{ic|i965}} : for Intel's Gen 4 hardware and later. It is officially supported by Intel.<br />
** {{ic|iris}} : for Intel's Gen 8 hardware and later. It is officially supported by Intel.<br />
** {{ic|r100}} : for AMD's Radeon R100 GPU series.<br />
** {{ic|r200}} : for AMD's Radeon R200 GPU series.<br />
** {{ic|r300}} : for AMD's Radeon R300, R400, and R500 GPU series.<br />
** {{ic|r600}} : for AMD's Radeon HD 2000 GPU series and later. It is officially supported by AMD.<br />
** {{ic|radeonsi}} : for AMD's Southern Island GPUs and later. It is officially supported by AMD.<br />
** {{ic|nouveau}} : [[Nouveau]] is the open-source driver for [[NVIDIA]] GPUs.<br />
** {{ic|virgl}} : is a virtual GPU driver for sharing a GPU with a host for virtual machines.<br />
** {{ic|svga}} : for VMware virtual GPUs.<br />
** {{ic|zink}} : is a Gallium driver, it can be used to run OpenGL on vulkan.<br />
** {{ic|swrast}} : Legacy software rasterizer.<br />
** {{ic|softpipe}} : Software rasterizer, a reference Gallium driver.<br />
** {{ic|llvmpipe}} : Software rasterizer, uses LLVM for x86 JIT code generation and is multi-threaded.<br />
** {{ic|swr}} : High performance software rasterizer that uses AVX and AVX2 CPU instructions, also known as [https://www.openswr.org/ OpenSWR].<br />
{{Note|The right driver for mesa should be selected automatically, you do not have to configure it, just install the package.}}<br />
<br />
* {{Pkg|nvidia-utils}} is proprietary driver for [[NVIDIA]] GPUs.<br />
<br />
* {{AUR|amdgpu-pro-libgl}} is proprietary driver for [[AMDGPU PRO|AMD PRO]] GPUs.<br />
<br />
{{Tip|<br />
* For AMD (and ATI) it is recommended to use the open-source driver unless you have a very strong reason to use proprietary one.<br />
* For NVIDIA installing the proprietary driver is mostly better for newer cards or better performance in general.}}<br />
<br />
== Verification ==<br />
<br />
To verify your OpenGL installation you can use {{Pkg|mesa-utils}} {{ic|glxinfo}} and you should get output like this :<br />
<br />
{{hc|1=$ glxinfo {{!}} grep OpenGL|2=<br />
OpenGL vendor string: X.Org<br />
OpenGL renderer string: AMD RV620 (DRM 2.50.0 / 5.10.12-arch1-1, LLVM 11.0.1)<br />
OpenGL core profile version string: 3.3 (Core Profile) Mesa 20.3.4<br />
OpenGL core profile shading language version string: 3.30<br />
OpenGL core profile context flags: (none)<br />
OpenGL core profile profile mask: core profile<br />
OpenGL core profile extensions:<br />
OpenGL version string: 3.0 Mesa 20.3.4<br />
OpenGL shading language version string: 1.30<br />
OpenGL context flags: (none)<br />
OpenGL extensions:<br />
OpenGL ES profile version string: OpenGL ES 3.0 Mesa 20.3.4<br />
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.00<br />
OpenGL ES profile extensions:<br />
}}<br />
(with different values depending on your setup of course)<br />
<br />
From the same package you can also try {{ic|glxgears}}, you should see 3 rotating gears.<br />
<br />
== Switching between drivers ==<br />
<br />
For [[Hybrid graphics]] you might want to see [[PRIME]].<br />
{{Note|According to a [https://www.reddit.com/r/linuxhardware/comments/he9nhe/amd_and_nvidia_gpus_in_the_same_machine_it_works/ reddit post] can have 2 GPUs from different vendors working concurrently just fine.}}<br />
<br />
=== Mesa ===<br />
<br />
You can override used driver using the following [[environment variable]]:<br />
<br />
MESA_LOADER_DRIVER_OVERRIDE=''driver''<br />
<br />
By default mesa searches for drivers in {{ic|/lib/dri/}} you can see the list of drivers by<br />
<br />
$ ls /lib/dri/<br />
<br />
{{ic|''driver''}} is the name of the driver without {{ic|_dri.so}}. If it failed it will fallback to llvmpipe.<br />
<br />
You can also use OpenGL software rasterizer drivers by setting the following [[environment variables]]:<br />
<br />
LIBGL_ALWAYS_SOFTWARE=true<br />
GALLIUM_DRIVER=''driver''<br />
<br />
{{ic|''driver''}} is one of {{ic|softpipe}}, {{ic|llvmpipe}}, or {{ic|swr}}.<br />
<br />
{{Tip|As of the time of writing this llvmpipe & swr are faster than softpipe.}}<br />
<br />
== OpenGL over Vulkan (Zink) ==<br />
If you experience some issues (a bug in radeonsi/iris/etc.), you may try using Zink.<br />
<br />
On AMD RX 6700 XT the FPS is 58-105% depending on a game compared to radeonsi according to [https://www.phoronix.com/scan.php?page=article&item=zink-ends-2021&num=1].<br />
<br />
On NVIDIA at the moment (2021-11-30) many apps still don't work on NVIDIA GPUs when using the latest driver 495.44 and mesa-git's master branch. When paired with Copper DRI extension the FPS in Tomb Raider is 20% higher.<br />
<br />
$ env __GLX_VENDOR_LIBRARY_NAME=mesa MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink %app%<br />
<br />
== Development ==<br />
<br />
{{Note|This section is for developers who wants to use OpenGL. End users do not need any thing from this section.}}<br />
Using OpenGL in code requires functions loader, read more at [https://www.khronos.org/opengl/wiki/OpenGL_Loading_Library Khronos].<br />
<br />
{{Expansion|Put list of packages relevant to OpenGL and in Arch repo}}<br />
<br />
=== OpenGL Hardware Database ===<br />
<br />
[https://www.gpuinfo.org/ GPUInfo] provides user reported GPU/driver combinations, supported extensions, capabilities, etc.</div>Arzethhttps://wiki.archlinux.org/index.php?title=OpenGL&diff=703931OpenGL2021-11-30T20:03:02Z<p>Arzeth: /* OpenGL over Vulkan (Zink) */ fix whitespace</p>
<hr />
<div>[[Category:Graphics]]<br />
[[Category:Development]]<br />
From [[wikipedia:OpenGL]]:<br />
: OpenGL (Open Graphics Library) is a cross-language, cross-platform application programming interface (API) for rendering 2D and 3D vector graphics.<br />
<br />
Learn more at [https://www.khronos.org/opengl/ Khronos].<br />
<br />
== Installation ==<br />
<br />
To run any application that uses OpenGL you will need to [[install]] driver(s) for your hardware (either GPUs or CPUs)<br />
<br />
* {{Pkg|mesa}} is an open-source OpenGL implementation, continually updated to support the latest OpenGL specification. It has a collection of open-source drivers for [[Intel graphics]], [[ATI]], [[AMDGPU|AMD]], [[AMDGPU PRO|AMD PRO]], and [[NVIDIA]] GPUs and also provides software rasterizers, The included drivers in the package are<br />
** {{ic|i915}} : for GMA 916G as well as the i830, i845 and i865 integrated GPU series.<br />
** {{ic|i965}} : for Intel's Gen 4 hardware and later. It is officially supported by Intel.<br />
** {{ic|iris}} : for Intel's Gen 8 hardware and later. It is officially supported by Intel.<br />
** {{ic|r100}} : for AMD's Radeon R100 GPU series.<br />
** {{ic|r200}} : for AMD's Radeon R200 GPU series.<br />
** {{ic|r300}} : for AMD's Radeon R300, R400, and R500 GPU series.<br />
** {{ic|r600}} : for AMD's Radeon HD 2000 GPU series and later. It is officially supported by AMD.<br />
** {{ic|radeonsi}} : for AMD's Southern Island GPUs and later. It is officially supported by AMD.<br />
** {{ic|nouveau}} : [[Nouveau]] is the open-source driver for [[NVIDIA]] GPUs.<br />
** {{ic|virgl}} : is a virtual GPU driver for sharing a GPU with a host for virtual machines.<br />
** {{ic|svga}} : for VMware virtual GPUs.<br />
** {{ic|zink}} : is a Gallium driver, it can be used to run OpenGL on vulkan.<br />
** {{ic|swrast}} : Legacy software rasterizer.<br />
** {{ic|softpipe}} : Software rasterizer, a reference Gallium driver.<br />
** {{ic|llvmpipe}} : Software rasterizer, uses LLVM for x86 JIT code generation and is multi-threaded.<br />
** {{ic|swr}} : High performance software rasterizer that uses AVX and AVX2 CPU instructions, also known as [https://www.openswr.org/ OpenSWR].<br />
{{Note|The right driver for mesa should be selected automatically, you do not have to configure it, just install the package.}}<br />
<br />
* {{Pkg|nvidia-utils}} is proprietary driver for [[NVIDIA]] GPUs.<br />
<br />
* {{AUR|amdgpu-pro-libgl}} is proprietary driver for [[AMDGPU PRO|AMD PRO]] GPUs.<br />
<br />
{{Tip|<br />
* For AMD (and ATI) it is recommended to use the open-source driver unless you have a very strong reason to use proprietary one.<br />
* For NVIDIA installing the proprietary driver is mostly better for newer cards or better performance in general.}}<br />
<br />
== Verification ==<br />
<br />
To verify your OpenGL installation you can use {{Pkg|mesa-utils}} {{ic|glxinfo}} and you should get output like this :<br />
<br />
{{hc|1=$ glxinfo {{!}} grep OpenGL|2=<br />
OpenGL vendor string: X.Org<br />
OpenGL renderer string: AMD RV620 (DRM 2.50.0 / 5.10.12-arch1-1, LLVM 11.0.1)<br />
OpenGL core profile version string: 3.3 (Core Profile) Mesa 20.3.4<br />
OpenGL core profile shading language version string: 3.30<br />
OpenGL core profile context flags: (none)<br />
OpenGL core profile profile mask: core profile<br />
OpenGL core profile extensions:<br />
OpenGL version string: 3.0 Mesa 20.3.4<br />
OpenGL shading language version string: 1.30<br />
OpenGL context flags: (none)<br />
OpenGL extensions:<br />
OpenGL ES profile version string: OpenGL ES 3.0 Mesa 20.3.4<br />
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.00<br />
OpenGL ES profile extensions:<br />
}}<br />
(with different values depending on your setup of course)<br />
<br />
From the same package you can also try {{ic|glxgears}}, you should see 3 rotating gears.<br />
<br />
== Switching between drivers ==<br />
<br />
For [[Hybrid graphics]] you might want to see [[PRIME]].<br />
{{Note|According to a [https://www.reddit.com/r/linuxhardware/comments/he9nhe/amd_and_nvidia_gpus_in_the_same_machine_it_works/ reddit post] can have 2 GPUs from different vendors working concurrently just fine.}}<br />
<br />
=== Mesa ===<br />
<br />
You can override used driver using the following [[environment variable]]:<br />
<br />
MESA_LOADER_DRIVER_OVERRIDE=''driver''<br />
<br />
By default mesa searches for drivers in {{ic|/lib/dri/}} you can see the list of drivers by<br />
<br />
$ ls /lib/dri/<br />
<br />
{{ic|''driver''}} is the name of the driver without {{ic|_dri.so}}. If it failed it will fallback to llvmpipe.<br />
<br />
You can also use OpenGL software rasterizer drivers by setting the following [[environment variables]]:<br />
<br />
LIBGL_ALWAYS_SOFTWARE=true<br />
GALLIUM_DRIVER=''driver''<br />
<br />
{{ic|''driver''}} is one of {{ic|softpipe}}, {{ic|llvmpipe}}, or {{ic|swr}}.<br />
<br />
{{Tip|As of the time of writing this llvmpipe & swr are faster than softpipe.}}<br />
<br />
== OpenGL over Vulkan (Zink) ==<br />
If you experience some issues (a bug in radeonsi/iris/etc.), you may try using Zink.<br />
<br />
On AMD RX 6700 XT the FPS is 58-105% depending on a game compared to radeonsi according to [https://www.phoronix.com/scan.php?page=article&item=zink-ends-2021&num=1].<br />
<br />
On NVIDIA the FPS is sometimes higher (e.g. Tomb Raider), but at the moment (2021-11-30) many apps still don't work on NVIDIA GPUs even when using driver 495.44 and mesa-git's master branch.<br />
<br />
$ env __GLX_VENDOR_LIBRARY_NAME=mesa MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink %app%<br />
<br />
== Development ==<br />
<br />
{{Note|This section is for developers who wants to use OpenGL. End users do not need any thing from this section.}}<br />
Using OpenGL in code requires functions loader, read more at [https://www.khronos.org/opengl/wiki/OpenGL_Loading_Library Khronos].<br />
<br />
{{Expansion|Put list of packages relevant to OpenGL and in Arch repo}}<br />
<br />
=== OpenGL Hardware Database ===<br />
<br />
[https://www.gpuinfo.org/ GPUInfo] provides user reported GPU/driver combinations, supported extensions, capabilities, etc.</div>Arzethhttps://wiki.archlinux.org/index.php?title=OpenGL&diff=703929OpenGL2021-11-30T20:01:18Z<p>Arzeth: Add "OpenGL over Vulkan (Zink)" section</p>
<hr />
<div>[[Category:Graphics]]<br />
[[Category:Development]]<br />
From [[wikipedia:OpenGL]]:<br />
: OpenGL (Open Graphics Library) is a cross-language, cross-platform application programming interface (API) for rendering 2D and 3D vector graphics.<br />
<br />
Learn more at [https://www.khronos.org/opengl/ Khronos].<br />
<br />
== Installation ==<br />
<br />
To run any application that uses OpenGL you will need to [[install]] driver(s) for your hardware (either GPUs or CPUs)<br />
<br />
* {{Pkg|mesa}} is an open-source OpenGL implementation, continually updated to support the latest OpenGL specification. It has a collection of open-source drivers for [[Intel graphics]], [[ATI]], [[AMDGPU|AMD]], [[AMDGPU PRO|AMD PRO]], and [[NVIDIA]] GPUs and also provides software rasterizers, The included drivers in the package are<br />
** {{ic|i915}} : for GMA 916G as well as the i830, i845 and i865 integrated GPU series.<br />
** {{ic|i965}} : for Intel's Gen 4 hardware and later. It is officially supported by Intel.<br />
** {{ic|iris}} : for Intel's Gen 8 hardware and later. It is officially supported by Intel.<br />
** {{ic|r100}} : for AMD's Radeon R100 GPU series.<br />
** {{ic|r200}} : for AMD's Radeon R200 GPU series.<br />
** {{ic|r300}} : for AMD's Radeon R300, R400, and R500 GPU series.<br />
** {{ic|r600}} : for AMD's Radeon HD 2000 GPU series and later. It is officially supported by AMD.<br />
** {{ic|radeonsi}} : for AMD's Southern Island GPUs and later. It is officially supported by AMD.<br />
** {{ic|nouveau}} : [[Nouveau]] is the open-source driver for [[NVIDIA]] GPUs.<br />
** {{ic|virgl}} : is a virtual GPU driver for sharing a GPU with a host for virtual machines.<br />
** {{ic|svga}} : for VMware virtual GPUs.<br />
** {{ic|zink}} : is a Gallium driver, it can be used to run OpenGL on vulkan.<br />
** {{ic|swrast}} : Legacy software rasterizer.<br />
** {{ic|softpipe}} : Software rasterizer, a reference Gallium driver.<br />
** {{ic|llvmpipe}} : Software rasterizer, uses LLVM for x86 JIT code generation and is multi-threaded.<br />
** {{ic|swr}} : High performance software rasterizer that uses AVX and AVX2 CPU instructions, also known as [https://www.openswr.org/ OpenSWR].<br />
{{Note|The right driver for mesa should be selected automatically, you do not have to configure it, just install the package.}}<br />
<br />
* {{Pkg|nvidia-utils}} is proprietary driver for [[NVIDIA]] GPUs.<br />
<br />
* {{AUR|amdgpu-pro-libgl}} is proprietary driver for [[AMDGPU PRO|AMD PRO]] GPUs.<br />
<br />
{{Tip|<br />
* For AMD (and ATI) it is recommended to use the open-source driver unless you have a very strong reason to use proprietary one.<br />
* For NVIDIA installing the proprietary driver is mostly better for newer cards or better performance in general.}}<br />
<br />
== Verification ==<br />
<br />
To verify your OpenGL installation you can use {{Pkg|mesa-utils}} {{ic|glxinfo}} and you should get output like this :<br />
<br />
{{hc|1=$ glxinfo {{!}} grep OpenGL|2=<br />
OpenGL vendor string: X.Org<br />
OpenGL renderer string: AMD RV620 (DRM 2.50.0 / 5.10.12-arch1-1, LLVM 11.0.1)<br />
OpenGL core profile version string: 3.3 (Core Profile) Mesa 20.3.4<br />
OpenGL core profile shading language version string: 3.30<br />
OpenGL core profile context flags: (none)<br />
OpenGL core profile profile mask: core profile<br />
OpenGL core profile extensions:<br />
OpenGL version string: 3.0 Mesa 20.3.4<br />
OpenGL shading language version string: 1.30<br />
OpenGL context flags: (none)<br />
OpenGL extensions:<br />
OpenGL ES profile version string: OpenGL ES 3.0 Mesa 20.3.4<br />
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.00<br />
OpenGL ES profile extensions:<br />
}}<br />
(with different values depending on your setup of course)<br />
<br />
From the same package you can also try {{ic|glxgears}}, you should see 3 rotating gears.<br />
<br />
== Switching between drivers ==<br />
<br />
For [[Hybrid graphics]] you might want to see [[PRIME]].<br />
{{Note|According to a [https://www.reddit.com/r/linuxhardware/comments/he9nhe/amd_and_nvidia_gpus_in_the_same_machine_it_works/ reddit post] can have 2 GPUs from different vendors working concurrently just fine.}}<br />
<br />
=== Mesa ===<br />
<br />
You can override used driver using the following [[environment variable]]:<br />
<br />
MESA_LOADER_DRIVER_OVERRIDE=''driver''<br />
<br />
By default mesa searches for drivers in {{ic|/lib/dri/}} you can see the list of drivers by<br />
<br />
$ ls /lib/dri/<br />
<br />
{{ic|''driver''}} is the name of the driver without {{ic|_dri.so}}. If it failed it will fallback to llvmpipe.<br />
<br />
You can also use OpenGL software rasterizer drivers by setting the following [[environment variables]]:<br />
<br />
LIBGL_ALWAYS_SOFTWARE=true<br />
GALLIUM_DRIVER=''driver''<br />
<br />
{{ic|''driver''}} is one of {{ic|softpipe}}, {{ic|llvmpipe}}, or {{ic|swr}}.<br />
<br />
{{Tip|As of the time of writing this llvmpipe & swr are faster than softpipe.}}<br />
<br />
== OpenGL over Vulkan (Zink) ==<br />
If you experience some issues (a bug in radeonsi/iris/etc.), you may try using Zink. On AMD RX 6700 XT the FPS is 58-105% depending on a game compared to radeonsi according to [https://www.phoronix.com/scan.php?page=article&item=zink-ends-2021&num=1]. On NVIDIA the FPS is sometimes higher (e.g. Tomb Raider), but at the moment (2021-11-30) many apps still don't work on NVIDIA GPUs even when using driver 495.44 and mesa-git's master branch.<br />
$ env __GLX_VENDOR_LIBRARY_NAME=mesa MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink %app%<br />
<br />
== Development ==<br />
<br />
{{Note|This section is for developers who wants to use OpenGL. End users do not need any thing from this section.}}<br />
Using OpenGL in code requires functions loader, read more at [https://www.khronos.org/opengl/wiki/OpenGL_Loading_Library Khronos].<br />
<br />
{{Expansion|Put list of packages relevant to OpenGL and in Arch repo}}<br />
<br />
=== OpenGL Hardware Database ===<br />
<br />
[https://www.gpuinfo.org/ GPUInfo] provides user reported GPU/driver combinations, supported extensions, capabilities, etc.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Vulkan&diff=697621Vulkan2021-09-27T18:49:41Z<p>Arzeth: Info about how to use Lavapipe</p>
<hr />
<div>[[Category:Graphics]]<br />
[[Category:Development]]<br />
[[ja:Vulkan]]<br />
[[pt:Vulkan]]<br />
[[ru:Vulkan]]<br />
From [[wikipedia:Vulkan (API)]]:<br />
:Vulkan is a low-overhead, cross-platform 3D graphics and compute API.<br />
<br />
Learn more at [https://www.khronos.org/vulkan/ Khronos].<br />
<br />
== Installation ==<br />
<br />
{{Note|1=<br />
On hybrid graphics ([[NVIDIA Optimus]]/AMD Dynamic Switchable Graphics):<br />
<br />
* Vulkan is not currently officially supported by [[Bumblebee]] [https://github.com/Bumblebee-Project/Bumblebee/issues/769] but does work with {{Pkg|primus_vk}} or {{AUR|primus-vk-git}}.<br />
* The Radeon Vulkan driver now supports [[PRIME]] [https://www.phoronix.com/scan.php?page=news_item&px=RADV-PRIME-Lands].<br />
}}<br />
<br />
To run a Vulkan application, you will need to [[install]] the {{Pkg|vulkan-icd-loader}} package (and {{Pkg|lib32-vulkan-icd-loader}} if you also want to run 32-bit applications), as well as Vulkan drivers for your graphics card(s). There are several packages [[PKGBUILD#provides|providing]] a ''vulkan-driver'':<br />
<br />
* [[Intel]]: {{Pkg|vulkan-intel}} (or {{Pkg|lib32-vulkan-intel}})<br />
* [[NVIDIA]]: {{Pkg|nvidia-utils}} (or {{Pkg|lib32-nvidia-utils}})<br />
* [[AMDGPU|AMD]]: there are three implementations, which could be installed simultaneously: <br />
** {{Pkg|vulkan-radeon}} (or {{Pkg|lib32-vulkan-radeon}}) - RADV (part of Mesa project)<br />
** {{Pkg|amdvlk}} (or {{Pkg|lib32-amdvlk}}) - AMDVLK Open (maintained by AMD)<br />
** {{AUR|vulkan-amdgpu-pro}} (or {{AUR|lib32-vulkan-amdgpu-pro}}) - AMDVLK Closed (maintained by AMD)<br />
<br />
You can also install the software Vulkan rasterizer known as lavapipe: {{Pkg|vulkan-swrast}}<br />
<br />
{{Warning|"lavapipe is not a conformant Vulkan implementation, testing use only." (quoted from the driver itself)}}<br />
<br />
Other drivers may be installed manually instead:<br />
<br />
* PowerVR: https://imgtec.com/vulkan{{Dead link|2021|05|17|status=404}}<br />
* Adreno: https://developer.qualcomm.com/software/adreno-gpu-sdk/gpu<br />
<br />
For Vulkan application development, [[install]] {{Pkg|vulkan-headers}}, and optionally {{Pkg|vulkan-validation-layers}} and {{Pkg|vulkan-tools}} (you can find the vulkaninfo tool in here).<br />
<br />
== Verification ==<br />
<br />
To see which Vulkan implementations are currently installed on your system, use the following command:<br />
<br />
$ ls /usr/share/vulkan/icd.d/<br />
<br />
To ensure that Vulkan is working with your hardware, [[install]] {{Pkg|vulkan-tools}} and use the {{ic|vulkaninfo}} command to pull up relevant information about your system. If you get info about your graphics card, you will know that Vulkan is working.<br />
<br />
$ vulkaninfo<br />
<br />
You can see https://linuxconfig.org/install-and-test-vulkan-on-linux for more information.<br />
<br />
== Selecting Vulkan driver ==<br />
<br />
In some cases, multiple vulkan driver are installed (for example RADV and AMDVLK). As of {{Pkg|amdvlk}} 2021.Q3.4, a new switching logic was implemented which enforces AMDVLK as the default and mandates you either<br />
<br />
* set {{ic|1=AMD_VULKAN_ICD=RADV}} to switch from the AMDVLK default,<br />
* or globally set {{ic|1=DISABLE_LAYER_AMD_SWITCHABLE_GRAPHICS_1=1}} to re-enable the ICD loader method below.<br />
<br />
When {{ic|1=DISABLE_LAYER_AMD_SWITCHABLE_GRAPHICS_1=1}}, you can choose your preferred driver by setting the environment variable {{ic|VK_ICD_FILENAMES}}. For example, running [[Steam]] with the RADV driver is done by<br />
<br />
$ VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/radeon_icd.i686.json:/usr/share/vulkan/icd.d/radeon_icd.x86_64.json steam<br />
<br />
To avoid crashes with 32-bit games, it is possible to assign the 32-bit variant and the 64-bit variant to the environment variable.<br />
<br />
== Software Vulkan: Lavapipe ==<br />
$ sudo pacman -S vulkan-swrast<br />
$ LIBGL_ALWAYS_SOFTWARE=1 __GLX_VENDOR_LIBRARY_NAME=mesa VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.i686.json:/usr/share/vulkan/icd.d/lvp_icd.x86_64.json vulkaninfo | less<br />
There is no 32-bit vulkan-swrast package for now (even in AUR), so 32-bit games over DXVK won't work probably.<br />
<br />
== Vulkan Hardware Database ==<br />
<br />
The [https://vulkan.gpuinfo.org/ Vulkan Hardware Database] provides user reported GPU/driver combinations. Supplying own information is possible by using {{AUR|vulkan-caps-viewer-wayland}} or {{AUR|vulkan-caps-viewer-x11}}.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Error - vulkan: No DRI3 support ===<br />
<br />
If you get the message above and using [[Intel graphics]], you may need to force DRI3 and restart [[Xorg]]:<br />
<br />
{{hc|/etc/X11/xorg.conf.d/20-intel.conf|<br />
Section "Device"<br />
Identifier "Intel Graphics"<br />
Driver "intel"<br />
Option "DRI" "3"<br />
EndSection<br />
}}<br />
<br />
=== Nvidia - vulkan is not working and can not initialize ===<br />
<br />
Check if you have any other vulkan driver installed, it may prevent Nvidia's vulkan driver from being detected.<br />
<br />
Alternatively set the [[environment variable]] {{ic|VK_ICD_FILENAMES}} to {{ic|/usr/share/vulkan/icd.d/nvidia_icd.json}}.<br />
<br />
If you have a dual-graphics system, like [[NVIDIA Optimus]], ensure that your system is using the graphics card that you installed Vulkan drivers for.<br />
<br />
{{Accuracy|optimus-manager is just one of several utilities for [[NVIDIA Optimus]].}}<br />
{{Style|Command in code block requires a [[Help:Style#Command line text|prompt symbol]].}}<br />
<br />
{{hc|optimus-manager --status|<br />
Optimus Manager (Client) version 1.4<br />
<br />
Current GPU mode : nvidia<br />
GPU mode requested for next login : no change<br />
GPU at startup : integrated<br />
Temporary config path: no<br />
}}<br />
<br />
=== No device for the display GPU found. Are the intel-mesa drivers installed? ===<br />
<br />
Try to list both the intel_icd and primus_vk_wrapper configurations in VK_ICD_FILENAMES<br />
<br />
export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/intel_icd.x86_64.json:/usr/share/vulkan/icd.d/nv_vulkan_wrapper.json<br />
<br />
=== AMDGPU - ERROR_INITIALIZATION_FAILED after vulkaninfo===<br />
<br />
If after running {{ic|vulkaninfo}} on AMD card from GCN1 or GCN2 family you got error message like:<br />
{{bc|ERROR at /build/vulkan-tools/src/Vulkan-Tools-1.2.135/vulkaninfo/vulkaninfo.h:240:vkEnumerateInstanceExtensionProperties failed with ERROR_INITIALIZATION_FAILED}}<br />
Then check if you have correctly enable support for this models of graphics cards ([[AMDGPU#Enable Southern Islands (SI) and Sea Islands (CIK) support]]).<br />
<br />
One of possibility to check if gpu drivers are correctly loaded is {{ic|lspci -k}}, after running this command check kernel driver of your gpu. It should be {{ic|amdgpu}}.<br />
<br />
{{hc|$ lspci -k|<br />
...<br />
01:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Curacao PRO [Radeon R7 370 / R9 270/370 OEM]<br />
Subsystem: Gigabyte Technology Co., Ltd Device 226c<br />
Kernel driver in use: amdgpu<br />
Kernel modules: radeon, amdgpu<br />
...<br />
}}<br />
<br />
Some forum threads about this problem: [https://bbs.archlinux.org/viewtopic.php?id=254015] [https://bbs.archlinux.org/viewtopic.php?id=253843]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695800PipeWire2021-09-15T01:28:52Z<p>Arzeth: /* Changing the sample rate */ Add info on how to verify the result</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire/ to /usr/share/pipewire/. System wide config can still be done in /etc/pipewire/ and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire/. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
PipeWire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
To check out which output sample rate and sample format are the data sent to DAC (probably you need to change digits):<br />
cat /proc/asound/card0/pcm0p/sub0/hw_params<br />
To check out which input sample rate is used, change {{ic|pcm№p}} to {{ic|pcm№c}} ({{ic|c}} is short for "capture", {{ic|p}} is for "playback").<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire (without sudo): {{ic|systemctl --user restart pipewire.service pipewire-pulse.socket}} (never forget {{ic|pipewire-pulse.socket}} if you want your config changes to be applied).<br />
<br />
There is a very little quality difference between {{ic|10}} and {{ic|15}}, but the CPU load difference is 2-3x. And the latency difference between {{ic|4}}, {{ic|10}}, {{ic|15}} is yet to be investigated by anybody. {{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes {{ic|pipewire}} or {{ic|pipewire-pulse}} processes to cause 4.0% one CPU core load.<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, PipeWire includes its standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink. Or just use a plugin in your music player (e.g., Qmmp has SoX plugin).<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695799PipeWire2021-09-15T01:17:06Z<p>Arzeth: /* Sound quality (resampling quality) */ style</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire/ to /usr/share/pipewire/. System wide config can still be done in /etc/pipewire/ and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire/. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire (without sudo): {{ic|systemctl --user restart pipewire.service pipewire-pulse.socket}} (never forget {{ic|pipewire-pulse.socket}} if you want your config changes to be applied).<br />
<br />
There is a very little quality difference between {{ic|10}} and {{ic|15}}, but the CPU load difference is 2-3x. And the latency difference between {{ic|4}}, {{ic|10}}, {{ic|15}} is yet to be investigated by anybody. {{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes {{ic|pipewire}} or {{ic|pipewire-pulse}} processes to cause 4.0% one CPU core load.<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, PipeWire includes its standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink. Or just use a plugin in your music player (e.g., Qmmp has SoX plugin).<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695798PipeWire2021-09-15T01:15:13Z<p>Arzeth: /* Sound quality (resampling quality) */ better English</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire/ to /usr/share/pipewire/. System wide config can still be done in /etc/pipewire/ and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire/. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire (without sudo): {{ic|systemctl --user restart pipewire.service pipewire-pulse.socket}} (never forget {{ic|pipewire-pulse.socket}} if you want your config changes to be applied).<br />
<br />
There is a very little quality difference between {{ic|10}} and {{ic|15}}, but the CPU load difference is 2-3x. And the latency difference between {{ic|4}}, {{ic|10}}, {{ic|15}} is yet to be investigated by anybody. {{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 4.0% one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, PipeWire includes its standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink. Or just use a plugin in your music player (e.g., Qmmp has SoX plugin).<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695797PipeWire2021-09-15T01:14:43Z<p>Arzeth: /* Sound quality (resampling quality) */ style</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire/ to /usr/share/pipewire/. System wide config can still be done in /etc/pipewire/ and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire/. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire (without sudo): {{ic|systemctl --user restart pipewire.service pipewire-pulse.socket}} (never forget {{ic|pipewire-pulse.socket}} if you want your config changes to be applied).<br />
<br />
There is a very little quality difference between {{ic|10}} and {{ic|15}}, but CPU difference is 2-3x. And the latency difference between {{ic|4}}, {{ic|10}}, {{ic|15}} is yet to be investigated by anybody. {{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 4.0% one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, PipeWire includes its standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink. Or just use a plugin in your music player (e.g., Qmmp has SoX plugin).<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695796PipeWire2021-09-15T01:13:26Z<p>Arzeth: /* Sound quality (resampling quality) */ my typo</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire/ to /usr/share/pipewire/. System wide config can still be done in /etc/pipewire/ and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire/. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire (without sudo): {{ic|systemctl --user restart pipewire.service pipewire-pulse.socket}} (never forget {{ic|pipewire-pulse.socket}} if you want your config changes to be applied).<br />
<br />
There is a very little quality difference between 10 and 15, but 2-3x CPU difference. And the latency difference between 4, 10, 15 is yet to be investigated by anybody. {{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 4.0% one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, PipeWire includes its standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink. Or just use a plugin in your music player (e.g., Qmmp has SoX plugin).<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695795PipeWire2021-09-15T01:13:01Z<p>Arzeth: /* Sound quality (resampling quality) */ Fixes</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire/ to /usr/share/pipewire/. System wide config can still be done in /etc/pipewire/ and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire/. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire (without sudo): {{ic|systemctl --user restart pipewire.service pipewire-pulse.socket}} (never forget {{ic|pipewire-pulse.socket}} if you want your config changes to be applied).<br />
<br />
There is a very little quality difference between 10 and 15, but 2-3x CPU difference. And the latency difference between 4, 10, 16 is yet to be investigated by anybody. {{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 4.0% one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, PipeWire includes its standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink. Or just use a plugin in your music player (e.g., Qmmp has SoX plugin).<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695794PipeWire2021-09-15T00:53:34Z<p>Arzeth: /* Troubleshooting */ Make it more evident that they are folders</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire/ to /usr/share/pipewire/. System wide config can still be done in /etc/pipewire/ and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire/. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire: {{ic|systemctl --user restart pipewire.service}} (without sudo). <br />
<br />
{{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 1.4% (or more likely 0.5%) one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, PipeWire includes its standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink.<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695793PipeWire2021-09-15T00:50:53Z<p>Arzeth: /* Sound quality (resampling quality) */</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire to /usr/share/pipewire. System wide config can still be done in /etc/pipewire and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire: {{ic|systemctl --user restart pipewire.service}} (without sudo). <br />
<br />
{{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 1.4% (or more likely 0.5%) one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, PipeWire includes its standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink.<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695792PipeWire2021-09-15T00:49:50Z<p>Arzeth: /* Sound quality (resampling quality) */ add -q 15 param</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire to /usr/share/pipewire. System wide config can still be done in /etc/pipewire and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire: {{ic|systemctl --user restart pipewire.service}} (without sudo). <br />
<br />
{{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 1.4% (or more likely 0.5%) one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, it has a standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -q 15 -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink.<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695790PipeWire2021-09-15T00:48:40Z<p>Arzeth: /* Sound quality (resampling quality) */ Add info on how to use PipeWire's resampler Spa on files so that users themselves could compare resamplers</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire to /usr/share/pipewire. System wide config can still be done in /etc/pipewire and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire: {{ic|systemctl --user restart pipewire.service}} (without sudo). <br />
<br />
{{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 1.4% (or more likely 0.5%) one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa. Like with SoX's {{ic|sox}}, Speex's {{ic|speexenc}}, it has a standalone version: {{ic|spa-resample}}. Usage:<br />
spa-resample -f s24 -r 48000 input16bit44100orAnythingElse.wav output24bit48000hz.wav<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink.<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PipeWire&diff=695787PipeWire2021-09-15T00:28:11Z<p>Arzeth: Add "Sound quality (resampling quality)" section</p>
<hr />
<div>[[Category:Multimedia]]<br />
[[fi:PipeWire]]<br />
[[ja:PipeWire]]<br />
[[pt:PipeWire]]<br />
[[ru:PipeWire]]<br />
{{Related articles start}}<br />
{{Related|PipeWire/Examples}}<br />
{{Related articles end}}<br />
<br />
[https://pipewire.org PipeWire] is a new low-level multimedia framework. It aims to offer capture and playback for both audio and video with minimal latency and support for [[PulseAudio]], [[JACK]], [[ALSA]] and [[GStreamer]]-based applications.<br />
<br />
The daemon based on the framework can be configured to be both an audio server (with PulseAudio and JACK features) and a video capture server.<br />
<br />
PipeWire also supports containers like [[Flatpak]] and does not rely on ''audio'' and ''video'' [[user group]]s but rather it uses a [[Polkit]]-like security model asking Flatpak or Wayland for permission to record screen or audio.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|pipewire}} package from the official repositories.<br />
<br />
Pipewire uses [[systemd/User]] for management of the server and automatic socket activation.<br />
<br />
Optionally, install {{Pkg|pipewire-docs}} to review the documentation. Other packages, such as {{Pkg|pipewire-alsa}}, {{Pkg|pipewire-pulse}}, and {{Pkg|pipewire-jack}} are normally not needed unless one wants to [[#Audio|use PipeWire as a PulseAudio/JACK replacement]]. Also available are {{Pkg|lib32-pipewire}} and {{Pkg|lib32-pipewire-jack}} for multilib support.<br />
<br />
=== GUI ===<br />
<br />
* {{App|Helvum|GTK-based patchbay for pipewire, inspired by the JACK tool catia.|https://gitlab.freedesktop.org/ryuukyu/helvum|{{AUR|helvum}} or {{AUR|helvum-git}}}}<br />
<br />
== Usage ==<br />
<br />
=== WebRTC screen sharing ===<br />
<br />
Most browsers used to rely on X11 for capturing the desktop (or individual applications) when using WebRTC (e.g. on Google Hangouts). On Wayland, the sharing mechanism is handled differently for security reasons. PipeWire enables sharing content under Wayland with fine-grained access controls.<br />
<br />
This requires {{Pkg|xdg-desktop-portal}} and one of its backends [http://jgrulich.cz/2018/07/04/how-to-enable-and-use-screen-sharing-on-wayland to be installed]. The available backends are:<br />
<br />
* {{Pkg|xdg-desktop-portal-gtk}} for GNOME.<br />
* {{Pkg|xdg-desktop-portal-kde}} for KDE.<br />
* {{Pkg|xdg-desktop-portal-wlr}} for wlroots-based compositor (e.g. [[Sway]], [https://github.com/djpohly/dwl dwl])<br />
<br />
Firefox (84+) supports this method by default, while on Chromium (73+) one needs to enable [https://bugs.chromium.org/p/chromium/issues/detail?id=682122 WebRTC PipeWire support] by setting the corresponding (experimental) flag at the following URL:<br />
<br />
chrome://flags/#enable-webrtc-pipewire-capturer<br />
<br />
For {{ic|xdg-desktop-portal-wlr}} to work you need to install {{Pkg|pipewire-media-session}} [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ/db63ec1ab6c0170334c1d1f45d1ebe543cc375fa#how-do-i-run-xdpw] and make sure that {{ic|1=XDG_CURRENT_DESKTOP=sway}} is set in the session [https://github.com/emersion/xdg-desktop-portal-wlr#running]. You need to set {{ic|1=XDG_SESSION_TYPE=wayland}} as well [https://github.com/emersion/xdg-desktop-portal-wlr/issues/117].<br />
<br />
{{Tip|To share an individual monitor with {{ic|xdg-desktop-portal-wlr}} if you have more than one, you can use configuration file options, see {{man|5|xdg-desktop-portal-wlr|SCREENCAST OPTIONS}}:<br />
{{hc|~/.config/xdg-desktop-portal-wlr/config|2=<br />
chooser_type = none<br />
output_name = ''Monitor''<br />
}}<br />
In [[Sway]], you can get the ''Monitor'' value using the {{ic|swaymsg -t get_outputs}} command.}}<br />
<br />
{{Accuracy|Since [https://github.com/flatpak/xdg-desktop-portal-gtk/pull/225 this pull request] was merged, the following note about specific app/window sharing may be not correct anymore for {{Pkg|xdg-desktop-portal-gtk}}. Also see the ticket tracking the discussion at [https://github.com/flatpak/xdg-desktop-portal-gtk/issues/204].}}<br />
<br />
Note that the only supported feature is sharing the entire desktop and not a specific app/window [https://github.com/emersion/xdg-desktop-portal-wlr/wiki/FAQ#will-this-let-me-share-individual-windows][https://github.com/KDE/xdg-desktop-portal-kde/blob/master/TODO].<br />
<br />
=== Video ===<br />
<br />
Although the software is not yet production-ready, it is safe to play around with. Most applications that rely on [[GStreamer]] to handle e.g. video streams should work out-of-the-box using the PipeWire GStreamer plugin, see [[GStreamer#PipeWire]]. Applications like e.g. {{Pkg|cheese}} are therefore already able to share video input using it.<br />
<br />
=== Audio ===<br />
<br />
PipeWire can be used as an audio server, similar to PulseAudio and JACK. It aims to replace both PulseAudio and JACK, by providing a PulseAudio-compatible server implementation and ABI-compatible libraries for JACK clients. See [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ this blog entry] for more information.<br />
<br />
==== ALSA/Legacy applications ====<br />
<br />
Install {{Pkg|pipewire-alsa}} to route all application using the ALSA API through PipeWire.<br />
<br />
==== PulseAudio clients ====<br />
<br />
Install {{Pkg|pipewire-pulse}}. It will replace {{Pkg|pulseaudio}} and {{Pkg|pulseaudio-bluetooth}}. Reboot, re-login or execute {{ic|systemctl start --user pipewire-pulse.service}} to see the effect. <br />
<br />
Normally, no further action is needed, as the user service {{ic|pipewire-pulse.socket}} should be enabled automatically by the package. To check if the replacement is working, run the following command and see the output:<br />
<br />
{{hc|1=$ pactl info|2=<br />
...<br />
Server Name: PulseAudio (on PipeWire 0.3.32)<br />
...<br />
}}<br />
<br />
If PipeWire does not work correctly on system startup, validate that the [[Systemd/User]] services {{ic|pipewire-pulse.service}}, {{ic|pipewire.service}}, and {{ic|pipewire-media-session.service}} are up and running. Keep in mind that {{ic|pipewire-pulse.service}} and {{ic|pipewire-pulse.socket}} have a {{ic|ConditionUser}} against running as root.<br />
<br />
==== JACK clients ====<br />
<br />
Install {{Pkg|pipewire-jack}} and use {{ic|pw-jack}} to launch JACK clients with the compatible libraries instead of the original {{ic|libjack*}}:<br />
<br />
pw-jack ''application''<br />
<br />
It is also possible to request a custom buffer size by setting a quotient of buffersize/samplerate (which equals the block latency in seconds):<br />
<br />
PIPEWIRE_LATENCY="128/48000" pw-jack ''application''<br />
<br />
Alternatively, install {{AUR|pipewire-jack-dropin}} or uninstall {{AUR|jack}}/{{Pkg|jack2}} to let JACK clients load the compatible libraries automatically.<br />
<br />
Use {{ic|ldd}} to verify that the JACK application links to the correct library:<br />
<br />
{{hc|1=$ ldd /usr/bin/qjackctl {{!}} grep -i libjack|2=<br />
libjack.so.0 => /usr/lib/pipewire-0.3/jack/libjack.so.0 (0x00007f7e5080a000)<br />
}}<br />
<br />
==== Bluetooth devices ====<br />
<br />
PipeWire handles Bluetooth audio devices if the {{Pkg|pipewire-pulse}} package is installed. More specifically, the media session daemon checks for {{ic|/etc/pipewire/media-session.d/with-pulseaudio}}, and enables its {{ic|bluez5}} module automatically if the file exists.<br />
<br />
The configuration is located in the {{ic|bluez-monitor}} configuration file, either {{ic|/etc/pipewire/media-session.d/bluez-monitor.conf}} (for system-wide configuration) or {{ic|~/.config/pipewire/media-session.d/bluez-monitor.conf}} (for user-specific configuration). A template for the configuration file can be copied from {{ic|/usr/share/pipewire/media-session.d/bluez-monitor.conf}}.<br />
<br />
===== Automatic profile selection =====<br />
<br />
To automatically switch between HSP/HFP and A2DP profiles when an input stream is detected, set the {{ic|bluez5.autoswitch-profile}} property to {{ic|true}}:<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
{<br />
...<br />
actions = {<br />
update-props = {<br />
...<br />
bluez5.autoswitch-profile = true<br />
...<br />
}}<br />
<br />
==== Run PipeWire on top of native JACK ====<br />
<br />
PipeWire can also run as a JACK client on top of the native JACK daemon if desired. See [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/JACK JACK and PipeWire] for more information.<br />
<br />
== Audio post-processing ==<br />
<br />
=== EasyEffects ===<br />
<br />
EasyEffects (former PulseEffects) is a GTK utility which provides a large array of audio effects and filters to individual application output streams and microphone input streams. Notable effects include an input/output equalizer, output loudness equalization and bass enhancement, input de-esser and noise reduction plug-in. See [https://github.com/wwmm/easyeffects the GitHub page] for a full list of effects.<br />
<br />
In order to use EasyEffects, install {{Pkg|easyeffects}}. See [https://github.com/wwmm/easyeffects/wiki/Community-presets Community Presets] for a collection of preset configurations. See [https://github.com/jaakkopasanen/AutoEq AutoEq] for collection of AI generated EQ presets for headphones.<br />
<br />
{{Note|For PulseEffects legacy version, see [[PulseAudio#PulseEffects]].}}<br />
<br />
=== NoiseTorch ===<br />
<br />
NoiseTorch is an alternative way for noise suppression. {{AUR|noisetorch}}. There also exists a binary version, {{AUR|noisetorch-bin}}, as well as a {{AUR|noisetorch-git}}.<br />
<br />
After starting it the module can be loaded for the selected microphone. It is possible to adjust the voice activation threshold, which should be set to the highest level, not filtering out any actual voice.<br />
<br />
=== LADSPA, LV2 and VST plugins ===<br />
<br />
If you want to choose between the full list of available LADSPA, LV2 and VST plugins, you can apply them using a custom Pulseaudio null sink and Carla Jack host. Install {{Pkg|pipewire-pulse}}, {{Pkg|pipewire-jack}} and {{Pkg|carla}}. At the begin, create a new Pulseaudio null sink named {{ic|default_null_sink}}.<br />
<br />
pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=default_null_sink channel_map=FL,FR<br />
<br />
Start Carla through Pipewire, {{ic|pw-jack carla-rack}}. In ''Rack'' tab add whichever plugin you want. Make sure they are ''stereo'' type. You can change their order, the one on top of the list will be the first to receive the audio stream, just like in EasyEffects. Afterwards move to ''Patchbay'' tab and connect the {{ic|default_null_sink}} L/R monitors to Carla inputs, then Carla outputs to the playbacks of your desired device (speakers, earphones, HDMI, etc). Save the configuration to a local folder, i.e. {{ic|~/Documents/carla_sink_effects.carxp}}.<br />
<br />
You can test the effects while a multimedia application is reproducing audio, i.e. watching a video on a website through Firefox. There are two methods to do it. The first one, inside Carla ''Patchbay'' tab, disconnecting all Firefox connections and linking its L/R outputs to {{ic|default_null_sink}} playbacks. The second through {{Pkg|pavucontrol}}, locating Firefox audio stream and redirecting it to {{ic|default_null_sink}} (this should remember the connection to automatically redirect the application to the same sink on the next instance).<br />
<br />
To apply these settings at startup, create two systemd user service units:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service|output=<br />
[Unit]<br />
Description=Load Carla Rack JACK host<br />
<br />
[Service]<br />
PassEnvironment="PIPEWIRE_LINK_PASSIVE=true"<br />
Type=exec<br />
ExecStart=/usr/bin/pw-jack carla-rack -n<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
{{hc|~/.config/systemd/user/pulseaudio-null-sink@.service|output=<br />
[Unit]<br />
Description=Load %i Pulseaudio null sink<br />
Before=jack-carla-rack.service<br />
After=pipewire-pulse.service<br />
<br />
[Service]<br />
Type=oneshot<br />
ExecStart=/usr/bin/pactl load-module module-null-sink object.linger=1 media.class=Audio/Sink sink_name=%i channel_map=FL,FR<br />
ExecStop=/usr/bin/pactl unload-module module-null-sink<br />
RemainAfterExit=yes<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then override ''jack-carla-rack'' service specifying the full path of your Carla configuration at ''Environment'' directive:<br />
<br />
{{hc|~/.config/systemd/user/jack-carla-rack.service.d/override.conf|output=<br />
Environment="CARLA_CONFIG_FILE=/home/username/Documents/carla_sink_effects.carxp"<br />
ExecStart=<br />
ExecStart=/usr/bin/pw-jack carla-rack -n $CARLA_CONFIG_FILE<br />
}}<br />
<br />
At last, enable these two services specifying {{ic|default_null_sink}} as argument for ''pulseaudio-null-sink'' service:<br />
<br />
systemctl --user enable pulseaudio-null-sink@default_null_sink.service<br />
systemctl --user enable jack-carla-rack.service<br />
<br />
Note that if you set the {{ic|default_null_sink}} as the default device in system settings, all applications will be redirected to it and the volume keys will change its level, not the one on the speakers. If you want to control volume speakers, leave them as the default in system settings and redirect your desired application to {{ic|default_null_sink}} inside pavucontrol (Pipewire compatibility layer will remember the connection on the next instance of the same application).<br />
<br />
=== Noise suppression for voice ===<br />
<br />
Install {{AUR|noise-suppression-for-voice}} and see https://github.com/werman/noise-suppression-for-voice#pipewire. Then, set the noise cancelled source as default in your audio settings. You might need to restart your application prior being able to use it.<br />
<br />
== Troubleshooting ==<br />
<br />
{{Out of date|Factory config files were moved from /etc/pipewire to /usr/share/pipewire. System wide config can still be done in /etc/pipewire and user config in $HOME/.config/pipewire/, but files must be copied from /usr/share/pipewire. https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/1609126bcd720304b7a4c81b87cc3e70ae91ff44}}<br />
<br />
=== Microphone is not detected by PipeWire ===<br />
<br />
PipeWires {{ic|alsa-monitor}} module uses {{Pkg|alsa-card-profiles}} to detect devices by default. If this is not working for you, try to turn off {{ic|api.alsa.use-acp}}, or optionally turn on {{ic|api.alsa.use-ucm}} in {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, under {{ic|rules}} -> the first rule -> {{ic|actions}} -> {{ic|update-props}}:<br />
<br />
...<br />
update-props = {<br />
api.alsa.use-acp = false<br />
...<br />
<br />
Then, restart pipewire and check available devices:<br />
<br />
{{hc| 1=<br />
$ pw-record --list-targets<br />
|2=<br />
Available targets ("*" denotes default): 62<br />
58: description="Built-in Audio" prio=1872<br />
60: description="Built-in Audio" prio=2000<br />
* 62: description="Built-in Audio (Loopback PCM)" prio=1984<br />
}}<br />
<br />
=== No sound after connecting to Bluetooth device ===<br />
<br />
As of 2020-12-07, if there is no sound after connecting a Bluetooth device, you might need to switch the default sink and/or move a sink input to the correct sink. Use {{ic|pactl list sinks}} to list the available sinks and {{ic|pactl set-default-sink}} to switch the default sink to the Bluetooth device. This can be automated via [[udev]] using a script similar to [https://gist.github.com/tinywrkb/04e7fd644afa9b92d33a3a99ab07ee9e this one].<br />
<br />
See this [https://www.reddit.com/r/archlinux/comments/jydd02/pipewirepulse_03164_in_testing_now_replaces/gd3m7fu/?context=3 Reddit thread] for a discussion of the issue. According to author of the script, the headset profile (HSP) might still have problems.<br />
<br />
=== Low volume ===<br />
<br />
After replacing PulseAudio with Pipewire, sound worked fine, but after a reboot, the volume was intolerably low.<br />
<br />
Open {{ic|alsamixer}}, use {{ic|F6}} to select the proper soundcard, and make sure the ALSA volumes are at 100%. {{ic|alsactl}} should maintain this setting after reboot.<br />
<br />
=== Increasing RLIMIT_MEMLOCK ===<br />
<br />
Dec 13 11:11:11 HOST pipewire-pulse[99999]: Failed to mlock memory 0x7f4f659d8000 32832: This is not a problem but for best performance, consider increasing RLIMIT_MEMLOCK<br />
<br />
Install {{Pkg|realtime-privileges}} and add your own user to the {{ic|realtime}} group.<br />
<br />
Alternatively, increasing memlock from 64kB to 128kB seems enough to fix this. If you are running {{ic|pipewire-pulse}} under [[systemd/User]], add:<br />
<br />
username soft memlock 64<br />
username hard memlock 128<br />
<br />
to {{ic|/etc/security/limits.d/username.conf}}<br />
<br />
=== Changing the sample rate ===<br />
<br />
By default PipeWire sets a global sample rate of 48kHz. If you need to change it (e.g. you own a DAC supporting a higher value) you can do it by editing the line {{ic|1=default.clock.rate = 48000}} in the configuration file {{ic|/etc/pipewire/pipewire.conf}}. For example, if you want 192kHz, uncomment and change value {{ic|48000}} to {{ic|1=default.clock.rate = 192000}}.<br />
<br />
Pipewire can also change output sample rates supported by your DAC. To configure, uncomment and set the line {{ic|1=default.clock.allowed-rates = [ 48000 ]}}, for example, {{ic|[ 44100,48000,88200,96000 ]}}. The sample rate follows the sample rate of the audio stream being played when the card is idle.<br />
<br />
=== Sound quality (resampling quality) ===<br />
<br />
If you used PulseAudio with {{ic|1=resample-method = speex-float-10}} or {{ic|soxr-vhq}}, then you might consider uncommenting and changing {{ic|1=resample.quality = 4}} to {{ic|10}} or the maximum {{ic|15}} in {{ic|stream.properties}} block in both {{ic|/etc/pipewire/client.conf}} and {{ic|/etc/pipewire/pipewire-pulse.conf}} (copy them from {{ic|/usr/share/pipewire/}} if they don't exist). Don't forget to restart PipeWire: {{ic|systemctl --user restart pipewire.service}} (without sudo). <br />
<br />
{{ic|1= resample.quality = 15}} on 44100→48000 Hz on Ryzen 2600 causes 1.4% (or more likely 0.5%) one CPU core total load ({{ic|pipewire}} or {{ic|pipewire-pulse}} processes).<br />
<br />
You can compare resamplers here: https://src.infinitewave.ca/ (don't pay attention to anything above 18 KHz and over 120 dB). speex is listed as "Xiph.org Speex".<br />
<br />
PipeWire uses its own resampling algorithm called Spa, whose standalone version is {{ic|spa-resample}}.<br />
<br />
Probably it's somehow possible to use other resamplers by creating your own sink.<br />
<br />
=== External sound card not activated after reconnect ===<br />
<br />
Check {{ic|~/.config/pipewire-media-session/default-profile}} if there is any entry with default profile "off" and remove it. If that does not help, remove all files from {{ic|~/.config/pipewire-media-session/}} and restart PipeWire using {{ic|systemctl --user restart pipewire.service}}.<br />
<br />
=== No Sound or pactl info shows Failure: Connection refused ===<br />
<br />
It means applications are unable to connect to the PipeWire-Pulse service, confirm that {{ic|/etc/pipewire/pipewire-pulse.conf}} exists and is not empty and restart PipeWire-Pulse using {{ic|systemctl --user restart pipewire-pulse.service}}.<br />
<br />
If that does not fix it, run {{ic|strace -f -o /tmp/pipe.txt pactl info}} and pastebin {{ic|/tmp/pipe.txt}} while seeking help on IRC ([ircs://irc.oftc.net/pipewire #pipewire] on OFTC) or the mailing-lists.<br />
<br />
=== Low audio quality on Bluetooth ===<br />
<br />
In case Bluetooth playback stutters, check {{ic|pipewire.service}} using {{ic|systemctl --user status pipewire.service}}. If there are errors like this one, <br />
<br />
Feb 17 18:23:01 HOST pipewire[249297]: (bluez_input.18:54:CF:04:00:56.a2dp-sink-60) client too slow! rate:512/48000 pos:370688 status:triggered<br />
<br />
check the currently selected codec using {{ic|pactl list sinks}} and try changing it by setting {{ic|bluez5.codecs}} to one of {{ic|sbc aac ldac aptx aptx_hd}} in<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
properties = {<br />
...<br />
bluez5.codecs = [sbc]<br />
...<br />
}}<br />
<br />
Try enabling mSBC support (fixes mic on Sony 1000XM3):<br />
<br />
{{hc|/etc/pipewire/media-session.d/bluez-monitor.conf|output=<br />
...<br />
rules = [<br />
...<br />
actions = {<br />
...<br />
update-props = {<br />
...<br />
bluez5.msbc-support = true<br />
...<br />
}}<br />
<br />
Restart PipeWire using {{ic|systemctl --user restart pipewire.service}} for the changes to take effect.<br />
<br />
=== No devices detected after PipeWire update and reboot (git / >=0.3.23) ===<br />
<br />
As of commit [https://gitlab.freedesktop.org/pipewire/pipewire/-/commit/012a68f8ef33705f1a40ec8ac294b8cce7f6aa88 012a68f8], a new [[user unit]] has been added which is disabled by default, meaning there is no ''pipewire-media-session'' running on user login. Run this program on login by [[enabling]] the {{ic|pipewire-media-session.service}} user unit.<br />
<br />
If the user or the package manager have not sorted out the configuration file changes after update, then another instance of ''pipewire-media-session'' might be running in {{ic|pipewire.service}}. Verify whether this is the case by checking the [[unit status]] of the {{ic|pipewire.service}} user unit. If it shows ''pipewire'' and ''pipewire-media-session'' running, update your system and/or user configuration:<br />
<br />
{{hc|/etc/pipewire/pipewire.conf<br />
~/.config/pipewire/pipewire.conf|output=<br />
context.exec = {<br />
...<br />
# Line below should be commented out<br />
#"/usr/bin/pipewire-media-session" = { args = "" }<br />
...<br />
}<br />
}}<br />
<br />
=== Noticeable audio delay when starting playback ===<br />
<br />
This is caused by node suspension when inactive. It can be disabled by editing {{ic|/etc/pipewire/media-session.d/*-monitor.conf}} depending on where the delay occurs and changing property {{ic|session.suspend-timeout-seconds}} to 0 to disable or to experiment with other values and see what works. Alternatively you can comment out the line {{ic|suspend-node}} in {{ic|/etc/pipewire/media-session.d/media-session.conf}}. Restart both the {{ic|pipewire}} and {{ic|pipewire-pulse}} systemd services to apply these changes, or alternatively reboot.<br />
<br />
=== Audio cutting out when multiple streams start playing ===<br />
<br />
This problem can typically be diagnosed by running {{ic|journalctl --user -b -u pipewire-pulse}} and finding lines similar to:<br />
<br />
pipewire-pulse[21740]: pulse-server 0x56009b9d5de0: [Nightly] UNDERFLOW channel:0 offset:370676 underrun:940<br />
<br />
According to the [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Troubleshooting#underrununderflow-and-broken-pipe-errors official PipeWire troubleshooting guide], to solve this problem edit {{ic|/etc/pipewire/media-session.d/alsa-monitor.conf}}, uncomment the line saying {{ic|1=api.alsa.headroom = 0}} and change its value to {{ic|1024}}.<br />
<br />
=== Audio is distorted ===<br />
<br />
* For microphones, try navigating to the card that is having issues after running {{ic|alsamixer}} and use the arrow keys to reduce any "Mic Boost" or "Internal Mic Boost" options.<br />
* Uncomment the {{ic|1=default.clock.rate = 48000}} setting in {{ic|/etc/pipewire/pipewire.conf}} and reduce the value to {{ic|44100}}<br />
<br />
=== Audio problems after standby ===<br />
<br />
If the sound is missing or otherwise garbled after waking the machine up from sleep, it might help to reinitialize ALSA:<br />
<br />
# alsactl init<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/home Wiki] — PipeWire Wiki on Freedesktop GitLab<br />
* [https://blogs.gnome.org/uraeus/2018/01/26/an-update-on-pipewire-the-multimedia-revolution-an-update/ Pipewire Update Blog Post] — Blog post from January 2018 outlining the state of PipeWire at the time<br />
* [https://blogs.gnome.org/uraeus/2020/09/04/pipewire-late-summer-update-2020/ PipeWire Late Summer Update 2020] — Blog post from September 2020</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=371128PostgreSQL (Русский)2015-04-25T18:37:46Z<p>Arzeth: /* Создание Вашей первой базы данных */ а то непонятно про какого пользователя (БД или Линукса) речь.</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ sudo su - postgres<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создаём новую базу данных. Создавать можно только от пользователя (например, postgres, за которого мы зашли), имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под любым пользователем управлять БД:<br />
$ psql имя_базы -U имя_пользователя_бд<br />
*Если имя базы данных '''И''' имя пользователя БД совпадают с текущим именем пользователя ($USER), то можно просто:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''— Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
* Список всех возможных команд (например, {{ic|CREATE TABLE}}) для запросов<br />
=> \h<br />
* Подробное описание команды<br />
=> \h CREATE_TABLE<br />
*Подключаем опредлённую базу данных<br />
=> \c <database><br />
*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
*Меняем пароль<br />
=> \password<br />
*Показать все используемые настройки<br />
=> SHOW ALL;<br />
*Выйти из psql<br />
=> \q или CTRL+d<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
{{Note (Русский)|По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.}}<br />
Из-под пользователя root редактируем файл<pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
В разделе connections and authentications раскомментируйте или исправьте строку <code>listen_addresses</code> по вашему желанию на<br />
listen_addresses = '*'<br />
либо<br />
listen_addresses = 'localhost,ip_у_сервера_в_сети'<br />
и внимательно просмотрите другие строки.<br />
<br>Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br />
# IPv4 local connections:<br />
host all all your_desired_ip_address/32 trust<br />
где <code>your_desired_ip_address</code> — IP-адрес клиента.<br />
После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
{{Note (Русский)|PostgreSQL по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения.}}<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и он медленный, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=Very_Secure_FTP_Daemon_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370890Very Secure FTP Daemon (Русский)2015-04-23T20:31:58Z<p>Arzeth: Стилевые правки и пунктуация.</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Networking (Русский)]]<br />
[[cs:Very Secure FTP Daemon]]<br />
[[en:Very Secure FTP Daemon]]<br />
[[es:Very Secure FTP Daemon]]<br />
[[it:Very Secure FTP Daemon]]<br />
[[zh-CN:Very Secure FTP Daemon]]<br />
{{Unmaintained (Русский)}}<br />
vsftpd расшифровывается как «Very Secure FTP Daemon» (очень безопасный FTP демон). Это хороший маленький FTP-сервер.<br />
<br />
Он может работать и без xinetd, но я опишу способ использования с xinetd.<br />
<br />
Сначала установите необоходимые пакеты с помощью pacman:<br />
# pacman -S xinetd vsftpd<br />
<br />
Следующий файл настроек нуждается в редактировании:<br />
<br />
/etc/xinetd.d/vsftpd:<br />
<pre><br />
service ftp<br />
{<br />
socket_type = stream<br />
wait = no<br />
user = root<br />
server = /usr/sbin/vsftpd<br />
log_on_success += HOST DURATION<br />
log_on_failure += HOST<br />
disable = no<br />
}<br />
</pre><br />
<br />
{{ic|/etc/vsftpd.conf}} достаточно хорошо документированный конфигурационный файл, но, возможно, по умолчанию вы захотите изменить что либо, например:<br />
<pre><br />
anonymous_enable=NO # Запрещает анонимный доступ к FTP-серверу<br />
local_enable=YES # Пользователи с локальной машины могут заходить<br />
write_enable=YES # Будьте осторожны, при использовании опции совместно с anonymous_enable=YES<br />
</pre><br />
<br />
Наконец, добавьте xinetd в список демонов в файле /etc/rc.conf. Не надо добавлять туда vsftpd, он будет вызван xinetd, когда это будет необходимо.<br />
<br />
Если вы получили ошибку типа:<br />
500 OOPS: cap_set_proc<br />
при соединении с сервером, вам необходимо добавить ''capability'' в список MODULES в /etc/rc.conf.<br />
<br />
ВНИМАНИЕ: <br />
После апгрейда до версии 2.1.0 вы можете получить сообщение об ошибке типа приведённого ниже, при попытке соединения с сервером:<br />
<pre><br />
500 OOPS: could not bind listening IPv4 socket<br />
</pre><br />
<br />
В старых версиях этом можно было исправить оставив следующую строчку закоментированной:<br />
<pre><br />
# Use this to use vsftpd in standalone mode, otherwise it runs through (x)inetd<br />
# listen=YES<br />
</pre><br />
<br />
В новой версии, и возможно в следующих релизах, требуется явно указать в конфигурации, что сервер не работает демоном, а вызывается через (x)inetd. Пример ниже:<br />
<pre><br />
# Use this to use vsftpd in standalone mode, otherwise it runs through (x)inetd<br />
listen=NO<br />
</pre></div>Arzethhttps://wiki.archlinux.org/index.php?title=Very_Secure_FTP_Daemon_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370888Very Secure FTP Daemon (Русский)2015-04-23T20:24:54Z<p>Arzeth: подправил описание anonymous_enable</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Networking (Русский)]]<br />
[[cs:Very Secure FTP Daemon]]<br />
[[en:Very Secure FTP Daemon]]<br />
[[es:Very Secure FTP Daemon]]<br />
[[it:Very Secure FTP Daemon]]<br />
[[zh-CN:Very Secure FTP Daemon]]<br />
{{Unmaintained (Русский)}}<br />
vsftpd расшифровывается как "very secure ftp daemon" (очень безопасный ftp демон). Это хороший маленький фтп-сервер.<br />
<br />
Он может работать и без xinetd, но я опишу способ использования с xinetd.<br />
<br />
Сначала установите необоходимые пакеты с помощью pacman:<br />
pacman -S xinetd vsftpd<br />
<br />
Следующий файл настроек нуждается в редактировании:<br />
<br />
/etc/xinetd.d/vsftpd:<br />
<pre><br />
service ftp<br />
{<br />
socket_type = stream<br />
wait = no<br />
user = root<br />
server = /usr/sbin/vsftpd<br />
log_on_success += HOST DURATION<br />
log_on_failure += HOST<br />
disable = no<br />
}<br />
</pre><br />
<br />
/etc/vsftpd.conf достаточно хорошо документированный конфигурационный файл, но, возможно, по умолчанию вы захотите изменить что либо, например:<br />
<pre><br />
anonymous_enable=NO # Запрещает анонимный доступ к FTP-серверу<br />
local_enable=YES # Пользователи с локальной машины могут заходить<br />
write_enable=YES # Будьте осторожны, при использовании опции совместно с anonymous_enable=YES<br />
</pre><br />
<br />
Наконец, добавьте xinetd в список демонов в файле /etc/rc.conf. Не надо добавлять туда vsftpd, он будет вызван xinetd когда это будет необходимо.<br />
<br />
Если выполучили ошибку типа:<br />
500 OOPS: cap_set_proc<br />
при соединении с сервером, вам необходимо добавить ''capability'' в список MODULES в /etc/rc.conf.<br />
<br />
ВНИМАНИЕ: <br />
После апгрейда до версии 2.1.0 вы можете получить сообщение об ошибке типа приведенного ниже, при попытке соединения с сервером:<br />
<pre><br />
500 OOPS: could not bind listening IPv4 socket<br />
</pre><br />
<br />
В старых версиях этом можно было исправить оставив следующую строчку закоментированной:<br />
<pre><br />
# Use this to use vsftpd in standalone mode, otherwise it runs through (x)inetd<br />
# listen=YES<br />
</pre><br />
<br />
В новой версии, и возможно в следующих релизах требуется явно указать в конфигурации что сервер не работает демоном, а вызывается через (x)inetd. Пример ниже:<br />
<pre><br />
# Use this to use vsftpd in standalone mode, otherwise it runs through (x)inetd<br />
listen=NO<br />
</pre></div>Arzethhttps://wiki.archlinux.org/index.php?title=DOSBox_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370884DOSBox (Русский)2015-04-23T20:08:11Z<p>Arzeth: /* Настройка */ добавил про то, что для каждого приложения можно свой dosbox.conf и привёл ссылку, где все настройки описаны.</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Emulators (Русский)]]<br />
[[cs:DOSBox]]<br />
[[en:DOSBox]]<br />
[[es:DOSBox]]<br />
[[zh-CN:DOSBox]]<br />
{{Unmaintained (Русский)}}<br />
=Введение=<br />
DOSBox это эмулятор PC со встроенным DOS'ом предназначенный для запуска старых DOS'овских игр и программ.<br />
<br />
=Установка=<br />
Установка очень проста:<br />
# pacman -S dosbox<br />
=Настройка=<br />
Никакой начальной конфигурации не требуется.<br />
Тем не менее, официальное руководство DOSBox говорит о конфигурационном файле {{ic|dosbox.conf}}.<br />
<br />
Изначально этого файла не существует, но Вы можете его создать. Для этого просто запустите {{ic|dosbox}} без параметров:<br />
$ dosbox<br />
<br />
И затем в командной строке DOS введите:<br />
Z:\> config -wc dosbox.conf<br />
<br />
Конфигурационный файл {{ic|dosbox.conf}} будет сохранён в текущем каталоге. Также вы можете использовать для каждого приложения свой {{ic|dosbox.conf}}, для этого просто помещайте его в каталог с приложением.<br />
<br />
Все настройки описаны на официальном wiki проекта DOSBox: http://www.dosbox.com/wiki/Dosbox.conf.<br />
<br />
=Использование=<br />
Положите вашу любимую игру/программу в каталог, затем запустите {{ic|dosbox}} с именем этого каталога:<br />
$ dosbox ./theoldgame/<br />
<br />
Вот и всё. Вы в командной строке DOS, и можете начать играть в ваши любимые старые игры.<br />
<br />
За дополнительной информацией обращайтесь на официальный сайт DOSBox:<br />
http://dosbox.sourceforge.net/<br />
<br />
=Советы=<br />
*Если DOSBox захватил фокус мыши/клавиатуры, нажмите {{ic|Ctrl+F10}}, чтобы освободить его.</div>Arzethhttps://wiki.archlinux.org/index.php?title=DOSBox_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370882DOSBox (Русский)2015-04-23T20:01:31Z<p>Arzeth: Стилевые правки.</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Emulators (Русский)]]<br />
[[cs:DOSBox]]<br />
[[en:DOSBox]]<br />
[[es:DOSBox]]<br />
[[zh-CN:DOSBox]]<br />
{{Unmaintained (Русский)}}<br />
=Введение=<br />
DOSBox это эмулятор PC со встроенным DOS'ом предназначенный для запуска старых DOS'овских игр и программ.<br />
<br />
=Установка=<br />
Установка очень проста:<br />
# pacman -S dosbox<br />
=Настройка=<br />
Никакой начальной конфигурации не требуется.<br />
Тем не менее, официальное руководство DOSBox говорит о конфигурационном файле {{ic|dosbox.conf}}<br />
<br><br />
Изначально этого файла не существует, но Вы можете его создать. Для этого просто запустите {{ic|dosbox}} без параметров:<br />
$ dosbox<br />
<br />
И затем в командной строке DOS введите:<br />
Z:\> config -wc dosbox.conf<br />
<br />
Конфигурационный файл {{ic|dosbox.conf}} будет сохранён в текущем каталоге.<br />
<br />
=Использование=<br />
Положите вашу любимую игру/программу в каталог, затем запустите {{ic|dosbox}} с именем этого каталога:<br />
$ dosbox ./theoldgame/<br />
<br />
Вот и всё. Вы в командной строке DOS, и можете начать играть в ваши любимые старые игры.<br />
<br />
За дополнительной информацией обращайтесь на официальный сайт DOSBox:<br />
http://dosbox.sourceforge.net/<br />
<br />
=Советы=<br />
*Если DOSBox захватил фокус мыши/клавиатуры, нажмите {{ic|Ctrl+F10}}, чтобы освободить его.</div>Arzethhttps://wiki.archlinux.org/index.php?title=DOSBox_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370879DOSBox (Русский)2015-04-23T19:46:21Z<p>Arzeth: перевёл совет с англ. версии</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Emulators (Русский)]]<br />
[[cs:DOSBox]]<br />
[[en:DOSBox]]<br />
[[es:DOSBox]]<br />
[[zh-CN:DOSBox]]<br />
{{Unmaintained (Русский)}}<br />
=Введение=<br />
DOSBox это эмулятор PC со встроенным DOS'ом предназначенный для запуска старых DOS'овских игр и программ.<br />
<br />
=Установка=<br />
Установка очень проста:<br />
# pacman -S dosbox<br />
=Настройка=<br />
Никакой начальной конфигурации не требуется.<br />
Тем не менее, официальное руководство DOSBox'a говорит о конфигурационном файле "dosbox.conf"<br />
<br><br />
Изначально этого файла не существует, Вы можете его создать:<br />
<br />
Просто запустите dosbox без параметров:<br />
$ dosbox<br />
<br />
Затем в командной строке DOS:<br />
Z:\> config -wc dosbox.conf<br />
<br />
Конфигурационный файл dosbox.conf будет сохранен в текущем каталоге<br />
<br />
=Использование=<br />
Положите вашу любимую игру/программу в каталог, затем запустите dosbox с именем этого каталога:<br />
$ dosbox ./theoldgame/<br />
<br />
Вот и все. Вы в командной строке DOS и можете начать играть в ваши любимые старые игры.<br />
<br />
За дополнительной информацией обращайтесь на официальный сайт DOSBox:<br />
http://dosbox.sourceforge.net/<br />
<br />
=Советы=<br />
*Если DOSBox захватил фокус мыши/клавиатуры, нажмите {{ic|Ctrl+F10}}, чтобы освободить его.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_from_existing_Linux_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370875Install Arch Linux from existing Linux (Русский)2015-04-23T19:35:35Z<p>Arzeth: /* Хост Debian */ Поменьше тавтологии. Добавил запятую перед «что». Убрал запятую (мы же не ставим запятую в «На моих сапогах мышь ищет сыр»).</p>
<hr />
<div>[[Category:Getting and installing Arch (Русский)]]<br />
[[Category:Русский]]<br />
{{Related articles start (Русский)}}<br />
{{Related|Install from SSH (Русский)}}<br />
{{Related articles end}}<br />
[[en:Install from existing Linux]]<br />
[[es:Install from Existing Linux]]<br />
[[fr:Install chroot]]<br />
[[it:Install from Existing Linux]]<br />
[[ja:Install from Existing Linux]]<br />
[[pt:Install from Existing Linux]]<br />
[[uk:Install from Existing Linux]]<br />
[[zh-CN:Install from existing Linux]]<br />
[[zh-TW:Install from Existing Linux]]<br />
{{Unmaintained (Русский)}}<br />
{{Translateme (Русский)|Устаревший контент был заменён английским на момент 21 февраля 2015.}}<br />
Этот документ описывает bootstrapping process, нужный для того, чтобы установить Arch Linux из уже работающего хоста Linux.<br />
После bootstrapping, установка продолжается так, как описано в [[Installation guide (Русский)|руководстве по установке]] Arch Linux.<br />
<br />
Установка Arch Linux из-под другого Linux полезна для:<br />
* беспроводной установки Arch Linux, например для виртуального сервера<br />
* замены существующего Linux без LiveCD (смотрите [[#Замена уже существующей системы без LiveCD]])<br />
* создания нового дистрибутива Linux или LiveCD основанного на Arch Linux<br />
* создания chroot окружения Arch Linux, например для контейнеров Docker<br />
* [[Diskless_network_boot_NFS_root|rootfs-over-NFS для бездисковых систем]]<br />
<br />
Цель процедуры начальной загрузки в том, чтобы настроить окружение, из которого можно будет запустить {{Pkg|arch-install-scripts}} (содержит такие скрипты как {{ic|pacstrap}} и {{ic|arch-root}}). Установить {{Pkg|arch-install-scripts}} нужно на самой хост-системе или настройкой chroot основанного на Arch Linux.<br />
<br />
Если хост работает под Arch Linux, сразу установите {{Pkg|arch-install-scripts}}.<br />
<br />
{{Note (Русский)|Этот гайд расчитан на то, что имеющийся хост может запускать программы архитектуры нового Arch Linux. В случае с x86_64 хостом, можно даже использовать i686-pacman при сборке 32-битного окружения chroot. Смотрите [[Arch64 Install bundled 32bit system | Arch64 - установка встроенной 32-битной системы]].}} <br />
<br />
==Arch Linux-based chroot==<br />
Идея состоит в том, чтобы как бы запустить Arch Linux внутри уже имеющейся системы.<br />
Настоящая установка, которая будет содержаться внутри chroot, будет затем запущена из этой Arch системы.<br />
Есть два способа настроить и войти в chroot, они представлены ниже.<br />
<br />
{{Note (Русский)|Хост-система должна использовать Linux 2.6.32 или новее.}}<br />
{{Note (Русский)|Используйте только один из двух способов, и не забудьте дочитать эту статью до конца, чтобы закончить установку.}}<br />
<br />
===Создаём chroot===<br />
<br />
====Способ 1: Использование Bootstrap образа (рекомендуется)====<br />
<br />
Скачиваем образ bootstrap с [https://www.archlinux.org/download любого желаемого зеркала], либо сразу используя прямую ссылку на нужный вам образ (с зеркала kernel.org):<br />
<br>Образ x86_64:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-x86_64.tar.gz<br />
Образ i686:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-i686.tar.gz<br />
<br />
Распаковываем его:<br />
# cd /tmp<br />
# tar xzf <путь-к-каталогу-где-образ>/archlinux-bootstrap-2015.02.01-*.tar.gz<br />
Выбираем подходящий для вашего интернета сервер, откуда будут загружаться основные репозитории:<br />
# nano /tmp/root.*/etc/pacman.d/mirrorlist<br />
<br />
{{Note (Русский)|Если ваша хост-система — x86_64, а образ boostrap — i686, то также подправьте {{Ic|/tmp/root.i686/etc/pacman.conf}}, ясно указав {{Ic|1=Architecture = i686}}, чтобы pacman качал пакеты под архитектуру i686.}}<br />
<br />
Войдём в chroot<br />
* Если установлен bash 4 или новее, то:<br />
# /tmp/root.*/bin/arch-chroot /tmp/root.*/<br />
* Иначе:<br />
# cd /tmp/root.*<br />
# cp /etc/resolv.conf etc<br />
# mount --rbind /proc proc<br />
# mount --rbind /sys sys<br />
# mount --rbind /dev dev<br />
# mount --rbind /run run<br />
(при условии, что /run существует)<br />
# chroot /tmp/root.* /bin/bash<br />
<br />
====Способ 2: Используя образ LiveCD====<br />
<br />
Можно смонтировать корневой образ последнего установочного диска Arch Linux и затем заchroot'ить туда. Плюс этого способа в том, что у вас будет сразу рабочий Arch Linux installation прямо внутри хост-системы без надобности в его настройки.<br />
<br />
{{Note (Русский)|Перед тем как продолжить, удостоверьтесь, что у вас последняя версия [http://squashfs.sourceforge.net/ squashfs] на хост-системе. Иначе будут ошибки типа: {{ic|FATAL ERROR aborting: uncompress_inode_table: failed to read block}}.}}<br />
<br />
* Корневой образ можно скачать с одного из [https://www.archlinux.org/download зеркал] в папке arch/x86_64/ либо arch/i686/, смотря какую архитектуру хотите. Образ имеет формат squashfs, который является read-only, поэтому нам надо распаковать его и смонтировать корневой образ (root-image.fs).<br />
<br />
*Чтобы распаковать корневой образ, надо<br />
{{bc|# unsquashfs -d /squashfs-root root-image.fs.sfs}}<br />
<br />
* Теперь смонтируем его с помощью опции loop<br />
{{bc|<br />
# mkdir /arch<br />
# mount -o loop /squashfs-root/root-image.fs /arch<br />
}}<br />
<br />
* Перед тем как [[Change root|chrooting]] to it, нужно смонтировать некоторые виртуальные системные разделы, а затем скопировать resolv.conf для интернета.<br />
{{bc|<br />
# mount -t proc none /arch/proc<br />
# mount -t sysfs none /arch/sys<br />
# mount -o bind /dev /arch/dev<br />
# mount -o bind /dev/pts /arch/dev/pts # важно для pacman (для проверки подписей)<br />
# cp -L /etc/resolv.conf /arch/etc # а это, чтобы мог работать интернет в chroot<br />
}}<br />
<br />
* Теперь всё готово, чтобы to chroot в только что установленное окружение Arch<br />
{{bc|# chroot /arch bash}}<br />
<br />
===Используем наше chroot окружение===<br />
<br />
====Начальная настройка хранилища ключей pacman====<br />
Перед установкой, ключи pacman должны быть настроены. Перед тем как вводить следующие две команды, можете почитать [[pacman-key#Initializing the keyring]], чтобы узнать entropy requirements:<br />
{{bc|<br />
# pacman-key --init<br />
# pacman-key --populate archlinux<br />
}}<br />
<br />
====Установка====<br />
Следуйте [[Installation guide#Mount the partitions]] и [[Installation guide#Install the base packages]].<br />
<br />
=====Хост Debian=====<br />
На хостах Debian {{ic|pacstrap}} выводит следующую ошибку:<br />
# pacstrap /mnt base<br />
# ==> Creating install root at /mnt<br />
# mount: mount point /mnt/dev/shm is a symbolic link to nowhere<br />
# ==> ERROR: failed to setup API filesystems in new root<br />
<br />
Это потому, что в Debian {{ic|/dev/shm}} ссылается на {{ic|/run/shm}}, который в Arch-based chroot не существует, поэтому ссылка не рабочая. Чтобы исправить это, просто создайте каталог {{ic|/run/shm}}:<br />
# mkdir /run/shm<br />
<br />
=====Хост Fedora=====<br />
На хостах Fedora и Live USB, если у вас не получается сгенерировать ваш {{ic|[[fstab (Русский)|fstab]]}} с помощью {{ic|genfstab}}, то удалите из fstab одинаковые записи и везде опции {{ic|seclabel}} (это опция специфична для Fedora и поэтому не даст вам загрузиться).<br />
<br />
====Настройка системы====<br />
<br />
С этого момента просто следуйте согласно разделам начиная с «[[Installation_guide_(Русский)#Монтирование разделов|Монтирование разделов]]» из [[Installation guide|руководства по установке Arch Linux]].<br />
<br />
==Замена уже существующей системы без LiveCD==<br />
Освободите ~650МБ, например, переформатировав существующий swap-раздел (после окончания установки, можете обратно создать swap). Если не можете столько освободить, выясните точно, какие пакеты группы base вам понадобятся для того, чтобы get a system с работающим интернетом and running in the temporary partition. То есть надо будет ясно указать каждый пакет для pacstrap. И ещё надо указать -c, чтобы пакеты скачивались на хост-систему, дабы избежать недостатка свободного места.<br />
<br />
После того как установили, перезагрузитесь в свою новую систему, затем [[Full system backup with rsync#With_a_single_command|rsync the entire system]] to the primary partition.<br />
Fix the bootloader configuration before rebooting.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_from_existing_Linux_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370872Install Arch Linux from existing Linux (Русский)2015-04-23T19:26:25Z<p>Arzeth: /* Хост Debian */ выделил пути с помощью {{ic|путь}}</p>
<hr />
<div>[[Category:Getting and installing Arch (Русский)]]<br />
[[Category:Русский]]<br />
{{Related articles start (Русский)}}<br />
{{Related|Install from SSH (Русский)}}<br />
{{Related articles end}}<br />
[[en:Install from existing Linux]]<br />
[[es:Install from Existing Linux]]<br />
[[fr:Install chroot]]<br />
[[it:Install from Existing Linux]]<br />
[[ja:Install from Existing Linux]]<br />
[[pt:Install from Existing Linux]]<br />
[[uk:Install from Existing Linux]]<br />
[[zh-CN:Install from existing Linux]]<br />
[[zh-TW:Install from Existing Linux]]<br />
{{Unmaintained (Русский)}}<br />
{{Translateme (Русский)|Устаревший контент был заменён английским на момент 21 февраля 2015.}}<br />
Этот документ описывает bootstrapping process, нужный для того, чтобы установить Arch Linux из уже работающего хоста Linux.<br />
После bootstrapping, установка продолжается так, как описано в [[Installation guide (Русский)|руководстве по установке]] Arch Linux.<br />
<br />
Установка Arch Linux из-под другого Linux полезна для:<br />
* беспроводной установки Arch Linux, например для виртуального сервера<br />
* замены существующего Linux без LiveCD (смотрите [[#Замена уже существующей системы без LiveCD]])<br />
* создания нового дистрибутива Linux или LiveCD основанного на Arch Linux<br />
* создания chroot окружения Arch Linux, например для контейнеров Docker<br />
* [[Diskless_network_boot_NFS_root|rootfs-over-NFS для бездисковых систем]]<br />
<br />
Цель процедуры начальной загрузки в том, чтобы настроить окружение, из которого можно будет запустить {{Pkg|arch-install-scripts}} (содержит такие скрипты как {{ic|pacstrap}} и {{ic|arch-root}}). Установить {{Pkg|arch-install-scripts}} нужно на самой хост-системе или настройкой chroot основанного на Arch Linux.<br />
<br />
Если хост работает под Arch Linux, сразу установите {{Pkg|arch-install-scripts}}.<br />
<br />
{{Note (Русский)|Этот гайд расчитан на то, что имеющийся хост может запускать программы архитектуры нового Arch Linux. В случае с x86_64 хостом, можно даже использовать i686-pacman при сборке 32-битного окружения chroot. Смотрите [[Arch64 Install bundled 32bit system | Arch64 - установка встроенной 32-битной системы]].}} <br />
<br />
==Arch Linux-based chroot==<br />
Идея состоит в том, чтобы как бы запустить Arch Linux внутри уже имеющейся системы.<br />
Настоящая установка, которая будет содержаться внутри chroot, будет затем запущена из этой Arch системы.<br />
Есть два способа настроить и войти в chroot, они представлены ниже.<br />
<br />
{{Note (Русский)|Хост-система должна использовать Linux 2.6.32 или новее.}}<br />
{{Note (Русский)|Используйте только один из двух способов, и не забудьте дочитать эту статью до конца, чтобы закончить установку.}}<br />
<br />
===Создаём chroot===<br />
<br />
====Способ 1: Использование Bootstrap образа (рекомендуется)====<br />
<br />
Скачиваем образ bootstrap с [https://www.archlinux.org/download любого желаемого зеркала], либо сразу используя прямую ссылку на нужный вам образ (с зеркала kernel.org):<br />
<br>Образ x86_64:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-x86_64.tar.gz<br />
Образ i686:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-i686.tar.gz<br />
<br />
Распаковываем его:<br />
# cd /tmp<br />
# tar xzf <путь-к-каталогу-где-образ>/archlinux-bootstrap-2015.02.01-*.tar.gz<br />
Выбираем подходящий для вашего интернета сервер, откуда будут загружаться основные репозитории:<br />
# nano /tmp/root.*/etc/pacman.d/mirrorlist<br />
<br />
{{Note (Русский)|Если ваша хост-система — x86_64, а образ boostrap — i686, то также подправьте {{Ic|/tmp/root.i686/etc/pacman.conf}}, ясно указав {{Ic|1=Architecture = i686}}, чтобы pacman качал пакеты под архитектуру i686.}}<br />
<br />
Войдём в chroot<br />
* Если установлен bash 4 или новее, то:<br />
# /tmp/root.*/bin/arch-chroot /tmp/root.*/<br />
* Иначе:<br />
# cd /tmp/root.*<br />
# cp /etc/resolv.conf etc<br />
# mount --rbind /proc proc<br />
# mount --rbind /sys sys<br />
# mount --rbind /dev dev<br />
# mount --rbind /run run<br />
(при условии, что /run существует)<br />
# chroot /tmp/root.* /bin/bash<br />
<br />
====Способ 2: Используя образ LiveCD====<br />
<br />
Можно смонтировать корневой образ последнего установочного диска Arch Linux и затем заchroot'ить туда. Плюс этого способа в том, что у вас будет сразу рабочий Arch Linux installation прямо внутри хост-системы без надобности в его настройки.<br />
<br />
{{Note (Русский)|Перед тем как продолжить, удостоверьтесь, что у вас последняя версия [http://squashfs.sourceforge.net/ squashfs] на хост-системе. Иначе будут ошибки типа: {{ic|FATAL ERROR aborting: uncompress_inode_table: failed to read block}}.}}<br />
<br />
* Корневой образ можно скачать с одного из [https://www.archlinux.org/download зеркал] в папке arch/x86_64/ либо arch/i686/, смотря какую архитектуру хотите. Образ имеет формат squashfs, который является read-only, поэтому нам надо распаковать его и смонтировать корневой образ (root-image.fs).<br />
<br />
*Чтобы распаковать корневой образ, надо<br />
{{bc|# unsquashfs -d /squashfs-root root-image.fs.sfs}}<br />
<br />
* Теперь смонтируем его с помощью опции loop<br />
{{bc|<br />
# mkdir /arch<br />
# mount -o loop /squashfs-root/root-image.fs /arch<br />
}}<br />
<br />
* Перед тем как [[Change root|chrooting]] to it, нужно смонтировать некоторые виртуальные системные разделы, а затем скопировать resolv.conf для интернета.<br />
{{bc|<br />
# mount -t proc none /arch/proc<br />
# mount -t sysfs none /arch/sys<br />
# mount -o bind /dev /arch/dev<br />
# mount -o bind /dev/pts /arch/dev/pts # важно для pacman (для проверки подписей)<br />
# cp -L /etc/resolv.conf /arch/etc # а это, чтобы мог работать интернет в chroot<br />
}}<br />
<br />
* Теперь всё готово, чтобы to chroot в только что установленное окружение Arch<br />
{{bc|# chroot /arch bash}}<br />
<br />
===Используем наше chroot окружение===<br />
<br />
====Начальная настройка хранилища ключей pacman====<br />
Перед установкой, ключи pacman должны быть настроены. Перед тем как вводить следующие две команды, можете почитать [[pacman-key#Initializing the keyring]], чтобы узнать entropy requirements:<br />
{{bc|<br />
# pacman-key --init<br />
# pacman-key --populate archlinux<br />
}}<br />
<br />
====Установка====<br />
Следуйте [[Installation guide#Mount the partitions]] и [[Installation guide#Install the base packages]].<br />
<br />
=====Хост Debian=====<br />
На хостах Debian, {{ic|pacstrap}} выводит следующую ошибку:<br />
# pacstrap /mnt base<br />
# ==> Creating install root at /mnt<br />
# mount: mount point /mnt/dev/shm is a symbolic link to nowhere<br />
# ==> ERROR: failed to setup API filesystems in new root<br />
<br />
Это потому что в Debian {{ic|/dev/shm}} ссылается на {{ic|/run/shm}}, а в Arch-based chroot {{ic|/run/shm}} не существует, поэтому ссылка не рабочая. Чтобы исправить это, просто создайте каталог {{ic|/run/shm}}:<br />
# mkdir /run/shm<br />
<br />
=====Хост Fedora=====<br />
На хостах Fedora и Live USB, если у вас не получается сгенерировать ваш {{ic|[[fstab (Русский)|fstab]]}} с помощью {{ic|genfstab}}, то удалите из fstab одинаковые записи и везде опции {{ic|seclabel}} (это опция специфична для Fedora и поэтому не даст вам загрузиться).<br />
<br />
====Настройка системы====<br />
<br />
С этого момента просто следуйте согласно разделам начиная с «[[Installation_guide_(Русский)#Монтирование разделов|Монтирование разделов]]» из [[Installation guide|руководства по установке Arch Linux]].<br />
<br />
==Замена уже существующей системы без LiveCD==<br />
Освободите ~650МБ, например, переформатировав существующий swap-раздел (после окончания установки, можете обратно создать swap). Если не можете столько освободить, выясните точно, какие пакеты группы base вам понадобятся для того, чтобы get a system с работающим интернетом and running in the temporary partition. То есть надо будет ясно указать каждый пакет для pacstrap. И ещё надо указать -c, чтобы пакеты скачивались на хост-систему, дабы избежать недостатка свободного места.<br />
<br />
После того как установили, перезагрузитесь в свою новую систему, затем [[Full system backup with rsync#With_a_single_command|rsync the entire system]] to the primary partition.<br />
Fix the bootloader configuration before rebooting.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_from_existing_Linux_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370871Install Arch Linux from existing Linux (Русский)2015-04-23T19:25:07Z<p>Arzeth: ссылку # обновил, т. к. перевёл</p>
<hr />
<div>[[Category:Getting and installing Arch (Русский)]]<br />
[[Category:Русский]]<br />
{{Related articles start (Русский)}}<br />
{{Related|Install from SSH (Русский)}}<br />
{{Related articles end}}<br />
[[en:Install from existing Linux]]<br />
[[es:Install from Existing Linux]]<br />
[[fr:Install chroot]]<br />
[[it:Install from Existing Linux]]<br />
[[ja:Install from Existing Linux]]<br />
[[pt:Install from Existing Linux]]<br />
[[uk:Install from Existing Linux]]<br />
[[zh-CN:Install from existing Linux]]<br />
[[zh-TW:Install from Existing Linux]]<br />
{{Unmaintained (Русский)}}<br />
{{Translateme (Русский)|Устаревший контент был заменён английским на момент 21 февраля 2015.}}<br />
Этот документ описывает bootstrapping process, нужный для того, чтобы установить Arch Linux из уже работающего хоста Linux.<br />
После bootstrapping, установка продолжается так, как описано в [[Installation guide (Русский)|руководстве по установке]] Arch Linux.<br />
<br />
Установка Arch Linux из-под другого Linux полезна для:<br />
* беспроводной установки Arch Linux, например для виртуального сервера<br />
* замены существующего Linux без LiveCD (смотрите [[#Замена уже существующей системы без LiveCD]])<br />
* создания нового дистрибутива Linux или LiveCD основанного на Arch Linux<br />
* создания chroot окружения Arch Linux, например для контейнеров Docker<br />
* [[Diskless_network_boot_NFS_root|rootfs-over-NFS для бездисковых систем]]<br />
<br />
Цель процедуры начальной загрузки в том, чтобы настроить окружение, из которого можно будет запустить {{Pkg|arch-install-scripts}} (содержит такие скрипты как {{ic|pacstrap}} и {{ic|arch-root}}). Установить {{Pkg|arch-install-scripts}} нужно на самой хост-системе или настройкой chroot основанного на Arch Linux.<br />
<br />
Если хост работает под Arch Linux, сразу установите {{Pkg|arch-install-scripts}}.<br />
<br />
{{Note (Русский)|Этот гайд расчитан на то, что имеющийся хост может запускать программы архитектуры нового Arch Linux. В случае с x86_64 хостом, можно даже использовать i686-pacman при сборке 32-битного окружения chroot. Смотрите [[Arch64 Install bundled 32bit system | Arch64 - установка встроенной 32-битной системы]].}} <br />
<br />
==Arch Linux-based chroot==<br />
Идея состоит в том, чтобы как бы запустить Arch Linux внутри уже имеющейся системы.<br />
Настоящая установка, которая будет содержаться внутри chroot, будет затем запущена из этой Arch системы.<br />
Есть два способа настроить и войти в chroot, они представлены ниже.<br />
<br />
{{Note (Русский)|Хост-система должна использовать Linux 2.6.32 или новее.}}<br />
{{Note (Русский)|Используйте только один из двух способов, и не забудьте дочитать эту статью до конца, чтобы закончить установку.}}<br />
<br />
===Создаём chroot===<br />
<br />
====Способ 1: Использование Bootstrap образа (рекомендуется)====<br />
<br />
Скачиваем образ bootstrap с [https://www.archlinux.org/download любого желаемого зеркала], либо сразу используя прямую ссылку на нужный вам образ (с зеркала kernel.org):<br />
<br>Образ x86_64:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-x86_64.tar.gz<br />
Образ i686:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-i686.tar.gz<br />
<br />
Распаковываем его:<br />
# cd /tmp<br />
# tar xzf <путь-к-каталогу-где-образ>/archlinux-bootstrap-2015.02.01-*.tar.gz<br />
Выбираем подходящий для вашего интернета сервер, откуда будут загружаться основные репозитории:<br />
# nano /tmp/root.*/etc/pacman.d/mirrorlist<br />
<br />
{{Note (Русский)|Если ваша хост-система — x86_64, а образ boostrap — i686, то также подправьте {{Ic|/tmp/root.i686/etc/pacman.conf}}, ясно указав {{Ic|1=Architecture = i686}}, чтобы pacman качал пакеты под архитектуру i686.}}<br />
<br />
Войдём в chroot<br />
* Если установлен bash 4 или новее, то:<br />
# /tmp/root.*/bin/arch-chroot /tmp/root.*/<br />
* Иначе:<br />
# cd /tmp/root.*<br />
# cp /etc/resolv.conf etc<br />
# mount --rbind /proc proc<br />
# mount --rbind /sys sys<br />
# mount --rbind /dev dev<br />
# mount --rbind /run run<br />
(при условии, что /run существует)<br />
# chroot /tmp/root.* /bin/bash<br />
<br />
====Способ 2: Используя образ LiveCD====<br />
<br />
Можно смонтировать корневой образ последнего установочного диска Arch Linux и затем заchroot'ить туда. Плюс этого способа в том, что у вас будет сразу рабочий Arch Linux installation прямо внутри хост-системы без надобности в его настройки.<br />
<br />
{{Note (Русский)|Перед тем как продолжить, удостоверьтесь, что у вас последняя версия [http://squashfs.sourceforge.net/ squashfs] на хост-системе. Иначе будут ошибки типа: {{ic|FATAL ERROR aborting: uncompress_inode_table: failed to read block}}.}}<br />
<br />
* Корневой образ можно скачать с одного из [https://www.archlinux.org/download зеркал] в папке arch/x86_64/ либо arch/i686/, смотря какую архитектуру хотите. Образ имеет формат squashfs, который является read-only, поэтому нам надо распаковать его и смонтировать корневой образ (root-image.fs).<br />
<br />
*Чтобы распаковать корневой образ, надо<br />
{{bc|# unsquashfs -d /squashfs-root root-image.fs.sfs}}<br />
<br />
* Теперь смонтируем его с помощью опции loop<br />
{{bc|<br />
# mkdir /arch<br />
# mount -o loop /squashfs-root/root-image.fs /arch<br />
}}<br />
<br />
* Перед тем как [[Change root|chrooting]] to it, нужно смонтировать некоторые виртуальные системные разделы, а затем скопировать resolv.conf для интернета.<br />
{{bc|<br />
# mount -t proc none /arch/proc<br />
# mount -t sysfs none /arch/sys<br />
# mount -o bind /dev /arch/dev<br />
# mount -o bind /dev/pts /arch/dev/pts # важно для pacman (для проверки подписей)<br />
# cp -L /etc/resolv.conf /arch/etc # а это, чтобы мог работать интернет в chroot<br />
}}<br />
<br />
* Теперь всё готово, чтобы to chroot в только что установленное окружение Arch<br />
{{bc|# chroot /arch bash}}<br />
<br />
===Используем наше chroot окружение===<br />
<br />
====Начальная настройка хранилища ключей pacman====<br />
Перед установкой, ключи pacman должны быть настроены. Перед тем как вводить следующие две команды, можете почитать [[pacman-key#Initializing the keyring]], чтобы узнать entropy requirements:<br />
{{bc|<br />
# pacman-key --init<br />
# pacman-key --populate archlinux<br />
}}<br />
<br />
====Установка====<br />
Следуйте [[Installation guide#Mount the partitions]] и [[Installation guide#Install the base packages]].<br />
<br />
=====Хост Debian=====<br />
На хостах Debian, {{ic|pacstrap}} выводит следующую ошибку:<br />
# pacstrap /mnt base<br />
# ==> Creating install root at /mnt<br />
# mount: mount point /mnt/dev/shm is a symbolic link to nowhere<br />
# ==> ERROR: failed to setup API filesystems in new root<br />
<br />
Это потому что в Debian /dev/shm ссылается на /run/shm, а в Arch-based chroot /run/shm не существует, поэтому ссылка не рабочая. Чтобы исправить это, просто создайте каталог /run/shm:<br />
# mkdir /run/shm<br />
<br />
=====Хост Fedora=====<br />
На хостах Fedora и Live USB, если у вас не получается сгенерировать ваш {{ic|[[fstab (Русский)|fstab]]}} с помощью {{ic|genfstab}}, то удалите из fstab одинаковые записи и везде опции {{ic|seclabel}} (это опция специфична для Fedora и поэтому не даст вам загрузиться).<br />
<br />
====Настройка системы====<br />
<br />
С этого момента просто следуйте согласно разделам начиная с «[[Installation_guide_(Русский)#Монтирование разделов|Монтирование разделов]]» из [[Installation guide|руководства по установке Arch Linux]].<br />
<br />
==Замена уже существующей системы без LiveCD==<br />
Освободите ~650МБ, например, переформатировав существующий swap-раздел (после окончания установки, можете обратно создать swap). Если не можете столько освободить, выясните точно, какие пакеты группы base вам понадобятся для того, чтобы get a system с работающим интернетом and running in the temporary partition. То есть надо будет ясно указать каждый пакет для pacstrap. И ещё надо указать -c, чтобы пакеты скачивались на хост-систему, дабы избежать недостатка свободного места.<br />
<br />
После того как установили, перезагрузитесь в свою новую систему, затем [[Full system backup with rsync#With_a_single_command|rsync the entire system]] to the primary partition.<br />
Fix the bootloader configuration before rebooting.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_from_existing_Linux_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370870Install Arch Linux from existing Linux (Русский)2015-04-23T19:23:42Z<p>Arzeth: </p>
<hr />
<div>[[Category:Getting and installing Arch (Русский)]]<br />
[[Category:Русский]]<br />
{{Related articles start (Русский)}}<br />
{{Related|Install from SSH (Русский)}}<br />
{{Related articles end}}<br />
[[en:Install from existing Linux]]<br />
[[es:Install from Existing Linux]]<br />
[[fr:Install chroot]]<br />
[[it:Install from Existing Linux]]<br />
[[ja:Install from Existing Linux]]<br />
[[pt:Install from Existing Linux]]<br />
[[uk:Install from Existing Linux]]<br />
[[zh-CN:Install from existing Linux]]<br />
[[zh-TW:Install from Existing Linux]]<br />
{{Unmaintained (Русский)}}<br />
{{Translateme (Русский)|Устаревший контент был заменён английским на момент 21 февраля 2015.}}<br />
Этот документ описывает bootstrapping process, нужный для того, чтобы установить Arch Linux из уже работающего хоста Linux.<br />
После bootstrapping, установка продолжается так, как описано в [[Installation guide (Русский)|руководстве по установке]] Arch Linux.<br />
<br />
Установка Arch Linux из-под другого Linux полезна для:<br />
* беспроводной установки Arch Linux, например для виртуального сервера<br />
* замены существующего Linux без LiveCD (смотрите [[#Replacing the Existing System without a LiveCD]])<br />
* создания нового дистрибутива Linux или LiveCD основанного на Arch Linux<br />
* создания chroot окружения Arch Linux, например для контейнеров Docker<br />
* [[Diskless_network_boot_NFS_root|rootfs-over-NFS для бездисковых систем]]<br />
<br />
Цель процедуры начальной загрузки в том, чтобы настроить окружение, из которого можно будет запустить {{Pkg|arch-install-scripts}} (содержит такие скрипты как {{ic|pacstrap}} и {{ic|arch-root}}). Установить {{Pkg|arch-install-scripts}} нужно на самой хост-системе или настройкой chroot основанного на Arch Linux.<br />
<br />
Если хост работает под Arch Linux, сразу установите {{Pkg|arch-install-scripts}}.<br />
<br />
{{Note (Русский)|Этот гайд расчитан на то, что имеющийся хост может запускать программы архитектуры нового Arch Linux. В случае с x86_64 хостом, можно даже использовать i686-pacman при сборке 32-битного окружения chroot. Смотрите [[Arch64 Install bundled 32bit system | Arch64 - установка встроенной 32-битной системы]].}} <br />
<br />
==Arch Linux-based chroot==<br />
Идея состоит в том, чтобы как бы запустить Arch Linux внутри уже имеющейся системы.<br />
Настоящая установка, которая будет содержаться внутри chroot, будет затем запущена из этой Arch системы.<br />
Есть два способа настроить и войти в chroot, они представлены ниже.<br />
<br />
{{Note (Русский)|Хост-система должна использовать Linux 2.6.32 или новее.}}<br />
{{Note (Русский)|Используйте только один из двух способов, и не забудьте дочитать эту статью до конца, чтобы закончить установку.}}<br />
<br />
===Создаём chroot===<br />
<br />
====Способ 1: Использование Bootstrap образа (рекомендуется)====<br />
<br />
Скачиваем образ bootstrap с [https://www.archlinux.org/download любого желаемого зеркала], либо сразу используя прямую ссылку на нужный вам образ (с зеркала kernel.org):<br />
<br>Образ x86_64:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-x86_64.tar.gz<br />
Образ i686:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-i686.tar.gz<br />
<br />
Распаковываем его:<br />
# cd /tmp<br />
# tar xzf <путь-к-каталогу-где-образ>/archlinux-bootstrap-2015.02.01-*.tar.gz<br />
Выбираем подходящий для вашего интернета сервер, откуда будут загружаться основные репозитории:<br />
# nano /tmp/root.*/etc/pacman.d/mirrorlist<br />
<br />
{{Note (Русский)|Если ваша хост-система — x86_64, а образ boostrap — i686, то также подправьте {{Ic|/tmp/root.i686/etc/pacman.conf}}, ясно указав {{Ic|1=Architecture = i686}}, чтобы pacman качал пакеты под архитектуру i686.}}<br />
<br />
Войдём в chroot<br />
* Если установлен bash 4 или новее, то:<br />
# /tmp/root.*/bin/arch-chroot /tmp/root.*/<br />
* Иначе:<br />
# cd /tmp/root.*<br />
# cp /etc/resolv.conf etc<br />
# mount --rbind /proc proc<br />
# mount --rbind /sys sys<br />
# mount --rbind /dev dev<br />
# mount --rbind /run run<br />
(при условии, что /run существует)<br />
# chroot /tmp/root.* /bin/bash<br />
<br />
====Способ 2: Используя образ LiveCD====<br />
<br />
Можно смонтировать корневой образ последнего установочного диска Arch Linux и затем заchroot'ить туда. Плюс этого способа в том, что у вас будет сразу рабочий Arch Linux installation прямо внутри хост-системы без надобности в его настройки.<br />
<br />
{{Note (Русский)|Перед тем как продолжить, удостоверьтесь, что у вас последняя версия [http://squashfs.sourceforge.net/ squashfs] на хост-системе. Иначе будут ошибки типа: {{ic|FATAL ERROR aborting: uncompress_inode_table: failed to read block}}.}}<br />
<br />
* Корневой образ можно скачать с одного из [https://www.archlinux.org/download зеркал] в папке arch/x86_64/ либо arch/i686/, смотря какую архитектуру хотите. Образ имеет формат squashfs, который является read-only, поэтому нам надо распаковать его и смонтировать корневой образ (root-image.fs).<br />
<br />
*Чтобы распаковать корневой образ, надо<br />
{{bc|# unsquashfs -d /squashfs-root root-image.fs.sfs}}<br />
<br />
* Теперь смонтируем его с помощью опции loop<br />
{{bc|<br />
# mkdir /arch<br />
# mount -o loop /squashfs-root/root-image.fs /arch<br />
}}<br />
<br />
* Перед тем как [[Change root|chrooting]] to it, нужно смонтировать некоторые виртуальные системные разделы, а затем скопировать resolv.conf для интернета.<br />
{{bc|<br />
# mount -t proc none /arch/proc<br />
# mount -t sysfs none /arch/sys<br />
# mount -o bind /dev /arch/dev<br />
# mount -o bind /dev/pts /arch/dev/pts # важно для pacman (для проверки подписей)<br />
# cp -L /etc/resolv.conf /arch/etc # а это, чтобы мог работать интернет в chroot<br />
}}<br />
<br />
* Теперь всё готово, чтобы to chroot в только что установленное окружение Arch<br />
{{bc|# chroot /arch bash}}<br />
<br />
===Используем наше chroot окружение===<br />
<br />
====Начальная настройка хранилища ключей pacman====<br />
Перед установкой, ключи pacman должны быть настроены. Перед тем как вводить следующие две команды, можете почитать [[pacman-key#Initializing the keyring]], чтобы узнать entropy requirements:<br />
{{bc|<br />
# pacman-key --init<br />
# pacman-key --populate archlinux<br />
}}<br />
<br />
====Установка====<br />
Следуйте [[Installation guide#Mount the partitions]] и [[Installation guide#Install the base packages]].<br />
<br />
=====Хост Debian=====<br />
На хостах Debian, {{ic|pacstrap}} выводит следующую ошибку:<br />
# pacstrap /mnt base<br />
# ==> Creating install root at /mnt<br />
# mount: mount point /mnt/dev/shm is a symbolic link to nowhere<br />
# ==> ERROR: failed to setup API filesystems in new root<br />
<br />
Это потому что в Debian /dev/shm ссылается на /run/shm, а в Arch-based chroot /run/shm не существует, поэтому ссылка не рабочая. Чтобы исправить это, просто создайте каталог /run/shm:<br />
# mkdir /run/shm<br />
<br />
=====Хост Fedora=====<br />
На хостах Fedora и Live USB, если у вас не получается сгенерировать ваш {{ic|[[fstab (Русский)|fstab]]}} с помощью {{ic|genfstab}}, то удалите из fstab одинаковые записи и везде опции {{ic|seclabel}} (это опция специфична для Fedora и поэтому не даст вам загрузиться).<br />
<br />
====Настройка системы====<br />
<br />
С этого момента просто следуйте согласно разделам начиная с «[[Installation_guide_(Русский)#Монтирование разделов|Монтирование разделов]]» из [[Installation guide|руководства по установке Arch Linux]].<br />
<br />
==Замена уже существующей системы без LiveCD==<br />
Освободите ~650МБ, например, переформатировав существующий swap-раздел (после окончания установки, можете обратно создать swap). Если не можете столько освободить, выясните точно, какие пакеты группы base вам понадобятся для того, чтобы get a system с работающим интернетом and running in the temporary partition. То есть надо будет ясно указать каждый пакет для pacstrap. И ещё надо указать -c, чтобы пакеты скачивались на хост-систему, дабы избежать недостатка свободного места.<br />
<br />
После того как установили, перезагрузитесь в свою новую систему, затем [[Full system backup with rsync#With_a_single_command|rsync the entire system]] to the primary partition.<br />
Fix the bootloader configuration before rebooting.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_from_existing_Linux_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370864Install Arch Linux from existing Linux (Русский)2015-04-23T19:12:40Z<p>Arzeth: </p>
<hr />
<div>[[Category:Getting and installing Arch (Русский)]]<br />
[[Category:Русский]]<br />
{{Related articles start (Русский)}}<br />
{{Related|Install from SSH (Русский)}}<br />
{{Related articles end}}<br />
[[en:Install from existing Linux]]<br />
[[es:Install from Existing Linux]]<br />
[[fr:Install chroot]]<br />
[[it:Install from Existing Linux]]<br />
[[ja:Install from Existing Linux]]<br />
[[pt:Install from Existing Linux]]<br />
[[uk:Install from Existing Linux]]<br />
[[zh-CN:Install from existing Linux]]<br />
[[zh-TW:Install from Existing Linux]]<br />
{{Unmaintained (Русский)}}<br />
{{Translateme (Русский)|Устаревший контент был заменён английским на момент 21 февраля 2015.}}<br />
Этот документ описывает bootstrapping process, нужный для того, чтобы установить Arch Linux из уже работающего хоста Linux.<br />
После bootstrapping, установка продолжается так, как описано в [[Installation guide]].<br />
<br />
Установка Arch Linux из-под другого Linux полезна для:<br />
* беспроводной установки Arch Linux, например для виртуального сервера<br />
* замены существующего Linux без LiveCD (смотрите [[#Replacing the Existing System without a LiveCD]])<br />
* создания нового дистрибутива Linux или LiveCD основанного на Arch Linux<br />
* создания chroot окружения Arch Linux, например для (Docker base container?)<br />
* [[Diskless_network_boot_NFS_root|rootfs-over-NFS для бездисковых систем]]<br />
<br />
Цель процедуры начальной загрузки в том, чтобы настроить окружение из которого {{Pkg|arch-install-scripts}} (такие как {{ic|pacstrap}} и {{ic|arch-root}}) запускаются.<br />
Цель достигается установкой {{Pkg|arch-install-scripts}} изначально на хост-систему или настройкой chroot основанного на Arch Linux.<br />
<br />
Если хост работает под Arch Linux, сразу установите {{Pkg|arch-install-scripts}}.<br />
<br />
{{Note (Русский)|Этот гайд расчитан на то, что имеющийся хост может запускать программы архитектуры нового Arch Linux. В случае с x86_64 хостом, можно даже использовать i686-pacman при сборке 32-битного окружения chroot. Смотрите [[Arch64 Install bundled 32bit system | Arch64 - установка встроенной 32-битной системы]].}} <br />
<br />
==Arch Linux-based chroot==<br />
Идея состоит в том, чтобы как бы запустить Arch Linux внутри уже имеющейся системы.<br />
Настоящая установка, которая будет содержаться внутри chroot, будет затем запущена из этой Arch системы.<br />
Есть два способа настроить и войти в chroot, они представлены ниже.<br />
<br />
{{Note (Русский)|Хост-система должна использовать Linux 2.6.32 или новее.}}<br />
{{Note (Русский)|Используйте только один из двух способов, и не забудьте дочитать эту статью до конца, чтобы закончить установку.}}<br />
<br />
===Создаём chroot===<br />
<br />
====Способ 1: Использование Bootstrap образа (рекомендуется)====<br />
<br />
Скачиваем образ bootstrap с [https://www.archlinux.org/download любого желаемого зеркала], либо сразу используя прямую ссылку на нужный вам образ (с зеркала kernel.org):<br />
<br>Образ x86_64:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-x86_64.tar.gz<br />
Образ i686:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-i686.tar.gz<br />
<br />
Распаковываем его:<br />
# cd /tmp<br />
# tar xzf <путь-к-каталогу-где-образ>/archlinux-bootstrap-2015.02.01-*.tar.gz<br />
Выбираем подходящий для вашего интернета сервер, откуда будут загружаться основные репозитории:<br />
# nano /tmp/root.*/etc/pacman.d/mirrorlist<br />
<br />
{{Note (Русский)|Если ваша хост-система — x86_64, а образ boostrap — i686, то также подправьте {{Ic|/tmp/root.i686/etc/pacman.conf}}, ясно указав {{Ic|1=Architecture = i686}}, чтобы pacman качал пакеты под архитектуру i686.}}<br />
<br />
Войдём в chroot<br />
* Если установлен bash 4 или новее, то:<br />
# /tmp/root.*/bin/arch-chroot /tmp/root.*/<br />
* Иначе:<br />
# cd /tmp/root.*<br />
# cp /etc/resolv.conf etc<br />
# mount --rbind /proc proc<br />
# mount --rbind /sys sys<br />
# mount --rbind /dev dev<br />
# mount --rbind /run run<br />
(при условии, что /run существует)<br />
# chroot /tmp/root.* /bin/bash<br />
<br />
====Способ 2: Используя образ LiveCD====<br />
<br />
Можно смонтировать корневой образ последнего установочного диска Arch Linux и затем заchroot'ить туда. Плюс этого способа в том, что у вас будет сразу рабочий Arch Linux installation прямо внутри хост-системы без надобности в его настройки.<br />
<br />
{{Note (Русский)|Перед тем как продолжить, удостоверьтесь, что у вас последняя версия [http://squashfs.sourceforge.net/ squashfs] на хост-системе. Иначе будут ошибки типа: {{ic|FATAL ERROR aborting: uncompress_inode_table: failed to read block}}.}}<br />
<br />
* Корневой образ можно скачать с одного из [https://www.archlinux.org/download зеркал] в папке arch/x86_64/ либо arch/i686/, смотря какую архитектуру хотите. Образ имеет формат squashfs, который является read-only, поэтому нам надо распаковать его и смонтировать корневой образ (root-image.fs).<br />
<br />
*Чтобы распаковать корневой образ, надо<br />
{{bc|# unsquashfs -d /squashfs-root root-image.fs.sfs}}<br />
<br />
* Теперь смонтируем его с помощью опции loop<br />
{{bc|<br />
# mkdir /arch<br />
# mount -o loop /squashfs-root/root-image.fs /arch<br />
}}<br />
<br />
* Перед тем как [[Change root|chrooting]] to it, нужно смонтировать некоторые виртуальные системные разделы, а затем скопировать resolv.conf для интернета.<br />
{{bc|<br />
# mount -t proc none /arch/proc<br />
# mount -t sysfs none /arch/sys<br />
# mount -o bind /dev /arch/dev<br />
# mount -o bind /dev/pts /arch/dev/pts # важно для pacman (для проверки подписей)<br />
# cp -L /etc/resolv.conf /arch/etc # а это, чтобы мог работать интернет в chroot<br />
}}<br />
<br />
* Теперь всё готово, чтобы to chroot в только что установленное окружение Arch<br />
{{bc|# chroot /arch bash}}<br />
<br />
===Используем наше chroot окружение===<br />
<br />
====Начальная настройка хранилища ключей pacman====<br />
Перед установкой, ключи pacman должны быть настроены. Перед тем как вводить следующие две команды, можете почитать [[pacman-key#Initializing the keyring]], чтобы узнать entropy requirements:<br />
{{bc|<br />
# pacman-key --init<br />
# pacman-key --populate archlinux<br />
}}<br />
<br />
====Установка====<br />
Следуйте [[Installation guide#Mount the partitions]] и [[Installation guide#Install the base packages]].<br />
<br />
=====Хост Debian=====<br />
На хостах Debian, {{ic|pacstrap}} выводит следующую ошибку:<br />
# pacstrap /mnt base<br />
# ==> Creating install root at /mnt<br />
# mount: mount point /mnt/dev/shm is a symbolic link to nowhere<br />
# ==> ERROR: failed to setup API filesystems in new root<br />
<br />
Это потому что в Debian /dev/shm ссылается на /run/shm, а в Arch-based chroot /run/shm не существует, поэтому ссылка не рабочая. Чтобы исправить это, просто создайте каталог /run/shm:<br />
# mkdir /run/shm<br />
<br />
=====Хост Fedora=====<br />
На хостах Fedora и Live USB, если у вас не получается сгенерировать ваш {{ic|[[fstab (Русский)|fstab]]}} с помощью {{ic|genfstab}}, то удалите из fstab одинаковые записи и везде опции {{ic|seclabel}} (это опция специфична для Fedora и поэтому не даст вам загрузиться).<br />
<br />
====Настройка системы====<br />
<br />
С этого момента просто следуйте согласно разделам начиная с «[[Installation_guide_(Русский)#Монтирование разделов|Монтирование разделов]]» из [[Installation guide|руководства по установке Arch Linux]].<br />
<br />
==Замена уже существующей системы без LiveCD==<br />
Освободите ~650МБ, например, переформатировав существующий swap-раздел (после окончания установки, можете обратно создать swap). Если не можете столько освободить, выясните точно, какие пакеты группы base вам понадобятся для того, чтобы get a system с работающим интернетом and running in the temporary partition. То есть надо будет ясно указать каждый пакет для pacstrap. И ещё надо указать -c, чтобы пакеты скачивались на хост-систему, дабы избежать недостатка свободного места.<br />
<br />
После того как установили, перезагрузитесь в свою новую систему, затем [[Full system backup with rsync#With_a_single_command|rsync the entire system]] to the primary partition.<br />
Fix the bootloader configuration before rebooting.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_from_existing_Linux_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370861Install Arch Linux from existing Linux (Русский)2015-04-23T19:08:23Z<p>Arzeth: /* Способ 2: Используя образ LiveCD */</p>
<hr />
<div>[[Category:Getting and installing Arch (Русский)]]<br />
[[Category:Русский]]<br />
{{Related articles start (Русский)}}<br />
{{Related|Install from SSH (Русский)}}<br />
{{Related articles end}}<br />
[[en:Install from existing Linux]]<br />
[[es:Install from Existing Linux]]<br />
[[fr:Install chroot]]<br />
[[it:Install from Existing Linux]]<br />
[[ja:Install from Existing Linux]]<br />
[[pt:Install from Existing Linux]]<br />
[[uk:Install from Existing Linux]]<br />
[[zh-CN:Install from existing Linux]]<br />
[[zh-TW:Install from Existing Linux]]<br />
{{Unmaintained (Русский)}}<br />
{{Translateme (Русский)|Устаревший контент был заменён английским на момент 21 февраля 2015.}}<br />
Этот документ описывает bootstrapping process, нужный для того, чтобы установить Arch Linux из уже работающего хоста Linux.<br />
После bootstrapping, установка продолжается так, как описано в [[Installation guide]].<br />
<br />
Установка Arch Linux из-под другого Linux полезна для:<br />
* беспроводной установки Arch Linux, например для виртуального сервера<br />
* замены существующего Linux без LiveCD (смотрите [[#Replacing the Existing System without a LiveCD]])<br />
* создания нового дистрибутива Linux или LiveCD основанного на Arch Linux<br />
* создания chroot окружения Arch Linux, например для (Docker base container?)<br />
* [[Diskless_network_boot_NFS_root|rootfs-over-NFS для бездисковых систем]]<br />
<br />
Цель процедуры начальной загрузки в том, чтобы настроить окружение из которого {{Pkg|arch-install-scripts}} (такие как {{ic|pacstrap}} и {{ic|arch-root}}) запускаются.<br />
Цель достигается установкой {{Pkg|arch-install-scripts}} изначально на хост-систему или настройкой chroot основанного на Arch Linux.<br />
<br />
Если хост работает под Arch Linux, сразу установите {{Pkg|arch-install-scripts}}.<br />
<br />
{{Note (Русский)|Этот гайд расчитан на то, что имеющийся хост может запускать программы архитектуры нового Arch Linux. В случае с x86_64 хостом, можно даже использовать i686-pacman при сборке 32-битного окружения chroot. Смотрите [[Arch64 Install bundled 32bit system | Arch64 - установка встроенной 32-битной системы]].}} <br />
<br />
==Arch Linux-based chroot==<br />
Идея состоит в том, чтобы запустить Arch Linux внутри уже имеющейся системы.<br />
Настоящая установка будет затем запущена из этой Arch системы.<br />
This nested system is contained inside a chroot.<br />
Есть два способа настроить и войти в chroot, они представлены ниже.<br />
<br />
{{Note (Русский)|Хост-система должна использовать Linux 2.6.32 или новее.}}<br />
{{Note (Русский)|Используйте только один из двух способов, и не забудьте дочитать эту статью до конца, чтобы закончить установку.}}<br />
<br />
===Создаём chroot===<br />
<br />
====Способ 1: Использование Bootstrap образа (рекомендуется)====<br />
<br />
Скачиваем образ bootstrap с [https://www.archlinux.org/download любого желаемого зеркала], либо сразу используя прямую ссылку на нужный вам образ (с зеркала kernel.org):<br />
<br>Образ x86_64:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-x86_64.tar.gz<br />
Образ i686:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-i686.tar.gz<br />
<br />
Распаковываем его:<br />
# cd /tmp<br />
# tar xzf <путь-к-каталогу-где-образ>/archlinux-bootstrap-2015.02.01-*.tar.gz<br />
Выбираем подходящий для вашего интернета сервер, откуда будут загружаться основные репозитории:<br />
# nano /tmp/root.*/etc/pacman.d/mirrorlist<br />
<br />
{{Note (Русский)|Если ваша хост-система — x86_64, а образ boostrap — i686, то также подправьте {{Ic|/tmp/root.i686/etc/pacman.conf}}, ясно указав {{Ic|1=Architecture = i686}}, чтобы pacman качал пакеты под архитектуру i686.}}<br />
<br />
Войдём в chroot<br />
* Если установлен bash 4 или новее, то:<br />
# /tmp/root.*/bin/arch-chroot /tmp/root.*/<br />
* Иначе:<br />
# cd /tmp/root.*<br />
# cp /etc/resolv.conf etc<br />
# mount --rbind /proc proc<br />
# mount --rbind /sys sys<br />
# mount --rbind /dev dev<br />
# mount --rbind /run run<br />
(при условии, что /run существует)<br />
# chroot /tmp/root.* /bin/bash<br />
<br />
====Способ 2: Используя образ LiveCD====<br />
<br />
Можно смонтировать корневой образ последнего установочного диска Arch Linux и затем заchroot'ить туда. Плюс этого способа в том, что у вас будет сразу рабочий Arch Linux installation прямо внутри хост-системы без надобности в его настройки.<br />
<br />
{{Note (Русский)|Перед тем как продолжить, удостоверьтесь, что у вас последняя версия [http://squashfs.sourceforge.net/ squashfs] на хост-системе. Иначе будут ошибки типа: {{ic|FATAL ERROR aborting: uncompress_inode_table: failed to read block}}.}}<br />
<br />
* Корневой образ можно скачать с одного из [https://www.archlinux.org/download зеркал] в папке arch/x86_64/ либо arch/i686/, смотря какую архитектуру хотите. Образ имеет формат squashfs, который является read-only, поэтому нам надо распаковать его и смонтировать корневой образ (root-image.fs).<br />
<br />
*Чтобы распаковать корневой образ, надо<br />
{{bc|# unsquashfs -d /squashfs-root root-image.fs.sfs}}<br />
<br />
* Теперь смонтируем его с помощью опции loop<br />
{{bc|<br />
# mkdir /arch<br />
# mount -o loop /squashfs-root/root-image.fs /arch<br />
}}<br />
<br />
* Перед тем как [[Change root|chrooting]] to it, нужно смонтировать некоторые виртуальные системные разделы, а затем скопировать resolv.conf для интернета.<br />
{{bc|<br />
# mount -t proc none /arch/proc<br />
# mount -t sysfs none /arch/sys<br />
# mount -o bind /dev /arch/dev<br />
# mount -o bind /dev/pts /arch/dev/pts # важно для pacman (для проверки подписей)<br />
# cp -L /etc/resolv.conf /arch/etc # а это, чтобы мог работать интернет в chroot<br />
}}<br />
<br />
* Теперь всё готово, чтобы to chroot в только что установленное окружение Arch<br />
{{bc|# chroot /arch bash}}<br />
<br />
===Используем наше chroot окружение===<br />
<br />
====Начальная настройка хранилища ключей pacman====<br />
Перед установкой, ключи pacman должны быть настроены. Перед тем как вводить следующие две команды, можете почитать [[pacman-key#Initializing the keyring]], чтобы узнать entropy requirements:<br />
{{bc|<br />
# pacman-key --init<br />
# pacman-key --populate archlinux<br />
}}<br />
<br />
====Установка====<br />
Следуйте [[Installation guide#Mount the partitions]] и [[Installation guide#Install the base packages]].<br />
<br />
=====Хост на базе Debian=====<br />
На хостах на базе Debian, {{ic|pacstrap}} выводит следующую ошибку:<br />
# pacstrap /mnt base<br />
# ==> Creating install root at /mnt<br />
# mount: mount point /mnt/dev/shm is a symbolic link to nowhere<br />
# ==> ERROR: failed to setup API filesystems in new root<br />
<br />
Это потому что в Debian /dev/shm ссылается на /run/shm, а в Arch-based chroot /run/shm не существует, поэтому ссылка не рабочая. Чтобы исправить это, просто создайте каталог /run/shm:<br />
# mkdir /run/shm<br />
<br />
=====Хост на базе Fedora=====<br />
На хостах на базе Fedora и в Live USB, если у вас не получается сгенерировать ваш {{ic|[[fstab (Русский)|fstab]]}} с помощью {{ic|genfstab}}, то удалите из fstab одинаковые записи и везде опции {{ic|seclabel}} (это опция специфична для Fedora и поэтому не даст вам загрузиться).<br />
<br />
====Настройка системы====<br />
<br />
С этого момента просто следуйте согласно разделам начиная с «[[Installation_guide_(Русский)#Монтирование разделов|Монтирование разделов]]» из [[Installation guide|руководства по установке Arch Linux]].<br />
<br />
==Замена уже существующей системы без LiveCD==<br />
Освободите ~650МБ, например, переформатировав существующий swap-раздел (после окончания установки, можете обратно создать swap). Если не можете столько освободить, выясните точно, какие пакеты группы base вам понадобятся для того, чтобы get a system с работающим интернетом and running in the temporary partition. То есть надо будет ясно указать каждый пакет для pacstrap. И ещё надо указать -c, чтобы пакеты скачивались на хост-систему, дабы избежать недостатка свободного места.<br />
<br />
После того как установили, перезагрузитесь в свою новую систему, затем [[Full system backup with rsync#With_a_single_command|rsync the entire system]] to the primary partition.<br />
Fix the bootloader configuration before rebooting.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_from_existing_Linux_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370858Install Arch Linux from existing Linux (Русский)2015-04-23T18:48:18Z<p>Arzeth: /* Способ 1: Использование Bootstrap образа (рекомендуется) */ подправил так, чтобы пользователи i686 тоже могли воспользоваться.</p>
<hr />
<div>[[Category:Getting and installing Arch (Русский)]]<br />
[[Category:Русский]]<br />
{{Related articles start (Русский)}}<br />
{{Related|Install from SSH (Русский)}}<br />
{{Related articles end}}<br />
[[en:Install from existing Linux]]<br />
[[es:Install from Existing Linux]]<br />
[[fr:Install chroot]]<br />
[[it:Install from Existing Linux]]<br />
[[ja:Install from Existing Linux]]<br />
[[pt:Install from Existing Linux]]<br />
[[uk:Install from Existing Linux]]<br />
[[zh-CN:Install from existing Linux]]<br />
[[zh-TW:Install from Existing Linux]]<br />
{{Unmaintained (Русский)}}<br />
{{Translateme (Русский)|Устаревший контент был заменён английским на момент 21 февраля 2015.}}<br />
Этот документ описывает bootstrapping process, нужный для того, чтобы установить Arch Linux из уже работающего хоста Linux.<br />
После bootstrapping, установка продолжается так, как описано в [[Installation guide]].<br />
<br />
Установка Arch Linux из-под другого Linux полезна для:<br />
* беспроводной установки Arch Linux, например для виртуального сервера<br />
* замены существующего Linux без LiveCD (смотрите [[#Replacing the Existing System without a LiveCD]])<br />
* создания нового дистрибутива Linux или LiveCD основанного на Arch Linux<br />
* создания chroot окружения Arch Linux, например для (Docker base container?)<br />
* [[Diskless_network_boot_NFS_root|rootfs-over-NFS для бездисковых систем]]<br />
<br />
Цель процедуры начальной загрузки в том, чтобы настроить окружение из которого {{Pkg|arch-install-scripts}} (такие как {{ic|pacstrap}} и {{ic|arch-root}}) запускаются.<br />
Цель достигается установкой {{Pkg|arch-install-scripts}} изначально на хост-систему или настройкой chroot основанного на Arch Linux.<br />
<br />
Если хост работает под Arch Linux, сразу установите {{Pkg|arch-install-scripts}}.<br />
<br />
{{Note (Русский)|Этот гайд расчитан на то, что имеющийся хост может запускать программы архитектуры нового Arch Linux. В случае с x86_64 хостом, можно даже использовать i686-pacman при сборке 32-битного окружения chroot. Смотрите [[Arch64 Install bundled 32bit system | Arch64 - установка встроенной 32-битной системы]].}} <br />
<br />
==Arch Linux-based chroot==<br />
Идея состоит в том, чтобы запустить Arch Linux внутри уже имеющейся системы.<br />
Настоящая установка будет затем запущена из этой Arch системы.<br />
This nested system is contained inside a chroot.<br />
Есть два способа настроить и войти в chroot, они представлены ниже.<br />
<br />
{{Note (Русский)|Хост-система должна использовать Linux 2.6.32 или новее.}}<br />
{{Note (Русский)|Используйте только один из двух способов, и не забудьте дочитать эту статью до конца, чтобы закончить установку.}}<br />
<br />
===Создаём chroot===<br />
<br />
====Способ 1: Использование Bootstrap образа (рекомендуется)====<br />
<br />
Скачиваем образ bootstrap с [https://www.archlinux.org/download любого желаемого зеркала], либо сразу используя прямую ссылку на нужный вам образ (с зеркала kernel.org):<br />
<br>Образ x86_64:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-x86_64.tar.gz<br />
Образ i686:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.04.01/archlinux-bootstrap-2015.04.01-i686.tar.gz<br />
<br />
Распаковываем его:<br />
# cd /tmp<br />
# tar xzf <путь-к-каталогу-где-образ>/archlinux-bootstrap-2015.02.01-*.tar.gz<br />
Выбираем подходящий для вашего интернета сервер, откуда будут загружаться основные репозитории:<br />
# nano /tmp/root.*/etc/pacman.d/mirrorlist<br />
<br />
{{Note (Русский)|Если ваша хост-система — x86_64, а образ boostrap — i686, то также подправьте {{Ic|/tmp/root.i686/etc/pacman.conf}}, ясно указав {{Ic|1=Architecture = i686}}, чтобы pacman качал пакеты под архитектуру i686.}}<br />
<br />
Войдём в chroot<br />
* Если установлен bash 4 или новее, то:<br />
# /tmp/root.*/bin/arch-chroot /tmp/root.*/<br />
* Иначе:<br />
# cd /tmp/root.*<br />
# cp /etc/resolv.conf etc<br />
# mount --rbind /proc proc<br />
# mount --rbind /sys sys<br />
# mount --rbind /dev dev<br />
# mount --rbind /run run<br />
(при условии, что /run существует)<br />
# chroot /tmp/root.* /bin/bash<br />
<br />
====Способ 2: Используя образ LiveCD====<br />
<br />
Можно смонтировать корневой образ последнего установочного диска Arch Linux и затем заchroot'ить туда. Плюс этого способа в том, что у вас будет сразу рабочий Arch Linux installation прямо внутри хост-системы без надобности в его настройки.<br />
<br />
{{Note (Русский)|Перед тем как продолжить, удостоверьтесь, что у вас последняя версия [http://squashfs.sourceforge.net/ squashfs] на хост-системе. Иначе будут ошибки типа: {{ic|FATAL ERROR aborting: uncompress_inode_table: failed to read block}}.}}<br />
<br />
* Корневой образ можно скачать с одного из [https://www.archlinux.org/download зеркал] в папке arch/x86_64/ либо arch/i686/, смотря какую архитектуру хотите. Образ имеет формат squashfs, который является read-only, поэтому нам надо unsquash корневой образ и смонтировать его.<br />
<br />
*Чтобы unsquash корневой образ, надо<br />
{{bc|# unsquashfs -d /squashfs-root root-image.fs.sfs}}<br />
<br />
* Теперь смонтируем корневой образ с помощью опции loop<br />
{{bc|<br />
# mkdir /arch<br />
# mount -o loop /squashfs-root/root-image.fs /arch<br />
}}<br />
<br />
* Перед тем как [[Change root|chrooting]] to it, нужно смонтировать некоторые виртуальные системные разделы, а затем скопировать resolv.conf для интернета.<br />
{{bc|<br />
# mount -t proc none /arch/proc<br />
# mount -t sysfs none /arch/sys<br />
# mount -o bind /dev /arch/dev<br />
# mount -o bind /dev/pts /arch/dev/pts # important for pacman (for signature check)<br />
# cp -L /etc/resolv.conf /arch/etc #this is needed to use networking within the chroot<br />
}}<br />
<br />
* Теперь всё готово, чтобы to chroot в только что установленное окружение Arch<br />
{{bc|# chroot /arch bash}}<br />
<br />
===Используем наше chroot окружение===<br />
<br />
====Начальная настройка хранилища ключей pacman====<br />
Перед установкой, ключи pacman должны быть настроены. Перед тем как вводить следующие две команды, можете почитать [[pacman-key#Initializing the keyring]], чтобы узнать entropy requirements:<br />
{{bc|<br />
# pacman-key --init<br />
# pacman-key --populate archlinux<br />
}}<br />
<br />
====Установка====<br />
Следуйте [[Installation guide#Mount the partitions]] и [[Installation guide#Install the base packages]].<br />
<br />
=====Хост на базе Debian=====<br />
На хостах на базе Debian, {{ic|pacstrap}} выводит следующую ошибку:<br />
# pacstrap /mnt base<br />
# ==> Creating install root at /mnt<br />
# mount: mount point /mnt/dev/shm is a symbolic link to nowhere<br />
# ==> ERROR: failed to setup API filesystems in new root<br />
<br />
Это потому что в Debian /dev/shm ссылается на /run/shm, а в Arch-based chroot /run/shm не существует, поэтому ссылка не рабочая. Чтобы исправить это, просто создайте каталог /run/shm:<br />
# mkdir /run/shm<br />
<br />
=====Хост на базе Fedora=====<br />
На хостах на базе Fedora и в Live USB, если у вас не получается сгенерировать ваш {{ic|[[fstab (Русский)|fstab]]}} с помощью {{ic|genfstab}}, то удалите из fstab одинаковые записи и везде опции {{ic|seclabel}} (это опция специфична для Fedora и поэтому не даст вам загрузиться).<br />
<br />
====Настройка системы====<br />
<br />
С этого момента просто следуйте согласно разделам начиная с «[[Installation_guide_(Русский)#Монтирование разделов|Монтирование разделов]]» из [[Installation guide|руководства по установке Arch Linux]].<br />
<br />
==Замена уже существующей системы без LiveCD==<br />
Освободите ~650МБ, например, переформатировав существующий swap-раздел (после окончания установки, можете обратно создать swap). Если не можете столько освободить, выясните точно, какие пакеты группы base вам понадобятся для того, чтобы get a system с работающим интернетом and running in the temporary partition. То есть надо будет ясно указать каждый пакет для pacstrap. И ещё надо указать -c, чтобы пакеты скачивались на хост-систему, дабы избежать недостатка свободного места.<br />
<br />
После того как установили, перезагрузитесь в свою новую систему, затем [[Full system backup with rsync#With_a_single_command|rsync the entire system]] to the primary partition.<br />
Fix the bootloader configuration before rebooting.</div>Arzethhttps://wiki.archlinux.org/index.php?title=Install_Arch_Linux_from_existing_Linux_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370761Install Arch Linux from existing Linux (Русский)2015-04-23T10:42:05Z<p>Arzeth: Перевёл частично. Потом допереведу. Фиг знает как обращаться со словом chroot. И не знаю как перевести unsquash и bootstrap.</p>
<hr />
<div>[[Category:Getting and installing Arch (Русский)]]<br />
[[Category:Русский]]<br />
{{Related articles start (Русский)}}<br />
{{Related|Install from SSH (Русский)}}<br />
{{Related articles end}}<br />
[[en:Install from existing Linux]]<br />
[[es:Install from Existing Linux]]<br />
[[fr:Install chroot]]<br />
[[it:Install from Existing Linux]]<br />
[[ja:Install from Existing Linux]]<br />
[[pt:Install from Existing Linux]]<br />
[[uk:Install from Existing Linux]]<br />
[[zh-CN:Install from existing Linux]]<br />
[[zh-TW:Install from Existing Linux]]<br />
{{Unmaintained (Русский)}}<br />
{{Translateme (Русский)|Устаревший контент был заменён английским на момент 21 февраля 2015.}}<br />
Этот документ описывает bootstrapping process, нужный для того, чтобы установить Arch Linux из уже работающего хоста Linux.<br />
После bootstrapping, установка продолжается так, как описано в [[Installation guide]].<br />
<br />
Установка Arch Linux из-под другого Linux полезна для:<br />
* беспроводной установки Arch Linux, например для виртуального сервера<br />
* замены существующего Linux без LiveCD (смотрите [[#Replacing the Existing System without a LiveCD]])<br />
* создания нового дистрибутива Linux или LiveCD основанного на Arch Linux<br />
* создания chroot окружения Arch Linux, например для (Docker base container?)<br />
* [[Diskless_network_boot_NFS_root|rootfs-over-NFS для бездисковых систем]]<br />
<br />
Цель процедуры начальной загрузки в том, чтобы настроить окружение из которого {{Pkg|arch-install-scripts}} (такие как {{ic|pacstrap}} и {{ic|arch-root}}) запускаются.<br />
Цель достигается установкой {{Pkg|arch-install-scripts}} изначально на хост-систему или настройкой chroot основанного на Arch Linux.<br />
<br />
Если хост работает под Arch Linux, сразу установите {{Pkg|arch-install-scripts}}.<br />
<br />
{{Note (Русский)|Этот гайд расчитан на то, что имеющийся хост может запускать программы архитектуры нового Arch Linux. В случае с x86_64 хостом, можно даже использовать i686-pacman при сборке 32-битного окружения chroot. Смотрите [[Arch64 Install bundled 32bit system | Arch64 - установка встроенной 32-битной системы]].}} <br />
<br />
==Arch Linux-based chroot==<br />
Идея состоит в том, чтобы запустить Arch Linux внутри уже имеющейся системы.<br />
Настоящая установка будет затем запущена из этой Arch системы.<br />
This nested system is contained inside a chroot.<br />
Есть два способа настроить и войти в chroot, они представлены ниже.<br />
<br />
{{Note (Русский)|Хост-система должна использовать Linux 2.6.32 или новее.}}<br />
{{Note (Русский)|Используйте только один из двух способов, и не забудьте дочитать эту статью до конца, чтобы закончить установку.}}<br />
<br />
===Создаём chroot===<br />
<br />
====Способ 1: Использование Bootstrap образа (рекомендуется)====<br />
<br />
Скачиваем bootstrap образ с [https://www.archlinux.org/download mirror]:<br />
$ curl -O https://mirrors.kernel.org/archlinux/iso/2015.02.01/archlinux-bootstrap-2015.02.01-x86_64.tar.gz<br />
Распаковываем его:<br />
# cd /tmp<br />
# tar xzf <path-to-bootstrap-image>/archlinux-bootstrap-2015.02.01-x86_64.tar.gz<br />
Выбираем нужный сервер с репозиториием:<br />
# nano /tmp/root.x86_64/etc/pacman.d/mirrorlist<br />
<br />
{{Note (Русский)|If bootstrapping an i686 image from an x86_64 host system, то также подправьте {{Ic|/tmp/root.i686/etc/pacman.conf}} ясно указав {{Ic|1=Architecture = i686}}, чтобы pacman мог to pull the proper i686 packages.}}<br />
<br />
Войдём в chroot<br />
* Если установлен bash 4 или новее, то:<br />
# /tmp/root.x86_64/bin/arch-chroot /tmp/root.x86_64/<br />
* Иначе:<br />
# cd /tmp/root.x86_64<br />
# cp /etc/resolv.conf etc<br />
# mount --rbind /proc proc<br />
# mount --rbind /sys sys<br />
# mount --rbind /dev dev<br />
# mount --rbind /run run<br />
(при условии, что /run существует)<br />
# chroot /tmp/root.x86_64 /bin/bash<br />
<br />
====Способ 2: Используя образ LiveCD====<br />
<br />
Можно смонтировать корневой образ последнего установочного диска Arch Linux и затем заchroot'ить туда. Плюс этого способа в том, что у вас будет сразу рабочий Arch Linux installation прямо внутри хост-системы без надобности в его настройки.<br />
<br />
{{Note (Русский)|Перед тем как продолжить, удостоверьтесь, что у вас последняя версия [http://squashfs.sourceforge.net/ squashfs] на хост-системе. Иначе будут ошибки типа: {{ic|FATAL ERROR aborting: uncompress_inode_table: failed to read block}}.}}<br />
<br />
* Корневой образ можно скачать с одного из [https://www.archlinux.org/download зеркал] в папке arch/x86_64/ либо arch/i686/, смотря какую архитектуру хотите. Образ имеет формат squashfs, который является read-only, поэтому нам надо unsquash корневой образ и смонтировать его.<br />
<br />
*Чтобы unsquash корневой образ, надо<br />
{{bc|# unsquashfs -d /squashfs-root root-image.fs.sfs}}<br />
<br />
* Теперь смонтируем корневой образ с помощью опции loop<br />
{{bc|<br />
# mkdir /arch<br />
# mount -o loop /squashfs-root/root-image.fs /arch<br />
}}<br />
<br />
* Перед тем как [[Change root|chrooting]] to it, нужно смонтировать некоторые виртуальные системные разделы, а затем скопировать resolv.conf для интернета.<br />
{{bc|<br />
# mount -t proc none /arch/proc<br />
# mount -t sysfs none /arch/sys<br />
# mount -o bind /dev /arch/dev<br />
# mount -o bind /dev/pts /arch/dev/pts # important for pacman (for signature check)<br />
# cp -L /etc/resolv.conf /arch/etc #this is needed to use networking within the chroot<br />
}}<br />
<br />
* Теперь всё готово, чтобы to chroot в только что установленное окружение Arch<br />
{{bc|# chroot /arch bash}}<br />
<br />
===Используем наше chroot окружение===<br />
<br />
====Начальная настройка хранилища ключей pacman====<br />
Перед установкой, ключи pacman должны быть настроены. Перед тем как вводить следующие две команды, можете почитать [[pacman-key#Initializing the keyring]], чтобы узнать entropy requirements:<br />
{{bc|<br />
# pacman-key --init<br />
# pacman-key --populate archlinux<br />
}}<br />
<br />
====Установка====<br />
Следуйте [[Installation guide#Mount the partitions]] и [[Installation guide#Install the base packages]].<br />
<br />
=====Хост на базе Debian=====<br />
На хостах на базе Debian, {{ic|pacstrap}} выводит следующую ошибку:<br />
# pacstrap /mnt base<br />
# ==> Creating install root at /mnt<br />
# mount: mount point /mnt/dev/shm is a symbolic link to nowhere<br />
# ==> ERROR: failed to setup API filesystems in new root<br />
<br />
Это потому что в Debian /dev/shm ссылается на /run/shm, а в Arch-based chroot /run/shm не существует, поэтому ссылка не рабочая. Чтобы исправить это, просто создайте каталог /run/shm:<br />
# mkdir /run/shm<br />
<br />
=====Хост на базе Fedora=====<br />
На хостах на базе Fedora и в Live USB, если у вас не получается сгенерировать ваш {{ic|[[fstab (Русский)|fstab]]}} с помощью {{ic|genfstab}}, то удалите из fstab одинаковые записи и везде опции {{ic|seclabel}} (это опция специфична для Fedora и поэтому не даст вам загрузиться).<br />
<br />
====Настройка системы====<br />
<br />
С этого момента просто следуйте согласно разделам начиная с «[[Installation_guide_(Русский)#Монтирование разделов|Монтирование разделов]]» из [[Installation guide|руководства по установке Arch Linux]].<br />
<br />
==Замена уже существующей системы без LiveCD==<br />
Освободите ~650МБ, например, переформатировав существующий swap-раздел (после окончания установки, можете обратно создать swap). Если не можете столько освободить, выясните точно, какие пакеты группы base вам понадобятся для того, чтобы get a system с работающим интернетом and running in the temporary partition. То есть надо будет ясно указать каждый пакет для pacstrap. И ещё надо указать -c, чтобы пакеты скачивались на хост-систему, дабы избежать недостатка свободного места.<br />
<br />
После того как установили, перезагрузитесь в свою новую систему, затем [[Full system backup with rsync#With_a_single_command|rsync the entire system]] to the primary partition.<br />
Fix the bootloader configuration before rebooting.</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370605PostgreSQL (Русский)2015-04-22T09:41:43Z<p>Arzeth: /* Ускорение мелких транзакций */ менее английско звучит так.</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ sudo su - postgres<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под любым пользователем управлять БД:<br />
$ psql имя_базы -U имя_пользователя_бд<br />
*Если имя базы данных '''И''' имя пользователя БД совпадают с текущим именем пользователя ($USER), то можно просто:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''— Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
* Список всех возможных команд (например, {{ic|CREATE TABLE}}) для запросов<br />
=> \h<br />
* Подробное описание команды<br />
=> \h CREATE_TABLE<br />
*Подключаем опредлённую базу данных<br />
=> \c <database><br />
*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
*Меняем пароль<br />
=> \password<br />
*Показать все используемые настройки<br />
=> SHOW ALL;<br />
*Выйти из psql<br />
=> \q или CTRL+d<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
{{Note (Русский)|По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.}}<br />
Из-под пользователя root редактируем файл<pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
В разделе connections and authentications раскомментируйте или исправьте строку <code>listen_addresses</code> по вашему желанию на<br />
listen_addresses = '*'<br />
либо<br />
listen_addresses = 'localhost,ip_у_сервера_в_сети'<br />
и внимательно просмотрите другие строки.<br />
<br>Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br />
# IPv4 local connections:<br />
host all all your_desired_ip_address/32 trust<br />
где <code>your_desired_ip_address</code> — IP-адрес клиента.<br />
После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
{{Note (Русский)|PostgreSQL по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения.}}<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и он медленный, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370604PostgreSQL (Русский)2015-04-22T09:37:02Z<p>Arzeth: /* Доступ к оболочке базы данных */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ sudo su - postgres<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под любым пользователем управлять БД:<br />
$ psql имя_базы -U имя_пользователя_бд<br />
*Если имя базы данных '''И''' имя пользователя БД совпадают с текущим именем пользователя ($USER), то можно просто:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''— Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
* Список всех возможных команд (например, {{ic|CREATE TABLE}}) для запросов<br />
=> \h<br />
* Подробное описание команды<br />
=> \h CREATE_TABLE<br />
*Подключаем опредлённую базу данных<br />
=> \c <database><br />
*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
*Меняем пароль<br />
=> \password<br />
*Показать все используемые настройки<br />
=> SHOW ALL;<br />
*Выйти из psql<br />
=> \q или CTRL+d<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
{{Note (Русский)|По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.}}<br />
Из-под пользователя root редактируем файл<pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
В разделе connections and authentications раскомментируйте или исправьте строку <code>listen_addresses</code> по вашему желанию на<br />
listen_addresses = '*'<br />
либо<br />
listen_addresses = 'localhost,ip_у_сервера_в_сети'<br />
и внимательно просмотрите другие строки.<br />
<br>Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br />
# IPv4 local connections:<br />
host all all your_desired_ip_address/32 trust<br />
где <code>your_desired_ip_address</code> — IP-адрес клиента.<br />
После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
{{Note (Русский)|PostgreSQL по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения.}}<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370602PostgreSQL (Русский)2015-04-22T09:21:34Z<p>Arzeth: /* Доступ к оболочке базы данных */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ sudo su - postgres<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под любым пользователем управлять БД:<br />
$ psql имя_базы -U имя_пользователя_бд<br />
*Если имя базы данных '''И''' имя пользователя БД совпадают с текущим именем пользователя ($USER), то можно просто:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''— Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
* Список всех возможных команд (например, CREATE TABLE) для запросов<br />
=> \h<br />
* Подробное описание команды<br />
=> \h CREATE_TABLE<br />
*Подключаем опредлённую базу данных<br />
=> \c <database><br />
*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
*Меняем пароль<br />
=> \password<br />
*Показать все используемые настройки<br />
=> SHOW ALL;<br />
*Выйти из psql<br />
=> \q или CTRL+d<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
{{Note (Русский)|По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.}}<br />
Из-под пользователя root редактируем файл<pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
В разделе connections and authentications раскомментируйте или исправьте строку <code>listen_addresses</code> по вашему желанию на<br />
listen_addresses = '*'<br />
либо<br />
listen_addresses = 'localhost,ip_у_сервера_в_сети'<br />
и внимательно просмотрите другие строки.<br />
<br>Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br />
# IPv4 local connections:<br />
host all all your_desired_ip_address/32 trust<br />
где <code>your_desired_ip_address</code> — IP-адрес клиента.<br />
После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
{{Note (Русский)|PostgreSQL по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения.}}<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370597PostgreSQL (Русский)2015-04-22T09:10:25Z<p>Arzeth: /* Создание Вашей первой базы данных */ опечатка моя</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ sudo su - postgres<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под любым пользователем управлять БД:<br />
$ psql имя_базы -U имя_пользователя_бд<br />
*Если имя базы данных '''И''' имя пользователя БД совпадают с текущим именем пользователя ($USER), то можно просто:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
{{Note (Русский)|По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.}}<br />
Из-под пользователя root редактируем файл<pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
В разделе connections and authentications раскомментируйте или исправьте строку <code>listen_addresses</code> по вашему желанию на<br />
listen_addresses = '*'<br />
либо<br />
listen_addresses = 'localhost,ip_у_сервера_в_сети'<br />
и внимательно просмотрите другие строки.<br />
<br>Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br />
# IPv4 local connections:<br />
host all all your_desired_ip_address/32 trust<br />
где <code>your_desired_ip_address</code> — IP-адрес клиента.<br />
После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
{{Note (Русский)|PostgreSQL по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения.}}<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370596PostgreSQL (Русский)2015-04-22T09:09:43Z<p>Arzeth: /* Настройка удалённого доступа к PostgreSQL */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ sudo su - postgres<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под любым пользователем управлять БД:<br />
$ psql имя_базы -U имя_пользователя_бд<br />
*Если имя базы данных '''И''' имя пользователя БД совпадают с текущий именем пользователя ($USER), то можно просто:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
{{Note (Русский)|По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.}}<br />
Из-под пользователя root редактируем файл<pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
В разделе connections and authentications раскомментируйте или исправьте строку <code>listen_addresses</code> по вашему желанию на<br />
listen_addresses = '*'<br />
либо<br />
listen_addresses = 'localhost,ip_у_сервера_в_сети'<br />
и внимательно просмотрите другие строки.<br />
<br>Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br />
# IPv4 local connections:<br />
host all all your_desired_ip_address/32 trust<br />
где <code>your_desired_ip_address</code> — IP-адрес клиента.<br />
После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
{{Note (Русский)|PostgreSQL по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения.}}<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370595PostgreSQL (Русский)2015-04-22T09:08:16Z<p>Arzeth: /* Настройка удалённого доступа к PostgreSQL */ сделал стиль для замечаний. Убрал из строчек конфига <br></p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ sudo su - postgres<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под любым пользователем управлять БД:<br />
$ psql имя_базы -U имя_пользователя_бд<br />
*Если имя базы данных '''И''' имя пользователя БД совпадают с текущий именем пользователя ($USER), то можно просто:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
{{Note (Русский)|По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.}}<br />
Из-под пользователя root редактируем файл<pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
В разделе connections and authentications раскомментируйте или исправьте строку <code>listen_addresses</code> по вашему желанию<pre>listen_addresses = '*'</pre>либо<pre>listen_addresses = 'localhost,ip_у_сервера_в_сети'</pre>и внимательно просмотрите другие строки.<br />
Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br />
# IPv4 local connections:<br />
host all all your_desired_ip_address/32 trust<br />
где <code>your_desired_ip_address</code> IP-адрес клиента.<br />
После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
{{Note (Русский)|PostgreSQL по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения.}}<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370592PostgreSQL (Русский)2015-04-22T08:44:24Z<p>Arzeth: /* Создание Вашей первой базы данных */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ sudo su - postgres<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под любым пользователем управлять БД:<br />
$ psql имя_базы -U имя_пользователя_бд<br />
*Если имя базы данных '''И''' имя пользователя БД совпадают с текущий именем пользователя ($USER), то можно просто:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370591PostgreSQL (Русский)2015-04-22T08:35:28Z<p>Arzeth: /* Установка PostgreSQL */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что в данном примере используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ su -c "su - postgres"<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под своим пользователем управлять БД:<br />
$ psql -U имя_пользователя_бд -d имя_базы<br />
*Если имя базы данных или имя пользователя БД совпадают с именем пользователя ($USER), то соответствующие параметры можно опустить:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370590PostgreSQL (Русский)2015-04-22T08:33:32Z<p>Arzeth: /* Настройка PostgreSQL для работы с PHP */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что тут используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ su -c "su - postgres"<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под своим пользователем управлять БД:<br />
$ psql -U имя_пользователя_бд -d имя_базы<br />
*Если имя базы данных или имя пользователя БД совпадают с именем пользователя ($USER), то соответствующие параметры можно опустить:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code>, и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370589PostgreSQL (Русский)2015-04-22T08:29:35Z<p>Arzeth: /* Создание Вашей первой базы данных */ su root === su</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что тут используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ su -c "su - postgres"<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под своим пользователем управлять БД:<br />
$ psql -U имя_пользователя_бд -d имя_базы<br />
*Если имя базы данных или имя пользователя БД совпадают с именем пользователя ($USER), то соответствующие параметры можно опустить:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code> и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370588PostgreSQL (Русский)2015-04-22T08:26:21Z<p>Arzeth: /* Установка PostgreSQL */ а то я вот не обратил внимания</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе). Обратите внимание, что тут используем {{ic|ru_RU.UTF-8}}<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ su root -c "su - postgres"<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под своим пользователем управлять БД:<br />
$ psql -U имя_пользователя_бд -d имя_базы<br />
*Если имя базы данных или имя пользователя БД совпадают с именем пользователя ($USER), то соответствующие параметры можно опустить:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code> и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370586PostgreSQL (Русский)2015-04-22T08:22:15Z<p>Arzeth: /* Создание Вашей первой базы данных */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе)<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ su root -c "su - postgres"<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под своим пользователем управлять БД:<br />
$ psql -U имя_пользователя_бд -d имя_базы<br />
*Если имя базы данных или имя пользователя БД совпадают с именем пользователя ($USER), то соответствующие параметры можно опустить:<br />
$ psql<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code> и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370585PostgreSQL (Русский)2015-04-22T08:16:03Z<p>Arzeth: /* Создание Вашей первой базы данных */ ой</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе)<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ su root -c "su - postgres"<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под своим пользователем управлять БД:<br />
$ psql -d имя_базы<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code> и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370584PostgreSQL (Русский)2015-04-22T08:15:16Z<p>Arzeth: /* Создание Вашей первой базы данных */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе)<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ su root -c "su - postgres"<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (то есть просто <code>$ psql</code>, что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под своим пользователем управлять БД:<br />
$ psql -d имя_базы<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code> и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370583PostgreSQL (Русский)2015-04-22T08:14:24Z<p>Arzeth: /* Создание Вашей первой базы данных */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе)<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres (пользователь postgres не имеет пароля по умолчанию, поэтому таким вот образом)<br />
$ su root -c "su - postgres"<br />
*Добавляем нового пользователя базы данных<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду <code>createuser</code> без параметров. Вывод в терминале выглядит так:<br />
<br />
$ createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER), вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (то есть просто <code>$ psql</code>, что весьма удобно).<br />
<br />
*Создайте новую базу данных от пользователя, имеющего разрешение на чтение и запись (read/write). Если кодировку не указать, то она будет той, что вы указали в разделе [[PostgreSQL (Русский)#Установка PostgreSQL|«Установка PostgreSQL»]].<br />
$ [http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана. Теперь можете уже под своим пользователем управлять БД, для этого введите:<br />
$ psql -d имя_базы<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code> и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370581PostgreSQL (Русский)2015-04-22T07:56:03Z<p>Arzeth: /* Создание Вашей первой базы данных */ $USER — это переменная</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе)<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres<br />
su root<br />
su - postgres<br />
*Добавляем нового пользователя базы данных<br />
[http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду createuser без параметров. Вывод в терминале выглядит так:<br />
<br />
# createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($USER) вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу даных от пользователя, имеющего разрешение на чтение и запись (read/write).<br />
[http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана.<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code> и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzethhttps://wiki.archlinux.org/index.php?title=PostgreSQL_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=370580PostgreSQL (Русский)2015-04-22T07:51:37Z<p>Arzeth: /* Настройка PostgreSQL для работы с PHP */</p>
<hr />
<div>[[Category:Русский]]<br />
[[Category:Database management systems (Русский)]]<br />
[[en:PostgreSQL]]<br />
[[it:PostgreSQL]]<br />
[[ja:PostgreSQL]]<br />
[[zh-CN:PostgreSQL]]<br />
{{Unmaintained (Русский)}}<br />
{{translateme (Русский)}}<br />
{{Out of date (Русский)|rc.d references. Needs update, see [[Systemd (Русский)]].}}<br />
Эта статья описывает как настроить PostgreSQL и интегрировать ее с [[PHP]] и [[Apache]]. Она также описывает, как сделать PostgreSQL доступным из клиента удалённого доступа. Считаем, что [[PHP]] и [[Apache]] уже установлены. Если вам нужна помощь настройки любой из этих программ, смотрите [[LAMP]] и следуйте всем разделам, кроме связанного с [[MySQL]].<br />
<br />
==Установка PostgreSQL==<br />
*Устанавливаем postgresql<br />
$ sudo pacman -S postgresql<br />
*Создаём конфигурационный файл из готовых шаблонов systemd (они находятся по адресу /usr/lib/tmpfiles.d/)<br />
$ systemd-tmpfiles --create postgresql.conf<br />
*Инициализируем кластер с нужной локалью (она должна быть доступна в системе)<br />
$ sudo su - postgres -c "initdb --locale ru_RU.UTF-8 -E UTF8 -D '/var/lib/postgres/data'"<br />
*Запускаем сервер PostgreSQL<br />
$ systemctl start postgresql<br />
*Допонительно его можно добавить в автозагрузку<br />
$ systemctl enable postgresql<br />
<br />
==Создание Вашей первой базы данных==<br />
*Становимся пользователем postgres<br />
su root<br />
su - postgres<br />
*Добавляем нового пользователя базы данных<br />
[http://www.postgresql.org/docs/8.3/static/app-createuser.html createuser] -DRSP <username><br />
-D Пользователь не может создавать базы данных<br><br />
-R Пользователь не может создавать аккаунты<br><br />
-S Пользователь не является суперпользователем<br><br />
-P Запрашивать пароль при создании<br><br />
<br />
С другой стороны, вы можете использовать команду createuser без параметров. Вывод в терминале выглядит так:<br />
<br />
# createuser <username><br />
Shall the new role be a superuser? (y/n) n<br />
Shall the new role be allowed to create databases? (y/n) y<br />
Shall the new role be allowed to create more new roles? (y/n) y<br />
<br />
*Если имя созданного пользователя совпадает с именем пользователя ($ USER) вы получите доступ к базе данных оболочки PostgreSQL без указания имени пользователя (что весьма удобно).<br />
<br />
*Создайте новую базу даных от пользователя, имеющего разрешение на чтение и запись (read/write).<br />
[http://www.postgresql.org/docs/8.3/static/app-createdb.html createdb] -O username databasename [-E database_encoding]<br />
*Вот и всё! Ваша база данных создана.<br />
<br />
==Знакомство с PostgreSQL==<br />
<br />
===Доступ к оболочке базы данных===<br />
*Становимся postgres пользователем, чтобы иметь возможность задать ваши права (как у основного пользователя)<br />
$ sudo su postgres<br />
<br />
*Запускаем основную оболочку базы данных, в которой мы сможем создавать, удалять базы данных/таблицы, задавать права и запускать команды SQL.<br />
$ [http://www.postgresql.org/docs/8.3/static/app-psql.html psql]<br />
:''--Вы также можете использовать `psql <database_name>` для редактирования конкретной базы данных.''<br />
*Подключаем базу данных<br />
=> \c <database><br />
Configure Postgre*Список всех пользователей и их уровни доступа<br />
=> \du<br />
*Краткая информация о всех таблицах в текущей базе данных<br />
=> \dt<br />
Есть, конечно, много других мета-команд, но именно эти должны помочь вам начать работу.<br />
<br />
==Настройка удалённого доступа к PostgreSQL==<br />
Файл настроек сервера баз данных PostgreSQL <code>postgresql.conf</code>. Этот файл находится в папке данных сервера, обычно <code>/var/lib/postgres/data</code>. В этой же папке находятся основные файлы настроек включая и <code>pg_hba.conf</code>.<br />
Замечание | По умолчанию эта папка не доступна даже для просмотра (или поиска) от лица обычного пользователя.<br />
#Из-под пользователя root редактируем файл <br><pre>$ sudo nano /var/lib/postgres/data/postgresql.conf</pre><br />
#В разделе connections and authentications раскомментируйте или исправьте строку<code>listen_addresses</code> по вашему желанию <br><pre>listen_addresses = '*'</pre>и внимательно просмотрите другие строки.<br />
#Далее добавляем следующую строку в основной файл настройки проверки подлинности <code>/var/lib/postgres/data/pg_hba.conf</code>. Этот файл определяет, каким хостам разрешено подключаться, '''так что будьте осторожны'''.<br><pre># IPv4 local connections: <br>host all all your_desired_ip_address/32 trust</pre>где <code>your_desired_ip_address</code> ip адрес клиента.<br />
#После этого необходимо перезапустить демон, чтобы изменения вступили в силу <br><pre>$ systemctl restart postgresql</pre><br />
<br />
Замечание | Postgresql по умолчанию использует порт 5432 для удалённого доступа. Поэтому убедитесь, что этот порт открыт и может принимать входящие соединения<br />
<br />
Если возникли проблемы взгляните на лог-файл сервера<br />
$ journalctl -u postgresql<br />
<br />
==Настройка PostgreSQL для работы с PHP==<br />
#Установите модуль PHP-PostgreSQL <pre>$ pacman -S php-pgsql </pre><br />
#Откройте файл '''<code>/etc/php/php.ini</code>''' в удобном для вас текстовом редакторе, например,<pre>$ sudo nano /etc/php/php.ini</pre><br />
#Найдите строку, начинающуюся с <code>;extension=pgsql.so</code> и из неё уберите {{ic|;}} ({{ic|;}} значит, что строка закомментирована). Если вы используете PDO, сделайте то же самое с <code>;extension=pdo.so</code> и <code>;extension=pdo_pgsql.so</code>. Если этих строк нет, добавьте их (без {{ic|;}}). Эти строки надо искать в разделе файла «Dynamic Extensions» (по умолчанию) или в самом конце файла.<br />
#Перезапустите веб-сервер Apache<pre># systemctl restart httpd</pre><br />
#Либо, если у вас nginx + php-fpm, то <pre># systemctl reload php-fpm</pre><br />
<br />
==Настройка PostgreSQL для работы с HHVM==<br />
$ git clone https://github.com/PocketRent/hhvm-pgsql.git<br />
$ cd hhvm-pgsql<br />
Если вы используете не ночную версию, то выполните это команду (проверено на HHVM 3.6.1), чтобы избежать ошибок компиляции:<br />
$ git checkout tags/3.6.0<br />
Затем надо собрать (если улучшенная поддержка языка Hack не нужна, то уберите -DHACK_FRIENDLY=ON):<br />
$ hphpize<br />
$ cmake -DHACK_FRIENDLY=ON .<br />
$ make<br />
Скопируем скомпилированное расширение:<br />
$ sudo cp pgsql.so /etc/hhvm/<br />
Затем в /etc/hhvm/server.ini добавляем:<br />
<pre>extension_dir = /etc/hhvm<br />
hhvm.extensions[pgsql] = pgsql.so</pre><br />
<br />
==Изменение кодировки новой базы данных на UTF-8 (по вашему усмотрению)==<br />
Когда создаётся новая база данных (например, <code>createdb blog</code>) PostgreSQL просто копирует шаблон базы данных. Есть два стандартных шаблона: template0 - ваниль, и template1 используемый по умолчанию. Один из вариантов изменения кодировки новой базы данных, заключается в изменении шаблона template1. Для этого, заходим в оболочку PostgresSQL (psql) и делаем вот что:<br />
<br />
1. Первое, мы должны сбросить template1. Шаблоны не могут быть сброшены, так что мы сначала изменим его, как обычную базу данных:<br />
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';<br />
2. Сейчас уже можно сбросить её:<br />
DROP DATABASE template1;<br />
3. Создаём новую базу данных, с новой кодировкой по умолчанию из template0:<br />
CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';<br />
4. Теперь снова сделаем template1 шаблоном:<br />
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1'; <br />
5. (Рекомендация) Документация по PostgreSQL [http://www.postgresql.org/docs/8.1/interactive/manage-ag-templatedbs.html advises] рекомендует "замораживать" изменения шаблона функцией VACUUM FREEZE:<br />
\c template1<br />
VACUUM FREEZE;<br />
6. (По желанию) Если вы не хотите, чтобы кто-либо подключался к этому шаблону, присвойте параметру datallowconn значение FALSE:<br />
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template1';<br />
<br />
Теперь вы можете создать базу данных используя стандартные команды в терминале:<br />
su - <br />
su - postgres<br />
createdb blog;<br />
<br />
Если снова войти в PSQL и проверить базу данных, вы должны увидеть правильную кодировку новой базы данных:<br />
\l<br />
returns<br />
List of databases<br />
Name | Owner | Encoding | Collation | Ctype | Access privileges <br />
-----------+----------+-----------+-----------+-------+----------------------<br />
blog | postgres | UTF8 | C | C | <br />
postgres | postgres | SQL_ASCII | C | C | <br />
template0 | postgres | SQL_ASCII | C | C | =c/postgres<br />
: postgres=CTc/postgres<br />
template1 | postgres | UTF8 | C | C |<br />
<br />
<br />
== Решение проблем ==<br />
=== Ускорение мелких транзакций ===<br />
Если вы используете PostgreSQL на своей локальной машине для разработки и вы считаете его медленным, то можете попробовать [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT отключить synchronous_commit] в конфигурации. Однако, не забывайте про его [http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT особенности].<br />
=== Запретить запись на диск во время бездействия ===<br />
PostgreSQL периодически обновляет свою статистику, лежающую в файле. По умолчанию этот файл находится на диске, что не даёт отдыхать (и изнашивает) жёсткому диску, заставляя его шуршать. Однако можно легко и безопасно поменять локацию файла внутрь ФС (/run) расположенной в ОЗУ с помощью такой настройки:<br />
<br />
{{hc|1=/var/lib/postgres/data/postgresql.conf|2=<br />
stats_temp_directory = '/run/postgresql'<br />
}}<br />
<br />
<br />
==Больше информации==<br />
*[http://www.postgresql.org/ Официальная страница PostgreSQL]</div>Arzeth