pn53x.c 104 KB
Newer Older
1
/*-
2
 * Free/Libre Near Field Communication (NFC) library
3
 *
4 5 6 7 8 9 10
 * Libnfc historical contributors:
 * Copyright (C) 2009      Roel Verdult
 * Copyright (C) 2009-2013 Romuald Conty
 * Copyright (C) 2010-2012 Romain Tartière
 * Copyright (C) 2010-2013 Philippe Teuwen
 * Copyright (C) 2012-2013 Ludovic Rousseau
 * Additional contributors of this file:
11
 *
12 13 14 15
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
16
 *
17 18 19 20 21 22 23
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
24 25 26
 */

/**
27
 * @file pn53x.c
28 29 30
 * @brief PN531, PN532 and PN533 common functions
 */

31
#ifdef HAVE_CONFIG_H
32
#  include "config.h"
33 34
#endif // HAVE_CONFIG_H

35
#include <inttypes.h>
36
#include <stdio.h>
Romain Tartiere's avatar
Romain Tartiere committed
37 38
#include <stdlib.h>
#include <string.h>
39
#include <stdlib.h>
Romain Tartiere's avatar
Romain Tartiere committed
40

41 42
#include "nfc/nfc.h"
#include "nfc-internal.h"
43
#include "pn53x.h"
44
#include "pn53x-internal.h"
45 46

#include "mirror-subr.h"
47

Romuald Conty's avatar
Romuald Conty committed
48
#define LOG_CATEGORY "libnfc.chip.pn53x"
Romuald Conty's avatar
Romuald Conty committed
49
#define LOG_GROUP NFC_LOG_GROUP_CHIP
50

51 52 53
const uint8_t pn53x_ack_frame[] = { 0x00, 0x00, 0xff, 0x00, 0xff, 0x00 };
const uint8_t pn53x_nack_frame[] = { 0x00, 0x00, 0xff, 0xff, 0x00, 0x00 };
static const uint8_t pn53x_error_frame[] = { 0x00, 0x00, 0xff, 0x01, 0xff, 0x7f, 0x81, 0x00 };
54 55 56 57 58 59 60
const nfc_baud_rate pn53x_iso14443a_supported_baud_rates[] = { NBR_106, 0 };
const nfc_baud_rate pn53x_felica_supported_baud_rates[] = { NBR_424, NBR_212, 0 };
const nfc_baud_rate pn53x_dep_supported_baud_rates[] = { NBR_424, NBR_212, NBR_106, 0 };
const nfc_baud_rate pn53x_jewel_supported_baud_rates[] = { NBR_106, 0 };
const nfc_baud_rate pn532_iso14443b_supported_baud_rates[] = { NBR_106, 0 };
const nfc_baud_rate pn533_iso14443b_supported_baud_rates[] = { NBR_847, NBR_424, NBR_212, NBR_106, 0 };
const nfc_modulation_type pn53x_supported_modulation_as_target[] = {NMT_ISO14443A, NMT_FELICA, NMT_DEP, 0};
Romain Tartiere's avatar
Romain Tartiere committed
61

62
/* prototypes */
63 64
int pn53x_reset_settings(struct nfc_device *pnd);
int pn53x_writeback_register(struct nfc_device *pnd);
65

66 67 68
nfc_modulation pn53x_ptt_to_nm(const pn53x_target_type ptt);
pn53x_modulation pn53x_nm_to_pm(const nfc_modulation nm);
pn53x_target_type pn53x_nm_to_ptt(const nfc_modulation nm);
69

70 71 72
void pn53x_current_target_new(const struct nfc_device *pnd, const nfc_target *pnt);
void pn53x_current_target_free(const struct nfc_device *pnd);
bool pn53x_current_target_is(const struct nfc_device *pnd, const nfc_target *pnt);
73 74

/* implementations */
75
int
76
pn53x_init(struct nfc_device *pnd)
77
{
78
  int res = 0;
79
  // GetFirmwareVersion command is used to set PN53x chips type (PN531, PN532 or PN533)
80
  if ((res = pn53x_decode_firmware_version(pnd)) < 0) {
81
    return res;
82 83
  }

84 85
  if (!CHIP_DATA(pnd)->supported_modulation_as_initiator) {
    CHIP_DATA(pnd)->supported_modulation_as_initiator = malloc(sizeof(nfc_modulation) * 9);
86 87
    if (! CHIP_DATA(pnd)->supported_modulation_as_initiator)
      return NFC_ESOFT;
88 89 90 91 92 93
    int nbSupportedModulation = 0;
    if ((pnd->btSupportByte & SUPPORT_ISO14443A)) {
      CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443A;
      nbSupportedModulation++;
      CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_FELICA;
      nbSupportedModulation++;
94
    }
95 96 97
    if (pnd->btSupportByte & SUPPORT_ISO14443B) {
      CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443B;
      nbSupportedModulation++;
98
    }
99
    if (CHIP_DATA(pnd)->type != PN531) {
100 101 102 103 104 105 106
      CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_JEWEL;
      nbSupportedModulation++;
    }
    CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_DEP;
    nbSupportedModulation++;
    CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = 0;
  }
107

108
  if (!CHIP_DATA(pnd)->supported_modulation_as_target) {
109
    CHIP_DATA(pnd)->supported_modulation_as_target = (nfc_modulation_type *) pn53x_supported_modulation_as_target;
110
  }
111

112 113 114 115
  // CRC handling should be enabled by default as declared in nfc_device_new
  // which is the case by default for pn53x, so nothing to do here
  // Parity handling should be enabled by default as declared in nfc_device_new
  // which is the case by default for pn53x, so nothing to do here
116 117 118

  // We can't read these parameters, so we set a default config by using the SetParameters wrapper
  // Note: pn53x_SetParameters() will save the sent value in pnd->ui8Parameters cache
119
  if ((res = pn53x_SetParameters(pnd, PARAM_AUTO_ATR_RES | PARAM_AUTO_RATS)) < 0) {
120
    return res;
121 122
  }

123 124
  if ((res = pn53x_reset_settings(pnd)) < 0) {
    return res;
125
  }
126
  return NFC_SUCCESS;
127 128
}

