dmitrystu / sboot_stm32

Secure USB DFU1.1 bootloader for STM32
Apache License 2.0
303 stars 63 forks source link

Unable programm if rdp>0 #23

Open test3210-d opened 3 years ago

test3210-d commented 3 years ago

If DFU_SEAL_LEVEL != 0 i recive state(10) = dfuERROR, status(4) = Memory erase function failed. What i do wrong ? cpu stm32f103c8

dfu-util -v -d 0483:df11 -D outfile.bin 0x8002000 dfu-util 0.9

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc. Copyright 2010-2016 Tormod Volden and Stefan Schmidt This program is Free Software and has ABSOLUTELY NO WARRANTY Please report bugs to http://sourceforge.net/p/dfu-util/tickets/

dfu-util: Invalid DFU suffix signature dfu-util: A valid DFU suffix will be required in a future dfu-util release!!! Opening DFU capable USB device... ID 0483:df11 Run-time device DFU version 0110 Claiming USB DFU Interface... Setting Alternate Setting #0 ... Determining device status: state = dfuIDLE, status = 0 dfuIDLE, continuing DFU mode device DFU version 0110 Device returned transfer size 128 Copying data from PC to DFU device Download [ ] 0% 0 bytes failed! state(10) = dfuERROR, status(4) = Memory erase function failed

config


/* DEFAULT CONFIG STARTS HERE */
/* Skip unwanted dfuDNLOAD_SYNC phase. Slightly improve speed, but don't meets DFU1.1 state diagram */
#ifndef DFU_DNLOAD_NOSYNC
#define DFU_DNLOAD_NOSYNC   _ENABLE
#endif
/** Add extra DFU interface for EEPROM */
#ifndef DFU_INTF_EEPROM
#define DFU_INTF_EEPROM     _DISABLE
#endif
/** Firmware can be uploaded from device */
#ifndef DFU_CAN_UPLOAD
#define DFU_CAN_UPLOAD     _DISABLE
#endif
/** Handle DFU_DETACH request in DFU mode. System reset will be issued. */
#ifndef DFU_DETACH
#define DFU_DETACH          _ENABLE
#endif
/** Whether application image is verified by a checksum algorithm */
#ifndef DFU_VERIFY_CHECKSUM
#define DFU_VERIFY_CHECKSUM CRC64FAST
#endif
/** Memory Readout Protection level **/
#ifndef DFU_SEAL_LEVEL
#define DFU_SEAL_LEVEL    1
#endif
/* USB VID */
#ifndef DFU_VENDOR_ID
#define DFU_VENDOR_ID       0x0483
#endif
/* USB PID */
#ifndef DFU_DEVICE_ID
#define DFU_DEVICE_ID       0xDF11
#endif
/* USB manufacturer string */
#ifndef DFU_STR_MANUF
#define DFU_STR_MANUF       "Cdi.biz.ua"
#endif
/* USB product sting */
#ifndef DFU_STR_PRODUCT
#define DFU_STR_PRODUCT     "Bootloader"
#endif
/* USB string for DFU configureation string descriptor. */
#ifndef DFU_DSC_CONFIG
#define DFU_DSC_CONFIG      _ENABLE
#endif
#ifndef DFU_STR_CONFIG
#define DFU_STR_CONFIG      "DFU"
#endif
/* USB string for DFU flash interface string descriptor. */
#ifndef DFU_DSC_FLASH
#define DFU_DSC_FLASH       _ENABLE
#endif
#ifndef DFU_STR_FLASH
#define DFU_STR_FLASH       "Internal flash"
#endif
/* USB string for DFU EEPROM interface sreing descriptor */
#ifndef DFU_DSC_EEPROM
#define DFU_DSC_EEPROM     _DISABLE
#endif
#ifndef DFU_STR_EEPROM
#define DFU_STR_EEPROM       "Internal EEPROM"
#endif
/* USB EP0 size. Must be 8 for USB FS */
#define DFU_EP0_SIZE        8
/* DFU properties */
#ifndef DFU_POLL_TIMEOUT
#define DFU_POLL_TIMEOUT    20
#endif
#ifndef DFU_DETACH_TIMEOUT
#define DFU_DETACH_TIMEOUT  200
#endif
#ifndef DFU_BLOCKSZ
#define DFU_BLOCKSZ         0x80
#endif
/* 32 bit DFU bootkey value */
#ifndef DFU_BOOTKEY
#define DFU_BOOTKEY         0x77777777
#endif
/* DFU bootkey address. Top of the ram by default. _AUTO, _DISABLE or set address.
 * May be enabled internally. */
