Merge branch 'egalax' into for-linus
[pandora-kernel.git] / drivers / isdn / gigaset / capi.c
1 /*
2  * Kernel CAPI interface for the Gigaset driver
3  *
4  * Copyright (c) 2009 by Tilman Schmidt <tilman@imap.cc>.
5  *
6  * =====================================================================
7  *      This program is free software; you can redistribute it and/or
8  *      modify it under the terms of the GNU General Public License as
9  *      published by the Free Software Foundation; either version 2 of
10  *      the License, or (at your option) any later version.
11  * =====================================================================
12  */
13
14 #include "gigaset.h"
15 #include <linux/proc_fs.h>
16 #include <linux/seq_file.h>
17 #include <linux/isdn/capilli.h>
18 #include <linux/isdn/capicmd.h>
19 #include <linux/isdn/capiutil.h>
20
21 /* missing from kernelcapi.h */
22 #define CapiNcpiNotSupportedByProtocol  0x0001
23 #define CapiFlagsNotSupportedByProtocol 0x0002
24 #define CapiAlertAlreadySent            0x0003
25 #define CapiFacilitySpecificFunctionNotSupported        0x3011
26
27 /* missing from capicmd.h */
28 #define CAPI_CONNECT_IND_BASELEN        (CAPI_MSG_BASELEN+4+2+8*1)
29 #define CAPI_CONNECT_ACTIVE_IND_BASELEN (CAPI_MSG_BASELEN+4+3*1)
30 #define CAPI_CONNECT_B3_IND_BASELEN     (CAPI_MSG_BASELEN+4+1)
31 #define CAPI_CONNECT_B3_ACTIVE_IND_BASELEN      (CAPI_MSG_BASELEN+4+1)
32 #define CAPI_DATA_B3_REQ_LEN64          (CAPI_MSG_BASELEN+4+4+2+2+2+8)
33 #define CAPI_DATA_B3_CONF_LEN           (CAPI_MSG_BASELEN+4+2+2)
34 #define CAPI_DISCONNECT_IND_LEN         (CAPI_MSG_BASELEN+4+2)
35 #define CAPI_DISCONNECT_B3_IND_BASELEN  (CAPI_MSG_BASELEN+4+2+1)
36 #define CAPI_FACILITY_CONF_BASELEN      (CAPI_MSG_BASELEN+4+2+2+1)
37 /* most _CONF messages contain only Controller/PLCI/NCCI and Info parameters */
38 #define CAPI_STDCONF_LEN                (CAPI_MSG_BASELEN+4+2)
39
40 #define CAPI_FACILITY_HANDSET   0x0000
41 #define CAPI_FACILITY_DTMF      0x0001
42 #define CAPI_FACILITY_V42BIS    0x0002
43 #define CAPI_FACILITY_SUPPSVC   0x0003
44 #define CAPI_FACILITY_WAKEUP    0x0004
45 #define CAPI_FACILITY_LI        0x0005
46
47 #define CAPI_SUPPSVC_GETSUPPORTED       0x0000
48
49 /* missing from capiutil.h */
50 #define CAPIMSG_PLCI_PART(m)    CAPIMSG_U8(m, 9)
51 #define CAPIMSG_NCCI_PART(m)    CAPIMSG_U16(m, 10)
52 #define CAPIMSG_HANDLE_REQ(m)   CAPIMSG_U16(m, 18) /* DATA_B3_REQ/_IND only! */
53 #define CAPIMSG_FLAGS(m)        CAPIMSG_U16(m, 20)
54 #define CAPIMSG_SETCONTROLLER(m, contr) capimsg_setu8(m, 8, contr)
55 #define CAPIMSG_SETPLCI_PART(m, plci)   capimsg_setu8(m, 9, plci)
56 #define CAPIMSG_SETNCCI_PART(m, ncci)   capimsg_setu16(m, 10, ncci)
57 #define CAPIMSG_SETFLAGS(m, flags)      capimsg_setu16(m, 20, flags)
58
59 /* parameters with differing location in DATA_B3_CONF/_RESP: */
60 #define CAPIMSG_SETHANDLE_CONF(m, handle)       capimsg_setu16(m, 12, handle)
61 #define CAPIMSG_SETINFO_CONF(m, info)           capimsg_setu16(m, 14, info)
62
63 /* Flags (DATA_B3_REQ/_IND) */
64 #define CAPI_FLAGS_DELIVERY_CONFIRMATION        0x04
65 #define CAPI_FLAGS_RESERVED                     (~0x1f)
66
67 /* buffer sizes */
68 #define MAX_BC_OCTETS 11
69 #define MAX_HLC_OCTETS 3
70 #define MAX_NUMBER_DIGITS 20
71 #define MAX_FMT_IE_LEN 20
72
73 /* values for gigaset_capi_appl.connected */
74 #define APCONN_NONE     0       /* inactive/listening */
75 #define APCONN_SETUP    1       /* connecting */
76 #define APCONN_ACTIVE   2       /* B channel up */
77
78 /* registered application data structure */
79 struct gigaset_capi_appl {
80         struct list_head ctrlist;
81         struct gigaset_capi_appl *bcnext;
82         u16 id;
83         u16 nextMessageNumber;
84         u32 listenInfoMask;
85         u32 listenCIPmask;
86         int connected;
87 };
88
89 /* CAPI specific controller data structure */
90 struct gigaset_capi_ctr {
91         struct capi_ctr ctr;
92         struct list_head appls;
93         struct sk_buff_head sendqueue;
94         atomic_t sendqlen;
95         /* two _cmsg structures possibly used concurrently: */
96         _cmsg hcmsg;    /* for message composition triggered from hardware */
97         _cmsg acmsg;    /* for dissection of messages sent from application */
98         u8 bc_buf[MAX_BC_OCTETS+1];
99         u8 hlc_buf[MAX_HLC_OCTETS+1];
100         u8 cgpty_buf[MAX_NUMBER_DIGITS+3];
101         u8 cdpty_buf[MAX_NUMBER_DIGITS+2];
102 };
103
104 /* CIP Value table (from CAPI 2.0 standard, ch. 6.1) */
105 static struct {
106         u8 *bc;
107         u8 *hlc;
108 } cip2bchlc[] = {
109         [1] = { "8090A3", NULL },
110                 /* Speech (A-law) */
111         [2] = { "8890", NULL },
112                 /* Unrestricted digital information */
113         [3] = { "8990", NULL },
114                 /* Restricted digital information */
115         [4] = { "9090A3", NULL },
116                 /* 3,1 kHz audio (A-law) */
117         [5] = { "9190", NULL },
118                 /* 7 kHz audio */
119         [6] = { "9890", NULL },
120                 /* Video */
121         [7] = { "88C0C6E6", NULL },
122                 /* Packet mode */
123         [8] = { "8890218F", NULL },
124                 /* 56 kbit/s rate adaptation */
125         [9] = { "9190A5", NULL },
126                 /* Unrestricted digital information with tones/announcements */
127         [16] = { "8090A3", "9181" },
128                 /* Telephony */
129         [17] = { "9090A3", "9184" },
130                 /* Group 2/3 facsimile */
131         [18] = { "8890", "91A1" },
132                 /* Group 4 facsimile Class 1 */
133         [19] = { "8890", "91A4" },
134                 /* Teletex service basic and mixed mode
135                    and Group 4 facsimile service Classes II and III */
136         [20] = { "8890", "91A8" },
137                 /* Teletex service basic and processable mode */
138         [21] = { "8890", "91B1" },
139                 /* Teletex service basic mode */
140         [22] = { "8890", "91B2" },
141                 /* International interworking for Videotex */
142         [23] = { "8890", "91B5" },
143                 /* Telex */
144         [24] = { "8890", "91B8" },
145                 /* Message Handling Systems in accordance with X.400 */
146         [25] = { "8890", "91C1" },
147                 /* OSI application in accordance with X.200 */
148         [26] = { "9190A5", "9181" },
149                 /* 7 kHz telephony */
150         [27] = { "9190A5", "916001" },
151                 /* Video telephony, first connection */
152         [28] = { "8890", "916002" },
153                 /* Video telephony, second connection */
154 };
155
156 /*
157  * helper functions
158  * ================
159  */
160
161 /*
162  * emit unsupported parameter warning
163  */
164 static inline void ignore_cstruct_param(struct cardstate *cs, _cstruct param,
165                                        char *msgname, char *paramname)
166 {
167         if (param && *param)
168                 dev_warn(cs->dev, "%s: ignoring unsupported parameter: %s\n",
169                          msgname, paramname);
170 }
171
172 /*
173  * convert hex to binary
174  */
175 static inline u8 hex2bin(char c)
176 {
177         int result = c & 0x0f;
178         if (c & 0x40)
179                 result += 9;
180         return result;
181 }
182
183 /*
184  * convert an IE from Gigaset hex string to ETSI binary representation
185  * including length byte
186  * return value: result length, -1 on error
187  */
188 static int encode_ie(char *in, u8 *out, int maxlen)
189 {
190         int l = 0;
191         while (*in) {
192                 if (!isxdigit(in[0]) || !isxdigit(in[1]) || l >= maxlen)
193                         return -1;
194                 out[++l] = (hex2bin(in[0]) << 4) + hex2bin(in[1]);
195                 in += 2;
196         }
197         out[0] = l;
198         return l;
199 }
200
201 /*
202  * convert an IE from ETSI binary representation including length byte
203  * to Gigaset hex string
204  */
205 static void decode_ie(u8 *in, char *out)
206 {
207         int i = *in;
208         while (i-- > 0) {
209                 /* ToDo: conversion to upper case necessary? */
210                 *out++ = toupper(hex_asc_hi(*++in));
211                 *out++ = toupper(hex_asc_lo(*in));
212         }
213 }
214
215 /*
216  * retrieve application data structure for an application ID
217  */
218 static inline struct gigaset_capi_appl *
219 get_appl(struct gigaset_capi_ctr *iif, u16 appl)
220 {
221         struct gigaset_capi_appl *ap;
222
223         list_for_each_entry(ap, &iif->appls, ctrlist)
224                 if (ap->id == appl)
225                         return ap;
226         return NULL;
227 }
228
229 /*
230  * dump CAPI message to kernel messages for debugging
231  */
232 static inline void dump_cmsg(enum debuglevel level, const char *tag, _cmsg *p)
233 {
234 #ifdef CONFIG_GIGASET_DEBUG
235         _cdebbuf *cdb;
236
237         if (!(gigaset_debuglevel & level))
238                 return;
239
240         cdb = capi_cmsg2str(p);
241         if (cdb) {
242                 gig_dbg(level, "%s: [%d] %s", tag, p->ApplId, cdb->buf);
243                 cdebbuf_free(cdb);
244         } else {
245                 gig_dbg(level, "%s: [%d] %s", tag, p->ApplId,
246                         capi_cmd2str(p->Command, p->Subcommand));
247         }
248 #endif
249 }
250
251 static inline void dump_rawmsg(enum debuglevel level, const char *tag,
252                                unsigned char *data)
253 {
254 #ifdef CONFIG_GIGASET_DEBUG
255         char *dbgline;
256         int i, l;
257
258         if (!(gigaset_debuglevel & level))
259                 return;
260
261         l = CAPIMSG_LEN(data);
262         if (l < 12) {
263                 gig_dbg(level, "%s: ??? LEN=%04d", tag, l);
264                 return;
265         }
266         gig_dbg(level, "%s: 0x%02x:0x%02x: ID=%03d #0x%04x LEN=%04d NCCI=0x%x",
267                 tag, CAPIMSG_COMMAND(data), CAPIMSG_SUBCOMMAND(data),
268                 CAPIMSG_APPID(data), CAPIMSG_MSGID(data), l,
269                 CAPIMSG_CONTROL(data));
270         l -= 12;
271         dbgline = kmalloc(3*l, GFP_ATOMIC);
272         if (!dbgline)
273                 return;
274         for (i = 0; i < l; i++) {
275                 dbgline[3*i] = hex_asc_hi(data[12+i]);
276                 dbgline[3*i+1] = hex_asc_lo(data[12+i]);
277                 dbgline[3*i+2] = ' ';
278         }
279         dbgline[3*l-1] = '\0';
280         gig_dbg(level, "  %s", dbgline);
281         kfree(dbgline);
282         if (CAPIMSG_COMMAND(data) == CAPI_DATA_B3 &&
283             (CAPIMSG_SUBCOMMAND(data) == CAPI_REQ ||
284              CAPIMSG_SUBCOMMAND(data) == CAPI_IND) &&
285             CAPIMSG_DATALEN(data) > 0) {
286                 l = CAPIMSG_DATALEN(data);
287                 dbgline = kmalloc(3*l, GFP_ATOMIC);
288                 if (!dbgline)
289                         return;
290                 data += CAPIMSG_LEN(data);
291                 for (i = 0; i < l; i++) {
292                         dbgline[3*i] = hex_asc_hi(data[i]);
293                         dbgline[3*i+1] = hex_asc_lo(data[i]);
294                         dbgline[3*i+2] = ' ';
295                 }
296                 dbgline[3*l-1] = '\0';
297                 gig_dbg(level, "  %s", dbgline);
298                 kfree(dbgline);
299         }
300 #endif
301 }
302
303 /*
304  * format CAPI IE as string
305  */
306
307 static const char *format_ie(const char *ie)
308 {
309         static char result[3*MAX_FMT_IE_LEN];
310         int len, count;
311         char *pout = result;
312
313         if (!ie)
314                 return "NULL";
315
316         count = len = ie[0];
317         if (count > MAX_FMT_IE_LEN)
318                 count = MAX_FMT_IE_LEN-1;
319         while (count--) {
320                 *pout++ = hex_asc_hi(*++ie);
321                 *pout++ = hex_asc_lo(*ie);
322                 *pout++ = ' ';
323         }
324         if (len > MAX_FMT_IE_LEN) {
325                 *pout++ = '.';
326                 *pout++ = '.';
327                 *pout++ = '.';
328         }
329         *--pout = 0;
330         return result;
331 }
332
333
334 /*
335  * driver interface functions
336  * ==========================
337  */
338
339 /**
340  * gigaset_skb_sent() - acknowledge transmission of outgoing skb
341  * @bcs:        B channel descriptor structure.
342  * @skb:        sent data.
343  *
344  * Called by hardware module {bas,ser,usb}_gigaset when the data in a
345  * skb has been successfully sent, for signalling completion to the LL.
346  */
347 void gigaset_skb_sent(struct bc_state *bcs, struct sk_buff *dskb)
348 {
349         struct cardstate *cs = bcs->cs;
350         struct gigaset_capi_ctr *iif = cs->iif;
351         struct gigaset_capi_appl *ap = bcs->ap;
352         unsigned char *req = skb_mac_header(dskb);
353         struct sk_buff *cskb;
354         u16 flags;
355
356         /* update statistics */
357         ++bcs->trans_up;
358
359         if (!ap) {
360                 dev_err(cs->dev, "%s: no application\n", __func__);
361                 return;
362         }
363
364         /* don't send further B3 messages if disconnected */
365         if (ap->connected < APCONN_ACTIVE) {
366                 gig_dbg(DEBUG_LLDATA, "disconnected, discarding ack");
367                 return;
368         }
369
370         /* ToDo: honor unset "delivery confirmation" bit */
371         flags = CAPIMSG_FLAGS(req);
372
373         /* build DATA_B3_CONF message */
374         cskb = alloc_skb(CAPI_DATA_B3_CONF_LEN, GFP_ATOMIC);
375         if (!cskb) {
376                 dev_err(cs->dev, "%s: out of memory\n", __func__);
377                 return;
378         }
379         /* frequent message, avoid _cmsg overhead */
380         CAPIMSG_SETLEN(cskb->data, CAPI_DATA_B3_CONF_LEN);
381         CAPIMSG_SETAPPID(cskb->data, ap->id);
382         CAPIMSG_SETCOMMAND(cskb->data, CAPI_DATA_B3);
383         CAPIMSG_SETSUBCOMMAND(cskb->data,  CAPI_CONF);
384         CAPIMSG_SETMSGID(cskb->data, CAPIMSG_MSGID(req));
385         CAPIMSG_SETCONTROLLER(cskb->data, iif->ctr.cnr);
386         CAPIMSG_SETPLCI_PART(cskb->data, bcs->channel + 1);
387         CAPIMSG_SETNCCI_PART(cskb->data, 1);
388         CAPIMSG_SETHANDLE_CONF(cskb->data, CAPIMSG_HANDLE_REQ(req));
389         if (flags & ~CAPI_FLAGS_DELIVERY_CONFIRMATION)
390                 CAPIMSG_SETINFO_CONF(cskb->data,
391                                      CapiFlagsNotSupportedByProtocol);
392         else
393                 CAPIMSG_SETINFO_CONF(cskb->data, CAPI_NOERROR);
394
395         /* emit message */
396         dump_rawmsg(DEBUG_LLDATA, "DATA_B3_CONF", cskb->data);
397         capi_ctr_handle_message(&iif->ctr, ap->id, cskb);
398 }
399 EXPORT_SYMBOL_GPL(gigaset_skb_sent);
400
401 /**
402  * gigaset_skb_rcvd() - pass received skb to LL
403  * @bcs:        B channel descriptor structure.
404  * @skb:        received data.
405  *
406  * Called by hardware module {bas,ser,usb}_gigaset when user data has
407  * been successfully received, for passing to the LL.
408  * Warning: skb must not be accessed anymore!
409  */
410 void gigaset_skb_rcvd(struct bc_state *bcs, struct sk_buff *skb)
411 {
412         struct cardstate *cs = bcs->cs;
413         struct gigaset_capi_ctr *iif = cs->iif;
414         struct gigaset_capi_appl *ap = bcs->ap;
415         int len = skb->len;
416
417         /* update statistics */
418         bcs->trans_down++;
419
420         if (!ap) {
421                 dev_err(cs->dev, "%s: no application\n", __func__);
422                 return;
423         }
424
425         /* don't send further B3 messages if disconnected */
426         if (ap->connected < APCONN_ACTIVE) {
427                 gig_dbg(DEBUG_LLDATA, "disconnected, discarding data");
428                 dev_kfree_skb_any(skb);
429                 return;
430         }
431
432         /*
433          * prepend DATA_B3_IND message to payload
434          * Parameters: NCCI = 1, all others 0/unused
435          * frequent message, avoid _cmsg overhead
436          */
437         skb_push(skb, CAPI_DATA_B3_REQ_LEN);
438         CAPIMSG_SETLEN(skb->data, CAPI_DATA_B3_REQ_LEN);
439         CAPIMSG_SETAPPID(skb->data, ap->id);
440         CAPIMSG_SETCOMMAND(skb->data, CAPI_DATA_B3);
441         CAPIMSG_SETSUBCOMMAND(skb->data,  CAPI_IND);
442         CAPIMSG_SETMSGID(skb->data, ap->nextMessageNumber++);
443         CAPIMSG_SETCONTROLLER(skb->data, iif->ctr.cnr);
444         CAPIMSG_SETPLCI_PART(skb->data, bcs->channel + 1);
445         CAPIMSG_SETNCCI_PART(skb->data, 1);
446         /* Data parameter not used */
447         CAPIMSG_SETDATALEN(skb->data, len);
448         /* Data handle parameter not used */
449         CAPIMSG_SETFLAGS(skb->data, 0);
450         /* Data64 parameter not present */
451
452         /* emit message */
453         dump_rawmsg(DEBUG_LLDATA, "DATA_B3_IND", skb->data);
454         capi_ctr_handle_message(&iif->ctr, ap->id, skb);
455 }
456 EXPORT_SYMBOL_GPL(gigaset_skb_rcvd);
457
458 /**
459  * gigaset_isdn_rcv_err() - signal receive error
460  * @bcs:        B channel descriptor structure.
461  *
462  * Called by hardware module {bas,ser,usb}_gigaset when a receive error
463  * has occurred, for signalling to the LL.
464  */
465 void gigaset_isdn_rcv_err(struct bc_state *bcs)
466 {
467         /* if currently ignoring packets, just count down */
468         if (bcs->ignore) {
469                 bcs->ignore--;
470                 return;
471         }
472
473         /* update statistics */
474         bcs->corrupted++;
475
476         /* ToDo: signal error -> LL */
477 }
478 EXPORT_SYMBOL_GPL(gigaset_isdn_rcv_err);
479
480 /**
481  * gigaset_isdn_icall() - signal incoming call
482  * @at_state:   connection state structure.
483  *
484  * Called by main module at tasklet level to notify the LL that an incoming
485  * call has been received. @at_state contains the parameters of the call.
486  *
487  * Return value: call disposition (ICALL_*)
488  */
489 int gigaset_isdn_icall(struct at_state_t *at_state)
490 {
491         struct cardstate *cs = at_state->cs;
492         struct bc_state *bcs = at_state->bcs;
493         struct gigaset_capi_ctr *iif = cs->iif;
494         struct gigaset_capi_appl *ap;
495         u32 actCIPmask;
496         struct sk_buff *skb;
497         unsigned int msgsize;
498         int i;
499
500         /*
501          * ToDo: signal calls without a free B channel, too
502          * (requires a u8 handle for the at_state structure that can
503          * be stored in the PLCI and used in the CONNECT_RESP message
504          * handler to retrieve it)
505          */
506         if (!bcs)
507                 return ICALL_IGNORE;
508
509         /* prepare CONNECT_IND message, using B channel number as PLCI */
510         capi_cmsg_header(&iif->hcmsg, 0, CAPI_CONNECT, CAPI_IND, 0,
511                          iif->ctr.cnr | ((bcs->channel + 1) << 8));
512
513         /* minimum size, all structs empty */
514         msgsize = CAPI_CONNECT_IND_BASELEN;
515
516         /* Bearer Capability (mandatory) */
517         if (at_state->str_var[STR_ZBC]) {
518                 /* pass on BC from Gigaset */
519                 if (encode_ie(at_state->str_var[STR_ZBC], iif->bc_buf,
520                               MAX_BC_OCTETS) < 0) {
521                         dev_warn(cs->dev, "RING ignored - bad BC %s\n",
522                                  at_state->str_var[STR_ZBC]);
523                         return ICALL_IGNORE;
524                 }
525
526                 /* look up corresponding CIP value */
527                 iif->hcmsg.CIPValue = 0;        /* default if nothing found */
528                 for (i = 0; i < ARRAY_SIZE(cip2bchlc); i++)
529                         if (cip2bchlc[i].bc != NULL &&
530                             cip2bchlc[i].hlc == NULL &&
531                             !strcmp(cip2bchlc[i].bc,
532                                     at_state->str_var[STR_ZBC])) {
533                                 iif->hcmsg.CIPValue = i;
534                                 break;
535                         }
536         } else {
537                 /* no BC (internal call): assume CIP 1 (speech, A-law) */
538                 iif->hcmsg.CIPValue = 1;
539                 encode_ie(cip2bchlc[1].bc, iif->bc_buf, MAX_BC_OCTETS);
540         }
541         iif->hcmsg.BC = iif->bc_buf;
542         msgsize += iif->hcmsg.BC[0];
543
544         /* High Layer Compatibility (optional) */
545         if (at_state->str_var[STR_ZHLC]) {
546                 /* pass on HLC from Gigaset */
547                 if (encode_ie(at_state->str_var[STR_ZHLC], iif->hlc_buf,
548                               MAX_HLC_OCTETS) < 0) {
549                         dev_warn(cs->dev, "RING ignored - bad HLC %s\n",
550                                  at_state->str_var[STR_ZHLC]);
551                         return ICALL_IGNORE;
552                 }
553                 iif->hcmsg.HLC = iif->hlc_buf;
554                 msgsize += iif->hcmsg.HLC[0];
555
556                 /* look up corresponding CIP value */
557                 /* keep BC based CIP value if none found */
558                 if (at_state->str_var[STR_ZBC])
559                         for (i = 0; i < ARRAY_SIZE(cip2bchlc); i++)
560                                 if (cip2bchlc[i].hlc != NULL &&
561                                     !strcmp(cip2bchlc[i].hlc,
562                                             at_state->str_var[STR_ZHLC]) &&
563                                     !strcmp(cip2bchlc[i].bc,
564                                             at_state->str_var[STR_ZBC])) {
565                                         iif->hcmsg.CIPValue = i;
566                                         break;
567                                 }
568         }
569
570         /* Called Party Number (optional) */
571         if (at_state->str_var[STR_ZCPN]) {
572                 i = strlen(at_state->str_var[STR_ZCPN]);
573                 if (i > MAX_NUMBER_DIGITS) {
574                         dev_warn(cs->dev, "RING ignored - bad number %s\n",
575                                  at_state->str_var[STR_ZBC]);
576                         return ICALL_IGNORE;
577                 }
578                 iif->cdpty_buf[0] = i + 1;
579                 iif->cdpty_buf[1] = 0x80; /* type / numbering plan unknown */
580                 memcpy(iif->cdpty_buf+2, at_state->str_var[STR_ZCPN], i);
581                 iif->hcmsg.CalledPartyNumber = iif->cdpty_buf;
582                 msgsize += iif->hcmsg.CalledPartyNumber[0];
583         }
584
585         /* Calling Party Number (optional) */
586         if (at_state->str_var[STR_NMBR]) {
587                 i = strlen(at_state->str_var[STR_NMBR]);
588                 if (i > MAX_NUMBER_DIGITS) {
589                         dev_warn(cs->dev, "RING ignored - bad number %s\n",
590                                  at_state->str_var[STR_ZBC]);
591                         return ICALL_IGNORE;
592                 }
593                 iif->cgpty_buf[0] = i + 2;
594                 iif->cgpty_buf[1] = 0x00; /* type / numbering plan unknown */
595                 iif->cgpty_buf[2] = 0x80; /* pres. allowed, not screened */
596                 memcpy(iif->cgpty_buf+3, at_state->str_var[STR_NMBR], i);
597                 iif->hcmsg.CallingPartyNumber = iif->cgpty_buf;
598                 msgsize += iif->hcmsg.CallingPartyNumber[0];
599         }
600
601         /* remaining parameters (not supported, always left NULL):
602          * - CalledPartySubaddress
603          * - CallingPartySubaddress
604          * - AdditionalInfo
605          *   - BChannelinformation
606          *   - Keypadfacility
607          *   - Useruserdata
608          *   - Facilitydataarray
609          */
610
611         gig_dbg(DEBUG_CMD, "icall: PLCI %x CIP %d BC %s",
612                 iif->hcmsg.adr.adrPLCI, iif->hcmsg.CIPValue,
613                 format_ie(iif->hcmsg.BC));
614         gig_dbg(DEBUG_CMD, "icall: HLC %s",
615                 format_ie(iif->hcmsg.HLC));
616         gig_dbg(DEBUG_CMD, "icall: CgPty %s",
617                 format_ie(iif->hcmsg.CallingPartyNumber));
618         gig_dbg(DEBUG_CMD, "icall: CdPty %s",
619                 format_ie(iif->hcmsg.CalledPartyNumber));
620
621         /* scan application list for matching listeners */
622         bcs->ap = NULL;
623         actCIPmask = 1 | (1 << iif->hcmsg.CIPValue);
624         list_for_each_entry(ap, &iif->appls, ctrlist)
625                 if (actCIPmask & ap->listenCIPmask) {
626                         /* build CONNECT_IND message for this application */
627                         iif->hcmsg.ApplId = ap->id;
628                         iif->hcmsg.Messagenumber = ap->nextMessageNumber++;
629
630                         skb = alloc_skb(msgsize, GFP_ATOMIC);
631                         if (!skb) {
632                                 dev_err(cs->dev, "%s: out of memory\n",
633                                         __func__);
634                                 break;
635                         }
636                         capi_cmsg2message(&iif->hcmsg, __skb_put(skb, msgsize));
637                         dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
638
639                         /* add to listeners on this B channel, update state */
640                         ap->bcnext = bcs->ap;
641                         bcs->ap = ap;
642                         bcs->chstate |= CHS_NOTIFY_LL;
643                         ap->connected = APCONN_SETUP;
644
645                         /* emit message */
646                         capi_ctr_handle_message(&iif->ctr, ap->id, skb);
647                 }
648
649         /*
650          * Return "accept" if any listeners.
651          * Gigaset will send ALERTING.
652          * There doesn't seem to be a way to avoid this.
653          */
654         return bcs->ap ? ICALL_ACCEPT : ICALL_IGNORE;
655 }
656
657 /*
658  * send a DISCONNECT_IND message to an application
659  * does not sleep, clobbers the controller's hcmsg structure
660  */
661 static void send_disconnect_ind(struct bc_state *bcs,
662                                 struct gigaset_capi_appl *ap, u16 reason)
663 {
664         struct cardstate *cs = bcs->cs;
665         struct gigaset_capi_ctr *iif = cs->iif;
666         struct sk_buff *skb;
667
668         if (ap->connected == APCONN_NONE)
669                 return;
670
671         capi_cmsg_header(&iif->hcmsg, ap->id, CAPI_DISCONNECT, CAPI_IND,
672                          ap->nextMessageNumber++,
673                          iif->ctr.cnr | ((bcs->channel + 1) << 8));
674         iif->hcmsg.Reason = reason;
675         skb = alloc_skb(CAPI_DISCONNECT_IND_LEN, GFP_ATOMIC);
676         if (!skb) {
677                 dev_err(cs->dev, "%s: out of memory\n", __func__);
678                 return;
679         }
680         capi_cmsg2message(&iif->hcmsg, __skb_put(skb, CAPI_DISCONNECT_IND_LEN));
681         dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
682         ap->connected = APCONN_NONE;
683         capi_ctr_handle_message(&iif->ctr, ap->id, skb);
684 }
685
686 /*
687  * send a DISCONNECT_B3_IND message to an application
688  * Parameters: NCCI = 1, NCPI empty, Reason_B3 = 0
689  * does not sleep, clobbers the controller's hcmsg structure
690  */
691 static void send_disconnect_b3_ind(struct bc_state *bcs,
692                                    struct gigaset_capi_appl *ap)
693 {
694         struct cardstate *cs = bcs->cs;
695         struct gigaset_capi_ctr *iif = cs->iif;
696         struct sk_buff *skb;
697
698         /* nothing to do if no logical connection active */
699         if (ap->connected < APCONN_ACTIVE)
700                 return;
701         ap->connected = APCONN_SETUP;
702
703         capi_cmsg_header(&iif->hcmsg, ap->id, CAPI_DISCONNECT_B3, CAPI_IND,
704                          ap->nextMessageNumber++,
705                          iif->ctr.cnr | ((bcs->channel + 1) << 8) | (1 << 16));
706         skb = alloc_skb(CAPI_DISCONNECT_B3_IND_BASELEN, GFP_ATOMIC);
707         if (!skb) {
708                 dev_err(cs->dev, "%s: out of memory\n", __func__);
709                 return;
710         }
711         capi_cmsg2message(&iif->hcmsg,
712                           __skb_put(skb, CAPI_DISCONNECT_B3_IND_BASELEN));
713         dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
714         capi_ctr_handle_message(&iif->ctr, ap->id, skb);
715 }
716
717 /**
718  * gigaset_isdn_connD() - signal D channel connect
719  * @bcs:        B channel descriptor structure.
720  *
721  * Called by main module at tasklet level to notify the LL that the D channel
722  * connection has been established.
723  */
724 void gigaset_isdn_connD(struct bc_state *bcs)
725 {
726         struct cardstate *cs = bcs->cs;
727         struct gigaset_capi_ctr *iif = cs->iif;
728         struct gigaset_capi_appl *ap = bcs->ap;
729         struct sk_buff *skb;
730         unsigned int msgsize;
731
732         if (!ap) {
733                 dev_err(cs->dev, "%s: no application\n", __func__);
734                 return;
735         }
736         while (ap->bcnext) {
737                 /* this should never happen */
738                 dev_warn(cs->dev, "%s: dropping extra application %u\n",
739                          __func__, ap->bcnext->id);
740                 send_disconnect_ind(bcs, ap->bcnext,
741                                     CapiCallGivenToOtherApplication);
742                 ap->bcnext = ap->bcnext->bcnext;
743         }
744         if (ap->connected == APCONN_NONE) {
745                 dev_warn(cs->dev, "%s: application %u not connected\n",
746                          __func__, ap->id);
747                 return;
748         }
749
750         /* prepare CONNECT_ACTIVE_IND message
751          * Note: LLC not supported by device
752          */
753         capi_cmsg_header(&iif->hcmsg, ap->id, CAPI_CONNECT_ACTIVE, CAPI_IND,
754                          ap->nextMessageNumber++,
755                          iif->ctr.cnr | ((bcs->channel + 1) << 8));
756
757         /* minimum size, all structs empty */
758         msgsize = CAPI_CONNECT_ACTIVE_IND_BASELEN;
759
760         /* ToDo: set parameter: Connected number
761          * (requires ev-layer state machine extension to collect
762          * ZCON device reply)
763          */
764
765         /* build and emit CONNECT_ACTIVE_IND message */
766         skb = alloc_skb(msgsize, GFP_ATOMIC);
767         if (!skb) {
768                 dev_err(cs->dev, "%s: out of memory\n", __func__);
769                 return;
770         }
771         capi_cmsg2message(&iif->hcmsg, __skb_put(skb, msgsize));
772         dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
773         capi_ctr_handle_message(&iif->ctr, ap->id, skb);
774 }
775
776 /**
777  * gigaset_isdn_hupD() - signal D channel hangup
778  * @bcs:        B channel descriptor structure.
779  *
780  * Called by main module at tasklet level to notify the LL that the D channel
781  * connection has been shut down.
782  */
783 void gigaset_isdn_hupD(struct bc_state *bcs)
784 {
785         struct gigaset_capi_appl *ap;
786
787         /*
788          * ToDo: pass on reason code reported by device
789          * (requires ev-layer state machine extension to collect
790          * ZCAU device reply)
791          */
792         for (ap = bcs->ap; ap != NULL; ap = ap->bcnext) {
793                 send_disconnect_b3_ind(bcs, ap);
794                 send_disconnect_ind(bcs, ap, 0);
795         }
796         bcs->ap = NULL;
797 }
798
799 /**
800  * gigaset_isdn_connB() - signal B channel connect
801  * @bcs:        B channel descriptor structure.
802  *
803  * Called by main module at tasklet level to notify the LL that the B channel
804  * connection has been established.
805  */
806 void gigaset_isdn_connB(struct bc_state *bcs)
807 {
808         struct cardstate *cs = bcs->cs;
809         struct gigaset_capi_ctr *iif = cs->iif;
810         struct gigaset_capi_appl *ap = bcs->ap;
811         struct sk_buff *skb;
812         unsigned int msgsize;
813         u8 command;
814
815         if (!ap) {
816                 dev_err(cs->dev, "%s: no application\n", __func__);
817                 return;
818         }
819         while (ap->bcnext) {
820                 /* this should never happen */
821                 dev_warn(cs->dev, "%s: dropping extra application %u\n",
822                          __func__, ap->bcnext->id);
823                 send_disconnect_ind(bcs, ap->bcnext,
824                                     CapiCallGivenToOtherApplication);
825                 ap->bcnext = ap->bcnext->bcnext;
826         }
827         if (!ap->connected) {
828                 dev_warn(cs->dev, "%s: application %u not connected\n",
829                          __func__, ap->id);
830                 return;
831         }
832
833         /*
834          * emit CONNECT_B3_ACTIVE_IND if we already got CONNECT_B3_REQ;
835          * otherwise we have to emit CONNECT_B3_IND first, and follow up with
836          * CONNECT_B3_ACTIVE_IND in reply to CONNECT_B3_RESP
837          * Parameters in both cases always: NCCI = 1, NCPI empty
838          */
839         if (ap->connected >= APCONN_ACTIVE) {
840                 command = CAPI_CONNECT_B3_ACTIVE;
841                 msgsize = CAPI_CONNECT_B3_ACTIVE_IND_BASELEN;
842         } else {
843                 command = CAPI_CONNECT_B3;
844                 msgsize = CAPI_CONNECT_B3_IND_BASELEN;
845         }
846         capi_cmsg_header(&iif->hcmsg, ap->id, command, CAPI_IND,
847                          ap->nextMessageNumber++,
848                          iif->ctr.cnr | ((bcs->channel + 1) << 8) | (1 << 16));
849         skb = alloc_skb(msgsize, GFP_ATOMIC);
850         if (!skb) {
851                 dev_err(cs->dev, "%s: out of memory\n", __func__);
852                 return;
853         }
854         capi_cmsg2message(&iif->hcmsg, __skb_put(skb, msgsize));
855         dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
856         ap->connected = APCONN_ACTIVE;
857         capi_ctr_handle_message(&iif->ctr, ap->id, skb);
858 }
859
860 /**
861  * gigaset_isdn_hupB() - signal B channel hangup
862  * @bcs:        B channel descriptor structure.
863  *
864  * Called by main module to notify the LL that the B channel connection has
865  * been shut down.
866  */
867 void gigaset_isdn_hupB(struct bc_state *bcs)
868 {
869         struct cardstate *cs = bcs->cs;
870         struct gigaset_capi_appl *ap = bcs->ap;
871
872         /* ToDo: assure order of DISCONNECT_B3_IND and DISCONNECT_IND ? */
873
874         if (!ap) {
875                 dev_err(cs->dev, "%s: no application\n", __func__);
876                 return;
877         }
878
879         send_disconnect_b3_ind(bcs, ap);
880 }
881
882 /**
883  * gigaset_isdn_start() - signal device availability
884  * @cs:         device descriptor structure.
885  *
886  * Called by main module to notify the LL that the device is available for
887  * use.
888  */
889 void gigaset_isdn_start(struct cardstate *cs)
890 {
891         struct gigaset_capi_ctr *iif = cs->iif;
892
893         /* fill profile data: manufacturer name */
894         strcpy(iif->ctr.manu, "Siemens");
895         /* CAPI and device version */
896         iif->ctr.version.majorversion = 2;              /* CAPI 2.0 */
897         iif->ctr.version.minorversion = 0;
898         /* ToDo: check/assert cs->gotfwver? */
899         iif->ctr.version.majormanuversion = cs->fwver[0];
900         iif->ctr.version.minormanuversion = cs->fwver[1];
901         /* number of B channels supported */
902         iif->ctr.profile.nbchannel = cs->channels;
903         /* global options: internal controller, supplementary services */
904         iif->ctr.profile.goptions = 0x11;
905         /* B1 protocols: 64 kbit/s HDLC or transparent */
906         iif->ctr.profile.support1 =  0x03;
907         /* B2 protocols: transparent only */
908         /* ToDo: X.75 SLP ? */
909         iif->ctr.profile.support2 =  0x02;
910         /* B3 protocols: transparent only */
911         iif->ctr.profile.support3 =  0x01;
912         /* no serial number */
913         strcpy(iif->ctr.serial, "0");
914         capi_ctr_ready(&iif->ctr);
915 }
916
917 /**
918  * gigaset_isdn_stop() - signal device unavailability
919  * @cs:         device descriptor structure.
920  *
921  * Called by main module to notify the LL that the device is no longer
922  * available for use.
923  */
924 void gigaset_isdn_stop(struct cardstate *cs)
925 {
926         struct gigaset_capi_ctr *iif = cs->iif;
927         capi_ctr_down(&iif->ctr);
928 }
929
930 /*
931  * kernel CAPI callback methods
932  * ============================
933  */
934
935 /*
936  * load firmware
937  */
938 static int gigaset_load_firmware(struct capi_ctr *ctr, capiloaddata *data)
939 {
940         struct cardstate *cs = ctr->driverdata;
941
942         /* AVM specific operation, not needed for Gigaset -- ignore */
943         dev_notice(cs->dev, "load_firmware ignored\n");
944
945         return 0;
946 }
947
948 /*
949  * reset (deactivate) controller
950  */
951 static void gigaset_reset_ctr(struct capi_ctr *ctr)
952 {
953         struct cardstate *cs = ctr->driverdata;
954
955         /* AVM specific operation, not needed for Gigaset -- ignore */
956         dev_notice(cs->dev, "reset_ctr ignored\n");
957 }
958
959 /*
960  * register CAPI application
961  */
962 static void gigaset_register_appl(struct capi_ctr *ctr, u16 appl,
963                            capi_register_params *rp)
964 {
965         struct gigaset_capi_ctr *iif
966                 = container_of(ctr, struct gigaset_capi_ctr, ctr);
967         struct cardstate *cs = ctr->driverdata;
968         struct gigaset_capi_appl *ap;
969
970         list_for_each_entry(ap, &iif->appls, ctrlist)
971                 if (ap->id == appl) {
972                         dev_notice(cs->dev,
973                                    "application %u already registered\n", appl);
974                         return;
975                 }
976
977         ap = kzalloc(sizeof(*ap), GFP_KERNEL);
978         if (!ap) {
979                 dev_err(cs->dev, "%s: out of memory\n", __func__);
980                 return;
981         }
982         ap->id = appl;
983
984         list_add(&ap->ctrlist, &iif->appls);
985 }
986
987 /*
988  * release CAPI application
989  */
990 static void gigaset_release_appl(struct capi_ctr *ctr, u16 appl)
991 {
992         struct gigaset_capi_ctr *iif
993                 = container_of(ctr, struct gigaset_capi_ctr, ctr);
994         struct cardstate *cs = iif->ctr.driverdata;
995         struct gigaset_capi_appl *ap, *tmp;
996
997         list_for_each_entry_safe(ap, tmp, &iif->appls, ctrlist)
998                 if (ap->id == appl) {
999                         if (ap->connected != APCONN_NONE) {
1000                                 dev_err(cs->dev,
1001                                         "%s: application %u still connected\n",
1002                                         __func__, ap->id);
1003                                 /* ToDo: clear active connection */
1004                         }
1005                         list_del(&ap->ctrlist);
1006                         kfree(ap);
1007                 }
1008
1009 }
1010
1011 /*
1012  * =====================================================================
1013  * outgoing CAPI message handler
1014  * =====================================================================
1015  */
1016
1017 /*
1018  * helper function: emit reply message with given Info value
1019  */
1020 static void send_conf(struct gigaset_capi_ctr *iif,
1021                       struct gigaset_capi_appl *ap,
1022                       struct sk_buff *skb,
1023                       u16 info)
1024 {
1025         /*
1026          * _CONF replies always only have NCCI and Info parameters
1027          * so they'll fit into the _REQ message skb
1028          */
1029         capi_cmsg_answer(&iif->acmsg);
1030         iif->acmsg.Info = info;
1031         capi_cmsg2message(&iif->acmsg, skb->data);
1032         __skb_trim(skb, CAPI_STDCONF_LEN);
1033         dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
1034         capi_ctr_handle_message(&iif->ctr, ap->id, skb);
1035 }
1036
1037 /*
1038  * process FACILITY_REQ message
1039  */
1040 static void do_facility_req(struct gigaset_capi_ctr *iif,
1041                             struct gigaset_capi_appl *ap,
1042                             struct sk_buff *skb)
1043 {
1044         struct cardstate *cs = iif->ctr.driverdata;
1045         _cmsg *cmsg = &iif->acmsg;
1046         struct sk_buff *cskb;
1047         u8 *pparam;
1048         unsigned int msgsize = CAPI_FACILITY_CONF_BASELEN;
1049         u16 function, info;
1050         static u8 confparam[10];        /* max. 9 octets + length byte */
1051
1052         /* decode message */
1053         capi_message2cmsg(cmsg, skb->data);
1054         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1055
1056         /*
1057          * Facility Request Parameter is not decoded by capi_message2cmsg()
1058          * encoding depends on Facility Selector
1059          */
1060         switch (cmsg->FacilitySelector) {
1061         case CAPI_FACILITY_DTMF:        /* ToDo */
1062                 info = CapiFacilityNotSupported;
1063                 confparam[0] = 2;       /* length */
1064                 /* DTMF information: Unknown DTMF request */
1065                 capimsg_setu16(confparam, 1, 2);
1066                 break;
1067
1068         case CAPI_FACILITY_V42BIS:      /* not supported */
1069                 info = CapiFacilityNotSupported;
1070                 confparam[0] = 2;       /* length */
1071                 /* V.42 bis information: not available */
1072                 capimsg_setu16(confparam, 1, 1);
1073                 break;
1074
1075         case CAPI_FACILITY_SUPPSVC:
1076                 /* decode Function parameter */
1077                 pparam = cmsg->FacilityRequestParameter;
1078                 if (pparam == NULL || *pparam < 2) {
1079                         dev_notice(cs->dev, "%s: %s missing\n", "FACILITY_REQ",
1080                                    "Facility Request Parameter");
1081                         send_conf(iif, ap, skb, CapiIllMessageParmCoding);
1082                         return;
1083                 }
1084                 function = CAPIMSG_U16(pparam, 1);
1085                 switch (function) {
1086                 case CAPI_SUPPSVC_GETSUPPORTED:
1087                         info = CapiSuccess;
1088                         /* Supplementary Service specific parameter */
1089                         confparam[3] = 6;       /* length */
1090                         /* Supplementary services info: Success */
1091                         capimsg_setu16(confparam, 4, CapiSuccess);
1092                         /* Supported Services: none */
1093                         capimsg_setu32(confparam, 6, 0);
1094                         break;
1095                 /* ToDo: add supported services */
1096                 default:
1097                         info = CapiFacilitySpecificFunctionNotSupported;
1098                         /* Supplementary Service specific parameter */
1099                         confparam[3] = 2;       /* length */
1100                         /* Supplementary services info: not supported */
1101                         capimsg_setu16(confparam, 4,
1102                                        CapiSupplementaryServiceNotSupported);
1103                 }
1104
1105                 /* Facility confirmation parameter */
1106                 confparam[0] = confparam[3] + 3;        /* total length */
1107                 /* Function: copy from _REQ message */
1108                 capimsg_setu16(confparam, 1, function);
1109                 /* Supplementary Service specific parameter already set above */
1110                 break;
1111
1112         case CAPI_FACILITY_WAKEUP:      /* ToDo */
1113                 info = CapiFacilityNotSupported;
1114                 confparam[0] = 2;       /* length */
1115                 /* Number of accepted awake request parameters: 0 */
1116                 capimsg_setu16(confparam, 1, 0);
1117                 break;
1118
1119         default:
1120                 info = CapiFacilityNotSupported;
1121                 confparam[0] = 0;       /* empty struct */
1122         }
1123
1124         /* send FACILITY_CONF with given Info and confirmation parameter */
1125         capi_cmsg_answer(cmsg);
1126         cmsg->Info = info;
1127         cmsg->FacilityConfirmationParameter = confparam;
1128         msgsize += confparam[0];        /* length */
1129         cskb = alloc_skb(msgsize, GFP_ATOMIC);
1130         if (!cskb) {
1131                 dev_err(cs->dev, "%s: out of memory\n", __func__);
1132                 return;
1133         }
1134         capi_cmsg2message(cmsg, __skb_put(cskb, msgsize));
1135         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1136         capi_ctr_handle_message(&iif->ctr, ap->id, cskb);
1137 }
1138
1139
1140 /*
1141  * process LISTEN_REQ message
1142  * just store the masks in the application data structure
1143  */
1144 static void do_listen_req(struct gigaset_capi_ctr *iif,
1145                           struct gigaset_capi_appl *ap,
1146                           struct sk_buff *skb)
1147 {
1148         /* decode message */
1149         capi_message2cmsg(&iif->acmsg, skb->data);
1150         dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
1151
1152         /* store listening parameters */
1153         ap->listenInfoMask = iif->acmsg.InfoMask;
1154         ap->listenCIPmask = iif->acmsg.CIPmask;
1155         send_conf(iif, ap, skb, CapiSuccess);
1156 }
1157
1158 /*
1159  * process ALERT_REQ message
1160  * nothing to do, Gigaset always alerts anyway
1161  */
1162 static void do_alert_req(struct gigaset_capi_ctr *iif,
1163                          struct gigaset_capi_appl *ap,
1164                          struct sk_buff *skb)
1165 {
1166         /* decode message */
1167         capi_message2cmsg(&iif->acmsg, skb->data);
1168         dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
1169         send_conf(iif, ap, skb, CapiAlertAlreadySent);
1170 }
1171
1172 /*
1173  * process CONNECT_REQ message
1174  * allocate a B channel, prepare dial commands, queue a DIAL event,
1175  * emit CONNECT_CONF reply
1176  */
1177 static void do_connect_req(struct gigaset_capi_ctr *iif,
1178                            struct gigaset_capi_appl *ap,
1179                            struct sk_buff *skb)
1180 {
1181         struct cardstate *cs = iif->ctr.driverdata;
1182         _cmsg *cmsg = &iif->acmsg;
1183         struct bc_state *bcs;
1184         char **commands;
1185         char *s;
1186         u8 *pp;
1187         int i, l;
1188         u16 info;
1189
1190         /* decode message */
1191         capi_message2cmsg(cmsg, skb->data);
1192         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1193
1194         /* get free B channel & construct PLCI */
1195         bcs = gigaset_get_free_channel(cs);
1196         if (!bcs) {
1197                 dev_notice(cs->dev, "%s: no B channel available\n",
1198                            "CONNECT_REQ");
1199                 send_conf(iif, ap, skb, CapiNoPlciAvailable);
1200                 return;
1201         }
1202         ap->bcnext = NULL;
1203         bcs->ap = ap;
1204         cmsg->adr.adrPLCI |= (bcs->channel + 1) << 8;
1205
1206         /* build command table */
1207         commands = kzalloc(AT_NUM*(sizeof *commands), GFP_KERNEL);
1208         if (!commands)
1209                 goto oom;
1210
1211         /* encode parameter: Called party number */
1212         pp = cmsg->CalledPartyNumber;
1213         if (pp == NULL || *pp == 0) {
1214                 dev_notice(cs->dev, "%s: %s missing\n",
1215                            "CONNECT_REQ", "Called party number");
1216                 info = CapiIllMessageParmCoding;
1217                 goto error;
1218         }
1219         l = *pp++;
1220         /* check type of number/numbering plan byte */
1221         switch (*pp) {
1222         case 0x80:      /* unknown type / unknown numbering plan */
1223         case 0x81:      /* unknown type / ISDN/Telephony numbering plan */
1224                 break;
1225         default:        /* others: warn about potential misinterpretation */
1226                 dev_notice(cs->dev, "%s: %s type/plan 0x%02x unsupported\n",
1227                            "CONNECT_REQ", "Called party number", *pp);
1228         }
1229         pp++;
1230         l--;
1231         /* translate "**" internal call prefix to CTP value */
1232         if (l >= 2 && pp[0] == '*' && pp[1] == '*') {
1233                 s = "^SCTP=0\r";
1234                 pp += 2;
1235                 l -= 2;
1236         } else {
1237                 s = "^SCTP=1\r";
1238         }
1239         commands[AT_TYPE] = kstrdup(s, GFP_KERNEL);
1240         if (!commands[AT_TYPE])
1241                 goto oom;
1242         commands[AT_DIAL] = kmalloc(l+3, GFP_KERNEL);
1243         if (!commands[AT_DIAL])
1244                 goto oom;
1245         snprintf(commands[AT_DIAL], l+3, "D%.*s\r", l, pp);
1246
1247         /* encode parameter: Calling party number */
1248         pp = cmsg->CallingPartyNumber;
1249         if (pp != NULL && *pp > 0) {
1250                 l = *pp++;
1251
1252                 /* check type of number/numbering plan byte */
1253                 /* ToDo: allow for/handle Ext=1? */
1254                 switch (*pp) {
1255                 case 0x00:      /* unknown type / unknown numbering plan */
1256                 case 0x01:      /* unknown type / ISDN/Telephony num. plan */
1257                         break;
1258                 default:
1259                         dev_notice(cs->dev,
1260                                    "%s: %s type/plan 0x%02x unsupported\n",
1261                                    "CONNECT_REQ", "Calling party number", *pp);
1262                 }
1263                 pp++;
1264                 l--;
1265
1266                 /* check presentation indicator */
1267                 if (!l) {
1268                         dev_notice(cs->dev, "%s: %s IE truncated\n",
1269                                    "CONNECT_REQ", "Calling party number");
1270                         info = CapiIllMessageParmCoding;
1271                         goto error;
1272                 }
1273                 switch (*pp & 0xfc) { /* ignore Screening indicator */
1274                 case 0x80:      /* Presentation allowed */
1275                         s = "^SCLIP=1\r";
1276                         break;
1277                 case 0xa0:      /* Presentation restricted */
1278                         s = "^SCLIP=0\r";
1279                         break;
1280                 default:
1281                         dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
1282                                    "CONNECT_REQ",
1283                                    "Presentation/Screening indicator",
1284                                    *pp);
1285                         s = "^SCLIP=1\r";
1286                 }
1287                 commands[AT_CLIP] = kstrdup(s, GFP_KERNEL);
1288                 if (!commands[AT_CLIP])
1289                         goto oom;
1290                 pp++;
1291                 l--;
1292
1293                 if (l) {
1294                         /* number */
1295                         commands[AT_MSN] = kmalloc(l+8, GFP_KERNEL);
1296                         if (!commands[AT_MSN])
1297                                 goto oom;
1298                         snprintf(commands[AT_MSN], l+8, "^SMSN=%*s\r", l, pp);
1299                 }
1300         }
1301
1302         /* check parameter: CIP Value */
1303         if (cmsg->CIPValue >= ARRAY_SIZE(cip2bchlc) ||
1304             (cmsg->CIPValue > 0 && cip2bchlc[cmsg->CIPValue].bc == NULL)) {
1305                 dev_notice(cs->dev, "%s: unknown CIP value %d\n",
1306                            "CONNECT_REQ", cmsg->CIPValue);
1307                 info = CapiCipValueUnknown;
1308                 goto error;
1309         }
1310
1311         /* check/encode parameter: BC */
1312         if (cmsg->BC && cmsg->BC[0]) {
1313                 /* explicit BC overrides CIP */
1314                 l = 2*cmsg->BC[0] + 7;
1315                 commands[AT_BC] = kmalloc(l, GFP_KERNEL);
1316                 if (!commands[AT_BC])
1317                         goto oom;
1318                 strcpy(commands[AT_BC], "^SBC=");
1319                 decode_ie(cmsg->BC, commands[AT_BC]+5);
1320                 strcpy(commands[AT_BC] + l - 2, "\r");
1321         } else if (cip2bchlc[cmsg->CIPValue].bc) {
1322                 l = strlen(cip2bchlc[cmsg->CIPValue].bc) + 7;
1323                 commands[AT_BC] = kmalloc(l, GFP_KERNEL);
1324                 if (!commands[AT_BC])
1325                         goto oom;
1326                 snprintf(commands[AT_BC], l, "^SBC=%s\r",
1327                          cip2bchlc[cmsg->CIPValue].bc);
1328         }
1329
1330         /* check/encode parameter: HLC */
1331         if (cmsg->HLC && cmsg->HLC[0]) {
1332                 /* explicit HLC overrides CIP */
1333                 l = 2*cmsg->HLC[0] + 7;
1334                 commands[AT_HLC] = kmalloc(l, GFP_KERNEL);
1335                 if (!commands[AT_HLC])
1336                         goto oom;
1337                 strcpy(commands[AT_HLC], "^SHLC=");
1338                 decode_ie(cmsg->HLC, commands[AT_HLC]+5);
1339                 strcpy(commands[AT_HLC] + l - 2, "\r");
1340         } else if (cip2bchlc[cmsg->CIPValue].hlc) {
1341                 l = strlen(cip2bchlc[cmsg->CIPValue].hlc) + 7;
1342                 commands[AT_HLC] = kmalloc(l, GFP_KERNEL);
1343                 if (!commands[AT_HLC])
1344                         goto oom;
1345                 snprintf(commands[AT_HLC], l, "^SHLC=%s\r",
1346                          cip2bchlc[cmsg->CIPValue].hlc);
1347         }
1348
1349         /* check/encode parameter: B Protocol */
1350         if (cmsg->BProtocol == CAPI_DEFAULT) {
1351                 bcs->proto2 = L2_HDLC;
1352                 dev_warn(cs->dev,
1353                     "B2 Protocol X.75 SLP unsupported, using Transparent\n");
1354         } else {
1355                 switch (cmsg->B1protocol) {
1356                 case 0:
1357                         bcs->proto2 = L2_HDLC;
1358                         break;
1359                 case 1:
1360                         bcs->proto2 = L2_BITSYNC;
1361                         break;
1362                 default:
1363                         dev_warn(cs->dev,
1364                             "B1 Protocol %u unsupported, using Transparent\n",
1365                                  cmsg->B1protocol);
1366                         bcs->proto2 = L2_BITSYNC;
1367                 }
1368                 if (cmsg->B2protocol != 1)
1369                         dev_warn(cs->dev,
1370                             "B2 Protocol %u unsupported, using Transparent\n",
1371                                  cmsg->B2protocol);
1372                 if (cmsg->B3protocol != 0)
1373                         dev_warn(cs->dev,
1374                             "B3 Protocol %u unsupported, using Transparent\n",
1375                                  cmsg->B3protocol);
1376                 ignore_cstruct_param(cs, cmsg->B1configuration,
1377                                         "CONNECT_REQ", "B1 Configuration");
1378                 ignore_cstruct_param(cs, cmsg->B2configuration,
1379                                         "CONNECT_REQ", "B2 Configuration");
1380                 ignore_cstruct_param(cs, cmsg->B3configuration,
1381                                         "CONNECT_REQ", "B3 Configuration");
1382         }
1383         commands[AT_PROTO] = kmalloc(9, GFP_KERNEL);
1384         if (!commands[AT_PROTO])
1385                 goto oom;
1386         snprintf(commands[AT_PROTO], 9, "^SBPR=%u\r", bcs->proto2);
1387
1388         /* ToDo: check/encode remaining parameters */
1389         ignore_cstruct_param(cs, cmsg->CalledPartySubaddress,
1390                                         "CONNECT_REQ", "Called pty subaddr");
1391         ignore_cstruct_param(cs, cmsg->CallingPartySubaddress,
1392                                         "CONNECT_REQ", "Calling pty subaddr");
1393         ignore_cstruct_param(cs, cmsg->LLC,
1394                                         "CONNECT_REQ", "LLC");
1395         if (cmsg->AdditionalInfo != CAPI_DEFAULT) {
1396                 ignore_cstruct_param(cs, cmsg->BChannelinformation,
1397                                         "CONNECT_REQ", "B Channel Information");
1398                 ignore_cstruct_param(cs, cmsg->Keypadfacility,
1399                                         "CONNECT_REQ", "Keypad Facility");
1400                 ignore_cstruct_param(cs, cmsg->Useruserdata,
1401                                         "CONNECT_REQ", "User-User Data");
1402                 ignore_cstruct_param(cs, cmsg->Facilitydataarray,
1403                                         "CONNECT_REQ", "Facility Data Array");
1404         }
1405
1406         /* encode parameter: B channel to use */
1407         commands[AT_ISO] = kmalloc(9, GFP_KERNEL);
1408         if (!commands[AT_ISO])
1409                 goto oom;
1410         snprintf(commands[AT_ISO], 9, "^SISO=%u\r",
1411                  (unsigned) bcs->channel + 1);
1412
1413         /* queue & schedule EV_DIAL event */
1414         if (!gigaset_add_event(cs, &bcs->at_state, EV_DIAL, commands,
1415                                bcs->at_state.seq_index, NULL)) {
1416                 info = CAPI_MSGOSRESOURCEERR;
1417                 goto error;
1418         }
1419         gigaset_schedule_event(cs);
1420         ap->connected = APCONN_SETUP;
1421         send_conf(iif, ap, skb, CapiSuccess);
1422         return;
1423
1424 oom:
1425         dev_err(cs->dev, "%s: out of memory\n", __func__);
1426         info = CAPI_MSGOSRESOURCEERR;
1427 error:
1428         if (commands)
1429                 for (i = 0; i < AT_NUM; i++)
1430                         kfree(commands[i]);
1431         kfree(commands);
1432         gigaset_free_channel(bcs);
1433         send_conf(iif, ap, skb, info);
1434 }
1435
1436 /*
1437  * process CONNECT_RESP message
1438  * checks protocol parameters and queues an ACCEPT or HUP event
1439  */
1440 static void do_connect_resp(struct gigaset_capi_ctr *iif,
1441                             struct gigaset_capi_appl *ap,
1442                             struct sk_buff *skb)
1443 {
1444         struct cardstate *cs = iif->ctr.driverdata;
1445         _cmsg *cmsg = &iif->acmsg;
1446         struct bc_state *bcs;
1447         struct gigaset_capi_appl *oap;
1448         int channel;
1449
1450         /* decode message */
1451         capi_message2cmsg(cmsg, skb->data);
1452         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1453         dev_kfree_skb_any(skb);
1454
1455         /* extract and check channel number from PLCI */
1456         channel = (cmsg->adr.adrPLCI >> 8) & 0xff;
1457         if (!channel || channel > cs->channels) {
1458                 dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
1459                            "CONNECT_RESP", "PLCI", cmsg->adr.adrPLCI);
1460                 return;
1461         }
1462         bcs = cs->bcs + channel - 1;
1463
1464         switch (cmsg->Reject) {
1465         case 0:         /* Accept */
1466                 /* drop all competing applications, keep only this one */
1467                 for (oap = bcs->ap; oap != NULL; oap = oap->bcnext)
1468                         if (oap != ap)
1469                                 send_disconnect_ind(bcs, oap,
1470                                         CapiCallGivenToOtherApplication);
1471                 ap->bcnext = NULL;
1472                 bcs->ap = ap;
1473                 bcs->chstate |= CHS_NOTIFY_LL;
1474
1475                 /* check/encode B channel protocol */
1476                 if (cmsg->BProtocol == CAPI_DEFAULT) {
1477                         bcs->proto2 = L2_HDLC;
1478                         dev_warn(cs->dev,
1479                 "B2 Protocol X.75 SLP unsupported, using Transparent\n");
1480                 } else {
1481                         switch (cmsg->B1protocol) {
1482                         case 0:
1483                                 bcs->proto2 = L2_HDLC;
1484                                 break;
1485                         case 1:
1486                                 bcs->proto2 = L2_BITSYNC;
1487                                 break;
1488                         default:
1489                                 dev_warn(cs->dev,
1490                         "B1 Protocol %u unsupported, using Transparent\n",
1491                                          cmsg->B1protocol);
1492                                 bcs->proto2 = L2_BITSYNC;
1493                         }
1494                         if (cmsg->B2protocol != 1)
1495                                 dev_warn(cs->dev,
1496                         "B2 Protocol %u unsupported, using Transparent\n",
1497                                          cmsg->B2protocol);
1498                         if (cmsg->B3protocol != 0)
1499                                 dev_warn(cs->dev,
1500                         "B3 Protocol %u unsupported, using Transparent\n",
1501                                          cmsg->B3protocol);
1502                         ignore_cstruct_param(cs, cmsg->B1configuration,
1503                                         "CONNECT_RESP", "B1 Configuration");
1504                         ignore_cstruct_param(cs, cmsg->B2configuration,
1505                                         "CONNECT_RESP", "B2 Configuration");
1506                         ignore_cstruct_param(cs, cmsg->B3configuration,
1507                                         "CONNECT_RESP", "B3 Configuration");
1508                 }
1509
1510                 /* ToDo: check/encode remaining parameters */
1511                 ignore_cstruct_param(cs, cmsg->ConnectedNumber,
1512                                         "CONNECT_RESP", "Connected Number");
1513                 ignore_cstruct_param(cs, cmsg->ConnectedSubaddress,
1514                                         "CONNECT_RESP", "Connected Subaddress");
1515                 ignore_cstruct_param(cs, cmsg->LLC,
1516                                         "CONNECT_RESP", "LLC");
1517                 if (cmsg->AdditionalInfo != CAPI_DEFAULT) {
1518                         ignore_cstruct_param(cs, cmsg->BChannelinformation,
1519                                         "CONNECT_RESP", "BChannel Information");
1520                         ignore_cstruct_param(cs, cmsg->Keypadfacility,
1521                                         "CONNECT_RESP", "Keypad Facility");
1522                         ignore_cstruct_param(cs, cmsg->Useruserdata,
1523                                         "CONNECT_RESP", "User-User Data");
1524                         ignore_cstruct_param(cs, cmsg->Facilitydataarray,
1525                                         "CONNECT_RESP", "Facility Data Array");
1526                 }
1527
1528                 /* Accept call */
1529                 if (!gigaset_add_event(cs, &cs->bcs[channel-1].at_state,
1530                                        EV_ACCEPT, NULL, 0, NULL))
1531                         return;
1532                 gigaset_schedule_event(cs);
1533                 return;
1534
1535         case 1:                 /* Ignore */
1536                 /* send DISCONNECT_IND to this application */
1537                 send_disconnect_ind(bcs, ap, 0);
1538
1539                 /* remove it from the list of listening apps */
1540                 if (bcs->ap == ap) {
1541                         bcs->ap = ap->bcnext;
1542                         if (bcs->ap == NULL)
1543                                 /* last one: stop ev-layer hupD notifications */
1544                                 bcs->chstate &= ~CHS_NOTIFY_LL;
1545                         return;
1546                 }
1547                 for (oap = bcs->ap; oap != NULL; oap = oap->bcnext) {
1548                         if (oap->bcnext == ap) {
1549                                 oap->bcnext = oap->bcnext->bcnext;
1550                                 return;
1551                         }
1552                 }
1553                 dev_err(cs->dev, "%s: application %u not found\n",
1554                         __func__, ap->id);
1555                 return;
1556
1557         default:                /* Reject */
1558                 /* drop all competing applications, keep only this one */
1559                 for (oap = bcs->ap; oap != NULL; oap = oap->bcnext)
1560                         if (oap != ap)
1561                                 send_disconnect_ind(bcs, oap,
1562                                         CapiCallGivenToOtherApplication);
1563                 ap->bcnext = NULL;
1564                 bcs->ap = ap;
1565
1566                 /* reject call - will trigger DISCONNECT_IND for this app */
1567                 dev_info(cs->dev, "%s: Reject=%x\n",
1568                          "CONNECT_RESP", cmsg->Reject);
1569                 if (!gigaset_add_event(cs, &cs->bcs[channel-1].at_state,
1570                                        EV_HUP, NULL, 0, NULL))
1571                         return;
1572                 gigaset_schedule_event(cs);
1573                 return;
1574         }
1575 }
1576
1577 /*
1578  * process CONNECT_B3_REQ message
1579  * build NCCI and emit CONNECT_B3_CONF reply
1580  */
1581 static void do_connect_b3_req(struct gigaset_capi_ctr *iif,
1582                               struct gigaset_capi_appl *ap,
1583                               struct sk_buff *skb)
1584 {
1585         struct cardstate *cs = iif->ctr.driverdata;
1586         _cmsg *cmsg = &iif->acmsg;
1587         int channel;
1588
1589         /* decode message */
1590         capi_message2cmsg(cmsg, skb->data);
1591         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1592
1593         /* extract and check channel number from PLCI */
1594         channel = (cmsg->adr.adrPLCI >> 8) & 0xff;
1595         if (!channel || channel > cs->channels) {
1596                 dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
1597                            "CONNECT_B3_REQ", "PLCI", cmsg->adr.adrPLCI);
1598                 send_conf(iif, ap, skb, CapiIllContrPlciNcci);
1599                 return;
1600         }
1601
1602         /* mark logical connection active */
1603         ap->connected = APCONN_ACTIVE;
1604
1605         /* build NCCI: always 1 (one B3 connection only) */
1606         cmsg->adr.adrNCCI |= 1 << 16;
1607
1608         /* NCPI parameter: not applicable for B3 Transparent */
1609         ignore_cstruct_param(cs, cmsg->NCPI, "CONNECT_B3_REQ", "NCPI");
1610         send_conf(iif, ap, skb, (cmsg->NCPI && cmsg->NCPI[0]) ?
1611                                 CapiNcpiNotSupportedByProtocol : CapiSuccess);
1612 }
1613
1614 /*
1615  * process CONNECT_B3_RESP message
1616  * Depending on the Reject parameter, either emit CONNECT_B3_ACTIVE_IND
1617  * or queue EV_HUP and emit DISCONNECT_B3_IND.
1618  * The emitted message is always shorter than the received one,
1619  * allowing to reuse the skb.
1620  */
1621 static void do_connect_b3_resp(struct gigaset_capi_ctr *iif,
1622                                struct gigaset_capi_appl *ap,
1623                                struct sk_buff *skb)
1624 {
1625         struct cardstate *cs = iif->ctr.driverdata;
1626         _cmsg *cmsg = &iif->acmsg;
1627         struct bc_state *bcs;
1628         int channel;
1629         unsigned int msgsize;
1630         u8 command;
1631
1632         /* decode message */
1633         capi_message2cmsg(cmsg, skb->data);
1634         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1635
1636         /* extract and check channel number and NCCI */
1637         channel = (cmsg->adr.adrNCCI >> 8) & 0xff;
1638         if (!channel || channel > cs->channels ||
1639             ((cmsg->adr.adrNCCI >> 16) & 0xffff) != 1) {
1640                 dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
1641                            "CONNECT_B3_RESP", "NCCI", cmsg->adr.adrNCCI);
1642                 dev_kfree_skb_any(skb);
1643                 return;
1644         }
1645         bcs = &cs->bcs[channel-1];
1646
1647         if (cmsg->Reject) {
1648                 /* Reject: clear B3 connect received flag */
1649                 ap->connected = APCONN_SETUP;
1650
1651                 /* trigger hangup, causing eventual DISCONNECT_IND */
1652                 if (!gigaset_add_event(cs, &bcs->at_state,
1653                                        EV_HUP, NULL, 0, NULL)) {
1654                         dev_kfree_skb_any(skb);
1655                         return;
1656                 }
1657                 gigaset_schedule_event(cs);
1658
1659                 /* emit DISCONNECT_B3_IND */
1660                 command = CAPI_DISCONNECT_B3;
1661                 msgsize = CAPI_DISCONNECT_B3_IND_BASELEN;
1662         } else {
1663                 /*
1664                  * Accept: emit CONNECT_B3_ACTIVE_IND immediately, as
1665                  * we only send CONNECT_B3_IND if the B channel is up
1666                  */
1667                 command = CAPI_CONNECT_B3_ACTIVE;
1668                 msgsize = CAPI_CONNECT_B3_ACTIVE_IND_BASELEN;
1669         }
1670         capi_cmsg_header(cmsg, ap->id, command, CAPI_IND,
1671                          ap->nextMessageNumber++, cmsg->adr.adrNCCI);
1672         __skb_trim(skb, msgsize);
1673         capi_cmsg2message(cmsg, skb->data);
1674         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1675         capi_ctr_handle_message(&iif->ctr, ap->id, skb);
1676 }
1677
1678 /*
1679  * process DISCONNECT_REQ message
1680  * schedule EV_HUP and emit DISCONNECT_B3_IND if necessary,
1681  * emit DISCONNECT_CONF reply
1682  */
1683 static void do_disconnect_req(struct gigaset_capi_ctr *iif,
1684                               struct gigaset_capi_appl *ap,
1685                               struct sk_buff *skb)
1686 {
1687         struct cardstate *cs = iif->ctr.driverdata;
1688         _cmsg *cmsg = &iif->acmsg;
1689         struct bc_state *bcs;
1690         _cmsg *b3cmsg;
1691         struct sk_buff *b3skb;
1692         int channel;
1693
1694         /* decode message */
1695         capi_message2cmsg(cmsg, skb->data);
1696         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1697
1698         /* extract and check channel number from PLCI */
1699         channel = (cmsg->adr.adrPLCI >> 8) & 0xff;
1700         if (!channel || channel > cs->channels) {
1701                 dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
1702                            "DISCONNECT_REQ", "PLCI", cmsg->adr.adrPLCI);
1703                 send_conf(iif, ap, skb, CapiIllContrPlciNcci);
1704                 return;
1705         }
1706         bcs = cs->bcs + channel - 1;
1707
1708         /* ToDo: process parameter: Additional info */
1709         if (cmsg->AdditionalInfo != CAPI_DEFAULT) {
1710                 ignore_cstruct_param(cs, cmsg->BChannelinformation,
1711                                      "DISCONNECT_REQ", "B Channel Information");
1712                 ignore_cstruct_param(cs, cmsg->Keypadfacility,
1713                                      "DISCONNECT_REQ", "Keypad Facility");
1714                 ignore_cstruct_param(cs, cmsg->Useruserdata,
1715                                      "DISCONNECT_REQ", "User-User Data");
1716                 ignore_cstruct_param(cs, cmsg->Facilitydataarray,
1717                                      "DISCONNECT_REQ", "Facility Data Array");
1718         }
1719
1720         /* skip if DISCONNECT_IND already sent */
1721         if (!ap->connected)
1722                 return;
1723
1724         /* check for active logical connection */
1725         if (ap->connected >= APCONN_ACTIVE) {
1726                 /*
1727                  * emit DISCONNECT_B3_IND with cause 0x3301
1728                  * use separate cmsg structure, as the content of iif->acmsg
1729                  * is still needed for creating the _CONF message
1730                  */
1731                 b3cmsg = kmalloc(sizeof(*b3cmsg), GFP_KERNEL);
1732                 if (!b3cmsg) {
1733                         dev_err(cs->dev, "%s: out of memory\n", __func__);
1734                         send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
1735                         return;
1736                 }
1737                 capi_cmsg_header(b3cmsg, ap->id, CAPI_DISCONNECT_B3, CAPI_IND,
1738                                  ap->nextMessageNumber++,
1739                                  cmsg->adr.adrPLCI | (1 << 16));
1740                 b3cmsg->Reason_B3 = CapiProtocolErrorLayer1;
1741                 b3skb = alloc_skb(CAPI_DISCONNECT_B3_IND_BASELEN, GFP_KERNEL);
1742                 if (b3skb == NULL) {
1743                         dev_err(cs->dev, "%s: out of memory\n", __func__);
1744                         send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
1745                         return;
1746                 }
1747                 capi_cmsg2message(b3cmsg,
1748                         __skb_put(b3skb, CAPI_DISCONNECT_B3_IND_BASELEN));
1749                 kfree(b3cmsg);
1750                 capi_ctr_handle_message(&iif->ctr, ap->id, b3skb);
1751         }
1752
1753         /* trigger hangup, causing eventual DISCONNECT_IND */
1754         if (!gigaset_add_event(cs, &bcs->at_state, EV_HUP, NULL, 0, NULL)) {
1755                 send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
1756                 return;
1757         }
1758         gigaset_schedule_event(cs);
1759
1760         /* emit reply */
1761         send_conf(iif, ap, skb, CapiSuccess);
1762 }
1763
1764 /*
1765  * process DISCONNECT_B3_REQ message
1766  * schedule EV_HUP and emit DISCONNECT_B3_CONF reply
1767  */
1768 static void do_disconnect_b3_req(struct gigaset_capi_ctr *iif,
1769                                  struct gigaset_capi_appl *ap,
1770                                  struct sk_buff *skb)
1771 {
1772         struct cardstate *cs = iif->ctr.driverdata;
1773         _cmsg *cmsg = &iif->acmsg;
1774         int channel;
1775
1776         /* decode message */
1777         capi_message2cmsg(cmsg, skb->data);
1778         dump_cmsg(DEBUG_CMD, __func__, cmsg);
1779
1780         /* extract and check channel number and NCCI */
1781         channel = (cmsg->adr.adrNCCI >> 8) & 0xff;
1782         if (!channel || channel > cs->channels ||
1783             ((cmsg->adr.adrNCCI >> 16) & 0xffff) != 1) {
1784                 dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
1785                            "DISCONNECT_B3_REQ", "NCCI", cmsg->adr.adrNCCI);
1786                 send_conf(iif, ap, skb, CapiIllContrPlciNcci);
1787                 return;
1788         }
1789
1790         /* reject if logical connection not active */
1791         if (ap->connected < APCONN_ACTIVE) {
1792                 send_conf(iif, ap, skb,
1793                           CapiMessageNotSupportedInCurrentState);
1794                 return;
1795         }
1796
1797         /* trigger hangup, causing eventual DISCONNECT_B3_IND */
1798         if (!gigaset_add_event(cs, &cs->bcs[channel-1].at_state,
1799                                EV_HUP, NULL, 0, NULL)) {
1800                 send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
1801                 return;
1802         }
1803         gigaset_schedule_event(cs);
1804
1805         /* NCPI parameter: not applicable for B3 Transparent */
1806         ignore_cstruct_param(cs, cmsg->NCPI,
1807                                 "DISCONNECT_B3_REQ", "NCPI");
1808         send_conf(iif, ap, skb, (cmsg->NCPI && cmsg->NCPI[0]) ?
1809                                 CapiNcpiNotSupportedByProtocol : CapiSuccess);
1810 }
1811
1812 /*
1813  * process DATA_B3_REQ message
1814  */
1815 static void do_data_b3_req(struct gigaset_capi_ctr *iif,
1816                            struct gigaset_capi_appl *ap,
1817                            struct sk_buff *skb)
1818 {
1819         struct cardstate *cs = iif->ctr.driverdata;
1820         int channel = CAPIMSG_PLCI_PART(skb->data);
1821         u16 ncci = CAPIMSG_NCCI_PART(skb->data);
1822         u16 msglen = CAPIMSG_LEN(skb->data);
1823         u16 datalen = CAPIMSG_DATALEN(skb->data);
1824         u16 flags = CAPIMSG_FLAGS(skb->data);
1825
1826         /* frequent message, avoid _cmsg overhead */
1827         dump_rawmsg(DEBUG_LLDATA, "DATA_B3_REQ", skb->data);
1828
1829         gig_dbg(DEBUG_LLDATA,
1830                 "Receiving data from LL (ch: %d, flg: %x, sz: %d|%d)",
1831                 channel, flags, msglen, datalen);
1832
1833         /* check parameters */
1834         if (channel == 0 || channel > cs->channels || ncci != 1) {
1835                 dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
1836                            "DATA_B3_REQ", "NCCI", CAPIMSG_NCCI(skb->data));
1837                 send_conf(iif, ap, skb, CapiIllContrPlciNcci);
1838                 return;
1839         }
1840         if (msglen != CAPI_DATA_B3_REQ_LEN && msglen != CAPI_DATA_B3_REQ_LEN64)
1841                 dev_notice(cs->dev, "%s: unexpected length %d\n",
1842                            "DATA_B3_REQ", msglen);
1843         if (msglen + datalen != skb->len)
1844                 dev_notice(cs->dev, "%s: length mismatch (%d+%d!=%d)\n",
1845                            "DATA_B3_REQ", msglen, datalen, skb->len);
1846         if (msglen + datalen > skb->len) {
1847                 /* message too short for announced data length */
1848                 send_conf(iif, ap, skb, CapiIllMessageParmCoding); /* ? */
1849                 return;
1850         }
1851         if (flags & CAPI_FLAGS_RESERVED) {
1852                 dev_notice(cs->dev, "%s: reserved flags set (%x)\n",
1853                            "DATA_B3_REQ", flags);
1854                 send_conf(iif, ap, skb, CapiIllMessageParmCoding);
1855                 return;
1856         }
1857
1858         /* reject if logical connection not active */
1859         if (ap->connected < APCONN_ACTIVE) {
1860                 send_conf(iif, ap, skb, CapiMessageNotSupportedInCurrentState);
1861                 return;
1862         }
1863
1864         /* pull CAPI message into link layer header */
1865         skb_reset_mac_header(skb);
1866         skb->mac_len = msglen;
1867         skb_pull(skb, msglen);
1868
1869         /* pass to device-specific module */
1870         if (cs->ops->send_skb(&cs->bcs[channel-1], skb) < 0) {
1871                 send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
1872                 return;
1873         }
1874
1875         /* DATA_B3_CONF reply will be sent by gigaset_skb_sent() */
1876
1877         /*
1878          * ToDo: honor unset "delivery confirmation" bit
1879          * (send DATA_B3_CONF immediately?)
1880          */
1881 }
1882
1883 /*
1884  * process RESET_B3_REQ message
1885  * just always reply "not supported by current protocol"
1886  */
1887 static void do_reset_b3_req(struct gigaset_capi_ctr *iif,
1888                             struct gigaset_capi_appl *ap,
1889                             struct sk_buff *skb)
1890 {
1891         /* decode message */
1892         capi_message2cmsg(&iif->acmsg, skb->data);
1893         dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
1894         send_conf(iif, ap, skb,
1895                   CapiResetProcedureNotSupportedByCurrentProtocol);
1896 }
1897
1898 /*
1899  * dump unsupported/ignored messages at most twice per minute,
1900  * some apps send those very frequently
1901  */
1902 static unsigned long ignored_msg_dump_time;
1903
1904 /*
1905  * unsupported CAPI message handler
1906  */
1907 static void do_unsupported(struct gigaset_capi_ctr *iif,
1908                            struct gigaset_capi_appl *ap,
1909                            struct sk_buff *skb)
1910 {
1911         /* decode message */
1912         capi_message2cmsg(&iif->acmsg, skb->data);
1913         if (printk_timed_ratelimit(&ignored_msg_dump_time, 30 * 1000))
1914                 dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
1915         send_conf(iif, ap, skb, CapiMessageNotSupportedInCurrentState);
1916 }
1917
1918 /*
1919  * CAPI message handler: no-op
1920  */
1921 static void do_nothing(struct gigaset_capi_ctr *iif,
1922                        struct gigaset_capi_appl *ap,
1923                        struct sk_buff *skb)
1924 {
1925         if (printk_timed_ratelimit(&ignored_msg_dump_time, 30 * 1000)) {
1926                 /* decode message */
1927                 capi_message2cmsg(&iif->acmsg, skb->data);
1928                 dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
1929         }
1930         dev_kfree_skb_any(skb);
1931 }
1932
1933 static void do_data_b3_resp(struct gigaset_capi_ctr *iif,
1934                             struct gigaset_capi_appl *ap,
1935                             struct sk_buff *skb)
1936 {
1937         dump_rawmsg(DEBUG_LLDATA, __func__, skb->data);
1938         dev_kfree_skb_any(skb);
1939 }
1940
1941 /* table of outgoing CAPI message handlers with lookup function */
1942 typedef void (*capi_send_handler_t)(struct gigaset_capi_ctr *,
1943                                     struct gigaset_capi_appl *,
1944                                     struct sk_buff *);
1945
1946 static struct {
1947         u16 cmd;
1948         capi_send_handler_t handler;
1949 } capi_send_handler_table[] = {
1950         /* most frequent messages first for faster lookup */
1951         { CAPI_DATA_B3_REQ, do_data_b3_req },
1952         { CAPI_DATA_B3_RESP, do_data_b3_resp },
1953
1954         { CAPI_ALERT_REQ, do_alert_req },
1955         { CAPI_CONNECT_ACTIVE_RESP, do_nothing },
1956         { CAPI_CONNECT_B3_ACTIVE_RESP, do_nothing },
1957         { CAPI_CONNECT_B3_REQ, do_connect_b3_req },
1958         { CAPI_CONNECT_B3_RESP, do_connect_b3_resp },
1959         { CAPI_CONNECT_B3_T90_ACTIVE_RESP, do_nothing },
1960         { CAPI_CONNECT_REQ, do_connect_req },
1961         { CAPI_CONNECT_RESP, do_connect_resp },
1962         { CAPI_DISCONNECT_B3_REQ, do_disconnect_b3_req },
1963         { CAPI_DISCONNECT_B3_RESP, do_nothing },
1964         { CAPI_DISCONNECT_REQ, do_disconnect_req },
1965         { CAPI_DISCONNECT_RESP, do_nothing },
1966         { CAPI_FACILITY_REQ, do_facility_req },
1967         { CAPI_FACILITY_RESP, do_nothing },
1968         { CAPI_LISTEN_REQ, do_listen_req },
1969         { CAPI_SELECT_B_PROTOCOL_REQ, do_unsupported },
1970         { CAPI_RESET_B3_REQ, do_reset_b3_req },
1971         { CAPI_RESET_B3_RESP, do_nothing },
1972
1973         /*
1974          * ToDo: support overlap sending (requires ev-layer state
1975          * machine extension to generate additional ATD commands)
1976          */
1977         { CAPI_INFO_REQ, do_unsupported },
1978         { CAPI_INFO_RESP, do_nothing },
1979
1980         /*
1981          * ToDo: what's the proper response for these?
1982          */
1983         { CAPI_MANUFACTURER_REQ, do_nothing },
1984         { CAPI_MANUFACTURER_RESP, do_nothing },
1985 };
1986
1987 /* look up handler */
1988 static inline capi_send_handler_t lookup_capi_send_handler(const u16 cmd)
1989 {
1990         size_t i;
1991
1992         for (i = 0; i < ARRAY_SIZE(capi_send_handler_table); i++)
1993                 if (capi_send_handler_table[i].cmd == cmd)
1994                         return capi_send_handler_table[i].handler;
1995         return NULL;
1996 }
1997
1998
1999 /**
2000  * gigaset_send_message() - accept a CAPI message from an application
2001  * @ctr:        controller descriptor structure.
2002  * @skb:        CAPI message.
2003  *
2004  * Return value: CAPI error code
2005  * Note: capidrv (and probably others, too) only uses the return value to
2006  * decide whether it has to free the skb (only if result != CAPI_NOERROR (0))
2007  */
2008 static u16 gigaset_send_message(struct capi_ctr *ctr, struct sk_buff *skb)
2009 {
2010         struct gigaset_capi_ctr *iif
2011                 = container_of(ctr, struct gigaset_capi_ctr, ctr);
2012         struct cardstate *cs = ctr->driverdata;
2013         struct gigaset_capi_appl *ap;
2014         capi_send_handler_t handler;
2015
2016         /* can only handle linear sk_buffs */
2017         if (skb_linearize(skb) < 0) {
2018                 dev_warn(cs->dev, "%s: skb_linearize failed\n", __func__);
2019                 return CAPI_MSGOSRESOURCEERR;
2020         }
2021
2022         /* retrieve application data structure */
2023         ap = get_appl(iif, CAPIMSG_APPID(skb->data));
2024         if (!ap) {
2025                 dev_notice(cs->dev, "%s: application %u not registered\n",
2026                            __func__, CAPIMSG_APPID(skb->data));
2027                 return CAPI_ILLAPPNR;
2028         }
2029
2030         /* look up command */
2031         handler = lookup_capi_send_handler(CAPIMSG_CMD(skb->data));
2032         if (!handler) {
2033                 /* unknown/unsupported message type */
2034                 if (printk_ratelimit())
2035                         dev_notice(cs->dev, "%s: unsupported message %u\n",
2036                                    __func__, CAPIMSG_CMD(skb->data));
2037                 return CAPI_ILLCMDORSUBCMDORMSGTOSMALL;
2038         }
2039
2040         /* serialize */
2041         if (atomic_add_return(1, &iif->sendqlen) > 1) {
2042                 /* queue behind other messages */
2043                 skb_queue_tail(&iif->sendqueue, skb);
2044                 return CAPI_NOERROR;
2045         }
2046
2047         /* process message */
2048         handler(iif, ap, skb);
2049
2050         /* process other messages arrived in the meantime */
2051         while (atomic_sub_return(1, &iif->sendqlen) > 0) {
2052                 skb = skb_dequeue(&iif->sendqueue);
2053                 if (!skb) {
2054                         /* should never happen */
2055                         dev_err(cs->dev, "%s: send queue empty\n", __func__);
2056                         continue;
2057                 }
2058                 ap = get_appl(iif, CAPIMSG_APPID(skb->data));
2059                 if (!ap) {
2060                         /* could that happen? */
2061                         dev_warn(cs->dev, "%s: application %u vanished\n",
2062                                  __func__, CAPIMSG_APPID(skb->data));
2063                         continue;
2064                 }
2065                 handler = lookup_capi_send_handler(CAPIMSG_CMD(skb->data));
2066                 if (!handler) {
2067                         /* should never happen */
2068                         dev_err(cs->dev, "%s: handler %x vanished\n",
2069                                 __func__, CAPIMSG_CMD(skb->data));
2070                         continue;
2071                 }
2072                 handler(iif, ap, skb);
2073         }
2074
2075         return CAPI_NOERROR;
2076 }
2077
2078 /**
2079  * gigaset_procinfo() - build single line description for controller
2080  * @ctr:        controller descriptor structure.
2081  *
2082  * Return value: pointer to generated string (null terminated)
2083  */
2084 static char *gigaset_procinfo(struct capi_ctr *ctr)
2085 {
2086         return ctr->name;       /* ToDo: more? */
2087 }
2088
2089 static int gigaset_proc_show(struct seq_file *m, void *v)
2090 {
2091         struct capi_ctr *ctr = m->private;
2092         struct cardstate *cs = ctr->driverdata;
2093         char *s;
2094         int i;
2095
2096         seq_printf(m, "%-16s %s\n", "name", ctr->name);
2097         seq_printf(m, "%-16s %s %s\n", "dev",
2098                         dev_driver_string(cs->dev), dev_name(cs->dev));
2099         seq_printf(m, "%-16s %d\n", "id", cs->myid);
2100         if (cs->gotfwver)
2101                 seq_printf(m, "%-16s %d.%d.%d.%d\n", "firmware",
2102                         cs->fwver[0], cs->fwver[1], cs->fwver[2], cs->fwver[3]);
2103         seq_printf(m, "%-16s %d\n", "channels", cs->channels);
2104         seq_printf(m, "%-16s %s\n", "onechannel", cs->onechannel ? "yes" : "no");
2105
2106         switch (cs->mode) {
2107         case M_UNKNOWN:
2108                 s = "unknown";
2109                 break;
2110         case M_CONFIG:
2111                 s = "config";
2112                 break;
2113         case M_UNIMODEM:
2114                 s = "Unimodem";
2115                 break;
2116         case M_CID:
2117                 s = "CID";
2118                 break;
2119         default:
2120                 s = "??";
2121         }
2122         seq_printf(m, "%-16s %s\n", "mode", s);
2123
2124         switch (cs->mstate) {
2125         case MS_UNINITIALIZED:
2126                 s = "uninitialized";
2127                 break;
2128         case MS_INIT:
2129                 s = "init";
2130                 break;
2131         case MS_LOCKED:
2132                 s = "locked";
2133                 break;
2134         case MS_SHUTDOWN:
2135                 s = "shutdown";
2136                 break;
2137         case MS_RECOVER:
2138                 s = "recover";
2139                 break;
2140         case MS_READY:
2141                 s = "ready";
2142                 break;
2143         default:
2144                 s = "??";
2145         }
2146         seq_printf(m, "%-16s %s\n", "mstate", s);
2147
2148         seq_printf(m, "%-16s %s\n", "running", cs->running ? "yes" : "no");
2149         seq_printf(m, "%-16s %s\n", "connected", cs->connected ? "yes" : "no");
2150         seq_printf(m, "%-16s %s\n", "isdn_up", cs->isdn_up ? "yes" : "no");
2151         seq_printf(m, "%-16s %s\n", "cidmode", cs->cidmode ? "yes" : "no");
2152
2153         for (i = 0; i < cs->channels; i++) {
2154                 seq_printf(m, "[%d]%-13s %d\n", i, "corrupted",
2155                                 cs->bcs[i].corrupted);
2156                 seq_printf(m, "[%d]%-13s %d\n", i, "trans_down",
2157                                 cs->bcs[i].trans_down);
2158                 seq_printf(m, "[%d]%-13s %d\n", i, "trans_up",
2159                                 cs->bcs[i].trans_up);
2160                 seq_printf(m, "[%d]%-13s %d\n", i, "chstate",
2161                                 cs->bcs[i].chstate);
2162                 switch (cs->bcs[i].proto2) {
2163                 case L2_BITSYNC:
2164                         s = "bitsync";
2165                         break;
2166                 case L2_HDLC:
2167                         s = "HDLC";
2168                         break;
2169                 case L2_VOICE:
2170                         s = "voice";
2171                         break;
2172                 default:
2173                         s = "??";
2174                 }
2175                 seq_printf(m, "[%d]%-13s %s\n", i, "proto2", s);
2176         }
2177         return 0;
2178 }
2179
2180 static int gigaset_proc_open(struct inode *inode, struct file *file)
2181 {
2182         return single_open(file, gigaset_proc_show, PDE(inode)->data);
2183 }
2184
2185 static const struct file_operations gigaset_proc_fops = {
2186         .owner          = THIS_MODULE,
2187         .open           = gigaset_proc_open,
2188         .read           = seq_read,
2189         .llseek         = seq_lseek,
2190         .release        = single_release,
2191 };
2192
2193 /**
2194  * gigaset_isdn_regdev() - register device to LL
2195  * @cs:         device descriptor structure.
2196  * @isdnid:     device name.
2197  *
2198  * Return value: 1 for success, 0 for failure
2199  */
2200 int gigaset_isdn_regdev(struct cardstate *cs, const char *isdnid)
2201 {
2202         struct gigaset_capi_ctr *iif;
2203         int rc;
2204
2205         iif = kmalloc(sizeof(*iif), GFP_KERNEL);
2206         if (!iif) {
2207                 pr_err("%s: out of memory\n", __func__);
2208                 return 0;
2209         }
2210
2211         /* prepare controller structure */
2212         iif->ctr.owner         = THIS_MODULE;
2213         iif->ctr.driverdata    = cs;
2214         strncpy(iif->ctr.name, isdnid, sizeof(iif->ctr.name));
2215         iif->ctr.driver_name   = "gigaset";
2216         iif->ctr.load_firmware = gigaset_load_firmware;
2217         iif->ctr.reset_ctr     = gigaset_reset_ctr;
2218         iif->ctr.register_appl = gigaset_register_appl;
2219         iif->ctr.release_appl  = gigaset_release_appl;
2220         iif->ctr.send_message  = gigaset_send_message;
2221         iif->ctr.procinfo      = gigaset_procinfo;
2222         iif->ctr.proc_fops = &gigaset_proc_fops;
2223         INIT_LIST_HEAD(&iif->appls);
2224         skb_queue_head_init(&iif->sendqueue);
2225         atomic_set(&iif->sendqlen, 0);
2226
2227         /* register controller with CAPI */
2228         rc = attach_capi_ctr(&iif->ctr);
2229         if (rc) {
2230                 pr_err("attach_capi_ctr failed (%d)\n", rc);
2231                 kfree(iif);
2232                 return 0;
2233         }
2234
2235         cs->iif = iif;
2236         cs->hw_hdr_len = CAPI_DATA_B3_REQ_LEN;
2237         return 1;
2238 }
2239
2240 /**
2241  * gigaset_isdn_unregdev() - unregister device from LL
2242  * @cs:         device descriptor structure.
2243  */
2244 void gigaset_isdn_unregdev(struct cardstate *cs)
2245 {
2246         struct gigaset_capi_ctr *iif = cs->iif;
2247
2248         detach_capi_ctr(&iif->ctr);
2249         kfree(iif);
2250         cs->iif = NULL;
2251 }
2252
2253 static struct capi_driver capi_driver_gigaset = {
2254         .name           = "gigaset",
2255         .revision       = "1.0",
2256 };
2257
2258 /**
2259  * gigaset_isdn_regdrv() - register driver to LL
2260  */
2261 void gigaset_isdn_regdrv(void)
2262 {
2263         pr_info("Kernel CAPI interface\n");
2264         register_capi_driver(&capi_driver_gigaset);
2265 }
2266
2267 /**
2268  * gigaset_isdn_unregdrv() - unregister driver from LL
2269  */
2270 void gigaset_isdn_unregdrv(void)
2271 {
2272         unregister_capi_driver(&capi_driver_gigaset);
2273 }