Revert "Remove support for xpp drivers."
[dahdi/linux.git] / drivers / dahdi / xpp / xbus-pcm.c
1 /*
2  * Written by Oron Peled <oron@actcom.co.il>
3  * Copyright (C) 2004-2007, Xorcom
4  *
5  * All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22 #include <linux/version.h>
23 #include <linux/kernel.h>
24 #include <linux/module.h>
25 #include "xbus-pcm.h"
26 #include "xbus-core.h"
27 #include "xpp_dahdi.h"
28 #include "dahdi_debug.h"
29 #include "parport_debug.h"
30
31 static const char rcsid[] = "$Id$";
32
33 extern int debug;
34 #ifdef  OPTIMIZE_CHANMUTE
35 static DEF_PARM_BOOL(optimize_chanmute, 1, 0644,
36                      "Optimize by muting inactive channels");
37 #endif
38
39 static DEF_PARM(int, disable_pcm, 0, 0644, "Disable all PCM transmissions");
40 #ifdef  DEBUG_PCMTX
41 DEF_PARM(int, pcmtx, -1, 0644,
42          "Forced PCM value to transmit (negative to disable)");
43 EXPORT_SYMBOL(pcmtx);
44 DEF_PARM(int, pcmtx_chan, 0, 0644, "channel to force PCM value");
45 EXPORT_SYMBOL(pcmtx_chan);
46 #endif
47 static DEF_PARM_BOOL(disable_pll_sync, 0, 0644,
48                      "Disable automatic adjustment of AB clocks");
49
50 static xbus_t *syncer;          /* current syncer */
51 static atomic_t xpp_tick_counter = ATOMIC_INIT(0);
52 static struct xpp_ticker dahdi_ticker;
53 /*
54  * The ref_ticker points to the current referece tick source.
55  * I.e: one of our AB or dahdi_ticker
56  */
57 static struct xpp_ticker *ref_ticker;
58 static DEFINE_SPINLOCK(ref_ticker_lock);
59 static DEFINE_SPINLOCK(elect_syncer_lock);
60 /* from /sys/bus/astribanks/drivers/xppdrv/sync */
61 static bool force_dahdi_sync;
62 static xbus_t *global_ticker;
63 static struct xpp_ticker global_ticks_series;
64
65 #define PROC_SYNC               "sync"
66 /* Sampling cycle in usec */
67 #define SYNC_CYCLE              500
68 /* Samples from end of SYNC_CYCLE */
69 #define SYNC_CYCLE_SAMPLE       100
70 /* Number of SYNC_CYCLE's to converge speed */
71 #define SYNC_CONVERGE           10
72 /* Offset from ref_ticker to other AB's */
73 #define SYNC_CENTER             500
74 /* If within +/-SYNC_DELTA, try to stay there */
75 #define SYNC_DELTA              40
76 #define BIG_TICK_INTERVAL       1000
77 /* maximal firmware drift unit (hardware limit 63) */
78 #define SYNC_ADJ_MAX            20
79
80 /*
81  * The USB bulk endpoints have a large jitter in the timing of frames
82  * from the AB to the ehci-hcd. This is because we cannot predict
83  * in which USB micro-frame our data passes. Each micro-frame is
84  * A 125 usec.
85  */
86 #define SYNC_ADJ_QUICK  1000
87 #define SYNC_ADJ_SLOW   10000
88
89 #ifdef  DAHDI_SYNC_TICK
90 static unsigned int dahdi_tick_count;
91 #endif
92
93 /*------------------------- SYNC Handling --------------------------*/
94
95 static void send_drift(xbus_t *xbus, int drift);
96
97 static void ticker_set_cycle(struct xpp_ticker *ticker, int cycle)
98 {
99         unsigned long flags;
100
101         spin_lock_irqsave(&ticker->lock, flags);
102         if (cycle < SYNC_ADJ_QUICK)
103                 cycle = SYNC_ADJ_QUICK;
104         if (cycle > SYNC_ADJ_SLOW)
105                 cycle = SYNC_ADJ_SLOW;
106         ticker->cycle = cycle;
107         spin_unlock_irqrestore(&ticker->lock, flags);
108 }
109
110 static void xpp_ticker_init(struct xpp_ticker *ticker)
111 {
112         memset(ticker, 0, sizeof(*ticker));
113         spin_lock_init(&ticker->lock);
114         do_gettimeofday(&ticker->last_sample.tv);
115         ticker->first_sample = ticker->last_sample;
116         ticker_set_cycle(ticker, SYNC_ADJ_QUICK);
117 }
118
119 static int xpp_ticker_step(struct xpp_ticker *ticker, const struct timeval *t)
120 {
121         unsigned long flags;
122         long usec;
123         bool cycled = 0;
124
125         spin_lock_irqsave(&ticker->lock, flags);
126         ticker->last_sample.tv = *t;
127         /* rate adjust */
128         if ((ticker->count % ticker->cycle) == ticker->cycle - 1) {
129                 usec =
130                     (long)usec_diff(&ticker->last_sample.tv,
131                                     &ticker->first_sample.tv);
132                 ticker->first_sample = ticker->last_sample;
133                 ticker->tick_period = usec / ticker->cycle;
134                 cycled = 1;
135         }
136         ticker->count++;
137         spin_unlock_irqrestore(&ticker->lock, flags);
138         return cycled;
139 }
140
141 /*
142  * No locking. It is called only from:
143  *   - update_sync_master() in a globall spinlock protected code.
144  *   - initalization.
145  */
146 static inline void xbus_drift_clear(xbus_t *xbus)
147 {
148         struct xpp_drift *di = &xbus->drift;
149
150         do_gettimeofday(&di->last_lost_tick.tv);
151         ticker_set_cycle(&xbus->ticker, SYNC_ADJ_QUICK);
152         di->max_speed = -SYNC_ADJ_MAX;
153         di->min_speed = SYNC_ADJ_MAX;
154 }
155
156 void xpp_drift_init(xbus_t *xbus)
157 {
158         memset(&xbus->drift, 0, sizeof(xbus->drift));
159         spin_lock_init(&xbus->drift.lock);
160         xpp_ticker_init(&xbus->ticker);
161         xbus_drift_clear(xbus);
162 }
163
164 #ifdef  SAMPLE_TICKS
165 static void sample_tick(xbus_t *xbus, int sample)
166 {
167         if (!xbus->sample_running)
168                 return;
169         if (xbus->sample_pos < SAMPLE_SIZE)
170                 xbus->sample_ticks[xbus->sample_pos++] = sample;
171         else {
172                 xbus->sample_running = 0;
173                 xbus->sample_pos = 0;
174         }
175 }
176 #else
177 #define sample_tick(x, y)
178 #endif
179
180 /*
181  * The following function adjust the clock of an astribank according
182  * to our reference clock (another astribank or another DAHDI device).
183  *
184  * It is VERY hard to stabilise these corrections:
185  *    - The measurments are affected by 125usec USB micro-frames.
186  *    - However, if we are off by more than +/-500usec we are risking
187  *      loosing frames.
188  *
189  * Every change must be tested rigorously with many device combinations
190  * including abrupt changes in sync -- to verify the stability of the
191  * algorithm.
192  */
193 static void xpp_drift_step(xbus_t *xbus, const struct timeval *tv)
194 {
195         struct xpp_drift *di = &xbus->drift;
196         struct xpp_ticker *ticker = &xbus->ticker;
197         unsigned long flags;
198
199         spin_lock_irqsave(&di->lock, flags);
200         xpp_ticker_step(&xbus->ticker, tv);
201         /*
202          * Do we need to be synchronized and is there an established reference
203          * ticker (another Astribank or another DAHDI device) already?
204          */
205         if (ref_ticker && ref_ticker != &xbus->ticker && syncer
206             && xbus->sync_mode == SYNC_MODE_PLL) {
207                 int new_delta_tick = ticker->count - ref_ticker->count;
208                 int lost_ticks = new_delta_tick - di->delta_tick;
209                 long usec_delta;
210
211                 di->delta_tick = new_delta_tick;
212                 if (lost_ticks) {
213                         static int rate_limit;
214
215                         /*
216                          * We just lost some ticks. Just report it and don't
217                          * try to adjust anything until we are stable again.
218                          */
219                         di->lost_ticks++;
220                         di->lost_tick_count += abs(lost_ticks);
221                         if ((rate_limit++ % 1003) == 0) {
222                                 /* FIXME: This should be a NOTICE.
223                                  * However we have several false ones at
224                                  * startup.
225                                  */
226                                 XBUS_DBG(SYNC, xbus, "Lost %d tick%s\n",
227                                          lost_ticks,
228                                          (abs(lost_ticks) > 1) ? "s" : "");
229                         }
230                         if (abs(lost_ticks) > 100) {
231                                 xbus_drift_clear(xbus);
232                                 ticker->count = ref_ticker->count;
233                         }
234                 } else {
235                         /* Sample a delta */
236                         usec_delta =
237                             (long)usec_diff(&ticker->last_sample.tv,
238                                             &ref_ticker->last_sample.tv);
239                         sample_tick(xbus, usec_delta);
240                         if ((ticker->count % SYNC_CYCLE) >
241                             (SYNC_CYCLE - SYNC_CYCLE_SAMPLE))
242                                 di->delta_sum += usec_delta;
243
244                         if ((ticker->count % SYNC_CYCLE) == 0) {
245                                 /*
246                                  * Full sampling cycle passed. Let's calculate
247                                  */
248                                 int offset =
249                                     di->delta_sum / SYNC_CYCLE_SAMPLE -
250                                     SYNC_CENTER;
251                                 int offset_prev = di->offset_prev;
252                                 int speed = xbus->sync_adjustment;
253                                 int fix = 0;
254                                 int best_speed =
255                                     (di->max_speed + di->min_speed) >> 1;
256
257                                 if (offset > 0 && offset < SYNC_DELTA) {
258                                         speed = best_speed - 1;
259                                 } else if (offset < 0 && offset > -SYNC_DELTA) {
260                                         speed = best_speed + 1;
261                                 } else {
262                                         if (offset > 0) {
263                                                 if (offset > offset_prev)
264                                                         fix--;
265                                         } else {
266                                                 if (offset < offset_prev)
267                                                         fix++;
268                                         }
269                                         speed += fix;
270                                 }
271                                 if (speed < -SYNC_ADJ_MAX)
272                                         speed = -SYNC_ADJ_MAX;
273                                 if (speed > SYNC_ADJ_MAX)
274                                         speed = SYNC_ADJ_MAX;
275                                 if (speed < di->min_speed)
276                                         di->min_speed = speed;
277                                 if (speed > di->max_speed)
278                                         di->max_speed = speed;
279                                 if (offset > di->offset_max)
280                                         di->offset_max = offset;
281                                 if (offset < di->offset_min)
282                                         di->offset_min = offset;
283
284                                 XBUS_DBG(SYNC, xbus,
285                                         "offset: %d, min_speed=%d, "
286                                         "max_speed=%d, usec_delta(last)=%ld\n",
287                                         offset_prev, di->min_speed,
288                                         di->max_speed, usec_delta);
289                                 XBUS_DBG(SYNC, xbus,
290                                         "ADJ: speed=%d (best_speed=%d) fix=%d\n",
291                                         speed, best_speed, fix);
292                                 xbus->sync_adjustment_offset = speed;
293                                 if (xbus != syncer
294                                     && xbus->sync_adjustment != speed)
295                                         send_drift(xbus, speed);
296                                 di->sync_inaccuracy =
297                                     abs(offset) + abs(di->offset_range) / 2;
298                                 if (ticker->count >= SYNC_CYCLE * SYNC_CONVERGE) {
299                                         di->offset_range =
300                                             di->offset_max - di->offset_min;
301                                         di->offset_min = INT_MAX;
302                                         di->offset_max = -INT_MAX;
303                                         if (di->max_speed > best_speed)
304                                                 di->max_speed--;
305                                         if (di->min_speed < best_speed)
306                                                 di->min_speed++;
307                                 }
308                                 di->offset_prev = offset;
309                                 di->delta_sum = 0;
310                         }
311                 }
312         }
313         spin_unlock_irqrestore(&di->lock, flags);
314 }
315
316 const char *sync_mode_name(enum sync_mode mode)
317 {
318         static const char *sync_mode_names[] = {
319                 [SYNC_MODE_AB] = "AB",
320                 [SYNC_MODE_NONE] = "NONE",
321                 [SYNC_MODE_PLL] = "PLL",
322                 [SYNC_MODE_QUERY] = "QUERY",
323         };
324         if (mode >= ARRAY_SIZE(sync_mode_names))
325                 return NULL;
326         return sync_mode_names[mode];
327 }
328 EXPORT_SYMBOL(sync_mode_name);
329
330 /*
331  * Caller must aquire/release the 'ref_ticker_lock' spinlock
332  */
333 static void xpp_set_syncer(xbus_t *xbus, bool on)
334 {
335         if (!xbus) {            /* Special case, no more syncers */
336                 DBG(SYNC, "No more syncers\n");
337                 syncer = NULL;
338                 if (ref_ticker != &dahdi_ticker)
339                         ref_ticker = NULL;
340                 return;
341         }
342         if (syncer != xbus && on) {
343                 XBUS_DBG(SYNC, xbus, "New syncer\n");
344                 syncer = xbus;
345         } else if (syncer == xbus && !on) {
346                 XBUS_DBG(SYNC, xbus, "Lost syncer\n");
347                 syncer = NULL;
348                 if (ref_ticker != &dahdi_ticker)
349                         ref_ticker = NULL;
350         } else
351                 XBUS_DBG(SYNC, xbus, "ignore %s (current syncer: %s)\n",
352                          (on) ? "ON" : "OFF",
353                          (syncer) ? syncer->busname : "NO-SYNC");
354 }
355
356 static void xbus_command_timer(TIMER_DATA_TYPE timer)
357 {
358         xbus_t *xbus = from_timer(xbus, timer, command_timer);
359         struct timeval now;
360
361         BUG_ON(!xbus);
362         do_gettimeofday(&now);
363         xbus_command_queue_tick(xbus);
364         if (!xbus->self_ticking) /* Must be 1KHz rate */
365                 mod_timer(&xbus->command_timer, jiffies + 1);
366 }
367
368 void xbus_set_command_timer(xbus_t *xbus, bool on)
369 {
370         XBUS_DBG(SYNC, xbus, "%s\n", (on) ? "ON" : "OFF");
371         if (on) {
372                 if (!timer_pending(&xbus->command_timer)) {
373                         XBUS_DBG(SYNC, xbus, "add_timer\n");
374                         timer_setup(&xbus->command_timer,
375                                 xbus_command_timer, 0);
376                         mod_timer(&xbus->command_timer, jiffies + 1);
377                 }
378         } else if (timer_pending(&xbus->command_timer)) {
379                 XBUS_DBG(SYNC, xbus, "del_timer\n");
380                 del_timer(&xbus->command_timer);
381         }
382         xbus->self_ticking = !on;
383 }
384
385 /*
386  * Called when the Astribank replies to a sync change request
387  */
388 void got_new_syncer(xbus_t *xbus, enum sync_mode mode, int drift)
389 {
390         unsigned long flags;
391         unsigned long flags2;
392
393         spin_lock_irqsave(&xbus->lock, flags);
394         spin_lock_irqsave(&ref_ticker_lock, flags2);
395         xbus->sync_adjustment = (signed char)drift;
396         if (xbus->sync_mode == mode) {
397                 XBUS_DBG(SYNC, xbus, "Already in mode '%s'. Ignored\n",
398                          sync_mode_name(mode));
399                 goto out;
400         }
401         XBUS_DBG(SYNC, xbus, "Mode %s (%d), drift=%d (pcm_rx_counter=%d)\n",
402                  sync_mode_name(mode), mode, drift,
403                  atomic_read(&xbus->pcm_rx_counter));
404         switch (mode) {
405         case SYNC_MODE_AB:
406                 xbus->sync_mode = mode;
407                 xbus_set_command_timer(xbus, 0);
408                 xpp_set_syncer(xbus, 1);
409                 global_ticker = xbus;
410                 break;
411         case SYNC_MODE_PLL:
412                 xbus->sync_mode = mode;
413                 xbus_set_command_timer(xbus, 0);
414                 xpp_set_syncer(xbus, 0);
415                 global_ticker = xbus;
416                 break;
417         case SYNC_MODE_NONE:    /* lost sync source */
418                 xbus->sync_mode = mode;
419                 xbus_set_command_timer(xbus, 1);
420                 xpp_set_syncer(xbus, 0);
421                 break;
422         case SYNC_MODE_QUERY:   /* ignore           */
423                 break;
424         default:
425                 XBUS_ERR(xbus, "%s: unknown mode=0x%X\n", __func__, mode);
426         }
427 out:
428         spin_unlock_irqrestore(&ref_ticker_lock, flags2);
429         spin_unlock_irqrestore(&xbus->lock, flags);
430 }
431 EXPORT_SYMBOL(got_new_syncer);
432
433 void xbus_request_sync(xbus_t *xbus, enum sync_mode mode)
434 {
435         unsigned long flags;
436
437         BUG_ON(!xbus);
438         XBUS_DBG(SYNC, xbus, "sent request (mode=%d)\n", mode);
439         CALL_PROTO(GLOBAL, SYNC_SOURCE, xbus, NULL, mode, 0);
440         if (mode == SYNC_MODE_NONE) {
441                 /*
442                  * We must deselect the syncer *now* and not wait for the
443                  * reply from the AB. Otherwise, a disconnect of the syncing
444                  * AB would result in a corrupted 'syncer'.
445                  */
446                 spin_lock_irqsave(&ref_ticker_lock, flags);
447                 xpp_set_syncer(xbus, 0);
448                 spin_unlock_irqrestore(&ref_ticker_lock, flags);
449                 /*
450                  * We must activate timer now since the commands go to
451                  * the command queue, and we should maintain something to
452                  * "tick" meanwhile until the AB get these commands and
453                  * start being "self_ticking".
454                  */
455                 xbus_set_command_timer(xbus, 1);
456         }
457 }
458 EXPORT_SYMBOL(xbus_request_sync);
459
460 static void reset_sync_counters(void)
461 {
462         int i;
463
464         //DBG(SYNC, "%d\n", atomic_read(&xpp_tick_counter));
465         for (i = 0; i < MAX_BUSES; i++) {
466                 xbus_t *xbus = get_xbus(__func__, i);
467
468                 if (xbus == NULL)
469                         continue;
470                 /*
471                  * Don't send to non self_ticking Astribanks:
472                  *  - Maybe they didn't finish initialization
473                  *  - Or maybe they didn't answer us in the first place
474                  (e.g: wrong firmware version, etc).
475                  */
476                 if (xbus->self_ticking) {
477                         if (!XBUS_FLAGS(xbus, CONNECTED)) {
478                                 XBUS_DBG(GENERAL, xbus,
479                                          "Dropped packet. Is shutting down.\n");
480                         } else {
481                                 /* Reset sync LEDs once in a while */
482                                 CALL_PROTO(GLOBAL, RESET_SYNC_COUNTERS, xbus,
483                                            NULL);
484                         }
485                 }
486                 put_xbus(__func__, xbus);
487         }
488 }
489
490 static void send_drift(xbus_t *xbus, int drift)
491 {
492         struct timeval now;
493         const char *msg;
494
495         BUG_ON(abs(drift) > SYNC_ADJ_MAX);
496         do_gettimeofday(&now);
497         if (drift > xbus->sync_adjustment)
498                 msg = "up";
499         else
500                 msg = "down";
501         XBUS_DBG(SYNC, xbus,
502                  "%sDRIFT adjust %s (%d) (last update %ld seconds ago)\n",
503                  (disable_pll_sync) ? "Fake " : "", msg, drift,
504                  now.tv_sec - xbus->pll_updated_at);
505         if (!disable_pll_sync)
506                 CALL_PROTO(GLOBAL, SYNC_SOURCE, xbus, NULL, SYNC_MODE_PLL,
507                            drift);
508         xbus->pll_updated_at = now.tv_sec;
509 }
510
511 static void global_tick(void)
512 {
513         struct timeval now;
514
515         do_gettimeofday(&now);
516         atomic_inc(&xpp_tick_counter);
517         if ((atomic_read(&xpp_tick_counter) % BIG_TICK_INTERVAL) == 0)
518                 reset_sync_counters();
519         xpp_ticker_step(&global_ticks_series, &now);
520 }
521
522 #ifdef  DAHDI_SYNC_TICK
523 void dahdi_sync_tick(struct dahdi_span *span, int is_master)
524 {
525         struct phonedev *phonedev = container_of(span, struct phonedev, span);
526         xpd_t *xpd = container_of(phonedev, struct xpd, phonedev);
527         static int redundant_ticks;     /* for extra spans */
528         struct timeval now;
529
530         if (!force_dahdi_sync)
531                 goto noop;
532         do_gettimeofday(&now);
533         BUG_ON(!xpd);
534         /*
535          * Detect if any of our spans is dahdi sync master
536          */
537         if (is_master) {
538                 static int rate_limit;
539
540                 if ((rate_limit++ % 10003) == 0)
541                         XPD_NOTICE(xpd,
542                                 "Is a DAHDI sync master: "
543                                 "ignore sync from DAHDI\n");
544                 goto noop;
545         }
546         /* Now we know for sure someone else is dahdi sync master */
547         if (syncer) {
548                 static int rate_limit;
549
550                 if ((rate_limit++ % 5003) == 0)
551                         XBUS_DBG(SYNC, syncer,
552                                  "is a SYNCer: ignore sync from DAHDI\n");
553                 goto noop;
554         }
555         /* ignore duplicate calls from all our registered spans */
556         if ((redundant_ticks++ % total_registered_spans()) != 0) {
557 #if 0
558                 static int rate_limit;
559
560                 if ((rate_limit++ % 1003) < 16)
561                         XPD_NOTICE(xpd, "boop (%d)\n", dahdi_tick_count);
562 #endif
563                 goto noop;
564         }
565         xpp_ticker_step(&dahdi_ticker, &now);
566         dahdi_tick_count++;
567         //flip_parport_bit(1);
568 noop:
569         return;
570 }
571 EXPORT_SYMBOL(dahdi_sync_tick);
572 #endif
573
574 /*
575  * called from elect_syncer()
576  * if new_syncer is NULL, than we move all to SYNC_MODE_PLL
577  * for DAHDI sync.
578  */
579 static void update_sync_master(xbus_t *new_syncer, bool force_dahdi)
580 {
581         const char *msg;
582         int i;
583         unsigned long flags;
584
585         WARN_ON(new_syncer && force_dahdi);     /* Ambigous */
586         force_dahdi_sync = force_dahdi;
587         msg = (force_dahdi_sync) ? "DAHDI" : "NO-SYNC";
588         DBG(SYNC, "%s => %s\n", (syncer) ? syncer->busname : msg,
589             (new_syncer) ? new_syncer->busname : msg);
590         /*
591          * This global locking protects:
592          *   - The ref_ticker so it won't be used while we change it.
593          *   - The xbus_drift_clear() from corrupting driftinfo data.
594          * It's important to set ref_ticker now:
595          *   - We cannot make the new xbus a syncer yet (until we get
596          *     a reply from AB). Maybe it's still not self_ticking, so
597          *     we must keep the timer for the command_queue to function.
598          *   - However, we must not send drift commands to it, because
599          *     they'll revert it to PLL instead of AB.
600          */
601         spin_lock_irqsave(&ref_ticker_lock, flags);
602         if (syncer)
603                 xbus_drift_clear(syncer);       /* Clean old data */
604         if (new_syncer) {
605                 XBUS_DBG(SYNC, new_syncer, "pcm_rx_counter=%d\n",
606                          atomic_read(&new_syncer->pcm_rx_counter));
607                 force_dahdi_sync = 0;
608                 ref_ticker = &new_syncer->ticker;
609                 xbus_drift_clear(new_syncer);   /* Clean new data */
610                 xpp_set_syncer(new_syncer, 1);
611                 xbus_request_sync(new_syncer, SYNC_MODE_AB);
612         } else if (force_dahdi_sync) {
613                 ref_ticker = &dahdi_ticker;
614         } else {
615                 ref_ticker = NULL;
616         }
617         spin_unlock_irqrestore(&ref_ticker_lock, flags);
618         DBG(SYNC, "stop unwanted syncers\n");
619         /* Shut all down except the wanted sync master */
620         for (i = 0; i < MAX_BUSES; i++) {
621                 xbus_t *xbus = get_xbus(__func__, i);
622                 if (xbus == NULL)
623                         continue;
624                 if (XBUS_FLAGS(xbus, CONNECTED) && xbus != new_syncer) {
625                         if (xbus->self_ticking)
626                                 xbus_request_sync(xbus,
627                                                   xbus->sync_mode_default);
628                         else
629                                 XBUS_DBG(SYNC, xbus,
630                                          "Not self_ticking yet. Ignore\n");
631                 }
632                 put_xbus(__func__, xbus);
633         }
634 }
635
636 void elect_syncer(const char *msg)
637 {
638         int i;
639         int j;
640         uint timing_priority = INT_MAX;
641         xpd_t *best_xpd = NULL;
642         xbus_t *the_xbus = NULL;
643         unsigned long flags;
644
645         spin_lock_irqsave(&elect_syncer_lock, flags);
646         DBG(SYNC, "%s: %s syncer=%s\n", __func__, msg,
647             (syncer) ? syncer->busname : "NULL");
648         for (i = 0; i < MAX_BUSES; i++) {
649                 xbus_t *xbus = get_xbus(__func__, i);
650
651                 if (xbus == NULL)
652                         continue;
653                 if (XBUS_IS(xbus, READY)) {
654                         if (!the_xbus)
655                                 the_xbus = xbus;        /* First candidate */
656                         for (j = 0; j < MAX_XPDS; j++) {
657                                 xpd_t *xpd = xpd_of(xbus, j);
658                                 int prio;
659
660                                 if (!xpd || !xpd->card_present
661                                     || !IS_PHONEDEV(xpd))
662                                         continue;
663                                 prio =
664                                     CALL_PHONE_METHOD(card_timing_priority,
665                                                       xpd);
666                                 if (prio < 0) {
667                                         DBG(SYNC, "%s/%s: skip sync\n",
668                                             xbus->busname, xpd->xpdname);
669                                         continue;
670                                 }
671                                 if (prio > 0 && prio < timing_priority) {
672                                         timing_priority = prio;
673                                         best_xpd = xpd;
674                                 }
675                         }
676                 }
677                 put_xbus(__func__, xbus);
678         }
679         if (best_xpd) {
680                 the_xbus = best_xpd->xbus;
681                 XPD_DBG(SYNC, best_xpd, "%s: elected with priority %d\n", msg,
682                         timing_priority);
683         } else if (the_xbus) {
684                 XBUS_DBG(SYNC, the_xbus, "%s: elected\n", msg);
685         } else {
686                 unsigned long flags;
687
688                 DBG(SYNC, "%s: No more syncers\n", msg);
689                 spin_lock_irqsave(&ref_ticker_lock, flags);
690                 xpp_set_syncer(NULL, 0);
691                 spin_unlock_irqrestore(&ref_ticker_lock, flags);
692                 the_xbus = NULL;
693         }
694         if (the_xbus != syncer)
695                 update_sync_master(the_xbus, force_dahdi_sync);
696         spin_unlock_irqrestore(&elect_syncer_lock, flags);
697 }
698 EXPORT_SYMBOL(elect_syncer);
699
700 /*
701  * This function should be called with the xpd already locked
702  */
703 void update_wanted_pcm_mask(xpd_t *xpd, xpp_line_t new_mask, uint new_pcm_len)
704 {
705         PHONEDEV(xpd).pcm_len = new_pcm_len;
706         PHONEDEV(xpd).wanted_pcm_mask = new_mask;
707         XPD_DBG(SIGNAL, xpd, "pcm_len=%d wanted_pcm_mask=0x%X\n",
708                 PHONEDEV(xpd).pcm_len, PHONEDEV(xpd).wanted_pcm_mask);
709 }
710 EXPORT_SYMBOL(update_wanted_pcm_mask);
711
712 /*
713  * This function is used by FXS/FXO. The pcm_mask argument signifies
714  * channels which should be *added* to the automatic calculation.
715  * Normally, this argument is 0.
716  */
717 void generic_card_pcm_recompute(xpd_t *xpd, xpp_line_t pcm_mask)
718 {
719         int i;
720         int line_count = 0;
721         unsigned long flags;
722         uint pcm_len;
723
724         spin_lock_irqsave(&PHONEDEV(xpd).lock_recompute_pcm, flags);
725         //XPD_DBG(SIGNAL, xpd, "pcm_mask=0x%X\n", pcm_mask);
726         /* Add/remove all the trivial cases */
727         pcm_mask |= PHONEDEV(xpd).offhook_state;
728         pcm_mask |= PHONEDEV(xpd).oht_pcm_pass;
729         pcm_mask &= ~(PHONEDEV(xpd).digital_inputs);
730         pcm_mask &= ~(PHONEDEV(xpd).digital_outputs);
731         for_each_line(xpd, i)
732             if (IS_SET(pcm_mask, i))
733                 line_count++;
734         /*
735          * FIXME: Workaround a bug in sync code of the Astribank.
736          *        Send dummy PCM for sync.
737          */
738         if (xpd->addr.unit == 0 && pcm_mask == 0) {
739                 pcm_mask = BIT(0);
740                 line_count = 1;
741         }
742         pcm_len = (line_count)
743             ? RPACKET_HEADERSIZE + sizeof(xpp_line_t) +
744             line_count * DAHDI_CHUNKSIZE : 0L;
745         update_wanted_pcm_mask(xpd, pcm_mask, pcm_len);
746         spin_unlock_irqrestore(&PHONEDEV(xpd).lock_recompute_pcm, flags);
747 }
748 EXPORT_SYMBOL(generic_card_pcm_recompute);
749
750 void fill_beep(u_char *buf, int num, int duration)
751 {
752         bool alternate = (duration) ? (jiffies / (duration * 1000)) & 0x1 : 0;
753         int which;
754         u_char *snd;
755
756         /*
757          * debug tones
758          */
759         static u_char beep[] = {
760                 0x7F, 0xBE, 0xD8, 0xBE, 0x80, 0x41, 0x24, 0x41, /* Dima */
761                 0x67, 0x90, 0x89, 0x90, 0xFF, 0x10, 0x09, 0x10, /* Izzy */
762         };
763         static u_char beep_alt[] = {
764                 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, /* silence */
765         };
766         if (alternate) {
767                 which = num % ARRAY_SIZE(beep_alt);
768                 snd = &beep_alt[which];
769         } else {
770                 which = num % ARRAY_SIZE(beep);
771                 snd = &beep[which];
772         }
773         memcpy(buf, snd, DAHDI_CHUNKSIZE);
774 }
775
776 static void do_ec(xpd_t *xpd)
777 {
778         int i;
779
780         for (i = 0; i < PHONEDEV(xpd).span.channels; i++) {
781                 struct dahdi_chan *chan = XPD_CHAN(xpd, i);
782
783                 /* Don't echo cancel BRI D-chans */
784                 if (unlikely(IS_SET(PHONEDEV(xpd).digital_signalling, i)))
785                         continue;
786                 /* No ec for unwanted PCM */
787                 if (!IS_SET(PHONEDEV(xpd).wanted_pcm_mask, i))
788                         continue;
789                 dahdi_ec_chunk(chan, chan->readchunk,
790                                PHONEDEV(xpd).ec_chunk2[i]);
791                 memcpy(PHONEDEV(xpd).ec_chunk2[i], PHONEDEV(xpd).ec_chunk1[i],
792                        DAHDI_CHUNKSIZE);
793                 memcpy(PHONEDEV(xpd).ec_chunk1[i], chan->writechunk,
794                        DAHDI_CHUNKSIZE);
795         }
796 }
797
798 #if 0
799 /* Okay, now we get to the signalling.  You have several options: */
800
801 /* Option 1: If you're a T1 like interface, you can just provide a
802    rbsbits function and we'll assert robbed bits for you.  Be sure to
803    set the DAHDI_FLAG_RBS in this case.  */
804
805 /* Opt: If the span uses A/B bits, set them here */
806 int (*rbsbits) (struct dahdi_chan * chan, int bits);
807
808 /* Option 2: If you don't know about sig bits, but do have their
809    equivalents (i.e. you can disconnect battery, detect off hook,
810    generate ring, etc directly) then you can just specify a
811    sethook function, and we'll call you with appropriate hook states
812    to set.  Still set the DAHDI_FLAG_RBS in this case as well */
813 int (*hooksig) (struct dahdi_chan * chan, enum dahdi_txsig hookstate);
814
815 /* Option 3: If you can't use sig bits, you can write a function
816    which handles the individual hook states  */
817 int (*sethook) (struct dahdi_chan * chan, int hookstate);
818 #endif
819
820 static bool pcm_valid(xpd_t *xpd, xpacket_t *pack)
821 {
822         xpp_line_t lines = RPACKET_FIELD(pack, GLOBAL, PCM_READ, lines);
823         int i;
824         int count = 0;
825         uint16_t good_len;
826
827         BUG_ON(!pack);
828         BUG_ON(XPACKET_OP(pack) != XPROTO_NAME(GLOBAL, PCM_READ));
829         /*
830          * Don't use for_each_line(xpd, i) here because for BRI it will
831          * ignore the channels of the other xpd's in the same unit.
832          */
833         for (i = 0; i < CHANNELS_PERXPD; i++)
834                 if (IS_SET(lines, i))
835                         count++;
836         /* FRAMES: include opcode in calculation */
837         good_len = RPACKET_HEADERSIZE + sizeof(xpp_line_t) + count * 8;
838         if (XPACKET_LEN(pack) != good_len) {
839                 static int rate_limit;
840
841                 XPD_COUNTER(xpd, RECV_ERRORS)++;
842                 if ((rate_limit++ % 1000) <= 10) {
843                         XPD_ERR(xpd,
844                                 "BAD PCM REPLY: packet_len=%d "
845                                 "(should be %d), count=%d\n",
846                                 XPACKET_LEN(pack), good_len, count);
847                         dump_packet("BAD PCM REPLY", pack, 1);
848                 }
849                 return 0;
850         }
851         return 1;
852 }
853
854 static inline void pcm_frame_out(xbus_t *xbus, xframe_t *xframe)
855 {
856         unsigned long flags;
857         struct timeval now;
858         unsigned long usec;
859
860         spin_lock_irqsave(&xbus->lock, flags);
861         do_gettimeofday(&now);
862         if (unlikely(disable_pcm || !XBUS_IS(xbus, READY)))
863                 goto dropit;
864         if (XPACKET_ADDR_SYNC((xpacket_t *)xframe->packets)) {
865                 usec = usec_diff(&now, &xbus->last_tx_sync);
866                 xbus->last_tx_sync = now;
867                 /* ignore startup statistics */
868                 if (likely
869                     (atomic_read(&xbus->pcm_rx_counter) > BIG_TICK_INTERVAL)) {
870                         if (abs(usec - 1000) > TICK_TOLERANCE) {
871                                 static int rate_limit;
872
873                                 if ((rate_limit++ % 5003) == 0)
874                                         XBUS_DBG(SYNC, xbus,
875                                                 "Bad PCM TX timing(%d): "
876                                                 "usec=%ld.\n",
877                                                 rate_limit, usec);
878                         }
879                         if (usec > xbus->max_tx_sync)
880                                 xbus->max_tx_sync = usec;
881                         if (usec < xbus->min_tx_sync)
882                                 xbus->min_tx_sync = usec;
883                 }
884         }
885         spin_unlock_irqrestore(&xbus->lock, flags);
886         /* OK, really send it */
887         if (debug & DBG_PCM)
888                 dump_xframe("TX_XFRAME_PCM", xbus, xframe, debug);
889         send_pcm_frame(xbus, xframe);
890         XBUS_COUNTER(xbus, TX_XFRAME_PCM)++;
891         return;
892 dropit:
893         spin_unlock_irqrestore(&xbus->lock, flags);
894         FREE_SEND_XFRAME(xbus, xframe);
895 }
896
897 /*
898  * Generic implementations of card_pcmfromspan()/card_pcmtospan()
899  * For FXS/FXO
900  */
901 void generic_card_pcm_fromspan(xpd_t *xpd, xpacket_t *pack)
902 {
903         __u8 *pcm;
904         unsigned long flags;
905         xpp_line_t wanted_lines;
906         int i;
907
908         BUG_ON(!xpd);
909         BUG_ON(!pack);
910         wanted_lines = PHONEDEV(xpd).wanted_pcm_mask;
911         RPACKET_FIELD(pack, GLOBAL, PCM_WRITE, lines) = wanted_lines;
912         pcm = RPACKET_FIELD(pack, GLOBAL, PCM_WRITE, pcm);
913         spin_lock_irqsave(&xpd->lock, flags);
914         for (i = 0; i < PHONEDEV(xpd).channels; i++) {
915                 struct dahdi_chan *chan = XPD_CHAN(xpd, i);
916
917                 if (IS_SET(wanted_lines, i)) {
918                         if (SPAN_REGISTERED(xpd)) {
919 #ifdef  DEBUG_PCMTX
920                                 int channo = chan->channo;
921
922                                 if (pcmtx >= 0 && pcmtx_chan == channo)
923                                         memset((u_char *)pcm, pcmtx,
924                                                DAHDI_CHUNKSIZE);
925                                 else
926 #endif
927                                         memcpy((u_char *)pcm, chan->writechunk,
928                                                DAHDI_CHUNKSIZE);
929                         } else
930                                 memset((u_char *)pcm, 0x7F, DAHDI_CHUNKSIZE);
931                         pcm += DAHDI_CHUNKSIZE;
932                 }
933         }
934         XPD_COUNTER(xpd, PCM_WRITE)++;
935         spin_unlock_irqrestore(&xpd->lock, flags);
936 }
937 EXPORT_SYMBOL(generic_card_pcm_fromspan);
938
939 void generic_card_pcm_tospan(xpd_t *xpd, xpacket_t *pack)
940 {
941         __u8 *pcm;
942         xpp_line_t pcm_mask;
943         xpp_line_t pcm_mute;
944         unsigned long flags;
945         int i;
946
947         pcm = RPACKET_FIELD(pack, GLOBAL, PCM_READ, pcm);
948         pcm_mask = RPACKET_FIELD(pack, GLOBAL, PCM_READ, lines);
949         spin_lock_irqsave(&xpd->lock, flags);
950         /*
951          * Calculate the channels we want to mute
952          */
953         pcm_mute = ~(PHONEDEV(xpd).wanted_pcm_mask);
954         pcm_mute |= PHONEDEV(xpd).mute_dtmf | PHONEDEV(xpd).silence_pcm;
955         if (!SPAN_REGISTERED(xpd))
956                 goto out;
957         for (i = 0; i < PHONEDEV(xpd).channels; i++) {
958                 volatile u_char *r = XPD_CHAN(xpd, i)->readchunk;
959                 bool got_data = IS_SET(pcm_mask, i);
960
961                 if (got_data && !IS_SET(pcm_mute, i)) {
962                         /* We have and want real data */
963                         // memset((u_char *)r, 0x5A, DAHDI_CHUNKSIZE);  // DEBUG
964                         memcpy((u_char *)r, pcm, DAHDI_CHUNKSIZE);
965                 } else
966                     if (IS_SET
967                         (PHONEDEV(xpd).wanted_pcm_mask | PHONEDEV(xpd).
968                          silence_pcm, i)) {
969                         /* Inject SILENCE */
970                         memset((u_char *)r, 0x7F, DAHDI_CHUNKSIZE);
971                         if (IS_SET(PHONEDEV(xpd).silence_pcm, i)) {
972                                 /*
973                                  * This will clear the EC buffers until next
974                                  * tick so we don't have noise residues
975                                  * from the past.
976                                  */
977                                 memset(PHONEDEV(xpd).ec_chunk2[i], 0x7F,
978                                        DAHDI_CHUNKSIZE);
979                                 memset(PHONEDEV(xpd).ec_chunk1[i], 0x7F,
980                                        DAHDI_CHUNKSIZE);
981                         }
982                 }
983                 if (got_data)
984                         pcm += DAHDI_CHUNKSIZE;
985         }
986 out:
987         XPD_COUNTER(xpd, PCM_READ)++;
988         spin_unlock_irqrestore(&xpd->lock, flags);
989 }
990 EXPORT_SYMBOL(generic_card_pcm_tospan);
991
992 int generic_echocancel_timeslot(xpd_t *xpd, int pos)
993 {
994         return xpd->addr.unit * 32 + pos;
995 }
996 EXPORT_SYMBOL(generic_echocancel_timeslot);
997
998 int generic_echocancel_setmask(xpd_t *xpd, xpp_line_t ec_mask)
999 {
1000         int i;
1001
1002         BUG_ON(!xpd);
1003         XPD_DBG(GENERAL, xpd, "0x%8X\n", ec_mask);
1004         if (!ECHOOPS(xpd->xbus)) {
1005                 XPD_DBG(GENERAL, xpd,
1006                         "No echo canceller in XBUS: Doing nothing.\n");
1007                 return -EINVAL;
1008         }
1009         for (i = 0; i < PHONEDEV(xpd).channels; i++) {
1010                 int on = BIT(i) & ec_mask;
1011                 CALL_EC_METHOD(ec_set, xpd->xbus, xpd, i, on);
1012         }
1013         CALL_EC_METHOD(ec_update, xpd->xbus, xpd->xbus);
1014         return 0;
1015 }
1016 EXPORT_SYMBOL(generic_echocancel_setmask);
1017
1018 static int copy_pcm_tospan(xbus_t *xbus, xframe_t *xframe)
1019 {
1020         __u8 *xframe_end;
1021         xpacket_t *pack;
1022         __u8 *p;
1023         int ret = -EPROTO;      /* Assume error */
1024
1025         if (debug & DBG_PCM)
1026                 dump_xframe("RX_XFRAME_PCM", xbus, xframe, debug);
1027         /* handle content */
1028
1029         p = xframe->packets;
1030         xframe_end = p + XFRAME_LEN(xframe);
1031         do {
1032                 int len;
1033                 xpd_t *xpd;
1034
1035                 pack = (xpacket_t *)p;
1036                 len = XPACKET_LEN(pack);
1037                 /* Sanity checks */
1038                 if (unlikely(XPACKET_OP(pack) != XPROTO_NAME(GLOBAL, PCM_READ))) {
1039                         static int rate_limit;
1040
1041                         if ((rate_limit++ % 1003) == 0) {
1042                                 XBUS_NOTICE(xbus,
1043                                         "%s: Non-PCM packet within "
1044                                         "a PCM xframe. (%d)\n",
1045                                         __func__, rate_limit);
1046                                 dump_xframe("In PCM xframe", xbus, xframe,
1047                                             debug);
1048                         }
1049                         goto out;
1050                 }
1051                 p += len;
1052                 if (p > xframe_end || len < RPACKET_HEADERSIZE) {
1053                         static int rate_limit;
1054
1055                         if ((rate_limit++ % 1003) == 0) {
1056                                 XBUS_NOTICE(xbus,
1057                                         "%s: Invalid packet length %d. (%d)\n",
1058                                         __func__, len, rate_limit);
1059                                 dump_xframe("BAD LENGTH", xbus, xframe, debug);
1060                         }
1061                         goto out;
1062                 }
1063                 xpd =
1064                     xpd_byaddr(xbus, XPACKET_ADDR_UNIT(pack),
1065                                XPACKET_ADDR_SUBUNIT(pack));
1066                 if (unlikely(!xpd)) {
1067                         static int rate_limit;
1068
1069                         if ((rate_limit++ % 1003) == 0) {
1070                                 notify_bad_xpd(__func__, xbus,
1071                                                XPACKET_ADDR(pack),
1072                                                "RECEIVE PCM");
1073                                 dump_xframe("Unknown XPD addr", xbus, xframe,
1074                                             debug);
1075                         }
1076                         goto out;
1077                 }
1078                 if (!pcm_valid(xpd, pack))
1079                         goto out;
1080                 if (SPAN_REGISTERED(xpd)) {
1081                         XBUS_COUNTER(xbus, RX_PACK_PCM)++;
1082                         CALL_PHONE_METHOD(card_pcm_tospan, xpd, pack);
1083                 }
1084         } while (p < xframe_end);
1085         ret = 0;                /* all good */
1086         XBUS_COUNTER(xbus, RX_XFRAME_PCM)++;
1087 out:
1088         FREE_RECV_XFRAME(xbus, xframe);
1089         return ret;
1090 }
1091
1092 int generic_timing_priority(xpd_t *xpd)
1093 {
1094         return PHONEDEV(xpd).timing_priority;
1095 }
1096 EXPORT_SYMBOL(generic_timing_priority);
1097
1098 static void xbus_tick(xbus_t *xbus)
1099 {
1100         int i;
1101         xpd_t *xpd;
1102         xframe_t *xframe = NULL;
1103         xpacket_t *pack = NULL;
1104         bool sent_sync_bit = 0;
1105
1106         /*
1107          * Update dahdi
1108          */
1109         for (i = 0; i < MAX_XPDS; i++) {
1110                 xpd = xpd_of(xbus, i);
1111                 if (xpd && SPAN_REGISTERED(xpd)) {
1112 #ifdef  OPTIMIZE_CHANMUTE
1113                         int j;
1114                         xpp_line_t xmit_mask = PHONEDEV(xpd).wanted_pcm_mask;
1115
1116                         xmit_mask |= PHONEDEV(xpd).silence_pcm;
1117                         xmit_mask |= PHONEDEV(xpd).digital_signalling;
1118                         for_each_line(xpd, j) {
1119                                 XPD_CHAN(xpd, j)->chanmute = (optimize_chanmute)
1120                                     ? !IS_SET(xmit_mask, j)
1121                                     : 0;
1122                         }
1123 #endif
1124                         /*
1125                          * calls to dahdi_transmit should be out of spinlocks,
1126                          * as it may call back our hook setting methods.
1127                          */
1128                         dahdi_transmit(&PHONEDEV(xpd).span);
1129                 }
1130         }
1131         /*
1132          * Fill xframes
1133          */
1134         for (i = 0; i < MAX_XPDS; i++) {
1135                 if ((xpd = xpd_of(xbus, i)) == NULL)
1136                         continue;
1137                 if (!IS_PHONEDEV(xpd))
1138                         continue;
1139                 if (SPAN_REGISTERED(xpd)) {
1140                         size_t pcm_len = PHONEDEV(xpd).pcm_len;
1141
1142                         if (pcm_len && xpd->card_present) {
1143                                 do {
1144 #if 0
1145                                         /* FORCE single packet frames */
1146                                         pack = NULL;
1147 #endif
1148                                         if (xframe && !pack) {  /* FULL frame */
1149                                                 pcm_frame_out(xbus, xframe);
1150                                                 xframe = NULL;
1151                                                 XBUS_COUNTER(xbus,
1152                                                              TX_PCM_FRAG)++;
1153                                         }
1154                                         if (!xframe) {  /* Alloc frame */
1155                                                 xframe =
1156                                                     ALLOC_SEND_XFRAME(xbus);
1157                                                 if (!xframe) {
1158                                                         static int rate_limit;
1159
1160                                                         if ((rate_limit++ % 3001) == 0)
1161                                                                 XBUS_ERR(xbus,
1162                                                                         "%s: failed to allocate new xframe\n",
1163                                                                         __func__);
1164                                                         return;
1165                                                 }
1166                                         }
1167                                         pack =
1168                                             xframe_next_packet(xframe, pcm_len);
1169                                 } while (!pack);
1170                                 XPACKET_INIT(pack, GLOBAL, PCM_WRITE,
1171                                              xpd->xbus_idx, 1, 0);
1172                                 XPACKET_LEN(pack) = pcm_len;
1173                                 if (!sent_sync_bit) {
1174                                         XPACKET_ADDR_SYNC(pack) = 1;
1175                                         sent_sync_bit = 1;
1176                                 }
1177                                 CALL_PHONE_METHOD(card_pcm_fromspan, xpd, pack);
1178                                 XBUS_COUNTER(xbus, TX_PACK_PCM)++;
1179                         }
1180                 }
1181         }
1182         if (xframe)             /* clean any leftovers */
1183                 pcm_frame_out(xbus, xframe);
1184         /*
1185          * Receive PCM
1186          */
1187         while ((xframe = xframe_dequeue(&xbus->pcm_tospan)) != NULL) {
1188                 copy_pcm_tospan(xbus, xframe);
1189                 if (XPACKET_ADDR_SYNC((xpacket_t *)xframe->packets)) {
1190                         struct timeval now;
1191                         unsigned long usec;
1192
1193                         do_gettimeofday(&now);
1194                         usec = usec_diff(&now, &xbus->last_rx_sync);
1195                         xbus->last_rx_sync = now;
1196                         /* ignore startup statistics */
1197                         if (likely
1198                             (atomic_read(&xbus->pcm_rx_counter) >
1199                              BIG_TICK_INTERVAL)) {
1200                                 if (abs(usec - 1000) > TICK_TOLERANCE) {
1201                                         static int rate_limit;
1202
1203                                         if ((rate_limit++ % 5003) == 0)
1204                                                 XBUS_DBG(SYNC, xbus,
1205                                                         "Bad PCM RX "
1206                                                         "timing(%d): "
1207                                                         "usec=%ld.\n",
1208                                                         rate_limit, usec);
1209                                 }
1210                                 if (usec > xbus->max_rx_sync)
1211                                         xbus->max_rx_sync = usec;
1212                                 if (usec < xbus->min_rx_sync)
1213                                         xbus->min_rx_sync = usec;
1214                         }
1215                 }
1216         }
1217         for (i = 0; i < MAX_XPDS; i++) {
1218                 xpd = xpd_of(xbus, i);
1219                 if (!xpd || !xpd->card_present)
1220                         continue;
1221                 if (IS_PHONEDEV(xpd)) {
1222                         if (SPAN_REGISTERED(xpd)) {
1223                                 do_ec(xpd);
1224                                 dahdi_receive(&PHONEDEV(xpd).span);
1225                         }
1226                         /* silence was injected */
1227                         PHONEDEV(xpd).silence_pcm = 0;
1228                 }
1229                 xpd->timer_count = xbus->global_counter;
1230                 /*
1231                  * Must be called *after* tx/rx so
1232                  * D-Chan counters may be cleared
1233                  */
1234                 CALL_XMETHOD(card_tick, xpd);
1235         }
1236 }
1237
1238 static void do_tick(xbus_t *xbus, const struct timeval *tv_received)
1239 {
1240         int counter = atomic_read(&xpp_tick_counter);
1241         unsigned long flags;
1242
1243         xbus_command_queue_tick(xbus);
1244         if (global_ticker == xbus)
1245                 global_tick();  /* called from here or dahdi_sync_tick() */
1246         spin_lock_irqsave(&ref_ticker_lock, flags);
1247         xpp_drift_step(xbus, tv_received);
1248         spin_unlock_irqrestore(&ref_ticker_lock, flags);
1249         if (likely(xbus->self_ticking))
1250                 xbus_tick(xbus);
1251         xbus->global_counter = counter;
1252 }
1253
1254 void xframe_receive_pcm(xbus_t *xbus, xframe_t *xframe)
1255 {
1256         if (!xframe_enqueue(&xbus->pcm_tospan, xframe)) {
1257                 static int rate_limit;
1258
1259                 if ((rate_limit++ % 1003) == 0)
1260                         XBUS_DBG(SYNC, xbus,
1261                                  "Failed to enqueue received pcm frame. (%d)\n",
1262                                  rate_limit);
1263                 FREE_RECV_XFRAME(xbus, xframe);
1264         }
1265         /*
1266          * The sync_master bit is marked at the first packet
1267          * of the frame, regardless of the XPD that is sync master.
1268          * FIXME: what about PRI split?
1269          */
1270         if (XPACKET_ADDR_SYNC((xpacket_t *)xframe->packets)) {
1271                 do_tick(xbus, &xframe->tv_received);
1272                 atomic_inc(&xbus->pcm_rx_counter);
1273         } else
1274                 xbus->xbus_frag_count++;
1275 }
1276
1277 int exec_sync_command(const char *buf, size_t count)
1278 {
1279         int ret = count;
1280         int xbusno;
1281         xbus_t *xbus;
1282
1283         if (strncmp("DAHDI", buf, 6) == 0) {    /* Ignore the newline */
1284                 DBG(SYNC, "DAHDI");
1285                 update_sync_master(NULL, 1);
1286         } else if (sscanf(buf, "SYNC=%d", &xbusno) == 1) {
1287                 DBG(SYNC, "SYNC=%d\n", xbusno);
1288                 xbus = get_xbus(__func__, xbusno);
1289                 if (xbus == NULL) {
1290                         ERR("No bus %d exists\n", xbusno);
1291                         return -ENXIO;
1292                 }
1293                 update_sync_master(xbus, 0);
1294                 put_xbus(__func__, xbus);
1295         } else if (sscanf(buf, "QUERY=%d", &xbusno) == 1) {
1296                 DBG(SYNC, "QUERY=%d\n", xbusno);
1297                 xbus = get_xbus(__func__, xbusno);
1298                 if (xbus == NULL) {
1299                         ERR("No bus %d exists\n", xbusno);
1300                         return -ENXIO;
1301                 }
1302                 CALL_PROTO(GLOBAL, SYNC_SOURCE, xbus, NULL, SYNC_MODE_QUERY, 0);
1303                 put_xbus(__func__, xbus);
1304         } else {
1305                 ERR("%s: cannot parse '%s'\n", __func__, buf);
1306                 ret = -EINVAL;
1307         }
1308         return ret;
1309 }
1310
1311 int fill_sync_string(char *buf, size_t count)
1312 {
1313         int len = 0;
1314
1315         if (!syncer) {
1316                 len +=
1317                     snprintf(buf, count, "%s\n",
1318                              (force_dahdi_sync) ? "DAHDI" : "NO-SYNC");
1319         } else
1320                 len += snprintf(buf, count, "SYNC=%02d\n", syncer->num);
1321         return len;
1322 }
1323
1324 int xbus_pcm_init(void *toplevel)
1325 {
1326         int ret = 0;
1327
1328 #ifdef  OPTIMIZE_CHANMUTE
1329         INFO("FEATURE: with CHANMUTE optimization (%sactivated)\n",
1330              (optimize_chanmute) ? "" : "de");
1331 #endif
1332 #ifdef  DAHDI_SYNC_TICK
1333         INFO("FEATURE: with sync_tick() from DAHDI\n");
1334 #else
1335         INFO("FEATURE: without sync_tick() from DAHDI\n");
1336 #endif
1337         xpp_ticker_init(&global_ticks_series);
1338         xpp_ticker_init(&dahdi_ticker);
1339         return ret;
1340 }
1341
1342 void xbus_pcm_shutdown(void)
1343 {
1344 }