/* * POSIX message queues filesystem for Linux. * * Copyright (C) 2003,2004 Krzysztof Benedyczak (golbi@mat.uni.torun.pl) * Michal Wronski (michal.wronski@gmail.com) * * Spinlocks: Mohamed Abbas (abbas.mohamed@intel.com) * Lockless receive & send, fd based notify: * Manfred Spraul (manfred@colorfullife.com) * * Audit: George Wilson (ltcgcw@us.ibm.com) * * This file is released under the GPL.
*/
/* * Locking: * * Accesses to a message queue are synchronized by acquiring info->lock. * * There are two notable exceptions: * - The actual wakeup of a sleeping task is performed using the wake_q * framework. info->lock is already released when wake_up_q is called. * - The exit codepaths after sleeping check ext_wait_queue->state without * any locks. If it is STATE_READY, then the syscall is completed without * acquiring info->lock. * * MQ_BARRIER: * To achieve proper release/acquire memory barrier pairing, the state is set to * STATE_READY with smp_store_release(), and it is read with READ_ONCE followed * by smp_acquire__after_ctrl_dep(). In addition, wake_q_add_safe() is used. * * This prevents the following races: * * 1) With the simple wake_q_add(), the task could be gone already before * the increase of the reference happens * Thread A * Thread B * WRITE_ONCE(wait.state, STATE_NONE); * schedule_hrtimeout() * wake_q_add(A) * if (cmpxchg()) // success * ->state = STATE_READY (reordered) * <timeout returns> * if (wait.state == STATE_READY) return; * sysret to user space * sys_exit() * get_task_struct() // UaF * * Solution: Use wake_q_add_safe() and perform the get_task_struct() before * the smp_store_release() that does ->state = STATE_READY. * * 2) Without proper _release/_acquire barriers, the woken up task * could read stale data * * Thread A * Thread B * do_mq_timedreceive * WRITE_ONCE(wait.state, STATE_NONE); * schedule_hrtimeout() * state = STATE_READY; * <timeout returns> * if (wait.state == STATE_READY) return; * msg_ptr = wait.msg; // Access to stale data! * receiver->msg = message; (reordered) * * Solution: use _release and _acquire barriers. * * 3) There is intentionally no barrier when setting current->state * to TASK_INTERRUPTIBLE: spin_unlock(&info->lock) provides the * release memory barrier, and the wakeup is triggered when holding * info->lock, i.e. spin_lock(&info->lock) provided a pairing * acquire memory barrier.
*/
struct ext_wait_queue { /* queue of sleeping tasks */ struct task_struct *task; struct list_head list; struct msg_msg *msg; /* ptr of loaded message */ int state; /* one of STATE_* values */
};
/* * This routine should be called with the mq_lock held.
*/ staticinlinestruct ipc_namespace *__get_ns_from_inode(struct inode *inode)
{ return get_ipc_ns(inode->i_sb->s_fs_info);
}
try_again: /* * During insert, low priorities go to the left and high to the * right. On receive, we want the highest priorities first, so * walk all the way to the right.
*/
parent = info->msg_tree_rightmost; if (!parent) { if (info->attr.mq_curmsgs) {
pr_warn_once("Inconsistency in POSIX message queue, " "no tree element, but supposedly messages " "should exist!\n");
info->attr.mq_curmsgs = 0;
} return NULL;
}
leaf = rb_entry(parent, struct posix_msg_tree_node, rb_node); if (unlikely(list_empty(&leaf->msg_list))) {
pr_warn_once("Inconsistency in POSIX message queue, " "empty leaf node but we haven't implemented " "lazy leaf delete!\n");
msg_tree_erase(leaf, info); goto try_again;
} else {
msg = list_first_entry(&leaf->msg_list, struct msg_msg, m_list);
list_del(&msg->m_list); if (list_empty(&leaf->msg_list)) {
msg_tree_erase(leaf, info);
}
}
info->attr.mq_curmsgs--;
info->qsize -= msg->m_ts; return msg;
}
if (S_ISREG(mode)) { struct mqueue_inode_info *info; unsignedlong mq_bytes, mq_treesize;
inode->i_fop = &mqueue_file_operations;
inode->i_size = FILENT_SIZE; /* mqueue specific info */
info = MQUEUE_I(inode);
spin_lock_init(&info->lock);
init_waitqueue_head(&info->wait_q);
INIT_LIST_HEAD(&info->e_wait_q[0].list);
INIT_LIST_HEAD(&info->e_wait_q[1].list);
info->notify_owner = NULL;
info->notify_user_ns = NULL;
info->qsize = 0;
info->ucounts = NULL; /* set when all is ok */
info->msg_tree = RB_ROOT;
info->msg_tree_rightmost = NULL;
info->node_cache = NULL;
memset(&info->attr, 0, sizeof(info->attr));
info->attr.mq_maxmsg = min(ipc_ns->mq_msg_max,
ipc_ns->mq_msg_default);
info->attr.mq_msgsize = min(ipc_ns->mq_msgsize_max,
ipc_ns->mq_msgsize_default); if (attr) {
info->attr.mq_maxmsg = attr->mq_maxmsg;
info->attr.mq_msgsize = attr->mq_msgsize;
} /* * We used to allocate a static array of pointers and account * the size of that array as well as one msg_msg struct per * possible message into the queue size. That's no longer * accurate as the queue is now an rbtree and will grow and * shrink depending on usage patterns. We can, however, still * account one msg_msg struct per message, but the nodes are * allocated depending on priority usage, and most programs * only use one, or a handful, of priorities. However, since * this is pinned memory, we need to assume worst case, so * that means the min(mq_maxmsg, max_priorities) * struct * posix_msg_tree_node.
*/
ret = -EINVAL; if (info->attr.mq_maxmsg <= 0 || info->attr.mq_msgsize <= 0) goto out_inode; if (capable(CAP_SYS_RESOURCE)) { if (info->attr.mq_maxmsg > HARD_MSGMAX ||
info->attr.mq_msgsize > HARD_MSGSIZEMAX) goto out_inode;
} else { if (info->attr.mq_maxmsg > ipc_ns->mq_msg_max ||
info->attr.mq_msgsize > ipc_ns->mq_msgsize_max) goto out_inode;
}
ret = -EOVERFLOW; /* check for overflow */ if (info->attr.mq_msgsize > ULONG_MAX/info->attr.mq_maxmsg) goto out_inode;
mq_treesize = info->attr.mq_maxmsg * sizeof(struct msg_msg) +
min_t(unsignedint, info->attr.mq_maxmsg, MQ_PRIO_MAX) * sizeof(struct posix_msg_tree_node);
mq_bytes = info->attr.mq_maxmsg * info->attr.mq_msgsize; if (mq_bytes + mq_treesize < mq_bytes) goto out_inode;
mq_bytes += mq_treesize;
info->ucounts = get_ucounts(current_ucounts()); if (info->ucounts) { long msgqueue;
spin_lock(&mq_lock);
msgqueue = inc_rlimit_ucounts(info->ucounts, UCOUNT_RLIMIT_MSGQUEUE, mq_bytes); if (msgqueue == LONG_MAX || msgqueue > rlimit(RLIMIT_MSGQUEUE)) {
dec_rlimit_ucounts(info->ucounts, UCOUNT_RLIMIT_MSGQUEUE, mq_bytes);
spin_unlock(&mq_lock);
put_ucounts(info->ucounts);
info->ucounts = NULL; /* mqueue_evict_inode() releases info->messages */
ret = -EMFILE; goto out_inode;
}
spin_unlock(&mq_lock);
}
} elseif (S_ISDIR(mode)) {
inc_nlink(inode); /* Some things misbehave if size == 0 on a directory */
inode->i_size = 2 * DIRENT_SIZE;
inode->i_op = &mqueue_dir_inode_operations;
inode->i_fop = &simple_dir_operations;
}
/* * With a newly created ipc namespace, we don't need to do a search * for an ipc namespace match, but we still need to set s_fs_info.
*/ if (ctx->newns) {
fc->s_fs_info = ctx->ipc_ns; return get_tree_nodev(fc, mqueue_fill_super);
} return get_tree_keyed(fc, mqueue_fill_super, ctx->ipc_ns);
}
/* * mq_init_ns() is currently the only caller of mq_create_mount(). * So the ns parameter is always a newly created ipc namespace.
*/ staticstruct vfsmount *mq_create_mount(struct ipc_namespace *ns)
{ struct mqueue_fs_context *ctx; struct fs_context *fc; struct vfsmount *mnt;
fc = fs_context_for_mount(&mqueue_fs_type, SB_KERNMOUNT); if (IS_ERR(fc)) return ERR_CAST(fc);
spin_lock(&mq_lock);
dec_rlimit_ucounts(info->ucounts, UCOUNT_RLIMIT_MSGQUEUE, mq_bytes); /* * get_ns_from_inode() ensures that the * (ipc_ns = sb->s_fs_info) is either a valid ipc_ns * to which we now hold a reference, or it is NULL. * We can't put it here under mq_lock, though.
*/ if (ipc_ns)
ipc_ns->mq_queues_count--;
spin_unlock(&mq_lock);
put_ucounts(info->ucounts);
info->ucounts = NULL;
} if (ipc_ns)
put_ipc_ns(ipc_ns);
}
/* * This is routine for system read from queue file. * To avoid mess with doing here some sort of mq_receive we allow * to read only queue size & notification info (the only values * that are interesting from user point of view and aren't accessible * through std routines)
*/ static ssize_t mqueue_read_file(struct file *filp, char __user *u_data,
size_t count, loff_t *off)
{ struct inode *inode = file_inode(filp); struct mqueue_inode_info *info = MQUEUE_I(inode); char buffer[FILENT_SIZE];
ssize_t ret;
spin_lock(&info->lock); if (info->attr.mq_curmsgs)
retval = EPOLLIN | EPOLLRDNORM;
if (info->attr.mq_curmsgs < info->attr.mq_maxmsg)
retval |= EPOLLOUT | EPOLLWRNORM;
spin_unlock(&info->lock);
return retval;
}
/* Adds current to info->e_wait_q[sr] before element with smaller prio */ staticvoid wq_add(struct mqueue_inode_info *info, int sr, struct ext_wait_queue *ewp)
{ struct ext_wait_queue *walk;
/* * Puts current task to sleep. Caller must hold queue lock. After return * lock isn't held. * sr: SEND or RECV
*/ staticint wq_sleep(struct mqueue_inode_info *info, int sr,
ktime_t *timeout, struct ext_wait_queue *ewp)
__releases(&info->lock)
{ int retval; signedlong time;
wq_add(info, sr, ewp);
for (;;) { /* memory barrier not required, we hold info->lock */
__set_current_state(TASK_INTERRUPTIBLE);
spin_unlock(&info->lock);
time = schedule_hrtimeout_range_clock(timeout, 0,
HRTIMER_MODE_ABS, CLOCK_REALTIME);
if (READ_ONCE(ewp->state) == STATE_READY) { /* see MQ_BARRIER for purpose/pairing */
smp_acquire__after_ctrl_dep();
retval = 0; goto out;
}
spin_lock(&info->lock);
/* we hold info->lock, so no memory barrier required */ if (READ_ONCE(ewp->state) == STATE_READY) {
retval = 0; goto out_unlock;
} if (signal_pending(current)) {
retval = -ERESTARTSYS; break;
} if (time == 0) {
retval = -ETIMEDOUT; break;
}
}
list_del(&ewp->list);
out_unlock:
spin_unlock(&info->lock);
out: return retval;
}
/* * Returns waiting task that should be serviced first or NULL if none exists
*/ staticstruct ext_wait_queue *wq_get_first_waiter( struct mqueue_inode_info *info, int sr)
{ struct list_head *ptr;
/* * The next function is only to split too long sys_mq_timedsend
*/ staticvoid __do_notify(struct mqueue_inode_info *info)
{ /* notification * invoked when there is registered process and there isn't process * waiting synchronously for message AND state of queue changed from * empty to not empty. Here we are sure that no one is waiting
* synchronously. */ if (info->notify_owner &&
info->attr.mq_curmsgs == 1) { switch (info->notify.sigev_notify) { case SIGEV_NONE: break; case SIGEV_SIGNAL: { struct kernel_siginfo sig_i; struct task_struct *task;
/* Pipelined send and receive functions. * * If a receiver finds no waiting message, then it registers itself in the * list of waiting receivers. A sender checks that list before adding the new * message into the message array. If there is a waiting receiver, then it * bypasses the message array and directly hands the message over to the * receiver. The receiver accepts the message and returns without grabbing the * queue spinlock: * * - Set pointer to message. * - Queue the receiver task for later wakeup (without the info->lock). * - Update its state to STATE_READY. Now the receiver can continue. * - Wake up the process after the lock is dropped. Should the process wake up * before this wakeup (due to a timeout or a signal) it will either see * STATE_READY and continue or acquire the lock to check the state again. * * The same algorithm is used for senders.
*/
/* see MQ_BARRIER for purpose/pairing */
smp_store_release(&this->state, STATE_READY);
wake_q_add_safe(wake_q, task);
}
/* pipelined_send() - send a message directly to the task waiting in * sys_mq_timedreceive() (without inserting message into a queue).
*/ staticinlinevoid pipelined_send(struct wake_q_head *wake_q, struct mqueue_inode_info *info, struct msg_msg *message, struct ext_wait_queue *receiver)
{
receiver->msg = message;
__pipelined_op(wake_q, info, receiver);
}
/* pipelined_receive() - if there is task waiting in sys_mq_timedsend()
* gets its message and put to the queue (we have one free place for sure). */ staticinlinevoid pipelined_receive(struct wake_q_head *wake_q, struct mqueue_inode_info *info)
{ struct ext_wait_queue *sender = wq_get_first_waiter(info, SEND);
if (!sender) { /* for poll */
wake_up_interruptible(&info->wait_q); return;
} if (msg_insert(sender->msg, info)) return;
if (unlikely(msg_prio >= (unsignedlong) MQ_PRIO_MAX)) return -EINVAL;
if (ts) {
expires = timespec64_to_ktime(*ts);
timeout = &expires;
}
audit_mq_sendrecv(mqdes, msg_len, msg_prio, ts);
CLASS(fd, f)(mqdes); if (fd_empty(f)) return -EBADF;
inode = file_inode(fd_file(f)); if (unlikely(fd_file(f)->f_op != &mqueue_file_operations)) return -EBADF;
info = MQUEUE_I(inode);
audit_file(fd_file(f));
if (unlikely(!(fd_file(f)->f_mode & FMODE_WRITE))) return -EBADF;
if (unlikely(msg_len > info->attr.mq_msgsize)) return -EMSGSIZE;
/* First try to allocate memory, before doing anything with
* existing queues. */
msg_ptr = load_msg(u_msg_ptr, msg_len); if (IS_ERR(msg_ptr)) return PTR_ERR(msg_ptr);
msg_ptr->m_ts = msg_len;
msg_ptr->m_type = msg_prio;
/* * msg_insert really wants us to have a valid, spare node struct so * it doesn't have to kmalloc a GFP_ATOMIC allocation, but it will * fall back to that if necessary.
*/ if (!info->node_cache)
new_leaf = kmalloc(sizeof(*new_leaf), GFP_KERNEL);
spin_lock(&info->lock);
if (!info->node_cache && new_leaf) { /* Save our speculative allocation into the cache */
INIT_LIST_HEAD(&new_leaf->msg_list);
info->node_cache = new_leaf;
new_leaf = NULL;
} else {
kfree(new_leaf);
}
if (info->attr.mq_curmsgs == info->attr.mq_maxmsg) { if (fd_file(f)->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
} else {
wait.task = current;
wait.msg = (void *) msg_ptr;
/* memory barrier not required, we hold info->lock */
WRITE_ONCE(wait.state, STATE_NONE);
ret = wq_sleep(info, SEND, timeout, &wait); /* * wq_sleep must be called with info->lock held, and * returns with the lock released
*/ goto out_free;
}
} else {
receiver = wq_get_first_waiter(info, RECV); if (receiver) {
pipelined_send(&wake_q, info, msg_ptr, receiver);
} else { /* adds message to the queue */
ret = msg_insert(msg_ptr, info); if (ret) goto out_unlock;
__do_notify(info);
}
simple_inode_init_ts(inode);
}
out_unlock:
spin_unlock(&info->lock);
wake_up_q(&wake_q);
out_free: if (ret)
free_msg(msg_ptr); return ret;
}
if (ts) {
expires = timespec64_to_ktime(*ts);
timeout = &expires;
}
audit_mq_sendrecv(mqdes, msg_len, 0, ts);
CLASS(fd, f)(mqdes); if (fd_empty(f)) return -EBADF;
inode = file_inode(fd_file(f)); if (unlikely(fd_file(f)->f_op != &mqueue_file_operations)) return -EBADF;
info = MQUEUE_I(inode);
audit_file(fd_file(f));
if (unlikely(!(fd_file(f)->f_mode & FMODE_READ))) return -EBADF;
/* checks if buffer is big enough */ if (unlikely(msg_len < info->attr.mq_msgsize)) return -EMSGSIZE;
/* * msg_insert really wants us to have a valid, spare node struct so * it doesn't have to kmalloc a GFP_ATOMIC allocation, but it will * fall back to that if necessary.
*/ if (!info->node_cache)
new_leaf = kmalloc(sizeof(*new_leaf), GFP_KERNEL);
spin_lock(&info->lock);
if (!info->node_cache && new_leaf) { /* Save our speculative allocation into the cache */
INIT_LIST_HEAD(&new_leaf->msg_list);
info->node_cache = new_leaf;
} else {
kfree(new_leaf);
}
if (info->attr.mq_curmsgs == 0) { if (fd_file(f)->f_flags & O_NONBLOCK) {
spin_unlock(&info->lock);
ret = -EAGAIN;
} else {
wait.task = current;
/* memory barrier not required, we hold info->lock */
WRITE_ONCE(wait.state, STATE_NONE);
ret = wq_sleep(info, RECV, timeout, &wait);
msg_ptr = wait.msg;
}
} else {
DEFINE_WAKE_Q(wake_q);
msg_ptr = msg_get(info);
simple_inode_init_ts(inode);
/* There is now free space in queue. */
pipelined_receive(&wake_q, info);
spin_unlock(&info->lock);
wake_up_q(&wake_q);
ret = 0;
} if (ret == 0) {
ret = msg_ptr->m_ts;
if ((u_msg_prio && put_user(msg_ptr->m_type, u_msg_prio)) ||
store_msg(u_msg_ptr, msg_ptr, msg_ptr->m_ts)) {
ret = -EFAULT;
}
free_msg(msg_ptr);
} return ret;
}
SYSCALL_DEFINE5(mq_timedsend, mqd_t, mqdes, constchar __user *, u_msg_ptr,
size_t, msg_len, unsignedint, msg_prio, conststruct __kernel_timespec __user *, u_abs_timeout)
{ struct timespec64 ts, *p = NULL; if (u_abs_timeout) { int res = prepare_timeout(u_abs_timeout, &ts); if (res) return res;
p = &ts;
} return do_mq_timedsend(mqdes, u_msg_ptr, msg_len, msg_prio, p);
}
SYSCALL_DEFINE5(mq_timedreceive, mqd_t, mqdes, char __user *, u_msg_ptr,
size_t, msg_len, unsignedint __user *, u_msg_prio, conststruct __kernel_timespec __user *, u_abs_timeout)
{ struct timespec64 ts, *p = NULL; if (u_abs_timeout) { int res = prepare_timeout(u_abs_timeout, &ts); if (res) return res;
p = &ts;
} return do_mq_timedreceive(mqdes, u_msg_ptr, msg_len, u_msg_prio, p);
}
/* * Notes: the case when user wants us to deregister (with NULL as pointer) * and he isn't currently owner of notification, will be silently discarded. * It isn't explicitly defined in the POSIX.
*/ staticint do_mq_notify(mqd_t mqdes, conststruct sigevent *notification)
{ int ret; struct sock *sock; struct inode *inode; struct mqueue_inode_info *info; struct sk_buff *nc;
audit_mq_notify(mqdes, notification);
nc = NULL;
sock = NULL; if (notification != NULL) { if (unlikely(notification->sigev_notify != SIGEV_NONE &&
notification->sigev_notify != SIGEV_SIGNAL &&
notification->sigev_notify != SIGEV_THREAD)) return -EINVAL; if (notification->sigev_notify == SIGEV_SIGNAL &&
!valid_signal(notification->sigev_signo)) { return -EINVAL;
} if (notification->sigev_notify == SIGEV_THREAD) { long timeo;
/* create the notify skb */
nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL); if (!nc) return -ENOMEM;
if (copy_from_user(nc->data,
notification->sigev_value.sival_ptr,
NOTIFY_COOKIE_LEN)) {
kfree_skb(nc); return -EFAULT;
}
/* TODO: add a header? */
skb_put(nc, NOTIFY_COOKIE_LEN); /* and attach it to the socket */
retry:
sock = netlink_getsockbyfd(notification->sigev_signo); if (IS_ERR(sock)) {
kfree_skb(nc); return PTR_ERR(sock);
}
timeo = MAX_SCHEDULE_TIMEOUT;
ret = netlink_attachskb(sock, nc, &timeo, NULL); if (ret == 1) goto retry; if (ret) return ret;
}
}
CLASS(fd, f)(mqdes); if (fd_empty(f)) {
ret = -EBADF; goto out;
}
inode = file_inode(fd_file(f)); if (unlikely(fd_file(f)->f_op != &mqueue_file_operations)) {
ret = -EBADF; goto out;
}
info = MQUEUE_I(inode);
if (u_mqstat) { new = &mqstat; if (copy_from_user(new, u_mqstat, sizeof(struct mq_attr))) return -EFAULT;
} if (u_omqstat)
old = &omqstat;
ret = do_mq_getsetattr(mqdes, new, old); if (ret || !old) return ret;
if (copy_to_user(u_omqstat, old, sizeof(struct mq_attr))) return -EFAULT; return 0;
}
#ifdef CONFIG_COMPAT
struct compat_mq_attr {
compat_long_t mq_flags; /* message queue flags */
compat_long_t mq_maxmsg; /* maximum number of messages */
compat_long_t mq_msgsize; /* maximum message size */
compat_long_t mq_curmsgs; /* number of messages currently queued */
compat_long_t __reserved[4]; /* ignored for input, zeroed for output */
};
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.