#ifndef DFU_BOOTKEY_ADDR
#define DFU_BOOTKEY_ADDR    0x20001000
#endif
/* DFU bootstrap port/pin settings. Set GPIOx or _DISABLE */
#ifndef DFU_BOOTSTRAP_GPIO
#define DFU_BOOTSTRAP_GPIO  _DISABLE
#endif
#ifndef DFU_BOOTSTRAP_PIN
#define DFU_BOOTSTRAP_PIN   2
#endif
/* Active bootstrap pin logic level. _HIGH, _LOW */
#ifndef DFU_BOOTSTRAP_LEVEL
#define DFU_BOOTSTRAP_LEVEL  _LOW
#endif
/* Pullup or pulldown settings for the bootstrap pin _AUTO, _DISABLE, _HIGH, _LOW */
#ifndef DFU_BOOTSTRAP_PULL
#define DFU_BOOTSTRAP_PULL  _DISABLE
#endif
/* Double reset waiting time in mS. _DISABLE or time in mS */
#ifndef DFU_DBLRESET_MS
#define DFU_DBLRESET_MS    500
#endif
/* User application address. _AUTO or page aligned address.
 * for _AUTO check __app_start address in output linker map file*/
#ifndef DFU_APP_START
#define DFU_APP_START       0x8002000 
#endif
/* User application size. _AUTO or required size in bytes. */
#ifndef DFU_APP_SIZE
#define DFU_APP_SIZE        _AUTO
#endif

i change DFU_STR_FLASH Found DFU: [0483:df11] ver=0100, devnum=59, cfg=1, intf=0, path="1-1", alt=0, name="@Internal Flash /0x08002000/56*1Kg", serial="9488CE25" and still have error

Device returned transfer size 128
DfuSe interface name: "Internal Flash   "
Downloading to address = 0x08002000, size = 37008
Download        [                         ]   0%            0 bytesstate(10) = dfuERROR, status(4) = Memory erase function failed
Wrong state after command "ERASE_PAGE" download
dmitrystu commented 3 years ago

Can't reproduce with my STM32F103C8T6. Do you cycle the power of the MCU after flashing bootloader? Are there OK with RDP=0? PS. Don't specify flash address to the dfu-util. This is DFU, not a DfuSe!

/* testconf.h */
#define DFU_SEAL_LEVEL      1
#define DFU_VERIFY_CHECKSUM CRC64FAST
#define DFU_STR_MANUF       "Cdi.biz.ua"
#define DFU_STR_PRODUCT     "Bootloader"
#define DFU_BOOTKEY         0x77777777
#define DFU_BOOTKEY_ADDR    0x20001000
#define DFU_BOOTSTRAP_GPIO  _DISABLE
#define DFU_DBLRESET_MS     500
#define DFU_APP_START       0x8002000

Build log:

>:~/proj/sboot_stm32$ make DFU_USER_CONFIG=testconf.h stm32f103x8 program
make bootloader FWCPU='-mcpu=cortex-m3' \
                   FWSTARTUP='mcu/stm32f103.S' \
                   FWDEFS='STM32F1 STM32F103x6 USBD_ASM_DRIVER' \
                   LDPARAMS='ROMLEN=64K RAMLEN=20K'
.......
make[2]: Leaving directory '/home/fdi/proj/sboot_stm32'
building bootloader
   text    data     bss     dec     hex filename
   3756     192    2416    6364    18dc build/firmware.elf
