rmi4update.cpp revision bef9c2dd3bfbe71b75f59c0dba08402414e008a2
1/*
2 * Copyright (C) 2014 Andrew Duggan
3 * Copyright (C) 2014 Synaptics Inc
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#include <alloca.h>
19#include <time.h>
20#include <stdint.h>
21#include <stdio.h>
22#include <unistd.h>
23#include <string.h>
24#include <stdlib.h>
25#include <errno.h>
26
27#include "rmi4update.h"
28
29#define RMI_F34_QUERY_SIZE		7
30#define RMI_F34_HAS_NEW_REG_MAP		(1 << 0)
31#define RMI_F34_IS_UNLOCKED		(1 << 1)
32#define RMI_F34_HAS_CONFIG_ID		(1 << 2)
33#define RMI_F34_BLOCK_SIZE_OFFSET	1
34#define RMI_F34_FW_BLOCKS_OFFSET	3
35#define RMI_F34_CONFIG_BLOCKS_OFFSET	5
36
37#define RMI_F34_BLOCK_SIZE_V1_OFFSET	0
38#define RMI_F34_FW_BLOCKS_V1_OFFSET	0
39#define RMI_F34_CONFIG_BLOCKS_V1_OFFSET	2
40
41#define RMI_F34_BLOCK_DATA_OFFSET	2
42#define RMI_F34_BLOCK_DATA_V1_OFFSET	1
43
44#define RMI_F34_COMMAND_MASK		0x0F
45#define RMI_F34_STATUS_MASK		0x07
46#define RMI_F34_STATUS_SHIFT		4
47#define RMI_F34_ENABLED_MASK		0x80
48
49#define RMI_F34_COMMAND_V1_MASK		0x3F
50#define RMI_F34_STATUS_V1_MASK		0x3F
51#define RMI_F34_ENABLED_V1_MASK		0x80
52
53#define RMI_F34_WRITE_FW_BLOCK        0x02
54#define RMI_F34_ERASE_ALL             0x03
55#define RMI_F34_WRITE_LOCKDOWN_BLOCK  0x04
56#define RMI_F34_WRITE_CONFIG_BLOCK    0x06
57#define RMI_F34_ENABLE_FLASH_PROG     0x0f
58
59#define RMI_F34_ENABLE_WAIT_MS 300
60#define RMI_F34_ERASE_WAIT_MS (5 * 1000)
61#define RMI_F34_IDLE_WAIT_MS 500
62
63/* Most recent device status event */
64#define RMI_F01_STATUS_CODE(status)		((status) & 0x0f)
65/* Indicates that flash programming is enabled (bootloader mode). */
66#define RMI_F01_STATUS_BOOTLOADER(status)	(!!((status) & 0x40))
67/* The device has lost its configuration for some reason. */
68#define RMI_F01_STATUS_UNCONFIGURED(status)	(!!((status) & 0x80))
69
70/*
71 * Sleep mode controls power management on the device and affects all
72 * functions of the device.
73 */
74#define RMI_F01_CTRL0_SLEEP_MODE_MASK	0x03
75
76#define RMI_SLEEP_MODE_NORMAL		0x00
77#define RMI_SLEEP_MODE_SENSOR_SLEEP	0x01
78#define RMI_SLEEP_MODE_RESERVED0	0x02
79#define RMI_SLEEP_MODE_RESERVED1	0x03
80
81/*
82 * This bit disables whatever sleep mode may be selected by the sleep_mode
83 * field and forces the device to run at full power without sleeping.
84 */
85#define RMI_F01_CRTL0_NOSLEEP_BIT	(1 << 2)
86
87int RMI4Update::UpdateFirmware(bool force, bool performLockdown)
88{
89	struct timespec start;
90	struct timespec end;
91	long long int duration_us = 0;
92	int rc;
93	const unsigned char eraseAll = RMI_F34_ERASE_ALL;
94
95	rc = FindUpdateFunctions();
96	if (rc != UPDATE_SUCCESS)
97		return rc;
98
99	rc = m_device.QueryBasicProperties();
100	if (rc < 0)
101		return UPDATE_FAIL_QUERY_BASIC_PROPERTIES;
102
103	fprintf(stdout, "Device Properties:\n");
104	m_device.PrintProperties();
105
106	rc = DisableNonessentialInterupts();
107	if (rc != UPDATE_SUCCESS)
108		return rc;
109
110	rc = ReadF34Queries();
111	if (rc != UPDATE_SUCCESS)
112		return rc;
113
114	rc = m_firmwareImage.VerifyImageMatchesDevice(GetFirmwareSize(), GetConfigSize());
115	if (rc != UPDATE_SUCCESS)
116		return rc;
117
118	rc = EnterFlashProgramming();
119	if (rc != UPDATE_SUCCESS) {
120		fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
121		return rc;
122	}
123
124	if (!force && m_firmwareImage.HasIO()) {
125		if (m_firmwareImage.GetFirmwareID() <= m_device.GetFirmwareID()) {
126			m_device.Reset();
127			fprintf(stderr, "Firmware image (%ld) is not newer then the firmware on the device (%ld)\n",
128				m_firmwareImage.GetFirmwareID(), m_device.GetFirmwareID());
129			return UPDATE_FAIL_FIRMWARE_IMAGE_IS_OLDER;
130		}
131	}
132
133	if (performLockdown && m_unlocked) {
134		if (m_firmwareImage.GetLockdownData()) {
135			fprintf(stdout, "Writing lockdown...\n");
136			clock_gettime(CLOCK_MONOTONIC, &start);
137			rc = WriteBlocks(m_firmwareImage.GetLockdownData(),
138					m_firmwareImage.GetLockdownSize() / 0x10,
139					RMI_F34_WRITE_LOCKDOWN_BLOCK);
140			if (rc != UPDATE_SUCCESS) {
141				fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
142				return rc;
143			}
144			clock_gettime(CLOCK_MONOTONIC, &end);
145			duration_us = diff_time(&start, &end);
146			fprintf(stdout, "Done writing lockdown, time: %lld us.\n", duration_us);
147		}
148
149		rc = EnterFlashProgramming();
150		if (rc != UPDATE_SUCCESS) {
151			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
152			return rc;
153		}
154
155	}
156
157	rc = WriteBootloaderID();
158	if (rc != UPDATE_SUCCESS) {
159		fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
160		return rc;
161	}
162
163	fprintf(stdout, "Erasing FW...\n");
164	clock_gettime(CLOCK_MONOTONIC, &start);
165	rc = m_device.Write(m_f34StatusAddr, &eraseAll, 1);
166	if (rc < 0) {
167		fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(UPDATE_FAIL_ERASE_ALL));
168		return UPDATE_FAIL_ERASE_ALL;
169	}
170
171	rc = WaitForIdle(RMI_F34_ERASE_WAIT_MS);
172	if (rc != UPDATE_SUCCESS) {
173		fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
174		return rc;
175	}
176	clock_gettime(CLOCK_MONOTONIC, &end);
177	duration_us = diff_time(&start, &end);
178	fprintf(stdout, "Erase complete, time: %lld us.\n", duration_us);
179
180	if (m_firmwareImage.GetFirmwareData()) {
181		fprintf(stdout, "Writing firmware...\n");
182		clock_gettime(CLOCK_MONOTONIC, &start);
183		rc = WriteBlocks(m_firmwareImage.GetFirmwareData(), m_fwBlockCount,
184						RMI_F34_WRITE_FW_BLOCK);
185		if (rc != UPDATE_SUCCESS) {
186			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
187			return rc;
188		}
189		clock_gettime(CLOCK_MONOTONIC, &end);
190		duration_us = diff_time(&start, &end);
191		fprintf(stdout, "Done writing FW, time: %lld us.\n", duration_us);
192	}
193
194	if (m_firmwareImage.GetConfigData()) {
195		fprintf(stdout, "Writing configuration...\n");
196		clock_gettime(CLOCK_MONOTONIC, &start);
197		rc = WriteBlocks(m_firmwareImage.GetConfigData(), m_configBlockCount,
198				RMI_F34_WRITE_CONFIG_BLOCK);
199		if (rc != UPDATE_SUCCESS) {
200			fprintf(stderr, "%s: %s\n", __func__, update_err_to_string(rc));
201			return rc;
202		}
203		clock_gettime(CLOCK_MONOTONIC, &end);
204		duration_us = diff_time(&start, &end);
205		fprintf(stdout, "Done writing config, time: %lld us.\n", duration_us);
206	}
207	m_device.Reset();
208
209	return UPDATE_SUCCESS;
210
211}
212
213int RMI4Update::DisableNonessentialInterupts()
214{
215	int rc;
216	unsigned char interruptEnabeMask = m_f34.GetInterruptMask() | m_f01.GetInterruptMask();
217
218	rc = m_device.Write(m_f01.GetControlBase() + 1, &interruptEnabeMask, 1);
219	if (rc < 0)
220		return rc;
221
222	return UPDATE_SUCCESS;
223}
224
225int RMI4Update::FindUpdateFunctions()
226{
227	if (0 > m_device.ScanPDT())
228		return UPDATE_FAIL_SCAN_PDT;
229
230	if (!m_device.GetFunction(m_f01, 0x01))
231		return UPDATE_FAIL_NO_FUNCTION_01;
232
233	if (!m_device.GetFunction(m_f34, 0x34))
234		return UPDATE_FAIL_NO_FUNCTION_34;
235
236	return UPDATE_SUCCESS;
237}
238
239int RMI4Update::ReadF34Queries()
240{
241	int rc;
242	unsigned char idStr[3];
243	unsigned char buf[8];
244	unsigned short queryAddr = m_f34.GetQueryBase();
245	unsigned short f34Version = m_f34.GetFunctionVersion();
246	unsigned short querySize;
247
248	if (f34Version == 0x1)
249		querySize = 8;
250	else
251		querySize = 2;
252
253	rc = m_device.Read(queryAddr, m_bootloaderID, RMI_BOOTLOADER_ID_SIZE);
254	if (rc < 0)
255		return UPDATE_FAIL_READ_BOOTLOADER_ID;
256
257	if (f34Version == 0x1)
258		++queryAddr;
259	else
260		queryAddr += querySize;
261
262	if (f34Version == 0x1) {
263		rc = m_device.Read(queryAddr, buf, 1);
264		if (rc < 0)
265			return UPDATE_FAIL_READ_F34_QUERIES;
266
267		m_hasNewRegmap = buf[0] & RMI_F34_HAS_NEW_REG_MAP;
268		m_unlocked = buf[0] & RMI_F34_IS_UNLOCKED;;
269		m_hasConfigID = buf[0] & RMI_F34_HAS_CONFIG_ID;
270
271		++queryAddr;
272
273		rc = m_device.Read(queryAddr, buf, 2);
274		if (rc < 0)
275			return UPDATE_FAIL_READ_F34_QUERIES;
276
277		m_blockSize = extract_short(buf + RMI_F34_BLOCK_SIZE_V1_OFFSET);
278
279		++queryAddr;
280
281		rc = m_device.Read(queryAddr, buf, 8);
282		if (rc < 0)
283			return UPDATE_FAIL_READ_F34_QUERIES;
284
285		m_fwBlockCount = extract_short(buf + RMI_F34_FW_BLOCKS_V1_OFFSET);
286		m_configBlockCount = extract_short(buf + RMI_F34_CONFIG_BLOCKS_V1_OFFSET);
287	} else {
288		rc = m_device.Read(queryAddr, buf, RMI_F34_QUERY_SIZE);
289		if (rc < 0)
290			return UPDATE_FAIL_READ_F34_QUERIES;
291
292		m_hasNewRegmap = buf[0] & RMI_F34_HAS_NEW_REG_MAP;
293		m_unlocked = buf[0] & RMI_F34_IS_UNLOCKED;;
294		m_hasConfigID = buf[0] & RMI_F34_HAS_CONFIG_ID;
295		m_blockSize = extract_short(buf + RMI_F34_BLOCK_SIZE_OFFSET);
296		m_fwBlockCount = extract_short(buf + RMI_F34_FW_BLOCKS_OFFSET);
297		m_configBlockCount = extract_short(buf + RMI_F34_CONFIG_BLOCKS_OFFSET);
298	}
299
300	idStr[0] = m_bootloaderID[0];
301	idStr[1] = m_bootloaderID[1];
302	idStr[2] = 0;
303
304	fprintf(stdout, "F34 bootloader id: %s (%#04x %#04x)\n", idStr, m_bootloaderID[0],
305		m_bootloaderID[1]);
306	fprintf(stdout, "F34 has config id: %d\n", m_hasConfigID);
307	fprintf(stdout, "F34 unlocked:      %d\n", m_unlocked);
308	fprintf(stdout, "F34 new reg map:   %d\n", m_hasNewRegmap);
309	fprintf(stdout, "F34 block size:    %d\n", m_blockSize);
310	fprintf(stdout, "F34 fw blocks:     %d\n", m_fwBlockCount);
311	fprintf(stdout, "F34 config blocks: %d\n", m_configBlockCount);
312	fprintf(stdout, "\n");
313
314	if (f34Version == 0x1)
315		m_f34StatusAddr = m_f34.GetDataBase() + 2;
316	else
317		m_f34StatusAddr = m_f34.GetDataBase() + RMI_F34_BLOCK_DATA_OFFSET + m_blockSize;
318
319	return UPDATE_SUCCESS;
320}
321
322int RMI4Update::ReadF34Controls()
323{
324	int rc;
325	unsigned char buf[2];
326
327	if (m_f34.GetFunctionVersion() == 0x1) {
328		rc = m_device.Read(m_f34StatusAddr, buf, 2);
329		if (rc < 0)
330			return UPDATE_FAIL_READ_F34_CONTROLS;
331
332		m_f34Command = buf[0] & RMI_F34_COMMAND_V1_MASK;
333		m_f34Status = buf[1] & RMI_F34_STATUS_V1_MASK;
334		m_programEnabled = !!(buf[1] & RMI_F34_ENABLED_MASK);
335
336	} else {
337		rc = m_device.Read(m_f34StatusAddr, buf, 1);
338		if (rc < 0)
339			return UPDATE_FAIL_READ_F34_CONTROLS;
340
341		m_f34Command = buf[0] & RMI_F34_COMMAND_MASK;
342		m_f34Status = (buf[0] >> RMI_F34_STATUS_SHIFT) & RMI_F34_STATUS_MASK;
343		m_programEnabled = !!(buf[0] & RMI_F34_ENABLED_MASK);
344	}
345
346	return UPDATE_SUCCESS;
347}
348
349int RMI4Update::WriteBootloaderID()
350{
351	int rc;
352	int blockDataOffset = RMI_F34_BLOCK_DATA_OFFSET;
353
354	if (m_f34.GetFunctionVersion() == 0x1)
355		blockDataOffset = RMI_F34_BLOCK_DATA_V1_OFFSET;
356
357	rc = m_device.Write(m_f34.GetDataBase() + blockDataOffset,
358				m_bootloaderID, RMI_BOOTLOADER_ID_SIZE);
359	if (rc < 0)
360		return UPDATE_FAIL_WRITE_BOOTLOADER_ID;
361
362	return UPDATE_SUCCESS;
363}
364
365int RMI4Update::EnterFlashProgramming()
366{
367	int rc;
368	unsigned char f01Control_0;
369	const unsigned char enableProg = RMI_F34_ENABLE_FLASH_PROG;
370
371	rc = WriteBootloaderID();
372	if (rc != UPDATE_SUCCESS)
373		return rc;
374
375	fprintf(stdout, "Enabling flash programming.\n");
376	rc = m_device.Write(m_f34StatusAddr, &enableProg, 1);
377	if (rc < 0)
378		return UPDATE_FAIL_ENABLE_FLASH_PROGRAMMING;
379
380	rc = WaitForIdle(RMI_F34_ENABLE_WAIT_MS);
381	if (rc != UPDATE_SUCCESS)
382		return UPDATE_FAIL_NOT_IN_IDLE_STATE;
383
384	if (!m_programEnabled)
385		return UPDATE_FAIL_PROGRAMMING_NOT_ENABLED;
386
387	fprintf(stdout, "Programming is enabled.\n");
388	rc = FindUpdateFunctions();
389	if (rc != UPDATE_SUCCESS)
390		return rc;
391
392	rc = m_device.Read(m_f01.GetDataBase(), &m_deviceStatus, 1);
393	if (rc < 0)
394		return UPDATE_FAIL_READ_DEVICE_STATUS;
395
396	if (!RMI_F01_STATUS_BOOTLOADER(m_deviceStatus))
397		return UPDATE_FAIL_DEVICE_NOT_IN_BOOTLOADER;
398
399	rc = ReadF34Queries();
400	if (rc != UPDATE_SUCCESS)
401		return rc;
402
403	rc = m_device.Read(m_f01.GetControlBase(), &f01Control_0, 1);
404	if (rc < 0)
405		return UPDATE_FAIL_READ_F01_CONTROL_0;
406
407	f01Control_0 |= RMI_F01_CRTL0_NOSLEEP_BIT;
408	f01Control_0 = (f01Control_0 & ~RMI_F01_CTRL0_SLEEP_MODE_MASK) | RMI_SLEEP_MODE_NORMAL;
409
410	rc = m_device.Write(m_f01.GetControlBase(), &f01Control_0, 1);
411	if (rc < 0)
412		return UPDATE_FAIL_WRITE_F01_CONTROL_0;
413
414	return UPDATE_SUCCESS;
415}
416
417int RMI4Update::WriteBlocks(unsigned char *block, unsigned short count, unsigned char cmd)
418{
419	int blockNum;
420	unsigned char zeros[] = { 0, 0 };
421	int rc;
422	unsigned short addr;
423
424	if (m_f34.GetFunctionVersion() == 0x1)
425		addr = m_f34.GetDataBase() + RMI_F34_BLOCK_DATA_V1_OFFSET;
426	else
427		addr = m_f34.GetDataBase() + RMI_F34_BLOCK_DATA_OFFSET;
428
429	rc = m_device.Write(m_f34.GetDataBase(), zeros, 2);
430	if (rc < 0)
431		return UPDATE_FAIL_WRITE_INITIAL_ZEROS;
432
433	for (blockNum = 0; blockNum < count; ++blockNum) {
434		rc = m_device.Write(addr, block, m_blockSize);
435		if (rc < 0) {
436			fprintf(stderr, "failed to write block %d\n", blockNum);
437			return UPDATE_FAIL_WRITE_BLOCK;
438		}
439
440		rc = m_device.Write(m_f34StatusAddr, &cmd, 1);
441		if (rc < 0) {
442			fprintf(stderr, "failed to write command for block %d\n", blockNum);
443			return UPDATE_FAIL_WRITE_FLASH_COMMAND;
444		}
445
446		rc = WaitForIdle(RMI_F34_IDLE_WAIT_MS);
447		if (rc != UPDATE_SUCCESS) {
448			fprintf(stderr, "failed to go into idle after writing block %d\n", blockNum);
449			return UPDATE_FAIL_NOT_IN_IDLE_STATE;
450		}
451
452		block += m_blockSize;
453	}
454
455	return UPDATE_SUCCESS;
456}
457
458/*
459 * This is a limited implementation of WaitForIdle which assumes WaitForAttention is supported
460 * this will be true for HID, but other protocols will need to revert polling. Polling
461 * is not implemented yet.
462 */
463int RMI4Update::WaitForIdle(int timeout_ms)
464{
465	int rc;
466	struct timeval tv;
467
468	tv.tv_sec = timeout_ms / 1000;
469	tv.tv_usec = (timeout_ms % 1000) * 1000;
470
471	rc = m_device.WaitForAttention(&tv, m_f34.GetInterruptMask());
472	if (rc == -ETIMEDOUT)
473		/*
474		 * If for some reason we are not getting attention reports for HID devices
475		 * then we can still continue after the timeout and read F34 status
476		 * but if we have to wait for the timeout to ellapse everytime then this
477		 * will be slow. If this message shows up a lot then something is wrong
478		 * with receiving attention reports and that should be fixed.
479		 */
480		fprintf(stderr, "Timed out waiting for attn report\n");
481
482	rc = ReadF34Controls();
483	if (rc != UPDATE_SUCCESS)
484		return rc;
485
486	if (!m_f34Status && !m_f34Command) {
487		if (!m_programEnabled) {
488			fprintf(stderr, "Bootloader is idle but program_enabled bit isn't set.\n");
489			return UPDATE_FAIL_PROGRAMMING_NOT_ENABLED;
490		} else {
491			return UPDATE_SUCCESS;
492		}
493	}
494
495	fprintf(stderr, "ERROR: Waiting for idle status.\n");
496	fprintf(stderr, "Command: %#04x\n", m_f34Command);
497	fprintf(stderr, "Status:  %#04x\n", m_f34Status);
498	fprintf(stderr, "Enabled: %d\n", m_programEnabled);
499	fprintf(stderr, "Idle:    %d\n", !m_f34Command && !m_f34Status);
500
501	return UPDATE_FAIL_NOT_IN_IDLE_STATE;
502}