1
2
3
4
5
6
7
8
9
10
11
12
13
14
15#include <linux/export.h>
16#include <linux/sched.h>
17#include <linux/timex.h>
18#include <linux/preempt.h>
19#include <linux/delay.h>
20
21#include <asm/processor.h>
22#include <asm/delay.h>
23#include <asm/timer.h>
24#include <asm/mwait.h>
25
26#ifdef CONFIG_SMP
27# include <asm/smp.h>
28#endif
29
30
31static void delay_loop(unsigned long loops)
32{
33 asm volatile(
34 " test %0,%0 \n"
35 " jz 3f \n"
36 " jmp 1f \n"
37
38 ".align 16 \n"
39 "1: jmp 2f \n"
40
41 ".align 16 \n"
42 "2: dec %0 \n"
43 " jnz 2b \n"
44 "3: dec %0 \n"
45
46 :
47 :"a" (loops)
48 );
49}
50
51
52static void delay_tsc(unsigned long __loops)
53{
54 u64 bclock, now, loops = __loops;
55 int cpu;
56
57 preempt_disable();
58 cpu = smp_processor_id();
59 bclock = rdtsc_ordered();
60 for (;;) {
61 now = rdtsc_ordered();
62 if ((now - bclock) >= loops)
63 break;
64
65
66 preempt_enable();
67 rep_nop();
68 preempt_disable();
69
70
71
72
73
74
75
76
77
78
79 if (unlikely(cpu != smp_processor_id())) {
80 loops -= (now - bclock);
81 cpu = smp_processor_id();
82 bclock = rdtsc_ordered();
83 }
84 }
85 preempt_enable();
86}
87
88
89
90
91
92
93static void delay_mwaitx(unsigned long __loops)
94{
95 u64 start, end, delay, loops = __loops;
96
97
98
99
100
101 if (loops == 0)
102 return;
103
104 start = rdtsc_ordered();
105
106 for (;;) {
107 delay = min_t(u64, MWAITX_MAX_LOOPS, loops);
108
109
110
111
112
113 __monitorx(raw_cpu_ptr(&cpu_tss_rw), 0, 0);
114
115
116
117
118
119
120 __mwaitx(MWAITX_DISABLE_CSTATES, delay, MWAITX_ECX_TIMER_ENABLE);
121
122 end = rdtsc_ordered();
123
124 if (loops <= end - start)
125 break;
126
127 loops -= end - start;
128
129 start = end;
130 }
131}
132
133
134
135
136
137static void (*delay_fn)(unsigned long) = delay_loop;
138
139void use_tsc_delay(void)
140{
141 if (delay_fn == delay_loop)
142 delay_fn = delay_tsc;
143}
144
145void use_mwaitx_delay(void)
146{
147 delay_fn = delay_mwaitx;
148}
149
150int read_current_timer(unsigned long *timer_val)
151{
152 if (delay_fn == delay_tsc) {
153 *timer_val = rdtsc();
154 return 0;
155 }
156 return -1;
157}
158
159void __delay(unsigned long loops)
160{
161 delay_fn(loops);
162}
163EXPORT_SYMBOL(__delay);
164
165noinline void __const_udelay(unsigned long xloops)
166{
167 unsigned long lpj = this_cpu_read(cpu_info.loops_per_jiffy) ? : loops_per_jiffy;
168 int d0;
169
170 xloops *= 4;
171 asm("mull %%edx"
172 :"=d" (xloops), "=&a" (d0)
173 :"1" (xloops), "0" (lpj * (HZ / 4)));
174
175 __delay(++xloops);
176}
177EXPORT_SYMBOL(__const_udelay);
178
179void __udelay(unsigned long usecs)
180{
181 __const_udelay(usecs * 0x000010c7);
182}
183EXPORT_SYMBOL(__udelay);
184
185void __ndelay(unsigned long nsecs)
186{
187 __const_udelay(nsecs * 0x00005);
188}
189EXPORT_SYMBOL(__ndelay);
190