.......
st-flash --reset --format ihex write build/firmware.hex
st-flash 1.5.1-92-gf5d0454
2020-09-29T11:37:38 INFO common.c: Loading device parameters....
2020-09-29T11:37:38 INFO common.c: Device connected is: F1 Medium-density device, id 0x20036410
2020-09-29T11:37:38 INFO common.c: SRAM size: 0x5000 bytes (20 KiB), Flash: 0x10000 bytes (64 KiB) in pages of 1024 bytes
2020-09-29T11:37:38 INFO common.c: Attempting to write 3948 (0xf6c) bytes to stm32 address: 134217728 (0x8000000)
Flash page at addr: 0x08000c00 erased
2020-09-29T11:37:38 INFO common.c: Finished erasing 4 pages of 1024 (0x400) bytes
2020-09-29T11:37:38 INFO common.c: Starting Flash write for VL/F0/F3/F1_XL core id
2020-09-29T11:37:38 INFO flash_loader.c: Successfully loaded flash loader in sram
  4/4 pages written
2020-09-29T11:37:38 INFO common.c: Starting verification of write complete
2020-09-29T11:37:38 INFO common.c: Flash written and verified! jolly good!

lsusb

>:~/proj/sboot_stm32$ lsusb -d 0483:df11 -v

Bus 002 Device 077: ID 0483:df11 STMicroelectronics STM Device in DFU Mode
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0 
  bDeviceProtocol         0 
  bMaxPacketSize0         8
  idVendor           0x0483 STMicroelectronics
  idProduct          0xdf11 STM Device in DFU Mode
  bcdDevice            1.00
  iManufacturer           1 Cdi.biz.ua
  iProduct                2 Bootloader
  iSerial               254 2F82F221
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           27
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          3 DFU
    bmAttributes         0xc0
      Self Powered
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass       254 Application Specific Interface
      bInterfaceSubClass      1 Device Firmware Update
      bInterfaceProtocol      2 
      iInterface              4 Internal flash
      Device Firmware Upgrade Interface Descriptor:
        bLength                             9
        bDescriptorType                    33
        bmAttributes                        7
          Will Not Detach
          Manifestation Tolerant
          Upload Supported
          Download Supported
        wDetachTimeout                    200 milliseconds
        wTransferSize                     128 bytes
        bcdDFUVersion                   1.10
Device Status:     0x0000
  (Bus Powered)

dfu-util

>:~/proj/sboot_stm32$ dfu-util -D test1.bin
dfu-util 0.9

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2016 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to http://sourceforge.net/p/dfu-util/tickets/

dfu-util: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
Opening DFU capable USB device...
ID 0483:df11
Run-time device DFU version 0110
Claiming USB DFU Interface...
Setting Alternate Setting #0 ...
Determining device status: state = dfuIDLE, status = 0
dfuIDLE, continuing
DFU mode device DFU version 0110
Device returned transfer size 128
Copying data from PC to DFU device
Download        [=========================] 100%        57344 bytes
Download done.
state(6) = dfuMANIFEST-SYNC, status(0) = No error condition is present
state(2) = dfuIDLE, status(0) = No error condition is present
Done!

checking RDP by ST tool

>:~/proj/sboot_stm32$ ~/STMicroelectronics/STM32Cube/STM32CubeProgrammer/bin/STM32_Programmer_CLI -c port=SWD -ob displ
      -------------------------------------------------------------------
                        STM32CubeProgrammer v2.4.0                  
      -------------------------------------------------------------------

ST-LINK SN  : 51FF73064986525618330487
ST-LINK FW  : V2J32S0
Voltage     : 3,23V
SWD freq    : 4000 KHz
Connect mode: Normal
Reset mode  : Software reset
Device ID   : 0x410
Device name : STM32F101/F102/F103 Medium-density
Flash size  : 128 KBytes (default)
Device type : MCU
Device CPU  : Cortex-M3

UPLOADING OPTION BYTES DATA ...

  Bank          : 0x00
  Address       : 0x4002201c
  Size          : 8 Bytes

[==================================================] 100% 

  Bank          : 0x01
  Address       : 0x1ffff800
  Size          : 16 Bytes