129
int
130
pn53x_reset_settings(struct nfc_device *pnd)
131
{
132
  int res = 0;
133
  // Reset the ending transmission bits register, it is unknown what the last tranmission used there
134 135
  CHIP_DATA(pnd)->ui8TxBits = 0;
  if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_BitFraming, SYMBOL_TX_LAST_BITS, 0x00)) < 0) {
136
    return res;
137
  }
138 139 140 141 142 143 144 145 146 147 148 149
  // Make sure we reset the CRC and parity to chip handling.
  if ((res = pn53x_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0)
    return res;
  if ((res = pn53x_set_property_bool(pnd, NP_HANDLE_PARITY, true)) < 0)
    return res;
  // Activate "easy framing" feature by default
  if ((res = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0)
    return res;
  // Deactivate the CRYPTO1 cipher, it may could cause problems when still active
  if ((res = pn53x_set_property_bool(pnd, NP_ACTIVATE_CRYPTO1, false)) < 0)
    return res;

150
  return NFC_SUCCESS;
151 152
}

153
int
154
pn53x_transceive(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRxLen, int timeout)
155
{
156
  int res = 0;
157 158
  if (CHIP_DATA(pnd)->wb_trigged) {
    if ((res = pn53x_writeback_register(pnd)) < 0) {
159
      return res;
160 161 162
    }
  }

163
  PNCMD_TRACE(pbtTx[0]);
Romuald Conty's avatar
Romuald Conty committed
164
  if (timeout > 0) {
Romuald Conty's avatar
Romuald Conty committed
165
    log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Timeout values: %d", timeout);
Romuald Conty's avatar
Romuald Conty committed
166
  } else if (timeout == 0) {
Romuald Conty's avatar
Romuald Conty committed
167
    log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "No timeout");
Romuald Conty's avatar
Romuald Conty committed
168
  } else if (timeout == -1) {
169
    timeout = CHIP_DATA(pnd)->timeout_command;
Romuald Conty's avatar
Romuald Conty committed
170
  } else {
Romuald Conty's avatar
Romuald Conty committed
171
    log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid timeout value: %d", timeout);
Romuald Conty's avatar
Romuald Conty committed
172
  }
173

174
  uint8_t  abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN];
175
  size_t  szRx = sizeof(abtRx);
176 177

  // Check if receiving buffers are available, if not, replace them
178
  if (szRxLen == 0 || !pbtRx) {
179
    pbtRx = abtRx;
180 181
  } else {
    szRx = szRxLen;
182 183
  }

184
  // Call the send/receice callback functions of the current driver
185
  if ((res = CHIP_DATA(pnd)->io->send(pnd, pbtTx, szTx, timeout)) < 0) {
186
    return res;
187
  }
188

189
  // Command is sent, we store the command
190
  CHIP_DATA(pnd)->last_command = pbtTx[0];
191

192
  // Handle power mode for PN532
193 194
  if ((CHIP_DATA(pnd)->type == PN532) && (TgInitAsTarget == pbtTx[0])) {  // PN532 automatically goes into PowerDown mode when TgInitAsTarget command will be sent
    CHIP_DATA(pnd)->power_mode = POWERDOWN;
195 196
  }

197
  if ((res = CHIP_DATA(pnd)->io->receive(pnd, pbtRx, szRx, timeout)) < 0) {
198
    return res;
199 200
  }

201
  if ((CHIP_DATA(pnd)->type == PN532) && (TgInitAsTarget == pbtTx[0])) { // PN532 automatically wakeup on external RF field
202
    CHIP_DATA(pnd)->power_mode = NORMAL; // When TgInitAsTarget reply that means an external RF have waken up the chip
203 204
  }

205
  szRx = (size_t) res;
206
  switch (pbtTx[0]) {
207 208 209 210 211 212 213 214 215 216 217 218 219 220
    case PowerDown:
    case InDataExchange:
    case InCommunicateThru:
    case InJumpForPSL:
    case InPSL:
    case InATR:
    case InSelect:
    case InJumpForDEP:
    case TgGetData:
    case TgGetInitiatorCommand:
    case TgSetData:
    case TgResponseToInitiator:
    case TgSetGeneralBytes:
    case TgSetMetaData:
221 222
      if (pbtRx[0] & 0x80) { abort(); } // NAD detected
      if (pbtRx[0] & 0x40) { abort(); } // MI detected
223
      CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f;
224
      break;
225 226 227 228 229 230 231
    case Diagnose:
      if (pbtTx[1] == 0x06) { // Diagnose: Card presence detection
        CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f;
      } else {
        CHIP_DATA(pnd)->last_status_byte = 0;
      };
      break;
232 233 234 235 236
    case InDeselect:
    case InRelease:
      if (CHIP_DATA(pnd)->type == RCS360) {
        // Error code is in pbtRx[1] but we ignore error code anyway
        // because other PN53x chips always return 0 on those commands
237
        CHIP_DATA(pnd)->last_status_byte = 0;
238 239
        break;
      }
240
      CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f;
241
      break;
242 243 244 245
    case ReadRegister:
    case WriteRegister:
      if (CHIP_DATA(pnd)->type == PN533) {
        // PN533 prepends its answer by the status byte
246
        CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f;
247
      } else {
248
        CHIP_DATA(pnd)->last_status_byte = 0;
249 250
      }
      break;
251
    default:
252
      CHIP_DATA(pnd)->last_status_byte = 0;
253
  }
