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