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