+static int gp2x_read_battery_(void)
+{
+ unsigned short magic_val = 0;
+
+ if (battdev < 0)
+ return -1;
+ if (read(battdev, &magic_val, sizeof(magic_val)) != sizeof(magic_val))
+ return -1;
+ switch (magic_val) {
+ default:
+ case 1: return 100;
+ case 2: return 66;
+ case 3: return 40;
+ case 4: return 0;
+ }
+}
+
+#define TIMER_BASE3 0x1980
+#define TIMER_REG(x) memregl[(TIMER_BASE3 + x) >> 2]
+
+static unsigned int gp2x_get_ticks_us_(void)
+{
+ TIMER_REG(0x08) = 0x4b; /* run timer, latch value */
+ return TIMER_REG(0);
+}
+
+static unsigned int gp2x_get_ticks_ms_(void)
+{
+ /* approximate /= 1000 */
+ unsigned long long v64;
+ v64 = (unsigned long long)gp2x_get_ticks_us_() * 4294968;
+ return v64 >> 32;
+}
+
+static void timer_cleanup(void)
+{
+ TIMER_REG(0x40) = 0x0c; /* be sure clocks are on */
+ TIMER_REG(0x08) = 0x23; /* stop the timer, clear irq in case it's pending */
+ TIMER_REG(0x00) = 0; /* clear counter */
+ TIMER_REG(0x40) = 0; /* clocks off */
+ TIMER_REG(0x44) = 0; /* dividers back to default */
+}
+
+/* note: both PLLs are programmed the same way,
+ * the databook incorrectly states that PLL1 differs */
+static int decode_pll(unsigned int reg)
+{
+ long long v;
+ int p, m, s;
+
+ p = (reg >> 18) & 0x3f;
+ m = (reg >> 8) & 0x3ff;
+ s = reg & 0xff;
+
+ if (p == 0)
+ p = 1;
+
+ v = 27000000; // master clock
+ v = v * m / (p << s);
+ return v;
+}
+
+int pollux_get_real_snd_rate(int req_rate)
+{
+ int clk0_src, clk1_src, rate, div;
+
+ clk0_src = (memregl[0xdbc4>>2] >> 1) & 7;
+ clk1_src = (memregl[0xdbc8>>2] >> 1) & 7;
+ if (clk0_src > 1 || clk1_src != 7) {
+ fprintf(stderr, "get_real_snd_rate: bad clk sources: %d %d\n", clk0_src, clk1_src);
+ return req_rate;
+ }
+
+ rate = decode_pll(clk0_src ? memregl[0xf008>>2] : memregl[0xf004>>2]);
+
+ // apply divisors
+ div = ((memregl[0xdbc4>>2] >> 4) & 0x3f) + 1;
+ rate /= div;
+ div = ((memregl[0xdbc8>>2] >> 4) & 0x3f) + 1;
+ rate /= div;
+ rate /= 64;
+
+ //printf("rate %d\n", rate);
+ rate -= rate * timer_drift / 1000000;
+ printf("adjusted rate: %d\n", rate);
+
+ if (rate < 8000-1000 || rate > 44100+1000) {
+ fprintf(stderr, "get_real_snd_rate: got bad rate: %d\n", rate);
+ return req_rate;
+ }
+
+ return rate;
+}
+