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