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