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 ssp_sensor_data *spd;
281 	struct iio_dev **indio_devs = data->sensor_devs;
282 
283 	for (idx = 0; idx < len;) {
284 		switch (dataframe[idx++]) {
285 		case SSP_MSG2AP_INST_BYPASS_DATA:
286 			sd = dataframe[idx++];
287 			if (sd < 0 || sd >= SSP_SENSOR_MAX) {
288 				dev_err(SSP_DEV,
289 					"Mcu data frame1 error %d\n", sd);
290 				return -EPROTO;
291 			}
292 
293 			if (indio_devs[sd]) {
294 				spd = iio_priv(indio_devs[sd]);
295 				if (spd->process_data)
296 					spd->process_data(indio_devs[sd],
297 							  &dataframe[idx],
298 							  data->timestamp);
299 			} else {
300 				dev_err(SSP_DEV, "no client for frame\n");
301 			}
302 
303 			idx += ssp_offset_map[sd];
304 			break;
305 		case SSP_MSG2AP_INST_DEBUG_DATA:
306 			sd = ssp_print_mcu_debug(dataframe, &idx, len);
307 			if (sd) {
308 				dev_err(SSP_DEV,
309 					"Mcu data frame3 error %d\n", sd);
310 				return sd;
311 			}
312 			break;
313 		case SSP_MSG2AP_INST_LIBRARY_DATA:
314 			idx += len;
315 			break;
316 		case SSP_MSG2AP_INST_BIG_DATA:
317 			ssp_handle_big_data(data, dataframe, &idx);
318 			break;
319 		case SSP_MSG2AP_INST_TIME_SYNC:
320 			data->time_syncing = true;
321 			break;
322 		case SSP_MSG2AP_INST_RESET:
323 			ssp_queue_ssp_refresh_task(data, 0);
324 			break;
325 		}
326 	}
327 
328 	if (data->time_syncing)
329 		data->timestamp = ktime_get_real_ns();
330 
331 	return 0;
332 }
333 
334 /* threaded irq */
335 int ssp_irq_msg(struct ssp_data *data)
336 {
337 	bool found = false;
338 	char *buffer;
339 	u8 msg_type;
340 	int ret;
341 	u16 length, msg_options;
342 	struct ssp_msg *msg, *n;
343 
344 	ret = spi_read(data->spi, data->header_buffer, SSP_HEADER_BUFFER_SIZE);
345 	if (ret < 0) {
346 		dev_err(SSP_DEV, "header read fail\n");
347 		return ret;
348 	}
349 
350 	length = le16_to_cpu(data->header_buffer[1]);
351 	msg_options = le16_to_cpu(data->header_buffer[0]);
352 
353 	if (length == 0) {
354 		dev_err(SSP_DEV, "length received from mcu is 0\n");
355 		return -EINVAL;
356 	}
357 
358 	msg_type = SSP_GET_MESSAGE_TYPE(msg_options);
359 
360 	switch (msg_type) {
361 	case SSP_AP2HUB_READ:
362 	case SSP_AP2HUB_WRITE:
363 		/*
364 		 * this is a small list, a few elements - the packets can be
365 		 * received with no order
366 		 */
367 		mutex_lock(&data->pending_lock);
368 		list_for_each_entry_safe(msg, n, &data->pending_list, list) {
369 			if (msg->options == msg_options) {
370 				list_del(&msg->list);
371 				found = true;
372 				break;
373 			}
374 		}
375 
376 		if (!found) {
377 			/*
378 			 * here can be implemented dead messages handling
379 			 * but the slave should not send such ones - it is to
380 			 * check but let's handle this
381 			 */
382 			buffer = kmalloc(length, GFP_KERNEL | GFP_DMA);
383 			if (!buffer) {
384 				ret = -ENOMEM;
385 				goto _unlock;
386 			}
387 
388 			/* got dead packet so it is always an error */
389 			ret = spi_read(data->spi, buffer, length);
390 			if (ret >= 0)
391 				ret = -EPROTO;
392 
393 			kfree(buffer);
394 
395 			dev_err(SSP_DEV, "No match error %x\n",
396 				msg_options);
397 
398 			goto _unlock;
399 		}
400 
401 		if (msg_type == SSP_AP2HUB_READ)
402 			ret = spi_read(data->spi,
403 				       &msg->buffer[SSP_HEADER_SIZE_ALIGNED],
404 				       msg->length);
405 
406 		if (msg_type == SSP_AP2HUB_WRITE) {
407 			ret = spi_write(data->spi,
408 					&msg->buffer[SSP_HEADER_SIZE_ALIGNED],
409 					msg->length);
410 			if (msg_options & SSP_AP2HUB_RETURN) {
411 				msg->options =
412 					SSP_AP2HUB_READ | SSP_AP2HUB_RETURN;
413 				msg->length = 1;
414 
415 				list_add_tail(&msg->list, &data->pending_list);
416 				goto _unlock;
417 			}
418 		}
419 
420 		if (msg->done)
421 			if (!completion_done(msg->done))
422 				complete(msg->done);
423 _unlock:
424 		mutex_unlock(&data->pending_lock);
425 		break;
426 	case SSP_HUB2AP_WRITE:
427 		buffer = kzalloc(length, GFP_KERNEL | GFP_DMA);
428 		if (!buffer)
429 			return -ENOMEM;
430 
431 		ret = spi_read(data->spi, buffer, length);
432 		if (ret < 0) {
433 			dev_err(SSP_DEV, "spi read fail\n");
434 			kfree(buffer);
435 			break;
436 		}
437 
438 		ret = ssp_parse_dataframe(data, buffer, length);
439 
440 		kfree(buffer);
441 		break;
442 
443 	default:
444 		dev_err(SSP_DEV, "unknown msg type\n");
445 		return -EPROTO;
446 	}
447 
448 	return ret;
449 }
450 
451 void ssp_clean_pending_list(struct ssp_data *data)
452 {
453 	struct ssp_msg *msg, *n;
454 
455 	mutex_lock(&data->pending_lock);
456 	list_for_each_entry_safe(msg, n, &data->pending_list, list) {
457 		list_del(&msg->list);
458 
459 		if (msg->done)
460 			if (!completion_done(msg->done))
461 				complete(msg->done);
462 	}
463 	mutex_unlock(&data->pending_lock);
464 }
465 
466 int ssp_command(struct ssp_data *data, char command, int arg)
467 {
468 	int ret;
469 	struct ssp_msg *msg;
470 
471 	msg = ssp_create_msg(command, 0, SSP_AP2HUB_WRITE, arg);
472 	if (!msg)
473 		return -ENOMEM;
474 
475 	ssp_dbg("%s - command 0x%x %d\n", __func__, command, arg);
476 
477 	ret = ssp_spi_sync_command(data, msg);
478 	ssp_clean_msg(msg);
479 
480 	return ret;
481 }
482 
483 int ssp_send_instruction(struct ssp_data *data, u8 inst, u8 sensor_type,
484 			 u8 *send_buf, u8 length)
485 {
486 	int ret;
487 	struct ssp_msg *msg;
488 
489 	if (data->fw_dl_state == SSP_FW_DL_STATE_DOWNLOADING) {
490 		dev_err(SSP_DEV, "%s - Skip Inst! DL state = %d\n",
491 			__func__, data->fw_dl_state);
492 		return -EBUSY;
493 	} else if (!(data->available_sensors & BIT(sensor_type)) &&
494 		   (inst <= SSP_MSG2SSP_INST_CHANGE_DELAY)) {
495 		dev_err(SSP_DEV, "%s - Bypass Inst Skip! - %u\n",
496 			__func__, sensor_type);
497 		return -EIO; /* just fail */
498 	}
499 
500 	msg = ssp_create_msg(inst, length + 2, SSP_AP2HUB_WRITE, 0);
501 	if (!msg)
502 		return -ENOMEM;
503 
504 	ssp_fill_buffer(msg, 0, &sensor_type, 1);
505 	ssp_fill_buffer(msg, 1, send_buf, length);
506 
507 	ssp_dbg("%s - Inst = 0x%x, Sensor Type = 0x%x, data = %u\n",
508 		__func__, inst, sensor_type, send_buf[1]);
509 
510 	ret = ssp_spi_sync(data, msg, 1000);
511 	ssp_clean_msg(msg);
512 
513 	return ret;
514 }
515 
516 int ssp_get_chipid(struct ssp_data *data)
517 {
518 	int ret;
519 	char buffer;
520 	struct ssp_msg *msg;
521 
522 	msg = ssp_create_msg(SSP_MSG2SSP_AP_WHOAMI, 1, SSP_AP2HUB_READ, 0);
523 	if (!msg)
524 		return -ENOMEM;
525 
526 	ret = ssp_spi_sync(data, msg, 1000);
527 
528 	buffer = SSP_GET_BUFFER_AT_INDEX(msg, 0);
529 
530 	ssp_clean_msg(msg);
531 
532 	return ret < 0 ? ret : buffer;
533 }
534 
535 int ssp_set_magnetic_matrix(struct ssp_data *data)
536 {
537 	int ret;
538 	struct ssp_msg *msg;
539 
540 	msg = ssp_create_msg(SSP_MSG2SSP_AP_SET_MAGNETIC_STATIC_MATRIX,
541 			     data->sensorhub_info->mag_length, SSP_AP2HUB_WRITE,
542 			     0);
543 	if (!msg)
544 		return -ENOMEM;
545 
546 	ssp_fill_buffer(msg, 0, data->sensorhub_info->mag_table,
547 			data->sensorhub_info->mag_length);
548 
549 	ret = ssp_spi_sync(data, msg, 1000);
550 	ssp_clean_msg(msg);
551 
552 	return ret;
553 }
554 
555 unsigned int ssp_get_sensor_scanning_info(struct ssp_data *data)
556 {
557 	int ret;
558 	__le32 result;
559 	u32 cpu_result = 0;
560 
561 	struct ssp_msg *msg = ssp_create_msg(SSP_MSG2SSP_AP_SENSOR_SCANNING, 4,
562 					     SSP_AP2HUB_READ, 0);
563 	if (!msg)
564 		return 0;
565 
566 	ret = ssp_spi_sync(data, msg, 1000);
567 	if (ret < 0) {
568 		dev_err(SSP_DEV, "%s - spi read fail %d\n", __func__, ret);
569 		goto _exit;
570 	}
571 
572 	ssp_get_buffer(msg, 0, &result, 4);
573 	cpu_result = le32_to_cpu(result);
574 
575 	dev_info(SSP_DEV, "%s state: 0x%08x\n", __func__, cpu_result);
576 
577 _exit:
578 	ssp_clean_msg(msg);
579 	return cpu_result;
580 }
581 
582 unsigned int ssp_get_firmware_rev(struct ssp_data *data)
583 {
584 	int ret;
585 	__le32 result;
586 
587 	struct ssp_msg *msg = ssp_create_msg(SSP_MSG2SSP_AP_FIRMWARE_REV, 4,
588 					     SSP_AP2HUB_READ, 0);
589 	if (!msg)
590 		return SSP_INVALID_REVISION;
591 
592 	ret = ssp_spi_sync(data, msg, 1000);
593 	if (ret < 0) {
594 		dev_err(SSP_DEV, "%s - transfer fail %d\n", __func__, ret);
595 		ret = SSP_INVALID_REVISION;
596 		goto _exit;
597 	}
598 
599 	ssp_get_buffer(msg, 0, &result, 4);
600 	ret = le32_to_cpu(result);
601 
602 _exit:
603 	ssp_clean_msg(msg);
604 	return ret;
605 }
606