1// SPDX-License-Identifier: GPL-2.0
2/*
3 * The Virtual DVB test driver serves as a reference DVB driver and helps
4 * validate the existing APIs in the media subsystem. It can also aid
5 * developers working on userspace applications.
6 *
7 * Copyright (C) 2020 Daniel W. S. Almeida
8 */
9#define pr_fmt(fmt) KBUILD_MODNAME ":%s, %d: " fmt, __func__, __LINE__
10
11#include <linux/printk.h>
12#include <linux/ratelimit.h>
13#include <linux/string.h>
14#include <linux/types.h>
15
16#include "vidtv_common.h"
17
18/**
19 * vidtv_memcpy() - wrapper routine to be used by MPEG-TS
20 *	generator, in order to avoid going past the
21 *	output buffer.
22 * @to:	Starting element to where a MPEG-TS packet will
23 *	be copied.
24 * @to_offset:	Starting position of the @to buffer to be filled.
25 * @to_size:	Size of the @to buffer.
26 * @from:	Starting element of the buffer to be copied.
27 * @len:	Number of elements to be copy from @from buffer
28 *	into @to+ @to_offset buffer.
29 *
30 * Note:
31 *	Real digital TV demod drivers should not have memcpy
32 *	wrappers. We use it here because emulating MPEG-TS
33 *	generation at kernelspace requires some extra care.
34 *
35 * Return:
36 *	Returns the number of bytes written
37 */
38u32 vidtv_memcpy(void *to,
39		 size_t to_offset,
40		 size_t to_size,
41		 const void *from,
42		 size_t len)
43{
44	if (unlikely(to_offset + len > to_size)) {
45		pr_err_ratelimited("overflow detected, skipping. Try increasing the buffer size. Needed %zu, had %zu\n",
46				   to_offset + len,
47				   to_size);
48		return 0;
49	}
50
51	memcpy(to + to_offset, from, len);
52	return len;
53}
54
55/**
56 * vidtv_memset() - wrapper routine to be used by MPEG-TS
57 *	generator, in order to avoid going past the
58 *	output buffer.
59 * @to:	Starting element to set
60 * @to_offset:	Starting position of the @to buffer to be filled.
61 * @to_size:	Size of the @to buffer.
62 * @c:		The value to set the memory to.
63 * @len:	Number of elements to be copy from @from buffer
64 *	into @to+ @to_offset buffer.
65 *
66 * Note:
67 *	Real digital TV demod drivers should not have memset
68 *	wrappers. We use it here because emulating MPEG-TS
69 *	generation at kernelspace requires some extra care.
70 *
71 * Return:
72 *	Returns the number of bytes written
73 */
74u32 vidtv_memset(void *to,
75		 size_t to_offset,
76		 size_t to_size,
77		 const int c,
78		 size_t len)
79{
80	if (unlikely(to_offset + len > to_size)) {
81		pr_err_ratelimited("overflow detected, skipping. Try increasing the buffer size. Needed %zu, had %zu\n",
82				   to_offset + len,
83				   to_size);
84		return 0;
85	}
86
87	memset(to + to_offset, c, len);
88	return len;
89}
90