xref: /openbmc/hiomapd/vpnor/table.cpp (revision 82077511)
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright (C) 2018 IBM Corp.
3 #include "config.h"
4 
5 extern "C" {
6 #include "backend.h"
7 #include "common.h"
8 #include "mboxd.h"
9 }
10 
11 #include "vpnor/table.hpp"
12 #include "xyz/openbmc_project/Common/error.hpp"
13 
14 #include <endian.h>
15 #include <syslog.h>
16 
17 #include <algorithm>
18 #include <fstream>
19 #include <phosphor-logging/elog-errors.hpp>
20 #include <regex>
21 
22 namespace openpower
23 {
24 namespace virtual_pnor
25 {
26 
27 using namespace phosphor::logging;
28 using namespace sdbusplus::xyz::openbmc_project::Common::Error;
29 
30 namespace partition
31 {
32 
Table(const struct backend * be)33 Table::Table(const struct backend* be) :
34     szBytes(sizeof(pnor_partition_table)), numParts(0),
35     blockSize(1 << be->erase_size_shift), pnorSize(be->flash_size)
36 {
37     preparePartitions((const struct vpnor_data*)be->priv);
38     prepareHeader();
39     hostTbl = endianFixup(tbl);
40 }
41 
prepareHeader()42 void Table::prepareHeader()
43 {
44     decltype(auto) table = getNativeTable();
45     table.data.magic = PARTITION_HEADER_MAGIC;
46     table.data.version = PARTITION_VERSION_1;
47     table.data.size = blocks();
48     table.data.entry_size = sizeof(pnor_partition);
49     table.data.entry_count = numParts;
50     table.data.block_size = blockSize;
51     table.data.block_count = pnorSize / blockSize;
52     table.checksum = details::checksum(table.data);
53 }
54 
allocateMemory(const fs::path & tocFile)55 inline void Table::allocateMemory(const fs::path& tocFile)
56 {
57     size_t num = 0;
58     std::string line;
59     std::ifstream file(tocFile.c_str());
60 
61     // Find number of lines in partition file - this will help
62     // determine the number of partitions and hence also how much
63     // memory to allocate for the partitions array.
64     // The actual number of partitions may turn out to be lesser than this,
65     // in case of errors.
66     while (std::getline(file, line))
67     {
68         // Check if line starts with "partition"
69         if (std::string::npos != line.find("partition", 0))
70         {
71             ++num;
72         }
73     }
74 
75     szBytes = sizeof(pnor_partition_table) + (num * sizeof(pnor_partition));
76     tbl.resize(capacity());
77 }
78 
preparePartitions(const struct vpnor_data * priv)79 void Table::preparePartitions(const struct vpnor_data* priv)
80 {
81     const fs::path roDir(priv->paths.ro_loc);
82     const fs::path rwDir(priv->paths.rw_loc);
83     const fs::path patchDir(priv->paths.patch_loc);
84     fs::path tocFile = rwDir / PARTITION_TOC_FILE;
85     if (!fs::exists(tocFile))
86     {
87         tocFile = roDir / PARTITION_TOC_FILE;
88     }
89     allocateMemory(tocFile);
90 
91     std::ifstream file(tocFile.c_str());
92     std::string line;
93     decltype(auto) table = getNativeTable();
94 
95     while (std::getline(file, line))
96     {
97         pnor_partition& part = table.partitions[numParts];
98         fs::path patch;
99         fs::path file;
100 
101         // The ToC file presented in the vpnor squashfs looks like:
102         //
103         // version=IBM-witherspoon-ibm-OP9_v1.19_1.135
104         // extended_version=op-build-v1.19-571-g04f4690-dirty,buildroot-2017.11-5-g65679be,skiboot-v5.10-rc4,hostboot-4c46d66,linux-4.14.20-openpower1-p4a6b675,petitboot-v1.6.6-pe5aaec2,machine-xml-0fea226,occ-3286b6b,hostboot-binaries-3d1af8f,capp-ucode-p9-dd2-v3,sbe-99e2fe2
105         // partition00=part,0x00000000,0x00002000,00,READWRITE
106         // partition01=HBEL,0x00008000,0x0002c000,00,ECC,REPROVISION,CLEARECC,READWRITE
107         // ...
108         //
109         // As such we want to skip any lines that don't begin with 'partition'
110         if (std::string::npos == line.find("partition", 0))
111         {
112             continue;
113         }
114 
115         parseTocLine(line, blockSize, part);
116 
117         if (numParts > 0)
118         {
119             struct pnor_partition& prev = table.partitions[numParts - 1];
120             uint32_t prev_end = prev.data.base + prev.data.size;
121 
122             if (part.data.id == prev.data.id)
123             {
124                 MSG_ERR("ID for previous partition '%s' at block 0x%" PRIx32
125                         "matches current partition '%s' at block 0x%" PRIx32
126                         ": %" PRId32 "\n",
127                         prev.data.name, prev.data.base, part.data.name,
128                         part.data.base, part.data.id);
129             }
130 
131             if (part.data.base < prev_end)
132             {
133                 std::stringstream err;
134                 err << "Partition '" << part.data.name << "' start block 0x"
135                     << std::hex << part.data.base << "is less than the end "
136                     << "block 0x" << std::hex << prev_end << " of '"
137                     << prev.data.name << "'";
138                 throw InvalidTocEntry(err.str());
139             }
140         }
141 
142         file = rwDir / part.data.name;
143         if (!fs::exists(file))
144         {
145             file = roDir / part.data.name;
146         }
147         if (!fs::exists(file))
148         {
149             std::stringstream err;
150             err << "Partition file " << file.native() << " does not exist";
151             throw InvalidTocEntry(err.str());
152         }
153 
154         patch = patchDir / part.data.name;
155         if (fs::is_regular_file(patch))
156         {
157             const size_t size = part.data.size * blockSize;
158             part.data.actual =
159                 std::min(size, static_cast<size_t>(fs::file_size(patch)));
160         }
161 
162         ++numParts;
163     }
164 }
165 
partition(size_t offset) const166 const pnor_partition& Table::partition(size_t offset) const
167 {
168     decltype(auto) table = getNativeTable();
169     size_t blockOffset = offset / blockSize;
170 
171     for (decltype(numParts) i{}; i < numParts; ++i)
172     {
173         const struct pnor_partition& part = table.partitions[i];
174         size_t len = part.data.size;
175 
176         if ((blockOffset >= part.data.base) &&
177             (blockOffset < (part.data.base + len)))
178         {
179             return part;
180         }
181 
182         /* Are we in a hole between partitions? */
183         if (blockOffset < part.data.base)
184         {
185             throw UnmappedOffset(offset, part.data.base * blockSize);
186         }
187     }
188 
189     throw UnmappedOffset(offset, pnorSize);
190 }
191 
partition(const std::string & name) const192 const pnor_partition& Table::partition(const std::string& name) const
193 {
194     decltype(auto) table = getNativeTable();
195 
196     for (decltype(numParts) i{}; i < numParts; ++i)
197     {
198         if (name == table.partitions[i].data.name)
199         {
200             return table.partitions[i];
201         }
202     }
203 
204     std::stringstream err;
205     err << "Partition " << name << " is not listed in the table of contents";
206     throw UnknownPartition(err.str());
207 }
208 
209 } // namespace partition
210 
endianFixup(const PartitionTable & in)211 PartitionTable endianFixup(const PartitionTable& in)
212 {
213     PartitionTable out;
214     out.resize(in.size());
215     auto src = reinterpret_cast<const pnor_partition_table*>(in.data());
216     auto dst = reinterpret_cast<pnor_partition_table*>(out.data());
217 
218     dst->data.magic = htobe32(src->data.magic);
219     dst->data.version = htobe32(src->data.version);
220     dst->data.size = htobe32(src->data.size);
221     dst->data.entry_size = htobe32(src->data.entry_size);
222     dst->data.entry_count = htobe32(src->data.entry_count);
223     dst->data.block_size = htobe32(src->data.block_size);
224     dst->data.block_count = htobe32(src->data.block_count);
225     dst->checksum = details::checksum(dst->data);
226 
227     for (decltype(src->data.entry_count) i{}; i < src->data.entry_count; ++i)
228     {
229         auto psrc = &src->partitions[i];
230         auto pdst = &dst->partitions[i];
231         strncpy(pdst->data.name, psrc->data.name, PARTITION_NAME_MAX);
232         // Just to be safe
233         pdst->data.name[PARTITION_NAME_MAX] = '\0';
234         pdst->data.base = htobe32(psrc->data.base);
235         pdst->data.size = htobe32(psrc->data.size);
236         pdst->data.pid = htobe32(psrc->data.pid);
237         pdst->data.id = htobe32(psrc->data.id);
238         pdst->data.type = htobe32(psrc->data.type);
239         pdst->data.flags = htobe32(psrc->data.flags);
240         pdst->data.actual = htobe32(psrc->data.actual);
241         for (size_t j = 0; j < PARTITION_USER_WORDS; ++j)
242         {
243             pdst->data.user.data[j] = htobe32(psrc->data.user.data[j]);
244         }
245         pdst->checksum = details::checksum(pdst->data);
246     }
247 
248     return out;
249 }
250 
writeSizes(pnor_partition & part,size_t start,size_t end,size_t blockSize)251 static inline void writeSizes(pnor_partition& part, size_t start, size_t end,
252                               size_t blockSize)
253 {
254     size_t size = end - start;
255     part.data.base = align_up(start, blockSize) / blockSize;
256     size_t sizeInBlocks = align_up(size, blockSize) / blockSize;
257     part.data.size = sizeInBlocks;
258     part.data.actual = size;
259 }
260 
writeUserdata(pnor_partition & part,uint32_t version,const std::string & data)261 static inline void writeUserdata(pnor_partition& part, uint32_t version,
262                                  const std::string& data)
263 {
264     std::istringstream stream(data);
265     std::string flag{};
266     auto perms = 0;
267     auto state = 0;
268 
269     MSG_DBG("Parsing ToC flags '%s'\n", data.c_str());
270     while (std::getline(stream, flag, ','))
271     {
272         if (flag == "")
273             continue;
274 
275         if (flag == "ECC")
276         {
277             state |= PARTITION_ECC_PROTECTED;
278         }
279         else if (flag == "READONLY")
280         {
281             perms |= PARTITION_READONLY;
282         }
283         else if (flag == "READWRITE")
284         {
285             perms &= ~PARTITION_READONLY;
286         }
287         else if (flag == "PRESERVED")
288         {
289             perms |= PARTITION_PRESERVED;
290         }
291         else if (flag == "REPROVISION")
292         {
293             perms |= PARTITION_REPROVISION;
294         }
295         else if (flag == "VOLATILE")
296         {
297             perms |= PARTITION_VOLATILE;
298         }
299         else if (flag == "CLEARECC")
300         {
301             perms |= PARTITION_CLEARECC;
302         }
303         else
304         {
305             MSG_INFO("Found unimplemented partition property: %s\n",
306                      flag.c_str());
307         }
308     }
309 
310     // Awful hack: Detect the TOC partition and force it read-only.
311     //
312     // Note that as it stands in the caller code we populate the critical
313     // elements before the user data. These tests make doing so a requirement.
314     if (part.data.id == 0 && !part.data.base && part.data.size)
315     {
316         perms |= PARTITION_READONLY;
317     }
318 
319     part.data.user.data[0] = state;
320     part.data.user.data[1] = perms;
321     part.data.user.data[1] |= version;
322 }
323 
writeDefaults(pnor_partition & part)324 static inline void writeDefaults(pnor_partition& part)
325 {
326     part.data.pid = PARENT_PATITION_ID;
327     part.data.type = PARTITION_TYPE_DATA;
328     part.data.flags = 0; // flags unused
329 }
330 
writeNameAndId(pnor_partition & part,std::string && name,const std::string & id)331 static inline void writeNameAndId(pnor_partition& part, std::string&& name,
332                                   const std::string& id)
333 {
334     name.resize(PARTITION_NAME_MAX);
335     memcpy(part.data.name, name.c_str(), sizeof(part.data.name));
336     part.data.id = std::stoul(id);
337 }
338 
parseTocLine(const std::string & line,size_t blockSize,pnor_partition & part)339 void parseTocLine(const std::string& line, size_t blockSize,
340                   pnor_partition& part)
341 {
342     static constexpr auto ID_MATCH = 1;
343     static constexpr auto NAME_MATCH = 2;
344     static constexpr auto START_ADDR_MATCH = 4;
345     static constexpr auto END_ADDR_MATCH = 6;
346     static constexpr auto VERSION_MATCH = 8;
347     constexpr auto versionShift = 24;
348 
349     // Parse PNOR toc (table of contents) file, which has lines like :
350     // partition01=HBB,0x00010000,0x000a0000,0x80,ECC,PRESERVED, to indicate
351     // partition information
352     std::regex regex{
353         "^partition([0-9]+)=([A-Za-z0-9_]+),"
354         "(0x)?([0-9a-fA-F]+),(0x)?([0-9a-fA-F]+),(0x)?([A-Fa-f0-9]{2})",
355         std::regex::extended};
356 
357     std::smatch match;
358     if (!std::regex_search(line, match, regex))
359     {
360         std::stringstream err;
361         err << "Malformed partition description: " << line.c_str() << "\n";
362         throw MalformedTocEntry(err.str());
363     }
364 
365     writeNameAndId(part, match[NAME_MATCH].str(), match[ID_MATCH].str());
366     writeDefaults(part);
367 
368     unsigned long start =
369         std::stoul(match[START_ADDR_MATCH].str(), nullptr, 16);
370     if (start & (blockSize - 1))
371     {
372         MSG_ERR("Start offset 0x%lx for partition '%s' is not aligned to block "
373                 "size 0x%zx\n",
374                 start, match[NAME_MATCH].str().c_str(), blockSize);
375     }
376 
377     unsigned long end = std::stoul(match[END_ADDR_MATCH].str(), nullptr, 16);
378     if ((end - start) & (blockSize - 1))
379     {
380         MSG_ERR("Partition '%s' has a size 0x%lx that is not aligned to block "
381                 "size 0x%zx\n",
382                 match[NAME_MATCH].str().c_str(), (end - start), blockSize);
383     }
384 
385     if (start >= end)
386     {
387         std::stringstream err;
388         err << "Partition " << match[NAME_MATCH].str()
389             << " has an invalid range: start offset (0x" << std::hex << start
390             << " is beyond open end (0x" << std::hex << end << ")\n";
391         throw InvalidTocEntry(err.str());
392     }
393     writeSizes(part, start, end, blockSize);
394 
395     // Use the shift to convert "80" to 0x80000000
396     unsigned long version = std::stoul(match[VERSION_MATCH].str(), nullptr, 16);
397     // Note that we must have written the partition ID and sizes prior to
398     // populating the userdata. See the note about awful hacks in
399     // writeUserdata()
400     writeUserdata(part, version << versionShift, match.suffix().str());
401     part.checksum = details::checksum(part.data);
402 }
403 
404 } // namespace virtual_pnor
405 } // namespace openpower
406