1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Common data handling layer for ser_gigaset and usb_gigaset
4  *
5  * Copyright (c) 2005 by Tilman Schmidt <tilman@imap.cc>,
6  *                       Hansjoerg Lipp <hjlipp@web.de>,
7  *                       Stefan Eilers.
8  *
9  * =====================================================================
10  * =====================================================================
11  */
12 
13 #include "gigaset.h"
14 #include <linux/crc-ccitt.h>
15 #include <linux/bitrev.h>
16 #include <linux/export.h>
17 
18 /* check if byte must be stuffed/escaped
19  * I'm not sure which data should be encoded.
20  * Therefore I will go the hard way and encode every value
21  * less than 0x20, the flag sequence and the control escape char.
22  */
muststuff(unsigned char c)23 static inline int muststuff(unsigned char c)
24 {
25 	if (c < PPP_TRANS) return 1;
26 	if (c == PPP_FLAG) return 1;
27 	if (c == PPP_ESCAPE) return 1;
28 	/* other possible candidates: */
29 	/* 0x91: XON with parity set */
30 	/* 0x93: XOFF with parity set */
31 	return 0;
32 }
33 
34 /* == data input =========================================================== */
35 
36 /* process a block of received bytes in command mode
37  * (mstate != MS_LOCKED && (inputstate & INS_command))
38  * Append received bytes to the command response buffer and forward them
39  * line by line to the response handler. Exit whenever a mode/state change
40  * might have occurred.
41  * Note: Received lines may be terminated by CR, LF, or CR LF, which will be
42  * removed before passing the line to the response handler.
43  * Return value:
44  *	number of processed bytes
45  */
cmd_loop(unsigned numbytes,struct inbuf_t * inbuf)46 static unsigned cmd_loop(unsigned numbytes, struct inbuf_t *inbuf)
47 {
48 	unsigned char *src = inbuf->data + inbuf->head;
49 	struct cardstate *cs = inbuf->cs;
50 	unsigned cbytes = cs->cbytes;
51 	unsigned procbytes = 0;
52 	unsigned char c;
53 
54 	while (procbytes < numbytes) {
55 		c = *src++;
56 		procbytes++;
57 
58 		switch (c) {
59 		case '\n':
60 			if (cbytes == 0 && cs->respdata[0] == '\r') {
61 				/* collapse LF with preceding CR */
62 				cs->respdata[0] = 0;
63 				break;
64 			}
65 			/* fall through */
66 		case '\r':
67 			/* end of message line, pass to response handler */
68 			if (cbytes >= MAX_RESP_SIZE) {
69 				dev_warn(cs->dev, "response too large (%d)\n",
70 					 cbytes);
71 				cbytes = MAX_RESP_SIZE;
72 			}
73 			cs->cbytes = cbytes;
74 			gigaset_dbg_buffer(DEBUG_TRANSCMD, "received response",
75 					   cbytes, cs->respdata);
76 			gigaset_handle_modem_response(cs);
77 			cbytes = 0;
78 
79 			/* store EOL byte for CRLF collapsing */
80 			cs->respdata[0] = c;
81 
82 			/* cs->dle may have changed */
83 			if (cs->dle && !(inbuf->inputstate & INS_DLE_command))
84 				inbuf->inputstate &= ~INS_command;
85 
86 			/* return for reevaluating state */
87 			goto exit;
88 
89 		case DLE_FLAG:
90 			if (inbuf->inputstate & INS_DLE_char) {
91 				/* quoted DLE: clear quote flag */
92 				inbuf->inputstate &= ~INS_DLE_char;
93 			} else if (cs->dle ||
94 				   (inbuf->inputstate & INS_DLE_command)) {
95 				/* DLE escape, pass up for handling */
96 				inbuf->inputstate |= INS_DLE_char;
97 				goto exit;
98 			}
99 			/* quoted or not in DLE mode: treat as regular data */
100 			/* fall through */
101 		default:
102 			/* append to line buffer if possible */
103 			if (cbytes < MAX_RESP_SIZE)
104 				cs->respdata[cbytes] = c;
105 			cbytes++;
106 		}
107 	}
108 exit:
109 	cs->cbytes = cbytes;
110 	return procbytes;
111 }
112 
113 /* process a block of received bytes in lock mode
114  * All received bytes are passed unmodified to the tty i/f.
115  * Return value:
116  *	number of processed bytes
117  */
lock_loop(unsigned numbytes,struct inbuf_t * inbuf)118 static unsigned lock_loop(unsigned numbytes, struct inbuf_t *inbuf)
119 {
120 	unsigned char *src = inbuf->data + inbuf->head;
121 
122 	gigaset_dbg_buffer(DEBUG_LOCKCMD, "received response", numbytes, src);
123 	gigaset_if_receive(inbuf->cs, src, numbytes);
124 	return numbytes;
125 }
126 
127 /* process a block of received bytes in HDLC data mode
128  * (mstate != MS_LOCKED && !(inputstate & INS_command) && proto2 == L2_HDLC)
129  * Collect HDLC frames, undoing byte stuffing and watching for DLE escapes.
130  * When a frame is complete, check the FCS and pass valid frames to the LL.
131  * If DLE is encountered, return immediately to let the caller handle it.
132  * Return value:
133  *	number of processed bytes
134  */
hdlc_loop(unsigned numbytes,struct inbuf_t * inbuf)135 static unsigned hdlc_loop(unsigned numbytes, struct inbuf_t *inbuf)
136 {
137 	struct cardstate *cs = inbuf->cs;
138 	struct bc_state *bcs = cs->bcs;
139 	int inputstate = bcs->inputstate;
140 	__u16 fcs = bcs->rx_fcs;
141 	struct sk_buff *skb = bcs->rx_skb;
142 	unsigned char *src = inbuf->data + inbuf->head;
143 	unsigned procbytes = 0;
144 	unsigned char c;
145 
146 	if (inputstate & INS_byte_stuff) {
147 		if (!numbytes)
148 			return 0;
149 		inputstate &= ~INS_byte_stuff;
150 		goto byte_stuff;
151 	}
152 
153 	while (procbytes < numbytes) {
154 		c = *src++;
155 		procbytes++;
156 		if (c == DLE_FLAG) {
157 			if (inputstate & INS_DLE_char) {
158 				/* quoted DLE: clear quote flag */
159 				inputstate &= ~INS_DLE_char;
160 			} else if (cs->dle || (inputstate & INS_DLE_command)) {
161 				/* DLE escape, pass up for handling */
162 				inputstate |= INS_DLE_char;
163 				break;
164 			}
165 		}
166 
167 		if (c == PPP_ESCAPE) {
168 			/* byte stuffing indicator: pull in next byte */
169 			if (procbytes >= numbytes) {
170 				/* end of buffer, save for later processing */
171 				inputstate |= INS_byte_stuff;
172 				break;
173 			}
174 byte_stuff:
175 			c = *src++;
176 			procbytes++;
177 			if (c == DLE_FLAG) {
178 				if (inputstate & INS_DLE_char) {
179 					/* quoted DLE: clear quote flag */
180 					inputstate &= ~INS_DLE_char;
181 				} else if (cs->dle ||
182 					   (inputstate & INS_DLE_command)) {
183 					/* DLE escape, pass up for handling */
184 					inputstate |=
185 						INS_DLE_char | INS_byte_stuff;
186 					break;
187 				}
188 			}
189 			c ^= PPP_TRANS;
190 #ifdef CONFIG_GIGASET_DEBUG
191 			if (!muststuff(c))
192 				gig_dbg(DEBUG_HDLC, "byte stuffed: 0x%02x", c);
193 #endif
194 		} else if (c == PPP_FLAG) {
195 			/* end of frame: process content if any */
196 			if (inputstate & INS_have_data) {
197 				gig_dbg(DEBUG_HDLC,
198 					"7e----------------------------");
199 
200 				/* check and pass received frame */
201 				if (!skb) {
202 					/* skipped frame */
203 					gigaset_isdn_rcv_err(bcs);
204 				} else if (skb->len < 2) {
205 					/* frame too short for FCS */
206 					dev_warn(cs->dev,
207 						 "short frame (%d)\n",
208 						 skb->len);
209 					gigaset_isdn_rcv_err(bcs);
210 					dev_kfree_skb_any(skb);
211 				} else if (fcs != PPP_GOODFCS) {
212 					/* frame check error */
213 					dev_err(cs->dev,
214 						"Checksum failed, %u bytes corrupted!\n",
215 						skb->len);
216 					gigaset_isdn_rcv_err(bcs);
217 					dev_kfree_skb_any(skb);
218 				} else {
219 					/* good frame */
220 					__skb_trim(skb, skb->len - 2);
221 					gigaset_skb_rcvd(bcs, skb);
222 				}
223 
224 				/* prepare reception of next frame */
225 				inputstate &= ~INS_have_data;
226 				skb = gigaset_new_rx_skb(bcs);
227 			} else {
228 				/* empty frame (7E 7E) */
229 #ifdef CONFIG_GIGASET_DEBUG
230 				++bcs->emptycount;
231 #endif
232 				if (!skb) {
233 					/* skipped (?) */
234 					gigaset_isdn_rcv_err(bcs);
235 					skb = gigaset_new_rx_skb(bcs);
236 				}
237 			}
238 
239 			fcs = PPP_INITFCS;
240 			continue;
241 #ifdef CONFIG_GIGASET_DEBUG
242 		} else if (muststuff(c)) {
243 			/* Should not happen. Possible after ZDLE=1<CR><LF>. */
244 			gig_dbg(DEBUG_HDLC, "not byte stuffed: 0x%02x", c);
245 #endif
246 		}
247 
248 		/* regular data byte, append to skb */
249 #ifdef CONFIG_GIGASET_DEBUG
250 		if (!(inputstate & INS_have_data)) {
251 			gig_dbg(DEBUG_HDLC, "7e (%d x) ================",
252 				bcs->emptycount);
253 			bcs->emptycount = 0;
254 		}
255 #endif
256 		inputstate |= INS_have_data;
257 		if (skb) {
258 			if (skb->len >= bcs->rx_bufsize) {
259 				dev_warn(cs->dev, "received packet too long\n");
260 				dev_kfree_skb_any(skb);
261 				/* skip remainder of packet */
262 				bcs->rx_skb = skb = NULL;
263 			} else {
264 				__skb_put_u8(skb, c);
265 				fcs = crc_ccitt_byte(fcs, c);
266 			}
267 		}
268 	}
269 
270 	bcs->inputstate = inputstate;
271 	bcs->rx_fcs = fcs;
272 	return procbytes;
273 }
274 
275 /* process a block of received bytes in transparent data mode
276  * (mstate != MS_LOCKED && !(inputstate & INS_command) && proto2 != L2_HDLC)
277  * Invert bytes, undoing byte stuffing and watching for DLE escapes.
278  * If DLE is encountered, return immediately to let the caller handle it.
279  * Return value:
280  *	number of processed bytes
281  */
iraw_loop(unsigned numbytes,struct inbuf_t * inbuf)282 static unsigned iraw_loop(unsigned numbytes, struct inbuf_t *inbuf)
283 {
284 	struct cardstate *cs = inbuf->cs;
285 	struct bc_state *bcs = cs->bcs;
286 	int inputstate = bcs->inputstate;
287 	struct sk_buff *skb = bcs->rx_skb;
288 	unsigned char *src = inbuf->data + inbuf->head;
289 	unsigned procbytes = 0;
290 	unsigned char c;
291 
292 	if (!skb) {
293 		/* skip this block */
294 		gigaset_new_rx_skb(bcs);
295 		return numbytes;
296 	}
297 
298 	while (procbytes < numbytes && skb->len < bcs->rx_bufsize) {
299 		c = *src++;
300 		procbytes++;
301 
302 		if (c == DLE_FLAG) {
303 			if (inputstate & INS_DLE_char) {
304 				/* quoted DLE: clear quote flag */
305 				inputstate &= ~INS_DLE_char;
306 			} else if (cs->dle || (inputstate & INS_DLE_command)) {
307 				/* DLE escape, pass up for handling */
308 				inputstate |= INS_DLE_char;
309 				break;
310 			}
311 		}
312 
313 		/* regular data byte: append to current skb */
314 		inputstate |= INS_have_data;
315 		__skb_put_u8(skb, bitrev8(c));
316 	}
317 
318 	/* pass data up */
319 	if (inputstate & INS_have_data) {
320 		gigaset_skb_rcvd(bcs, skb);
321 		inputstate &= ~INS_have_data;
322 		gigaset_new_rx_skb(bcs);
323 	}
324 
325 	bcs->inputstate = inputstate;
326 	return procbytes;
327 }
328 
329 /* process DLE escapes
330  * Called whenever a DLE sequence might be encountered in the input stream.
331  * Either processes the entire DLE sequence or, if that isn't possible,
332  * notes the fact that an initial DLE has been received in the INS_DLE_char
333  * inputstate flag and resumes processing of the sequence on the next call.
334  */
handle_dle(struct inbuf_t * inbuf)335 static void handle_dle(struct inbuf_t *inbuf)
336 {
337 	struct cardstate *cs = inbuf->cs;
338 
339 	if (cs->mstate == MS_LOCKED)
340 		return;		/* no DLE processing in lock mode */
341 
342 	if (!(inbuf->inputstate & INS_DLE_char)) {
343 		/* no DLE pending */
344 		if (inbuf->data[inbuf->head] == DLE_FLAG &&
345 		    (cs->dle || inbuf->inputstate & INS_DLE_command)) {
346 			/* start of DLE sequence */
347 			inbuf->head++;
348 			if (inbuf->head == inbuf->tail ||
349 			    inbuf->head == RBUFSIZE) {
350 				/* end of buffer, save for later processing */
351 				inbuf->inputstate |= INS_DLE_char;
352 				return;
353 			}
354 		} else {
355 			/* regular data byte */
356 			return;
357 		}
358 	}
359 
360 	/* consume pending DLE */
361 	inbuf->inputstate &= ~INS_DLE_char;
362 
363 	switch (inbuf->data[inbuf->head]) {
364 	case 'X':	/* begin of event message */
365 		if (inbuf->inputstate & INS_command)
366 			dev_notice(cs->dev,
367 				   "received <DLE>X in command mode\n");
368 		inbuf->inputstate |= INS_command | INS_DLE_command;
369 		inbuf->head++;	/* byte consumed */
370 		break;
371 	case '.':	/* end of event message */
372 		if (!(inbuf->inputstate & INS_DLE_command))
373 			dev_notice(cs->dev,
374 				   "received <DLE>. without <DLE>X\n");
375 		inbuf->inputstate &= ~INS_DLE_command;
376 		/* return to data mode if in DLE mode */
377 		if (cs->dle)
378 			inbuf->inputstate &= ~INS_command;
379 		inbuf->head++;	/* byte consumed */
380 		break;
381 	case DLE_FLAG:	/* DLE in data stream */
382 		/* mark as quoted */
383 		inbuf->inputstate |= INS_DLE_char;
384 		if (!(cs->dle || inbuf->inputstate & INS_DLE_command))
385 			dev_notice(cs->dev,
386 				   "received <DLE><DLE> not in DLE mode\n");
387 		break;	/* quoted byte left in buffer */
388 	default:
389 		dev_notice(cs->dev, "received <DLE><%02x>\n",
390 			   inbuf->data[inbuf->head]);
391 		/* quoted byte left in buffer */
392 	}
393 }
394 
395 /**
396  * gigaset_m10x_input() - process a block of data received from the device
397  * @inbuf:	received data and device descriptor structure.
398  *
399  * Called by hardware module {ser,usb}_gigaset with a block of received
400  * bytes. Separates the bytes received over the serial data channel into
401  * user data and command replies (locked/unlocked) according to the
402  * current state of the interface.
403  */
gigaset_m10x_input(struct inbuf_t * inbuf)404 void gigaset_m10x_input(struct inbuf_t *inbuf)
405 {
406 	struct cardstate *cs = inbuf->cs;
407 	unsigned numbytes, procbytes;
408 
409 	gig_dbg(DEBUG_INTR, "buffer state: %u -> %u", inbuf->head, inbuf->tail);
410 
411 	while (inbuf->head != inbuf->tail) {
412 		/* check for DLE escape */
413 		handle_dle(inbuf);
414 
415 		/* process a contiguous block of bytes */
416 		numbytes = (inbuf->head > inbuf->tail ?
417 			    RBUFSIZE : inbuf->tail) - inbuf->head;
418 		gig_dbg(DEBUG_INTR, "processing %u bytes", numbytes);
419 		/*
420 		 * numbytes may be 0 if handle_dle() ate the last byte.
421 		 * This does no harm, *_loop() will just return 0 immediately.
422 		 */
423 
424 		if (cs->mstate == MS_LOCKED)
425 			procbytes = lock_loop(numbytes, inbuf);
426 		else if (inbuf->inputstate & INS_command)
427 			procbytes = cmd_loop(numbytes, inbuf);
428 		else if (cs->bcs->proto2 == L2_HDLC)
429 			procbytes = hdlc_loop(numbytes, inbuf);
430 		else
431 			procbytes = iraw_loop(numbytes, inbuf);
432 		inbuf->head += procbytes;
433 
434 		/* check for buffer wraparound */
435 		if (inbuf->head >= RBUFSIZE)
436 			inbuf->head = 0;
437 
438 		gig_dbg(DEBUG_INTR, "head set to %u", inbuf->head);
439 	}
440 }
441 EXPORT_SYMBOL_GPL(gigaset_m10x_input);
442 
443 
444 /* == data output ========================================================== */
445 
446 /*
447  * Encode a data packet into an octet stuffed HDLC frame with FCS,
448  * opening and closing flags, preserving headroom data.
449  * parameters:
450  *	skb		skb containing original packet (freed upon return)
451  * Return value:
452  *	pointer to newly allocated skb containing the result frame
453  *	and the original link layer header, NULL on error
454  */
HDLC_Encode(struct sk_buff * skb)455 static struct sk_buff *HDLC_Encode(struct sk_buff *skb)
456 {
457 	struct sk_buff *hdlc_skb;
458 	__u16 fcs;
459 	unsigned char c;
460 	unsigned char *cp;
461 	int len;
462 	unsigned int stuf_cnt;
463 
464 	stuf_cnt = 0;
465 	fcs = PPP_INITFCS;
466 	cp = skb->data;
467 	len = skb->len;
468 	while (len--) {
469 		if (muststuff(*cp))
470 			stuf_cnt++;
471 		fcs = crc_ccitt_byte(fcs, *cp++);
472 	}
473 	fcs ^= 0xffff;			/* complement */
474 
475 	/* size of new buffer: original size + number of stuffing bytes
476 	 * + 2 bytes FCS + 2 stuffing bytes for FCS (if needed) + 2 flag bytes
477 	 * + room for link layer header
478 	 */
479 	hdlc_skb = dev_alloc_skb(skb->len + stuf_cnt + 6 + skb->mac_len);
480 	if (!hdlc_skb) {
481 		dev_kfree_skb_any(skb);
482 		return NULL;
483 	}
484 
485 	/* Copy link layer header into new skb */
486 	skb_reset_mac_header(hdlc_skb);
487 	skb_reserve(hdlc_skb, skb->mac_len);
488 	memcpy(skb_mac_header(hdlc_skb), skb_mac_header(skb), skb->mac_len);
489 	hdlc_skb->mac_len = skb->mac_len;
490 
491 	/* Add flag sequence in front of everything.. */
492 	skb_put_u8(hdlc_skb, PPP_FLAG);
493 
494 	/* Perform byte stuffing while copying data. */
495 	while (skb->len--) {
496 		if (muststuff(*skb->data)) {
497 			skb_put_u8(hdlc_skb, PPP_ESCAPE);
498 			skb_put_u8(hdlc_skb, (*skb->data++) ^ PPP_TRANS);
499 		} else
500 			skb_put_u8(hdlc_skb, *skb->data++);
501 	}
502 
503 	/* Finally add FCS (byte stuffed) and flag sequence */
504 	c = (fcs & 0x00ff);	/* least significant byte first */
505 	if (muststuff(c)) {
506 		skb_put_u8(hdlc_skb, PPP_ESCAPE);
507 		c ^= PPP_TRANS;
508 	}
509 	skb_put_u8(hdlc_skb, c);
510 
511 	c = ((fcs >> 8) & 0x00ff);
512 	if (muststuff(c)) {
513 		skb_put_u8(hdlc_skb, PPP_ESCAPE);
514 		c ^= PPP_TRANS;
515 	}
516 	skb_put_u8(hdlc_skb, c);
517 
518 	skb_put_u8(hdlc_skb, PPP_FLAG);
519 
520 	dev_kfree_skb_any(skb);
521 	return hdlc_skb;
522 }
523 
524 /*
525  * Encode a data packet into an octet stuffed raw bit inverted frame,
526  * preserving headroom data.
527  * parameters:
528  *	skb		skb containing original packet (freed upon return)
529  * Return value:
530  *	pointer to newly allocated skb containing the result frame
531  *	and the original link layer header, NULL on error
532  */
iraw_encode(struct sk_buff * skb)533 static struct sk_buff *iraw_encode(struct sk_buff *skb)
534 {
535 	struct sk_buff *iraw_skb;
536 	unsigned char c;
537 	unsigned char *cp;
538 	int len;
539 
540 	/* size of new buffer (worst case = every byte must be stuffed):
541 	 * 2 * original size + room for link layer header
542 	 */
543 	iraw_skb = dev_alloc_skb(2 * skb->len + skb->mac_len);
544 	if (!iraw_skb) {
545 		dev_kfree_skb_any(skb);
546 		return NULL;
547 	}
548 
549 	/* copy link layer header into new skb */
550 	skb_reset_mac_header(iraw_skb);
551 	skb_reserve(iraw_skb, skb->mac_len);
552 	memcpy(skb_mac_header(iraw_skb), skb_mac_header(skb), skb->mac_len);
553 	iraw_skb->mac_len = skb->mac_len;
554 
555 	/* copy and stuff data */
556 	cp = skb->data;
557 	len = skb->len;
558 	while (len--) {
559 		c = bitrev8(*cp++);
560 		if (c == DLE_FLAG)
561 			skb_put_u8(iraw_skb, c);
562 		skb_put_u8(iraw_skb, c);
563 	}
564 	dev_kfree_skb_any(skb);
565 	return iraw_skb;
566 }
567 
568 /**
569  * gigaset_m10x_send_skb() - queue an skb for sending
570  * @bcs:	B channel descriptor structure.
571  * @skb:	data to send.
572  *
573  * Called by LL to encode and queue an skb for sending, and start
574  * transmission if necessary.
575  * Once the payload data has been transmitted completely, gigaset_skb_sent()
576  * will be called with the skb's link layer header preserved.
577  *
578  * Return value:
579  *	number of bytes accepted for sending (skb->len) if ok,
580  *	error code < 0 (eg. -ENOMEM) on error
581  */
gigaset_m10x_send_skb(struct bc_state * bcs,struct sk_buff * skb)582 int gigaset_m10x_send_skb(struct bc_state *bcs, struct sk_buff *skb)
583 {
584 	struct cardstate *cs = bcs->cs;
585 	unsigned len = skb->len;
586 	unsigned long flags;
587 
588 	if (bcs->proto2 == L2_HDLC)
589 		skb = HDLC_Encode(skb);
590 	else
591 		skb = iraw_encode(skb);
592 	if (!skb) {
593 		dev_err(cs->dev,
594 			"unable to allocate memory for encoding!\n");
595 		return -ENOMEM;
596 	}
597 
598 	skb_queue_tail(&bcs->squeue, skb);
599 	spin_lock_irqsave(&cs->lock, flags);
600 	if (cs->connected)
601 		tasklet_schedule(&cs->write_tasklet);
602 	spin_unlock_irqrestore(&cs->lock, flags);
603 
604 	return len;	/* ok so far */
605 }
606 EXPORT_SYMBOL_GPL(gigaset_m10x_send_skb);
607