repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
Whisper
github_2023
Const-me
c
ggml_compute_backward
static void ggml_compute_backward(struct ggml_context * ctx, struct ggml_tensor * tensor, bool inplace) { struct ggml_tensor * src0 = tensor->src0; struct ggml_tensor * src1 = tensor->src1; switch (tensor->op) { case GGML_OP_DUP: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace); } } break; case GGML_OP_ADD: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace); } if (src1->grad) { src1->grad = ggml_add_impl(ctx, src1->grad, tensor->grad, inplace); } } break; case GGML_OP_SUB: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace); } if (src1->grad) { src1->grad = ggml_sub_impl(ctx, src1->grad, tensor->grad, inplace); } } break; case GGML_OP_MUL: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, ggml_mul(ctx, src1, tensor->grad), inplace); } if (src1->grad) { src1->grad = ggml_add_impl(ctx, src1->grad, ggml_mul(ctx, src0, tensor->grad), inplace); } } break; case GGML_OP_DIV: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, ggml_div(ctx, tensor->grad, src1), inplace); } if (src1->grad) { src1->grad = ggml_sub_impl(ctx, src1->grad, ggml_mul(ctx, tensor->grad, ggml_div(ctx, tensor, src1)), inplace); } } break; case GGML_OP_SQR: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, ggml_mul(ctx, ggml_mul(ctx, src0, tensor->grad), ggml_repeat(ctx, ggml_new_f32(ctx, 2.0f), src0)), inplace); } } break; case GGML_OP_SQRT: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, ggml_div(ctx, ggml_repeat(ctx, ggml_new_f32(ctx, 0.5f), tensor), tensor), inplace); } } break; case GGML_OP_SUM: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, ggml_repeat(ctx, tensor->grad, src0->grad), inplace); } } break; case GGML_OP_MEAN: { assert(false); // TODO: implement } break; case GGML_OP_REPEAT: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, ggml_sum(ctx, tensor->grad), inplace); } } break; case GGML_OP_ABS: { if (src0->grad) { src0->grad = ggml_add_impl(ctx, src0->grad, ggml_mul(ctx, ggml_sgn(ctx, src0), tensor->grad), inplace); } } break; case GGML_OP_SGN: { if (src0->grad) { // noop } } break; case GGML_OP_NEG: { if (src0->grad) { src0->grad = ggml_sub_impl(ctx, src0->grad, tensor->grad, inplace); } } break; case GGML_OP_STEP: { if (src0->grad) { // noop } } break; case GGML_OP_RELU: { if (src0->grad) { src0->grad = ggml_sub_impl(ctx, src0->grad, ggml_mul(ctx, ggml_step(ctx, src0), tensor->grad), inplace); } } break; case GGML_OP_GELU: { assert(false); // TODO: not implemented } break; case GGML_OP_NORM: { assert(false); // TODO: not implemented } break; case GGML_OP_MUL_MAT: { if (src0->grad) { // TODO: this requires outer product - ggml_out_prod(ctx, src1, tensor->grad); assert(false); } if (src1->grad) { src1->grad = ggml_add_impl(ctx, src1->grad, // TODO: fix transpose, the node will break the graph connections ggml_mul_mat(ctx, ggml_transpose(ctx, src0), tensor->grad), inplace); } } break; case GGML_OP_SCALE: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_CPY: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_RESHAPE: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_VIEW: { GGML_ASSERT(false); // not supported } break; case GGML_OP_PERMUTE: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_TRANSPOSE: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_GET_ROWS: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_DIAG_MASK_INF: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_SOFT_MAX: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_ROPE: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_CONV_1D_1S: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_CONV_1D_2S: { GGML_ASSERT(false); // TODO: not implemented } break; case GGML_OP_FLASH_ATTN: { GGML_ASSERT(false); // not supported } break; case GGML_OP_FLASH_FF: { GGML_ASSERT(false); // not supported } break; case GGML_OP_NONE: { // nop } break; case GGML_OP_COUNT: { GGML_ASSERT(false); } break; } }
////////////////////////////////////////////////////////////////////////////////
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L6484-L6726
306aadd1fce4b168cd38659236f4ba7c1603cebd
Whisper
github_2023
Const-me
c
ggml_graph_find
static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) { if (cgraph == NULL) { return true; } for (int i = 0; i < cgraph->n_nodes; i++) { if (cgraph->nodes[i] == node) { return true; } } return false; }
// check if node is part of the graph
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L7442-L7454
306aadd1fce4b168cd38659236f4ba7c1603cebd
Whisper
github_2023
Const-me
c
ggml_opt_set_params
static void ggml_opt_set_params(int np, struct ggml_tensor * const ps[], const float * x) { int i = 0; for (int p = 0; p < np; ++p) { const int ne = ggml_nelements(ps[p]) ; // TODO: add function to set tensor from array for (int j = 0; j < ne; ++j) { ggml_set_f32_1d(ps[p], j, x[i++]); } } }
////////////////////////////////////////////////////////////////////////////////
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L7585-L7594
306aadd1fce4b168cd38659236f4ba7c1603cebd
Whisper
github_2023
Const-me
c
ggml_opt_adam
static enum ggml_opt_result ggml_opt_adam( struct ggml_context * ctx, struct ggml_opt_params params, struct ggml_tensor * f, struct ggml_cgraph * gf, struct ggml_cgraph * gb) { assert(ggml_is_scalar(f)); gf->n_threads = params.n_threads; gb->n_threads = params.n_threads; // these will store the parameters we want to optimize struct ggml_tensor * ps[GGML_MAX_PARAMS]; int np = 0; int nx = 0; for (int i = 0; i < gf->n_nodes; ++i) { if (gf->nodes[i]->is_param) { GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op); assert(np < GGML_MAX_PARAMS); ps[np++] = gf->nodes[i]; nx += ggml_nelements(gf->nodes[i]); } } // constants const float alpha = params.adam.alpha; const float beta1 = params.adam.beta1; const float beta2 = params.adam.beta2; const float eps = params.adam.eps; float * x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // view of the parameters float * g1 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // gradient float * g2 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // gradient squared float * m = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // first moment float * v = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // second moment float * mh = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // first moment hat float * vh = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // second moment hat float * pf = params.past > 0 ? ggml_new_tensor_1d(ctx, GGML_TYPE_F32, params.past)->data : NULL; // past function values // initialize ggml_vec_set_f32(nx, m, 0.0f); ggml_vec_set_f32(nx, v, 0.0f); // update view ggml_opt_get_params(np, ps, x); // compute the function value ggml_graph_reset (gf); ggml_set_f32 (f->grad, 1.0f); ggml_graph_compute(ctx, gb); float fx_prev = ggml_get_f32_1d(f, 0); if (pf) { pf[0] = fx_prev; } int n_no_improvement = 0; float fx_best = fx_prev; // run the optimizer for (int t = 0; t < params.adam.n_iter; ++t) { GGML_PRINT_DEBUG ("=== iter %d ===\n", t); GGML_PRINT_DEBUG ("f = %10.6f\n", ggml_get_f32_1d(f, 0)); GGML_PRINT_DEBUG_5("df/dx0 = %10.6f\n", ggml_get_f32_1d(ps[0]->grad, 0)); GGML_PRINT_DEBUG_5("df/dx1 = %10.6f\n", ggml_get_f32_1d(ps[1]->grad, 0)); for (int i = 0; i < np; ++i) { GGML_PRINT_DEBUG("param %d: %10.6f, g = %10.6f\n", i, ggml_get_f32_1d(ps[i], 0), ggml_get_f32_1d(ps[i]->grad, 0)); } const int64_t t_start_wall = ggml_time_us(); const int64_t t_start_cpu = ggml_cycles(); UNUSED(t_start_wall); UNUSED(t_start_cpu); { // update the gradient ggml_opt_get_grad(np, ps, g1); // m_t = beta1*m_t-1 + (1 - beta1)*g_t ggml_vec_scale_f32(nx, m, beta1); ggml_vec_mad_f32 (nx, m, g1, 1.0f - beta1); // g2 = g1^2 ggml_vec_sqr_f32 (nx, g2, g1); // v_t = beta2*v_t-1 + (1 - beta2)*g_t^2 ggml_vec_scale_f32(nx, v, beta2); ggml_vec_mad_f32 (nx, v, g2, 1.0f - beta2); // m^hat = m_t / (1 - beta1^t) // v^hat = v_t / (1 - beta2^t) // x_t = x_t-1 - alpha*m^hat/(sqrt(v^hat) + eps) ggml_vec_cpy_f32 (nx, mh, m); ggml_vec_cpy_f32 (nx, vh, v); ggml_vec_scale_f32(nx, mh, alpha/(1.0f - powf(beta1, t + 1))); ggml_vec_scale_f32(nx, vh, 1.0f/(1.0f - powf(beta2, t + 1))); ggml_vec_sqrt_f32 (nx, vh, vh); ggml_vec_acc1_f32 (nx, vh, eps); ggml_vec_div_f32 (nx, mh, mh, vh); ggml_vec_sub_f32 (nx, x, x, mh); // update the parameters ggml_opt_set_params(np, ps, x); } ggml_graph_reset (gf); ggml_set_f32 (f->grad, 1.0f); ggml_graph_compute(ctx, gb); const float fx = ggml_get_f32_1d(f, 0); // check convergence if (fabsf(fx - fx_prev)/fx < params.adam.eps_f) { GGML_PRINT_DEBUG("converged\n"); return GGML_OPT_OK; } // delta-based convergence test if (pf != NULL) { // need at least params.past iterations to start checking for convergence if (params.past <= t) { const float rate = (pf[t%params.past] - fx)/fx; if (fabs(rate) < params.delta) { return GGML_OPT_OK; } } pf[t%params.past] = fx; } // check for improvement if (params.max_no_improvement > 0) { if (fx_best > fx) { fx_best = fx; n_no_improvement = 0; } else { ++n_no_improvement; if (n_no_improvement >= params.max_no_improvement) { return GGML_OPT_OK; } } } fx_prev = fx; { const int64_t t_end_cpu = ggml_cycles(); GGML_PRINT_DEBUG("time iter: %5.3f s\n", ((float)(t_end_cpu - t_start_cpu))/CLOCKS_PER_SEC); UNUSED(t_end_cpu); const int64_t t_end_wall = ggml_time_us(); GGML_PRINT_DEBUG("wall time iter: %5.3f s\n", (t_end_wall - t_start_wall)/1e6); UNUSED(t_end_wall); } } return GGML_OPT_DID_NOT_CONVERGE; }
// // ADAM // // ref: https://arxiv.org/pdf/1412.6980.pdf //
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L7624-L7794
306aadd1fce4b168cd38659236f4ba7c1603cebd
Whisper
github_2023
Const-me
c
ggml_cpu_has_avx
int ggml_cpu_has_avx(void) { #if defined(__AVX__) return 1; #else return 0; #endif }
////////////////////////////////////////////////////////////////////////////////
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L8256-L8262
306aadd1fce4b168cd38659236f4ba7c1603cebd
libxev
github_2023
mitchellh
c
task_callback
void task_callback(xev_threadpool_task* t) { job_t *job = container_of(t, job_t, pool_task); job->done = true; }
// This is the callback that is invoked when the task is being worked on.
https://github.com/mitchellh/libxev/blob/c6e8719a321088691829e2e4bf4d13eed5d4fb69/examples/threadpool.c#L22-L25
c6e8719a321088691829e2e4bf4d13eed5d4fb69
LenovoLegionLinux
github_2023
johnfanv2
c
acpi_erax_dh
void acpi_erax_dh(acpi_handle object, void *data){ pr_info("sdfsdf\n"); }
/* ================================================ */ /* Trying to find memory region experiements */ /* ================================================ */ // experimental and currently not used!
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop-unused-snippets.c#L418-L420
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_acpi_get_ec_start
static int legion_acpi_get_ec_start(struct acpi_device *adev, phys_addr_t * mm_start_addr){ struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; struct acpi_resource *resource; //struct acpi_resource_address64 address; acpi_status status; int err; unsigned long long erax_addr; struct acpi_device_info *info; // ERAX is an OperationRegion in SystemMemory. It is the start // of the memory mapped region to access the RAM of the embedded // controller acpi_handle erax_handle; status = acpi_get_handle(NULL, "\\_SB_.PCI0.LPC0.EC0_.ERAX", &erax_handle); if (ACPI_FAILURE(status)) { pr_info("ERAX in ACPI not found.\n"); } else { pr_info("ERAX in ACPI found.\n"); } status = acpi_get_object_info(erax_handle, &info); if (ACPI_FAILURE(status)) { pr_info("ERAX in ACPI not found.\n"); } else { pr_info("acpi_get_object_info success.\n"); } status = acpi_walk_namespace(ACPI_TYPE_ANY , erax_handle, ACPI_UINT32_MAX, acpi_walk_callback_erax, NULL, NULL, NULL); if (ACPI_FAILURE(status)) { pr_info("acpi_walk_namespace failed.\n"); } else { pr_info("acpi_walk_namespace success.\n"); } status = acpi_walk_resources(adev->handle, "_CRS", acpi_walk_ec_cb , NULL); if (ACPI_FAILURE(status)) { pr_info("acpi_walk_resources failed: %d \n", status); } else { pr_info("acpi_walk_resources was successful.\n"); } struct acpi_gpio_chip *acpi_gpio; status = acpi_get_data(erax_handle, acpi_erax_dh, (void **)&acpi_gpio); if (ACPI_FAILURE(status)) { pr_info("acpi_get_data failed.\n"); } else { pr_info("acpi_get_data was succesful.\n"); } status = acpi_evaluate_integer(erax_handle, "_REG", NULL, &erax_addr); if (ACPI_FAILURE(status)) { pr_info("ERAX _ADR not found.\n"); } else { pr_info("ERAX _ADR not found.\n"); } status = acpi_evaluate_object(NULL, "\\_SB_.PCI0.LPC0.EC0_.ERAX", NULL, &buffer); if (ACPI_FAILURE(status)){ pr_info("getting EC start address: acpi_evaluate_object to get ERAX failed.\n"); err = -EINVAL; goto error_acpi_evaluate_object; } // u8 a; // ec_read(0, &a); // resource = buffer.pointer; // if (resource->type != ACPI_RESOURCE_TYPE_ADDRESS16 && // resource->type != ACPI_RESOURCE_TYPE_ADDRESS32 && // resource->type != ACPI_RESOURCE_TYPE_ADDRESS64) { // err = -EINVAL; // pr_info("getting EC start address: acpi_evaluate_object to get ERAX failed.\n"); // goto error_ressource_type; // } // if(resource->type == ACPI_RESOURCE_TYPE_ADDRESS32){ // pr_info("Got 32 bit ACPI Address.\n"); // } // acpi_resource_to_address64(resource, &address); // address = resource->data.address; // phys_addr_t phy_addr = address; // pr_info("Start address at %p \n", (void*) phy_addr); return 0; error_ressource_type: kfree(resource); error_acpi_evaluate_object: return err; }
/** * Get the memory mapped start address of the memory of the embedded controller . */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop-unused-snippets.c#L455-L550
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ideapad_acpi_add
static int ideapad_acpi_add(struct acpi_device *adev) { struct legion_private *priv = &_legion_priv; int err; phys_addr_t start_addr_ec; pr_info("Loading platform/ACPI driver.\n"); if (!adev || eval_int(adev->handle, "_CFG", &cfg)){ err = -ENODEV; return err; } pr_info("acpi device and _CFG successful.\n"); err = legion_acpi_get_ec_start(adev, &start_addr_ec); if(err){ pr_info("legion_acpi_get_ec_start failed!\n"); return err; } priv->adev = adev; priv->ec_start_addr = start_addr_ec; //priv->platform_device = pdev; priv->loaded = true; return 0; }
//////////// /* * Platform driver from ideapad_acpi.c in linux kernel (modified) * Use either that or ACPI driver. */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop-unused-snippets.c#L563-L589
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
eval_int
static int eval_int(acpi_handle handle, const char *name, unsigned long *res) { unsigned long long result; acpi_status status; status = acpi_evaluate_integer(handle, (char *)name, NULL, &result); if (ACPI_FAILURE(status)) return -EIO; *res = result; return 0; }
/* ================================= */ /* ACPI and WMI access */ /* ================================= */ // function from ideapad-laptop.c
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1354-L1366
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
exec_simple_method
static int exec_simple_method(acpi_handle handle, const char *name, unsigned long arg) { acpi_status status = acpi_execute_simple_method(handle, (char *)name, arg); return ACPI_FAILURE(status) ? -EIO : 0; }
// function from ideapad-laptop.c
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1369-L1376
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
exec_sbmc
static int exec_sbmc(acpi_handle handle, unsigned long arg) { // \_SB.PCI0.LPC0.EC0.VPC0.SBMC return exec_simple_method(handle, "VPC0.SBMC", arg); }
// function from ideapad-laptop.c
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1379-L1383
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
eval_gbmd
static int eval_gbmd(acpi_handle handle, unsigned long *res) { return eval_int(handle, "VPC0.GBMD", res); }
//static int eval_qcho(acpi_handle handle, unsigned long *res) //{ // // \_SB.PCI0.LPC0.EC0.QCHO // return eval_int(handle, "QCHO", res); //}
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1391-L1394
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
wmi_exec_ints
static int wmi_exec_ints(const char *guid, u8 instance, u32 method_id, const struct acpi_buffer *params, u8 *res, size_t ressize) { acpi_status status; struct acpi_buffer out_buffer = { ACPI_ALLOCATE_BUFFER, NULL }; status = wmi_evaluate_method(guid, instance, method_id, params, &out_buffer); return acpi_process_buffer_to_ints(guid, method_id, status, &out_buffer, res, ressize); }
//static int exec_ints(acpi_handle handle, const char *method_name, // struct acpi_object_list *params, u8 *res, size_t ressize) //{ // acpi_status status; // struct acpi_buffer out_buffer = { ACPI_ALLOCATE_BUFFER, NULL }; // status = acpi_evaluate_object(handle, (acpi_string)method_name, params, // &out_buffer); // return acpi_process_buffer_to_ints(method_name, 0, status, &out_buffer, // res, ressize); //}
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1459-L1470
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ecram_memoryio_init
static ssize_t ecram_memoryio_init(struct ecram_memoryio *ec_memoryio, phys_addr_t physical_start, phys_addr_t physical_ec_start, size_t size) { void *virtual_start = ioremap(physical_start, size); if (!IS_ERR_OR_NULL(virtual_start)) { ec_memoryio->virtual_start = virtual_start; ec_memoryio->physical_start = physical_start; ec_memoryio->physical_ec_start = physical_ec_start; ec_memoryio->size = size; pr_info("Successfully mapped embedded controller: 0x%llx (in RAM)/0x%llx (in EC) to virtual 0x%p\n", ec_memoryio->physical_start, ec_memoryio->physical_ec_start, ec_memoryio->virtual_start); } else { pr_info("Error mapping embedded controller memory at 0x%llx\n", physical_start); return -ENOMEM; } return 0; }
/** * physical_start : corresponds to EC RAM 0 inside EC * size: size of remapped region * * strong exception safety */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1760-L1781
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ecram_memoryio_read
static ssize_t ecram_memoryio_read(const struct ecram_memoryio *ec_memoryio, u16 ec_offset, u8 *value) { if (ec_offset < ec_memoryio->physical_ec_start) { pr_info("Unexpected read at offset %d into EC RAM\n", ec_offset); return -1; } *value = *(ec_memoryio->virtual_start + (ec_offset - ec_memoryio->physical_ec_start)); return 0; }
/* Read a byte from the EC RAM. * * Return status because of commong signature for alle * methods to access EC RAM. */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1800-L1811
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ecram_memoryio_write
static ssize_t ecram_memoryio_write(const struct ecram_memoryio *ec_memoryio, u16 ec_offset, u8 value) { if (ec_offset < ec_memoryio->physical_ec_start) { pr_info("Unexpected write at offset %d into EC RAM\n", ec_offset); return -1; } *(ec_memoryio->virtual_start + (ec_offset - ec_memoryio->physical_ec_start)) = value; return 0; }
/* Write a byte to the EC RAM. * * Return status because of commong signature for alle * methods to access EC RAM. */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1818-L1829
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ecram_portio_read
static ssize_t ecram_portio_read(struct ecram_portio *ec_portio, u16 offset, u8 *value) { mutex_lock(&ec_portio->io_port_mutex); outb(0x2E, ECRAM_PORTIO_ADDR_PORT); outb(0x11, ECRAM_PORTIO_DATA_PORT); outb(0x2F, ECRAM_PORTIO_ADDR_PORT); // TODO: no explicit cast between types seems to be sometimes // done and sometimes not outb((u8)((offset >> 8) & 0xFF), ECRAM_PORTIO_DATA_PORT); outb(0x2E, ECRAM_PORTIO_ADDR_PORT); outb(0x10, ECRAM_PORTIO_DATA_PORT); outb(0x2F, ECRAM_PORTIO_ADDR_PORT); outb((u8)(offset & 0xFF), ECRAM_PORTIO_DATA_PORT); outb(0x2E, ECRAM_PORTIO_ADDR_PORT); outb(0x12, ECRAM_PORTIO_DATA_PORT); outb(0x2F, ECRAM_PORTIO_ADDR_PORT); *value = inb(ECRAM_PORTIO_DATA_PORT); mutex_unlock(&ec_portio->io_port_mutex); return 0; }
/* Read a byte from the EC RAM. * * Return status because of commong signature for alle * methods to access EC RAM. */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1899-L1923
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ecram_portio_write
static ssize_t ecram_portio_write(struct ecram_portio *ec_portio, u16 offset, u8 value) { mutex_lock(&ec_portio->io_port_mutex); outb(0x2E, ECRAM_PORTIO_ADDR_PORT); outb(0x11, ECRAM_PORTIO_DATA_PORT); outb(0x2F, ECRAM_PORTIO_ADDR_PORT); // TODO: no explicit cast between types seems to be sometimes // done and sometimes not outb((u8)((offset >> 8) & 0xFF), ECRAM_PORTIO_DATA_PORT); outb(0x2E, ECRAM_PORTIO_ADDR_PORT); outb(0x10, ECRAM_PORTIO_DATA_PORT); outb(0x2F, ECRAM_PORTIO_ADDR_PORT); outb((u8)(offset & 0xFF), ECRAM_PORTIO_DATA_PORT); outb(0x2E, ECRAM_PORTIO_ADDR_PORT); outb(0x12, ECRAM_PORTIO_DATA_PORT); outb(0x2F, ECRAM_PORTIO_ADDR_PORT); outb(value, ECRAM_PORTIO_DATA_PORT); mutex_unlock(&ec_portio->io_port_mutex); // TODO: remove this //pr_info("Writing %d to addr %x\n", value, offset); return 0; }
/* Write a byte to the EC RAM. * * Return status because of commong signature for alle * methods to access EC RAM. */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1930-L1956
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ecram_read
static u8 ecram_read(struct ecram *ecram, u16 ecram_offset) { u8 value; int err; err = ecram_portio_read(&ecram->portio, ecram_offset, &value); if (err) pr_info("Error reading EC RAM at 0x%x.\n", ecram_offset); return value; }
/** Read from EC RAM * ecram_offset address on the EC */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L1994-L2003
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
read_ec_id
static u16 read_ec_id(struct ecram *ecram, const struct model_config *model) { u8 id1 = ecram_read(ecram, model->registers->ECHIPID1); u8 id2 = ecram_read(ecram, model->registers->ECHIPID2); return (id1 << 8) + id2; }
/* =============================== */ /* Reads from EC */ /* =============================== */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2024-L2030
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
fancurve_is_valid_min_temp
static bool fancurve_is_valid_min_temp(int min_temp) { return min_temp >= 0 && min_temp <= 127; }
// validation functions
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2133-L2136
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
fancurve_set_speed_pwm
static bool fancurve_set_speed_pwm(struct fancurve *fancurve, int point_id, int fan_id, int value) { u8 *speed; if (!(point_id == 0 ? value == 0 : (value >= 0 && value <= 255))) { pr_err("Value %d PWM not in allowed range to point with id %d", value, point_id); return false; } if (!(point_id < fancurve->size && fan_id >= 0 && fan_id < 2)) { pr_err("Setting point id %d, fan id %d not valid for fancurve with size %ld", point_id, fan_id, fancurve->size); return false; } speed = fan_id == 0 ? &fancurve->points[point_id].speed1 : &fancurve->points[point_id].speed2; switch (fancurve->fan_speed_unit) { case FAN_SPEED_UNIT_PERCENT: *speed = clamp_t(u8, value * 100 / 255, 0, 255); return true; case FAN_SPEED_UNIT_PWM: *speed = clamp_t(u8, value, 0, 255); return true; case FAN_SPEED_UNIT_RPM_HUNDRED: *speed = clamp_t(u8, value * MAX_RPM / 100 / 255, 0, 255); return true; default: pr_info("No method to set for fan_speed_unit %d.", fancurve->fan_speed_unit); return false; } return false; }
// setters with validation // - make hwmon implementation easier // - keep fancurve valid, otherwise EC will not properly control fan
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2147-L2181
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
fancurve_set_accel
static bool fancurve_set_accel(struct fancurve *fancurve, int point_id, int accel) { bool valid = accel >= 2 && accel <= 5; if (valid) fancurve->points[point_id].accel = accel; return valid; }
// TODO: remove { ... } from single line if body
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2225-L2233
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ec_read_sensor_values
static int ec_read_sensor_values(struct ecram *ecram, const struct model_config *model, struct sensor_values *values) { values->fan1_target_rpm = 100 * ecram_read(ecram, model->registers->EXT_FAN1_TARGET_RPM); values->fan2_target_rpm = 100 * ecram_read(ecram, model->registers->EXT_FAN2_TARGET_RPM); values->fan1_rpm = ecram_read(ecram, model->registers->EXT_FAN1_RPM_LSB) + (((int)ecram_read(ecram, model->registers->EXT_FAN1_RPM_MSB)) << 8); values->fan2_rpm = ecram_read(ecram, model->registers->EXT_FAN2_RPM_LSB) + (((int)ecram_read(ecram, model->registers->EXT_FAN2_RPM_MSB)) << 8); values->cpu_temp_celsius = ecram_read(ecram, model->registers->EXT_CPU_TEMP_INPUT); values->gpu_temp_celsius = ecram_read(ecram, model->registers->EXT_GPU_TEMP_INPUT); values->ic_temp_celsius = ecram_read(ecram, model->registers->EXT_IC_TEMP_INPUT); values->cpu_temp_celsius = ecram_read(ecram, 0xC5E6); values->gpu_temp_celsius = ecram_read(ecram, 0xC5E7); values->ic_temp_celsius = ecram_read(ecram, 0xC5E8); return 0; }
/* ============================= */ /* Sensor value reading/writing */ /* ============================= */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2519-L2549
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
wmi_read_fanspeed
static ssize_t wmi_read_fanspeed(int fan_id, int *fanspeed_rpm) { int err; unsigned long res; struct acpi_buffer params; params.length = 1; params.pointer = &fan_id; err = wmi_exec_int(WMI_GUID_LENOVO_FAN_METHOD, 0, WMI_METHOD_ID_FAN_GETCURRENTFANSPEED, &params, &res); if (!err) *fanspeed_rpm = res; return err; }
// fan_id: 0 or 1
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2650-L2665
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
wmi_read_temperature
static ssize_t wmi_read_temperature(int sensor_id, int *temperature) { int err; unsigned long res; struct acpi_buffer params; if (sensor_id == 0) sensor_id = 0x03; else if (sensor_id == 1) sensor_id = 0x04; else { // TODO: use all correct error codes return -EEXIST; } params.length = 1; params.pointer = &sensor_id; err = wmi_exec_int(WMI_GUID_LENOVO_FAN_METHOD, 0, WMI_METHOD_ID_FAN_GETCURRENTSENSORTEMPERATURE, &params, &res); if (!err) *temperature = res; return err; }
//sensor_id: cpu = 0, gpu = 1
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2668-L2693
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
wmi_read_fanspeed_gz
static ssize_t wmi_read_fanspeed_gz(int fan_id, int *fanspeed_rpm) { int err; u32 method_id; unsigned long res; if (fan_id == 0) method_id = WMI_METHOD_ID_GETFAN1SPEED; else if (fan_id == 1) method_id = WMI_METHOD_ID_GETFAN2SPEED; else { // TODO: use all correct error codes return -EEXIST; } err = wmi_exec_noarg_int(LEGION_WMI_GAMEZONE_GUID, 0, method_id, &res); if (!err) *fanspeed_rpm = res; return err; }
// fan_id: 0 or 1
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2696-L2715
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
wmi_read_temperature_gz
static ssize_t wmi_read_temperature_gz(int sensor_id, int *temperature) { int err; u32 method_id; unsigned long res; if (sensor_id == 0) method_id = WMI_METHOD_ID_GETCPUTEMP; else if (sensor_id == 1) method_id = WMI_METHOD_ID_GETGPUTEMP; else { // TODO: use all correct error codes return -EEXIST; } err = wmi_exec_noarg_int(LEGION_WMI_GAMEZONE_GUID, 0, method_id, &res); if (!err) *temperature = res; return err; }
//sensor_id: cpu = 0, gpu = 1
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2718-L2738
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
wmi_read_fanspeed_other
static ssize_t wmi_read_fanspeed_other(int fan_id, int *fanspeed_rpm) { int err; enum OtherMethodFeature featured_id; int res; if (fan_id == 0) featured_id = OtherMethodFeature_FAN_SPEED_1; else if (fan_id == 1) featured_id = OtherMethodFeature_FAN_SPEED_2; else { // TODO: use all correct error codes return -EEXIST; } err = wmi_other_method_get_value(featured_id, &res); if (!err) *fanspeed_rpm = res; return err; }
// fan_id: 0 or 1
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2741-L2761
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
wmi_read_temperature_other
static ssize_t wmi_read_temperature_other(int sensor_id, int *temperature) { int err; enum OtherMethodFeature featured_id; int res; if (sensor_id == 0) featured_id = OtherMethodFeature_TEMP_CPU; else if (sensor_id == 1) featured_id = OtherMethodFeature_TEMP_GPU; else { // TODO: use all correct error codes return -EEXIST; } err = wmi_other_method_get_value(featured_id, &res); if (!err) *temperature = res; return err; }
//sensor_id: cpu = 0, gpu = 1
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2764-L2783
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
ec_read_fancurve_legion
static int ec_read_fancurve_legion(struct ecram *ecram, const struct model_config *model, struct fancurve *fancurve) { size_t i = 0; fancurve->fan_speed_unit = FAN_SPEED_UNIT_RPM_HUNDRED; for (i = 0; i < MAXFANCURVESIZE; ++i) { struct fancurve_point *point = &fancurve->points[i]; point->speed1 = ecram_read(ecram, model->registers->EXT_FAN1_BASE + i); point->speed2 = ecram_read(ecram, model->registers->EXT_FAN2_BASE + i); point->accel = ecram_read( ecram, model->registers->EXT_FAN_ACC_BASE + i); point->decel = ecram_read( ecram, model->registers->EXT_FAN_DEC_BASE + i); point->cpu_max_temp_celsius = ecram_read(ecram, model->registers->EXT_CPU_TEMP + i); point->cpu_min_temp_celsius = ecram_read( ecram, model->registers->EXT_CPU_TEMP_HYST + i); point->gpu_max_temp_celsius = ecram_read(ecram, model->registers->EXT_GPU_TEMP + i); point->gpu_min_temp_celsius = ecram_read( ecram, model->registers->EXT_GPU_TEMP_HYST + i); point->ic_max_temp_celsius = ecram_read(ecram, model->registers->EXT_VRM_TEMP + i); point->ic_min_temp_celsius = ecram_read( ecram, model->registers->EXT_VRM_TEMP_HYST + i); } // Do not trust that hardware; It might suddenly report // a larger size, so clamp it. fancurve->size = ecram_read(ecram, model->registers->EXT_FAN_POINTS_SIZE); fancurve->size = min(fancurve->size, (typeof(fancurve->size))(MAXFANCURVESIZE)); fancurve->current_point_i = ecram_read(ecram, model->registers->EXT_FAN_CUR_POINT); fancurve->current_point_i = min(fancurve->current_point_i, fancurve->size); return 0; }
/* Read the fan curve from the EC. * * In newer models (>=2022) there is an ACPI/WMI to read fan curve as * a whole. So read/write fan table as a whole to use the * same interface for both cases. * * It reads all points from EC memory, even if stored fancurve is smaller, so * it can contain 0 entries. */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L2958-L3002
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
toggle_powermode
static void toggle_powermode(struct legion_private *priv) { int old_powermode; int next_powermode; read_powermode(priv, &old_powermode); next_powermode = old_powermode == 0 ? 1 : 0; write_powermode(priv, next_powermode); mdelay(1500); write_powermode(priv, old_powermode); }
/** * Shortly toggle powermode to a different mode * and switch back, e.g. to reset fan curve. */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L3599-L3610
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_kbd_bl2_brightness_get
static ssize_t legion_kbd_bl2_brightness_get(struct legion_private *priv) { unsigned long state = 0; int err; err = wmi_exec_noarg_int(LEGION_WMI_GAMEZONE_GUID, 0, WMI_METHOD_ID_GETKEYBOARDLIGHT, &state); if (err) return -EINVAL; return state; }
/* ============================= */ /* Keyboard backlight read/write */ /* ============================= */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L3659-L3670
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
debugfs_ecmemory_show
static int debugfs_ecmemory_show(struct seq_file *s, void *unused) { struct legion_private *priv = s->private; size_t offset; for (offset = 0; offset < priv->conf->memoryio_size; ++offset) { char value = ecram_read(&priv->ecram, priv->conf->memoryio_physical_ec_start + offset); seq_write(s, &value, 1); } return 0; }
/* ============================= */ /* debugfs interface */ /* ============================ */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L3761-L3774
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
seq_file_print_with_error
static void seq_file_print_with_error(struct seq_file *s, const char *name, ssize_t err, int value) { seq_printf(s, "%s error: %ld\n", name, err); seq_printf(s, "%s: %d\n", name, value); }
//TODO: make (almost) all methods static
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L3799-L3804
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
show_simple_wmi_attribute
static int show_simple_wmi_attribute(struct device *dev, struct device_attribute *attr, char *buf, const char *guid, u8 instance, u32 method_id, bool invert, unsigned long scale) { unsigned long state = 0; int err; struct legion_private *priv = dev_get_drvdata(dev); mutex_lock(&priv->fancurve_mutex); err = get_simple_wmi_attribute(priv, guid, instance, method_id, invert, scale, &state); mutex_unlock(&priv->fancurve_mutex); if (err) return -EINVAL; return sysfs_emit(buf, "%lu\n", state); }
/* ============================= */ /* sysfs interface */ /* ============================ */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L3990-L4009
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
touchpad_show
static ssize_t touchpad_show(struct device *dev, struct device_attribute *attr, char *buf) { return show_simple_wmi_attribute(dev, attr, buf, LEGION_WMI_GAMEZONE_GUID, 0, WMI_METHOD_ID_GETTPSTATUS, true, 1); }
// on newer models the touchpad feature in ideapad does not work anymore, so // we need this
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L4196-L4202
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
cpumaxfrequency_show
static ssize_t cpumaxfrequency_show(struct device *dev, struct device_attribute *attr, char *buf) { return show_simple_wmi_attribute(dev, attr, buf, LEGION_WMI_GAMEZONE_GUID, 0, WMI_METHOD_ID_GETCPUMAXFREQUENCY, false, 1); }
// TOOD: probably remove again because provided by other means; only useful for overclocking
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L4273-L4280
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
gpu_default_ppab_ctrgp_powerlimit_show
static ssize_t gpu_default_ppab_ctrgp_powerlimit_show(struct device *dev, struct device_attribute *attr, char *buf) { return show_simple_wmi_attribute( dev, attr, buf, WMI_GUID_LENOVO_GPU_METHOD, 0, WMI_METHOD_ID_GPU_GET_DEFAULT_PPAB_CTGP_POWERLIMIT, false, 1); }
// TOOD: probably remove again because provided by other means; only useful for overclocking
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L4518-L4525
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
gpu_boost_clock_show
static ssize_t gpu_boost_clock_show(struct device *dev, struct device_attribute *attr, char *buf) { return show_simple_wmi_attribute(dev, attr, buf, WMI_GUID_LENOVO_GPU_METHOD, 0, WMI_METHOD_ID_GPU_GET_BOOST_CLOCK, false, 1); }
// TOOD: probably remove again because provided by other means; only useful for overclocking
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L4549-L4556
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_wmi_notify
static void legion_wmi_notify(struct wmi_device *wdev, union acpi_object *data) { struct legion_wmi_private *wpriv; struct legion_private *priv; mutex_lock(&legion_shared_mutex); priv = legion_shared; if ((!priv) && (priv->loaded)) { pr_info("Received WMI event while not initialized!\n"); goto unlock; } wpriv = dev_get_drvdata(&wdev->dev); switch (wpriv->event) { case LEGION_EVENT_A: pr_info("Fan event: legion type: %d; acpi type: %d (%d=integer)", wpriv->event, data->type, ACPI_TYPE_INTEGER); // TODO: here it is too early (first unlock mutext, then wait a bit) //legion_platform_profile_notify(); break; default: pr_info("Event: legion type: %d; acpi type: %d (%d=integer)", wpriv->event, data->type, ACPI_TYPE_INTEGER); break; } unlock: mutex_unlock(&legion_shared_mutex); // todo; fix that! // problem: we get an event just before the powermode change (from the key?), // so if we notify too early, it will read the old power mode/platform profile msleep(500); legion_platform_profile_notify(); }
//static void legion_wmi_notify2(u32 value, void *context) // { // pr_info("WMI notify\n" ); // }
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L4742-L4775
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_wmi_init
static int legion_wmi_init(void) { return wmi_driver_register(&legion_wmi_driver); }
//acpi_status status = wmi_install_notify_handler(LEGION_WMI_GAMEZONE_GUID, // legion_wmi_notify2, NULL); //if (ACPI_FAILURE(status)) { // return -ENODEV; //} //return 0;
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L4855-L4858
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_platform_profile_notify
static void legion_platform_profile_notify(void) { if (!enable_platformprofile) pr_info("Skipping platform_profile_notify because enable_platformprofile is false\n"); platform_profile_notify(); }
/* ============================= */ /* Platform profile */ /* ============================ */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L4874-L4880
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
sensor_label_show
static ssize_t sensor_label_show(struct device *dev, struct device_attribute *attr, char *buf) { int sensor_id = (to_sensor_dev_attr(attr))->index; const char *label; switch (sensor_id) { case SENSOR_CPU_TEMP_ID: label = "CPU Temperature\n"; break; case SENSOR_GPU_TEMP_ID: label = "GPU Temperature\n"; break; case SENSOR_IC_TEMP_ID: label = "IC Temperature\n"; break; case SENSOR_FAN1_RPM_ID: label = "Fan 1\n"; break; case SENSOR_FAN2_RPM_ID: label = "Fan 2\n"; break; case SENSOR_FAN1_TARGET_RPM_ID: label = "Fan 1 Target\n"; break; case SENSOR_FAN2_TARGET_RPM_ID: label = "Fan 2 Target\n"; break; default: return -EOPNOTSUPP; } return sprintf(buf, label); }
/* ============================= */ /* hwom interface */ /* ============================ */ // hw-mon interface // todo: register_group or register_info? // TODO: use one common function (like here) or one function per attribute?
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L4992-L5025
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
sensor_show
static ssize_t sensor_show(struct device *dev, struct device_attribute *devattr, char *buf) { struct legion_private *priv = dev_get_drvdata(dev); int sensor_id = (to_sensor_dev_attr(devattr))->index; struct sensor_values values; int outval; int err = -EIO; switch (sensor_id) { case SENSOR_CPU_TEMP_ID: err = read_temperature(priv, 0, &outval); outval *= 1000; break; case SENSOR_GPU_TEMP_ID: err = read_temperature(priv, 1, &outval); outval *= 1000; break; case SENSOR_IC_TEMP_ID: ec_read_sensor_values(&priv->ecram, priv->conf, &values); outval = 1000 * values.ic_temp_celsius; err = 0; break; case SENSOR_FAN1_RPM_ID: err = read_fanspeed(priv, 0, &outval); break; case SENSOR_FAN2_RPM_ID: err = read_fanspeed(priv, 1, &outval); break; case SENSOR_FAN1_TARGET_RPM_ID: ec_read_sensor_values(&priv->ecram, priv->conf, &values); outval = values.fan1_target_rpm; err = 0; break; case SENSOR_FAN2_TARGET_RPM_ID: ec_read_sensor_values(&priv->ecram, priv->conf, &values); outval = values.fan2_target_rpm; err = 0; break; default: pr_info("Error reading sensor value with id %d\n", sensor_id); return -EOPNOTSUPP; } if (err) return err; return sprintf(buf, "%d\n", outval); }
// TODO: use one common function (like here) or one function per attribute?
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L5028-L5075
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
pwm1_mode_store
static ssize_t pwm1_mode_store(struct device *dev, struct device_attribute *devattr, const char *buf, size_t count) { int value; int is_maximumfanspeed; int err; struct legion_private *priv = dev_get_drvdata(dev); err = kstrtoint(buf, 0, &value); if (err) { err = -1; pr_info("Parsing hwmon store failed: error:%d\n", err); goto error; } is_maximumfanspeed = value == 0; mutex_lock(&priv->fancurve_mutex); err = ec_write_fanfullspeed(&priv->ecram, priv->conf, is_maximumfanspeed); if (err) { err = -1; pr_info("Failed to write pwm1_mode/maximumfanspeed\n"); goto error_unlock; } mutex_unlock(&priv->fancurve_mutex); return count; error_unlock: mutex_unlock(&priv->fancurve_mutex); error: return err; }
// TODO: remove? or use WMI method?
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L5593-L5625
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
acpi_init
static int acpi_init(struct legion_private *priv, struct acpi_device *adev) { int err; unsigned long cfg; bool skip_acpi_sta_check; struct device *dev = &priv->platform_device->dev; priv->adev = adev; if (!priv->adev) { dev_info(dev, "Could not get ACPI handle\n"); goto err_acpi_init; } skip_acpi_sta_check = force || (!priv->conf->acpi_check_dev); if (!skip_acpi_sta_check) { err = eval_int(priv->adev->handle, "_STA", &cfg); if (err) { dev_info(dev, "Could not evaluate ACPI _STA\n"); goto err_acpi_init; } err = eval_int(priv->adev->handle, "VPC0._CFG", &cfg); if (err) { dev_info(dev, "Could not evaluate ACPI _CFG\n"); goto err_acpi_init; } dev_info(dev, "ACPI CFG: %lu\n", cfg); } else { dev_info(dev, "Skipping ACPI _STA check"); } return 0; err_acpi_init: return err; }
/* ACPI*/
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L5800-L5835
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_kbd_bl_led_cdev_brightness_get
static enum led_brightness legion_kbd_bl_led_cdev_brightness_get(struct led_classdev *led_cdev) { struct legion_private *priv = container_of(led_cdev, struct legion_private, kbd_bl.led); return legion_kbd_bl_brightness_get(priv); }
/* ============================= */ /* White Keyboard Backlight */ /* ============================ */ // In style of ideapad-driver and with code modified from ideapad-driver.
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L5842-L5849
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_kbd_bl_exit
static void legion_kbd_bl_exit(struct legion_private *priv) { if (!priv->kbd_bl.initialized) return; priv->kbd_bl.initialized = false; led_classdev_unregister(&priv->kbd_bl.led); }
/** * Deinit keyboard backlight. * * Can also be called if init was not successful. * */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L5906-L5914
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_wmi_cdev_brightness_get
static enum led_brightness legion_wmi_cdev_brightness_get(struct led_classdev *led_cdev) { struct legion_private *priv = container_of(led_cdev, struct legion_private, kbd_bl.led); struct light *light_ins = container_of(led_cdev, struct light, led); return legion_wmi_light_get(priv, light_ins->light_id, light_ins->lower_limit, light_ins->upper_limit); }
/* ============================= */ /* Additional light driver */ /* ============================ */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L5920-L5930
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_light_exit
static void legion_light_exit(struct legion_private *priv, struct light *light_ins) { if (!light_ins->initialized) return; light_ins->initialized = false; led_classdev_unregister(&light_ins->led); }
/** * Deinit light. * * Can also be called if init was not successful. * */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L5992-L6001
ae96a82adb879e729c5727c8769888b47ee1181f
LenovoLegionLinux
github_2023
johnfanv2
c
legion_add
static int legion_add(struct platform_device *pdev) { struct legion_private *priv; const struct dmi_system_id *dmi_sys; int err; u16 ec_read_id; bool skip_ec_id_check; bool is_ec_id_valid; bool is_denied = true; bool is_allowed = false; bool do_load_by_list = false; bool do_load = false; //struct legion_private *priv = dev_get_drvdata(&pdev->dev); dev_info(&pdev->dev, "legion_laptop platform driver probing\n"); dev_info( &pdev->dev, "Read identifying information: DMI_SYS_VENDOR: %s; DMI_PRODUCT_NAME: %s; DMI_BIOS_VERSION:%s\n", dmi_get_system_info(DMI_SYS_VENDOR), dmi_get_system_info(DMI_PRODUCT_NAME), dmi_get_system_info(DMI_BIOS_VERSION)); // TODO: allocate? priv = &_priv; priv->platform_device = pdev; err = legion_shared_init(priv); if (err) { dev_info(&pdev->dev, "legion_laptop is forced to load.\n"); goto err_legion_shared_init; } dev_set_drvdata(&pdev->dev, priv); // TODO: remove pr_info("Read identifying information: DMI_SYS_VENDOR: %s; DMI_PRODUCT_NAME: %s; DMI_BIOS_VERSION:%s\n", dmi_get_system_info(DMI_SYS_VENDOR), dmi_get_system_info(DMI_PRODUCT_NAME), dmi_get_system_info(DMI_BIOS_VERSION)); dmi_sys = dmi_first_match(optimistic_allowlist); is_allowed = dmi_sys != NULL; is_denied = dmi_check_system(denylist); do_load_by_list = is_allowed && !is_denied; do_load = do_load_by_list || force; dev_info( &pdev->dev, "is_denied: %d; is_allowed: %d; do_load_by_list: %d; do_load: %d\n", is_denied, is_allowed, do_load_by_list, do_load); if (!(do_load)) { dev_info( &pdev->dev, "Module not usable for this laptop because it is not in allowlist. Notify the maintainer if you want to add your device or force load with param force.\n"); err = -ENOMEM; goto err_model_mismtach; } if (force) dev_info(&pdev->dev, "legion_laptop is forced to load.\n"); if (!do_load_by_list && do_load) { dev_info( &pdev->dev, "legion_laptop is forced to load and would otherwise not be loaded\n"); } // if forced and no module found, use config for first model if (dmi_sys == NULL) dmi_sys = &optimistic_allowlist[0]; dev_info(&pdev->dev, "Using configuration for system: %s\n", dmi_sys->ident); priv->conf = dmi_sys->driver_data; err = acpi_init(priv, ACPI_COMPANION(&pdev->dev)); if (err) { dev_info(&pdev->dev, "Could not init ACPI access: %d\n", err); goto err_acpi_init; } // TODO: remove; only used for reverse engineering pr_info("Creating RAM access to embedded controller\n"); err = ecram_memoryio_init(&priv->ec_memoryio, priv->conf->ramio_physical_start, 0, priv->conf->ramio_size); if (err) { dev_info( &pdev->dev, "Could not init RAM access to embedded controller: %d\n", err); goto err_ecram_memoryio_init; } err = ecram_init(&priv->ecram, priv->conf->memoryio_physical_ec_start, priv->conf->memoryio_size); if (err) { dev_info(&pdev->dev, "Could not init access to embedded controller: %d\n", err); goto err_ecram_init; } ec_read_id = read_ec_id(&priv->ecram, priv->conf); dev_info(&pdev->dev, "Read embedded controller ID 0x%x\n", ec_read_id); skip_ec_id_check = force || (!priv->conf->check_embedded_controller_id); is_ec_id_valid = skip_ec_id_check || (ec_read_id == priv->conf->embedded_controller_id); if (!is_ec_id_valid) { err = -ENOMEM; dev_info(&pdev->dev, "Expected EC chip id 0x%x but read 0x%x\n", priv->conf->embedded_controller_id, ec_read_id); goto err_ecram_id; } if (skip_ec_id_check) { dev_info(&pdev->dev, "Skipped checking embedded controller id\n"); } dev_info(&pdev->dev, "Creating debugfs interface\n"); legion_debugfs_init(priv); pr_info("Creating sysfs interface\n"); err = legion_sysfs_init(priv); if (err) { dev_info(&pdev->dev, "Failed to create sysfs interface: %d\n", err); goto err_sysfs_init; } pr_info("Creating hwmon interface"); err = legion_hwmon_init(priv); if (err) { dev_info(&pdev->dev, "Failed to create hwmon interface: %d\n", err); goto err_hwmon_init; } pr_info("Creating platform profile support\n"); err = legion_platform_profile_init(priv); if (err) { dev_info(&pdev->dev, "Failed to create platform profile: %d\n", err); goto err_platform_profile; } pr_info("Init WMI driver support\n"); err = legion_wmi_init(); if (err) { dev_info(&pdev->dev, "Failed to init WMI driver: %d\n", err); goto err_wmi; } pr_info("Init keyboard backlight LED driver\n"); err = legion_kbd_bl_init(priv); if (err) { dev_info( &pdev->dev, "Failed to init keyboard backlight LED driver. Skipping ...\n"); } pr_info("Init Y-Logo LED driver\n"); err = legion_light_init(priv, &priv->ylogo_light, LIGHT_ID_YLOGO, 0, 1, "platform::ylogo"); if (err) { dev_info(&pdev->dev, "Failed to init Y-Logo LED driver. Skipping ...\n"); } pr_info("Init IO-Port LED driver\n"); err = legion_light_init(priv, &priv->iport_light, LIGHT_ID_IOPORT, 1, 2, "platform::ioport"); if (err) { dev_info(&pdev->dev, "Failed to init IO-Port LED driver. Skipping ...\n"); } dev_info(&pdev->dev, "legion_laptop loaded for this device\n"); return 0; // TODO: remove eventually legion_light_exit(priv, &priv->iport_light); legion_light_exit(priv, &priv->ylogo_light); legion_kbd_bl_exit(priv); legion_wmi_exit(); err_wmi: legion_platform_profile_exit(priv); err_platform_profile: legion_hwmon_exit(priv); err_hwmon_init: legion_sysfs_exit(priv); err_sysfs_init: legion_debugfs_exit(priv); err_ecram_id: ecram_exit(&priv->ecram); err_ecram_init: ecram_memoryio_exit(&priv->ec_memoryio); err_ecram_memoryio_init: err_acpi_init: legion_shared_exit(priv); err_legion_shared_init: err_model_mismtach: dev_info(&pdev->dev, "legion_laptop not loaded for this device\n"); return err; }
/* ============================= */ /* Platform driver */ /* ============================ */
https://github.com/johnfanv2/LenovoLegionLinux/blob/ae96a82adb879e729c5727c8769888b47ee1181f/kernel_module/legion-laptop.c#L6007-L6210
ae96a82adb879e729c5727c8769888b47ee1181f
teddycloud
github_2023
toniebox-reverse-engineering
c
open_append
FRESULT open_append ( FIL* fp, /* [OUT] File object to create */ const char* path /* [IN] File name to be opened */ ) { FRESULT fr; /* Opens an existing file. If not exist, creates a new file. */ fr = f_open(fp, path, FA_WRITE | FA_OPEN_ALWAYS); if (fr == FR_OK) { /* Seek to end of the file to append data */ fr = f_lseek(fp, f_size(fp)); if (fr != FR_OK) f_close(fp); } return fr; }
/*------------------------------------------------------------/ / Open or create a file in append mode / (This function was sperseded by FA_OPEN_APPEND flag at FatFs R0.12a) /------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/documents/res/app1.c#L6-L22
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
delete_node
FRESULT delete_node ( TCHAR* path, /* Path name buffer with the sub-directory to delete */ UINT sz_buff, /* Size of path name buffer (items) */ FILINFO* fno /* Name read buffer */ ) { UINT i, j; FRESULT fr; DIR dir; fr = f_opendir(&dir, path); /* Open the sub-directory to make it empty */ if (fr != FR_OK) return fr; for (i = 0; path[i]; i++) ; /* Get current path length */ path[i++] = _T('/'); for (;;) { fr = f_readdir(&dir, fno); /* Get a directory item */ if (fr != FR_OK || !fno->fname[0]) break; /* End of directory? */ j = 0; do { /* Make a path name */ if (i + j >= sz_buff) { /* Buffer over flow? */ fr = 100; break; /* Fails with 100 when buffer overflow */ } path[i + j] = fno->fname[j]; } while (fno->fname[j++]); if (fno->fattrib & AM_DIR) { /* Item is a sub-directory */ fr = delete_node(path, sz_buff, fno); } else { /* Item is a file */ fr = f_unlink(path); } if (fr != FR_OK) break; } path[--i] = 0; /* Restore the path name */ f_closedir(&dir); if (fr == FR_OK) fr = f_unlink(path); /* Delete the empty sub-directory */ return fr; }
/*------------------------------------------------------------/ / Delete a sub-directory even if it contains any file /-------------------------------------------------------------/ / The delete_node() function is for R0.12+. / It works regardless of FF_FS_RPATH. */
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/documents/res/app2.c#L9-L49
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
test_contiguous_file
FRESULT test_contiguous_file ( FIL* fp, /* [IN] Open file object to be checked */ int* cont /* [OUT] 1:Contiguous, 0:Fragmented or zero-length */ ) { DWORD clst, clsz, step; FSIZE_t fsz; FRESULT fr; *cont = 0; fr = f_rewind(fp); /* Validates and prepares the file */ if (fr != FR_OK) return fr; #if FF_MAX_SS == FF_MIN_SS clsz = (DWORD)fp->obj.fs->csize * FF_MAX_SS; /* Cluster size */ #else clsz = (DWORD)fp->obj.fs->csize * fp->obj.fs->ssize; #endif fsz = f_size(fp); if (fsz > 0) { clst = fp->obj.sclust - 1; /* A cluster leading the first cluster for first test */ while (fsz) { step = (fsz >= clsz) ? clsz : (DWORD)fsz; fr = f_lseek(fp, f_tell(fp) + step); /* Advances file pointer a cluster */ if (fr != FR_OK) return fr; if (clst + 1 != fp->clust) break; /* Is not the cluster next to previous one? */ clst = fp->clust; fsz -= step; /* Get current cluster for next test */ } if (fsz == 0) *cont = 1; /* All done without fail? */ } return FR_OK; }
/*----------------------------------------------------------------------/ / Test if the file is contiguous / /----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/documents/res/app5.c#L5-L38
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
disk_status
DSTATUS disk_status ( BYTE pdrv /* Physical drive nmuber to identify the drive */ ) { DSTATUS stat; int result; switch (pdrv) { case DEV_RAM : result = RAM_disk_status(); // translate the reslut code here return stat; case DEV_MMC : result = MMC_disk_status(); // translate the reslut code here return stat; case DEV_USB : result = USB_disk_status(); // translate the reslut code here return stat; } return STA_NOINIT; }
/*-----------------------------------------------------------------------*/ /* Get Drive Status */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/diskio.c#L23-L53
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
disk_initialize
DSTATUS disk_initialize ( BYTE pdrv /* Physical drive nmuber to identify the drive */ ) { DSTATUS stat; int result; switch (pdrv) { case DEV_RAM : result = RAM_disk_initialize(); // translate the reslut code here return stat; case DEV_MMC : result = MMC_disk_initialize(); // translate the reslut code here return stat; case DEV_USB : result = USB_disk_initialize(); // translate the reslut code here return stat; } return STA_NOINIT; }
/*-----------------------------------------------------------------------*/ /* Inidialize a Drive */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/diskio.c#L61-L91
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
disk_read
DRESULT disk_read ( BYTE pdrv, /* Physical drive nmuber to identify the drive */ BYTE *buff, /* Data buffer to store read data */ LBA_t sector, /* Start sector in LBA */ UINT count /* Number of sectors to read */ ) { DRESULT res; int result; switch (pdrv) { case DEV_RAM : // translate the arguments here result = RAM_disk_read(buff, sector, count); // translate the reslut code here return res; case DEV_MMC : // translate the arguments here result = MMC_disk_read(buff, sector, count); // translate the reslut code here return res; case DEV_USB : // translate the arguments here result = USB_disk_read(buff, sector, count); // translate the reslut code here return res; } return RES_PARERR; }
/*-----------------------------------------------------------------------*/ /* Read Sector(s) */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/diskio.c#L99-L139
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
disk_ioctl
DRESULT disk_ioctl ( BYTE pdrv, /* Physical drive nmuber (0..) */ BYTE cmd, /* Control code */ void *buff /* Buffer to send/receive control data */ ) { DRESULT res; int result; switch (pdrv) { case DEV_RAM : // Process of the command for the RAM drive return res; case DEV_MMC : // Process of the command for the MMC/SD card return res; case DEV_USB : // Process of the command the USB drive return res; } return RES_PARERR; }
/*-----------------------------------------------------------------------*/ /* Miscellaneous Functions */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/diskio.c#L198-L228
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
ld_word
static WORD ld_word (const BYTE* ptr) /* Load a 2-byte little-endian word */ { WORD rv; rv = ptr[1]; rv = rv << 8 | ptr[0]; return rv; }
/*-------------------------------------------------------------------------- Module Private Functions ---------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/ /* Load/Store multi-byte word in the FAT structure */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L618-L625
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
dbc_1st
static int dbc_1st (BYTE c) { #if FF_CODE_PAGE == 0 /* Variable code page */ if (DbcTbl && c >= DbcTbl[0]) { if (c <= DbcTbl[1]) return 1; /* 1st byte range 1 */ if (c >= DbcTbl[2] && c <= DbcTbl[3]) return 1; /* 1st byte range 2 */ } #elif FF_CODE_PAGE >= 900 /* DBCS fixed code page */ if (c >= DbcTbl[0]) { if (c <= DbcTbl[1]) return 1; if (c >= DbcTbl[2] && c <= DbcTbl[3]) return 1; } #else /* SBCS fixed code page */ if (c != 0) return 0; /* Always false */ #endif return 0; }
/* !FF_FS_READONLY */ /*-----------------------------------------------------------------------*/ /* String functions */ /*-----------------------------------------------------------------------*/ /* Test if the byte is DBC 1st byte */
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L692-L708
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
dbc_2nd
static int dbc_2nd (BYTE c) { #if FF_CODE_PAGE == 0 /* Variable code page */ if (DbcTbl && c >= DbcTbl[4]) { if (c <= DbcTbl[5]) return 1; /* 2nd byte range 1 */ if (c >= DbcTbl[6] && c <= DbcTbl[7]) return 1; /* 2nd byte range 2 */ if (c >= DbcTbl[8] && c <= DbcTbl[9]) return 1; /* 2nd byte range 3 */ } #elif FF_CODE_PAGE >= 900 /* DBCS fixed code page */ if (c >= DbcTbl[4]) { if (c <= DbcTbl[5]) return 1; if (c >= DbcTbl[6] && c <= DbcTbl[7]) return 1; if (c >= DbcTbl[8] && c <= DbcTbl[9]) return 1; } #else /* SBCS fixed code page */ if (c != 0) return 0; /* Always false */ #endif return 0; }
/* Test if the byte is DBC 2nd byte */
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L712-L730
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tchar2uni
static DWORD tchar2uni ( /* Returns a character in UTF-16 encoding (>=0x10000 on surrogate pair, 0xFFFFFFFF on decode error) */ const TCHAR** str /* Pointer to pointer to TCHAR string in configured encoding */ ) { DWORD uc; const TCHAR *p = *str; #if FF_LFN_UNICODE == 1 /* UTF-16 input */ WCHAR wc; uc = *p++; /* Get a unit */ if (IsSurrogate(uc)) { /* Surrogate? */ wc = *p++; /* Get low surrogate */ if (!IsSurrogateH(uc) || !IsSurrogateL(wc)) return 0xFFFFFFFF; /* Wrong surrogate? */ uc = uc << 16 | wc; } #elif FF_LFN_UNICODE == 2 /* UTF-8 input */ BYTE b; int nf; uc = (BYTE)*p++; /* Get an encoding unit */ if (uc & 0x80) { /* Multiple byte code? */ if ((uc & 0xE0) == 0xC0) { /* 2-byte sequence? */ uc &= 0x1F; nf = 1; } else if ((uc & 0xF0) == 0xE0) { /* 3-byte sequence? */ uc &= 0x0F; nf = 2; } else if ((uc & 0xF8) == 0xF0) { /* 4-byte sequence? */ uc &= 0x07; nf = 3; } else { /* Wrong sequence */ return 0xFFFFFFFF; } do { /* Get trailing bytes */ b = (BYTE)*p++; if ((b & 0xC0) != 0x80) return 0xFFFFFFFF; /* Wrong sequence? */ uc = uc << 6 | (b & 0x3F); } while (--nf != 0); if (uc < 0x80 || IsSurrogate(uc) || uc >= 0x110000) return 0xFFFFFFFF; /* Wrong code? */ if (uc >= 0x010000) uc = 0xD800DC00 | ((uc - 0x10000) << 6 & 0x3FF0000) | (uc & 0x3FF); /* Make a surrogate pair if needed */ } #elif FF_LFN_UNICODE == 3 /* UTF-32 input */ uc = (TCHAR)*p++; /* Get a unit */ if (uc >= 0x110000 || IsSurrogate(uc)) return 0xFFFFFFFF; /* Wrong code? */ if (uc >= 0x010000) uc = 0xD800DC00 | ((uc - 0x10000) << 6 & 0x3FF0000) | (uc & 0x3FF); /* Make a surrogate pair if needed */ #else /* ANSI/OEM input */ BYTE b; WCHAR wc; wc = (BYTE)*p++; /* Get a byte */ if (dbc_1st((BYTE)wc)) { /* Is it a DBC 1st byte? */ b = (BYTE)*p++; /* Get 2nd byte */ if (!dbc_2nd(b)) return 0xFFFFFFFF; /* Invalid code? */ wc = (wc << 8) + b; /* Make a DBC */ } if (wc != 0) { wc = ff_oem2uni(wc, CODEPAGE); /* ANSI/OEM ==> Unicode */ if (wc == 0) return 0xFFFFFFFF; /* Invalid code? */ } uc = wc; #endif *str = p; /* Next read pointer */ return uc; }
/* Get a Unicode code point from the TCHAR string in defined API encodeing */
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L736-L801
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
put_utf
static UINT put_utf ( /* Returns number of encoding units written (0:buffer overflow or wrong encoding) */ DWORD chr, /* UTF-16 encoded character (Surrogate pair if >=0x10000) */ TCHAR* buf, /* Output buffer */ UINT szb /* Size of the buffer */ ) { #if FF_LFN_UNICODE == 1 /* UTF-16 output */ WCHAR hs, wc; hs = (WCHAR)(chr >> 16); wc = (WCHAR)chr; if (hs == 0) { /* Single encoding unit? */ if (szb < 1 || IsSurrogate(wc)) return 0; /* Buffer overflow or wrong code? */ *buf = wc; return 1; } if (szb < 2 || !IsSurrogateH(hs) || !IsSurrogateL(wc)) return 0; /* Buffer overflow or wrong surrogate? */ *buf++ = hs; *buf++ = wc; return 2; #elif FF_LFN_UNICODE == 2 /* UTF-8 output */ DWORD hc; if (chr < 0x80) { /* Single byte code? */ if (szb < 1) return 0; /* Buffer overflow? */ *buf = (TCHAR)chr; return 1; } if (chr < 0x800) { /* 2-byte sequence? */ if (szb < 2) return 0; /* Buffer overflow? */ *buf++ = (TCHAR)(0xC0 | (chr >> 6 & 0x1F)); *buf++ = (TCHAR)(0x80 | (chr >> 0 & 0x3F)); return 2; } if (chr < 0x10000) { /* 3-byte sequence? */ if (szb < 3 || IsSurrogate(chr)) return 0; /* Buffer overflow or wrong code? */ *buf++ = (TCHAR)(0xE0 | (chr >> 12 & 0x0F)); *buf++ = (TCHAR)(0x80 | (chr >> 6 & 0x3F)); *buf++ = (TCHAR)(0x80 | (chr >> 0 & 0x3F)); return 3; } /* 4-byte sequence */ if (szb < 4) return 0; /* Buffer overflow? */ hc = ((chr & 0xFFFF0000) - 0xD8000000) >> 6; /* Get high 10 bits */ chr = (chr & 0xFFFF) - 0xDC00; /* Get low 10 bits */ if (hc >= 0x100000 || chr >= 0x400) return 0; /* Wrong surrogate? */ chr = (hc | chr) + 0x10000; *buf++ = (TCHAR)(0xF0 | (chr >> 18 & 0x07)); *buf++ = (TCHAR)(0x80 | (chr >> 12 & 0x3F)); *buf++ = (TCHAR)(0x80 | (chr >> 6 & 0x3F)); *buf++ = (TCHAR)(0x80 | (chr >> 0 & 0x3F)); return 4; #elif FF_LFN_UNICODE == 3 /* UTF-32 output */ DWORD hc; if (szb < 1) return 0; /* Buffer overflow? */ if (chr >= 0x10000) { /* Out of BMP? */ hc = ((chr & 0xFFFF0000) - 0xD8000000) >> 6; /* Get high 10 bits */ chr = (chr & 0xFFFF) - 0xDC00; /* Get low 10 bits */ if (hc >= 0x100000 || chr >= 0x400) return 0; /* Wrong surrogate? */ chr = (hc | chr) + 0x10000; } *buf++ = (TCHAR)chr; return 1; #else /* ANSI/OEM output */ WCHAR wc; wc = ff_uni2oem(chr, CODEPAGE); if (wc >= 0x100) { /* Is this a DBC? */ if (szb < 2) return 0; *buf++ = (char)(wc >> 8); /* Store DBC 1st byte */ *buf++ = (TCHAR)wc; /* Store DBC 2nd byte */ return 2; } if (wc == 0 || szb < 1) return 0; /* Invalid char or buffer overflow? */ *buf++ = (TCHAR)wc; /* Store the character */ return 1; #endif }
/* Store a Unicode char in defined API encoding */
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L805-L886
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
lock_volume
static int lock_volume ( /* 1:Ok, 0:timeout */ FATFS* fs, /* Filesystem object to lock */ int syslock /* System lock required */ ) { int rv; #if FF_FS_LOCK rv = ff_mutex_take(fs->ldrv); /* Lock the volume */ if (rv && syslock) { /* System lock reqiered? */ rv = ff_mutex_take(FF_VOLUMES); /* Lock the system */ if (rv) { SysLock = 2; /* System lock succeeded */ } else { ff_mutex_give(fs->ldrv); /* Failed system lock */ } } #else rv = syslock ? ff_mutex_take(fs->ldrv) : ff_mutex_take(fs->ldrv); /* Lock the volume (this is to prevent compiler warning) */ #endif return rv; }
/*-----------------------------------------------------------------------*/ /* Request/Release grant to access the volume */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L895-L917
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
chk_share
static FRESULT chk_share ( /* Check if the file can be accessed */ DIR* dp, /* Directory object pointing the file to be checked */ int acc /* Desired access type (0:Read mode open, 1:Write mode open, 2:Delete or rename) */ ) { UINT i, be; /* Search open object table for the object */ be = 0; for (i = 0; i < FF_FS_LOCK; i++) { if (Files[i].fs) { /* Existing entry */ if (Files[i].fs == dp->obj.fs && /* Check if the object matches with an open object */ Files[i].clu == dp->obj.sclust && Files[i].ofs == dp->dptr) break; } else { /* Blank entry */ be = 1; } } if (i == FF_FS_LOCK) { /* The object has not been opened */ return (!be && acc != 2) ? FR_TOO_MANY_OPEN_FILES : FR_OK; /* Is there a blank entry for new object? */ } /* The object was opened. Reject any open against writing file and all write mode open */ return (acc != 0 || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK; }
/*-----------------------------------------------------------------------*/ /* File shareing control functions */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L945-L969
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
sync_fs
static FRESULT sync_fs ( /* Returns FR_OK or FR_DISK_ERR */ FATFS* fs /* Filesystem object */ ) { FRESULT res; res = sync_window(fs); if (res == FR_OK) { if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) { /* FAT32: Update FSInfo sector if needed */ /* Create FSInfo structure */ memset(fs->win, 0, sizeof fs->win); st_word(fs->win + BS_55AA, 0xAA55); /* Boot signature */ st_dword(fs->win + FSI_LeadSig, 0x41615252); /* Leading signature */ st_dword(fs->win + FSI_StrucSig, 0x61417272); /* Structure signature */ st_dword(fs->win + FSI_Free_Count, fs->free_clst); /* Number of free clusters */ st_dword(fs->win + FSI_Nxt_Free, fs->last_clst); /* Last allocated culuster */ fs->winsect = fs->volbase + 1; /* Write it into the FSInfo sector (Next to VBR) */ disk_write(fs->pdrv, fs->win, fs->winsect, 1); fs->fsi_flag = 0; } /* Make sure that no pending write process in the lower layer */ if (disk_ioctl(fs->pdrv, CTRL_SYNC, 0) != RES_OK) res = FR_DISK_ERR; } return res; }
/*-----------------------------------------------------------------------*/ /* Synchronize filesystem and data on the storage */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1108-L1134
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
clst2sect
static LBA_t clst2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */ FATFS* fs, /* Filesystem object */ DWORD clst /* Cluster# to be converted */ ) { clst -= 2; /* Cluster number is origin from 2 */ if (clst >= fs->n_fatent - 2) return 0; /* Is it invalid cluster number? */ return fs->database + (LBA_t)fs->csize * clst; /* Start sector number of the cluster */ }
/*-----------------------------------------------------------------------*/ /* Get physical sector number from cluster number */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1144-L1152
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
get_fat
static DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */ FFOBJID* obj, /* Corresponding object */ DWORD clst /* Cluster number to get the value */ ) { UINT wc, bc; DWORD val; FATFS *fs = obj->fs; if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */ val = 1; /* Internal error */ } else { val = 0xFFFFFFFF; /* Default value falls on disk error */ switch (fs->fs_type) { case FS_FAT12 : bc = (UINT)clst; bc += bc / 2; if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break; wc = fs->win[bc++ % SS(fs)]; /* Get 1st byte of the entry */ if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break; wc |= fs->win[bc % SS(fs)] << 8; /* Merge 2nd byte of the entry */ val = (clst & 1) ? (wc >> 4) : (wc & 0xFFF); /* Adjust bit position */ break; case FS_FAT16 : if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break; val = ld_word(fs->win + clst * 2 % SS(fs)); /* Simple WORD array */ break; case FS_FAT32 : if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break; val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x0FFFFFFF; /* Simple DWORD array but mask out upper 4 bits */ break; #if FF_FS_EXFAT case FS_EXFAT : if ((obj->objsize != 0 && obj->sclust != 0) || obj->stat == 0) { /* Object except root dir must have valid data length */ DWORD cofs = clst - obj->sclust; /* Offset from start cluster */ DWORD clen = (DWORD)((LBA_t)((obj->objsize - 1) / SS(fs)) / fs->csize); /* Number of clusters - 1 */ if (obj->stat == 2 && cofs <= clen) { /* Is it a contiguous chain? */ val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* No data on the FAT, generate the value */ break; } if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the 1st fragment? */ val = clst + 1; /* Generate the value */ break; } if (obj->stat != 2) { /* Get value from FAT if FAT chain is valid */ if (obj->n_frag != 0) { /* Is it on the growing edge? */ val = 0x7FFFFFFF; /* Generate EOC */ } else { if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break; val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x7FFFFFFF; } break; } } val = 1; /* Internal error */ break; #endif default: val = 1; /* Internal error */ } } return val; }
/*-----------------------------------------------------------------------*/ /* FAT access - Read value of an FAT entry */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1161-L1229
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
put_fat
static FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */ FATFS* fs, /* Corresponding filesystem object */ DWORD clst, /* FAT index number (cluster number) to be changed */ DWORD val /* New value to be set to the entry */ ) { UINT bc; BYTE *p; FRESULT res = FR_INT_ERR; if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */ switch (fs->fs_type) { case FS_FAT12: bc = (UINT)clst; bc += bc / 2; /* bc: byte offset of the entry */ res = move_window(fs, fs->fatbase + (bc / SS(fs))); if (res != FR_OK) break; p = fs->win + bc++ % SS(fs); *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; /* Update 1st byte */ fs->wflag = 1; res = move_window(fs, fs->fatbase + (bc / SS(fs))); if (res != FR_OK) break; p = fs->win + bc % SS(fs); *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); /* Update 2nd byte */ fs->wflag = 1; break; case FS_FAT16: res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))); if (res != FR_OK) break; st_word(fs->win + clst * 2 % SS(fs), (WORD)val); /* Simple WORD array */ fs->wflag = 1; break; case FS_FAT32: #if FF_FS_EXFAT case FS_EXFAT: #endif res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))); if (res != FR_OK) break; if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) { val = (val & 0x0FFFFFFF) | (ld_dword(fs->win + clst * 4 % SS(fs)) & 0xF0000000); } st_dword(fs->win + clst * 4 % SS(fs), val); fs->wflag = 1; break; } } return res; }
/*-----------------------------------------------------------------------*/ /* FAT access - Change value of an FAT entry */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1239-L1288
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
find_bitmap
static DWORD find_bitmap ( /* 0:Not found, 2..:Cluster block found, 0xFFFFFFFF:Disk error */ FATFS* fs, /* Filesystem object */ DWORD clst, /* Cluster number to scan from */ DWORD ncl /* Number of contiguous clusters to find (1..) */ ) { BYTE bm, bv; UINT i; DWORD val, scl, ctr; clst -= 2; /* The first bit in the bitmap corresponds to cluster #2 */ if (clst >= fs->n_fatent - 2) clst = 0; scl = val = clst; ctr = 0; for (;;) { if (move_window(fs, fs->bitbase + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF; i = val / 8 % SS(fs); bm = 1 << (val % 8); do { do { bv = fs->win[i] & bm; bm <<= 1; /* Get bit value */ if (++val >= fs->n_fatent - 2) { /* Next cluster (with wrap-around) */ val = 0; bm = 0; i = SS(fs); } if (bv == 0) { /* Is it a free cluster? */ if (++ctr == ncl) return scl + 2; /* Check if run length is sufficient for required */ } else { scl = val; ctr = 0; /* Encountered a cluster in-use, restart to scan */ } if (val == clst) return 0; /* All cluster scanned? */ } while (bm != 0); bm = 1; } while (++i < SS(fs)); } }
/*-----------------------------------------------------------------------*/ /* exFAT: Accessing FAT and Allocation Bitmap */ /*-----------------------------------------------------------------------*/ /*--------------------------------------*/ /* Find a contiguous free cluster block */ /*--------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1304-L1337
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
change_bitmap
static FRESULT change_bitmap ( FATFS* fs, /* Filesystem object */ DWORD clst, /* Cluster number to change from */ DWORD ncl, /* Number of clusters to be changed */ int bv /* bit value to be set (0 or 1) */ ) { BYTE bm; UINT i; LBA_t sect; clst -= 2; /* The first bit corresponds to cluster #2 */ sect = fs->bitbase + clst / 8 / SS(fs); /* Sector address */ i = clst / 8 % SS(fs); /* Byte offset in the sector */ bm = 1 << (clst % 8); /* Bit mask in the byte */ for (;;) { if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR; do { do { if (bv == (int)((fs->win[i] & bm) != 0)) return FR_INT_ERR; /* Is the bit expected value? */ fs->win[i] ^= bm; /* Flip the bit */ fs->wflag = 1; if (--ncl == 0) return FR_OK; /* All bits processed? */ } while (bm <<= 1); /* Next bit */ bm = 1; } while (++i < SS(fs)); /* Next byte */ i = 0; } }
/*----------------------------------------*/ /* Set/Clear a block of allocation bitmap */ /*----------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1344-L1373
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
fill_first_frag
static FRESULT fill_first_frag ( FFOBJID* obj /* Pointer to the corresponding object */ ) { FRESULT res; DWORD cl, n; if (obj->stat == 3) { /* Has the object been changed 'fragmented' in this session? */ for (cl = obj->sclust, n = obj->n_cont; n; cl++, n--) { /* Create cluster chain on the FAT */ res = put_fat(obj->fs, cl, cl + 1); if (res != FR_OK) return res; } obj->stat = 0; /* Change status 'FAT chain is valid' */ } return FR_OK; }
/*---------------------------------------------*/ /* Fill the first fragment of the FAT chain */ /*---------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1380-L1396
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
fill_last_frag
static FRESULT fill_last_frag ( FFOBJID* obj, /* Pointer to the corresponding object */ DWORD lcl, /* Last cluster of the fragment */ DWORD term /* Value to set the last FAT entry */ ) { FRESULT res; while (obj->n_frag > 0) { /* Create the chain of last fragment */ res = put_fat(obj->fs, lcl - obj->n_frag + 1, (obj->n_frag > 1) ? lcl - obj->n_frag + 2 : term); if (res != FR_OK) return res; obj->n_frag--; } return FR_OK; }
/*---------------------------------------------*/ /* Fill the last fragment of the FAT chain */ /*---------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1403-L1418
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
remove_chain
static FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */ FFOBJID* obj, /* Corresponding object */ DWORD clst, /* Cluster to remove a chain from */ DWORD pclst /* Previous cluster of clst (0 if entire chain) */ ) { FRESULT res = FR_OK; DWORD nxt; FATFS *fs = obj->fs; #if FF_FS_EXFAT || FF_USE_TRIM DWORD scl = clst, ecl = clst; #endif #if FF_USE_TRIM LBA_t rt[2]; #endif if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */ /* Mark the previous cluster 'EOC' on the FAT if it exists */ if (pclst != 0 && (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT || obj->stat != 2)) { res = put_fat(fs, pclst, 0xFFFFFFFF); if (res != FR_OK) return res; } /* Remove the chain */ do { nxt = get_fat(obj, clst); /* Get cluster status */ if (nxt == 0) break; /* Empty cluster? */ if (nxt == 1) return FR_INT_ERR; /* Internal error? */ if (nxt == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error? */ if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) { res = put_fat(fs, clst, 0); /* Mark the cluster 'free' on the FAT */ if (res != FR_OK) return res; } if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */ fs->free_clst++; fs->fsi_flag |= 1; } #if FF_FS_EXFAT || FF_USE_TRIM if (ecl + 1 == nxt) { /* Is next cluster contiguous? */ ecl = nxt; } else { /* End of contiguous cluster block */ #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { res = change_bitmap(fs, scl, ecl - scl + 1, 0); /* Mark the cluster block 'free' on the bitmap */ if (res != FR_OK) return res; } #endif #if FF_USE_TRIM rt[0] = clst2sect(fs, scl); /* Start of data area to be freed */ rt[1] = clst2sect(fs, ecl) + fs->csize - 1; /* End of data area to be freed */ disk_ioctl(fs->pdrv, CTRL_TRIM, rt); /* Inform storage device that the data in the block may be erased */ #endif scl = ecl = nxt; } #endif clst = nxt; /* Next cluster */ } while (clst < fs->n_fatent); /* Repeat while not the last link */ #if FF_FS_EXFAT /* Some post processes for chain status */ if (fs->fs_type == FS_EXFAT) { if (pclst == 0) { /* Has the entire chain been removed? */ obj->stat = 0; /* Change the chain status 'initial' */ } else { if (obj->stat == 0) { /* Is it a fragmented chain from the beginning of this session? */ clst = obj->sclust; /* Follow the chain to check if it gets contiguous */ while (clst != pclst) { nxt = get_fat(obj, clst); if (nxt < 2) return FR_INT_ERR; if (nxt == 0xFFFFFFFF) return FR_DISK_ERR; if (nxt != clst + 1) break; /* Not contiguous? */ clst++; } if (clst == pclst) { /* Has the chain got contiguous again? */ obj->stat = 2; /* Change the chain status 'contiguous' */ } } else { if (obj->stat == 3 && pclst >= obj->sclust && pclst <= obj->sclust + obj->n_cont) { /* Was the chain fragmented in this session and got contiguous again? */ obj->stat = 2; /* Change the chain status 'contiguous' */ } } } } #endif return FR_OK; }
/*-----------------------------------------------------------------------*/ /* FAT handling - Remove a cluster chain */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1429-L1515
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
create_chain
static DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */ FFOBJID* obj, /* Corresponding object */ DWORD clst /* Cluster# to stretch, 0:Create a new chain */ ) { DWORD cs, ncl, scl; FRESULT res; FATFS *fs = obj->fs; if (clst == 0) { /* Create a new chain */ scl = fs->last_clst; /* Suggested cluster to start to find */ if (scl == 0 || scl >= fs->n_fatent) scl = 1; } else { /* Stretch a chain */ cs = get_fat(obj, clst); /* Check the cluster status */ if (cs < 2) return 1; /* Test for insanity */ if (cs == 0xFFFFFFFF) return cs; /* Test for disk error */ if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */ scl = clst; /* Cluster to start to find */ } if (fs->free_clst == 0) return 0; /* No free cluster */ #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */ ncl = find_bitmap(fs, scl, 1); /* Find a free cluster */ if (ncl == 0 || ncl == 0xFFFFFFFF) return ncl; /* No free cluster or hard error? */ res = change_bitmap(fs, ncl, 1, 1); /* Mark the cluster 'in use' */ if (res == FR_INT_ERR) return 1; if (res == FR_DISK_ERR) return 0xFFFFFFFF; if (clst == 0) { /* Is it a new chain? */ obj->stat = 2; /* Set status 'contiguous' */ } else { /* It is a stretched chain */ if (obj->stat == 2 && ncl != scl + 1) { /* Is the chain got fragmented? */ obj->n_cont = scl - obj->sclust; /* Set size of the contiguous part */ obj->stat = 3; /* Change status 'just fragmented' */ } } if (obj->stat != 2) { /* Is the file non-contiguous? */ if (ncl == clst + 1) { /* Is the cluster next to previous one? */ obj->n_frag = obj->n_frag ? obj->n_frag + 1 : 2; /* Increment size of last framgent */ } else { /* New fragment */ if (obj->n_frag == 0) obj->n_frag = 1; res = fill_last_frag(obj, clst, ncl); /* Fill last fragment on the FAT and link it to new one */ if (res == FR_OK) obj->n_frag = 1; } } } else #endif { /* On the FAT/FAT32 volume */ ncl = 0; if (scl == clst) { /* Stretching an existing chain? */ ncl = scl + 1; /* Test if next cluster is free */ if (ncl >= fs->n_fatent) ncl = 2; cs = get_fat(obj, ncl); /* Get next cluster status */ if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* Test for error */ if (cs != 0) { /* Not free? */ cs = fs->last_clst; /* Start at suggested cluster if it is valid */ if (cs >= 2 && cs < fs->n_fatent) scl = cs; ncl = 0; } } if (ncl == 0) { /* The new cluster cannot be contiguous and find another fragment */ ncl = scl; /* Start cluster */ for (;;) { ncl++; /* Next cluster */ if (ncl >= fs->n_fatent) { /* Check wrap-around */ ncl = 2; if (ncl > scl) return 0; /* No free cluster found? */ } cs = get_fat(obj, ncl); /* Get the cluster status */ if (cs == 0) break; /* Found a free cluster? */ if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* Test for error */ if (ncl == scl) return 0; /* No free cluster found? */ } } res = put_fat(fs, ncl, 0xFFFFFFFF); /* Mark the new cluster 'EOC' */ if (res == FR_OK && clst != 0) { res = put_fat(fs, clst, ncl); /* Link it from the previous one if needed */ } } if (res == FR_OK) { /* Update FSINFO if function succeeded. */ fs->last_clst = ncl; if (fs->free_clst <= fs->n_fatent - 2) fs->free_clst--; fs->fsi_flag |= 1; } else { ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; /* Failed. Generate error status */ } return ncl; /* Return new cluster number or error status */ }
/*-----------------------------------------------------------------------*/ /* FAT handling - Stretch a chain or Create a new chain */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1524-L1615
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
clmt_clust
static DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */ FIL* fp, /* Pointer to the file object */ FSIZE_t ofs /* File offset to be converted to cluster# */ ) { DWORD cl, ncl; DWORD *tbl; FATFS *fs = fp->obj.fs; tbl = fp->cltbl + 1; /* Top of CLMT */ cl = (DWORD)(ofs / SS(fs) / fs->csize); /* Cluster order from top of the file */ for (;;) { ncl = *tbl++; /* Number of cluters in the fragment */ if (ncl == 0) return 0; /* End of table? (error) */ if (cl < ncl) break; /* In this fragment? */ cl -= ncl; tbl++; /* Next fragment */ } return cl + *tbl; /* Return the cluster number */ }
/*-----------------------------------------------------------------------*/ /* FAT handling - Convert offset into cluster with link map table */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1627-L1646
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
dir_sdi
static FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */ DIR* dp, /* Pointer to directory object */ DWORD ofs /* Offset of directory table */ ) { DWORD csz, clst; FATFS *fs = dp->obj.fs; if (ofs >= (DWORD)((FF_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR) || ofs % SZDIRE) { /* Check range of offset and alignment */ return FR_INT_ERR; } dp->dptr = ofs; /* Set current offset */ clst = dp->obj.sclust; /* Table start cluster (0:root) */ if (clst == 0 && fs->fs_type >= FS_FAT32) { /* Replace cluster# 0 with root cluster# */ clst = (DWORD)fs->dirbase; if (FF_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */ } if (clst == 0) { /* Static table (root-directory on the FAT volume) */ if (ofs / SZDIRE >= fs->n_rootdir) return FR_INT_ERR; /* Is index out of range? */ dp->sect = fs->dirbase; } else { /* Dynamic table (sub-directory or root-directory on the FAT32/exFAT volume) */ csz = (DWORD)fs->csize * SS(fs); /* Bytes per cluster */ while (ofs >= csz) { /* Follow cluster chain */ clst = get_fat(&dp->obj, clst); /* Get next cluster */ if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */ if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Reached to end of table or internal error */ ofs -= csz; } dp->sect = clst2sect(fs, clst); } dp->clust = clst; /* Current cluster# */ if (dp->sect == 0) return FR_INT_ERR; dp->sect += ofs / SS(fs); /* Sector# of the directory entry */ dp->dir = fs->win + (ofs % SS(fs)); /* Pointer to the entry in the win[] */ return FR_OK; }
/* !FF_FS_READONLY */ /*-----------------------------------------------------------------------*/ /* Directory handling - Set directory index */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1697-L1736
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
dir_next
static FRESULT dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */ DIR* dp, /* Pointer to the directory object */ int stretch /* 0: Do not stretch table, 1: Stretch table if needed */ ) { DWORD ofs, clst; FATFS *fs = dp->obj.fs; ofs = dp->dptr + SZDIRE; /* Next entry */ if (ofs >= (DWORD)((FF_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR)) dp->sect = 0; /* Disable it if the offset reached the max value */ if (dp->sect == 0) return FR_NO_FILE; /* Report EOT if it has been disabled */ if (ofs % SS(fs) == 0) { /* Sector changed? */ dp->sect++; /* Next sector */ if (dp->clust == 0) { /* Static table */ if (ofs / SZDIRE >= fs->n_rootdir) { /* Report EOT if it reached end of static table */ dp->sect = 0; return FR_NO_FILE; } } else { /* Dynamic table */ if ((ofs / SS(fs) & (fs->csize - 1)) == 0) { /* Cluster changed? */ clst = get_fat(&dp->obj, dp->clust); /* Get next cluster */ if (clst <= 1) return FR_INT_ERR; /* Internal error */ if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */ if (clst >= fs->n_fatent) { /* It reached end of dynamic table */ #if !FF_FS_READONLY if (!stretch) { /* If no stretch, report EOT */ dp->sect = 0; return FR_NO_FILE; } clst = create_chain(&dp->obj, dp->clust); /* Allocate a cluster */ if (clst == 0) return FR_DENIED; /* No free cluster */ if (clst == 1) return FR_INT_ERR; /* Internal error */ if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */ if (dir_clear(fs, clst) != FR_OK) return FR_DISK_ERR; /* Clean up the stretched table */ if (FF_FS_EXFAT) dp->obj.stat |= 4; /* exFAT: The directory has been stretched */ #else if (!stretch) dp->sect = 0; /* (this line is to suppress compiler warning) */ dp->sect = 0; return FR_NO_FILE; /* Report EOT */ #endif } dp->clust = clst; /* Initialize data for new cluster */ dp->sect = clst2sect(fs, clst); } } } dp->dptr = ofs; /* Current entry */ dp->dir = fs->win + ofs % SS(fs); /* Pointer to the entry in the win[] */ return FR_OK; }
/*-----------------------------------------------------------------------*/ /* Directory handling - Move directory table index next */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1745-L1796
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
ld_clust
static DWORD ld_clust ( /* Returns the top cluster value of the SFN entry */ FATFS* fs, /* Pointer to the fs object */ const BYTE* dir /* Pointer to the key entry */ ) { DWORD cl; cl = ld_word(dir + DIR_FstClusLO); if (fs->fs_type == FS_FAT32) { cl |= (DWORD)ld_word(dir + DIR_FstClusHI) << 16; } return cl; }
/* !FF_FS_READONLY */ /*-----------------------------------------------------------------------*/ /* FAT: Directory handling - Load/Store start cluster number */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1848-L1861
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
cmp_lfn
static int cmp_lfn ( /* 1:matched, 0:not matched */ const WCHAR* lfnbuf, /* Pointer to the LFN working buffer to be compared */ BYTE* dir /* Pointer to the directory entry containing the part of LFN */ ) { UINT i, s; WCHAR wc, uc; if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */ i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */ for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */ uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */ if (wc != 0) { if (i >= FF_MAX_LFN + 1 || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */ return 0; /* Not matched */ } wc = uc; } else { if (uc != 0xFFFF) return 0; /* Check filler */ } } if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) return 0; /* Last segment matched but different length */ return 1; /* The part of LFN matched */ }
/*--------------------------------------------------------*/ /* FAT-LFN: Compare a part of file name with an LFN entry */ /*--------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1885-L1913
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
pick_lfn
static int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */ WCHAR* lfnbuf, /* Pointer to the LFN working buffer */ BYTE* dir /* Pointer to the LFN entry */ ) { UINT i, s; WCHAR wc, uc; if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO is 0 */ i = ((dir[LDIR_Ord] & ~LLEF) - 1) * 13; /* Offset in the LFN buffer */ for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */ uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */ if (wc != 0) { if (i >= FF_MAX_LFN + 1) return 0; /* Buffer overflow? */ lfnbuf[i++] = wc = uc; /* Store it */ } else { if (uc != 0xFFFF) return 0; /* Check filler */ } } if (dir[LDIR_Ord] & LLEF && wc != 0) { /* Put terminator if it is the last LFN part and not terminated */ if (i >= FF_MAX_LFN + 1) return 0; /* Buffer overflow? */ lfnbuf[i] = 0; } return 1; /* The part of LFN is valid */ }
/*-----------------------------------------------------*/ /* FAT-LFN: Pick a part of file name from an LFN entry */ /*-----------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1921-L1950
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
put_lfn
static void put_lfn ( const WCHAR* lfn, /* Pointer to the LFN */ BYTE* dir, /* Pointer to the LFN entry to be created */ BYTE ord, /* LFN order (1-20) */ BYTE sum /* Checksum of the corresponding SFN */ ) { UINT i, s; WCHAR wc; dir[LDIR_Chksum] = sum; /* Set checksum */ dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */ dir[LDIR_Type] = 0; st_word(dir + LDIR_FstClusLO, 0); i = (ord - 1) * 13; /* Get offset in the LFN working buffer */ s = wc = 0; do { if (wc != 0xFFFF) wc = lfn[i++]; /* Get an effective character */ st_word(dir + LfnOfs[s], wc); /* Put it */ if (wc == 0) wc = 0xFFFF; /* Padding characters for following items */ } while (++s < 13); if (wc == 0xFFFF || !lfn[i]) ord |= LLEF; /* Last LFN part is the start of LFN sequence */ dir[LDIR_Ord] = ord; /* Set the LFN order */ }
/*-----------------------------------------*/ /* FAT-LFN: Create an entry of LFN entries */ /*-----------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1959-L1984
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
gen_numname
static void gen_numname ( BYTE* dst, /* Pointer to the buffer to store numbered SFN */ const BYTE* src, /* Pointer to SFN in directory form */ const WCHAR* lfn, /* Pointer to LFN */ UINT seq /* Sequence number */ ) { BYTE ns[8], c; UINT i, j; WCHAR wc; DWORD sreg; memcpy(dst, src, 11); /* Prepare the SFN to be modified */ if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */ sreg = seq; while (*lfn) { /* Create a CRC as hash value */ wc = *lfn++; for (i = 0; i < 16; i++) { sreg = (sreg << 1) + (wc & 1); wc >>= 1; if (sreg & 0x10000) sreg ^= 0x11021; } } seq = (UINT)sreg; } /* Make suffix (~ + hexadecimal) */ i = 7; do { c = (BYTE)((seq % 16) + '0'); seq /= 16; if (c > '9') c += 7; ns[i--] = c; } while (i && seq); ns[i] = '~'; /* Append the suffix to the SFN body */ for (j = 0; j < i && dst[j] != ' '; j++) { /* Find the offset to append */ if (dbc_1st(dst[j])) { /* To avoid DBC break up */ if (j == i - 1) break; j++; } } do { /* Append the suffix */ dst[j++] = (i < 8) ? ns[i++] : ' '; } while (j < 8); }
/*-----------------------------------------------------------------------*/ /* FAT-LFN: Create a Numbered SFN */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L1996-L2043
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
sum_sfn
static BYTE sum_sfn ( const BYTE* dir /* Pointer to the SFN entry */ ) { BYTE sum = 0; UINT n = 11; do { sum = (sum >> 1) + (sum << 7) + *dir++; } while (--n); return sum; }
/*-----------------------------------------------------------------------*/ /* FAT-LFN: Calculate checksum of an SFN entry */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2053-L2064
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
xdir_sum
static WORD xdir_sum ( /* Get checksum of the directoly entry block */ const BYTE* dir /* Directory entry block to be calculated */ ) { UINT i, szblk; WORD sum; szblk = (dir[XDIR_NumSec] + 1) * SZDIRE; /* Number of bytes of the entry block */ for (i = sum = 0; i < szblk; i++) { if (i == XDIR_SetSum) { /* Skip 2-byte sum field */ i++; } else { sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + dir[i]; } } return sum; }
/*-----------------------------------------------------------------------*/ /* exFAT: Checksum */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2075-L2092
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
load_xdir
static FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */ DIR* dp /* Reading directory object pointing top of the entry block to load */ ) { FRESULT res; UINT i, sz_ent; BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory directory entry block 85+C0+C1s */ /* Load file directory entry */ res = move_window(dp->obj.fs, dp->sect); if (res != FR_OK) return res; if (dp->dir[XDIR_Type] != ET_FILEDIR) return FR_INT_ERR; /* Invalid order */ memcpy(dirb + 0 * SZDIRE, dp->dir, SZDIRE); sz_ent = (dirb[XDIR_NumSec] + 1) * SZDIRE; if (sz_ent < 3 * SZDIRE || sz_ent > 19 * SZDIRE) return FR_INT_ERR; /* Load stream extension entry */ res = dir_next(dp, 0); if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */ if (res != FR_OK) return res; res = move_window(dp->obj.fs, dp->sect); if (res != FR_OK) return res; if (dp->dir[XDIR_Type] != ET_STREAM) return FR_INT_ERR; /* Invalid order */ memcpy(dirb + 1 * SZDIRE, dp->dir, SZDIRE); if (MAXDIRB(dirb[XDIR_NumName]) > sz_ent) return FR_INT_ERR; /* Load file name entries */ i = 2 * SZDIRE; /* Name offset to load */ do { res = dir_next(dp, 0); if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */ if (res != FR_OK) return res; res = move_window(dp->obj.fs, dp->sect); if (res != FR_OK) return res; if (dp->dir[XDIR_Type] != ET_FILENAME) return FR_INT_ERR; /* Invalid order */ if (i < MAXDIRB(FF_MAX_LFN)) memcpy(dirb + i, dp->dir, SZDIRE); } while ((i += SZDIRE) < sz_ent); /* Sanity check (do it for only accessible object) */ if (i <= MAXDIRB(FF_MAX_LFN)) { if (xdir_sum(dirb) != ld_word(dirb + XDIR_SetSum)) return FR_INT_ERR; } return FR_OK; }
/*------------------------------------*/ /* exFAT: Get a directory entry block */ /*------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2130-L2174
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
init_alloc_info
static void init_alloc_info ( FATFS* fs, /* Filesystem object */ FFOBJID* obj /* Object allocation information to be initialized */ ) { obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Start cluster */ obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize); /* Size */ obj->stat = fs->dirbuf[XDIR_GenFlags] & 2; /* Allocation status */ obj->n_frag = 0; /* No last fragment info */ }
/*------------------------------------------------------------------*/ /* exFAT: Initialize object allocation info with loaded entry block */ /*------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2181-L2190
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
load_obj_xdir
static FRESULT load_obj_xdir ( DIR* dp, /* Blank directory object to be used to access containing directory */ const FFOBJID* obj /* Object with its containing directory information */ ) { FRESULT res; /* Open object containing directory */ dp->obj.fs = obj->fs; dp->obj.sclust = obj->c_scl; dp->obj.stat = (BYTE)obj->c_size; dp->obj.objsize = obj->c_size & 0xFFFFFF00; dp->obj.n_frag = 0; dp->blk_ofs = obj->c_ofs; res = dir_sdi(dp, dp->blk_ofs); /* Goto object's entry block */ if (res == FR_OK) { res = load_xdir(dp); /* Load the object's entry block */ } return res; }
/*------------------------------------------------*/ /* exFAT: Load the object's directory entry block */ /*------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2199-L2219
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
store_xdir
static FRESULT store_xdir ( DIR* dp /* Pointer to the directory object */ ) { FRESULT res; UINT nent; BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the directory entry block 85+C0+C1s */ /* Create set sum */ st_word(dirb + XDIR_SetSum, xdir_sum(dirb)); nent = dirb[XDIR_NumSec] + 1; /* Store the directory entry block to the directory */ res = dir_sdi(dp, dp->blk_ofs); while (res == FR_OK) { res = move_window(dp->obj.fs, dp->sect); if (res != FR_OK) break; memcpy(dp->dir, dirb, SZDIRE); dp->obj.fs->wflag = 1; if (--nent == 0) break; dirb += SZDIRE; res = dir_next(dp, 0); } return (res == FR_OK || res == FR_DISK_ERR) ? res : FR_INT_ERR; }
/*----------------------------------------*/ /* exFAT: Store the directory entry block */ /*----------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2228-L2252
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
create_xdir
static void create_xdir ( BYTE* dirb, /* Pointer to the directory entry block buffer */ const WCHAR* lfn /* Pointer to the object name */ ) { UINT i; BYTE nc1, nlen; WCHAR wc; /* Create file-directory and stream-extension entry */ memset(dirb, 0, 2 * SZDIRE); dirb[0 * SZDIRE + XDIR_Type] = ET_FILEDIR; dirb[1 * SZDIRE + XDIR_Type] = ET_STREAM; /* Create file-name entries */ i = SZDIRE * 2; /* Top of file_name entries */ nlen = nc1 = 0; wc = 1; do { dirb[i++] = ET_FILENAME; dirb[i++] = 0; do { /* Fill name field */ if (wc != 0 && (wc = lfn[nlen]) != 0) nlen++; /* Get a character if exist */ st_word(dirb + i, wc); /* Store it */ i += 2; } while (i % SZDIRE != 0); nc1++; } while (lfn[nlen]); /* Fill next entry if any char follows */ dirb[XDIR_NumName] = nlen; /* Set name length */ dirb[XDIR_NumSec] = 1 + nc1; /* Set secondary count (C0 + C1s) */ st_word(dirb + XDIR_NameHash, xname_sum(lfn)); /* Set name hash */ }
/*-------------------------------------------*/ /* exFAT: Create a new directory entry block */ /*-------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2260-L2291
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
dir_find
static FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */ DIR* dp /* Pointer to the directory object with the file name */ ) { FRESULT res; FATFS *fs = dp->obj.fs; BYTE c; #if FF_USE_LFN BYTE a, ord, sum; #endif res = dir_sdi(dp, 0); /* Rewind directory object */ if (res != FR_OK) return res; #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */ BYTE nc; UINT di, ni; WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */ while ((res = DIR_READ_FILE(dp)) == FR_OK) { /* Read an item */ #if FF_MAX_LFN < 255 if (fs->dirbuf[XDIR_NumName] > FF_MAX_LFN) continue; /* Skip comparison if inaccessible object name */ #endif if (ld_word(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip comparison if hash mismatched */ for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */ if ((di % SZDIRE) == 0) di += 2; if (ff_wtoupper(ld_word(fs->dirbuf + di)) != ff_wtoupper(fs->lfnbuf[ni])) break; } if (nc == 0 && !fs->lfnbuf[ni]) break; /* Name matched? */ } return res; } #endif /* On the FAT/FAT32 volume */ #if FF_USE_LFN ord = sum = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */ #endif do { res = move_window(fs, dp->sect); if (res != FR_OK) break; c = dp->dir[DIR_Name]; if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */ #if FF_USE_LFN /* LFN configuration */ dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK; if (c == DDEM || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */ ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */ } else { if (a == AM_LFN) { /* An LFN entry is found */ if (!(dp->fn[NSFLAG] & NS_NOLFN)) { if (c & LLEF) { /* Is it start of LFN sequence? */ sum = dp->dir[LDIR_Chksum]; c &= (BYTE)~LLEF; ord = c; /* LFN start order */ dp->blk_ofs = dp->dptr; /* Start offset of LFN */ } /* Check validity of the LFN entry and compare it with given name */ ord = (c == ord && sum == dp->dir[LDIR_Chksum] && cmp_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF; } } else { /* An SFN entry is found */ if (ord == 0 && sum == sum_sfn(dp->dir)) break; /* LFN matched? */ if (!(dp->fn[NSFLAG] & NS_LOSS) && !memcmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */ ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */ } } #else /* Non LFN configuration */ dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK; if (!(dp->dir[DIR_Attr] & AM_VOL) && !memcmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */ #endif res = dir_next(dp, 0); /* Next entry */ } while (res == FR_OK); return res; }
/* FF_FS_MINIMIZE <= 1 || FF_USE_LABEL || FF_FS_RPATH >= 2 */ /*-----------------------------------------------------------------------*/ /* Directory handling - Find an object in the directory */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2384-L2455
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
dir_register
static FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */ DIR* dp /* Target directory with object name to be created */ ) { FRESULT res; FATFS *fs = dp->obj.fs; #if FF_USE_LFN /* LFN configuration */ UINT n, len, n_ent; BYTE sn[12], sum; if (dp->fn[NSFLAG] & (NS_DOT | NS_NONAME)) return FR_INVALID_NAME; /* Check name validity */ for (len = 0; fs->lfnbuf[len]; len++) ; /* Get lfn length */ #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */ n_ent = (len + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */ res = dir_alloc(dp, n_ent); /* Allocate directory entries */ if (res != FR_OK) return res; dp->blk_ofs = dp->dptr - SZDIRE * (n_ent - 1); /* Set the allocated entry block offset */ if (dp->obj.stat & 4) { /* Has the directory been stretched by new allocation? */ dp->obj.stat &= ~4; res = fill_first_frag(&dp->obj); /* Fill the first fragment on the FAT if needed */ if (res != FR_OK) return res; res = fill_last_frag(&dp->obj, dp->clust, 0xFFFFFFFF); /* Fill the last fragment on the FAT if needed */ if (res != FR_OK) return res; if (dp->obj.sclust != 0) { /* Is it a sub-directory? */ DIR dj; res = load_obj_xdir(&dj, &dp->obj); /* Load the object status */ if (res != FR_OK) return res; dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase the directory size by cluster size */ st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize); st_qword(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize); fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1; /* Update the allocation status */ res = store_xdir(&dj); /* Store the object status */ if (res != FR_OK) return res; } } create_xdir(fs->dirbuf, fs->lfnbuf); /* Create on-memory directory block to be written later */ return FR_OK; } #endif /* On the FAT/FAT32 volume */ memcpy(sn, dp->fn, 12); if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */ dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */ for (n = 1; n < 100; n++) { gen_numname(dp->fn, sn, fs->lfnbuf, n); /* Generate a numbered name */ res = dir_find(dp); /* Check if the name collides with existing SFN */ if (res != FR_OK) break; } if (n == 100) return FR_DENIED; /* Abort if too many collisions */ if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */ dp->fn[NSFLAG] = sn[NSFLAG]; } /* Create an SFN with/without LFNs. */ n_ent = (sn[NSFLAG] & NS_LFN) ? (len + 12) / 13 + 1 : 1; /* Number of entries to allocate */ res = dir_alloc(dp, n_ent); /* Allocate entries */ if (res == FR_OK && --n_ent) { /* Set LFN entry if needed */ res = dir_sdi(dp, dp->dptr - n_ent * SZDIRE); if (res == FR_OK) { sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */ do { /* Store LFN entries in bottom first */ res = move_window(fs, dp->sect); if (res != FR_OK) break; put_lfn(fs->lfnbuf, dp->dir, (BYTE)n_ent, sum); fs->wflag = 1; res = dir_next(dp, 0); /* Next entry */ } while (res == FR_OK && --n_ent); } } #else /* Non LFN configuration */ res = dir_alloc(dp, 1); /* Allocate an entry for SFN */ #endif /* Set SFN entry */ if (res == FR_OK) { res = move_window(fs, dp->sect); if (res == FR_OK) { memset(dp->dir, 0, SZDIRE); /* Clean the entry */ memcpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */ #if FF_USE_LFN dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */ #endif fs->wflag = 1; } } return res; }
/*-----------------------------------------------------------------------*/ /* Register an object to the directory */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2465-L2560
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
dir_remove
static FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */ DIR* dp /* Directory object pointing the entry to be removed */ ) { FRESULT res; FATFS *fs = dp->obj.fs; #if FF_USE_LFN /* LFN configuration */ DWORD last = dp->dptr; res = (dp->blk_ofs == 0xFFFFFFFF) ? FR_OK : dir_sdi(dp, dp->blk_ofs); /* Goto top of the entry block if LFN is exist */ if (res == FR_OK) { do { res = move_window(fs, dp->sect); if (res != FR_OK) break; if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */ dp->dir[XDIR_Type] &= 0x7F; /* Clear the entry InUse flag. */ } else { /* On the FAT/FAT32 volume */ dp->dir[DIR_Name] = DDEM; /* Mark the entry 'deleted'. */ } fs->wflag = 1; if (dp->dptr >= last) break; /* If reached last entry then all entries of the object has been deleted. */ res = dir_next(dp, 0); /* Next entry */ } while (res == FR_OK); if (res == FR_NO_FILE) res = FR_INT_ERR; } #else /* Non LFN configuration */ res = move_window(fs, dp->sect); if (res == FR_OK) { dp->dir[DIR_Name] = DDEM; /* Mark the entry 'deleted'.*/ fs->wflag = 1; } #endif return res; }
/*-----------------------------------------------------------------------*/ /* Remove an object from the directory */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2571-L2606
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
get_fileinfo
static void get_fileinfo ( DIR* dp, /* Pointer to the directory object */ FILINFO* fno /* Pointer to the file information to be filled */ ) { UINT si, di; #if FF_USE_LFN BYTE lcf; WCHAR wc, hs; FATFS *fs = dp->obj.fs; UINT nw; #else TCHAR c; #endif fno->fname[0] = 0; /* Invaidate file info */ if (dp->sect == 0) return; /* Exit if read pointer has reached end of directory */ #if FF_USE_LFN /* LFN configuration */ #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { /* exFAT volume */ UINT nc = 0; si = SZDIRE * 2; di = 0; /* 1st C1 entry in the entry block */ hs = 0; while (nc < fs->dirbuf[XDIR_NumName]) { if (si >= MAXDIRB(FF_MAX_LFN)) { /* Truncated directory block? */ di = 0; break; } if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */ wc = ld_word(fs->dirbuf + si); si += 2; nc++; /* Get a character */ if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */ hs = wc; continue; /* Get low surrogate */ } nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */ if (nw == 0) { /* Buffer overflow or wrong char? */ di = 0; break; } di += nw; hs = 0; } if (hs != 0) di = 0; /* Broken surrogate pair? */ if (di == 0) fno->fname[di++] = '\?'; /* Inaccessible object name? */ fno->fname[di] = 0; /* Terminate the name */ fno->altname[0] = 0; /* exFAT does not support SFN */ fno->fattrib = fs->dirbuf[XDIR_Attr] & AM_MASKX; /* Attribute */ fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(fs->dirbuf + XDIR_FileSize); /* Size */ fno->ftime = ld_word(fs->dirbuf + XDIR_ModTime + 0); /* Time */ fno->fdate = ld_word(fs->dirbuf + XDIR_ModTime + 2); /* Date */ return; } else #endif { /* FAT/FAT32 volume */ if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */ si = di = 0; hs = 0; while (fs->lfnbuf[si] != 0) { wc = fs->lfnbuf[si++]; /* Get an LFN character (UTF-16) */ if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */ hs = wc; continue; /* Get low surrogate */ } nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */ if (nw == 0) { /* Buffer overflow or wrong char? */ di = 0; break; } di += nw; hs = 0; } if (hs != 0) di = 0; /* Broken surrogate pair? */ fno->fname[di] = 0; /* Terminate the LFN (null string means LFN is invalid) */ } } si = di = 0; while (si < 11) { /* Get SFN from SFN entry */ wc = dp->dir[si++]; /* Get a char */ if (wc == ' ') continue; /* Skip padding spaces */ if (wc == RDDEM) wc = DDEM; /* Restore replaced DDEM character */ if (si == 9 && di < FF_SFN_BUF) fno->altname[di++] = '.'; /* Insert a . if extension is exist */ #if FF_LFN_UNICODE >= 1 /* Unicode output */ if (dbc_1st((BYTE)wc) && si != 8 && si != 11 && dbc_2nd(dp->dir[si])) { /* Make a DBC if needed */ wc = wc << 8 | dp->dir[si++]; } wc = ff_oem2uni(wc, CODEPAGE); /* ANSI/OEM -> Unicode */ if (wc == 0) { /* Wrong char in the current code page? */ di = 0; break; } nw = put_utf(wc, &fno->altname[di], FF_SFN_BUF - di); /* Store it in API encoding */ if (nw == 0) { /* Buffer overflow? */ di = 0; break; } di += nw; #else /* ANSI/OEM output */ fno->altname[di++] = (TCHAR)wc; /* Store it without any conversion */ #endif } fno->altname[di] = 0; /* Terminate the SFN (null string means SFN is invalid) */ if (fno->fname[0] == 0) { /* If LFN is invalid, altname[] needs to be copied to fname[] */ if (di == 0) { /* If LFN and SFN both are invalid, this object is inaccessible */ fno->fname[di++] = '\?'; } else { for (si = di = 0, lcf = NS_BODY; fno->altname[si]; si++, di++) { /* Copy altname[] to fname[] with case information */ wc = (WCHAR)fno->altname[si]; if (wc == '.') lcf = NS_EXT; if (IsUpper(wc) && (dp->dir[DIR_NTres] & lcf)) wc += 0x20; fno->fname[di] = (TCHAR)wc; } } fno->fname[di] = 0; /* Terminate the LFN */ if (!dp->dir[DIR_NTres]) fno->altname[0] = 0; /* Altname is not needed if neither LFN nor case info is exist. */ } #else /* Non-LFN configuration */ si = di = 0; while (si < 11) { /* Copy name body and extension */ c = (TCHAR)dp->dir[si++]; if (c == ' ') continue; /* Skip padding spaces */ if (c == RDDEM) c = DDEM; /* Restore replaced DDEM character */ if (si == 9) fno->fname[di++] = '.';/* Insert a . if extension is exist */ fno->fname[di++] = c; } fno->fname[di] = 0; /* Terminate the SFN */ #endif fno->fattrib = dp->dir[DIR_Attr] & AM_MASK; /* Attribute */ fno->fsize = ld_dword(dp->dir + DIR_FileSize); /* Size */ fno->ftime = ld_word(dp->dir + DIR_ModTime + 0); /* Time */ fno->fdate = ld_word(dp->dir + DIR_ModTime + 2); /* Date */ }
/*-----------------------------------------------------------------------*/ /* Get file information from directory entry */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2617-L2748
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
create_name
static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */ DIR* dp, /* Pointer to the directory object */ const TCHAR** path /* Pointer to pointer to the segment in the path string */ ) { #if FF_USE_LFN /* LFN configuration */ BYTE b, cf; WCHAR wc; WCHAR *lfn; const TCHAR* p; DWORD uc; UINT i, ni, si, di; /* Create LFN into LFN working buffer */ p = *path; lfn = dp->obj.fs->lfnbuf; di = 0; for (;;) { uc = tchar2uni(&p); /* Get a character */ if (uc == 0xFFFFFFFF) return FR_INVALID_NAME; /* Invalid code or UTF decode error */ if (uc >= 0x10000) lfn[di++] = (WCHAR)(uc >> 16); /* Store high surrogate if needed */ wc = (WCHAR)uc; if (wc < ' ' || IsSeparator(wc)) break; /* Break if end of the path or a separator is found */ if (wc < 0x80 && strchr("*:<>|\"\?\x7F", (int)wc)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */ if (di >= FF_MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */ lfn[di++] = wc; /* Store the Unicode character */ } if (wc < ' ') { /* Stopped at end of the path? */ cf = NS_LAST; /* Last segment */ } else { /* Stopped at a separator */ while (IsSeparator(*p)) p++; /* Skip duplicated separators if exist */ cf = 0; /* Next segment may follow */ if (IsTerminator(*p)) cf = NS_LAST; /* Ignore terminating separator */ } *path = p; /* Return pointer to the next segment */ #if FF_FS_RPATH != 0 if ((di == 1 && lfn[di - 1] == '.') || (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */ lfn[di] = 0; for (i = 0; i < 11; i++) { /* Create dot name for SFN entry */ dp->fn[i] = (i < di) ? '.' : ' '; } dp->fn[i] = cf | NS_DOT; /* This is a dot entry */ return FR_OK; } #endif while (di) { /* Snip off trailing spaces and dots if exist */ wc = lfn[di - 1]; if (wc != ' ' && wc != '.') break; di--; } lfn[di] = 0; /* LFN is created into the working buffer */ if (di == 0) return FR_INVALID_NAME; /* Reject null name */ /* Create SFN in directory form */ for (si = 0; lfn[si] == ' '; si++) ; /* Remove leading spaces */ if (si > 0 || lfn[si] == '.') cf |= NS_LOSS | NS_LFN; /* Is there any leading space or dot? */ while (di > 0 && lfn[di - 1] != '.') di--; /* Find last dot (di<=si: no extension) */ memset(dp->fn, ' ', 11); i = b = 0; ni = 8; for (;;) { wc = lfn[si++]; /* Get an LFN character */ if (wc == 0) break; /* Break on end of the LFN */ if (wc == ' ' || (wc == '.' && si != di)) { /* Remove embedded spaces and dots */ cf |= NS_LOSS | NS_LFN; continue; } if (i >= ni || si == di) { /* End of field? */ if (ni == 11) { /* Name extension overflow? */ cf |= NS_LOSS | NS_LFN; break; } if (si != di) cf |= NS_LOSS | NS_LFN; /* Name body overflow? */ if (si > di) break; /* No name extension? */ si = di; i = 8; ni = 11; b <<= 2; /* Enter name extension */ continue; } if (wc >= 0x80) { /* Is this an extended character? */ cf |= NS_LFN; /* LFN entry needs to be created */ #if FF_CODE_PAGE == 0 if (ExCvt) { /* In SBCS cfg */ wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */ if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */ } else { /* In DBCS cfg */ wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */ } #elif FF_CODE_PAGE < 900 /* In SBCS cfg */ wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */ if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */ #else /* In DBCS cfg */ wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */ #endif } if (wc >= 0x100) { /* Is this a DBC? */ if (i >= ni - 1) { /* Field overflow? */ cf |= NS_LOSS | NS_LFN; i = ni; continue; /* Next field */ } dp->fn[i++] = (BYTE)(wc >> 8); /* Put 1st byte */ } else { /* SBC */ if (wc == 0 || strchr("+,;=[]", (int)wc)) { /* Replace illegal characters for SFN */ wc = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */ } else { if (IsUpper(wc)) { /* ASCII upper case? */ b |= 2; } if (IsLower(wc)) { /* ASCII lower case? */ b |= 1; wc -= 0x20; } } } dp->fn[i++] = (BYTE)wc; } if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */ if (ni == 8) b <<= 2; /* Shift capital flags if no extension */ if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) cf |= NS_LFN; /* LFN entry needs to be created if composite capitals */ if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */ if (b & 0x01) cf |= NS_EXT; /* NT flag (Extension has small capital letters only) */ if (b & 0x04) cf |= NS_BODY; /* NT flag (Body has small capital letters only) */ } dp->fn[NSFLAG] = cf; /* SFN is created into dp->fn[] */ return FR_OK; #else /* FF_USE_LFN : Non-LFN configuration */ BYTE c, d; BYTE *sfn; UINT ni, si, i; const char *p; /* Create file name in directory form */ p = *path; sfn = dp->fn; memset(sfn, ' ', 11); si = i = 0; ni = 8; #if FF_FS_RPATH != 0 if (p[si] == '.') { /* Is this a dot entry? */ for (;;) { c = (BYTE)p[si++]; if (c != '.' || si >= 3) break; sfn[i++] = c; } if (!IsSeparator(c) && c > ' ') return FR_INVALID_NAME; *path = p + si; /* Return pointer to the next segment */ sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */ return FR_OK; } #endif for (;;) { c = (BYTE)p[si++]; /* Get a byte */ if (c <= ' ') break; /* Break if end of the path name */ if (IsSeparator(c)) { /* Break if a separator is found */ while (IsSeparator(p[si])) si++; /* Skip duplicated separator if exist */ break; } if (c == '.' || i >= ni) { /* End of body or field overflow? */ if (ni == 11 || c != '.') return FR_INVALID_NAME; /* Field overflow or invalid dot? */ i = 8; ni = 11; /* Enter file extension field */ continue; } #if FF_CODE_PAGE == 0 if (ExCvt && c >= 0x80) { /* Is SBC extended character? */ c = ExCvt[c & 0x7F]; /* To upper SBC extended character */ } #elif FF_CODE_PAGE < 900 if (c >= 0x80) { /* Is SBC extended character? */ c = ExCvt[c & 0x7F]; /* To upper SBC extended character */ } #endif if (dbc_1st(c)) { /* Check if it is a DBC 1st byte */ d = (BYTE)p[si++]; /* Get 2nd byte */ if (!dbc_2nd(d) || i >= ni - 1) return FR_INVALID_NAME; /* Reject invalid DBC */ sfn[i++] = c; sfn[i++] = d; } else { /* SBC */ if (strchr("*+,:;<=>[]|\"\?\x7F", (int)c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */ if (IsLower(c)) c -= 0x20; /* To upper */ sfn[i++] = c; } } *path = &p[si]; /* Return pointer to the next segment */ if (i == 0) return FR_INVALID_NAME; /* Reject nul string */ if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */ sfn[NSFLAG] = (c <= ' ' || p[si] <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */ return FR_OK; #endif /* FF_USE_LFN */ }
/* FF_USE_FIND && FF_FS_MINIMIZE <= 1 */ /*-----------------------------------------------------------------------*/ /* Pick a top segment and create the object name in directory form */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L2847-L3042
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
follow_path
static FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */ DIR* dp, /* Directory object to return last directory and found object */ const TCHAR* path /* Full-path string to find a file or directory */ ) { FRESULT res; BYTE ns; FATFS *fs = dp->obj.fs; #if FF_FS_RPATH != 0 if (!IsSeparator(*path) && (FF_STR_VOLUME_ID != 2 || !IsTerminator(*path))) { /* Without heading separator */ dp->obj.sclust = fs->cdir; /* Start at the current directory */ } else #endif { /* With heading separator */ while (IsSeparator(*path)) path++; /* Strip separators */ dp->obj.sclust = 0; /* Start from the root directory */ } #if FF_FS_EXFAT dp->obj.n_frag = 0; /* Invalidate last fragment counter of the object */ #if FF_FS_RPATH != 0 if (fs->fs_type == FS_EXFAT && dp->obj.sclust) { /* exFAT: Retrieve the sub-directory's status */ DIR dj; dp->obj.c_scl = fs->cdc_scl; dp->obj.c_size = fs->cdc_size; dp->obj.c_ofs = fs->cdc_ofs; res = load_obj_xdir(&dj, &dp->obj); if (res != FR_OK) return res; dp->obj.objsize = ld_dword(fs->dirbuf + XDIR_FileSize); dp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2; } #endif #endif if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */ dp->fn[NSFLAG] = NS_NONAME; res = dir_sdi(dp, 0); } else { /* Follow path */ for (;;) { res = create_name(dp, &path); /* Get a segment name of the path */ if (res != FR_OK) break; res = dir_find(dp); /* Find an object with the segment name */ ns = dp->fn[NSFLAG]; if (res != FR_OK) { /* Failed to find the object */ if (res == FR_NO_FILE) { /* Object is not found */ if (FF_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, stay there */ if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */ dp->fn[NSFLAG] = NS_NONAME; res = FR_OK; } else { /* Could not find the object */ if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */ } } break; } if (ns & NS_LAST) break; /* Last segment matched. Function completed. */ /* Get into the sub-directory */ if (!(dp->obj.attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */ res = FR_NO_PATH; break; } #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { /* Save containing directory information for next dir */ dp->obj.c_scl = dp->obj.sclust; dp->obj.c_size = ((DWORD)dp->obj.objsize & 0xFFFFFF00) | dp->obj.stat; dp->obj.c_ofs = dp->blk_ofs; init_alloc_info(fs, &dp->obj); /* Open next directory */ } else #endif { dp->obj.sclust = ld_clust(fs, fs->win + dp->dptr % SS(fs)); /* Open next directory */ } } } return res; }
/*-----------------------------------------------------------------------*/ /* Follow a file path */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3051-L3129
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
get_ldnumber
static int get_ldnumber ( /* Returns logical drive number (-1:invalid drive number or null pointer) */ const TCHAR** path /* Pointer to pointer to the path name */ ) { const TCHAR *tp; const TCHAR *tt; TCHAR tc; int i; int vol = -1; #if FF_STR_VOLUME_ID /* Find string volume ID */ const char *sp; char c; #endif tt = tp = *path; if (!tp) return vol; /* Invalid path name? */ do { /* Find a colon in the path */ tc = *tt++; } while (!IsTerminator(tc) && tc != ':'); if (tc == ':') { /* DOS/Windows style volume ID? */ i = FF_VOLUMES; if (IsDigit(*tp) && tp + 2 == tt) { /* Is there a numeric volume ID + colon? */ i = (int)*tp - '0'; /* Get the LD number */ } #if FF_STR_VOLUME_ID == 1 /* Arbitrary string is enabled */ else { i = 0; do { sp = VolumeStr[i]; tp = *path; /* This string volume ID and path name */ do { /* Compare the volume ID with path name */ c = *sp++; tc = *tp++; if (IsLower(c)) c -= 0x20; if (IsLower(tc)) tc -= 0x20; } while (c && (TCHAR)c == tc); } while ((c || tp != tt) && ++i < FF_VOLUMES); /* Repeat for each id until pattern match */ } #endif if (i < FF_VOLUMES) { /* If a volume ID is found, get the drive number and strip it */ vol = i; /* Drive number */ *path = tt; /* Snip the drive prefix off */ } return vol; } #if FF_STR_VOLUME_ID == 2 /* Unix style volume ID is enabled */ if (*tp == '/') { /* Is there a volume ID? */ while (*(tp + 1) == '/') tp++; /* Skip duplicated separator */ i = 0; do { tt = tp; sp = VolumeStr[i]; /* Path name and this string volume ID */ do { /* Compare the volume ID with path name */ c = *sp++; tc = *(++tt); if (IsLower(c)) c -= 0x20; if (IsLower(tc)) tc -= 0x20; } while (c && (TCHAR)c == tc); } while ((c || (tc != '/' && !IsTerminator(tc))) && ++i < FF_VOLUMES); /* Repeat for each ID until pattern match */ if (i < FF_VOLUMES) { /* If a volume ID is found, get the drive number and strip it */ vol = i; /* Drive number */ *path = tt; /* Snip the drive prefix off */ } return vol; } #endif /* No drive prefix is found */ #if FF_FS_RPATH != 0 vol = CurrVol; /* Default drive is current drive */ #else vol = 0; /* Default drive is 0 */ #endif return vol; /* Return the default drive */ }
/*-----------------------------------------------------------------------*/ /* Get logical drive number from path name */ /*-----------------------------------------------------------------------*/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3138-L3208
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
crc32
static DWORD crc32 ( /* Returns next CRC value */ DWORD crc, /* Current CRC value */ BYTE d /* A byte to be processed */ ) { BYTE b; for (b = 1; b; b <<= 1) { crc ^= (d & b) ? 1 : 0; crc = (crc & 1) ? crc >> 1 ^ 0xEDB88320 : crc >> 1; } return crc; }
/* Calculate CRC32 in byte-by-byte */
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3221-L3234
83d3b29cbfc74e8f76f48f8782646c8e464055b2