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