xref: /freebsd/sys/dev/hyperv/utilities/hv_kvp.c (revision 2c8d04d0228871c24017509cf039e7c5d97d97be)
1 /*-
2  * Copyright (c) 2014,2016 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$");
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/selinfo.h>
48 #include <sys/sysctl.h>
49 #include <sys/poll.h>
50 #include <sys/proc.h>
51 #include <sys/kthread.h>
52 #include <sys/syscallsubr.h>
53 #include <sys/sysproto.h>
54 #include <sys/un.h>
55 #include <sys/endian.h>
56 #include <sys/_null.h>
57 #include <sys/signal.h>
58 #include <sys/syslog.h>
59 #include <sys/systm.h>
60 #include <sys/mutex.h>
61 
62 #include <net/if.h>
63 #include <net/if_arp.h>
64 #include <net/if_var.h>
65 
66 #include <dev/hyperv/include/hyperv.h>
67 #include <dev/hyperv/netvsc/hv_net_vsc.h>
68 #include <dev/hyperv/utilities/hv_utilreg.h>
69 
70 #include "hv_util.h"
71 #include "unicode.h"
72 #include "hv_kvp.h"
73 #include "vmbus_if.h"
74 
75 /* hv_kvp defines */
76 #define BUFFERSIZE	sizeof(struct hv_kvp_msg)
77 #define KVP_SUCCESS	0
78 #define KVP_ERROR	1
79 #define kvp_hdr		hdr.kvp_hdr
80 
81 /* hv_kvp debug control */
82 static int hv_kvp_log = 0;
83 
84 #define	hv_kvp_log_error(...)	do {				\
85 	if (hv_kvp_log > 0)				\
86 		log(LOG_ERR, "hv_kvp: " __VA_ARGS__);	\
87 } while (0)
88 
89 #define	hv_kvp_log_info(...) do {				\
90 	if (hv_kvp_log > 1)				\
91 		log(LOG_INFO, "hv_kvp: " __VA_ARGS__);		\
92 } while (0)
93 
94 static const struct hyperv_guid service_guid = { .hv_guid =
95 	{0xe7, 0xf4, 0xa0, 0xa9, 0x45, 0x5a, 0x96, 0x4d,
96 	0xb8, 0x27, 0x8a, 0x84, 0x1e, 0x8c, 0x3,  0xe6} };
97 
98 /* character device prototypes */
99 static d_open_t		hv_kvp_dev_open;
100 static d_close_t	hv_kvp_dev_close;
101 static d_read_t		hv_kvp_dev_daemon_read;
102 static d_write_t	hv_kvp_dev_daemon_write;
103 static d_poll_t		hv_kvp_dev_daemon_poll;
104 
105 /* hv_kvp character device structure */
106 static struct cdevsw hv_kvp_cdevsw =
107 {
108 	.d_version	= D_VERSION,
109 	.d_open		= hv_kvp_dev_open,
110 	.d_close	= hv_kvp_dev_close,
111 	.d_read		= hv_kvp_dev_daemon_read,
112 	.d_write	= hv_kvp_dev_daemon_write,
113 	.d_poll		= hv_kvp_dev_daemon_poll,
114 	.d_name		= "hv_kvp_dev",
115 };
116 
117 
118 /*
119  * Global state to track and synchronize multiple
120  * KVP transaction requests from the host.
121  */
122 typedef struct hv_kvp_sc {
123 	struct hv_util_sc	util_sc;
124 	device_t		dev;
125 
126 	/* Unless specified the pending mutex should be
127 	 * used to alter the values of the following parameters:
128 	 * 1. req_in_progress
129 	 * 2. req_timed_out
130 	 */
131 	struct mtx		pending_mutex;
132 
133 	struct task		task;
134 
135 	/* To track if transaction is active or not */
136 	boolean_t		req_in_progress;
137 	/* Tracks if daemon did not reply back in time */
138 	boolean_t		req_timed_out;
139 	/* Tracks if daemon is serving a request currently */
140 	boolean_t		daemon_busy;
141 
142 	/* Length of host message */
143 	uint32_t		host_msg_len;
144 
145 	/* Host message id */
146 	uint64_t		host_msg_id;
147 
148 	/* Current kvp message from the host */
149 	struct hv_kvp_msg	*host_kvp_msg;
150 
151 	 /* Current kvp message for daemon */
152 	struct hv_kvp_msg	daemon_kvp_msg;
153 
154 	/* Rcv buffer for communicating with the host*/
155 	uint8_t			*rcv_buf;
156 
157 	/* Device semaphore to control communication */
158 	struct sema		dev_sema;
159 
160 	/* Indicates if daemon registered with driver */
161 	boolean_t		register_done;
162 
163 	/* Character device status */
164 	boolean_t		dev_accessed;
165 
166 	struct cdev *hv_kvp_dev;
167 
168 	struct proc *daemon_task;
169 
170 	struct selinfo hv_kvp_selinfo;
171 } hv_kvp_sc;
172 
173 /* hv_kvp prototypes */
174 static int	hv_kvp_req_in_progress(hv_kvp_sc *sc);
175 static void	hv_kvp_transaction_init(hv_kvp_sc *sc, uint32_t, uint64_t, uint8_t *);
176 static void	hv_kvp_send_msg_to_daemon(hv_kvp_sc *sc);
177 static void	hv_kvp_process_request(void *context, int pending);
178 
179 /*
180  * hv_kvp low level functions
181  */
182 
183 /*
184  * Check if kvp transaction is in progres
185  */
186 static int
187 hv_kvp_req_in_progress(hv_kvp_sc *sc)
188 {
189 
190 	return (sc->req_in_progress);
191 }
192 
193 
194 /*
195  * This routine is called whenever a message is received from the host
196  */
197 static void
198 hv_kvp_transaction_init(hv_kvp_sc *sc, uint32_t rcv_len,
199 			uint64_t request_id, uint8_t *rcv_buf)
200 {
201 
202 	/* Store all the relevant message details in the global structure */
203 	/* Do not need to use mutex for req_in_progress here */
204 	sc->req_in_progress = true;
205 	sc->host_msg_len = rcv_len;
206 	sc->host_msg_id = request_id;
207 	sc->rcv_buf = rcv_buf;
208 	sc->host_kvp_msg = (struct hv_kvp_msg *)&rcv_buf[
209 		sizeof(struct hv_vmbus_pipe_hdr) +
210 		sizeof(struct hv_vmbus_icmsg_hdr)];
211 }
212 
213 
214 /*
215  * hv_kvp - version neogtiation function
216  */
217 static void
218 hv_kvp_negotiate_version(struct hv_vmbus_icmsg_hdr *icmsghdrp,
219 			 struct hv_vmbus_icmsg_negotiate *negop,
220 			 uint8_t *buf)
221 {
222 	int icframe_vercnt;
223 	int icmsg_vercnt;
224 
225 	icmsghdrp->icmsgsize = 0x10;
226 
227 	negop = (struct hv_vmbus_icmsg_negotiate *)&buf[
228 		sizeof(struct hv_vmbus_pipe_hdr) +
229 		sizeof(struct hv_vmbus_icmsg_hdr)];
230 	icframe_vercnt = negop->icframe_vercnt;
231 	icmsg_vercnt = negop->icmsg_vercnt;
232 
233 	/*
234 	 * Select the framework version number we will support
235 	 */
236 	if ((icframe_vercnt >= 2) && (negop->icversion_data[1].major == 3)) {
237 		icframe_vercnt = 3;
238 		if (icmsg_vercnt > 2)
239 			icmsg_vercnt = 4;
240 		else
241 			icmsg_vercnt = 3;
242 	} else {
243 		icframe_vercnt = 1;
244 		icmsg_vercnt = 1;
245 	}
246 
247 	negop->icframe_vercnt = 1;
248 	negop->icmsg_vercnt = 1;
249 	negop->icversion_data[0].major = icframe_vercnt;
250 	negop->icversion_data[0].minor = 0;
251 	negop->icversion_data[1].major = icmsg_vercnt;
252 	negop->icversion_data[1].minor = 0;
253 }
254 
255 
256 /*
257  * Convert ip related info in umsg from utf8 to utf16 and store in hmsg
258  */
259 static int
260 hv_kvp_convert_utf8_ipinfo_to_utf16(struct hv_kvp_msg *umsg,
261 				    struct hv_kvp_ip_msg *host_ip_msg)
262 {
263 	int err_ip, err_subnet, err_gway, err_dns, err_adap;
264 	int UNUSED_FLAG = 1;
265 
266 	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.ip_addr,
267 	    MAX_IP_ADDR_SIZE,
268 	    (char *)umsg->body.kvp_ip_val.ip_addr,
269 	    strlen((char *)umsg->body.kvp_ip_val.ip_addr),
270 	    UNUSED_FLAG,
271 	    &err_ip);
272 	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.sub_net,
273 	    MAX_IP_ADDR_SIZE,
274 	    (char *)umsg->body.kvp_ip_val.sub_net,
275 	    strlen((char *)umsg->body.kvp_ip_val.sub_net),
276 	    UNUSED_FLAG,
277 	    &err_subnet);
278 	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.gate_way,
279 	    MAX_GATEWAY_SIZE,
280 	    (char *)umsg->body.kvp_ip_val.gate_way,
281 	    strlen((char *)umsg->body.kvp_ip_val.gate_way),
282 	    UNUSED_FLAG,
283 	    &err_gway);
284 	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.dns_addr,
285 	    MAX_IP_ADDR_SIZE,
286 	    (char *)umsg->body.kvp_ip_val.dns_addr,
287 	    strlen((char *)umsg->body.kvp_ip_val.dns_addr),
288 	    UNUSED_FLAG,
289 	    &err_dns);
290 	utf8_to_utf16((uint16_t *)host_ip_msg->kvp_ip_val.adapter_id,
291 	    MAX_IP_ADDR_SIZE,
292 	    (char *)umsg->body.kvp_ip_val.adapter_id,
293 	    strlen((char *)umsg->body.kvp_ip_val.adapter_id),
294 	    UNUSED_FLAG,
295 	    &err_adap);
296 
297 	host_ip_msg->kvp_ip_val.dhcp_enabled = umsg->body.kvp_ip_val.dhcp_enabled;
298 	host_ip_msg->kvp_ip_val.addr_family = umsg->body.kvp_ip_val.addr_family;
299 
300 	return (err_ip | err_subnet | err_gway | err_dns | err_adap);
301 }
302 
303 
304 /*
305  * Convert ip related info in hmsg from utf16 to utf8 and store in umsg
306  */
307 static int
308 hv_kvp_convert_utf16_ipinfo_to_utf8(struct hv_kvp_ip_msg *host_ip_msg,
309 				    struct hv_kvp_msg *umsg)
310 {
311 	int err_ip, err_subnet, err_gway, err_dns, err_adap;
312 	int UNUSED_FLAG = 1;
313 	device_t *devs;
314 	int devcnt;
315 
316 	/* IP Address */
317 	utf16_to_utf8((char *)umsg->body.kvp_ip_val.ip_addr,
318 	    MAX_IP_ADDR_SIZE,
319 	    (uint16_t *)host_ip_msg->kvp_ip_val.ip_addr,
320 	    MAX_IP_ADDR_SIZE,
321 	    UNUSED_FLAG,
322 	    &err_ip);
323 
324 	/* Adapter ID : GUID */
325 	utf16_to_utf8((char *)umsg->body.kvp_ip_val.adapter_id,
326 	    MAX_ADAPTER_ID_SIZE,
327 	    (uint16_t *)host_ip_msg->kvp_ip_val.adapter_id,
328 	    MAX_ADAPTER_ID_SIZE,
329 	    UNUSED_FLAG,
330 	    &err_adap);
331 
332 	if (devclass_get_devices(devclass_find("hn"), &devs, &devcnt) == 0) {
333 		for (devcnt = devcnt - 1; devcnt >= 0; devcnt--) {
334 			/* XXX access other driver's softc?  are you kidding? */
335 			device_t dev = devs[devcnt];
336 			struct hn_softc *sc = device_get_softc(dev);
337 			struct vmbus_channel *chan;
338 			char buf[HYPERV_GUID_STRLEN];
339 
340 			/*
341 			 * Trying to find GUID of Network Device
342 			 * TODO: need vmbus interface.
343 			 */
344 			chan = vmbus_get_channel(dev);
345 			hyperv_guid2str(vmbus_chan_guid_inst(chan),
346 			    buf, sizeof(buf));
347 
348 			if (strncmp(buf, (char *)umsg->body.kvp_ip_val.adapter_id,
349 			    HYPERV_GUID_STRLEN - 1) == 0) {
350 				strlcpy((char *)umsg->body.kvp_ip_val.adapter_id,
351 				    sc->hn_ifp->if_xname, MAX_ADAPTER_ID_SIZE);
352 				break;
353 			}
354 		}
355 		free(devs, M_TEMP);
356 	}
357 
358 	/* Address Family , DHCP , SUBNET, Gateway, DNS */
359 	umsg->kvp_hdr.operation = host_ip_msg->operation;
360 	umsg->body.kvp_ip_val.addr_family = host_ip_msg->kvp_ip_val.addr_family;
361 	umsg->body.kvp_ip_val.dhcp_enabled = host_ip_msg->kvp_ip_val.dhcp_enabled;
362 	utf16_to_utf8((char *)umsg->body.kvp_ip_val.sub_net, MAX_IP_ADDR_SIZE,
363 	    (uint16_t *)host_ip_msg->kvp_ip_val.sub_net,
364 	    MAX_IP_ADDR_SIZE,
365 	    UNUSED_FLAG,
366 	    &err_subnet);
367 
368 	utf16_to_utf8((char *)umsg->body.kvp_ip_val.gate_way, MAX_GATEWAY_SIZE,
369 	    (uint16_t *)host_ip_msg->kvp_ip_val.gate_way,
370 	    MAX_GATEWAY_SIZE,
371 	    UNUSED_FLAG,
372 	    &err_gway);
373 
374 	utf16_to_utf8((char *)umsg->body.kvp_ip_val.dns_addr, MAX_IP_ADDR_SIZE,
375 	    (uint16_t *)host_ip_msg->kvp_ip_val.dns_addr,
376 	    MAX_IP_ADDR_SIZE,
377 	    UNUSED_FLAG,
378 	    &err_dns);
379 
380 	return (err_ip | err_subnet | err_gway | err_dns | err_adap);
381 }
382 
383 
384 /*
385  * Prepare a user kvp msg based on host kvp msg (utf16 to utf8)
386  * Ensure utf16_utf8 takes care of the additional string terminating char!!
387  */
388 static void
389 hv_kvp_convert_hostmsg_to_usermsg(struct hv_kvp_msg *hmsg, struct hv_kvp_msg *umsg)
390 {
391 	int utf_err = 0;
392 	uint32_t value_type;
393 	struct hv_kvp_ip_msg *host_ip_msg;
394 
395 	host_ip_msg = (struct hv_kvp_ip_msg*)hmsg;
396 	memset(umsg, 0, sizeof(struct hv_kvp_msg));
397 
398 	umsg->kvp_hdr.operation = hmsg->kvp_hdr.operation;
399 	umsg->kvp_hdr.pool = hmsg->kvp_hdr.pool;
400 
401 	switch (umsg->kvp_hdr.operation) {
402 	case HV_KVP_OP_SET_IP_INFO:
403 		hv_kvp_convert_utf16_ipinfo_to_utf8(host_ip_msg, umsg);
404 		break;
405 
406 	case HV_KVP_OP_GET_IP_INFO:
407 		utf16_to_utf8((char *)umsg->body.kvp_ip_val.adapter_id,
408 		    MAX_ADAPTER_ID_SIZE,
409 		    (uint16_t *)host_ip_msg->kvp_ip_val.adapter_id,
410 		    MAX_ADAPTER_ID_SIZE, 1, &utf_err);
411 
412 		umsg->body.kvp_ip_val.addr_family =
413 		    host_ip_msg->kvp_ip_val.addr_family;
414 		break;
415 
416 	case HV_KVP_OP_SET:
417 		value_type = hmsg->body.kvp_set.data.value_type;
418 
419 		switch (value_type) {
420 		case HV_REG_SZ:
421 			umsg->body.kvp_set.data.value_size =
422 			    utf16_to_utf8(
423 				(char *)umsg->body.kvp_set.data.msg_value.value,
424 				HV_KVP_EXCHANGE_MAX_VALUE_SIZE - 1,
425 				(uint16_t *)hmsg->body.kvp_set.data.msg_value.value,
426 				hmsg->body.kvp_set.data.value_size,
427 				1, &utf_err);
428 			/* utf8 encoding */
429 			umsg->body.kvp_set.data.value_size =
430 			    umsg->body.kvp_set.data.value_size / 2;
431 			break;
432 
433 		case HV_REG_U32:
434 			umsg->body.kvp_set.data.value_size =
435 			    sprintf(umsg->body.kvp_set.data.msg_value.value, "%d",
436 				hmsg->body.kvp_set.data.msg_value.value_u32) + 1;
437 			break;
438 
439 		case HV_REG_U64:
440 			umsg->body.kvp_set.data.value_size =
441 			    sprintf(umsg->body.kvp_set.data.msg_value.value, "%llu",
442 				(unsigned long long)
443 				hmsg->body.kvp_set.data.msg_value.value_u64) + 1;
444 			break;
445 		}
446 
447 		umsg->body.kvp_set.data.key_size =
448 		    utf16_to_utf8(
449 			umsg->body.kvp_set.data.key,
450 			HV_KVP_EXCHANGE_MAX_KEY_SIZE - 1,
451 			(uint16_t *)hmsg->body.kvp_set.data.key,
452 			hmsg->body.kvp_set.data.key_size,
453 			1, &utf_err);
454 
455 		/* utf8 encoding */
456 		umsg->body.kvp_set.data.key_size =
457 		    umsg->body.kvp_set.data.key_size / 2;
458 		break;
459 
460 	case HV_KVP_OP_GET:
461 		umsg->body.kvp_get.data.key_size =
462 		    utf16_to_utf8(umsg->body.kvp_get.data.key,
463 			HV_KVP_EXCHANGE_MAX_KEY_SIZE - 1,
464 			(uint16_t *)hmsg->body.kvp_get.data.key,
465 			hmsg->body.kvp_get.data.key_size,
466 			1, &utf_err);
467 		/* utf8 encoding */
468 		umsg->body.kvp_get.data.key_size =
469 		    umsg->body.kvp_get.data.key_size / 2;
470 		break;
471 
472 	case HV_KVP_OP_DELETE:
473 		umsg->body.kvp_delete.key_size =
474 		    utf16_to_utf8(umsg->body.kvp_delete.key,
475 			HV_KVP_EXCHANGE_MAX_KEY_SIZE - 1,
476 			(uint16_t *)hmsg->body.kvp_delete.key,
477 			hmsg->body.kvp_delete.key_size,
478 			1, &utf_err);
479 		/* utf8 encoding */
480 		umsg->body.kvp_delete.key_size =
481 		    umsg->body.kvp_delete.key_size / 2;
482 		break;
483 
484 	case HV_KVP_OP_ENUMERATE:
485 		umsg->body.kvp_enum_data.index =
486 		    hmsg->body.kvp_enum_data.index;
487 		break;
488 
489 	default:
490 		hv_kvp_log_info("%s: daemon_kvp_msg: Invalid operation : %d\n",
491 		    __func__, umsg->kvp_hdr.operation);
492 	}
493 }
494 
495 
496 /*
497  * Prepare a host kvp msg based on user kvp msg (utf8 to utf16)
498  */
499 static int
500 hv_kvp_convert_usermsg_to_hostmsg(struct hv_kvp_msg *umsg, struct hv_kvp_msg *hmsg)
501 {
502 	int hkey_len = 0, hvalue_len = 0, utf_err = 0;
503 	struct hv_kvp_exchg_msg_value *host_exchg_data;
504 	char *key_name, *value;
505 
506 	struct hv_kvp_ip_msg *host_ip_msg = (struct hv_kvp_ip_msg *)hmsg;
507 
508 	switch (hmsg->kvp_hdr.operation) {
509 	case HV_KVP_OP_GET_IP_INFO:
510 		return (hv_kvp_convert_utf8_ipinfo_to_utf16(umsg, host_ip_msg));
511 
512 	case HV_KVP_OP_SET_IP_INFO:
513 	case HV_KVP_OP_SET:
514 	case HV_KVP_OP_DELETE:
515 		return (KVP_SUCCESS);
516 
517 	case HV_KVP_OP_ENUMERATE:
518 		host_exchg_data = &hmsg->body.kvp_enum_data.data;
519 		key_name = umsg->body.kvp_enum_data.data.key;
520 		hkey_len = utf8_to_utf16((uint16_t *)host_exchg_data->key,
521 				((HV_KVP_EXCHANGE_MAX_KEY_SIZE / 2) - 2),
522 				key_name, strlen(key_name),
523 				1, &utf_err);
524 		/* utf16 encoding */
525 		host_exchg_data->key_size = 2 * (hkey_len + 1);
526 		value = umsg->body.kvp_enum_data.data.msg_value.value;
527 		hvalue_len = utf8_to_utf16(
528 				(uint16_t *)host_exchg_data->msg_value.value,
529 				((HV_KVP_EXCHANGE_MAX_VALUE_SIZE / 2) - 2),
530 				value, strlen(value),
531 				1, &utf_err);
532 		host_exchg_data->value_size = 2 * (hvalue_len + 1);
533 		host_exchg_data->value_type = HV_REG_SZ;
534 
535 		if ((hkey_len < 0) || (hvalue_len < 0))
536 			return (HV_KVP_E_FAIL);
537 
538 		return (KVP_SUCCESS);
539 
540 	case HV_KVP_OP_GET:
541 		host_exchg_data = &hmsg->body.kvp_get.data;
542 		value = umsg->body.kvp_get.data.msg_value.value;
543 		hvalue_len = utf8_to_utf16(
544 				(uint16_t *)host_exchg_data->msg_value.value,
545 				((HV_KVP_EXCHANGE_MAX_VALUE_SIZE / 2) - 2),
546 				value, strlen(value),
547 				1, &utf_err);
548 		/* Convert value size to uft16 */
549 		host_exchg_data->value_size = 2 * (hvalue_len + 1);
550 		/* Use values by string */
551 		host_exchg_data->value_type = HV_REG_SZ;
552 
553 		if ((hkey_len < 0) || (hvalue_len < 0))
554 			return (HV_KVP_E_FAIL);
555 
556 		return (KVP_SUCCESS);
557 
558 	default:
559 		return (HV_KVP_E_FAIL);
560 	}
561 }
562 
563 
564 /*
565  * Send the response back to the host.
566  */
567 static void
568 hv_kvp_respond_host(hv_kvp_sc *sc, int error)
569 {
570 	struct hv_vmbus_icmsg_hdr *hv_icmsg_hdrp;
571 
572 	hv_icmsg_hdrp = (struct hv_vmbus_icmsg_hdr *)
573 	    &sc->rcv_buf[sizeof(struct hv_vmbus_pipe_hdr)];
574 
575 	if (error)
576 		error = HV_KVP_E_FAIL;
577 
578 	hv_icmsg_hdrp->status = error;
579 	hv_icmsg_hdrp->icflags = HV_ICMSGHDRFLAG_TRANSACTION | HV_ICMSGHDRFLAG_RESPONSE;
580 
581 	error = vmbus_chan_send(vmbus_get_channel(sc->dev),
582 	    VMBUS_CHANPKT_TYPE_INBAND, 0, sc->rcv_buf, sc->host_msg_len,
583 	    sc->host_msg_id);
584 	if (error)
585 		hv_kvp_log_info("%s: hv_kvp_respond_host: sendpacket error:%d\n",
586 			__func__, error);
587 }
588 
589 
590 /*
591  * This is the main kvp kernel process that interacts with both user daemon
592  * and the host
593  */
594 static void
595 hv_kvp_send_msg_to_daemon(hv_kvp_sc *sc)
596 {
597 	struct hv_kvp_msg *hmsg = sc->host_kvp_msg;
598 	struct hv_kvp_msg *umsg = &sc->daemon_kvp_msg;
599 
600 	/* Prepare kvp_msg to be sent to user */
601 	hv_kvp_convert_hostmsg_to_usermsg(hmsg, umsg);
602 
603 	/* Send the msg to user via function deamon_read - setting sema */
604 	sema_post(&sc->dev_sema);
605 
606 	/* We should wake up the daemon, in case it's doing poll() */
607 	selwakeup(&sc->hv_kvp_selinfo);
608 }
609 
610 
611 /*
612  * Function to read the kvp request buffer from host
613  * and interact with daemon
614  */
615 static void
616 hv_kvp_process_request(void *context, int pending)
617 {
618 	uint8_t *kvp_buf;
619 	struct vmbus_channel *channel;
620 	uint32_t recvlen = 0;
621 	uint64_t requestid;
622 	struct hv_vmbus_icmsg_hdr *icmsghdrp;
623 	int ret = 0;
624 	hv_kvp_sc		*sc;
625 
626 	hv_kvp_log_info("%s: entering hv_kvp_process_request\n", __func__);
627 
628 	sc = (hv_kvp_sc*)context;
629 	kvp_buf = sc->util_sc.receive_buffer;
630 	channel = vmbus_get_channel(sc->dev);
631 
632 	recvlen = 2 * PAGE_SIZE;
633 	ret = vmbus_chan_recv(channel, kvp_buf, &recvlen, &requestid);
634 	KASSERT(ret != ENOBUFS, ("hvkvp recvbuf is not large enough"));
635 	/* XXX check recvlen to make sure that it contains enough data */
636 
637 	while ((ret == 0) && (recvlen > 0)) {
638 
639 		icmsghdrp = (struct hv_vmbus_icmsg_hdr *)
640 			&kvp_buf[sizeof(struct hv_vmbus_pipe_hdr)];
641 
642 		hv_kvp_transaction_init(sc, recvlen, requestid, kvp_buf);
643 		if (icmsghdrp->icmsgtype == HV_ICMSGTYPE_NEGOTIATE) {
644 			hv_kvp_negotiate_version(icmsghdrp, NULL, kvp_buf);
645 			hv_kvp_respond_host(sc, ret);
646 
647 			/*
648 			 * It is ok to not acquire the mutex before setting
649 			 * req_in_progress here because negotiation is the
650 			 * first thing that happens and hence there is no
651 			 * chance of a race condition.
652 			 */
653 
654 			sc->req_in_progress = false;
655 			hv_kvp_log_info("%s :version negotiated\n", __func__);
656 
657 		} else {
658 			if (!sc->daemon_busy) {
659 
660 				hv_kvp_log_info("%s: issuing qury to daemon\n", __func__);
661 				mtx_lock(&sc->pending_mutex);
662 				sc->req_timed_out = false;
663 				sc->daemon_busy = true;
664 				mtx_unlock(&sc->pending_mutex);
665 
666 				hv_kvp_send_msg_to_daemon(sc);
667 				hv_kvp_log_info("%s: waiting for daemon\n", __func__);
668 			}
669 
670 			/* Wait 5 seconds for daemon to respond back */
671 			tsleep(sc, 0, "kvpworkitem", 5 * hz);
672 			hv_kvp_log_info("%s: came out of wait\n", __func__);
673 		}
674 
675 		mtx_lock(&sc->pending_mutex);
676 
677 		/* Notice that once req_timed_out is set to true
678 		 * it will remain true until the next request is
679 		 * sent to the daemon. The response from daemon
680 		 * is forwarded to host only when this flag is
681 		 * false.
682 		 */
683 		sc->req_timed_out = true;
684 
685 		/*
686 		 * Cancel request if so need be.
687 		 */
688 		if (hv_kvp_req_in_progress(sc)) {
689 			hv_kvp_log_info("%s: request was still active after wait so failing\n", __func__);
690 			hv_kvp_respond_host(sc, HV_KVP_E_FAIL);
691 			sc->req_in_progress = false;
692 		}
693 
694 		mtx_unlock(&sc->pending_mutex);
695 
696 		/*
697 		 * Try reading next buffer
698 		 */
699 		recvlen = 2 * PAGE_SIZE;
700 		ret = vmbus_chan_recv(channel, kvp_buf, &recvlen, &requestid);
701 		KASSERT(ret != ENOBUFS, ("hvkvp recvbuf is not large enough"));
702 		/* XXX check recvlen to make sure that it contains enough data */
703 
704 		hv_kvp_log_info("%s: read: context %p, ret =%d, recvlen=%d\n",
705 			__func__, context, ret, recvlen);
706 	}
707 }
708 
709 
710 /*
711  * Callback routine that gets called whenever there is a message from host
712  */
713 static void
714 hv_kvp_callback(struct vmbus_channel *chan __unused, void *context)
715 {
716 	hv_kvp_sc *sc = (hv_kvp_sc*)context;
717 	/*
718 	 The first request from host will not be handled until daemon is registered.
719 	 when callback is triggered without a registered daemon, callback just return.
720 	 When a new daemon gets regsitered, this callbcak is trigged from _write op.
721 	*/
722 	if (sc->register_done) {
723 		hv_kvp_log_info("%s: Queuing work item\n", __func__);
724 		taskqueue_enqueue(taskqueue_thread, &sc->task);
725 	}
726 }
727 
728 static int
729 hv_kvp_dev_open(struct cdev *dev, int oflags, int devtype,
730 				struct thread *td)
731 {
732 	hv_kvp_sc *sc = (hv_kvp_sc*)dev->si_drv1;
733 
734 	hv_kvp_log_info("%s: Opened device \"hv_kvp_device\" successfully.\n", __func__);
735 	if (sc->dev_accessed)
736 		return (-EBUSY);
737 
738 	sc->daemon_task = curproc;
739 	sc->dev_accessed = true;
740 	sc->daemon_busy = false;
741 	return (0);
742 }
743 
744 
745 static int
746 hv_kvp_dev_close(struct cdev *dev __unused, int fflag __unused, int devtype __unused,
747 				 struct thread *td __unused)
748 {
749 	hv_kvp_sc *sc = (hv_kvp_sc*)dev->si_drv1;
750 
751 	hv_kvp_log_info("%s: Closing device \"hv_kvp_device\".\n", __func__);
752 	sc->dev_accessed = false;
753 	sc->register_done = false;
754 	return (0);
755 }
756 
757 
758 /*
759  * hv_kvp_daemon read invokes this function
760  * acts as a send to daemon
761  */
762 static int
763 hv_kvp_dev_daemon_read(struct cdev *dev, struct uio *uio, int ioflag __unused)
764 {
765 	size_t amt;
766 	int error = 0;
767 	struct hv_kvp_msg *hv_kvp_dev_buf;
768 	hv_kvp_sc *sc = (hv_kvp_sc*)dev->si_drv1;
769 
770 	/* Check hv_kvp daemon registration status*/
771 	if (!sc->register_done)
772 		return (KVP_ERROR);
773 
774 	sema_wait(&sc->dev_sema);
775 
776 	hv_kvp_dev_buf = malloc(sizeof(*hv_kvp_dev_buf), M_TEMP, M_WAITOK);
777 	memcpy(hv_kvp_dev_buf, &sc->daemon_kvp_msg, sizeof(struct hv_kvp_msg));
778 
779 	amt = MIN(uio->uio_resid, uio->uio_offset >= BUFFERSIZE + 1 ? 0 :
780 		BUFFERSIZE + 1 - uio->uio_offset);
781 
782 	if ((error = uiomove(hv_kvp_dev_buf, amt, uio)) != 0)
783 		hv_kvp_log_info("%s: hv_kvp uiomove read failed!\n", __func__);
784 
785 	free(hv_kvp_dev_buf, M_TEMP);
786 	return (error);
787 }
788 
789 
790 /*
791  * hv_kvp_daemon write invokes this function
792  * acts as a receive from daemon
793  */
794 static int
795 hv_kvp_dev_daemon_write(struct cdev *dev, struct uio *uio, int ioflag __unused)
796 {
797 	size_t amt;
798 	int error = 0;
799 	struct hv_kvp_msg *hv_kvp_dev_buf;
800 	hv_kvp_sc *sc = (hv_kvp_sc*)dev->si_drv1;
801 
802 	uio->uio_offset = 0;
803 	hv_kvp_dev_buf = malloc(sizeof(*hv_kvp_dev_buf), M_TEMP, M_WAITOK);
804 
805 	amt = MIN(uio->uio_resid, BUFFERSIZE);
806 	error = uiomove(hv_kvp_dev_buf, amt, uio);
807 
808 	if (error != 0) {
809 		free(hv_kvp_dev_buf, M_TEMP);
810 		return (error);
811 	}
812 	memcpy(&sc->daemon_kvp_msg, hv_kvp_dev_buf, sizeof(struct hv_kvp_msg));
813 
814 	free(hv_kvp_dev_buf, M_TEMP);
815 	if (sc->register_done == false) {
816 		if (sc->daemon_kvp_msg.kvp_hdr.operation == HV_KVP_OP_REGISTER) {
817 			sc->register_done = true;
818 			hv_kvp_callback(vmbus_get_channel(sc->dev), dev->si_drv1);
819 		}
820 		else {
821 			hv_kvp_log_info("%s, KVP Registration Failed\n", __func__);
822 			return (KVP_ERROR);
823 		}
824 	} else {
825 
826 		mtx_lock(&sc->pending_mutex);
827 
828 		if(!sc->req_timed_out) {
829 			struct hv_kvp_msg *hmsg = sc->host_kvp_msg;
830 			struct hv_kvp_msg *umsg = &sc->daemon_kvp_msg;
831 
832 			hv_kvp_convert_usermsg_to_hostmsg(umsg, hmsg);
833 			hv_kvp_respond_host(sc, KVP_SUCCESS);
834 			wakeup(sc);
835 			sc->req_in_progress = false;
836 		}
837 
838 		sc->daemon_busy = false;
839 		mtx_unlock(&sc->pending_mutex);
840 	}
841 
842 	return (error);
843 }
844 
845 
846 /*
847  * hv_kvp_daemon poll invokes this function to check if data is available
848  * for daemon to read.
849  */
850 static int
851 hv_kvp_dev_daemon_poll(struct cdev *dev, int events, struct thread *td)
852 {
853 	int revents = 0;
854 	hv_kvp_sc *sc = (hv_kvp_sc*)dev->si_drv1;
855 
856 	mtx_lock(&sc->pending_mutex);
857 	/*
858 	 * We check global flag daemon_busy for the data availiability for
859 	 * userland to read. Deamon_busy is set to true before driver has data
860 	 * for daemon to read. It is set to false after daemon sends
861 	 * then response back to driver.
862 	 */
863 	if (sc->daemon_busy == true)
864 		revents = POLLIN;
865 	else
866 		selrecord(td, &sc->hv_kvp_selinfo);
867 
868 	mtx_unlock(&sc->pending_mutex);
869 
870 	return (revents);
871 }
872 
873 static int
874 hv_kvp_probe(device_t dev)
875 {
876 	if (resource_disabled("hvkvp", 0))
877 		return ENXIO;
878 
879 	if (VMBUS_PROBE_GUID(device_get_parent(dev), dev, &service_guid) == 0) {
880 		device_set_desc(dev, "Hyper-V KVP Service");
881 		return BUS_PROBE_DEFAULT;
882 	}
883 	return ENXIO;
884 }
885 
886 static int
887 hv_kvp_attach(device_t dev)
888 {
889 	int error;
890 	struct sysctl_oid_list *child;
891 	struct sysctl_ctx_list *ctx;
892 
893 	hv_kvp_sc *sc = (hv_kvp_sc*)device_get_softc(dev);
894 
895 	sc->util_sc.callback = hv_kvp_callback;
896 	sc->dev = dev;
897 	sema_init(&sc->dev_sema, 0, "hv_kvp device semaphore");
898 	mtx_init(&sc->pending_mutex, "hv-kvp pending mutex",
899 		NULL, MTX_DEF);
900 
901 	ctx = device_get_sysctl_ctx(dev);
902 	child = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
903 
904 	SYSCTL_ADD_INT(ctx, child, OID_AUTO, "hv_kvp_log",
905 	    CTLFLAG_RW, &hv_kvp_log, 0, "Hyperv KVP service log level");
906 
907 	TASK_INIT(&sc->task, 0, hv_kvp_process_request, sc);
908 
909 	/* create character device */
910 	error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK,
911 			&sc->hv_kvp_dev,
912 			&hv_kvp_cdevsw,
913 			0,
914 			UID_ROOT,
915 			GID_WHEEL,
916 			0640,
917 			"hv_kvp_dev");
918 
919 	if (error != 0)
920 		return (error);
921 	sc->hv_kvp_dev->si_drv1 = sc;
922 
923 	return hv_util_attach(dev);
924 }
925 
926 static int
927 hv_kvp_detach(device_t dev)
928 {
929 	hv_kvp_sc *sc = (hv_kvp_sc*)device_get_softc(dev);
930 
931 	if (sc->daemon_task != NULL) {
932 		PROC_LOCK(sc->daemon_task);
933 		kern_psignal(sc->daemon_task, SIGKILL);
934 		PROC_UNLOCK(sc->daemon_task);
935 	}
936 
937 	destroy_dev(sc->hv_kvp_dev);
938 	return hv_util_detach(dev);
939 }
940 
941 static device_method_t kvp_methods[] = {
942 	/* Device interface */
943 	DEVMETHOD(device_probe, hv_kvp_probe),
944 	DEVMETHOD(device_attach, hv_kvp_attach),
945 	DEVMETHOD(device_detach, hv_kvp_detach),
946 	{ 0, 0 }
947 };
948 
949 static driver_t kvp_driver = { "hvkvp", kvp_methods, sizeof(hv_kvp_sc)};
950 
951 static devclass_t kvp_devclass;
952 
953 DRIVER_MODULE(hv_kvp, vmbus, kvp_driver, kvp_devclass, NULL, NULL);
954 MODULE_VERSION(hv_kvp, 1);
955 MODULE_DEPEND(hv_kvp, vmbus, 1, 1, 1);
956