Make-initrd development discussion
 help / color / mirror / Atom feed
From: Alexey Gladkov <legion@kernel.org>
To: make-initrd@lists.altlinux.org
Subject: Re: [make-initrd] [PATCH 2/2] runtime: Fix console lock shadowing by /dev mount
Date: Sat, 17 Oct 2026 18:41:13 +0200
Message-ID: <atOlKaOKHj8krAZO@example.org> (raw)
In-Reply-To: <4509be5e-e769-4e84-90e8-daeceba47f76@gmail.com>

On Sat, Oct 17, 2026 at 07:19:50PM +0300, Leonid Krivoshein wrote:
> 
> 
> On 10/17/26 12:45 PM, Alexey Gladkov wrote:
> > On Fri, Oct 16, 2026 at 11:02:36PM +0300, Leonid Krivoshein wrote:
> > > Привет!
> > > 
> > > 
> > > On 10/16/26 3:06 PM, Alexey Gladkov wrote:
> > > > /etc/rc.d/rc acquires an exclusive lock on /dev/console before starting
> > > > runlevel services. When the mountfs service mounts devtmpfs over /dev,
> > > > the original /dev/console inode on rootfs is shadowed by a new inode on
> > > > devtmpfs. Consequently, rc holds the lock on the shadowed inode while
> > > > processes started after mountfs lock the new /dev/console inode without
> > > > waiting for rc to finish starting services. In particular, with the
> > > > rdshell boot parameter, rootdelayd acquires the console lock and starts
> > > > the emergency shell in the middle of runlevel 3 instead of after all
> > > > services have started.
> > > > 
> > > > Once the console lock is preserved across mountfs, the network-up init
> > > > service deadlocks against its parent /etc/rc.d/rc because network-up
> > > > requests a shared lock on the console while rc already holds an
> > > > exclusive lock for the duration of the runlevel scripts.
> > > > 
> > > > Use a dedicated /.initrd/console.lock file in /.initrd so the lock
> > > > remains on the same inode across /dev mount operations, and drop the
> > > > redundant lock acquisition from the synchronous network-up init script.
> > > 
> > > Хорошо, что нашлось решение и есть в сообществе люди, умеющие не только
> > > репортить баги, но и разбирающиеся в них, предлагающие патчи! Я всего-то
> > > хотел уточнить, поскольку вносил изменения в свою документацию, а тут
> > > столько всего поменялось. :-)
> > > 
> > > Но есть вопросы к этим изменениям, см. ниже...
> > > 
> > > 
> > > > 
> > > > Fixes: 598a4b241a4f ("Rewrite console locking")
> > > > Reported-by: Leonid Krivoshein <klark.devel@gmail.com>
> > > > Signed-off-by: Alexey Gladkov <gladkov.alexey@gmail.com>
> > > > ---
> > > >    features/fsck/data/lib/uevent/handlers/040-mountdev         | 2 +-
> > > >    features/luks/data/lib/uevent/handlers/085-luks             | 2 +-
> > > >    features/network/data/etc/rc.d/init.d/network-up            | 3 ---
> > > >    features/runtime/data/etc/rc.d/rc                           | 2 +-
> > > >    features/runtime/data/init                                  | 1 +
> > > >    .../runtime/data/lib/uevent/handlers/mount/900-localdev     | 2 +-
> > > >    features/runtime/data/sbin/rootdelayd                       | 6 +++---
> > > >    features/sshfsroot/data/lib/uevent/handlers/040-sshfsroot   | 2 +-
> > > >    features/zfs/data/sbin/ueventd-zfs                          | 2 +-
> > > >    9 files changed, 10 insertions(+), 12 deletions(-)
> > > > 
> > > > diff --git a/features/fsck/data/lib/uevent/handlers/040-mountdev b/features/fsck/data/lib/uevent/handlers/040-mountdev
> > > > index 53208f0d..9e9f06ea 100755
> > > > --- a/features/fsck/data/lib/uevent/handlers/040-mountdev
> > > > +++ b/features/fsck/data/lib/uevent/handlers/040-mountdev
> > > > @@ -56,7 +56,7 @@ handler()
> > > >    }
> > > >    exec 0</dev/console >/dev/console 2>&1
> > > > -fd_lock 90 /dev/console
> > > > +fd_lock 90 /.initrd/console.lock
> > > Получается, здесь сначала выполняется открытие файла консоли, только потом
> > > её захват. Не лучше ли наоборот или это непринципиально?
> > 
> > Это блокировка не открытия /dev/console, а записи в неё. Открыть и держать
> > открытой её может кто угодно.
> > 
> 
> По всем трём вопросам теперь понятно, спасибо! Однако замечу...
> 
> 
> > > Коль блокировка консоли используется внутри make-initrd во многих местах,
> > > нет ли смысла скрыть её внутреннюю реализацию как раз на случай таких
> > > изменений? Что-то типа fd_lock_console() / fd_unlock_console().
> > 
> > Я этого не делал с самого начала в первую очередь из-за номера
> > дескриптора. Для вызываемых утилит его иногда стоит закрывать по номеру.
> > Хардкодить этот номер внутри функции и использовать магические числа в
> > коде выше выглядит неправильно:
> > 
> >    fd_lock_console
> >    rdshell "Emergency shell" 90<&-
> >    fd_unlock_console
> > 
> > или
> > 
> >    fd_lock_console
> >    rdshell "Emergency shell" $fd_console<&-
> >    fd_unlock_console
> > 
> > выглядит криво.
> 
> а если так?
> 
> fd_lock_console
> fd_locked_console rdshell "Emergency shell"
> fd_unlock_console
> 
> # wrapper
> fd_locked_console()
> {
>     "$@" $fd_console<&-
> }
> 
> 
> 
> > Плюс если потребуется залочить ещё какой-то ресурс, то
> > встанет проблема синхронизации номеров дескрипторов.
> > 
> 
> Этой проблемы нет, если назначать номера дескрипторов динамически.
> 
> 
> > Поэтому я решил не прятать эти аргументы и предоставить вызывающему
> > больший контроль.
> > 
> > > Насколько безопасно использовать статически заданный дескриптор для этой
> > > блокировки? Не лучше ли его определять динамически?
> > 
> > В шелле нет хорошего способа выбрать свободный дескриптор. Только перебор
> > по /proc/self/fd/*. Это намного затратнее и требует смонтированного /proc.
> > Всё это будет медленнее.
> > 
> > И опять же придётся делать целую библиотеку с выбором дескрптора,
> > глобальной переменной, где этот номер будет жить.
> > 
> 
> Есть вариант для bash >= 4.1. Причём, если делать это в субшеле, то даже
> необязательно закрывать файл, bash его сама закроет. Пример:
> 
> exec {fd_console}>/.initrd/console-fd.lock
> echo "..." >&$fd_console
> exec {fd_console}>&-
> 
> Только я не знаю, можно ли в случае make-initrd полагаться, что у bash
> версия не меньше 4.1, но на Альте данный код работает, проверил на p11.

Ты будешь смеяться, но я буквально только что нашёл этот же снипет :)
Я уже тестирую новый API для блокировок [1]. Как пройдут тесты сделаю v2
патчей.

Даже bash-4.2 появился 15 лет назад. Думаю, что это достаточно большой
срок, чтобы добавить requires bash >= 4.1

[1] https://github.com/osboot/make-initrd/commit/6fb0fe5992568859e5bb6c95b6289eaee6a70f4e

> 
> > Без нужды я не вижу смысла такое городить.
> > 
> 
> Да, тут тебе конечно видней.

> 
> -- 
> WBR, Leonid Krivoshein.
> 
> _______________________________________________
> Make-initrd mailing list
> Make-initrd@lists.altlinux.org
> https://lists.altlinux.org/mailman/listinfo/make-initrd

-- 
Rgrds, legion



  reply	other threads:[~2026-10-17 16:41 UTC|newest]

Thread overview: 47+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-10-12 22:42 [make-initrd] Параметр rdshell Leonid Krivoshein
2026-10-14 10:04 ` Egor Shestakov
2026-10-14 16:01   ` Leonid Krivoshein
2026-10-15 14:48     ` [make-initrd] [RFC PATCH] runtime: fix a suspended boot after rdshell Egor Shestakov
2026-10-16 10:20       ` Alexey Gladkov
2026-10-16 13:39         ` Egor Shestakov
2026-10-16 14:09           ` Alexey Gladkov
2026-10-16 14:13             ` Egor Shestakov
2026-10-16 14:11           ` Egor Shestakov
2026-10-19 10:22   ` [make-initrd] Параметр rdshell Alexey Gladkov
2026-10-19 12:51     ` [make-initrd] kmscon (was: Параметр rdshell) Egor Shestakov
2026-10-19 13:38       ` Alexey Gladkov
2026-10-19 15:09         ` Egor Shestakov
2026-10-19 16:14           ` Alexey Gladkov
2026-10-16 12:06 ` [make-initrd] [PATCH 0/2] runtime: Fix console locking Alexey Gladkov
2026-10-16 12:06   ` [make-initrd] [PATCH 1/2] runtime: Fix a lock leak in rootdelayd Alexey Gladkov
2026-10-16 12:06   ` [make-initrd] [PATCH 2/2] runtime: Fix console lock shadowing by /dev mount Alexey Gladkov
2026-10-16 20:02     ` Leonid Krivoshein
2026-10-17  9:45       ` Alexey Gladkov
2026-10-17 16:19         ` Leonid Krivoshein
2026-10-17 16:41           ` Alexey Gladkov [this message]
2026-10-19  9:57 ` [make-initrd] [PATCH v2 00/11] Improve support for atomic actions Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 01/11] runtime: Fix a lock leak in rootdelayd Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 02/11] runtime: Fix console lock shadowing by /dev mount Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 03/11] runtime: Avoid leaking lock descriptor 90 to child processes Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 04/11] runtime: Replace /.initrd/initenv locking with atomic file update Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 05/11] runtime: Centralize file and console locking helpers Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 06/11] create-rootfs: Require bash 4.1 or newer for initramfs Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 07/11] network: Share DHCP hook lock between IPv4 and IPv6 on the same interface Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 08/11] luks: Serialize /etc/luks.keys updates and avoid duplicate entries Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 09/11] runtime: Synchronize concurrent /etc/fstab access with shared and exclusive locks Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 10/11] runtime: Update rootdelay deadline and failure message atomically Alexey Gladkov
2026-10-19  9:57   ` [make-initrd] [PATCH v2 11/11] runtime: Centralize atomic file replacement in write_atomic helper Alexey Gladkov
2026-10-19 19:30   ` [make-initrd] [PATCH v2 00/11] Improve support for atomic actions Leonid Krivoshein
2026-10-20 14:59     ` Alexey Gladkov
2026-10-20 19:04       ` Leonid Krivoshein
2026-10-20 19:23         ` [make-initrd] Уточнение по rootdelay_unpause() Leonid Krivoshein
2026-10-21 10:10           ` [make-initrd] [PATCH] runtime: Freeze rootdelay countdown while paused Alexey Gladkov
2026-10-21  7:18         ` [make-initrd] [PATCH v2 00/11] Improve support for atomic actions Alexey Gladkov
2026-10-21  8:50           ` Leonid Krivoshein
2026-10-21 10:18             ` Alexey Gladkov
2026-10-21 18:52               ` Leonid Krivoshein
2026-10-21 19:30                 ` Alexey Gladkov
2026-10-21 19:33                   ` Leonid Krivoshein
2026-10-21 19:31                 ` Leonid Krivoshein
2026-10-21 20:03                   ` Alexey Gladkov
2026-10-21 20:48                     ` Leonid Krivoshein

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=atOlKaOKHj8krAZO@example.org \
    --to=legion@kernel.org \
    --cc=make-initrd@lists.altlinux.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link

Make-initrd development discussion

This inbox may be cloned and mirrored by anyone:

	git clone --mirror http://lore.altlinux.org/make-initrd/0 make-initrd/git/0.git

	# If you have public-inbox 1.1+ installed, you may
	# initialize and index your mirror using the following commands:
	public-inbox-init -V2 make-initrd make-initrd/ http://lore.altlinux.org/make-initrd \
		make-initrd@lists.altlinux.org make-initrd@lists.altlinux.ru make-initrd@lists.altlinux.com
	public-inbox-index make-initrd

Example config snippet for mirrors.
Newsgroup available over NNTP:
	nntp://lore.altlinux.org/org.altlinux.lists.make-initrd


AGPL code for this site: git clone https://public-inbox.org/public-inbox.git