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