Merge branch 'mlxsw-Two-port-module-fixes'
[sfrench/cifs-2.6.git] / drivers / hv / channel_mgmt.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  */
21 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
22
23 #include <linux/kernel.h>
24 #include <linux/interrupt.h>
25 #include <linux/sched.h>
26 #include <linux/wait.h>
27 #include <linux/mm.h>
28 #include <linux/slab.h>
29 #include <linux/list.h>
30 #include <linux/module.h>
31 #include <linux/completion.h>
32 #include <linux/delay.h>
33 #include <linux/hyperv.h>
34 #include <asm/mshyperv.h>
35
36 #include "hyperv_vmbus.h"
37
38 static void init_vp_index(struct vmbus_channel *channel, u16 dev_type);
39
40 static const struct vmbus_device vmbus_devs[] = {
41         /* IDE */
42         { .dev_type = HV_IDE,
43           HV_IDE_GUID,
44           .perf_device = true,
45         },
46
47         /* SCSI */
48         { .dev_type = HV_SCSI,
49           HV_SCSI_GUID,
50           .perf_device = true,
51         },
52
53         /* Fibre Channel */
54         { .dev_type = HV_FC,
55           HV_SYNTHFC_GUID,
56           .perf_device = true,
57         },
58
59         /* Synthetic NIC */
60         { .dev_type = HV_NIC,
61           HV_NIC_GUID,
62           .perf_device = true,
63         },
64
65         /* Network Direct */
66         { .dev_type = HV_ND,
67           HV_ND_GUID,
68           .perf_device = true,
69         },
70
71         /* PCIE */
72         { .dev_type = HV_PCIE,
73           HV_PCIE_GUID,
74           .perf_device = false,
75         },
76
77         /* Synthetic Frame Buffer */
78         { .dev_type = HV_FB,
79           HV_SYNTHVID_GUID,
80           .perf_device = false,
81         },
82
83         /* Synthetic Keyboard */
84         { .dev_type = HV_KBD,
85           HV_KBD_GUID,
86           .perf_device = false,
87         },
88
89         /* Synthetic MOUSE */
90         { .dev_type = HV_MOUSE,
91           HV_MOUSE_GUID,
92           .perf_device = false,
93         },
94
95         /* KVP */
96         { .dev_type = HV_KVP,
97           HV_KVP_GUID,
98           .perf_device = false,
99         },
100
101         /* Time Synch */
102         { .dev_type = HV_TS,
103           HV_TS_GUID,
104           .perf_device = false,
105         },
106
107         /* Heartbeat */
108         { .dev_type = HV_HB,
109           HV_HEART_BEAT_GUID,
110           .perf_device = false,
111         },
112
113         /* Shutdown */
114         { .dev_type = HV_SHUTDOWN,
115           HV_SHUTDOWN_GUID,
116           .perf_device = false,
117         },
118
119         /* File copy */
120         { .dev_type = HV_FCOPY,
121           HV_FCOPY_GUID,
122           .perf_device = false,
123         },
124
125         /* Backup */
126         { .dev_type = HV_BACKUP,
127           HV_VSS_GUID,
128           .perf_device = false,
129         },
130
131         /* Dynamic Memory */
132         { .dev_type = HV_DM,
133           HV_DM_GUID,
134           .perf_device = false,
135         },
136
137         /* Unknown GUID */
138         { .dev_type = HV_UNKNOWN,
139           .perf_device = false,
140         },
141 };
142
143 static const struct {
144         guid_t guid;
145 } vmbus_unsupported_devs[] = {
146         { HV_AVMA1_GUID },
147         { HV_AVMA2_GUID },
148         { HV_RDV_GUID   },
149 };
150
151 /*
152  * The rescinded channel may be blocked waiting for a response from the host;
153  * take care of that.
154  */
155 static void vmbus_rescind_cleanup(struct vmbus_channel *channel)
156 {
157         struct vmbus_channel_msginfo *msginfo;
158         unsigned long flags;
159
160
161         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
162         channel->rescind = true;
163         list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
164                                 msglistentry) {
165
166                 if (msginfo->waiting_channel == channel) {
167                         complete(&msginfo->waitevent);
168                         break;
169                 }
170         }
171         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
172 }
173
174 static bool is_unsupported_vmbus_devs(const guid_t *guid)
175 {
176         int i;
177
178         for (i = 0; i < ARRAY_SIZE(vmbus_unsupported_devs); i++)
179                 if (guid_equal(guid, &vmbus_unsupported_devs[i].guid))
180                         return true;
181         return false;
182 }
183
184 static u16 hv_get_dev_type(const struct vmbus_channel *channel)
185 {
186         const guid_t *guid = &channel->offermsg.offer.if_type;
187         u16 i;
188
189         if (is_hvsock_channel(channel) || is_unsupported_vmbus_devs(guid))
190                 return HV_UNKNOWN;
191
192         for (i = HV_IDE; i < HV_UNKNOWN; i++) {
193                 if (guid_equal(guid, &vmbus_devs[i].guid))
194                         return i;
195         }
196         pr_info("Unknown GUID: %pUl\n", guid);
197         return i;
198 }
199
200 /**
201  * vmbus_prep_negotiate_resp() - Create default response for Negotiate message
202  * @icmsghdrp: Pointer to msg header structure
203  * @buf: Raw buffer channel data
204  * @fw_version: The framework versions we can support.
205  * @fw_vercnt: The size of @fw_version.
206  * @srv_version: The service versions we can support.
207  * @srv_vercnt: The size of @srv_version.
208  * @nego_fw_version: The selected framework version.
209  * @nego_srv_version: The selected service version.
210  *
211  * Note: Versions are given in decreasing order.
212  *
213  * Set up and fill in default negotiate response message.
214  * Mainly used by Hyper-V drivers.
215  */
216 bool vmbus_prep_negotiate_resp(struct icmsg_hdr *icmsghdrp,
217                                 u8 *buf, const int *fw_version, int fw_vercnt,
218                                 const int *srv_version, int srv_vercnt,
219                                 int *nego_fw_version, int *nego_srv_version)
220 {
221         int icframe_major, icframe_minor;
222         int icmsg_major, icmsg_minor;
223         int fw_major, fw_minor;
224         int srv_major, srv_minor;
225         int i, j;
226         bool found_match = false;
227         struct icmsg_negotiate *negop;
228
229         icmsghdrp->icmsgsize = 0x10;
230         negop = (struct icmsg_negotiate *)&buf[
231                 sizeof(struct vmbuspipe_hdr) +
232                 sizeof(struct icmsg_hdr)];
233
234         icframe_major = negop->icframe_vercnt;
235         icframe_minor = 0;
236
237         icmsg_major = negop->icmsg_vercnt;
238         icmsg_minor = 0;
239
240         /*
241          * Select the framework version number we will
242          * support.
243          */
244
245         for (i = 0; i < fw_vercnt; i++) {
246                 fw_major = (fw_version[i] >> 16);
247                 fw_minor = (fw_version[i] & 0xFFFF);
248
249                 for (j = 0; j < negop->icframe_vercnt; j++) {
250                         if ((negop->icversion_data[j].major == fw_major) &&
251                             (negop->icversion_data[j].minor == fw_minor)) {
252                                 icframe_major = negop->icversion_data[j].major;
253                                 icframe_minor = negop->icversion_data[j].minor;
254                                 found_match = true;
255                                 break;
256                         }
257                 }
258
259                 if (found_match)
260                         break;
261         }
262
263         if (!found_match)
264                 goto fw_error;
265
266         found_match = false;
267
268         for (i = 0; i < srv_vercnt; i++) {
269                 srv_major = (srv_version[i] >> 16);
270                 srv_minor = (srv_version[i] & 0xFFFF);
271
272                 for (j = negop->icframe_vercnt;
273                         (j < negop->icframe_vercnt + negop->icmsg_vercnt);
274                         j++) {
275
276                         if ((negop->icversion_data[j].major == srv_major) &&
277                                 (negop->icversion_data[j].minor == srv_minor)) {
278
279                                 icmsg_major = negop->icversion_data[j].major;
280                                 icmsg_minor = negop->icversion_data[j].minor;
281                                 found_match = true;
282                                 break;
283                         }
284                 }
285
286                 if (found_match)
287                         break;
288         }
289
290         /*
291          * Respond with the framework and service
292          * version numbers we can support.
293          */
294
295 fw_error:
296         if (!found_match) {
297                 negop->icframe_vercnt = 0;
298                 negop->icmsg_vercnt = 0;
299         } else {
300                 negop->icframe_vercnt = 1;
301                 negop->icmsg_vercnt = 1;
302         }
303
304         if (nego_fw_version)
305                 *nego_fw_version = (icframe_major << 16) | icframe_minor;
306
307         if (nego_srv_version)
308                 *nego_srv_version = (icmsg_major << 16) | icmsg_minor;
309
310         negop->icversion_data[0].major = icframe_major;
311         negop->icversion_data[0].minor = icframe_minor;
312         negop->icversion_data[1].major = icmsg_major;
313         negop->icversion_data[1].minor = icmsg_minor;
314         return found_match;
315 }
316
317 EXPORT_SYMBOL_GPL(vmbus_prep_negotiate_resp);
318
319 /*
320  * alloc_channel - Allocate and initialize a vmbus channel object
321  */
322 static struct vmbus_channel *alloc_channel(void)
323 {
324         struct vmbus_channel *channel;
325
326         channel = kzalloc(sizeof(*channel), GFP_ATOMIC);
327         if (!channel)
328                 return NULL;
329
330         spin_lock_init(&channel->lock);
331         init_completion(&channel->rescind_event);
332
333         INIT_LIST_HEAD(&channel->sc_list);
334         INIT_LIST_HEAD(&channel->percpu_list);
335
336         tasklet_init(&channel->callback_event,
337                      vmbus_on_event, (unsigned long)channel);
338
339         hv_ringbuffer_pre_init(channel);
340
341         return channel;
342 }
343
344 /*
345  * free_channel - Release the resources used by the vmbus channel object
346  */
347 static void free_channel(struct vmbus_channel *channel)
348 {
349         tasklet_kill(&channel->callback_event);
350         vmbus_remove_channel_attr_group(channel);
351
352         kobject_put(&channel->kobj);
353 }
354
355 static void percpu_channel_enq(void *arg)
356 {
357         struct vmbus_channel *channel = arg;
358         struct hv_per_cpu_context *hv_cpu
359                 = this_cpu_ptr(hv_context.cpu_context);
360
361         list_add_tail_rcu(&channel->percpu_list, &hv_cpu->chan_list);
362 }
363
364 static void percpu_channel_deq(void *arg)
365 {
366         struct vmbus_channel *channel = arg;
367
368         list_del_rcu(&channel->percpu_list);
369 }
370
371
372 static void vmbus_release_relid(u32 relid)
373 {
374         struct vmbus_channel_relid_released msg;
375         int ret;
376
377         memset(&msg, 0, sizeof(struct vmbus_channel_relid_released));
378         msg.child_relid = relid;
379         msg.header.msgtype = CHANNELMSG_RELID_RELEASED;
380         ret = vmbus_post_msg(&msg, sizeof(struct vmbus_channel_relid_released),
381                              true);
382
383         trace_vmbus_release_relid(&msg, ret);
384 }
385
386 void hv_process_channel_removal(struct vmbus_channel *channel)
387 {
388         struct vmbus_channel *primary_channel;
389         unsigned long flags;
390
391         BUG_ON(!mutex_is_locked(&vmbus_connection.channel_mutex));
392         BUG_ON(!channel->rescind);
393
394         if (channel->target_cpu != get_cpu()) {
395                 put_cpu();
396                 smp_call_function_single(channel->target_cpu,
397                                          percpu_channel_deq, channel, true);
398         } else {
399                 percpu_channel_deq(channel);
400                 put_cpu();
401         }
402
403         if (channel->primary_channel == NULL) {
404                 list_del(&channel->listentry);
405
406                 primary_channel = channel;
407         } else {
408                 primary_channel = channel->primary_channel;
409                 spin_lock_irqsave(&primary_channel->lock, flags);
410                 list_del(&channel->sc_list);
411                 spin_unlock_irqrestore(&primary_channel->lock, flags);
412         }
413
414         /*
415          * We need to free the bit for init_vp_index() to work in the case
416          * of sub-channel, when we reload drivers like hv_netvsc.
417          */
418         if (channel->affinity_policy == HV_LOCALIZED)
419                 cpumask_clear_cpu(channel->target_cpu,
420                                   &primary_channel->alloced_cpus_in_node);
421
422         vmbus_release_relid(channel->offermsg.child_relid);
423
424         free_channel(channel);
425 }
426
427 void vmbus_free_channels(void)
428 {
429         struct vmbus_channel *channel, *tmp;
430
431         list_for_each_entry_safe(channel, tmp, &vmbus_connection.chn_list,
432                 listentry) {
433                 /* hv_process_channel_removal() needs this */
434                 channel->rescind = true;
435
436                 vmbus_device_unregister(channel->device_obj);
437         }
438 }
439
440 /* Note: the function can run concurrently for primary/sub channels. */
441 static void vmbus_add_channel_work(struct work_struct *work)
442 {
443         struct vmbus_channel *newchannel =
444                 container_of(work, struct vmbus_channel, add_channel_work);
445         struct vmbus_channel *primary_channel = newchannel->primary_channel;
446         unsigned long flags;
447         u16 dev_type;
448         int ret;
449
450         dev_type = hv_get_dev_type(newchannel);
451
452         init_vp_index(newchannel, dev_type);
453
454         if (newchannel->target_cpu != get_cpu()) {
455                 put_cpu();
456                 smp_call_function_single(newchannel->target_cpu,
457                                          percpu_channel_enq,
458                                          newchannel, true);
459         } else {
460                 percpu_channel_enq(newchannel);
461                 put_cpu();
462         }
463
464         /*
465          * This state is used to indicate a successful open
466          * so that when we do close the channel normally, we
467          * can cleanup properly.
468          */
469         newchannel->state = CHANNEL_OPEN_STATE;
470
471         if (primary_channel != NULL) {
472                 /* newchannel is a sub-channel. */
473                 struct hv_device *dev = primary_channel->device_obj;
474
475                 if (vmbus_add_channel_kobj(dev, newchannel))
476                         goto err_deq_chan;
477
478                 if (primary_channel->sc_creation_callback != NULL)
479                         primary_channel->sc_creation_callback(newchannel);
480
481                 newchannel->probe_done = true;
482                 return;
483         }
484
485         /*
486          * Start the process of binding the primary channel to the driver
487          */
488         newchannel->device_obj = vmbus_device_create(
489                 &newchannel->offermsg.offer.if_type,
490                 &newchannel->offermsg.offer.if_instance,
491                 newchannel);
492         if (!newchannel->device_obj)
493                 goto err_deq_chan;
494
495         newchannel->device_obj->device_id = dev_type;
496         /*
497          * Add the new device to the bus. This will kick off device-driver
498          * binding which eventually invokes the device driver's AddDevice()
499          * method.
500          */
501         ret = vmbus_device_register(newchannel->device_obj);
502
503         if (ret != 0) {
504                 pr_err("unable to add child device object (relid %d)\n",
505                         newchannel->offermsg.child_relid);
506                 kfree(newchannel->device_obj);
507                 goto err_deq_chan;
508         }
509
510         newchannel->probe_done = true;
511         return;
512
513 err_deq_chan:
514         mutex_lock(&vmbus_connection.channel_mutex);
515
516         /*
517          * We need to set the flag, otherwise
518          * vmbus_onoffer_rescind() can be blocked.
519          */
520         newchannel->probe_done = true;
521
522         if (primary_channel == NULL) {
523                 list_del(&newchannel->listentry);
524         } else {
525                 spin_lock_irqsave(&primary_channel->lock, flags);
526                 list_del(&newchannel->sc_list);
527                 spin_unlock_irqrestore(&primary_channel->lock, flags);
528         }
529
530         mutex_unlock(&vmbus_connection.channel_mutex);
531
532         if (newchannel->target_cpu != get_cpu()) {
533                 put_cpu();
534                 smp_call_function_single(newchannel->target_cpu,
535                                          percpu_channel_deq,
536                                          newchannel, true);
537         } else {
538                 percpu_channel_deq(newchannel);
539                 put_cpu();
540         }
541
542         vmbus_release_relid(newchannel->offermsg.child_relid);
543
544         free_channel(newchannel);
545 }
546
547 /*
548  * vmbus_process_offer - Process the offer by creating a channel/device
549  * associated with this offer
550  */
551 static void vmbus_process_offer(struct vmbus_channel *newchannel)
552 {
553         struct vmbus_channel *channel;
554         struct workqueue_struct *wq;
555         unsigned long flags;
556         bool fnew = true;
557
558         mutex_lock(&vmbus_connection.channel_mutex);
559
560         /*
561          * Now that we have acquired the channel_mutex,
562          * we can release the potentially racing rescind thread.
563          */
564         atomic_dec(&vmbus_connection.offer_in_progress);
565
566         list_for_each_entry(channel, &vmbus_connection.chn_list, listentry) {
567                 if (guid_equal(&channel->offermsg.offer.if_type,
568                                &newchannel->offermsg.offer.if_type) &&
569                     guid_equal(&channel->offermsg.offer.if_instance,
570                                &newchannel->offermsg.offer.if_instance)) {
571                         fnew = false;
572                         break;
573                 }
574         }
575
576         if (fnew)
577                 list_add_tail(&newchannel->listentry,
578                               &vmbus_connection.chn_list);
579         else {
580                 /*
581                  * Check to see if this is a valid sub-channel.
582                  */
583                 if (newchannel->offermsg.offer.sub_channel_index == 0) {
584                         mutex_unlock(&vmbus_connection.channel_mutex);
585                         /*
586                          * Don't call free_channel(), because newchannel->kobj
587                          * is not initialized yet.
588                          */
589                         kfree(newchannel);
590                         WARN_ON_ONCE(1);
591                         return;
592                 }
593                 /*
594                  * Process the sub-channel.
595                  */
596                 newchannel->primary_channel = channel;
597                 spin_lock_irqsave(&channel->lock, flags);
598                 list_add_tail(&newchannel->sc_list, &channel->sc_list);
599                 spin_unlock_irqrestore(&channel->lock, flags);
600         }
601
602         mutex_unlock(&vmbus_connection.channel_mutex);
603
604         /*
605          * vmbus_process_offer() mustn't call channel->sc_creation_callback()
606          * directly for sub-channels, because sc_creation_callback() ->
607          * vmbus_open() may never get the host's response to the
608          * OPEN_CHANNEL message (the host may rescind a channel at any time,
609          * e.g. in the case of hot removing a NIC), and vmbus_onoffer_rescind()
610          * may not wake up the vmbus_open() as it's blocked due to a non-zero
611          * vmbus_connection.offer_in_progress, and finally we have a deadlock.
612          *
613          * The above is also true for primary channels, if the related device
614          * drivers use sync probing mode by default.
615          *
616          * And, usually the handling of primary channels and sub-channels can
617          * depend on each other, so we should offload them to different
618          * workqueues to avoid possible deadlock, e.g. in sync-probing mode,
619          * NIC1's netvsc_subchan_work() can race with NIC2's netvsc_probe() ->
620          * rtnl_lock(), and causes deadlock: the former gets the rtnl_lock
621          * and waits for all the sub-channels to appear, but the latter
622          * can't get the rtnl_lock and this blocks the handling of
623          * sub-channels.
624          */
625         INIT_WORK(&newchannel->add_channel_work, vmbus_add_channel_work);
626         wq = fnew ? vmbus_connection.handle_primary_chan_wq :
627                     vmbus_connection.handle_sub_chan_wq;
628         queue_work(wq, &newchannel->add_channel_work);
629 }
630
631 /*
632  * We use this state to statically distribute the channel interrupt load.
633  */
634 static int next_numa_node_id;
635 /*
636  * init_vp_index() accesses global variables like next_numa_node_id, and
637  * it can run concurrently for primary channels and sub-channels: see
638  * vmbus_process_offer(), so we need the lock to protect the global
639  * variables.
640  */
641 static DEFINE_SPINLOCK(bind_channel_to_cpu_lock);
642
643 /*
644  * Starting with Win8, we can statically distribute the incoming
645  * channel interrupt load by binding a channel to VCPU.
646  * We distribute the interrupt loads to one or more NUMA nodes based on
647  * the channel's affinity_policy.
648  *
649  * For pre-win8 hosts or non-performance critical channels we assign the
650  * first CPU in the first NUMA node.
651  */
652 static void init_vp_index(struct vmbus_channel *channel, u16 dev_type)
653 {
654         u32 cur_cpu;
655         bool perf_chn = vmbus_devs[dev_type].perf_device;
656         struct vmbus_channel *primary = channel->primary_channel;
657         int next_node;
658         cpumask_var_t available_mask;
659         struct cpumask *alloced_mask;
660
661         if ((vmbus_proto_version == VERSION_WS2008) ||
662             (vmbus_proto_version == VERSION_WIN7) || (!perf_chn) ||
663             !alloc_cpumask_var(&available_mask, GFP_KERNEL)) {
664                 /*
665                  * Prior to win8, all channel interrupts are
666                  * delivered on cpu 0.
667                  * Also if the channel is not a performance critical
668                  * channel, bind it to cpu 0.
669                  * In case alloc_cpumask_var() fails, bind it to cpu 0.
670                  */
671                 channel->numa_node = 0;
672                 channel->target_cpu = 0;
673                 channel->target_vp = hv_cpu_number_to_vp_number(0);
674                 return;
675         }
676
677         spin_lock(&bind_channel_to_cpu_lock);
678
679         /*
680          * Based on the channel affinity policy, we will assign the NUMA
681          * nodes.
682          */
683
684         if ((channel->affinity_policy == HV_BALANCED) || (!primary)) {
685                 while (true) {
686                         next_node = next_numa_node_id++;
687                         if (next_node == nr_node_ids) {
688                                 next_node = next_numa_node_id = 0;
689                                 continue;
690                         }
691                         if (cpumask_empty(cpumask_of_node(next_node)))
692                                 continue;
693                         break;
694                 }
695                 channel->numa_node = next_node;
696                 primary = channel;
697         }
698         alloced_mask = &hv_context.hv_numa_map[primary->numa_node];
699
700         if (cpumask_weight(alloced_mask) ==
701             cpumask_weight(cpumask_of_node(primary->numa_node))) {
702                 /*
703                  * We have cycled through all the CPUs in the node;
704                  * reset the alloced map.
705                  */
706                 cpumask_clear(alloced_mask);
707         }
708
709         cpumask_xor(available_mask, alloced_mask,
710                     cpumask_of_node(primary->numa_node));
711
712         cur_cpu = -1;
713
714         if (primary->affinity_policy == HV_LOCALIZED) {
715                 /*
716                  * Normally Hyper-V host doesn't create more subchannels
717                  * than there are VCPUs on the node but it is possible when not
718                  * all present VCPUs on the node are initialized by guest.
719                  * Clear the alloced_cpus_in_node to start over.
720                  */
721                 if (cpumask_equal(&primary->alloced_cpus_in_node,
722                                   cpumask_of_node(primary->numa_node)))
723                         cpumask_clear(&primary->alloced_cpus_in_node);
724         }
725
726         while (true) {
727                 cur_cpu = cpumask_next(cur_cpu, available_mask);
728                 if (cur_cpu >= nr_cpu_ids) {
729                         cur_cpu = -1;
730                         cpumask_copy(available_mask,
731                                      cpumask_of_node(primary->numa_node));
732                         continue;
733                 }
734
735                 if (primary->affinity_policy == HV_LOCALIZED) {
736                         /*
737                          * NOTE: in the case of sub-channel, we clear the
738                          * sub-channel related bit(s) in
739                          * primary->alloced_cpus_in_node in
740                          * hv_process_channel_removal(), so when we
741                          * reload drivers like hv_netvsc in SMP guest, here
742                          * we're able to re-allocate
743                          * bit from primary->alloced_cpus_in_node.
744                          */
745                         if (!cpumask_test_cpu(cur_cpu,
746                                               &primary->alloced_cpus_in_node)) {
747                                 cpumask_set_cpu(cur_cpu,
748                                                 &primary->alloced_cpus_in_node);
749                                 cpumask_set_cpu(cur_cpu, alloced_mask);
750                                 break;
751                         }
752                 } else {
753                         cpumask_set_cpu(cur_cpu, alloced_mask);
754                         break;
755                 }
756         }
757
758         channel->target_cpu = cur_cpu;
759         channel->target_vp = hv_cpu_number_to_vp_number(cur_cpu);
760
761         spin_unlock(&bind_channel_to_cpu_lock);
762
763         free_cpumask_var(available_mask);
764 }
765
766 static void vmbus_wait_for_unload(void)
767 {
768         int cpu;
769         void *page_addr;
770         struct hv_message *msg;
771         struct vmbus_channel_message_header *hdr;
772         u32 message_type;
773
774         /*
775          * CHANNELMSG_UNLOAD_RESPONSE is always delivered to the CPU which was
776          * used for initial contact or to CPU0 depending on host version. When
777          * we're crashing on a different CPU let's hope that IRQ handler on
778          * the cpu which receives CHANNELMSG_UNLOAD_RESPONSE is still
779          * functional and vmbus_unload_response() will complete
780          * vmbus_connection.unload_event. If not, the last thing we can do is
781          * read message pages for all CPUs directly.
782          */
783         while (1) {
784                 if (completion_done(&vmbus_connection.unload_event))
785                         break;
786
787                 for_each_online_cpu(cpu) {
788                         struct hv_per_cpu_context *hv_cpu
789                                 = per_cpu_ptr(hv_context.cpu_context, cpu);
790
791                         page_addr = hv_cpu->synic_message_page;
792                         msg = (struct hv_message *)page_addr
793                                 + VMBUS_MESSAGE_SINT;
794
795                         message_type = READ_ONCE(msg->header.message_type);
796                         if (message_type == HVMSG_NONE)
797                                 continue;
798
799                         hdr = (struct vmbus_channel_message_header *)
800                                 msg->u.payload;
801
802                         if (hdr->msgtype == CHANNELMSG_UNLOAD_RESPONSE)
803                                 complete(&vmbus_connection.unload_event);
804
805                         vmbus_signal_eom(msg, message_type);
806                 }
807
808                 mdelay(10);
809         }
810
811         /*
812          * We're crashing and already got the UNLOAD_RESPONSE, cleanup all
813          * maybe-pending messages on all CPUs to be able to receive new
814          * messages after we reconnect.
815          */
816         for_each_online_cpu(cpu) {
817                 struct hv_per_cpu_context *hv_cpu
818                         = per_cpu_ptr(hv_context.cpu_context, cpu);
819
820                 page_addr = hv_cpu->synic_message_page;
821                 msg = (struct hv_message *)page_addr + VMBUS_MESSAGE_SINT;
822                 msg->header.message_type = HVMSG_NONE;
823         }
824 }
825
826 /*
827  * vmbus_unload_response - Handler for the unload response.
828  */
829 static void vmbus_unload_response(struct vmbus_channel_message_header *hdr)
830 {
831         /*
832          * This is a global event; just wakeup the waiting thread.
833          * Once we successfully unload, we can cleanup the monitor state.
834          */
835         complete(&vmbus_connection.unload_event);
836 }
837
838 void vmbus_initiate_unload(bool crash)
839 {
840         struct vmbus_channel_message_header hdr;
841
842         /* Pre-Win2012R2 hosts don't support reconnect */
843         if (vmbus_proto_version < VERSION_WIN8_1)
844                 return;
845
846         init_completion(&vmbus_connection.unload_event);
847         memset(&hdr, 0, sizeof(struct vmbus_channel_message_header));
848         hdr.msgtype = CHANNELMSG_UNLOAD;
849         vmbus_post_msg(&hdr, sizeof(struct vmbus_channel_message_header),
850                        !crash);
851
852         /*
853          * vmbus_initiate_unload() is also called on crash and the crash can be
854          * happening in an interrupt context, where scheduling is impossible.
855          */
856         if (!crash)
857                 wait_for_completion(&vmbus_connection.unload_event);
858         else
859                 vmbus_wait_for_unload();
860 }
861
862 /*
863  * vmbus_onoffer - Handler for channel offers from vmbus in parent partition.
864  *
865  */
866 static void vmbus_onoffer(struct vmbus_channel_message_header *hdr)
867 {
868         struct vmbus_channel_offer_channel *offer;
869         struct vmbus_channel *newchannel;
870
871         offer = (struct vmbus_channel_offer_channel *)hdr;
872
873         trace_vmbus_onoffer(offer);
874
875         /* Allocate the channel object and save this offer. */
876         newchannel = alloc_channel();
877         if (!newchannel) {
878                 vmbus_release_relid(offer->child_relid);
879                 atomic_dec(&vmbus_connection.offer_in_progress);
880                 pr_err("Unable to allocate channel object\n");
881                 return;
882         }
883
884         /*
885          * Setup state for signalling the host.
886          */
887         newchannel->sig_event = VMBUS_EVENT_CONNECTION_ID;
888
889         if (vmbus_proto_version != VERSION_WS2008) {
890                 newchannel->is_dedicated_interrupt =
891                                 (offer->is_dedicated_interrupt != 0);
892                 newchannel->sig_event = offer->connection_id;
893         }
894
895         memcpy(&newchannel->offermsg, offer,
896                sizeof(struct vmbus_channel_offer_channel));
897         newchannel->monitor_grp = (u8)offer->monitorid / 32;
898         newchannel->monitor_bit = (u8)offer->monitorid % 32;
899
900         vmbus_process_offer(newchannel);
901 }
902
903 /*
904  * vmbus_onoffer_rescind - Rescind offer handler.
905  *
906  * We queue a work item to process this offer synchronously
907  */
908 static void vmbus_onoffer_rescind(struct vmbus_channel_message_header *hdr)
909 {
910         struct vmbus_channel_rescind_offer *rescind;
911         struct vmbus_channel *channel;
912         struct device *dev;
913
914         rescind = (struct vmbus_channel_rescind_offer *)hdr;
915
916         trace_vmbus_onoffer_rescind(rescind);
917
918         /*
919          * The offer msg and the corresponding rescind msg
920          * from the host are guranteed to be ordered -
921          * offer comes in first and then the rescind.
922          * Since we process these events in work elements,
923          * and with preemption, we may end up processing
924          * the events out of order. Given that we handle these
925          * work elements on the same CPU, this is possible only
926          * in the case of preemption. In any case wait here
927          * until the offer processing has moved beyond the
928          * point where the channel is discoverable.
929          */
930
931         while (atomic_read(&vmbus_connection.offer_in_progress) != 0) {
932                 /*
933                  * We wait here until any channel offer is currently
934                  * being processed.
935                  */
936                 msleep(1);
937         }
938
939         mutex_lock(&vmbus_connection.channel_mutex);
940         channel = relid2channel(rescind->child_relid);
941         mutex_unlock(&vmbus_connection.channel_mutex);
942
943         if (channel == NULL) {
944                 /*
945                  * We failed in processing the offer message;
946                  * we would have cleaned up the relid in that
947                  * failure path.
948                  */
949                 return;
950         }
951
952         /*
953          * Before setting channel->rescind in vmbus_rescind_cleanup(), we
954          * should make sure the channel callback is not running any more.
955          */
956         vmbus_reset_channel_cb(channel);
957
958         /*
959          * Now wait for offer handling to complete.
960          */
961         vmbus_rescind_cleanup(channel);
962         while (READ_ONCE(channel->probe_done) == false) {
963                 /*
964                  * We wait here until any channel offer is currently
965                  * being processed.
966                  */
967                 msleep(1);
968         }
969
970         /*
971          * At this point, the rescind handling can proceed safely.
972          */
973
974         if (channel->device_obj) {
975                 if (channel->chn_rescind_callback) {
976                         channel->chn_rescind_callback(channel);
977                         return;
978                 }
979                 /*
980                  * We will have to unregister this device from the
981                  * driver core.
982                  */
983                 dev = get_device(&channel->device_obj->device);
984                 if (dev) {
985                         vmbus_device_unregister(channel->device_obj);
986                         put_device(dev);
987                 }
988         }
989         if (channel->primary_channel != NULL) {
990                 /*
991                  * Sub-channel is being rescinded. Following is the channel
992                  * close sequence when initiated from the driveri (refer to
993                  * vmbus_close() for details):
994                  * 1. Close all sub-channels first
995                  * 2. Then close the primary channel.
996                  */
997                 mutex_lock(&vmbus_connection.channel_mutex);
998                 if (channel->state == CHANNEL_OPEN_STATE) {
999                         /*
1000                          * The channel is currently not open;
1001                          * it is safe for us to cleanup the channel.
1002                          */
1003                         hv_process_channel_removal(channel);
1004                 } else {
1005                         complete(&channel->rescind_event);
1006                 }
1007                 mutex_unlock(&vmbus_connection.channel_mutex);
1008         }
1009 }
1010
1011 void vmbus_hvsock_device_unregister(struct vmbus_channel *channel)
1012 {
1013         BUG_ON(!is_hvsock_channel(channel));
1014
1015         /* We always get a rescind msg when a connection is closed. */
1016         while (!READ_ONCE(channel->probe_done) || !READ_ONCE(channel->rescind))
1017                 msleep(1);
1018
1019         vmbus_device_unregister(channel->device_obj);
1020 }
1021 EXPORT_SYMBOL_GPL(vmbus_hvsock_device_unregister);
1022
1023
1024 /*
1025  * vmbus_onoffers_delivered -
1026  * This is invoked when all offers have been delivered.
1027  *
1028  * Nothing to do here.
1029  */
1030 static void vmbus_onoffers_delivered(
1031                         struct vmbus_channel_message_header *hdr)
1032 {
1033 }
1034
1035 /*
1036  * vmbus_onopen_result - Open result handler.
1037  *
1038  * This is invoked when we received a response to our channel open request.
1039  * Find the matching request, copy the response and signal the requesting
1040  * thread.
1041  */
1042 static void vmbus_onopen_result(struct vmbus_channel_message_header *hdr)
1043 {
1044         struct vmbus_channel_open_result *result;
1045         struct vmbus_channel_msginfo *msginfo;
1046         struct vmbus_channel_message_header *requestheader;
1047         struct vmbus_channel_open_channel *openmsg;
1048         unsigned long flags;
1049
1050         result = (struct vmbus_channel_open_result *)hdr;
1051
1052         trace_vmbus_onopen_result(result);
1053
1054         /*
1055          * Find the open msg, copy the result and signal/unblock the wait event
1056          */
1057         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1058
1059         list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
1060                                 msglistentry) {
1061                 requestheader =
1062                         (struct vmbus_channel_message_header *)msginfo->msg;
1063
1064                 if (requestheader->msgtype == CHANNELMSG_OPENCHANNEL) {
1065                         openmsg =
1066                         (struct vmbus_channel_open_channel *)msginfo->msg;
1067                         if (openmsg->child_relid == result->child_relid &&
1068                             openmsg->openid == result->openid) {
1069                                 memcpy(&msginfo->response.open_result,
1070                                        result,
1071                                        sizeof(
1072                                         struct vmbus_channel_open_result));
1073                                 complete(&msginfo->waitevent);
1074                                 break;
1075                         }
1076                 }
1077         }
1078         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1079 }
1080
1081 /*
1082  * vmbus_ongpadl_created - GPADL created handler.
1083  *
1084  * This is invoked when we received a response to our gpadl create request.
1085  * Find the matching request, copy the response and signal the requesting
1086  * thread.
1087  */
1088 static void vmbus_ongpadl_created(struct vmbus_channel_message_header *hdr)
1089 {
1090         struct vmbus_channel_gpadl_created *gpadlcreated;
1091         struct vmbus_channel_msginfo *msginfo;
1092         struct vmbus_channel_message_header *requestheader;
1093         struct vmbus_channel_gpadl_header *gpadlheader;
1094         unsigned long flags;
1095
1096         gpadlcreated = (struct vmbus_channel_gpadl_created *)hdr;
1097
1098         trace_vmbus_ongpadl_created(gpadlcreated);
1099
1100         /*
1101          * Find the establish msg, copy the result and signal/unblock the wait
1102          * event
1103          */
1104         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1105
1106         list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
1107                                 msglistentry) {
1108                 requestheader =
1109                         (struct vmbus_channel_message_header *)msginfo->msg;
1110
1111                 if (requestheader->msgtype == CHANNELMSG_GPADL_HEADER) {
1112                         gpadlheader =
1113                         (struct vmbus_channel_gpadl_header *)requestheader;
1114
1115                         if ((gpadlcreated->child_relid ==
1116                              gpadlheader->child_relid) &&
1117                             (gpadlcreated->gpadl == gpadlheader->gpadl)) {
1118                                 memcpy(&msginfo->response.gpadl_created,
1119                                        gpadlcreated,
1120                                        sizeof(
1121                                         struct vmbus_channel_gpadl_created));
1122                                 complete(&msginfo->waitevent);
1123                                 break;
1124                         }
1125                 }
1126         }
1127         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1128 }
1129
1130 /*
1131  * vmbus_ongpadl_torndown - GPADL torndown handler.
1132  *
1133  * This is invoked when we received a response to our gpadl teardown request.
1134  * Find the matching request, copy the response and signal the requesting
1135  * thread.
1136  */
1137 static void vmbus_ongpadl_torndown(
1138                         struct vmbus_channel_message_header *hdr)
1139 {
1140         struct vmbus_channel_gpadl_torndown *gpadl_torndown;
1141         struct vmbus_channel_msginfo *msginfo;
1142         struct vmbus_channel_message_header *requestheader;
1143         struct vmbus_channel_gpadl_teardown *gpadl_teardown;
1144         unsigned long flags;
1145
1146         gpadl_torndown = (struct vmbus_channel_gpadl_torndown *)hdr;
1147
1148         trace_vmbus_ongpadl_torndown(gpadl_torndown);
1149
1150         /*
1151          * Find the open msg, copy the result and signal/unblock the wait event
1152          */
1153         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1154
1155         list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
1156                                 msglistentry) {
1157                 requestheader =
1158                         (struct vmbus_channel_message_header *)msginfo->msg;
1159
1160                 if (requestheader->msgtype == CHANNELMSG_GPADL_TEARDOWN) {
1161                         gpadl_teardown =
1162                         (struct vmbus_channel_gpadl_teardown *)requestheader;
1163
1164                         if (gpadl_torndown->gpadl == gpadl_teardown->gpadl) {
1165                                 memcpy(&msginfo->response.gpadl_torndown,
1166                                        gpadl_torndown,
1167                                        sizeof(
1168                                         struct vmbus_channel_gpadl_torndown));
1169                                 complete(&msginfo->waitevent);
1170                                 break;
1171                         }
1172                 }
1173         }
1174         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1175 }
1176
1177 /*
1178  * vmbus_onversion_response - Version response handler
1179  *
1180  * This is invoked when we received a response to our initiate contact request.
1181  * Find the matching request, copy the response and signal the requesting
1182  * thread.
1183  */
1184 static void vmbus_onversion_response(
1185                 struct vmbus_channel_message_header *hdr)
1186 {
1187         struct vmbus_channel_msginfo *msginfo;
1188         struct vmbus_channel_message_header *requestheader;
1189         struct vmbus_channel_version_response *version_response;
1190         unsigned long flags;
1191
1192         version_response = (struct vmbus_channel_version_response *)hdr;
1193
1194         trace_vmbus_onversion_response(version_response);
1195
1196         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1197
1198         list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
1199                                 msglistentry) {
1200                 requestheader =
1201                         (struct vmbus_channel_message_header *)msginfo->msg;
1202
1203                 if (requestheader->msgtype ==
1204                     CHANNELMSG_INITIATE_CONTACT) {
1205                         memcpy(&msginfo->response.version_response,
1206                               version_response,
1207                               sizeof(struct vmbus_channel_version_response));
1208                         complete(&msginfo->waitevent);
1209                 }
1210         }
1211         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1212 }
1213
1214 /* Channel message dispatch table */
1215 const struct vmbus_channel_message_table_entry
1216 channel_message_table[CHANNELMSG_COUNT] = {
1217         { CHANNELMSG_INVALID,                   0, NULL },
1218         { CHANNELMSG_OFFERCHANNEL,              0, vmbus_onoffer },
1219         { CHANNELMSG_RESCIND_CHANNELOFFER,      0, vmbus_onoffer_rescind },
1220         { CHANNELMSG_REQUESTOFFERS,             0, NULL },
1221         { CHANNELMSG_ALLOFFERS_DELIVERED,       1, vmbus_onoffers_delivered },
1222         { CHANNELMSG_OPENCHANNEL,               0, NULL },
1223         { CHANNELMSG_OPENCHANNEL_RESULT,        1, vmbus_onopen_result },
1224         { CHANNELMSG_CLOSECHANNEL,              0, NULL },
1225         { CHANNELMSG_GPADL_HEADER,              0, NULL },
1226         { CHANNELMSG_GPADL_BODY,                0, NULL },
1227         { CHANNELMSG_GPADL_CREATED,             1, vmbus_ongpadl_created },
1228         { CHANNELMSG_GPADL_TEARDOWN,            0, NULL },
1229         { CHANNELMSG_GPADL_TORNDOWN,            1, vmbus_ongpadl_torndown },
1230         { CHANNELMSG_RELID_RELEASED,            0, NULL },
1231         { CHANNELMSG_INITIATE_CONTACT,          0, NULL },
1232         { CHANNELMSG_VERSION_RESPONSE,          1, vmbus_onversion_response },
1233         { CHANNELMSG_UNLOAD,                    0, NULL },
1234         { CHANNELMSG_UNLOAD_RESPONSE,           1, vmbus_unload_response },
1235         { CHANNELMSG_18,                        0, NULL },
1236         { CHANNELMSG_19,                        0, NULL },
1237         { CHANNELMSG_20,                        0, NULL },
1238         { CHANNELMSG_TL_CONNECT_REQUEST,        0, NULL },
1239 };
1240
1241 /*
1242  * vmbus_onmessage - Handler for channel protocol messages.
1243  *
1244  * This is invoked in the vmbus worker thread context.
1245  */
1246 void vmbus_onmessage(void *context)
1247 {
1248         struct hv_message *msg = context;
1249         struct vmbus_channel_message_header *hdr;
1250         int size;
1251
1252         hdr = (struct vmbus_channel_message_header *)msg->u.payload;
1253         size = msg->header.payload_size;
1254
1255         trace_vmbus_on_message(hdr);
1256
1257         if (hdr->msgtype >= CHANNELMSG_COUNT) {
1258                 pr_err("Received invalid channel message type %d size %d\n",
1259                            hdr->msgtype, size);
1260                 print_hex_dump_bytes("", DUMP_PREFIX_NONE,
1261                                      (unsigned char *)msg->u.payload, size);
1262                 return;
1263         }
1264
1265         if (channel_message_table[hdr->msgtype].message_handler)
1266                 channel_message_table[hdr->msgtype].message_handler(hdr);
1267         else
1268                 pr_err("Unhandled channel message type %d\n", hdr->msgtype);
1269 }
1270
1271 /*
1272  * vmbus_request_offers - Send a request to get all our pending offers.
1273  */
1274 int vmbus_request_offers(void)
1275 {
1276         struct vmbus_channel_message_header *msg;
1277         struct vmbus_channel_msginfo *msginfo;
1278         int ret;
1279
1280         msginfo = kmalloc(sizeof(*msginfo) +
1281                           sizeof(struct vmbus_channel_message_header),
1282                           GFP_KERNEL);
1283         if (!msginfo)
1284                 return -ENOMEM;
1285
1286         msg = (struct vmbus_channel_message_header *)msginfo->msg;
1287
1288         msg->msgtype = CHANNELMSG_REQUESTOFFERS;
1289
1290         ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_message_header),
1291                              true);
1292
1293         trace_vmbus_request_offers(ret);
1294
1295         if (ret != 0) {
1296                 pr_err("Unable to request offers - %d\n", ret);
1297
1298                 goto cleanup;
1299         }
1300
1301 cleanup:
1302         kfree(msginfo);
1303
1304         return ret;
1305 }
1306
1307 static void invoke_sc_cb(struct vmbus_channel *primary_channel)
1308 {
1309         struct list_head *cur, *tmp;
1310         struct vmbus_channel *cur_channel;
1311
1312         if (primary_channel->sc_creation_callback == NULL)
1313                 return;
1314
1315         list_for_each_safe(cur, tmp, &primary_channel->sc_list) {
1316                 cur_channel = list_entry(cur, struct vmbus_channel, sc_list);
1317
1318                 primary_channel->sc_creation_callback(cur_channel);
1319         }
1320 }
1321
1322 void vmbus_set_sc_create_callback(struct vmbus_channel *primary_channel,
1323                                 void (*sc_cr_cb)(struct vmbus_channel *new_sc))
1324 {
1325         primary_channel->sc_creation_callback = sc_cr_cb;
1326 }
1327 EXPORT_SYMBOL_GPL(vmbus_set_sc_create_callback);
1328
1329 bool vmbus_are_subchannels_present(struct vmbus_channel *primary)
1330 {
1331         bool ret;
1332
1333         ret = !list_empty(&primary->sc_list);
1334
1335         if (ret) {
1336                 /*
1337                  * Invoke the callback on sub-channel creation.
1338                  * This will present a uniform interface to the
1339                  * clients.
1340                  */
1341                 invoke_sc_cb(primary);
1342         }
1343
1344         return ret;
1345 }
1346 EXPORT_SYMBOL_GPL(vmbus_are_subchannels_present);
1347
1348 void vmbus_set_chn_rescind_callback(struct vmbus_channel *channel,
1349                 void (*chn_rescind_cb)(struct vmbus_channel *))
1350 {
1351         channel->chn_rescind_callback = chn_rescind_cb;
1352 }
1353 EXPORT_SYMBOL_GPL(vmbus_set_chn_rescind_callback);