1 /*
2  *  Copyright (C) 2014, Samsung Electronics Co. Ltd. All Rights Reserved.
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  */
15 
16 #include "ssp.h"
17 
18 #define SSP_DEV (&data->spi->dev)
19 #define SSP_GET_MESSAGE_TYPE(data) (data & (3 << SSP_RW))
20 
21 /*
22  * SSP -> AP Instruction
23  * They tell what packet type can be expected. In the future there will
24  * be less of them. BYPASS means common sensor packets with accel, gyro,
25  * hrm etc. data. LIBRARY and META are mock-up's for now.
26  */
27 #define SSP_MSG2AP_INST_BYPASS_DATA		0x37
28 #define SSP_MSG2AP_INST_LIBRARY_DATA		0x01
29 #define SSP_MSG2AP_INST_DEBUG_DATA		0x03
30 #define SSP_MSG2AP_INST_BIG_DATA		0x04
31 #define SSP_MSG2AP_INST_META_DATA		0x05
32 #define SSP_MSG2AP_INST_TIME_SYNC		0x06
33 #define SSP_MSG2AP_INST_RESET			0x07
34 
35 #define SSP_UNIMPLEMENTED -1
36 
37 struct ssp_msg_header {
38 	u8 cmd;
39 	__le16 length;
40 	__le16 options;
41 	__le32 data;
42 } __attribute__((__packed__));
43 
44 struct ssp_msg {
45 	u16 length;
46 	u16 options;
47 	struct list_head list;
48 	struct completion *done;
49 	struct ssp_msg_header *h;
50 	char *buffer;
51 };
52 
53 static const int ssp_offset_map[SSP_SENSOR_MAX] = {
54 	[SSP_ACCELEROMETER_SENSOR] =		SSP_ACCELEROMETER_SIZE +
55 						SSP_TIME_SIZE,
56 	[SSP_GYROSCOPE_SENSOR] =		SSP_GYROSCOPE_SIZE +
57 						SSP_TIME_SIZE,
58 	[SSP_GEOMAGNETIC_UNCALIB_SENSOR] =	SSP_UNIMPLEMENTED,
59 	[SSP_GEOMAGNETIC_RAW] =			SSP_UNIMPLEMENTED,
60 	[SSP_GEOMAGNETIC_SENSOR] =		SSP_UNIMPLEMENTED,
61 	[SSP_PRESSURE_SENSOR] =			SSP_UNIMPLEMENTED,
62 	[SSP_GESTURE_SENSOR] =			SSP_UNIMPLEMENTED,
63 	[SSP_PROXIMITY_SENSOR] =		SSP_UNIMPLEMENTED,
64 	[SSP_TEMPERATURE_HUMIDITY_SENSOR] =	SSP_UNIMPLEMENTED,
65 	[SSP_LIGHT_SENSOR] =			SSP_UNIMPLEMENTED,
66 	[SSP_PROXIMITY_RAW] =			SSP_UNIMPLEMENTED,
67 	[SSP_ORIENTATION_SENSOR] =		SSP_UNIMPLEMENTED,
68 	[SSP_STEP_DETECTOR] =			SSP_UNIMPLEMENTED,
69 	[SSP_SIG_MOTION_SENSOR] =		SSP_UNIMPLEMENTED,
70 	[SSP_GYRO_UNCALIB_SENSOR] =		SSP_UNIMPLEMENTED,
71 	[SSP_GAME_ROTATION_VECTOR] =		SSP_UNIMPLEMENTED,
72 	[SSP_ROTATION_VECTOR] =			SSP_UNIMPLEMENTED,
73 	[SSP_STEP_COUNTER] =			SSP_UNIMPLEMENTED,
74 	[SSP_BIO_HRM_RAW] =			SSP_BIO_HRM_RAW_SIZE +
75 						SSP_TIME_SIZE,
76 	[SSP_BIO_HRM_RAW_FAC] =			SSP_BIO_HRM_RAW_FAC_SIZE +
77 						SSP_TIME_SIZE,
78 	[SSP_BIO_HRM_LIB] =			SSP_BIO_HRM_LIB_SIZE +
79 						SSP_TIME_SIZE,
80 };
81 
82 #define SSP_HEADER_SIZE		(sizeof(struct ssp_msg_header))
83 #define SSP_HEADER_SIZE_ALIGNED	(ALIGN(SSP_HEADER_SIZE, 4))
84 
85 static struct ssp_msg *ssp_create_msg(u8 cmd, u16 len, u16 opt, u32 data)
86 {
87 	struct ssp_msg_header h;
88 	struct ssp_msg *msg;
89 
90 	msg = kzalloc(sizeof(*msg), GFP_KERNEL);
91 	if (!msg)
92 		return NULL;
93 
94 	h.cmd = cmd;
95 	h.length = cpu_to_le16(len);
96 	h.options = cpu_to_le16(opt);
97 	h.data = cpu_to_le32(data);
98 
99 	msg->buffer = kzalloc(SSP_HEADER_SIZE_ALIGNED + len,
100 			      GFP_KERNEL | GFP_DMA);
101 	if (!msg->buffer) {
102 		kfree(msg);
103 		return NULL;
104 	}
105 
106 	msg->length = len;
107 	msg->options = opt;
108 
109 	memcpy(msg->buffer, &h, SSP_HEADER_SIZE);
110 
111 	return msg;
112 }
113 
114 /*
115  * It is a bit heavy to do it this way but often the function is used to compose
116  * the message from smaller chunks which are placed on the stack.  Often the
117  * chunks are small so memcpy should be optimalized.
118  */
119 static inline void ssp_fill_buffer(struct ssp_msg *m, unsigned int offset,
120 				   const void *src, unsigned int len)
121 {
122 	memcpy(&m->buffer[SSP_HEADER_SIZE_ALIGNED + offset], src, len);
123 }
124 
125 static inline void ssp_get_buffer(struct ssp_msg *m, unsigned int offset,
126 				  void *dest, unsigned int len)
127 {
128 	memcpy(dest, &m->buffer[SSP_HEADER_SIZE_ALIGNED + offset],  len);
129 }
130 
131 #define SSP_GET_BUFFER_AT_INDEX(m, index) \
132 	(m->buffer[SSP_HEADER_SIZE_ALIGNED + index])
133 #define SSP_SET_BUFFER_AT_INDEX(m, index, val) \
134 	(m->buffer[SSP_HEADER_SIZE_ALIGNED + index] = val)
135 
136 static void ssp_clean_msg(struct ssp_msg *m)
137 {
138 	kfree(m->buffer);
139 	kfree(m);
140 }
141 
142 static int ssp_print_mcu_debug(char *data_frame, int *data_index,
143 			       int received_len)
144 {
145 	int length = data_frame[(*data_index)++];
146 
147 	if (length > received_len - *data_index || length <= 0) {
148 		ssp_dbg("[SSP]: MSG From MCU-invalid debug length(%d/%d)\n",
149 			length, received_len);
150 		return length ? length : -EPROTO;
151 	}
152 
153 	ssp_dbg("[SSP]: MSG From MCU - %s\n", &data_frame[*data_index]);
154 
155 	*data_index += length;
156 
157 	return 0;
158 }
159 
160 /*
161  * It was designed that way - additional lines to some kind of handshake,
162  * please do not ask why - only the firmware guy can know it.
163  */
164 static int ssp_check_lines(struct ssp_data *data, bool state)
165 {
166 	int delay_cnt = 0;
167 
168 	gpio_set_value_cansleep(data->ap_mcu_gpio, state);
169 
170 	while (gpio_get_value_cansleep(data->mcu_ap_gpio) != state) {
171 		usleep_range(3000, 3500);
172 
173 		if (data->shut_down || delay_cnt++ > 500) {
174 			dev_err(SSP_DEV, "%s:timeout, hw ack wait fail %d\n",
175 				__func__, state);
176 
177 			if (!state)
178 				gpio_set_value_cansleep(data->ap_mcu_gpio, 1);
179 
180 			return -ETIMEDOUT;
181 		}
182 	}
183 
184 	return 0;
185 }
186 
187 static int ssp_do_transfer(struct ssp_data *data, struct ssp_msg *msg,
188 			   struct completion *done, int timeout)
189 {
190 	int status;
191 	/*
192 	 * check if this is a short one way message or the whole transfer has
193 	 * second part after an interrupt
194 	 */
195 	const bool use_no_irq = msg->length == 0;
196 
197 	if (data->shut_down)
198 		return -EPERM;
199 
200 	msg->done = done;
201 
202 	mutex_lock(&data->comm_lock);
203 
204 	status = ssp_check_lines(data, false);
205 	if (status < 0)
206 		goto _error_locked;
207 
208 	status = spi_write(data->spi, msg->buffer, SSP_HEADER_SIZE);
209 	if (status < 0) {
210 		gpio_set_value_cansleep(data->ap_mcu_gpio, 1);
211 		dev_err(SSP_DEV, "%s spi_write fail\n", __func__);
212 		goto _error_locked;
213 	}
214 
215 	if (!use_no_irq) {
216 		mutex_lock(&data->pending_lock);
217 		list_add_tail(&msg->list, &data->pending_list);
218 		mutex_unlock(&data->pending_lock);
219 	}
220 
221 	status = ssp_check_lines(data, true);
222 	if (status < 0) {
223 		if (!use_no_irq) {
224 			mutex_lock(&data->pending_lock);
225 			list_del(&msg->list);
226 			mutex_unlock(&data->pending_lock);
227 		}
228 		goto _error_locked;
229 	}
230 
231 	mutex_unlock(&data->comm_lock);
232 
233 	if (!use_no_irq && done)
234 		if (wait_for_completion_timeout(done,
235 						msecs_to_jiffies(timeout)) ==
236 		    0) {
237 			mutex_lock(&data->pending_lock);
238 			list_del(&msg->list);
239 			mutex_unlock(&data->pending_lock);
240 
241 			data->timeout_cnt++;
242 			return -ETIMEDOUT;
243 		}
244 
245 	return 0;
246 
247 _error_locked:
248 	mutex_unlock(&data->comm_lock);
249 	data->timeout_cnt++;
250 	return status;
251 }
252 
253 static inline int ssp_spi_sync_command(struct ssp_data *data,
254 				       struct ssp_msg *msg)
255 {
256 	return ssp_do_transfer(data, msg, NULL, 0);
257 }
258 
259 static int ssp_spi_sync(struct ssp_data *data, struct ssp_msg *msg,
260 			int timeout)
261 {
262 	DECLARE_COMPLETION_ONSTACK(done);
263 
264 	if (WARN_ON(!msg->length))
265 		return -EPERM;
266 
267 	return ssp_do_transfer(data, msg, &done, timeout);
268 }
269 
270 static int ssp_handle_big_data(struct ssp_data *data, char *dataframe, int *idx)
271 {
272 	/* mock-up, it will be changed with adding another sensor types */
273 	*idx += 8;
274 	return 0;
275 }
276 
277 static int ssp_parse_dataframe(struct ssp_data *data, char *dataframe, int len)
278 {
279 	int idx, sd;
280 	struct timespec ts;
281 	struct ssp_sensor_data *spd;
282 	struct iio_dev **indio_devs = data->sensor_devs;
283 
284 	getnstimeofday(&ts);
285 
286 	for (idx = 0; idx < len;) {
287 		switch (dataframe[idx++]) {
288 		case SSP_MSG2AP_INST_BYPASS_DATA:
289 			sd = dataframe[idx++];
290 			if (sd < 0 || sd >= SSP_SENSOR_MAX) {
291 				dev_err(SSP_DEV,
292 					"Mcu data frame1 error %d\n", sd);
293 				return -EPROTO;
294 			}
295 
296 			if (indio_devs[sd]) {
297 				spd = iio_priv(indio_devs[sd]);
298 				if (spd->process_data)
299 					spd->process_data(indio_devs[sd],
300 							  &dataframe[idx],
301 							  data->timestamp);
302 			} else {
303 				dev_err(SSP_DEV, "no client for frame\n");
304 			}
305 
306 			idx += ssp_offset_map[sd];
307 			break;
308 		case SSP_MSG2AP_INST_DEBUG_DATA:
309 			sd = ssp_print_mcu_debug(dataframe, &idx, len);
310 			if (sd) {
311 				dev_err(SSP_DEV,
312 					"Mcu data frame3 error %d\n", sd);
313 				return sd;
314 			}
315 			break;
316 		case SSP_MSG2AP_INST_LIBRARY_DATA:
317 			idx += len;
318 			break;
319 		case SSP_MSG2AP_INST_BIG_DATA:
320 			ssp_handle_big_data(data, dataframe, &idx);
321 			break;
322 		case SSP_MSG2AP_INST_TIME_SYNC:
323 			data->time_syncing = true;
324 			break;
325 		case SSP_MSG2AP_INST_RESET:
326 			ssp_queue_ssp_refresh_task(data, 0);
327 			break;
328 		}
329 	}
330 
331 	if (data->time_syncing)
332 		data->timestamp = ts.tv_sec * 1000000000ULL + ts.tv_nsec;
333 
334 	return 0;
335 }
336 
337 /* threaded irq */
338 int ssp_irq_msg(struct ssp_data *data)
339 {
340 	bool found = false;
341 	char *buffer;
342 	u8 msg_type;
343 	int ret;
344 	u16 length, msg_options;
345 	struct ssp_msg *msg, *n;
346 
347 	ret = spi_read(data->spi, data->header_buffer, SSP_HEADER_BUFFER_SIZE);
348 	if (ret < 0) {
349 		dev_err(SSP_DEV, "header read fail\n");
350 		return ret;
351 	}
352 
353 	length = le16_to_cpu(data->header_buffer[1]);
354 	msg_options = le16_to_cpu(data->header_buffer[0]);
355 
356 	if (length == 0) {
357 		dev_err(SSP_DEV, "length received from mcu is 0\n");
358 		return -EINVAL;
359 	}
360 
361 	msg_type = SSP_GET_MESSAGE_TYPE(msg_options);
362 
363 	switch (msg_type) {
364 	case SSP_AP2HUB_READ:
365 	case SSP_AP2HUB_WRITE:
366 		/*
367 		 * this is a small list, a few elements - the packets can be
368 		 * received with no order
369 		 */
370 		mutex_lock(&data->pending_lock);
371 		list_for_each_entry_safe(msg, n, &data->pending_list, list) {
372 			if (msg->options == msg_options) {
373 				list_del(&msg->list);
374 				found = true;
375 				break;
376 			}
377 		}
378 
379 		if (!found) {
380 			/*
381 			 * here can be implemented dead messages handling
382 			 * but the slave should not send such ones - it is to
383 			 * check but let's handle this
384 			 */
385 			buffer = kmalloc(length, GFP_KERNEL | GFP_DMA);
386 			if (!buffer) {
387 				ret = -ENOMEM;
388 				goto _unlock;
389 			}
390 
391 			/* got dead packet so it is always an error */
392 			ret = spi_read(data->spi, buffer, length);
393 			if (ret >= 0)
394 				ret = -EPROTO;
395 
396 			kfree(buffer);
397 
398 			dev_err(SSP_DEV, "No match error %x\n",
399 				msg_options);
400 
401 			goto _unlock;
402 		}
403 
404 		if (msg_type == SSP_AP2HUB_READ)
405 			ret = spi_read(data->spi,
406 				       &msg->buffer[SSP_HEADER_SIZE_ALIGNED],
407 				       msg->length);
408 
409 		if (msg_type == SSP_AP2HUB_WRITE) {
410 			ret = spi_write(data->spi,
411 					&msg->buffer[SSP_HEADER_SIZE_ALIGNED],
412 					msg->length);
413 			if (msg_options & SSP_AP2HUB_RETURN) {
414 				msg->options =
415 					SSP_AP2HUB_READ | SSP_AP2HUB_RETURN;
416 				msg->length = 1;
417 
418 				list_add_tail(&msg->list, &data->pending_list);
419 				goto _unlock;
420 			}
421 		}
422 
423 		if (msg->done)
424 			if (!completion_done(msg->done))
425 				complete(msg->done);
426 _unlock:
427 		mutex_unlock(&data->pending_lock);
428 		break;
429 	case SSP_HUB2AP_WRITE:
430 		buffer = kzalloc(length, GFP_KERNEL | GFP_DMA);
431 		if (!buffer)
432 			return -ENOMEM;
433 
434 		ret = spi_read(data->spi, buffer, length);
435 		if (ret < 0) {
436 			dev_err(SSP_DEV, "spi read fail\n");
437 			kfree(buffer);
438 			break;
439 		}
440 
441 		ret = ssp_parse_dataframe(data, buffer, length);
442 
443 		kfree(buffer);
444 		break;
445 
446 	default:
447 		dev_err(SSP_DEV, "unknown msg type\n");
448 		return -EPROTO;
449 	}
450 
451 	return ret;
452 }
453 
454 void ssp_clean_pending_list(struct ssp_data *data)
455 {
456 	struct ssp_msg *msg, *n;
457 
458 	mutex_lock(&data->pending_lock);
459 	list_for_each_entry_safe(msg, n, &data->pending_list, list) {
460 		list_del(&msg->list);
461 
462 		if (msg->done)
463 			if (!completion_done(msg->done))
464 				complete(msg->done);
465 	}
466 	mutex_unlock(&data->pending_lock);
467 }
468 
469 int ssp_command(struct ssp_data *data, char command, int arg)
470 {
471 	int ret;
472 	struct ssp_msg *msg;
473 
474 	msg = ssp_create_msg(command, 0, SSP_AP2HUB_WRITE, arg);
475 	if (!msg)
476 		return -ENOMEM;
477 
478 	ssp_dbg("%s - command 0x%x %d\n", __func__, command, arg);
479 
480 	ret = ssp_spi_sync_command(data, msg);
481 	ssp_clean_msg(msg);
482 
483 	return ret;
484 }
485 
486 int ssp_send_instruction(struct ssp_data *data, u8 inst, u8 sensor_type,
487 			 u8 *send_buf, u8 length)
488 {
489 	int ret;
490 	struct ssp_msg *msg;
491 
492 	if (data->fw_dl_state == SSP_FW_DL_STATE_DOWNLOADING) {
493 		dev_err(SSP_DEV, "%s - Skip Inst! DL state = %d\n",
494 			__func__, data->fw_dl_state);
495 		return -EBUSY;
496 	} else if (!(data->available_sensors & BIT(sensor_type)) &&
497 		   (inst <= SSP_MSG2SSP_INST_CHANGE_DELAY)) {
498 		dev_err(SSP_DEV, "%s - Bypass Inst Skip! - %u\n",
499 			__func__, sensor_type);
500 		return -EIO; /* just fail */
501 	}
502 
503 	msg = ssp_create_msg(inst, length + 2, SSP_AP2HUB_WRITE, 0);
504 	if (!msg)
505 		return -ENOMEM;
506 
507 	ssp_fill_buffer(msg, 0, &sensor_type, 1);
508 	ssp_fill_buffer(msg, 1, send_buf, length);
509 
510 	ssp_dbg("%s - Inst = 0x%x, Sensor Type = 0x%x, data = %u\n",
511 		__func__, inst, sensor_type, send_buf[1]);
512 
513 	ret = ssp_spi_sync(data, msg, 1000);
514 	ssp_clean_msg(msg);
515 
516 	return ret;
517 }
518 
519 int ssp_get_chipid(struct ssp_data *data)
520 {
521 	int ret;
522 	char buffer;
523 	struct ssp_msg *msg;
524 
525 	msg = ssp_create_msg(SSP_MSG2SSP_AP_WHOAMI, 1, SSP_AP2HUB_READ, 0);
526 	if (!msg)
527 		return -ENOMEM;
528 
529 	ret = ssp_spi_sync(data, msg, 1000);
530 
531 	buffer = SSP_GET_BUFFER_AT_INDEX(msg, 0);
532 
533 	ssp_clean_msg(msg);
534 
535 	return ret < 0 ? ret : buffer;
536 }
537 
538 int ssp_set_magnetic_matrix(struct ssp_data *data)
539 {
540 	int ret;
541 	struct ssp_msg *msg;
542 
543 	msg = ssp_create_msg(SSP_MSG2SSP_AP_SET_MAGNETIC_STATIC_MATRIX,
544 			     data->sensorhub_info->mag_length, SSP_AP2HUB_WRITE,
545 			     0);
546 	if (!msg)
547 		return -ENOMEM;
548 
549 	ssp_fill_buffer(msg, 0, data->sensorhub_info->mag_table,
550 			data->sensorhub_info->mag_length);
551 
552 	ret = ssp_spi_sync(data, msg, 1000);
553 	ssp_clean_msg(msg);
554 
555 	return ret;
556 }
557 
558 unsigned int ssp_get_sensor_scanning_info(struct ssp_data *data)
559 {
560 	int ret;
561 	__le32 result;
562 	u32 cpu_result = 0;
563 
564 	struct ssp_msg *msg = ssp_create_msg(SSP_MSG2SSP_AP_SENSOR_SCANNING, 4,
565 					     SSP_AP2HUB_READ, 0);
566 	if (!msg)
567 		return 0;
568 
569 	ret = ssp_spi_sync(data, msg, 1000);
570 	if (ret < 0) {
571 		dev_err(SSP_DEV, "%s - spi read fail %d\n", __func__, ret);
572 		goto _exit;
573 	}
574 
575 	ssp_get_buffer(msg, 0, &result, 4);
576 	cpu_result = le32_to_cpu(result);
577 
578 	dev_info(SSP_DEV, "%s state: 0x%08x\n", __func__, cpu_result);
579 
580 _exit:
581 	ssp_clean_msg(msg);
582 	return cpu_result;
583 }
584 
585 unsigned int ssp_get_firmware_rev(struct ssp_data *data)
586 {
587 	int ret;
588 	__le32 result;
589 
590 	struct ssp_msg *msg = ssp_create_msg(SSP_MSG2SSP_AP_FIRMWARE_REV, 4,
591 					     SSP_AP2HUB_READ, 0);
592 	if (!msg)
593 		return SSP_INVALID_REVISION;
594 
595 	ret = ssp_spi_sync(data, msg, 1000);
596 	if (ret < 0) {
597 		dev_err(SSP_DEV, "%s - transfer fail %d\n", __func__, ret);
598 		ret = SSP_INVALID_REVISION;
599 		goto _exit;
600 	}
601 
602 	ssp_get_buffer(msg, 0, &result, 4);
603 	ret = le32_to_cpu(result);
604 
605 _exit:
606 	ssp_clean_msg(msg);
607 	return ret;
608 }
609