Skip to contentSkip to conversation

printk: remove logbuf_lock

PATCH Superseded John Ogness 6 participants 47 messages Dec 1, 2020 – Dec 9, 2020 Printk

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

John Ogness

author maintainer
#0 lore raw

v2 cover printk: remove logbuf_lock

Hello,

Here is a v2 of the next series for the printk-rework. It removes the @logbuf_lock. v1 is here [0]. Since this lock protected more than just the ringbuffer, a new finer-grained @syslog_lock is introduced.

With this series, vprintk_store() becomes lockless.

A consequence of this locklessness is that a buffer for temporary sprint space is no longer available. To get around this, vsnprintf() is used to determine the full length to reserve in the ringbuffer and then the message is directly sprint'ed to the reserved space.

Since the sprint'ed message may include syslog prefix and newline (both of which get stripped), there will be some bytes of wasted space per message. This space could be reclaimed by introducing a "trimming function" to the ringbuffer, which could reduce the size of a reserved data block if no newer block is reserved. However, such a function is not part of this series.

This series falls in line with the printk-rework plan as presented [1] at Linux Plumbers in Lisbon 2019.

The series is based on next-20201201.

John Ogness

[0] https://lkml.kernel.org/r/[email protected]
[1] https://linuxplumbersconf.org/event/4/contributions/290/attachments/276/463/lpc2019_jogness_printk.pdf (slide 23)

John Ogness (3):
printk: inline log_output(),log_store() in vprintk_store()
printk: change @clear_seq to atomic64_t
printk: remove logbuf_lock, add syslog_lock

 include/linux/printk.h      |   1 +
 kernel/printk/internal.h    |   4 +-
 kernel/printk/printk.c      | 411 ++++++++++++++++++------------------
 kernel/printk/printk_safe.c |  18 +-
 4 files changed, 212 insertions(+), 222 deletions(-)
Signature · 1 line
2.20.1
author maintainer
#1 lore raw

PATCH v2 1/3 printk: inline log_output(),log_store() in vprintk_store()

In preparation for removing logbuf_lock, inline log_output() and log_store() into vprintk_store(). This will simplify dealing with the various code branches and fallbacks that are possible.

---
 kernel/printk/printk.c | 134 +++++++++++++++++------------------------
 1 file changed, 56 insertions(+), 78 deletions(-)
kernel/printk/printk.c +56 -78
index f279d4fbd9dd..fc5e3a7d6d89 100644
@@ -491,52 +491,6 @@ static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
 		*trunc_msg_len = 0;
 }
 
-/* insert record into the buffer, discard old ones, update heads */
-static int log_store(u32 caller_id, int facility, int level,
-		     enum log_flags flags, u64 ts_nsec,
-		     const struct dev_printk_info *dev_info,
-		     const char *text, u16 text_len)
-{
-	struct prb_reserved_entry e;
-	struct printk_record r;
-	u16 trunc_msg_len = 0;
-
-	prb_rec_init_wr(&r, text_len);
-
-	if (!prb_reserve(&e, prb, &r)) {
-		/* truncate the message if it is too long for empty buffer */
-		truncate_msg(&text_len, &trunc_msg_len);
-		prb_rec_init_wr(&r, text_len + trunc_msg_len);
-		/* survive when the log buffer is too small for trunc_msg */
-		if (!prb_reserve(&e, prb, &r))
-			return 0;
-	}
-
-	/* fill message */
-	memcpy(&r.text_buf[0], text, text_len);
-	if (trunc_msg_len)
-		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
-	r.info->text_len = text_len + trunc_msg_len;
-	r.info->facility = facility;
-	r.info->level = level & 7;
-	r.info->flags = flags & 0x1f;
-	if (ts_nsec > 0)
-		r.info->ts_nsec = ts_nsec;
-	else
-		r.info->ts_nsec = local_clock();
-	r.info->caller_id = caller_id;
-	if (dev_info)
-		memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
-
-	/* A message without a trailing newline can be continued. */
-	if (!(flags & LOG_NEWLINE))
-		prb_commit(&e);
-	else
-		prb_final_commit(&e);
-
-	return (text_len + trunc_msg_len);
-}
-
 int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
 
 static int syslog_action_restricted(int type)
@@ -1907,44 +1861,22 @@ static inline u32 printk_caller_id(void)
 		0x80000000 + raw_smp_processor_id();
 }
 
