console-server: refactor pollfd management

Instead of the previous memory management of pollfd array,
with a fixed and flexible part and hardcoded indices,
provide two functions to request and release pollfds.

- console_server_request_pollfd
- console_server_release_pollfd

The pollfds are still in the same array but can be requested and
released by these functions now. struct console_server and
struct console now contain indices into that array of pollfds.

The benefit of this contribution is that the new interface provides a
clean allocator-like abstraction for requesting and releasing pollfds,
which will scale to multiple consoles and can be refactored or
unit-tested more easily in the future.

The previous implementation was tightly coupled to the single-console
use-case and the pollfds stored at hardcoded indices.

Change-Id: I93226699618130b175bffbeb4f71c20c91a7083a
Signed-off-by: Alexander Hansen <alexander.hansen@9elements.com>
Signed-off-by: Andrew Jeffery <andrew@codeconstruct.com.au>
diff --git a/console-server.h b/console-server.h
index 1b7c15c..5213dd0 100644
--- a/console-server.h
+++ b/console-server.h
@@ -115,6 +115,15 @@
 		};
 	} tty;
 
+	// All the pollfds are stored here,
+	// so 'poll' can operate on them.
+	// The other 'pollfd*' are just pointers to this array.
+	struct pollfd *pollfds;
+	size_t capacity_pollfds;
+
+	// index into pollfds
+	size_t tty_pollfd_index;
+
 	struct console *active;
 };
 
@@ -137,7 +146,9 @@
 	struct poller **pollers;
 	long n_pollers;
 
-	struct pollfd *pollfds;
+	// index into (struct console_server)->pollfds
+	size_t dbus_pollfd_index;
+
 	struct sd_bus *bus;
 };
 
@@ -149,13 +160,9 @@
 	poller_timeout_fn_t timeout_fn;
 	struct timeval timeout;
 	bool remove;
-};
 
-/* we have two extra entry in the pollfds array for the VUART tty */
-enum internal_pollfds {
-	POLLFD_HOSTTTY = 0,
-	POLLFD_DBUS = 1,
-	MAX_INTERNAL_POLLFD = 2,
+	// index into (struct console_server)->pollfds
+	size_t pollfd_index;
 };
 
 struct poller *console_poller_register(struct console *console,
@@ -253,3 +260,11 @@
 	} while (0)
 
 #define BUILD_ASSERT_OR_ZERO(c) (sizeof(char[(c) ? 1 : -1]) - 1)
+
+// returns the index of that pollfd in server->pollfds
+// we cannot return a pointer because 'realloc' may move server->pollfds
+ssize_t console_server_request_pollfd(struct console_server *server, int fd,
+				      short int events);
+
+int console_server_release_pollfd(struct console_server *server,
+				  size_t pollfd_index);