File size: 23,445 Bytes
7df9186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
#!/usr/bin/python

# Runtime support for programming SPI boot flash over the network.
# Also ties into the FPGA runtime-reboot mechanism.

# The gateware that this python code communicates with has nothing
# to do with the usual LBNL local bus!  Rather, spi_flash.v is its
# own plugin to Packet Badger, with its own UDP port (typically 804).

# Additional use-case documentation in ../flash.md.

# Historical notes about network setup on Linux
# ifconfig eth0 up 192.168.21.1
# route add -net 192.168.8.0 netmask 255.255.255.0 dev eth0
# also see ~/llrf/eth_2012/lantest
# and ~/llrf/eth_2012/UDP_TxRx_test.lua

# Typical flash chips:
# Winbond W25X16, W25X32, W25X64
# See w25x.pdf and spi_flash_engine.v
# Cypress S25FL128S, S25FL256S
# See s25fl128s.pdf

# XC7A100T on Marble-Mini:  bitfile is 3727 kBytes
# XC7K160T on Marble:  bitfile is 6536 kBytes
# with 128 Mbit = 16 Mbyte flash chip,
# use TBPROT=1 BP2=1 BP1=1 BP0=0 to protect the lower half (8192 kByte),
# since Xilinx FPGAs SPI-boot from address zero.

import socket
import struct
import time
import logging
import sys
import os
import binascii


# Work towards compatibility with both python2 and python3
def bafromhex(bs):
    return bytearray(binascii.unhexlify(bs))


def hexfromba(ba):
    if sys.version_info[0] < 3:
        return binascii.hexlify(ba)
    else:
        return ba.hex()


EXPERT = False  # not externally documented

default_bp_bits = 5  # 101 = protect lower 1/4 (see Section 8.3, Table 41)
# that makes sense now that our golden images are compressed to ~2 MB
default_sr1 = 0x80 | (default_bp_bits << 2)  # Set SRWD bit.  This byte used to be 0x98, now 0x94

# prefix
MSG_PREFIX     = bafromhex(b'5201')            # 52 01
CHK_PREFIX     = bafromhex(b'5200')            # 52 00

# instruction set
RELEASE_PD     = bafromhex(b'01ab')            # 01 ab              Release Power Down
READ_STATUS_1  = bafromhex(b'020500')          # 05 dd              Read Status Register
READ_STATUS_2  = bafromhex(b'023500')
READ_JEDEC_ID  = bafromhex(b'049f000000')      # 9F dd dd dd        Read JEDEC ID (RDID)
READ_DEVICE_ID = bafromhex(b'06900000000000')  # 90 00 00 00 dd dd  Read Device ID
READ_CONFIG_REG = bafromhex(b'023500')         # 35 dd              Read Configuration Register
CLEAR_STATUS   = bafromhex(b'0130')            # 30                 Clear Status Register
RESET_CHIP     = bafromhex(b'01f0')            # f0                 Software reset

ERASE_SECTOR   = bafromhex(b'0420')            # 20 nn nn nn        Erase Sector (4kB)
ERASE_BLOCK_32 = bafromhex(b'0452')            # 52 nn nn nn        Erase Block  (32kB)
ERASE_BLOCK_64 = bafromhex(b'04d8')            # d8 nn nn nn        Erase Block  (64kB)
READ_FAST      = bafromhex(b'0d0b')            # 0b nn nn nn        Fast Read (261 bytes)
READ_DATA      = bafromhex(b'0c03')            # 03 nn nn nn        Read Data (260 bytes)
PAGE_PROG      = bafromhex(b'0c02')            # 02 nn nn nn dd     Page program (260 bytes)
WRITE_DISABLE  = bafromhex(b'0104')            # 04                 Write Disable
WRITE_ENABLE   = bafromhex(b'0106')            # 06                 Write Enable (WREN)
WRITE_STATUS   = bafromhex(b'0201')            # 01 dd              Write Status Register (WRR)
WRITE_CONFIG   = bafromhex(b'0301')            # 01 dd dd           Write Status and Config (WRR)
READ_OTP       = bafromhex(b'0d4b')            # 4b nn nn nn        Like Fast Read (261 bytes)

