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