OPTION BYTES BANK: 0

   Read Out Protection:

     RDP          : Enabled (Flash memory is read-protected.) 

   User Configuration:

     WDG_SW       : 0x1 (Software watchdog) 
     nRST_STOP    : 0x1 (No reset generated) 
     nRST_STDBY   : 0x1 (No reset generated) 

   User Data:

     Data0        : 0xFF  (0xFF) 
     Data1        : 0xFF  (0xFF) 

   Write Protection:

     WRP0         : 0x1 (Write protection not active on this sector) 
     WRP1         : 0x1 (Write protection not active on this sector) 
     WRP2         : 0x1 (Write protection not active on this sector) 
     WRP3         : 0x1 (Write protection not active on this sector) 
     WRP4         : 0x1 (Write protection not active on this sector) 
     WRP5         : 0x1 (Write protection not active on this sector) 
     WRP6         : 0x1 (Write protection not active on this sector) 
     WRP7         : 0x1 (Write protection not active on this sector) 
     WRP8         : 0x1 (Write protection not active on this sector) 
     WRP9         : 0x1 (Write protection not active on this sector) 
     WRP10        : 0x1 (Write protection not active on this sector) 
     WRP11        : 0x1 (Write protection not active on this sector) 
     WRP12        : 0x1 (Write protection not active on this sector) 
     WRP13        : 0x1 (Write protection not active on this sector) 
     WRP14        : 0x1 (Write protection not active on this sector) 
     WRP15        : 0x1 (Write protection not active on this sector) 
     WRP16        : 0x1 (Write protection not active on this sector) 
     WRP17        : 0x1 (Write protection not active on this sector) 
     WRP18        : 0x1 (Write protection not active on this sector) 
     WRP19        : 0x1 (Write protection not active on this sector) 
     WRP20        : 0x1 (Write protection not active on this sector) 
     WRP21        : 0x1 (Write protection not active on this sector) 
     WRP22        : 0x1 (Write protection not active on this sector) 
     WRP23        : 0x1 (Write protection not active on this sector) 
     WRP24        : 0x1 (Write protection not active on this sector) 
     WRP25        : 0x1 (Write protection not active on this sector) 
     WRP26        : 0x1 (Write protection not active on this sector) 
     WRP27        : 0x1 (Write protection not active on this sector) 
     WRP28        : 0x1 (Write protection not active on this sector) 
     WRP29        : 0x1 (Write protection not active on this sector) 
     WRP30        : 0x1 (Write protection not active on this sector) 
     WRP31        : 0x1 (Write protection not active on this sector) 
test3210-d commented 3 years ago

make log

make DFU_USER_CONFIG=testconf.h stm32f103x8 program
make bootloader FWCPU='-mcpu=cortex-m3' \
                   FWSTARTUP='mcu/stm32f103.S' \
                   FWDEFS='STM32F1 STM32F103x6 USBD_ASM_DRIVER' \
                   LDPARAMS='ROMLEN=64K RAMLEN=20K'
make[1]: вход в каталог «/home/deniss/sboot_stm32»
compiling src/arc4.c
compiling src/chacha.c
compiling src/gost.c
compiling src/raiden.c
compiling src/rc5.c
compiling src/speck.c
compiling src/xtea.c
compiling src/xtea1.c
compiling src/blowfish.c
compiling src/rtea.c
compiling src/rc6.c
compiling src/rijndael.c
compiling src/magma.c
compiling src/checksum.c
compiling src/crypto.c
assembling mcu/stm32f103.S
compiling src/descriptors.c
In file included from usb/inc/usb.h:22:0,
                 from src/descriptors.c:21:
usb/inc/usbd_core.h:38:1: warning: "/*" within comment [-Wcomment]
 /** @} */
 ^
compiling src/bootloader.c
In file included from usb/inc/usb.h:22:0,
                 from src/bootloader.c:21:
usb/inc/usbd_core.h:38:1: warning: "/*" within comment [-Wcomment]
 /** @} */
 ^