# ICAP_SPARTAN6 commands
# UG380 table 7-1
ICAP_DUMMY     = bafromhex(b'ffff')            # DUMMY
ICAP_SYNC_H    = bafromhex(b'aa99')
ICAP_SYNC_L    = bafromhex(b'5566')
ICAP_W_GEN1    = bafromhex(b'3261')
ICAP_W_GEN2    = bafromhex(b'3281')
ICAP_W_GEN3    = bafromhex(b'32a1')
ICAP_W_GEN4    = bafromhex(b'32c1')
ICAP_W_CMD     = bafromhex(b'30a1')
ICAP_IPROG     = bafromhex(b'000e')
ICAP_NOOP      = bafromhex(b'2000')            # NO OP for IPROG

# GENERAL 3,4, where Golden image lives
# GOLDEN_AD      = 0x10000
GOLDEN_AD      = 0x0

# addressing information of target
# grep "ip =" board_support/xilinx/ether_mc.vh
IPADDR = 'localhost'
PORTNUM = 4000
WAIT = 0.05
PAGE = 256


# Reverse bits within a byte
def byterev(n):
    unib = n >> 4
    lnib = n & 0x0f
    mapper = "084c2a6e195d3b7f"  # bit-reversed nibble lookup
    return (mapper[lnib] + mapper[unib]).decode('hex')


def do_message(s, p, verbose=False):
    pp = MSG_PREFIX + bytearray(p)
    if verbose:
        print("sending  " + hexfromba(pp))
    s.send(pp)
    rr, addr = s.recvfrom(1024)  # buffer size is 1024 bytes
    rr = bytearray(rr)
    r_status = rr[1]
    if verbose:
        print("initiator: status %d, length %d" % (r_status, len(rr)))
    # status 2: accepted command, not done
    # status 0: rejected command, still not done with previous one
    # status 1: rejected command, but at least the previous one is done
    retries = 0
    while r_status != 1:
        time.sleep(WAIT)
        flusher = CHK_PREFIX + bytearray(len(p) * [0])
        s.send(flusher)
        rr, addr = s.recvfrom(1024)  # buffer size is 1024 bytes
        rr = bytearray(rr)
        r_status = rr[1]
        retries += 1
        if verbose:
            print("retry %d: status %d, length %d" % (retries, r_status, len(rr)))
    if verbose:
        print("received " + hexfromba(rr))
    if verbose or rr[0] != 0x51:
        print("rtype  = 0x%02x (expected 0x51)" % rr[0])
    r = rr[2:]
    return r, addr


# Read Manufacturer ID, JEDEC ID and Device ID
def read_id(s):
    logging.info('Reading ID...')
    p = READ_STATUS_1 + READ_STATUS_2 + READ_STATUS_1 + READ_JEDEC_ID + READ_DEVICE_ID
    r, addr = do_message(s, p, verbose=False)
    manu_id = r[len(r) - 2]
    dev_id = r[len(r) - 1]
    capacity = r[len(r) - 8]
    mem_type = r[len(r) - 9]
    logging.debug('From: %s \n Tx length: %d\n Rx length: %d\n' % (addr, len(p), len(r)))
    manu_list = {1: "Cypress"}
    manu_name = manu_list[manu_id] if manu_id in manu_list else "Unknown"
    cap_list = {0x18: "128 Mb", 0x19: "256 Mb"}
    cap_name = cap_list[capacity] if capacity in cap_list else "Unknown"
    print('Manufacturer ID: %02x (%s)' % (manu_id, manu_name))
    print('Device ID:       %02x' % dev_id)
    print('Memory Type:     %02x' % mem_type)
    print('Capacity:        %02x (%s)' % (capacity, cap_name))
    return


# Read status reg 1, twice for good measure
def read_status_config(s, verbose=False):
    p = READ_CONFIG_REG + 2 * READ_STATUS_1
    r, addr = do_message(s, p, verbose=False)
    status_reg = r[len(r) - 1]
    config_reg = r[len(r) - 1 - 2 * len(READ_STATUS_1)]
    if verbose:
        print("CONFIG_REG (CR1) = 0x%2.2x" % config_reg)
        bits = ["LC1", "LC0", "TBPROT", "DNU", "BPNV", "TBPARM", "QUAD", "FREEZE"]
        for ix, b in enumerate(bits):
            v = (config_reg >> (7 - ix)) & 1
            print("%8s %d" % (b, v))
        logging.debug('From: %s \n Tx length: %d\n Rx length: %d\n' % (addr, len(p), len(r)))
        logging.info('Check Status Reg: %02x' % status_reg)
    return status_reg, config_reg


