Message queues in Zephyr

How k_msgq_put and k_msgq_get move messages through a ring buffer, and how the kernel finishes a waiting thread's call for it, so that a woken thread never has to try again.

Producer and consumer on Zephyr v4.5.0

Simulated kernel: Zephyr v4.5.0. This scenario and every other one are in the scheduler playground. The simulator and its data files are not covered by the site's CC BY-SA license; see their license notices.

This walkthrough follows the producer and consumer through Zephyr’s kernel/msg_q.c. Set the step level to Line and go to tick 4: the message queue Q is full, Producer is about to send its fourth message and Consumer has not run yet.

What a message queue is

K_MSGQ_DEFINE(Q, sizeof(uint32_t), 3, 4);

defines a struct k_msgq and a buffer for 3 messages of 4 bytes, aligned to 4. Its fields (all but msg_size are in the kernel panel):

  • msg_size and max_msgs: the size of a message and how many fit.
  • used_msgs: how many slots hold a message.
  • read_ptr: the oldest message, the one the next k_msgq_get() copies out.
  • write_ptr: the slot the next k_msgq_put() copies into.
  • wait_q: the threads that are waiting, most urgent first.

There is only one wait queue. Threads wait to receive only while the queue is empty, and to send only while it is full, so at any moment the waiting threads are all receivers or all senders. The panel marks each one “to send” or “to receive”.

The two pointers wrap round at buffer_end, so the slots form a ring. The panel draws them in memory order, with the oldest message marked “out” and write_ptr’s slot marked “in”.

Sending to a full queue

k_msgq_put() is put_msg_in_queue() with the message going to the back:

static inline int put_msg_in_queue(struct k_msgq *msgq, const void *data,
			k_timeout_t timeout, bool put_at_back)
{
	__ASSERT(!arch_is_in_isr() || K_TIMEOUT_EQ(timeout, K_NO_WAIT), "");

	struct k_thread *pending_thread = NULL;
	k_spinlock_key_t key;
	int result;
	bool resched = false;

	key = k_spin_lock(&msgq->lock);

	if (put_at_back) {
		SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_msgq, put, msgq, timeout);
	} else {
		SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_msgq, put_front, msgq, timeout);
	}

	if (msgq->used_msgs < msgq->max_msgs) {
		/* message queue isn't full. Try to hand the message
		 * directly to the longest-waiting receiver, atomically
		 * under the scheduler's spinlock so a racing in-flight timeout
		 * handler cannot wake the receiver before the message
		 * has been copied into its buffer.
		 */
		LOCK_SCHED_SPINLOCK {
			pending_thread = z_unpend_first_thread_locked(&msgq->wait_q);
			if (pending_thread != NULL) {
				/* copy into the receiver's buffer */
				(void)memcpy(pending_thread->base.swap_data, data,
					     msgq->msg_size);
				arch_thread_return_value_set(pending_thread, 0);
				z_sched_ready_locked(pending_thread);
				resched = true;
			}
		}
		if (pending_thread == NULL) {
			size_t msg_size = msgq->msg_size;
			char *slot;

			__ASSERT_NO_MSG((msgq->write_ptr >= msgq->buffer_start) &&
					(msgq->write_ptr <= (msgq->buffer_end - 1)) &&
					((size_t)(uintptr_t)(msgq->buffer_end - msgq->write_ptr) >=
						msgq->msg_size));
			/*
			 * Pick the slot and update the ring state from
			 * registers first: the compiler cannot tell that the
			 * copy leaves the queue fields alone, so copying last
			 * saves it re-reading them afterwards.
			 */
			if (put_at_back) {
				/*
				 * to write a message to the back of the queue,
				 * take the slot write_ptr points at and
				 * advance write_ptr past it
				 */
				char *next;

				slot = msgq->write_ptr;
				next = slot + msg_size;
				if (next == msgq->buffer_end) {
					next = msgq->buffer_start;
				}
				msgq->write_ptr = next;
			} else {
				/*
				 * to write a message to the head of the queue,
				 * first decrement the read pointer (to open
				 * space at the front of the queue) then copy
				 * the message to the newly created space.
				 */
				slot = msgq->read_ptr;
				if (slot == msgq->buffer_start) {
					slot = msgq->buffer_end;
				}
				slot -= msg_size;
				msgq->read_ptr = slot;
			}
			msgq->used_msgs++;
			(void)memcpy(slot, data, msg_size);
			resched = msgq_handle_poll_events(msgq);
		}
		result = 0;
	} else if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) {
		/* don't wait for message space to become available */
		result = -ENOMSG;
	} else {
		if (put_at_back) {
			SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_msgq, put, msgq, timeout);
		} else {
			SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_msgq, put_front, msgq, timeout);
		}

		/* wait for put message success, failure, or timeout */
		_current->base.swap_data = (void *) data;

		result = z_pend_curr(&msgq->lock, key, &msgq->wait_q, timeout);

		if (put_at_back) {
			SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, put, msgq, timeout, result);
		} else {
			SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, put_front, msgq, timeout, result);
		}

		return result;
	}

	if (put_at_back) {
		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, put, msgq, timeout, result);
	} else {
		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, put_front, msgq, timeout, result);
	}

	if (resched) {
		z_reschedule(&msgq->lock, key);
	} else {
		k_spin_unlock(&msgq->lock, key);
	}

	return result;
}

kernel/msg_q.c, lines 152–272 · Zephyr v4.5.0 · Apache-2.0 license

