+/* Try to examine chain layout according to IEEE 1149.1 §12
+ */
+int jtag_examine_chain()
+{
+ jtag_device_t *device = jtag_devices;
+ scan_field_t field;
+ u8 idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
+ int i;
+ int bit_count;
+ int device_count = 0;
+ u8 zero_check = 0x0;
+ u8 one_check = 0xff;
+
+ field.device = 0;
+ field.num_bits = sizeof(idcode_buffer) * 8;
+ field.out_value = idcode_buffer;
+ field.out_mask = NULL;
+ field.in_value = idcode_buffer;
+ field.in_check_value = NULL;
+ field.in_check_mask = NULL;
+ field.in_handler = NULL;
+ field.in_handler_priv = NULL;
+
+ for (i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
+ {
+ buf_set_u32(idcode_buffer, i * 32, 32, 0x000000FF);
+ }
+
+ jtag_add_plain_dr_scan(1, &field, TAP_TLR);
+ jtag_execute_queue();
+
+ for (i = 0; i < JTAG_MAX_CHAIN_SIZE * 4; i++)
+ {
+ zero_check |= idcode_buffer[i];
+ one_check &= idcode_buffer[i];
+ }
+
+ /* if there wasn't a single non-zero bit or if all bits were one, the scan isn't valid */
+ if ((zero_check == 0x00) || (one_check == 0xff))
+ {
+ LOG_ERROR("JTAG communication failure, check connection, JTAG interface, target power etc.");
+ return ERROR_JTAG_INIT_FAILED;
+ }
+
+ for (bit_count = 0; bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;)
+ {
+ u32 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
+ if ((idcode & 1) == 0)
+ {
+ /* LSB must not be 0, this indicates a device in bypass */
+ device_count++;
+
+ bit_count += 1;
+ }
+ else
+ {
+ u32 manufacturer;
+ u32 part;
+ u32 version;
+
+ if (idcode == 0x000000FF)
+ {
+ /* End of chain (invalid manufacturer ID) */
+ break;
+ }
+
+ if (device)
+ {
+ device->idcode = idcode;
+ device = device->next;
+ }
+ device_count++;
+
+ manufacturer = (idcode & 0xffe) >> 1;
+ part = (idcode & 0xffff000) >> 12;
+ version = (idcode & 0xf0000000) >> 28;
+
+ LOG_INFO("JTAG device found: 0x%8.8x (Manufacturer: 0x%3.3x, Part: 0x%4.4x, Version: 0x%1.1x)",
+ idcode, manufacturer, part, version);
+
+ bit_count += 32;
+ }
+ }
+
+ /* see if number of discovered devices matches configuration */
+ if (device_count != jtag_num_devices)
+ {
+ LOG_ERROR("number of discovered devices in JTAG chain (%i) doesn't match configuration (%i)",
+ device_count, jtag_num_devices);
+ LOG_ERROR("check the config file and ensure proper JTAG communication (connections, speed, ...)");
+ return ERROR_JTAG_INIT_FAILED;
+ }
+
+ return ERROR_OK;
+}
+