Romuald Conty's avatar
Romuald Conty committed
254

255 256
  switch (CHIP_DATA(pnd)->last_status_byte) {
    case 0:
257
      res = (int)szRx;
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
      break;
    case ETIMEOUT:
    case ECRC:
    case EPARITY:
    case EBITCOUNT:
    case EFRAMING:
    case EBITCOLL:
    case ERFPROTO:
    case ERFTIMEOUT:
    case EDEPUNKCMD:
    case EDEPINVSTATE:
    case ENAD:
    case ENFCID3:
    case EINVRXFRAM:
    case EBCC:
    case ECID:
      res = NFC_ERFTRANS;
      break;
    case ESMALLBUF:
    case EOVCURRENT:
    case EBUFOVF:
    case EOVHEAT:
    case EINBUFOVF:
      res = NFC_ECHIP;
      break;
    case EINVPARAM:
    case EOPNOTALL:
    case ECMD:
    case ENSECNOTSUPP:
      res = NFC_EINVARG;
      break;
    case ETGREL:
    case ECDISCARDED:
      res = NFC_ETGRELEASED;
292
      pn53x_current_target_free(pnd);
293
      break;
294 295
    case EMFAUTH:
      // When a MIFARE Classic AUTH fails, the tag is automatically in HALT state
296
      res = NFC_EMFCAUTHFAIL;
297
      break;
298 299 300 301
    default:
      res = NFC_ECHIP;
      break;
  };
Romuald Conty's avatar
Romuald Conty committed
302

303 304
  if (res < 0) {
    pnd->last_error = res;
Romuald Conty's avatar
Romuald Conty committed
305
    log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Chip error: \"%s\" (%02x), returned error: \"%s\" (%d))", pn53x_strerror(pnd), CHIP_DATA(pnd)->last_status_byte, nfc_strerror(pnd), res);
306 307 308
  } else {
    pnd->last_error = 0;
  }
309
  return res;
310 311
}

312
int
313
pn53x_set_parameters(struct nfc_device *pnd, const uint8_t ui8Parameter, const bool bEnable)
314
{
315 316
  uint8_t ui8Value = (bEnable) ? (CHIP_DATA(pnd)->ui8Parameters | ui8Parameter) : (CHIP_DATA(pnd)->ui8Parameters & ~(ui8Parameter));
  if (ui8Value != CHIP_DATA(pnd)->ui8Parameters) {
317 318
    return pn53x_SetParameters(pnd, ui8Value);
  }
319
  return NFC_SUCCESS;
320 321
}

322
int
323
pn53x_set_tx_bits(struct nfc_device *pnd, const uint8_t ui8Bits)
324 325
{
  // Test if we need to update the transmission bits register setting
326
  if (CHIP_DATA(pnd)->ui8TxBits != ui8Bits) {
327
    int res = 0;
328
    // Set the amount of transmission bits in the PN53X chip register
329
    if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_BitFraming, SYMBOL_TX_LAST_BITS, ui8Bits)) < 0)
330
      return res;
331 332

    // Store the new setting
333
    CHIP_DATA(pnd)->ui8TxBits = ui8Bits;
334
  }
335
  return NFC_SUCCESS;
336 337
}

338
int
339 340
pn53x_wrap_frame(const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar,
                 uint8_t *pbtFrame)
341
{
342 343
  uint8_t  btFrame;
  uint8_t  btData;
344 345
  uint32_t uiBitPos;
  uint32_t uiDataPos = 0;
346
  size_t  szBitsLeft = szTxBits;
347
  size_t szFrameBits = 0;
348 349

  // Make sure we should frame at least something
350
  if (szBitsLeft == 0)
351
    return NFC_ECHIP;
352 353

  // Handle a short response (1byte) as a special case
354
  if (szBitsLeft < 9) {
355
    *pbtFrame = *pbtTx;
356 357
    szFrameBits = szTxBits;
    return szFrameBits;
358 359
  }
  // We start by calculating the frame length in bits
360
  szFrameBits = szTxBits + (szTxBits / 8);
361 362 363 364

  // Parse the data bytes and add the parity bits
  // This is really a sensitive process, mirror the frame bytes and append parity bits
  // buffer = mirror(frame-byte) + parity + mirror(frame-byte) + parity + ...
365
  // split "buffer" up in segments of 8 bits again and mirror them
366
  // air-bytes = mirror(buffer-byte) + mirror(buffer-byte) + mirror(buffer-byte) + ..
367
  while (true) {
368 369 370
    // Reset the temporary frame byte;
    btFrame = 0;

371
    for (uiBitPos = 0; uiBitPos < 8; uiBitPos++) {
372
      // Copy as much data that fits in the frame byte
373
      btData = mirror(pbtTx[uiDataPos]);
374 375
      btFrame |= (btData >> uiBitPos);
      // Save this frame byte
376
      *pbtFrame = mirror(btFrame);
377
      // Set the remaining bits of the date in the new frame byte and append the parity bit
378 379
      btFrame = (btData << (8 - uiBitPos));
      btFrame |= ((pbtTxPar[uiDataPos] & 0x01) << (7 - uiBitPos));
380 381
      // Backup the frame bits we have so far
      pbtFrame++;
382
      *pbtFrame = mirror(btFrame);
383 384 385
      // Increase the data (without parity bit) position
      uiDataPos++;
      // Test if we are done
386
      if (szBitsLeft < 9)
387
        return szFrameBits;
388 389 390 391 392 393 394
      szBitsLeft -= 8;
    }
    // Every 8 data bytes we lose one frame byte to the parities
    pbtFrame++;
  }
}

