1 /* SPDX-License-Identifier: GPL-2.0-only */
20 #define ALIGN(x,a) __ALIGN_MASK(x,(typeof(x))(a)-1)
21 #define __ALIGN_MASK(x,mask) (((x)+(mask))&~(mask))
23 static void *cbfs_mapped
;
24 static void *cbfs_offset
;
25 static void* virt_to_phys(u32 virt
)
27 return cbfs_offset
+ virt
;
31 #define debug(x...) printf(x)
33 #define debug(x...) while(0) {}
36 static int cbfs_check_magic(struct cbfs_file
*file
)
38 return !strcmp(file
->magic
, CBFS_FILE_MAGIC
) ? 1 : 0;
41 static struct cbfs_header
*cbfs_master_header(void)
43 struct cbfs_header
*header
;
45 void *ptr
= virt_to_phys(*((u32
*)virt_to_phys(CBFS_HEADPTR_ADDR
)));
46 debug("Check CBFS header at %p\n", ptr
);
47 header
= (struct cbfs_header
*) ptr
;
49 debug("magic is %08x\n", ntohl(header
->magic
));
50 if (ntohl(header
->magic
) != CBFS_HEADER_MAGIC
) {
51 printf("ERROR: No valid CBFS header found!\n");
55 debug("Found CBFS header at %p\n", ptr
);
59 struct cbfs_file
*cbfs_find(const char *name
)
61 struct cbfs_header
*header
= cbfs_master_header();
66 offset
= virt_to_phys(0 - ntohl(header
->romsize
) + ntohl(header
->offset
));
68 int align
= ntohl(header
->align
);
71 struct cbfs_file
*file
= (struct cbfs_file
*) offset
;
72 if (!cbfs_check_magic(file
)) return NULL
;
73 debug("Check %s\n", CBFS_NAME(file
));
74 if (!strcmp(CBFS_NAME(file
), name
))
77 int flen
= ntohl(file
->len
);
78 int foffset
= ntohl(file
->offset
);
79 debug("CBFS: follow chain: %p + %x + %x + align -> ", offset
, foffset
, flen
);
81 void *oldoffset
= offset
;
82 offset
= (void*)ALIGN((uintptr_t)(offset
+ foffset
+ flen
), align
);
83 debug("%p\n", (void *)offset
);
84 if (offset
<= oldoffset
) return NULL
;
86 if (offset
< virt_to_phys(0xFFFFFFFF - ntohl(header
->romsize
)))
91 void *cbfs_find_file(const char *name
, unsigned int type
, unsigned int *len
)
93 struct cbfs_file
*file
= cbfs_find(name
);
96 printf("CBFS: Could not find file %s\n",
101 if (ntohl(file
->type
) != type
) {
102 printf("CBFS: File %s is of type %x instead of"
103 "type %x\n", name
, file
->type
, type
);
107 if (len
!= NULL
) *len
= file
->len
;
109 return (void *) CBFS_SUBHEADER(file
);
112 void open_cbfs(const char *filename
)
114 struct stat cbfs_stat
;
117 cbfs_fd
= open(filename
, O_RDWR
);
119 printf("Couldn't open '%s'\n", filename
);
122 if (fstat(cbfs_fd
, &cbfs_stat
) == -1) {
123 printf("Couldn't stat '%s'\n", filename
);
126 cbfs_mapped
= mmap(NULL
, cbfs_stat
.st_size
, PROT_READ
| PROT_WRITE
,
127 MAP_SHARED
, cbfs_fd
, 0);
129 if (cbfs_mapped
== MAP_FAILED
) {
130 printf("Couldn't map '%s'\n", filename
);
133 cbfs_offset
= cbfs_mapped
-(0xffffffff-cbfs_stat
.st_size
+1);