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