ipc/mqueue: enforce hard limits
[cascardo/linux.git] / ipc / mqueue.c
1 /*
2  * POSIX message queues filesystem for Linux.
3  *
4  * Copyright (C) 2003,2004  Krzysztof Benedyczak    (golbi@mat.uni.torun.pl)
5  *                          Michal Wronski          (michal.wronski@gmail.com)
6  *
7  * Spinlocks:               Mohamed Abbas           (abbas.mohamed@intel.com)
8  * Lockless receive & send, fd based notify:
9  *                          Manfred Spraul          (manfred@colorfullife.com)
10  *
11  * Audit:                   George Wilson           (ltcgcw@us.ibm.com)
12  *
13  * This file is released under the GPL.
14  */
15
16 #include <linux/capability.h>
17 #include <linux/init.h>
18 #include <linux/pagemap.h>
19 #include <linux/file.h>
20 #include <linux/mount.h>
21 #include <linux/namei.h>
22 #include <linux/sysctl.h>
23 #include <linux/poll.h>
24 #include <linux/mqueue.h>
25 #include <linux/msg.h>
26 #include <linux/skbuff.h>
27 #include <linux/netlink.h>
28 #include <linux/syscalls.h>
29 #include <linux/audit.h>
30 #include <linux/signal.h>
31 #include <linux/mutex.h>
32 #include <linux/nsproxy.h>
33 #include <linux/pid.h>
34 #include <linux/ipc_namespace.h>
35 #include <linux/user_namespace.h>
36 #include <linux/slab.h>
37
38 #include <net/sock.h>
39 #include "util.h"
40
41 #define MQUEUE_MAGIC    0x19800202
42 #define DIRENT_SIZE     20
43 #define FILENT_SIZE     80
44
45 #define SEND            0
46 #define RECV            1
47
48 #define STATE_NONE      0
49 #define STATE_PENDING   1
50 #define STATE_READY     2
51
52 struct ext_wait_queue {         /* queue of sleeping tasks */
53         struct task_struct *task;
54         struct list_head list;
55         struct msg_msg *msg;    /* ptr of loaded message */
56         int state;              /* one of STATE_* values */
57 };
58
59 struct mqueue_inode_info {
60         spinlock_t lock;
61         struct inode vfs_inode;
62         wait_queue_head_t wait_q;
63
64         struct msg_msg **messages;
65         struct mq_attr attr;
66
67         struct sigevent notify;
68         struct pid* notify_owner;
69         struct user_namespace *notify_user_ns;
70         struct user_struct *user;       /* user who created, for accounting */
71         struct sock *notify_sock;
72         struct sk_buff *notify_cookie;
73
74         /* for tasks waiting for free space and messages, respectively */
75         struct ext_wait_queue e_wait_q[2];
76
77         unsigned long qsize; /* size of queue in memory (sum of all msgs) */
78 };
79
80 static const struct inode_operations mqueue_dir_inode_operations;
81 static const struct file_operations mqueue_file_operations;
82 static const struct super_operations mqueue_super_ops;
83 static void remove_notification(struct mqueue_inode_info *info);
84
85 static struct kmem_cache *mqueue_inode_cachep;
86
87 static struct ctl_table_header * mq_sysctl_table;
88
89 static inline struct mqueue_inode_info *MQUEUE_I(struct inode *inode)
90 {
91         return container_of(inode, struct mqueue_inode_info, vfs_inode);
92 }
93
94 /*
95  * This routine should be called with the mq_lock held.
96  */
97 static inline struct ipc_namespace *__get_ns_from_inode(struct inode *inode)
98 {
99         return get_ipc_ns(inode->i_sb->s_fs_info);
100 }
101
102 static struct ipc_namespace *get_ns_from_inode(struct inode *inode)
103 {
104         struct ipc_namespace *ns;
105
106         spin_lock(&mq_lock);
107         ns = __get_ns_from_inode(inode);
108         spin_unlock(&mq_lock);
109         return ns;
110 }
111
112 static struct inode *mqueue_get_inode(struct super_block *sb,
113                 struct ipc_namespace *ipc_ns, umode_t mode,
114                 struct mq_attr *attr)
115 {
116         struct user_struct *u = current_user();
117         struct inode *inode;
118         int ret = -ENOMEM;
119
120         inode = new_inode(sb);
121         if (!inode)
122                 goto err;
123
124         inode->i_ino = get_next_ino();
125         inode->i_mode = mode;
126         inode->i_uid = current_fsuid();
127         inode->i_gid = current_fsgid();
128         inode->i_mtime = inode->i_ctime = inode->i_atime = CURRENT_TIME;
129
130         if (S_ISREG(mode)) {
131                 struct mqueue_inode_info *info;
132                 unsigned long mq_bytes, mq_msg_tblsz;
133
134                 inode->i_fop = &mqueue_file_operations;
135                 inode->i_size = FILENT_SIZE;
136                 /* mqueue specific info */
137                 info = MQUEUE_I(inode);
138                 spin_lock_init(&info->lock);
139                 init_waitqueue_head(&info->wait_q);
140                 INIT_LIST_HEAD(&info->e_wait_q[0].list);
141                 INIT_LIST_HEAD(&info->e_wait_q[1].list);
142                 info->notify_owner = NULL;
143                 info->notify_user_ns = NULL;
144                 info->qsize = 0;
145                 info->user = NULL;      /* set when all is ok */
146                 memset(&info->attr, 0, sizeof(info->attr));
147                 info->attr.mq_maxmsg = min(ipc_ns->mq_msg_max, DFLT_MSG);
148                 info->attr.mq_msgsize =
149                         min(ipc_ns->mq_msgsize_max, DFLT_MSGSIZE);
150                 if (attr) {
151                         info->attr.mq_maxmsg = attr->mq_maxmsg;
152                         info->attr.mq_msgsize = attr->mq_msgsize;
153                 }
154                 mq_msg_tblsz = info->attr.mq_maxmsg * sizeof(struct msg_msg *);
155                 info->messages = kmalloc(mq_msg_tblsz, GFP_KERNEL);
156                 if (!info->messages)
157                         goto out_inode;
158
159                 mq_bytes = (mq_msg_tblsz +
160                         (info->attr.mq_maxmsg * info->attr.mq_msgsize));
161
162                 spin_lock(&mq_lock);
163                 if (u->mq_bytes + mq_bytes < u->mq_bytes ||
164                     u->mq_bytes + mq_bytes > rlimit(RLIMIT_MSGQUEUE)) {
165                         spin_unlock(&mq_lock);
166                         /* mqueue_evict_inode() releases info->messages */
167                         ret = -EMFILE;
168                         goto out_inode;
169                 }
170                 u->mq_bytes += mq_bytes;
171                 spin_unlock(&mq_lock);
172
173                 /* all is ok */
174                 info->user = get_uid(u);
175         } else if (S_ISDIR(mode)) {
176                 inc_nlink(inode);
177                 /* Some things misbehave if size == 0 on a directory */
178                 inode->i_size = 2 * DIRENT_SIZE;
179                 inode->i_op = &mqueue_dir_inode_operations;
180                 inode->i_fop = &simple_dir_operations;
181         }
182
183         return inode;
184 out_inode:
185         iput(inode);
186 err:
187         return ERR_PTR(ret);
188 }
189
190 static int mqueue_fill_super(struct super_block *sb, void *data, int silent)
191 {
192         struct inode *inode;
193         struct ipc_namespace *ns = data;
194
195         sb->s_blocksize = PAGE_CACHE_SIZE;
196         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
197         sb->s_magic = MQUEUE_MAGIC;
198         sb->s_op = &mqueue_super_ops;
199
200         inode = mqueue_get_inode(sb, ns, S_IFDIR | S_ISVTX | S_IRWXUGO, NULL);
201         if (IS_ERR(inode))
202                 return PTR_ERR(inode);
203
204         sb->s_root = d_make_root(inode);
205         if (!sb->s_root)
206                 return -ENOMEM;
207         return 0;
208 }
209
210 static struct dentry *mqueue_mount(struct file_system_type *fs_type,
211                          int flags, const char *dev_name,
212                          void *data)
213 {
214         if (!(flags & MS_KERNMOUNT))
215                 data = current->nsproxy->ipc_ns;
216         return mount_ns(fs_type, flags, data, mqueue_fill_super);
217 }
218
219 static void init_once(void *foo)
220 {
221         struct mqueue_inode_info *p = (struct mqueue_inode_info *) foo;
222
223         inode_init_once(&p->vfs_inode);
224 }
225
226 static struct inode *mqueue_alloc_inode(struct super_block *sb)
227 {
228         struct mqueue_inode_info *ei;
229
230         ei = kmem_cache_alloc(mqueue_inode_cachep, GFP_KERNEL);
231         if (!ei)
232                 return NULL;
233         return &ei->vfs_inode;
234 }
235
236 static void mqueue_i_callback(struct rcu_head *head)
237 {
238         struct inode *inode = container_of(head, struct inode, i_rcu);
239         kmem_cache_free(mqueue_inode_cachep, MQUEUE_I(inode));
240 }
241
242 static void mqueue_destroy_inode(struct inode *inode)
243 {
244         call_rcu(&inode->i_rcu, mqueue_i_callback);
245 }
246
247 static void mqueue_evict_inode(struct inode *inode)
248 {
249         struct mqueue_inode_info *info;
250         struct user_struct *user;
251         unsigned long mq_bytes;
252         int i;
253         struct ipc_namespace *ipc_ns;
254
255         clear_inode(inode);
256
257         if (S_ISDIR(inode->i_mode))
258                 return;
259
260         ipc_ns = get_ns_from_inode(inode);
261         info = MQUEUE_I(inode);
262         spin_lock(&info->lock);
263         for (i = 0; i < info->attr.mq_curmsgs; i++)
264                 free_msg(info->messages[i]);
265         kfree(info->messages);
266         spin_unlock(&info->lock);
267
268         /* Total amount of bytes accounted for the mqueue */
269         mq_bytes = info->attr.mq_maxmsg * (sizeof(struct msg_msg *)
270             + info->attr.mq_msgsize);
271         user = info->user;
272         if (user) {
273                 spin_lock(&mq_lock);
274                 user->mq_bytes -= mq_bytes;
275                 /*
276                  * get_ns_from_inode() ensures that the
277                  * (ipc_ns = sb->s_fs_info) is either a valid ipc_ns
278                  * to which we now hold a reference, or it is NULL.
279                  * We can't put it here under mq_lock, though.
280                  */
281                 if (ipc_ns)
282                         ipc_ns->mq_queues_count--;
283                 spin_unlock(&mq_lock);
284                 free_uid(user);
285         }
286         if (ipc_ns)
287                 put_ipc_ns(ipc_ns);
288 }
289
290 static int mqueue_create(struct inode *dir, struct dentry *dentry,
291                                 umode_t mode, struct nameidata *nd)
292 {
293         struct inode *inode;
294         struct mq_attr *attr = dentry->d_fsdata;
295         int error;
296         struct ipc_namespace *ipc_ns;
297
298         spin_lock(&mq_lock);
299         ipc_ns = __get_ns_from_inode(dir);
300         if (!ipc_ns) {
301                 error = -EACCES;
302                 goto out_unlock;
303         }
304         if (ipc_ns->mq_queues_count >= HARD_QUEUESMAX ||
305             (ipc_ns->mq_queues_count >= ipc_ns->mq_queues_max &&
306              !capable(CAP_SYS_RESOURCE))) {
307                 error = -ENOSPC;
308                 goto out_unlock;
309         }
310         ipc_ns->mq_queues_count++;
311         spin_unlock(&mq_lock);
312
313         inode = mqueue_get_inode(dir->i_sb, ipc_ns, mode, attr);
314         if (IS_ERR(inode)) {
315                 error = PTR_ERR(inode);
316                 spin_lock(&mq_lock);
317                 ipc_ns->mq_queues_count--;
318                 goto out_unlock;
319         }
320
321         put_ipc_ns(ipc_ns);
322         dir->i_size += DIRENT_SIZE;
323         dir->i_ctime = dir->i_mtime = dir->i_atime = CURRENT_TIME;
324
325         d_instantiate(dentry, inode);
326         dget(dentry);
327         return 0;
328 out_unlock:
329         spin_unlock(&mq_lock);
330         if (ipc_ns)
331                 put_ipc_ns(ipc_ns);
332         return error;
333 }
334
335 static int mqueue_unlink(struct inode *dir, struct dentry *dentry)
336 {
337         struct inode *inode = dentry->d_inode;
338
339         dir->i_ctime = dir->i_mtime = dir->i_atime = CURRENT_TIME;
340         dir->i_size -= DIRENT_SIZE;
341         drop_nlink(inode);
342         dput(dentry);
343         return 0;
344 }
345
346 /*
347 *       This is routine for system read from queue file.
348 *       To avoid mess with doing here some sort of mq_receive we allow
349 *       to read only queue size & notification info (the only values
350 *       that are interesting from user point of view and aren't accessible
351 *       through std routines)
352 */
353 static ssize_t mqueue_read_file(struct file *filp, char __user *u_data,
354                                 size_t count, loff_t *off)
355 {
356         struct mqueue_inode_info *info = MQUEUE_I(filp->f_path.dentry->d_inode);
357         char buffer[FILENT_SIZE];
358         ssize_t ret;
359
360         spin_lock(&info->lock);
361         snprintf(buffer, sizeof(buffer),
362                         "QSIZE:%-10lu NOTIFY:%-5d SIGNO:%-5d NOTIFY_PID:%-6d\n",
363                         info->qsize,
364                         info->notify_owner ? info->notify.sigev_notify : 0,
365                         (info->notify_owner &&
366                          info->notify.sigev_notify == SIGEV_SIGNAL) ?
367                                 info->notify.sigev_signo : 0,
368                         pid_vnr(info->notify_owner));
369         spin_unlock(&info->lock);
370         buffer[sizeof(buffer)-1] = '\0';
371
372         ret = simple_read_from_buffer(u_data, count, off, buffer,
373                                 strlen(buffer));
374         if (ret <= 0)
375                 return ret;
376
377         filp->f_path.dentry->d_inode->i_atime = filp->f_path.dentry->d_inode->i_ctime = CURRENT_TIME;
378         return ret;
379 }
380
381 static int mqueue_flush_file(struct file *filp, fl_owner_t id)
382 {
383         struct mqueue_inode_info *info = MQUEUE_I(filp->f_path.dentry->d_inode);
384
385         spin_lock(&info->lock);
386         if (task_tgid(current) == info->notify_owner)
387                 remove_notification(info);
388
389         spin_unlock(&info->lock);
390         return 0;
391 }
392
393 static unsigned int mqueue_poll_file(struct file *filp, struct poll_table_struct *poll_tab)
394 {
395         struct mqueue_inode_info *info = MQUEUE_I(filp->f_path.dentry->d_inode);
396         int retval = 0;
397
398         poll_wait(filp, &info->wait_q, poll_tab);
399
400         spin_lock(&info->lock);
401         if (info->attr.mq_curmsgs)
402                 retval = POLLIN | POLLRDNORM;
403
404         if (info->attr.mq_curmsgs < info->attr.mq_maxmsg)
405                 retval |= POLLOUT | POLLWRNORM;
406         spin_unlock(&info->lock);
407
408         return retval;
409 }
410
411 /* Adds current to info->e_wait_q[sr] before element with smaller prio */
412 static void wq_add(struct mqueue_inode_info *info, int sr,
413                         struct ext_wait_queue *ewp)
414 {
415         struct ext_wait_queue *walk;
416
417         ewp->task = current;
418
419         list_for_each_entry(walk, &info->e_wait_q[sr].list, list) {
420                 if (walk->task->static_prio <= current->static_prio) {
421                         list_add_tail(&ewp->list, &walk->list);
422                         return;
423                 }
424         }
425         list_add_tail(&ewp->list, &info->e_wait_q[sr].list);
426 }
427
428 /*
429  * Puts current task to sleep. Caller must hold queue lock. After return
430  * lock isn't held.
431  * sr: SEND or RECV
432  */
433 static int wq_sleep(struct mqueue_inode_info *info, int sr,
434                     ktime_t *timeout, struct ext_wait_queue *ewp)
435 {
436         int retval;
437         signed long time;
438
439         wq_add(info, sr, ewp);
440
441         for (;;) {
442                 set_current_state(TASK_INTERRUPTIBLE);
443
444                 spin_unlock(&info->lock);
445                 time = schedule_hrtimeout_range_clock(timeout, 0,
446                         HRTIMER_MODE_ABS, CLOCK_REALTIME);
447
448                 while (ewp->state == STATE_PENDING)
449                         cpu_relax();
450
451                 if (ewp->state == STATE_READY) {
452                         retval = 0;
453                         goto out;
454                 }
455                 spin_lock(&info->lock);
456                 if (ewp->state == STATE_READY) {
457                         retval = 0;
458                         goto out_unlock;
459                 }
460                 if (signal_pending(current)) {
461                         retval = -ERESTARTSYS;
462                         break;
463                 }
464                 if (time == 0) {
465                         retval = -ETIMEDOUT;
466                         break;
467                 }
468         }
469         list_del(&ewp->list);
470 out_unlock:
471         spin_unlock(&info->lock);
472 out:
473         return retval;
474 }
475
476 /*
477  * Returns waiting task that should be serviced first or NULL if none exists
478  */
479 static struct ext_wait_queue *wq_get_first_waiter(
480                 struct mqueue_inode_info *info, int sr)
481 {
482         struct list_head *ptr;
483
484         ptr = info->e_wait_q[sr].list.prev;
485         if (ptr == &info->e_wait_q[sr].list)
486                 return NULL;
487         return list_entry(ptr, struct ext_wait_queue, list);
488 }
489
490 /* Auxiliary functions to manipulate messages' list */
491 static void msg_insert(struct msg_msg *ptr, struct mqueue_inode_info *info)
492 {
493         int k;
494
495         k = info->attr.mq_curmsgs - 1;
496         while (k >= 0 && info->messages[k]->m_type >= ptr->m_type) {
497                 info->messages[k + 1] = info->messages[k];
498                 k--;
499         }
500         info->attr.mq_curmsgs++;
501         info->qsize += ptr->m_ts;
502         info->messages[k + 1] = ptr;
503 }
504
505 static inline struct msg_msg *msg_get(struct mqueue_inode_info *info)
506 {
507         info->qsize -= info->messages[--info->attr.mq_curmsgs]->m_ts;
508         return info->messages[info->attr.mq_curmsgs];
509 }
510
511 static inline void set_cookie(struct sk_buff *skb, char code)
512 {
513         ((char*)skb->data)[NOTIFY_COOKIE_LEN-1] = code;
514 }
515
516 /*
517  * The next function is only to split too long sys_mq_timedsend
518  */
519 static void __do_notify(struct mqueue_inode_info *info)
520 {
521         /* notification
522          * invoked when there is registered process and there isn't process
523          * waiting synchronously for message AND state of queue changed from
524          * empty to not empty. Here we are sure that no one is waiting
525          * synchronously. */
526         if (info->notify_owner &&
527             info->attr.mq_curmsgs == 1) {
528                 struct siginfo sig_i;
529                 switch (info->notify.sigev_notify) {
530                 case SIGEV_NONE:
531                         break;
532                 case SIGEV_SIGNAL:
533                         /* sends signal */
534
535                         sig_i.si_signo = info->notify.sigev_signo;
536                         sig_i.si_errno = 0;
537                         sig_i.si_code = SI_MESGQ;
538                         sig_i.si_value = info->notify.sigev_value;
539                         /* map current pid/uid into info->owner's namespaces */
540                         rcu_read_lock();
541                         sig_i.si_pid = task_tgid_nr_ns(current,
542                                                 ns_of_pid(info->notify_owner));
543                         sig_i.si_uid = from_kuid_munged(info->notify_user_ns, current_uid());
544                         rcu_read_unlock();
545
546                         kill_pid_info(info->notify.sigev_signo,
547                                       &sig_i, info->notify_owner);
548                         break;
549                 case SIGEV_THREAD:
550                         set_cookie(info->notify_cookie, NOTIFY_WOKENUP);
551                         netlink_sendskb(info->notify_sock, info->notify_cookie);
552                         break;
553                 }
554                 /* after notification unregisters process */
555                 put_pid(info->notify_owner);
556                 put_user_ns(info->notify_user_ns);
557                 info->notify_owner = NULL;
558                 info->notify_user_ns = NULL;
559         }
560         wake_up(&info->wait_q);
561 }
562
563 static int prepare_timeout(const struct timespec __user *u_abs_timeout,
564                            ktime_t *expires, struct timespec *ts)
565 {
566         if (copy_from_user(ts, u_abs_timeout, sizeof(struct timespec)))
567                 return -EFAULT;
568         if (!timespec_valid(ts))
569                 return -EINVAL;
570
571         *expires = timespec_to_ktime(*ts);
572         return 0;
573 }
574
575 static void remove_notification(struct mqueue_inode_info *info)
576 {
577         if (info->notify_owner != NULL &&
578             info->notify.sigev_notify == SIGEV_THREAD) {
579                 set_cookie(info->notify_cookie, NOTIFY_REMOVED);
580                 netlink_sendskb(info->notify_sock, info->notify_cookie);
581         }
582         put_pid(info->notify_owner);
583         put_user_ns(info->notify_user_ns);
584         info->notify_owner = NULL;
585         info->notify_user_ns = NULL;
586 }
587
588 static int mq_attr_ok(struct ipc_namespace *ipc_ns, struct mq_attr *attr)
589 {
590         if (attr->mq_maxmsg <= 0 || attr->mq_msgsize <= 0)
591                 return 0;
592         if (capable(CAP_SYS_RESOURCE)) {
593                 if (attr->mq_maxmsg > HARD_MSGMAX ||
594                     attr->mq_msgsize > HARD_MSGSIZEMAX)
595                         return 0;
596         } else {
597                 if (attr->mq_maxmsg > ipc_ns->mq_msg_max ||
598                                 attr->mq_msgsize > ipc_ns->mq_msgsize_max)
599                         return 0;
600         }
601         /* check for overflow */
602         if (attr->mq_msgsize > ULONG_MAX/attr->mq_maxmsg)
603                 return 0;
604         if ((unsigned long)(attr->mq_maxmsg * (attr->mq_msgsize
605             + sizeof (struct msg_msg *))) <
606             (unsigned long)(attr->mq_maxmsg * attr->mq_msgsize))
607                 return 0;
608         return 1;
609 }
610
611 /*
612  * Invoked when creating a new queue via sys_mq_open
613  */
614 static struct file *do_create(struct ipc_namespace *ipc_ns, struct dentry *dir,
615                         struct dentry *dentry, int oflag, umode_t mode,
616                         struct mq_attr *attr)
617 {
618         const struct cred *cred = current_cred();
619         struct file *result;
620         int ret;
621
622         if (attr) {
623                 if (!mq_attr_ok(ipc_ns, attr)) {
624                         ret = -EINVAL;
625                         goto out;
626                 }
627                 /* store for use during create */
628                 dentry->d_fsdata = attr;
629         }
630
631         mode &= ~current_umask();
632         ret = mnt_want_write(ipc_ns->mq_mnt);
633         if (ret)
634                 goto out;
635         ret = vfs_create(dir->d_inode, dentry, mode, NULL);
636         dentry->d_fsdata = NULL;
637         if (ret)
638                 goto out_drop_write;
639
640         result = dentry_open(dentry, ipc_ns->mq_mnt, oflag, cred);
641         /*
642          * dentry_open() took a persistent mnt_want_write(),
643          * so we can now drop this one.
644          */
645         mnt_drop_write(ipc_ns->mq_mnt);
646         return result;
647
648 out_drop_write:
649         mnt_drop_write(ipc_ns->mq_mnt);
650 out:
651         dput(dentry);
652         mntput(ipc_ns->mq_mnt);
653         return ERR_PTR(ret);
654 }
655
656 /* Opens existing queue */
657 static struct file *do_open(struct ipc_namespace *ipc_ns,
658                                 struct dentry *dentry, int oflag)
659 {
660         int ret;
661         const struct cred *cred = current_cred();
662
663         static const int oflag2acc[O_ACCMODE] = { MAY_READ, MAY_WRITE,
664                                                   MAY_READ | MAY_WRITE };
665
666         if ((oflag & O_ACCMODE) == (O_RDWR | O_WRONLY)) {
667                 ret = -EINVAL;
668                 goto err;
669         }
670
671         if (inode_permission(dentry->d_inode, oflag2acc[oflag & O_ACCMODE])) {
672                 ret = -EACCES;
673                 goto err;
674         }
675
676         return dentry_open(dentry, ipc_ns->mq_mnt, oflag, cred);
677
678 err:
679         dput(dentry);
680         mntput(ipc_ns->mq_mnt);
681         return ERR_PTR(ret);
682 }
683
684 SYSCALL_DEFINE4(mq_open, const char __user *, u_name, int, oflag, umode_t, mode,
685                 struct mq_attr __user *, u_attr)
686 {
687         struct dentry *dentry;
688         struct file *filp;
689         char *name;
690         struct mq_attr attr;
691         int fd, error;
692         struct ipc_namespace *ipc_ns = current->nsproxy->ipc_ns;
693
694         if (u_attr && copy_from_user(&attr, u_attr, sizeof(struct mq_attr)))
695                 return -EFAULT;
696
697         audit_mq_open(oflag, mode, u_attr ? &attr : NULL);
698
699         if (IS_ERR(name = getname(u_name)))
700                 return PTR_ERR(name);
701
702         fd = get_unused_fd_flags(O_CLOEXEC);
703         if (fd < 0)
704                 goto out_putname;
705
706         mutex_lock(&ipc_ns->mq_mnt->mnt_root->d_inode->i_mutex);
707         dentry = lookup_one_len(name, ipc_ns->mq_mnt->mnt_root, strlen(name));
708         if (IS_ERR(dentry)) {
709                 error = PTR_ERR(dentry);
710                 goto out_putfd;
711         }
712         mntget(ipc_ns->mq_mnt);
713
714         if (oflag & O_CREAT) {
715                 if (dentry->d_inode) {  /* entry already exists */
716                         audit_inode(name, dentry);
717                         if (oflag & O_EXCL) {
718                                 error = -EEXIST;
719                                 goto out;
720                         }
721                         filp = do_open(ipc_ns, dentry, oflag);
722                 } else {
723                         filp = do_create(ipc_ns, ipc_ns->mq_mnt->mnt_root,
724                                                 dentry, oflag, mode,
725                                                 u_attr ? &attr : NULL);
726                 }
727         } else {
728                 if (!dentry->d_inode) {
729                         error = -ENOENT;
730                         goto out;
731                 }
732                 audit_inode(name, dentry);
733                 filp = do_open(ipc_ns, dentry, oflag);
734         }
735
736         if (IS_ERR(filp)) {
737                 error = PTR_ERR(filp);
738                 goto out_putfd;
739         }
740
741         fd_install(fd, filp);
742         goto out_upsem;
743
744 out:
745         dput(dentry);
746         mntput(ipc_ns->mq_mnt);
747 out_putfd:
748         put_unused_fd(fd);
749         fd = error;
750 out_upsem:
751         mutex_unlock(&ipc_ns->mq_mnt->mnt_root->d_inode->i_mutex);
752 out_putname:
753         putname(name);
754         return fd;
755 }
756
757 SYSCALL_DEFINE1(mq_unlink, const char __user *, u_name)
758 {
759         int err;
760         char *name;
761         struct dentry *dentry;
762         struct inode *inode = NULL;
763         struct ipc_namespace *ipc_ns = current->nsproxy->ipc_ns;
764
765         name = getname(u_name);
766         if (IS_ERR(name))
767                 return PTR_ERR(name);
768
769         mutex_lock_nested(&ipc_ns->mq_mnt->mnt_root->d_inode->i_mutex,
770                         I_MUTEX_PARENT);
771         dentry = lookup_one_len(name, ipc_ns->mq_mnt->mnt_root, strlen(name));
772         if (IS_ERR(dentry)) {
773                 err = PTR_ERR(dentry);
774                 goto out_unlock;
775         }
776
777         if (!dentry->d_inode) {
778                 err = -ENOENT;
779                 goto out_err;
780         }
781
782         inode = dentry->d_inode;
783         if (inode)
784                 ihold(inode);
785         err = mnt_want_write(ipc_ns->mq_mnt);
786         if (err)
787                 goto out_err;
788         err = vfs_unlink(dentry->d_parent->d_inode, dentry);
789         mnt_drop_write(ipc_ns->mq_mnt);
790 out_err:
791         dput(dentry);
792
793 out_unlock:
794         mutex_unlock(&ipc_ns->mq_mnt->mnt_root->d_inode->i_mutex);
795         putname(name);
796         if (inode)
797                 iput(inode);
798
799         return err;
800 }
801
802 /* Pipelined send and receive functions.
803  *
804  * If a receiver finds no waiting message, then it registers itself in the
805  * list of waiting receivers. A sender checks that list before adding the new
806  * message into the message array. If there is a waiting receiver, then it
807  * bypasses the message array and directly hands the message over to the
808  * receiver.
809  * The receiver accepts the message and returns without grabbing the queue
810  * spinlock. Therefore an intermediate STATE_PENDING state and memory barriers
811  * are necessary. The same algorithm is used for sysv semaphores, see
812  * ipc/sem.c for more details.
813  *
814  * The same algorithm is used for senders.
815  */
816
817 /* pipelined_send() - send a message directly to the task waiting in
818  * sys_mq_timedreceive() (without inserting message into a queue).
819  */
820 static inline void pipelined_send(struct mqueue_inode_info *info,
821                                   struct msg_msg *message,
822                                   struct ext_wait_queue *receiver)
823 {
824         receiver->msg = message;
825         list_del(&receiver->list);
826         receiver->state = STATE_PENDING;
827         wake_up_process(receiver->task);
828         smp_wmb();
829         receiver->state = STATE_READY;
830 }
831
832 /* pipelined_receive() - if there is task waiting in sys_mq_timedsend()
833  * gets its message and put to the queue (we have one free place for sure). */
834 static inline void pipelined_receive(struct mqueue_inode_info *info)
835 {
836         struct ext_wait_queue *sender = wq_get_first_waiter(info, SEND);
837
838         if (!sender) {
839                 /* for poll */
840                 wake_up_interruptible(&info->wait_q);
841                 return;
842         }
843         msg_insert(sender->msg, info);
844         list_del(&sender->list);
845         sender->state = STATE_PENDING;
846         wake_up_process(sender->task);
847         smp_wmb();
848         sender->state = STATE_READY;
849 }
850
851 SYSCALL_DEFINE5(mq_timedsend, mqd_t, mqdes, const char __user *, u_msg_ptr,
852                 size_t, msg_len, unsigned int, msg_prio,
853                 const struct timespec __user *, u_abs_timeout)
854 {
855         struct file *filp;
856         struct inode *inode;
857         struct ext_wait_queue wait;
858         struct ext_wait_queue *receiver;
859         struct msg_msg *msg_ptr;
860         struct mqueue_inode_info *info;
861         ktime_t expires, *timeout = NULL;
862         struct timespec ts;
863         int ret;
864
865         if (u_abs_timeout) {
866                 int res = prepare_timeout(u_abs_timeout, &expires, &ts);
867                 if (res)
868                         return res;
869                 timeout = &expires;
870         }
871
872         if (unlikely(msg_prio >= (unsigned long) MQ_PRIO_MAX))
873                 return -EINVAL;
874
875         audit_mq_sendrecv(mqdes, msg_len, msg_prio, timeout ? &ts : NULL);
876
877         filp = fget(mqdes);
878         if (unlikely(!filp)) {
879                 ret = -EBADF;
880                 goto out;
881         }
882
883         inode = filp->f_path.dentry->d_inode;
884         if (unlikely(filp->f_op != &mqueue_file_operations)) {
885                 ret = -EBADF;
886                 goto out_fput;
887         }
888         info = MQUEUE_I(inode);
889         audit_inode(NULL, filp->f_path.dentry);
890
891         if (unlikely(!(filp->f_mode & FMODE_WRITE))) {
892                 ret = -EBADF;
893                 goto out_fput;
894         }
895
896         if (unlikely(msg_len > info->attr.mq_msgsize)) {
897                 ret = -EMSGSIZE;
898                 goto out_fput;
899         }
900
901         /* First try to allocate memory, before doing anything with
902          * existing queues. */
903         msg_ptr = load_msg(u_msg_ptr, msg_len);
904         if (IS_ERR(msg_ptr)) {
905                 ret = PTR_ERR(msg_ptr);
906                 goto out_fput;
907         }
908         msg_ptr->m_ts = msg_len;
909         msg_ptr->m_type = msg_prio;
910
911         spin_lock(&info->lock);
912
913         if (info->attr.mq_curmsgs == info->attr.mq_maxmsg) {
914                 if (filp->f_flags & O_NONBLOCK) {
915                         spin_unlock(&info->lock);
916                         ret = -EAGAIN;
917                 } else {
918                         wait.task = current;
919                         wait.msg = (void *) msg_ptr;
920                         wait.state = STATE_NONE;
921                         ret = wq_sleep(info, SEND, timeout, &wait);
922                 }
923                 if (ret < 0)
924                         free_msg(msg_ptr);
925         } else {
926                 receiver = wq_get_first_waiter(info, RECV);
927                 if (receiver) {
928                         pipelined_send(info, msg_ptr, receiver);
929                 } else {
930                         /* adds message to the queue */
931                         msg_insert(msg_ptr, info);
932                         __do_notify(info);
933                 }
934                 inode->i_atime = inode->i_mtime = inode->i_ctime =
935                                 CURRENT_TIME;
936                 spin_unlock(&info->lock);
937                 ret = 0;
938         }
939 out_fput:
940         fput(filp);
941 out:
942         return ret;
943 }
944
945 SYSCALL_DEFINE5(mq_timedreceive, mqd_t, mqdes, char __user *, u_msg_ptr,
946                 size_t, msg_len, unsigned int __user *, u_msg_prio,
947                 const struct timespec __user *, u_abs_timeout)
948 {
949         ssize_t ret;
950         struct msg_msg *msg_ptr;
951         struct file *filp;
952         struct inode *inode;
953         struct mqueue_inode_info *info;
954         struct ext_wait_queue wait;
955         ktime_t expires, *timeout = NULL;
956         struct timespec ts;
957
958         if (u_abs_timeout) {
959                 int res = prepare_timeout(u_abs_timeout, &expires, &ts);
960                 if (res)
961                         return res;
962                 timeout = &expires;
963         }
964
965         audit_mq_sendrecv(mqdes, msg_len, 0, timeout ? &ts : NULL);
966
967         filp = fget(mqdes);
968         if (unlikely(!filp)) {
969                 ret = -EBADF;
970                 goto out;
971         }
972
973         inode = filp->f_path.dentry->d_inode;
974         if (unlikely(filp->f_op != &mqueue_file_operations)) {
975                 ret = -EBADF;
976                 goto out_fput;
977         }
978         info = MQUEUE_I(inode);
979         audit_inode(NULL, filp->f_path.dentry);
980
981         if (unlikely(!(filp->f_mode & FMODE_READ))) {
982                 ret = -EBADF;
983                 goto out_fput;
984         }
985
986         /* checks if buffer is big enough */
987         if (unlikely(msg_len < info->attr.mq_msgsize)) {
988                 ret = -EMSGSIZE;
989                 goto out_fput;
990         }
991
992         spin_lock(&info->lock);
993         if (info->attr.mq_curmsgs == 0) {
994                 if (filp->f_flags & O_NONBLOCK) {
995                         spin_unlock(&info->lock);
996                         ret = -EAGAIN;
997                 } else {
998                         wait.task = current;
999                         wait.state = STATE_NONE;
1000                         ret = wq_sleep(info, RECV, timeout, &wait);
1001                         msg_ptr = wait.msg;
1002                 }
1003         } else {
1004                 msg_ptr = msg_get(info);
1005
1006                 inode->i_atime = inode->i_mtime = inode->i_ctime =
1007                                 CURRENT_TIME;
1008
1009                 /* There is now free space in queue. */
1010                 pipelined_receive(info);
1011                 spin_unlock(&info->lock);
1012                 ret = 0;
1013         }
1014         if (ret == 0) {
1015                 ret = msg_ptr->m_ts;
1016
1017                 if ((u_msg_prio && put_user(msg_ptr->m_type, u_msg_prio)) ||
1018                         store_msg(u_msg_ptr, msg_ptr, msg_ptr->m_ts)) {
1019                         ret = -EFAULT;
1020                 }
1021                 free_msg(msg_ptr);
1022         }
1023 out_fput:
1024         fput(filp);
1025 out:
1026         return ret;
1027 }
1028
1029 /*
1030  * Notes: the case when user wants us to deregister (with NULL as pointer)
1031  * and he isn't currently owner of notification, will be silently discarded.
1032  * It isn't explicitly defined in the POSIX.
1033  */
1034 SYSCALL_DEFINE2(mq_notify, mqd_t, mqdes,
1035                 const struct sigevent __user *, u_notification)
1036 {
1037         int ret;
1038         struct file *filp;
1039         struct sock *sock;
1040         struct inode *inode;
1041         struct sigevent notification;
1042         struct mqueue_inode_info *info;
1043         struct sk_buff *nc;
1044
1045         if (u_notification) {
1046                 if (copy_from_user(&notification, u_notification,
1047                                         sizeof(struct sigevent)))
1048                         return -EFAULT;
1049         }
1050
1051         audit_mq_notify(mqdes, u_notification ? &notification : NULL);
1052
1053         nc = NULL;
1054         sock = NULL;
1055         if (u_notification != NULL) {
1056                 if (unlikely(notification.sigev_notify != SIGEV_NONE &&
1057                              notification.sigev_notify != SIGEV_SIGNAL &&
1058                              notification.sigev_notify != SIGEV_THREAD))
1059                         return -EINVAL;
1060                 if (notification.sigev_notify == SIGEV_SIGNAL &&
1061                         !valid_signal(notification.sigev_signo)) {
1062                         return -EINVAL;
1063                 }
1064                 if (notification.sigev_notify == SIGEV_THREAD) {
1065                         long timeo;
1066
1067                         /* create the notify skb */
1068                         nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL);
1069                         if (!nc) {
1070                                 ret = -ENOMEM;
1071                                 goto out;
1072                         }
1073                         if (copy_from_user(nc->data,
1074                                         notification.sigev_value.sival_ptr,
1075                                         NOTIFY_COOKIE_LEN)) {
1076                                 ret = -EFAULT;
1077                                 goto out;
1078                         }
1079
1080                         /* TODO: add a header? */
1081                         skb_put(nc, NOTIFY_COOKIE_LEN);
1082                         /* and attach it to the socket */
1083 retry:
1084                         filp = fget(notification.sigev_signo);
1085                         if (!filp) {
1086                                 ret = -EBADF;
1087                                 goto out;
1088                         }
1089                         sock = netlink_getsockbyfilp(filp);
1090                         fput(filp);
1091                         if (IS_ERR(sock)) {
1092                                 ret = PTR_ERR(sock);
1093                                 sock = NULL;
1094                                 goto out;
1095                         }
1096
1097                         timeo = MAX_SCHEDULE_TIMEOUT;
1098                         ret = netlink_attachskb(sock, nc, &timeo, NULL);
1099                         if (ret == 1)
1100                                 goto retry;
1101                         if (ret) {
1102                                 sock = NULL;
1103                                 nc = NULL;
1104                                 goto out;
1105                         }
1106                 }
1107         }
1108
1109         filp = fget(mqdes);
1110         if (!filp) {
1111                 ret = -EBADF;
1112                 goto out;
1113         }
1114
1115         inode = filp->f_path.dentry->d_inode;
1116         if (unlikely(filp->f_op != &mqueue_file_operations)) {
1117                 ret = -EBADF;
1118                 goto out_fput;
1119         }
1120         info = MQUEUE_I(inode);
1121
1122         ret = 0;
1123         spin_lock(&info->lock);
1124         if (u_notification == NULL) {
1125                 if (info->notify_owner == task_tgid(current)) {
1126                         remove_notification(info);
1127                         inode->i_atime = inode->i_ctime = CURRENT_TIME;
1128                 }
1129         } else if (info->notify_owner != NULL) {
1130                 ret = -EBUSY;
1131         } else {
1132                 switch (notification.sigev_notify) {
1133                 case SIGEV_NONE:
1134                         info->notify.sigev_notify = SIGEV_NONE;
1135                         break;
1136                 case SIGEV_THREAD:
1137                         info->notify_sock = sock;
1138                         info->notify_cookie = nc;
1139                         sock = NULL;
1140                         nc = NULL;
1141                         info->notify.sigev_notify = SIGEV_THREAD;
1142                         break;
1143                 case SIGEV_SIGNAL:
1144                         info->notify.sigev_signo = notification.sigev_signo;
1145                         info->notify.sigev_value = notification.sigev_value;
1146                         info->notify.sigev_notify = SIGEV_SIGNAL;
1147                         break;
1148                 }
1149
1150                 info->notify_owner = get_pid(task_tgid(current));
1151                 info->notify_user_ns = get_user_ns(current_user_ns());
1152                 inode->i_atime = inode->i_ctime = CURRENT_TIME;
1153         }
1154         spin_unlock(&info->lock);
1155 out_fput:
1156         fput(filp);
1157 out:
1158         if (sock) {
1159                 netlink_detachskb(sock, nc);
1160         } else if (nc) {
1161                 dev_kfree_skb(nc);
1162         }
1163         return ret;
1164 }
1165
1166 SYSCALL_DEFINE3(mq_getsetattr, mqd_t, mqdes,
1167                 const struct mq_attr __user *, u_mqstat,
1168                 struct mq_attr __user *, u_omqstat)
1169 {
1170         int ret;
1171         struct mq_attr mqstat, omqstat;
1172         struct file *filp;
1173         struct inode *inode;
1174         struct mqueue_inode_info *info;
1175
1176         if (u_mqstat != NULL) {
1177                 if (copy_from_user(&mqstat, u_mqstat, sizeof(struct mq_attr)))
1178                         return -EFAULT;
1179                 if (mqstat.mq_flags & (~O_NONBLOCK))
1180                         return -EINVAL;
1181         }
1182
1183         filp = fget(mqdes);
1184         if (!filp) {
1185                 ret = -EBADF;
1186                 goto out;
1187         }
1188
1189         inode = filp->f_path.dentry->d_inode;
1190         if (unlikely(filp->f_op != &mqueue_file_operations)) {
1191                 ret = -EBADF;
1192                 goto out_fput;
1193         }
1194         info = MQUEUE_I(inode);
1195
1196         spin_lock(&info->lock);
1197
1198         omqstat = info->attr;
1199         omqstat.mq_flags = filp->f_flags & O_NONBLOCK;
1200         if (u_mqstat) {
1201                 audit_mq_getsetattr(mqdes, &mqstat);
1202                 spin_lock(&filp->f_lock);
1203                 if (mqstat.mq_flags & O_NONBLOCK)
1204                         filp->f_flags |= O_NONBLOCK;
1205                 else
1206                         filp->f_flags &= ~O_NONBLOCK;
1207                 spin_unlock(&filp->f_lock);
1208
1209                 inode->i_atime = inode->i_ctime = CURRENT_TIME;
1210         }
1211
1212         spin_unlock(&info->lock);
1213
1214         ret = 0;
1215         if (u_omqstat != NULL && copy_to_user(u_omqstat, &omqstat,
1216                                                 sizeof(struct mq_attr)))
1217                 ret = -EFAULT;
1218
1219 out_fput:
1220         fput(filp);
1221 out:
1222         return ret;
1223 }
1224
1225 static const struct inode_operations mqueue_dir_inode_operations = {
1226         .lookup = simple_lookup,
1227         .create = mqueue_create,
1228         .unlink = mqueue_unlink,
1229 };
1230
1231 static const struct file_operations mqueue_file_operations = {
1232         .flush = mqueue_flush_file,
1233         .poll = mqueue_poll_file,
1234         .read = mqueue_read_file,
1235         .llseek = default_llseek,
1236 };
1237
1238 static const struct super_operations mqueue_super_ops = {
1239         .alloc_inode = mqueue_alloc_inode,
1240         .destroy_inode = mqueue_destroy_inode,
1241         .evict_inode = mqueue_evict_inode,
1242         .statfs = simple_statfs,
1243 };
1244
1245 static struct file_system_type mqueue_fs_type = {
1246         .name = "mqueue",
1247         .mount = mqueue_mount,
1248         .kill_sb = kill_litter_super,
1249 };
1250
1251 int mq_init_ns(struct ipc_namespace *ns)
1252 {
1253         ns->mq_queues_count  = 0;
1254         ns->mq_queues_max    = DFLT_QUEUESMAX;
1255         ns->mq_msg_max       = DFLT_MSGMAX;
1256         ns->mq_msgsize_max   = DFLT_MSGSIZEMAX;
1257
1258         ns->mq_mnt = kern_mount_data(&mqueue_fs_type, ns);
1259         if (IS_ERR(ns->mq_mnt)) {
1260                 int err = PTR_ERR(ns->mq_mnt);
1261                 ns->mq_mnt = NULL;
1262                 return err;
1263         }
1264         return 0;
1265 }
1266
1267 void mq_clear_sbinfo(struct ipc_namespace *ns)
1268 {
1269         ns->mq_mnt->mnt_sb->s_fs_info = NULL;
1270 }
1271
1272 void mq_put_mnt(struct ipc_namespace *ns)
1273 {
1274         kern_unmount(ns->mq_mnt);
1275 }
1276
1277 static int __init init_mqueue_fs(void)
1278 {
1279         int error;
1280
1281         mqueue_inode_cachep = kmem_cache_create("mqueue_inode_cache",
1282                                 sizeof(struct mqueue_inode_info), 0,
1283                                 SLAB_HWCACHE_ALIGN, init_once);
1284         if (mqueue_inode_cachep == NULL)
1285                 return -ENOMEM;
1286
1287         /* ignore failures - they are not fatal */
1288         mq_sysctl_table = mq_register_sysctl_table();
1289
1290         error = register_filesystem(&mqueue_fs_type);
1291         if (error)
1292                 goto out_sysctl;
1293
1294         spin_lock_init(&mq_lock);
1295
1296         error = mq_init_ns(&init_ipc_ns);
1297         if (error)
1298                 goto out_filesystem;
1299
1300         return 0;
1301
1302 out_filesystem:
1303         unregister_filesystem(&mqueue_fs_type);
1304 out_sysctl:
1305         if (mq_sysctl_table)
1306                 unregister_sysctl_table(mq_sysctl_table);
1307         kmem_cache_destroy(mqueue_inode_cachep);
1308         return error;
1309 }
1310
1311 __initcall(init_mqueue_fs);