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