Skip to content

os/kernel/mqueue: allocate messages by requested length instead of fixed MQ_MAXMSGSIZE - #7643

Open
hyunjongkim123 wants to merge 4 commits into
Samsung:masterfrom
hyunjongkim123:fix_mq
Open

hyunjongkim123 wants to merge 4 commits into
Samsung:masterfrom
hyunjongkim123:fix_mq

Conversation

@hyunjongkim123

@hyunjongkim123 hyunjongkim123 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Every message was a fixed struct mqueue_msg_s with a CONFIG_MQ_MAXMSGSIZE
byte payload embedded in it. The pre-allocated pool was made of those
structs, and when the pool ran out mq_msgalloc() took the same fixed
struct from the heap, so a task sending a few bytes still paid for the
largest message any queue may ever carry.

Restructure the message so its payload is sized when it is allocated:

  • struct mqueue_msg_s ends in a flexible payload (char mail[]) instead
    of mail[MQ_MAX_BYTES]. A message holding an n byte payload is
    MQ_MSG_SIZE(n) bytes. The pool block is walked by byte stride,
    MQ_MSG_BLOCK(n), instead of being indexed as a struct array.

  • Add CONFIG_PREALLOC_MQ_MSGSIZE, the payload capacity of the
    CONFIG_PREALLOC_MQ_MSGS pool entries. CONFIG_MQ_MAXMSGSIZE keeps its
    role as the upper bound for mq_open() msgsize and as the entry size of
    the interrupt pool, which has no heap fallback. The default is
    MQ_MAXMSGSIZE, so a board that does not set it behaves as before.

  • mq_msgalloc(msglen) takes a pool entry when msglen fits in
    CONFIG_PREALLOC_MQ_MSGSIZE and one is free. When the pool is exhausted,
    or msglen is larger than a pool entry, a task gets
    kmm_malloc(MQ_MSG_SIZE(msglen)): exactly the length requested rather
    than CONFIG_MQ_MAXMSGSIZE. An ISR still falls back to the interrupt
    pool. mq_send()/mq_timedsend() pass msglen.

Comment thread os/kernel/mqueue/mq_initialize.c Outdated

