xref: /freebsd/sys/dev/xen/control/control.c (revision b0d29bc47dba79f6f38e67eabadfb4b32ffd9390)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD AND BSD-4-Clause
3  *
4  * Copyright (c) 2010 Justin T. Gibbs, Spectra Logic Corporation
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification.
13  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
14  *    substantially similar to the "NO WARRANTY" disclaimer below
15  *    ("Disclaimer") and any redistribution must be conditioned upon
16  *    including a substantially similar Disclaimer requirement for further
17  *    binary redistribution.
18  *
19  * NO WARRANTY
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
28  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
29  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGES.
31  */
32 
33 /*-
34  * PV suspend/resume support:
35  *
36  * Copyright (c) 2004 Christian Limpach.
37  * Copyright (c) 2004-2006,2008 Kip Macy
38  * All rights reserved.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *      This product includes software developed by Christian Limpach.
51  * 4. The name of the author may not be used to endorse or promote products
52  *    derived from this software without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
55  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
56  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
57  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
58  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
59  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
60  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
61  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
62  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
63  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  */
65 
66 /*-
67  * HVM suspend/resume support:
68  *
69  * Copyright (c) 2008 Citrix Systems, Inc.
70  * All rights reserved.
71  *
72  * Redistribution and use in source and binary forms, with or without
73  * modification, are permitted provided that the following conditions
74  * are met:
75  * 1. Redistributions of source code must retain the above copyright
76  *    notice, this list of conditions and the following disclaimer.
77  * 2. Redistributions in binary form must reproduce the above copyright
78  *    notice, this list of conditions and the following disclaimer in the
79  *    documentation and/or other materials provided with the distribution.
80  *
81  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
82  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
84  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
85  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
86  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
87  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
88  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
89  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
90  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
91  * SUCH DAMAGE.
92  */
93 #include <sys/cdefs.h>
94 __FBSDID("$FreeBSD$");
95 
96 /**
97  * \file control.c
98  *
99  * \brief Device driver to repond to control domain events that impact
100  *        this VM.
101  */
102 
103 #include <sys/param.h>
104 #include <sys/systm.h>
105 #include <sys/kernel.h>
106 #include <sys/malloc.h>
107 
108 #include <sys/bio.h>
109 #include <sys/bus.h>
110 #include <sys/conf.h>
111 #include <sys/disk.h>
112 #include <sys/fcntl.h>
113 #include <sys/filedesc.h>
114 #include <sys/kdb.h>
115 #include <sys/module.h>
116 #include <sys/namei.h>
117 #include <sys/proc.h>
118 #include <sys/reboot.h>
119 #include <sys/rman.h>
120 #include <sys/sched.h>
121 #include <sys/taskqueue.h>
122 #include <sys/types.h>
123 #include <sys/vnode.h>
124 #include <sys/sched.h>
125 #include <sys/smp.h>
126 #include <sys/eventhandler.h>
127 #include <sys/timetc.h>
128 
129 #include <geom/geom.h>
130 
131 #include <machine/_inttypes.h>
132 #include <machine/intr_machdep.h>
133 
134 #include <x86/apicvar.h>
135 
136 #include <vm/vm.h>
137 #include <vm/vm_extern.h>
138 #include <vm/vm_kern.h>
139 
140 #include <xen/xen-os.h>
141 #include <xen/blkif.h>
142 #include <xen/evtchn.h>
143 #include <xen/gnttab.h>
144 #include <xen/xen_intr.h>
145 
146 #include <xen/hvm.h>
147 
148 #include <xen/interface/event_channel.h>
149 #include <xen/interface/grant_table.h>
150 
151 #include <xen/xenbus/xenbusvar.h>
152 
153 bool xen_suspend_cancelled;
154 /*--------------------------- Forward Declarations --------------------------*/
155 /** Function signature for shutdown event handlers. */
156 typedef	void (xctrl_shutdown_handler_t)(void);
157 
158 static xctrl_shutdown_handler_t xctrl_poweroff;
159 static xctrl_shutdown_handler_t xctrl_reboot;
160 static xctrl_shutdown_handler_t xctrl_suspend;
161 static xctrl_shutdown_handler_t xctrl_crash;
162 
163 /*-------------------------- Private Data Structures -------------------------*/
164 /** Element type for lookup table of event name to handler. */
165 struct xctrl_shutdown_reason {
166 	const char		 *name;
167 	xctrl_shutdown_handler_t *handler;
168 };
169 
170 /** Lookup table for shutdown event name to handler. */
171 static const struct xctrl_shutdown_reason xctrl_shutdown_reasons[] = {
172 	{ "poweroff", xctrl_poweroff },
173 	{ "reboot",   xctrl_reboot   },
174 	{ "suspend",  xctrl_suspend  },
175 	{ "crash",    xctrl_crash    },
176 	{ "halt",     xctrl_poweroff },
177 };
178 
179 struct xctrl_softc {
180 	struct xs_watch    xctrl_watch;
181 };
182 
183 /*------------------------------ Event Handlers ------------------------------*/
184 static void
185 xctrl_poweroff()
186 {
187 	shutdown_nice(RB_POWEROFF|RB_HALT);
188 }
189 
190 static void
191 xctrl_reboot()
192 {
193 	shutdown_nice(0);
194 }
195 
196 static void
197 xctrl_suspend()
198 {
199 #ifdef SMP
200 	cpuset_t cpu_suspend_map;
201 #endif
202 
203 	EVENTHANDLER_INVOKE(power_suspend_early);
204 	xs_lock();
205 	stop_all_proc();
206 	xs_unlock();
207 	EVENTHANDLER_INVOKE(power_suspend);
208 
209 #ifdef EARLY_AP_STARTUP
210 	MPASS(mp_ncpus == 1 || smp_started);
211 	thread_lock(curthread);
212 	sched_bind(curthread, 0);
213 	thread_unlock(curthread);
214 #else
215 	if (smp_started) {
216 		thread_lock(curthread);
217 		sched_bind(curthread, 0);
218 		thread_unlock(curthread);
219 	}
220 #endif
221 	KASSERT((PCPU_GET(cpuid) == 0), ("Not running on CPU#0"));
222 
223 	/*
224 	 * Be sure to hold Giant across DEVICE_SUSPEND/RESUME since non-MPSAFE
225 	 * drivers need this.
226 	 */
227 	mtx_lock(&Giant);
228 	if (DEVICE_SUSPEND(root_bus) != 0) {
229 		mtx_unlock(&Giant);
230 		printf("%s: device_suspend failed\n", __func__);
231 		return;
232 	}
233 
234 #ifdef SMP
235 #ifdef EARLY_AP_STARTUP
236 	/*
237 	 * Suspend other CPUs. This prevents IPIs while we
238 	 * are resuming, and will allow us to reset per-cpu
239 	 * vcpu_info on resume.
240 	 */
241 	cpu_suspend_map = all_cpus;
242 	CPU_CLR(PCPU_GET(cpuid), &cpu_suspend_map);
243 	if (!CPU_EMPTY(&cpu_suspend_map))
244 		suspend_cpus(cpu_suspend_map);
245 #else
246 	CPU_ZERO(&cpu_suspend_map);	/* silence gcc */
247 	if (smp_started) {
248 		/*
249 		 * Suspend other CPUs. This prevents IPIs while we
250 		 * are resuming, and will allow us to reset per-cpu
251 		 * vcpu_info on resume.
252 		 */
253 		cpu_suspend_map = all_cpus;
254 		CPU_CLR(PCPU_GET(cpuid), &cpu_suspend_map);
255 		if (!CPU_EMPTY(&cpu_suspend_map))
256 			suspend_cpus(cpu_suspend_map);
257 	}
258 #endif
259 #endif
260 
261 	/*
262 	 * Prevent any races with evtchn_interrupt() handler.
263 	 */
264 	disable_intr();
265 	intr_suspend();
266 	xen_hvm_suspend();
267 
268 	xen_suspend_cancelled = !!HYPERVISOR_suspend(0);
269 
270 	if (!xen_suspend_cancelled) {
271 		xen_hvm_resume(false);
272 	}
273 	intr_resume(xen_suspend_cancelled != 0);
274 	enable_intr();
275 
276 	/*
277 	 * Reset grant table info.
278 	 */
279 	if (!xen_suspend_cancelled) {
280 		gnttab_resume(NULL);
281 	}
282 
283 #ifdef SMP
284 	if (!CPU_EMPTY(&cpu_suspend_map)) {
285 		/*
286 		 * Now that event channels have been initialized,
287 		 * resume CPUs.
288 		 */
289 		resume_cpus(cpu_suspend_map);
290 		/* Send an IPI_BITMAP in case there are pending bitmap IPIs. */
291 		lapic_ipi_vectored(IPI_BITMAP_VECTOR, APIC_IPI_DEST_ALL);
292 	}
293 #endif
294 
295 	/*
296 	 * FreeBSD really needs to add DEVICE_SUSPEND_CANCEL or
297 	 * similar.
298 	 */
299 	DEVICE_RESUME(root_bus);
300 	mtx_unlock(&Giant);
301 
302 	/*
303 	 * Warm up timecounter again and reset system clock.
304 	 */
305 	timecounter->tc_get_timecount(timecounter);
306 	timecounter->tc_get_timecount(timecounter);
307 	inittodr(time_second);
308 
309 #ifdef EARLY_AP_STARTUP
310 	thread_lock(curthread);
311 	sched_unbind(curthread);
312 	thread_unlock(curthread);
313 #else
314 	if (smp_started) {
315 		thread_lock(curthread);
316 		sched_unbind(curthread);
317 		thread_unlock(curthread);
318 	}
319 #endif
320 
321 	resume_all_proc();
322 
323 	EVENTHANDLER_INVOKE(power_resume);
324 
325 	if (bootverbose)
326 		printf("System resumed after suspension\n");
327 
328 }
329 
330 static void
331 xctrl_crash()
332 {
333 	panic("Xen directed crash");
334 }
335 
336 static void
337 xen_pv_shutdown_final(void *arg, int howto)
338 {
339 	/*
340 	 * Inform the hypervisor that shutdown is complete.
341 	 * This is not necessary in HVM domains since Xen
342 	 * emulates ACPI in that mode and FreeBSD's ACPI
343 	 * support will request this transition.
344 	 */
345 	if (howto & (RB_HALT | RB_POWEROFF))
346 		HYPERVISOR_shutdown(SHUTDOWN_poweroff);
347 	else
348 		HYPERVISOR_shutdown(SHUTDOWN_reboot);
349 }
350 
351 /*------------------------------ Event Reception -----------------------------*/
352 static void
353 xctrl_on_watch_event(struct xs_watch *watch, const char **vec, unsigned int len)
354 {
355 	const struct xctrl_shutdown_reason *reason;
356 	const struct xctrl_shutdown_reason *last_reason;
357 	char *result;
358 	int   error;
359 	int   result_len;
360 
361 	error = xs_read(XST_NIL, "control", "shutdown",
362 			&result_len, (void **)&result);
363 	if (error != 0)
364 		return;
365 
366 	/* Acknowledge the request by writing back an empty string. */
367 	error = xs_write(XST_NIL, "control", "shutdown", "");
368 	if (error != 0)
369 		printf("unable to ack shutdown request, proceeding anyway\n");
370 
371 	reason = xctrl_shutdown_reasons;
372 	last_reason = reason + nitems(xctrl_shutdown_reasons);
373 	while (reason < last_reason) {
374 
375 		if (!strcmp(result, reason->name)) {
376 			reason->handler();
377 			break;
378 		}
379 		reason++;
380 	}
381 
382 	free(result, M_XENSTORE);
383 }
384 
385 /*------------------ Private Device Attachment Functions  --------------------*/
386 /**
387  * \brief Identify instances of this device type in the system.
388  *
389  * \param driver  The driver performing this identify action.
390  * \param parent  The NewBus parent device for any devices this method adds.
391  */
392 static void
393 xctrl_identify(driver_t *driver __unused, device_t parent)
394 {
395 	/*
396 	 * A single device instance for our driver is always present
397 	 * in a system operating under Xen.
398 	 */
399 	BUS_ADD_CHILD(parent, 0, driver->name, 0);
400 }
401 
402 /**
403  * \brief Probe for the existence of the Xen Control device
404  *
405  * \param dev  NewBus device_t for this Xen control instance.
406  *
407  * \return  Always returns 0 indicating success.
408  */
409 static int
410 xctrl_probe(device_t dev)
411 {
412 	device_set_desc(dev, "Xen Control Device");
413 
414 	return (BUS_PROBE_NOWILDCARD);
415 }
416 
417 /**
418  * \brief Attach the Xen control device.
419  *
420  * \param dev  NewBus device_t for this Xen control instance.
421  *
422  * \return  On success, 0. Otherwise an errno value indicating the
423  *          type of failure.
424  */
425 static int
426 xctrl_attach(device_t dev)
427 {
428 	struct xctrl_softc *xctrl;
429 
430 	xctrl = device_get_softc(dev);
431 
432 	/* Activate watch */
433 	xctrl->xctrl_watch.node = "control/shutdown";
434 	xctrl->xctrl_watch.callback = xctrl_on_watch_event;
435 	xctrl->xctrl_watch.callback_data = (uintptr_t)xctrl;
436 	xs_register_watch(&xctrl->xctrl_watch);
437 
438 	if (xen_pv_domain())
439 		EVENTHANDLER_REGISTER(shutdown_final, xen_pv_shutdown_final, NULL,
440 		                      SHUTDOWN_PRI_LAST);
441 
442 	return (0);
443 }
444 
445 /**
446  * \brief Detach the Xen control device.
447  *
448  * \param dev  NewBus device_t for this Xen control device instance.
449  *
450  * \return  On success, 0. Otherwise an errno value indicating the
451  *          type of failure.
452  */
453 static int
454 xctrl_detach(device_t dev)
455 {
456 	struct xctrl_softc *xctrl;
457 
458 	xctrl = device_get_softc(dev);
459 
460 	/* Release watch */
461 	xs_unregister_watch(&xctrl->xctrl_watch);
462 
463 	return (0);
464 }
465 
466 /*-------------------- Private Device Attachment Data  -----------------------*/
467 static device_method_t xctrl_methods[] = {
468 	/* Device interface */
469 	DEVMETHOD(device_identify,	xctrl_identify),
470 	DEVMETHOD(device_probe,         xctrl_probe),
471 	DEVMETHOD(device_attach,        xctrl_attach),
472 	DEVMETHOD(device_detach,        xctrl_detach),
473 
474 	DEVMETHOD_END
475 };
476 
477 DEFINE_CLASS_0(xctrl, xctrl_driver, xctrl_methods, sizeof(struct xctrl_softc));
478 devclass_t xctrl_devclass;
479 
480 DRIVER_MODULE(xctrl, xenstore, xctrl_driver, xctrl_devclass, NULL, NULL);
481