xref: /freebsd/stand/lua/core.lua (revision a500341916bd89c46a42166078decb5699f7d518)
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$
30--
31
32local config = require("config")
33local hook = require("hook")
34
35local core = {}
36
37local function composeLoaderCmd(cmd_name, argstr)
38	if argstr ~= nil then
39		cmd_name = cmd_name .. " " .. argstr
40	end
41	return cmd_name
42end
43
44-- Globals
45-- try_include will return the loaded module on success, or nil on failure.
46-- A message will also be printed on failure, with one exception: non-verbose
47-- loading will suppress 'module not found' errors.
48function try_include(module)
49	local status, ret = pcall(require, module)
50	-- ret is the module if we succeeded.
51	if status then
52		return ret
53	end
54	-- Otherwise, ret is just a message; filter out ENOENT unless we're
55	-- doing a verbose load. As a consequence, try_include prior to loading
56	-- configuration will not display 'module not found'. All other errors
57	-- in loading will be printed.
58	if config.verbose or ret:match("^module .+ not found") == nil then
59		error(ret, 2)
60	end
61	return nil
62end
63
64-- Module exports
65-- Commonly appearing constants
66core.KEY_BACKSPACE	= 8
67core.KEY_ENTER		= 13
68core.KEY_DELETE		= 127
69
70-- Note that this is a decimal representation, despite the leading 0 that in
71-- other contexts (outside of Lua) may mean 'octal'
72core.KEYSTR_ESCAPE	= "\027"
73core.KEYSTR_CSI		= core.KEYSTR_ESCAPE .. "["
74
75core.MENU_RETURN	= "return"
76core.MENU_ENTRY		= "entry"
77core.MENU_SEPARATOR	= "separator"
78core.MENU_SUBMENU	= "submenu"
79core.MENU_CAROUSEL_ENTRY	= "carousel_entry"
80
81function core.setVerbose(verbose)
82	if verbose == nil then
83		verbose = not core.verbose
84	end
85
86	if verbose then
87		loader.setenv("boot_verbose", "YES")
88	else
89		loader.unsetenv("boot_verbose")
90	end
91	core.verbose = verbose
92end
93
94function core.setSingleUser(single_user)
95	if single_user == nil then
96		single_user = not core.su
97	end
98
99	if single_user then
100		loader.setenv("boot_single", "YES")
101	else
102		loader.unsetenv("boot_single")
103	end
104	core.su = single_user
105end
106
107function core.getACPIPresent(checking_system_defaults)
108	local c = loader.getenv("hint.acpi.0.rsdp")
109
110	if c ~= nil then
111		if checking_system_defaults then
112			return true
113		end
114		-- Otherwise, respect disabled if it's set
115		c = loader.getenv("hint.acpi.0.disabled")
116		return c == nil or tonumber(c) ~= 1
117	end
118	return false
119end
120
121function core.setACPI(acpi)
122	if acpi == nil then
123		acpi = not core.acpi
124	end
125
126	if acpi then
127		loader.setenv("acpi_load", "YES")
128		loader.setenv("hint.acpi.0.disabled", "0")
129		loader.unsetenv("loader.acpi_disabled_by_user")
130	else
131		loader.unsetenv("acpi_load")
132		loader.setenv("hint.acpi.0.disabled", "1")
133		loader.setenv("loader.acpi_disabled_by_user", "1")
134	end
135	core.acpi = acpi
136end
137
138function core.setSafeMode(safe_mode)
139	if safe_mode == nil then
140		safe_mode = not core.sm
141	end
142	if safe_mode then
143		loader.setenv("kern.smp.disabled", "1")
144		loader.setenv("hw.ata.ata_dma", "0")
145		loader.setenv("hw.ata.atapi_dma", "0")
146		loader.setenv("hw.ata.wc", "0")
147		loader.setenv("hw.eisa_slots", "0")
148		loader.setenv("kern.eventtimer.periodic", "1")
149		loader.setenv("kern.geom.part.check_integrity", "0")
150	else
151		loader.unsetenv("kern.smp.disabled")
152		loader.unsetenv("hw.ata.ata_dma")
153		loader.unsetenv("hw.ata.atapi_dma")
154		loader.unsetenv("hw.ata.wc")
155		loader.unsetenv("hw.eisa_slots")
156		loader.unsetenv("kern.eventtimer.periodic")
157		loader.unsetenv("kern.geom.part.check_integrity")
158	end
159	core.sm = safe_mode
160end
161
162function core.clearCachedKernels()
163	-- Clear the kernel cache on config changes, autodetect might have
164	-- changed or if we've switched boot environments then we could have
165	-- a new kernel set.
166	core.cached_kernels = nil
167end
168
169function core.kernelList()
170	if core.cached_kernels ~= nil then
171		return core.cached_kernels
172	end
173
174	local k = loader.getenv("kernel")
175	local v = loader.getenv("kernels")
176	local autodetect = loader.getenv("kernels_autodetect") or ""
177
178	local kernels = {}
179	local unique = {}
180	local i = 0
181	if k ~= nil then
182		i = i + 1
183		kernels[i] = k
184		unique[k] = true
185	end
186
187	if v ~= nil then
188		for n in v:gmatch("([^;, ]+)[;, ]?") do
189			if unique[n] == nil then
190				i = i + 1
191				kernels[i] = n
192				unique[n] = true
193			end
194		end
195	end
196
197	-- Base whether we autodetect kernels or not on a loader.conf(5)
198	-- setting, kernels_autodetect. If it's set to 'yes', we'll add
199	-- any kernels we detect based on the criteria described.
200	if autodetect:lower() ~= "yes" then
201		core.cached_kernels = kernels
202		return core.cached_kernels
203	end
204
205	-- Automatically detect other bootable kernel directories using a
206	-- heuristic.  Any directory in /boot that contains an ordinary file
207	-- named "kernel" is considered eligible.
208	for file in lfs.dir("/boot") do
209		local fname = "/boot/" .. file
210
211		if file == "." or file == ".." then
212			goto continue
213		end
214
215		if lfs.attributes(fname, "mode") ~= "directory" then
216			goto continue
217		end
218
219		if lfs.attributes(fname .. "/kernel", "mode") ~= "file" then
220			goto continue
221		end
222
223		if unique[file] == nil then
224			i = i + 1
225			kernels[i] = file
226			unique[file] = true
227		end
228
229		::continue::
230	end
231	core.cached_kernels = kernels
232	return core.cached_kernels
233end
234
235function core.bootenvDefault()
236	return loader.getenv("zfs_be_active")
237end
238
239function core.bootenvList()
240	local bootenv_count = tonumber(loader.getenv("bootenvs_count"))
241	local bootenvs = {}
242	local curenv
243	local envcount = 0
244	local unique = {}
245
246	if bootenv_count == nil or bootenv_count <= 0 then
247		return bootenvs
248	end
249
250	-- Currently selected bootenv is always first/default
251	curenv = core.bootenvDefault()
252	if curenv ~= nil then
253		envcount = envcount + 1
254		bootenvs[envcount] = curenv
255		unique[curenv] = true
256	end
257
258	for curenv_idx = 0, bootenv_count - 1 do
259		curenv = loader.getenv("bootenvs[" .. curenv_idx .. "]")
260		if curenv ~= nil and unique[curenv] == nil then
261			envcount = envcount + 1
262			bootenvs[envcount] = curenv
263			unique[curenv] = true
264		end
265	end
266	return bootenvs
267end
268
269function core.setDefaults()
270	core.setACPI(core.getACPIPresent(true))
271	core.setSafeMode(false)
272	core.setSingleUser(false)
273	core.setVerbose(false)
274end
275
276function core.autoboot(argstr)
277	-- loadelf() only if we've not already loaded a kernel
278	if loader.getenv("kernelname") == nil then
279		config.loadelf()
280	end
281	loader.perform(composeLoaderCmd("autoboot", argstr))
282end
283
284function core.boot(argstr)
285	-- loadelf() only if we've not already loaded a kernel
286	if loader.getenv("kernelname") == nil then
287		config.loadelf()
288	end
289	loader.perform(composeLoaderCmd("boot", argstr))
290end
291
292function core.isSingleUserBoot()
293	local single_user = loader.getenv("boot_single")
294	return single_user ~= nil and single_user:lower() == "yes"
295end
296
297function core.isUEFIBoot()
298	local efiver = loader.getenv("efi-version")
299
300	return efiver ~= nil
301end
302
303function core.isZFSBoot()
304	local c = loader.getenv("currdev")
305
306	if c ~= nil then
307		return c:match("^zfs:") ~= nil
308	end
309	return false
310end
311
312function core.isSerialBoot()
313	local s = loader.getenv("boot_serial")
314	if s ~= nil then
315		return true
316	end
317
318	local m = loader.getenv("boot_multicons")
319	if m ~= nil then
320		return true
321	end
322	return false
323end
324
325function core.isSystem386()
326	return loader.machine_arch == "i386"
327end
328
329-- Is the menu skipped in the environment in which we've booted?
330function core.isMenuSkipped()
331	return string.lower(loader.getenv("beastie_disable") or "") == "yes"
332end
333
334-- This may be a better candidate for a 'utility' module.
335function core.deepCopyTable(tbl)
336	local new_tbl = {}
337	for k, v in pairs(tbl) do
338		if type(v) == "table" then
339			new_tbl[k] = core.deepCopyTable(v)
340		else
341			new_tbl[k] = v
342		end
343	end
344	return new_tbl
345end
346
347-- XXX This should go away if we get the table lib into shape for importing.
348-- As of now, it requires some 'os' functions, so we'll implement this in lua
349-- for our uses
350function core.popFrontTable(tbl)
351	-- Shouldn't reasonably happen
352	if #tbl == 0 then
353		return nil, nil
354	elseif #tbl == 1 then
355		return tbl[1], {}
356	end
357
358	local first_value = tbl[1]
359	local new_tbl = {}
360	-- This is not a cheap operation
361	for k, v in ipairs(tbl) do
362		if k > 1 then
363			new_tbl[k - 1] = v
364		end
365	end
366
367	return first_value, new_tbl
368end
369
370-- On i386, hint.acpi.0.rsdp will be set before we're loaded. On !i386, it will
371-- generally be set upon execution of the kernel. Because of this, we can't (or
372-- don't really want to) detect/disable ACPI on !i386 reliably. Just set it
373-- enabled if we detect it and leave well enough alone if we don't.
374if core.isSystem386() and core.getACPIPresent(false) then
375	core.setACPI(true)
376end
377
378hook.register("config.reloaded", core.clearCachedKernels)
379return core
380