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