-static size_t log_output(int facility, int level, enum log_flags lflags,
-			 const struct dev_printk_info *dev_info,
-			 char *text, size_t text_len)
-{
-	const u32 caller_id = printk_caller_id();
-
-	if (lflags & LOG_CONT) {
-		struct prb_reserved_entry e;
-		struct printk_record r;
-
-		prb_rec_init_wr(&r, text_len);
-		if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
-			memcpy(&r.text_buf[r.info->text_len], text, text_len);
-			r.info->text_len += text_len;
-			if (lflags & LOG_NEWLINE) {
-				r.info->flags |= LOG_NEWLINE;
-				prb_final_commit(&e);
-			} else {
-				prb_commit(&e);
-			}
-			return text_len;
-		}
-	}
-
-	/* Store it in the record log */
-	return log_store(caller_id, facility, level, lflags, 0,
-			 dev_info, text, text_len);
-}
-
 /* Must be called under logbuf_lock. */
 int vprintk_store(int facility, int level,
 		  const struct dev_printk_info *dev_info,
 		  const char *fmt, va_list args)
 {
+	const u32 caller_id = printk_caller_id();
 	static char textbuf[LOG_LINE_MAX];
-	char *text = textbuf;
-	size_t text_len;
+	struct prb_reserved_entry e;
 	enum log_flags lflags = 0;
+	struct printk_record r;
+	u16 trunc_msg_len = 0;
+	char *text = textbuf;
+	u16 text_len;
+	u64 ts_nsec;
+
+	ts_nsec = local_clock();
 
 	/*
 	 * The printf needs to come first; we need the syslog
@@ -1983,7 +1915,53 @@ int vprintk_store(int facility, int level,
 	if (dev_info)
 		lflags |= LOG_NEWLINE;
 
-	return log_output(facility, level, lflags, dev_info, text, text_len);
+	if (lflags & LOG_CONT) {
+		prb_rec_init_wr(&r, text_len);
+		if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
+			memcpy(&r.text_buf[r.info->text_len], text, text_len);
+			r.info->text_len += text_len;
+
+			if (lflags & LOG_NEWLINE) {
+				r.info->flags |= LOG_NEWLINE;
+				prb_final_commit(&e);
+			} else {
+				prb_commit(&e);
+			}
+
+			return text_len;
+		}
+	}
+
+	prb_rec_init_wr(&r, text_len);
+	if (!prb_reserve(&e, prb, &r)) {
+		/* truncate the message if it is too long for empty buffer */
+		truncate_msg(&text_len, &trunc_msg_len);
+
+		prb_rec_init_wr(&r, text_len + trunc_msg_len);
+		if (!prb_reserve(&e, prb, &r))
+			return 0;
+	}
+
+	/* fill message */
+	memcpy(&r.text_buf[0], text, text_len);
+	if (trunc_msg_len)
+		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
+	r.info->text_len = text_len + trunc_msg_len;
+	r.info->facility = facility;
+	r.info->level = level & 7;
+	r.info->flags = lflags & 0x1f;
+	r.info->ts_nsec = ts_nsec;
+	r.info->caller_id = caller_id;
+	if (dev_info)
+		memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
+
+	/* A message without a trailing newline can be continued. */
+	if (!(lflags & LOG_NEWLINE))
+		prb_commit(&e);
+	else
+		prb_final_commit(&e);
+
+	return (text_len + trunc_msg_len);
 }
 
 asmlinkage int vprintk_emit(int facility, int level,
Signature · 1 line
2.20.1
maintainer Reviewed-by on v2 1/3
#2 lore raw

Re: [PATCH next v2 1/3] printk: inline log_output(),log_store() in vprintk_store()

Quoted 24 lines · John Ogness

In preparation for removing logbuf_lock, inline log_output() and log_store() into vprintk_store(). This will simplify dealing with the various code branches and fallbacks that are possible.

---
 kernel/printk/printk.c | 134 +++++++++++++++++------------------------
 1 file changed, 56 insertions(+), 78 deletions(-)
kernel/printk/printk.c +8 -1
index f279d4fbd9dd..fc5e3a7d6d89 100644
@@ -1983,7 +1915,53 @@ int vprintk_store(int facility, int level,
 	if (dev_info)
 		lflags |= LOG_NEWLINE;
 
-	return log_output(facility, level, lflags, dev_info, text, text_len);
+	if (lflags & LOG_CONT) {
+		prb_rec_init_wr(&r, text_len);
+		if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
+			memcpy(&r.text_buf[r.info->text_len], text, text_len);
+			r.info->text_len += text_len;
+
+			if (lflags & LOG_NEWLINE) {
+				r.info->flags |= LOG_NEWLINE;

kernel/printk/printk.c int vprintk_store(int facility, int level, · line 1935

Quoted 10 lines
kernel/printk/printk.c +10 -0
+				prb_final_commit(&e);
+			} else {
+				prb_commit(&e);
+			}
+
+			return text_len;
+		}
+	}
+
+	prb_rec_init_wr(&r, text_len);

This is called in both branches. I would do it just once at the beginning.

Quoted 8 lines
kernel/printk/printk.c +8 -0
+	if (!prb_reserve(&e, prb, &r)) {
+		/* truncate the message if it is too long for empty buffer */
+		truncate_msg(&text_len, &trunc_msg_len);
+
+		prb_rec_init_wr(&r, text_len + trunc_msg_len);
+		if (!prb_reserve(&e, prb, &r))
+			return 0;
+	}

kernel/printk/printk.c int vprintk_store(int facility, int level, · line 1953

Quoted 10 lines
kernel/printk/printk.c +10 -0
+
+	/* fill message */
+	memcpy(&r.text_buf[0], text, text_len);
+	if (trunc_msg_len)
+		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
+	r.info->text_len = text_len + trunc_msg_len;
+	r.info->facility = facility;
+	r.info->level = level & 7;
+	r.info->flags = lflags & 0x1f;
+	r.info->ts_nsec = ts_nsec;

This is the only location where ts_nsec is used. I would remove the variable and call:

	r.info->ts_nsec = local_clock();

kernel/printk/printk.c int vprintk_store(int facility, int level, · line 1965

Quoted 12 lines
kernel/printk/printk.c +11 -0
+	r.info->caller_id = caller_id;
+	if (dev_info)
+		memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
+
+	/* A message without a trailing newline can be continued. */
+	if (!(lflags & LOG_NEWLINE))
+		prb_commit(&e);
+	else
+		prb_final_commit(&e);
+
+	return (text_len + trunc_msg_len);
 }

Both changes are cosmetic and I do not resist on them. Please, do the changes if v3 is needed and you agree with them.

Anyway, feel free to use:

Best Regards,
Petr

author maintainer
#3 lore raw

Re: [PATCH next v2 1/3] printk: inline log_output(),log_store() in vprintk_store()

Quoted 13 lines · Petr Mladek
Quoted 13 lines
kernel/printk/printk.c +13 -0
+	if (lflags & LOG_CONT) {
+		prb_rec_init_wr(&r, text_len);
+		if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
+			memcpy(&r.text_buf[r.info->text_len], text, text_len);
+			r.info->text_len += text_len;
+
+			if (lflags & LOG_NEWLINE) {
+				r.info->flags |= LOG_NEWLINE;
+				prb_final_commit(&e);
+			} else {
+				prb_commit(&e);
+			}
+
Quoted 8 lines

kernel/printk/printk.c int vprintk_store(int facility, int level, · line 1935

Quoted 5 lines
kernel/printk/printk.c +5 -0
+			return text_len;
+		}
+	}
+
+	prb_rec_init_wr(&r, text_len);

This is called in both branches. I would do it just once at the beginning.

Actually that leads to a crash when prb_reserve_in_last() fails and the fallback code uses a record that prb_reserve_in_last() has already touched. The implementation of prb_reserve_in_last() would have to be changed so that failure guarantees that @r has not been modified. Currently prb_reserve_in_last() can fail after modifying @r.

Quoted 22 lines
Quoted 8 lines
kernel/printk/printk.c +8 -0
+	if (!prb_reserve(&e, prb, &r)) {
+		/* truncate the message if it is too long for empty buffer */
+		truncate_msg(&text_len, &trunc_msg_len);
+
+		prb_rec_init_wr(&r, text_len + trunc_msg_len);
+		if (!prb_reserve(&e, prb, &r))
+			return 0;
+	}

kernel/printk/printk.c int vprintk_store(int facility, int level, · line 1953

Quoted 10 lines
kernel/printk/printk.c +10 -0
+
+	/* fill message */
+	memcpy(&r.text_buf[0], text, text_len);
+	if (trunc_msg_len)
+		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
+	r.info->text_len = text_len + trunc_msg_len;
+	r.info->facility = facility;
+	r.info->level = level & 7;
+	r.info->flags = lflags & 0x1f;
+	r.info->ts_nsec = ts_nsec;

This is the only location where ts_nsec is used. I would remove the variable and call:

Quoted 1 line
	r.info->ts_nsec = local_clock();

My reason for grabbing the clock at the beginning is so that the timestamp is as close to the printk() call as possible. IMHO it is a more deterministic timestamp than if it is taken after reservation(s) and sprint'ing. I prefer to keep it as it is, but will not object if such a change is necessary for mailine acceptance.

John Ogness

Reviewed-by
#4 lore raw

Re: [PATCH next v2 1/3] printk: inline log_output(),log_store() in vprintk_store()

On (20/12/03 17:31), John Ogness wrote:
[..]

Quoted 22 lines
Quoted 22 lines
Quoted 8 lines
kernel/printk/printk.c +8 -0
+	if (!prb_reserve(&e, prb, &r)) {
+		/* truncate the message if it is too long for empty buffer */
+		truncate_msg(&text_len, &trunc_msg_len);
+
+		prb_rec_init_wr(&r, text_len + trunc_msg_len);
+		if (!prb_reserve(&e, prb, &r))
+			return 0;
+	}

kernel/printk/printk.c int vprintk_store(int facility, int level, · line 1953

Quoted 10 lines
kernel/printk/printk.c +10 -0
+
+	/* fill message */
+	memcpy(&r.text_buf[0], text, text_len);
+	if (trunc_msg_len)
+		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
+	r.info->text_len = text_len + trunc_msg_len;
+	r.info->facility = facility;
+	r.info->level = level & 7;
+	r.info->flags = lflags & 0x1f;
+	r.info->ts_nsec = ts_nsec;

This is the only location where ts_nsec is used. I would remove the variable and call:

Quoted 7 lines
Quoted 1 line
	r.info->ts_nsec = local_clock();

My reason for grabbing the clock at the beginning is so that the timestamp is as close to the printk() call as possible. IMHO it is a more deterministic timestamp than if it is taken after reservation(s) and sprint'ing. I prefer to keep it as it is, but will not object if such a change is necessary for mailine acceptance.

Sounds reasonable

	-ss
maintainer
#5 lore raw

Re: [PATCH next v2 1/3] printk: inline log_output(),log_store() in vprintk_store()

In reply to John Ogness
Quoted 23 lines · John Ogness
Quoted 13 lines · Petr Mladek
Quoted 13 lines
kernel/printk/printk.c +13 -0
+	if (lflags & LOG_CONT) {
+		prb_rec_init_wr(&r, text_len);
+		if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
+			memcpy(&r.text_buf[r.info->text_len], text, text_len);
+			r.info->text_len += text_len;
+
+			if (lflags & LOG_NEWLINE) {
+				r.info->flags |= LOG_NEWLINE;
+				prb_final_commit(&e);
+			} else {
+				prb_commit(&e);
+			}
+
Quoted 8 lines

kernel/printk/printk.c int vprintk_store(int facility, int level, · line 1935

Quoted 5 lines
kernel/printk/printk.c +5 -0
+			return text_len;
+		}
+	}
+
+	prb_rec_init_wr(&r, text_len);

This is called in both branches. I would do it just once at the beginning.

Quoted 5 lines

Actually that leads to a crash when prb_reserve_in_last() fails and the fallback code uses a record that prb_reserve_in_last() has already touched. The implementation of prb_reserve_in_last() would have to be changed so that failure guarantees that @r has not been modified. Currently prb_reserve_in_last() can fail after modifying @r.

I see. It would deserve a comment so that nobody repeats my mistake again. I am sure that I would be able to do it once again few months from now ;-)

Quoted 22 lines
Quoted 22 lines
Quoted 8 lines
kernel/printk/printk.c +8 -0
+	if (!prb_reserve(&e, prb, &r)) {
+		/* truncate the message if it is too long for empty buffer */
+		truncate_msg(&text_len, &trunc_msg_len);
+
+		prb_rec_init_wr(&r, text_len + trunc_msg_len);
+		if (!prb_reserve(&e, prb, &r))
+			return 0;
+	}

kernel/printk/printk.c int vprintk_store(int facility, int level, · line 1953

Quoted 10 lines
kernel/printk/printk.c +10 -0
+
+	/* fill message */
+	memcpy(&r.text_buf[0], text, text_len);
+	if (trunc_msg_len)
+		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
+	r.info->text_len = text_len + trunc_msg_len;
+	r.info->facility = facility;
+	r.info->level = level & 7;
+	r.info->flags = lflags & 0x1f;
+	r.info->ts_nsec = ts_nsec;

This is the only location where ts_nsec is used. I would remove the variable and call:

Quoted 7 lines
Quoted 1 line
	r.info->ts_nsec = local_clock();

My reason for grabbing the clock at the beginning is so that the timestamp is as close to the printk() call as possible. IMHO it is a more deterministic timestamp than if it is taken after reservation(s) and sprint'ing. I prefer to keep it as it is, but will not object if such a change is necessary for mailine acceptance.

Fair enough. It would deserve a comment as well.

Best Regards,
Petr

author maintainer
#6 lore raw

PATCH v2 2/3 printk: change @clear_seq to atomic64_t

In reply to John Ogness

Currently @clear_seq access is protected by @logbuf_lock. Once @logbuf_lock is removed some other form of synchronization will be required. Change the type of @clear_seq to atomic64_t to provide the synchronization.

---
 kernel/printk/printk.c | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)
kernel/printk/printk.c +14 -8
index fc5e3a7d6d89..e9018c4e1b66 100644
@@ -403,7 +403,7 @@ static u64 exclusive_console_stop_seq;
 static unsigned long console_dropped;
 
 /* the next printk record to read after the last 'clear' command */
-static u64 clear_seq;
+static atomic64_t clear_seq = ATOMIC64_INIT(0);
 
 #ifdef CONFIG_PRINTK_CALLER
 #define PREFIX_MAX		48
@@ -797,7 +797,7 @@ static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
 		 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
 		 * changes no global state, and does not clear anything.
 		 */
-		user->seq = clear_seq;
+		user->seq = atomic64_read(&clear_seq);
 		break;
 	case SEEK_END:
 		/* after the last record */
@@ -914,6 +914,9 @@ void log_buf_vmcoreinfo_setup(void)
 	 * parse it and detect any changes to structure down the line.
 	 */
 
+	VMCOREINFO_SIZE(atomic64_t);
+	VMCOREINFO_TYPE_OFFSET(atomic64_t, counter);
+
 	VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
 	VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
 	VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
@@ -1476,6 +1479,7 @@ static int syslog_print_all(char __user *buf, int size, bool clear)
 	struct printk_info info;
 	unsigned int line_count;
 	struct printk_record r;
+	u64 clr_seq;
 	char *text;
 	int len = 0;
 	u64 seq;
@@ -1487,15 +1491,17 @@ static int syslog_print_all(char __user *buf, int size, bool clear)
 
 	time = printk_time;
 	logbuf_lock_irq();
+	clr_seq = atomic64_read(&clear_seq);
+
 	/*
 	 * Find first record that fits, including all following records,
 	 * into the user-provided buffer for this dump.
 	 */
-	prb_for_each_info(clear_seq, prb, seq, &info, &line_count)
+	prb_for_each_info(clr_seq, prb, seq, &info, &line_count)
 		len += get_record_print_text_size(&info, line_count, true, time);
 
 	/* move first record forward until length fits into the buffer */
-	prb_for_each_info(clear_seq, prb, seq, &info, &line_count) {
+	prb_for_each_info(clr_seq, prb, seq, &info, &line_count) {
 		if (len <= size)
 			break;
 		len -= get_record_print_text_size(&info, line_count, true, time);
@@ -1526,7 +1532,7 @@ static int syslog_print_all(char __user *buf, int size, bool clear)
 	}
 
 	if (clear)
-		clear_seq = seq;
+		atomic64_set(&clear_seq, seq);
 	logbuf_unlock_irq();
 
 	kfree(text);
@@ -1536,7 +1542,7 @@ static int syslog_print_all(char __user *buf, int size, bool clear)
 static void syslog_clear(void)
 {
 	logbuf_lock_irq();
-	clear_seq = prb_next_seq(prb);
+	atomic64_set(&clear_seq, prb_next_seq(prb));
 	logbuf_unlock_irq();
 }
 
@@ -3205,7 +3211,7 @@ void kmsg_dump(enum kmsg_dump_reason reason)
 		dumper->active = true;
 
 		logbuf_lock_irqsave(flags);
-		dumper->cur_seq = clear_seq;
+		dumper->cur_seq = atomic64_read(&clear_seq);
 		dumper->next_seq = prb_next_seq(prb);
 		logbuf_unlock_irqrestore(flags);
 
@@ -3412,7 +3418,7 @@ EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
  */
 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
 {
-	dumper->cur_seq = clear_seq;
+	dumper->cur_seq = atomic64_read(&clear_seq);
 	dumper->next_seq = prb_next_seq(prb);
 }
 
Signature · 1 line
2.20.1
maintainer
#7 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 10 lines · John Ogness

Currently @clear_seq access is protected by @logbuf_lock. Once @logbuf_lock is removed some other form of synchronization will be required. Change the type of @clear_seq to atomic64_t to provide the synchronization.

kernel/printk/printk.c +0 -0
index fc5e3a7d6d89..e9018c4e1b66 100644

kernel/printk/printk.c EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer); · line 3421

Quoted 5 lines
kernel/printk/printk.c +1 -1
@@ -3412,7 +3418,7 @@ EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
  */
 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
 {
-	dumper->cur_seq = clear_seq;
+	dumper->cur_seq = atomic64_read(&clear_seq);

Sigh, atomic64_read() uses a spin lock in the generic implementation that is used on some architectures.

Hmm, this seems to be the only location where the lock must not be used. At the same time, a best effort might be acceptable here.

I am not super-happy with the following hack but it might work:

	/*
	 * Use the best effort to avoid locks. In the worst case,
	 * the bottom and upper halves will be inconsistent. Then
	 * the value will be far too big or far too low. Fallback
	 * to the first available sequence number when it is
	 * too big.
	 */
	if (IS_ENABLED(CONFIG_GENERIC_ATOMIC64)) {
		u64 first_seq = prb_first_seq(prb);

		dumper->cur_seq = READ_ONCE(&clear_seq->counter);
		if (dumper->cur_seq > first_seq)
			dumper->cur_seq = first_seq;
	} else {
		dumper->cur_seq = atomic64_read(&clear_seq);
	}

Alternative solution would to always fallback to the first_seq on these architectures. Few people would complain when they see more messages. We could always improve it when it causes problems.

Adding Peter Zijstra for his opinion [*].

kernel/printk/printk.c EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer); · line 3422

Quoted 1 line
kernel/printk/printk.c +0 -0
 	dumper->next_seq = prb_next_seq(prb);

[*] I am going to hide under a stone for the above hack.

Best Regards,
Petr

author maintainer
#8 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 20 lines · Petr Mladek
Quoted 10 lines · John Ogness

Currently @clear_seq access is protected by @logbuf_lock. Once @logbuf_lock is removed some other form of synchronization will be required. Change the type of @clear_seq to atomic64_t to provide the synchronization.

kernel/printk/printk.c +0 -0
index fc5e3a7d6d89..e9018c4e1b66 100644

kernel/printk/printk.c EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer); · line 3421

Quoted 5 lines
kernel/printk/printk.c +1 -1
@@ -3412,7 +3418,7 @@ EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
  */
 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
 {
-	dumper->cur_seq = clear_seq;
+	dumper->cur_seq = atomic64_read(&clear_seq);

Sigh, atomic64_read() uses a spin lock in the generic implementation that is used on some architectures.

Quoted 2 lines

Hmm, this seems to be the only location where the lock must not be used.

Yes, and it is read-only access. Perhaps atomic64_t is the wrong thing to use here. We could use a seqcount_latch and a shadow variable so that if a writer has been preempted, we can use the previous value. (Only kmsg_dump would need to use the lockless variant to read the value.)

void clear_seq_set(u64 val)

{
        spin_lock_irq(&clear_lock);
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[0] = val;
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[1] = val;
        spin_unlock_irq(&clear_lock);
}

u64 clear_seq_get_nolock(void)

{
        unsigned int seq, idx;
        u64 val;

        do {
                seq = raw_read_seqcount_latch(&clear_latch);
                idx = seq & 0x1;
                val = clear_seq[idx];
        } while (read_seqcount_latch_retry(&clear_latch, seq));

        return val;
}

u64 clear_seq_get(void)

{
        u64 val;
        
        spin_lock_irq(&clear_lock);
        val = clear_seq[0];
        spin_unlock_irq(&clear_lock);
        return val;
}
Quoted 3 lines

Alternative solution would to always fallback to the first_seq on these architectures. Few people would complain when they see more messages. We could always improve it when it causes problems.

I am also OK with this solution.

John Ogness

#9 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 16 lines · John Ogness

Yes, and it is read-only access. Perhaps atomic64_t is the wrong thing to use here. We could use a seqcount_latch and a shadow variable so that if a writer has been preempted, we can use the previous value. (Only kmsg_dump would need to use the lockless variant to read the value.)

void clear_seq_set(u64 val)

{
        spin_lock_irq(&clear_lock);
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[0] = val;
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[1] = val;
        spin_unlock_irq(&clear_lock);
}

u64 clear_seq_get_nolock(void)

Quoted 12 lines
{
        unsigned int seq, idx;
        u64 val;

        do {
                seq = raw_read_seqcount_latch(&clear_latch);
                idx = seq & 0x1;
                val = clear_seq[idx];
        } while (read_seqcount_latch_retry(&clear_latch, seq));

        return val;
}

That's overly complicated.

If you're going to double the storage you can simply do:

	seq = val
	smp_wmb();
	seq_copy = val;

vs

	do {
		tmp = seq_copy;
		smp_rmb();
		val = seq;
	} while (val != tmp);

Also look for CONFIG_64_BIT in kernel/sched/fair.c.

author maintainer
#10 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 38 lines · Peter Zijlstra
Quoted 16 lines

Yes, and it is read-only access. Perhaps atomic64_t is the wrong thing to use here. We could use a seqcount_latch and a shadow variable so that if a writer has been preempted, we can use the previous value. (Only kmsg_dump would need to use the lockless variant to read the value.)

void clear_seq_set(u64 val)

{
        spin_lock_irq(&clear_lock);
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[0] = val;
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[1] = val;
        spin_unlock_irq(&clear_lock);
}

u64 clear_seq_get_nolock(void)

Quoted 12 lines
{
        unsigned int seq, idx;
        u64 val;

        do {
                seq = raw_read_seqcount_latch(&clear_latch);
                idx = seq & 0x1;
                val = clear_seq[idx];
        } while (read_seqcount_latch_retry(&clear_latch, seq));

        return val;
}

That's overly complicated.

If you're going to double the storage you can simply do:

	seq = val
	smp_wmb();
	seq_copy = val;
Quoted 7 lines

vs

	do {
		tmp = seq_copy;
		smp_rmb();
		val = seq;
	} while (val != tmp);

That will not work. We are talking about a situation where the writer is preempted. So seq will never equal seq_copy in that situation. I expect that the seqcount_latch is necessary.

John Ogness

#11 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 3 lines · John Ogness

That will not work. We are talking about a situation where the writer is preempted. So seq will never equal seq_copy in that situation. I expect that the seqcount_latch is necessary.

Interrupted rather, I would think, specifically NMIs? Then yes, latch should work. Gets you either the old or new, but never something in between.

maintainer
#12 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

In reply to John Ogness
Quoted 47 lines · John Ogness
Quoted 38 lines · Peter Zijlstra
Quoted 16 lines

Yes, and it is read-only access. Perhaps atomic64_t is the wrong thing to use here. We could use a seqcount_latch and a shadow variable so that if a writer has been preempted, we can use the previous value. (Only kmsg_dump would need to use the lockless variant to read the value.)

void clear_seq_set(u64 val)

{
        spin_lock_irq(&clear_lock);
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[0] = val;
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[1] = val;
        spin_unlock_irq(&clear_lock);
}

u64 clear_seq_get_nolock(void)

Quoted 12 lines
{
        unsigned int seq, idx;
        u64 val;

        do {
                seq = raw_read_seqcount_latch(&clear_latch);
                idx = seq & 0x1;
                val = clear_seq[idx];
        } while (read_seqcount_latch_retry(&clear_latch, seq));

        return val;
}

That's overly complicated.

If you're going to double the storage you can simply do:

	seq = val
	smp_wmb();
	seq_copy = val;
Quoted 7 lines

vs

	do {
		tmp = seq_copy;
		smp_rmb();
		val = seq;
	} while (val != tmp);
Quoted 3 lines

That will not work. We are talking about a situation where the writer is preempted. So seq will never equal seq_copy in that situation. I expect that the seqcount_latch is necessary.

Or we could disable interrupts around the writer.

But seqcount_latch will actually be need so that it works in panic(). The writer might be on a CPU that has been stopped using NMI. And this code is used by dumpers() that are called during panic().

Sigh, I have to take a coffee and try to really understand the latch code ;-)

Best Regards,
Petr

#13 lore raw

RE: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

In reply to John Ogness

From: John Ogness

Quoted 49 lines

Sent: 07 December 2020 10:04

Quoted 38 lines · Peter Zijlstra
Quoted 16 lines

Yes, and it is read-only access. Perhaps atomic64_t is the wrong thing to use here. We could use a seqcount_latch and a shadow variable so that if a writer has been preempted, we can use the previous value. (Only kmsg_dump would need to use the lockless variant to read the value.)

void clear_seq_set(u64 val)

{
        spin_lock_irq(&clear_lock);
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[0] = val;
        raw_write_seqcount_latch(&clear_latch);
        clear_seq[1] = val;
        spin_unlock_irq(&clear_lock);
}

u64 clear_seq_get_nolock(void)

Quoted 12 lines
{
        unsigned int seq, idx;
        u64 val;

        do {
                seq = raw_read_seqcount_latch(&clear_latch);
                idx = seq & 0x1;
                val = clear_seq[idx];
        } while (read_seqcount_latch_retry(&clear_latch, seq));

        return val;
}

That's overly complicated.

If you're going to double the storage you can simply do:

	seq = val
	smp_wmb();
	seq_copy = val;
Quoted 7 lines

vs

	do {
		tmp = seq_copy;
		smp_rmb();
		val = seq;
	} while (val != tmp);
Quoted 3 lines

That will not work. We are talking about a situation where the writer is preempted. So seq will never equal seq_copy in that situation. I expect that the seqcount_latch is necessary.

Is the value just being incremented??
If so you can do:

	seq_hi_0 = val >> 32;
	smp_wmb();
	seq_lo = val;
	smp_wmb();
	seq_hi_1 = val >> 32;

Then the reader can assume that seq_lo is zero if seq_h1_0 and seq_hi_1 differ.

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)

#14 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

In reply to Petr Mladek
Quoted 6 lines · Petr Mladek
Quoted 5 lines · John Ogness

Currently @clear_seq access is protected by @logbuf_lock. Once @logbuf_lock is removed some other form of synchronization will be required. Change the type of @clear_seq to atomic64_t to provide the synchronization.

Quoted 13 lines

kernel/printk/printk.c EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer); · line 3421

Quoted 10 lines
kernel/printk/printk.c +1 -1
index fc5e3a7d6d89..e9018c4e1b66 100644
@@ -3412,7 +3418,7 @@ EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
  */
 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
 {
-	dumper->cur_seq = clear_seq;
+	dumper->cur_seq = atomic64_read(&clear_seq);

Sigh, atomic64_read() uses a spin lock in the generic implementation that is used on some architectures.

Oh... So on those archs prb is not lockless in fact, it actually takes the spin_lock each time we read the descriptor state?

	desc_read()
	  atomic_long_read(state_var)
	    atomic64_read()
	      raw_spin_lock_irqsave(lock, flags)
	        << NMI panic >>

Am I missing something?

	-ss
author maintainer
#15 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 6 lines · Sergey Senozhatsky
Quoted 2 lines

Sigh, atomic64_read() uses a spin lock in the generic implementation that is used on some architectures.

Oh... So on those archs prb is not lockless in fact, it actually takes the spin_lock each time we read the descriptor state?

Quoted 7 lines
	desc_read()
	  atomic_long_read(state_var)
	    atomic64_read()
	      raw_spin_lock_irqsave(lock, flags)
	        << NMI panic >>

Am I missing something?

For the state variable we chose atomic_long_t instead of atomic64_t for this reason. atomic_long_t operations are available atomically on all architectures. However, for clear_seq we need 64-bit (even on 32-bit machines). The seqcount_latch is an excellent solution here since clear_seq does not require lockless writers.

John Ogness

#16 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 13 lines · John Ogness
Quoted 12 lines · Sergey Senozhatsky
Quoted 2 lines

Sigh, atomic64_read() uses a spin lock in the generic implementation that is used on some architectures.

Oh... So on those archs prb is not lockless in fact, it actually takes the spin_lock each time we read the descriptor state?

	desc_read()
	  atomic_long_read(state_var)
	    atomic64_read()
	      raw_spin_lock_irqsave(lock, flags)
	        << NMI panic >>
Quoted 5 lines
Quoted 1 line

Am I missing something?

For the state variable we chose atomic_long_t instead of atomic64_t for this reason. atomic_long_t operations are available atomically on all architectures.

Right. Looking more at Kconfigs, it seems that when atomic_long_t is atomic64 (64BIT) then GENERIC_ATOMIC64 is not selected. Those archs that select GENERIC_ATOMIC64 unconditionally all seem to be 32-bit.

Thanks.

	-ss
#17 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

In reply to John Ogness
Quoted 3 lines · John Ogness

For the state variable we chose atomic_long_t instead of atomic64_t for this reason. atomic_long_t operations are available atomically on all architectures.

Please put on your eye cancer gear and inspect the atomic implementation of PA-RISC, Sparc32, feh, I forgot who else.

Those SMP capable architectures are gifted with just one XCHG like atomic instruction :/ Anyway, as said in the other email, they also don't have NMIs so it mostly works.

#18 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 11 lines · Peter Zijlstra
Quoted 3 lines · John Ogness

For the state variable we chose atomic_long_t instead of atomic64_t for this reason. atomic_long_t operations are available atomically on all architectures.

Please put on your eye cancer gear and inspect the atomic implementation of PA-RISC, Sparc32, feh, I forgot who else.

Those SMP capable architectures are gifted with just one XCHG like atomic instruction :/ Anyway, as said in the other email, they also don't have NMIs so it mostly works.

Hmm, wow. OK, I definitely want to look further.

When some CONFIG_DEBUG_FOO_BAR code wants to pr_err from prb->atomic_op on those archs then we deadlock in printk once again?

	-ss
#19 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 7 lines · Sergey Senozhatsky
Quoted 7 lines

Please put on your eye cancer gear and inspect the atomic implementation of PA-RISC, Sparc32, feh, I forgot who else.

Those SMP capable architectures are gifted with just one XCHG like atomic instruction :/ Anyway, as said in the other email, they also don't have NMIs so it mostly works.

PeterZ, thanks for the pointers!

Quoted 4 lines

Hmm, wow. OK, I definitely want to look further.

When some CONFIG_DEBUG_FOO_BAR code wants to pr_err from prb->atomic_op on those archs then we deadlock in printk once again?

E.g. arch/sparc/lib/atomic32.c

	spinlock_t __atomic_hash[ATOMIC_HASH_SIZE];
	atomic_foo()
	{
		spin_lock_irqsave(ATOMIC_HASH(v), flags)
		...
		spin_unlock_irqrestore(ATOMIC_HASH(v), flags);
	}

So another potential re-entry path is

	atomic_foo()
	 spin_lock_irqsave(ATOMIC_HASH(v), flags)
	  printk()
	   prb()
	    atomic_foo()
	     spin_lock_irqsave(ATOMIC_HASH(v), flags)

which can deadlock, in theory, if both atomics HASH to the same key (same spin_lock).

I wonder what else am I missing.

	-ss
#20 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 36 lines · Sergey Senozhatsky
Quoted 7 lines · Sergey Senozhatsky
Quoted 7 lines

Please put on your eye cancer gear and inspect the atomic implementation of PA-RISC, Sparc32, feh, I forgot who else.

Those SMP capable architectures are gifted with just one XCHG like atomic instruction :/ Anyway, as said in the other email, they also don't have NMIs so it mostly works.

PeterZ, thanks for the pointers!

Quoted 4 lines

Hmm, wow. OK, I definitely want to look further.

When some CONFIG_DEBUG_FOO_BAR code wants to pr_err from prb->atomic_op on those archs then we deadlock in printk once again?

E.g. arch/sparc/lib/atomic32.c

	spinlock_t __atomic_hash[ATOMIC_HASH_SIZE];
	atomic_foo()
	{
		spin_lock_irqsave(ATOMIC_HASH(v), flags)
		...
		spin_unlock_irqrestore(ATOMIC_HASH(v), flags);
	}

So another potential re-entry path is

	atomic_foo()
	 spin_lock_irqsave(ATOMIC_HASH(v), flags)
	  printk()
	   prb()
	    atomic_foo()
	     spin_lock_irqsave(ATOMIC_HASH(v), flags)
Quoted 2 lines

which can deadlock, in theory, if both atomics HASH to the same key (same spin_lock).

Yep, but see the 'mostly' in the 'they mostly work'. Given the limitiations of these architectures there's really only so much you can do.

#21 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 9 lines · Peter Zijlstra
Quoted 9 lines

So another potential re-entry path is

	atomic_foo()
	 spin_lock_irqsave(ATOMIC_HASH(v), flags)
	  printk()
	   prb()
	    atomic_foo()
	     spin_lock_irqsave(ATOMIC_HASH(v), flags)
Quoted 6 lines
Quoted 2 lines

which can deadlock, in theory, if both atomics HASH to the same key (same spin_lock).

Yep, but see the 'mostly' in the 'they mostly work'. Given the limitiations of these architectures there's really only so much you can do.

Right, agreed.

Nevertheless TIL that lockless printk buffer is not always lockless. Perhaps, people that work with those archs need to also know this. I haven't checked all the archs, but if, somehow, (IF) some of them can panic the system with the atomic hash entries locked, then on those archs new printk may not be able to flush-on-panic. Because while printk iterates logbuf it may HASH to the atomic hash table entry, that will never be unlocked. So there are some changes in atomic/printk department on those archs.

	-ss
#22 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

Quoted 13 lines · Sergey Senozhatsky
Quoted 12 lines · Peter Zijlstra
Quoted 11 lines

So another potential re-entry path is

	atomic_foo()
	 spin_lock_irqsave(ATOMIC_HASH(v), flags)
	  printk()
	   prb()
	    atomic_foo()
	     spin_lock_irqsave(ATOMIC_HASH(v), flags)

which can deadlock, in theory, if both atomics HASH to the same key (same spin_lock).

Quoted 8 lines
Quoted 3 lines

Yep, but see the 'mostly' in the 'they mostly work'. Given the limitiations of these architectures there's really only so much you can do.

Right, agreed.

Nevertheless TIL that lockless printk buffer is not always lockless. Perhaps, people that work with those archs need to also know this.

Last time I broke them, they were aware they're 'special' and IIRC they're mostly just limping along on prayers.

Quoted 6 lines

I haven't checked all the archs, but if, somehow, (IF) some of them can panic the system with the atomic hash entries locked, then on those archs new printk may not be able to flush-on-panic. Because while printk iterates logbuf it may HASH to the atomic hash table entry, that will never be unlocked. So there are some changes in atomic/printk department on those archs.

Yeah, so I wouldn't put too much effort into thinking about it. Hopefully we can eventually delete these architectures and really forget they exist.

#23 lore raw

Re: [PATCH next v2 2/3] printk: change @clear_seq to atomic64_t

In reply to Sergey Senozhatsky
Quoted 21 lines · Sergey Senozhatsky
Quoted 6 lines · Petr Mladek
Quoted 5 lines · John Ogness

Currently @clear_seq access is protected by @logbuf_lock. Once @logbuf_lock is removed some other form of synchronization will be required. Change the type of @clear_seq to atomic64_t to provide the synchronization.

Quoted 13 lines

kernel/printk/printk.c EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer); · line 3421

Quoted 10 lines
kernel/printk/printk.c +1 -1
index fc5e3a7d6d89..e9018c4e1b66 100644
@@ -3412,7 +3418,7 @@ EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
  */
 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
 {
-	dumper->cur_seq = clear_seq;
+	dumper->cur_seq = atomic64_read(&clear_seq);

Sigh, atomic64_read() uses a spin lock in the generic implementation that is used on some architectures.

Quoted 2 lines

Oh... So on those archs prb is not lockless in fact, it actually takes the spin_lock each time we read the descriptor state?

Yeah, many 32bit archs cannot natively do 64bit atomics and get to use the horrible hashed spinlock crap.

But it gets even worse, we have a few architectures that cannot do atomics _at_all_ and _always_ use the horrible hashed spinlock crap for all atomics, even native word length ones.

I consider these architectures broken crap, and they work mostly by accident than anything else, but we have them :/ The good new is that they don't have NMIs either, so that helps.

author maintainer
#24 lore raw

PATCH v2 3/3 printk: remove logbuf_lock, add syslog_lock

In reply to John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

This means that printk_nmi_direct and printk_safe_flush_on_panic() no longer need to acquire any lock to run.

The global variables @syslog_seq, @syslog_partial, @syslog_time were also protected by @logbuf_lock. Introduce @syslog_lock to protect these.

@console_seq, @exclusive_console_stop_seq, @console_dropped are protected by @console_lock.

Without @logbuf_lock it is no longer possible to use the single static buffer for temporarily sprint'ing the message. Instead, use vsnprintf() to determine the length and perform the real vscnprintf() using the area reserved from the ringbuffer. This leads to suboptimal packing of the message data, but will result in less wasted storage than multiple per-cpu buffers to support lockless temporary sprint'ing.

---
 include/linux/printk.h      |   1 +
 kernel/printk/internal.h    |   4 +-
 kernel/printk/printk.c      | 285 +++++++++++++++++++-----------------
 kernel/printk/printk_safe.c |  18 +--
 4 files changed, 157 insertions(+), 151 deletions(-)
include/linux/printk.h +1 -0
index fe7eb2351610..6d8f844bfdff 100644
@@ -45,6 +45,7 @@ static inline const char *printk_skip_headers(const char *buffer)
 }
 
 #define CONSOLE_EXT_LOG_MAX	8192
+#define CONSOLE_LOG_MAX		1024
 
 /* printk's without a loglevel use this.. */
 #define MESSAGE_LOGLEVEL_DEFAULT CONFIG_MESSAGE_LOGLEVEL_DEFAULT
kernel/printk/internal.h +1 -3
index 3a8fd491758c..e7acc2888c8e 100644
@@ -12,8 +12,6 @@
 
 #define PRINTK_NMI_CONTEXT_OFFSET	0x010000000
 
-extern raw_spinlock_t logbuf_lock;
-
 __printf(4, 0)
 int vprintk_store(int facility, int level,
 		  const struct dev_printk_info *dev_info,
@@ -59,7 +57,7 @@ void defer_console_output(void);
 __printf(1, 0) int vprintk_func(const char *fmt, va_list args) { return 0; }
 
 /*
- * In !PRINTK builds we still export logbuf_lock spin_lock, console_sem
+ * In !PRINTK builds we still export console_sem
  * semaphore and some of console functions (console_unlock()/etc.), so
  * printk-safe must preserve the existing local IRQ guarantees.
  */
kernel/printk/printk.c +153 -132

645 lines not on this page · raw message

kernel/printk/printk_safe.c +2 -16
index a0e6f746de6c..7248b6e3df6c 100644
@@ -266,18 +266,6 @@ void printk_safe_flush(void)
  */
 void printk_safe_flush_on_panic(void)
 {
-	/*
-	 * Make sure that we could access the main ring buffer.
-	 * Do not risk a double release when more CPUs are up.
-	 */
-	if (raw_spin_is_locked(&logbuf_lock)) {
-		if (num_online_cpus() > 1)
-			return;
-
-		debug_locks_off();
-		raw_spin_lock_init(&logbuf_lock);
-	}
-
 	printk_safe_flush();
 }
 
@@ -371,17 +359,15 @@ __printf(1, 0) int vprintk_func(const char *fmt, va_list args)
 	 * Try to use the main logbuf even in NMI. But avoid calling console
 	 * drivers that might have their own locks.
 	 */
-	if ((this_cpu_read(printk_context) & PRINTK_NMI_DIRECT_CONTEXT_MASK) &&
-	    raw_spin_trylock(&logbuf_lock)) {
+	if ((this_cpu_read(printk_context) & PRINTK_NMI_DIRECT_CONTEXT_MASK)) {
 		int len;
 
 		len = vprintk_store(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
-		raw_spin_unlock(&logbuf_lock);
 		defer_console_output();
 		return len;
 	}
 
-	/* Use extra buffer in NMI when logbuf_lock is taken or in safe mode. */
+	/* Use extra buffer in NMI or in safe mode. */
 	if (this_cpu_read(printk_context) & PRINTK_NMI_CONTEXT_MASK)
 		return vprintk_nmi(fmt, args);
 
Signature · 1 line
2.20.1
#25 lore raw

Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 5 lines · John Ogness
kernel/printk/printk.c +4 -0
+#ifdef CONFIG_PRINTK_NMI
+#define NUM_RECURSION_CTX 2
+#else
+#define NUM_RECURSION_CTX 1

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1827

Quoted 10 lines
kernel/printk/printk.c +10 -0
+#endif
+
+struct printk_recursion {
+	char	count[NUM_RECURSION_CTX];
+};
+
+static DEFINE_PER_CPU(struct printk_recursion, percpu_printk_recursion);
+static char printk_recursion_count[NUM_RECURSION_CTX];
+
+static char *get_printk_count(void)

A nit: I think get_foo() has some sort of special meaning and one would expect that there should be put_foo() as well, and that those have something to do with the ref counting.

Quoted 11 lines
kernel/printk/printk.c +11 -0
+{
+	struct printk_recursion *rec;
+	char *count;
+
+	if (!printk_percpu_data_ready()) {
+		count = &printk_recursion_count[0];
+	} else {
+		rec = this_cpu_ptr(&percpu_printk_recursion);
+
+		count = &rec->count[0];
+	}

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1848

Quoted 10 lines
kernel/printk/printk.c +10 -0
+
+#ifdef CONFIG_PRINTK_NMI
+	if (in_nmi())
+		count++;
+#endif
+
+	return count;
+}
+
+static bool printk_enter(unsigned long *flags)

This better explicitly state that it disables local IRQs

printk_enter_irqsave()

I'm not very certain that printk_enter/printk_exit are best names:

	if (!printk_enter())
		return;

Maybe it can spell out why we couldn't enter printk so the function name can contain recursion_limit or something.

Quoted 6 lines
kernel/printk/printk.c +6 -0
+{
+	char *count;
+
+	local_irq_save(*flags);
+	count = get_printk_count();
+	/* Only 1 level of recursion allowed. */

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1864

Quoted 10 lines
kernel/printk/printk.c +10 -0
+	if (*count > 1) {
+		local_irq_restore(*flags);
+		return false;
+	}
+	(*count)++;
+
+	return true;
+}
+
+static void printk_exit(unsigned long flags)

This enables local IRQs, so

printk_exit_irqrestore()

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1871

Quoted 7 lines
kernel/printk/printk.c +7 -0
+{
+	char *count;
+
+	count = get_printk_count();
+	(*count)--;
+	local_irq_restore(flags);
+}
	-ss
author maintainer
#26 lore raw

Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 5 lines · Sergey Senozhatsky
Quoted 1 line

+static char *get_printk_count(void)

A nit: I think get_foo() has some sort of special meaning and one would expect that there should be put_foo() as well, and that those have something to do with the ref counting.

OK. How about:

static char *printk_recursion_counter(void)

?

Quoted 6 lines
Quoted 1 line

+static bool printk_enter(unsigned long *flags)

This better explicitly state that it disables local IRQs

printk_enter_irqsave()

Quoted 7 lines

I'm not very certain that printk_enter/printk_exit are best names:

	if (!printk_enter())
		return;

Maybe it can spell out why we couldn't enter printk so the function name can contain recursion_limit or something.

printk_recurse_irqsave() ?

I would prefer printk_enter_irqsave() and just add comments that say it is checking the recursion level. It is only used in one place.

Quoted 5 lines
Quoted 1 line

+static void printk_exit(unsigned long flags)

This enables local IRQs, so

printk_exit_irqrestore()

Yes, I like that.

John Ogness

maintainer
#27 lore raw

devkmsg: was [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

In reply to John Ogness
Quoted 2 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

I am going to split the feedback into few mails. It might make sense to split also this patch into few more pieces that would remove the lock from a particular interface.

kernel/printk/printk.c static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence) · line 788

Quoted 9 lines
kernel/printk/printk.c +0 -1
index e9018c4e1b66..7385101210be 100644
@@ -785,7 +749,6 @@ static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
 	if (offset)
 		return -ESPIPE;
 
-	logbuf_lock_irq();

user->seq manipulation is not longer safe from the atomicity point of view.

One solution would be to use atomic variable in struct devkmsg_user(). Another solution would be to synchronize it with user->lock like we do in devkmsg_read().

user->lock looks like an overhead. But it actually would make sense to prevent seek in the middle of a read.

kernel/printk/printk.c static __poll_t devkmsg_poll(struct file *file, poll_table *wait) · line 785

Quoted 9 lines
kernel/printk/printk.c +0 -1
 	switch (whence) {
 	case SEEK_SET:
 		/* the first record */
@@ -820,7 +782,6 @@ static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
 
 	poll_wait(file, &log_wait, wait);
 
-	logbuf_lock_irq();
 	if (prb_read_valid(prb, user->seq, NULL)) {

Same here. The atomicity of user->seq read/write is not guaranteed.

kernel/printk/printk.c static __poll_t devkmsg_poll(struct file *file, poll_table *wait) · line 787

Quoted 2 lines
kernel/printk/printk.c +0 -0
 		/* return error when data has vanished underneath us */
 		if (user->seq < prb_first_valid_seq(prb))

Best Regards,
Petr

author maintainer
#28 lore raw

Re: devkmsg: was [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 5 lines · Petr Mladek
Quoted 2 lines

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

It might make sense to split also this patch into few more pieces that would remove the lock from a particular interface.

OK.

Quoted 13 lines

kernel/printk/printk.c static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence) · line 788

Quoted 9 lines
kernel/printk/printk.c +0 -1
index e9018c4e1b66..7385101210be 100644
@@ -785,7 +749,6 @@ static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
 	if (offset)
 		return -ESPIPE;
 
-	logbuf_lock_irq();

user->seq manipulation is not longer safe from the atomicity point of view.

Quoted 6 lines

One solution would be to use atomic variable in struct devkmsg_user(). Another solution would be to synchronize it with user->lock like we do in devkmsg_read().

user->lock looks like an overhead. But it actually would make sense to prevent seek in the middle of a read.

I would prefer using atomic64_t. Using user->lock could introduce some wacky regression.

Quoted 11 lines

kernel/printk/printk.c static __poll_t devkmsg_poll(struct file *file, poll_table *wait) · line 785

Quoted 9 lines
kernel/printk/printk.c +0 -1
 	switch (whence) {
 	case SEEK_SET:
 		/* the first record */
@@ -820,7 +782,6 @@ static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
 
 	poll_wait(file, &log_wait, wait);
 
-	logbuf_lock_irq();
 	if (prb_read_valid(prb, user->seq, NULL)) {

Same here. The atomicity of user->seq read/write is not guaranteed.

Right.

John Ogness

maintainer
#29 lore raw

Re: devkmsg: was [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 18 lines · John Ogness
Quoted 17 lines · Petr Mladek

kernel/printk/printk.c static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence) · line 788

Quoted 9 lines
kernel/printk/printk.c +0 -1
index e9018c4e1b66..7385101210be 100644
@@ -785,7 +749,6 @@ static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
 	if (offset)
 		return -ESPIPE;
 
-	logbuf_lock_irq();

user->seq manipulation is not longer safe from the atomicity point of view.

One solution would be to use atomic variable in struct devkmsg_user(). Another solution would be to synchronize it with user->lock like we do in devkmsg_read().

Quoted 5 lines
Quoted 2 lines

user->lock looks like an overhead. But it actually would make sense to prevent seek in the middle of a read.

I would prefer using atomic64_t. Using user->lock could introduce some wacky regression.

OK, fair enough. User space might do crazy stuff.

Best Regards,
Petr

maintainer
#30 lore raw

syslog: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

In reply to John Ogness
Quoted 15 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

kernel/printk/printk.c +0 -1
@@ -1490,19 +1444,30 @@ static int syslog_print_all(char __user *buf, int size, bool clear)
 		return -ENOMEM;
 
 	time = printk_time;
-	logbuf_lock_irq();
 	clr_seq = atomic64_read(&clear_seq);
 
 	/*
 	 * Find first record that fits, including all following records,
 	 * into the user-provided buffer for this dump.

kernel/printk/printk.c static int syslog_print_all(char __user *buf, int size, bool clear) · line 1460

Quoted 10 lines
kernel/printk/printk.c +5 -1
 	 */
+
 	prb_for_each_info(clr_seq, prb, seq, &info, &line_count)
 		len += get_record_print_text_size(&info, line_count, true, time);
 
-	/* move first record forward until length fits into the buffer */
+	/*
+	 * Keep track of the latest in case new records are coming in fast
+	 * and overwriting the older records.
+	 */

"overwriting the older records" sounds like the code is somehow able to remove the overwritten records from "len". But it is not true.

kernel/printk/printk.c static int syslog_print_all(char __user *buf, int size, bool clear) · line 1468

Quoted 8 lines
kernel/printk/printk.c +8 -0
+	newest_seq = seq;
+
+	/*
+	 * Move first record forward until length fits into the buffer. This
+	 * is a best effort attempt. If @newest_seq is reached because the
+	 * ringbuffer is wrapping too fast, just start filling the buffer
+	 * from there.
+	 */

It might be that I do not understand English well. But "start filling the buffer from there" sounds like we start filling the buffer from "newest_seq".

What about the following?

/*
* Move first record forward until length fits into the buffer.
* Ignore newest messages that were not counted in the above
* cycle. Messages might appear and get lost in the meantime.
* This is the best effort that prevents an infinite loop. */
newest_seq = seq;

kernel/printk/printk.c int do_syslog(int type, char __user *buf, int len, int source) · line 1534

Quoted 13 lines
kernel/printk/printk.c +4 -1
 	prb_for_each_info(clr_seq, prb, seq, &info, &line_count) {
-		if (len <= size)
+		if (len <= size || info.seq > newest_seq)
 			break;
 		len -= get_record_print_text_size(&info, line_count, true, time);
 	}
@@ -1568,8 +1529,11 @@ int do_syslog(int type, char __user *buf, int len, int source)
 			return 0;
 		if (!access_ok(buf, len))
 			return -EFAULT;
+		spin_lock_irq(&syslog_lock);
+		seq = syslog_seq;
+		spin_unlock_irq(&syslog_lock);

It would deserve a comment that the locking is needed to guarantee atomicity of the operation.

Quoted 7 lines
kernel/printk/printk.c +1 -1
 		error = wait_event_interruptible(log_wait,
-				prb_read_valid(prb, syslog_seq, NULL));
+				prb_read_valid(prb, seq, NULL));
 		if (error)
 			return error;
 		error = syslog_print(buf, len);

kernel/printk/printk.c void register_console(struct console *newcon) · line 2859

Quoted 9 lines
kernel/printk/printk.c +1 -5
@@ -2809,11 +2856,7 @@ void register_console(struct console *newcon)
 		nr_ext_console_drivers++;
 
 	if (newcon->flags & CON_PRINTBUFFER) {
-		/*
-		 * console_unlock(); will print out the buffered messages
-		 * for us.
-		 */
-		logbuf_lock_irqsave(flags);
+		spin_lock_irqsave(&syslog_lock, flags);

We should take the lock only around assigning syslog_seq. And add a comment that it guarantees atomic update.

kernel/printk/printk.c void register_console(struct console *newcon) · line 2875

Quoted 12 lines
kernel/printk/printk.c +1 -1
 		/*
 		 * We're about to replay the log buffer.  Only do this to the
 		 * just-registered console to avoid excessive message spam to
@@ -2826,7 +2869,7 @@ void register_console(struct console *newcon)
 		exclusive_console = newcon;
 		exclusive_console_stop_seq = console_seq;
 		console_seq = syslog_seq;
-		logbuf_unlock_irqrestore(flags);
+		spin_unlock_irqrestore(&syslog_lock, flags);
 	}
 	console_unlock();
 	console_sysfs_notify();

Best Regards,
Petr

author maintainer
#31 lore raw

Re: syslog: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 21 lines · Petr Mladek
Quoted 20 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

kernel/printk/printk.c +1 -1
@@ -1490,19 +1444,30 @@ static int syslog_print_all(char __user *buf, int size, bool clear)
 		return -ENOMEM;
 
 	time = printk_time;
-	logbuf_lock_irq();
 	clr_seq = atomic64_read(&clear_seq);
 
 	/*
 	 * Find first record that fits, including all following records,
 	 * into the user-provided buffer for this dump.
 	 */
+
 	prb_for_each_info(clr_seq, prb, seq, &info, &line_count)
 		len += get_record_print_text_size(&info, line_count, true, time);
 
Quoted 5 lines

kernel/printk/printk.c static int syslog_print_all(char __user *buf, int size, bool clear) · line 1460

Quoted 5 lines
kernel/printk/printk.c +4 -1
-	/* move first record forward until length fits into the buffer */
+	/*
+	 * Keep track of the latest in case new records are coming in fast
+	 * and overwriting the older records.
+	 */

Your suggestion to merge this and the next comment block is fine.

Quoted 15 lines

kernel/printk/printk.c static int syslog_print_all(char __user *buf, int size, bool clear) · line 1468

Quoted 8 lines
kernel/printk/printk.c +8 -0
+	newest_seq = seq;
+
+	/*
+	 * Move first record forward until length fits into the buffer. This
+	 * is a best effort attempt. If @newest_seq is reached because the
+	 * ringbuffer is wrapping too fast, just start filling the buffer
+	 * from there.
+	 */

It might be that I do not understand English well. But "start filling the buffer from there" sounds like we start filling the buffer from "newest_seq".

What about the following?

Quoted 7 lines

/*
* Move first record forward until length fits into the buffer.
* Ignore newest messages that were not counted in the above
* cycle. Messages might appear and get lost in the meantime.
* This is the best effort that prevents an infinite loop. */
newest_seq = seq;

OK.

Quoted 8 lines
Quoted 8 lines
kernel/printk/printk.c +1 -1
 	prb_for_each_info(clr_seq, prb, seq, &info, &line_count) {
-		if (len <= size)
+		if (len <= size || info.seq > newest_seq)
 			break;
 		len -= get_record_print_text_size(&info, line_count, true, time);
 	}
@@ -1568,8 +1529,11 @@ int do_syslog(int type, char __user *buf, int len, int source)
 			return 0;
Quoted 8 lines

kernel/printk/printk.c int do_syslog(int type, char __user *buf, int len, int source) · line 1534

Quoted 5 lines
kernel/printk/printk.c +3 -0
 		if (!access_ok(buf, len))
 			return -EFAULT;
+		spin_lock_irq(&syslog_lock);
+		seq = syslog_seq;
+		spin_unlock_irq(&syslog_lock);

It would deserve a comment that the locking is needed to guarantee atomicity of the operation.

OK.

Quoted 9 lines
Quoted 9 lines
kernel/printk/printk.c +1 -1
 		error = wait_event_interruptible(log_wait,
-				prb_read_valid(prb, syslog_seq, NULL));
+				prb_read_valid(prb, seq, NULL));
 		if (error)
 			return error;
 		error = syslog_print(buf, len);
@@ -2809,11 +2856,7 @@ void register_console(struct console *newcon)
 		nr_ext_console_drivers++;
 
Quoted 10 lines

kernel/printk/printk.c void register_console(struct console *newcon) · line 2859

Quoted 7 lines
kernel/printk/printk.c +1 -5
 	if (newcon->flags & CON_PRINTBUFFER) {
-		/*
-		 * console_unlock(); will print out the buffered messages
-		 * for us.
-		 */
-		logbuf_lock_irqsave(flags);
+		spin_lock_irqsave(&syslog_lock, flags);

We should take the lock only around assigning syslog_seq. And add a comment that it guarantees atomic update.

OK. So you just want "exclusive_console = newcon;" moved outside the critical section.

Quoted 4 lines
Quoted 4 lines
kernel/printk/printk.c +0 -0
 		/*
 		 * We're about to replay the log buffer.  Only do this to the
 		 * just-registered console to avoid excessive message spam to
@@ -2826,7 +2869,7 @@ void register_console(struct console *newcon)
Quoted 8 lines

kernel/printk/printk.c void register_console(struct console *newcon) · line 2875

Quoted 8 lines
kernel/printk/printk.c +1 -1
 		exclusive_console = newcon;
 		exclusive_console_stop_seq = console_seq;
 		console_seq = syslog_seq;
-		logbuf_unlock_irqrestore(flags);
+		spin_unlock_irqrestore(&syslog_lock, flags);
 	}
 	console_unlock();
 	console_sysfs_notify();

John Ogness

maintainer
#32 lore raw

Re: syslog: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 21 lines · John Ogness
Quoted 9 lines · Petr Mladek
Quoted 8 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

kernel/printk/printk.c +0 -0
@@ -2809,11 +2856,7 @@ void register_console(struct console *newcon)
 		nr_ext_console_drivers++;
 
Quoted 10 lines

kernel/printk/printk.c void register_console(struct console *newcon) · line 2859

Quoted 7 lines
kernel/printk/printk.c +1 -5
 	if (newcon->flags & CON_PRINTBUFFER) {
-		/*
-		 * console_unlock(); will print out the buffered messages
-		 * for us.
-		 */
-		logbuf_lock_irqsave(flags);
+		spin_lock_irqsave(&syslog_lock, flags);

We should take the lock only around assigning syslog_seq. And add a comment that it guarantees atomic update.

Quoted 2 lines

OK. So you just want "exclusive_console = newcon;" moved outside the critical section.

Exactly, I would like to make it clear that it synchronizes only the single assignment. Otherwise, people might get wrong assumption.

I know that there is a comment describing the scope of each lock. But people might miss it or do not search for it at all.

Best Regards,
Petr

maintainer
#33 lore raw

recursion handling: Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

In reply to John Ogness

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1812

Quoted 8 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

kernel/printk/printk.c +0 -0
@@ -1847,6 +1811,65 @@ static void call_console_drivers(const char *ext_text, size_t ext_len,
 	}
 }

The recursion-related code needs some explanation or we should do it another way. I spent quite some time on it and I am still not sure that I understand it. Let me describe how I understand it.

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1818

Quoted 5 lines
kernel/printk/printk.c +5 -0
+#ifdef CONFIG_PRINTK_NMI
+#define NUM_RECURSION_CTX 2
+#else
+#define NUM_RECURSION_CTX 1
+#endif

OK, the number of context is limited because interrupts are disabled inside print_enter()/printk_exit(). It is basically the same reason why we have only two printk_safe buffers (NNI + other contexts).

What is the exact reason to disable interrupts around the entire vprintk_store(), please? It should get documented.

One reason is the use of per-cpu variables. Alternative solution would be to store printk_context into task_struct. Well, I am not sure if "current" task is available during early boot. But it might solve problems with per-cpu variables that are not working during early boot.

That said, I am not sure if it is worth it.

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len,

Quoted 7 lines
kernel/printk/printk.c +6 -0
+
+struct printk_recursion {
+	char	count[NUM_RECURSION_CTX];
+};
 
+static DEFINE_PER_CPU(struct printk_recursion, percpu_printk_recursion);
+static char printk_recursion_count[NUM_RECURSION_CTX];

This is pretty confusing. The array is hidden in a struct when per-cpu variables are used. And a naked array is used for early boot.

Is the structure really needed? What about?

static DEFINE_PER_CPU(char [PRINTK_CTX_NUM], printk_count); static char printk_count_early[NUM_RECURSION_CTX];

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1833

Quoted 8 lines
kernel/printk/printk.c +8 -0
+
+static char *get_printk_count(void)
+{
+	struct printk_recursion *rec;
+	char *count;
+
+	if (!printk_percpu_data_ready()) {
+		count = &printk_recursion_count[0];

I see why you avoided per-cpu variables for early boot. I am just curious how printk_context variable works these days. It is used by any printk(), including early code, see vprintk_func().

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1843

Quoted 10 lines
kernel/printk/printk.c +10 -0
+	} else {
+		rec = this_cpu_ptr(&percpu_printk_recursion);
+
+		count = &rec->count[0];
+	}
+
+#ifdef CONFIG_PRINTK_NMI
+	if (in_nmi())
+		count++;
+#endif

This is extremely confusing. It is far from obvious that the pointer and not the value is incremented.

If we really need this to avoid per-cpu variables during early boot then a more clear implementation would be:

char *get_printk_counter_by_ctx()

{
	int ctx = 0;

	if (in_nmi)
		ctx = 1;

	if (!printk_percpu_data_ready())
		return &printk_count_early[ctx];

	return this_cpu_ptr(printk_count[ctx]);
}

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1854

Quoted 11 lines
kernel/printk/printk.c +11 -0
+
+	return count;
+}
+
+static bool printk_enter(unsigned long *flags)
+{
+	char *count;
+
+	local_irq_save(*flags);
+	count = get_printk_count();
+	/* Only 1 level of recursion allowed. */

We should allow at least some level of recursion. Otherwise, we would not see warnings printed from vsprintf code.

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1862

Quoted 8 lines
kernel/printk/printk.c +8 -0
+	if (*count > 1) {
+		local_irq_restore(*flags);
+		return false;
+	}
+	(*count)++;
+
+	return true;
+}

This should be unified with printk_context, printk_nmi_enter(), printk_nmi_exit(). It does not make sense to have two separate printk context counters.

Or is there any plan to remove printk_safe and printk_context?

BTW: I prefer to use the bitmask approach. It allows to check the normal context by a single operation (no bit is set). There is no need to go through all counters.

Note that we need at least one more context for gdb.

Best Regards,
Petr

#34 lore raw

Re: recursion handling: Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

On (20/12/04 17:10), Petr Mladek wrote:
[..]

Quoted 13 lines

char *get_printk_counter_by_ctx()

{
	int ctx = 0;

	if (in_nmi)
		ctx = 1;

	if (!printk_percpu_data_ready())
		return &printk_count_early[ctx];

	return this_cpu_ptr(printk_count[ctx]);
}
Quoted 14 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1854

Quoted 11 lines
kernel/printk/printk.c +11 -0
+
+	return count;
+}
+
+static bool printk_enter(unsigned long *flags)
+{
+	char *count;
+
+	local_irq_save(*flags);
+	count = get_printk_count();
+	/* Only 1 level of recursion allowed. */

We should allow at least some level of recursion. Otherwise, we would not see warnings printed from vsprintf code.

One level of recursion seems reasonable on one hand, but on the other hand I also wonder if we can get useful info from recursion levels 2 and higher. Would be great to maybe list possible scenarios. vsprintf() still call re-enter printk() -- WARN_ONCE()-s in the code -- external format specifiers handlers also can. Would we need to let two levels of recursion printk->vsprintf->printk->???->printk or one is just enough?

It also would make sense to add the lost messages counter to per-CPU recursion counter struct, to count the number of times we bailout of printk due to recursion limit. So that we'll at least have "%d recursive printk messages lost" hints.

Overall...
I wonder where does the "limit printk recursion" come from? printk_safe doesn't impose any strict limits (print_context is limited, but still) and we've been running it for years now; have we ever seen any reports of printk recursion overflows?

Quoted 4 lines
Quoted 4 lines
kernel/printk/printk.c +4 -0
+	if (*count > 1) {
+		local_irq_restore(*flags);
+		return false;
+	}
Quoted 8 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1862

Quoted 4 lines
kernel/printk/printk.c +4 -0
+	(*count)++;
+
+	return true;
+}

This should be unified with printk_context, printk_nmi_enter(), printk_nmi_exit(). It does not make sense to have two separate printk context counters.

Agreed.

Quoted 1 line

Or is there any plan to remove printk_safe and printk_context?

That's a good point. This patch set and printk_safe answer the same question in different ways, as far as I understand it. The question is "Why do we want to track printk recursion"? This patch set merely wants to, correct me if I'm wrong, avoid the very deep vprintk_store() recursion stacks (which is a subset of printk() recursion superset):

	vprintk_store()
	{
		if (!printk_enter())
			return;

		vsprintf/prb
		print_exit();
	}

And that's pretty much it, at least for the time being.

printk_safe()'s answer is - we don't want to re-enter parts of the kernel that sit in the core, behind the scenes, and that are not ready to be re-entered. Things like

	printk()
	 down_console_sem()
	  down()
	   raw_spin_lock_irqsave(&sem->lock)
	    printk()
	     down_console_sem()
	      down()
	       raw_spin_lock_irqsave(&sem->lock)

	-ss
author maintainer
#35 lore raw

Re: recursion handling: Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 10 lines · Sergey Senozhatsky
Quoted 2 lines

We should allow at least some level of recursion. Otherwise, we would not see warnings printed from vsprintf code.

One level of recursion seems reasonable on one hand, but on the other hand I also wonder if we can get useful info from recursion levels 2 and higher. Would be great to maybe list possible scenarios. vsprintf() still call re-enter printk() -- WARN_ONCE()-s in the code -- external format specifiers handlers also can. Would we need to let two levels of recursion printk->vsprintf->printk->???->printk or one is just enough?

Quoted 4 lines

It also would make sense to add the lost messages counter to per-CPU recursion counter struct, to count the number of times we bailout of printk due to recursion limit. So that we'll at least have "%d recursive printk messages lost" hints.

We do not need such a counter to be per-cpu. A global atomic_long_t would suffice. Although I am not sure if that should be separate from the @fail member of the ringbuffer.

Quoted 5 lines

Overall...
I wonder where does the "limit printk recursion" come from? printk_safe doesn't impose any strict limits (print_context is limited, but still) and we've been running it for years now; have we ever seen any reports of printk recursion overflows?

The printk code is undergoing some major changes and we have already had bugs slip into the merge window. IMHO the additional code to track the recursion does not add significant complexity or runtime overhead. I would prefer to keep it until we are finished with this major rework.

John Ogness

#36 lore raw

Re: recursion handling: Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

In reply to Petr Mladek
Quoted 3 lines · Petr Mladek

One reason is the use of per-cpu variables. Alternative solution would be to store printk_context into task_struct.

We can keep per-CPU, disable preemption and have counters for every context (task, soft/hard irq, NMI). Shouldn't be a problem

	vprintk_emit()
	{
		preempt_disable()
		vprintk_store()
		preempt_enable()

		preempt_disable()
		console_unlock()
		preempt_enable()
	}

vprintk_store() is a small fraction of console_unlock() time wise.

	-ss
author maintainer
#37 lore raw

Re: recursion handling: Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 5 lines · Sergey Senozhatsky
Quoted 2 lines

One reason is the use of per-cpu variables. Alternative solution would be to store printk_context into task_struct.

We can keep per-CPU, disable preemption and have counters for every context (task, soft/hard irq, NMI). Shouldn't be a problem

These contexts are difficult to track correctly for all the preemption models (especially when PREEMPT_RT is included). But I will look into this idea. It would be nice to keep interrupts enabled for that first vsnprintf() in vprintk_store().

John Ogness

author maintainer
#38 lore raw

Re: recursion handling: Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

In reply to Petr Mladek
Quoted 4 lines · Petr Mladek
Quoted 3 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

Quoted 9 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1812

Quoted 5 lines
kernel/printk/printk.c +0 -0
@@ -1847,6 +1811,65 @@ static void call_console_drivers(const char *ext_text, size_t ext_len,
 	}
 }

The recursion-related code needs some explanation or we should do it another way. I spent quite some time on it and I am still not sure that I understand it.

Sorry. :-/

Quoted 11 lines

Let me describe how I understand it.

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1818

Quoted 5 lines
kernel/printk/printk.c +5 -0
+#ifdef CONFIG_PRINTK_NMI
+#define NUM_RECURSION_CTX 2
+#else
+#define NUM_RECURSION_CTX 1
+#endif

OK, the number of context is limited because interrupts are disabled inside print_enter()/printk_exit(). It is basically the same reason why we have only two printk_safe buffers (NNI + other contexts).

Correct.

Quoted 2 lines

What is the exact reason to disable interrupts around the entire vprintk_store(), please? It should get documented.

It simplifies the context tracking. Also, in mainline interrupts are already disabled for all of vprintk_store(). AFAIK latencies due to logbuf_lock contention were not an issue.

Quoted 7 lines

One reason is the use of per-cpu variables. Alternative solution would be to store printk_context into task_struct. Well, I am not sure if "current" task is available during early boot. But it might solve problems with per-cpu variables that are not working during early boot.

That said, I am not sure if it is worth it.

I really don't want to touch task_struct. IMHO the usefulness of that struct is limited, considering that printk can be called from scheduling and interrupting contexts.

Quoted 11 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len,

Quoted 7 lines
kernel/printk/printk.c +6 -0
+
+struct printk_recursion {
+	char	count[NUM_RECURSION_CTX];
+};
 
+static DEFINE_PER_CPU(struct printk_recursion, percpu_printk_recursion);
+static char printk_recursion_count[NUM_RECURSION_CTX];

This is pretty confusing. The array is hidden in a struct when per-cpu variables are used. And a naked array is used for early boot.

Quoted 4 lines

Is the structure really needed? What about?

static DEFINE_PER_CPU(char [PRINTK_CTX_NUM], printk_count); static char printk_count_early[NUM_RECURSION_CTX];

OK.

Quoted 4 lines
Quoted 4 lines
kernel/printk/printk.c +4 -0
+
+static char *get_printk_count(void)
+{
+	struct printk_recursion *rec;
Quoted 8 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1833

Quoted 4 lines
kernel/printk/printk.c +4 -0
+	char *count;
+
+	if (!printk_percpu_data_ready()) {
+		count = &printk_recursion_count[0];

I see why you avoided per-cpu variables for early boot. I am just curious how printk_context variable works these days. It is used by any printk(), including early code, see vprintk_func().

IMO printk_context is serving a different purpose. With the existance of logbuf_lock, printk_context exists for the sole purpose of making sure logbuf_lock is not taken recursively or that the CPU does not spin on it in NMI context. printk_context is simply gating calls to the safe buffers.

For the lockless ringbuffer, there is no issue of taking a lock recursively or dangers from NMI. There is no need for the printk_context "gate". However, IMHO there is a real danger if a bug in printk (or its ringbuffer) lead to infinite recursion. This new recursion counter is offering safety against this scenario. Until now this scenario has been ignored. So I suppose if we are comfortable with continuing to ignore the scenario, then we don't need to track the recursion level.

To test, I triggered artificial WARNs in vsnprintf() of printk code. I found it nice to be able to see the stack trace going into printk and at the same time I was relieved that such a nested warning was not blasting the system into infinite recursion.

Quoted 18 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1843

Quoted 10 lines
kernel/printk/printk.c +10 -0
+	} else {
+		rec = this_cpu_ptr(&percpu_printk_recursion);
+
+		count = &rec->count[0];
+	}
+
+#ifdef CONFIG_PRINTK_NMI
+	if (in_nmi())
+		count++;
+#endif

This is extremely confusing. It is far from obvious that the pointer and not the value is incremented.

If we really need this to avoid per-cpu variables during early boot then a more clear implementation would be:

char *get_printk_counter_by_ctx()

Quoted 11 lines
{
	int ctx = 0;

	if (in_nmi)
		ctx = 1;

	if (!printk_percpu_data_ready())
		return &printk_count_early[ctx];

	return this_cpu_ptr(printk_count[ctx]);
}

Yes, much cleaner. Thank you.

Quoted 6 lines
Quoted 6 lines
kernel/printk/printk.c +6 -0
+
+	return count;
+}
+
+static bool printk_enter(unsigned long *flags)
+{
Quoted 8 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1854

Quoted 5 lines
kernel/printk/printk.c +5 -0
+	char *count;
+
+	local_irq_save(*flags);
+	count = get_printk_count();
+	/* Only 1 level of recursion allowed. */

We should allow at least some level of recursion. Otherwise, we would not see warnings printed from vsprintf code.

With 1 level, you will see warnings from vsprintf code. I'm not sure it makes sense to allow more than 1 level. It causes exponential logging.

Quoted 13 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1862

Quoted 8 lines
kernel/printk/printk.c +8 -0
+	if (*count > 1) {
+		local_irq_restore(*flags);
+		return false;
+	}
+	(*count)++;
+
+	return true;
+}

This should be unified with printk_context, printk_nmi_enter(), printk_nmi_exit(). It does not make sense to have two separate printk context counters.

Quoted 1 line

Or is there any plan to remove printk_safe and printk_context?

Yes, I plan to remove the safe buffers, which also removes printk_safe.c and the printk_context "gate".

Quoted 3 lines

BTW: I prefer to use the bitmask approach. It allows to check the normal context by a single operation (no bit is set). There is no need to go through all counters.

OK.

Quoted 1 line

Note that we need at least one more context for gdb.

Ah yes, thank you.

John Ogness

maintainer
#39 lore raw

Re: recursion handling: Re: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 10 lines · John Ogness
Quoted 8 lines · Petr Mladek

kernel/printk/printk.c

Quoted 5 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

kernel/printk/printk.c +0 -0

What is the exact reason to disable interrupts around the entire vprintk_store(), please? It should get documented.

Quoted 7 lines

It simplifies the context tracking. Also, in mainline interrupts are already disabled for all of vprintk_store(). AFAIK latencies due to logbuf_lock contention were not an issue.

I really don't want to touch task_struct. IMHO the usefulness of that struct is limited, considering that printk can be called from scheduling and interrupting contexts.

Fair enough. I am fine with the per-CPU variables and the disabled interrupts around vprintk_store().

Note: We should also prevent calling console_trylock() for recursive messages to avoid infinite loop or even deadlock in this part of the code.

Quoted 31 lines
Quoted 11 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len,

Quoted 7 lines
kernel/printk/printk.c +6 -0
+
+struct printk_recursion {
+	char	count[NUM_RECURSION_CTX];
+};
 
+static DEFINE_PER_CPU(struct printk_recursion, percpu_printk_recursion);
+static char printk_recursion_count[NUM_RECURSION_CTX];

This is pretty confusing. The array is hidden in a struct when per-cpu variables are used. And a naked array is used for early boot.

Quoted 4 lines

Is the structure really needed? What about?

static DEFINE_PER_CPU(char [PRINTK_CTX_NUM], printk_count); static char printk_count_early[NUM_RECURSION_CTX];

OK.

Quoted 4 lines
Quoted 4 lines
kernel/printk/printk.c +4 -0
+
+static char *get_printk_count(void)
+{
+	struct printk_recursion *rec;
Quoted 8 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1833

Quoted 4 lines
kernel/printk/printk.c +4 -0
+	char *count;
+
+	if (!printk_percpu_data_ready()) {
+		count = &printk_recursion_count[0];

I see why you avoided per-cpu variables for early boot. I am just curious how printk_context variable works these days. It is used by any printk(), including early code, see vprintk_func().

Quoted 5 lines

IMO printk_context is serving a different purpose. With the existance of logbuf_lock, printk_context exists for the sole purpose of making sure logbuf_lock is not taken recursively or that the CPU does not spin on it in NMI context. printk_context is simply gating calls to the safe buffers.

Well, both printk_count and printk_context are able to count recursion in different context. They both are used to decide how printk() will behave...

Anyway, it is not necessary to fight over words. You write below that the plan is to remove printk_safe, including printk_context. It will solve my problem.

I am fine with having both of them for some transition period. I guess that it will make our life easier, from the coding and review point of view.

Quoted 11 lines
Quoted 10 lines

kernel/printk/printk.c static void call_console_drivers(const char *ext_text, size_t ext_len, · line 1854

Quoted 7 lines
kernel/printk/printk.c +7 -0
+static bool printk_enter(unsigned long *flags)
+{
+	char *count;
+
+	local_irq_save(*flags);
+	count = get_printk_count();
+	/* Only 1 level of recursion allowed. */

We should allow at least some level of recursion. Otherwise, we would not see warnings printed from vsprintf code.

Quoted 2 lines

With 1 level, you will see warnings from vsprintf code. I'm not sure it makes sense to allow more than 1 level. It causes exponential logging.

Shame on me. I have missed that 1 level was actually enabled.

Anyway, I would like to allow 2 level recursion at least. However, for example, 5 level recursion, would be even better.

We need to know when there is problem to store the recursive/nested message. And I would rather see the same message repeated 3 times than to do not see it at all.

Note that the risk of infinite recursion is pretty low. We have most of the code called from vprintk_emit() under control. There are many pr_once() or WARN_ONCE(). The error messages have rather simple and commonly used formatting, so the risk of recursive errors in vsprintf() code is low.

Quoted 1 line
Quoted 1 line

Or is there any plan to remove printk_safe and printk_context?

I am feeling relief to read this.

Do not take me wrong. printk_safe() was really great idea and served well its purpose. But it is yet another tricky lockless code. There is another complexity with flushing the temporary buffers and handling panic(). It is nice that we could remove some of this complexity.

Best Regards,
Petr

maintainer
#40 lore raw

vprintk_store: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

In reply to John Ogness
Quoted 13 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

kernel/printk/printk.c +3 -1
@@ -1867,40 +1890,75 @@ static inline u32 printk_caller_id(void)
 		0x80000000 + raw_smp_processor_id();
 }
 
-/* Must be called under logbuf_lock. */
+static u16 printk_sprint(char *text, u16 size, int facility, enum log_flags *lflags,
+			 const char *fmt, va_list args)
+{

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1905

Quoted 10 lines
kernel/printk/printk.c +10 -0
+	char *orig_text = text;
+	u16 text_len;
+
+	text_len = vscnprintf(text, size, fmt, args);
+
+	/* Mark and strip a trailing newline. */
+	if (text_len && text[text_len - 1] == '\n') {
+		text_len--;
+		*lflags |= LOG_NEWLINE;
+	}

We reserve the space for '\n' anyway. It would make sense to just store it and remove all these LOG_NEWLINE-specific hacks.

Well, let's leave it as is now. It is still possible that people will not love this approach and we will need to format the message into some temporary buffer first.

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1907

Quoted 1 line
kernel/printk/printk.c +1 -0
+	/* Strip kernel syslog prefix. */

Syslog actually uses: <level> format. We are skipping log level and control flags here.

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1912

Quoted 5 lines
kernel/printk/printk.c +5 -0
+	if (facility == 0) {
+		while (text_len >= 2 && printk_get_level(text)) {
+			text_len -= 2;
+			text += 2;
+		}

We should avoid two completely different approaches that handle printk_level prefix.

One solution is to implement something like:

static char *parse_prefix(text, &level, &flags)

That would return pointer to the text after the prefix. And fill level and flags only when non-NULL pointers are passed.

Another solution would be to pass this information from vprintk_store(). The prefix has already been parsed after all.

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1916

Quoted 4 lines
kernel/printk/printk.c +4 -0
+
+		if (text != orig_text)
+			memmove(orig_text, text, text_len);
+	}

We should clear the freed space to make the ring buffer as human readable as possible when someone just dumps the memory.

Sigh, I have to admit that I missed the problem with prefix and trailing '\n' when I suggested to avoid the temporary buffers. This memmove() and the space wasting is pity.

Well, it is typically 3 bytes per message. And the copying would be necessary even with the temporary buffer. So, I am less convinced but I would still try to avoid the temporary buffers for now.

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1921

Quoted 5 lines
kernel/printk/printk.c +5 -0
+
+	return text_len;
+}
+
+__printf(4, 0)

Best Regards,
Petr

author maintainer
#41 lore raw

Re: vprintk_store: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 4 lines · Petr Mladek

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1907

Quoted 1 line
kernel/printk/printk.c +1 -0
+	/* Strip kernel syslog prefix. */

Syslog actually uses: <level> format. We are skipping log level and control flags here.

OK.

Quoted 9 lines

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1912

Quoted 5 lines
kernel/printk/printk.c +5 -0
+	if (facility == 0) {
+		while (text_len >= 2 && printk_get_level(text)) {
+			text_len -= 2;
+			text += 2;
+		}

We should avoid two completely different approaches that handle printk_level prefix.

Quoted 6 lines

One solution is to implement something like:

static char *parse_prefix(text, &level, &flags)

That would return pointer to the text after the prefix. And fill level and flags only when non-NULL pointers are passed.

OK.

Quoted 3 lines

Another solution would be to pass this information from vprintk_store(). The prefix has already been parsed after all.

Well, there is a vscnprintf() that happens in between and I don't think we should trust the parsed offset from the first vsnprintf().

Quoted 7 lines

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1916

Quoted 4 lines
kernel/printk/printk.c +4 -0
+
+		if (text != orig_text)
+			memmove(orig_text, text, text_len);
+	}

We should clear the freed space to make the ring buffer as human readable as possible when someone just dumps the memory.

Data blocks are currently padded and that padding is not cleared. So it is already not perfectly human readable on a raw dump.

Quoted 7 lines

Sigh, I have to admit that I missed the problem with prefix and trailing '\n' when I suggested to avoid the temporary buffers. This memmove() and the space wasting is pity.

Well, it is typically 3 bytes per message. And the copying would be necessary even with the temporary buffer. So, I am less convinced but I would still try to avoid the temporary buffers for now.

Agreed. I think this approach is better than the temporary buffers I previously used. Also, if we add a trimming feature to the ringbuffer, it will keep the ringbuffer mostly clean anyway. Something like this:

prb_rec_init_wr(&r, text_len);
prb_reserve(&e, prb, &r);
text_len = printk_sprint(&r.text_buf[0], text_len, ...); r.info->text_len = text_len;
prb_trim_rec(&e, &r); <--- try to reduce datablock size to @text_len prb_commit(&e);

I see no urgency to add such a feature. But I think we should keep it on our radar.

John Ogness

maintainer
#42 lore raw

Re: vprintk_store: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 17 lines · John Ogness
Quoted 9 lines · Petr Mladek

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1912

Quoted 5 lines
kernel/printk/printk.c +5 -0
+	if (facility == 0) {
+		while (text_len >= 2 && printk_get_level(text)) {
+			text_len -= 2;
+			text += 2;
+		}

We should avoid two completely different approaches that handle printk_level prefix.

Quoted 6 lines

One solution is to implement something like:

static char *parse_prefix(text, &level, &flags)

That would return pointer to the text after the prefix. And fill level and flags only when non-NULL pointers are passed.

Quoted 8 lines

OK.

Quoted 3 lines

Another solution would be to pass this information from vprintk_store(). The prefix has already been parsed after all.

Well, there is a vscnprintf() that happens in between and I don't think we should trust the parsed offset from the first vsnprintf().

Good point!

Quoted 10 lines
Quoted 7 lines

kernel/printk/printk.c static inline u32 printk_caller_id(void) · line 1916

Quoted 4 lines
kernel/printk/printk.c +4 -0
+
+		if (text != orig_text)
+			memmove(orig_text, text, text_len);
+	}

We should clear the freed space to make the ring buffer as human readable as possible when someone just dumps the memory.

Data blocks are currently padded and that padding is not cleared. So it is already not perfectly human readable on a raw dump.

It would be nice to clean up the padding as well. But it is a cosmetic improvement that might be done anytime later.

Quoted 10 lines
Quoted 7 lines

Sigh, I have to admit that I missed the problem with prefix and trailing '\n' when I suggested to avoid the temporary buffers. This memmove() and the space wasting is pity.

Well, it is typically 3 bytes per message. And the copying would be necessary even with the temporary buffer. So, I am less convinced but I would still try to avoid the temporary buffers for now.

Agreed. I think this approach is better than the temporary buffers I previously used.

Another motivation is that it allows to simply handle recursion/nesting. Othrewise, we would need temporary buffers for each allowed recursion level or some tricky code.

Quoted 10 lines

Also, if we add a trimming feature to the ringbuffer,
it will keep the ringbuffer mostly clean anyway. Something like this:

prb_rec_init_wr(&r, text_len);
prb_reserve(&e, prb, &r);
text_len = printk_sprint(&r.text_buf[0], text_len, ...); r.info->text_len = text_len;
prb_trim_rec(&e, &r); <--- try to reduce datablock size to @text_len prb_commit(&e);

Quoted 2 lines

I see no urgency to add such a feature. But I think we should keep it on our radar.

Yup. I thought about it as well. I agree that it is not a priority.

Best Regards,
Petr

maintainer
#43 lore raw

consoles: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

In reply to John Ogness

kernel/printk/internal.h void defer_console_output(void); · line 62

Quoted 13 lines · John Ogness

Since the ringbuffer is lockless, there is no need for it to be protected by @logbuf_lock. Remove @logbuf_lock.

kernel/printk/internal.h +1 -1
@@ -59,7 +57,7 @@ void defer_console_output(void);
 __printf(1, 0) int vprintk_func(const char *fmt, va_list args) { return 0; }
 
 /*
- * In !PRINTK builds we still export logbuf_lock spin_lock, console_sem
+ * In !PRINTK builds we still export console_sem
  * semaphore and some of console functions (console_unlock()/etc.), so
  * printk-safe must preserve the existing local IRQ guarantees.

We should revisit whether it is still needed just for console_sem. Well, I wonder why we need printk_safe at all.

kernel/printk/printk.c void console_unlock(void) · line 2492

Quoted 6 lines
kernel/printk/printk.c +0 -0
@@ -2432,7 +2490,6 @@ void console_unlock(void)
 		size_t len;
 
 		printk_safe_enter_irqsave(flags);

Why do we actually need to use the printk_safe context here? There is not longer a risk of deadlock caused by logbuf_lock. All other recursions should be prevented by console_trylock() in printk(). Do I miss anything?

Note that we still need to disable interrupts around

     console_lock_spinning_enable();
     console_lock_spinning_disable_and_check();

to make sure that printk() could busy wait for passing the console lock.

kernel/printk/printk.c void console_unlock(void) · line 2495

Quoted 4 lines
kernel/printk/printk.c +0 -1
-		raw_spin_lock(&logbuf_lock);
 skip:
 		if (!prb_read_valid(prb, console_seq, &r))
 			break;

Best Regards,
Petr

#44 lore raw

Re: consoles: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

On (20/12/04 17:19), Petr Mladek wrote:
[..]

Quoted 11 lines

kernel/printk/printk.c void console_unlock(void) · line 2492

Quoted 6 lines
kernel/printk/printk.c +0 -0
@@ -2432,7 +2490,6 @@ void console_unlock(void)
 		size_t len;
 
 		printk_safe_enter_irqsave(flags);

Why do we actually need to use the printk_safe context here? There is not longer a risk of deadlock caused by logbuf_lock. All other recursions should be prevented by console_trylock() in printk().

All semaphore functions, including down_trylock(), acquire semaphore spin_lock; and then some call into the scheduler (or other kernel core functions) under semaphore's spin_lock. For instance

	up()
	 raw_spin_lock_irqsave(&sem->lock)
	   __up()
	     wake_up_process()
	       try_to_wake_up()

	-ss
maintainer
#45 lore raw

Re: consoles: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

Quoted 14 lines · Sergey Senozhatsky

On (20/12/04 17:19), Petr Mladek wrote:
[..]

Quoted 11 lines

kernel/printk/printk.c void console_unlock(void) · line 2492

Quoted 6 lines
kernel/printk/printk.c +0 -0
@@ -2432,7 +2490,6 @@ void console_unlock(void)
 		size_t len;
 
 		printk_safe_enter_irqsave(flags);

Why do we actually need to use the printk_safe context here? There is not longer a risk of deadlock caused by logbuf_lock. All other recursions should be prevented by console_trylock() in printk().

Quoted 2 lines

All semaphore functions, including down_trylock(), acquire semaphore spin_lock;

This has a very easy solution. The patch adds a code that counts recursion level. We just must not call console_trylock() when being inside a recursive printk.

printk_safe() has two functions:

1. It allows to store messages a lockless way. This is obsoleted by the lockless ringbuffer.

2. It prevents calling consoles. We could move this check into vprintk_store(). We already have there similar check for printk_deferred().

Quoted 9 lines

and then some call into the scheduler
(or other kernel core functions) under semaphore's spin_lock. For instance

	up()
	 raw_spin_lock_irqsave(&sem->lock)
	   __up()
	     wake_up_process()
	       try_to_wake_up()

This problem is partly solved by printk_deferred(). In each case, printk_safe() does not help here.

I still do _not_ see a reason to keep printk_safe()!

Best Regards,
Petr

#46 lore raw

Re: consoles: was: [PATCH next v2 3/3] printk: remove logbuf_lock, add syslog_lock

On (20/12/07 10:50), Petr Mladek wrote:
[..]

Quoted 4 lines
Quoted 4 lines

and then some call into the scheduler
(or other kernel core functions) under semaphore's spin_lock. For instance

Quoted 8 lines
Quoted 5 lines
	up()
	 raw_spin_lock_irqsave(&sem->lock)
	   __up()
	     wake_up_process()
	       try_to_wake_up()

This problem is partly solved by printk_deferred(). In each case, printk_safe() does not help here.

printk_deferred() has never been used in all the critical code paths. So I think printk_safe does help here; it takes care of all the remaining cases, that are not "partly solved by printk_deferred()".

Quoted 1 line

I still do _not_ see a reason to keep printk_safe()!

Not sure I'm following, sorry. To put it simply - we better keep printk_safe until "new recursion prevention" >= printk_safe(). In this patch set "new recursion prevention" < printk_safe().

	-ss