#  20 nn nn nn   Sector Erase (4 kB)
#  05 rr         Read status register until completion, S0=0
def erase_mem(s, ad, size):
    if size == 'SECTOR':
        p = ERASE_SECTOR
    elif size == '32KB':
        p = ERASE_BLOCK_32
    elif size == '64KB':
        p = ERASE_BLOCK_64
    else:
        logging.error('Wrong buffer size to erase.')
    logging.info('Erasing %s at address 0x%x...' % (size, ad))
    pp = p + three_bytes(ad) + 5 * READ_STATUS_1
    r, addr = do_message(s, pp)
    status_reg = r[-1]
    logging.debug('From: %s \n Tx length: %d\n Rx length: %d\n' % (addr, len(pp), len(r)))
    logging.debug('Check Status Reg: %x' % status_reg)
    return ~status_reg


#  06/04         Write Enable/Disable
#  05 rr         Read status register until completion, S0=0
def write_enable(s, enable):
    if enable is True:
        p = WRITE_ENABLE
        logging.debug('Enabling Write Register')
    else:
        p = WRITE_DISABLE
        logging.debug('Disabling Write Register')
    pp = p + 6 * READ_STATUS_1
    r, addr = do_message(s, pp)
    status_reg = r[-1]
    logging.debug('From: %s \n Tx length: %d\n Rx length: %d\n' % (addr, len(pp), len(r)))
    logging.debug('Check Write Enable Status Reg: %x' % status_reg)
    if (status_reg & 0x60) != 0:
        print("Aaaaugh!  Errors reported in write_enable status reg 0x%2.2x" % status_reg)
        exit()
    return (status_reg & 0x3) == 0x2


# encode an integer as three bytes
# used to specify addresses when building SPI commands
def three_bytes(ad):
    adx = struct.pack('!i', ad)
    return bytearray(adx[1:4])


def page_read(s, ad, fast=False, otp=False):
    if otp:
        #  4b nn nn nn xx dd dd ... dd  Fast Read (261 bytes)
        #  note padding byte between address and first data byte
        p = READ_OTP + three_bytes(ad) + bytearray(257 * [0])
    elif fast:
        #  0b nn nn nn xx dd dd ... dd  Fast Read (261 bytes)
        #  note padding byte between address and first data byte
        p = READ_FAST + three_bytes(ad) + bytearray(257 * [0])
    else:
        #  03 nn nn nn xx dd ... dd  Fast Read (260 bytes)
        p = READ_DATA + three_bytes(ad) + bytearray(256 * [0])
    r, addr = do_message(s, p)
    if len(r) != len(p):
        logging.warning('length error %d reading address %d\n' % (len(r), ad))
    block = r[-256:]
    return block


# C. Wolf's spiflash.v simulation of a W25Q128JV needs to hear this command
# before it will run normal commands
def power_up(s):
    p = RELEASE_PD
    r, addr = do_message(s, p)
    return


# Needed after an attempt to erase or program a write-protected block
def clear_status(s):
    p = CLEAR_STATUS
    r, addr = do_message(s, p)
    return


def prog_status(s):
    good = True
    clear_status(s)
    status, cnf = read_status_config(s)
    if (status & 0x3) != 0:
        logging.info("Status 0x%2.2x: clear errors first" % status)
        good = False
    # require TBPROT set, BPNV clear
    # ignore DNU and TBPARM at least for now
    if (cnf & 0x28) != 0x20:
        logging.info("CONFIG_REG 0x%2x OTP bits not good for programming!" % cnf)
        good = False

    return good, status, cnf


def set_block_protect(s, protect=True):
    good = True
    clear_status(s)
    status, cnf = read_status_config(s)
    status1 = status & 0xE3  # first clear all BP bits in our copy
    if protect:
        status1 = status1 | (default_bp_bits << 2)

    write_status(s, status1)
    time.sleep(0.3)  # empirically needed,
    read_id(s)  # otherwise status2 comes back not updated
    status2, cnf = read_status_config(s)
    if status2 != status1:
        logging.info("Failed to set status from 0x%2.2x to 0x%2.2x, now 0x%2.2x" % (status, status1, status2))
        logging.info("Check Write-Protect switch")
        good = False

    return good, status, cnf


def enable_wp(s):
    return set_block_protect(s, protect=True)


