xref: /freebsd/stand/lua/core.lua (revision 637e4ef1a6bcd8677dabd8c08916df3091be5f64)
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_acpi = false
36local default_safe_mode = false
37local default_single_user = false
38local default_verbose = false
39
40local bootenv_list = "bootenvs"
41
42local function composeLoaderCmd(cmd_name, argstr)
43	if argstr ~= nil then
44		cmd_name = cmd_name .. " " .. argstr
45	end
46	return cmd_name
47end
48
49local function recordDefaults()
50	local boot_single = loader.getenv("boot_single") or "no"
51	local boot_verbose = loader.getenv("boot_verbose") or "no"
52
53	default_acpi = core.getACPI()
54	default_single_user = boot_single:lower() ~= "no"
55	default_verbose = boot_verbose:lower() ~= "no"
56
57	core.setACPI(default_acpi)
58	core.setSingleUser(default_single_user)
59	core.setVerbose(default_verbose)
60end
61
62
63-- Globals
64-- try_include will return the loaded module on success, or false and the error
65-- message on failure.
66function try_include(module)
67	if module:sub(1, 1) ~= "/" then
68		local lua_path = loader.lua_path
69		-- XXX Temporary compat shim; this should be removed once the
70		-- loader.lua_path export has sufficiently spread.
71		if lua_path == nil then
72			lua_path = "/boot/lua"
73		end
74		module = lua_path .. "/" .. module
75		-- We only attempt to append an extension if an absolute path
76		-- wasn't specified.  This assumes that the caller either wants
77		-- to treat this like it would require() and specify just the
78		-- base filename, or they know what they're doing as they've
79		-- specified an absolute path and we shouldn't impede.
80		if module:match(".lua$") == nil then
81			module = module .. ".lua"
82		end
83	end
84	if lfs.attributes(module, "mode") ~= "file" then
85		return
86	end
87
88	return dofile(module)
89end
90
91-- Module exports
92-- Commonly appearing constants
93core.KEY_BACKSPACE	= 8
94core.KEY_ENTER		= 13
95core.KEY_DELETE		= 127
96
97-- Note that this is a decimal representation, despite the leading 0 that in
98-- other contexts (outside of Lua) may mean 'octal'
99core.KEYSTR_ESCAPE	= "\027"
100core.KEYSTR_CSI		= core.KEYSTR_ESCAPE .. "["
101core.KEYSTR_RESET	= core.KEYSTR_ESCAPE .. "c"
102
103core.MENU_RETURN	= "return"
104core.MENU_ENTRY		= "entry"
105core.MENU_SEPARATOR	= "separator"
106core.MENU_SUBMENU	= "submenu"
107core.MENU_CAROUSEL_ENTRY	= "carousel_entry"
108
109function core.setVerbose(verbose)
110	if verbose == nil then
111		verbose = not core.verbose
112	end
113
114	if verbose then
115		loader.setenv("boot_verbose", "YES")
116	else
117		loader.unsetenv("boot_verbose")
118	end
119	core.verbose = verbose
120end
121
122function core.setSingleUser(single_user)
123	if single_user == nil then
124		single_user = not core.su
125	end
126
127	if single_user then
128		loader.setenv("boot_single", "YES")
129	else
130		loader.unsetenv("boot_single")
131	end
132	core.su = single_user
133end
134
135function core.hasACPI()
136	return loader.getenv("acpi.rsdp") ~= nil
137end
138
139function core.isX86()
140	return loader.machine_arch == "i386" or loader.machine_arch == "amd64"
141end
142
143function core.getACPI()
144	if not core.hasACPI() then
145		-- x86 requires ACPI pretty much
146		return false or core.isX86()
147	end
148
149	-- Otherwise, respect disabled if it's set
150	local c = loader.getenv("hint.acpi.0.disabled")
151	return c == nil or tonumber(c) ~= 1
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(default_acpi)
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
444-- Is the menu skipped in the environment in which we've booted?
445function core.isMenuSkipped()
446	return string.lower(loader.getenv("beastie_disable") or "") == "yes"
447end
448
449-- This may be a better candidate for a 'utility' module.
450function core.deepCopyTable(tbl)
451	local new_tbl = {}
452	for k, v in pairs(tbl) do
453		if type(v) == "table" then
454			new_tbl[k] = core.deepCopyTable(v)
455		else
456			new_tbl[k] = v
457		end
458	end
459	return new_tbl
460end
461
462-- XXX This should go away if we get the table lib into shape for importing.
463-- As of now, it requires some 'os' functions, so we'll implement this in lua
464-- for our uses
465function core.popFrontTable(tbl)
466	-- Shouldn't reasonably happen
467	if #tbl == 0 then
468		return nil, nil
469	elseif #tbl == 1 then
470		return tbl[1], {}
471	end
472
473	local first_value = tbl[1]
474	local new_tbl = {}
475	-- This is not a cheap operation
476	for k, v in ipairs(tbl) do
477		if k > 1 then
478			new_tbl[k - 1] = v
479		end
480	end
481
482	return first_value, new_tbl
483end
484
485function core.getConsoleName()
486	if loader.getenv("boot_multicons") ~= nil then
487		if loader.getenv("boot_serial") ~= nil then
488			return "Dual (Serial primary)"
489		else
490			return "Dual (Video primary)"
491		end
492	else
493		if loader.getenv("boot_serial") ~= nil then
494			return "Serial"
495		else
496			return "Video"
497		end
498	end
499end
500
501function core.nextConsoleChoice()
502	if loader.getenv("boot_multicons") ~= nil then
503		if loader.getenv("boot_serial") ~= nil then
504			loader.unsetenv("boot_serial")
505		else
506			loader.unsetenv("boot_multicons")
507			loader.setenv("boot_serial", "YES")
508		end
509	else
510		if loader.getenv("boot_serial") ~= nil then
511			loader.unsetenv("boot_serial")
512		else
513			loader.setenv("boot_multicons", "YES")
514			loader.setenv("boot_serial", "YES")
515		end
516	end
517end
518
519recordDefaults()
520hook.register("config.reloaded", core.clearCachedKernels)
521return core
522