hv_kvp.c revision 272322
1/*-
2 * Copyright (c) 2014 Microsoft Corp.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice unmodified, this list of conditions, and the following
10 *    disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27/*
28 *	Author:	Sainath Varanasi.
29 *	Date:	4/2012
30 *	Email:	bsdic@microsoft.com
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: stable/10/sys/dev/hyperv/utilities/hv_kvp.c 272322 2014-09-30 17:54:57Z delphij $");
35
36#include <sys/param.h>
37#include <sys/kernel.h>
38#include <sys/conf.h>
39#include <sys/uio.h>
40#include <sys/bus.h>
41#include <sys/malloc.h>
42#include <sys/mbuf.h>
43#include <sys/module.h>
44#include <sys/reboot.h>
45#include <sys/lock.h>
46#include <sys/taskqueue.h>
47#include <sys/sysctl.h>
48#include <sys/poll.h>
49#include <sys/proc.h>
50#include <sys/kthread.h>
51#include <sys/syscallsubr.h>
52#include <sys/sysproto.h>
53#include <sys/un.h>
54#include <sys/endian.h>
55#include <sys/_null.h>
56#include <sys/signal.h>
57#include <sys/syslog.h>
58#include <sys/mutex.h>
59#include <net/if_arp.h>
60
61#include <dev/hyperv/include/hyperv.h>
62#include <dev/hyperv/netvsc/hv_net_vsc.h>
63
64#include "unicode.h"
65#include "hv_kvp.h"
66
67/* hv_kvp defines */
68#define BUFFERSIZE	sizeof(struct hv_kvp_msg)
69#define KVP_SUCCESS	0
70#define KVP_ERROR	1
71#define kvp_hdr		hdr.kvp_hdr
72
73/* hv_kvp debug control */
74static int hv_kvp_log = 0;
75SYSCTL_INT(_dev, OID_AUTO, hv_kvp_log, CTLFLAG_RW, &hv_kvp_log, 0,
76	"hv_kvp log");
77
78#define	hv_kvp_log_error(...)	do {				\
79	if (hv_kvp_log > 0)				\
80		log(LOG_ERR, "hv_kvp: " __VA_ARGS__);	\
81} while (0)
82
83#define	hv_kvp_log_info(...) do {				\
84	if (hv_kvp_log > 1)				\
85		log(LOG_INFO, "hv_kvp: " __VA_ARGS__);		\
86} while (0)
87
88/* character device prototypes */
89static d_open_t		hv_kvp_dev_open;
90static d_close_t	hv_kvp_dev_close;
91static d_read_t		hv_kvp_dev_daemon_read;
92static d_write_t	hv_kvp_dev_daemon_write;
93static d_poll_t		hv_kvp_dev_daemon_poll;
94
95/* hv_kvp prototypes */
96static int	hv_kvp_req_in_progress(void);
97static void	hv_kvp_transaction_init(uint32_t, hv_vmbus_channel *, uint64_t, uint8_t *);
98static void	hv_kvp_send_msg_to_daemon(void);
99static void	hv_kvp_process_request(void *context);
100
101/* hv_kvp character device structure */
102static struct cdevsw hv_kvp_cdevsw =
103{
104	.d_version	= D_VERSION,
105	.d_open		= hv_kvp_dev_open,
106	.d_close	= hv_kvp_dev_close,
107	.d_read		= hv_kvp_dev_daemon_read,
108	.d_write	= hv_kvp_dev_daemon_write,
109	.d_poll		= hv_kvp_dev_daemon_poll,
110	.d_name		= "hv_kvp_dev",
111};
112static struct cdev *hv_kvp_dev;
113static struct hv_kvp_msg *hv_kvp_dev_buf;
114struct proc *daemon_task;
115
116/*
117 * Global state to track and synchronize multiple
118 * KVP transaction requests from the host.
119 */
120static struct {
121
122	/* Pre-allocated work item for queue */
123	hv_work_item		work_item;
124
125	/* Unless specified the pending mutex should be
126	 * used to alter the values of the following paramters:
127	 * 1. req_in_progress
128	 * 2. req_timed_out
129	 * 3. pending_reqs.
130	 */
131	struct mtx		pending_mutex;
132
133	/* To track if transaction is active or not */
134	boolean_t		req_in_progress;
135	/* Tracks if daemon did not reply back in time */
136	boolean_t		req_timed_out;
137	/* Tracks if daemon is serving a request currently */
138	boolean_t		daemon_busy;
139	/* Count of KVP requests from Hyper-V. */
140	uint64_t		pending_reqs;
141
142
143	/* Length of host message */
144	uint32_t		host_msg_len;
145
146	/* Pointer to channel */
147	hv_vmbus_channel	*channelp;
148
149	/* Host message id */
150	uint64_t		host_msg_id;
151
152	/* Current kvp message from the host */
153	struct hv_kvp_msg	*host_kvp_msg;
154
155	 /* Current kvp message for daemon */
156	struct hv_kvp_msg	daemon_kvp_msg;
157
158	/* Rcv buffer for communicating with the host*/
159	uint8_t			*rcv_buf;
160
161	/* Device semaphore to control communication */
162	struct sema		dev_sema;
163
164	/* Indicates if daemon registered with driver */
165	boolean_t		register_done;
166
167	/* Character device status */
168	boolean_t		dev_accessed;
169} kvp_globals;
170
171/* global vars */
172MALLOC_DECLARE(M_HV_KVP_DEV_BUF);
173MALLOC_DEFINE(M_HV_KVP_DEV_BUF, "hv_kvp_dev buffer", "buffer for hv_kvp_dev module");
174
175/*
176 * hv_kvp low level functions
177 */
178
179/*
180 * Check if kvp transaction is in progres
181 */
182static int
183hv_kvp_req_in_progress(void)
184{
185
186	return (kvp_globals.req_in_progress);
187}
188
189
190/*
191 * This routine is called whenever a message is received from the host
192 */
193static void
194hv_kvp_transaction_init(uint32_t rcv_len, hv_vmbus_channel *rcv_channel,
195			uint64_t request_id, uint8_t *rcv_buf)
196{
197
198	/* Store all the relevant message details in the global structure */
199	/* Do not need to use mutex for req_in_progress here */
200	kvp_globals.req_in_progress = true;
201	kvp_globals.host_msg_len = rcv_len;
202	kvp_globals.channelp = rcv_channel;
203	kvp_globals.host_msg_id = request_id;
204	kvp_globals.rcv_buf = rcv_buf;
205	kvp_globals.host_kvp_msg = (struct hv_kvp_msg *)&rcv_buf[
206		sizeof(struct hv_vmbus_pipe_hdr) +
207		sizeof(struct hv_vmbus_icmsg_hdr)];
208}
209
210
211/*
212 * hv_kvp - version neogtiation function
213 */
214static void
215hv_kvp_negotiate_version(struct hv_vmbus_icmsg_hdr *icmsghdrp,
216			 struct hv_vmbus_icmsg_negotiate *negop,
217			 uint8_t *buf)
218{
219	int icframe_vercnt;
220	int icmsg_vercnt;
221
222	icmsghdrp->icmsgsize = 0x10;
223
224	negop = (struct hv_vmbus_icmsg_negotiate *)&buf[
225		sizeof(struct hv_vmbus_pipe_hdr) +
226		sizeof(struct hv_vmbus_icmsg_hdr)];
227	icframe_vercnt = negop->icframe_vercnt;
228	icmsg_vercnt = negop->icmsg_vercnt;
229
230	/*
231	 * Select the framework version number we will support
232	 */
233	if ((icframe_vercnt >= 2) && (negop->icversion_data[1].major == 3)) {
234		icframe_vercnt = 3;
235		if (icmsg_vercnt >= 2)
236			icmsg_vercnt = 4;
237		else
238			icmsg_vercnt = 3;
239	} else {
240		icframe_vercnt = 1;
241		icmsg_vercnt = 1;
242	}
243
244	negop->icframe_vercnt = 1;
245	negop->icmsg_vercnt = 1;
246	negop->icversion_data[0].major = icframe_vercnt;
247	negop->icversion_data[0].minor = 0;
248	negop->icversion_data[1].major = icmsg_vercnt;
249	negop->icversion_data[1].minor = 0;
250}
251
252
253/*
254 * Convert ip related info in umsg from utf8 to utf16 and store in hmsg
255 */
256static int
257hv_kvp_convert_utf8_ipinfo_to_utf16(struct hv_kvp_msg *umsg,
258				    struct hv_kvp_ip_msg *host_ip_msg)
259{
260	int err_ip, err_subnet, err_gway, err_dns, err_adap;
261	int UNUSED_FLAG = 1;
262
263	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.ip_addr,
264	    MAX_IP_ADDR_SIZE,
265	    (char *)umsg->body.kvp_ip_val.ip_addr,
266	    strlen((char *)umsg->body.kvp_ip_val.ip_addr),
267	    UNUSED_FLAG,
268	    &err_ip);
269	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.sub_net,
270	    MAX_IP_ADDR_SIZE,
271	    (char *)umsg->body.kvp_ip_val.sub_net,
272	    strlen((char *)umsg->body.kvp_ip_val.sub_net),
273	    UNUSED_FLAG,
274	    &err_subnet);
275	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.gate_way,
276	    MAX_GATEWAY_SIZE,
277	    (char *)umsg->body.kvp_ip_val.gate_way,
278	    strlen((char *)umsg->body.kvp_ip_val.gate_way),
279	    UNUSED_FLAG,
280	    &err_gway);
281	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.dns_addr,
282	    MAX_IP_ADDR_SIZE,
283	    (char *)umsg->body.kvp_ip_val.dns_addr,
284	    strlen((char *)umsg->body.kvp_ip_val.dns_addr),
285	    UNUSED_FLAG,
286	    &err_dns);
287	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.adapter_id,
288	    MAX_IP_ADDR_SIZE,
289	    (char *)umsg->body.kvp_ip_val.adapter_id,
290	    strlen((char *)umsg->body.kvp_ip_val.adapter_id),
291	    UNUSED_FLAG,
292	    &err_adap);
293
294	host_ip_msg->kvp_ip_val.dhcp_enabled = umsg->body.kvp_ip_val.dhcp_enabled;
295	host_ip_msg->kvp_ip_val.addr_family = umsg->body.kvp_ip_val.addr_family;
296
297	return (err_ip | err_subnet | err_gway | err_dns | err_adap);
298}
299
300
301/*
302 * Convert ip related info in hmsg from utf16 to utf8 and store in umsg
303 */
304static int
305hv_kvp_convert_utf16_ipinfo_to_utf8(struct hv_kvp_ip_msg *host_ip_msg,
306				    struct hv_kvp_msg *umsg)
307{
308	int err_ip, err_subnet, err_gway, err_dns, err_adap;
309	int UNUSED_FLAG = 1;
310	int guid_index;
311	struct hv_device *hv_dev;       /* GUID Data Structure */
312	hn_softc_t *sc;                 /* hn softc structure  */
313	char if_name[4];
314	unsigned char guid_instance[40];
315	char *guid_data = NULL;
316	char buf[39];
317
318	struct guid_extract {
319		char	a1[2];
320		char	a2[2];
321		char	a3[2];
322		char	a4[2];
323		char	b1[2];
324		char	b2[2];
325		char	c1[2];
326		char	c2[2];
327		char	d[4];
328		char	e[12];
329	};
330
331	struct guid_extract *id;
332	device_t *devs;
333	int devcnt;
334
335	/* IP Address */
336	utf16_to_utf8((char *)umsg->body.kvp_ip_val.ip_addr,
337	    MAX_IP_ADDR_SIZE,
338	    (uint16_t *)host_ip_msg->kvp_ip_val.ip_addr,
339	    MAX_IP_ADDR_SIZE,
340	    UNUSED_FLAG,
341	    &err_ip);
342
343	/* Adapter ID : GUID */
344	utf16_to_utf8((char *)umsg->body.kvp_ip_val.adapter_id,
345	    MAX_ADAPTER_ID_SIZE,
346	    (uint16_t *)host_ip_msg->kvp_ip_val.adapter_id,
347	    MAX_ADAPTER_ID_SIZE,
348	    UNUSED_FLAG,
349	    &err_adap);
350
351	if (devclass_get_devices(devclass_find("hn"), &devs, &devcnt) == 0) {
352		for (devcnt = devcnt - 1; devcnt >= 0; devcnt--) {
353			sc = device_get_softc(devs[devcnt]);
354
355			/* Trying to find GUID of Network Device */
356			hv_dev = sc->hn_dev_obj;
357
358			for (guid_index = 0; guid_index < 16; guid_index++) {
359				sprintf(&guid_instance[guid_index * 2], "%02x",
360				    hv_dev->device_id.data[guid_index]);
361			}
362
363			guid_data = (char *)guid_instance;
364			id = (struct guid_extract *)guid_data;
365			snprintf(buf, sizeof(buf), "{%.2s%.2s%.2s%.2s-%.2s%.2s-%.2s%.2s-%.4s-%s}",
366			    id->a4, id->a3, id->a2, id->a1,
367			    id->b2, id->b1, id->c2, id->c1, id->d, id->e);
368			guid_data = NULL;
369			sprintf(if_name, "%s%d", "hn", device_get_unit(devs[devcnt]));
370
371			if (strncmp(buf, (char *)umsg->body.kvp_ip_val.adapter_id, 39) == 0) {
372				strcpy((char *)umsg->body.kvp_ip_val.adapter_id, if_name);
373				break;
374			}
375		}
376		free(devs, M_TEMP);
377	}
378
379	/* Address Family , DHCP , SUBNET, Gateway, DNS */
380	umsg->kvp_hdr.operation = host_ip_msg->operation;
381	umsg->body.kvp_ip_val.addr_family = host_ip_msg->kvp_ip_val.addr_family;
382	umsg->body.kvp_ip_val.dhcp_enabled = host_ip_msg->kvp_ip_val.dhcp_enabled;
383	utf16_to_utf8((char *)umsg->body.kvp_ip_val.sub_net, MAX_IP_ADDR_SIZE,
384	    (uint16_t *)host_ip_msg->kvp_ip_val.sub_net,
385	    MAX_IP_ADDR_SIZE,
386	    UNUSED_FLAG,
387	    &err_subnet);
388
389	utf16_to_utf8((char *)umsg->body.kvp_ip_val.gate_way, MAX_GATEWAY_SIZE,
390	    (uint16_t *)host_ip_msg->kvp_ip_val.gate_way,
391	    MAX_GATEWAY_SIZE,
392	    UNUSED_FLAG,
393	    &err_gway);
394
395	utf16_to_utf8((char *)umsg->body.kvp_ip_val.dns_addr, MAX_IP_ADDR_SIZE,
396	    (uint16_t *)host_ip_msg->kvp_ip_val.dns_addr,
397	    MAX_IP_ADDR_SIZE,
398	    UNUSED_FLAG,
399	    &err_dns);
400
401	return (err_ip | err_subnet | err_gway | err_dns | err_adap);
402}
403
404
405/*
406 * Prepare a user kvp msg based on host kvp msg (utf16 to utf8)
407 * Ensure utf16_utf8 takes care of the additional string terminating char!!
408 */
409static void
410hv_kvp_convert_hostmsg_to_usermsg(void)
411{
412	int utf_err = 0;
413	uint32_t value_type;
414	struct hv_kvp_ip_msg *host_ip_msg = (struct hv_kvp_ip_msg *)
415		kvp_globals.host_kvp_msg;
416
417	struct hv_kvp_msg *hmsg = kvp_globals.host_kvp_msg;
418	struct hv_kvp_msg *umsg = &kvp_globals.daemon_kvp_msg;
419
420	memset(umsg, 0, sizeof(struct hv_kvp_msg));
421
422	umsg->kvp_hdr.operation = hmsg->kvp_hdr.operation;
423	umsg->kvp_hdr.pool = hmsg->kvp_hdr.pool;
424
425	switch (umsg->kvp_hdr.operation) {
426	case HV_KVP_OP_SET_IP_INFO:
427		hv_kvp_convert_utf16_ipinfo_to_utf8(host_ip_msg, umsg);
428		break;
429
430	case HV_KVP_OP_GET_IP_INFO:
431		utf16_to_utf8((char *)umsg->body.kvp_ip_val.adapter_id,
432		    MAX_ADAPTER_ID_SIZE,
433		    (uint16_t *)host_ip_msg->kvp_ip_val.adapter_id,
434		    MAX_ADAPTER_ID_SIZE, 1, &utf_err);
435
436		umsg->body.kvp_ip_val.addr_family =
437		    host_ip_msg->kvp_ip_val.addr_family;
438		break;
439
440	case HV_KVP_OP_SET:
441		value_type = hmsg->body.kvp_set.data.value_type;
442
443		switch (value_type) {
444		case HV_REG_SZ:
445			umsg->body.kvp_set.data.value_size =
446			    utf16_to_utf8(
447				(char *)umsg->body.kvp_set.data.msg_value.value,
448				HV_KVP_EXCHANGE_MAX_VALUE_SIZE - 1,
449				(uint16_t *)hmsg->body.kvp_set.data.msg_value.value,
450				hmsg->body.kvp_set.data.value_size,
451				1, &utf_err);
452			/* utf8 encoding */
453			umsg->body.kvp_set.data.value_size =
454			    umsg->body.kvp_set.data.value_size / 2;
455			break;
456
457		case HV_REG_U32:
458			umsg->body.kvp_set.data.value_size =
459			    sprintf(umsg->body.kvp_set.data.msg_value.value, "%d",
460				hmsg->body.kvp_set.data.msg_value.value_u32) + 1;
461			break;
462
463		case HV_REG_U64:
464			umsg->body.kvp_set.data.value_size =
465			    sprintf(umsg->body.kvp_set.data.msg_value.value, "%llu",
466				(unsigned long long)
467				hmsg->body.kvp_set.data.msg_value.value_u64) + 1;
468			break;
469		}
470
471		umsg->body.kvp_set.data.key_size =
472		    utf16_to_utf8(
473			umsg->body.kvp_set.data.key,
474			HV_KVP_EXCHANGE_MAX_KEY_SIZE - 1,
475			(uint16_t *)hmsg->body.kvp_set.data.key,
476			hmsg->body.kvp_set.data.key_size,
477			1, &utf_err);
478
479		/* utf8 encoding */
480		umsg->body.kvp_set.data.key_size =
481		    umsg->body.kvp_set.data.key_size / 2;
482		break;
483
484	case HV_KVP_OP_GET:
485		umsg->body.kvp_get.data.key_size =
486		    utf16_to_utf8(umsg->body.kvp_get.data.key,
487			HV_KVP_EXCHANGE_MAX_KEY_SIZE - 1,
488			(uint16_t *)hmsg->body.kvp_get.data.key,
489			hmsg->body.kvp_get.data.key_size,
490			1, &utf_err);
491		/* utf8 encoding */
492		umsg->body.kvp_get.data.key_size =
493		    umsg->body.kvp_get.data.key_size / 2;
494		break;
495
496	case HV_KVP_OP_DELETE:
497		umsg->body.kvp_delete.key_size =
498		    utf16_to_utf8(umsg->body.kvp_delete.key,
499			HV_KVP_EXCHANGE_MAX_KEY_SIZE - 1,
500			(uint16_t *)hmsg->body.kvp_delete.key,
501			hmsg->body.kvp_delete.key_size,
502			1, &utf_err);
503		/* utf8 encoding */
504		umsg->body.kvp_delete.key_size =
505		    umsg->body.kvp_delete.key_size / 2;
506		break;
507
508	case HV_KVP_OP_ENUMERATE:
509		umsg->body.kvp_enum_data.index =
510		    hmsg->body.kvp_enum_data.index;
511		break;
512
513	default:
514		hv_kvp_log_info("%s: daemon_kvp_msg: Invalid operation : %d\n",
515		    __func__, umsg->kvp_hdr.operation);
516	}
517}
518
519
520/*
521 * Prepare a host kvp msg based on user kvp msg (utf8 to utf16)
522 */
523static int
524hv_kvp_convert_usermsg_to_hostmsg(void)
525{
526	int hkey_len = 0, hvalue_len = 0, utf_err = 0;
527	struct hv_kvp_exchg_msg_value *host_exchg_data;
528	char *key_name, *value;
529
530	struct hv_kvp_msg *umsg = &kvp_globals.daemon_kvp_msg;
531	struct hv_kvp_msg *hmsg = kvp_globals.host_kvp_msg;
532	struct hv_kvp_ip_msg *host_ip_msg = (struct hv_kvp_ip_msg *)hmsg;
533
534	switch (hmsg->kvp_hdr.operation) {
535	case HV_KVP_OP_GET_IP_INFO:
536		return (hv_kvp_convert_utf8_ipinfo_to_utf16(umsg, host_ip_msg));
537
538	case HV_KVP_OP_SET_IP_INFO:
539	case HV_KVP_OP_SET:
540	case HV_KVP_OP_DELETE:
541		return (KVP_SUCCESS);
542
543	case HV_KVP_OP_ENUMERATE:
544		host_exchg_data = &hmsg->body.kvp_enum_data.data;
545		key_name = umsg->body.kvp_enum_data.data.key;
546		hkey_len = utf8_to_utf16((uint16_t *)host_exchg_data->key,
547				((HV_KVP_EXCHANGE_MAX_KEY_SIZE / 2) - 2),
548				key_name, strlen(key_name),
549				1, &utf_err);
550		/* utf16 encoding */
551		host_exchg_data->key_size = 2 * (hkey_len + 1);
552		value = umsg->body.kvp_enum_data.data.msg_value.value;
553		hvalue_len = utf8_to_utf16(
554				(uint16_t *)host_exchg_data->msg_value.value,
555				((HV_KVP_EXCHANGE_MAX_VALUE_SIZE / 2) - 2),
556				value, strlen(value),
557				1, &utf_err);
558		host_exchg_data->value_size = 2 * (hvalue_len + 1);
559		host_exchg_data->value_type = HV_REG_SZ;
560
561		if ((hkey_len < 0) || (hvalue_len < 0))
562			return (HV_KVP_E_FAIL);
563
564		return (KVP_SUCCESS);
565
566	case HV_KVP_OP_GET:
567		host_exchg_data = &hmsg->body.kvp_get.data;
568		value = umsg->body.kvp_get.data.msg_value.value;
569		hvalue_len = utf8_to_utf16(
570				(uint16_t *)host_exchg_data->msg_value.value,
571				((HV_KVP_EXCHANGE_MAX_VALUE_SIZE / 2) - 2),
572				value, strlen(value),
573				1, &utf_err);
574		/* Convert value size to uft16 */
575		host_exchg_data->value_size = 2 * (hvalue_len + 1);
576		/* Use values by string */
577		host_exchg_data->value_type = HV_REG_SZ;
578
579		if ((hkey_len < 0) || (hvalue_len < 0))
580			return (HV_KVP_E_FAIL);
581
582		return (KVP_SUCCESS);
583
584	default:
585		return (HV_KVP_E_FAIL);
586	}
587}
588
589
590/*
591 * Send the response back to the host.
592 */
593static void
594hv_kvp_respond_host(int error)
595{
596	struct hv_vmbus_icmsg_hdr *hv_icmsg_hdrp;
597
598	hv_icmsg_hdrp = (struct hv_vmbus_icmsg_hdr *)
599	    &kvp_globals.rcv_buf[sizeof(struct hv_vmbus_pipe_hdr)];
600
601	if (error)
602		error = HV_KVP_E_FAIL;
603
604	hv_icmsg_hdrp->status = error;
605	hv_icmsg_hdrp->icflags = HV_ICMSGHDRFLAG_TRANSACTION | HV_ICMSGHDRFLAG_RESPONSE;
606
607	error = hv_vmbus_channel_send_packet(kvp_globals.channelp,
608			kvp_globals.rcv_buf,
609			kvp_globals.host_msg_len, kvp_globals.host_msg_id,
610			HV_VMBUS_PACKET_TYPE_DATA_IN_BAND, 0);
611
612	if (error)
613		hv_kvp_log_info("%s: hv_kvp_respond_host: sendpacket error:%d\n",
614			__func__, error);
615}
616
617
618/*
619 * This is the main kvp kernel process that interacts with both user daemon
620 * and the host
621 */
622static void
623hv_kvp_send_msg_to_daemon(void)
624{
625	/* Prepare kvp_msg to be sent to user */
626	hv_kvp_convert_hostmsg_to_usermsg();
627
628	/* Send the msg to user via function deamon_read - setting sema */
629	sema_post(&kvp_globals.dev_sema);
630}
631
632
633/*
634 * Function to read the kvp request buffer from host
635 * and interact with daemon
636 */
637static void
638hv_kvp_process_request(void *context)
639{
640	uint8_t *kvp_buf;
641	hv_vmbus_channel *channel = context;
642	uint32_t recvlen = 0;
643	uint64_t requestid;
644	struct hv_vmbus_icmsg_hdr *icmsghdrp;
645	int ret = 0;
646	uint64_t pending_cnt = 1;
647
648	hv_kvp_log_info("%s: entering hv_kvp_process_request\n", __func__);
649	kvp_buf = receive_buffer[HV_KVP];
650	ret = hv_vmbus_channel_recv_packet(channel, kvp_buf, 2 * PAGE_SIZE,
651		&recvlen, &requestid);
652
653	/*
654	 * We start counting only after the daemon registers
655	 * and therefore there could be requests pending in
656	 * the VMBus that are not reflected in pending_cnt.
657	 * Therefore we continue reading as long as either of
658	 * the below conditions is true.
659	 */
660
661	while ((pending_cnt>0) || ((ret == 0) && (recvlen > 0))) {
662
663		if ((ret == 0) && (recvlen>0)) {
664
665			icmsghdrp = (struct hv_vmbus_icmsg_hdr *)
666					&kvp_buf[sizeof(struct hv_vmbus_pipe_hdr)];
667
668			hv_kvp_transaction_init(recvlen, channel, requestid, kvp_buf);
669			if (icmsghdrp->icmsgtype == HV_ICMSGTYPE_NEGOTIATE) {
670				hv_kvp_negotiate_version(icmsghdrp, NULL, kvp_buf);
671				hv_kvp_respond_host(ret);
672
673				/*
674				 * It is ok to not acquire the mutex before setting
675				 * req_in_progress here because negotiation is the
676				 * first thing that happens and hence there is no
677				 * chance of a race condition.
678				 */
679
680				kvp_globals.req_in_progress = false;
681				hv_kvp_log_info("%s :version negotiated\n", __func__);
682
683			} else {
684				if (!kvp_globals.daemon_busy) {
685
686					hv_kvp_log_info("%s: issuing qury to daemon\n", __func__);
687					mtx_lock(&kvp_globals.pending_mutex);
688					kvp_globals.req_timed_out = false;
689					kvp_globals.daemon_busy = true;
690					mtx_unlock(&kvp_globals.pending_mutex);
691
692					hv_kvp_send_msg_to_daemon();
693					hv_kvp_log_info("%s: waiting for daemon\n", __func__);
694				}
695
696				/* Wait 5 seconds for daemon to respond back */
697				tsleep(&kvp_globals, 0, "kvpworkitem", 5 * hz);
698				hv_kvp_log_info("%s: came out of wait\n", __func__);
699			}
700		}
701
702		mtx_lock(&kvp_globals.pending_mutex);
703
704		/* Notice that once req_timed_out is set to true
705		 * it will remain true until the next request is
706		 * sent to the daemon. The response from daemon
707		 * is forwarded to host only when this flag is
708		 * false.
709		 */
710		kvp_globals.req_timed_out = true;
711
712		/*
713		 * Cancel request if so need be.
714		 */
715		if (hv_kvp_req_in_progress()) {
716			hv_kvp_log_info("%s: request was still active after wait so failing\n", __func__);
717			hv_kvp_respond_host(HV_KVP_E_FAIL);
718			kvp_globals.req_in_progress = false;
719		}
720
721		/*
722		* Decrement pending request count and
723		*/
724		if (kvp_globals.pending_reqs>0) {
725			kvp_globals.pending_reqs = kvp_globals.pending_reqs - 1;
726		}
727		pending_cnt = kvp_globals.pending_reqs;
728
729		mtx_unlock(&kvp_globals.pending_mutex);
730
731		/*
732		 * Try reading next buffer
733		 */
734		recvlen = 0;
735		ret = hv_vmbus_channel_recv_packet(channel, kvp_buf, 2 * PAGE_SIZE,
736			&recvlen, &requestid);
737		hv_kvp_log_info("%s: read: context %p, pending_cnt %ju ret =%d, recvlen=%d\n",
738			__func__, context, pending_cnt, ret, recvlen);
739	}
740}
741
742
743/*
744 * Callback routine that gets called whenever there is a message from host
745 */
746void
747hv_kvp_callback(void *context)
748{
749	uint64_t pending_cnt = 0;
750
751	if (kvp_globals.register_done == false) {
752
753		kvp_globals.channelp = context;
754	} else {
755
756		mtx_lock(&kvp_globals.pending_mutex);
757		kvp_globals.pending_reqs = kvp_globals.pending_reqs + 1;
758		pending_cnt = kvp_globals.pending_reqs;
759		mtx_unlock(&kvp_globals.pending_mutex);
760		if (pending_cnt == 1) {
761			hv_kvp_log_info("%s: Queuing work item\n", __func__);
762			hv_queue_work_item(
763					service_table[HV_KVP].work_queue,
764					hv_kvp_process_request,
765					context
766					);
767		}
768	}
769}
770
771
772/*
773 * This function is called by the hv_kvp_init -
774 * creates character device hv_kvp_dev
775 * allocates memory to hv_kvp_dev_buf
776 *
777 */
778static int
779hv_kvp_dev_init(void)
780{
781	int error = 0;
782
783	/* initialize semaphore */
784	sema_init(&kvp_globals.dev_sema, 0, "hv_kvp device semaphore");
785	/* create character device */
786	error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK,
787			&hv_kvp_dev,
788			&hv_kvp_cdevsw,
789			0,
790			UID_ROOT,
791			GID_WHEEL,
792			0640,
793			"hv_kvp_dev");
794
795	if (error != 0)
796		return (error);
797
798	/*
799	 * Malloc with M_WAITOK flag will never fail.
800	 */
801	hv_kvp_dev_buf = malloc(sizeof(*hv_kvp_dev_buf), M_HV_KVP_DEV_BUF, M_WAITOK |
802				M_ZERO);
803
804	return (0);
805}
806
807
808/*
809 * This function is called by the hv_kvp_deinit -
810 * destroy character device
811 */
812static void
813hv_kvp_dev_destroy(void)
814{
815
816        if (daemon_task != NULL) {
817		PROC_LOCK(daemon_task);
818        	kern_psignal(daemon_task, SIGKILL);
819		PROC_UNLOCK(daemon_task);
820	}
821
822	destroy_dev(hv_kvp_dev);
823	free(hv_kvp_dev_buf, M_HV_KVP_DEV_BUF);
824	return;
825}
826
827
828static int
829hv_kvp_dev_open(struct cdev *dev, int oflags, int devtype,
830				struct thread *td)
831{
832
833	hv_kvp_log_info("%s: Opened device \"hv_kvp_device\" successfully.\n", __func__);
834	if (kvp_globals.dev_accessed)
835		return (-EBUSY);
836
837	daemon_task = curproc;
838	kvp_globals.dev_accessed = true;
839	kvp_globals.daemon_busy = false;
840	return (0);
841}
842
843
844static int
845hv_kvp_dev_close(struct cdev *dev __unused, int fflag __unused, int devtype __unused,
846				 struct thread *td __unused)
847{
848
849	hv_kvp_log_info("%s: Closing device \"hv_kvp_device\".\n", __func__);
850	kvp_globals.dev_accessed = false;
851	kvp_globals.register_done = false;
852	return (0);
853}
854
855
856/*
857 * hv_kvp_daemon read invokes this function
858 * acts as a send to daemon
859 */
860static int
861hv_kvp_dev_daemon_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused)
862{
863	size_t amt;
864	int error = 0;
865
866	/* Check hv_kvp daemon registration status*/
867	if (!kvp_globals.register_done)
868		return (KVP_ERROR);
869
870	sema_wait(&kvp_globals.dev_sema);
871
872	memcpy(hv_kvp_dev_buf, &kvp_globals.daemon_kvp_msg, sizeof(struct hv_kvp_msg));
873
874	amt = MIN(uio->uio_resid, uio->uio_offset >= BUFFERSIZE + 1 ? 0 :
875		BUFFERSIZE + 1 - uio->uio_offset);
876
877	if ((error = uiomove(hv_kvp_dev_buf, amt, uio)) != 0)
878		hv_kvp_log_info("%s: hv_kvp uiomove read failed!\n", __func__);
879
880	return (error);
881}
882
883
884/*
885 * hv_kvp_daemon write invokes this function
886 * acts as a recieve from daemon
887 */
888static int
889hv_kvp_dev_daemon_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused)
890{
891	size_t amt;
892	int error = 0;
893
894	uio->uio_offset = 0;
895
896	amt = MIN(uio->uio_resid, BUFFERSIZE);
897	error = uiomove(hv_kvp_dev_buf, amt, uio);
898
899	if (error != 0)
900		return (error);
901
902	memcpy(&kvp_globals.daemon_kvp_msg, hv_kvp_dev_buf, sizeof(struct hv_kvp_msg));
903
904	if (kvp_globals.register_done == false) {
905		if (kvp_globals.daemon_kvp_msg.kvp_hdr.operation == HV_KVP_OP_REGISTER) {
906
907			kvp_globals.register_done = true;
908			if (kvp_globals.channelp) {
909
910				hv_kvp_callback(kvp_globals.channelp);
911			}
912		}
913		else {
914			hv_kvp_log_info("%s, KVP Registration Failed\n", __func__);
915			return (KVP_ERROR);
916		}
917	} else {
918
919		mtx_lock(&kvp_globals.pending_mutex);
920
921		if(!kvp_globals.req_timed_out) {
922
923			hv_kvp_convert_usermsg_to_hostmsg();
924			hv_kvp_respond_host(KVP_SUCCESS);
925			wakeup(&kvp_globals);
926			kvp_globals.req_in_progress = false;
927		}
928
929		kvp_globals.daemon_busy = false;
930		mtx_unlock(&kvp_globals.pending_mutex);
931	}
932
933	return (error);
934}
935
936
937/*
938 * hv_kvp_daemon poll invokes this function to check if data is available
939 * for daemon to read.
940 */
941static int
942hv_kvp_dev_daemon_poll(struct cdev *dev __unused, int events, struct thread *td  __unused)
943{
944	int revents = 0;
945
946	mtx_lock(&kvp_globals.pending_mutex);
947	/*
948	 * We check global flag daemon_busy for the data availiability for
949	 * userland to read. Deamon_busy is set to true before driver has data
950	 * for daemon to read. It is set to false after daemon sends
951	 * then response back to driver.
952	 */
953	if (kvp_globals.daemon_busy == true)
954		revents = POLLIN;
955	mtx_unlock(&kvp_globals.pending_mutex);
956
957	return (revents);
958}
959
960
961/*
962 * hv_kvp initialization function
963 * called from hv_util service.
964 *
965 */
966int
967hv_kvp_init(hv_vmbus_service *srv)
968{
969	int error = 0;
970	hv_work_queue *work_queue = NULL;
971
972	memset(&kvp_globals, 0, sizeof(kvp_globals));
973
974	work_queue = hv_work_queue_create("KVP Service");
975	if (work_queue == NULL) {
976		hv_kvp_log_info("%s: Work queue alloc failed\n", __func__);
977		error = ENOMEM;
978		hv_kvp_log_error("%s: ENOMEM\n", __func__);
979		goto Finish;
980	}
981	srv->work_queue = work_queue;
982
983	error = hv_kvp_dev_init();
984	mtx_init(&kvp_globals.pending_mutex, "hv-kvp pending mutex",
985		       	NULL, MTX_DEF);
986	kvp_globals.pending_reqs = 0;
987
988
989Finish:
990	return (error);
991}
992
993
994void
995hv_kvp_deinit(void)
996{
997	hv_kvp_dev_destroy();
998	mtx_destroy(&kvp_globals.pending_mutex);
999
1000	return;
1001}
1002