def disable_wp(s):
    return set_block_protect(s, protect=False)


def set_prog(s, prog=True):
    prog_good, _, _ = prog_status(s)
    if not prog_good:
        return False

    protect = not prog
    write_good, _, _ = set_block_protect(s, protect=protect)
    if not write_good:
        return False

    return True


def enable_prog(s):
    set_prog(s, prog=True)


def disable_prog(s):
    set_prog(s, prog=False)


def check_prog(s):
    good, status, cnf = prog_status(s)
    logging.info('Status Reg: 0x%02x, Config Reg: 0x%02x' % (status, cnf))

    if good and ((status & 0x1C) == 0):
        print("Flash is writable")
        return True
    else:
        print("Flash is NOT writable")
        return False


# Not currently used
def reset_chip(s):
    p = RESET_CHIP
    r, addr = do_message(s, p)
    return


def page_program(s, ad, bd):
    # 256 bytes of data 'bd' to be written to page at address 'ad'
    if len(bd) != PAGE:
        logging.warning('length of data %d not equal to 256' % (len(bd)))
        # pad with 0xff
        pad = (PAGE - len(bd)) * bytearray(b'\xFF')
        bd += pad
        logging.warning('padded length now %d' % (len(bd)))
    logging.debug('Page Programming at %d...', ad)
    # sys.stdout.write('.')
    p = PAGE_PROG + three_bytes(ad) + bd
    r, addr = do_message(s, p)
    time.sleep(0.00055)
    logging.debug('From: %s \n Tx length: %d\n Rx length: %d\n' % (addr, len(p), len(r)))
    return


# Write Status Register (and optionally Config)
def write_status(s, v, config=None):
    clear_status(s)
    if config is None:
        p = WRITE_ENABLE + WRITE_STATUS + bytes([v])
    else:
        p = WRITE_ENABLE + WRITE_CONFIG + bytes([v, config])
    pp = p + 7 * READ_STATUS_1
    logging.info('Write Status')
    r, addr = do_message(s, pp, verbose=True)


# Read flash content and dump
def flash_dump(s, file_name, ad, page_count, otp=False):
    size = page_count << 8
    logging.info('Dumping flash content from add 0x%x to add 0x%x into %s, length = 0x%x...'
                 % (ad, ad + size, file_name, size))
    f = open(file_name, 'wb')
    for ba in range(ad >> 8, (ad + size) >> 8):
        bd = page_read(s, ba << 8, fast=False, otp=otp)
        f.write(bd)
    f.close()
    return


# Verify that flash contents match local file
def remote_verify(s, file_name, ad, size):
    start_p = ad >> 8
    stop_p = ((ad + size - 1) >> 8) + 1
    final_a = (stop_p << 8) + 255
    logging.info('Verifying file %s to %s from add 0x%x to add 0x%x, length = 0x%x...'
                 % (file_name, IPADDR, ad, final_a, size))
    f = open(file_name, 'rb')
    ok = True
    for ba in range(start_p, stop_p):
        f.seek((ba << 8) - ad)
        bd_file = f.read(PAGE)
        bd = page_read(s, ba << 8, fast=False, otp=False)
        if ba+1 == stop_p:  # last block of file may be short
            bd = bd[:len(bd_file)]
        # print(ba, len(bd), len(bd_file), bd == bd_file)
        if ba % 512 == 0:
            sys.stdout.write(".")
            sys.stdout.flush()
        if bd != bd_file:
            ok = False
            break
    sys.stdout.write("\n")
    f.close()
    return ok


# Read local file and write to flash from FF to 00
def remote_program(s, file_name, ad, size):
    start_p = ad >> 8
    # start_a = start_p << 8
    stop_p = ((ad + size - 1) >> 8) + 1
    final_a = (stop_p << 8) + 255
    logging.info('Programming file %s to %s from add 0x%x to add 0x%x, length = 0x%x...'
                 % (file_name, IPADDR, ad, final_a, size))
    f = open(file_name, 'rb')
    # assume that '.bin' file size is always less than whole pages
    for ba in reversed(range(start_p, stop_p)):
        print("block %d\r" % ba, end='', flush=True)
        f.seek((ba << 8) - ad)
        bd = f.read(PAGE)
        while not (write_enable(s, True)):
            time.sleep(WAIT)
        page_program(s, ba << 8, bd)
    else:
        print('')
    f.close()
    return