assembling src/rc5a.S
assembling src/chacha_a.S
assembling src/rc6a.S
building module usb
make[2]: вход в каталог «/home/deniss/sboot_stm32/usb»
make /home/deniss/sboot_stm32/build/objfw/libusb.a
make[3]: вход в каталог «/home/deniss/sboot_stm32/usb»
compiling src/usbd_stm32l052_devfs.c
compiling src/usbd_stm32l100_devfs.c
compiling src/usbd_core.c
compiling src/usbd_stm32f429_otgfs.c
compiling src/usbd_stm32f446_otgfs.c
compiling src/usbd_stm32l476_otgfs.c
compiling src/usbd_stm32f429_otghs.c
compiling src/usbd_stm32f105_otgfs.c
compiling src/usbd_stm32l433_devfs.c
compiling src/usbd_stm32f446_otghs.c
compiling src/usbd_stm32f103_devfs.c
src/usbd_stm32f103_devfs.c:64:13: note: #pragma message: PMA memory size is not defined. Use 512 bytes by default
     #pragma message "PMA memory size is not defined. Use 512 bytes by default"
             ^
assembling src/usbd_stm32f103_devfs_asm.S
assembling src/usbd_stm32l052_devfs_asm.S
assembling src/usbd_stm32l100_devfs_asm.S
a - obj/usbd_stm32l052_devfs.o
a - obj/usbd_stm32l100_devfs.o
a - obj/usbd_core.o
a - obj/usbd_stm32f429_otgfs.o
a - obj/usbd_stm32f446_otgfs.o
a - obj/usbd_stm32l476_otgfs.o
a - obj/usbd_stm32f429_otghs.o
a - obj/usbd_stm32f105_otgfs.o
a - obj/usbd_stm32l433_devfs.o
a - obj/usbd_stm32f446_otghs.o
a - obj/usbd_stm32f103_devfs.o
a - obj/usbd_stm32f103_devfs_asm.o
a - obj/usbd_stm32l052_devfs_asm.o
a - obj/usbd_stm32l100_devfs_asm.o
make[3]: выход из каталога «/home/deniss/sboot_stm32/usb»
make[2]: выход из каталога «/home/deniss/sboot_stm32/usb»
make -f ldscript.mk ROMLEN=64K RAMLEN=20K OUTFILE=build/objfw/script.ld
make[2]: вход в каталог «/home/deniss/sboot_stm32»
Building linker script
make[2]: выход из каталога «/home/deniss/sboot_stm32»
building bootloader
   text    data     bss     dec     hex filename
   3784     192    2412    6388    18f4 build/firmware.elf
creating build/firmware.hex
creating build/firmware.bin
make[1]: выход из каталога «/home/deniss/sboot_stm32»
st-flash --reset --format ihex write build/firmware.hex
st-flash 1.6.1-96-gbf41f14
2020-09-29T12:50:39 INFO common.c: F1xx Medium-density: 20 KiB SRAM, 64 KiB flash in at least 1 KiB pages.
2020-09-29T12:50:39 INFO common.c: Attempting to write 3976 (0xf88) bytes to stm32 address: 134217728 (0x8000000)
2020-09-29T12:50:39 INFO common.c: Flash page at addr: 0x08000000 erased
2020-09-29T12:50:39 INFO common.c: Flash page at addr: 0x08000400 erased
2020-09-29T12:50:39 INFO common.c: Flash page at addr: 0x08000800 erased
2020-09-29T12:50:39 INFO common.c: Flash page at addr: 0x08000c00 erased
2020-09-29T12:50:39 INFO common.c: Finished erasing 4 pages of 1024 (0x400) bytes
2020-09-29T12:50:39 INFO common.c: Starting Flash write for VL/F0/F3/F1_XL core id
2020-09-29T12:50:39 INFO flash_loader.c: Successfully loaded flash loader in sram
  4/4 pages written
2020-09-29T12:50:40 INFO common.c: Starting verification of write complete
2020-09-29T12:50:40 INFO common.c: Flash written and verified! jolly good!
deniss@deniss-K43SJ:~/sboot_stm32$ 

After flash i do power cycle. Dmesg empty. Try several times , try enter to booloader. same usb devise absent. Manualy set rdp =1 via st-link

i get new usb device, but some different