if (mqmsgblock) {
struct mqueue_msg_s *mqmsg = mqmsgblock;
FAR char *ptr = (FAR char *)mqmsgblock;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need FAR anymore.
You can remove FAR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll address it

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove all FAR in this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed it.

Comment thread os/kernel/mqueue/mq_sndinternal.c Outdated
* messages reserved for interrupt handlers.
*/

if (up_interrupt_context()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously the ISR path entered the critical section only once to check both g_msgfree and g_msgfreeirq.
In this PR, the worst case (msglen <= MQ_PREALLOC_BYTES and g_msgfree is empty in interrupt context), it enters and leaves the critical section twice.
Could we keep both lookups under a single critical section for the ISR path to avoid redundant lock/unlock overhead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. I'll restructure mq_msgalloc() so both pool lokups happen under a single critical section.

@seokhun-eom24

Copy link
Copy Markdown
Contributor

Could you update bk7239n defconfgs and rtl8730e/loadable_apps and rtl8730e/flat_apps?

@seokhun-eom24

Copy link
Copy Markdown
Contributor

Do we need to update kernel_tc about this change?

Comment thread os/kernel/mqueue/mqueue.h Outdated
uint8_t priority; /* priority of message */
size_t msglen; /* Message data length */
char mail[MQ_MAX_BYTES]; /* Message data */
char mail[1]; /* Message data (payload follows) */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed it.

…GSIZE

Every message was a fixed struct mqueue_msg_s with a CONFIG_MQ_MAXMSGSIZE
byte payload embedded in it. The pre-allocated pool was made of those
structs, and when the pool ran out mq_msgalloc() took the same fixed
struct from the heap, so a task sending a few bytes still paid for the
largest message any queue may ever carry.

Restructure the message so its payload is sized when it is allocated:

- struct mqueue_msg_s ends in a flexible payload (char mail[]) instead
  of mail[MQ_MAX_BYTES]. A message holding an n byte payload is
  MQ_MSG_SIZE(n) bytes. The pool block is walked by byte stride,
  MQ_MSG_BLOCK(n), instead of being indexed as a struct array.

- Add CONFIG_PREALLOC_MQ_MSGSIZE, the payload capacity of the
  CONFIG_PREALLOC_MQ_MSGS pool entries. CONFIG_MQ_MAXMSGSIZE keeps its
  role as the upper bound for mq_open() msgsize and as the entry size of
  the interrupt pool, which has no heap fallback. The default is
  MQ_MAXMSGSIZE, so a board that does not set it behaves as before.

- mq_msgalloc(msglen) takes a pool entry when msglen fits in
  CONFIG_PREALLOC_MQ_MSGSIZE and one is free. When the pool is exhausted,
  or msglen is larger than a pool entry, a task gets
  kmm_malloc(MQ_MSG_SIZE(msglen)): exactly the length requested rather
  than CONFIG_MQ_MAXMSGSIZE. An ISR still falls back to the interrupt
  pool. mq_send()/mq_timedsend() pass msglen.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit 0bd9be9489b499a1ca0c6f6db762e3ce4df2316f)
hyunjongkim123 and others added 3 commits December 1, 2026 11:42
Change the pre-allocated mqueue message pool to 10 messages of 256 bytes
(CONFIG_PREALLOC_MQ_MSGS=10, CONFIG_PREALLOC_MQ_MSGSIZE=256) and align
CONFIG_MQ_MAXMSGSIZE to 600 on all rtl8730e configs to optimize internal
memory usage.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Change the pre-allocated mqueue message pool to 10 messages of 256 bytes
(CONFIG_PREALLOC_MQ_MSGS=10, CONFIG_PREALLOC_MQ_MSGSIZE=256) and align
CONFIG_MQ_MAXMSGSIZE to 600 on all bk7239n configs to optimize internal
memory usage.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Change the pre-allocated mqueue message pool to 10 messages of 256 bytes
(CONFIG_PREALLOC_MQ_MSGS=10, CONFIG_PREALLOC_MQ_MSGSIZE=256) and align
CONFIG_MQ_MAXMSGSIZE to 600 on all rtl8721csm configs to optimize
internal memory usage.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@hyunjongkim123

Copy link
Copy Markdown
Contributor Author

Do we need to update kernel_tc about this change?

kernel_tc: mqueue test cases

Test case What it verifies Why this change does not affect it
tc_mqueue_mq_open_close_send_receive Sends and receives 10 messages of 31 B (maxmsg 20) and checks length and content. Also checks wakeup by signal, cancel, close and unlink. 31 B fits the 256 B pre-allocated slot. Content, length and ordering are handled exactly as before; only the slot size changes.
tc_mqueue_mq_notify Signal notification on a 15 B send, plus the error cases (NULL mqd, invalid signo, double registration, detach). Notification logic is untouched, and 15 B fits the pool slot.
tc_mqueue_mq_timedsend_timedreceive Timeout on a full queue (3+1 sends, maxmsg 3) and on an empty queue, EMSGSIZE for 33 B into a 31 B queue, and EINVAL for a NULL timeout. The checks run against the queue's own attributes before any allocation. Blocking and timeout paths are unchanged.
tc_mqueue_mq_timedsend_timedreceive_failurechecks Error returns for a NULL mqd, an expired abstime and an empty queue. All of these are argument and state checks done before message allocation.
tc_mqueue_mq_unlink The second unlink returns ENOENT. The open/unlink path is not modified.
tc_mqueue_mq_getattr mq_maxmsg and mq_msgsize read back as set (20 / 31), plus NULL-argument errors. Queue attributes are stored as before. The mq_open limit (CONFIG_MQ_MAXMSGSIZE = 600) only widened.
tc_mqueue_mq_setattr Toggling O_NONBLOCK and reading back the old flags, plus NULL-argument errors. Flag handling is not modified.

No test case references the message struct, mq_msgalloc() or the pool. They use only the POSIX mq API, so the allocation source (pool or heap) is not visible to them.

Could you update bk7239n defconfgs and rtl8730e/loadable_apps and rtl8730e/flat_apps?

fixed it

@seokhun-eom24

Copy link
Copy Markdown
Contributor

🤖 AI Code Review · 0f558827ba21

PR Summary: The PR introduces a configurable pre-allocated message size (CONFIG_PREALLOC_MQ_MSGSIZE), changing mqueue_msg_s.mail to a flexible array member. mq_msgalloc now takes a payload length, uses exact-size heap allocation for oversized messages, and correctly selects between the general and interrupt pools based on context and size. All callers and macros are updated consistently, and the memory management logic is sound.

📋 Findings Overview (0 issues)

✅ Checked with no findings: Memory Leaks, Crashes, Hangs, Correctness


if (ret == OK) {
mqmsg = mq_msgalloc();
mqmsg = mq_msgalloc(msglen);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When mq_msgalloc returns ERROR, mq_timedsend will return OK.
Could you check this scenario?

Comment thread os/kernel/Kconfig

config PREALLOC_MQ_MSGSIZE
int "Payload size of pre-allocated messages"
default MQ_MAXMSGSIZE

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add range in this config and MQ_MAXMSGSIZE.
Because mq_msgblockalloc can accept uint16_t parameter type.

@mangeshraut712 mangeshraut712 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against the merge-base. Not an approval — that's for a maintainer.

The allocator rework is correct and the overflow-safety chain closes. The one thing I'd want a maintainer to see before merging is the memory-layout change on 24 defconfigs, which the description doesn't cover.

Size arithmetic is safe — the chain is closed

MQ_MSG_SIZE(n) = offsetof(mail) + n could wrap for an n near SIZE_MAX, so I traced every caller:

  • mq_open → mq_msgqalloc.c:121 rejects attr->mq_msgsize > MQ_MAX_BYTES, bounding maxmsgsize.
  • mq_verifysend → mq_sndinternal.c:144 rejects msglen > mqdes->msgq->maxmsgsize.
  • Both send paths (mq_send.c:175, mq_timedsend.c:258/314) call mq_verifysend before mq_msgalloc(msglen).

So msglen ≤ MQ_MAX_BYTES on every path into MQ_MSG_SIZE(), and the pool stride MQ_MSG_BLOCK(bufsize) × nmsgs is a uint16_t count times a small stride — no overflow. mq_msgalloc itself doesn't re-check, which is fine given the above but worth a one-line comment pointing at mq_verifysend as the guard.

Byte-stride pool walk is correctly aligned

mq_msgblockalloc takes the block from kmm_malloc (maximally aligned), and stride = MQ_MSG_BLOCK(bufsize) is rounded to sizeof(void *), so every ptr += stride lands on a valid struct mqueue_msg_s * boundary. Good.

Header is 12 bytes on 32-bit ARM (next 4 + type 1 + priority 1 + 2 pad + msglen 4), which matters for the numbers below.

The defconfig changes are a real trade-off, not plumbing

All 24 defconfigs get PREALLOC_MQ_MSGS=10 and PREALLOC_MQ_MSGSIZE=256, and MQ_MAXMSGSIZE=600 where it was lower. What that means per board family (h ≈ 12):

boards before after Δ
10 (hello, tc, tls_test, …) MAXMSGSIZE=32, MSGS=4 → 4×44 ≈ 176 B 10×268 ≈ 2.7 KB +2.5 KB, max msg 32→600
4 (loadable_apps) MAXMSGSIZE=256, MSGS=32 → 32×268 ≈ 8.6 KB 10×268 ≈ 2.7 KB −5.9 KB, 32→10 free entries
14 (xip_all, …) MAXMSGSIZE=600, MSGS=4 → 4×612 ≈ 2.4 KB 10×268 ≈ 2.7 KB ≈ same, more entries

And the interrupt pool keeps MQ_MAX_BYTES with NUM_INTERRUPT_MSGS=32 (it has no heap fallback). On the 10 boards where MAXMSGSIZE was 32, that pool grows 32×44 ≈ 1.4 KB → 32×612 ≈ 19.5 KB. That's the largest single delta in the PR and it's static allocation, so it shows up on every build of those boards.

None of this is wrong — the Kconfig default (MQ_MAXMSGSIZE) genuinely preserves old behaviour for boards that don't opt in, as you say. But these 24 boards do opt in, and the body reads as if the defconfig edits are bookkeeping. A short "Memory impact" section with the table above would let a board owner evaluate their board in seconds.

Minor

  • mq_send.c / mq_timedsend.c still have an ISR branch calling mq_msgalloc(msglen) with the full-size MQ_ALLOC_IRQ pool — correct, and the new MQ_ALLOC_* tags make the three allocators easy to tell apart. Nice.
  • The #error on PREALLOC_MQ_MSGSIZE > MQ_MAXMSGSIZE catches the one misconfiguration that would make a pool entry unable to hold a legal message. Good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants