1--
2-- SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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-- $FreeBSD: stable/11/stand/lua/core.lua 360599 2020-05-03 04:03:05Z kevans $
30--
31
32local config = require("config")
33local hook = require("hook")
34
35local core = {}
36
37local default_safe_mode = false
38local default_single_user = false
39local default_verbose = false
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	-- Base whether we autodetect kernels or not on a loader.conf(5)
231	-- setting, kernels_autodetect. If it's set to 'yes', we'll add
232	-- any kernels we detect based on the criteria described.
233	if autodetect:lower() ~= "yes" then
234		core.cached_kernels = kernels
235		return core.cached_kernels
236	end
237
238	-- Automatically detect other bootable kernel directories using a
239	-- heuristic.  Any directory in /boot that contains an ordinary file
240	-- named "kernel" is considered eligible.
241	for file in lfs.dir("/boot") do
242		local fname = "/boot/" .. file
243
244		if file == "." or file == ".." then
245			goto continue
246		end
247
248		if lfs.attributes(fname, "mode") ~= "directory" then
249			goto continue
250		end
251
252		if lfs.attributes(fname .. "/kernel", "mode") ~= "file" then
253			goto continue
254		end
255
256		if unique[file] == nil then
257			i = i + 1
258			kernels[i] = file
259			unique[file] = true
260		end
261
262		::continue::
263	end
264	core.cached_kernels = kernels
265	return core.cached_kernels
266end
267
268function core.bootenvDefault()
269	return loader.getenv("zfs_be_active")
270end
271
272function core.bootenvList()
273	local bootenv_count = tonumber(loader.getenv("bootenvs_count"))
274	local bootenvs = {}
275	local curenv
276	local envcount = 0
277	local unique = {}
278
279	if bootenv_count == nil or bootenv_count <= 0 then
280		return bootenvs
281	end
282
283	-- Currently selected bootenv is always first/default
284	curenv = core.bootenvDefault()
285	if curenv ~= nil then
286		envcount = envcount + 1
287		bootenvs[envcount] = curenv
288		unique[curenv] = true
289	end
290
291	for curenv_idx = 0, bootenv_count - 1 do
292		curenv = loader.getenv("bootenvs[" .. curenv_idx .. "]")
293		if curenv ~= nil and unique[curenv] == nil then
294			envcount = envcount + 1
295			bootenvs[envcount] = curenv
296			unique[curenv] = true
297		end
298	end
299	return bootenvs
300end
301
302function core.setDefaults()
303	core.setACPI(core.getACPIPresent(true))
304	core.setSafeMode(default_safe_mode)
305	core.setSingleUser(default_single_user)
306	core.setVerbose(default_verbose)
307end
308
309function core.autoboot(argstr)
310	-- loadelf() only if we've not already loaded a kernel
311	if loader.getenv("kernelname") == nil then
312		config.loadelf()
313	end
314	loader.perform(composeLoaderCmd("autoboot", argstr))
315end
316
317function core.boot(argstr)
318	-- loadelf() only if we've not already loaded a kernel
319	if loader.getenv("kernelname") == nil then
320		config.loadelf()
321	end
322	loader.perform(composeLoaderCmd("boot", argstr))
323end
324
325function core.isSingleUserBoot()
326	local single_user = loader.getenv("boot_single")
327	return single_user ~= nil and single_user:lower() == "yes"
328end
329
330function core.isZFSBoot()
331	local c = loader.getenv("currdev")
332
333	if c ~= nil then
334		return c:match("^zfs:") ~= nil
335	end
336	return false
337end
338
339function core.isSerialConsole()
340	local c = loader.getenv("console")
341	if c ~= nil then
342		if c:find("comconsole") ~= nil then
343			return true
344		end
345	end
346	return false
347end
348
349function core.isSerialBoot()
350	local s = loader.getenv("boot_serial")
351	if s ~= nil then
352		return true
353	end
354
355	local m = loader.getenv("boot_multicons")
356	if m ~= nil then
357		return true
358	end
359	return false
360end
361
362function core.isSystem386()
363	return loader.machine_arch == "i386"
364end
365
366-- Is the menu skipped in the environment in which we've booted?
367function core.isMenuSkipped()
368	return string.lower(loader.getenv("beastie_disable") or "") == "yes"
369end
370
371-- This may be a better candidate for a 'utility' module.
372function core.deepCopyTable(tbl)
373	local new_tbl = {}
374	for k, v in pairs(tbl) do
375		if type(v) == "table" then
376			new_tbl[k] = core.deepCopyTable(v)
377		else
378			new_tbl[k] = v
379		end
380	end
381	return new_tbl
382end
383
384-- XXX This should go away if we get the table lib into shape for importing.
385-- As of now, it requires some 'os' functions, so we'll implement this in lua
386-- for our uses
387function core.popFrontTable(tbl)
388	-- Shouldn't reasonably happen
389	if #tbl == 0 then
390		return nil, nil
391	elseif #tbl == 1 then
392		return tbl[1], {}
393	end
394
395	local first_value = tbl[1]
396	local new_tbl = {}
397	-- This is not a cheap operation
398	for k, v in ipairs(tbl) do
399		if k > 1 then
400			new_tbl[k - 1] = v
401		end
402	end
403
404	return first_value, new_tbl
405end
406
407recordDefaults()
408hook.register("config.reloaded", core.clearCachedKernels)
409return core
410