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