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