395
int
396
pn53x_unwrap_frame(const uint8_t *pbtFrame, const size_t szFrameBits, uint8_t *pbtRx, uint8_t *pbtRxPar)
397
{
398 399
  uint8_t  btFrame;
  uint8_t  btData;
400 401
  uint8_t uiBitPos;
  uint32_t uiDataPos = 0;
402
  uint8_t *pbtFramePos = (uint8_t *) pbtFrame;
403
  size_t  szBitsLeft = szFrameBits;
404
  size_t szRxBits = 0;
405 406

  // Make sure we should frame at least something
407
  if (szBitsLeft == 0)
408
    return NFC_ECHIP;
409 410

  // Handle a short response (1byte) as a special case
411
  if (szBitsLeft < 9) {
412
    *pbtRx = *pbtFrame;
413 414
    szRxBits = szFrameBits;
    return szRxBits;
415 416
  }
  // Calculate the data length in bits
417
  szRxBits = szFrameBits - (szFrameBits / 9);
418 419 420

  // Parse the frame bytes, remove the parity bits and store them in the parity array
  // This process is the reverse of WrapFrame(), look there for more info
421 422
  while (true) {
    for (uiBitPos = 0; uiBitPos < 8; uiBitPos++) {
423
      btFrame = mirror(pbtFramePos[uiDataPos]);
424
      btData = (btFrame << uiBitPos);
425
      btFrame = mirror(pbtFramePos[uiDataPos + 1]);
426
      btData |= (btFrame >> (8 - uiBitPos));
427
      pbtRx[uiDataPos] = mirror(btData);
428 429
      if (pbtRxPar != NULL)
        pbtRxPar[uiDataPos] = ((btFrame >> (7 - uiBitPos)) & 0x01);
430 431 432
      // Increase the data (without parity bit) position
      uiDataPos++;
      // Test if we are done
433
      if (szBitsLeft < 9)
434
        return szRxBits;
435 436 437 438 439 440 441
      szBitsLeft -= 9;
    }
    // Every 8 data bytes we lose one frame byte to the parities
    pbtFramePos++;
  }
}

442
int
443 444
pn53x_decode_target_data(const uint8_t *pbtRawData, size_t szRawData, pn53x_type type, nfc_modulation_type nmt,
                         nfc_target_info *pnti)
