1#!/usr/bin/env python3
2# SPDX-License-Identifier: BSD-3-Clause
3#
4# Copyright (c) 2022, Intel Corporation. All rights reserved.
5
6#pylint:disable=mixed-indentation
7
8# Tool to stream data from Linux SOF driver "mtrace" debugfs
9# interface to standard output. Plain "cat" is not sufficient
10# as each read() syscall returns log data with a 32bit binary
11# header, containing the payload length.
12
13import struct
14import os
15import sys
16
17READ_BUFFER = 16384
18MTRACE_FILE = "/sys/kernel/debug/sof/mtrace/core0"
19
20fd = os.open(MTRACE_FILE, os.O_RDONLY)
21while fd >= 0:
22    # direct unbuffered os.read() must be used to comply with
23    # debugfs protocol used. each non-zero read will return
24    # a buffer containing a 32bit header and a payload
25    read_bytes = os.read(fd, READ_BUFFER)
26
27    # handle end-of-file
28    if len(read_bytes) == 0:
29        continue
30
31    if len(read_bytes) <= 4:
32        continue
33
34    header = struct.unpack('I', read_bytes[0:4])
35    data_len = header[0]
36    data = read_bytes[4:4+data_len]
37
38    os.write(sys.stdout.fileno(), data)
39