# Erase flash from 00 to FF, step 64KB
def remote_erase(s, ad, size):
    start_p = ad >> 16
    start_a = start_p << 16
    stop_p = ((ad + size - 1) >> 16) + 1
    final_a = (stop_p << 16) - 1
    logging.info('Erasing flash %s from addr 0x%x to addr 0x%x, length = 0x%x...'
                 % (IPADDR, start_a, final_a, size))
    for ba in range(start_p, stop_p):
        while not (write_enable(s, True)):
            time.sleep(WAIT)
        erase_mem(s, ba << 16, '64KB')
    return


# Specific to Spartan-6
def reboot_spartan6(s, ad):
    logging.info('Rebooting FPGA %s to add 0x%x...' % (IPADDR, ad))
    #      88ffffffffffffaa9955663261xxxx328103xx32a1xxxx32c103xx30a1000e
    # p = '88ffffffffffffaa995566326100003281030132a1000032c1031030a1000e'.decode('hex')
    p1 = bafromhex('88') + 3 * ICAP_DUMMY + ICAP_SYNC_H + ICAP_SYNC_L
    ad1 = bytearray(struct.pack('!i', ad))
    ad2 = bytearray(struct.pack('!i', GOLDEN_AD))
    p2 = ICAP_W_GEN1 + ad1[2:4] + ICAP_W_GEN2 + bytearray([READ_DATA[1], ad1[1]])
    p3 = ICAP_W_GEN3 + ad2[2:4] + ICAP_W_GEN4 + bytearray([READ_DATA[1], ad2[1]])
    p4 = ICAP_W_CMD + ICAP_IPROG
    p = p1 + p2 + p3 + p4 + 113 * ICAP_NOOP
    print(hexfromba(p))
    if len(p) != 257:
        print("internal error")
        sys.exit()
    s.send(MSG_PREFIX + p)
    # if the reboot succeeds, we don't get an answer.
    # could read with a timeout, as a way to report failure to reboot.


def reboot_7series(s, ad):
    '''
    ICAPE2 commands (7-series)
    UG953? no, that just covers instantiation
    XAPP1247? no
    UG470? yes, see example in Table 5-18, Configuration Packets on p. 103,
    and register address in Table 5-22.
    FFFFFFFF  dummy
    AA995566  sync
    20000000  Type 1 No Op
    30020001  Type 1 Write 1 word to WBSTAR
    00000000  Warm Boot Start Address
    30008001  Type 1 Write 1 word to CMD
    0000000F  IPROG command
    20000000  Type 1 No Op
    Our hardware uses 16-bit access to ICAPE2, but that's kind of hidden
    '''
    wbstar = "%8.8x" % ad
    # first command byte encodes payload length 256, route to ICAPE2
    cmds = "88" + "FFFFFFFFFFFFFFFFAA9955662000000030020001" + wbstar + "300080010000000F"
    icape2_noop = "20000000"
    print(cmds)
    cmdb = bafromhex(cmds + 56 * icape2_noop)
    if len(cmdb) != 257:
        print("internal error")
        sys.exit()
    s.send(MSG_PREFIX + cmdb)