445
{
446
  uint8_t szAttribRes;
447

448 449 450 451
  switch (nmt) {
    case NMT_ISO14443A:
      // We skip the first byte: its the target number (Tg)
      pbtRawData++;
452

453 454 455 456 457 458 459 460 461 462 463
      // Somehow they switched the lower and upper ATQA bytes around for the PN531 chipset
      if (type == PN531) {
        pnti->nai.abtAtqa[1] = *(pbtRawData++);
        pnti->nai.abtAtqa[0] = *(pbtRawData++);
      } else {
        pnti->nai.abtAtqa[0] = *(pbtRawData++);
        pnti->nai.abtAtqa[1] = *(pbtRawData++);
      }
      pnti->nai.btSak = *(pbtRawData++);
      // Copy the NFCID1
      pnti->nai.szUidLen = *(pbtRawData++);
464
      memcpy(pnti->nai.abtUid, pbtRawData, pnti->nai.szUidLen);
465 466 467 468 469
      pbtRawData += pnti->nai.szUidLen;

      // Did we received an optional ATS (Smardcard ATR)
      if (szRawData > (pnti->nai.szUidLen + 5)) {
        pnti->nai.szAtsLen = ((*(pbtRawData++)) - 1);     // In pbtRawData, ATS Length byte is counted in ATS Frame.
470
        memcpy(pnti->nai.abtAts, pbtRawData, pnti->nai.szAtsLen);
471 472 473
      } else {
        pnti->nai.szAtsLen = 0;
      }
474

475 476 477 478
      // Strip CT (Cascade Tag) to retrieve and store the _real_ UID
      // (e.g. 0x8801020304050607 is in fact 0x01020304050607)
      if ((pnti->nai.szUidLen == 8) && (pnti->nai.abtUid[0] == 0x88)) {
        pnti->nai.szUidLen = 7;
479
        memmove(pnti->nai.abtUid, pnti->nai.abtUid + 1, 7);
480 481
      } else if ((pnti->nai.szUidLen == 12) && (pnti->nai.abtUid[0] == 0x88) && (pnti->nai.abtUid[4] == 0x88)) {
        pnti->nai.szUidLen = 10;
482 483
        memmove(pnti->nai.abtUid, pnti->nai.abtUid + 1, 3);
        memmove(pnti->nai.abtUid + 3, pnti->nai.abtUid + 5, 7);
484 485
      }
      break;
486

487 488 489
    case NMT_ISO14443B:
      // We skip the first byte: its the target number (Tg)
      pbtRawData++;
490

491 492
      // Now we are in ATQB, we skip the first ATQB byte always equal to 0x50
      pbtRawData++;
493

494
      // Store the PUPI (Pseudo-Unique PICC Identifier)
495
      memcpy(pnti->nbi.abtPupi, pbtRawData, 4);
496 497 498
      pbtRawData += 4;

      // Store the Application Data
499
      memcpy(pnti->nbi.abtApplicationData, pbtRawData, 4);
500 501 502
      pbtRawData += 4;

      // Store the Protocol Info
503
      memcpy(pnti->nbi.abtProtocolInfo, pbtRawData, 3);
504 505 506 507 508 509 510 511 512
      pbtRawData += 3;

      // We leave the ATQB field, we now enter in Card IDentifier
      szAttribRes = *(pbtRawData++);
      if (szAttribRes) {
        pnti->nbi.ui8CardIdentifier = *(pbtRawData++);
      }
      break;

513 514 515
    case NMT_ISO14443BI:
      // Skip V & T Addresses
      pbtRawData++;
516
      if (*pbtRawData != 0x07) { // 0x07 = REPGEN
517
        return NFC_ECHIP;
518 519 520
      }
      pbtRawData++;
      // Store the UID
521
      memcpy(pnti->nii.abtDIV, pbtRawData, 4);
522 523 524 525 526
      pbtRawData += 4;
      pnti->nii.btVerLog = *(pbtRawData++);
      if (pnti->nii.btVerLog & 0x80) { // Type = long?
        pnti->nii.btConfig = *(pbtRawData++);
        if (pnti->nii.btConfig & 0x40) {
527
          memcpy(pnti->nii.abtAtr, pbtRawData, szRawData - 8);
528 529 530 531 532
          pnti->nii.szAtrLen = szRawData - 8;
        }
      }
      break;

533
    case NMT_ISO14443B2SR:
534
      // Store the UID
535
      memcpy(pnti->nsi.abtUID, pbtRawData, 8);
536 537
      break;

538 539
    case NMT_ISO14443B2CT:
      // Store UID LSB
540
      memcpy(pnti->nci.abtUID, pbtRawData, 2);
541 542 543 544 545
      pbtRawData += 2;
      // Store Prod Code & Fab Code
      pnti->nci.btProdCode = *(pbtRawData++);
      pnti->nci.btFabCode = *(pbtRawData++);
      // Store UID MSB
546
      memcpy(pnti->nci.abtUID + 2, pbtRawData, 2);
547 548
      break;

549 550 551 552 553 554 555 556
    case NMT_FELICA:
      // We skip the first byte: its the target number (Tg)
      pbtRawData++;

      // Store the mandatory info
      pnti->nfi.szLen = *(pbtRawData++);
      pnti->nfi.btResCode = *(pbtRawData++);
      // Copy the NFCID2t
557
      memcpy(pnti->nfi.abtId, pbtRawData, 8);
558 559
      pbtRawData += 8;
      // Copy the felica padding
560
      memcpy(pnti->nfi.abtPad, pbtRawData, 8);
561 562 563
      pbtRawData += 8;
      // Test if the System code (SYST_CODE) is available
      if (pnti->nfi.szLen > 18) {
564
        memcpy(pnti->nfi.abtSysCode, pbtRawData, 2);
565 566 567 568 569 570 571
      }
      break;
    case NMT_JEWEL:
      // We skip the first byte: its the target number (Tg)
      pbtRawData++;

      // Store the mandatory info
572
      memcpy(pnti->nji.btSensRes, pbtRawData, 2);
573
      pbtRawData += 2;
574
      memcpy(pnti->nji.btId, pbtRawData, 4);
575
      break;
576
      // Should not happend...
577
    case NMT_DEP:
578
      return NFC_ECHIP;
579
      break;
580
  }
581
  return NFC_SUCCESS;
582 583
}

584
static int
585
pn53x_ReadRegister(struct nfc_device *pnd, uint16_t ui16RegisterAddress, uint8_t *ui8Value)
586
{
587 588
  uint8_t  abtCmd[] = { ReadRegister, ui16RegisterAddress >> 8, ui16RegisterAddress & 0xff };
  uint8_t  abtRegValue[2];
589
  size_t  szRegValue = sizeof(abtRegValue);
590
  int res = 0;
591

592 593
  PNREG_TRACE(ui16RegisterAddress);
  if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRegValue, szRegValue, -1)) < 0) {
594
    return res;
595 596 597 598 599 600
  }
  if (CHIP_DATA(pnd)->type == PN533) {
    // PN533 prepends its answer by a status byte
    *ui8Value = abtRegValue[1];
  } else {
    *ui8Value = abtRegValue[0];
601
  }
602
  return NFC_SUCCESS;
603 604
}

605
int pn53x_read_register(struct nfc_device *pnd, uint16_t ui16RegisterAddress, uint8_t *ui8Value)
606
{
607
  return pn53x_ReadRegister(pnd, ui16RegisterAddress, ui8Value);
608
}
609

610
static int
611
pn53x_WriteRegister(struct nfc_device *pnd, const uint16_t ui16RegisterAddress, const uint8_t ui8Value)
612
{
613
  uint8_t  abtCmd[] = { WriteRegister, ui16RegisterAddress >> 8, ui16RegisterAddress & 0xff, ui8Value };
614 615
  PNREG_TRACE(ui16RegisterAddress);
  return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1);
616
}
617

