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