[68977.929078] usb 3-1: new full-speed USB device number 75 using xhci_hcd
[68978.116384] usb 3-1: New USB device found, idVendor=0483, idProduct=df11
[68978.116395] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=254
[68978.116402] usb 3-1: Product: Bootloader
[68978.116408] usb 3-1: Manufacturer: Cdi.biz.ua
[68978.116414] usb 3-1: SerialNumber: 5A0DF47F
deniss@deniss-K43SJ:~/sboot_stm32$ lsusb -d 0483:df11 -v

Bus 003 Device 075: ID 0483:df11 STMicroelectronics STM Device in DFU Mode
Couldn't open device, some information will be missing
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0 
  bDeviceProtocol         0 
  bMaxPacketSize0         8
  idVendor           0x0483 STMicroelectronics
  idProduct          0xdf11 STM Device in DFU Mode
  bcdDevice            1.00
  iManufacturer           1 
  iProduct                2 
  iSerial               254 
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           27
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          3 
    bmAttributes         0xc0
      Self Powered
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass       254 Application Specific Interface
      bInterfaceSubClass      1 Device Firmware Update
      bInterfaceProtocol      2 
      iInterface              4 
      Device Firmware Upgrade Interface Descriptor:
        bLength                             9
        bDescriptorType                    33
        bmAttributes                        7
          Will Not Detach
          Manifestation Tolerant
          Upload Supported
          Download Supported
        wDetachTimeout                    200 milliseconds
        wTransferSize                     128 bytes
        bcdDFUVersion                   1.10
deniss@deniss-K43SJ:~/sboot_stm32$ 

and dfu-util


deniss@deniss-K43SJ:~/sboot_stm32/build$ dfu-util -D outfile.bin 
dfu-util 0.8

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

dfu-util: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
Opening DFU capable USB device...
ID 0483:df11
Run-time device DFU version 0110
Claiming USB DFU Interface...
Setting Alternate Setting #0 ...
Determining device status: state = dfuIDLE, status = 0
dfuIDLE, continuing
DFU mode device DFU version 0110
Device returned transfer size 128
Copying data from PC to DFU device
Download    [                         ]   0%            0 bytes failed!
state(10) = dfuERROR, status(4) = Memory erase function faile

While rdp=0 all work fine if i change rdp from user software have same problem

dmitrystu commented 3 years ago

I was checked STM32F103 errata sheets and I have no more ideas, but I found one strange thing. From 1st message.

Found DFU: [0483:df11] ver=0100, devnum=59, cfg=1, intf=0, path="1-1", alt=0, name="@internal Flash /0x08002000/56*1Kg", serial="9488CE25"

From 2nd message:

[68978.116402] usb 3-1: Product: Bootloader [68978.116408] usb 3-1: Manufacturer: Cdi.biz.ua [68978.116414] usb 3-1: SerialNumber: 5A0DF47F

The different serial numbers. Was it the same chip? If yes, it must be something wrong with MCU. "SerialNumber" string descriptor is auto-generated (FNV1A32) from the factory programmed 96-bit chip UID. It must be the same on the same chip.

test3210-d commented 3 years ago

no , different, first from home second i test from work

test3210-d commented 3 years ago

As i understand it goes the following sequence setup pins ......

if DFU_SEAL_LEVEL 0 tcheck is rdp on if rdp=0 turn read out protection and restart.

but itself bootloader not turn on rdp !!!

test3210-d commented 3 years ago

I found problem It is a very very china cpu. Original stm32f103 work fine. I think need add disclaimer about non original stm processors in my case it is I found a small logo cks ...

test3210-d commented 3 years ago

I try do some test on this cpu if i find solution i add it. Strange on this cpu arduino code

    FLASH_Unlock();
  FLASH_ReadOutProtection(0x33CC);
  FLASH_Lock();
  nvic_sys_reset();

work fine, used flashstm library


void FLASH_Unlock(void)
{
    /* Authorize the FPEC Access */
    FLASH_BASE->KEYR = FLASH_KEY1;
    FLASH_BASE->KEYR = FLASH_KEY2;
}

/**
  * @brief  Locks the FLASH Program Erase Controller.
  * @param  None
  * @retval None
  */
void FLASH_Lock(void)
{
    /* Set the Lock Bit to lock the FPEC and the FCR */
    FLASH_BASE->CR |= FLASH_CR_LOCK;
}