618
int
619
pn53x_write_register(struct nfc_device *pnd, const uint16_t ui16RegisterAddress, const uint8_t ui8SymbolMask, const uint8_t ui8Value)
620
{
621 622 623
  if ((ui16RegisterAddress < PN53X_CACHE_REGISTER_MIN_ADDRESS) || (ui16RegisterAddress > PN53X_CACHE_REGISTER_MAX_ADDRESS)) {
    // Direct write
    if (ui8SymbolMask != 0xff) {
624
      int res = 0;
625
      uint8_t ui8CurrentValue;
626
      if ((res = pn53x_read_register(pnd, ui16RegisterAddress, &ui8CurrentValue)) < 0)
627
        return res;
628 629
      uint8_t ui8NewValue = ((ui8Value & ui8SymbolMask) | (ui8CurrentValue & (~ui8SymbolMask)));
      if (ui8NewValue != ui8CurrentValue) {
630
        return pn53x_WriteRegister(pnd, ui16RegisterAddress, ui8NewValue);
631 632
      }
    } else {
633
      return pn53x_WriteRegister(pnd, ui16RegisterAddress, ui8Value);
634
    }
635
  } else {
636 637
    // Write-back cache area
    const int internal_address = ui16RegisterAddress - PN53X_CACHE_REGISTER_MIN_ADDRESS;
638 639 640
    CHIP_DATA(pnd)->wb_data[internal_address] = (CHIP_DATA(pnd)->wb_data[internal_address] & CHIP_DATA(pnd)->wb_mask[internal_address] & (~ui8SymbolMask)) | (ui8Value & ui8SymbolMask);
    CHIP_DATA(pnd)->wb_mask[internal_address] = CHIP_DATA(pnd)->wb_mask[internal_address] | ui8SymbolMask;
    CHIP_DATA(pnd)->wb_trigged = true;
641
  }
642
  return NFC_SUCCESS;
643 644
}

645
int
646
pn53x_writeback_register(struct nfc_device *pnd)
647
{
648
  int res = 0;
649
  // TODO Check at each step (ReadRegister, WriteRegister) if we didn't exceed max supported frame length
650 651
  BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN);
  BUFFER_APPEND(abtReadRegisterCmd, ReadRegister);
652

653
  // First step, it looks for registers to be read before applying the requested mask
654
  CHIP_DATA(pnd)->wb_trigged = false;
655
  for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) {
656
    if ((CHIP_DATA(pnd)->wb_mask[n]) && (CHIP_DATA(pnd)->wb_mask[n] != 0xff)) {
657
      // This register needs to be read: mask is present but does not cover full data width (ie. mask != 0xff)
658
      const uint16_t pn53x_register_address = PN53X_CACHE_REGISTER_MIN_ADDRESS + n;
659 660
      BUFFER_APPEND(abtReadRegisterCmd, pn53x_register_address  >> 8);
      BUFFER_APPEND(abtReadRegisterCmd, pn53x_register_address & 0xff);
661 662 663
    }
  }

664
  if (BUFFER_SIZE(abtReadRegisterCmd) > 1) {
665
    // It needs to read some registers
666 667
    uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN];
    size_t szRes = sizeof(abtRes);
668
    // It transceives the previously constructed ReadRegister command
669
    if ((res = pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1)) < 0) {
670
      return res;
671 672 673 674 675 676
    }
    size_t i = 0;
    if (CHIP_DATA(pnd)->type == PN533) {
      // PN533 prepends its answer by a status byte
      i = 1;
    }
677
    for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) {
678 679 680
      if ((CHIP_DATA(pnd)->wb_mask[n]) && (CHIP_DATA(pnd)->wb_mask[n] != 0xff)) {
        CHIP_DATA(pnd)->wb_data[n] = ((CHIP_DATA(pnd)->wb_data[n] & CHIP_DATA(pnd)->wb_mask[n]) | (abtRes[i] & (~CHIP_DATA(pnd)->wb_mask[n])));
        if (CHIP_DATA(pnd)->wb_data[n] != abtRes[i]) {
681
          // Requested value is different from read one
682
          CHIP_DATA(pnd)->wb_mask[n] = 0xff;  // We can now apply whole data bits
683
        } else {
684
          CHIP_DATA(pnd)->wb_mask[n] = 0x00;  // We already have the right value
685 686 687 688 689
        }
        i++;
      }
    }
  }
690
  // Now, the writeback-cache only has masks with 0xff, we can start to WriteRegister
691 692
  BUFFER_INIT(abtWriteRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN);
  BUFFER_APPEND(abtWriteRegisterCmd, WriteRegister);
693
  for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) {
694
    if (CHIP_DATA(pnd)->wb_mask[n] == 0xff) {
695
      const uint16_t pn53x_register_address = PN53X_CACHE_REGISTER_MIN_ADDRESS + n;
696 697 698 699
      PNREG_TRACE(pn53x_register_address);
      BUFFER_APPEND(abtWriteRegisterCmd, pn53x_register_address  >> 8);
      BUFFER_APPEND(abtWriteRegisterCmd, pn53x_register_address & 0xff);
      BUFFER_APPEND(abtWriteRegisterCmd, CHIP_DATA(pnd)->wb_data[n]);
700
      // This register is handled, we reset the mask to prevent
701
      CHIP_DATA(pnd)->wb_mask[n] = 0x00;
702 703 704
    }
  }

705
  if (BUFFER_SIZE(abtWriteRegisterCmd) > 1) {
706
    // We need to write some registers
707
    if ((res = pn53x_transceive(pnd, abtWriteRegisterCmd, BUFFER_SIZE(abtWriteRegisterCmd), NULL, 0, -1)) < 0) {
708
      return res;
709
    }
710
  }
711
  return NFC_SUCCESS;
712
}
713

