net: add a generic udp protocol

This commit adds a generic udp protocol framework in the
network loop. So protocol based on udp may be implemented
without modifying the network loop (for example custom
wait magic packet).

Signed-off-by: Philippe Reynes <philippe.reynes@softathome.com>
Reviewed-by: Simon Glass <sjg@chromium.org>
diff --git a/net/Kconfig b/net/Kconfig
index 6874b55..1b3e420 100644
--- a/net/Kconfig
+++ b/net/Kconfig
@@ -8,6 +8,12 @@
 
 if NET
 
+config PROT_UDP
+	bool "Enable generic udp framework"
+	help
+	  Enable a generic udp framework that allows defining a custom
+	  handler for udp protocol.
+
 config BOOTP_SEND_HOSTNAME
 	bool "Send hostname to DNS server"
 	help
diff --git a/net/Makefile b/net/Makefile
index fef71b9..76527f7 100644
--- a/net/Makefile
+++ b/net/Makefile
@@ -27,6 +27,7 @@
 obj-$(CONFIG_CMD_TFTPBOOT) += tftp.o
 obj-$(CONFIG_UDP_FUNCTION_FASTBOOT)  += fastboot.o
 obj-$(CONFIG_CMD_WOL)  += wol.o
+obj-$(CONFIG_PROT_UDP) += udp.o
 
 # Disable this warning as it is triggered by:
 # sprintf(buf, index ? "foo%d" : "foo", index)
diff --git a/net/net.c b/net/net.c
index 28d9eeb..1ce0eb5 100644
--- a/net/net.c
+++ b/net/net.c
@@ -102,6 +102,7 @@
 #if defined(CONFIG_CMD_PCAP)
 #include <net/pcap.h>
 #endif
+#include <net/udp.h>
 #if defined(CONFIG_LED_STATUS)
 #include <miiphy.h>
 #include <status_led.h>
@@ -544,6 +545,9 @@
 			break;
 		}
 
+		if (IS_ENABLED(CONFIG_PROT_UDP) && protocol == UDP)
+			udp_start();
+
 		break;
 	}
 
@@ -1364,6 +1368,13 @@
 		}
 		goto common;
 #endif
+#if defined(CONFIG_PROT_UDP)
+	case UDP:
+		if (udp_prereq())
+			return 1;
+		goto common;
+#endif
+
 #if defined(CONFIG_CMD_NFS)
 	case NFS:
 #endif
@@ -1375,7 +1386,7 @@
 			return 1;
 		}
 #if	defined(CONFIG_CMD_PING) || defined(CONFIG_CMD_SNTP) || \
-	defined(CONFIG_CMD_DNS)
+	defined(CONFIG_CMD_DNS) || defined(CONFIG_PROT_UDP)
 common:
 #endif
 		/* Fall through */
diff --git a/net/udp.c b/net/udp.c
new file mode 100644
index 0000000..a93822f
--- /dev/null
+++ b/net/udp.c
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (C) 2020 Philippe Reynes <philippe.reynes@softathome.com>
+ */
+
+#include <common.h>
+#include <net.h>
+#include <net/udp.h>
+
+static struct udp_ops *udp_ops;
+
+int udp_prereq(void)
+{
+	int ret = 0;
+
+	if (udp_ops->prereq)
+		ret = udp_ops->prereq(udp_ops->data);
+
+	return ret;
+}
+
+int udp_start(void)
+{
+	return udp_ops->start(udp_ops->data);
+}
+
+int udp_loop(struct udp_ops *ops)
+{
+	int ret = -1;
+
+	if (!ops) {
+		printf("%s: ops should not be null\n", __func__);
+		goto out;
+	}
+
+	if (!ops->start) {
+		printf("%s: no start function defined\n", __func__);
+		goto out;
+	}
+
+	udp_ops = ops;
+	ret = net_loop(UDP);
+
+ out:
+	return ret;
+}