#define CR_PG_Set                ((uint32_t)0x00000001)
#define CR_PG_Reset              ((uint32_t)0x00001FFE) 
#define CR_PER_Set               ((uint32_t)0x00000002)
#define CR_PER_Reset             ((uint32_t)0x00001FFD)
#define CR_MER_Set               ((uint32_t)0x00000004)
#define CR_MER_Reset             ((uint32_t)0x00001FFB)
#define CR_OPTPG_Set             ((uint32_t)0x00000010)
#define CR_OPTPG_Reset           ((uint32_t)0x00001FEF)
#define CR_OPTER_Set             ((uint32_t)0x00000020)
#define CR_OPTER_Reset           ((uint32_t)0x00001FDF)
#define CR_STRT_Set              ((uint32_t)0x00000040)
#define CR_LOCK_Set ((uint32_t)0x00000080)
#define RDP_Key                  ((uint16_t)0x5AA5)
uint16 OB= ((uint16*)0x1FFFF800);

int FLASH_ReadOutProtection(int NewState)
{
  FLASH_Status status = FLASH_COMPLETE;
  /* Check the parameters */
//  assert_param(IS_FUNCTIONAL_STATE(NewState));
  status = FLASH_WaitForLastOperation(EraseTimeout);
  if(status == FLASH_COMPLETE)
  {
    /* Authorizes the small information block programming */
    FLASH_BASE->OPTKEYR = FLASH_KEY1;
    FLASH_BASE->OPTKEYR = FLASH_KEY2;
    FLASH_BASE->CR |= CR_OPTER_Set;
    FLASH_BASE->CR |= CR_STRT_Set;
    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation(EraseTimeout);
    if(status == FLASH_COMPLETE)
    {
      /* if the erase operation is completed, disable the OPTER Bit */
      FLASH_BASE->CR &= CR_OPTER_Reset;
      /* Enable the Option Bytes Programming operation */
      FLASH_BASE->CR |= CR_OPTPG_Set; 
      if(NewState != 0)
      {
        OB  = 0x0;
      }
      else
      {
        OB  = RDP_Key;  
      }
      /* Wait for last operation to be completed */
      status = FLASH_WaitForLastOperation(EraseTimeout); 

      if(status != FLASH_TIMEOUT)
      {
        /* if the program operation is completed, disable the OPTPG Bit */
        FLASH_BASE->CR &= CR_OPTPG_Reset;
      }
    }
    else 
    {
      if(status != FLASH_TIMEOUT)
      {
        /* Disable the OPTER Bit */
        FLASH_BASE->CR &= CR_OPTER_Reset;
      }
    }
  }
  /* Return the protection operation Status */
  return status;       
} 

i see some code difference, but must work , i don't understand why code not worked

dmitrystu commented 3 years ago

