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