summaryrefslogtreecommitdiffstats
path: root/src/progs/tbl_bootloader/base/tbl_bootloader.cpp
blob: 381e827a99f627f3d49c10a7d14ed34c3f3ba0b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/***************************************************************************
 *   Copyright (C) 2007 Nicolas Hadacek <hadacek@kde.org>                  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/
#include "tbl_bootloader.h"

#include "tbl_bootloader_data.h"
#include "progs/base/prog_config.h"

//-----------------------------------------------------------------------------
Port::Serial::Speed TinyBootloader::Config::readSpeed()
{
  uint speed = readUIntEntry("port_speed", 19200);
  for (uint i=0; i<Port::Serial::Nb_Speeds; i++)
    if ( speed==Port::Serial::SPEED_VALUES[i] ) return Port::Serial::Speed(i);
  return Port::Serial::S19200;
}
void TinyBootloader::Config::writeSpeed(Port::Serial::Speed speed)
{
  writeEntry("port_speed", Port::Serial::SPEED_VALUES[speed]);
}

uint TinyBootloader::Config::readTimeout()
{
  return readUIntEntry("timeout", 300);
}
void TinyBootloader::Config::writeTimeout(uint timeout)
{
  writeEntry("timeout", timeout);
}

uint TinyBootloader::Config::readRetries()
{
  return readUIntEntry("nb_retries", 5);
}
void TinyBootloader::Config::writeRetries(uint nb)
{
  writeEntry("nb_retries", nb);
}

//-----------------------------------------------------------------------------
TinyBootloader::Hardware::Hardware(::Programmer::Base &base, const TQString &portDevice)
  : ::Bootloader::Hardware(base, new Port::Serial(portDevice, Port::Serial::NoProperty, base))
{
  Config config;
  _timeout = config.readTimeout();
  _retries = config.readRetries();
}

bool TinyBootloader::Hardware::openPort()
{
  if ( !port()->open() ) return false;
  Config config;
  if ( !port()->setMode(Port::Serial::IgnoreBreak | Port::Serial::IgnoreParity,
                        Port::Serial::ByteSize8 | Port::Serial::IgnoreControlLines,
                        config.readSpeed(), _timeout) )
    return false;
  return true;
}

bool TinyBootloader::Hardware::internalConnectHardware()
{
  if ( !openPort() ) return false;
  // #### possibly do hard (RTS) or soft reset (codes)
  uchar uc = 0xC1;
  if ( !port()->sendChar(uc, _timeout) ) return false;
  if ( !port()->receiveChar((char &)_id, _timeout) ) return false;
  if ( !waitReady(0) ) return false;
  return true;
}

bool TinyBootloader::Hardware::verifyDeviceId()
{
  uchar id = data(device().name()).id;
  TQValueVector<TQString> list = _base.group().supportedDevices();
  TQStringList devices;
  for (uint i=0; i<uint(list.count()); i++)
    if ( _id==data(list[i]).id ) devices.append(list[i]);
  if ( _id!=id ) {
    if ( devices.count()==0 ) log(Log::LineType::Error, i18n("Unknown id returned by bootloader (%1 read and %2 expected).").arg(toHexLabel(_id, 2)).arg(toHexLabel(id, 2)));
    else log(Log::LineType::Error, i18n("Id returned by bootloader corresponds to other devices: %1 (%2 read and %3 expected).").arg(devices.join(" ")).arg(toHexLabel(_id, 2)).arg(toHexLabel(id, 2)));
    // we can't ask for "continue anyway?" because bootloader can timeout...
    return false;
  }
  log(Log::LineType::Information, "  " + i18n("Bootloader identified device as: %1").arg(devices.join(" ")));
  return true;
}

bool TinyBootloader::Hardware::waitReady(bool *checkCRC)
{
  char c;
  if ( !port()->receiveChar(c, _timeout) ) return false;
  if ( c=='K' ) {
    if (checkCRC) *checkCRC = true;
    return true;
  }
  if (checkCRC) {
    *checkCRC = false;
    if ( c=='N' ) return true;
    log(Log::LineType::Error, i18n("Received unexpected character ('%1' received; 'K' or 'N' expected).").arg(toPrintable(c, PrintAlphaNum)));
    return true;
  }
  log(Log::LineType::Error, i18n("Received unexpected character ('%1' received; 'K' expected).").arg(toPrintable(c, PrintAlphaNum)));
  return false;
}

bool TinyBootloader::Hardware::sendChar(char c, uchar *crc)
{
  if (crc) *crc += c;
  return port()->sendChar(c, 10*_timeout);
}

bool TinyBootloader::Hardware::sendCodeAddress(uint address, uchar &crc)
{
  switch (device().architecture().type()) {
    case Pic::Architecture::P16X:
      if ( !sendChar(address >> 8, &crc) ) return false;          // address high
      if ( !sendChar(address & 0xFF, &crc) ) return false;        // address low
      break;
    case Pic::Architecture::P18F:
      if ( !sendChar(address >> 16, &crc) ) return false;           // address upper
      if ( !sendChar((address >> 8) & 0xFF, &crc) ) return false;   // address high
      if ( !sendChar(address & 0xFF, &crc) ) return false;          // address low
      break;
    case Pic::Architecture::P30F:
      if ( !sendChar(address & 0xFF, &crc) ) return false;          // address low
      if ( !sendChar((address >> 8) & 0xFF, &crc) ) return false;   // address high
      if ( !sendChar(address >> 16, &crc) ) return false;           // address upper
      break;
    default: Q_ASSERT(false); return false;
  }
  return true;
}

bool TinyBootloader::Hardware::endWrite(uchar crc, uint &retries, bool &ok)
{
  if ( !sendChar(-crc & 0xFF, 0) ) return false;
  if ( !waitReady(&ok) ) return false;
  if ( !ok ) {
    if ( retries==0 ) {
      log(Log::LineType::Error, i18n("Too many failures: bailing out."));
      return false;
    }
    retries--;
    log(Log::LineType::Warning, i18n("CRC error from bootloader: retrying..."));
  }
  return true;
}

bool TinyBootloader::Hardware::writeCode(const Device::Array &data, bool erase)
{
  uint nb = data.count() - 100;
  Device::Array wdata(nb+4);

  // check that there is nothing on top of bootloader
  for (uint i=nb; i<data.size(); i++) {
    if ( data[i]==device().mask(Pic::MemoryRangeType::Code) ) continue;
    uint address = device().addressIncrement(Pic::MemoryRangeType::Code) * i;
    log(Log::LineType::Warning, "  " + i18n("Code is present in bootloader reserved area (at address %1). It will be ignored.").arg(toHexLabel(address, device().nbCharsAddress())));
    break;
  }

  // check first 4 instructions for "goto" and copy them
  if (erase) {
    for (uint i=0; i<4; i++) wdata[nb+i] = device().nopInstruction();
  } else {
    bool ok = false;
    for (uint i=0; i<4; i++) {
      wdata[nb+i] = data[i];
      if ( !ok && device().isGotoInstruction(data[i]) ) {
        ok = true;
        if ( i==3 && device().gotoInstruction(0x0, false).count()==2 )
          log(Log::LineType::Warning, "  " + i18n("Only the first word of the \"goto\" instruction is into the first four instructions."));
      }
    }
    if ( !ok ) log(Log::LineType::Warning, "  " + i18n("No \"goto\" instruction in the first four instructions."));
  }

  // place "goto size-100" at reset vector
  wdata[0] = device().nopInstruction(); // for icd2
  uint address = device().addressIncrement(Pic::MemoryRangeType::Code) * (nb+4);
  Device::Array a = device().gotoInstruction(address, true);
  for (uint i=0; i<a.size(); i++) wdata[1+i] = a[i];
  // copy the rest
  for (uint i=4; i<nb; i++) wdata[i] = data[i];

  uint retries = _retries, nbWords = 0x20; // 16F: 64 bytes (80 bytes reserved) ; 18F: 64 bytes ; 30F: 96 bytes
  Q_ASSERT( (data.count()%nbWords)==0 );
  for (uint i=0; i<wdata.count(); i+=nbWords) {
    if ( !erase ) {
      bool write = false;
      for (uint k=0; k<nbWords; k++) {
        if ( wdata[i+k]==device().mask(Pic::MemoryRangeType::Code) ) continue;
        write = true;
        break;
      }
      if ( !write ) continue; // skip
    }
    for (;;) {
      uchar crc = 0;
      uint address = device().addressIncrement(Pic::MemoryRangeType::Code) * i;
      if ( !sendCodeAddress(address, crc) ) return false;
      uint nbw = device().nbBytesWord(Pic::MemoryRangeType::Code);
      if ( !sendChar(nbw*nbWords, &crc) ) return false;
      log(Log::DebugLevel::Normal, TQString("write code memory at %1: %2 bytes").arg(toHexLabel(address, 4)).arg(2*nbWords));
      for(uint k=0; k<nbWords; k++) {
        if ( !sendChar(wdata[i+k].byte(0), &crc) ) return false;           // data low
        if ( !sendChar(wdata[i+k].byte(1), &crc) ) return false;           // data high
        if ( nbw==3 && !sendChar(wdata[i+k].byte(2), &crc) ) return false; // upper byte
      }
      bool ok;
      if ( !endWrite(crc, retries, ok) ) return false;
      if (ok) break;
    }
  }
  return true;
}

bool TinyBootloader::Hardware::writeConfig(const Device::Array &data)
{
  if ( device().architecture()==Pic::Architecture::P16X ) return false;
  uint retries = _retries;
  for (uint i=0; i<data.count(); i++) {
    for (;;) {
      uchar crc = 0;
      Address address = device().range(Pic::MemoryRangeType::Config).start + i;
      switch (device().architecture().type()) {
        case Pic::Architecture::P18F:
          if ( !sendChar(0x80 | address.byte(2), &crc) ) return false; // address upper | flag
          if ( !sendChar(address.byte(1), &crc) ) return false;        // address high
          if ( !sendChar(address.byte(0), &crc) ) return false;        // address low
          if ( !sendChar(1, &crc) ) return false;                       // nb bytes
          if ( !sendChar(data[i].byte(0), &crc) ) return false;        // data
          break;
        case Pic::Architecture::P30F:
          if ( !sendChar(address.byte(0), &crc) ) return false; // address low
          if ( !sendChar(address.byte(1), &crc) ) return false; // address high
          if ( !sendChar(address.byte(2), &crc) ) return false; // address upper
          if ( !sendChar(2, &crc) ) return false;                // nb bytes
          if ( !sendChar(data[i].byte(0), &crc) ) return false; // data low
          if ( !sendChar(data[i].byte(1), &crc) ) return false; // data high
          break;
        default: Q_ASSERT(false); return false;
      }
      bool ok;
      if ( !endWrite(crc, retries, ok) ) return false;
      if (ok) break;
    }
  }
  return true;
}

bool TinyBootloader::Hardware::writeEeprom(const Device::Array &data)
{
  uint retries = _retries;
  for (uint i=0; i<data.count(); i++) {
    for (;;) {
      uchar crc = 0;
      Address address = device().range(Pic::MemoryRangeType::Config).start + i;
      switch (device().architecture().type()) {
        case Pic::Architecture::P16X:
          if ( !sendChar(0x40, &crc) ) return false;             // flag
          if ( !sendChar(address.byte(0), &crc) ) return false; // address
          if ( !sendChar(1, &crc) ) return false;                // nb bytes
          if ( !sendChar(data[i].byte(0), &crc) ) return false; // data
          break;
        case Pic::Architecture::P18F:
          if ( !sendChar(0x40, &crc) ) return false;             // flag
          if ( !sendChar(address.byte(0), &crc) ) return false; // address
          if ( !sendChar(data[i].byte(0), &crc) ) return false; // data
          if ( !sendChar(0x00, &crc) ) return false;             // dummy
          break;
        case Pic::Architecture::P30F:
          if ( !sendChar(address.byte(0), &crc) ) return false; // address low
          if ( !sendChar(address.byte(1), &crc) ) return false; // address high
          if ( !sendChar(address.byte(2), &crc) ) return false; // address upper
          if ( !sendChar(2, &crc) ) return false;                // nb bytes
          if ( !sendChar(data[i].byte(0), &crc) ) return false; // data low
          if ( !sendChar(data[i].byte(1), &crc) ) return false; // data high
          break;
        default: Q_ASSERT(false); return false;
      }
      bool ok;
      if ( !endWrite(crc, retries, ok) ) return false;
      if (ok) break;
    }
  }
  return true;
}

bool TinyBootloader::Hardware::write(Pic::MemoryRangeType type, const Device::Array &data)
{
  Q_ASSERT( data.count()==device().nbWords(type) );
  if ( type==Pic::MemoryRangeType::Code ) return writeCode(data, false);
  if ( type==Pic::MemoryRangeType::Config ) return writeConfig(data);
  if ( type==Pic::MemoryRangeType::Eeprom ) return writeEeprom(data);
  return false;
}

//-----------------------------------------------------------------------------
bool TinyBootloader::DeviceSpecific::canWriteRange(Pic::MemoryRangeType type) const
{
  if ( type==Pic::MemoryRangeType::Eeprom || type==Pic::MemoryRangeType::Code ) return true;
  if ( device().architecture()==Pic::Architecture::P18F && type==Pic::MemoryRangeType::Config ) return true;
  return false;
}

bool TinyBootloader::DeviceSpecific::doErase(bool)
{
  bool eeprom = readConfigEntry(::Programmer::Config::ProgramEeprom).toBool();
  if (eeprom) log(Log::LineType::Warning, "  " + i18n("Only code and EEPROM will be erased."));
  else log(Log::LineType::Warning, "  " + i18n("Only code will be erased."));
  if ( doEraseRange(Pic::MemoryRangeType::Code)==false ) return false;
  if ( eeprom && doEraseRange(Pic::MemoryRangeType::Eeprom)==false ) return false;
  return true;
}

bool TinyBootloader::DeviceSpecific::doEraseRange(Pic::MemoryRangeType type)
{
  Pic::Memory memory(device());
  if ( type==Pic::MemoryRangeType::Code ) return static_cast<Hardware &>(hardware()).writeCode(memory.arrayForWriting(type), true);
  return hardware().write(type, memory.arrayForWriting(type));
}