def main():
    logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
    import argparse
    parser = argparse.ArgumentParser(
        description="Utility for working with SPI Flash chips attached to Packet Badger")
    parser.add_argument('--ip', default='192.168.19.8', help='IP address')
    parser.add_argument('--udp', type=int, default=804, help='UDP Port number')
    if EXPERT:
        parser.add_argument('-a', '--add', type=lambda x: int(x, 0), help='Flash offset address')
    parser.add_argument('--upper', action='store_true', help="Use upper half of flash")
    parser.add_argument('--pages', type=int, help='Number of 256-byte pages')
    parser.add_argument('--mem_read', action='store_true', help='Read ROM info')
    parser.add_argument('--id', action='store_true',
                        help='Read SPI flash chip identification and status')
    parser.add_argument('--erase', type=lambda x: int(x, 0),
                        help='Number of 256-byte sectors to erase')
    parser.add_argument('--power', action='store_true', help='power up the flash chip')
    parser.add_argument('--program', type=str, help='File to be stored in SPI Flash')
    parser.add_argument('--verify', action='store_true', help="just verify, don't program")
    parser.add_argument('--dump', type=str, help='Dump flash memory contents into file')
    parser.add_argument('--wait', default=0.001, type=float,
                        help='Wait time between consecutive writes (seconds)')
    parser.add_argument('--otp', action='store_true',
                        help='Access One Time Programmable area of S25FL chip')
    parser.add_argument('--clear_status', action='store_true',
                        help='Clear status (CLSR)')
    parser.add_argument('--force_write_enable', action='store_true',
                        help='Configure flash to write normally protected blocks; only works if WE# pin is high')
    parser.add_argument('--check_prog', action='store_true', help="Check if flash is writable")
    if EXPERT:
        parser.add_argument('--disable_wp', action='store_true', help="Disable Write-Protect mechanism")
        parser.add_argument('--enable_wp', action='store_true', help="Enable Write-Protect mechanism")
        parser.add_argument('--status_write', type=lambda x: int(x, 0),
                            help='A value to be written to status register (Experts only)')
        parser.add_argument('--config_write', type=lambda x: int(x, 0),
                            help='A value to be written to the config register (Experts only)')
    parser.add_argument('--config_init', action='store_true',
                        help='Set OTP bits to Marble default')
    # TODO: Does the user really need to know this? Can this just be queried from the chip?
    parser.add_argument('--reboot6', action='store_true',
                        help='Reboot chip using Xilinx Spartan6 ICAP primitive')
    parser.add_argument('--reboot7', action='store_true',
                        help='Reboot chip using Xilinx 7-Series ICAPE2 primitive')
    args = parser.parse_args()

    # numeric_level = getattr(logging, "DEBUG", None)
    # logging.basicConfig(level=numeric_level)

    global IPADDR, PORTNUM, WAIT
    IPADDR, PORTNUM, WAIT = args.ip, args.udp, args.wait
    # initialize a socket, think of it as a cable
    # SOCK_DGRAM specifies that this is UDP
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    # connect the socket, think of it as connecting the cable to the address location

    sock.connect((IPADDR, PORTNUM))

    # default starting address and length
    ad = 8388608 if args.upper else 0
    if EXPERT and args.add is not None:
        ad = args.add
    # 1814 for XC6SLX16, could also get this from JEDEC status?
    page_count = 1814
    page_count = 2

    if args.pages is not None:
        page_count = args.pages

    if args.power:
        power_up(sock)

    if args.dump is not None:
        flash_dump(sock, args.dump, ad, page_count, otp=args.otp)

    if args.program is not None:
        prog_file = args.program
        fileinfo = os.stat(prog_file)
        size = fileinfo.st_size
        print("file size %d" % size)
        if size > 7*1024*1024:
            print("Too big!")
            exit(1)

        prog_good, _, _ = prog_status(sock)
        if not prog_good:
            exit(1)

        if args.force_write_enable:
            if args.verify:
                print("Don't force and verify at the same time")
                exit(1)
            write_good = disable_wp(sock)
            if not write_good:
                exit(1)
        if args.verify:
            ok = remote_verify(sock, prog_file, ad, size)
            print("Verify result is %s" % ("GOOD" if ok else "BAD"))
            exit(0 if ok else 1)
        else:
            remote_erase(sock, ad, size)
            remote_program(sock, prog_file, ad, size)
        if args.force_write_enable:
            enable_wp(sock)  # back to what it was

    if args.check_prog:
        check_prog(sock)

    if EXPERT and args.disable_wp is True:
        enable_prog(sock)

    if EXPERT and args.enable_wp is True:
        enable_wp(sock)  # can be used to recover messed-up BP bits?

    if args.erase:
        remote_erase(sock, ad, args.erase)

    if args.clear_status:
        clear_status(sock)
        write_enable(sock, False)
        clear_status(sock)

    if args.id:
        read_id(sock)
        read_status_config(sock, verbose=True)

    # TODO: Ignoring test_tx since no code path exists

    if args.config_init:
        print("Before:")
        status, cnf = read_status_config(sock, verbose=True)
        if (cnf != 0) and not EXPERT:
            print("Unexpected CONFIG, aborting")
            exit(1)
        write_status(sock, default_sr1, config=0x24)
    elif EXPERT and args.status_write is not None:
        write_status(sock, args.status_write, config=args.config_write)

    if args.reboot6:
        reboot_spartan6(sock, ad)
    elif args.reboot7:
        reboot_7series(sock, ad)

    logging.info('Done.')

    # close the socket
    sock.close()


if __name__ == "__main__":
    main()