Is this code work well with fake F103? I see only two differences with my code. (stm32f103.S#L401)

  1. Using a read-modify-write instead of direct-write for the FLASH->CR. It may affect "Reserved" bitfields that can actually be in use.
  2. Set FLASH->CR to the LOCK state before issuing an NVIC reset.
test3210-d commented 3 years ago

yes this code work


   FLASH_Unlock();
  FLASH_ReadOutProtection(0x33CC);
  nvic_sys_reset();

worked too

test3210-d commented 3 years ago

part of boot code from stm bootloader https://github.com/trebisky/stm32f103/blob/master/serial_boot/boot.txt

; 1ffff438: 45670123        .word 0x45670123  KEY1
; 1ffff43c: cdef89ab        .word 0xcdef89ab  KEY2

1ffff04a:   48fa        ldr r0, [pc, #1000] ; (0x1ffff434) flash
1ffff04c:   49fa        ldr r1, [pc, #1000] ; (0x1ffff438)
1ffff04e:   6081        str r1, [r0, #8]
1ffff050:   49fa        ldr r1, [pc, #1000] ; (0x1ffff43c)
1ffff052:   6081        str r1, [r0, #8]
1ffff054:   4770        bx  lr

1ffff056:   48f7        ldr r0, [pc, #988]  ; (0x1ffff434) flash
1ffff058:   49f7        ldr r1, [pc, #988]  ; (0x1ffff438)
1ffff05a:   6041        str r1, [r0, #4]
1ffff05c:   49f7        ldr r1, [pc, #988]  ; (0x1ffff43c)
1ffff05e:   6041        str r1, [r0, #4]
1ffff060:   4770        bx  lr

; perform option byte erase
1ffff062:   b500        push    {lr}
1ffff064:   f7ff fff7   bl  0x1ffff056  ; unlock flash
1ffff068:   f7ff ffef   bl  0x1ffff04a  ; unlock options
1ffff06c:   f7ff ffe8   bl  0x1ffff040  ; wait until idle
1ffff070:   4af0        ldr r2, [pc, #960]  ; (0x1ffff434) flash
1ffff072:   6910        ldr r0, [r2, #16]   ; read flash CR
1ffff074:   f040 0020   orr.w   r0, r0, #32 ; set bit 0x20 (OPTER)
1ffff078:   6110        str r0, [r2, #16]
1ffff07a:   6910        ldr r0, [r2, #16]
1ffff07c:   f040 0040   orr.w   r0, r0, #64 ; set bit 0x40 (START)
1ffff080:   6110        str r0, [r2, #16]
1ffff082:   f7ff ffdd   bl  0x1ffff040  ; wait until idle
1ffff086:   6910        ldr r0, [r2, #16]
1ffff088:   f020 0020   bic.w   r0, r0, #32 ; clear bit 0x20
1ffff08c:   6110        str r0, [r2, #16]
1ffff08e:   bd00        pop {pc}

i change your section to

/* erasing OPTION data. */
    ldr r0, [r3, #16]    
    orr.w    r0, r0, #32    
    str r0, [r3, #16]
    ldr r0, [r3, #16]
    orr.w    r0, r0, #64    
    str r0, [r3, #16]
    bl      wait_prog_done
/* set RDP */

rdp is set but i still have error about flash erase

i try

/* erasing OPTION data. */
    ldr    r1, [r3, FLASH_CR]
    movs    r1, 0x20               // OPTER
    str     r1, [r3, FLASH_CR]
    ldr    r1, [r3, FLASH_CR]
    movs    r1, 0x60               // START + OPTER
    str     r1, [r3, FLASH_CR]
    bl      wait_prog_done
/* set RDP */

and this code not work

test3210-d commented 3 years ago

https://github.com/rogerclarkmelbourne/STM32duino-bootloader work on this chip witch enabled rdp i try modify erasing page sequence

/* erasing page */
    ldr    r4, [r3, FLASH_CR]
    movs    r4,  0x02               // PER
    str     r4, [r3, FLASH_CR]
    str     r0, [r3, FLASH_AR]
    ldr    r4, [r3, FLASH_CR]
    orr.w   r4, r4, 0x42             // PER + START
    str     r4, [r3, FLASH_CR]
    bl      wait_prog_done
    bcc     Err_erase 

still no effect

test3210-d commented 3 years ago

@dmitrystu Откровенно говоря я так не понял что не хватает и почему работает загрузчик STM32duino-bootloader при установленной защите а ваш нет, в то-же время судя по даташиту надо именно биты менять а не байт целиком, пробовал повторить алгоритм отсюда https://github.com/rogerclarkmelbourne/STM32duino-bootloader/blob/df689808b6030280480c0d151ee9c552ecf6b405/hardware.c#L330 но результат нулевой, может я криво код написал , не знаю , пока идеи закончились

dmitrystu commented 3 years ago

Как я понимаю, при использовании китайского клона F103 возникает ошибка стирания страницы при записи во флеш, причем независимо от того, каким образом был установлен RDP: бутлоадером, пользовательским кодом или через stprog. Сам RDP устанавливается корректно. Так ? Попробую найти такой клон. PS. Посмотрел по ссылке, там используется макрос SETREG который тоже пишет напрямки а не read-modify-write. Но у него не прооверяется бит EOP в FLASH->SR после стирания. Он по ходу вообще его не проверяет. Го в пм по этому вопросу.

KostyaSha commented 3 months ago

чем закончилось чтиво?) (первый коммент на github не на англ)