Merge tag 'stackleak-v4.20-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux-2.6-microblaze.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 <linux/sched/task_stack.h>
38
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/efi.h>
45 #include <linux/random.h>
46 #include "hyperv_vmbus.h"
47
48 struct vmbus_dynid {
49         struct list_head node;
50         struct hv_vmbus_device_id id;
51 };
52
53 static struct acpi_device  *hv_acpi_dev;
54
55 static struct completion probe_event;
56
57 static int hyperv_cpuhp_online;
58
59 static void *hv_panic_page;
60
61 static int hyperv_panic_event(struct notifier_block *nb, unsigned long val,
62                               void *args)
63 {
64         struct pt_regs *regs;
65
66         regs = current_pt_regs();
67
68         hyperv_report_panic(regs, val);
69         return NOTIFY_DONE;
70 }
71
72 static int hyperv_die_event(struct notifier_block *nb, unsigned long val,
73                             void *args)
74 {
75         struct die_args *die = (struct die_args *)args;
76         struct pt_regs *regs = die->regs;
77
78         hyperv_report_panic(regs, val);
79         return NOTIFY_DONE;
80 }
81
82 static struct notifier_block hyperv_die_block = {
83         .notifier_call = hyperv_die_event,
84 };
85 static struct notifier_block hyperv_panic_block = {
86         .notifier_call = hyperv_panic_event,
87 };
88
89 static const char *fb_mmio_name = "fb_range";
90 static struct resource *fb_mmio;
91 static struct resource *hyperv_mmio;
92 static DEFINE_SEMAPHORE(hyperv_mmio_lock);
93
94 static int vmbus_exists(void)
95 {
96         if (hv_acpi_dev == NULL)
97                 return -ENODEV;
98
99         return 0;
100 }
101
102 #define VMBUS_ALIAS_LEN ((sizeof((struct hv_vmbus_device_id *)0)->guid) * 2)
103 static void print_alias_name(struct hv_device *hv_dev, char *alias_name)
104 {
105         int i;
106         for (i = 0; i < VMBUS_ALIAS_LEN; i += 2)
107                 sprintf(&alias_name[i], "%02x", hv_dev->dev_type.b[i/2]);
108 }
109
110 static u8 channel_monitor_group(const struct vmbus_channel *channel)
111 {
112         return (u8)channel->offermsg.monitorid / 32;
113 }
114
115 static u8 channel_monitor_offset(const struct vmbus_channel *channel)
116 {
117         return (u8)channel->offermsg.monitorid % 32;
118 }
119
120 static u32 channel_pending(const struct vmbus_channel *channel,
121                            const struct hv_monitor_page *monitor_page)
122 {
123         u8 monitor_group = channel_monitor_group(channel);
124
125         return monitor_page->trigger_group[monitor_group].pending;
126 }
127
128 static u32 channel_latency(const struct vmbus_channel *channel,
129                            const struct hv_monitor_page *monitor_page)
130 {
131         u8 monitor_group = channel_monitor_group(channel);
132         u8 monitor_offset = channel_monitor_offset(channel);
133
134         return monitor_page->latency[monitor_group][monitor_offset];
135 }
136
137 static u32 channel_conn_id(struct vmbus_channel *channel,
138                            struct hv_monitor_page *monitor_page)
139 {
140         u8 monitor_group = channel_monitor_group(channel);
141         u8 monitor_offset = channel_monitor_offset(channel);
142         return monitor_page->parameter[monitor_group][monitor_offset].connectionid.u.id;
143 }
144
145 static ssize_t id_show(struct device *dev, struct device_attribute *dev_attr,
146                        char *buf)
147 {
148         struct hv_device *hv_dev = device_to_hv_device(dev);
149
150         if (!hv_dev->channel)
151                 return -ENODEV;
152         return sprintf(buf, "%d\n", hv_dev->channel->offermsg.child_relid);
153 }
154 static DEVICE_ATTR_RO(id);
155
156 static ssize_t state_show(struct device *dev, struct device_attribute *dev_attr,
157                           char *buf)
158 {
159         struct hv_device *hv_dev = device_to_hv_device(dev);
160
161         if (!hv_dev->channel)
162                 return -ENODEV;
163         return sprintf(buf, "%d\n", hv_dev->channel->state);
164 }
165 static DEVICE_ATTR_RO(state);
166
167 static ssize_t monitor_id_show(struct device *dev,
168                                struct device_attribute *dev_attr, char *buf)
169 {
170         struct hv_device *hv_dev = device_to_hv_device(dev);
171
172         if (!hv_dev->channel)
173                 return -ENODEV;
174         return sprintf(buf, "%d\n", hv_dev->channel->offermsg.monitorid);
175 }
176 static DEVICE_ATTR_RO(monitor_id);
177
178 static ssize_t class_id_show(struct device *dev,
179                                struct device_attribute *dev_attr, char *buf)
180 {
181         struct hv_device *hv_dev = device_to_hv_device(dev);
182
183         if (!hv_dev->channel)
184                 return -ENODEV;
185         return sprintf(buf, "{%pUl}\n",
186                        hv_dev->channel->offermsg.offer.if_type.b);
187 }
188 static DEVICE_ATTR_RO(class_id);
189
190 static ssize_t device_id_show(struct device *dev,
191                               struct device_attribute *dev_attr, char *buf)
192 {
193         struct hv_device *hv_dev = device_to_hv_device(dev);
194
195         if (!hv_dev->channel)
196                 return -ENODEV;
197         return sprintf(buf, "{%pUl}\n",
198                        hv_dev->channel->offermsg.offer.if_instance.b);
199 }
200 static DEVICE_ATTR_RO(device_id);
201
202 static ssize_t modalias_show(struct device *dev,
203                              struct device_attribute *dev_attr, char *buf)
204 {
205         struct hv_device *hv_dev = device_to_hv_device(dev);
206         char alias_name[VMBUS_ALIAS_LEN + 1];
207
208         print_alias_name(hv_dev, alias_name);
209         return sprintf(buf, "vmbus:%s\n", alias_name);
210 }
211 static DEVICE_ATTR_RO(modalias);
212
213 #ifdef CONFIG_NUMA
214 static ssize_t numa_node_show(struct device *dev,
215                               struct device_attribute *attr, char *buf)
216 {
217         struct hv_device *hv_dev = device_to_hv_device(dev);
218
219         if (!hv_dev->channel)
220                 return -ENODEV;
221
222         return sprintf(buf, "%d\n", hv_dev->channel->numa_node);
223 }
224 static DEVICE_ATTR_RO(numa_node);
225 #endif
226
227 static ssize_t server_monitor_pending_show(struct device *dev,
228                                            struct device_attribute *dev_attr,
229                                            char *buf)
230 {
231         struct hv_device *hv_dev = device_to_hv_device(dev);
232
233         if (!hv_dev->channel)
234                 return -ENODEV;
235         return sprintf(buf, "%d\n",
236                        channel_pending(hv_dev->channel,
237                                        vmbus_connection.monitor_pages[1]));
238 }
239 static DEVICE_ATTR_RO(server_monitor_pending);
240
241 static ssize_t client_monitor_pending_show(struct device *dev,
242                                            struct device_attribute *dev_attr,
243                                            char *buf)
244 {
245         struct hv_device *hv_dev = device_to_hv_device(dev);
246
247         if (!hv_dev->channel)
248                 return -ENODEV;
249         return sprintf(buf, "%d\n",
250                        channel_pending(hv_dev->channel,
251                                        vmbus_connection.monitor_pages[1]));
252 }
253 static DEVICE_ATTR_RO(client_monitor_pending);
254
255 static ssize_t server_monitor_latency_show(struct device *dev,
256                                            struct device_attribute *dev_attr,
257                                            char *buf)
258 {
259         struct hv_device *hv_dev = device_to_hv_device(dev);
260
261         if (!hv_dev->channel)
262                 return -ENODEV;
263         return sprintf(buf, "%d\n",
264                        channel_latency(hv_dev->channel,
265                                        vmbus_connection.monitor_pages[0]));
266 }
267 static DEVICE_ATTR_RO(server_monitor_latency);
268
269 static ssize_t client_monitor_latency_show(struct device *dev,
270                                            struct device_attribute *dev_attr,
271                                            char *buf)
272 {
273         struct hv_device *hv_dev = device_to_hv_device(dev);
274
275         if (!hv_dev->channel)
276                 return -ENODEV;
277         return sprintf(buf, "%d\n",
278                        channel_latency(hv_dev->channel,
279                                        vmbus_connection.monitor_pages[1]));
280 }
281 static DEVICE_ATTR_RO(client_monitor_latency);
282
283 static ssize_t server_monitor_conn_id_show(struct device *dev,
284                                            struct device_attribute *dev_attr,
285                                            char *buf)
286 {
287         struct hv_device *hv_dev = device_to_hv_device(dev);
288
289         if (!hv_dev->channel)
290                 return -ENODEV;
291         return sprintf(buf, "%d\n",
292                        channel_conn_id(hv_dev->channel,
293                                        vmbus_connection.monitor_pages[0]));
294 }
295 static DEVICE_ATTR_RO(server_monitor_conn_id);
296
297 static ssize_t client_monitor_conn_id_show(struct device *dev,
298                                            struct device_attribute *dev_attr,
299                                            char *buf)
300 {
301         struct hv_device *hv_dev = device_to_hv_device(dev);
302
303         if (!hv_dev->channel)
304                 return -ENODEV;
305         return sprintf(buf, "%d\n",
306                        channel_conn_id(hv_dev->channel,
307                                        vmbus_connection.monitor_pages[1]));
308 }
309 static DEVICE_ATTR_RO(client_monitor_conn_id);
310
311 static ssize_t out_intr_mask_show(struct device *dev,
312                                   struct device_attribute *dev_attr, char *buf)
313 {
314         struct hv_device *hv_dev = device_to_hv_device(dev);
315         struct hv_ring_buffer_debug_info outbound;
316
317         if (!hv_dev->channel)
318                 return -ENODEV;
319         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
320         return sprintf(buf, "%d\n", outbound.current_interrupt_mask);
321 }
322 static DEVICE_ATTR_RO(out_intr_mask);
323
324 static ssize_t out_read_index_show(struct device *dev,
325                                    struct device_attribute *dev_attr, char *buf)
326 {
327         struct hv_device *hv_dev = device_to_hv_device(dev);
328         struct hv_ring_buffer_debug_info outbound;
329
330         if (!hv_dev->channel)
331                 return -ENODEV;
332         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
333         return sprintf(buf, "%d\n", outbound.current_read_index);
334 }
335 static DEVICE_ATTR_RO(out_read_index);
336
337 static ssize_t out_write_index_show(struct device *dev,
338                                     struct device_attribute *dev_attr,
339                                     char *buf)
340 {
341         struct hv_device *hv_dev = device_to_hv_device(dev);
342         struct hv_ring_buffer_debug_info outbound;
343
344         if (!hv_dev->channel)
345                 return -ENODEV;
346         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
347         return sprintf(buf, "%d\n", outbound.current_write_index);
348 }
349 static DEVICE_ATTR_RO(out_write_index);
350
351 static ssize_t out_read_bytes_avail_show(struct device *dev,
352                                          struct device_attribute *dev_attr,
353                                          char *buf)
354 {
355         struct hv_device *hv_dev = device_to_hv_device(dev);
356         struct hv_ring_buffer_debug_info outbound;
357
358         if (!hv_dev->channel)
359                 return -ENODEV;
360         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
361         return sprintf(buf, "%d\n", outbound.bytes_avail_toread);
362 }
363 static DEVICE_ATTR_RO(out_read_bytes_avail);
364
365 static ssize_t out_write_bytes_avail_show(struct device *dev,
366                                           struct device_attribute *dev_attr,
367                                           char *buf)
368 {
369         struct hv_device *hv_dev = device_to_hv_device(dev);
370         struct hv_ring_buffer_debug_info outbound;
371
372         if (!hv_dev->channel)
373                 return -ENODEV;
374         hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound, &outbound);
375         return sprintf(buf, "%d\n", outbound.bytes_avail_towrite);
376 }
377 static DEVICE_ATTR_RO(out_write_bytes_avail);
378
379 static ssize_t in_intr_mask_show(struct device *dev,
380                                  struct device_attribute *dev_attr, char *buf)
381 {
382         struct hv_device *hv_dev = device_to_hv_device(dev);
383         struct hv_ring_buffer_debug_info inbound;
384
385         if (!hv_dev->channel)
386                 return -ENODEV;
387         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
388         return sprintf(buf, "%d\n", inbound.current_interrupt_mask);
389 }
390 static DEVICE_ATTR_RO(in_intr_mask);
391
392 static ssize_t in_read_index_show(struct device *dev,
393                                   struct device_attribute *dev_attr, char *buf)
394 {
395         struct hv_device *hv_dev = device_to_hv_device(dev);
396         struct hv_ring_buffer_debug_info inbound;
397
398         if (!hv_dev->channel)
399                 return -ENODEV;
400         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
401         return sprintf(buf, "%d\n", inbound.current_read_index);
402 }
403 static DEVICE_ATTR_RO(in_read_index);
404
405 static ssize_t in_write_index_show(struct device *dev,
406                                    struct device_attribute *dev_attr, char *buf)
407 {
408         struct hv_device *hv_dev = device_to_hv_device(dev);
409         struct hv_ring_buffer_debug_info inbound;
410
411         if (!hv_dev->channel)
412                 return -ENODEV;
413         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
414         return sprintf(buf, "%d\n", inbound.current_write_index);
415 }
416 static DEVICE_ATTR_RO(in_write_index);
417
418 static ssize_t in_read_bytes_avail_show(struct device *dev,
419                                         struct device_attribute *dev_attr,
420                                         char *buf)
421 {
422         struct hv_device *hv_dev = device_to_hv_device(dev);
423         struct hv_ring_buffer_debug_info inbound;
424
425         if (!hv_dev->channel)
426                 return -ENODEV;
427         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
428         return sprintf(buf, "%d\n", inbound.bytes_avail_toread);
429 }
430 static DEVICE_ATTR_RO(in_read_bytes_avail);
431
432 static ssize_t in_write_bytes_avail_show(struct device *dev,
433                                          struct device_attribute *dev_attr,
434                                          char *buf)
435 {
436         struct hv_device *hv_dev = device_to_hv_device(dev);
437         struct hv_ring_buffer_debug_info inbound;
438
439         if (!hv_dev->channel)
440                 return -ENODEV;
441         hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
442         return sprintf(buf, "%d\n", inbound.bytes_avail_towrite);
443 }
444 static DEVICE_ATTR_RO(in_write_bytes_avail);
445
446 static ssize_t channel_vp_mapping_show(struct device *dev,
447                                        struct device_attribute *dev_attr,
448                                        char *buf)
449 {
450         struct hv_device *hv_dev = device_to_hv_device(dev);
451         struct vmbus_channel *channel = hv_dev->channel, *cur_sc;
452         unsigned long flags;
453         int buf_size = PAGE_SIZE, n_written, tot_written;
454         struct list_head *cur;
455
456         if (!channel)
457                 return -ENODEV;
458
459         tot_written = snprintf(buf, buf_size, "%u:%u\n",
460                 channel->offermsg.child_relid, channel->target_cpu);
461
462         spin_lock_irqsave(&channel->lock, flags);
463
464         list_for_each(cur, &channel->sc_list) {
465                 if (tot_written >= buf_size - 1)
466                         break;
467
468                 cur_sc = list_entry(cur, struct vmbus_channel, sc_list);
469                 n_written = scnprintf(buf + tot_written,
470                                      buf_size - tot_written,
471                                      "%u:%u\n",
472                                      cur_sc->offermsg.child_relid,
473                                      cur_sc->target_cpu);
474                 tot_written += n_written;
475         }
476
477         spin_unlock_irqrestore(&channel->lock, flags);
478
479         return tot_written;
480 }
481 static DEVICE_ATTR_RO(channel_vp_mapping);
482
483 static ssize_t vendor_show(struct device *dev,
484                            struct device_attribute *dev_attr,
485                            char *buf)
486 {
487         struct hv_device *hv_dev = device_to_hv_device(dev);
488         return sprintf(buf, "0x%x\n", hv_dev->vendor_id);
489 }
490 static DEVICE_ATTR_RO(vendor);
491
492 static ssize_t device_show(struct device *dev,
493                            struct device_attribute *dev_attr,
494                            char *buf)
495 {
496         struct hv_device *hv_dev = device_to_hv_device(dev);
497         return sprintf(buf, "0x%x\n", hv_dev->device_id);
498 }
499 static DEVICE_ATTR_RO(device);
500
501 static ssize_t driver_override_store(struct device *dev,
502                                      struct device_attribute *attr,
503                                      const char *buf, size_t count)
504 {
505         struct hv_device *hv_dev = device_to_hv_device(dev);
506         char *driver_override, *old, *cp;
507
508         /* We need to keep extra room for a newline */
509         if (count >= (PAGE_SIZE - 1))
510                 return -EINVAL;
511
512         driver_override = kstrndup(buf, count, GFP_KERNEL);
513         if (!driver_override)
514                 return -ENOMEM;
515
516         cp = strchr(driver_override, '\n');
517         if (cp)
518                 *cp = '\0';
519
520         device_lock(dev);
521         old = hv_dev->driver_override;
522         if (strlen(driver_override)) {
523                 hv_dev->driver_override = driver_override;
524         } else {
525                 kfree(driver_override);
526                 hv_dev->driver_override = NULL;
527         }
528         device_unlock(dev);
529
530         kfree(old);
531
532         return count;
533 }
534
535 static ssize_t driver_override_show(struct device *dev,
536                                     struct device_attribute *attr, char *buf)
537 {
538         struct hv_device *hv_dev = device_to_hv_device(dev);
539         ssize_t len;
540
541         device_lock(dev);
542         len = snprintf(buf, PAGE_SIZE, "%s\n", hv_dev->driver_override);
543         device_unlock(dev);
544
545         return len;
546 }
547 static DEVICE_ATTR_RW(driver_override);
548
549 /* Set up per device attributes in /sys/bus/vmbus/devices/<bus device> */
550 static struct attribute *vmbus_dev_attrs[] = {
551         &dev_attr_id.attr,
552         &dev_attr_state.attr,
553         &dev_attr_monitor_id.attr,
554         &dev_attr_class_id.attr,
555         &dev_attr_device_id.attr,
556         &dev_attr_modalias.attr,
557 #ifdef CONFIG_NUMA
558         &dev_attr_numa_node.attr,
559 #endif
560         &dev_attr_server_monitor_pending.attr,
561         &dev_attr_client_monitor_pending.attr,
562         &dev_attr_server_monitor_latency.attr,
563         &dev_attr_client_monitor_latency.attr,
564         &dev_attr_server_monitor_conn_id.attr,
565         &dev_attr_client_monitor_conn_id.attr,
566         &dev_attr_out_intr_mask.attr,
567         &dev_attr_out_read_index.attr,
568         &dev_attr_out_write_index.attr,
569         &dev_attr_out_read_bytes_avail.attr,
570         &dev_attr_out_write_bytes_avail.attr,
571         &dev_attr_in_intr_mask.attr,
572         &dev_attr_in_read_index.attr,
573         &dev_attr_in_write_index.attr,
574         &dev_attr_in_read_bytes_avail.attr,
575         &dev_attr_in_write_bytes_avail.attr,
576         &dev_attr_channel_vp_mapping.attr,
577         &dev_attr_vendor.attr,
578         &dev_attr_device.attr,
579         &dev_attr_driver_override.attr,
580         NULL,
581 };
582 ATTRIBUTE_GROUPS(vmbus_dev);
583
584 /*
585  * vmbus_uevent - add uevent for our device
586  *
587  * This routine is invoked when a device is added or removed on the vmbus to
588  * generate a uevent to udev in the userspace. The udev will then look at its
589  * rule and the uevent generated here to load the appropriate driver
590  *
591  * The alias string will be of the form vmbus:guid where guid is the string
592  * representation of the device guid (each byte of the guid will be
593  * represented with two hex characters.
594  */
595 static int vmbus_uevent(struct device *device, struct kobj_uevent_env *env)
596 {
597         struct hv_device *dev = device_to_hv_device(device);
598         int ret;
599         char alias_name[VMBUS_ALIAS_LEN + 1];
600
601         print_alias_name(dev, alias_name);
602         ret = add_uevent_var(env, "MODALIAS=vmbus:%s", alias_name);
603         return ret;
604 }
605
606 static const uuid_le null_guid;
607
608 static inline bool is_null_guid(const uuid_le *guid)
609 {
610         if (uuid_le_cmp(*guid, null_guid))
611                 return false;
612         return true;
613 }
614
615 static const struct hv_vmbus_device_id *
616 hv_vmbus_dev_match(const struct hv_vmbus_device_id *id, const uuid_le *guid)
617
618 {
619         if (id == NULL)
620                 return NULL; /* empty device table */
621
622         for (; !is_null_guid(&id->guid); id++)
623                 if (!uuid_le_cmp(id->guid, *guid))
624                         return id;
625
626         return NULL;
627 }
628
629 static const struct hv_vmbus_device_id *
630 hv_vmbus_dynid_match(struct hv_driver *drv, const uuid_le *guid)
631 {
632         const struct hv_vmbus_device_id *id = NULL;
633         struct vmbus_dynid *dynid;
634
635         spin_lock(&drv->dynids.lock);
636         list_for_each_entry(dynid, &drv->dynids.list, node) {
637                 if (!uuid_le_cmp(dynid->id.guid, *guid)) {
638                         id = &dynid->id;
639                         break;
640                 }
641         }
642         spin_unlock(&drv->dynids.lock);
643
644         return id;
645 }
646
647 static const struct hv_vmbus_device_id vmbus_device_null = {
648         .guid = NULL_UUID_LE,
649 };
650
651 /*
652  * Return a matching hv_vmbus_device_id pointer.
653  * If there is no match, return NULL.
654  */
655 static const struct hv_vmbus_device_id *hv_vmbus_get_id(struct hv_driver *drv,
656                                                         struct hv_device *dev)
657 {
658         const uuid_le *guid = &dev->dev_type;
659         const struct hv_vmbus_device_id *id;
660
661         /* When driver_override is set, only bind to the matching driver */
662         if (dev->driver_override && strcmp(dev->driver_override, drv->name))
663                 return NULL;
664
665         /* Look at the dynamic ids first, before the static ones */
666         id = hv_vmbus_dynid_match(drv, guid);
667         if (!id)
668                 id = hv_vmbus_dev_match(drv->id_table, guid);
669
670         /* driver_override will always match, send a dummy id */
671         if (!id && dev->driver_override)
672                 id = &vmbus_device_null;
673
674         return id;
675 }
676
677 /* vmbus_add_dynid - add a new device ID to this driver and re-probe devices */
678 static int vmbus_add_dynid(struct hv_driver *drv, uuid_le *guid)
679 {
680         struct vmbus_dynid *dynid;
681
682         dynid = kzalloc(sizeof(*dynid), GFP_KERNEL);
683         if (!dynid)
684                 return -ENOMEM;
685
686         dynid->id.guid = *guid;
687
688         spin_lock(&drv->dynids.lock);
689         list_add_tail(&dynid->node, &drv->dynids.list);
690         spin_unlock(&drv->dynids.lock);
691
692         return driver_attach(&drv->driver);
693 }
694
695 static void vmbus_free_dynids(struct hv_driver *drv)
696 {
697         struct vmbus_dynid *dynid, *n;
698
699         spin_lock(&drv->dynids.lock);
700         list_for_each_entry_safe(dynid, n, &drv->dynids.list, node) {
701                 list_del(&dynid->node);
702                 kfree(dynid);
703         }
704         spin_unlock(&drv->dynids.lock);
705 }
706
707 /*
708  * store_new_id - sysfs frontend to vmbus_add_dynid()
709  *
710  * Allow GUIDs to be added to an existing driver via sysfs.
711  */
712 static ssize_t new_id_store(struct device_driver *driver, const char *buf,
713                             size_t count)
714 {
715         struct hv_driver *drv = drv_to_hv_drv(driver);
716         uuid_le guid;
717         ssize_t retval;
718
719         retval = uuid_le_to_bin(buf, &guid);
720         if (retval)
721                 return retval;
722
723         if (hv_vmbus_dynid_match(drv, &guid))
724                 return -EEXIST;
725
726         retval = vmbus_add_dynid(drv, &guid);
727         if (retval)
728                 return retval;
729         return count;
730 }
731 static DRIVER_ATTR_WO(new_id);
732
733 /*
734  * store_remove_id - remove a PCI device ID from this driver
735  *
736  * Removes a dynamic pci device ID to this driver.
737  */
738 static ssize_t remove_id_store(struct device_driver *driver, const char *buf,
739                                size_t count)
740 {
741         struct hv_driver *drv = drv_to_hv_drv(driver);
742         struct vmbus_dynid *dynid, *n;
743         uuid_le guid;
744         ssize_t retval;
745
746         retval = uuid_le_to_bin(buf, &guid);
747         if (retval)
748                 return retval;
749
750         retval = -ENODEV;
751         spin_lock(&drv->dynids.lock);
752         list_for_each_entry_safe(dynid, n, &drv->dynids.list, node) {
753                 struct hv_vmbus_device_id *id = &dynid->id;
754
755                 if (!uuid_le_cmp(id->guid, guid)) {
756                         list_del(&dynid->node);
757                         kfree(dynid);
758                         retval = count;
759                         break;
760                 }
761         }
762         spin_unlock(&drv->dynids.lock);
763
764         return retval;
765 }
766 static DRIVER_ATTR_WO(remove_id);
767
768 static struct attribute *vmbus_drv_attrs[] = {
769         &driver_attr_new_id.attr,
770         &driver_attr_remove_id.attr,
771         NULL,
772 };
773 ATTRIBUTE_GROUPS(vmbus_drv);
774
775
776 /*
777  * vmbus_match - Attempt to match the specified device to the specified driver
778  */
779 static int vmbus_match(struct device *device, struct device_driver *driver)
780 {
781         struct hv_driver *drv = drv_to_hv_drv(driver);
782         struct hv_device *hv_dev = device_to_hv_device(device);
783
784         /* The hv_sock driver handles all hv_sock offers. */
785         if (is_hvsock_channel(hv_dev->channel))
786                 return drv->hvsock;
787
788         if (hv_vmbus_get_id(drv, hv_dev))
789                 return 1;
790
791         return 0;
792 }
793
794 /*
795  * vmbus_probe - Add the new vmbus's child device
796  */
797 static int vmbus_probe(struct device *child_device)
798 {
799         int ret = 0;
800         struct hv_driver *drv =
801                         drv_to_hv_drv(child_device->driver);
802         struct hv_device *dev = device_to_hv_device(child_device);
803         const struct hv_vmbus_device_id *dev_id;
804
805         dev_id = hv_vmbus_get_id(drv, dev);
806         if (drv->probe) {
807                 ret = drv->probe(dev, dev_id);
808                 if (ret != 0)
809                         pr_err("probe failed for device %s (%d)\n",
810                                dev_name(child_device), ret);
811
812         } else {
813                 pr_err("probe not set for driver %s\n",
814                        dev_name(child_device));
815                 ret = -ENODEV;
816         }
817         return ret;
818 }
819
820 /*
821  * vmbus_remove - Remove a vmbus device
822  */
823 static int vmbus_remove(struct device *child_device)
824 {
825         struct hv_driver *drv;
826         struct hv_device *dev = device_to_hv_device(child_device);
827
828         if (child_device->driver) {
829                 drv = drv_to_hv_drv(child_device->driver);
830                 if (drv->remove)
831                         drv->remove(dev);
832         }
833
834         return 0;
835 }
836
837
838 /*
839  * vmbus_shutdown - Shutdown a vmbus device
840  */
841 static void vmbus_shutdown(struct device *child_device)
842 {
843         struct hv_driver *drv;
844         struct hv_device *dev = device_to_hv_device(child_device);
845
846
847         /* The device may not be attached yet */
848         if (!child_device->driver)
849                 return;
850
851         drv = drv_to_hv_drv(child_device->driver);
852
853         if (drv->shutdown)
854                 drv->shutdown(dev);
855 }
856
857
858 /*
859  * vmbus_device_release - Final callback release of the vmbus child device
860  */
861 static void vmbus_device_release(struct device *device)
862 {
863         struct hv_device *hv_dev = device_to_hv_device(device);
864         struct vmbus_channel *channel = hv_dev->channel;
865
866         mutex_lock(&vmbus_connection.channel_mutex);
867         hv_process_channel_removal(channel);
868         mutex_unlock(&vmbus_connection.channel_mutex);
869         kfree(hv_dev);
870 }
871
872 /* The one and only one */
873 static struct bus_type  hv_bus = {
874         .name =         "vmbus",
875         .match =                vmbus_match,
876         .shutdown =             vmbus_shutdown,
877         .remove =               vmbus_remove,
878         .probe =                vmbus_probe,
879         .uevent =               vmbus_uevent,
880         .dev_groups =           vmbus_dev_groups,
881         .drv_groups =           vmbus_drv_groups,
882 };
883
884 struct onmessage_work_context {
885         struct work_struct work;
886         struct hv_message msg;
887 };
888
889 static void vmbus_onmessage_work(struct work_struct *work)
890 {
891         struct onmessage_work_context *ctx;
892
893         /* Do not process messages if we're in DISCONNECTED state */
894         if (vmbus_connection.conn_state == DISCONNECTED)
895                 return;
896
897         ctx = container_of(work, struct onmessage_work_context,
898                            work);
899         vmbus_onmessage(&ctx->msg);
900         kfree(ctx);
901 }
902
903 static void hv_process_timer_expiration(struct hv_message *msg,
904                                         struct hv_per_cpu_context *hv_cpu)
905 {
906         struct clock_event_device *dev = hv_cpu->clk_evt;
907
908         if (dev->event_handler)
909                 dev->event_handler(dev);
910
911         vmbus_signal_eom(msg, HVMSG_TIMER_EXPIRED);
912 }
913
914 void vmbus_on_msg_dpc(unsigned long data)
915 {
916         struct hv_per_cpu_context *hv_cpu = (void *)data;
917         void *page_addr = hv_cpu->synic_message_page;
918         struct hv_message *msg = (struct hv_message *)page_addr +
919                                   VMBUS_MESSAGE_SINT;
920         struct vmbus_channel_message_header *hdr;
921         const struct vmbus_channel_message_table_entry *entry;
922         struct onmessage_work_context *ctx;
923         u32 message_type = msg->header.message_type;
924
925         if (message_type == HVMSG_NONE)
926                 /* no msg */
927                 return;
928
929         hdr = (struct vmbus_channel_message_header *)msg->u.payload;
930
931         trace_vmbus_on_msg_dpc(hdr);
932
933         if (hdr->msgtype >= CHANNELMSG_COUNT) {
934                 WARN_ONCE(1, "unknown msgtype=%d\n", hdr->msgtype);
935                 goto msg_handled;
936         }
937
938         entry = &channel_message_table[hdr->msgtype];
939         if (entry->handler_type == VMHT_BLOCKING) {
940                 ctx = kmalloc(sizeof(*ctx), GFP_ATOMIC);
941                 if (ctx == NULL)
942                         return;
943
944                 INIT_WORK(&ctx->work, vmbus_onmessage_work);
945                 memcpy(&ctx->msg, msg, sizeof(*msg));
946
947                 /*
948                  * The host can generate a rescind message while we
949                  * may still be handling the original offer. We deal with
950                  * this condition by ensuring the processing is done on the
951                  * same CPU.
952                  */
953                 switch (hdr->msgtype) {
954                 case CHANNELMSG_RESCIND_CHANNELOFFER:
955                         /*
956                          * If we are handling the rescind message;
957                          * schedule the work on the global work queue.
958                          */
959                         schedule_work_on(vmbus_connection.connect_cpu,
960                                          &ctx->work);
961                         break;
962
963                 case CHANNELMSG_OFFERCHANNEL:
964                         atomic_inc(&vmbus_connection.offer_in_progress);
965                         queue_work_on(vmbus_connection.connect_cpu,
966                                       vmbus_connection.work_queue,
967                                       &ctx->work);
968                         break;
969
970                 default:
971                         queue_work(vmbus_connection.work_queue, &ctx->work);
972                 }
973         } else
974                 entry->message_handler(hdr);
975
976 msg_handled:
977         vmbus_signal_eom(msg, message_type);
978 }
979
980
981 /*
982  * Direct callback for channels using other deferred processing
983  */
984 static void vmbus_channel_isr(struct vmbus_channel *channel)
985 {
986         void (*callback_fn)(void *);
987
988         callback_fn = READ_ONCE(channel->onchannel_callback);
989         if (likely(callback_fn != NULL))
990                 (*callback_fn)(channel->channel_callback_context);
991 }
992
993 /*
994  * Schedule all channels with events pending
995  */
996 static void vmbus_chan_sched(struct hv_per_cpu_context *hv_cpu)
997 {
998         unsigned long *recv_int_page;
999         u32 maxbits, relid;
1000
1001         if (vmbus_proto_version < VERSION_WIN8) {
1002                 maxbits = MAX_NUM_CHANNELS_SUPPORTED;
1003                 recv_int_page = vmbus_connection.recv_int_page;
1004         } else {
1005                 /*
1006                  * When the host is win8 and beyond, the event page
1007                  * can be directly checked to get the id of the channel
1008                  * that has the interrupt pending.
1009                  */
1010                 void *page_addr = hv_cpu->synic_event_page;
1011                 union hv_synic_event_flags *event
1012                         = (union hv_synic_event_flags *)page_addr +
1013                                                  VMBUS_MESSAGE_SINT;
1014
1015                 maxbits = HV_EVENT_FLAGS_COUNT;
1016                 recv_int_page = event->flags;
1017         }
1018
1019         if (unlikely(!recv_int_page))
1020                 return;
1021
1022         for_each_set_bit(relid, recv_int_page, maxbits) {
1023                 struct vmbus_channel *channel;
1024
1025                 if (!sync_test_and_clear_bit(relid, recv_int_page))
1026                         continue;
1027
1028                 /* Special case - vmbus channel protocol msg */
1029                 if (relid == 0)
1030                         continue;
1031
1032                 rcu_read_lock();
1033
1034                 /* Find channel based on relid */
1035                 list_for_each_entry_rcu(channel, &hv_cpu->chan_list, percpu_list) {
1036                         if (channel->offermsg.child_relid != relid)
1037                                 continue;
1038
1039                         if (channel->rescind)
1040                                 continue;
1041
1042                         trace_vmbus_chan_sched(channel);
1043
1044                         ++channel->interrupts;
1045
1046                         switch (channel->callback_mode) {
1047                         case HV_CALL_ISR:
1048                                 vmbus_channel_isr(channel);
1049                                 break;
1050
1051                         case HV_CALL_BATCHED:
1052                                 hv_begin_read(&channel->inbound);
1053                                 /* fallthrough */
1054                         case HV_CALL_DIRECT:
1055                                 tasklet_schedule(&channel->callback_event);
1056                         }
1057                 }
1058
1059                 rcu_read_unlock();
1060         }
1061 }
1062
1063 static void vmbus_isr(void)
1064 {
1065         struct hv_per_cpu_context *hv_cpu
1066                 = this_cpu_ptr(hv_context.cpu_context);
1067         void *page_addr = hv_cpu->synic_event_page;
1068         struct hv_message *msg;
1069         union hv_synic_event_flags *event;
1070         bool handled = false;
1071
1072         if (unlikely(page_addr == NULL))
1073                 return;
1074
1075         event = (union hv_synic_event_flags *)page_addr +
1076                                          VMBUS_MESSAGE_SINT;
1077         /*
1078          * Check for events before checking for messages. This is the order
1079          * in which events and messages are checked in Windows guests on
1080          * Hyper-V, and the Windows team suggested we do the same.
1081          */
1082
1083         if ((vmbus_proto_version == VERSION_WS2008) ||
1084                 (vmbus_proto_version == VERSION_WIN7)) {
1085
1086                 /* Since we are a child, we only need to check bit 0 */
1087                 if (sync_test_and_clear_bit(0, event->flags))
1088                         handled = true;
1089         } else {
1090                 /*
1091                  * Our host is win8 or above. The signaling mechanism
1092                  * has changed and we can directly look at the event page.
1093                  * If bit n is set then we have an interrup on the channel
1094                  * whose id is n.
1095                  */
1096                 handled = true;
1097         }
1098
1099         if (handled)
1100                 vmbus_chan_sched(hv_cpu);
1101
1102         page_addr = hv_cpu->synic_message_page;
1103         msg = (struct hv_message *)page_addr + VMBUS_MESSAGE_SINT;
1104
1105         /* Check if there are actual msgs to be processed */
1106         if (msg->header.message_type != HVMSG_NONE) {
1107                 if (msg->header.message_type == HVMSG_TIMER_EXPIRED)
1108                         hv_process_timer_expiration(msg, hv_cpu);
1109                 else
1110                         tasklet_schedule(&hv_cpu->msg_dpc);
1111         }
1112
1113         add_interrupt_randomness(HYPERVISOR_CALLBACK_VECTOR, 0);
1114 }
1115
1116 /*
1117  * Boolean to control whether to report panic messages over Hyper-V.
1118  *
1119  * It can be set via /proc/sys/kernel/hyperv/record_panic_msg
1120  */
1121 static int sysctl_record_panic_msg = 1;
1122
1123 /*
1124  * Callback from kmsg_dump. Grab as much as possible from the end of the kmsg
1125  * buffer and call into Hyper-V to transfer the data.
1126  */
1127 static void hv_kmsg_dump(struct kmsg_dumper *dumper,
1128                          enum kmsg_dump_reason reason)
1129 {
1130         size_t bytes_written;
1131         phys_addr_t panic_pa;
1132
1133         /* We are only interested in panics. */
1134         if ((reason != KMSG_DUMP_PANIC) || (!sysctl_record_panic_msg))
1135                 return;
1136
1137         panic_pa = virt_to_phys(hv_panic_page);
1138
1139         /*
1140          * Write dump contents to the page. No need to synchronize; panic should
1141          * be single-threaded.
1142          */
1143         kmsg_dump_get_buffer(dumper, true, hv_panic_page, PAGE_SIZE,
1144                              &bytes_written);
1145         if (bytes_written)
1146                 hyperv_report_panic_msg(panic_pa, bytes_written);
1147 }
1148
1149 static struct kmsg_dumper hv_kmsg_dumper = {
1150         .dump = hv_kmsg_dump,
1151 };
1152
1153 static struct ctl_table_header *hv_ctl_table_hdr;
1154 static int zero;
1155 static int one = 1;
1156
1157 /*
1158  * sysctl option to allow the user to control whether kmsg data should be
1159  * reported to Hyper-V on panic.
1160  */
1161 static struct ctl_table hv_ctl_table[] = {
1162         {
1163                 .procname       = "hyperv_record_panic_msg",
1164                 .data           = &sysctl_record_panic_msg,
1165                 .maxlen         = sizeof(int),
1166                 .mode           = 0644,
1167                 .proc_handler   = proc_dointvec_minmax,
1168                 .extra1         = &zero,
1169                 .extra2         = &one
1170         },
1171         {}
1172 };
1173
1174 static struct ctl_table hv_root_table[] = {
1175         {
1176                 .procname       = "kernel",
1177                 .mode           = 0555,
1178                 .child          = hv_ctl_table
1179         },
1180         {}
1181 };
1182
1183 /*
1184  * vmbus_bus_init -Main vmbus driver initialization routine.
1185  *
1186  * Here, we
1187  *      - initialize the vmbus driver context
1188  *      - invoke the vmbus hv main init routine
1189  *      - retrieve the channel offers
1190  */
1191 static int vmbus_bus_init(void)
1192 {
1193         int ret;
1194
1195         /* Hypervisor initialization...setup hypercall page..etc */
1196         ret = hv_init();
1197         if (ret != 0) {
1198                 pr_err("Unable to initialize the hypervisor - 0x%x\n", ret);
1199                 return ret;
1200         }
1201
1202         ret = bus_register(&hv_bus);
1203         if (ret)
1204                 return ret;
1205
1206         hv_setup_vmbus_irq(vmbus_isr);
1207
1208         ret = hv_synic_alloc();
1209         if (ret)
1210                 goto err_alloc;
1211         /*
1212          * Initialize the per-cpu interrupt state and
1213          * connect to the host.
1214          */
1215         ret = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "hyperv/vmbus:online",
1216                                 hv_synic_init, hv_synic_cleanup);
1217         if (ret < 0)
1218                 goto err_alloc;
1219         hyperv_cpuhp_online = ret;
1220
1221         ret = vmbus_connect();
1222         if (ret)
1223                 goto err_connect;
1224
1225         /*
1226          * Only register if the crash MSRs are available
1227          */
1228         if (ms_hyperv.misc_features & HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE) {
1229                 u64 hyperv_crash_ctl;
1230                 /*
1231                  * Sysctl registration is not fatal, since by default
1232                  * reporting is enabled.
1233                  */
1234                 hv_ctl_table_hdr = register_sysctl_table(hv_root_table);
1235                 if (!hv_ctl_table_hdr)
1236                         pr_err("Hyper-V: sysctl table register error");
1237
1238                 /*
1239                  * Register for panic kmsg callback only if the right
1240                  * capability is supported by the hypervisor.
1241                  */
1242                 hv_get_crash_ctl(hyperv_crash_ctl);
1243                 if (hyperv_crash_ctl & HV_CRASH_CTL_CRASH_NOTIFY_MSG) {
1244                         hv_panic_page = (void *)get_zeroed_page(GFP_KERNEL);
1245                         if (hv_panic_page) {
1246                                 ret = kmsg_dump_register(&hv_kmsg_dumper);
1247                                 if (ret)
1248                                         pr_err("Hyper-V: kmsg dump register "
1249                                                 "error 0x%x\n", ret);
1250                         } else
1251                                 pr_err("Hyper-V: panic message page memory "
1252                                         "allocation failed");
1253                 }
1254
1255                 register_die_notifier(&hyperv_die_block);
1256                 atomic_notifier_chain_register(&panic_notifier_list,
1257                                                &hyperv_panic_block);
1258         }
1259
1260         vmbus_request_offers();
1261
1262         return 0;
1263
1264 err_connect:
1265         cpuhp_remove_state(hyperv_cpuhp_online);
1266 err_alloc:
1267         hv_synic_free();
1268         hv_remove_vmbus_irq();
1269
1270         bus_unregister(&hv_bus);
1271         free_page((unsigned long)hv_panic_page);
1272         unregister_sysctl_table(hv_ctl_table_hdr);
1273         hv_ctl_table_hdr = NULL;
1274         return ret;
1275 }
1276
1277 /**
1278  * __vmbus_child_driver_register() - Register a vmbus's driver
1279  * @hv_driver: Pointer to driver structure you want to register
1280  * @owner: owner module of the drv
1281  * @mod_name: module name string
1282  *
1283  * Registers the given driver with Linux through the 'driver_register()' call
1284  * and sets up the hyper-v vmbus handling for this driver.
1285  * It will return the state of the 'driver_register()' call.
1286  *
1287  */
1288 int __vmbus_driver_register(struct hv_driver *hv_driver, struct module *owner, const char *mod_name)
1289 {
1290         int ret;
1291
1292         pr_info("registering driver %s\n", hv_driver->name);
1293
1294         ret = vmbus_exists();
1295         if (ret < 0)
1296                 return ret;
1297
1298         hv_driver->driver.name = hv_driver->name;
1299         hv_driver->driver.owner = owner;
1300         hv_driver->driver.mod_name = mod_name;
1301         hv_driver->driver.bus = &hv_bus;
1302
1303         spin_lock_init(&hv_driver->dynids.lock);
1304         INIT_LIST_HEAD(&hv_driver->dynids.list);
1305
1306         ret = driver_register(&hv_driver->driver);
1307
1308         return ret;
1309 }
1310 EXPORT_SYMBOL_GPL(__vmbus_driver_register);
1311
1312 /**
1313  * vmbus_driver_unregister() - Unregister a vmbus's driver
1314  * @hv_driver: Pointer to driver structure you want to
1315  *             un-register
1316  *
1317  * Un-register the given driver that was previous registered with a call to
1318  * vmbus_driver_register()
1319  */
1320 void vmbus_driver_unregister(struct hv_driver *hv_driver)
1321 {
1322         pr_info("unregistering driver %s\n", hv_driver->name);
1323
1324         if (!vmbus_exists()) {
1325                 driver_unregister(&hv_driver->driver);
1326                 vmbus_free_dynids(hv_driver);
1327         }
1328 }
1329 EXPORT_SYMBOL_GPL(vmbus_driver_unregister);
1330
1331
1332 /*
1333  * Called when last reference to channel is gone.
1334  */
1335 static void vmbus_chan_release(struct kobject *kobj)
1336 {
1337         struct vmbus_channel *channel
1338                 = container_of(kobj, struct vmbus_channel, kobj);
1339
1340         kfree_rcu(channel, rcu);
1341 }
1342
1343 struct vmbus_chan_attribute {
1344         struct attribute attr;
1345         ssize_t (*show)(const struct vmbus_channel *chan, char *buf);
1346         ssize_t (*store)(struct vmbus_channel *chan,
1347                          const char *buf, size_t count);
1348 };
1349 #define VMBUS_CHAN_ATTR(_name, _mode, _show, _store) \
1350         struct vmbus_chan_attribute chan_attr_##_name \
1351                 = __ATTR(_name, _mode, _show, _store)
1352 #define VMBUS_CHAN_ATTR_RW(_name) \
1353         struct vmbus_chan_attribute chan_attr_##_name = __ATTR_RW(_name)
1354 #define VMBUS_CHAN_ATTR_RO(_name) \
1355         struct vmbus_chan_attribute chan_attr_##_name = __ATTR_RO(_name)
1356 #define VMBUS_CHAN_ATTR_WO(_name) \
1357         struct vmbus_chan_attribute chan_attr_##_name = __ATTR_WO(_name)
1358
1359 static ssize_t vmbus_chan_attr_show(struct kobject *kobj,
1360                                     struct attribute *attr, char *buf)
1361 {
1362         const struct vmbus_chan_attribute *attribute
1363                 = container_of(attr, struct vmbus_chan_attribute, attr);
1364         const struct vmbus_channel *chan
1365                 = container_of(kobj, struct vmbus_channel, kobj);
1366
1367         if (!attribute->show)
1368                 return -EIO;
1369
1370         if (chan->state != CHANNEL_OPENED_STATE)
1371                 return -EINVAL;
1372
1373         return attribute->show(chan, buf);
1374 }
1375
1376 static const struct sysfs_ops vmbus_chan_sysfs_ops = {
1377         .show = vmbus_chan_attr_show,
1378 };
1379
1380 static ssize_t out_mask_show(const struct vmbus_channel *channel, char *buf)
1381 {
1382         const struct hv_ring_buffer_info *rbi = &channel->outbound;
1383
1384         return sprintf(buf, "%u\n", rbi->ring_buffer->interrupt_mask);
1385 }
1386 static VMBUS_CHAN_ATTR_RO(out_mask);
1387
1388 static ssize_t in_mask_show(const struct vmbus_channel *channel, char *buf)
1389 {
1390         const struct hv_ring_buffer_info *rbi = &channel->inbound;
1391
1392         return sprintf(buf, "%u\n", rbi->ring_buffer->interrupt_mask);
1393 }
1394 static VMBUS_CHAN_ATTR_RO(in_mask);
1395
1396 static ssize_t read_avail_show(const struct vmbus_channel *channel, char *buf)
1397 {
1398         const struct hv_ring_buffer_info *rbi = &channel->inbound;
1399
1400         return sprintf(buf, "%u\n", hv_get_bytes_to_read(rbi));
1401 }
1402 static VMBUS_CHAN_ATTR_RO(read_avail);
1403
1404 static ssize_t write_avail_show(const struct vmbus_channel *channel, char *buf)
1405 {
1406         const struct hv_ring_buffer_info *rbi = &channel->outbound;
1407
1408         return sprintf(buf, "%u\n", hv_get_bytes_to_write(rbi));
1409 }
1410 static VMBUS_CHAN_ATTR_RO(write_avail);
1411
1412 static ssize_t show_target_cpu(const struct vmbus_channel *channel, char *buf)
1413 {
1414         return sprintf(buf, "%u\n", channel->target_cpu);
1415 }
1416 static VMBUS_CHAN_ATTR(cpu, S_IRUGO, show_target_cpu, NULL);
1417
1418 static ssize_t channel_pending_show(const struct vmbus_channel *channel,
1419                                     char *buf)
1420 {
1421         return sprintf(buf, "%d\n",
1422                        channel_pending(channel,
1423                                        vmbus_connection.monitor_pages[1]));
1424 }
1425 static VMBUS_CHAN_ATTR(pending, S_IRUGO, channel_pending_show, NULL);
1426
1427 static ssize_t channel_latency_show(const struct vmbus_channel *channel,
1428                                     char *buf)
1429 {
1430         return sprintf(buf, "%d\n",
1431                        channel_latency(channel,
1432                                        vmbus_connection.monitor_pages[1]));
1433 }
1434 static VMBUS_CHAN_ATTR(latency, S_IRUGO, channel_latency_show, NULL);
1435
1436 static ssize_t channel_interrupts_show(const struct vmbus_channel *channel, char *buf)
1437 {
1438         return sprintf(buf, "%llu\n", channel->interrupts);
1439 }
1440 static VMBUS_CHAN_ATTR(interrupts, S_IRUGO, channel_interrupts_show, NULL);
1441
1442 static ssize_t channel_events_show(const struct vmbus_channel *channel, char *buf)
1443 {
1444         return sprintf(buf, "%llu\n", channel->sig_events);
1445 }
1446 static VMBUS_CHAN_ATTR(events, S_IRUGO, channel_events_show, NULL);
1447
1448 static ssize_t subchannel_monitor_id_show(const struct vmbus_channel *channel,
1449                                           char *buf)
1450 {
1451         return sprintf(buf, "%u\n", channel->offermsg.monitorid);
1452 }
1453 static VMBUS_CHAN_ATTR(monitor_id, S_IRUGO, subchannel_monitor_id_show, NULL);
1454
1455 static ssize_t subchannel_id_show(const struct vmbus_channel *channel,
1456                                   char *buf)
1457 {
1458         return sprintf(buf, "%u\n",
1459                        channel->offermsg.offer.sub_channel_index);
1460 }
1461 static VMBUS_CHAN_ATTR_RO(subchannel_id);
1462
1463 static struct attribute *vmbus_chan_attrs[] = {
1464         &chan_attr_out_mask.attr,
1465         &chan_attr_in_mask.attr,
1466         &chan_attr_read_avail.attr,
1467         &chan_attr_write_avail.attr,
1468         &chan_attr_cpu.attr,
1469         &chan_attr_pending.attr,
1470         &chan_attr_latency.attr,
1471         &chan_attr_interrupts.attr,
1472         &chan_attr_events.attr,
1473         &chan_attr_monitor_id.attr,
1474         &chan_attr_subchannel_id.attr,
1475         NULL
1476 };
1477
1478 static struct kobj_type vmbus_chan_ktype = {
1479         .sysfs_ops = &vmbus_chan_sysfs_ops,
1480         .release = vmbus_chan_release,
1481         .default_attrs = vmbus_chan_attrs,
1482 };
1483
1484 /*
1485  * vmbus_add_channel_kobj - setup a sub-directory under device/channels
1486  */
1487 int vmbus_add_channel_kobj(struct hv_device *dev, struct vmbus_channel *channel)
1488 {
1489         struct kobject *kobj = &channel->kobj;
1490         u32 relid = channel->offermsg.child_relid;
1491         int ret;
1492
1493         kobj->kset = dev->channels_kset;
1494         ret = kobject_init_and_add(kobj, &vmbus_chan_ktype, NULL,
1495                                    "%u", relid);
1496         if (ret)
1497                 return ret;
1498
1499         kobject_uevent(kobj, KOBJ_ADD);
1500
1501         return 0;
1502 }
1503
1504 /*
1505  * vmbus_device_create - Creates and registers a new child device
1506  * on the vmbus.
1507  */
1508 struct hv_device *vmbus_device_create(const uuid_le *type,
1509                                       const uuid_le *instance,
1510                                       struct vmbus_channel *channel)
1511 {
1512         struct hv_device *child_device_obj;
1513
1514         child_device_obj = kzalloc(sizeof(struct hv_device), GFP_KERNEL);
1515         if (!child_device_obj) {
1516                 pr_err("Unable to allocate device object for child device\n");
1517                 return NULL;
1518         }
1519
1520         child_device_obj->channel = channel;
1521         memcpy(&child_device_obj->dev_type, type, sizeof(uuid_le));
1522         memcpy(&child_device_obj->dev_instance, instance,
1523                sizeof(uuid_le));
1524         child_device_obj->vendor_id = 0x1414; /* MSFT vendor ID */
1525
1526
1527         return child_device_obj;
1528 }
1529
1530 /*
1531  * vmbus_device_register - Register the child device
1532  */
1533 int vmbus_device_register(struct hv_device *child_device_obj)
1534 {
1535         struct kobject *kobj = &child_device_obj->device.kobj;
1536         int ret;
1537
1538         dev_set_name(&child_device_obj->device, "%pUl",
1539                      child_device_obj->channel->offermsg.offer.if_instance.b);
1540
1541         child_device_obj->device.bus = &hv_bus;
1542         child_device_obj->device.parent = &hv_acpi_dev->dev;
1543         child_device_obj->device.release = vmbus_device_release;
1544
1545         /*
1546          * Register with the LDM. This will kick off the driver/device
1547          * binding...which will eventually call vmbus_match() and vmbus_probe()
1548          */
1549         ret = device_register(&child_device_obj->device);
1550         if (ret) {
1551                 pr_err("Unable to register child device\n");
1552                 return ret;
1553         }
1554
1555         child_device_obj->channels_kset = kset_create_and_add("channels",
1556                                                               NULL, kobj);
1557         if (!child_device_obj->channels_kset) {
1558                 ret = -ENOMEM;
1559                 goto err_dev_unregister;
1560         }
1561
1562         ret = vmbus_add_channel_kobj(child_device_obj,
1563                                      child_device_obj->channel);
1564         if (ret) {
1565                 pr_err("Unable to register primary channeln");
1566                 goto err_kset_unregister;
1567         }
1568
1569         return 0;
1570
1571 err_kset_unregister:
1572         kset_unregister(child_device_obj->channels_kset);
1573
1574 err_dev_unregister:
1575         device_unregister(&child_device_obj->device);
1576         return ret;
1577 }
1578
1579 /*
1580  * vmbus_device_unregister - Remove the specified child device
1581  * from the vmbus.
1582  */
1583 void vmbus_device_unregister(struct hv_device *device_obj)
1584 {
1585         pr_debug("child device %s unregistered\n",
1586                 dev_name(&device_obj->device));
1587
1588         kset_unregister(device_obj->channels_kset);
1589
1590         /*
1591          * Kick off the process of unregistering the device.
1592          * This will call vmbus_remove() and eventually vmbus_device_release()
1593          */
1594         device_unregister(&device_obj->device);
1595 }
1596
1597
1598 /*
1599  * VMBUS is an acpi enumerated device. Get the information we
1600  * need from DSDT.
1601  */
1602 #define VTPM_BASE_ADDRESS 0xfed40000
1603 static acpi_status vmbus_walk_resources(struct acpi_resource *res, void *ctx)
1604 {
1605         resource_size_t start = 0;
1606         resource_size_t end = 0;
1607         struct resource *new_res;
1608         struct resource **old_res = &hyperv_mmio;
1609         struct resource **prev_res = NULL;
1610
1611         switch (res->type) {
1612
1613         /*
1614          * "Address" descriptors are for bus windows. Ignore
1615          * "memory" descriptors, which are for registers on
1616          * devices.
1617          */
1618         case ACPI_RESOURCE_TYPE_ADDRESS32:
1619                 start = res->data.address32.address.minimum;
1620                 end = res->data.address32.address.maximum;
1621                 break;
1622
1623         case ACPI_RESOURCE_TYPE_ADDRESS64:
1624                 start = res->data.address64.address.minimum;
1625                 end = res->data.address64.address.maximum;
1626                 break;
1627
1628         default:
1629                 /* Unused resource type */
1630                 return AE_OK;
1631
1632         }
1633         /*
1634          * Ignore ranges that are below 1MB, as they're not
1635          * necessary or useful here.
1636          */
1637         if (end < 0x100000)
1638                 return AE_OK;
1639
1640         new_res = kzalloc(sizeof(*new_res), GFP_ATOMIC);
1641         if (!new_res)
1642                 return AE_NO_MEMORY;
1643
1644         /* If this range overlaps the virtual TPM, truncate it. */
1645         if (end > VTPM_BASE_ADDRESS && start < VTPM_BASE_ADDRESS)
1646                 end = VTPM_BASE_ADDRESS;
1647
1648         new_res->name = "hyperv mmio";
1649         new_res->flags = IORESOURCE_MEM;
1650         new_res->start = start;
1651         new_res->end = end;
1652
1653         /*
1654          * If two ranges are adjacent, merge them.
1655          */
1656         do {
1657                 if (!*old_res) {
1658                         *old_res = new_res;
1659                         break;
1660                 }
1661
1662                 if (((*old_res)->end + 1) == new_res->start) {
1663                         (*old_res)->end = new_res->end;
1664                         kfree(new_res);
1665                         break;
1666                 }
1667
1668                 if ((*old_res)->start == new_res->end + 1) {
1669                         (*old_res)->start = new_res->start;
1670                         kfree(new_res);
1671                         break;
1672                 }
1673
1674                 if ((*old_res)->start > new_res->end) {
1675                         new_res->sibling = *old_res;
1676                         if (prev_res)
1677                                 (*prev_res)->sibling = new_res;
1678                         *old_res = new_res;
1679                         break;
1680                 }
1681
1682                 prev_res = old_res;
1683                 old_res = &(*old_res)->sibling;
1684
1685         } while (1);
1686
1687         return AE_OK;
1688 }
1689
1690 static int vmbus_acpi_remove(struct acpi_device *device)
1691 {
1692         struct resource *cur_res;
1693         struct resource *next_res;
1694
1695         if (hyperv_mmio) {
1696                 if (fb_mmio) {
1697                         __release_region(hyperv_mmio, fb_mmio->start,
1698                                          resource_size(fb_mmio));
1699                         fb_mmio = NULL;
1700                 }
1701
1702                 for (cur_res = hyperv_mmio; cur_res; cur_res = next_res) {
1703                         next_res = cur_res->sibling;
1704                         kfree(cur_res);
1705                 }
1706         }
1707
1708         return 0;
1709 }
1710
1711 static void vmbus_reserve_fb(void)
1712 {
1713         int size;
1714         /*
1715          * Make a claim for the frame buffer in the resource tree under the
1716          * first node, which will be the one below 4GB.  The length seems to
1717          * be underreported, particularly in a Generation 1 VM.  So start out
1718          * reserving a larger area and make it smaller until it succeeds.
1719          */
1720
1721         if (screen_info.lfb_base) {
1722                 if (efi_enabled(EFI_BOOT))
1723                         size = max_t(__u32, screen_info.lfb_size, 0x800000);
1724                 else
1725                         size = max_t(__u32, screen_info.lfb_size, 0x4000000);
1726
1727                 for (; !fb_mmio && (size >= 0x100000); size >>= 1) {
1728                         fb_mmio = __request_region(hyperv_mmio,
1729                                                    screen_info.lfb_base, size,
1730                                                    fb_mmio_name, 0);
1731                 }
1732         }
1733 }
1734
1735 /**
1736  * vmbus_allocate_mmio() - Pick a memory-mapped I/O range.
1737  * @new:                If successful, supplied a pointer to the
1738  *                      allocated MMIO space.
1739  * @device_obj:         Identifies the caller
1740  * @min:                Minimum guest physical address of the
1741  *                      allocation
1742  * @max:                Maximum guest physical address
1743  * @size:               Size of the range to be allocated
1744  * @align:              Alignment of the range to be allocated
1745  * @fb_overlap_ok:      Whether this allocation can be allowed
1746  *                      to overlap the video frame buffer.
1747  *
1748  * This function walks the resources granted to VMBus by the
1749  * _CRS object in the ACPI namespace underneath the parent
1750  * "bridge" whether that's a root PCI bus in the Generation 1
1751  * case or a Module Device in the Generation 2 case.  It then
1752  * attempts to allocate from the global MMIO pool in a way that
1753  * matches the constraints supplied in these parameters and by
1754  * that _CRS.
1755  *
1756  * Return: 0 on success, -errno on failure
1757  */
1758 int vmbus_allocate_mmio(struct resource **new, struct hv_device *device_obj,
1759                         resource_size_t min, resource_size_t max,
1760                         resource_size_t size, resource_size_t align,
1761                         bool fb_overlap_ok)
1762 {
1763         struct resource *iter, *shadow;
1764         resource_size_t range_min, range_max, start;
1765         const char *dev_n = dev_name(&device_obj->device);
1766         int retval;
1767
1768         retval = -ENXIO;
1769         down(&hyperv_mmio_lock);
1770
1771         /*
1772          * If overlaps with frame buffers are allowed, then first attempt to
1773          * make the allocation from within the reserved region.  Because it
1774          * is already reserved, no shadow allocation is necessary.
1775          */
1776         if (fb_overlap_ok && fb_mmio && !(min > fb_mmio->end) &&
1777             !(max < fb_mmio->start)) {
1778
1779                 range_min = fb_mmio->start;
1780                 range_max = fb_mmio->end;
1781                 start = (range_min + align - 1) & ~(align - 1);
1782                 for (; start + size - 1 <= range_max; start += align) {
1783                         *new = request_mem_region_exclusive(start, size, dev_n);
1784                         if (*new) {
1785                                 retval = 0;
1786                                 goto exit;
1787                         }
1788                 }
1789         }
1790
1791         for (iter = hyperv_mmio; iter; iter = iter->sibling) {
1792                 if ((iter->start >= max) || (iter->end <= min))
1793                         continue;
1794
1795                 range_min = iter->start;
1796                 range_max = iter->end;
1797                 start = (range_min + align - 1) & ~(align - 1);
1798                 for (; start + size - 1 <= range_max; start += align) {
1799                         shadow = __request_region(iter, start, size, NULL,
1800                                                   IORESOURCE_BUSY);
1801                         if (!shadow)
1802                                 continue;
1803
1804                         *new = request_mem_region_exclusive(start, size, dev_n);
1805                         if (*new) {
1806                                 shadow->name = (char *)*new;
1807                                 retval = 0;
1808                                 goto exit;
1809                         }
1810
1811                         __release_region(iter, start, size);
1812                 }
1813         }
1814
1815 exit:
1816         up(&hyperv_mmio_lock);
1817         return retval;
1818 }
1819 EXPORT_SYMBOL_GPL(vmbus_allocate_mmio);
1820
1821 /**
1822  * vmbus_free_mmio() - Free a memory-mapped I/O range.
1823  * @start:              Base address of region to release.
1824  * @size:               Size of the range to be allocated
1825  *
1826  * This function releases anything requested by
1827  * vmbus_mmio_allocate().
1828  */
1829 void vmbus_free_mmio(resource_size_t start, resource_size_t size)
1830 {
1831         struct resource *iter;
1832
1833         down(&hyperv_mmio_lock);
1834         for (iter = hyperv_mmio; iter; iter = iter->sibling) {
1835                 if ((iter->start >= start + size) || (iter->end <= start))
1836                         continue;
1837
1838                 __release_region(iter, start, size);
1839         }
1840         release_mem_region(start, size);
1841         up(&hyperv_mmio_lock);
1842
1843 }
1844 EXPORT_SYMBOL_GPL(vmbus_free_mmio);
1845
1846 static int vmbus_acpi_add(struct acpi_device *device)
1847 {
1848         acpi_status result;
1849         int ret_val = -ENODEV;
1850         struct acpi_device *ancestor;
1851
1852         hv_acpi_dev = device;
1853
1854         result = acpi_walk_resources(device->handle, METHOD_NAME__CRS,
1855                                         vmbus_walk_resources, NULL);
1856
1857         if (ACPI_FAILURE(result))
1858                 goto acpi_walk_err;
1859         /*
1860          * Some ancestor of the vmbus acpi device (Gen1 or Gen2
1861          * firmware) is the VMOD that has the mmio ranges. Get that.
1862          */
1863         for (ancestor = device->parent; ancestor; ancestor = ancestor->parent) {
1864                 result = acpi_walk_resources(ancestor->handle, METHOD_NAME__CRS,
1865                                              vmbus_walk_resources, NULL);
1866
1867                 if (ACPI_FAILURE(result))
1868                         continue;
1869                 if (hyperv_mmio) {
1870                         vmbus_reserve_fb();
1871                         break;
1872                 }
1873         }
1874         ret_val = 0;
1875
1876 acpi_walk_err:
1877         complete(&probe_event);
1878         if (ret_val)
1879                 vmbus_acpi_remove(device);
1880         return ret_val;
1881 }
1882
1883 static const struct acpi_device_id vmbus_acpi_device_ids[] = {
1884         {"VMBUS", 0},
1885         {"VMBus", 0},
1886         {"", 0},
1887 };
1888 MODULE_DEVICE_TABLE(acpi, vmbus_acpi_device_ids);
1889
1890 static struct acpi_driver vmbus_acpi_driver = {
1891         .name = "vmbus",
1892         .ids = vmbus_acpi_device_ids,
1893         .ops = {
1894                 .add = vmbus_acpi_add,
1895                 .remove = vmbus_acpi_remove,
1896         },
1897 };
1898
1899 static void hv_kexec_handler(void)
1900 {
1901         hv_synic_clockevents_cleanup();
1902         vmbus_initiate_unload(false);
1903         vmbus_connection.conn_state = DISCONNECTED;
1904         /* Make sure conn_state is set as hv_synic_cleanup checks for it */
1905         mb();
1906         cpuhp_remove_state(hyperv_cpuhp_online);
1907         hyperv_cleanup();
1908 };
1909
1910 static void hv_crash_handler(struct pt_regs *regs)
1911 {
1912         vmbus_initiate_unload(true);
1913         /*
1914          * In crash handler we can't schedule synic cleanup for all CPUs,
1915          * doing the cleanup for current CPU only. This should be sufficient
1916          * for kdump.
1917          */
1918         vmbus_connection.conn_state = DISCONNECTED;
1919         hv_synic_cleanup(smp_processor_id());
1920         hyperv_cleanup();
1921 };
1922
1923 static int __init hv_acpi_init(void)
1924 {
1925         int ret, t;
1926
1927         if (!hv_is_hyperv_initialized())
1928                 return -ENODEV;
1929
1930         init_completion(&probe_event);
1931
1932         /*
1933          * Get ACPI resources first.
1934          */
1935         ret = acpi_bus_register_driver(&vmbus_acpi_driver);
1936
1937         if (ret)
1938                 return ret;
1939
1940         t = wait_for_completion_timeout(&probe_event, 5*HZ);
1941         if (t == 0) {
1942                 ret = -ETIMEDOUT;
1943                 goto cleanup;
1944         }
1945
1946         ret = vmbus_bus_init();
1947         if (ret)
1948                 goto cleanup;
1949
1950         hv_setup_kexec_handler(hv_kexec_handler);
1951         hv_setup_crash_handler(hv_crash_handler);
1952
1953         return 0;
1954
1955 cleanup:
1956         acpi_bus_unregister_driver(&vmbus_acpi_driver);
1957         hv_acpi_dev = NULL;
1958         return ret;
1959 }
1960
1961 static void __exit vmbus_exit(void)
1962 {
1963         int cpu;
1964
1965         hv_remove_kexec_handler();
1966         hv_remove_crash_handler();
1967         vmbus_connection.conn_state = DISCONNECTED;
1968         hv_synic_clockevents_cleanup();
1969         vmbus_disconnect();
1970         hv_remove_vmbus_irq();
1971         for_each_online_cpu(cpu) {
1972                 struct hv_per_cpu_context *hv_cpu
1973                         = per_cpu_ptr(hv_context.cpu_context, cpu);
1974
1975                 tasklet_kill(&hv_cpu->msg_dpc);
1976         }
1977         vmbus_free_channels();
1978
1979         if (ms_hyperv.misc_features & HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE) {
1980                 kmsg_dump_unregister(&hv_kmsg_dumper);
1981                 unregister_die_notifier(&hyperv_die_block);
1982                 atomic_notifier_chain_unregister(&panic_notifier_list,
1983                                                  &hyperv_panic_block);
1984         }
1985
1986         free_page((unsigned long)hv_panic_page);
1987         unregister_sysctl_table(hv_ctl_table_hdr);
1988         hv_ctl_table_hdr = NULL;
1989         bus_unregister(&hv_bus);
1990
1991         cpuhp_remove_state(hyperv_cpuhp_online);
1992         hv_synic_free();
1993         acpi_bus_unregister_driver(&vmbus_acpi_driver);
1994 }
1995
1996
1997 MODULE_LICENSE("GPL");
1998
1999 subsys_initcall(hv_acpi_init);
2000 module_exit(vmbus_exit);