714
int
715
pn53x_decode_firmware_version(struct nfc_device *pnd)
716
{
717 718
  const uint8_t abtCmd[] = { GetFirmwareVersion };
  uint8_t  abtFw[4];
719
  size_t  szFwLen = sizeof(abtFw);
720
  int res = 0;
721
  if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtFw, szFwLen, -1)) < 0) {
722
    return res;
723
  }
724
  szFwLen = (size_t) res;
725 726 727 728 729 730
  // Determine which version of chip it is: PN531 will return only 2 bytes, while others return 4 bytes and have the first to tell the version IC
  if (szFwLen == 2) {
    CHIP_DATA(pnd)->type = PN531;
  } else if (szFwLen == 4) {
    if (abtFw[0] == 0x32) { // PN532 version IC
      CHIP_DATA(pnd)->type = PN532;
731 732
    } else if (abtFw[0] == 0x33)  { // PN533 version IC
      if (abtFw[1] == 0x01) { // Sony ROM code
733
        CHIP_DATA(pnd)->type = RCS360;
734 735 736
      } else {
        CHIP_DATA(pnd)->type = PN533;
      }
737 738
    } else {
      // Unknown version IC
739
      return NFC_ENOTIMPL;
740 741 742
    }
  } else {
    // Unknown chip
743
    return NFC_ENOTIMPL;
744 745 746 747
  }
  // Convert firmware info in text, PN531 gives 2 bytes info, but PN532 and PN533 gives 4
  switch (CHIP_DATA(pnd)->type) {
    case PN531:
748
      snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN531 v%d.%d", abtFw[0], abtFw[1]);
749 750 751
      pnd->btSupportByte = SUPPORT_ISO14443A | SUPPORT_ISO18092;
      break;
    case PN532:
752
      snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN532 v%d.%d", abtFw[1], abtFw[2]);
753 754 755
      pnd->btSupportByte = abtFw[3];
      break;
    case PN533:
756
    case RCS360:
757
      snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN533 v%d.%d", abtFw[1], abtFw[2]);
758 759
      pnd->btSupportByte = abtFw[3];
      break;
760 761 762
    case PN53X:
      // Could not happend
      break;
763
  }
764
  return NFC_SUCCESS;
765 766
}

767
static uint8_t
768
pn53x_int_to_timeout(const int ms)
769 770 771 772
{
  uint8_t res = 0;
  if (ms) {
    res = 0x10;
773
    for (int i = 3280; i > 1; i /= 2) {
774 775 776 777 778 779 780 781
      if (ms > i)
        break;
      res--;
    }
  }
  return res;
}

782
int
783
pn53x_set_property_int(struct nfc_device *pnd, const nfc_property property, const int value)
784 785 786
{
  switch (property) {
    case NP_TIMEOUT_COMMAND:
787
      CHIP_DATA(pnd)->timeout_command = value;
788
      break;
789
    case NP_TIMEOUT_ATR:
790 791
      CHIP_DATA(pnd)->timeout_atr = value;
      return pn53x_RFConfiguration__Various_timings(pnd, pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_atr), pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_communication));
792
      break;
793
    case NP_TIMEOUT_COM:
794 795
      CHIP_DATA(pnd)->timeout_communication = value;
      return pn53x_RFConfiguration__Various_timings(pnd, pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_atr), pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_communication));
796
      break;
797
      // Following properties are invalid (not integer)
798 799 800 801 802 803 804 805 806 807 808 809
    case NP_HANDLE_CRC:
    case NP_HANDLE_PARITY:
    case NP_ACTIVATE_FIELD:
    case NP_ACTIVATE_CRYPTO1:
    case NP_INFINITE_SELECT:
    case NP_ACCEPT_INVALID_FRAMES:
    case NP_ACCEPT_MULTIPLE_FRAMES:
    case NP_AUTO_ISO14443_4:
    case NP_EASY_FRAMING:
    case NP_FORCE_ISO14443_A:
    case NP_FORCE_ISO14443_B:
    case NP_FORCE_SPEED_106:
810
      return NFC_EINVARG;
811 812 813 814 815
  }
  return NFC_SUCCESS;
}

int
816
pn53x_set_property_bool(struct nfc_device *pnd, const nfc_property property, const bool bEnable)
817
{
818
  uint8_t  btValue;
819
  int res = 0;
820 821
  switch (property) {
    case NP_HANDLE_CRC:
822
      // Enable or disable automatic receiving/sending of CRC bytes
823 824
      if (bEnable == pnd->bCrc) {
        // Nothing to do
825
        return NFC_SUCCESS;
826
      }
827 828
      // TX and RX are both represented by the symbol 0x80
      btValue = (bEnable) ? 0x80 : 0x00;
829
      if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_CRC_ENABLE, btValue)) < 0)
830
        return res;
831
      if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_CRC_ENABLE, btValue)) < 0)
832
        return res;
833
      pnd->bCrc = bEnable;
834
      return NFC_SUCCESS;
835 836
      break;

837
    case NP_HANDLE_PARITY:
838
      // Handle parity bit by PN53X chip or parse it as data bit
839 840
      if (bEnable == pnd->bPar)
        // Nothing to do
841
        return NFC_SUCCESS;
842
      btValue = (bEnable) ? 0x00 : SYMBOL_PARITY_DISABLE;
843
      if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_ManualRCV, SYMBOL_PARITY_DISABLE, btValue)) < 0)
844
        return res;
845
      pnd->bPar = bEnable;
846
      return NFC_SUCCESS;
847 848
      break;

849
    case NP_EASY_FRAMING:
850
      pnd->bEasyFraming = bEnable;
