50b776464964c86b9e17a0ef6f9baadb39c9a420
[linux-2.6.git] / kernel / posix-timers.c
1 /*
2  * linux/kernel/posix_timers.c
3  *
4  *
5  * 2002-10-15  Posix Clocks & timers
6  *                           by George Anzinger george@mvista.com
7  *
8  *                           Copyright (C) 2002 2003 by MontaVista Software.
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or (at
13  * your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  *
24  * MontaVista Software | 1237 East Arques Avenue | Sunnyvale | CA 94085 | USA
25  */
26
27 /* These are all the functions necessary to implement
28  * POSIX clocks & timers
29  */
30 #include <linux/mm.h>
31 #include <linux/smp_lock.h>
32 #include <linux/interrupt.h>
33 #include <linux/slab.h>
34 #include <linux/time.h>
35
36 #include <asm/uaccess.h>
37 #include <asm/semaphore.h>
38 #include <linux/list.h>
39 #include <linux/init.h>
40 #include <linux/compiler.h>
41 #include <linux/idr.h>
42 #include <linux/posix-timers.h>
43 #include <linux/wait.h>
44
45 #ifndef div_long_long_rem
46 #include <asm/div64.h>
47
48 #define div_long_long_rem(dividend,divisor,remainder) ({ \
49                        u64 result = dividend;           \
50                        *remainder = do_div(result,divisor); \
51                        result; })
52
53 #endif
54 #define CLOCK_REALTIME_RES TICK_NSEC  /* In nano seconds. */
55
56 static inline u64  mpy_l_X_l_ll(unsigned long mpy1,unsigned long mpy2)
57 {
58         return (u64)mpy1 * mpy2;
59 }
60 /*
61  * Management arrays for POSIX timers.   Timers are kept in slab memory
62  * Timer ids are allocated by an external routine that keeps track of the
63  * id and the timer.  The external interface is:
64  *
65  * void *idr_find(struct idr *idp, int id);           to find timer_id <id>
66  * int idr_get_new(struct idr *idp, void *ptr);       to get a new id and
67  *                                                    related it to <ptr>
68  * void idr_remove(struct idr *idp, int id);          to release <id>
69  * void idr_init(struct idr *idp);                    to initialize <idp>
70  *                                                    which we supply.
71  * The idr_get_new *may* call slab for more memory so it must not be
72  * called under a spin lock.  Likewise idr_remore may release memory
73  * (but it may be ok to do this under a lock...).
74  * idr_find is just a memory look up and is quite fast.  A -1 return
75  * indicates that the requested id does not exist.
76  */
77
78 /*
79  * Lets keep our timers in a slab cache :-)
80  */
81 static kmem_cache_t *posix_timers_cache;
82 static struct idr posix_timers_id;
83 static spinlock_t idr_lock = SPIN_LOCK_UNLOCKED;
84
85 /*
86  * Just because the timer is not in the timer list does NOT mean it is
87  * inactive.  It could be in the "fire" routine getting a new expire time.
88  */
89 #define TIMER_INACTIVE 1
90 #define TIMER_RETRY 1
91
92 #ifdef CONFIG_SMP
93 # define timer_active(tmr) \
94                 ((tmr)->it_timer.entry.prev != (void *)TIMER_INACTIVE)
95 # define set_timer_inactive(tmr) \
96                 do { \
97                         (tmr)->it_timer.entry.prev = (void *)TIMER_INACTIVE; \
98                 } while (0)
99 #else
100 # define timer_active(tmr) BARFY        // error to use outside of SMP
101 # define set_timer_inactive(tmr) do { } while (0)
102 #endif
103 /*
104  * we assume that the new SIGEV_THREAD_ID shares no bits with the other
105  * SIGEV values.  Here we put out an error if this assumption fails.
106  */
107 #if SIGEV_THREAD_ID != (SIGEV_THREAD_ID & \
108                        ~(SIGEV_SIGNAL | SIGEV_NONE | SIGEV_THREAD))
109 #error "SIGEV_THREAD_ID must not share bit with other SIGEV values!"
110 #endif
111
112
113 #define REQUEUE_PENDING 1
114 /*
115  * The timer ID is turned into a timer address by idr_find().
116  * Verifying a valid ID consists of:
117  *
118  * a) checking that idr_find() returns other than -1.
119  * b) checking that the timer id matches the one in the timer itself.
120  * c) that the timer owner is in the callers thread group.
121  */
122
123 /*
124  * CLOCKs: The POSIX standard calls for a couple of clocks and allows us
125  *          to implement others.  This structure defines the various
126  *          clocks and allows the possibility of adding others.  We
127  *          provide an interface to add clocks to the table and expect
128  *          the "arch" code to add at least one clock that is high
129  *          resolution.  Here we define the standard CLOCK_REALTIME as a
130  *          1/HZ resolution clock.
131  *
132  * CPUTIME & THREAD_CPUTIME: We are not, at this time, definding these
133  *          two clocks (and the other process related clocks (Std
134  *          1003.1d-1999).  The way these should be supported, we think,
135  *          is to use large negative numbers for the two clocks that are
136  *          pinned to the executing process and to use -pid for clocks
137  *          pinned to particular pids.  Calls which supported these clock
138  *          ids would split early in the function.
139  *
140  * RESOLUTION: Clock resolution is used to round up timer and interval
141  *          times, NOT to report clock times, which are reported with as
142  *          much resolution as the system can muster.  In some cases this
143  *          resolution may depend on the underlaying clock hardware and
144  *          may not be quantifiable until run time, and only then is the
145  *          necessary code is written.  The standard says we should say
146  *          something about this issue in the documentation...
147  *
148  * FUNCTIONS: The CLOCKs structure defines possible functions to handle
149  *          various clock functions.  For clocks that use the standard
150  *          system timer code these entries should be NULL.  This will
151  *          allow dispatch without the overhead of indirect function
152  *          calls.  CLOCKS that depend on other sources (e.g. WWV or GPS)
153  *          must supply functions here, even if the function just returns
154  *          ENOSYS.  The standard POSIX timer management code assumes the
155  *          following: 1.) The k_itimer struct (sched.h) is used for the
156  *          timer.  2.) The list, it_lock, it_clock, it_id and it_process
157  *          fields are not modified by timer code.
158  *
159  *          At this time all functions EXCEPT clock_nanosleep can be
160  *          redirected by the CLOCKS structure.  Clock_nanosleep is in
161  *          there, but the code ignors it.
162  *
163  * Permissions: It is assumed that the clock_settime() function defined
164  *          for each clock will take care of permission checks.  Some
165  *          clocks may be set able by any user (i.e. local process
166  *          clocks) others not.  Currently the only set able clock we
167  *          have is CLOCK_REALTIME and its high res counter part, both of
168  *          which we beg off on and pass to do_sys_settimeofday().
169  */
170
171 static struct k_clock posix_clocks[MAX_CLOCKS];
172
173 #define if_clock_do(clock_fun,alt_fun,parms) \
174                 (!clock_fun) ? alt_fun parms : clock_fun parms
175
176 #define p_timer_get(clock,a,b) \
177                 if_clock_do((clock)->timer_get,do_timer_gettime, (a,b))
178
179 #define p_nsleep(clock,a,b,c) \
180                 if_clock_do((clock)->nsleep, do_nsleep, (a,b,c))
181
182 #define p_timer_del(clock,a) \
183                 if_clock_do((clock)->timer_del, do_timer_delete, (a))
184
185 void register_posix_clock(int clock_id, struct k_clock *new_clock);
186 static int do_posix_gettime(struct k_clock *clock, struct timespec *tp);
187 static u64 do_posix_clock_monotonic_gettime_parts(
188         struct timespec *tp, struct timespec *mo);
189 int do_posix_clock_monotonic_gettime(struct timespec *tp);
190 int do_posix_clock_monotonic_settime(struct timespec *tp);
191 static struct k_itimer *lock_timer(timer_t timer_id, unsigned long *flags);
192
193 static inline void unlock_timer(struct k_itimer *timr, unsigned long flags)
194 {
195         spin_unlock_irqrestore(&timr->it_lock, flags);
196 }
197
198 /*
199  * Initialize everything, well, just everything in Posix clocks/timers ;)
200  */
201 static __init int init_posix_timers(void)
202 {
203         struct k_clock clock_realtime = {.res = CLOCK_REALTIME_RES };
204         struct k_clock clock_monotonic = {.res = CLOCK_REALTIME_RES,
205                 .clock_get = do_posix_clock_monotonic_gettime,
206                 .clock_set = do_posix_clock_monotonic_settime
207         };
208
209         register_posix_clock(CLOCK_REALTIME, &clock_realtime);
210         register_posix_clock(CLOCK_MONOTONIC, &clock_monotonic);
211
212         posix_timers_cache = kmem_cache_create("posix_timers_cache",
213                                         sizeof (struct k_itimer), 0, 0, 0, 0);
214         idr_init(&posix_timers_id);
215
216         return 0;
217 }
218
219 __initcall(init_posix_timers);
220
221 static void tstojiffie(struct timespec *tp, int res, u64 *jiff)
222 {
223         long sec = tp->tv_sec;
224         long nsec = tp->tv_nsec + res - 1;
225
226         if (nsec > NSEC_PER_SEC) {
227                 sec++;
228                 nsec -= NSEC_PER_SEC;
229         }
230
231         /*
232          * The scaling constants are defined in <linux/time.h>
233          * The difference between there and here is that we do the
234          * res rounding and compute a 64-bit result (well so does that
235          * but it then throws away the high bits).
236          */
237         *jiff =  (mpy_l_X_l_ll(sec, SEC_CONVERSION) +
238                   (mpy_l_X_l_ll(nsec, NSEC_CONVERSION) >> 
239                    (NSEC_JIFFIE_SC - SEC_JIFFIE_SC))) >> SEC_JIFFIE_SC;
240 }
241
242 static void schedule_next_timer(struct k_itimer *timr)
243 {
244         struct now_struct now;
245
246         /* Set up the timer for the next interval (if there is one) */
247         if (!timr->it_incr) 
248                 return;
249
250         posix_get_now(&now);
251         do {
252                 posix_bump_timer(timr);
253         }while (posix_time_before(&timr->it_timer, &now));
254
255         timr->it_overrun_last = timr->it_overrun;
256         timr->it_overrun = -1;
257         ++timr->it_requeue_pending;
258         add_timer(&timr->it_timer);
259 }
260
261 /*
262  * This function is exported for use by the signal deliver code.  It is
263  * called just prior to the info block being released and passes that
264  * block to us.  It's function is to update the overrun entry AND to
265  * restart the timer.  It should only be called if the timer is to be
266  * restarted (i.e. we have flagged this in the sys_private entry of the
267  * info block).
268  *
269  * To protect aginst the timer going away while the interrupt is queued,
270  * we require that the it_requeue_pending flag be set.
271  */
272 void do_schedule_next_timer(struct siginfo *info)
273 {
274         struct k_itimer *timr;
275         unsigned long flags;
276
277         timr = lock_timer(info->si_tid, &flags);
278
279         if (!timr || timr->it_requeue_pending != info->si_sys_private)
280                 goto exit;
281
282         schedule_next_timer(timr);
283         info->si_overrun = timr->it_overrun_last;
284 exit:
285         if (timr)
286                 unlock_timer(timr, flags);
287 }
288
289 /*
290  * Notify the task and set up the timer for the next expiration (if
291  * applicable).  This function requires that the k_itimer structure
292  * it_lock is taken.  This code will requeue the timer only if we get
293  * either an error return or a flag (ret > 0) from send_seg_info
294  * indicating that the signal was either not queued or was queued
295  * without an info block.  In this case, we will not get a call back to
296  * do_schedule_next_timer() so we do it here.  This should be rare...
297
298  * An interesting problem can occur if, while a signal, and thus a call
299  * back is pending, the timer is rearmed, i.e. stopped and restarted.
300  * We then need to sort out the call back and do the right thing.  What
301  * we do is to put a counter in the info block and match it with the
302  * timers copy on the call back.  If they don't match, we just ignore
303  * the call back.  The counter is local to the timer and we use odd to
304  * indicate a call back is pending.  Note that we do allow the timer to 
305  * be deleted while a signal is pending.  The standard says we can
306  * allow that signal to be delivered, and we do. 
307  */
308
309 static void timer_notify_task(struct k_itimer *timr)
310 {
311         int ret;
312
313         memset(&timr->sigq->info, 0, sizeof(siginfo_t));
314
315         /* Send signal to the process that owns this timer. */
316         timr->sigq->info.si_signo = timr->it_sigev_signo;
317         timr->sigq->info.si_errno = 0;
318         timr->sigq->info.si_code = SI_TIMER;
319         timr->sigq->info.si_tid = timr->it_id;
320         timr->sigq->info.si_value = timr->it_sigev_value;
321         if (timr->it_incr)
322                 timr->sigq->info.si_sys_private = ++timr->it_requeue_pending;
323
324         if (timr->it_sigev_notify & SIGEV_THREAD_ID) {
325                 if (unlikely(timr->it_process->flags & PF_EXITING)) {
326                         timr->it_sigev_notify = SIGEV_SIGNAL;
327                         put_task_struct(timr->it_process);
328                         timr->it_process = timr->it_process->group_leader;
329                         goto group;
330                 }
331                 ret = send_sigqueue(timr->it_sigev_signo, timr->sigq,
332                         timr->it_process);
333         }
334         else {
335         group:
336                 ret = send_group_sigqueue(timr->it_sigev_signo, timr->sigq,
337                         timr->it_process);
338         }
339         if (ret) {
340                 /*
341                  * signal was not sent because of sig_ignor
342                  * we will not get a call back to restart it AND
343                  * it should be restarted.
344                  */
345                 schedule_next_timer(timr);
346         }
347 }
348
349 /*
350  * This function gets called when a POSIX.1b interval timer expires.  It
351  * is used as a callback from the kernel internal timer.  The
352  * run_timer_list code ALWAYS calls with interrutps on.
353  */
354 static void posix_timer_fn(unsigned long __data)
355 {
356         struct k_itimer *timr = (struct k_itimer *) __data;
357         unsigned long flags;
358
359         spin_lock_irqsave(&timr->it_lock, flags);
360         set_timer_inactive(timr);
361         timer_notify_task(timr);
362         unlock_timer(timr, flags);
363 }
364
365
366 static inline struct task_struct * good_sigevent(sigevent_t * event)
367 {
368         struct task_struct *rtn = current->group_leader;
369
370         if ((event->sigev_notify & SIGEV_THREAD_ID ) &&
371                 (!(rtn = find_task_by_pid(event->sigev_notify_thread_id)) ||
372                  rtn->tgid != current->tgid ||
373                  (event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_SIGNAL))
374                 return NULL;
375
376         if (((event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE) &&
377             ((event->sigev_signo <= 0) || (event->sigev_signo > SIGRTMAX)))
378                 return NULL;
379
380         return rtn;
381 }
382
383 void register_posix_clock(int clock_id, struct k_clock *new_clock)
384 {
385         if ((unsigned) clock_id >= MAX_CLOCKS) {
386                 printk("POSIX clock register failed for clock_id %d\n",
387                        clock_id);
388                 return;
389         }
390         posix_clocks[clock_id] = *new_clock;
391 }
392
393 static struct k_itimer * alloc_posix_timer(void)
394 {
395         struct k_itimer *tmr;
396         tmr = kmem_cache_alloc(posix_timers_cache, GFP_KERNEL);
397         if (!tmr)
398                 return tmr;
399         memset(tmr, 0, sizeof (struct k_itimer));
400         if (unlikely(!(tmr->sigq = sigqueue_alloc()))) {
401                 kmem_cache_free(posix_timers_cache, tmr);
402                 tmr = 0;
403         }
404         return tmr;
405 }
406
407 #define IT_ID_SET       1
408 #define IT_ID_NOT_SET   0
409 static void release_posix_timer(struct k_itimer *tmr, int it_id_set)
410 {
411         if (it_id_set) {
412                 unsigned long flags;
413                 spin_lock_irqsave(&idr_lock, flags);
414                 idr_remove(&posix_timers_id, tmr->it_id);
415                 spin_unlock_irqrestore(&idr_lock, flags);
416         }
417         sigqueue_free(tmr->sigq);
418         if (unlikely(tmr->it_process) &&
419             tmr->it_sigev_notify == (SIGEV_SIGNAL|SIGEV_THREAD_ID))
420                 put_task_struct(tmr->it_process);
421         kmem_cache_free(posix_timers_cache, tmr);
422 }
423
424 /* Create a POSIX.1b interval timer. */
425
426 asmlinkage long
427 sys_timer_create(clockid_t which_clock,
428                  struct sigevent __user *timer_event_spec,
429                  timer_t __user * created_timer_id)
430 {
431         int error = 0;
432         struct k_itimer *new_timer = NULL;
433         int new_timer_id;
434         struct task_struct *process = 0;
435         unsigned long flags;
436         sigevent_t event;
437         int it_id_set = IT_ID_NOT_SET;
438
439         if ((unsigned) which_clock >= MAX_CLOCKS ||
440                                 !posix_clocks[which_clock].res)
441                 return -EINVAL;
442
443         new_timer = alloc_posix_timer();
444         if (unlikely(!new_timer))
445                 return -EAGAIN;
446
447         spin_lock_init(&new_timer->it_lock);
448  retry:
449         if (unlikely(!idr_pre_get(&posix_timers_id, GFP_KERNEL))) {
450                 error = -EAGAIN;
451                 goto out;
452         }
453         spin_lock_irq(&idr_lock);
454         error = idr_get_new(&posix_timers_id,
455                             (void *) new_timer,
456                             &new_timer_id);
457         spin_unlock_irq(&idr_lock);
458         if (error == -EAGAIN)
459                 goto retry;
460         else if (error) {
461                 /*
462                  * Wierd looking, but we return EAGAIN if the IDR is
463                  * full (proper POSIX return value for this)
464                  */
465                 error = -EAGAIN;
466                 goto out;
467         }
468
469         it_id_set = IT_ID_SET;
470         new_timer->it_id = (timer_t) new_timer_id;
471         new_timer->it_clock = which_clock;
472         new_timer->it_incr = 0;
473         new_timer->it_overrun = -1;
474         init_timer(&new_timer->it_timer);
475         new_timer->it_timer.expires = 0;
476         new_timer->it_timer.data = (unsigned long) new_timer;
477         new_timer->it_timer.function = posix_timer_fn;
478         set_timer_inactive(new_timer);
479
480         /*
481          * return the timer_id now.  The next step is hard to
482          * back out if there is an error.
483          */
484         if (copy_to_user(created_timer_id,
485                          &new_timer_id, sizeof (new_timer_id))) {
486                 error = -EFAULT;
487                 goto out;
488         }
489         if (timer_event_spec) {
490                 if (copy_from_user(&event, timer_event_spec, sizeof (event))) {
491                         error = -EFAULT;
492                         goto out;
493                 }
494                 new_timer->it_sigev_notify = event.sigev_notify;
495                 new_timer->it_sigev_signo = event.sigev_signo;
496                 new_timer->it_sigev_value = event.sigev_value;
497
498                 read_lock(&tasklist_lock);
499                 if ((process = good_sigevent(&event))) {
500                         /*
501                          * We may be setting up this process for another
502                          * thread.  It may be exiting.  To catch this
503                          * case the we check the PF_EXITING flag.  If
504                          * the flag is not set, the siglock will catch
505                          * him before it is too late (in exit_itimers).
506                          *
507                          * The exec case is a bit more invloved but easy
508                          * to code.  If the process is in our thread
509                          * group (and it must be or we would not allow
510                          * it here) and is doing an exec, it will cause
511                          * us to be killed.  In this case it will wait
512                          * for us to die which means we can finish this
513                          * linkage with our last gasp. I.e. no code :)
514                          */
515                         spin_lock_irqsave(&process->sighand->siglock, flags);
516                         if (!(process->flags & PF_EXITING)) {
517                                 new_timer->it_process = process;
518                                 list_add(&new_timer->list,
519                                          &process->signal->posix_timers);
520                                 spin_unlock_irqrestore(&process->sighand->siglock, flags);
521                                 get_task_struct(process);
522                         } else {
523                                 spin_unlock_irqrestore(&process->sighand->siglock, flags);
524                                 process = 0;
525                         }
526                 }
527                 read_unlock(&tasklist_lock);
528                 if (!process) {
529                         error = -EINVAL;
530                         goto out;
531                 }
532         } else {
533                 new_timer->it_sigev_notify = SIGEV_SIGNAL;
534                 new_timer->it_sigev_signo = SIGALRM;
535                 new_timer->it_sigev_value.sival_int = new_timer->it_id;
536                 process = current->group_leader;
537                 spin_lock_irqsave(&process->sighand->siglock, flags);
538                 new_timer->it_process = process;
539                 list_add(&new_timer->list, &process->signal->posix_timers);
540                 spin_unlock_irqrestore(&process->sighand->siglock, flags);
541         }
542
543         /*
544          * In the case of the timer belonging to another task, after
545          * the task is unlocked, the timer is owned by the other task
546          * and may cease to exist at any time.  Don't use or modify
547          * new_timer after the unlock call.
548          */
549
550 out:
551         if (error)
552                 release_posix_timer(new_timer, it_id_set);
553
554         return error;
555 }
556
557 /*
558  * good_timespec
559  *
560  * This function checks the elements of a timespec structure.
561  *
562  * Arguments:
563  * ts        : Pointer to the timespec structure to check
564  *
565  * Return value:
566  * If a NULL pointer was passed in, or the tv_nsec field was less than 0
567  * or greater than NSEC_PER_SEC, or the tv_sec field was less than 0,
568  * this function returns 0. Otherwise it returns 1.
569  */
570 static int good_timespec(const struct timespec *ts)
571 {
572         if ((!ts) || (ts->tv_sec < 0) ||
573                         ((unsigned) ts->tv_nsec >= NSEC_PER_SEC))
574                 return 0;
575         return 1;
576 }
577
578 /*
579  * Locking issues: We need to protect the result of the id look up until
580  * we get the timer locked down so it is not deleted under us.  The
581  * removal is done under the idr spinlock so we use that here to bridge
582  * the find to the timer lock.  To avoid a dead lock, the timer id MUST
583  * be release with out holding the timer lock.
584  */
585 static struct k_itimer * lock_timer(timer_t timer_id, unsigned long *flags)
586 {
587         struct k_itimer *timr;
588         /*
589          * Watch out here.  We do a irqsave on the idr_lock and pass the
590          * flags part over to the timer lock.  Must not let interrupts in
591          * while we are moving the lock.
592          */
593
594         spin_lock_irqsave(&idr_lock, *flags);
595         timr = (struct k_itimer *) idr_find(&posix_timers_id, (int) timer_id);
596         if (timr) {
597                 spin_lock(&timr->it_lock);
598                 spin_unlock(&idr_lock);
599
600                 if ((timr->it_id != timer_id) || !(timr->it_process) ||
601                                 timr->it_process->tgid != current->tgid) {
602                         unlock_timer(timr, *flags);
603                         timr = NULL;
604                 }
605         } else
606                 spin_unlock_irqrestore(&idr_lock, *flags);
607
608         return timr;
609 }
610
611 /*
612  * Get the time remaining on a POSIX.1b interval timer.  This function
613  * is ALWAYS called with spin_lock_irq on the timer, thus it must not
614  * mess with irq.
615  *
616  * We have a couple of messes to clean up here.  First there is the case
617  * of a timer that has a requeue pending.  These timers should appear to
618  * be in the timer list with an expiry as if we were to requeue them
619  * now.
620  *
621  * The second issue is the SIGEV_NONE timer which may be active but is
622  * not really ever put in the timer list (to save system resources).
623  * This timer may be expired, and if so, we will do it here.  Otherwise
624  * it is the same as a requeue pending timer WRT to what we should
625  * report.
626  */
627 static void
628 do_timer_gettime(struct k_itimer *timr, struct itimerspec *cur_setting)
629 {
630         unsigned long expires;
631         struct now_struct now;
632
633         do
634                 expires = timr->it_timer.expires;
635         while ((volatile long) (timr->it_timer.expires) != expires);
636
637         posix_get_now(&now);
638
639         if (expires &&
640             ((timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE) &&
641             !timr->it_incr &&
642             posix_time_before(&timr->it_timer, &now))
643                 timr->it_timer.expires = expires = 0;
644         if (expires) {
645                 if (timr->it_requeue_pending & REQUEUE_PENDING ||
646                     (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE) {
647                         while (posix_time_before(&timr->it_timer, &now))
648                                 posix_bump_timer(timr);
649                         expires = timr->it_timer.expires;
650                 }
651                 else
652                         if (!timer_pending(&timr->it_timer))
653                                 expires = 0;
654                 if (expires)
655                         expires -= now.jiffies;
656         }
657         jiffies_to_timespec(expires, &cur_setting->it_value);
658         jiffies_to_timespec(timr->it_incr, &cur_setting->it_interval);
659
660         if (cur_setting->it_value.tv_sec < 0) {
661                 cur_setting->it_value.tv_nsec = 1;
662                 cur_setting->it_value.tv_sec = 0;
663         }
664 }
665
666 /* Get the time remaining on a POSIX.1b interval timer. */
667 asmlinkage long
668 sys_timer_gettime(timer_t timer_id, struct itimerspec __user *setting)
669 {
670         struct k_itimer *timr;
671         struct itimerspec cur_setting;
672         unsigned long flags;
673
674         timr = lock_timer(timer_id, &flags);
675         if (!timr)
676                 return -EINVAL;
677
678         p_timer_get(&posix_clocks[timr->it_clock], timr, &cur_setting);
679
680         unlock_timer(timr, flags);
681
682         if (copy_to_user(setting, &cur_setting, sizeof (cur_setting)))
683                 return -EFAULT;
684
685         return 0;
686 }
687 /*
688  * Get the number of overruns of a POSIX.1b interval timer.  This is to
689  * be the overrun of the timer last delivered.  At the same time we are
690  * accumulating overruns on the next timer.  The overrun is frozen when
691  * the signal is delivered, either at the notify time (if the info block
692  * is not queued) or at the actual delivery time (as we are informed by
693  * the call back to do_schedule_next_timer().  So all we need to do is
694  * to pick up the frozen overrun.
695  */
696
697 asmlinkage long
698 sys_timer_getoverrun(timer_t timer_id)
699 {
700         struct k_itimer *timr;
701         int overrun;
702         long flags;
703
704         timr = lock_timer(timer_id, &flags);
705         if (!timr)
706                 return -EINVAL;
707
708         overrun = timr->it_overrun_last;
709         unlock_timer(timr, flags);
710
711         return overrun;
712 }
713 /*
714  * Adjust for absolute time
715  *
716  * If absolute time is given and it is not CLOCK_MONOTONIC, we need to
717  * adjust for the offset between the timer clock (CLOCK_MONOTONIC) and
718  * what ever clock he is using.
719  *
720  * If it is relative time, we need to add the current (CLOCK_MONOTONIC)
721  * time to it to get the proper time for the timer.
722  */
723 static int adjust_abs_time(struct k_clock *clock, struct timespec *tp, 
724                            int abs, u64 *exp)
725 {
726         struct timespec now;
727         struct timespec oc = *tp;
728         struct timespec wall_to_mono;
729         u64 jiffies_64_f;
730         int rtn =0;
731
732         if (abs) {
733                 /*
734                  * The mask pick up the 4 basic clocks 
735                  */
736                 if (!(clock - &posix_clocks[0]) & ~CLOCKS_MASK) {
737                         jiffies_64_f = do_posix_clock_monotonic_gettime_parts(
738                                 &now,  &wall_to_mono);
739                         /*
740                          * If we are doing a MONOTONIC clock
741                          */
742                         if((clock - &posix_clocks[0]) & CLOCKS_MONO){
743                                 now.tv_sec += wall_to_mono.tv_sec;
744                                 now.tv_nsec += wall_to_mono.tv_nsec;
745                         }
746                 } else {
747                         /*
748                          * Not one of the basic clocks
749                          */
750                         do_posix_gettime(clock, &now);  
751                         jiffies_64_f = get_jiffies_64();
752                 }
753                 /*
754                  * Take away now to get delta
755                  */
756                 oc.tv_sec -= now.tv_sec;
757                 oc.tv_nsec -= now.tv_nsec;
758                 /*
759                  * Normalize...
760                  */
761                 while ((oc.tv_nsec - NSEC_PER_SEC) >= 0) {
762                         oc.tv_nsec -= NSEC_PER_SEC;
763                         oc.tv_sec++;
764                 }
765                 while ((oc.tv_nsec) < 0) {
766                         oc.tv_nsec += NSEC_PER_SEC;
767                         oc.tv_sec--;
768                 }
769         }else{
770                 jiffies_64_f = get_jiffies_64();
771         }
772         /*
773          * Check if the requested time is prior to now (if so set now)
774          */
775         if (oc.tv_sec < 0)
776                 oc.tv_sec = oc.tv_nsec = 0;
777         tstojiffie(&oc, clock->res, exp);
778
779         /*
780          * Check if the requested time is more than the timer code
781          * can handle (if so we error out but return the value too).
782          */
783         if (*exp > ((u64)MAX_JIFFY_OFFSET))
784                         /*
785                          * This is a considered response, not exactly in
786                          * line with the standard (in fact it is silent on
787                          * possible overflows).  We assume such a large 
788                          * value is ALMOST always a programming error and
789                          * try not to compound it by setting a really dumb
790                          * value.
791                          */
792                         rtn = -EINVAL;
793         /*
794          * return the actual jiffies expire time, full 64 bits
795          */
796         *exp += jiffies_64_f;
797         return rtn;
798 }
799
800 /* Set a POSIX.1b interval timer. */
801 /* timr->it_lock is taken. */
802 static inline int
803 do_timer_settime(struct k_itimer *timr, int flags,
804                  struct itimerspec *new_setting, struct itimerspec *old_setting)
805 {
806         struct k_clock *clock = &posix_clocks[timr->it_clock];
807         u64 expire_64;
808
809         if (old_setting)
810                 do_timer_gettime(timr, old_setting);
811
812         /* disable the timer */
813         timr->it_incr = 0;
814         /*
815          * careful here.  If smp we could be in the "fire" routine which will
816          * be spinning as we hold the lock.  But this is ONLY an SMP issue.
817          */
818 #ifdef CONFIG_SMP
819         if (timer_active(timr) && !del_timer(&timr->it_timer))
820                 /*
821                  * It can only be active if on an other cpu.  Since
822                  * we have cleared the interval stuff above, it should
823                  * clear once we release the spin lock.  Of course once
824                  * we do that anything could happen, including the
825                  * complete melt down of the timer.  So return with
826                  * a "retry" exit status.
827                  */
828                 return TIMER_RETRY;
829
830         set_timer_inactive(timr);
831 #else
832         del_timer(&timr->it_timer);
833 #endif
834         timr->it_requeue_pending = (timr->it_requeue_pending + 2) & 
835                 ~REQUEUE_PENDING;
836         timr->it_overrun_last = 0;
837         timr->it_overrun = -1;
838         /*
839          *switch off the timer when it_value is zero
840          */
841         if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec) {
842                 timr->it_timer.expires = 0;
843                 return 0;
844         }
845
846         if (adjust_abs_time(clock,
847                             &new_setting->it_value, flags & TIMER_ABSTIME, 
848                             &expire_64)) {
849                 return -EINVAL;
850         }
851         timr->it_timer.expires = (unsigned long)expire_64;      
852         tstojiffie(&new_setting->it_interval, clock->res, &expire_64);
853         timr->it_incr = (unsigned long)expire_64;
854
855
856         /*
857          * For some reason the timer does not fire immediately if expires is
858          * equal to jiffies, so the timer notify function is called directly.
859          * We do not even queue SIGEV_NONE timers!
860          */
861         if (((timr->it_sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE)) {
862                 if (timr->it_timer.expires == jiffies)
863                         timer_notify_task(timr);
864                 else
865                         add_timer(&timr->it_timer);
866         }
867         return 0;
868 }
869
870 /* Set a POSIX.1b interval timer */
871 asmlinkage long
872 sys_timer_settime(timer_t timer_id, int flags,
873                   const struct itimerspec __user *new_setting,
874                   struct itimerspec __user *old_setting)
875 {
876         struct k_itimer *timr;
877         struct itimerspec new_spec, old_spec;
878         int error = 0;
879         long flag;
880         struct itimerspec *rtn = old_setting ? &old_spec : NULL;
881
882         if (!new_setting)
883                 return -EINVAL;
884
885         if (copy_from_user(&new_spec, new_setting, sizeof (new_spec)))
886                 return -EFAULT;
887
888         if ((!good_timespec(&new_spec.it_interval)) ||
889             (!good_timespec(&new_spec.it_value)))
890                 return -EINVAL;
891 retry:
892         timr = lock_timer(timer_id, &flag);
893         if (!timr)
894                 return -EINVAL;
895
896         if (!posix_clocks[timr->it_clock].timer_set)
897                 error = do_timer_settime(timr, flags, &new_spec, rtn);
898         else
899                 error = posix_clocks[timr->it_clock].timer_set(timr,
900                                                                flags,
901                                                                &new_spec, rtn);
902         unlock_timer(timr, flag);
903         if (error == TIMER_RETRY) {
904                 rtn = NULL;     // We already got the old time...
905                 goto retry;
906         }
907
908         if (old_setting && !error && copy_to_user(old_setting,
909                                                   &old_spec, sizeof (old_spec)))
910                 error = -EFAULT;
911
912         return error;
913 }
914
915 static inline int do_timer_delete(struct k_itimer *timer)
916 {
917         timer->it_incr = 0;
918 #ifdef CONFIG_SMP
919         if (timer_active(timer) && !del_timer(&timer->it_timer))
920                 /*
921                  * It can only be active if on an other cpu.  Since
922                  * we have cleared the interval stuff above, it should
923                  * clear once we release the spin lock.  Of course once
924                  * we do that anything could happen, including the
925                  * complete melt down of the timer.  So return with
926                  * a "retry" exit status.
927                  */
928                 return TIMER_RETRY;
929 #else
930         del_timer(&timer->it_timer);
931 #endif
932         return 0;
933 }
934
935 /* Delete a POSIX.1b interval timer. */
936 asmlinkage long
937 sys_timer_delete(timer_t timer_id)
938 {
939         struct k_itimer *timer;
940         long flags;
941
942 #ifdef CONFIG_SMP
943         int error;
944 retry_delete:
945 #endif
946         timer = lock_timer(timer_id, &flags);
947         if (!timer)
948                 return -EINVAL;
949
950 #ifdef CONFIG_SMP
951         error = p_timer_del(&posix_clocks[timer->it_clock], timer);
952
953         if (error == TIMER_RETRY) {
954                 unlock_timer(timer, flags);
955                 goto retry_delete;
956         }
957 #else
958         p_timer_del(&posix_clocks[timer->it_clock], timer);
959 #endif
960         spin_lock(&current->sighand->siglock);
961         list_del(&timer->list);
962         spin_unlock(&current->sighand->siglock);
963         /*
964          * This keeps any tasks waiting on the spin lock from thinking
965          * they got something (see the lock code above).
966          */
967         if (timer->it_process) {
968                 if (timer->it_sigev_notify == (SIGEV_SIGNAL|SIGEV_THREAD_ID))
969                         put_task_struct(timer->it_process);
970         timer->it_process = NULL;
971         }
972         unlock_timer(timer, flags);
973         release_posix_timer(timer, IT_ID_SET);
974         return 0;
975 }
976 /*
977  * return timer owned by the process, used by exit_itimers
978  */
979 static inline void itimer_delete(struct k_itimer *timer)
980 {
981         unsigned long flags;
982
983 #ifdef CONFIG_SMP
984         int error;
985 retry_delete:
986 #endif
987         spin_lock_irqsave(&timer->it_lock, flags);
988
989 #ifdef CONFIG_SMP
990         error = p_timer_del(&posix_clocks[timer->it_clock], timer);
991
992         if (error == TIMER_RETRY) {
993                 unlock_timer(timer, flags);
994                 goto retry_delete;
995         }
996 #else
997         p_timer_del(&posix_clocks[timer->it_clock], timer);
998 #endif
999         list_del(&timer->list);
1000         /*
1001          * This keeps any tasks waiting on the spin lock from thinking
1002          * they got something (see the lock code above).
1003          */
1004         if (timer->it_process) {
1005                 if (timer->it_sigev_notify == (SIGEV_SIGNAL|SIGEV_THREAD_ID))
1006                         put_task_struct(timer->it_process);
1007                 timer->it_process = NULL;
1008         }
1009         unlock_timer(timer, flags);
1010         release_posix_timer(timer, IT_ID_SET);
1011 }
1012
1013 /*
1014  * This is called by __exit_signal, only when there are no more
1015  * references to the shared signal_struct.
1016  */
1017 void exit_itimers(struct signal_struct *sig)
1018 {
1019         struct k_itimer *tmr;
1020
1021         while (!list_empty(&sig->posix_timers)) {
1022                 tmr = list_entry(sig->posix_timers.next, struct k_itimer, list);
1023                 itimer_delete(tmr);
1024         }
1025 }
1026
1027 /*
1028  * And now for the "clock" calls
1029  *
1030  * These functions are called both from timer functions (with the timer
1031  * spin_lock_irq() held and from clock calls with no locking.   They must
1032  * use the save flags versions of locks.
1033  */
1034 static int do_posix_gettime(struct k_clock *clock, struct timespec *tp)
1035 {
1036         struct timeval tv;
1037
1038         if (clock->clock_get)
1039                 return clock->clock_get(tp);
1040
1041         do_gettimeofday(&tv);
1042         tp->tv_sec = tv.tv_sec;
1043         tp->tv_nsec = tv.tv_usec * NSEC_PER_USEC;
1044
1045         return 0;
1046 }
1047
1048 /*
1049  * We do ticks here to avoid the irq lock ( they take sooo long).
1050  * The seqlock is great here.  Since we a reader, we don't really care
1051  * if we are interrupted since we don't take lock that will stall us or
1052  * any other cpu. Voila, no irq lock is needed.
1053  *
1054  */
1055
1056 static u64 do_posix_clock_monotonic_gettime_parts(
1057         struct timespec *tp, struct timespec *mo)
1058 {
1059         u64 jiff;
1060         struct timeval tpv;
1061         unsigned int seq;
1062
1063         do {
1064                 seq = read_seqbegin(&xtime_lock);
1065                 do_gettimeofday(&tpv);
1066                 *mo = wall_to_monotonic;
1067                 jiff = jiffies_64;
1068
1069         } while(read_seqretry(&xtime_lock, seq));
1070
1071         /*
1072          * Love to get this before it is converted to usec.
1073          * It would save a div AND a mpy.
1074          */
1075         tp->tv_sec = tpv.tv_sec;
1076         tp->tv_nsec = tpv.tv_usec * NSEC_PER_USEC;
1077
1078         return jiff;
1079 }
1080
1081 int do_posix_clock_monotonic_gettime(struct timespec *tp)
1082 {
1083         struct timespec wall_to_mono;
1084
1085         do_posix_clock_monotonic_gettime_parts(tp, &wall_to_mono);
1086
1087         tp->tv_sec += wall_to_mono.tv_sec;
1088         tp->tv_nsec += wall_to_mono.tv_nsec;
1089
1090         if ((tp->tv_nsec - NSEC_PER_SEC) > 0) {
1091                 tp->tv_nsec -= NSEC_PER_SEC;
1092                 tp->tv_sec++;
1093         }
1094         return 0;
1095 }
1096
1097 int do_posix_clock_monotonic_settime(struct timespec *tp)
1098 {
1099         return -EINVAL;
1100 }
1101
1102 asmlinkage long
1103 sys_clock_settime(clockid_t which_clock, const struct timespec __user *tp)
1104 {
1105         struct timespec new_tp;
1106
1107         if ((unsigned) which_clock >= MAX_CLOCKS ||
1108                                         !posix_clocks[which_clock].res)
1109                 return -EINVAL;
1110         if (copy_from_user(&new_tp, tp, sizeof (*tp)))
1111                 return -EFAULT;
1112         if (posix_clocks[which_clock].clock_set)
1113                 return posix_clocks[which_clock].clock_set(&new_tp);
1114
1115         return do_sys_settimeofday(&new_tp, NULL);
1116 }
1117
1118 asmlinkage long
1119 sys_clock_gettime(clockid_t which_clock, struct timespec __user *tp)
1120 {
1121         struct timespec rtn_tp;
1122         int error = 0;
1123
1124         if ((unsigned) which_clock >= MAX_CLOCKS ||
1125                                         !posix_clocks[which_clock].res)
1126                 return -EINVAL;
1127
1128         error = do_posix_gettime(&posix_clocks[which_clock], &rtn_tp);
1129
1130         if (!error && copy_to_user(tp, &rtn_tp, sizeof (rtn_tp)))
1131                 error = -EFAULT;
1132
1133         return error;
1134
1135 }
1136
1137 asmlinkage long
1138 sys_clock_getres(clockid_t which_clock, struct timespec __user *tp)
1139 {
1140         struct timespec rtn_tp;
1141
1142         if ((unsigned) which_clock >= MAX_CLOCKS ||
1143                                         !posix_clocks[which_clock].res)
1144                 return -EINVAL;
1145
1146         rtn_tp.tv_sec = 0;
1147         rtn_tp.tv_nsec = posix_clocks[which_clock].res;
1148         if (tp && copy_to_user(tp, &rtn_tp, sizeof (rtn_tp)))
1149                 return -EFAULT;
1150
1151         return 0;
1152
1153 }
1154
1155 static void nanosleep_wake_up(unsigned long __data)
1156 {
1157         struct task_struct *p = (struct task_struct *) __data;
1158
1159         wake_up_process(p);
1160 }
1161
1162 /*
1163  * The standard says that an absolute nanosleep call MUST wake up at
1164  * the requested time in spite of clock settings.  Here is what we do:
1165  * For each nanosleep call that needs it (only absolute and not on
1166  * CLOCK_MONOTONIC* (as it can not be set)) we thread a little structure
1167  * into the "nanosleep_abs_list".  All we need is the task_struct pointer.
1168  * When ever the clock is set we just wake up all those tasks.   The rest
1169  * is done by the while loop in clock_nanosleep().
1170  *
1171  * On locking, clock_was_set() is called from update_wall_clock which
1172  * holds (or has held for it) a write_lock_irq( xtime_lock) and is
1173  * called from the timer bh code.  Thus we need the irq save locks.
1174  */
1175
1176 static DECLARE_WAIT_QUEUE_HEAD(nanosleep_abs_wqueue);
1177
1178 void clock_was_set(void)
1179 {
1180         wake_up_all(&nanosleep_abs_wqueue);
1181 }
1182
1183 long clock_nanosleep_restart(struct restart_block *restart_block);
1184
1185 extern long do_clock_nanosleep(clockid_t which_clock, int flags,
1186                                struct timespec *t);
1187
1188 asmlinkage long
1189 sys_clock_nanosleep(clockid_t which_clock, int flags,
1190                     const struct timespec __user *rqtp,
1191                     struct timespec __user *rmtp)
1192 {
1193         struct timespec t;
1194         struct restart_block *restart_block =
1195             &(current_thread_info()->restart_block);
1196         int ret;
1197
1198         if ((unsigned) which_clock >= MAX_CLOCKS ||
1199                                         !posix_clocks[which_clock].res)
1200                 return -EINVAL;
1201
1202         if (copy_from_user(&t, rqtp, sizeof (struct timespec)))
1203                 return -EFAULT;
1204
1205         if ((unsigned) t.tv_nsec >= NSEC_PER_SEC || t.tv_sec < 0)
1206                 return -EINVAL;
1207
1208         ret = do_clock_nanosleep(which_clock, flags, &t);
1209         /*
1210          * Do this here as do_clock_nanosleep does not have the real address
1211          */
1212         restart_block->arg1 = (unsigned long)rmtp;
1213
1214         if ((ret == -ERESTART_RESTARTBLOCK) && rmtp &&
1215                                         copy_to_user(rmtp, &t, sizeof (t)))
1216                 return -EFAULT;
1217         return ret;
1218 }
1219
1220 long
1221 do_clock_nanosleep(clockid_t which_clock, int flags, struct timespec *tsave)
1222 {
1223         struct timespec t;
1224         struct timer_list new_timer;
1225         DECLARE_WAITQUEUE(abs_wqueue, current);
1226         u64 rq_time = (u64)0;
1227         s64 left;
1228         int abs;
1229         struct restart_block *restart_block =
1230             &current_thread_info()->restart_block;
1231
1232         abs_wqueue.flags = 0;
1233         init_timer(&new_timer);
1234         new_timer.expires = 0;
1235         new_timer.data = (unsigned long) current;
1236         new_timer.function = nanosleep_wake_up;
1237         abs = flags & TIMER_ABSTIME;
1238
1239         if (restart_block->fn == clock_nanosleep_restart) {
1240                 /*
1241                  * Interrupted by a non-delivered signal, pick up remaining
1242                  * time and continue.  Remaining time is in arg2 & 3.
1243                  */
1244                 restart_block->fn = do_no_restart_syscall;
1245
1246                 rq_time = restart_block->arg3;
1247                 rq_time = (rq_time << 32) + restart_block->arg2;
1248                 if (!rq_time)
1249                         return -EINTR;
1250                 left = rq_time - get_jiffies_64();
1251                 if (left <= (s64)0)
1252                         return 0;       /* Already passed */
1253         }
1254
1255         if (abs && (posix_clocks[which_clock].clock_get !=
1256                             posix_clocks[CLOCK_MONOTONIC].clock_get))
1257                 add_wait_queue(&nanosleep_abs_wqueue, &abs_wqueue);
1258
1259         do {
1260                 t = *tsave;
1261                 if (abs || !rq_time) {
1262                         adjust_abs_time(&posix_clocks[which_clock], &t, abs,
1263                                         &rq_time);
1264                         rq_time += (t.tv_sec || t.tv_nsec);
1265                 }
1266
1267                 left = rq_time - get_jiffies_64();
1268                 if (left >= (s64)MAX_JIFFY_OFFSET)
1269                         left = (s64)MAX_JIFFY_OFFSET;
1270                 if (left < (s64)0)
1271                         break;
1272
1273                 new_timer.expires = jiffies + left;
1274                 __set_current_state(TASK_INTERRUPTIBLE);
1275                 add_timer(&new_timer);
1276
1277                 schedule();
1278
1279                 del_timer_sync(&new_timer);
1280                 left = rq_time - get_jiffies_64();
1281         } while (left > (s64)0 && !test_thread_flag(TIF_SIGPENDING));
1282
1283         if (abs_wqueue.task_list.next)
1284                 finish_wait(&nanosleep_abs_wqueue, &abs_wqueue);
1285
1286         if (left > (s64)0) {
1287
1288                 /*
1289                  * Always restart abs calls from scratch to pick up any
1290                  * clock shifting that happened while we are away.
1291                  */
1292                 if (abs)
1293                         return -ERESTARTNOHAND;
1294
1295                 left *= TICK_NSEC;
1296                 tsave->tv_sec = div_long_long_rem(left, 
1297                                                   NSEC_PER_SEC, 
1298                                                   &tsave->tv_nsec);
1299                 /*
1300                  * Restart works by saving the time remaing in 
1301                  * arg2 & 3 (it is 64-bits of jiffies).  The other
1302                  * info we need is the clock_id (saved in arg0). 
1303                  * The sys_call interface needs the users 
1304                  * timespec return address which _it_ saves in arg1.
1305                  * Since we have cast the nanosleep call to a clock_nanosleep
1306                  * both can be restarted with the same code.
1307                  */
1308                 restart_block->fn = clock_nanosleep_restart;
1309                 restart_block->arg0 = which_clock;
1310                 /*
1311                  * Caller sets arg1
1312                  */
1313                 restart_block->arg2 = rq_time & 0xffffffffLL;
1314                 restart_block->arg3 = rq_time >> 32;
1315
1316                 return -ERESTART_RESTARTBLOCK;
1317         }
1318
1319         return 0;
1320 }
1321 /*
1322  * This will restart clock_nanosleep.
1323  */
1324 long
1325 clock_nanosleep_restart(struct restart_block *restart_block)
1326 {
1327         struct timespec t;
1328         int ret = do_clock_nanosleep(restart_block->arg0, 0, &t);
1329
1330         if ((ret == -ERESTART_RESTARTBLOCK) && restart_block->arg1 &&
1331             copy_to_user((struct timespec __user *)(restart_block->arg1), &t,
1332                          sizeof (t)))
1333                 return -EFAULT;
1334         return ret;
1335 }