Revert "Remove support for xpp drivers."
[dahdi/linux.git] / drivers / dahdi / xpp / card_pri.c
1 /*
2  * Written by Oron Peled <oron@actcom.co.il>
3  * Copyright (C) 2004-2006, Xorcom
4  *
5  * Parts derived from Cologne demo driver for the chip.
6  *
7  * All rights reserved.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  */
24
25 #include <linux/init.h>
26 #include <linux/module.h>
27 #include <linux/fs.h>
28 #include <linux/delay.h>
29 #include "xpd.h"
30 #include "xproto.h"
31 #include "xpp_dahdi.h"
32 #include "card_pri.h"
33 #include "dahdi_debug.h"
34 #include "xbus-core.h"
35
36 static const char rcsid[] = "$Id$";
37
38 /* must be before dahdi_debug.h */
39 static DEF_PARM(int, debug, 0, 0644, "Print DBG statements");
40 static DEF_PARM(uint, poll_interval, 500, 0644,
41                 "Poll channel state interval in milliseconds (0 - disable)");
42
43 #define PRI_LINES_BITMASK       BITMASK(31)
44 #define PRI_SIGCAP      (               \
45                         DAHDI_SIG_EM            | \
46                         DAHDI_SIG_CLEAR         | \
47                         DAHDI_SIG_FXSLS         | \
48                         DAHDI_SIG_FXSGS         | \
49                         DAHDI_SIG_FXSKS         | \
50                         DAHDI_SIG_HARDHDLC      | \
51                         DAHDI_SIG_MTP2          | \
52                         DAHDI_SIG_FXOLS         | \
53                         DAHDI_SIG_FXOGS         | \
54                         DAHDI_SIG_FXOKS         | \
55                         DAHDI_SIG_CAS           | \
56                         DAHDI_SIG_EM_E1         | \
57                         DAHDI_SIG_DACS_RBS      \
58                         )
59
60 static bool is_sigtype_dchan(int sigtype)
61 {
62         if ((sigtype & DAHDI_SIG_HDLCRAW) == DAHDI_SIG_HDLCRAW)
63                 return 1;
64         if ((sigtype & DAHDI_SIG_HDLCFCS) == DAHDI_SIG_HDLCFCS)
65                 return 1;
66         if ((sigtype & DAHDI_SIG_HARDHDLC) == DAHDI_SIG_HARDHDLC)
67                 return 1;
68         return 0;
69 }
70
71 #define MAX_SLAVES              4       /* we have MUX of 4 clocks */
72
73 #define PRI_PORT(xpd)   ((xpd)->addr.subunit)
74 #define CHAN_PER_REGS(p)        (((p)->is_esf) ? 2 : 4)
75
76 /*---------------- PRI Protocol Commands ----------------------------------*/
77
78 static void dchan_state(xpd_t *xpd, bool up);
79 static bool pri_packet_is_valid(xpacket_t *pack);
80 static void pri_packet_dump(const char *msg, xpacket_t *pack);
81 static int pri_startup(struct file *file, struct dahdi_span *span);
82 static int pri_shutdown(struct dahdi_span *span);
83 static int pri_rbsbits(struct dahdi_chan *chan, int bits);
84 static int pri_lineconfig(xpd_t *xpd, int lineconfig);
85 static void send_idlebits(xpd_t *xpd, bool saveold);
86 static int apply_pri_protocol(xpd_t *xpd);
87
88 enum pri_protocol {
89         PRI_PROTO_0 = 0,
90         PRI_PROTO_E1 = 1,
91         PRI_PROTO_T1 = 2,
92         PRI_PROTO_J1 = 3
93 };
94
95 static const char *protocol_names[] = {
96         [PRI_PROTO_0] = "??",   /* unknown */
97         [PRI_PROTO_E1] = "E1",
98         [PRI_PROTO_T1] = "T1",
99         [PRI_PROTO_J1] = "J1"
100 };
101
102 static enum spantypes pri_protocol2spantype(enum pri_protocol pri_protocol)
103 {
104         switch (pri_protocol) {
105         case PRI_PROTO_E1: return SPANTYPE_DIGITAL_E1;
106         case PRI_PROTO_T1: return SPANTYPE_DIGITAL_T1;
107         case PRI_PROTO_J1: return SPANTYPE_DIGITAL_J1;
108         default:
109                 return SPANTYPE_INVALID;
110         }
111 }
112
113 static const char *pri_protocol_name(enum pri_protocol pri_protocol)
114 {
115         return protocol_names[pri_protocol];
116 }
117
118 static int pri_num_channels(enum pri_protocol pri_protocol)
119 {
120         static int num_channels[] = {
121                 [PRI_PROTO_0] = 0,
122                 [PRI_PROTO_E1] = 31,
123                 [PRI_PROTO_T1] = 24,
124                 [PRI_PROTO_J1] = 0
125         };
126         return num_channels[pri_protocol];
127 }
128
129 static const char *type_name(enum pri_protocol pri_protocol)
130 {
131         static const char *names[4] = {
132                 [PRI_PROTO_0] = "PRI-Unknown",
133                 [PRI_PROTO_E1] = "E1",
134                 [PRI_PROTO_T1] = "T1",
135                 [PRI_PROTO_J1] = "J1"
136         };
137
138         return names[pri_protocol];
139 }
140
141 static int pri_linecompat(enum pri_protocol pri_protocol)
142 {
143         static const int linecompat[] = {
144                 [PRI_PROTO_0] = 0,
145                 [PRI_PROTO_E1] =
146                     /* coding */
147                     DAHDI_CONFIG_CCS | DAHDI_CONFIG_CRC4 |
148                     /* framing */
149                     DAHDI_CONFIG_AMI | DAHDI_CONFIG_HDB3,
150                 [PRI_PROTO_T1] =
151                     /* coding */
152                     DAHDI_CONFIG_D4 | DAHDI_CONFIG_ESF |
153                     /* framing */
154                     DAHDI_CONFIG_AMI | DAHDI_CONFIG_B8ZS,
155                 [PRI_PROTO_J1] = 0
156         };
157
158         DBG(GENERAL, "pri_linecompat: pri_protocol=%d\n", pri_protocol);
159         return linecompat[pri_protocol];
160 }
161
162 #define PRI_DCHAN_IDX(priv)     ((priv)->dchan_num - 1)
163
164 enum pri_led_state {
165         PRI_LED_OFF = 0x0,
166         PRI_LED_ON = 0x1,
167         /*
168          * We blink by software from driver, so that
169          * if the driver malfunction that blink would stop.
170          */
171         // PRI_LED_BLINK_SLOW   = 0x2,  /* 1/2 a second blink cycle */
172         // PRI_LED_BLINK_FAST   = 0x3   /* 1/4 a second blink cycle */
173 };
174
175 enum pri_led_selectors {
176         BOTTOM_RED_LED = 0,
177         BOTTOM_GREEN_LED = 1,
178         TOP_RED_LED = 2,
179         TOP_GREEN_LED = 3,
180 };
181
182 #define NUM_LEDS        4
183
184 struct pri_leds {
185         __u8 state:2;           /* enum pri_led_state */
186         __u8 led_sel:2;         /* enum pri_led_selectors */
187         __u8 reserved:4;
188 };
189
190 #define REG_CCB1_T      0x2F    /* Clear Channel Register 1 */
191
192 #define REG_FRS0        0x4C    /* Framer Receive Status Register 0 */
193 #define REG_FRS0_T1_FSR BIT(0)  /* T1 - Frame Search Restart Flag */
194 #define REG_FRS0_LMFA   BIT(1)  /* Loss of Multiframe Alignment */
195 #define REG_FRS0_E1_NMF BIT(2)  /* E1 - No Multiframe Alignment Found */
196 #define REG_FRS0_RRA    BIT(4)  /* Receive Remote Alarm: T1-YELLOW-Alarm */
197 #define REG_FRS0_LFA    BIT(5)  /* Loss of Frame Alignment */
198 #define REG_FRS0_AIS    BIT(6)  /* Alarm Indication Signal: T1-BLUE-Alarm */
199 #define REG_FRS0_LOS    BIT(7)  /* Los Of Signal: T1-RED-Alarm */
200
201 #define REG_FRS1        0x4D    /* Framer Receive Status Register 1 */
202
203 #define REG_LIM0        0x36
204 /*
205  * Master Mode, DCO-R circuitry is frequency synchronized
206  * to the clock supplied by SYNC
207  */
208 #define REG_LIM0_MAS    BIT(0)
209 /*
210  * Receive Termination Resistance Selection:
211  * integrated resistor to create 75 Ohm termination (100 || 300 = 75)
212  * 0 = 100 Ohm
213  * 1 = 75 Ohm
214  */
215 #define REG_LIM0_RTRS   BIT(5)
216 #define REG_LIM0_LL     BIT(1)  /* LL (Local Loopback) */
217
218 #define REG_FMR0        0x1C
219 #define REG_FMR0_E_RC0  BIT(4)  /* Receive Code - LSB */
220 #define REG_FMR0_E_RC1  BIT(5)  /* Receive Code - MSB */
221 #define REG_FMR0_E_XC0  BIT(6)  /* Transmit Code - LSB */
222 #define REG_FMR0_E_XC1  BIT(7)  /* Transmit Code - MSB */
223
224 #define REG_FMR1        0x1D
225 #define REG_FMR1_XAIS   BIT(0)  /* Transmit AIS toward transmit end */
226 #define REG_FMR1_SSD0   BIT(1)
227 #define REG_FMR1_ECM    BIT(2)
228 #define REG_FMR1_T_CRC  BIT(3)  /* Enable CRC6 */
229 #define REG_FMR1_E_XFS  BIT(3)  /* Transmit Framing Select */
230 #define REG_FMR1_PMOD   BIT(4)  /* E1 = 0, T1/J1 = 1 */
231 #define REG_FMR1_EDL    BIT(5)
232 #define REG_FMR1_AFR    BIT(6)
233
234 #define REG_FMR2        0x1E
235 #define REG_FMR2_E_ALMF BIT(0)  /* Automatic Loss of Multiframe */
236 #define REG_FMR2_T_EXZE BIT(0)  /* Excessive Zeros Detection Enable */
237 #define REG_FMR2_E_AXRA BIT(1)  /* Automatic Transmit Remote Alarm */
238 #define REG_FMR2_T_AXRA BIT(1)  /* Automatic Transmit Remote Alarm */
239 #define REG_FMR2_E_PLB  BIT(2)  /* Payload Loop-Back */
240 #define REG_FMR2_E_RFS0 BIT(6)  /* Receive Framing Select - LSB */
241 #define REG_FMR2_E_RFS1 BIT(7)  /* Receive Framing Select - MSB */
242 /* Select Synchronization/Resynchronization Procedure */
243 #define REG_FMR2_T_SSP  BIT(5)
244 /* Multiple Candidates Synchronization Procedure */
245 #define REG_FMR2_T_MCSP BIT(6)
246 /* Automatic Force Resynchronization */
247 #define REG_FMR2_T_AFRS BIT(7)
248
249 #define REG_FMR3        0x31
250 #define REG_FMR3_EXTIW  BIT(0)  /* Extended CRC4 to Non-CRC4 Interworking */
251
252 #define REG_FMR4        0x20
253 #define REG_FMR4_FM0    BIT(0)
254 #define REG_FMR4_FM1    BIT(1)
255 #define REG_FMR4_AUTO   BIT(2)
256 #define REG_FMR4_SSC0   BIT(3)
257 #define REG_FMR4_SSC1   BIT(4)
258 #define REG_FMR4_XRA    BIT(5)  /* Transmit Remote Alarm (Yellow Alarm) */
259 #define REG_FMR4_TM     BIT(6)
260 #define REG_FMR4_AIS3   BIT(7)
261
262 #define REG_XSW_E       0x20
263 #define REG_XSW_E_XY4   BIT(0)
264 #define REG_XSW_E_XY3   BIT(1)
265 #define REG_XSW_E_XY2   BIT(2)
266 #define REG_XSW_E_XY1   BIT(3)
267 #define REG_XSW_E_XY0   BIT(4)
268 #define REG_XSW_E_XRA   BIT(5)  /* Transmit Remote Alarm (Yellow Alarm) */
269 #define REG_XSW_E_XTM   BIT(6)
270 #define REG_XSW_E_XSIS  BIT(7)
271
272 #define REG_XSP_E       0x21
273 #define REG_FMR5_T      0x21
274 /* Transmit Spare Bit For International Use (FAS Word)  */
275 #define REG_XSP_E_XSIF  BIT(2)
276 #define REG_FMR5_T_XTM  BIT(2)  /* Transmit Transparent Mode  */
277 /* Automatic Transmission of Submultiframe Status  */
278 #define REG_XSP_E_AXS   BIT(3)
279 /* E-Bit Polarity, Si-bit position of every outgoing CRC multiframe  */
280 #define REG_XSP_E_EBP   BIT(4)
281 #define REG_XSP_E_CASEN BIT(6)  /* CAS: Channel Associated Signaling Enable  */
282 #define REG_FMR5_T_EIBR BIT(6)  /* CAS: Enable Internal Bit Robbing Access   */
283
284 #define REG_XC0_T       0x22    /* Transmit Control 0 */
285 #define REG_XC0_BRIF    BIT(5)  /* Bit Robbing Idle Function */
286
287 #define REG_CMDR_E      0x02    /* Command Register */
288 #define REG_CMDR_RRES   BIT(6)  /* Receiver    reset */
289 #define REG_CMDR_XRES   BIT(4)  /* Transmitter reset */
290
291 #define REG_RC0         0x24
292 #define REG_RC0_SJR     BIT(7)  /* T1 = 0, J1 = 1 */
293
294 #define REG_CMR1        0x44
295 #define REG_CMR1_DRSS   (BIT(7) | BIT(6))
296 #define REG_CMR1_RS     (BIT(5) | BIT(4))
297 #define REG_CMR1_STF    BIT(2)
298
299 #define REG_RS1_E       0x70    /* Receive CAS Register 1       */
300 #define REG_RS2_E       0x71    /* Receive CAS Register 2       */
301 #define REG_RS3_E       0x72    /* Receive CAS Register 3       */
302 #define REG_RS4_E       0x73    /* Receive CAS Register 4       */
303 #define REG_RS5_E       0x74    /* Receive CAS Register 5       */
304 #define REG_RS6_E       0x75    /* Receive CAS Register 6       */
305 #define REG_RS7_E       0x76    /* Receive CAS Register 7       */
306 #define REG_RS8_E       0x77    /* Receive CAS Register 8       */
307 #define REG_RS9_E       0x78    /* Receive CAS Register 9       */
308 #define REG_RS10_E      0x79    /* Receive CAS Register 10      */
309 #define REG_RS11_E      0x7A    /* Receive CAS Register 11      */
310 #define REG_RS12_E      0x7B    /* Receive CAS Register 12      */
311 #define REG_RS13_E      0x7C    /* Receive CAS Register 13      */
312 #define REG_RS14_E      0x7D    /* Receive CAS Register 14      */
313 #define REG_RS15_E      0x7E    /* Receive CAS Register 15      */
314 #define REG_RS16_E      0x7F    /* Receive CAS Register 16      */
315
316 #define REG_PC2         0x81    /* Port Configuration 2 */
317 #define REG_PC3         0x82    /* Port Configuration 3 */
318 #define REG_PC4         0x83    /* Port Configuration 4 */
319
320 #define REG_XPM2        0x28    /* Transmit Pulse Mask 2 */
321
322 #define VAL_PC_SYPR     0x00    /* Synchronous Pulse Receive (Input, low active) */
323 #define VAL_PC_GPI      0x90    /* General purpose input */
324 #define VAL_PC_GPOH     0x0A    /* General Purpose Output, high level */
325 #define VAL_PC_GPOL     0x0B    /* General Purpose Output, low level */
326
327 #define NUM_CAS_RS_E    (REG_RS16_E - REG_RS2_E + 1)
328 /* and of those, the ones used in T1: */
329 #define NUM_CAS_RS_T    (REG_RS12_E - REG_RS1_E + 1)
330
331 struct PRI_priv_data {
332         bool clock_source;
333         enum pri_protocol pri_protocol;
334         xpp_line_t rbslines;
335         int deflaw;
336         unsigned int dchan_num;
337         bool initialized;
338         bool dchan_is_open;
339         int is_cas;
340
341         unsigned int chanconfig_dchan;
342 #define NO_DCHAN        (0)
343 #define DCHAN(p)        ((p)->chanconfig_dchan)
344 #define VALID_DCHAN(p)  (DCHAN(p) != NO_DCHAN)
345 #define SET_DCHAN(p, d) do { DCHAN(p) = (d); } while (0);
346
347         __u8 cas_rs_e[NUM_CAS_RS_E];
348         __u8 cas_ts_e[NUM_CAS_RS_E];
349         uint cas_replies;
350         bool is_esf;
351         bool local_loopback;
352         uint poll_noreplies;
353         uint layer1_replies;
354         __u8 reg_frs0;
355         __u8 reg_frs1;
356         bool layer1_up;
357         int alarms;
358         __u8 dchan_tx_sample;
359         __u8 dchan_rx_sample;
360         uint dchan_tx_counter;
361         uint dchan_rx_counter;
362         bool dchan_alive;
363         uint dchan_alive_ticks;
364         enum pri_led_state ledstate[NUM_LEDS];
365 };
366
367 static xproto_table_t PROTO_TABLE(PRI);
368
369 DEF_RPACKET_DATA(PRI, SET_LED,  /* Set one of the LED's */
370                  struct pri_leds pri_leds;);
371
372 static /* 0x33 */ DECLARE_CMD(PRI, SET_LED, enum pri_led_selectors led_sel,
373                               enum pri_led_state to_led_state);
374
375 #define DO_LED(xpd, which, tostate)     \
376                 CALL_PROTO(PRI, SET_LED, (xpd)->xbus, (xpd), (which), (tostate))
377
378 /*---------------- PRI: Methods -------------------------------------------*/
379
380 static int query_subunit(xpd_t *xpd, __u8 regnum)
381 {
382         XPD_DBG(REGS, xpd, "(%d%d): REG=0x%02X\n", xpd->addr.unit,
383                 xpd->addr.subunit, regnum);
384         return xpp_register_request(xpd->xbus, xpd, PRI_PORT(xpd),      /* portno       */
385                                     0,  /* writing      */
386                                     regnum, 0,  /* do_subreg    */
387                                     0,  /* subreg       */
388                                     0,  /* data_L       */
389                                     0,  /* do_datah     */
390                                     0,  /* data_H       */
391                                     0,  /* should_reply */
392                                     0   /* do_expander  */
393             );
394 }
395
396 static int write_subunit(xpd_t *xpd, __u8 regnum, __u8 val)
397 {
398         XPD_DBG(REGS, xpd, "(%d%d): REG=0x%02X dataL=0x%02X\n", xpd->addr.unit,
399                 xpd->addr.subunit, regnum, val);
400         return xpp_register_request(xpd->xbus, xpd,
401                         PRI_PORT(xpd),  /* portno       */
402                         1,              /* writing      */
403                         regnum, 0,      /* do_subreg    */
404                         0,              /* subreg       */
405                         val,            /* data_L       */
406                         0,              /* do_datah     */
407                         0,              /* data_H       */
408                         0,              /* should_reply */
409                         0               /* do_expander  */
410             );
411 }
412
413 static int pri_write_reg(xpd_t *xpd, int regnum, __u8 val)
414 {
415         XPD_DBG(REGS, xpd, "(%d%d): REG=0x%02X dataL=0x%02X\n", xpd->addr.unit,
416                 xpd->addr.subunit, regnum, val);
417         return xpp_register_request(xpd->xbus, xpd, 0,  /* portno=0     */
418                                     1,  /* writing      */
419                                     regnum, 0,  /* do_subreg    */
420                                     0,  /* subreg       */
421                                     val,        /* data_L       */
422                                     0,  /* do_datah     */
423                                     0,  /* data_H       */
424                                     0,  /* should_reply */
425                                     0   /* do_expander  */
426             );
427 }
428
429 static int cas_regbase(xpd_t *xpd)
430 {
431         struct PRI_priv_data *priv;
432
433         priv = xpd->priv;
434         switch (priv->pri_protocol) {
435         case PRI_PROTO_E1:
436                 return REG_RS2_E;
437         case PRI_PROTO_T1:
438                 /* fall-through */
439         case PRI_PROTO_J1:
440                 return REG_RS1_E;
441         case PRI_PROTO_0:
442                 /* fall-through */
443                 ;
444         }
445         BUG();
446         return 0;
447 }
448
449 static int cas_numregs(xpd_t *xpd)
450 {
451         struct PRI_priv_data *priv;
452
453         priv = xpd->priv;
454         switch (priv->pri_protocol) {
455         case PRI_PROTO_E1:
456                 return NUM_CAS_RS_E;
457         case PRI_PROTO_T1:
458                 /* fall-through */
459         case PRI_PROTO_J1:
460                 return NUM_CAS_RS_T;
461         case PRI_PROTO_0:
462                 /* fall-through */
463                 ;
464         }
465         BUG();
466         return 0;
467 }
468
469 static int write_cas_reg(xpd_t *xpd, int rsnum, __u8 val)
470 {
471         struct PRI_priv_data *priv;
472         int regbase = cas_regbase(xpd);
473         int num_cas_rs = cas_numregs(xpd);
474         int regnum;
475         bool is_d4 = 0;
476
477         BUG_ON(!xpd);
478         priv = xpd->priv;
479         if ((priv->pri_protocol == PRI_PROTO_T1) && !priv->is_esf) {
480                 /* same data should be copied to RS7..12 in D4 only */
481                 is_d4 = 1;
482         }
483         if (rsnum < 0 || rsnum >= num_cas_rs) {
484                 XPD_ERR(xpd, "RBS(TX): rsnum=%d\n", rsnum);
485                 BUG();
486         }
487         regnum = regbase + rsnum;
488         priv->cas_ts_e[rsnum] = val;
489         XPD_DBG(SIGNAL, xpd, "RBS(TX): reg=0x%X val=0x%02X\n", regnum, val);
490         write_subunit(xpd, regbase + rsnum, val);
491         if (is_d4) {
492                 /* same data should be copied to RS7..12 in D4 only */
493                 regnum = REG_RS7_E + rsnum;
494                 XPD_DBG(SIGNAL, xpd, "RBS(TX): reg=0x%X val=0x%02X\n", regnum,
495                         val);
496                 write_subunit(xpd, regnum, val);
497         }
498         return 0;
499 }
500
501 static bool valid_pri_modes(const xpd_t *xpd)
502 {
503         struct PRI_priv_data *priv;
504
505         BUG_ON(!xpd);
506         priv = xpd->priv;
507         if (priv->pri_protocol != PRI_PROTO_E1
508             && priv->pri_protocol != PRI_PROTO_T1
509             && priv->pri_protocol != PRI_PROTO_J1)
510                 return 0;
511         return 1;
512 }
513
514 static void PRI_card_pcm_recompute(xpd_t *xpd, xpp_line_t pcm_mask)
515 {
516         struct PRI_priv_data *priv;
517         int i;
518         int line_count = 0;
519         unsigned long flags;
520         uint pcm_len;
521
522         BUG_ON(!xpd);
523         priv = xpd->priv;
524         spin_lock_irqsave(&PHONEDEV(xpd).lock_recompute_pcm, flags);
525         //XPD_DBG(SIGNAL, xpd, "pcm_mask=0x%X\n", pcm_mask);
526         /* Add/remove all the trivial cases */
527         pcm_mask |= PHONEDEV(xpd).offhook_state;
528         if (priv->is_cas)
529                 pcm_mask |= BITMASK(PHONEDEV(xpd).channels);
530         for_each_line(xpd, i)
531             if (IS_SET(pcm_mask, i))
532                 line_count++;
533             else
534         if (priv->is_cas) {
535                 if (priv->pri_protocol == PRI_PROTO_E1) {
536                         /* CAS: Don't send PCM to D-Channel */
537                         line_count--;
538                         pcm_mask &= ~BIT(PRI_DCHAN_IDX(priv));
539                 }
540         }
541         /*
542          * FIXME: Workaround a bug in sync code of the Astribank.
543          *        Send dummy PCM for sync.
544          */
545         if (xpd->addr.unit == 0 && pcm_mask == 0) {
546                 pcm_mask = BIT(0);
547                 line_count = 1;
548         }
549         pcm_len = (line_count)
550             ? RPACKET_HEADERSIZE + sizeof(xpp_line_t) +
551             line_count * DAHDI_CHUNKSIZE : 0L;
552         update_wanted_pcm_mask(xpd, pcm_mask, pcm_len);
553         spin_unlock_irqrestore(&PHONEDEV(xpd).lock_recompute_pcm, flags);
554 }
555
556 /*
557  * Set E1/T1/J1
558  * May only be called on unregistered xpd's
559  * (the span and channel description are set according to this)
560  */
561 static int set_pri_proto(xpd_t *xpd, enum pri_protocol set_proto)
562 {
563         struct PRI_priv_data *priv;
564         int deflaw;
565         unsigned int dchan_num;
566         int default_lineconfig = 0;
567         int ret;
568         struct phonedev *phonedev;
569
570         BUG_ON(!xpd);
571         priv = xpd->priv;
572         phonedev = &PHONEDEV(xpd);
573         if (test_bit(DAHDI_FLAGBIT_REGISTERED, &phonedev->span.flags)) {
574                 XPD_NOTICE(xpd, "%s: %s already assigned as span %d\n",
575                            __func__, phonedev->span.name,
576                            phonedev->span.spanno);
577                 return -EBUSY;
578         }
579         if (priv->pri_protocol != PRI_PROTO_0) {
580                 if (priv->pri_protocol == set_proto) {
581                         XPD_NOTICE(xpd, "Already in protocol %s. Ignored\n",
582                                    pri_protocol_name(set_proto));
583                         return 0;
584                 } else {
585                         XPD_INFO(xpd, "Switching from %s to %s\n",
586                                  pri_protocol_name(priv->pri_protocol),
587                                  pri_protocol_name(set_proto));
588                 }
589         }
590         switch (set_proto) {
591         case PRI_PROTO_E1:
592                 deflaw = DAHDI_LAW_ALAW;
593                 dchan_num = 16;
594                 default_lineconfig =
595                     DAHDI_CONFIG_CCS | DAHDI_CONFIG_CRC4 | DAHDI_CONFIG_HDB3;
596                 break;
597         case PRI_PROTO_T1:
598                 deflaw = DAHDI_LAW_MULAW;
599                 dchan_num = 24;
600                 default_lineconfig = DAHDI_CONFIG_ESF | DAHDI_CONFIG_B8ZS;
601                 break;
602         case PRI_PROTO_J1:
603                 /*
604                  * Check all assumptions
605                  */
606                 deflaw = DAHDI_LAW_MULAW;
607                 dchan_num = 24;
608                 default_lineconfig = 0; /* FIXME: J1??? */
609                 XPD_NOTICE(xpd, "J1 is not supported yet\n");
610                 return -ENOSYS;
611         default:
612                 XPD_ERR(xpd, "%s: Unknown pri protocol = %d\n", __func__,
613                         set_proto);
614                 return -EINVAL;
615         }
616         priv->pri_protocol = set_proto;
617         priv->is_cas = -1;
618         phonedev_alloc_channels(xpd, pri_num_channels(set_proto));
619         phonedev->offhook_state = BITMASK(phonedev->channels);
620         CALL_PHONE_METHOD(card_pcm_recompute, xpd, 0);
621         priv->deflaw = deflaw;
622         priv->dchan_num = dchan_num;
623         priv->local_loopback = 0;
624         xpd->type_name = type_name(priv->pri_protocol);
625         XPD_DBG(GENERAL, xpd, "%s, channels=%d, dchan_num=%d, deflaw=%d\n",
626                 pri_protocol_name(set_proto), phonedev->channels,
627                 priv->dchan_num, priv->deflaw);
628         /*
629          * Must set default now, so layer1 polling (Register REG_FRS0) would
630          * give reliable results.
631          */
632         ret = pri_lineconfig(xpd, default_lineconfig);
633         if (ret) {
634                 XPD_NOTICE(xpd, "Failed setting PRI default line config\n");
635                 return ret;
636         }
637         return apply_pri_protocol(xpd);
638 }
639
640 static void dahdi_update_syncsrc(xpd_t *xpd)
641 {
642         struct PRI_priv_data *priv;
643         xpd_t *subxpd;
644         int best_spanno = 0;
645         int i;
646
647         if (!SPAN_REGISTERED(xpd))
648                 return;
649         for (i = 0; i < MAX_SLAVES; i++) {
650                 subxpd = xpd_byaddr(xpd->xbus, xpd->addr.unit, i);
651                 if (!subxpd)
652                         continue;
653                 priv = subxpd->priv;
654                 if (priv->clock_source && priv->alarms == 0) {
655                         if (best_spanno)
656                                 XPD_ERR(xpd,
657                                         "Duplicate XPD with clock_source=1\n");
658                         best_spanno = PHONEDEV(subxpd).span.spanno;
659                 }
660         }
661         for (i = 0; i < MAX_SLAVES; i++) {
662                 subxpd = xpd_byaddr(xpd->xbus, xpd->addr.unit, i);
663                 if (!subxpd)
664                         continue;
665                 if (PHONEDEV(subxpd).span.syncsrc == best_spanno)
666                         XPD_DBG(SYNC, xpd, "Setting SyncSource to span %d\n",
667                                 best_spanno);
668                 else
669                         XPD_DBG(SYNC, xpd, "Slaving to span %d\n", best_spanno);
670                 PHONEDEV(subxpd).span.syncsrc = best_spanno;
671         }
672 }
673
674 /*
675  * Called from:
676  *   - set_master_mode() --
677  *       As a result of dahdi_cfg
678  *   - layer1_state() --
679  *       As a result of an alarm.
680  */
681 static void set_clocking(xpd_t *xpd)
682 {
683         xbus_t *xbus;
684         xpd_t *best_xpd = NULL;
685         int best_subunit = -1;  /* invalid */
686         unsigned int best_subunit_prio = INT_MAX;
687         int i;
688
689         xbus = xpd->xbus;
690         /* Find subunit with best timing priority */
691         for (i = 0; i < MAX_SLAVES; i++) {
692                 struct PRI_priv_data *priv;
693                 xpd_t *subxpd;
694
695                 subxpd = xpd_byaddr(xbus, xpd->addr.unit, i);
696                 if (!subxpd)
697                         continue;
698                 priv = subxpd->priv;
699                 if (priv->alarms != 0)
700                         continue;
701                 if (PHONEDEV(subxpd).timing_priority > 0
702                     && PHONEDEV(subxpd).timing_priority < best_subunit_prio) {
703                         best_xpd = subxpd;
704                         best_subunit = i;
705                         best_subunit_prio = PHONEDEV(subxpd).timing_priority;
706                 }
707         }
708         /* Now set it */
709         if (best_xpd
710             && ((struct PRI_priv_data *)(best_xpd->priv))->clock_source == 0) {
711                 __u8 reg_pc_init[] = { VAL_PC_SYPR, VAL_PC_GPI, VAL_PC_GPI };
712
713                 for (i = 0; i < ARRAY_SIZE(reg_pc_init); i++) {
714                         __u8 reg_pc = reg_pc_init[i];
715
716                         reg_pc |=
717                             (best_subunit & (1 << i)) ? VAL_PC_GPOH :
718                             VAL_PC_GPOL;
719                         XPD_DBG(SYNC, best_xpd,
720                                 "ClockSource Set: PC%d=0x%02X\n", 2 + i,
721                                 reg_pc);
722                         pri_write_reg(xpd, REG_PC2 + i, reg_pc);
723                 }
724                 ((struct PRI_priv_data *)(best_xpd->priv))->clock_source = 1;
725         }
726         /* clear old clock sources */
727         for (i = 0; i < MAX_SLAVES; i++) {
728                 struct PRI_priv_data *priv;
729                 xpd_t *subxpd;
730
731                 subxpd = xpd_byaddr(xbus, xpd->addr.unit, i);
732                 if (subxpd && subxpd != best_xpd) {
733                         XPD_DBG(SYNC, subxpd, "Clearing clock source\n");
734                         priv = subxpd->priv;
735                         priv->clock_source = 0;
736                 }
737         }
738         dahdi_update_syncsrc(xpd);
739 }
740
741 static void set_reg_lim0(const char *msg, xpd_t *xpd)
742 {
743         struct PRI_priv_data *priv;
744         bool is_master_mode;
745         bool localloop;
746         __u8 lim0 = 0;
747
748         BUG_ON(!xpd);
749         priv = xpd->priv;
750         BUG_ON(!priv);
751         is_master_mode = PHONEDEV(xpd).timing_priority == 0;
752         localloop = priv->local_loopback;
753         lim0 |= (localloop) ? REG_LIM0_LL : 0;
754         if (is_master_mode)
755                 lim0 |= REG_LIM0_MAS;
756         else
757                 lim0 &= ~REG_LIM0_MAS;
758         XPD_DBG(SIGNAL, xpd, "%s(%s): %s, %s\n", __func__, msg,
759                 (is_master_mode) ? "MASTER" : "SLAVE",
760                 (localloop) ? "LOCALLOOP" : "NO_LOCALLOOP");
761         write_subunit(xpd, REG_LIM0, lim0);
762 }
763
764 /*
765  * Normally set by the timing parameter in /etc/dahdi/system.conf
766  * If this is called by dahdi_cfg, than it's too late to change
767  * dahdi sync priority (we are already registered)
768  *
769  * Also called from set_localloop()
770  */
771 static int set_master_mode(const char *msg, xpd_t *xpd)
772 {
773         BUG_ON(!xpd);
774         XPD_DBG(SIGNAL, xpd, "\n");
775         set_reg_lim0(__func__, xpd);
776         set_clocking(xpd);
777         return 0;
778 }
779
780 static int set_localloop(xpd_t *xpd, bool localloop)
781 {
782         struct PRI_priv_data *priv;
783
784         BUG_ON(!xpd);
785         priv = xpd->priv;
786         if (SPAN_REGISTERED(xpd)) {
787                 XPD_NOTICE(xpd, "Registered as span %d. Cannot do %s\n",
788                            PHONEDEV(xpd).span.spanno, __func__);
789                 return -EBUSY;
790         }
791         priv->local_loopback = localloop;
792         XPD_DBG(SIGNAL, xpd, "%s: %s\n", __func__,
793                 (localloop) ? "LOCALLOOP" : "NO");
794         set_master_mode(__func__, xpd);
795         return 0;
796 }
797
798 #define VALID_CONFIG(bit, flg, str)     [bit] = { .flags = flg, .name = str }
799
800 static const struct {
801         const char *name;
802         const int flags;
803 } valid_spanconfigs[sizeof(unsigned int) * 8] = {
804         /* These apply to T1 */
805         VALID_CONFIG(4, DAHDI_CONFIG_D4, "D4"),
806         VALID_CONFIG(5, DAHDI_CONFIG_ESF, "ESF"),
807         VALID_CONFIG(6, DAHDI_CONFIG_AMI, "AMI"),
808         VALID_CONFIG(7, DAHDI_CONFIG_B8ZS, "B8ZS"),
809         /* These apply to E1 */
810         VALID_CONFIG(8, DAHDI_CONFIG_CCS, "CCS"),
811         VALID_CONFIG(9, DAHDI_CONFIG_HDB3, "HDB3"),
812         VALID_CONFIG(10, DAHDI_CONFIG_CRC4, "CRC4"),
813 };
814
815 /*
816  * Mark the lines as CLEAR or RBS signalling.
817  * With T1, we need to mark the CLEAR lines on the REG_CCB1_T registers
818  * Should be called only when we are registered to DAHDI
819  * The channo parameter:
820  *      channo == 0: set lines for the whole span
821  *      channo != 0: only set modified lines
822  */
823 static void set_rbslines(xpd_t *xpd, int channo)
824 {
825         struct PRI_priv_data *priv;
826         xpp_line_t new_rbslines = 0;
827         xpp_line_t modified_lines;
828         int i;
829
830         priv = xpd->priv;
831         for_each_line(xpd, i) {
832                 struct dahdi_chan *chan = XPD_CHAN(xpd, i);
833
834                 if (chan->flags & DAHDI_FLAG_CLEAR)
835                         BIT_CLR(new_rbslines, i);
836                 else
837                         BIT_SET(new_rbslines, i);
838         }
839         new_rbslines &= BITMASK(PHONEDEV(xpd).channels);
840         modified_lines = priv->rbslines ^ new_rbslines;
841         XPD_DBG(DEVICES, xpd, "RBSLINES-%d(%s): 0x%X\n", channo,
842                 pri_protocol_name(priv->pri_protocol), new_rbslines);
843         if ((priv->pri_protocol == PRI_PROTO_T1)
844             || (priv->pri_protocol == PRI_PROTO_J1)) {
845                 __u8 clear_lines = 0;   /* Mark clear lines */
846                 bool reg_changed = 0;
847
848                 for_each_line(xpd, i) {
849                         int bytenum = i / 8;
850                         int bitnum = i % 8;
851
852                         if (!IS_SET(new_rbslines, i))
853                                 BIT_SET(clear_lines, (7 - bitnum));
854                         if (IS_SET(modified_lines, i))
855                                 reg_changed = 1;
856                         if (bitnum == 7) {
857                                 if (channo == 0 || reg_changed) {
858                                         bytenum += REG_CCB1_T;
859                                         XPD_DBG(DEVICES, xpd,
860                                                 "RBS(%s): modified=0x%X rbslines=0x%X reg=0x%X clear_lines=0x%X\n",
861                                                 pri_protocol_name(priv->pri_protocol),
862                                                 modified_lines, new_rbslines,
863                                                 bytenum, clear_lines);
864                                         write_subunit(xpd, bytenum, clear_lines);
865                                 }
866                                 clear_lines = 0;
867                                 reg_changed = 0;
868                         }
869                 }
870         }
871         priv->rbslines = new_rbslines;
872 }
873
874 static int set_mode_cas(xpd_t *xpd, bool want_cas)
875 {
876         struct PRI_priv_data *priv;
877
878         priv = xpd->priv;
879         XPD_INFO(xpd, "Setting TDM to %s\n", (want_cas) ? "CAS" : "PRI");
880         if (want_cas) {
881                 priv->is_cas = 1;
882                 priv->dchan_alive = 0;
883         } else {
884                 priv->is_cas = 0;
885         }
886         return 0;
887 }
888
889 static int pri_lineconfig(xpd_t *xpd, int lineconfig)
890 {
891         struct PRI_priv_data *priv;
892         const char *framingstr = "";
893         const char *codingstr = "";
894         const char *crcstr = "";
895 #ifdef JAPANEZE_SUPPORT
896         __u8 rc0 = 0;           /* FIXME: PCM offsets */
897 #endif
898         __u8 fmr0 = 0;
899         __u8 fmr1 = REG_FMR1_ECM;
900         __u8 fmr2 = 0;
901         __u8 fmr3 = 0;          /* write only for CRC4 */
902         __u8 fmr4 = 0;
903         __u8 cmdr = REG_CMDR_RRES | REG_CMDR_XRES;
904         __u8 xsp = 0;
905         unsigned int bad_bits;
906         bool force_cas = 0;
907         int i;
908
909         BUG_ON(!xpd);
910         priv = xpd->priv;
911         /*
912          * validate
913          */
914         bad_bits = lineconfig & pri_linecompat(priv->pri_protocol);
915         bad_bits = bad_bits ^ lineconfig;
916         for (i = 0; i < ARRAY_SIZE(valid_spanconfigs); i++) {
917                 unsigned int flags = valid_spanconfigs[i].flags;
918
919                 if (bad_bits & BIT(i)) {
920                         if (flags) {
921                                 XPD_ERR(xpd,
922                                         "Bad config item '%s' for %s. Ignore\n",
923                                         valid_spanconfigs[i].name,
924                                         pri_protocol_name(priv->pri_protocol));
925                         } else {
926                                 /* we got real garbage */
927                                 XPD_ERR(xpd,
928                                         "Unknown config item 0x%lX for %s. "
929                                         "Ignore.\n",
930                                         BIT(i),
931                                         pri_protocol_name(priv->pri_protocol));
932                         }
933                 }
934                 if (flags && flags != BIT(i)) {
935                         ERR("%s: BUG: i=%d flags=0x%X\n", __func__, i, flags);
936                         // BUG();
937                 }
938         }
939         if (bad_bits)
940                 goto bad_lineconfig;
941         if (priv->pri_protocol == PRI_PROTO_E1) {
942                 fmr1 |= REG_FMR1_AFR;
943                 fmr2 = REG_FMR2_E_AXRA | REG_FMR2_E_ALMF;       /* 0x03 */
944                 fmr4 = 0x9F;    /*  E1.XSW:  All spare bits = 1 */
945                 xsp |= REG_XSP_E_EBP | REG_XSP_E_AXS | REG_XSP_E_XSIF;
946         } else if (priv->pri_protocol == PRI_PROTO_T1) {
947                 fmr1 |= REG_FMR1_PMOD | REG_FMR1_T_CRC;
948                 fmr2 = REG_FMR2_T_SSP | REG_FMR2_T_AXRA;        /* 0x22 */
949                 fmr4 = 0x0C;
950                 xsp &= ~REG_FMR5_T_XTM;
951                 force_cas = 1;  /* T1 - Chip always in CAS mode */
952         } else if (priv->pri_protocol == PRI_PROTO_J1) {
953                 fmr1 |= REG_FMR1_PMOD;
954                 fmr4 = 0x1C;
955                 xsp &= ~REG_FMR5_T_XTM;
956                 force_cas = 1;  /* T1 - Chip always in CAS mode */
957                 XPD_ERR(xpd, "J1 unsupported yet\n");
958                 return -ENOSYS;
959         }
960         if (priv->local_loopback)
961                 fmr2 |= REG_FMR2_E_PLB;
962         /* framing first */
963         if (lineconfig & DAHDI_CONFIG_B8ZS) {
964                 framingstr = "B8ZS";
965                 fmr0 =
966                     REG_FMR0_E_XC1 | REG_FMR0_E_XC0 | REG_FMR0_E_RC1 |
967                     REG_FMR0_E_RC0;
968         } else if (lineconfig & DAHDI_CONFIG_AMI) {
969                 framingstr = "AMI";
970                 fmr0 = REG_FMR0_E_XC1 | REG_FMR0_E_RC1;
971                 /*
972                  * From Infineon Errata Sheet: PEF 22554, Version 3.1
973                  * Problem: Incorrect CAS Receiption when
974                  *          using AMI receive line code
975                  * Workaround: For E1,
976                  *               "...The receive line coding HDB3 is
977                  *                recommended instead."
978                  *             For T1,
979                  *               "...in T1 mode it is recommended to
980                  *                configure the Rx side to B8ZS coding"
981                  * For both cases this is the same bit in FMR0
982                  */
983                 if (priv->pri_protocol == PRI_PROTO_J1)
984                         XPD_NOTICE(xpd, "J1 is not supported yet\n");
985                 else
986                         fmr0 |= REG_FMR0_E_RC0;
987         } else if (lineconfig & DAHDI_CONFIG_HDB3) {
988                 framingstr = "HDB3";
989                 fmr0 =
990                     REG_FMR0_E_XC1 | REG_FMR0_E_XC0 | REG_FMR0_E_RC1 |
991                     REG_FMR0_E_RC0;
992         } else {
993                 XPD_NOTICE(xpd,
994                            "Bad lineconfig. Not (B8ZS|AMI|HDB3). Ignored.\n");
995                 return -EINVAL;
996         }
997         /* then coding */
998         priv->is_esf = 0;
999         if (lineconfig & DAHDI_CONFIG_ESF) {
1000                 codingstr = "ESF";
1001                 fmr4 |= REG_FMR4_FM1;
1002                 fmr2 |= REG_FMR2_T_AXRA | REG_FMR2_T_MCSP | REG_FMR2_T_SSP;
1003                 priv->is_esf = 1;
1004         } else if (lineconfig & DAHDI_CONFIG_D4) {
1005                 codingstr = "D4";
1006         } else if (lineconfig & DAHDI_CONFIG_CCS) {
1007                 codingstr = "CCS";
1008                 /* In E1 we know right from the span statement. */
1009                 set_mode_cas(xpd, 0);
1010         } else {
1011                 /* In E1 we know right from the span statement. */
1012                 codingstr = "CAS";
1013                 force_cas = 1;
1014                 set_mode_cas(xpd, 1);
1015         }
1016         CALL_PHONE_METHOD(card_pcm_recompute, xpd, 0);
1017         /*
1018          * E1's can enable CRC checking
1019          * CRC4 is legal only for E1, and it is checked by pri_linecompat()
1020          * in the beginning of the function.
1021          */
1022         if (lineconfig & DAHDI_CONFIG_CRC4) {
1023                 crcstr = "CRC4";
1024                 fmr1 |= REG_FMR1_E_XFS;
1025                 fmr2 |= REG_FMR2_E_RFS1;
1026                 fmr3 |= REG_FMR3_EXTIW;
1027         }
1028         XPD_DBG(GENERAL, xpd, "[%s] lineconfig=%s/%s/%s %s (0x%X)\n",
1029                 (priv->clock_source) ? "MASTER" : "SLAVE", framingstr,
1030                 codingstr, crcstr,
1031                 (lineconfig & DAHDI_CONFIG_NOTOPEN) ? "YELLOW" : "",
1032                 lineconfig);
1033         set_reg_lim0(__func__, xpd);
1034         XPD_DBG(GENERAL, xpd, "%s: fmr1(0x%02X) = 0x%02X\n", __func__, REG_FMR1,
1035                 fmr1);
1036         write_subunit(xpd, REG_FMR1, fmr1);
1037         XPD_DBG(GENERAL, xpd, "%s: fmr2(0x%02X) = 0x%02X\n", __func__, REG_FMR2,
1038                 fmr2);
1039         write_subunit(xpd, REG_FMR2, fmr2);
1040         XPD_DBG(GENERAL, xpd, "%s: fmr0(0x%02X) = 0x%02X\n", __func__, REG_FMR0,
1041                 fmr0);
1042         write_subunit(xpd, REG_FMR0, fmr0);
1043         XPD_DBG(GENERAL, xpd, "%s: fmr4(0x%02X) = 0x%02X\n", __func__, REG_FMR4,
1044                 fmr4);
1045         write_subunit(xpd, REG_FMR4, fmr4);
1046         if (fmr3) {
1047                 XPD_DBG(GENERAL, xpd, "%s: fmr3(0x%02X) = 0x%02X\n", __func__,
1048                         REG_FMR3, fmr3);
1049                 write_subunit(xpd, REG_FMR3, fmr3);
1050         }
1051         XPD_DBG(GENERAL, xpd, "%s: cmdr(0x%02X) = 0x%02X\n", __func__,
1052                 REG_CMDR_E, cmdr);
1053         write_subunit(xpd, REG_CMDR_E, cmdr);
1054 #ifdef JAPANEZE_SUPPORT
1055         if (rc0) {
1056                 XPD_DBG(GENERAL, xpd, "%s: rc0(0x%02X) = 0x%02X\n", __func__,
1057                         REG_RC0, rc0);
1058                 write_subunit(xpd, REG_RC0, rc0);
1059         }
1060 #endif
1061         if (force_cas) {
1062                 if (priv->pri_protocol == PRI_PROTO_E1) {
1063                         int rs1 = 0x0B;
1064
1065                         /*
1066                          * Set correct X1-X3 bits in the E1 CAS MFAS
1067                          * They are unused in E1 and should be 1
1068                          */
1069                         XPD_DBG(GENERAL, xpd, "%s: rs1(0x%02X) = 0x%02X\n",
1070                                 __func__, REG_RS1_E, rs1);
1071                         write_subunit(xpd, REG_RS1_E, rs1);
1072                 }
1073                 xsp |= REG_XSP_E_CASEN; /* Same as REG_FMR5_T_EIBR for T1 */
1074         }
1075         XPD_DBG(GENERAL, xpd, "%s: xsp(0x%02X) = 0x%02X\n", __func__, REG_XSP_E,
1076                 xsp);
1077         write_subunit(xpd, REG_XSP_E, xsp);
1078         return 0;
1079 bad_lineconfig:
1080         XPD_ERR(xpd, "Bad lineconfig. Abort\n");
1081         return -EINVAL;
1082 }
1083
1084 static int pri_set_spantype(struct dahdi_span *span, enum spantypes spantype)
1085 {
1086         struct phonedev *phonedev = container_of(span, struct phonedev, span);
1087         xpd_t *xpd = container_of(phonedev, struct xpd, phonedev);
1088         enum pri_protocol set_proto = PRI_PROTO_0;
1089         int ret;
1090
1091         XPD_INFO(xpd, "%s: %s\n", __func__, dahdi_spantype2str(spantype));
1092         switch (spantype) {
1093         case SPANTYPE_DIGITAL_E1:
1094                 set_proto = PRI_PROTO_E1;
1095                 break;
1096         case SPANTYPE_DIGITAL_T1:
1097                 set_proto = PRI_PROTO_T1;
1098                 break;
1099         case SPANTYPE_DIGITAL_J1:
1100                 set_proto = PRI_PROTO_J1;
1101                 break;
1102         default:
1103                 XPD_NOTICE(xpd, "%s: bad spantype '%s'\n",
1104                         __func__, dahdi_spantype2str(spantype));
1105                 return -EINVAL;
1106         }
1107         ret = set_pri_proto(xpd, set_proto);
1108         if (ret < 0) {
1109                 XPD_ERR(xpd, "%s: set_pri_proto failed\n", __func__);
1110                 return ret;
1111         }
1112         dahdi_init_span(span);
1113         return 0;
1114 }
1115
1116 static int PRI_card_open(xpd_t *xpd, lineno_t pos)
1117 {
1118         struct PRI_priv_data *priv;
1119         int d;
1120
1121         /*
1122          * DAHDI without AUDIO_NOTIFY.
1123          * Need to offhook all channels when D-Chan is up
1124          */
1125         priv = xpd->priv;
1126         d = PRI_DCHAN_IDX(priv);
1127         BUG_ON(!xpd);
1128         if (pos == d) {
1129 #ifndef DAHDI_AUDIO_NOTIFY
1130                 int i;
1131
1132                 LINE_DBG(SIGNAL, xpd, pos, "OFFHOOK the whole span\n");
1133                 for_each_line(xpd, i) {
1134                         if (i != d)
1135                                 BIT_SET(PHONEDEV(xpd).offhook_state, i);
1136                 }
1137                 CALL_PHONE_METHOD(card_pcm_recompute, xpd, 0);
1138 #endif
1139                 priv->dchan_is_open = 1;
1140         }
1141         return 0;
1142 }
1143
1144 static int PRI_card_close(xpd_t *xpd, lineno_t pos)
1145 {
1146         struct PRI_priv_data *priv;
1147         int d, i;
1148
1149         priv = xpd->priv;
1150         d = PRI_DCHAN_IDX(priv);
1151         BUG_ON(!xpd);
1152         if (pos == d) {
1153                 LINE_DBG(SIGNAL, xpd, pos, "OFFHOOK the whole span\n");
1154                 for_each_line(xpd, i) {
1155                         if (i != d)
1156                                 BIT_CLR(PHONEDEV(xpd).offhook_state, i);
1157                 }
1158                 CALL_PHONE_METHOD(card_pcm_recompute, xpd, 0);
1159                 dchan_state(xpd, 0);
1160                 priv->dchan_is_open = 0;
1161         } else if (!priv->dchan_is_open)
1162                 mark_offhook(xpd, pos, 0);      /* e.g: patgen/pattest */
1163         return 0;
1164 }
1165
1166 /*
1167  * Called only for 'span' keyword in /etc/dahdi/system.conf
1168  */
1169
1170 static int pri_spanconfig(struct file *file, struct dahdi_span *span,
1171                           struct dahdi_lineconfig *lc)
1172 {
1173         struct phonedev *phonedev = container_of(span, struct phonedev, span);
1174         xpd_t *xpd = container_of(phonedev, struct xpd, phonedev);
1175         struct PRI_priv_data *priv;
1176         int ret;
1177
1178         BUG_ON(!xpd);
1179         priv = xpd->priv;
1180         if (lc->span != PHONEDEV(xpd).span.spanno) {
1181                 XPD_ERR(xpd, "I am span %d but got spanconfig for span %d\n",
1182                         PHONEDEV(xpd).span.spanno, lc->span);
1183                 return -EINVAL;
1184         }
1185         /*
1186          * FIXME: lc->name is unused by dahdi_cfg and dahdi...
1187          *        We currently ignore it also.
1188          */
1189         XPD_DBG(GENERAL, xpd, "[%s] lbo=%d lineconfig=0x%X sync=%d\n",
1190                 (priv->clock_source) ? "MASTER" : "SLAVE", lc->lbo,
1191                 lc->lineconfig, lc->sync);
1192         ret = pri_lineconfig(xpd, lc->lineconfig);
1193         if (!ret) {
1194                 span->lineconfig = lc->lineconfig;
1195                 PHONEDEV(xpd).timing_priority = lc->sync;
1196                 set_master_mode("spanconfig", xpd);
1197                 elect_syncer("PRI-master_mode");
1198         }
1199         return ret;
1200 }
1201
1202 /*
1203  * Set signalling type (if appropriate)
1204  * Called from dahdi with spinlock held on chan. Must not call back
1205  * dahdi functions.
1206  */
1207 static int pri_chanconfig(struct file *file, struct dahdi_chan *chan,
1208                           int sigtype)
1209 {
1210         struct phonedev *phonedev =
1211             container_of(chan->span, struct phonedev, span);
1212         xpd_t *xpd = container_of(phonedev, struct xpd, phonedev);
1213         struct PRI_priv_data *priv;
1214
1215         BUG_ON(!xpd);
1216         priv = xpd->priv;
1217         DBG(GENERAL, "channel %d (%s) -> %s\n", chan->channo, chan->name,
1218             sig2str(sigtype));
1219         /*
1220          * Some bookkeeping to check if we have DChan defined or not
1221          * FIXME: actually use this to prevent duplicate DChan definitions
1222          *        and prevent DChan definitions with CAS.
1223          */
1224         if (is_sigtype_dchan(sigtype)) {
1225                 if (VALID_DCHAN(priv) && DCHAN(priv) != chan->channo) {
1226                         ERR("channel %d (%s) marked DChan but "
1227                                 "also channel %d.\n",
1228                                 chan->channo, chan->name, DCHAN(priv));
1229                         return -EINVAL;
1230                 }
1231                 XPD_DBG(GENERAL, xpd, "channel %d (%s) marked as DChan\n",
1232                         chan->channo, chan->name);
1233                 SET_DCHAN(priv, chan->channo);
1234                 /* In T1, we don't know before-hand */
1235                 if (priv->pri_protocol != PRI_PROTO_E1 && priv->is_cas != 0)
1236                         set_mode_cas(xpd, 0);
1237         } else {
1238                 if (chan->chanpos == 1) {
1239                         XPD_DBG(GENERAL, xpd,
1240                                 "channel %d (%s) marked a not DChan\n",
1241                                 chan->channo, chan->name);
1242                         SET_DCHAN(priv, NO_DCHAN);
1243                 }
1244                 /* In T1, we don't know before-hand */
1245                 if (priv->pri_protocol != PRI_PROTO_E1 && priv->is_cas != 1)
1246                         set_mode_cas(xpd, 1);
1247         }
1248         if (PHONEDEV(xpd).span.flags & DAHDI_FLAG_RUNNING) {
1249                 XPD_DBG(DEVICES, xpd, "Span is RUNNING. Updating rbslines.\n");
1250                 set_rbslines(xpd, chan->channo);
1251         }
1252         // FIXME: sanity checks:
1253         // - should be supported (within the sigcap)
1254         // - should not replace fxs <->fxo ??? (covered by previous?)
1255         return 0;
1256 }
1257
1258 static xpd_t *PRI_card_new(xbus_t *xbus, int unit, int subunit,
1259                            const xproto_table_t *proto_table,
1260                            const struct unit_descriptor *unit_descriptor,
1261                            bool to_phone)
1262 {
1263         xpd_t *xpd = NULL;
1264         struct PRI_priv_data *priv;
1265         int channels = min(31, CHANNELS_PERXPD);        /* worst case */
1266
1267         if ((unit_descriptor->ports_per_chip < 1) ||
1268                         (unit_descriptor->ports_per_chip > 4)) {
1269                 XBUS_ERR(xbus, "Bad ports_per_chip=%d\n",
1270                                 unit_descriptor->ports_per_chip);
1271                 return NULL;
1272         }
1273         if (unit_descriptor->numchips != 1) {
1274                 XBUS_ERR(xbus, "Bad numchips=%d\n",
1275                                 unit_descriptor->numchips);
1276                 return NULL;
1277         }
1278         XBUS_DBG(GENERAL, xbus, "\n");
1279         xpd =
1280             xpd_alloc(xbus, unit, subunit,
1281                       sizeof(struct PRI_priv_data), proto_table, unit_descriptor, channels);
1282         if (!xpd)
1283                 return NULL;
1284         priv = xpd->priv;
1285         /* Default, changes in set_pri_proto() */
1286         priv->pri_protocol = PRI_PROTO_0;
1287         /* Default, changes in set_pri_proto() */
1288         priv->deflaw = DAHDI_LAW_DEFAULT;
1289         xpd->type_name = type_name(priv->pri_protocol);
1290         xbus->sync_mode_default = SYNC_MODE_AB;
1291         return xpd;
1292 }
1293
1294 static int PRI_card_init(xbus_t *xbus, xpd_t *xpd)
1295 {
1296         struct PRI_priv_data *priv;
1297         int ret = 0;
1298
1299         BUG_ON(!xpd);
1300         XPD_DBG(GENERAL, xpd, "\n");
1301         xpd->xpd_type = XPD_TYPE_PRI;
1302         priv = xpd->priv;
1303         if (priv->pri_protocol == PRI_PROTO_0) {
1304                 /*
1305                  * init_card_* script didn't set pri protocol
1306                  * Let's have a default E1
1307                  */
1308                 ret = set_pri_proto(xpd, PRI_PROTO_E1);
1309                 if (ret < 0)
1310                         goto err;
1311         }
1312         SET_DCHAN(priv, NO_DCHAN);
1313         /*
1314          * initialization script should have set correct
1315          * operating modes.
1316          */
1317         if (!valid_pri_modes(xpd)) {
1318                 XPD_NOTICE(xpd, "PRI protocol not set\n");
1319                 goto err;
1320         }
1321         xpd->type_name = type_name(priv->pri_protocol);
1322         PHONEDEV(xpd).direction = TO_PSTN;
1323         XPD_DBG(DEVICES, xpd, "%s\n", xpd->type_name);
1324         PHONEDEV(xpd).timing_priority = 1;      /* High priority SLAVE */
1325         set_master_mode(__func__, xpd);
1326         for (ret = 0; ret < NUM_LEDS; ret++) {
1327                 DO_LED(xpd, ret, PRI_LED_ON);
1328                 msleep(20);
1329                 DO_LED(xpd, ret, PRI_LED_OFF);
1330         }
1331         priv->initialized = 1;
1332         priv->dchan_is_open = 0;
1333         return 0;
1334 err:
1335         XPD_ERR(xpd, "Failed initializing registers (%d)\n", ret);
1336         return ret;
1337 }
1338
1339 static int PRI_card_remove(xbus_t *xbus, xpd_t *xpd)
1340 {
1341         BUG_ON(!xpd);
1342         XPD_DBG(GENERAL, xpd, "\n");
1343         return 0;
1344 }
1345
1346 #ifdef  DAHDI_AUDIO_NOTIFY
1347 static int pri_audio_notify(struct dahdi_chan *chan, int on)
1348 {
1349         xpd_t *xpd = chan->pvt;
1350         int pos = chan->chanpos - 1;
1351
1352         BUG_ON(!xpd);
1353         LINE_DBG(SIGNAL, xpd, pos, "PRI-AUDIO: %s\n", (on) ? "on" : "off");
1354         mark_offhook(xpd, pos, on);
1355         return 0;
1356 }
1357 #endif
1358
1359 static const struct dahdi_span_ops PRI_span_ops = {
1360         .owner = THIS_MODULE,
1361         .set_spantype = pri_set_spantype,
1362         .spanconfig = pri_spanconfig,
1363         .chanconfig = pri_chanconfig,
1364         .startup = pri_startup,
1365         .shutdown = pri_shutdown,
1366         .rbsbits = pri_rbsbits,
1367         .open = xpp_open,
1368         .close = xpp_close,
1369         .ioctl = xpp_ioctl,
1370         .maint = xpp_maint,
1371         .echocan_create = xpp_echocan_create,
1372         .echocan_name = xpp_echocan_name,
1373         .assigned = xpp_span_assigned,
1374 #ifdef  DAHDI_SYNC_TICK
1375         .sync_tick = dahdi_sync_tick,
1376 #endif
1377 #ifdef  CONFIG_DAHDI_WATCHDOG
1378         .watchdog = xpp_watchdog,
1379 #endif
1380
1381 #ifdef  DAHDI_AUDIO_NOTIFY
1382         .audio_notify = pri_audio_notify,
1383 #endif
1384 };
1385
1386 static int apply_pri_protocol(xpd_t *xpd)
1387 {
1388         xbus_t *xbus;
1389         struct PRI_priv_data *priv;
1390         int i;
1391
1392         BUG_ON(!xpd);
1393         xbus = xpd->xbus;
1394         priv = xpd->priv;
1395         BUG_ON(!xbus);
1396         XPD_DBG(GENERAL, xpd, "\n");
1397         PHONEDEV(xpd).span.spantype = pri_protocol2spantype(priv->pri_protocol);
1398         PHONEDEV(xpd).span.linecompat = pri_linecompat(priv->pri_protocol);
1399         PHONEDEV(xpd).span.deflaw = priv->deflaw;
1400         PHONEDEV(xpd).span.alarms = DAHDI_ALARM_NONE;
1401         for_each_line(xpd, i) {
1402                 struct dahdi_chan *cur_chan = XPD_CHAN(xpd, i);
1403                 bool is_dchan = i == PRI_DCHAN_IDX(priv);
1404
1405                 XPD_DBG(GENERAL, xpd, "setting PRI channel %d (%s)\n", i,
1406                         (is_dchan) ? "DCHAN" : "CLEAR");
1407                 snprintf(cur_chan->name, MAX_CHANNAME, "XPP_%s/%02d/%1d%1d/%d",
1408                          xpd->type_name, xbus->num, xpd->addr.unit,
1409                          xpd->addr.subunit, i);
1410                 cur_chan->chanpos = i + 1;
1411                 cur_chan->pvt = xpd;
1412                 cur_chan->sigcap = PRI_SIGCAP;
1413                 if (is_dchan && !priv->is_cas) {        /* D-CHAN */
1414                         //FIXME: cur_chan->flags |= DAHDI_FLAG_PRIDCHAN;
1415                         cur_chan->flags &= ~DAHDI_FLAG_HDLC;
1416                 }
1417         }
1418         PHONEDEV(xpd).offhook_state = PHONEDEV(xpd).wanted_pcm_mask;
1419         PHONEDEV(xpd).span.ops = &PRI_span_ops;
1420         PHONEDEV(xpd).span.channels = PHONEDEV(xpd).channels;
1421         xpd_set_spanname(xpd);
1422         return 0;
1423 }
1424
1425 static int PRI_card_dahdi_preregistration(xpd_t *xpd, bool on)
1426 {
1427         xbus_t *xbus;
1428         struct PRI_priv_data *priv;
1429
1430         BUG_ON(!xpd);
1431         xbus = xpd->xbus;
1432         priv = xpd->priv;
1433         BUG_ON(!xbus);
1434         XPD_DBG(GENERAL, xpd, "%s (proto=%s, channels=%d, deflaw=%d)\n",
1435                 (on) ? "on" : "off", pri_protocol_name(priv->pri_protocol),
1436                 PHONEDEV(xpd).channels, priv->deflaw);
1437         if (!on) {
1438                 /* Nothing to do yet */
1439                 return 0;
1440         }
1441         return apply_pri_protocol(xpd);
1442 }
1443
1444 static int PRI_card_dahdi_postregistration(xpd_t *xpd, bool on)
1445 {
1446         xbus_t *xbus;
1447
1448         BUG_ON(!xpd);
1449         xbus = xpd->xbus;
1450         BUG_ON(!xbus);
1451         XPD_DBG(GENERAL, xpd, "%s\n", (on) ? "on" : "off");
1452         dahdi_update_syncsrc(xpd);
1453         return (0);
1454 }
1455
1456 static void dchan_state(xpd_t *xpd, bool up)
1457 {
1458         struct PRI_priv_data *priv;
1459
1460         BUG_ON(!xpd);
1461         priv = xpd->priv;
1462         BUG_ON(!priv);
1463         if (priv->is_cas)
1464                 return;
1465         if (priv->dchan_alive == up)
1466                 return;
1467         if (!priv->layer1_up)   /* No layer1, kill dchan */
1468                 up = 0;
1469         if (up) {
1470                 XPD_DBG(SIGNAL, xpd, "STATE CHANGE: D-Channel RUNNING\n");
1471                 priv->dchan_alive = 1;
1472         } else {
1473                 int d = PRI_DCHAN_IDX(priv);
1474
1475                 if (SPAN_REGISTERED(xpd) && d >= 0
1476                     && d < PHONEDEV(xpd).channels) {
1477                         __u8 *pcm;
1478
1479                         pcm = (__u8 *)XPD_CHAN(xpd, d)->readchunk;
1480                         pcm[0] = 0x00;
1481                         pcm = (__u8 *)XPD_CHAN(xpd, d)->writechunk;
1482                         pcm[0] = 0x00;
1483                 }
1484                 XPD_DBG(SIGNAL, xpd, "STATE CHANGE: D-Channel STOPPED\n");
1485                 priv->dchan_rx_counter = priv->dchan_tx_counter = 0;
1486                 priv->dchan_alive = 0;
1487                 priv->dchan_alive_ticks = 0;
1488                 priv->dchan_rx_sample = priv->dchan_tx_sample = 0x00;
1489         }
1490 }
1491
1492 /*
1493  * LED managment is done by the driver now:
1494  *   - Turn constant ON RED/GREEN led to indicate MASTER/SLAVE port
1495  *   - Very fast "Double Blink" to indicate Layer1 alive (without D-Channel)
1496  *   - Constant blink (1/2 sec cycle) to indicate D-Channel alive.
1497  */
1498 static void handle_leds(xbus_t *xbus, xpd_t *xpd)
1499 {
1500         struct PRI_priv_data *priv;
1501         unsigned int timer_count;
1502         int which_led;
1503         int other_led;
1504         enum pri_led_state ledstate;
1505         int mod;
1506
1507         BUG_ON(!xpd);
1508         priv = xpd->priv;
1509         BUG_ON(!priv);
1510         if (PHONEDEV(xpd).timing_priority == 0) {
1511                 which_led = TOP_RED_LED;
1512                 other_led = BOTTOM_GREEN_LED;
1513         } else {
1514                 which_led = BOTTOM_GREEN_LED;
1515                 other_led = TOP_RED_LED;
1516         }
1517         ledstate = priv->ledstate[which_led];
1518         timer_count = xpd->timer_count;
1519         if (xpd->blink_mode) {
1520                 if ((timer_count % DEFAULT_LED_PERIOD) == 0) {
1521                         // led state is toggled
1522                         if (ledstate == PRI_LED_OFF) {
1523                                 DO_LED(xpd, which_led, PRI_LED_ON);
1524                                 DO_LED(xpd, other_led, PRI_LED_ON);
1525                         } else {
1526                                 DO_LED(xpd, which_led, PRI_LED_OFF);
1527                                 DO_LED(xpd, other_led, PRI_LED_OFF);
1528                         }
1529                 }
1530                 return;
1531         }
1532         if (priv->ledstate[other_led] != PRI_LED_OFF)
1533                 DO_LED(xpd, other_led, PRI_LED_OFF);
1534         if (priv->dchan_alive) {
1535                 mod = timer_count % 1000;
1536                 switch (mod) {
1537                 case 0:
1538                         DO_LED(xpd, which_led, PRI_LED_ON);
1539                         break;
1540                 case 500:
1541                         DO_LED(xpd, which_led, PRI_LED_OFF);
1542                         break;
1543                 }
1544         } else if (priv->layer1_up) {
1545                 mod = timer_count % 1000;
1546                 switch (mod) {
1547                 case 0:
1548                 case 100:
1549                         DO_LED(xpd, which_led, PRI_LED_ON);
1550                         break;
1551                 case 50:
1552                 case 150:
1553                         DO_LED(xpd, which_led, PRI_LED_OFF);
1554                         break;
1555                 }
1556         } else {
1557                 if (priv->ledstate[which_led] != PRI_LED_ON)
1558                         DO_LED(xpd, which_led, PRI_LED_ON);
1559         }
1560 }
1561
1562 static int PRI_card_tick(xbus_t *xbus, xpd_t *xpd)
1563 {
1564         struct PRI_priv_data *priv;
1565
1566         BUG_ON(!xpd);
1567         priv = xpd->priv;
1568         BUG_ON(!priv);
1569         if (!priv->initialized || !xbus->self_ticking)
1570                 return 0;
1571         /*
1572          * Poll layer1 status (cascade subunits)
1573          */
1574         if (poll_interval != 0 && ((xpd->timer_count % poll_interval) == 0)) {
1575                 priv->poll_noreplies++;
1576                 query_subunit(xpd, REG_FRS0);
1577                 //query_subunit(xpd, REG_FRS1);
1578         }
1579         if (priv->dchan_tx_counter >= 1 && priv->dchan_rx_counter > 1) {
1580                 dchan_state(xpd, 1);
1581                 priv->dchan_alive_ticks++;
1582         }
1583         handle_leds(xbus, xpd);
1584         return 0;
1585 }
1586
1587 static int PRI_card_ioctl(xpd_t *xpd, int pos, unsigned int cmd,
1588                           unsigned long arg)
1589 {
1590         struct dahdi_chan *chan;
1591
1592         BUG_ON(!xpd);
1593         if (!XBUS_IS(xpd->xbus, READY))
1594                 return -ENODEV;
1595         chan = XPD_CHAN(xpd, pos);
1596         switch (cmd) {
1597                 /*
1598                  * Asterisk may send FXS type ioctl()'s to us:
1599                  *   - Some are sent to everybody (DAHDI_TONEDETECT)
1600                  *   - Some are sent because we may be in CAS mode
1601                  *     (FXS signalling)
1602                  * Ignore them.
1603                  */
1604         case DAHDI_TONEDETECT:
1605                 LINE_DBG(SIGNAL, xpd, pos, "PRI: TONEDETECT (%s)\n",
1606                          (chan->
1607                           flags & DAHDI_FLAG_AUDIO) ? "AUDIO" : "SILENCE");
1608                 return -ENOTTY;
1609         case DAHDI_ONHOOKTRANSFER:
1610                 LINE_DBG(SIGNAL, xpd, pos, "PRI: ONHOOKTRANSFER\n");
1611                 return -ENOTTY;
1612         case DAHDI_VMWI:
1613                 LINE_DBG(SIGNAL, xpd, pos, "PRI: VMWI\n");
1614                 return -ENOTTY;
1615         case DAHDI_VMWI_CONFIG:
1616                 LINE_DBG(SIGNAL, xpd, pos, "PRI: VMWI_CONFIG\n");
1617                 return -ENOTTY;
1618         case DAHDI_SETPOLARITY:
1619                 LINE_DBG(SIGNAL, xpd, pos, "PRI: SETPOLARITY\n");
1620                 return -ENOTTY;
1621                 /* report on really bad ioctl()'s */
1622         default:
1623                 report_bad_ioctl(THIS_MODULE->name, xpd, pos, cmd);
1624                 return -ENOTTY;
1625         }
1626         return 0;
1627 }
1628
1629 /*
1630  * Called only for 'span' keyword in /etc/dahdi/system.conf
1631  */
1632 static int pri_startup(struct file *file, struct dahdi_span *span)
1633 {
1634         struct phonedev *phonedev = container_of(span, struct phonedev, span);
1635         xpd_t *xpd = container_of(phonedev, struct xpd, phonedev);
1636         struct PRI_priv_data *priv;
1637
1638         BUG_ON(!xpd);
1639         priv = xpd->priv;
1640         BUG_ON(!priv);
1641         if (!XBUS_IS(xpd->xbus, READY)) {
1642                 XPD_DBG(GENERAL, xpd,
1643                         "Startup called by dahdi. No Hardware. Ignored\n");
1644                 return -ENODEV;
1645         }
1646         XPD_DBG(GENERAL, xpd, "STARTUP\n");
1647         // Turn on all channels
1648         CALL_PHONE_METHOD(card_state, xpd, 1);
1649         set_rbslines(xpd, 0);
1650         write_subunit(xpd, REG_XPM2, 0x00);
1651         return 0;
1652 }
1653
1654 /*
1655  * Called only for 'span' keyword in /etc/dahdi/system.conf
1656  */
1657 static int pri_shutdown(struct dahdi_span *span)
1658 {
1659         struct phonedev *phonedev = container_of(span, struct phonedev, span);
1660         xpd_t *xpd = container_of(phonedev, struct xpd, phonedev);
1661         struct PRI_priv_data *priv;
1662
1663         BUG_ON(!xpd);
1664         priv = xpd->priv;
1665         BUG_ON(!priv);
1666         if (!XBUS_IS(xpd->xbus, READY)) {
1667                 XPD_DBG(GENERAL, xpd,
1668                         "Shutdown called by dahdi. No Hardware. Ignored\n");
1669                 return -ENODEV;
1670         }
1671         XPD_DBG(GENERAL, xpd, "SHUTDOWN\n");
1672         // Turn off all channels
1673         CALL_PHONE_METHOD(card_state, xpd, 0);
1674         return 0;
1675 }
1676
1677 static int encode_rbsbits_e1(xpd_t *xpd, int pos, int bits)
1678 {
1679         struct PRI_priv_data *priv;
1680         __u8 val;
1681         int rsnum;
1682
1683         BUG_ON(!xpd);
1684         priv = xpd->priv;
1685         BUG_ON(!priv);
1686         BUG_ON(priv->pri_protocol != PRI_PROTO_E1);
1687         if (pos == 15)
1688                 return 0;       /* Don't write dchan in CAS */
1689         if (pos < 0 || pos > 31) {
1690                 XPD_NOTICE(xpd, "%s: pos=%d out of range. Ignore\n", __func__,
1691                            pos);
1692                 return 0;
1693         }
1694         if (pos >= 16) {
1695                 /* Low nibble */
1696                 rsnum = pos - 16;
1697                 val = (priv->cas_ts_e[rsnum] & 0xF0) | (bits & 0x0F);
1698         } else {
1699                 /* High nibble */
1700                 rsnum = pos;
1701                 val = (priv->cas_ts_e[rsnum] & 0x0F) | ((bits << 4) & 0xF0);
1702         }
1703         LINE_DBG(SIGNAL, xpd, pos, "RBS: TX: bits=0x%X\n", bits);
1704         write_cas_reg(xpd, rsnum, val);
1705         return 0;
1706 }
1707
1708 static int encode_rbsbits_t1(xpd_t *xpd, int pos, int bits)
1709 {
1710         struct PRI_priv_data *priv;
1711         int rsnum;
1712         int chan_per_reg;
1713         int offset;
1714         int width;
1715         uint tx_bits = bits;
1716         uint mask;
1717         __u8 val;
1718
1719         BUG_ON(!xpd);
1720         priv = xpd->priv;
1721         BUG_ON(!priv);
1722         BUG_ON(priv->pri_protocol != PRI_PROTO_T1);
1723         if (pos < 0 || pos >= PHONEDEV(xpd).channels) {
1724                 XPD_ERR(xpd, "%s: Bad pos=%d\n", __func__, pos);
1725                 return 0;
1726         }
1727         chan_per_reg = CHAN_PER_REGS(priv);
1728         width = 8 / chan_per_reg;
1729         rsnum = pos / chan_per_reg;
1730         offset = pos % chan_per_reg;
1731         mask = BITMASK(width) << (chan_per_reg - offset - 1) * width;
1732         if (!priv->is_esf)
1733                 tx_bits >>= 2;
1734         tx_bits &= BITMASK(width);
1735         tx_bits <<= (chan_per_reg - offset - 1) * width;
1736         val = priv->cas_ts_e[rsnum];
1737         val &= ~mask;
1738         val |= tx_bits;
1739         LINE_DBG(SIGNAL, xpd, pos,
1740                  "bits=0x%02X RS%02d(%s) offset=%d tx_bits=0x%02X\n", bits,
1741                  rsnum + 1, (priv->is_esf) ? "esf" : "d4", offset, tx_bits);
1742         write_cas_reg(xpd, rsnum, val);
1743         priv->dchan_tx_counter++;
1744         return 0;
1745 }
1746
1747 static void send_idlebits(xpd_t *xpd, bool saveold)
1748 {
1749         struct PRI_priv_data *priv;
1750         __u8 save_rs[NUM_CAS_RS_E];
1751         int i;
1752
1753         if (!SPAN_REGISTERED(xpd))
1754                 return;
1755         priv = xpd->priv;
1756         BUG_ON(!priv);
1757         XPD_DBG(SIGNAL, xpd, "saveold=%d\n", saveold);
1758         if (saveold)
1759                 memcpy(save_rs, priv->cas_ts_e, sizeof(save_rs));
1760         for_each_line(xpd, i) {
1761                 struct dahdi_chan *chan = XPD_CHAN(xpd, i);
1762
1763                 pri_rbsbits(chan, chan->idlebits);
1764         }
1765         if (saveold)
1766                 memcpy(priv->cas_ts_e, save_rs, sizeof(save_rs));
1767 }
1768
1769 static void send_oldbits(xpd_t *xpd)
1770 {
1771         struct PRI_priv_data *priv;
1772         int i;
1773
1774         BUG_ON(!xpd);
1775         priv = xpd->priv;
1776         BUG_ON(!priv);
1777         XPD_DBG(SIGNAL, xpd, "\n");
1778         for (i = 0; i < cas_numregs(xpd); i++)
1779                 write_cas_reg(xpd, i, priv->cas_ts_e[i]);
1780 }
1781
1782 static int pri_rbsbits(struct dahdi_chan *chan, int bits)
1783 {
1784         xpd_t *xpd;
1785         struct PRI_priv_data *priv;
1786         int pos;
1787
1788         xpd = chan->pvt;
1789         BUG_ON(!xpd);
1790         pos = chan->chanpos - 1;
1791         priv = xpd->priv;
1792         BUG_ON(!priv);
1793         if (!priv->is_cas) {
1794                 XPD_DBG(SIGNAL, xpd, "RBS: TX: not in CAS mode. Ignore.\n");
1795                 return 0;
1796         }
1797         if (chan->sig == DAHDI_SIG_NONE) {
1798                 LINE_DBG(SIGNAL, xpd, pos,
1799                          "RBS: TX: sigtyp=%s. , bits=0x%X. Ignore.\n",
1800                          sig2str(chan->sig), bits);
1801                 return 0;
1802         }
1803         if (!priv->layer1_up)
1804                 XPD_DBG(SIGNAL, xpd, "RBS: TX: No layer1 yet. Keep going.\n");
1805         if (priv->pri_protocol == PRI_PROTO_E1) {
1806                 if (encode_rbsbits_e1(xpd, pos, bits) < 0)
1807                         return -EINVAL;
1808         } else if (priv->pri_protocol == PRI_PROTO_T1) {
1809                 if (encode_rbsbits_t1(xpd, pos, bits) < 0)
1810                         return -EINVAL;
1811         } else {
1812                 XPD_NOTICE(xpd,
1813                            "%s: protocol %s is not supported yet with CAS\n",
1814                            __func__, pri_protocol_name(priv->pri_protocol));
1815                 return -EINVAL;
1816         }
1817         return 0;
1818 }
1819
1820 /*! Copy PCM chunks from the buffers of the xpd to a new packet
1821  * \param xbus  xbus of source xpd.
1822  * \param xpd   source xpd.
1823  * \param lines a bitmask of the active channels that need to be copied.
1824  * \param pack  packet to be filled.
1825  *
1826  * On PRI this function is should also shift the lines mask one bit, as
1827  * channel 0 on the wire is an internal chip control channel. We only
1828  * send 31 channels to the device, but they should be called 1-31 rather
1829  * than 0-30 .
1830  */
1831 static void PRI_card_pcm_fromspan(xpd_t *xpd, xpacket_t *pack)
1832 {
1833         struct PRI_priv_data *priv;
1834         __u8 *pcm;
1835         unsigned long flags;
1836         int i;
1837         xpp_line_t wanted_lines;
1838         int physical_chan;
1839         int physical_mask = 0;
1840
1841         BUG_ON(!xpd);
1842         BUG_ON(!pack);
1843         priv = xpd->priv;
1844         BUG_ON(!priv);
1845         pcm = RPACKET_FIELD(pack, GLOBAL, PCM_WRITE, pcm);
1846         spin_lock_irqsave(&xpd->lock, flags);
1847         wanted_lines = PHONEDEV(xpd).wanted_pcm_mask;
1848         physical_chan = 0;
1849         for_each_line(xpd, i) {
1850                 struct dahdi_chan *chan = XPD_CHAN(xpd, i);
1851
1852                 if (priv->pri_protocol == PRI_PROTO_E1) {
1853                         /* In E1 - Only 0'th channel is unused */
1854                         if (i == 0)
1855                                 physical_chan++;
1856                 } else if (priv->pri_protocol == PRI_PROTO_T1) {
1857                         /* In T1 - Every 4'th channel is unused */
1858                         if ((i % 3) == 0)
1859                                 physical_chan++;
1860                 }
1861                 if (IS_SET(wanted_lines, i)) {
1862                         physical_mask |= BIT(physical_chan);
1863                         if (SPAN_REGISTERED(xpd)) {
1864 #ifdef  DEBUG_PCMTX
1865                                 int channo = XPD_CHAN(xpd, i)->channo;
1866
1867                                 if (pcmtx >= 0 && pcmtx_chan == channo)
1868                                         memset((u_char *)pcm, pcmtx,
1869                                                DAHDI_CHUNKSIZE);
1870                                 else
1871 #endif
1872                                         memcpy((u_char *)pcm, chan->writechunk,
1873                                                DAHDI_CHUNKSIZE);
1874                                 if (i == PRI_DCHAN_IDX(priv)) {
1875                                         if (priv->dchan_tx_sample !=
1876                                             chan->writechunk[0]) {
1877                                                 priv->dchan_tx_sample =
1878                                                     chan->writechunk[0];
1879                                                 priv->dchan_tx_counter++;
1880                                         } else if (chan->writechunk[0] == 0xFF)
1881                                                 dchan_state(xpd, 0);
1882                                         else
1883                                                 /* Clobber for next tick */
1884                                                 chan->writechunk[0] = 0xFF;
1885                                 }
1886                         } else
1887                                 memset((u_char *)pcm, DAHDI_XLAW(0, chan),
1888                                        DAHDI_CHUNKSIZE);
1889                         pcm += DAHDI_CHUNKSIZE;
1890                 }
1891                 physical_chan++;
1892         }
1893         RPACKET_FIELD(pack, GLOBAL, PCM_WRITE, lines) = physical_mask;
1894         XPD_COUNTER(xpd, PCM_WRITE)++;
1895         spin_unlock_irqrestore(&xpd->lock, flags);
1896 }
1897
1898 /*! Copy PCM chunks from the packet we received to the xpd struct.
1899  * \param xbus  xbus of target xpd.
1900  * \param xpd   target xpd.
1901  * \param pack  Source packet.
1902  *
1903  * On PRI this function is should also shift the lines back mask one bit, as
1904  * channel 0 on the wire is an internal chip control channel.
1905  *
1906  * \see PRI_card_pcm_fromspan
1907  */
1908 static void PRI_card_pcm_tospan(xpd_t *xpd, xpacket_t *pack)
1909 {
1910         struct PRI_priv_data *priv;
1911         __u8 *pcm;
1912         xpp_line_t physical_mask;
1913         unsigned long flags;
1914         int i;
1915         int logical_chan;
1916
1917         if (!SPAN_REGISTERED(xpd))
1918                 return;
1919         priv = xpd->priv;
1920         BUG_ON(!priv);
1921         pcm = RPACKET_FIELD(pack, GLOBAL, PCM_READ, pcm);
1922         physical_mask = RPACKET_FIELD(pack, GLOBAL, PCM_WRITE, lines);
1923         spin_lock_irqsave(&xpd->lock, flags);
1924         logical_chan = 0;
1925         for (i = 0; i < CHANNELS_PERXPD; i++) {
1926                 volatile u_char *r;
1927
1928                 if (priv->pri_protocol == PRI_PROTO_E1) {
1929                         /* In E1 - Only 0'th channel is unused */
1930                         if (i == 0)
1931                                 continue;
1932                 } else if (priv->pri_protocol == PRI_PROTO_T1) {
1933                         /* In T1 - Every 4'th channel is unused */
1934                         if ((i % 4) == 0)
1935                                 continue;
1936                 }
1937                 if (logical_chan == PRI_DCHAN_IDX(priv) && !priv->is_cas) {
1938                         if (priv->dchan_rx_sample != pcm[0]) {
1939                                 if (debug & DBG_PCM) {
1940                                         XPD_INFO(xpd,
1941                                                 "RX-D-Chan: prev=0x%X now=0x%X\n",
1942                                                 priv->dchan_rx_sample, pcm[0]);
1943                                         dump_packet("RX-D-Chan", pack, 1);
1944                                 }
1945                                 priv->dchan_rx_sample = pcm[0];
1946                                 priv->dchan_rx_counter++;
1947                         } else if (pcm[0] == 0xFF)
1948                                 dchan_state(xpd, 0);
1949                 }
1950                 if (IS_SET(physical_mask, i)) {
1951                         struct dahdi_chan *chan = XPD_CHAN(xpd, logical_chan);
1952                         r = chan->readchunk;
1953                         // memset((u_char *)r, 0x5A, DAHDI_CHUNKSIZE);  // DEBUG
1954                         memcpy((u_char *)r, pcm, DAHDI_CHUNKSIZE);
1955                         pcm += DAHDI_CHUNKSIZE;
1956                 }
1957                 logical_chan++;
1958         }
1959         XPD_COUNTER(xpd, PCM_READ)++;
1960         spin_unlock_irqrestore(&xpd->lock, flags);
1961 }
1962
1963 static int PRI_timing_priority(xpd_t *xpd)
1964 {
1965         struct PRI_priv_data *priv;
1966
1967         priv = xpd->priv;
1968         BUG_ON(!priv);
1969         if (priv->layer1_up)
1970                 return PHONEDEV(xpd).timing_priority;
1971         XPD_DBG(SYNC, xpd, "No timing priority (no layer1)\n");
1972         return -ENOENT;
1973 }
1974
1975 static int PRI_echocancel_timeslot(xpd_t *xpd, int pos)
1976 {
1977         /*
1978          * Skip ts=0 (used for PRI sync)
1979          */
1980         return (1 + pos) * 4 + xpd->addr.subunit;
1981 }
1982
1983 static int PRI_echocancel_setmask(xpd_t *xpd, xpp_line_t ec_mask)
1984 {
1985         struct PRI_priv_data *priv;
1986         int i;
1987
1988         BUG_ON(!xpd);
1989         priv = xpd->priv;
1990         BUG_ON(!priv);
1991         XPD_DBG(GENERAL, xpd, "0x%8X\n", ec_mask);
1992         if (!ECHOOPS(xpd->xbus)) {
1993                 XPD_DBG(GENERAL, xpd,
1994                         "No echo canceller in XBUS: Doing nothing.\n");
1995                 return -EINVAL;
1996         }
1997         for (i = 0; i < PHONEDEV(xpd).channels; i++) {
1998                 int on = BIT(i) & ec_mask;
1999
2000                 if (i == PRI_DCHAN_IDX(priv))
2001                         on = 0;
2002                 CALL_EC_METHOD(ec_set, xpd->xbus, xpd, i, on);
2003         }
2004         CALL_EC_METHOD(ec_update, xpd->xbus, xpd->xbus);
2005         return 0;
2006 }
2007
2008 /*---------------- PRI: HOST COMMANDS -------------------------------------*/
2009
2010 static /* 0x33 */ HOSTCMD(PRI, SET_LED, enum pri_led_selectors led_sel,
2011                           enum pri_led_state to_led_state)
2012 {
2013         int ret = 0;
2014         xframe_t *xframe;
2015         xpacket_t *pack;
2016         struct pri_leds *pri_leds;
2017         struct PRI_priv_data *priv;
2018
2019         BUG_ON(!xbus);
2020         BUG_ON(!xpd);
2021         priv = xpd->priv;
2022         BUG_ON(!priv);
2023         XPD_DBG(LEDS, xpd, "led_sel=%d to_state=%d\n", led_sel, to_led_state);
2024         XFRAME_NEW_CMD(xframe, pack, xbus, PRI, SET_LED, xpd->xbus_idx);
2025         pri_leds = &RPACKET_FIELD(pack, PRI, SET_LED, pri_leds);
2026         pri_leds->state = to_led_state;
2027         pri_leds->led_sel = led_sel;
2028         pri_leds->reserved = 0;
2029         XPACKET_LEN(pack) = RPACKET_SIZE(PRI, SET_LED);
2030         ret = send_cmd_frame(xbus, xframe);
2031         priv->ledstate[led_sel] = to_led_state;
2032         return ret;
2033 }
2034
2035 /*---------------- PRI: Astribank Reply Handlers --------------------------*/
2036 static void layer1_state(xpd_t *xpd, __u8 data_low)
2037 {
2038         struct PRI_priv_data *priv;
2039         int alarms = DAHDI_ALARM_NONE;
2040         int layer1_up_prev;
2041
2042         BUG_ON(!xpd);
2043         priv = xpd->priv;
2044         BUG_ON(!priv);
2045         priv->poll_noreplies = 0;
2046         if (data_low & REG_FRS0_LOS)
2047                 alarms |= DAHDI_ALARM_RED;
2048         if (data_low & REG_FRS0_AIS)
2049                 alarms |= DAHDI_ALARM_BLUE;
2050         if (data_low & REG_FRS0_RRA)
2051                 alarms |= DAHDI_ALARM_YELLOW;
2052         layer1_up_prev = priv->layer1_up;
2053         priv->layer1_up = alarms == DAHDI_ALARM_NONE;
2054 #if 0
2055         /*
2056          * Some bad bits (e.g: LMFA and NMF have no alarm "colors"
2057          * associated. However, layer1 is still not working if they are set.
2058          * FIXME: These behave differently in E1/T1, so ignore them for while.
2059          */
2060         if (data_low & (REG_FRS0_LMFA | REG_FRS0_E1_NMF))
2061                 priv->layer1_up = 0;
2062 #endif
2063         priv->alarms = alarms;
2064         if (!priv->layer1_up) {
2065                 dchan_state(xpd, 0);
2066         } else if (priv->is_cas && !layer1_up_prev) {
2067                 int regbase = cas_regbase(xpd);
2068                 int i;
2069
2070                 XPD_DBG(SIGNAL, xpd,
2071                         "Returning From Alarm Refreshing Rx register data \n");
2072                 for (i = 0; i < cas_numregs(xpd); i++)
2073                         query_subunit(xpd, regbase + i);
2074         }
2075
2076         if (SPAN_REGISTERED(xpd) && PHONEDEV(xpd).span.alarms != alarms) {
2077                 char str1[MAX_PROC_WRITE];
2078                 char str2[MAX_PROC_WRITE];
2079
2080                 alarm2str(PHONEDEV(xpd).span.alarms, str1, sizeof(str1));
2081                 alarm2str(alarms, str2, sizeof(str2));
2082                 XPD_NOTICE(xpd, "Alarms: 0x%X (%s) => 0x%X (%s)\n",
2083                            PHONEDEV(xpd).span.alarms, str1, alarms, str2);
2084                 if (priv->is_cas) {
2085                         if (alarms == DAHDI_ALARM_NONE)
2086                                 send_oldbits(xpd);
2087                         else if (PHONEDEV(xpd).span.alarms == DAHDI_ALARM_NONE)
2088                                 send_idlebits(xpd, 1);
2089                 }
2090                 PHONEDEV(xpd).span.alarms = alarms;
2091                 elect_syncer("LAYER1");
2092                 dahdi_alarm_notify(&PHONEDEV(xpd).span);
2093                 set_clocking(xpd);
2094         }
2095         priv->reg_frs0 = data_low;
2096         priv->layer1_replies++;
2097         XPD_DBG(REGS, xpd, "subunit=%d data_low=0x%02X\n", xpd->addr.subunit,
2098                 data_low);
2099 }
2100
2101 static int decode_cas_e1(xpd_t *xpd, __u8 regnum, __u8 data_low)
2102 {
2103         struct PRI_priv_data *priv;
2104         uint pos = regnum - REG_RS2_E;
2105         int rsnum = pos + 2;
2106         int chan1 = pos;
2107         int chan2 = pos + 16;
2108         int val1 = (data_low >> 4) & 0xF;
2109         int val2 = data_low & 0xF;
2110
2111         priv = xpd->priv;
2112         BUG_ON(!priv->is_cas);
2113         BUG_ON(priv->pri_protocol != PRI_PROTO_E1);
2114         XPD_DBG(SIGNAL, xpd, "RBS: RX: data_low=0x%02X\n", data_low);
2115         if (pos >= NUM_CAS_RS_E) {
2116                 XPD_ERR(xpd, "%s: got bad pos=%d [0-%d]\n", __func__, pos,
2117                         NUM_CAS_RS_E);
2118                 return -EINVAL;
2119         }
2120         if (chan1 < 0 || chan1 > PHONEDEV(xpd).channels) {
2121                 XPD_NOTICE(xpd, "%s: %s CAS: Bad chan1 number (%d)\n", __func__,
2122                            pri_protocol_name(priv->pri_protocol), chan1);
2123                 return -EINVAL;
2124         }
2125         if (chan2 < 0 || chan2 > PHONEDEV(xpd).channels) {
2126                 XPD_NOTICE(xpd, "%s: %s CAS: Bad chan2 number (%d)\n", __func__,
2127                            pri_protocol_name(priv->pri_protocol), chan2);
2128                 return -EINVAL;
2129         }
2130         XPD_DBG(SIGNAL, xpd,
2131                 "RBS: RX: RS%02d (channel %2d, channel %2d): 0x%02X -> 0x%02X\n",
2132                 rsnum, chan1 + 1, chan2 + 1, priv->cas_rs_e[pos], data_low);
2133         if (SPAN_REGISTERED(xpd)) {
2134                 dahdi_rbsbits(XPD_CHAN(xpd, chan1), val1);
2135                 dahdi_rbsbits(XPD_CHAN(xpd, chan2), val2);
2136         }
2137         priv->dchan_rx_counter++;
2138         priv->cas_rs_e[pos] = data_low;
2139         return 0;
2140 }
2141
2142 static int decode_cas_t1(xpd_t *xpd, __u8 regnum, __u8 data_low)
2143 {
2144         struct PRI_priv_data *priv;
2145         uint rsnum;
2146         uint chan_per_reg;
2147         uint width;
2148         int i;
2149
2150         priv = xpd->priv;
2151         BUG_ON(!priv->is_cas);
2152         BUG_ON(priv->pri_protocol != PRI_PROTO_T1);
2153         rsnum = regnum - REG_RS1_E;
2154         if (rsnum >= 12) {
2155                 XPD_ERR(xpd, "Bad rsnum=%d\n", rsnum);
2156                 return 0;
2157         }
2158         if (!priv->is_esf)
2159                 rsnum = rsnum % 6;      /* 2 identical banks of 6 registers */
2160         chan_per_reg = CHAN_PER_REGS(priv);
2161         width = 8 / chan_per_reg;
2162         XPD_DBG(SIGNAL, xpd, "RBS: RX(%s,%d): RS%02d data_low=0x%02X\n",
2163                 (priv->is_esf) ? "esf" : "d4", chan_per_reg, rsnum + 1,
2164                 data_low);
2165         for (i = 0; i < chan_per_reg; i++) {
2166                 uint rxsig = (data_low >> (i * width)) & BITMASK(width);
2167                 int pos;
2168                 struct dahdi_chan *chan;
2169
2170                 if (!priv->is_esf)
2171                         rxsig <<= 2;
2172                 pos = rsnum * chan_per_reg + chan_per_reg - i - 1;
2173                 if (pos < 0 || pos >= PHONEDEV(xpd).channels) {
2174                         XPD_ERR(xpd, "%s: Bad pos=%d\n", __func__, pos);
2175                         continue;
2176                 }
2177                 chan = XPD_CHAN(xpd, pos);
2178                 if (!chan) {
2179                         XPD_ERR(xpd, "%s: Null channel in pos=%d\n", __func__,
2180                                 pos);
2181                         continue;
2182                 }
2183                 if (chan->rxsig != rxsig) {
2184                         LINE_DBG(SIGNAL, xpd, pos, "i=%d rxsig=0x%02X\n", i,
2185                                  rxsig);
2186                         dahdi_rbsbits(chan, rxsig);
2187                 }
2188         }
2189         priv->cas_rs_e[rsnum] = data_low;
2190         return 0;
2191 }
2192
2193 static void process_cas_dchan(xpd_t *xpd, __u8 regnum, __u8 data_low)
2194 {
2195         struct PRI_priv_data *priv;
2196
2197         priv = xpd->priv;
2198         if (!priv->is_cas) {
2199                 static int rate_limit;
2200
2201                 if ((rate_limit++ % 10003) == 0)
2202                         XPD_NOTICE(xpd, "RBS: RX: not in CAS mode. Ignore.\n");
2203                 return;
2204         }
2205         if (!priv->layer1_up) {
2206                 static int rate_limit;
2207
2208                 if ((rate_limit++ % 10003) == 0)
2209                         XPD_DBG(SIGNAL, xpd, "RBS: RX: No layer1.\n");
2210         }
2211         if (!SPAN_REGISTERED(xpd)) {
2212                 static int rate_limit;
2213
2214                 if ((rate_limit++ % 10003) == 0)
2215                         XPD_DBG(SIGNAL, xpd,
2216                                 "RBS: RX: Span not registered. Ignore.\n");
2217                 return;
2218         }
2219         if (priv->pri_protocol == PRI_PROTO_E1) {
2220                 if (regnum == REG_RS1_E)
2221                         return; /* Time slot 0: Ignored for E1 */
2222                 if (regnum < REG_RS2_E) {
2223                         /* Should not happen, but harmless. Ignore */
2224                         if (regnum == REG_RS1_E)
2225                                 return;
2226
2227                         XPD_NOTICE(xpd,
2228                                 "%s: received register 0x%X in protocol %s. "
2229                                 "Ignore.\n",
2230                                 __func__, regnum,
2231                                 pri_protocol_name(priv->pri_protocol));
2232                         return;
2233                 }
2234                 if (decode_cas_e1(xpd, regnum, data_low) < 0)
2235                         return;
2236         } else if (priv->pri_protocol == PRI_PROTO_T1) {
2237                 if (regnum > REG_RS12_E) {
2238                         XPD_NOTICE(xpd,
2239                                 "%s: received register 0x%X in protocol %s. "
2240                                 "Ignore.\n",
2241                                 __func__, regnum,
2242                                    pri_protocol_name(priv->pri_protocol));
2243                         return;
2244                 }
2245                 if (decode_cas_t1(xpd, regnum, data_low) < 0)
2246                         return;
2247         } else {
2248                 XPD_NOTICE(xpd,
2249                            "%s: protocol %s is not supported yet with CAS\n",
2250                            __func__, pri_protocol_name(priv->pri_protocol));
2251         }
2252         priv->cas_replies++;
2253 }
2254
2255 static int PRI_card_register_reply(xbus_t *xbus, xpd_t *xpd, reg_cmd_t *info)
2256 {
2257         unsigned long flags;
2258         struct PRI_priv_data *priv;
2259         struct xpd_addr addr;
2260         xpd_t *orig_xpd;
2261         __u8 regnum;
2262         __u8 data_low;
2263
2264         /* Map UNIT + PORTNUM to XPD */
2265         orig_xpd = xpd;
2266         addr.unit = orig_xpd->addr.unit;
2267         addr.subunit = info->h.portnum;
2268         regnum = REG_FIELD(info, regnum);
2269         data_low = REG_FIELD(info, data_low);
2270         xpd = xpd_byaddr(xbus, addr.unit, addr.subunit);
2271         if (!xpd) {
2272                 static int rate_limit;
2273
2274                 if ((rate_limit++ % 1003) < 5)
2275                         notify_bad_xpd(__func__, xbus, addr, orig_xpd->xpdname);
2276                 return -EPROTO;
2277         }
2278         spin_lock_irqsave(&xpd->lock, flags);
2279         priv = xpd->priv;
2280         BUG_ON(!priv);
2281         if (info->h.is_multibyte) {
2282                 XPD_NOTICE(xpd, "Got Multibyte: %d bytes, eoframe: %d\n",
2283                            info->h.bytes, info->h.eoframe);
2284                 goto end;
2285         }
2286         if (regnum == REG_FRS0 && !REG_FIELD(info, do_subreg))
2287                 layer1_state(xpd, data_low);
2288         else if (regnum == REG_FRS1 && !REG_FIELD(info, do_subreg))
2289                 priv->reg_frs1 = data_low;
2290         if (priv->is_cas && !REG_FIELD(info, do_subreg)) {
2291                 if (regnum >= REG_RS1_E && regnum <= REG_RS16_E)
2292                         process_cas_dchan(xpd, regnum, data_low);
2293         }
2294         /*
2295          * Update /proc info only if reply relate to the
2296          * last slic read request
2297          */
2298         if (REG_FIELD(&xpd->requested_reply, regnum) ==
2299                         REG_FIELD(info, regnum)
2300                 && REG_FIELD(&xpd->requested_reply, do_subreg) ==
2301                         REG_FIELD(info, do_subreg)
2302                 && REG_FIELD(&xpd->requested_reply, subreg) ==
2303                         REG_FIELD(info, subreg)) {
2304                 xpd->last_reply = *info;
2305         }
2306
2307 end:
2308         spin_unlock_irqrestore(&xpd->lock, flags);
2309         return 0;
2310 }
2311
2312 static int PRI_card_state(xpd_t *xpd, bool on)
2313 {
2314         BUG_ON(!xpd);
2315         XPD_DBG(GENERAL, xpd, "%s\n", (on) ? "on" : "off");
2316         return 0;
2317 }
2318
2319 static const struct xops pri_xops = {
2320         .card_new = PRI_card_new,
2321         .card_init = PRI_card_init,
2322         .card_remove = PRI_card_remove,
2323         .card_tick = PRI_card_tick,
2324         .card_register_reply = PRI_card_register_reply,
2325 };
2326
2327 static const struct phoneops pri_phoneops = {
2328         .card_dahdi_preregistration = PRI_card_dahdi_preregistration,
2329         .card_dahdi_postregistration = PRI_card_dahdi_postregistration,
2330         .card_pcm_recompute = PRI_card_pcm_recompute,
2331         .card_pcm_fromspan = PRI_card_pcm_fromspan,
2332         .card_pcm_tospan = PRI_card_pcm_tospan,
2333         .echocancel_timeslot = PRI_echocancel_timeslot,
2334         .echocancel_setmask = PRI_echocancel_setmask,
2335         .card_timing_priority = PRI_timing_priority,
2336         .card_ioctl = PRI_card_ioctl,
2337         .card_open = PRI_card_open,
2338         .card_close = PRI_card_close,
2339         .card_state = PRI_card_state,
2340 };
2341
2342 static xproto_table_t PROTO_TABLE(PRI) = {
2343         .owner = THIS_MODULE,
2344         .entries = {
2345                 /*      Table   Card    Opcode          */
2346         },
2347         .name = "PRI",  /* protocol name */
2348         .ports_per_subunit = 1,
2349         .type = XPD_TYPE_PRI,
2350         .xops = &pri_xops,
2351         .phoneops = &pri_phoneops,
2352         .packet_is_valid = pri_packet_is_valid,
2353         .packet_dump = pri_packet_dump,
2354 };
2355
2356 static bool pri_packet_is_valid(xpacket_t *pack)
2357 {
2358         const xproto_entry_t *xe = NULL;
2359         // DBG(GENERAL, "\n");
2360         xe = xproto_card_entry(&PROTO_TABLE(PRI), XPACKET_OP(pack));
2361         return xe != NULL;
2362 }
2363
2364 static void pri_packet_dump(const char *msg, xpacket_t *pack)
2365 {
2366         DBG(GENERAL, "%s\n", msg);
2367 }
2368
2369 /*------------------------- REGISTER Handling --------------------------*/
2370
2371 /*------------------------- sysfs stuff --------------------------------*/
2372 static DEVICE_ATTR_READER(pri_protocol_show, dev, buf)
2373 {
2374         xpd_t *xpd;
2375         struct PRI_priv_data *priv;
2376         unsigned long flags;
2377         int len = 0;
2378
2379         BUG_ON(!dev);
2380         xpd = dev_to_xpd(dev);
2381         if (!xpd)
2382                 return -ENODEV;
2383         priv = xpd->priv;
2384         BUG_ON(!priv);
2385         spin_lock_irqsave(&xpd->lock, flags);
2386         len += sprintf(buf, "%s\n", pri_protocol_name(priv->pri_protocol));
2387         spin_unlock_irqrestore(&xpd->lock, flags);
2388         return len;
2389 }
2390
2391 static DEVICE_ATTR_WRITER(pri_protocol_store, dev, buf, count)
2392 {
2393         xpd_t *xpd;
2394         enum pri_protocol new_protocol = PRI_PROTO_0;
2395         int i;
2396         int ret;
2397
2398         BUG_ON(!dev);
2399         xpd = dev_to_xpd(dev);
2400         XPD_DBG(GENERAL, xpd, "%s\n", buf);
2401         if (!xpd)
2402                 return -ENODEV;
2403         i = strcspn(buf, " \r\n");
2404         if (i != 2) {
2405                 XPD_NOTICE(xpd,
2406                         "Protocol name '%s' has %d characters (should be 2). "
2407                         "Ignored.\n",
2408                         buf, i);
2409                 return -EINVAL;
2410         }
2411         if (strncasecmp(buf, "E1", 2) == 0)
2412                 new_protocol = PRI_PROTO_E1;
2413         else if (strncasecmp(buf, "T1", 2) == 0)
2414                 new_protocol = PRI_PROTO_T1;
2415         else if (strncasecmp(buf, "J1", 2) == 0)
2416                 new_protocol = PRI_PROTO_J1;
2417         else {
2418                 XPD_NOTICE(xpd,
2419                         "Unknown PRI protocol '%s' (should be E1|T1|J1). "
2420                         "Ignored.\n",
2421                         buf);
2422                 return -EINVAL;
2423         }
2424         ret = set_pri_proto(xpd, new_protocol);
2425         return (ret < 0) ? ret : count;
2426 }
2427
2428 static DEVICE_ATTR(pri_protocol, S_IRUGO | S_IWUSR, pri_protocol_show,
2429                    pri_protocol_store);
2430
2431 static DEVICE_ATTR_READER(pri_localloop_show, dev, buf)
2432 {
2433         xpd_t *xpd;
2434         struct PRI_priv_data *priv;
2435         unsigned long flags;
2436         int len = 0;
2437
2438         BUG_ON(!dev);
2439         xpd = dev_to_xpd(dev);
2440         if (!xpd)
2441                 return -ENODEV;
2442         priv = xpd->priv;
2443         BUG_ON(!priv);
2444         spin_lock_irqsave(&xpd->lock, flags);
2445         len += sprintf(buf, "%c\n", (priv->local_loopback) ? 'Y' : 'N');
2446         spin_unlock_irqrestore(&xpd->lock, flags);
2447         return len;
2448 }
2449
2450 static DEVICE_ATTR_WRITER(pri_localloop_store, dev, buf, count)
2451 {
2452         xpd_t *xpd;
2453         bool ll = 0;
2454         int i;
2455         int ret;
2456
2457         BUG_ON(!dev);
2458         xpd = dev_to_xpd(dev);
2459         XPD_DBG(GENERAL, xpd, "%s\n", buf);
2460         if (!xpd)
2461                 return -ENODEV;
2462         if ((i = strcspn(buf, " \r\n")) != 1) {
2463                 XPD_NOTICE(xpd,
2464                         "Value '%s' has %d characters (should be 1). Ignored\n",
2465                         buf, i);
2466                 return -EINVAL;
2467         }
2468         if (strchr("1Yy", buf[0]) != NULL)
2469                 ll = 1;
2470         else if (strchr("0Nn", buf[0]) != NULL)
2471                 ll = 0;
2472         else {
2473                 XPD_NOTICE(xpd,
2474                         "Unknown value '%s' (should be [1Yy]|[0Nn]). Ignored\n",
2475                         buf);
2476                 return -EINVAL;
2477         }
2478         ret = set_localloop(xpd, ll);
2479         return (ret < 0) ? ret : count;
2480 }
2481
2482 static DEVICE_ATTR(pri_localloop, S_IRUGO | S_IWUSR, pri_localloop_show,
2483                    pri_localloop_store);
2484
2485 static DEVICE_ATTR_READER(pri_layer1_show, dev, buf)
2486 {
2487         xpd_t *xpd;
2488         struct PRI_priv_data *priv;
2489         unsigned long flags;
2490         int len = 0;
2491
2492         BUG_ON(!dev);
2493         xpd = dev_to_xpd(dev);
2494         if (!xpd)
2495                 return -ENODEV;
2496         priv = xpd->priv;
2497         BUG_ON(!priv);
2498         spin_lock_irqsave(&xpd->lock, flags);
2499         if (priv->poll_noreplies > 1)
2500                 len += sprintf(buf + len, "Unknown[%d]", priv->poll_noreplies);
2501         else
2502                 len +=
2503                     sprintf(buf + len, "%-10s",
2504                             ((priv->layer1_up) ? "UP" : "DOWN"));
2505         len += sprintf(buf + len, "%d\n", priv->layer1_replies);
2506         spin_unlock_irqrestore(&xpd->lock, flags);
2507         return len;
2508 }
2509
2510 static DEVICE_ATTR(pri_layer1, S_IRUGO, pri_layer1_show, NULL);
2511
2512 static DEVICE_ATTR_READER(pri_alarms_show, dev, buf)
2513 {
2514         xpd_t *xpd;
2515         struct PRI_priv_data *priv;
2516         unsigned long flags;
2517         int len = 0;
2518         static const struct {
2519                 __u8 bits;
2520                 const char *name;
2521         } alarm_types[] = {
2522                 {
2523                 REG_FRS0_LOS, "RED"}, {
2524                 REG_FRS0_AIS, "BLUE"}, {
2525         REG_FRS0_RRA, "YELLOW"},};
2526
2527         BUG_ON(!dev);
2528         xpd = dev_to_xpd(dev);
2529         if (!xpd)
2530                 return -ENODEV;
2531         priv = xpd->priv;
2532         BUG_ON(!priv);
2533         spin_lock_irqsave(&xpd->lock, flags);
2534         if (priv->poll_noreplies > 1)
2535                 len += sprintf(buf + len, "Unknown[%d]", priv->poll_noreplies);
2536         else {
2537                 int i;
2538
2539                 for (i = 0; i < ARRAY_SIZE(alarm_types); i++) {
2540                         if (priv->reg_frs0 & alarm_types[i].bits)
2541                                 len +=
2542                                     sprintf(buf + len, "%s ",
2543                                             alarm_types[i].name);
2544                 }
2545         }
2546         len += sprintf(buf + len, "\n");
2547         spin_unlock_irqrestore(&xpd->lock, flags);
2548         return len;
2549 }
2550
2551 static DEVICE_ATTR(pri_alarms, S_IRUGO, pri_alarms_show, NULL);
2552
2553 static DEVICE_ATTR_READER(pri_cas_show, dev, buf)
2554 {
2555         xpd_t *xpd;
2556         struct PRI_priv_data *priv;
2557         unsigned long flags;
2558         int len = 0;
2559
2560         BUG_ON(!dev);
2561         xpd = dev_to_xpd(dev);
2562         if (!xpd)
2563                 return -ENODEV;
2564         priv = xpd->priv;
2565         BUG_ON(!priv);
2566         spin_lock_irqsave(&xpd->lock, flags);
2567         if (priv->is_cas) {
2568                 int i;
2569
2570                 len +=
2571                     sprintf(buf + len, "CAS: replies=%d\n", priv->cas_replies);
2572                 len += sprintf(buf + len, "   CAS-TS: ");
2573                 for (i = 0; i < NUM_CAS_RS_E; i++)
2574                         len += sprintf(buf + len, " %02X", priv->cas_ts_e[i]);
2575                 len += sprintf(buf + len, "\n");
2576                 len += sprintf(buf + len, "   CAS-RS: ");
2577                 for (i = 0; i < NUM_CAS_RS_E; i++)
2578                         len += sprintf(buf + len, " %02X", priv->cas_rs_e[i]);
2579                 len += sprintf(buf + len, "\n");
2580         }
2581         spin_unlock_irqrestore(&xpd->lock, flags);
2582         return len;
2583 }
2584
2585 static DEVICE_ATTR(pri_cas, S_IRUGO, pri_cas_show, NULL);
2586
2587 static DEVICE_ATTR_READER(pri_dchan_show, dev, buf)
2588 {
2589         xpd_t *xpd;
2590         struct PRI_priv_data *priv;
2591         unsigned long flags;
2592         int len = 0;
2593
2594         BUG_ON(!dev);
2595         xpd = dev_to_xpd(dev);
2596         if (!xpd)
2597                 return -ENODEV;
2598         priv = xpd->priv;
2599         BUG_ON(!priv);
2600         spin_lock_irqsave(&xpd->lock, flags);
2601         len +=
2602             sprintf(buf + len,
2603                     "D-Channel: TX=[%5d] (0x%02X)   RX=[%5d] (0x%02X) ",
2604                     priv->dchan_tx_counter, priv->dchan_tx_sample,
2605                     priv->dchan_rx_counter, priv->dchan_rx_sample);
2606         if (priv->dchan_alive) {
2607                 len +=
2608                     sprintf(buf + len, "(alive %d K-ticks)\n",
2609                             priv->dchan_alive_ticks / 1000);
2610         } else {
2611                 len += sprintf(buf + len, "(dead)\n");
2612         }
2613         spin_unlock_irqrestore(&xpd->lock, flags);
2614         return len;
2615 }
2616
2617 static DEVICE_ATTR(pri_dchan, S_IRUGO, pri_dchan_show, NULL);
2618
2619 static DEVICE_ATTR_READER(pri_clocking_show, dev, buf)
2620 {
2621         xpd_t *xpd;
2622         struct PRI_priv_data *priv;
2623         unsigned long flags;
2624         int len = 0;
2625
2626         BUG_ON(!dev);
2627         xpd = dev_to_xpd(dev);
2628         if (!xpd)
2629                 return -ENODEV;
2630         priv = xpd->priv;
2631         BUG_ON(!priv);
2632         spin_lock_irqsave(&xpd->lock, flags);
2633         len +=
2634             sprintf(buf + len, "%s\n",
2635                     (priv->clock_source) ? "MASTER" : "SLAVE");
2636         spin_unlock_irqrestore(&xpd->lock, flags);
2637         return len;
2638 }
2639
2640 static DEVICE_ATTR(pri_clocking, S_IRUGO, pri_clocking_show, NULL);
2641
2642 static int pri_xpd_probe(struct device *dev)
2643 {
2644         xpd_t *xpd;
2645         int ret = 0;
2646
2647         xpd = dev_to_xpd(dev);
2648         /* Is it our device? */
2649         if (xpd->xpd_type != XPD_TYPE_PRI) {
2650                 XPD_ERR(xpd, "drop suggestion for %s (%d)\n", dev_name(dev),
2651                         xpd->xpd_type);
2652                 return -EINVAL;
2653         }
2654         XPD_DBG(DEVICES, xpd, "SYSFS\n");
2655         ret = device_create_file(dev, &dev_attr_pri_protocol);
2656         if (ret) {
2657                 XPD_ERR(xpd,
2658                         "%s: device_create_file(pri_protocol) failed: %d\n",
2659                         __func__, ret);
2660                 goto fail_pri_protocol;
2661         }
2662         ret = device_create_file(dev, &dev_attr_pri_localloop);
2663         if (ret) {
2664                 XPD_ERR(xpd,
2665                         "%s: device_create_file(pri_localloop) failed: %d\n",
2666                         __func__, ret);
2667                 goto fail_pri_localloop;
2668         }
2669         ret = device_create_file(dev, &dev_attr_pri_layer1);
2670         if (ret) {
2671                 XPD_ERR(xpd, "%s: device_create_file(pri_layer1) failed: %d\n",
2672                         __func__, ret);
2673                 goto fail_pri_layer1;
2674         }
2675         ret = device_create_file(dev, &dev_attr_pri_alarms);
2676         if (ret) {
2677                 XPD_ERR(xpd, "%s: device_create_file(pri_alarms) failed: %d\n",
2678                         __func__, ret);
2679                 goto fail_pri_alarms;
2680         }
2681         ret = device_create_file(dev, &dev_attr_pri_cas);
2682         if (ret) {
2683                 XPD_ERR(xpd, "%s: device_create_file(pri_cas) failed: %d\n",
2684                         __func__, ret);
2685                 goto fail_pri_cas;
2686         }
2687         ret = device_create_file(dev, &dev_attr_pri_dchan);
2688         if (ret) {
2689                 XPD_ERR(xpd, "%s: device_create_file(pri_dchan) failed: %d\n",
2690                         __func__, ret);
2691                 goto fail_pri_dchan;
2692         }
2693         ret = device_create_file(dev, &dev_attr_pri_clocking);
2694         if (ret) {
2695                 XPD_ERR(xpd,
2696                         "%s: device_create_file(pri_clocking) failed: %d\n",
2697                         __func__, ret);
2698                 goto fail_pri_clocking;
2699         }
2700         return 0;
2701 fail_pri_clocking:
2702         device_remove_file(dev, &dev_attr_pri_dchan);
2703 fail_pri_dchan:
2704         device_remove_file(dev, &dev_attr_pri_cas);
2705 fail_pri_cas:
2706         device_remove_file(dev, &dev_attr_pri_alarms);
2707 fail_pri_alarms:
2708         device_remove_file(dev, &dev_attr_pri_layer1);
2709 fail_pri_layer1:
2710         device_remove_file(dev, &dev_attr_pri_localloop);
2711 fail_pri_localloop:
2712         device_remove_file(dev, &dev_attr_pri_protocol);
2713 fail_pri_protocol:
2714         return ret;
2715 }
2716
2717 static int pri_xpd_remove(struct device *dev)
2718 {
2719         xpd_t *xpd;
2720
2721         xpd = dev_to_xpd(dev);
2722         XPD_DBG(DEVICES, xpd, "SYSFS\n");
2723         device_remove_file(dev, &dev_attr_pri_clocking);
2724         device_remove_file(dev, &dev_attr_pri_dchan);
2725         device_remove_file(dev, &dev_attr_pri_cas);
2726         device_remove_file(dev, &dev_attr_pri_alarms);
2727         device_remove_file(dev, &dev_attr_pri_layer1);
2728         device_remove_file(dev, &dev_attr_pri_localloop);
2729         device_remove_file(dev, &dev_attr_pri_protocol);
2730         return 0;
2731 }
2732
2733 static struct xpd_driver pri_driver = {
2734         .xpd_type = XPD_TYPE_PRI,
2735         .driver = {
2736                    .name = "pri",
2737                    .owner = THIS_MODULE,
2738                    .probe = pri_xpd_probe,
2739                    .remove = pri_xpd_remove}
2740 };
2741
2742 static int __init card_pri_startup(void)
2743 {
2744         int ret;
2745
2746         if ((ret = xpd_driver_register(&pri_driver.driver)) < 0)
2747                 return ret;
2748 #ifdef  DAHDI_AUDIO_NOTIFY
2749         INFO("FEATURE: WITH DAHDI_AUDIO_NOTIFY\n");
2750 #else
2751         INFO("FEATURE: WITHOUT DAHDI_AUDIO_NOTIFY\n");
2752 #endif
2753         xproto_register(&PROTO_TABLE(PRI));
2754         return 0;
2755 }
2756
2757 static void __exit card_pri_cleanup(void)
2758 {
2759         DBG(GENERAL, "\n");
2760         xproto_unregister(&PROTO_TABLE(PRI));
2761         xpd_driver_unregister(&pri_driver.driver);
2762 }
2763
2764 MODULE_DESCRIPTION("XPP PRI Card Driver");
2765 MODULE_AUTHOR("Oron Peled <oron@actcom.co.il>");
2766 MODULE_LICENSE("GPL");
2767 MODULE_ALIAS_XPD(XPD_TYPE_PRI);
2768
2769 module_init(card_pri_startup);
2770 module_exit(card_pri_cleanup);