xref: /spdk/scripts/spdk-gpt.py (revision 877573897ad52be4fa8989f7617bd655b87e05c4)
1#!/usr/bin/env python3
2#  SPDX-License-Identifier: BSD-3-Clause
3#  Copyright (C) 2021 Intel Corporation
4#  All rights reserved.
5#
6
7import argparse
8import os
9import stat
10import struct
11
12
13def block_exists(block):
14    return os.path.exists(block) and stat.S_ISBLK(os.stat(block).st_mode)
15
16
17def lbsize(block):
18    if not os.path.exists("/sys/block/%s/queue/logical_block_size" % block):
19        return 512
20
21    with open("/sys/block/%s/queue/logical_block_size" % block) as lbs:
22        return int(lbs.read())
23
24
25def readb(block, offset, length, format="Q"):
26    b = os.open(block, os.O_RDONLY)
27    os.lseek(b, offset, os.SEEK_SET)
28    data = os.read(b, length)
29    os.close(b)
30    return struct.unpack(format, data)[0]
31
32
33def is_spdk_gpt(block, entry):
34    block_path = "/dev/" + block
35
36    if not block_exists(block_path):
37        print("%s is not a block device" % block)
38        return False
39
40    disk_lbsize = lbsize(block)
41    gpt_sig = 0x5452415020494645  # EFI PART
42    spdk_guid = [0x7c5222bd, 0x8f5d, 0x4087, 0x9c00, 0xbf9843c7b58c]
43
44    if readb(block_path, disk_lbsize, 8) != gpt_sig:
45        print("No valid GPT data, bailing")
46        return False
47
48    part_entry_lba = disk_lbsize * readb(block_path, disk_lbsize + 72, 8)
49    part_entry_lba = part_entry_lba + (entry - 1) * 128
50
51    guid = [
52        readb(block_path, part_entry_lba, 4, "I"),
53        readb(block_path, part_entry_lba + 4, 2, "H"),
54        readb(block_path, part_entry_lba + 6, 2, "H"),
55        readb(block_path, part_entry_lba + 8, 2, ">H"),
56        readb(block_path, part_entry_lba + 10, 8, ">Q") >> 16
57    ]
58
59    return guid == spdk_guid
60
61
62if __name__ == "__main__":
63    parser = argparse.ArgumentParser(description='Checks if SPDK GUID is present on given block device')
64    parser.add_argument('block', type=str, help='block device to check')
65    parser.add_argument('-e', '--entry', dest='entry', help='GPT partition entry',
66                        required=False, type=int, default=1)
67    args = parser.parse_args()
68    try:
69        if is_spdk_gpt(args.block.replace("/dev/", ""), args.entry):
70            exit(0)
71        exit(1)
72    except Exception as e:
73        print("Failed to read GPT data from %s (%s)" % (args.block, e))
74        exit(1)
75