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