851
      return NFC_SUCCESS;
852 853
      break;

854 855 856
    case NP_ACTIVATE_FIELD:
      return pn53x_RFConfiguration__RF_field(pnd, bEnable);
      break;
857

858
    case NP_ACTIVATE_CRYPTO1:
859
      btValue = (bEnable) ? SYMBOL_MF_CRYPTO1_ON : 0x00;
860
      return pn53x_write_register(pnd, PN53X_REG_CIU_Status2, SYMBOL_MF_CRYPTO1_ON, btValue);
861 862
      break;

863
    case NP_INFINITE_SELECT:
864 865 866
      // TODO Made some research around this point:
      // timings could be tweak better than this, and maybe we can tweak timings
      // to "gain" a sort-of hardware polling (ie. like PN532 does)
Romuald Conty's avatar
Romuald Conty committed
867
      return pn53x_RFConfiguration__MaxRetries(pnd,
868 869 870 871
                                               (bEnable) ? 0xff : 0x00,        // MxRtyATR, default: active = 0xff, passive = 0x02
                                               (bEnable) ? 0xff : 0x01,        // MxRtyPSL, default: 0x01
                                               (bEnable) ? 0xff : 0x02         // MxRtyPassiveActivation, default: 0xff (0x00 leads to problems with PN531)
                                              );
872
      break;
873

874
    case NP_ACCEPT_INVALID_FRAMES:
875
      btValue = (bEnable) ? SYMBOL_RX_NO_ERROR : 0x00;
876
      return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_NO_ERROR, btValue);
877 878
      break;

879
    case NP_ACCEPT_MULTIPLE_FRAMES:
880
      btValue = (bEnable) ? SYMBOL_RX_MULTIPLE : 0x00;
881
      return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_MULTIPLE, btValue);
882 883
      break;

884
    case NP_AUTO_ISO14443_4:
885 886
      if (bEnable == pnd->bAutoIso14443_4)
        // Nothing to do
887
        return NFC_SUCCESS;
888
      pnd->bAutoIso14443_4 = bEnable;
889
      return pn53x_set_parameters(pnd, PARAM_AUTO_RATS, bEnable);
890 891
      break;

892
    case NP_FORCE_ISO14443_A:
893
      if (!bEnable) {
894
        // Nothing to do
895
        return NFC_SUCCESS;
896 897
      }
      // Force pn53x to be in ISO14443-A mode
898
      if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_FRAMING, 0x00)) < 0) {
899
        return res;
900
      }
901
      if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_FRAMING, 0x00)) < 0) {
902
        return res;
903
      }
904
      // Set the PN53X to force 100% ASK Modified miller decoding (default for 14443A cards)
905
      return pn53x_write_register(pnd, PN53X_REG_CIU_TxAuto, SYMBOL_FORCE_100_ASK, 0x40);
906
      break;
907

908
    case NP_FORCE_ISO14443_B:
909
      if (!bEnable) {
910
        // Nothing to do
911
        return NFC_SUCCESS;
912 913
      }
      // Force pn53x to be in ISO14443-B mode
914
      if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_FRAMING, 0x03)) < 0) {
915
        return res;
916
      }
917
      return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_FRAMING, 0x03);
918 919
      break;

920
    case NP_FORCE_SPEED_106:
921
      if (!bEnable) {
922
        // Nothing to do
923
        return NFC_SUCCESS;
924 925
      }
      // Force pn53x to be at 106 kbps
926
      if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_SPEED, 0x00)) < 0) {
927
        return res;
928
      }
929
      return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_SPEED, 0x00);
930
      break;
931
      // Following properties are invalid (not boolean)
932 933 934 935 936
    case NP_TIMEOUT_COMMAND:
    case NP_TIMEOUT_ATR:
    case NP_TIMEOUT_COM:
      return NFC_EINVARG;
      break;
937 938
  }

939
  return NFC_EINVARG;
940 941
}

942
int
943
pn53x_idle(struct nfc_device *pnd)
944
{
945
  int res = 0;
946
  switch (CHIP_DATA(pnd)->operating_mode) {
947
    case TARGET:
948 949
      // InRelease used in target mode stops the target emulation and no more
      // tag are seen from external initiator
950
      if ((res = pn53x_InRelease(pnd, 0)) < 0) {
951
        return res;
952
      }
953
      if ((CHIP_DATA(pnd)->type == PN532) && (pnd->driver->powerdown)) {
954
        // Use PowerDown to go in "Low VBat" power mode
955
        if ((res = pnd->driver->powerdown(pnd)) < 0) {
956
          return res;
957 958
        }
      }
959
      break;
960
    case INITIATOR:
961 962
      // Use InRelease to go in "Standby mode"
      if ((res = pn53x_InRelease(pnd, 0)) < 0) {
963
        return res;
964 965
      }
      // Disable RF field to avoid heating
966
      if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0) {
967
        return res;
968
      }
969
      if ((CHIP_DATA(pnd)->type == PN532) && (pnd->driver->powerdown)) {
970
        // Use PowerDown to go in "Low VBat" power mode
971
        if ((res = pnd->driver->powerdown(pnd)) < 0) {
972
          return res;
973 974
        }
      }
975
      break;
976
    case IDLE: // Nothing to do.
977
      break;
978
  };
979 980
  // Clear the current nfc_target
  pn53x_current_target_free(pnd);
981
  CHIP_DATA(pnd)->operating_mode = IDLE;
982
  return NFC_SUCCESS;
983 984
}

985
int
986
pn53x_check_communication(struct nfc_device *pnd)