At ticks 1 to 3 the queue has room and no thread is waiting to receive, so each message is copied to write_ptr, which moves on (wrapping from slot 2 to slot 0 after the third message), and used_msgs goes up.

At tick 4 used_msgs equals max_msgs. Producer passed K_FOREVER, so it waits. Before it calls z_pend_curr(), it stores the address of its message in _current->base.swap_data. That pointer is the key to the rest: whoever frees a slot can find the message and send it for Producer. z_pend_curr() takes Producer out of the run queue, puts it in Q’s wait_q and switches to Consumer.

Receiving, and finishing the sender’s call

int z_impl_k_msgq_get(struct k_msgq *msgq, void *data, k_timeout_t timeout)
{
	__ASSERT(!arch_is_in_isr() || K_TIMEOUT_EQ(timeout, K_NO_WAIT), "");

	k_spinlock_key_t key;
	struct k_thread *pending_thread;
	int result;
	bool resched = false;

	key = k_spin_lock(&msgq->lock);

	SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_msgq, get, msgq, timeout);

	if (likely(msgq->used_msgs > 0U)) {
		size_t msg_size = msgq->msg_size;
		char *slot = msgq->read_ptr;
		char *next = slot + msg_size;

		/* drop the message from the queue, then copy it out */
		if (next == msgq->buffer_end) {
			next = msgq->buffer_start;
		}
		msgq->read_ptr = next;
		msgq->used_msgs--;

		(void)memcpy(data, slot, msg_size);

		/* sanity-check write_ptr in case we hand the slot to a sender */
		__ASSERT_NO_MSG((msgq->write_ptr >= msgq->buffer_start) &&
				(msgq->write_ptr <= (msgq->buffer_end - 1)) &&
				((size_t)(uintptr_t)(msgq->buffer_end - msgq->write_ptr) >=
					msgq->msg_size));

		/* handle first thread waiting to write (if any). Done
		 * atomically under the scheduler's spinlock so we read the
		 * sender's swap_data and complete the wake before any
		 * racing in-flight timeout handler can wake the sender.
		 */
		LOCK_SCHED_SPINLOCK {
			pending_thread = z_unpend_first_thread_locked(&msgq->wait_q);
			if (pending_thread != NULL) {
				SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_msgq, get, msgq, timeout);

				/* add the sender's pending message to the queue */
				slot = msgq->write_ptr;
				next = slot + msg_size;
				if (next == msgq->buffer_end) {
					next = msgq->buffer_start;
				}
				msgq->write_ptr = next;
				msgq->used_msgs++;

				(void)memcpy(slot, pending_thread->base.swap_data, msg_size);

				arch_thread_return_value_set(pending_thread, 0);
				z_sched_ready_locked(pending_thread);
				resched = true;
			}
		}
		result = 0;
	} else if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) {
		/* don't wait for a message to become available */
		result = -ENOMSG;
	} else {
		SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_msgq, get, msgq, timeout);

		/* wait for get message success or timeout */
		_current->base.swap_data = data;

		result = z_pend_curr(&msgq->lock, key, &msgq->wait_q, timeout);
		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, get, msgq, timeout, result);
		return result;
	}

	SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_msgq, get, msgq, timeout, result);

	if (resched) {
		z_reschedule(&msgq->lock, key);
	} else {
		k_spin_unlock(&msgq->lock, key);
	}

	return result;
}

kernel/msg_q.c, lines 324–407 · Zephyr v4.5.0 · Apache-2.0 license

Consumer’s k_msgq_get() finds 3 messages. It takes the one at read_ptr (slot 0, Producer#1), moves read_ptr on and drops used_msgs to 2. Then, still holding the queue’s lock, it looks at the wait queue. A thread is waiting, and because a slot was just freed it must be a sender. The kernel does that sender’s work for it:

  1. z_unpend_first_thread_locked() takes Producer off the wait queue and cancels its timeout, if it had one.
  2. The message at Producer’s swap_data, Producer#4, is copied to write_ptr (slot 0, the slot just read), and used_msgs goes back to 3.
  3. arch_thread_return_value_set() makes Producer’s k_msgq_put() return 0 when it runs again.
  4. z_sched_ready_locked() puts Producer back in the run queue, and z_reschedule() switches to it, because it is more urgent than Consumer.

Producer resumes inside z_pend_curr(), gets 0, and returns from k_msgq_put() with its message already sent. It never touches the queue again. The event log shows the order: Consumer receives Producer#1, then Producer sends Producer#4, both inside Consumer’s call, and only then does Producer run.

Sending to a waiting receiver is the mirror image. If a thread waits in wait_q while the queue is empty, put_msg_in_queue() copies the message straight into that thread’s buffer (its swap_data) and readies it; the message never enters the queue. The queue handoff lesson shows what that changes.

Compared with FreeRTOS

FreeRTOS wakes the waiting task and lets it repeat its own call: the woken sender sends again, the woken receiver receives again, and either may find that another task got there first. Zephyr completes the operation before it wakes the thread, so a woken thread always has what it waited for. The price is the copy inside the other thread’s call, and a little state per thread (swap_data) to make it possible. Semaphores (k_sem_give()) and mutexes (k_mutex_unlock()) follow the same rule.

From an interrupt

k_msgq_put() can be called from an interrupt handler with K_NO_WAIT; the function asserts that an ISR never asks to wait. If a thread waits to receive, the handler’s message goes straight to it and the thread is readied, but z_reschedule() does not switch inside an ISR: the switch happens when the interrupt returns, as in the Zephyr interrupts walkthrough. If the queue is full, the call returns -ENOMSG and the message is lost.