random: add interrupt callback to VMBus IRQ handler
[firefly-linux-kernel-4.4.55.git] / drivers / hv / vmbus_drv.c
1 /*
2  * Copyright (c) 2009, Microsoft Corporation.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms and conditions of the GNU General Public License,
6  * version 2, as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
15  * Place - Suite 330, Boston, MA 02111-1307 USA.
16  *
17  * Authors:
18  *   Haiyang Zhang <haiyangz@microsoft.com>
19  *   Hank Janssen  <hjanssen@microsoft.com>
20  *   K. Y. Srinivasan <kys@microsoft.com>
21  *
22  */
23 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
24
25 #include <linux/init.h>
26 #include <linux/module.h>
27 #include <linux/device.h>
28 #include <linux/interrupt.h>
29 #include <linux/sysctl.h>
30 #include <linux/slab.h>
31 #include <linux/acpi.h>
32 #include <linux/completion.h>
33 #include <linux/hyperv.h>
34 #include <linux/kernel_stat.h>
35 #include <linux/clockchips.h>
36 #include <linux/cpu.h>
37 #include <asm/hyperv.h>
38 #include <asm/hypervisor.h>
39 #include <asm/mshyperv.h>
40 #include <linux/notifier.h>
41 #include <linux/ptrace.h>
42 #include <linux/screen_info.h>
43 #include <linux/kdebug.h>
44 #include <linux/random.h>
45 #include "hyperv_vmbus.h"
46
47 static struct acpi_device  *hv_acpi_dev;
48
49 static struct tasklet_struct msg_dpc;
50 static struct completion probe_event;
51 static int irq;
52
53
54 static void hyperv_report_panic(struct pt_regs *regs)
55 {
56         static bool panic_reported;
57
58         /*
59          * We prefer to report panic on 'die' chain as we have proper
60          * registers to report, but if we miss it (e.g. on BUG()) we need
61          * to report it on 'panic'.
62          */
63         if (panic_reported)
64                 return;
65         panic_reported = true;
66
67         wrmsrl(HV_X64_MSR_CRASH_P0, regs->ip);
68         wrmsrl(HV_X64_MSR_CRASH_P1, regs->ax);
69         wrmsrl(HV_X64_MSR_CRASH_P2, regs->bx);
70         wrmsrl(HV_X64_MSR_CRASH_P3, regs->cx);
71         wrmsrl(HV_X64_MSR_CRASH_P4, regs->dx);
72
73         /*
74          * Let Hyper-V know there is crash data available
75          */
76         wrmsrl(HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_CRASH_NOTIFY);
77 }
78
79 static int hyperv_panic_event(struct notifier_block *nb, unsigned long val,
80                               void *args)
81 {
82         struct pt_regs *regs;
83
84         regs = current_pt_regs();
85
86         hyperv_report_panic(regs);
87         return NOTIFY_DONE;
88 }
89
90 static int hyperv_die_event(struct notifier_block *nb, unsigned long val,
91                             void *args)
92 {
93         struct die_args *die = (struct die_args *)args;
94         struct pt_regs *regs = die->regs;
95
96         hyperv_report_panic(regs);
97         return NOTIFY_DONE;
98 }
99
100 static struct notifier_block hyperv_die_block = {
101         .notifier_call = hyperv_die_event,
102 };
103 static struct notifier_block hyperv_panic_block = {
104         .notifier_call = hyperv_panic_event,
105 };
106
107 struct resource *hyperv_mmio;
108
109 static int vmbus_exists(void)
110 {
111         if (hv_acpi_dev == NULL)
112                 return -ENODEV;
113
114         return 0;
115 }
116
117 #define VMBUS_ALIAS_LEN ((sizeof((struct hv_vmbus_device_id *)0)->guid) * 2)
118 static void print_alias_name(struct hv_device *hv_dev, char *alias_name)
119 {
120         int i;
121         for (i = 0; i < VMBUS_ALIAS_LEN; i += 2)
122                 sprintf(&alias_name[i], "%02x", hv_dev->dev_type.b[i/2]);
123 }
124
125 static u8 channel_monitor_group(struct vmbus_channel *channel)
126 {
127         return (u8)channel->offermsg.monitorid / 32;
128 }
129
130 static u8 channel_monitor_offset(struct vmbus_channel *channel)
131 {
132         return (u8)channel->offermsg.monitorid % 32;
133 }
134
135 static u32 channel_pending(struct vmbus_channel *channel,
136                            struct hv_monitor_page *monitor_page)
137 {
138         u8 monitor_group = channel_monitor_group(channel);
139         return monitor_page->trigger_group[monitor_group].pending;
140 }
141
142 static u32 channel_latency(struct vmbus_channel *channel,
143                            struct hv_monitor_page *monitor_page)
144 {
145         u8 monitor_group = channel_monitor_group(channel);
146         u8 monitor_offset = channel_monitor_offset(channel);
147         return monitor_page->latency[monitor_group][monitor_offset];
148 }
149
150 static u32 channel_conn_id(struct vmbus_channel *channel,
151                            struct hv_monitor_page *monitor_page)
152 {
153         u8 monitor_group = channel_monitor_group(channel);
154         u8 monitor_offset = channel_monitor_offset(channel);
155         return monitor_page->parameter[monitor_group][monitor_offset].connectionid.u.id;
156 }
157
158 static ssize_t id_show(struct device *dev, struct device_attribute *dev_attr,
159                        char *buf)
160 {
161         struct hv_device *hv_dev = device_to_hv_device(dev);
162
163         if (!hv_dev->channel)
164                 return -ENODEV;
165         return sprintf(buf, "%d\n", hv_dev->channel->offermsg.child_relid);
166 }
167 static DEVICE_ATTR_RO(id);
168
169 static ssize_t state_show(struct device *dev, struct device_attribute *dev_attr,
170                           char *buf)
171 {
172         struct hv_device *hv_dev = device_to_hv_device(dev);
173
174         if (!hv_dev->channel)
175                 return -ENODEV;
176         return sprintf(buf, "%d\n", hv_dev->channel->state);
177 }
178 static DEVICE_ATTR_RO(state);
179
180 static ssize_t monitor_id_show(struct device *dev,
181                                struct device_attribute *dev_attr, char *buf)
182 {
183         struct hv_device *hv_dev = device_to_hv_device(dev);
184
185         if (!hv_dev->channel)
186                 return -ENODEV;
187         return sprintf(buf, "%d\n", hv_dev->channel->offermsg.monitorid);
188 }
189 static DEVICE_ATTR_RO(monitor_id);
190
191 static ssize_t class_id_show(struct device *dev,
192                                struct device_attribute *dev_attr, char *buf)
193 {
194         struct hv_device *hv_dev = device_to_hv_device(dev);
195
196         if (!hv_dev->channel)
197                 return -ENODEV;
198         return sprintf(buf, "{%pUl}\n",
199                        hv_dev->channel->offermsg.offer.if_type.b);
200 }
201 static DEVICE_ATTR_RO(class_id);
202
203 static ssize_t device_id_show(struct device *dev,
204                               struct device_attribute *dev_attr, char *buf)
205 {
206         struct hv_device *hv_dev = device_to_hv_device(dev);
207
208         if (!hv_dev->channel)
209                 return -ENODEV;
210         return sprintf(buf, "{%pUl}\n",
211                        hv_dev->channel->offermsg.offer.if_instance.b);
212 }
213 static DEVICE_ATTR_RO(device_id);
214
215 static ssize_t modalias_show(struct device *dev,
216                              struct device_attribute *dev_attr, char *buf)
217 {
218         struct hv_device *hv_dev = device_to_hv_device(dev);
219         char alias_name[VMBUS_ALIAS_LEN + 1];
220
221         print_alias_name(hv_dev, alias_name);
222         return sprintf(buf, "vmbus:%s\n", alias_name);
223 }
224 static DEVICE_ATTR_RO(modalias);
225
226 static ssize_t server_monitor_pending_show(struct device *dev,
227                                            struct device_attribute *dev_attr,
228                                            char *buf)
229 {
230         struct hv_device *hv_dev = device_to_hv_device(dev);
231
232         if (!hv_dev->channel)
233                 return -ENODEV;
234         return sprintf(buf, "%d\n",
235                        channel_pending(hv_dev->channel,
236                                        vmbus_connection.monitor_pages[1]));
237 }
238 static DEVICE_ATTR_RO(server_monitor_pending);
239
240 static ssize_t client_monitor_pending_show(struct device *dev,
241                                            struct device_attribute *dev_attr,
242                                            char *buf)
243 {
244         struct hv_device *hv_dev = device_to_hv_device(dev);
245
246         if (!hv_dev->channel)
247                 return -ENODEV;
248         return sprintf(buf, "%d\n",
249                        channel_pending(hv_dev->channel,
250                                        vmbus_connection.monitor_pages[1]));
251 }
252 static DEVICE_ATTR_RO(client_monitor_pending);
253
254 static ssize_t server_monitor_latency_show(struct device *dev,
255                                            struct device_attribute *dev_attr,
256                                            char *buf)
257 {
258         struct hv_device *hv_dev = device_to_hv_device(dev);
259
260         if (!hv_dev->channel)
261                 return -ENODEV;
262         return sprintf(buf, "%d\n",
263                        channel_latency(hv_dev->channel,
264                                        vmbus_connection.monitor_pages[0]));
265 }
266 static DEVICE_ATTR_RO(server_monitor_latency);
267
268 static ssize_t client_monitor_latency_show(struct device *dev,
269                                            struct device_attribute *dev_attr,
270                                            char *buf)
271 {
272         struct hv_device *hv_dev = device_to_hv_device(dev);
273
274         if (!hv_dev->channel)
275                 return -ENODEV;
276         return sprintf(buf, "%d\n",
277                        channel_latency(hv_dev->channel,
278                                        vmbus_connection.monitor_pages[1]));
279 }
280 static DEVICE_ATTR_RO(client_monitor_latency);
281
282 static ssize_t server_monitor_conn_id_show(struct device *dev,
283                                            struct device_attribute *dev_attr,
284                                            char *buf)
285 {
286         struct hv_device *hv_dev = device_to_hv_device(dev);
287
288         if (!hv_dev->channel)
289                 return -ENODEV;
290         return sprintf(buf, "%d\n",
291                        channel_conn_id(hv_dev->channel,
292                                        vmbus_connection.monitor_pages[0]));
293 }
294 static DEVICE_ATTR_RO(server_monitor_conn_id);
295
296 static ssize_t client_monitor_conn_id_show(struct device *dev,
297                                            struct device_attribute *dev_attr,
298                                            char *buf)
299 {
300         struct hv_device *hv_dev = device_to_hv_device(dev);
301
302         if (!hv_dev->channel)
303                 return -ENODEV;
304         return sprintf(buf, "%d\n",
305                        channel_conn_id(hv_dev->channel,
306                                        vmbus_connection.monitor_pages[1]));
307 }
308 static DEVICE_ATTR_RO(client_monitor_conn_id);
309
310 static ssize_t out_intr_mask_show(struct device *dev,
311                                   struct device_attribute *dev_attr, char *buf)
312 {
313         struct hv_device *hv_dev = device_to_hv_device(dev);
314         struct hv_ring_buffer_debug_info outbound;
315
316         if (!hv_dev->channel)
317                 return -ENODEV;
318         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
319         return sprintf(buf, "%d\n", outbound.current_interrupt_mask);
320 }
321 static DEVICE_ATTR_RO(out_intr_mask);
322
323 static ssize_t out_read_index_show(struct device *dev,
324                                    struct device_attribute *dev_attr, char *buf)
325 {
326         struct hv_device *hv_dev = device_to_hv_device(dev);
327         struct hv_ring_buffer_debug_info outbound;
328
329         if (!hv_dev->channel)
330                 return -ENODEV;
331         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
332         return sprintf(buf, "%d\n", outbound.current_read_index);
333 }
334 static DEVICE_ATTR_RO(out_read_index);
335
336 static ssize_t out_write_index_show(struct device *dev,
337                                     struct device_attribute *dev_attr,
338                                     char *buf)
339 {
340         struct hv_device *hv_dev = device_to_hv_device(dev);
341         struct hv_ring_buffer_debug_info outbound;
342
343         if (!hv_dev->channel)
344                 return -ENODEV;
345         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
346         return sprintf(buf, "%d\n", outbound.current_write_index);
347 }
348 static DEVICE_ATTR_RO(out_write_index);
349
350 static ssize_t out_read_bytes_avail_show(struct device *dev,
351                                          struct device_attribute *dev_attr,
352                                          char *buf)
353 {
354         struct hv_device *hv_dev = device_to_hv_device(dev);
355         struct hv_ring_buffer_debug_info outbound;
356
357         if (!hv_dev->channel)
358                 return -ENODEV;
359         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
360         return sprintf(buf, "%d\n", outbound.bytes_avail_toread);
361 }
362 static DEVICE_ATTR_RO(out_read_bytes_avail);
363
364 static ssize_t out_write_bytes_avail_show(struct device *dev,
365                                           struct device_attribute *dev_attr,
366                                           char *buf)
367 {
368         struct hv_device *hv_dev = device_to_hv_device(dev);
369         struct hv_ring_buffer_debug_info outbound;
370
371         if (!hv_dev->channel)
372                 return -ENODEV;
373         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
374         return sprintf(buf, "%d\n", outbound.bytes_avail_towrite);
375 }
376 static DEVICE_ATTR_RO(out_write_bytes_avail);
377
378 static ssize_t in_intr_mask_show(struct device *dev,
379                                  struct device_attribute *dev_attr, char *buf)
380 {
381         struct hv_device *hv_dev = device_to_hv_device(dev);
382         struct hv_ring_buffer_debug_info inbound;
383
384         if (!hv_dev->channel)
385                 return -ENODEV;
386         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
387         return sprintf(buf, "%d\n", inbound.current_interrupt_mask);
388 }
389 static DEVICE_ATTR_RO(in_intr_mask);
390
391 static ssize_t in_read_index_show(struct device *dev,
392                                   struct device_attribute *dev_attr, char *buf)
393 {
394         struct hv_device *hv_dev = device_to_hv_device(dev);
395         struct hv_ring_buffer_debug_info inbound;
396
397         if (!hv_dev->channel)
398                 return -ENODEV;
399         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
400         return sprintf(buf, "%d\n", inbound.current_read_index);
401 }
402 static DEVICE_ATTR_RO(in_read_index);
403
404 static ssize_t in_write_index_show(struct device *dev,
405                                    struct device_attribute *dev_attr, char *buf)
406 {
407         struct hv_device *hv_dev = device_to_hv_device(dev);
408         struct hv_ring_buffer_debug_info inbound;
409
410         if (!hv_dev->channel)
411                 return -ENODEV;
412         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
413         return sprintf(buf, "%d\n", inbound.current_write_index);
414 }
415 static DEVICE_ATTR_RO(in_write_index);
416
417 static ssize_t in_read_bytes_avail_show(struct device *dev,
418                                         struct device_attribute *dev_attr,
419                                         char *buf)
420 {
421         struct hv_device *hv_dev = device_to_hv_device(dev);
422         struct hv_ring_buffer_debug_info inbound;
423
424         if (!hv_dev->channel)
425                 return -ENODEV;
426         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
427         return sprintf(buf, "%d\n", inbound.bytes_avail_toread);
428 }
429 static DEVICE_ATTR_RO(in_read_bytes_avail);
430
431 static ssize_t in_write_bytes_avail_show(struct device *dev,
432                                          struct device_attribute *dev_attr,
433                                          char *buf)
434 {
435         struct hv_device *hv_dev = device_to_hv_device(dev);
436         struct hv_ring_buffer_debug_info inbound;
437
438         if (!hv_dev->channel)
439                 return -ENODEV;
440         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
441         return sprintf(buf, "%d\n", inbound.bytes_avail_towrite);
442 }
443 static DEVICE_ATTR_RO(in_write_bytes_avail);
444
445 static ssize_t channel_vp_mapping_show(struct device *dev,
446                                        struct device_attribute *dev_attr,
447                                        char *buf)
448 {
449         struct hv_device *hv_dev = device_to_hv_device(dev);
450         struct vmbus_channel *channel = hv_dev->channel, *cur_sc;
451         unsigned long flags;
452         int buf_size = PAGE_SIZE, n_written, tot_written;
453         struct list_head *cur;
454
455         if (!channel)
456                 return -ENODEV;
457
458         tot_written = snprintf(buf, buf_size, "%u:%u\n",
459                 channel->offermsg.child_relid, channel->target_cpu);
460
461         spin_lock_irqsave(&channel->lock, flags);
462
463         list_for_each(cur, &channel->sc_list) {
464                 if (tot_written >= buf_size - 1)
465                         break;
466
467                 cur_sc = list_entry(cur, struct vmbus_channel, sc_list);
468                 n_written = scnprintf(buf + tot_written,
469                                      buf_size - tot_written,
470                                      "%u:%u\n",
471                                      cur_sc->offermsg.child_relid,
472                                      cur_sc->target_cpu);
473                 tot_written += n_written;
474         }
475
476         spin_unlock_irqrestore(&channel->lock, flags);
477
478         return tot_written;
479 }
480 static DEVICE_ATTR_RO(channel_vp_mapping);
481
482 /* Set up per device attributes in /sys/bus/vmbus/devices/<bus device> */
483 static struct attribute *vmbus_attrs[] = {
484         &dev_attr_id.attr,
485         &dev_attr_state.attr,
486         &dev_attr_monitor_id.attr,
487         &dev_attr_class_id.attr,
488         &dev_attr_device_id.attr,
489         &dev_attr_modalias.attr,
490         &dev_attr_server_monitor_pending.attr,
491         &dev_attr_client_monitor_pending.attr,
492         &dev_attr_server_monitor_latency.attr,
493         &dev_attr_client_monitor_latency.attr,
494         &dev_attr_server_monitor_conn_id.attr,
495         &dev_attr_client_monitor_conn_id.attr,
496         &dev_attr_out_intr_mask.attr,
497         &dev_attr_out_read_index.attr,
498         &dev_attr_out_write_index.attr,
499         &dev_attr_out_read_bytes_avail.attr,
500         &dev_attr_out_write_bytes_avail.attr,
501         &dev_attr_in_intr_mask.attr,
502         &dev_attr_in_read_index.attr,
503         &dev_attr_in_write_index.attr,
504         &dev_attr_in_read_bytes_avail.attr,
505         &dev_attr_in_write_bytes_avail.attr,
506         &dev_attr_channel_vp_mapping.attr,
507         NULL,
508 };
509 ATTRIBUTE_GROUPS(vmbus);
510
511 /*
512  * vmbus_uevent - add uevent for our device
513  *
514  * This routine is invoked when a device is added or removed on the vmbus to
515  * generate a uevent to udev in the userspace. The udev will then look at its
516  * rule and the uevent generated here to load the appropriate driver
517  *
518  * The alias string will be of the form vmbus:guid where guid is the string
519  * representation of the device guid (each byte of the guid will be
520  * represented with two hex characters.
521  */
522 static int vmbus_uevent(struct device *device, struct kobj_uevent_env *env)
523 {
524         struct hv_device *dev = device_to_hv_device(device);
525         int ret;
526         char alias_name[VMBUS_ALIAS_LEN + 1];
527
528         print_alias_name(dev, alias_name);
529         ret = add_uevent_var(env, "MODALIAS=vmbus:%s", alias_name);
530         return ret;
531 }
532
533 static const uuid_le null_guid;
534
535 static inline bool is_null_guid(const __u8 *guid)
536 {
537         if (memcmp(guid, &null_guid, sizeof(uuid_le)))
538                 return false;
539         return true;
540 }
541
542 /*
543  * Return a matching hv_vmbus_device_id pointer.
544  * If there is no match, return NULL.
545  */
546 static const struct hv_vmbus_device_id *hv_vmbus_get_id(
547                                         const struct hv_vmbus_device_id *id,
548                                         const __u8 *guid)
549 {
550         for (; !is_null_guid(id->guid); id++)
551                 if (!memcmp(&id->guid, guid, sizeof(uuid_le)))
552                         return id;
553
554         return NULL;
555 }
556
557
558
559 /*
560  * vmbus_match - Attempt to match the specified device to the specified driver
561  */
562 static int vmbus_match(struct device *device, struct device_driver *driver)
563 {
564         struct hv_driver *drv = drv_to_hv_drv(driver);
565         struct hv_device *hv_dev = device_to_hv_device(device);
566
567         if (hv_vmbus_get_id(drv->id_table, hv_dev->dev_type.b))
568                 return 1;
569
570         return 0;
571 }
572
573 /*
574  * vmbus_probe - Add the new vmbus's child device
575  */
576 static int vmbus_probe(struct device *child_device)
577 {
578         int ret = 0;
579         struct hv_driver *drv =
580                         drv_to_hv_drv(child_device->driver);
581         struct hv_device *dev = device_to_hv_device(child_device);
582         const struct hv_vmbus_device_id *dev_id;
583
584         dev_id = hv_vmbus_get_id(drv->id_table, dev->dev_type.b);
585         if (drv->probe) {
586                 ret = drv->probe(dev, dev_id);
587                 if (ret != 0)
588                         pr_err("probe failed for device %s (%d)\n",
589                                dev_name(child_device), ret);
590
591         } else {
592                 pr_err("probe not set for driver %s\n",
593                        dev_name(child_device));
594                 ret = -ENODEV;
595         }
596         return ret;
597 }
598
599 /*
600  * vmbus_remove - Remove a vmbus device
601  */
602 static int vmbus_remove(struct device *child_device)
603 {
604         struct hv_driver *drv;
605         struct hv_device *dev = device_to_hv_device(child_device);
606         u32 relid = dev->channel->offermsg.child_relid;
607
608         if (child_device->driver) {
609                 drv = drv_to_hv_drv(child_device->driver);
610                 if (drv->remove)
611                         drv->remove(dev);
612                 else {
613                         hv_process_channel_removal(dev->channel, relid);
614                         pr_err("remove not set for driver %s\n",
615                                 dev_name(child_device));
616                 }
617         } else {
618                 /*
619                  * We don't have a driver for this device; deal with the
620                  * rescind message by removing the channel.
621                  */
622                 hv_process_channel_removal(dev->channel, relid);
623         }
624
625         return 0;
626 }
627
628
629 /*
630  * vmbus_shutdown - Shutdown a vmbus device
631  */
632 static void vmbus_shutdown(struct device *child_device)
633 {
634         struct hv_driver *drv;
635         struct hv_device *dev = device_to_hv_device(child_device);
636
637
638         /* The device may not be attached yet */
639         if (!child_device->driver)
640                 return;
641
642         drv = drv_to_hv_drv(child_device->driver);
643
644         if (drv->shutdown)
645                 drv->shutdown(dev);
646
647         return;
648 }
649
650
651 /*
652  * vmbus_device_release - Final callback release of the vmbus child device
653  */
654 static void vmbus_device_release(struct device *device)
655 {
656         struct hv_device *hv_dev = device_to_hv_device(device);
657
658         kfree(hv_dev);
659
660 }
661
662 /* The one and only one */
663 static struct bus_type  hv_bus = {
664         .name =         "vmbus",
665         .match =                vmbus_match,
666         .shutdown =             vmbus_shutdown,
667         .remove =               vmbus_remove,
668         .probe =                vmbus_probe,
669         .uevent =               vmbus_uevent,
670         .dev_groups =           vmbus_groups,
671 };
672
673 struct onmessage_work_context {
674         struct work_struct work;
675         struct hv_message msg;
676 };
677
678 static void vmbus_onmessage_work(struct work_struct *work)
679 {
680         struct onmessage_work_context *ctx;
681
682         /* Do not process messages if we're in DISCONNECTED state */
683         if (vmbus_connection.conn_state == DISCONNECTED)
684                 return;
685
686         ctx = container_of(work, struct onmessage_work_context,
687                            work);
688         vmbus_onmessage(&ctx->msg);
689         kfree(ctx);
690 }
691
692 static void hv_process_timer_expiration(struct hv_message *msg, int cpu)
693 {
694         struct clock_event_device *dev = hv_context.clk_evt[cpu];
695
696         if (dev->event_handler)
697                 dev->event_handler(dev);
698
699         msg->header.message_type = HVMSG_NONE;
700
701         /*
702          * Make sure the write to MessageType (ie set to
703          * HVMSG_NONE) happens before we read the
704          * MessagePending and EOMing. Otherwise, the EOMing
705          * will not deliver any more messages since there is
706          * no empty slot
707          */
708         mb();
709
710         if (msg->header.message_flags.msg_pending) {
711                 /*
712                  * This will cause message queue rescan to
713                  * possibly deliver another msg from the
714                  * hypervisor
715                  */
716                 wrmsrl(HV_X64_MSR_EOM, 0);
717         }
718 }
719
720 static void vmbus_on_msg_dpc(unsigned long data)
721 {
722         int cpu = smp_processor_id();
723         void *page_addr = hv_context.synic_message_page[cpu];
724         struct hv_message *msg = (struct hv_message *)page_addr +
725                                   VMBUS_MESSAGE_SINT;
726         struct vmbus_channel_message_header *hdr;
727         struct vmbus_channel_message_table_entry *entry;
728         struct onmessage_work_context *ctx;
729
730         while (1) {
731                 if (msg->header.message_type == HVMSG_NONE)
732                         /* no msg */
733                         break;
734
735                 hdr = (struct vmbus_channel_message_header *)msg->u.payload;
736
737                 if (hdr->msgtype >= CHANNELMSG_COUNT) {
738                         WARN_ONCE(1, "unknown msgtype=%d\n", hdr->msgtype);
739                         goto msg_handled;
740                 }
741
742                 entry = &channel_message_table[hdr->msgtype];
743                 if (entry->handler_type == VMHT_BLOCKING) {
744                         ctx = kmalloc(sizeof(*ctx), GFP_ATOMIC);
745                         if (ctx == NULL)
746                                 continue;
747
748                         INIT_WORK(&ctx->work, vmbus_onmessage_work);
749                         memcpy(&ctx->msg, msg, sizeof(*msg));
750
751                         queue_work(vmbus_connection.work_queue, &ctx->work);
752                 } else
753                         entry->message_handler(hdr);
754
755 msg_handled:
756                 msg->header.message_type = HVMSG_NONE;
757
758                 /*
759                  * Make sure the write to MessageType (ie set to
760                  * HVMSG_NONE) happens before we read the
761                  * MessagePending and EOMing. Otherwise, the EOMing
762                  * will not deliver any more messages since there is
763                  * no empty slot
764                  */
765                 mb();
766
767                 if (msg->header.message_flags.msg_pending) {
768                         /*
769                          * This will cause message queue rescan to
770                          * possibly deliver another msg from the
771                          * hypervisor
772                          */
773                         wrmsrl(HV_X64_MSR_EOM, 0);
774                 }
775         }
776 }
777
778 static void vmbus_isr(void)
779 {
780         int cpu = smp_processor_id();
781         void *page_addr;
782         struct hv_message *msg;
783         union hv_synic_event_flags *event;
784         bool handled = false;
785
786         page_addr = hv_context.synic_event_page[cpu];
787         if (page_addr == NULL)
788                 return;
789
790         event = (union hv_synic_event_flags *)page_addr +
791                                          VMBUS_MESSAGE_SINT;
792         /*
793          * Check for events before checking for messages. This is the order
794          * in which events and messages are checked in Windows guests on
795          * Hyper-V, and the Windows team suggested we do the same.
796          */
797
798         if ((vmbus_proto_version == VERSION_WS2008) ||
799                 (vmbus_proto_version == VERSION_WIN7)) {
800
801                 /* Since we are a child, we only need to check bit 0 */
802                 if (sync_test_and_clear_bit(0,
803                         (unsigned long *) &event->flags32[0])) {
804                         handled = true;
805                 }
806         } else {
807                 /*
808                  * Our host is win8 or above. The signaling mechanism
809                  * has changed and we can directly look at the event page.
810                  * If bit n is set then we have an interrup on the channel
811                  * whose id is n.
812                  */
813                 handled = true;
814         }
815
816         if (handled)
817                 tasklet_schedule(hv_context.event_dpc[cpu]);
818
819
820         page_addr = hv_context.synic_message_page[cpu];
821         msg = (struct hv_message *)page_addr + VMBUS_MESSAGE_SINT;
822
823         /* Check if there are actual msgs to be processed */
824         if (msg->header.message_type != HVMSG_NONE) {
825                 if (msg->header.message_type == HVMSG_TIMER_EXPIRED)
826                         hv_process_timer_expiration(msg, cpu);
827                 else
828                         tasklet_schedule(&msg_dpc);
829         }
830
831         add_interrupt_randomness(HYPERVISOR_CALLBACK_VECTOR, 0);
832 }
833
834
835 /*
836  * vmbus_bus_init -Main vmbus driver initialization routine.
837  *
838  * Here, we
839  *      - initialize the vmbus driver context
840  *      - invoke the vmbus hv main init routine
841  *      - get the irq resource
842  *      - retrieve the channel offers
843  */
844 static int vmbus_bus_init(int irq)
845 {
846         int ret;
847
848         /* Hypervisor initialization...setup hypercall page..etc */
849         ret = hv_init();
850         if (ret != 0) {
851                 pr_err("Unable to initialize the hypervisor - 0x%x\n", ret);
852                 return ret;
853         }
854
855         tasklet_init(&msg_dpc, vmbus_on_msg_dpc, 0);
856
857         ret = bus_register(&hv_bus);
858         if (ret)
859                 goto err_cleanup;
860
861         hv_setup_vmbus_irq(vmbus_isr);
862
863         ret = hv_synic_alloc();
864         if (ret)
865                 goto err_alloc;
866         /*
867          * Initialize the per-cpu interrupt state and
868          * connect to the host.
869          */
870         on_each_cpu(hv_synic_init, NULL, 1);
871         ret = vmbus_connect();
872         if (ret)
873                 goto err_alloc;
874
875         if (vmbus_proto_version > VERSION_WIN7)
876                 cpu_hotplug_disable();
877
878         /*
879          * Only register if the crash MSRs are available
880          */
881         if (ms_hyperv.misc_features & HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE) {
882                 register_die_notifier(&hyperv_die_block);
883                 atomic_notifier_chain_register(&panic_notifier_list,
884                                                &hyperv_panic_block);
885         }
886
887         vmbus_request_offers();
888
889         return 0;
890
891 err_alloc:
892         hv_synic_free();
893         hv_remove_vmbus_irq();
894
895         bus_unregister(&hv_bus);
896
897 err_cleanup:
898         hv_cleanup();
899
900         return ret;
901 }
902
903 /**
904  * __vmbus_child_driver_register() - Register a vmbus's driver
905  * @hv_driver: Pointer to driver structure you want to register
906  * @owner: owner module of the drv
907  * @mod_name: module name string
908  *
909  * Registers the given driver with Linux through the 'driver_register()' call
910  * and sets up the hyper-v vmbus handling for this driver.
911  * It will return the state of the 'driver_register()' call.
912  *
913  */
914 int __vmbus_driver_register(struct hv_driver *hv_driver, struct module *owner, const char *mod_name)
915 {
916         int ret;
917
918         pr_info("registering driver %s\n", hv_driver->name);
919
920         ret = vmbus_exists();
921         if (ret < 0)
922                 return ret;
923
924         hv_driver->driver.name = hv_driver->name;
925         hv_driver->driver.owner = owner;
926         hv_driver->driver.mod_name = mod_name;
927         hv_driver->driver.bus = &hv_bus;
928
929         ret = driver_register(&hv_driver->driver);
930
931         return ret;
932 }
933 EXPORT_SYMBOL_GPL(__vmbus_driver_register);
934
935 /**
936  * vmbus_driver_unregister() - Unregister a vmbus's driver
937  * @hv_driver: Pointer to driver structure you want to
938  *             un-register
939  *
940  * Un-register the given driver that was previous registered with a call to
941  * vmbus_driver_register()
942  */
943 void vmbus_driver_unregister(struct hv_driver *hv_driver)
944 {
945         pr_info("unregistering driver %s\n", hv_driver->name);
946
947         if (!vmbus_exists())
948                 driver_unregister(&hv_driver->driver);
949 }
950 EXPORT_SYMBOL_GPL(vmbus_driver_unregister);
951
952 /*
953  * vmbus_device_create - Creates and registers a new child device
954  * on the vmbus.
955  */
956 struct hv_device *vmbus_device_create(const uuid_le *type,
957                                       const uuid_le *instance,
958                                       struct vmbus_channel *channel)
959 {
960         struct hv_device *child_device_obj;
961
962         child_device_obj = kzalloc(sizeof(struct hv_device), GFP_KERNEL);
963         if (!child_device_obj) {
964                 pr_err("Unable to allocate device object for child device\n");
965                 return NULL;
966         }
967
968         child_device_obj->channel = channel;
969         memcpy(&child_device_obj->dev_type, type, sizeof(uuid_le));
970         memcpy(&child_device_obj->dev_instance, instance,
971                sizeof(uuid_le));
972
973
974         return child_device_obj;
975 }
976
977 /*
978  * vmbus_device_register - Register the child device
979  */
980 int vmbus_device_register(struct hv_device *child_device_obj)
981 {
982         int ret = 0;
983
984         dev_set_name(&child_device_obj->device, "vmbus_%d",
985                      child_device_obj->channel->id);
986
987         child_device_obj->device.bus = &hv_bus;
988         child_device_obj->device.parent = &hv_acpi_dev->dev;
989         child_device_obj->device.release = vmbus_device_release;
990
991         /*
992          * Register with the LDM. This will kick off the driver/device
993          * binding...which will eventually call vmbus_match() and vmbus_probe()
994          */
995         ret = device_register(&child_device_obj->device);
996
997         if (ret)
998                 pr_err("Unable to register child device\n");
999         else
1000                 pr_debug("child device %s registered\n",
1001                         dev_name(&child_device_obj->device));
1002
1003         return ret;
1004 }
1005
1006 /*
1007  * vmbus_device_unregister - Remove the specified child device
1008  * from the vmbus.
1009  */
1010 void vmbus_device_unregister(struct hv_device *device_obj)
1011 {
1012         pr_debug("child device %s unregistered\n",
1013                 dev_name(&device_obj->device));
1014
1015         /*
1016          * Kick off the process of unregistering the device.
1017          * This will call vmbus_remove() and eventually vmbus_device_release()
1018          */
1019         device_unregister(&device_obj->device);
1020 }
1021
1022
1023 /*
1024  * VMBUS is an acpi enumerated device. Get the information we
1025  * need from DSDT.
1026  */
1027 #define VTPM_BASE_ADDRESS 0xfed40000
1028 static acpi_status vmbus_walk_resources(struct acpi_resource *res, void *ctx)
1029 {
1030         resource_size_t start = 0;
1031         resource_size_t end = 0;
1032         struct resource *new_res;
1033         struct resource **old_res = &hyperv_mmio;
1034         struct resource **prev_res = NULL;
1035
1036         switch (res->type) {
1037         case ACPI_RESOURCE_TYPE_IRQ:
1038                 irq = res->data.irq.interrupts[0];
1039                 return AE_OK;
1040
1041         /*
1042          * "Address" descriptors are for bus windows. Ignore
1043          * "memory" descriptors, which are for registers on
1044          * devices.
1045          */
1046         case ACPI_RESOURCE_TYPE_ADDRESS32:
1047                 start = res->data.address32.address.minimum;
1048                 end = res->data.address32.address.maximum;
1049                 break;
1050
1051         case ACPI_RESOURCE_TYPE_ADDRESS64:
1052                 start = res->data.address64.address.minimum;
1053                 end = res->data.address64.address.maximum;
1054                 break;
1055
1056         default:
1057                 /* Unused resource type */
1058                 return AE_OK;
1059
1060         }
1061         /*
1062          * Ignore ranges that are below 1MB, as they're not
1063          * necessary or useful here.
1064          */
1065         if (end < 0x100000)
1066                 return AE_OK;
1067
1068         new_res = kzalloc(sizeof(*new_res), GFP_ATOMIC);
1069         if (!new_res)
1070                 return AE_NO_MEMORY;
1071
1072         /* If this range overlaps the virtual TPM, truncate it. */
1073         if (end > VTPM_BASE_ADDRESS && start < VTPM_BASE_ADDRESS)
1074                 end = VTPM_BASE_ADDRESS;
1075
1076         new_res->name = "hyperv mmio";
1077         new_res->flags = IORESOURCE_MEM;
1078         new_res->start = start;
1079         new_res->end = end;
1080
1081         do {
1082                 if (!*old_res) {
1083                         *old_res = new_res;
1084                         break;
1085                 }
1086
1087                 if ((*old_res)->end < new_res->start) {
1088                         new_res->sibling = *old_res;
1089                         if (prev_res)
1090                                 (*prev_res)->sibling = new_res;
1091                         *old_res = new_res;
1092                         break;
1093                 }
1094
1095                 prev_res = old_res;
1096                 old_res = &(*old_res)->sibling;
1097
1098         } while (1);
1099
1100         return AE_OK;
1101 }
1102
1103 static int vmbus_acpi_remove(struct acpi_device *device)
1104 {
1105         struct resource *cur_res;
1106         struct resource *next_res;
1107
1108         if (hyperv_mmio) {
1109                 for (cur_res = hyperv_mmio; cur_res; cur_res = next_res) {
1110                         next_res = cur_res->sibling;
1111                         kfree(cur_res);
1112                 }
1113         }
1114
1115         return 0;
1116 }
1117
1118 /**
1119  * vmbus_allocate_mmio() - Pick a memory-mapped I/O range.
1120  * @new:                If successful, supplied a pointer to the
1121  *                      allocated MMIO space.
1122  * @device_obj:         Identifies the caller
1123  * @min:                Minimum guest physical address of the
1124  *                      allocation
1125  * @max:                Maximum guest physical address
1126  * @size:               Size of the range to be allocated
1127  * @align:              Alignment of the range to be allocated
1128  * @fb_overlap_ok:      Whether this allocation can be allowed
1129  *                      to overlap the video frame buffer.
1130  *
1131  * This function walks the resources granted to VMBus by the
1132  * _CRS object in the ACPI namespace underneath the parent
1133  * "bridge" whether that's a root PCI bus in the Generation 1
1134  * case or a Module Device in the Generation 2 case.  It then
1135  * attempts to allocate from the global MMIO pool in a way that
1136  * matches the constraints supplied in these parameters and by
1137  * that _CRS.
1138  *
1139  * Return: 0 on success, -errno on failure
1140  */
1141 int vmbus_allocate_mmio(struct resource **new, struct hv_device *device_obj,
1142                         resource_size_t min, resource_size_t max,
1143                         resource_size_t size, resource_size_t align,
1144                         bool fb_overlap_ok)
1145 {
1146         struct resource *iter;
1147         resource_size_t range_min, range_max, start, local_min, local_max;
1148         const char *dev_n = dev_name(&device_obj->device);
1149         u32 fb_end = screen_info.lfb_base + (screen_info.lfb_size << 1);
1150         int i;
1151
1152         for (iter = hyperv_mmio; iter; iter = iter->sibling) {
1153                 if ((iter->start >= max) || (iter->end <= min))
1154                         continue;
1155
1156                 range_min = iter->start;
1157                 range_max = iter->end;
1158
1159                 /* If this range overlaps the frame buffer, split it into
1160                    two tries. */
1161                 for (i = 0; i < 2; i++) {
1162                         local_min = range_min;
1163                         local_max = range_max;
1164                         if (fb_overlap_ok || (range_min >= fb_end) ||
1165                             (range_max <= screen_info.lfb_base)) {
1166                                 i++;
1167                         } else {
1168                                 if ((range_min <= screen_info.lfb_base) &&
1169                                     (range_max >= screen_info.lfb_base)) {
1170                                         /*
1171                                          * The frame buffer is in this window,
1172                                          * so trim this into the part that
1173                                          * preceeds the frame buffer.
1174                                          */
1175                                         local_max = screen_info.lfb_base - 1;
1176                                         range_min = fb_end;
1177                                 } else {
1178                                         range_min = fb_end;
1179                                         continue;
1180                                 }
1181                         }
1182
1183                         start = (local_min + align - 1) & ~(align - 1);
1184                         for (; start + size - 1 <= local_max; start += align) {
1185                                 *new = request_mem_region_exclusive(start, size,
1186                                                                     dev_n);
1187                                 if (*new)
1188                                         return 0;
1189                         }
1190                 }
1191         }
1192
1193         return -ENXIO;
1194 }
1195 EXPORT_SYMBOL_GPL(vmbus_allocate_mmio);
1196
1197 static int vmbus_acpi_add(struct acpi_device *device)
1198 {
1199         acpi_status result;
1200         int ret_val = -ENODEV;
1201         struct acpi_device *ancestor;
1202
1203         hv_acpi_dev = device;
1204
1205         result = acpi_walk_resources(device->handle, METHOD_NAME__CRS,
1206                                         vmbus_walk_resources, NULL);
1207
1208         if (ACPI_FAILURE(result))
1209                 goto acpi_walk_err;
1210         /*
1211          * Some ancestor of the vmbus acpi device (Gen1 or Gen2
1212          * firmware) is the VMOD that has the mmio ranges. Get that.
1213          */
1214         for (ancestor = device->parent; ancestor; ancestor = ancestor->parent) {
1215                 result = acpi_walk_resources(ancestor->handle, METHOD_NAME__CRS,
1216                                              vmbus_walk_resources, NULL);
1217
1218                 if (ACPI_FAILURE(result))
1219                         continue;
1220                 if (hyperv_mmio)
1221                         break;
1222         }
1223         ret_val = 0;
1224
1225 acpi_walk_err:
1226         complete(&probe_event);
1227         if (ret_val)
1228                 vmbus_acpi_remove(device);
1229         return ret_val;
1230 }
1231
1232 static const struct acpi_device_id vmbus_acpi_device_ids[] = {
1233         {"VMBUS", 0},
1234         {"VMBus", 0},
1235         {"", 0},
1236 };
1237 MODULE_DEVICE_TABLE(acpi, vmbus_acpi_device_ids);
1238
1239 static struct acpi_driver vmbus_acpi_driver = {
1240         .name = "vmbus",
1241         .ids = vmbus_acpi_device_ids,
1242         .ops = {
1243                 .add = vmbus_acpi_add,
1244                 .remove = vmbus_acpi_remove,
1245         },
1246 };
1247
1248 static void hv_kexec_handler(void)
1249 {
1250         int cpu;
1251
1252         hv_synic_clockevents_cleanup();
1253         vmbus_initiate_unload();
1254         for_each_online_cpu(cpu)
1255                 smp_call_function_single(cpu, hv_synic_cleanup, NULL, 1);
1256         hv_cleanup();
1257 };
1258
1259 static void hv_crash_handler(struct pt_regs *regs)
1260 {
1261         vmbus_initiate_unload();
1262         /*
1263          * In crash handler we can't schedule synic cleanup for all CPUs,
1264          * doing the cleanup for current CPU only. This should be sufficient
1265          * for kdump.
1266          */
1267         hv_synic_cleanup(NULL);
1268         hv_cleanup();
1269 };
1270
1271 static int __init hv_acpi_init(void)
1272 {
1273         int ret, t;
1274
1275         if (x86_hyper != &x86_hyper_ms_hyperv)
1276                 return -ENODEV;
1277
1278         init_completion(&probe_event);
1279
1280         /*
1281          * Get irq resources first.
1282          */
1283         ret = acpi_bus_register_driver(&vmbus_acpi_driver);
1284
1285         if (ret)
1286                 return ret;
1287
1288         t = wait_for_completion_timeout(&probe_event, 5*HZ);
1289         if (t == 0) {
1290                 ret = -ETIMEDOUT;
1291                 goto cleanup;
1292         }
1293
1294         if (irq <= 0) {
1295                 ret = -ENODEV;
1296                 goto cleanup;
1297         }
1298
1299         ret = vmbus_bus_init(irq);
1300         if (ret)
1301                 goto cleanup;
1302
1303         hv_setup_kexec_handler(hv_kexec_handler);
1304         hv_setup_crash_handler(hv_crash_handler);
1305
1306         return 0;
1307
1308 cleanup:
1309         acpi_bus_unregister_driver(&vmbus_acpi_driver);
1310         hv_acpi_dev = NULL;
1311         return ret;
1312 }
1313
1314 static void __exit vmbus_exit(void)
1315 {
1316         int cpu;
1317
1318         hv_remove_kexec_handler();
1319         hv_remove_crash_handler();
1320         vmbus_connection.conn_state = DISCONNECTED;
1321         hv_synic_clockevents_cleanup();
1322         vmbus_disconnect();
1323         hv_remove_vmbus_irq();
1324         tasklet_kill(&msg_dpc);
1325         vmbus_free_channels();
1326         if (ms_hyperv.misc_features & HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE) {
1327                 unregister_die_notifier(&hyperv_die_block);
1328                 atomic_notifier_chain_unregister(&panic_notifier_list,
1329                                                  &hyperv_panic_block);
1330         }
1331         bus_unregister(&hv_bus);
1332         hv_cleanup();
1333         for_each_online_cpu(cpu) {
1334                 tasklet_kill(hv_context.event_dpc[cpu]);
1335                 smp_call_function_single(cpu, hv_synic_cleanup, NULL, 1);
1336         }
1337         hv_synic_free();
1338         acpi_bus_unregister_driver(&vmbus_acpi_driver);
1339         if (vmbus_proto_version > VERSION_WIN7)
1340                 cpu_hotplug_enable();
1341 }
1342
1343
1344 MODULE_LICENSE("GPL");
1345
1346 subsys_initcall(hv_acpi_init);
1347 module_exit(vmbus_exit);