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