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