xref: /freebsd/stand/lua/core.lua (revision 90aad5d3e44d137ce80d2ec257de07c7c1367bd3)
1--
2-- SPDX-License-Identifier: BSD-2-Clause
3--
4-- Copyright (c) 2015 Pedro Souza <pedrosouza@freebsd.org>
5-- Copyright (c) 2018 Kyle Evans <kevans@FreeBSD.org>
6-- All rights reserved.
7--
8-- Redistribution and use in source and binary forms, with or without
9-- modification, are permitted provided that the following conditions
10-- are met:
11-- 1. Redistributions of source code must retain the above copyright
12--    notice, this list of conditions and the following disclaimer.
13-- 2. Redistributions in binary form must reproduce the above copyright
14--    notice, this list of conditions and the following disclaimer in the
15--    documentation and/or other materials provided with the distribution.
16--
17-- THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20-- ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26-- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27-- SUCH DAMAGE.
28--
29
30local config = require("config")
31local hook = require("hook")
32
33local core = {}
34
35local default_safe_mode = false
36local default_single_user = false
37local default_verbose = false
38
39local bootenv_list = "bootenvs"
40
41local function composeLoaderCmd(cmd_name, argstr)
42	if argstr ~= nil then
43		cmd_name = cmd_name .. " " .. argstr
44	end
45	return cmd_name
46end
47
48local function recordDefaults()
49	-- On i386, hint.acpi.0.rsdp will be set before we're loaded. On !i386,
50	-- it will generally be set upon execution of the kernel. Because of
51	-- this, we can't (or don't really want to) detect/disable ACPI on !i386
52	-- reliably. Just set it enabled if we detect it and leave well enough
53	-- alone if we don't.
54	local boot_acpi = core.isSystem386() and core.getACPIPresent(false)
55	local boot_single = loader.getenv("boot_single") or "no"
56	local boot_verbose = loader.getenv("boot_verbose") or "no"
57	default_single_user = boot_single:lower() ~= "no"
58	default_verbose = boot_verbose:lower() ~= "no"
59
60	if boot_acpi then
61		core.setACPI(true)
62	end
63	core.setSingleUser(default_single_user)
64	core.setVerbose(default_verbose)
65end
66
67
68-- Globals
69-- try_include will return the loaded module on success, or false and the error
70-- message on failure.
71function try_include(module)
72	if module:sub(1, 1) ~= "/" then
73		local lua_path = loader.lua_path
74		-- XXX Temporary compat shim; this should be removed once the
75		-- loader.lua_path export has sufficiently spread.
76		if lua_path == nil then
77			lua_path = "/boot/lua"
78		end
79		module = lua_path .. "/" .. module
80		-- We only attempt to append an extension if an absolute path
81		-- wasn't specified.  This assumes that the caller either wants
82		-- to treat this like it would require() and specify just the
83		-- base filename, or they know what they're doing as they've
84		-- specified an absolute path and we shouldn't impede.
85		if module:match(".lua$") == nil then
86			module = module .. ".lua"
87		end
88	end
89	if lfs.attributes(module, "mode") ~= "file" then
90		return
91	end
92
93	return dofile(module)
94end
95
96-- Module exports
97-- Commonly appearing constants
98core.KEY_BACKSPACE	= 8
99core.KEY_ENTER		= 13
100core.KEY_DELETE		= 127
101
102-- Note that this is a decimal representation, despite the leading 0 that in
103-- other contexts (outside of Lua) may mean 'octal'
104core.KEYSTR_ESCAPE	= "\027"
105core.KEYSTR_CSI		= core.KEYSTR_ESCAPE .. "["
106core.KEYSTR_RESET	= core.KEYSTR_ESCAPE .. "c"
107
108core.MENU_RETURN	= "return"
109core.MENU_ENTRY		= "entry"
110core.MENU_SEPARATOR	= "separator"
111core.MENU_SUBMENU	= "submenu"
112core.MENU_CAROUSEL_ENTRY	= "carousel_entry"
113
114function core.setVerbose(verbose)
115	if verbose == nil then
116		verbose = not core.verbose
117	end
118
119	if verbose then
120		loader.setenv("boot_verbose", "YES")
121	else
122		loader.unsetenv("boot_verbose")
123	end
124	core.verbose = verbose
125end
126
127function core.setSingleUser(single_user)
128	if single_user == nil then
129		single_user = not core.su
130	end
131
132	if single_user then
133		loader.setenv("boot_single", "YES")
134	else
135		loader.unsetenv("boot_single")
136	end
137	core.su = single_user
138end
139
140function core.getACPIPresent(checking_system_defaults)
141	local c = loader.getenv("hint.acpi.0.rsdp")
142
143	if c ~= nil then
144		if checking_system_defaults then
145			return true
146		end
147		-- Otherwise, respect disabled if it's set
148		c = loader.getenv("hint.acpi.0.disabled")
149		return c == nil or tonumber(c) ~= 1
150	end
151	return false
152end
153
154function core.setACPI(acpi)
155	if acpi == nil then
156		acpi = not core.acpi
157	end
158
159	if acpi then
160		loader.setenv("acpi_load", "YES")
161		loader.setenv("hint.acpi.0.disabled", "0")
162		loader.unsetenv("loader.acpi_disabled_by_user")
163	else
164		loader.unsetenv("acpi_load")
165		loader.setenv("hint.acpi.0.disabled", "1")
166		loader.setenv("loader.acpi_disabled_by_user", "1")
167	end
168	core.acpi = acpi
169end
170
171function core.setSafeMode(safe_mode)
172	if safe_mode == nil then
173		safe_mode = not core.sm
174	end
175	if safe_mode then
176		loader.setenv("kern.smp.disabled", "1")
177		loader.setenv("hw.ata.ata_dma", "0")
178		loader.setenv("hw.ata.atapi_dma", "0")
179		loader.setenv("hw.ata.wc", "0")
180		loader.setenv("hw.eisa_slots", "0")
181		loader.setenv("kern.eventtimer.periodic", "1")
182		loader.setenv("kern.geom.part.check_integrity", "0")
183	else
184		loader.unsetenv("kern.smp.disabled")
185		loader.unsetenv("hw.ata.ata_dma")
186		loader.unsetenv("hw.ata.atapi_dma")
187		loader.unsetenv("hw.ata.wc")
188		loader.unsetenv("hw.eisa_slots")
189		loader.unsetenv("kern.eventtimer.periodic")
190		loader.unsetenv("kern.geom.part.check_integrity")
191	end
192	core.sm = safe_mode
193end
194
195function core.clearCachedKernels()
196	-- Clear the kernel cache on config changes, autodetect might have
197	-- changed or if we've switched boot environments then we could have
198	-- a new kernel set.
199	core.cached_kernels = nil
200end
201
202function core.kernelList()
203	if core.cached_kernels ~= nil then
204		return core.cached_kernels
205	end
206
207	local k = loader.getenv("kernel")
208	local v = loader.getenv("kernels")
209	local autodetect = loader.getenv("kernels_autodetect") or ""
210
211	local kernels = {}
212	local unique = {}
213	local i = 0
214	if k ~= nil then
215		i = i + 1
216		kernels[i] = k
217		unique[k] = true
218	end
219
220	if v ~= nil then
221		for n in v:gmatch("([^;, ]+)[;, ]?") do
222			if unique[n] == nil then
223				i = i + 1
224				kernels[i] = n
225				unique[n] = true
226			end
227		end
228	end
229
230	-- Do not attempt to autodetect if underlying filesystem
231	-- do not support directory listing (e.g. tftp, http)
232	if not lfs.attributes("/boot", "mode") then
233		autodetect = "no"
234		loader.setenv("kernels_autodetect", "NO")
235	end
236
237	-- Base whether we autodetect kernels or not on a loader.conf(5)
238	-- setting, kernels_autodetect. If it's set to 'yes', we'll add
239	-- any kernels we detect based on the criteria described.
240	if autodetect:lower() ~= "yes" then
241		core.cached_kernels = kernels
242		return core.cached_kernels
243	end
244
245	-- Automatically detect other bootable kernel directories using a
246	-- heuristic.  Any directory in /boot that contains an ordinary file
247	-- named "kernel" is considered eligible.
248	for file, ftype in lfs.dir("/boot") do
249		local fname = "/boot/" .. file
250
251		if file == "." or file == ".." then
252			goto continue
253		end
254
255		if ftype then
256			if ftype ~= lfs.DT_DIR then
257				goto continue
258			end
259		elseif lfs.attributes(fname, "mode") ~= "directory" then
260			goto continue
261		end
262
263		if lfs.attributes(fname .. "/kernel", "mode") ~= "file" then
264			goto continue
265		end
266
267		if unique[file] == nil then
268			i = i + 1
269			kernels[i] = file
270			unique[file] = true
271		end
272
273		::continue::
274	end
275	core.cached_kernels = kernels
276	return core.cached_kernels
277end
278
279function core.bootenvDefault()
280	return loader.getenv("zfs_be_active")
281end
282
283function core.bootenvList()
284	local bootenv_count = tonumber(loader.getenv(bootenv_list .. "_count"))
285	local bootenvs = {}
286	local curenv
287	local envcount = 0
288	local unique = {}
289
290	if bootenv_count == nil or bootenv_count <= 0 then
291		return bootenvs
292	end
293
294	-- Currently selected bootenv is always first/default
295	-- On the rewinded list the bootenv may not exists
296	if core.isRewinded() then
297		curenv = core.bootenvDefaultRewinded()
298	else
299		curenv = core.bootenvDefault()
300	end
301	if curenv ~= nil then
302		envcount = envcount + 1
303		bootenvs[envcount] = curenv
304		unique[curenv] = true
305	end
306
307	for curenv_idx = 0, bootenv_count - 1 do
308		curenv = loader.getenv(bootenv_list .. "[" .. curenv_idx .. "]")
309		if curenv ~= nil and unique[curenv] == nil then
310			envcount = envcount + 1
311			bootenvs[envcount] = curenv
312			unique[curenv] = true
313		end
314	end
315	return bootenvs
316end
317
318function core.isCheckpointed()
319	return loader.getenv("zpool_checkpoint") ~= nil
320end
321
322function core.bootenvDefaultRewinded()
323	local defname =  "zfs:!" .. string.sub(core.bootenvDefault(), 5)
324	local bootenv_count = tonumber("bootenvs_check_count")
325
326	if bootenv_count == nil or bootenv_count <= 0 then
327		return defname
328	end
329
330	for curenv_idx = 0, bootenv_count - 1 do
331		local curenv = loader.getenv("bootenvs_check[" .. curenv_idx .. "]")
332		if curenv == defname then
333			return defname
334		end
335	end
336
337	return loader.getenv("bootenvs_check[0]")
338end
339
340function core.isRewinded()
341	return bootenv_list == "bootenvs_check"
342end
343
344function core.changeRewindCheckpoint()
345	if core.isRewinded() then
346		bootenv_list = "bootenvs"
347	else
348		bootenv_list = "bootenvs_check"
349	end
350end
351
352function core.loadEntropy()
353	if core.isUEFIBoot() then
354		if (loader.getenv("entropy_efi_seed") or "no"):lower() == "yes" then
355			loader.perform("efi-seed-entropy")
356		end
357	end
358end
359
360function core.setDefaults()
361	core.setACPI(core.getACPIPresent(true))
362	core.setSafeMode(default_safe_mode)
363	core.setSingleUser(default_single_user)
364	core.setVerbose(default_verbose)
365end
366
367function core.autoboot(argstr)
368	-- loadelf() only if we've not already loaded a kernel
369	if loader.getenv("kernelname") == nil then
370		config.loadelf()
371	end
372	core.loadEntropy()
373	loader.perform(composeLoaderCmd("autoboot", argstr))
374end
375
376function core.boot(argstr)
377	-- loadelf() only if we've not already loaded a kernel
378	if loader.getenv("kernelname") == nil then
379		config.loadelf()
380	end
381	core.loadEntropy()
382	loader.perform(composeLoaderCmd("boot", argstr))
383end
384
385function core.isSingleUserBoot()
386	local single_user = loader.getenv("boot_single")
387	return single_user ~= nil and single_user:lower() == "yes"
388end
389
390function core.isUEFIBoot()
391	local efiver = loader.getenv("efi-version")
392
393	return efiver ~= nil
394end
395
396function core.isZFSBoot()
397	local c = loader.getenv("currdev")
398
399	if c ~= nil then
400		return c:match("^zfs:") ~= nil
401	end
402	return false
403end
404
405function core.isFramebufferConsole()
406	local c = loader.getenv("console")
407	if c ~= nil then
408		if c:find("efi") == nil and c:find("vidconsole") == nil then
409			return false
410		end
411		if loader.getenv("screen.depth") ~= nil then
412			return true
413		end
414	end
415	return false
416end
417
418function core.isSerialConsole()
419	local c = loader.getenv("console")
420	if c ~= nil then
421		-- serial console is comconsole, but also userboot.
422		-- userboot is there, because we have no way to know
423		-- if the user terminal can draw unicode box chars or not.
424		if c:find("comconsole") ~= nil or c:find("userboot") ~= nil then
425			return true
426		end
427	end
428	return false
429end
430
431function core.isSerialBoot()
432	local s = loader.getenv("boot_serial")
433	if s ~= nil then
434		return true
435	end
436
437	local m = loader.getenv("boot_multicons")
438	if m ~= nil then
439		return true
440	end
441	return false
442end
443
444function core.isSystem386()
445	return loader.machine_arch == "i386"
446end
447
448-- Is the menu skipped in the environment in which we've booted?
449function core.isMenuSkipped()
450	return string.lower(loader.getenv("beastie_disable") or "") == "yes"
451end
452
453-- This may be a better candidate for a 'utility' module.
454function core.deepCopyTable(tbl)
455	local new_tbl = {}
456	for k, v in pairs(tbl) do
457		if type(v) == "table" then
458			new_tbl[k] = core.deepCopyTable(v)
459		else
460			new_tbl[k] = v
461		end
462	end
463	return new_tbl
464end
465
466-- XXX This should go away if we get the table lib into shape for importing.
467-- As of now, it requires some 'os' functions, so we'll implement this in lua
468-- for our uses
469function core.popFrontTable(tbl)
470	-- Shouldn't reasonably happen
471	if #tbl == 0 then
472		return nil, nil
473	elseif #tbl == 1 then
474		return tbl[1], {}
475	end
476
477	local first_value = tbl[1]
478	local new_tbl = {}
479	-- This is not a cheap operation
480	for k, v in ipairs(tbl) do
481		if k > 1 then
482			new_tbl[k - 1] = v
483		end
484	end
485
486	return first_value, new_tbl
487end
488
489function core.getConsoleName()
490	if loader.getenv("boot_multicons") ~= nil then
491		if loader.getenv("boot_serial") ~= nil then
492			return "Dual (Serial primary)"
493		else
494			return "Dual (Video primary)"
495		end
496	else
497		if loader.getenv("boot_serial") ~= nil then
498			return "Serial"
499		else
500			return "Video"
501		end
502	end
503end
504
505function core.nextConsoleChoice()
506	if loader.getenv("boot_multicons") ~= nil then
507		if loader.getenv("boot_serial") ~= nil then
508			loader.unsetenv("boot_serial")
509		else
510			loader.unsetenv("boot_multicons")
511			loader.setenv("boot_serial", "YES")
512		end
513	else
514		if loader.getenv("boot_serial") ~= nil then
515			loader.unsetenv("boot_serial")
516		else
517			loader.setenv("boot_multicons", "YES")
518			loader.setenv("boot_serial", "YES")
519		end
520	end
521end
522
523recordDefaults()
524hook.register("config.reloaded", core.clearCachedKernels)
525return core
526